@posthog/browser 0.4.2 → 0.5.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 (65) hide show
  1. package/ARCHITECTURE.md +34 -46
  2. package/README.md +56 -63
  3. package/dist/composition/npm/core.d.ts +2 -3
  4. package/dist/composition/npm/core.js +2 -1
  5. package/dist/composition/npm/core.mjs +2 -1
  6. package/dist/composition/npm/index.d.ts +3 -4
  7. package/dist/composition/npm/index.js +2 -1
  8. package/dist/composition/npm/index.mjs +2 -1
  9. package/dist/composition/npm/root-composition.d.ts +4 -4
  10. package/dist/composition/npm/root-composition.js +0 -16
  11. package/dist/composition/npm/root-composition.mjs +0 -16
  12. package/dist/core/context/browser-client.d.ts +4 -35
  13. package/dist/core/extensions/registry.d.ts +15 -36
  14. package/dist/core/extensions/registry.js +67 -198
  15. package/dist/core/extensions/registry.mjs +67 -198
  16. package/dist/core/posthog.d.ts +3 -2
  17. package/dist/core/posthog.js +104 -161
  18. package/dist/core/posthog.mjs +105 -162
  19. package/dist/core/state/state.d.ts +1 -0
  20. package/dist/core/state/state.js +5 -2
  21. package/dist/core/state/state.mjs +3 -3
  22. package/dist/core/types.d.ts +50 -12
  23. package/dist/primitives/version.js +1 -1
  24. package/dist/primitives/version.mjs +1 -1
  25. package/dist/products/analytics/analytics-core.d.ts +76 -0
  26. package/dist/products/analytics/analytics-core.js +472 -0
  27. package/dist/products/analytics/analytics-core.mjs +425 -0
  28. package/dist/products/analytics/analytics-internal.d.ts +14 -36
  29. package/dist/products/analytics/analytics-internal.js +2 -10
  30. package/dist/products/analytics/analytics-internal.mjs +1 -3
  31. package/dist/products/analytics/analytics-options.d.ts +0 -9
  32. package/dist/products/analytics/analytics-options.js +1 -38
  33. package/dist/products/analytics/analytics-options.mjs +1 -17
  34. package/dist/products/analytics/groups.d.ts +8 -0
  35. package/dist/products/analytics/groups.js +84 -0
  36. package/dist/products/analytics/groups.mjs +40 -0
  37. package/dist/products/analytics/person.d.ts +11 -0
  38. package/dist/products/analytics/person.js +91 -0
  39. package/dist/products/analytics/person.mjs +41 -0
  40. package/dist/products/autocapture/autocapture.js +2 -6
  41. package/dist/products/autocapture/autocapture.mjs +2 -6
  42. package/dist/products/flags/flags-internal.d.ts +1 -2
  43. package/dist/products/flags/flags-token.d.ts +3 -2
  44. package/dist/products/flags/flags.js +2 -7
  45. package/dist/products/flags/flags.mjs +2 -7
  46. package/dist/products/logs/logs.js +2 -5
  47. package/dist/products/logs/logs.mjs +2 -5
  48. package/dist/products/surveys/surveys-extension.js +4 -21
  49. package/dist/products/surveys/surveys-extension.mjs +4 -21
  50. package/package.json +4 -9
  51. package/dist/products/analytics/analytics-api.d.ts +0 -32
  52. package/dist/products/analytics/analytics-api.js +0 -18
  53. package/dist/products/analytics/analytics-api.mjs +0 -1
  54. package/dist/products/analytics/analytics-buffer.d.ts +0 -4
  55. package/dist/products/analytics/analytics-buffer.js +0 -41
  56. package/dist/products/analytics/analytics-buffer.mjs +0 -3
  57. package/dist/products/analytics/analytics-extension.d.ts +0 -87
  58. package/dist/products/analytics/analytics-extension.js +0 -649
  59. package/dist/products/analytics/analytics-extension.mjs +0 -611
  60. package/dist/products/analytics/analytics.d.ts +0 -6
  61. package/dist/products/analytics/analytics.js +0 -42
  62. package/dist/products/analytics/analytics.mjs +0 -4
  63. package/dist/products/analytics/automatic-analytics.d.ts +0 -3
  64. package/dist/products/analytics/automatic-analytics.js +0 -44
  65. package/dist/products/analytics/automatic-analytics.mjs +0 -6
package/ARCHITECTURE.md CHANGED
@@ -6,7 +6,7 @@ This document defines the bundle architecture for `@posthog/browser`.
6
6
 
7
7
  The goal is a behavior-complete core in the smallest practical bundle. Core behavior is a fixed constraint. Bundle size is the optimization objective.
8
8
 
9
- The root package must provide a useful capture host. It must preserve required capture admission, consent, identity, session, cross-context, no-throw, and extension-isolation behavior. The root acquires the complete analytics product when an application resolves it, an enabled initial pageview needs it, or a capture-producing product resolves its dependency. Once acquired, analytics owns a bounded buffer and lazily loads queue scheduling and Capture V1 delivery after admission; an explicitly supplied analytics extension includes delivery statically. Feature flags initialize by default. Logs, surveys orchestration and autocapture load from explicit configuration, saved-state or remote-configuration signals, or explicit resolution. The `@posthog/browser/core` entrypoint omits automatic product dynamic-import references for deliberate manual composition. Do not reduce bundle size by removing an invariant. Reimplement the invariant with a smaller mechanism or move only the policy that can safely begin after admission.
9
+ The root package must provide a useful capture host. It must preserve required capture admission, consent, identity, session, cross-context, no-throw, and extension-isolation behavior. The client owns capture admission and a bounded buffer; the root and `/core` deliver through Capture V1 with retries. Feature flags initialize by default. Logs, surveys orchestration and autocapture load from explicit configuration, saved-state or remote-configuration signals, or explicit resolution. The `@posthog/browser/core` entrypoint omits automatic product dynamic-import references for deliberate manual composition. Do not reduce bundle size by removing an invariant. Reimplement the invariant with a smaller mechanism or move only the policy that can safely begin after admission.
10
10
 
