@posthog/browser 0.4.2 → 0.6.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/ARCHITECTURE.md +36 -48
- package/README.md +97 -69
- package/dist/composition/npm/core.d.ts +3 -4
- package/dist/composition/npm/core.js +2 -1
- package/dist/composition/npm/core.mjs +2 -1
- package/dist/composition/npm/index.d.ts +4 -5
- package/dist/composition/npm/index.js +2 -1
- package/dist/composition/npm/index.mjs +2 -1
- package/dist/composition/npm/root-composition.d.ts +4 -4
- package/dist/composition/npm/root-composition.js +0 -16
- package/dist/composition/npm/root-composition.mjs +0 -16
- package/dist/core/context/browser-client.d.ts +4 -35
- package/dist/core/extensions/registry.d.ts +15 -36
- package/dist/core/extensions/registry.js +67 -198
- package/dist/core/extensions/registry.mjs +67 -198
- package/dist/core/posthog.d.ts +3 -2
- package/dist/core/posthog.js +190 -173
- package/dist/core/posthog.mjs +191 -174
- package/dist/core/state/state.d.ts +33 -3
- package/dist/core/state/state.js +122 -27
- package/dist/core/state/state.mjs +107 -27
- package/dist/core/types.d.ts +134 -14
- package/dist/persistence/cookie.d.ts +19 -0
- package/dist/persistence/cookie.js +273 -0
- package/dist/persistence/cookie.mjs +235 -0
- package/dist/platform/logger.d.ts +5 -1
- package/dist/platform/logger.js +3 -3
- package/dist/platform/logger.mjs +3 -3
- package/dist/primitives/id.d.ts +5 -0
- package/dist/primitives/id.js +10 -2
- package/dist/primitives/id.mjs +6 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.mjs +1 -1
- package/dist/products/analytics/analytics-core.d.ts +89 -0
- package/dist/products/analytics/analytics-core.js +563 -0
- package/dist/products/analytics/analytics-core.mjs +516 -0
- package/dist/products/analytics/analytics-internal.d.ts +16 -37
- package/dist/products/analytics/analytics-internal.js +2 -10
- package/dist/products/analytics/analytics-internal.mjs +1 -3
- package/dist/products/analytics/analytics-options.d.ts +0 -9
- package/dist/products/analytics/analytics-options.js +1 -38
- package/dist/products/analytics/analytics-options.mjs +1 -17
- package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
- package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
- package/dist/products/analytics/delivery/lane.d.ts +8 -1
- package/dist/products/analytics/delivery/lane.js +16 -4
- package/dist/products/analytics/delivery/lane.mjs +16 -4
- package/dist/products/analytics/groups.d.ts +8 -0
- package/dist/products/analytics/groups.js +84 -0
- package/dist/products/analytics/groups.mjs +40 -0
- package/dist/products/analytics/person.d.ts +11 -0
- package/dist/products/analytics/person.js +91 -0
- package/dist/products/analytics/person.mjs +41 -0
- package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
- package/dist/products/analytics/properties/analytics-properties.js +3 -0
- package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
- package/dist/products/autocapture/autocapture.js +2 -6
- package/dist/products/autocapture/autocapture.mjs +2 -6
- package/dist/products/flags/flags-internal.d.ts +4 -2
- package/dist/products/flags/flags-options.d.ts +16 -2
- package/dist/products/flags/flags-token.d.ts +31 -4
- package/dist/products/flags/flags.d.ts +1 -1
- package/dist/products/flags/flags.js +112 -11
- package/dist/products/flags/flags.mjs +112 -11
- package/dist/products/logs/logs.js +2 -5
- package/dist/products/logs/logs.mjs +2 -5
- package/dist/products/surveys/surveys-extension.js +78 -46
- package/dist/products/surveys/surveys-extension.mjs +80 -48
- package/dist/products/surveys/surveys-internal.d.ts +6 -0
- package/package.json +7 -7
- package/dist/products/analytics/analytics-api.d.ts +0 -32
- package/dist/products/analytics/analytics-api.js +0 -18
- package/dist/products/analytics/analytics-api.mjs +0 -1
- package/dist/products/analytics/analytics-buffer.d.ts +0 -4
- package/dist/products/analytics/analytics-buffer.js +0 -41
- package/dist/products/analytics/analytics-buffer.mjs +0 -3
- package/dist/products/analytics/analytics-extension.d.ts +0 -87
- package/dist/products/analytics/analytics-extension.js +0 -649
- package/dist/products/analytics/analytics-extension.mjs +0 -611
- package/dist/products/analytics/analytics.d.ts +0 -6
- package/dist/products/analytics/analytics.js +0 -42
- package/dist/products/analytics/analytics.mjs +0 -4
- package/dist/products/analytics/automatic-analytics.d.ts +0 -3
- package/dist/products/analytics/automatic-analytics.js +0 -44
- package/dist/products/analytics/automatic-analytics.mjs +0 -6
package/README.md
CHANGED
|
@@ -12,62 +12,56 @@ npm install @posthog/browser
|
|
|
12
12
|
import { createPostHog } from '@posthog/browser'
|
|
13
13
|
|
|
14
14
|
const posthog = await createPostHog({ projectToken: '<project-token>' })
|
|
15
|
-
|
|
16
|
-
posthog.analytics?.capture('signed_up')
|
|
15
|
+
posthog.capture('signed_up')
|
|
17
16
|
await posthog.flush()
|
|
18
17
|
```
|
|
19
18
|
|
|
20
|
-
|
|
19
|
+
The client is the single `Client` implementation that shared and browser extensions receive in `setup()`. Capture, identity, registration and their listeners are client members. Configure scheduling and person processing through the `analytics` option:
|
|
21
20
|
|
|
22
21
|
```ts
|
|
23
22
|
const posthog = await createPostHog({
|
|
24
23
|
projectToken: '<project-token>',
|
|
25
|
-
analytics: {
|
|
24
|
+
analytics: { flushAt: 20, flushInterval: 3_000, personProfiles: 'identified_only' },
|
|
26
25
|
})
|
|
27
26
|
```
|
|
28
27
|
|
|
29
|
-
|
|
28
|
+
Both entrypoints deliver through Capture V1 with retries, compression and payload splitting. They differ in how products load:
|
|
30
29
|
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
| Entrypoint | Products |
|
|
31
|
+
| ----------------------- | ------------------------------------------------------------------ |
|
|
32
|
+
| `@posthog/browser` | Loaded on demand from options, saved state or remote configuration |
|
|
33
|
+
| `@posthog/browser/core` | Only explicitly supplied extensions |
|
|
33
34
|
|
|
34
|
-
|
|
35
|
-
projectToken: '<project-token>',
|
|
36
|
-
extensions: [analytics({ flushAt: 5, flushInterval: 0 })],
|
|
37
|
-
})
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
Use `analytics: false` to block implicit analytics acquisition, including requests from other products. An explicitly supplied analytics instance takes precedence. The manual `@posthog/browser/core` entrypoint installs only supplied products and has no automatic product imports. Installed namespaces are synchronous lookups; `await posthog.resolveExtension('analytics')` acquires an eligible unloaded product and returns its installed instance, or undefined if disabled or unavailable. Concurrent requests share loading and setup. Supplied analytics initializes before other configured extensions; extensions needing a capture dependency resolve it before exposing synchronous operations.
|
|
35
|
+
Both entrypoints share identity, session, consent and persistence behavior. Installed products are synchronous client properties, such as `posthog.featureFlags`; reading one never starts loading. `await posthog.resolveExtension(token)` waits for a product that is loading, and `posthog.getExtension(name)` returns an installed extension or one of its bindings.
|
|
41
36
|
|
|
42
|
-
|
|
37
|
+
`personProfiles: 'always' | 'never' | 'identified_only'` defaults to `identified_only`. Anonymous events carry `process_person_profile: false` in Capture V1 options until identification, group registration or explicit profile enablement. SDK-computed processing metadata takes precedence over caller properties; `$process_person_profile` does not change the SDK's underlying processing state.
|
|
43
38
|
|
|
44
|
-
|
|
39
|
+
Person and group operations are client methods:
|
|
45
40
|
|
|
46
|
-
|
|
41
|
+
```ts
|
|
42
|
+
posthog.alias('account-123')
|
|
43
|
+
posthog.setPersonProperties({ plan: 'pro' })
|
|
44
|
+
posthog.group('organization', 'current-group')
|
|
45
|
+
posthog.groupIdentify('organization', 'another-group', { plan: 'enterprise' })
|
|
46
|
+
posthog.resetGroups()
|
|
47
|
+
```
|
|
47
48
|
|
|
48
|
-
|
|
49
|
+
Profile creation and property updates preserve the current anonymous identity; they do not identify the user. Set, set-once and unset also update local feature-flag person context. Exact repeated property updates are deduplicated only after local event admission. Reset clears explicit profile enablement and deduplication, without rewriting queued events. In `never` mode, person helpers, identify and group registration are no-ops; ordinary capture continues without person processing.
|
|
49
50
|
|
|
50
|
-
`
|
|
51
|
+
`posthog.alias(targetId)` links the current ID without changing the current identity or marking it identified; it enables person processing unless disabled by policy. Use `posthog.identify()` to switch the ambient identity.
|
|
51
52
|
|
|
52
|
-
|
|
53
|
-
const analytics = await posthog.resolveExtension('analytics')
|
|
54
|
-
analytics?.alias('account-123')
|
|
55
|
-
await analytics?.group('organization', 'current-group')
|
|
56
|
-
analytics?.groupIdentify('organization', 'another-group', { plan: 'enterprise' })
|
|
57
|
-
analytics?.resetGroups()
|
|
58
|
-
```
|
|
53
|
+
`posthog.group(type, key, properties?)` persists ambient membership. `posthog.groupIdentify(type, key, properties?, options?)` sends a group-profile update without changing membership or local flag-evaluation context; its key can be a string or finite number. Alias and group-profile events require capture consent and are suppressed in `never` mode. `posthog.resetGroups()` clears memberships, retaining identity, sessions, person properties and other stored state. When flags is installed it also clears group properties used for evaluation and requests a reload. It remains available for cleanup when capture is denied or person processing is disabled. Previously queued events retain their captured group context.
|
|
59
54
|
|
|
60
55
|
## Persistent event properties
|
|
61
56
|
|
|
62
|
-
|
|
57
|
+
Register context for future events:
|
|
63
58
|
|
|
64
59
|
```ts
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
analytics?.unregister('region')
|
|
60
|
+
posthog.register({ plan: 'pro', region: 'eu' })
|
|
61
|
+
posthog.registerOnce({ acquisitionSource: 'website' })
|
|
62
|
+
posthog.capture('dashboard', { plan: 'enterprise' })
|
|
63
|
+
const region = posthog.getProperty('region')
|
|
64
|
+
posthog.unregister('region')
|
|
71
65
|
```
|
|
72
66
|
|
|
73
67
|
`register(properties)` merges JSON-serializable properties into analytics' Core-owned persistent storage. `registerOnce(properties, defaultValue = 'None')` adds missing keys or replaces existing values strictly equal to the sentinel; other existing values, including `false`, `0`, `''` and `null`, are retained. `getProperty(key)` returns an isolated stored value, or `undefined` for a missing key. Registration inputs and captured events are snapshotted, so later input or stored-property changes do not rewrite queued events.
|
|
@@ -77,30 +71,32 @@ Persistent properties are overridden by session properties, then dynamic event-p
|
|
|
77
71
|
## Session event properties
|
|
78
72
|
|
|
79
73
|
```ts
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
analytics?.unregisterForSession('checkoutFlow')
|
|
74
|
+
posthog.registerForSession({ checkoutFlow: 'express' })
|
|
75
|
+
posthog.unregisterForSession('checkoutFlow')
|
|
83
76
|
```
|
|
84
77
|
|
|
85
78
|
With default browser storage, session properties use Core-owned per-tab storage, surviving reloads in the same SDK session. Independent tabs are isolated; copied tabs inherit a snapshot and then diverge. With a custom `storage` adapter, `storage: false` or unavailable native session storage, properties remain in per-instance memory. They override persistent defaults, but dynamic producers, caller properties, capture options and protected SDK metadata take precedence.
|
|
86
79
|
|
|
87
80
|
Registration and removal are local, do not create a session, and remain available under capture denial or `personProfiles: 'never'`. Properties registered before the first event or after the current session expires remain pending for the next admitted session. Registration does not extend session activity. On Core session rotation or adoption, old properties are excluded from the new session's events and cleared only after successful admission; rejected events retain the old scope. Full `reset()` clears session properties; `resetGroups()` retains them. Already-admitted events retain their finalized properties.
|
|
88
81
|
|
|
89
|
-
## Migrating
|
|
82
|
+
## Migrating from the analytics extension
|
|
90
83
|
|
|
91
|
-
|
|
84
|
+
Earlier 0.x versions exposed analytics as a separate product. It is now part of the client:
|
|
92
85
|
|
|
93
|
-
| Previous
|
|
94
|
-
|
|
|
95
|
-
| `capture()`, `captureImmediate()
|
|
96
|
-
| `
|
|
97
|
-
| `onEvent`, `isRateLimited`
|
|
98
|
-
| `
|
|
99
|
-
|
|
|
86
|
+
| Previous API | Replacement |
|
|
87
|
+
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------ |
|
|
88
|
+
| `posthog.analytics?.capture()`, `captureImmediate()`, `identify()`, `reset()` | The same method on `posthog` |
|
|
89
|
+
| `posthog.analytics?.register*()`, `getProperty()`, `registerForSession()` | The same method on `posthog` |
|
|
90
|
+
| `posthog.analytics?.onEvent`, `isRateLimited` | `posthog.onEvent`, `posthog.isRateLimited` |
|
|
91
|
+
| `posthog.analytics?.alias()`, person helpers | The same method on `posthog` |
|
|
92
|
+
| `posthog.analytics?.group()`, `groupIdentify()`, `resetGroups()` | The same method on `posthog` |
|
|
93
|
+
| `analytics()` from `@posthog/browser/analytics`, `analytics: { load }` | The `analytics` option configures scheduling and person processing |
|
|
94
|
+
| `IPostHogInternal`, `sharedClient` | Extensions receive the `IPostHog` client in `setup()` |
|
|
95
|
+
| `analytics: false`, `/core` without the analytics extension | Always captures; see `capturePageview` and `autocapture` below |
|
|
100
96
|
|
|
101
|
-
|
|
97
|
+
Capture is part of every client, so `analytics: false` (ignored, with a debug warning) and `/core` without the analytics extension no longer turn it off. Both entrypoints send the initial `$pageview`, `$feature_flag_called` the first time each flag value is read when flags is installed, and events from other installed products. Set `capturePageview: false` to skip the initial pageview and, on the root entrypoint, `autocapture: false` to turn off autocapture. `optOutByDefault: true` stops all capture until `optIn()`, but it also blocks flag and other product requests.
|
|
102
98
|
|
|
103
|
-
|
|
99
|
+
Extensions share the client's key-value store, as posthog-js extensions share its persistence. Data saved by earlier 0.x versions under per-extension namespaces is not migrated.
|
|
104
100
|
|
|
105
101
|
## Classic script installation (draft CDN distribution)
|
|
106
102
|
|
|
@@ -127,7 +123,7 @@ After the existing `createPostHog()` factory resolves, the script assigns `windo
|
|
|
127
123
|
|
|
128
124
|
```js
|
|
129
125
|
function onPostHogReady(client) {
|
|
130
|
-
client.
|
|
126
|
+
client.capture('signed_up')
|
|
131
127
|
}
|
|
132
128
|
if (window.posthog) {
|
|
133
129
|
onPostHogReady(window.posthog)
|
|
@@ -202,7 +198,9 @@ subscription?.dispose()
|
|
|
202
198
|
|
|
203
199
|
`FeatureFlagsExtension` is a lightweight typed lookup token, exported from the root, core, and flags entrypoints. `resolveExtension(FeatureFlagsExtension)` resolves to undefined when flags is disabled or failed to install. The extension's `getFeatureFlag()` returns undefined until a value is available. A disabled flag returns an object with `enabled: false`. Reads emit deduplicated flag-called analytics through ordinary capture; subscriptions do not. `updateFlags(values, payloads?, { merge })` injects flag values.
|
|
204
200
|
|
|
205
|
-
|
|
201
|
+
Pass `getFeatureFlag(key, { sendFeatureFlagEvent: false })` for a read without an exposure event. Omitted or undefined `sendFeatureFlagEvent` defaults to sending. `getAllFeatureFlags()` returns a synchronous snapshot of all known structured results, including disabled flags and payloads, without exposure events. Changing the snapshot or its JSON payloads does not change stored flags.
|
|
202
|
+
|
|
203
|
+
`getFeatureFlag(key, { fresh: true })` returns undefined unless the latest flag request in this instance succeeded, ignoring bootstrap and persisted values before then, as in `posthog-js`. Use it to avoid briefly showing a feature that has since been disabled. The `fresh` option does not itself force or await a reload; ordinary stale-cache auto-refresh still applies. Use `reloadFeatureFlags()` to request a remote evaluation and await its outcome before reading again:
|
|
206
204
|
|
|
207
205
|
```ts
|
|
208
206
|
if (featureFlags) {
|
|
@@ -215,6 +213,8 @@ if (featureFlags) {
|
|
|
215
213
|
|
|
216
214
|
The promise resolves with `loaded`, `error`, `skipped` (evaluation is disabled or unavailable), or `cancelled` (reset or disposal). It does not reject on request failures. Calls made before a request starts share that evaluation; calls during an active request wait for a follow-up evaluation. Cached values and `updateFlags()` do not complete a reload. `onFeatureFlags` remains a subscription to value changes, separate from reload completion.
|
|
217
215
|
|
|
216
|
+
`onReloading(callback)` observes automatic and explicit reload starts, before the debounced request. It does not replay an earlier start. A reload requested from the callback joins the starting request. Its returned `Disposable` stops that subscription; disposing the client stops all reload notifications.
|
|
217
|
+
|
|
218
218
|
For static inclusion, import the factory explicitly and pass the same configuration:
|
|
219
219
|
|
|
220
220
|
```ts
|
|
@@ -226,6 +226,27 @@ const posthog = await createPostHog({
|
|
|
226
226
|
})
|
|
227
227
|
```
|
|
228
228
|
|
|
229
|
+
Use the local property controls when evaluation needs context that has not reached ingestion yet:
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
posthog.featureFlags?.setPersonPropertiesForFlags({ plan: 'pro' })
|
|
233
|
+
posthog.featureFlags?.setGroupPropertiesForFlags({ organization: { employees: 25 } }, false)
|
|
234
|
+
await posthog.featureFlags?.reloadFeatureFlags()
|
|
235
|
+
posthog.featureFlags?.resetPersonPropertiesForFlags(false)
|
|
236
|
+
posthog.featureFlags?.resetGroupPropertiesForFlags('organization')
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Setters merge properties, including within each group type. Setters and resets reload by default; pass `false` to defer evaluation. Group reset clears one group type, or all group overrides when called without a group type. These controls do not identify a person, associate group membership, update profiles, or emit analytics. Local changes and flag evaluation requests remain available when capture is denied, as in `posthog-js`. Overrides use the client's configured persistence, survive recreation when storage is enabled, and clear on `reset()`. Disposed flags instances ignore these calls.
|
|
240
|
+
|
|
241
|
+
Early-access controls are also available on `posthog.featureFlags`:
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
posthog.featureFlags?.getEarlyAccessFeatures((features) => console.log(features), true, ['beta'])
|
|
245
|
+
posthog.featureFlags?.updateEarlyAccessFeatureEnrollment('new-onboarding', true, 'beta')
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
`getEarlyAccessFeatures(callback, forceReload?, stages?)` reuses cached definitions unless forced. Stage filters apply to requests, not an existing cache; force a reload when changing stages. As in `posthog-js`, any response with a JSON body replaces the cached definitions and reaches the callback, even when the request failed. Listing does not carry person data, so it is also requested while capture is opted out, matching `posthog-js`. Enrollment updates the stored flag value and person evaluation context immediately (active bootstrap values still take precedence until flags reload, as in `posthog-js`), then captures `$feature_enrollment_update` through ordinary consent gating. The optional stage and cached feature name are included in that event. Listing callbacks are isolated from application exceptions and stop after disposal. `EarlyAccessFeature`, `EarlyAccessFeatureCallback`, and `EarlyAccessFeatureStage` types are exported from the root and `/flags` entrypoints.
|
|
249
|
+
|
|
229
250
|
An explicit extension takes precedence over the top-level option, including `flags: false`. `featureFlagEvaluation: false` keeps local/bootstrap values without requesting remote evaluation; remote configuration remains available. Other options are `bootstrap.featureFlagPayloads`, `flagKeys`, `cacheTtlMs`, `refreshIntervalMs`, `deduplicateCallsPerSession`, and `onlyEvaluateSurveyFeatureFlags`. Refresh defaults to five minutes with idle backoff; `refreshIntervalMs: 0` disables automatic refresh. The manual `@posthog/browser/core` entrypoint supports explicit flags without referencing the automatic loader.
|
|
230
251
|
|
|
231
252
|
Flags uses the client's key-value store and configured persistence. With `storage: false`, values remain in memory. Reset clears flag state along with the client's other persisted state.
|
|
@@ -236,15 +257,15 @@ Creating an extension does not initialize it. Pass it in the `extensions` option
|
|
|
236
257
|
|
|
237
258
|
### Lifecycle notifications
|
|
238
259
|
|
|
239
|
-
|
|
260
|
+
Extensions receive the `IPostHog` client in `setup()`. It exposes installed products, asynchronous dependency resolution, and `onIdentify`, `onChangeProperties`, `onGroup`, `onGroupsReset` and `onReset` listeners. Identification uses `onIdentify`; person-property setters use `onChangeProperties` with `set`, `setOnce` and `unset` fields. Identification with properties publishes both kinds of notification. Group-only reset uses `onGroupsReset`; full identity reset uses `onReset`. These notifications fire synchronously after local state updates, independently of capture consent, and do not replay earlier operations. Listener errors are logged without stopping other listeners. Dispose subscriptions when the extension is disposed.
|
|
240
261
|
|
|
241
262
|
```ts
|
|
242
|
-
import type {
|
|
263
|
+
import type { Disposable, IPostHog } from '@posthog/browser'
|
|
243
264
|
|
|
244
265
|
let subscription: Disposable | undefined
|
|
245
266
|
const extension = {
|
|
246
267
|
name: 'identity-observer',
|
|
247
|
-
setup(client:
|
|
268
|
+
setup(client: IPostHog) {
|
|
248
269
|
subscription = client.onIdentify(({ distinctId, previousDistinctId }) => {
|
|
249
270
|
console.log(previousDistinctId, distinctId)
|
|
250
271
|
})
|
|
@@ -286,7 +307,7 @@ An explicit logs extension takes precedence over the top-level option, including
|
|
|
286
307
|
|
|
287
308
|
Logs includes the current URL as `url.full`. Configure `logs: { urlCapture: { path: true, search: false, hash: false } }` or pass the same `urlCapture` option to `logs()` to select which URL components are retained. These are the defaults, including for omitted fields: the origin and pathname are retained, while query parameters and fragments are removed. With `path: false`, the pathname becomes `/`. Invalid URLs are omitted. Component selection does not redact sensitive values within retained components.
|
|
288
309
|
|
|
289
|
-
The logs extension's `flush()` awaits both log queues. `posthog.flush()` awaits all installed extensions' flush methods, including
|
|
310
|
+
The logs extension's `flush()` awaits both log queues. `posthog.flush()` awaits the client's capture queue and all installed extensions' flush methods, including logs. Consent denial and reset discard queued logs; later opt-in does not revive them. Shutdown awaits normal log delivery within its timeout before cleanup. On pagehide, logs attempt best-effort Beacon delivery with keepalive Fetch fallback. Console hooks and page lifecycle listeners are removed on disposal. Logs use their own `/i/v1/logs` endpoint, JSON payload, and project-token query authentication, never the analytics queue. The existing SDK `logger` remains diagnostic output; application logs use the logs extension's `captureLog()`.
|
|
290
311
|
|
|
291
312
|
## Surveys
|
|
292
313
|
|
|
@@ -304,7 +325,9 @@ feedback?.getSurveys((surveys, context) => {
|
|
|
304
325
|
const eligibility = await feedback?.canRenderSurvey('feedback')
|
|
305
326
|
```
|
|
306
327
|
|
|
307
|
-
The options are `automaticDisplay` (default `true`), `requestTimeoutMs` (default `10_000`), `prefillFromUrl` (default `false`), `overrideDisplayLanguage`, `prepareStylesheet`, and `getCurrentUrl`. `getActiveMatchingSurveys(callback, forceReload?)` applies targeting; `onSurveysLoaded(callback)` returns a disposable subscription; `cancelPendingSurvey(id)` cancels pending display.
|
|
328
|
+
The options are `automaticDisplay` (default `true`), `requestTimeoutMs` (default `10_000`), `prefillFromUrl` (default `false`), `overrideDisplayLanguage`, `prepareStylesheet`, and `getCurrentUrl`. `getActiveMatchingSurveys(callback, forceReload?)` applies targeting; `onSurveysLoaded(callback)` returns a disposable subscription; `cancelPendingSurvey(id)` cancels pending display.
|
|
329
|
+
|
|
330
|
+
`onActiveMatchingSurveysChanged(callback)` loads surveys for manual use and returns a disposable subscription to the active matching set. It delivers the current set once loaded, then changes after event and action triggers, cancellation, captured `$pageview` events, survey display, dismissal and responses, feature-flag updates, definition refreshes and reset. Unchanged results are not delivered again. URL conditions are re-evaluated on captured pageviews, so capture `$pageview` after client-side navigation. Selector, device and wait-period conditions are checked on those updates rather than by observing the DOM or time. While surveys are unavailable the callback receives `([], { isLoaded: false })`, with an `error` when a load attempt fails; the subscription remains for later updates. Captured `survey dismissed` and `survey sent` events with a `$survey_id` mark that survey as seen, including events from an application's own survey UI. Capture consent still gates rendering and responses.
|
|
308
331
|
|
|
309
332
|
Use `surveys: false` to omit automatic inclusion. An explicitly supplied instance takes precedence, including over `false`. Importing the factory below includes orchestration only; rendering, styles, and HTML sanitization still load dynamically when needed. Importing the entrypoint or constructing the extension does not access browser globals.
|
|
310
333
|
|
|
@@ -321,47 +344,52 @@ feedback.displaySurvey('feedback')
|
|
|
321
344
|
|
|
322
345
|
Await client creation before using extension controls.
|
|
323
346
|
|
|
324
|
-
The manual core entrypoint never loads surveys automatically. Extension lookup returns undefined when surveys is omitted or fails setup. Without a document, rendering is unavailable. Disposal removes renderer listeners, polling, pending displays, and rendered elements. Survey abandonment uses
|
|
347
|
+
The manual core entrypoint never loads surveys automatically. Extension lookup returns undefined when surveys is omitted or fails setup. Without a document, rendering is unavailable. Disposal removes renderer listeners, polling, pending displays, and rendered elements. Survey abandonment uses the client's pagehide keepalive handoff, which delivery attaches when the client is constructed.
|
|
325
348
|
|
|
326
|
-
Definitions and event activation state use the
|
|
349
|
+
Definitions and event activation state use the client's shared `core` key-value store. Survey interaction state—seen markers, partial answers, and abandonment markers—uses dedicated browser localStorage, independently of configured SDK persistence, including `storage: false`. Partial answers fall back to memory when localStorage writes fail; abandonment is skipped when its marker cannot be read. Client reset clears persisted extension data, runtime state, and localStorage seen markers, partial answers, and the last-seen date. Abandonment markers are retained, matching legacy survey reset behavior. Event targeting works through admitted captures; DOM-action selector targeting uses the installed autocapture extension, including the default dynamic instance. Cached definitions hydrate their triggers without requiring a refresh. Selectors registered before autocapture setup are retained; later successful definition snapshots replace the selector set, while failed refreshes retain it. Both extension orders are supported. Matching retains the shared exact-target semantics, including SVG attribution to its enclosing control. URL-constrained actions use survey targeting context when the event has no URL; this local fallback does not add URL data to the captured event.
|
|
327
350
|
|
|
328
351
|
## Capture and delivery
|
|
329
352
|
|
|
330
|
-
Capture, immediate capture, identity
|
|
353
|
+
Capture, immediate capture, identity, reset and event-property registration are client methods, backed by the client's capture pipeline and the delivery its entrypoint selects. Feature flags initialize during startup. When their options are omitted, logs, surveys orchestration and autocapture load on existing saved-state or remote-config signals, or explicit asynchronous acquisition. Their collection and display retain their own consent and remote-configuration gates; survey rendering is a further deferred chunk.
|
|
331
354
|
|
|
332
|
-
`
|
|
355
|
+
`posthog.capture()` runs synchronously. Its `false` result is a rate-limit backpressure signal, not a general rejection signal. `true` is neither an admission nor a delivery acknowledgement: consent, lifecycle, filtering, invalid properties or queue limits can suppress an event while it still returns `true`. Use `captureImmediate()` and check its summary when persistence matters. Capture never waits for network delivery. `flush()` delivers queued work and resolves without discarding unexpired queued events when delivery is unavailable. Analytics retains at most 1,000 queued events and 8 MiB of active-plus-queued finalized analytics messages; queued work expires strictly after one hour on the next queue interaction. Queue overflow evicts the oldest queued prefix, while active bytes cannot be recalled and can cause a new event to be rejected.
|
|
333
356
|
|
|
334
357
|
Queued and immediate capture omit null or undefined object properties from delivered events, including nested objects and objects inside arrays. Array positions are preserved; null and undefined array entries are sent as JSON `null`. Events with no remaining custom properties are still delivered with their SDK metadata.
|
|
335
358
|
|
|
336
359
|
Use `captureImmediate()` only when the caller needs a terminal delivery outcome before continuing:
|
|
337
360
|
|
|
338
361
|
```ts
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
if (!summary) {
|
|
342
|
-
console.warn('Analytics is unavailable')
|
|
343
|
-
} else if (summary.error) {
|
|
362
|
+
const summary = await posthog.captureImmediate('import_completed', { source: 'warehouse' })
|
|
363
|
+
if (summary.error) {
|
|
344
364
|
console.warn('Immediate capture failed', summary.error)
|
|
345
365
|
} else if (summary.submitted !== 1 || !summary.allPersisted) {
|
|
346
366
|
// Capture V1 did not confirm persistence of this event.
|
|
347
367
|
}
|
|
348
368
|
```
|
|
349
369
|
|
|
350
|
-
Immediate capture finalizes the event through the same consent, identity, session, protected-property, size, and rate-limit boundaries, then bypasses the lane and sends inline through the same Capture V1 sender. A valid `2xx` resolves to a `CaptureSummary`; `drop`, final `retry`, and missing outcomes set `allPersisted` to `false`, while `warning` counts as persisted. Terminal HTTP failures, exhausted transport retries, malformed responses, cancellation, and unavailable delivery resolve with `summary.error` and `allPersisted: false`, retaining any known partial outcomes. These failures do not reject the promise. Local non-admission resolves an empty summary, so durability-sensitive callers must check both `submitted` and `allPersisted`. Immediate requests can overtake buffered events and run concurrently with each other; they are never retained for a later `flush()`. An
|
|
370
|
+
Immediate capture finalizes the event through the same consent, identity, session, protected-property, size, and rate-limit boundaries, then bypasses the lane and sends inline through the same Capture V1 sender. A valid `2xx` resolves to a `CaptureSummary`; `drop`, final `retry`, and missing outcomes set `allPersisted` to `false`, while `warning` counts as persisted. Terminal HTTP failures, exhausted transport retries, malformed responses, cancellation, and unavailable delivery resolve with `summary.error` and `allPersisted: false`, retaining any known partial outcomes. These failures do not reject the promise. Local non-admission resolves an empty summary, so durability-sensitive callers must check both `submitted` and `allPersisted`. Immediate requests can overtake buffered events and run concurrently with each other; they are never retained for a later `flush()`. An explicit opt-out cancels pending immediate dispatch and retries, even if the user opts in again; a cleared choice (`reset()` or `clearOptInOut()`) does not. Already-dispatched requests may finish.
|
|
371
|
+
|
|
372
|
+
`captureImmediate()` is available on both entrypoints because delivery is part of the client. The manual core captures even without supplied extensions: it sends the initial `$pageview` unless `capturePageview: false`, and an installed flags extension sends `$feature_flag_called` the first time each flag value is read.
|
|
351
373
|
|
|
352
|
-
|
|
374
|
+
Capture V1 delivery sends FIFO batches of at most 100 events and partitions large backlogs by exact uncompressed envelope size. `flushAt` defaults to 20 and triggers delivery by queued count; `flushInterval` defaults to 3,000 milliseconds and triggers delivery by age. Set `flushInterval: 0` to disable timer delivery. Explicit `flush()`, shutdown, and `capture(event, properties, { delivery: 'immediate' })` bypass both thresholds. A `delivery: 'immediate'` capture stays in the lane with normal retries and unload handoff, and starts a drain now that sends queued events with it. Prefer it over `capture()` followed by `flush()` when the event must not wait behind a full offline backlog or, with `flushInterval: 0`, behind a failed older batch: if an older batch exhausts its retries before the event is attempted, the lane makes one more drain instead of waiting for another trigger. `{ delivery: 'unload' }` sends the event through best-effort keepalive Fetch and does not confirm persistence. Retry-exhausted transient failures remain in the bounded lane for a later interval, reconnect, `delivery: 'immediate'` capture, or explicit flush rather than hot-looping or being discarded.
|
|
353
375
|
|
|
354
|
-
|
|
376
|
+
`posthog.setConfig({ debug, analytics: { personProfiles } })` changes only these options on a running client; other options are fixed at creation. `posthog.debug()` and `posthog.debug(false)` toggle diagnostic logs at runtime and are not persisted across page loads.
|
|
355
377
|
|
|
356
378
|
Both factories start one JSON remote-config request during initialization, without waiting for it before capture or factory completion. `remoteConfig` supplies an inline result instead of making a request. The default loader uses Fetch and `GET /array/{projectToken}/config`. Recognized PostHog US/EU hosts resolve to the corresponding assets host; custom hosts retain their configured base, including path prefixes. Loading is independent of capture consent. `fetch: false` disables built-in loading. Failure or the default 10-second `remoteConfigTimeoutMs` publishes `{ ok: false }` once, with no automatic retry; shutdown cancels the wait and suppresses late publication.
|
|
357
379
|
|
|
358
380
|
When remote configuration advertises gzip, eligible normal batches use native `CompressionStream`; delivery remains uncompressed while configuration is unresolved or compression is unavailable, invalid, stalled, or larger than the JSON body. While offline, finalized events remain admitted and avoid network attempts until an `online` notification. On `pagehide`, or `unload` where `pagehide` is unavailable, queued analytics receive one synchronous uncompressed handoff through headered keepalive Fetch under one conservative aggregate body budget. Beacon remains disabled until Capture V1 supports the required metadata without request headers.
|
|
359
381
|
|
|
360
|
-
One initial `$pageview` is admitted through the same queue after configured extensions install. Set `capturePageview: false` to disable it. Navigation tracking, URL/title enrichment, and page-leave capture remain optional product behavior.
|
|
382
|
+
One initial `$pageview` is admitted through the same queue after configured extensions install. Set `capturePageview: false` to disable it. Events captured after a `$pageview` in the same session carry its UUID as `$pageview_id`, and `posthog.getPageViewId()` returns it. Navigation tracking, URL/title enrichment, and page-leave capture remain optional product behavior.
|
|
383
|
+
|
|
384
|
+
Consent is stored separately from identity under `__ph_opt_in_out_<project-token>`. Use `consentPersistenceName` to supply a shared key verbatim. The client reads established `1`/`true`/`yes` and `0`/`false`/`no` values, including raw boolean and numeric compatibility values, and writes `1` or `0`. Configured extensions still initialize under prior denial. Identity, key-value persistence, remote configuration, feature flag evaluation and the early-access listing remain available, as in `posthog-js`, while analytics capture and other request transmission are consent-gated.
|
|
385
|
+
|
|
386
|
+
`posthog.getExplicitConsentStatus()` returns `'granted'`, `'denied'`, or `'pending'` when the user has not chosen, independently of `optOutByDefault`. `posthog.clearOptInOut()` forgets the stored choice and returns consent to the configured default. `reset()` also forgets the stored choice, as posthog-js does: a user who opted out is captured again after a logout reset unless the app calls `optOut()` again, and with `optOutByDefault` capture stops after `reset()` until the app calls `optIn()` again. Neither call discards analytics events captured before it, in this or another tab; they are still delivered.
|
|
387
|
+
|
|
388
|
+
Session and window IDs are created on the first successfully admitted capture. Rejected work does not create or advance them. Idle timeout, maximum length, and reset rotate both IDs. Same-origin tabs share the active session while retaining distinct window IDs; ordinary reloads preserve the window ID and copied tab storage receives a new one. Session rotation is activity-driven and starts no core timer. Session and window IDs are UUIDv7, as in posthog-js. `posthog.onSessionId(({ sessionId, windowId }) => …)` reports the current session without creating one, then every change; dispose the returned subscription to stop.
|
|
361
389
|
|
|
362
|
-
|
|
390
|
+
`reset()` starts a new anonymous identity and session and keeps the device ID. Pass `reset(true)` or `reset({ resetDeviceId: true })` to also replace the device ID, and `reset({ bootstrap: { distinctId, isIdentifiedId, sessionId } })` to seed the new identity and next session. The setup `bootstrap` option accepts the same values. A stored identity takes precedence, except that an identified bootstrap ID identifies a stored anonymous user, as in posthog-js. Use `bootstrap.sessionId` to continue a UUIDv7 session ID passed from another domain.
|
|
363
391
|
|
|
364
|
-
|
|
392
|
+
Identity and session state live in the configured storage only. To share them across subdomains, and with posthog-js through its `ph_<project-token>_posthog` cookie, pass `cookie: cookiePersistence()` from `@posthog/browser/persistence/cookie`. The cookie is opt-in, uses `SameSite=Lax`, is `Secure` on HTTPS pages, and accepts `crossSubdomain`, `secure`, `expirationDays`, and `name` options. Consent stays in the configured storage.
|
|
365
393
|
|
|
366
394
|
A compact in-memory token bucket admits 10 events per second with a burst of 100 and emits a bypassed aggregate ingestion warning when a runaway loop first reaches the limit. `shutdown(timeoutMs)` stops new work, makes one bounded normal flush attempt, removes timers and lifecycle listeners, and is idempotent. `dispose()` uses the same shutdown path.
|
|
367
395
|
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import type { CorePostHogOptions, IPostHog } from '../../core/types';
|
|
2
|
-
/** Creates
|
|
2
|
+
/** Creates the browser client with durable delivery and only explicitly supplied products. */
|
|
3
3
|
export declare const createPostHog: (options: CorePostHogOptions) => Promise<IPostHog>;
|
|
4
4
|
export { version } from '../../primitives/version';
|
|
5
5
|
export { FeatureFlagsExtension, type FeatureFlags } from '../../products/flags/flags-token';
|
|
6
|
-
export type {
|
|
7
|
-
export type {
|
|
8
|
-
export type { AnalyticsOptions, ApiResponse, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, NewSessionInfo, NewSessionReason, IPostHog, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
|
|
6
|
+
export type { BrowserExtension, IdentifyInfo, GroupInfo } from '../../core/context/browser-client';
|
|
7
|
+
export type { AnalyticsOptions, ApiResponse, BrowserFetch, BootstrapOptions, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, ExplicitConsentStatus, Extension, NewSessionInfo, NewSessionReason, IPostHog, RemoteConfig, ResetOptions, RuntimeOptions, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
|
|
9
8
|
export type { PersonProfileMode } from '../../products/analytics/analytics-options';
|
|
@@ -33,9 +33,10 @@ __webpack_require__.d(__webpack_exports__, {
|
|
|
33
33
|
version: ()=>version_js_namespaceObject.version
|
|
34
34
|
});
|
|
35
35
|
const posthog_js_namespaceObject = require("../../core/posthog.js");
|
|
36
|
+
const analytics_delivery_js_namespaceObject = require("../../products/analytics/delivery/analytics-delivery.js");
|
|
36
37
|
const version_js_namespaceObject = require("../../primitives/version.js");
|
|
37
38
|
const flags_token_js_namespaceObject = require("../../products/flags/flags-token.js");
|
|
38
|
-
const createPostHog = async (options)=>(0, posthog_js_namespaceObject.createPostHogCore)(options);
|
|
39
|
+
const createPostHog = async (options)=>(0, posthog_js_namespaceObject.createPostHogCore)(options, analytics_delivery_js_namespaceObject.createAnalyticsDelivery);
|
|
39
40
|
exports.FeatureFlagsExtension = __webpack_exports__.FeatureFlagsExtension;
|
|
40
41
|
exports.createPostHog = __webpack_exports__.createPostHog;
|
|
41
42
|
exports.version = __webpack_exports__.version;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createPostHogCore } from "../../core/posthog.mjs";
|
|
2
|
-
|
|
2
|
+
import { createAnalyticsDelivery } from "../../products/analytics/delivery/analytics-delivery.mjs";
|
|
3
|
+
const createPostHog = async (options)=>createPostHogCore(options, createAnalyticsDelivery);
|
|
3
4
|
export { version } from "../../primitives/version.mjs";
|
|
4
5
|
export { FeatureFlagsExtension } from "../../products/flags/flags-token.mjs";
|
|
5
6
|
export { createPostHog };
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import type { IPostHog, PostHogOptions } from '../../core/types';
|
|
2
|
-
/** Creates
|
|
2
|
+
/** Creates the browser client with durable delivery and on-demand products. */
|
|
3
3
|
export declare const createPostHog: (options: PostHogOptions) => Promise<IPostHog>;
|
|
4
|
-
export type { IAnalytics } from '../../products/analytics/analytics-api';
|
|
5
4
|
export { version } from '../../primitives/version';
|
|
6
5
|
export { FeatureFlagsExtension, type FeatureFlags } from '../../products/flags/flags-token';
|
|
7
|
-
export type {
|
|
8
|
-
export type {
|
|
9
|
-
export type { FlagsOptions, FlagsConfiguration, FlagsCallback, FeatureFlagResult, FeatureFlagsReloadResult, } from '../../products/flags/flags-options';
|
|
6
|
+
export type { BrowserExtension, IdentifyInfo, GroupInfo } from '../../core/context/browser-client';
|
|
7
|
+
export type { AnalyticsOptions, ApiResponse, BrowserFetch, BootstrapOptions, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, ExplicitConsentStatus, Extension, NewSessionInfo, NewSessionReason, IPostHog, PostHogOptions, RemoteConfig, ResetOptions, RuntimeOptions, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
|
|
8
|
+
export type { EarlyAccessFeature, EarlyAccessFeatureCallback, EarlyAccessFeatureStage, FlagsOptions, FlagsConfiguration, FlagsCallback, FlagsReadOptions, FeatureFlagResult, FeatureFlagsReloadResult, } from '../../products/flags/flags-options';
|
|
10
9
|
export type { LogsOptions, LogsConfiguration, CaptureLogOptions } from '../../products/logs/logs-options';
|
|
11
10
|
export type { SurveysOptions, SurveysConfiguration, Survey, SurveyCallback, DisplaySurveyOptions, SurveyRenderReason, } from '../../products/surveys/surveys-options';
|
|
12
11
|
export type { AutocaptureOptions, AutocaptureConfiguration, RageclickOptions, } from '../../products/autocapture/autocapture-options';
|
|
@@ -33,12 +33,13 @@ __webpack_require__.d(__webpack_exports__, {
|
|
|
33
33
|
version: ()=>version_js_namespaceObject.version
|
|
34
34
|
});
|
|
35
35
|
const posthog_js_namespaceObject = require("../../core/posthog.js");
|
|
36
|
+
const analytics_delivery_js_namespaceObject = require("../../products/analytics/delivery/analytics-delivery.js");
|
|
36
37
|
const external_root_composition_js_namespaceObject = require("./root-composition.js");
|
|
37
38
|
const version_js_namespaceObject = require("../../primitives/version.js");
|
|
38
39
|
const flags_token_js_namespaceObject = require("../../products/flags/flags-token.js");
|
|
39
40
|
const createPostHog = async (options)=>{
|
|
40
41
|
const { extensions, loaders, automatic, loadingErrors } = (0, external_root_composition_js_namespaceObject.createProductComposition)(options);
|
|
41
|
-
const client = await (0, posthog_js_namespaceObject.createPostHogCore)(options, extensions, loaders, automatic);
|
|
42
|
+
const client = await (0, posthog_js_namespaceObject.createPostHogCore)(options, analytics_delivery_js_namespaceObject.createAnalyticsDelivery, extensions, loaders, automatic);
|
|
42
43
|
for (const [label, error] of loadingErrors.reverse())client.logger.error(`Automatic ${label} loading failed`, error);
|
|
43
44
|
return client;
|
|
44
45
|
};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { createPostHogCore } from "../../core/posthog.mjs";
|
|
2
|
+
import { createAnalyticsDelivery } from "../../products/analytics/delivery/analytics-delivery.mjs";
|
|
2
3
|
import { createProductComposition } from "./root-composition.mjs";
|
|
3
4
|
const createPostHog = async (options)=>{
|
|
4
5
|
const { extensions, loaders, automatic, loadingErrors } = createProductComposition(options);
|
|
5
|
-
const client = await createPostHogCore(options, extensions, loaders, automatic);
|
|
6
|
+
const client = await createPostHogCore(options, createAnalyticsDelivery, extensions, loaders, automatic);
|
|
6
7
|
for (const [label, error] of loadingErrors.reverse())client.logger.error(`Automatic ${label} loading failed`, error);
|
|
7
8
|
return client;
|
|
8
9
|
};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { PostHogOptions } from '../../core/types';
|
|
1
|
+
import type { BrowserExtension } from '../../core/context/browser-client';
|
|
2
|
+
import type { IPostHog, PostHogOptions } from '../../core/types';
|
|
3
3
|
import type { AutomaticExtension, ExtensionLoader } from '../../core/extensions/registry';
|
|
4
4
|
interface ProductComposition {
|
|
5
5
|
extensions: BrowserExtension[];
|
|
6
|
-
loaders: Record<string, ExtensionLoader<
|
|
7
|
-
automatic: AutomaticExtension<
|
|
6
|
+
loaders: Record<string, ExtensionLoader<IPostHog>>;
|
|
7
|
+
automatic: AutomaticExtension<IPostHog>[];
|
|
8
8
|
loadingErrors: Array<[string, unknown]>;
|
|
9
9
|
}
|
|
10
10
|
export declare const createProductComposition: (options: PostHogOptions) => ProductComposition;
|
|
@@ -35,7 +35,6 @@ const surveys_config_namespaceObject = require("@posthog/browser-common/surveys-
|
|
|
35
35
|
const autocapture_options_js_namespaceObject = require("../../products/autocapture/autocapture-options.js");
|
|
36
36
|
const surveys_options_js_namespaceObject = require("../../products/surveys/surveys-options.js");
|
|
37
37
|
const logs_options_js_namespaceObject = require("../../products/logs/logs-options.js");
|
|
38
|
-
const analytics_options_js_namespaceObject = require("../../products/analytics/analytics-options.js");
|
|
39
38
|
const activateFromSignals = (hasSaved, enabled)=>(host, acquire)=>{
|
|
40
39
|
let loading;
|
|
41
40
|
host.onRemoteConfig((result)=>{
|
|
@@ -61,16 +60,6 @@ const registerProduct = (composition, name, label, configure)=>{
|
|
|
61
60
|
]);
|
|
62
61
|
}
|
|
63
62
|
};
|
|
64
|
-
const configureAnalytics = (options, composition)=>{
|
|
65
|
-
let configuration;
|
|
66
|
-
if (composition.extensions.some((extension)=>'analytics' === extension.name)) configuration = false;
|
|
67
|
-
else try {
|
|
68
|
-
configuration = options?.analytics;
|
|
69
|
-
} catch {}
|
|
70
|
-
const snapshot = (0, analytics_options_js_namespaceObject.snapshotAutomaticAnalyticsOptions)(configuration || {});
|
|
71
|
-
if (false !== configuration) composition.loaders.analytics = ()=>import("../../products/analytics/automatic-analytics.js").then(({ analytics })=>analytics(snapshot));
|
|
72
|
-
return snapshot;
|
|
73
|
-
};
|
|
74
63
|
const configureFlags = (options)=>{
|
|
75
64
|
const configuration = options?.flags;
|
|
76
65
|
if (false === configuration) return;
|
|
@@ -118,11 +107,6 @@ const createProductComposition = (options)=>{
|
|
|
118
107
|
automatic: [],
|
|
119
108
|
loadingErrors: []
|
|
120
109
|
};
|
|
121
|
-
const analyticsOptions = configureAnalytics(options, composition);
|
|
122
|
-
if ('eager' === analyticsOptions.load) composition.automatic.push({
|
|
123
|
-
name: 'analytics',
|
|
124
|
-
activate: (_host, acquire)=>acquire()
|
|
125
|
-
});
|
|
126
110
|
registerProduct(composition, 'featureFlags', 'flags', ()=>configureFlags(options));
|
|
127
111
|
registerProduct(composition, 'logs', 'logs', ()=>configureLogs(options));
|
|
128
112
|
registerProduct(composition, 'surveys', 'surveys', ()=>configureSurveys(options));
|
|
@@ -3,7 +3,6 @@ import { SURVEYS } from "@posthog/browser-common/surveys-config";
|
|
|
3
3
|
import { snapshotAutocaptureOptions } from "../../products/autocapture/autocapture-options.mjs";
|
|
4
4
|
import { snapshotSurveysOptions } from "../../products/surveys/surveys-options.mjs";
|
|
5
5
|
import { snapshotLogsOptions } from "../../products/logs/logs-options.mjs";
|
|
6
|
-
import { snapshotAutomaticAnalyticsOptions } from "../../products/analytics/analytics-options.mjs";
|
|
7
6
|
const activateFromSignals = (hasSaved, enabled)=>(host, acquire)=>{
|
|
8
7
|
let loading;
|
|
9
8
|
host.onRemoteConfig((result)=>{
|
|
@@ -29,16 +28,6 @@ const registerProduct = (composition, name, label, configure)=>{
|
|
|
29
28
|
]);
|
|
30
29
|
}
|
|
31
30
|
};
|
|
32
|
-
const configureAnalytics = (options, composition)=>{
|
|
33
|
-
let configuration;
|
|
34
|
-
if (composition.extensions.some((extension)=>'analytics' === extension.name)) configuration = false;
|
|
35
|
-
else try {
|
|
36
|
-
configuration = options?.analytics;
|
|
37
|
-
} catch {}
|
|
38
|
-
const snapshot = snapshotAutomaticAnalyticsOptions(configuration || {});
|
|
39
|
-
if (false !== configuration) composition.loaders.analytics = ()=>import("../../products/analytics/automatic-analytics.mjs").then(({ analytics })=>analytics(snapshot));
|
|
40
|
-
return snapshot;
|
|
41
|
-
};
|
|
42
31
|
const configureFlags = (options)=>{
|
|
43
32
|
const configuration = options?.flags;
|
|
44
33
|
if (false === configuration) return;
|
|
@@ -86,11 +75,6 @@ const createProductComposition = (options)=>{
|
|
|
86
75
|
automatic: [],
|
|
87
76
|
loadingErrors: []
|
|
88
77
|
};
|
|
89
|
-
const analyticsOptions = configureAnalytics(options, composition);
|
|
90
|
-
if ('eager' === analyticsOptions.load) composition.automatic.push({
|
|
91
|
-
name: 'analytics',
|
|
92
|
-
activate: (_host, acquire)=>acquire()
|
|
93
|
-
});
|
|
94
78
|
registerProduct(composition, 'featureFlags', 'flags', ()=>configureFlags(options));
|
|
95
79
|
registerProduct(composition, 'logs', 'logs', ()=>configureLogs(options));
|
|
96
80
|
registerProduct(composition, 'surveys', 'surveys', ()=>configureSurveys(options));
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type {
|
|
3
|
-
import type { IAnalyticsExtension } from '../../products/analytics/analytics-internal';
|
|
1
|
+
import type { DeepReadonly, Extension } from '@posthog/browser-common';
|
|
2
|
+
import type { IPostHog } from '../types';
|
|
4
3
|
import type { FeatureFlags } from '../../products/flags/flags-token';
|
|
5
|
-
import type { FlagsExtension } from '../../products/flags/flags-internal';
|
|
6
4
|
import type { LogsExtension } from '../../products/logs/logs-internal';
|
|
7
5
|
import type { SurveysExtension } from '../../products/surveys/surveys-internal';
|
|
8
6
|
import type { ConsentState } from '../state/state';
|
|
@@ -29,9 +27,9 @@ export interface ConsentChangeInfo {
|
|
|
29
27
|
readonly current: ConsentState;
|
|
30
28
|
readonly previous: ConsentState;
|
|
31
29
|
}
|
|
32
|
-
|
|
30
|
+
/** The shared extension contract, hosted by the browser client itself. */
|
|
31
|
+
export type BrowserExtension = Extension<IPostHog>;
|
|
33
32
|
export interface BrowserProducts {
|
|
34
|
-
analytics: IAnalytics;
|
|
35
33
|
featureFlags: FeatureFlags;
|
|
36
34
|
logs: LogsExtension;
|
|
37
35
|
surveys: SurveysExtension;
|
|
@@ -39,32 +37,3 @@ export interface BrowserProducts {
|
|
|
39
37
|
setElementSelectors(selectors: Set<string>): void;
|
|
40
38
|
};
|
|
41
39
|
}
|
|
42
|
-
export interface InternalBrowserProducts extends BrowserProducts {
|
|
43
|
-
analytics: IAnalyticsExtension;
|
|
44
|
-
featureFlags: FlagsExtension;
|
|
45
|
-
}
|
|
46
|
-
export type BrowserExtensionAccess<Products extends BrowserProducts = BrowserProducts> = Readonly<Partial<Products>> & {
|
|
47
|
-
resolveExtension<T extends BrowserExtension>(token: ExtensionToken<T>): Promise<T | undefined>;
|
|
48
|
-
resolveExtension<Name extends keyof Products>(name: Name): Promise<Products[Name] | undefined>;
|
|
49
|
-
resolveExtension<T extends BrowserExtension = BrowserExtension>(name: string): Promise<T | undefined>;
|
|
50
|
-
};
|
|
51
|
-
/** Shared Core capabilities, without application administration or product controls. */
|
|
52
|
-
export interface ICoreCapabilities extends Omit<Client, 'getExtension' | 'capture' | 'registerDynamicEventProperties' | 'isRateLimited' | 'onEvent'> {
|
|
53
|
-
/** Fires when consent changes, including changes observed from another tab. Does not replay. */
|
|
54
|
-
readonly onConsentChange: Listener<ConsentChangeInfo>;
|
|
55
|
-
/** Fires after identification, independently of capture consent. Does not replay. */
|
|
56
|
-
readonly onIdentify: Listener<IdentifyInfo>;
|
|
57
|
-
/** Fires after group membership or property updates, independently of capture consent. Does not replay. */
|
|
58
|
-
readonly onGroup: Listener<GroupInfo>;
|
|
59
|
-
/** Fires after group-only reset clears local membership. Does not replay. */
|
|
60
|
-
readonly onGroupsReset: Listener<void>;
|
|
61
|
-
/** Fires after local identity and persisted extension state are reset. Does not replay. */
|
|
62
|
-
readonly onReset: Listener<void>;
|
|
63
|
-
}
|
|
64
|
-
/** SDK-internal scoped view; shared implementations receive a separate Client adapter. */
|
|
65
|
-
export interface IPostHogInternal extends ICoreCapabilities, BrowserExtensionAccess<InternalBrowserProducts> {
|
|
66
|
-
readonly sharedClient: Client;
|
|
67
|
-
/** Local person-property changes, independently of capture consent. Does not replay. */
|
|
68
|
-
readonly onChangeProperties: Listener<ChangePropertiesInfo>;
|
|
69
|
-
readonly onEvent: Client['onEvent'];
|
|
70
|
-
}
|