@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/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
|
|
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,
|
|
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,58 +102,52 @@ 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
|
-
-
|
|
106
|
-
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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; an explicit opt-out purges 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
|
-
|
|
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
|
|
|
128
|
-
Consent is prospective point-in-time analytics authority, not a global client lifecycle lock or a transaction spanning an operation. Extension setup, registration, lookup, subscriptions, and cleanup always run. Check consent once when capture begins and immediately before each new analytics transport attempt or retry. An operation or request authorized at its boundary may finish after consent changes; except for pending immediate dispatch and retries described below, do not invalidate it using a historical consent generation. Denial purges work already queued at that transition and prevents new capture and analytics dispatch. Match `posthog-js` by retaining identity, group, session, and device state across capture denial; persistence restrictions are a separate policy. Client shutdown remains an independent terminal boundary.
|
|
122
|
+
Consent is prospective point-in-time analytics authority, not a global client lifecycle lock or a transaction spanning an operation. Extension setup, registration, lookup, subscriptions, and cleanup always run. Check consent once when capture begins and immediately before each new analytics transport attempt or retry. An operation or request authorized at its boundary may finish after consent changes; except for pending immediate dispatch and retries described below, do not invalidate it using a historical consent generation. Denial purges work already queued at that transition and prevents new capture and analytics dispatch. A denial that comes from a cleared choice (`reset()` or `clearOptInOut()`, in this or another context) is the exception: it prevents new capture but keeps work admitted before it deliverable, including pending immediate dispatch, because reset affects future events only; only an explicit `0` choice purges. A later explicit opt-out in the same client purges that kept work, including pending immediate dispatch. An explicit opt-out observed from another context does not purge it, because consent is already denied and no transition occurs; dispatch pauses while that explicit choice stands. A later opt-in redrives the kept work. A later cleared choice makes it deliverable again but sends no signal, so it goes out at the next flush, reconnect or page hide (captures are rejected while consent rests at the default denial). This matches `posthog-js` and sdk-specs `opt-in/spec.md`, which never discard data accepted while opted in. Every admission path, including `groupIdentify()` and `alias()`, checks `canCapture`, so keeping dispatch open for admitted work never admits new work. Match `posthog-js` by retaining identity, group, session, and device state across capture denial; persistence restrictions are a separate policy. Client shutdown remains an independent terminal boundary.
|
|
129
123
|
|
|
130
124
|
Apply those boundaries method by method:
|
|
131
125
|
|
|
132
|
-
| Surface
|
|
133
|
-
|
|
|
134
|
-
| Identity, group, device, and session getters
|
|
135
|
-
| `capture()`
|
|
136
|
-
| `identify()` and `group()`
|
|
137
|
-
| `reset()`
|
|
138
|
-
| `sendRequest()`
|
|
139
|
-
| Remote configuration
|
|
140
|
-
| Initial `$pageview`
|
|
141
|
-
| Extension KV
|
|
142
|
-
| Analytics initialization and delivery
|
|
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. Flag evaluation (`/flags/` on the flags host) and the early-access listing GET are sent while opted out, as in `posthog-js`; a blocked client still refuses them. 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. An explicit opt-out purges queued analytics and blocks dispatch; a cleared choice keeps dispatch open only for work admitted before it. |
|
|
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
|
|
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, shutdown, and `capture()` with `delivery: 'immediate'` bypass both thresholds. A `delivery: 'immediate'` capture keeps its event in the lane and forces a drain through it; if an earlier batch exhausts its retries before that event is attempted, the lane forces one more drain after the retained batch's retry cooldown. `delivery: 'unload'` bypasses the lane through best-effort keepalive delivery. 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
|
|
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, `delivery: 'immediate'` capture, or explicit flush. Kept work whose interval passed while another context's explicit opt-out paused it has no armed interval; an opt-in that ends the pause redrives it, but after a later cleared choice it goes out at the next flush, reconnect or page hide (captures are rejected while consent rests at the default denial). 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
|
|
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 explicit opt-out that purges queued work also cancels pending immediate dispatch and retries; a later opt-in does not revive them. A cleared choice does not cancel them. After a cleared choice, an explicit opt-out observed from another context only pauses them, as it pauses kept queued work: a retry that comes due while that opt-out stands is cancelled, but a later opt-in or cleared choice before then lets it proceed. 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
|
-
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,
|
|
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. Analytics keeps the UUID of the last admitted `$pageview` in memory for its session, sends it on later events as `$pageview_id`, adds `$prev_pageview_id` to `$pageview` and `$pageleave`, and exposes it through `getPageViewId()`; reset and session rotation clear it. The core event has no title, URL, referrer, history patching, or page-leave behavior; those remain in an optional page-view/browser-context product.
|
|
157
151
|
|
|
158
152
|
Select an optional lane through an explicit product API, such as `captureAi()`, not an event-name prefix or a caller-supplied lane string on general `capture()`. General `capture()` always uses analytics. The product module receives only its private lane sink. Install the lane lazily, then include it in client `flush()` and `dispose()`. Lane sinks, lane state, delivery policies, and the coordinator are package-private implementation details; do not export them from the package root or add them to the shared `Client` contract. This follows Python's `_capture_ai` lane and the unmerged Node `captureAi` design while keeping product code removable from the browser root.
|
|
159
153
|
|
|
@@ -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
|
|
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
|
|
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
|
|
203
|
-
const
|
|
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;
|
|
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
|
-
|
|
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
|
|
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
|
|
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.
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|