11
11
  Optional feature implementations must stay outside the initial root graph. Each public optional feature must remain in a removable chunk or explicit entrypoint, and the core entrypoint must not reference it. Application bundlers must be able to remove each unused module.
12
12
 
@@ -49,7 +49,7 @@ Source files are grouped by responsibility:
49
49
  | ------------------------------------ | ---------------------------------------------------------------------------------------- |
50
50
  | `src/composition/npm/` | Default and manual SDK compositions and product selection |
51
51
  | `src/composition/script/` | Self-initializing classic-script composition |
52
- | `src/core/` | Client lifecycle, shared contracts, scoped views, extension registry and state authority |
52
+ | `src/core/` | Client lifecycle, shared contracts, the KV store, extension registry and state authority |
53
53
  | `src/products/` | Product factories, operations and implementations |
54
54
  | `src/products/analytics/admission/` | Analytics event construction, buffering and admission |
55
55
  | `src/products/analytics/properties/` | Registered context and person-processing policy |
@@ -102,26 +102,20 @@ The core contains these responsibilities:
102
102
  - Device, anonymous, and identified state.
103
103
  - Session, window, and cross-context correctness.
104
104
  - Conflict-safe persistence and session-admission authority.
105
- - A scoped shared-client adapter that routes shared capture into analytics.
106
- - Coordination of one initial `$pageview` through the analytics owner without waiting for remote configuration or analytics delivery.
105
+ - The shared `Client` contract, implemented by the client itself and handed to every extension.
106
+ - Capture admission, identity operations, registered properties and one initial `$pageview`, without waiting for remote configuration.
107
107
  - A small control-plane Fetch path for immediate remote configuration and extension requests.
108
- - Consent and lifecycle authority for analytics dispatch, independent of delivery loading.
108
+ - Consent and lifecycle authority for analytics dispatch.
109
109
  - Extension lifecycle and isolation.
110
110
  - No-throw boundaries for customer-controlled and browser operations.
111
111
 
112
112
  Keep the capture pipeline fixed and direct. Use compact explicit state machines. Do not add a generic middleware framework or a general dependency-injection framework.
113
113
 
114
- The root `createPostHog` composition wrapper snapshots product options, keeps supplied instances, and injects literal dynamic product loaders into `createPostHogCore`. Core does not statically construct analytics, its buffer, rate limiter or property normalizers. The manual core entrypoint installs only supplied extensions and has no implicit analytics instance or automatic product imports. Owner properties are synchronous ready-only lookups; `resolveExtension()` starts an eligible loader, shares concurrent acquisition and waits for setup. `analytics: false` disables implicit acquisition, while an explicit analytics instance takes precedence.
114
+ The root `createPostHog` composition wrapper snapshots product options, keeps supplied instances, and injects literal dynamic product loaders and the Capture V1 delivery factory into `createPostHogCore`. The manual core entrypoint installs only supplied extensions and has no automatic product imports. Product properties are synchronous ready-only lookups; `resolveExtension()` starts an eligible loader, shares concurrent acquisition and waits for setup.
115
115
 
116
- Supplied analytics initializes before other supplied extensions. Flags, surveys and autocapture await analytics resolution before exposing shared implementations that capture synchronously; their controls still work when analytics is explicitly disabled. An enabled initial pageview requests analytics separately. The factory awaits visible pageview admission before readiness; a hidden document waits on its visibility listener. Eager analytics configuration acquires the product and delivery during initialization. Once acquired, analytics interprets its own loading and scheduling options, with `automatic-analytics.ts` providing the separate deferred-delivery loader.
116
+ The client implements the shared `Client` contract and passes itself to every extension's `setup()`. It owns capture finalization, admission, rate limiting, immediate delivery, identity operations, registered properties and dynamic event-property producers through an internal capture pipeline; consent transitions purge its queued work. There is no per-extension adapter or scoped view. Extensions share the client's key-value store, as posthog-js extensions share its persistence, and the client's logger. Extension names and their `bindings` share one lookup namespace for `getExtension()`; the registered extension remains the sole lifecycle owner.
117
117
 
118
- Analytics owns capture finalization, admission, rate limiting, immediate delivery, identity/group operations, and dynamic event-property producers. Core supplies retained state, session admission, consent/lifecycle authority, requests and diagnostics through `AnalyticsCaptureHost`; consent transitions purge the installed analytics owner. The registry flushes installed owners once and isolates failed acquisition/setup without publishing an unusable owner.
119
-
120
- First-party analytics receives package-private `AnalyticsCaptureHost` initialization with the bound request runtime, dispatch-time consent/lifecycle authority, diagnostic reporting, and a capacity-availability notification for pending initial pageviews. This preserves raw gzip bodies, abort signals, keepalive, and shutdown delivery without changing the shared `Client.sendRequest()` contract. Core neither constructs a delivery object nor supplies queue-control callbacks. Browser-next extensions receive a scoped `IPostHogInternal` during setup; shared implementations receive its separate narrow `sharedClient` adapter.
121
-
122
- Analytics owns one `EventBuffer` throughout its lifetime; `analytics-buffer.ts` contains admission and loading coordination, while `analytics-delivery.ts` creates the deferred `Lane` driver for that existing buffer. The driver owns scheduling, finite flush barriers, transport, and retry coordination. It is ordinary implementation code within analytics, not a registered extension.
123
-
124
- Review each core mechanism with compliance tests, bundle measurements, and module attribution. Move optional implementations out of core. Do not move a required invariant out only because it has a measurable cost.
118
+ The capture pipeline owns one `EventBuffer` for its lifetime. The delivery factory supplied to the client attaches to that buffer during construction: `analytics-delivery.ts` creates the `Lane` driver with scheduling, finite flush barriers, transport and retries. Group and person client methods delegate to `products/analytics/groups.ts` and `person.ts`, which use the pipeline's package-internal methods.
125
119
 
126
120
  Consent uses `__ph_opt_in_out_<project-token>` by default and accepts a verbatim `consentPersistenceName` override. Store interoperable `0`/`1` values and accept trimmed, case-insensitive `1`/`true`/`yes` and `0`/`false`/`no` forms, including raw boolean and numeric values from compatibility adapters. Keep this logical key independent of identity persistence and consistent across consent storage adapters. Default local storage uses native `storage` events plus a same-document SDK event; adapters can provide an optional keyed subscription for prompt external revocation. All listeners start during client initialization and stop during disposal. Deprecated prefix-derived keys and migration between storage backends belong in a compatibility entry point.
