posthog-node 6.1.1 → 6.2.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 +251 -124
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +23 -4
- package/dist/client.mjs +23 -4
- package/dist/emails/emails.d.ts +2 -1
- package/dist/emails/emails.d.ts.map +1 -1
- package/dist/emails/emails.js +27 -11
- package/dist/emails/emails.mjs +27 -11
- package/dist/emails/react-renderer-import.d.ts +3 -0
- package/dist/emails/react-renderer-import.d.ts.map +1 -0
- package/dist/emails/react-renderer-import.js +50 -0
- package/dist/emails/react-renderer-import.mjs +6 -0
- package/dist/emails/types.d.ts +15 -1
- package/dist/emails/types.d.ts.map +1 -1
- package/dist/entrypoints/otel.d.ts +20 -0
- package/dist/entrypoints/otel.d.ts.map +1 -1
- package/dist/exports.d.ts +3 -2
- package/dist/exports.d.ts.map +1 -1
- package/dist/extensions/context/listeners.d.ts +3 -2
- package/dist/extensions/context/listeners.d.ts.map +1 -1
- package/dist/extensions/context/types.d.ts +2 -0
- package/dist/extensions/context/types.d.ts.map +1 -1
- package/dist/extensions/express.d.ts +30 -4
- package/dist/extensions/express.d.ts.map +1 -1
- package/dist/extensions/nestjs.d.ts +23 -0
- package/dist/extensions/nestjs.d.ts.map +1 -1
- package/dist/types.d.ts +133 -96
- 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 +276 -130
- package/src/emails/emails.ts +35 -13
- package/src/emails/react-renderer-import.ts +7 -0
- package/src/emails/types.ts +16 -1
- package/src/entrypoints/otel.ts +20 -0
- package/src/exports.ts +3 -1
- package/src/extensions/context/listeners.ts +3 -2
- package/src/extensions/context/types.ts +2 -0
- package/src/extensions/express.ts +30 -4
- package/src/extensions/nestjs.ts +23 -0
- package/src/types.ts +138 -105
- package/src/version.ts +1 -1
package/src/emails/emails.ts
CHANGED
|
@@ -16,10 +16,12 @@ import {
|
|
|
16
16
|
refuseRenderedMessageOverLimit,
|
|
17
17
|
} from './attachments'
|
|
18
18
|
import { EmailError } from './errors'
|
|
19
|
+
import { importReactRenderer } from './react-renderer-import'
|
|
19
20
|
import type {
|
|
20
21
|
CodeEmailForm,
|
|
21
22
|
EmailPreferences,
|
|
22
23
|
EmailReactElement,
|
|
24
|
+
EmailReactRenderer,
|
|
23
25
|
EmailStatus,
|
|
24
26
|
EmailWarning,
|
|
25
27
|
Emails,
|
|
@@ -53,10 +55,6 @@ const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{1,255}$/
|
|
|
53
55
|
const TEMPLATE_KEY_PATTERN = /^[a-zA-Z0-9_-]{1,400}$/
|
|
54
56
|
|
|
55
57
|
type EveryField<Form> = Record<keyof Form, true>
|
|
56
|
-
interface ReactRenderer {
|
|
57
|
-
render(element: EmailReactElement): Promise<string>
|
|
58
|
-
toPlainText(html: string): string
|
|
59
|
-
}
|
|
60
58
|
type UncheckedSend = { [Field in keyof SendTemplateEmailOptions]?: unknown }
|
|
61
59
|
|
|
62
60
|
interface SendForm {
|
|
@@ -112,6 +110,7 @@ export interface EmailSenderConfig {
|
|
|
112
110
|
requestTimeoutMs: number
|
|
113
111
|
maxRetries: number
|
|
114
112
|
migratedFrom?: string
|
|
113
|
+
reactRenderer?: EmailReactRenderer
|
|
115
114
|
}
|
|
116
115
|
|
|
117
116
|
export interface EmailFetchOptions extends PostHogFetchOptions {
|
|
@@ -201,7 +200,7 @@ export class EmailSender implements Emails {
|
|
|
201
200
|
const content =
|
|
202
201
|
prepared.react === undefined
|
|
203
202
|
? prepared.content
|
|
204
|
-
: await withRenderedReact(prepared.content, prepared.react, this.config.
|
|
203
|
+
: await withRenderedReact(prepared.content, prepared.react, this.config, this.hooks.logger)
|
|
205
204
|
if (prepared.react !== undefined) {
|
|
206
205
|
refuseRenderedMessageOverLimit(prepared.files, content)
|
|
207
206
|
}
|
|
@@ -678,12 +677,29 @@ function isReactElement(value: unknown): value is EmailReactElement {
|
|
|
678
677
|
async function withRenderedReact(
|
|
679
678
|
content: Record<string, unknown>,
|
|
680
679
|
react: EmailReactElement,
|
|
681
|
-
|
|
680
|
+
config: EmailSenderConfig,
|
|
681
|
+
logger: Logger
|
|
682
682
|
): Promise<Record<string, unknown>> {
|
|
683
|
-
|
|
683
|
+
await Promise.resolve()
|
|
684
|
+
const renderer = config.reactRenderer ?? (await loadReactRenderer(logger))
|
|
684
685
|
try {
|
|
685
|
-
const html = await settleWithin(render(react),
|
|
686
|
-
|
|
686
|
+
const html = await settleWithin(renderer.render(react), config.requestTimeoutMs, 'Rendering the react element')
|
|
687
|
+
if (typeof html !== 'string') {
|
|
688
|
+
throw new Error('reactEmailRenderer.render must return an HTML string.')
|
|
689
|
+
}
|
|
690
|
+
if (content.text !== undefined) {
|
|
691
|
+
return { ...content, html }
|
|
692
|
+
}
|
|
693
|
+
const text: unknown = renderer.toPlainText(html)
|
|
694
|
+
if (typeof text !== 'string') {
|
|
695
|
+
try {
|
|
696
|
+
Promise.prototype.then.call(text, undefined, () => {})
|
|
697
|
+
} catch {
|
|
698
|
+
void 0
|
|
699
|
+
}
|
|
700
|
+
throw new Error('reactEmailRenderer.toPlainText must return a string.')
|
|
701
|
+
}
|
|
702
|
+
return { ...content, html, text }
|
|
687
703
|
} catch (cause) {
|
|
688
704
|
throw new EmailError({
|
|
689
705
|
code: 'react_render_failed',
|
|
@@ -705,17 +721,23 @@ async function settleWithin<T>(work: Promise<T>, timeoutMs: number, what: string
|
|
|
705
721
|
}
|
|
706
722
|
}
|
|
707
723
|
|
|
708
|
-
async function loadReactRenderer(): Promise<
|
|
724
|
+
async function loadReactRenderer(logger: Logger): Promise<EmailReactRenderer> {
|
|
709
725
|
try {
|
|
710
|
-
return await
|
|
726
|
+
return await importReactRenderer()
|
|
711
727
|
} catch (cause) {
|
|
712
|
-
|
|
728
|
+
const error = new EmailError({
|
|
713
729
|
code: 'missing_react_renderer',
|
|
714
730
|
message:
|
|
715
731
|
"react needs the @react-email/render package, which isn't installed or failed to load, so no email was sent.",
|
|
716
|
-
fix:
|
|
732
|
+
fix: "Install @react-email/render with react and react-dom next to posthog-node. If you bundle your app, also pass the client reactEmailRenderer: await import('@react-email/render'). Or render the email yourself and send html.",
|
|
717
733
|
cause,
|
|
718
734
|
})
|
|
735
|
+
try {
|
|
736
|
+
logger.warn(`PostHog email error ${error.code}: ${error.message} ${error.fix}`)
|
|
737
|
+
} catch {
|
|
738
|
+
void 0
|
|
739
|
+
}
|
|
740
|
+
throw error
|
|
719
741
|
}
|
|
720
742
|
}
|
|
721
743
|
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { EmailReactRenderer } from './types'
|
|
2
|
+
|
|
3
|
+
const PACKAGE_HIDDEN_FROM_BUNDLERS = '@react-email/render'
|
|
4
|
+
|
|
5
|
+
export function importReactRenderer(): Promise<EmailReactRenderer> {
|
|
6
|
+
return import(/* webpackIgnore: true */ /* @vite-ignore */ PACKAGE_HIDDEN_FROM_BUNDLERS)
|
|
7
|
+
}
|
package/src/emails/types.ts
CHANGED
|
@@ -125,6 +125,19 @@ export interface EmailReactElement {
|
|
|
125
125
|
props: unknown
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
+
/**
|
|
129
|
+
* Renders `react` sends: the `@react-email/render` module, or an object with its `render` and
|
|
130
|
+
* `toPlainText`.
|
|
131
|
+
*/
|
|
132
|
+
export interface EmailReactRenderer {
|
|
133
|
+
/**
|
|
134
|
+
* Renders a React element to HTML. Typed as `any` because `@react-email/render` takes
|
|
135
|
+
* `React.ReactNode`, which posthog-node doesn't depend on.
|
|
136
|
+
*/
|
|
137
|
+
render(element: any): Promise<string>
|
|
138
|
+
toPlainText(html: string): string
|
|
139
|
+
}
|
|
140
|
+
|
|
128
141
|
/**
|
|
129
142
|
* Email content from your code, named by a key: `html`, `text` or both, or a `react` element
|
|
130
143
|
* the client renders. PostHog sends it as is and never stores it. PostHog derives a missing
|
|
@@ -137,7 +150,9 @@ export type CodeEmailForm = CodeEmailFields &
|
|
|
137
150
|
| {
|
|
138
151
|
/**
|
|
139
152
|
* A React Email element. The client renders it into `html`, and into `text` when the
|
|
140
|
-
* send has none. Needs the `@react-email/render` package
|
|
153
|
+
* send has none. Needs the `@react-email/render` package: posthog-node loads it from
|
|
154
|
+
* `node_modules` at runtime, or set the client's `reactEmailRenderer` option when you bundle
|
|
155
|
+
* your app, such as for Cloudflare Workers, Convex, or Vercel Edge.
|
|
141
156
|
* The client renders the element after `send()` returns, so give each send its own
|
|
142
157
|
* element and props, and don't change them while the send is pending.
|
|
143
158
|
*/
|
package/src/entrypoints/otel.ts
CHANGED
|
@@ -10,12 +10,32 @@ function hasReadableAttributes(span: Span | undefined): span is ReadableSpan {
|
|
|
10
10
|
return !!span && 'attributes' in span && typeof span.attributes === 'object' && span.attributes !== null
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* OpenTelemetry `SpanProcessor` that stamps `posthogDistinctId` and `sessionId` from the active PostHog context onto recording spans and the nearest enclosing `SERVER` span.
|
|
15
|
+
*
|
|
16
|
+
* Requires `@opentelemetry/api` (`^1.2.0`) as an optional peer dependency. Skips spans when the client is disabled or opted out.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'
|
|
21
|
+
* import { PostHog } from 'posthog-node'
|
|
22
|
+
* import { PostHogContextSpanProcessor } from 'posthog-node/otel'
|
|
23
|
+
*
|
|
24
|
+
* const posthog = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' })
|
|
25
|
+
* const provider = new BasicTracerProvider({ spanProcessors: [new PostHogContextSpanProcessor(posthog)] })
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
13
28
|
export class PostHogContextSpanProcessor {
|
|
14
29
|
private active = true
|
|
15
30
|
private readonly snapshots = new WeakSet<Span>()
|
|
16
31
|
private readonly parents = new WeakMap<Span, WeakRef<Span>>()
|
|
17
32
|
private readonly unsubscribe: () => void
|
|
18
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Create a span processor bound to one PostHog client instance.
|
|
36
|
+
*
|
|
37
|
+
* @param posthog - Client whose active request context populates span attributes
|
|
38
|
+
*/
|
|
19
39
|
constructor(private readonly posthog: PostHogBackendClient) {
|
|
20
40
|
this.unsubscribe = addContextListener(posthog, (requestEntry) => {
|
|
21
41
|
const span = trace.getActiveSpan()
|
package/src/exports.ts
CHANGED
|
@@ -19,6 +19,7 @@ export type {
|
|
|
19
19
|
EmailDeliveryStatus,
|
|
20
20
|
EmailPreferences,
|
|
21
21
|
EmailReactElement,
|
|
22
|
+
EmailReactRenderer,
|
|
22
23
|
Emails,
|
|
23
24
|
EmailStatus,
|
|
24
25
|
EmailTracking,
|
|
@@ -43,7 +44,8 @@ export type {
|
|
|
43
44
|
// Re-export FeatureFlagError from core for backwards compatibility.
|
|
44
45
|
// These were originally defined in posthog-node and moved to core for reuse across SDKs.
|
|
45
46
|
export { FeatureFlagError } from '@posthog/core'
|
|
46
|
-
export type { FeatureFlagErrorType
|
|
47
|
+
export type { FeatureFlagErrorType } from '@posthog/core'
|
|
48
|
+
export type { UnresolvedFlagReason } from './types'
|
|
47
49
|
|
|
48
50
|
// Metrics types re-exported so consumers can name the `metrics` client option
|
|
49
51
|
// and API surface without a direct @posthog/core dependency.
|
|
@@ -28,8 +28,9 @@ export function notifyContextListeners(client: PostHogBackendClient, requestEntr
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/**
|
|
31
|
-
* Notify installed
|
|
32
|
-
*
|
|
31
|
+
* Notify installed `PostHogContextSpanProcessor` instances after request IDs become available.
|
|
32
|
+
*
|
|
33
|
+
* This helper doesn't load OpenTelemetry, so it's a no-op unless you register `PostHogContextSpanProcessor` from `posthog-node/otel`.
|
|
33
34
|
*/
|
|
34
35
|
export function enrichCurrentSpan(client: PostHogBackendClient): void {
|
|
35
36
|
notifyContextListeners(client, true)
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { EventOptions } from '../../types'
|
|
2
2
|
|
|
3
3
|
export interface ContextData {
|
|
4
|
+
/** Distinct ID applied to events, flag evaluations, logs, and spans inside the context when not passed directly. */
|
|
4
5
|
distinctId?: string
|
|
6
|
+
/** Session ID (UUIDv7) attached as `$session_id` on events and `sessionId` on logs and spans inside the context. */
|
|
5
7
|
sessionId?: string
|
|
6
8
|
/** Properties that fill the keys an event left unset. The event's own values win. */
|
|
7
9
|
properties?: Record<string, any>
|
|
@@ -65,9 +65,30 @@ function buildRequestContextData(posthog: PostHogBackendClient, req: Request): P
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
68
|
+
* Register Express middleware that binds per-request PostHog context before your routes run.
|
|
69
|
+
*
|
|
70
|
+
* Reads `x-posthog-session-id` and `x-posthog-distinct-id` headers (or the `posthog-js` cookie when `readPostHogCookie` is enabled) and attaches `$current_url`, `$request_method`, `$request_path`, `$user_agent`, and `$ip` (first `x-forwarded-for` entry or `req.socket.remoteAddress`) to events in that request.
|
|
71
|
+
*
|
|
72
|
+
* Tracing headers are untrusted client data, never authentication, so pass an authenticated `distinctId` explicitly for authorization or sensitive decisions. Client IP geolocation from `$ip` also requires `disableGeoip: false`.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```ts
|
|
76
|
+
* import express from 'express'
|
|
77
|
+
* import { PostHog, setupExpressErrorHandler, setupExpressRequestContext } from 'posthog-node'
|
|
78
|
+
*
|
|
79
|
+
* const app = express()
|
|
80
|
+
* const client = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' })
|
|
81
|
+
*
|
|
82
|
+
* setupExpressRequestContext(client, app)
|
|
83
|
+
* app.get('/', (_req, res) => {
|
|
84
|
+
* client.capture({ event: 'page_loaded' })
|
|
85
|
+
* res.send('ok')
|
|
86
|
+
* })
|
|
87
|
+
* setupExpressErrorHandler(client, app)
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* @param _posthog - PostHog client instance
|
|
91
|
+
* @param app - Express app or router with `.use()`
|
|
71
92
|
*/
|
|
72
93
|
export function setupExpressRequestContext(
|
|
73
94
|
_posthog: PostHogBackendClient,
|
|
@@ -88,7 +109,12 @@ function posthogRequestContext(posthog: PostHogBackendClient): ExpressMiddleware
|
|
|
88
109
|
}
|
|
89
110
|
|
|
90
111
|
/**
|
|
91
|
-
*
|
|
112
|
+
* Register Express error-handling middleware after your routes to capture unhandled exceptions.
|
|
113
|
+
*
|
|
114
|
+
* Attaches request context, `$response_status_code`, and `$session_id`, skips errors already captured by process autocapture, and forwards each error to `next(error)`.
|
|
115
|
+
*
|
|
116
|
+
* @param _posthog - PostHog client instance
|
|
117
|
+
* @param app - Express app with `.use()`
|
|
92
118
|
*/
|
|
93
119
|
export function setupExpressErrorHandler(
|
|
94
120
|
_posthog: PostHogBackendClient,
|
package/src/extensions/nestjs.ts
CHANGED
|
@@ -70,12 +70,34 @@ function getExceptionStatus(exception: unknown): number | undefined {
|
|
|
70
70
|
return undefined
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
/**
|
|
74
|
+
* NestJS interceptor from `posthog-node/nestjs` that isolates per-request PostHog context with `AsyncLocalStorage` and optionally captures controller exceptions.
|
|
75
|
+
*
|
|
76
|
+
* Resolves `distinctId` in order: `getDistinctId(request)`, then `x-posthog-distinct-id` (or cookie when `readPostHogCookie` is enabled), then any outer `withContext()`. Attaches `$current_url`, `$request_method`, `$request_path`, `$user_agent`, and `$ip`.
|
|
77
|
+
*
|
|
78
|
+
* Tracing headers are untrusted client data, never authentication. Set `captureExceptions: true` (or `{ minStatusToCapture }`, default `500`) to capture errors with `$response_status_code`.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```ts
|
|
82
|
+
* import { PostHog } from 'posthog-node'
|
|
83
|
+
* import { PostHogInterceptor } from 'posthog-node/nestjs'
|
|
84
|
+
*
|
|
85
|
+
* const posthog = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' })
|
|
86
|
+
* app.useGlobalInterceptors(new PostHogInterceptor(posthog, { captureExceptions: true }))
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
73
89
|
export class PostHogInterceptor implements NestInterceptor {
|
|
74
90
|
private posthog: PostHogBackendClient
|
|
75
91
|
private captureExceptions: boolean
|
|
76
92
|
private minStatusToCapture: number
|
|
77
93
|
private getDistinctId?: (request: any) => string | undefined
|
|
78
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Create a NestJS interceptor bound to a PostHog client.
|
|
97
|
+
*
|
|
98
|
+
* @param posthog - PostHog client instance
|
|
99
|
+
* @param options - Exception capture and user ID resolution options
|
|
100
|
+
*/
|
|
79
101
|
constructor(posthog: PostHogBackendClient, options?: PostHogInterceptorOptions) {
|
|
80
102
|
this.posthog = posthog
|
|
81
103
|
const capture = options?.captureExceptions
|
|
@@ -98,6 +120,7 @@ export class PostHogInterceptor implements NestInterceptor {
|
|
|
98
120
|
}
|
|
99
121
|
}
|
|
100
122
|
|
|
123
|
+
/** Wrap an incoming NestJS request in an isolated PostHog context. */
|
|
101
124
|
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
|
102
125
|
const httpHost = context.switchToHttp()
|
|
103
126
|
const request = httpHost.getRequest()
|