127
121
 
@@ -129,29 +123,29 @@ Consent is prospective point-in-time analytics authority, not a global client li
129
123
 
130
124
  Apply those boundaries method by method:
131
125
 
132
- | Surface | Consent and lifecycle boundary |
133
- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
134
- | Identity, group, device, and session getters | Prepare and return retained state without reinterpreting it from consent. `BrowserState` separately owns fresh compatible-consent observation. |
135
- | `capture()` | Check once before evaluating caller properties. The synchronous capture operation then runs to completion; delivery applies its own dispatch-time gate. |
136
- | `identify()` and `group()` | Valid calls update and persist state regardless of capture consent, matching `posthog-js`. Their generated analytics events pass through ordinary `capture()` admission. |
137
- | `reset()` | Treat reset as cleanup, not an operation that a consent transition can invalidate. Lifecycle still prevents mutation after disposal. |
138
- | `sendRequest()` | Check immediately before each actual transport dispatch. Do not prepare analytics identity state and do not reinterpret an already-started result after consent changes. |
139
- | Remote configuration | Consent does not gate control-plane loading, caching, subscriptions, or publication. Lifecycle prevents new work after shutdown. |
140
- | Initial `$pageview` | Rely on ordinary `capture()` admission. Do not duplicate consent checks around DOM access or listener setup. |
141
- | Extension KV | Reads and writes are independent of capture consent, matching `posthog-js`. Lifecycle and state readiness still apply; any future durable-storage restriction belongs to a separate persistence policy. |
142
- | Analytics initialization and delivery loading | Analytics initializes independently of consent. Eager or already-started delivery loading finishes under denial; lazy loading begins only after an admitted capture. Denial purges queued analytics and blocks dispatch. |
126
+ | Surface | Consent and lifecycle boundary |
127
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
128
+ | Identity, group, device, and session getters | Prepare and return retained state without reinterpreting it from consent. `BrowserState` separately owns fresh compatible-consent observation. |
129
+ | `capture()` | Check once before evaluating caller properties. The synchronous capture operation then runs to completion; delivery applies its own dispatch-time gate. |
130
+ | `identify()` and `group()` | Valid calls update and persist state regardless of capture consent, matching `posthog-js`. Their generated analytics events pass through ordinary `capture()` admission. |
131
+ | `reset()` | Treat reset as cleanup, not an operation that a consent transition can invalidate. Lifecycle still prevents mutation after disposal. |
132
+ | `sendRequest()` | Check immediately before each actual transport dispatch. Do not prepare analytics identity state and do not reinterpret an already-started result after consent changes. |
133
+ | Remote configuration | Consent does not gate control-plane loading, caching, subscriptions, or publication. Lifecycle prevents new work after shutdown. |
134
+ | Initial `$pageview` | Rely on ordinary `capture()` admission. Do not duplicate consent checks around DOM access or listener setup. |
135
+ | Extension KV | Reads and writes are independent of capture consent, matching `posthog-js`. Lifecycle and state readiness still apply; any future durable-storage restriction belongs to a separate persistence policy. |
136
+ | Analytics initialization and delivery | Analytics and its delivery initialize independently of consent. Denial purges queued analytics and blocks dispatch. |
143
137
 
144
138
  No general `canContinue` or `canUseState` predicate should coordinate these surfaces. State preparation belongs only to operations that consume persisted analytics state; requests, remote configuration, pageview listener setup, and delivery retries must not initialize identity state as a side effect of authorization.
145
139
 
146
140
  Create session and window IDs lazily on the first successfully admitted capture. Preview session context while finalizing an event, but do not expose, persist, or install tab lifecycle state until bounded admission succeeds; rejected work must not create, rotate, or advance session state. Match `posthog-js` analytics semantics by rotating both IDs after reset, idle timeout, or maximum session length, and by adopting a sibling tab's active session while retaining the receiving tab's current window ID. Persist monotonic session revisions and explicit reset tombstones so sequential stale identity, group, or extension-data writes preserve the newest session authority; revalidate authority around admission commit, and discard stale finalized work rather than overwrite a newer session or reset. Missing or malformed optional session data is not a reset. With default storage, preserve ordinary reload windows and separate copied tab storage through tab-scoped storage; lifecycle cleanup and a no-throw navigation-type fallback cover browser reload differences. Core must not run a background timer solely to rotate sessions. Replay owns proactive recorder shutdown, interaction state, snapshot buffering, and recording-age limits; session rotation or notification alone must not start or flush a product. The alpha still documents perfectly simultaneous equal-revision whole-record writers after the final authoritative read as last-writer-wins.
147
141
 
148
- The analytics delivery capability must use Capture Analytics V1 at `POST /i/v1/analytics/events`. It must not use the legacy `/e/` envelope. Normal analytics delivery must use Fetch so it can send required headers, observe the UUID-keyed result map, time out, rate limit, and retry only server-marked retry events. It receives the core's bound Fetch capability but owns analytics-specific batching, authentication, compression, response, retry, and teardown policy. `analytics({ flushAt, flushInterval })` configures count and timer triggers with defaults of 20 events and 3,000 milliseconds; `flushInterval: 0` disables the timer, while explicit flush and shutdown bypass both thresholds. It selects at most 100 FIFO events at a time, serializes transformed events once, and greedily partitions exact uncompressed V1 envelopes at a package-private soft 5 MiB target. A larger admitted event is sent alone, and `413` remains terminal rather than triggering response-driven splitting. Remote configuration uses the small core control-plane request path and must not wait for analytics delivery to load.
142
+ The analytics delivery capability must use Capture Analytics V1 at `POST /i/v1/analytics/events`. It must not use the legacy `/e/` envelope. Normal analytics delivery must use Fetch so it can send required headers, observe the UUID-keyed result map, time out, rate limit, and retry only server-marked retry events. It receives the core's bound Fetch capability but owns analytics-specific batching, authentication, compression, response, retry, and teardown policy. The `analytics` option's `flushAt` and `flushInterval` configure count and timer triggers with defaults of 20 events and 3,000 milliseconds; `flushInterval: 0` disables the timer, while explicit flush and shutdown bypass both thresholds. It selects at most 100 FIFO events at a time, serializes transformed events once, and greedily partitions exact uncompressed V1 envelopes at a package-private soft 5 MiB target. A larger admitted event is sent alone, and `413` remains terminal rather than triggering response-driven splitting. Remote configuration uses the small core control-plane request path and must not wait for analytics delivery to load.
149
143
 
150
144
  When remote configuration advertises `gzip-js`, analytics compresses exact request envelopes of at least 1 KiB through native `CompressionStream('gzip')`. It sends gzip only when the result is smaller and has a valid header, CRC, and input-size trailer. Missing, hostile, malformed, stalled, or expanding compression falls back to the unchanged JSON body without consuming a delivery attempt. Delivery proceeds uncompressed while remote configuration is unresolved, so the initial pageview and queued work do not wait for negotiation. These thresholds are measured browser policy, not Capture V1 server limits.
151
145
 
152
- Analytics exposes a stable typed admission capability and owns its buffer independently of delivery loading. The buffer retains at most 1,000 queued events and 8 MiB across active and queued UTF-8 serialized finalized messages. An individual finalized core message has the same 8 MiB local limit. Queue pressure evicts the oldest queued prefix when enough queued work is reclaimable; active work cannot be recalled, so active bytes can reject a new event without evicting valid queued work. Queue residence expires strictly after one hour at the next admission, installation, drain, flush, or retry handoff; expiry uses monotonic local admission time and starts no expiry timer. Retry-exhausted transient messages remain byte- and count-accounted at their original FIFO position, become ineligible for the current drive, and can be redriven by the next interval, reconnect, count trigger, or explicit flush. A flush barrier resolves after its admitted snapshot receives one delivery drive; it does not hot-loop retained failures or wait indefinitely for server acceptance. These package-private values bound browser memory and stale delivery and do not claim the deployed V1 event or batch limits. The policy owns one endpoint, event/batch serializer, server payload limits, compression, transport, response classification, retry policy, and teardown policy. Events with different policies must not share a batch. A failure in one lane must not requeue or resend events accepted in another lane. The composition root creates the analytics extension with usable buffering before delivery attaches. Analytics `capture()` performs bounded admission, commits Core's session authority only after acceptance, and rolls back queued work when session admission fails. Delivery loading starts only after successful admission. The default entrypoint supplies a literal dynamic-import reference; its initial chunk and the core entrypoint exclude the queue driver and analytics delivery policy. Attaching a policy must preserve queued event UUIDs, timestamps, identity, session, ordering, measured bytes, admission time, and retry multiplicity. Optional product entry points create their lanes only when imported; the root must not contain their implementations or a product catalog.
146
+ Analytics exposes a stable typed admission capability and owns its buffer; the client attaches delivery to it in the constructor. The buffer retains at most 1,000 queued events and 8 MiB across active and queued UTF-8 serialized finalized messages. An individual finalized core message has the same 8 MiB local limit. Queue pressure evicts the oldest queued prefix when enough queued work is reclaimable; active work cannot be recalled, so active bytes can reject a new event without evicting valid queued work. Queue residence expires strictly after one hour at the next admission, installation, drain, flush, or retry handoff; expiry uses monotonic local admission time and starts no expiry timer. Retry-exhausted transient messages remain byte- and count-accounted at their original FIFO position, become ineligible for the current drive, and can be redriven by the next interval, reconnect, count trigger, or explicit flush. A flush barrier resolves after its admitted snapshot receives one delivery drive; it does not hot-loop retained failures or wait indefinitely for server acceptance. These package-private values bound browser memory and stale delivery and do not claim the deployed V1 event or batch limits. The policy owns one endpoint, event/batch serializer, server payload limits, compression, transport, response classification, retry policy, and teardown policy. Events with different policies must not share a batch. A failure in one lane must not requeue or resend events accepted in another lane. The client creates its buffer before delivery attaches. Analytics `capture()` performs bounded admission, commits Core's session authority only after acceptance, and rolls back queued work when session admission fails. Attaching a policy must preserve queued event UUIDs, timestamps, identity, session, ordering, measured bytes, admission time, and retry multiplicity. Optional product entry points create their lanes only when imported; the root must not contain their implementations or a product catalog.
153
147
 
154
- `captureImmediate()` is the explicit exception to queued delivery. Analytics finalizes and commits one event through the same admission boundaries, then sends it inline. The capability's package-private immediate primitive accepts a readonly message array so single capture wraps the same batch-oriented Capture V1 sender and result classifier used by lane delivery. Immediate messages never enter the lane, are not retained for a later flush, can overtake buffered work, and may run concurrently. Unlike the general point-in-time consent rule, an observed denial permanently cancels pending immediate dispatch and retries; later opt-in does not revive them. Already-dispatched requests may finish. A valid `2xx` resolves to a terminal summary: only `ok` and `warning` count as persisted, while `drop`, final `retry`, and missing results do not. Request-level terminal failures, exhausted transport retries, malformed responses, cancellation, and unavailable delivery resolve with an operation-level `error` in the summary, retaining known partial outcomes and setting `allPersisted` to `false` even when nothing was submitted. The public immediate-capture boundary contains unexpected exceptions and rejected delivery promises as failure summaries. Local non-admission resolves an empty summary and callers requiring durability must verify both submitted count and persistence. The default entrypoint may satisfy an immediate call through its injected lazy loader; the core entrypoint contains no delivery import and requires an explicitly installed analytics capability. Analytics must degrade gracefully when a loaded delivery driver implements queued delivery without the immediate method.
148
+ `captureImmediate()` is the explicit exception to queued delivery. Analytics finalizes and commits one event through the same admission boundaries, then sends it inline. The capability's package-private immediate primitive accepts a readonly message array so single capture wraps the same batch-oriented Capture V1 sender and result classifier used by lane delivery. Immediate messages never enter the lane, are not retained for a later flush, can overtake buffered work, and may run concurrently. Unlike the general point-in-time consent rule, an observed denial permanently cancels pending immediate dispatch and retries; later opt-in does not revive them. Already-dispatched requests may finish. A valid `2xx` resolves to a terminal summary: only `ok` and `warning` count as persisted, while `drop`, final `retry`, and missing results do not. Request-level terminal failures, exhausted transport retries, malformed responses, cancellation, and unavailable delivery resolve with an operation-level `error` in the summary, retaining known partial outcomes and setting `allPersisted` to `false` even when nothing was submitted. The public immediate-capture boundary contains unexpected exceptions and rejected delivery promises as failure summaries. Local non-admission resolves an empty summary and callers requiring durability must verify both submitted count and persistence. Analytics must degrade gracefully when a loaded delivery driver implements queued delivery without the immediate method.
155
149
 
156
150
  After configured extensions install, core admits one enabled initial `$pageview` through ordinary capture before the factory resolves. `capturePageview: false` disables it. Hidden documents wait on one disposable visibility listener. Consent and bot filtering are enforced only when ordinary capture begins, and a later explicit opt-in can admit a pageview that prior denial held pending. The core event has no title, URL, referrer, page-view identifier, history patching, or page-leave behavior; those remain in an optional page-view/browser-context product.
157
151
 
@@ -161,7 +155,7 @@ Teardown delivery must use the Capture V1 header-less Beacon contract only after
161
155
 
162
156
  ### 4.4 Optional adapters and extensions
163
157
 
164
- Put delivery or product behavior in an extension, capability, or adapter. Examples include analytics delivery, replay, surveys, and web vitals. The analytics extension owns its queue and loads its delivery implementation as needed. Optional products likewise own their buffers and delivery policies.
158
+ Put delivery or product behavior in an extension, capability, or adapter. Examples include analytics delivery, replay, surveys, and web vitals. The client's capture pipeline owns its queue and attaches its entrypoint's delivery when the client is constructed. Optional products likewise own their buffers and delivery policies.
165
159
 
166
160
  An optional module can import the core. The core must not import the optional module.
167
161
 
@@ -192,18 +186,15 @@ Cross-context conflict safety is also a core invariant. Same-origin local-storag
192
186
 
193
187
  ## 5. Root entry point
194
188
 
195
- The initial root graph contains Core and product-composition glue, not analytics admission, buffering or delivery implementations. Resolving analytics acquires its API and buffer first; an admitted capture then starts its separate delivery import. `analytics.load: 'eager'` acquires both during initialization. `analytics: false` blocks implicit acquisition, but not an explicitly supplied instance. The manual core entrypoint has no implicit analytics product. Once acquired, the analytics owner remains the same instance before and after delivery loads.
189
+ The initial root graph contains the client, its capture pipeline, Capture V1 delivery and product-composition glue. Group and person operations are client methods in the root graph; optional products stay outside it.
196
190
 
197
191
  The root entry point must use named exports. It must not create a default client singleton.
198
192
 
199
193
  Use a narrow root wrapper with a literal dynamic loader and a separate core entry:
200
194
 
201
195
  ```ts
202
- // Root composition: acquire the whole product.
203
- const loadAnalytics = () => import('./automatic-analytics').then(({ analytics }) => analytics({}))
204
-
205
- // Inside the acquired product: load delivery separately.
206
- const loadDelivery = () => import('./analytics-delivery').then(({ createAnalyticsDelivery }) => createAnalyticsDelivery)
196
+ // Root composition: acquire a whole product on demand.
197
+ const loadFlags = () => import('../../products/flags/flags').then(({ flags }) => flags(snapshot))
207
198
 
208
199
  // @posthog/browser/core
209
200
  export { createPostHog } from './core'
@@ -216,7 +207,7 @@ export * from './products'
216
207
  export { default } from './singleton'
217
208
  ```
218
209
 
219
- The root entry point must not re-export optional runtime features. Its loaders acquire whole products; analytics delivery and survey rendering remain further deferred imports. Flags initializes by default. Logs, surveys and autocapture activate from explicit options, saved-state or remote-configuration signals, or explicit resolution. You can re-export types when the compiler produces no JavaScript import.
210
+ The root entry point must not re-export optional runtime features. Its loaders acquire whole products; survey rendering remains a further deferred import. Flags initializes by default. Logs, surveys and autocapture activate from explicit options, saved-state or remote-configuration signals, or explicit resolution. You can re-export types when the compiler produces no JavaScript import.
220
211
 
221
212
  Treat `createPostHog` and its static imports as one size unit.
222
213
  A bundler cannot remove an internal module when the factory always needs that module.
@@ -237,7 +228,7 @@ Survey action selectors are owned by the optional surveys module. It returns cop
237
228
 
238
229
  Applications access flag controls through `await posthog.resolveExtension(FeatureFlagsExtension)`. The typed token is lightweight and does not import the implementation. Result conversion, subscriptions, bootstrap, and evaluation stay in the optional module. Missing or failed extensions return undefined from lookup. Callbacks enumerate results without emitting flag-called events.
239
230
 
240
- Browser-next supplies an `IPostHogInternal` scoped host with a separate shared `Client` adapter. Identification publishes `onIdentify`; local person-property updates publish the product-host `onChangeProperties` notification with `set`, `setOnce` and `unset` fields. Property setters do not publish identification, while identification with properties publishes both notifications. Core also supplies `onGroup`, `onGroupsReset` and `onReset`. Notifications run synchronously, independently of capture admission. Publishers isolate listener failures and do not replay earlier operations. Extensions subscribe during setup and dispose their subscriptions during teardown. Flags uses identification to update identity-dependent tracking and property changes to update evaluation context; core does not look up product-specific hooks.
231
+ The client supplies browser notifications alongside the shared `Client` contract. Identification publishes `onIdentify`; local person-property updates publish the product-host `onChangeProperties` notification with `set`, `setOnce` and `unset` fields. Property setters do not publish identification, while identification with properties publishes both notifications. Core also supplies `onGroup`, `onGroupsReset` and `onReset`. Notifications run synchronously, independently of capture admission. Publishers isolate listener failures and do not replay earlier operations. Extensions subscribe during setup and dispose their subscriptions during teardown. Flags uses identification to update identity-dependent tracking and property changes to update evaluation context; core does not look up product-specific hooks.
241
232
 
242
233
  Flags passes the shared `Client` directly to the shared feature-flags implementation and stores its values through `Client.kv`. The host owns storage selection, serialization, and durable writes. Core reset clears persisted extension data before notifying flags to clear its in-memory evaluation state and reload. Flag values follow the client's configured persistence, including memory-only operation with `storage: false`.
243
234
 
@@ -259,9 +250,9 @@ Application-facing survey controls belong to the extension reference, obtained f
259
250
 
260
251
  The shared renderer, Preact components, CSS string, event/action receiver, and matching helpers are reused by legacy adapters. Capture, flags, submission IDs, configuration, and stylesheet preparation are explicit runtime capabilities, not a concrete PostHog facade. Legacy global routing, preview wrappers, and UUID behavior remain legacy-owned. Native capability reads occur at invocation/setup, preserving strict static-entry import purity.
261
252
 
262
- The optional module stores definitions and event-activation state through its host-provided `Client.kv` namespace. Survey interaction history—seen markers, partial answers, and abandonment markers—uses dedicated browser localStorage with the existing survey keys, independently of SDK persistence, including `storage: false`. Failed partial-answer writes retain an in-memory fallback. Abandonment checks capture permission before writing its marker and skips capture if reading the marker fails. Client reset clears persisted extension data, and the extension's reset subscription delegates to the shared surveys reset implementation. This clears in-memory progress and activation state, plus localStorage seen markers, partial answers, and the last-seen date. Abandonment markers remain, matching legacy survey reset behavior. Existing capture consent gates still control eligibility and submission, while cleanup always runs. The renderer owns polling, language/visibility listeners, pending display timeouts, and Preact unmounting.
253
+ The optional module stores definitions and event-activation state through the client's shared `core` `Client.kv` store. Survey interaction history—seen markers, partial answers, and abandonment markers—uses dedicated browser localStorage with the existing survey keys, independently of SDK persistence, including `storage: false`. Failed partial-answer writes retain an in-memory fallback. Abandonment checks capture permission before writing its marker and skips capture if reading the marker fails. Client reset clears persisted extension data, and the extension's reset subscription delegates to the shared surveys reset implementation. This clears in-memory progress and activation state, plus localStorage seen markers, partial answers, and the last-seen date. Abandonment markers remain, matching legacy survey reset behavior. Existing capture consent gates still control eligibility and submission, while cleanup always runs. The renderer owns polling, language/visibility listeners, pending display timeouts, and Preact unmounting.
263
254
 
264
- Survey abandonment uses a package-private analytics pre-teardown subscription: the analytics buffer retains callbacks across lazy delivery loading, and initialized delivery invokes them synchronously before its single keepalive queue handoff. Browser-native `pagehide` listener ordering is not portable (Chromium can invoke an earlier non-capture listener before a later capture listener), so capture phase alone cannot provide this ordering. Subscription failures are contained and disposal removes callbacks. A surveys-owned `pagehide` fallback admits abandonment when analytics delivery is unavailable, but cannot ensure delivery from a module still loading during unload.
255
+ Survey abandonment uses a package-private analytics pre-teardown subscription: the analytics buffer retains callbacks, and the delivery attached in the client constructor invokes them synchronously before its single keepalive queue handoff. Browser-native `pagehide` listener ordering is not portable (Chromium can invoke an earlier non-capture listener before a later capture listener), so capture phase alone cannot provide this ordering. Subscription failures are contained and disposal removes callbacks. A surveys-owned `pagehide` fallback admits abandonment when analytics delivery is unavailable, but cannot ensure delivery from a module still loading during unload.
265
256
 
266
257
  Survey definitions are fetched separately at `/api/surveys/` with the existing token query, cache TTL, and failure backoff. The surveys extension resolves the browser-next flags facade through `Client.getExtension()` for configuration and person-property context; shared surveys resolves common flags through its common token. Event targets observe admitted captures. Action matching can register DOM selectors through an optional autocapture capability; that extension must be installed for selector-backed DOM events.
267
258
 
@@ -345,7 +336,7 @@ If an import side effect is unavoidable, prefer a separate package. Otherwise, c
345
336
 
346
337
  ### 8.1 Use an import boundary
347
338
 
348
- Use a separate export subpath for each substantial optional feature. Automatic analytics delivery, feature flags, logs, surveys orchestration, and autocapture use literal dynamic imports from the root entrypoint; the core entrypoint references none of their automatic loaders.
339
+ Use a separate export subpath for each substantial optional feature. Feature flags, logs, surveys orchestration, and autocapture use literal dynamic imports from the root entrypoint; the core entrypoint references none of their automatic loaders.
349
340
 
350
341
  Example:
351
342
 
@@ -391,7 +382,7 @@ The change must include measurements that support this decision.
391
382
 
392
383
  ### 8.3 Register only selected extensions
393
384
 
394
- The extension registry stores configured instances and automatic instances selected by the root factory. Explicit analytics, feature-flags, logs, surveys, and autocapture instances take precedence over their corresponding top-level options. Analytics delivery loading does not add a registry entry; flags register the same extension implementation used by static inclusion.
385
+ The extension registry stores configured instances and automatic instances selected by the root factory. Explicit feature-flags, logs, surveys, and autocapture instances take precedence over their corresponding top-level options. Flags register the same extension implementation used by static inclusion.
395
386
 
396
387
  Keep product factories, option interpretation and literal imports in composition code. Core may store injected named loaders and dependency bookkeeping, but must not import a static catalog of product implementations. Other products require explicit composition until their automatic loading contract is implemented.
397
388
 
@@ -432,12 +423,9 @@ The client owns every configured or internally created extension for its lifetim
432
423
  An extension must release owned resources in its final `dispose()`.
433
424
  Cleanup must be safe after partial setup.
434
425
 
435
- The host must give each browser-next extension a scoped `IPostHogInternal` view, with its own narrow `sharedClient` adapter for shared implementations.
436
- These views must expose capabilities, not the concrete host implementation.
437
-
438
- The host must keep extension state separate. The host must dispose extensions in reverse installation order.
426
+ The client passes itself to every extension. The host must dispose extensions in reverse installation order.
439
427
 
440
- Owner names and shared binding names are separate namespaces. Browser product properties and awaited `resolveExtension()` return successfully initialized lifecycle owners. An extension's `bindings` map supplies targets only for the shared adapter's synchronous `getExtension()` lookup; owner names are not implicit shared bindings. For example, `client.featureFlags` returns the browser facade, while `client.sharedClient.getExtension('featureFlags')` returns its shared implementation. The registered extension is the sole lifecycle owner: binding targets are not independently set up, flushed or disposed. Shared bindings are reserved before setup and removed when the owner fails setup, is rolled back, or is disposed.
428
+ Extension names and binding names share one lookup namespace. Browser product properties and awaited `resolveExtension()` return successfully initialized lifecycle owners; `getExtension()` also returns binding targets, such as the shared flags implementation under `FeatureFlagsCommonExtension`. The registered extension is the sole lifecycle owner: binding targets are not independently set up, flushed or disposed. Names and bindings are reserved before setup and released when setup fails or the extension is disposed.
441
429
 
442
430
  An extension failure must not stop core capture. A failed setup must remove all reserved registry state.
443
431
 
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
- await posthog.resolveExtension('analytics')
16
- posthog.analytics?.capture('signed_up')
15
+ posthog.capture('signed_up')
17
16
  await posthog.flush()
18
17
  ```
19
18
 
20
- Configure scheduling or acquire analytics and start delivery while the client initializes:
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: { load: 'eager', flushAt: 20, flushInterval: 3_000 },
24
+ analytics: { flushAt: 20, flushInterval: 3_000, personProfiles: 'identified_only' },
26
25
  })
27
26
  ```
28
27
 
29
- Importing `@posthog/browser/analytics` statically includes both buffering and delivery. Supplying its extension selects that instance and its constructor options instead of automatic product acquisition:
28
+ Both entrypoints deliver through Capture V1 with retries, compression and payload splitting. They differ in how products load:
30
29
 
31
- ```ts
32
- import { analytics } from '@posthog/browser/analytics'
33
-
34
- const posthog = await createPostHog({
35
- projectToken: '<project-token>',
36
- extensions: [analytics({ flushAt: 5, flushInterval: 0 })],
37
- })
38
- ```
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 |
39
34
 
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
- Product namespaces expose owners only after successful setup. Reading a namespace never initiates loading. Use `await posthog.resolveExtension(token)` for typed custom-extension access; resolution waits for readiness and returns `undefined` when the extension is unavailable. Shared implementations receive a separate `Client` adapter with shared binding lookup.
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
- Analytics owns person-profile policy through `personProfiles: 'always' | 'never' | 'identified_only'`, defaulting to `identified_only`. Anonymous events carry `process_person_profile: false` in Capture V1 options until identification, group registration or explicit profile enablement. Configure it through `analytics: { personProfiles: 'always' }` or an explicit `analytics({ personProfiles: 'always' })` instance. SDK-computed processing metadata takes precedence over caller properties; `$process_person_profile` does not change the SDK's underlying processing state.
39
+ Person and group operations are client methods:
45
40
 
46
- Use the analytics product's `createPersonProfile()`, `setPersonProperties(set?, setOnce?)`, `unsetPersonProperties(names)` and `setInternalOrTestUser()` controls for explicit person updates. 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.
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
- Resolve or explicitly compose analytics before using its identity controls. `alias(targetId)` links the current ID without changing the current identity or marking it identified; it enables person processing unless disabled by policy. Use `identify()` to switch the ambient identity.
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
- `group(type, key, properties?)` persists ambient membership. `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, and its options use the ordinary capture pipeline. Alias and group-profile events require capture consent and are suppressed in `never` mode. `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. Persisted group flag properties can remain when flags is absent ([tracked in #5673](https://github.com/PostHog/posthog-js/issues/5673)). It remains available for cleanup when capture is denied or person processing is disabled. Previously queued events retain their captured group context.
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
- ```ts
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
- Use the installed analytics product to register context for future events:
57
+ Register context for future events:
63
58
 
64
59
  ```ts
65
- const analytics = await posthog.resolveExtension('analytics')
66
- analytics?.register({ plan: 'pro', region: 'eu' })
67
- analytics?.registerOnce({ acquisitionSource: 'website' })
68
- analytics?.capture('dashboard', { plan: 'enterprise' })
69
- const region = analytics?.getProperty('region')
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
- const analytics = await posthog.resolveExtension('analytics')
81
- analytics?.registerForSession({ checkoutFlow: 'express' })
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 to analytics-owned operations
82
+ ## Migrating from the analytics extension
90
83
 
91
- Analytics operations now belong to `posthog.analytics`, not the Core client:
84
+ Earlier 0.x versions exposed analytics as a separate product. It is now part of the client:
92
85
 
93
- | Previous client API | Replacement |
94
- | ---------------------------------- | ----------------------------------------------------------------------- |
95
- | `capture()`, `captureImmediate()` | `posthog.analytics?.capture()`, `posthog.analytics?.captureImmediate()` |
96
- | `identify()`, `group()`, `reset()` | The corresponding method on `posthog.analytics` |
97
- | `onEvent`, `isRateLimited` | The corresponding member on `posthog.analytics` |
98
- | `registerDynamicEventProperties()` | `posthog.analytics?.registerDynamicEventProperties()` |
99
- | Synchronous `getExtension(token)` | `await posthog.resolveExtension(token)` |
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
- Product namespaces are optional: they expose successfully initialized owners, not availability of network delivery. Resolve a product before using it when initialization may still be pending, and handle `undefined` when it is unavailable. `flush()` and `dispose()` remain on the client, alongside consent, identity/session getters, remote configuration and scoped key-value storage.
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
- Replace the removed application type export `PostHog` with `IPostHog`. For extension authors, replace the removed `BrowserClient` type export with `IPostHogInternal`. `BrowserExtension` (also exported as `Extension`) is the browser-next extension contract; shared implementations continue using `Client` from `@posthog/browser-common`. The setup host exposes browser product owners directly. Its `sharedClient` adapter supplies shared implementations with their binding lookup and capture surface; it is not the application client.
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.analytics?.capture('signed_up')
126
+ client.capture('signed_up')
131
127
  }
132
128
  if (window.posthog) {
133
129
  onPostHogReady(window.posthog)
@@ -236,15 +232,15 @@ Creating an extension does not initialize it. Pass it in the `extensions` option
236
232
 
237
233
  ### Lifecycle notifications
238
234
 
239
- Browser-next supplies an `IPostHogInternal` scoped host to extension setup. It exposes browser namespaces, asynchronous dependency resolution, and `onIdentify`, `onGroup`, `onGroupsReset` and `onReset` listeners. Identification uses `onIdentify`; person-property setters use the separate product-host `onChangeProperties` notification 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.
235
+ 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
236
 
241
237
  ```ts
242
- import type { IPostHogInternal, Disposable } from '@posthog/browser'
238
+ import type { Disposable, IPostHog } from '@posthog/browser'
243
239
 
244
240
  let subscription: Disposable | undefined
245
241
  const extension = {
246
242
  name: 'identity-observer',
247
- setup(client: IPostHogInternal) {
243
+ setup(client: IPostHog) {
248
244
  subscription = client.onIdentify(({ distinctId, previousDistinctId }) => {
249
245
  console.log(previousDistinctId, distinctId)
250
246
  })
@@ -286,7 +282,7 @@ An explicit logs extension takes precedence over the top-level option, including
286
282
 
287
283
  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
284
 
289
- The logs extension's `flush()` awaits both log queues. `posthog.flush()` awaits all installed extensions' flush methods, including analytics and 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()`.
285
+ 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
286
 
291
287
  ## Surveys
292
288
 
@@ -321,26 +317,23 @@ feedback.displaySurvey('feedback')
321
317
 
322
318
  Await client creation before using extension controls.
323
319
 
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 analytics' existing pagehide keepalive handoff when delivery is initialized; an analytics module still loading during pagehide cannot send it.
320
+ 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
321
 
326
- Definitions and event activation state use the host-provided surveys KV namespace in the core persistence record. 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.
322
+ 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
323
 
328
324
  ## Capture and delivery
329
325
 
330
- Capture, immediate capture, identity and group controls, reset and event-property registration live on the analytics extension. Core owns shared identity, sessions, groups, consent, persistence and lifecycle. The npm root acquires the complete analytics API through asynchronous resolution; delivery remains a separate lazy chunk until an admitted capture or an operation needs it. An enabled initial pageview or capture-producing product also acquires it. 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.
326
+ 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
327
 
332
- `analytics.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 code or network delivery. With pending queued work, `flush()` joins an in-progress delivery load and can retry failed automatic loading; without available delivery it resolves without discarding unexpired queued events. 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.
328
+ `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
329
 
334
330
  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
331
 
336
332
  Use `captureImmediate()` only when the caller needs a terminal delivery outcome before continuing:
337
333
 
338
334
  ```ts
339
- const analytics = await posthog.resolveExtension('analytics')
340
- const summary = await analytics?.captureImmediate('import_completed', { source: 'warehouse' })
341
- if (!summary) {
342
- console.warn('Analytics is unavailable')
343
- } else if (summary.error) {
335
+ const summary = await posthog.captureImmediate('import_completed', { source: 'warehouse' })
336
+ if (summary.error) {
344
337
  console.warn('Immediate capture failed', summary.error)
345
338
  } else if (summary.submitted !== 1 || !summary.allPersisted) {
346
339
  // Capture V1 did not confirm persistence of this event.
@@ -349,9 +342,9 @@ if (!summary) {
349
342
 
350
343
  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 observed consent denial permanently cancels pending immediate dispatch and retries, even if the user opts in again; already-dispatched requests may finish.
351
344
 
352
- Acquire analytics before making an immediate call. The manual core exposes analytics only when explicitly supplied through `extensions`. Analytics admission and its bounded buffer remain independent of the inner delivery loader; delayed delivery retains finalized event snapshots, cancellation and retries, not raw calls to replay.
345
+ `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.
353
346
 
354
- The analytics extension sends FIFO Capture V1 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()` and shutdown bypass both thresholds. Retry-exhausted transient failures remain in the bounded lane for a later interval, reconnect, or explicit flush rather than hot-looping or being discarded.
347
+ 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()` and shutdown bypass both thresholds. Retry-exhausted transient failures remain in the bounded lane for a later interval, reconnect, or explicit flush rather than hot-looping or being discarded.
355
348
 
356
349
  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
350
 
@@ -1,9 +1,8 @@
1
1
  import type { CorePostHogOptions, IPostHog } from '../../core/types';
2
- /** Creates a host with only explicitly supplied products and no automatic product imports. */
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 { IPostHogInternal, BrowserExtension, IdentifyInfo, GroupInfo } from '../../core/context/browser-client';
7
- export type { IAnalytics } from '../../products/analytics/analytics-api';
6
+ export type { BrowserExtension, IdentifyInfo, GroupInfo } from '../../core/context/browser-client';
8
7
  export type { AnalyticsOptions, ApiResponse, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, NewSessionInfo, NewSessionReason, IPostHog, RemoteConfig, 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
- const createPostHog = async (options)=>createPostHogCore(options);
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,11 +1,10 @@
1
1
  import type { IPostHog, PostHogOptions } from '../../core/types';
2
- /** Creates a browser host with on-demand first-party analytics acquisition. */
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 { IPostHogInternal, BrowserExtension, IdentifyInfo, GroupInfo } from '../../core/context/browser-client';
8
- export type { AnalyticsConfiguration, AnalyticsOptions, ApiResponse, AutomaticAnalyticsOptions, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, LoadStrategy, NewSessionInfo, NewSessionReason, IPostHog, PostHogOptions, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
6
+ export type { BrowserExtension, IdentifyInfo, GroupInfo } from '../../core/context/browser-client';
7
+ export type { AnalyticsOptions, ApiResponse, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, NewSessionInfo, NewSessionReason, IPostHog, PostHogOptions, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
9
8
  export type { FlagsOptions, FlagsConfiguration, FlagsCallback, 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';
@@ -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
  };