@posthog/browser 0.5.0 → 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.
Files changed (47) hide show
  1. package/ARCHITECTURE.md +17 -17
  2. package/README.md +42 -7
  3. package/dist/composition/npm/core.d.ts +1 -1
  4. package/dist/composition/npm/index.d.ts +2 -2
  5. package/dist/core/posthog.js +88 -14
  6. package/dist/core/posthog.mjs +88 -14
  7. package/dist/core/state/state.d.ts +32 -3
  8. package/dist/core/state/state.js +117 -25
  9. package/dist/core/state/state.mjs +105 -25
  10. package/dist/core/types.d.ts +87 -5
  11. package/dist/persistence/cookie.d.ts +19 -0
  12. package/dist/persistence/cookie.js +273 -0
  13. package/dist/persistence/cookie.mjs +235 -0
  14. package/dist/platform/logger.d.ts +5 -1
  15. package/dist/platform/logger.js +3 -3
  16. package/dist/platform/logger.mjs +3 -3
  17. package/dist/primitives/id.d.ts +5 -0
  18. package/dist/primitives/id.js +10 -2
  19. package/dist/primitives/id.mjs +6 -1
  20. package/dist/primitives/version.js +1 -1
  21. package/dist/primitives/version.mjs +1 -1
  22. package/dist/products/analytics/analytics-core.d.ts +17 -4
  23. package/dist/products/analytics/analytics-core.js +101 -10
  24. package/dist/products/analytics/analytics-core.mjs +101 -10
  25. package/dist/products/analytics/analytics-internal.d.ts +3 -2
  26. package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
  27. package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
  28. package/dist/products/analytics/delivery/lane.d.ts +8 -1
  29. package/dist/products/analytics/delivery/lane.js +16 -4
  30. package/dist/products/analytics/delivery/lane.mjs +16 -4
  31. package/dist/products/analytics/groups.js +1 -1
  32. package/dist/products/analytics/groups.mjs +1 -1
  33. package/dist/products/analytics/person.js +1 -1
  34. package/dist/products/analytics/person.mjs +1 -1
  35. package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
  36. package/dist/products/analytics/properties/analytics-properties.js +3 -0
  37. package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
  38. package/dist/products/flags/flags-internal.d.ts +3 -0
  39. package/dist/products/flags/flags-options.d.ts +16 -2
  40. package/dist/products/flags/flags-token.d.ts +28 -2
  41. package/dist/products/flags/flags.d.ts +1 -1
  42. package/dist/products/flags/flags.js +110 -4
  43. package/dist/products/flags/flags.mjs +110 -4
  44. package/dist/products/surveys/surveys-extension.js +75 -26
  45. package/dist/products/surveys/surveys-extension.mjs +77 -28
  46. package/dist/products/surveys/surveys-internal.d.ts +6 -0
  47. package/package.json +9 -4
package/ARCHITECTURE.md CHANGED
@@ -113,41 +113,41 @@ Keep the capture pipeline fixed and direct. Use compact explicit state machines.
113
113
 
114
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
- 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.
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
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.
119
119
 
120
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.
121
121
 
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. 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.
123
123
 
124
124
  Apply those boundaries method by method:
125
125
 
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. |
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. |
137
137
 
138
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.
139
139
 
140
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.
141
141
 
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.
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.
143
143
 
144
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.
145
145
 
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.
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.
147
147
 
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.
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.
149
149
 
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.
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.
151
151
 
152
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.
153
153
 
package/README.md CHANGED
@@ -198,7 +198,9 @@ subscription?.dispose()
198
198
 
199
199
  `FeatureFlagsExtension` is a lightweight typed lookup token, exported from the root, core, and flags entrypoints. `resolveExtension(FeatureFlagsExtension)` resolves to undefined when flags is disabled or failed to install. The extension's `getFeatureFlag()` returns undefined until a value is available. A disabled flag returns an object with `enabled: false`. Reads emit deduplicated flag-called analytics through ordinary capture; subscriptions do not. `updateFlags(values, payloads?, { merge })` injects flag values.
200
200
 
201
- Use `reloadFeatureFlags()` to request a remote evaluation and await its outcome before reading again:
201
+ Pass `getFeatureFlag(key, { sendFeatureFlagEvent: false })` for a read without an exposure event. Omitted or undefined `sendFeatureFlagEvent` defaults to sending. `getAllFeatureFlags()` returns a synchronous snapshot of all known structured results, including disabled flags and payloads, without exposure events. Changing the snapshot or its JSON payloads does not change stored flags.
202
+
203
+ `getFeatureFlag(key, { fresh: true })` returns undefined unless the latest flag request in this instance succeeded, ignoring bootstrap and persisted values before then, as in `posthog-js`. Use it to avoid briefly showing a feature that has since been disabled. The `fresh` option does not itself force or await a reload; ordinary stale-cache auto-refresh still applies. Use `reloadFeatureFlags()` to request a remote evaluation and await its outcome before reading again:
202
204
 
203
205
  ```ts
204
206
  if (featureFlags) {
@@ -211,6 +213,8 @@ if (featureFlags) {
211
213
 
212
214
  The promise resolves with `loaded`, `error`, `skipped` (evaluation is disabled or unavailable), or `cancelled` (reset or disposal). It does not reject on request failures. Calls made before a request starts share that evaluation; calls during an active request wait for a follow-up evaluation. Cached values and `updateFlags()` do not complete a reload. `onFeatureFlags` remains a subscription to value changes, separate from reload completion.
213
215
 
216
+ `onReloading(callback)` observes automatic and explicit reload starts, before the debounced request. It does not replay an earlier start. A reload requested from the callback joins the starting request. Its returned `Disposable` stops that subscription; disposing the client stops all reload notifications.
217
+
214
218
  For static inclusion, import the factory explicitly and pass the same configuration:
215
219
 
216
220
  ```ts
@@ -222,6 +226,27 @@ const posthog = await createPostHog({
222
226
  })
223
227
  ```
224
228
 
229
+ Use the local property controls when evaluation needs context that has not reached ingestion yet:
230
+
231
+ ```ts
232
+ posthog.featureFlags?.setPersonPropertiesForFlags({ plan: 'pro' })
233
+ posthog.featureFlags?.setGroupPropertiesForFlags({ organization: { employees: 25 } }, false)
234
+ await posthog.featureFlags?.reloadFeatureFlags()
235
+ posthog.featureFlags?.resetPersonPropertiesForFlags(false)
236
+ posthog.featureFlags?.resetGroupPropertiesForFlags('organization')
237
+ ```
238
+
239
+ Setters merge properties, including within each group type. Setters and resets reload by default; pass `false` to defer evaluation. Group reset clears one group type, or all group overrides when called without a group type. These controls do not identify a person, associate group membership, update profiles, or emit analytics. Local changes and flag evaluation requests remain available when capture is denied, as in `posthog-js`. Overrides use the client's configured persistence, survive recreation when storage is enabled, and clear on `reset()`. Disposed flags instances ignore these calls.
240
+
241
+ Early-access controls are also available on `posthog.featureFlags`:
242
+
243
+ ```ts
244
+ posthog.featureFlags?.getEarlyAccessFeatures((features) => console.log(features), true, ['beta'])
245
+ posthog.featureFlags?.updateEarlyAccessFeatureEnrollment('new-onboarding', true, 'beta')
246
+ ```
247
+
248
+ `getEarlyAccessFeatures(callback, forceReload?, stages?)` reuses cached definitions unless forced. Stage filters apply to requests, not an existing cache; force a reload when changing stages. As in `posthog-js`, any response with a JSON body replaces the cached definitions and reaches the callback, even when the request failed. Listing does not carry person data, so it is also requested while capture is opted out, matching `posthog-js`. Enrollment updates the stored flag value and person evaluation context immediately (active bootstrap values still take precedence until flags reload, as in `posthog-js`), then captures `$feature_enrollment_update` through ordinary consent gating. The optional stage and cached feature name are included in that event. Listing callbacks are isolated from application exceptions and stop after disposal. `EarlyAccessFeature`, `EarlyAccessFeatureCallback`, and `EarlyAccessFeatureStage` types are exported from the root and `/flags` entrypoints.
249
+
225
250
  An explicit extension takes precedence over the top-level option, including `flags: false`. `featureFlagEvaluation: false` keeps local/bootstrap values without requesting remote evaluation; remote configuration remains available. Other options are `bootstrap.featureFlagPayloads`, `flagKeys`, `cacheTtlMs`, `refreshIntervalMs`, `deduplicateCallsPerSession`, and `onlyEvaluateSurveyFeatureFlags`. Refresh defaults to five minutes with idle backoff; `refreshIntervalMs: 0` disables automatic refresh. The manual `@posthog/browser/core` entrypoint supports explicit flags without referencing the automatic loader.
226
251
 
227
252
  Flags uses the client's key-value store and configured persistence. With `storage: false`, values remain in memory. Reset clears flag state along with the client's other persisted state.
@@ -300,7 +325,9 @@ feedback?.getSurveys((surveys, context) => {
300
325
  const eligibility = await feedback?.canRenderSurvey('feedback')
301
326
  ```
302
327
 
303
- The options are `automaticDisplay` (default `true`), `requestTimeoutMs` (default `10_000`), `prefillFromUrl` (default `false`), `overrideDisplayLanguage`, `prepareStylesheet`, and `getCurrentUrl`. `getActiveMatchingSurveys(callback, forceReload?)` applies targeting; `onSurveysLoaded(callback)` returns a disposable subscription; `cancelPendingSurvey(id)` cancels pending display. Capture consent still gates rendering and responses.
328
+ The options are `automaticDisplay` (default `true`), `requestTimeoutMs` (default `10_000`), `prefillFromUrl` (default `false`), `overrideDisplayLanguage`, `prepareStylesheet`, and `getCurrentUrl`. `getActiveMatchingSurveys(callback, forceReload?)` applies targeting; `onSurveysLoaded(callback)` returns a disposable subscription; `cancelPendingSurvey(id)` cancels pending display.
329
+
330
+ `onActiveMatchingSurveysChanged(callback)` loads surveys for manual use and returns a disposable subscription to the active matching set. It delivers the current set once loaded, then changes after event and action triggers, cancellation, captured `$pageview` events, survey display, dismissal and responses, feature-flag updates, definition refreshes and reset. Unchanged results are not delivered again. URL conditions are re-evaluated on captured pageviews, so capture `$pageview` after client-side navigation. Selector, device and wait-period conditions are checked on those updates rather than by observing the DOM or time. While surveys are unavailable the callback receives `([], { isLoaded: false })`, with an `error` when a load attempt fails; the subscription remains for later updates. Captured `survey dismissed` and `survey sent` events with a `$survey_id` mark that survey as seen, including events from an application's own survey UI. Capture consent still gates rendering and responses.
304
331
 
305
332
  Use `surveys: false` to omit automatic inclusion. An explicitly supplied instance takes precedence, including over `false`. Importing the factory below includes orchestration only; rendering, styles, and HTML sanitization still load dynamically when needed. Importing the entrypoint or constructing the extension does not access browser globals.
306
333
 
@@ -340,21 +367,29 @@ if (summary.error) {
340
367
  }
341
368
  ```
342
369
 
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.
370
+ Immediate capture finalizes the event through the same consent, identity, session, protected-property, size, and rate-limit boundaries, then bypasses the lane and sends inline through the same Capture V1 sender. A valid `2xx` resolves to a `CaptureSummary`; `drop`, final `retry`, and missing outcomes set `allPersisted` to `false`, while `warning` counts as persisted. Terminal HTTP failures, exhausted transport retries, malformed responses, cancellation, and unavailable delivery resolve with `summary.error` and `allPersisted: false`, retaining any known partial outcomes. These failures do not reject the promise. Local non-admission resolves an empty summary, so durability-sensitive callers must check both `submitted` and `allPersisted`. Immediate requests can overtake buffered events and run concurrently with each other; they are never retained for a later `flush()`. An explicit opt-out cancels pending immediate dispatch and retries, even if the user opts in again; a cleared choice (`reset()` or `clearOptInOut()`) does not. Already-dispatched requests may finish.
344
371
 
345
372
  `captureImmediate()` is available on both entrypoints because delivery is part of the client. The manual core captures even without supplied extensions: it sends the initial `$pageview` unless `capturePageview: false`, and an installed flags extension sends `$feature_flag_called` the first time each flag value is read.
346
373
 
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.
374
+ Capture V1 delivery sends FIFO batches of at most 100 events and partitions large backlogs by exact uncompressed envelope size. `flushAt` defaults to 20 and triggers delivery by queued count; `flushInterval` defaults to 3,000 milliseconds and triggers delivery by age. Set `flushInterval: 0` to disable timer delivery. Explicit `flush()`, shutdown, and `capture(event, properties, { delivery: 'immediate' })` bypass both thresholds. A `delivery: 'immediate'` capture stays in the lane with normal retries and unload handoff, and starts a drain now that sends queued events with it. Prefer it over `capture()` followed by `flush()` when the event must not wait behind a full offline backlog or, with `flushInterval: 0`, behind a failed older batch: if an older batch exhausts its retries before the event is attempted, the lane makes one more drain instead of waiting for another trigger. `{ delivery: 'unload' }` sends the event through best-effort keepalive Fetch and does not confirm persistence. Retry-exhausted transient failures remain in the bounded lane for a later interval, reconnect, `delivery: 'immediate'` capture, or explicit flush rather than hot-looping or being discarded.
375
+
376
+ `posthog.setConfig({ debug, analytics: { personProfiles } })` changes only these options on a running client; other options are fixed at creation. `posthog.debug()` and `posthog.debug(false)` toggle diagnostic logs at runtime and are not persisted across page loads.
348
377
 
349
378
  Both factories start one JSON remote-config request during initialization, without waiting for it before capture or factory completion. `remoteConfig` supplies an inline result instead of making a request. The default loader uses Fetch and `GET /array/{projectToken}/config`. Recognized PostHog US/EU hosts resolve to the corresponding assets host; custom hosts retain their configured base, including path prefixes. Loading is independent of capture consent. `fetch: false` disables built-in loading. Failure or the default 10-second `remoteConfigTimeoutMs` publishes `{ ok: false }` once, with no automatic retry; shutdown cancels the wait and suppresses late publication.
350
379
 
351
380
  When remote configuration advertises gzip, eligible normal batches use native `CompressionStream`; delivery remains uncompressed while configuration is unresolved or compression is unavailable, invalid, stalled, or larger than the JSON body. While offline, finalized events remain admitted and avoid network attempts until an `online` notification. On `pagehide`, or `unload` where `pagehide` is unavailable, queued analytics receive one synchronous uncompressed handoff through headered keepalive Fetch under one conservative aggregate body budget. Beacon remains disabled until Capture V1 supports the required metadata without request headers.
352
381
 
353
- One initial `$pageview` is admitted through the same queue after configured extensions install. Set `capturePageview: false` to disable it. Navigation tracking, URL/title enrichment, and page-leave capture remain optional product behavior.
382
+ One initial `$pageview` is admitted through the same queue after configured extensions install. Set `capturePageview: false` to disable it. Events captured after a `$pageview` in the same session carry its UUID as `$pageview_id`, and `posthog.getPageViewId()` returns it. Navigation tracking, URL/title enrichment, and page-leave capture remain optional product behavior.
383
+
384
+ Consent is stored separately from identity under `__ph_opt_in_out_<project-token>`. Use `consentPersistenceName` to supply a shared key verbatim. The client reads established `1`/`true`/`yes` and `0`/`false`/`no` values, including raw boolean and numeric compatibility values, and writes `1` or `0`. Configured extensions still initialize under prior denial. Identity, key-value persistence, remote configuration, feature flag evaluation and the early-access listing remain available, as in `posthog-js`, while analytics capture and other request transmission are consent-gated.
385
+
386
+ `posthog.getExplicitConsentStatus()` returns `'granted'`, `'denied'`, or `'pending'` when the user has not chosen, independently of `optOutByDefault`. `posthog.clearOptInOut()` forgets the stored choice and returns consent to the configured default. `reset()` also forgets the stored choice, as posthog-js does: a user who opted out is captured again after a logout reset unless the app calls `optOut()` again, and with `optOutByDefault` capture stops after `reset()` until the app calls `optIn()` again. Neither call discards analytics events captured before it, in this or another tab; they are still delivered.
387
+
388
+ Session and window IDs are created on the first successfully admitted capture. Rejected work does not create or advance them. Idle timeout, maximum length, and reset rotate both IDs. Same-origin tabs share the active session while retaining distinct window IDs; ordinary reloads preserve the window ID and copied tab storage receives a new one. Session rotation is activity-driven and starts no core timer. Session and window IDs are UUIDv7, as in posthog-js. `posthog.onSessionId(({ sessionId, windowId }) => …)` reports the current session without creating one, then every change; dispose the returned subscription to stop.
354
389
 
355
- Consent is stored separately from identity under `__ph_opt_in_out_<project-token>`. Use `consentPersistenceName` to supply a shared key verbatim. The client reads established `1`/`true`/`yes` and `0`/`false`/`no` values, including raw boolean and numeric compatibility values, and writes `1` or `0`. Configured extensions still initialize under prior denial. Identity, key-value persistence, and remote configuration remain available, while analytics capture and request transmission are consent-gated.
390
+ `reset()` starts a new anonymous identity and session and keeps the device ID. Pass `reset(true)` or `reset({ resetDeviceId: true })` to also replace the device ID, and `reset({ bootstrap: { distinctId, isIdentifiedId, sessionId } })` to seed the new identity and next session. The setup `bootstrap` option accepts the same values. A stored identity takes precedence, except that an identified bootstrap ID identifies a stored anonymous user, as in posthog-js. Use `bootstrap.sessionId` to continue a UUIDv7 session ID passed from another domain.
356
391
 
357
- Session and window IDs are created on the first successfully admitted capture. Rejected work does not create or advance them. Idle timeout, maximum length, and reset rotate both IDs. Same-origin tabs share the active session while retaining distinct window IDs; ordinary reloads preserve the window ID and copied tab storage receives a new one. Session rotation is activity-driven and starts no core timer.
392
+ Identity and session state live in the configured storage only. To share them across subdomains, and with posthog-js through its `ph_<project-token>_posthog` cookie, pass `cookie: cookiePersistence()` from `@posthog/browser/persistence/cookie`. The cookie is opt-in, uses `SameSite=Lax`, is `Secure` on HTTPS pages, and accepts `crossSubdomain`, `secure`, `expirationDays`, and `name` options. Consent stays in the configured storage.
358
393
 
359
394
  A compact in-memory token bucket admits 10 events per second with a burst of 100 and emits a bypassed aggregate ingestion warning when a runaway loop first reaches the limit. `shutdown(timeoutMs)` stops new work, makes one bounded normal flush attempt, removes timers and lifecycle listeners, and is idempotent. `dispose()` uses the same shutdown path.
360
395
 
@@ -4,5 +4,5 @@ export declare const createPostHog: (options: CorePostHogOptions) => Promise<IPo
4
4
  export { version } from '../../primitives/version';
5
5
  export { FeatureFlagsExtension, type FeatureFlags } from '../../products/flags/flags-token';
6
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, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
7
+ export type { AnalyticsOptions, ApiResponse, BrowserFetch, BootstrapOptions, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, ExplicitConsentStatus, Extension, NewSessionInfo, NewSessionReason, IPostHog, RemoteConfig, ResetOptions, RuntimeOptions, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
8
8
  export type { PersonProfileMode } from '../../products/analytics/analytics-options';
@@ -4,8 +4,8 @@ export declare const createPostHog: (options: PostHogOptions) => Promise<IPostHo
4
4
  export { version } from '../../primitives/version';
5
5
  export { FeatureFlagsExtension, type FeatureFlags } from '../../products/flags/flags-token';
6
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';
8
- export type { FlagsOptions, FlagsConfiguration, FlagsCallback, FeatureFlagResult, FeatureFlagsReloadResult, } from '../../products/flags/flags-options';
7
+ export type { AnalyticsOptions, ApiResponse, BrowserFetch, BootstrapOptions, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, ExplicitConsentStatus, Extension, NewSessionInfo, NewSessionReason, IPostHog, PostHogOptions, RemoteConfig, ResetOptions, RuntimeOptions, SendRequestInit, SessionContext, StorageLike, } from '../../core/types';
8
+ export type { EarlyAccessFeature, EarlyAccessFeatureCallback, EarlyAccessFeatureStage, FlagsOptions, FlagsConfiguration, FlagsCallback, FlagsReadOptions, FeatureFlagResult, FeatureFlagsReloadResult, } from '../../products/flags/flags-options';
9
9
  export type { LogsOptions, LogsConfiguration, CaptureLogOptions } from '../../products/logs/logs-options';
10
10
  export type { SurveysOptions, SurveysConfiguration, Survey, SurveyCallback, DisplaySurveyOptions, SurveyRenderReason, } from '../../products/surveys/surveys-options';
11
11
  export type { AutocaptureOptions, AutocaptureConfiguration, RageclickOptions, } from '../../products/autocapture/autocapture-options';
@@ -39,11 +39,22 @@ const bot_filter_js_namespaceObject = require("./state/bot-filter.js");
39
39
  const registry_js_namespaceObject = require("./extensions/registry.js");
40
40
  const immutable_js_namespaceObject = require("../primitives/immutable.js");
41
41
  const logger_js_namespaceObject = require("../platform/logger.js");
42
+ const person_processing_js_namespaceObject = require("../products/analytics/properties/person-processing.js");
42
43
  const request_js_namespaceObject = require("../platform/request.js");
43
44
  const state_js_namespaceObject = require("./state/state.js");
44
45
  const version_js_namespaceObject = require("../primitives/version.js");
45
46
  const CONSENT_CHANGE_EVENT = '__posthog_browser_consent_change__';
46
47
  const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30000;
48
+ const EARLY_ACCESS_CATALOGUE_PATH = /^\/api\/early_access_features\/\?token=[^&#]*(&stage=(concept|alpha|beta|general-availability))*&?$/;
49
+ const resolveRequestPath = (host, path)=>{
50
+ try {
51
+ const base = new URL(`${host}/`);
52
+ const { pathname } = new URL(`.${path}`, base);
53
+ return pathname.startsWith(base.pathname) ? pathname.slice(base.pathname.length - 1) : void 0;
54
+ } catch {
55
+ return;
56
+ }
57
+ };
47
58
  const normalizeHost = (host)=>{
48
59
  let end = host.length;
49
60
  while(end > 0 && 47 === host.charCodeAt(end - 1))end--;
@@ -83,6 +94,7 @@ class PostHog {
83
94
  version: version_js_namespaceObject.version
84
95
  });
85
96
  this._immediateAuthority = {};
97
+ this._clearedChoiceRetainsWork = false;
86
98
  this._closing = false;
87
99
  this._disposed = false;
88
100
  this._initialPageviewPending = true;
@@ -93,7 +105,10 @@ class PostHog {
93
105
  } catch {}
94
106
  this.projectToken = projectToken;
95
107
  this._capturePageview = options.capturePageview ?? true;
96
- this.logger = (0, logger_js_namespaceObject.createLogger)('[PostHog]', options.debug ?? false);
108
+ this._logState = {
109
+ enabled: options.debug ?? false
110
+ };
111
+ this.logger = (0, logger_js_namespaceObject.createLogger)('[PostHog]', this._logState);
97
112
  if (!projectToken) this.logger.error('A PostHog project token is required');
98
113
  const initialPersonProperties = options.initialPersonProperties;
99
114
  try {
@@ -108,16 +123,19 @@ class PostHog {
108
123
  this._blocked = !projectToken || !(options.disableBotDetection ?? false) && (0, bot_filter_js_namespaceObject.isLikelyBot)(browserNavigator, options.blockedUserAgents ?? []);
109
124
  const requestedStorage = false === options.storage ? void 0 : options.storage ?? (0, state_js_namespaceObject.getDefaultStorage)();
110
125
  const storage = this._blocked ? void 0 : requestedStorage;
111
- this._state = new state_js_namespaceObject.BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? state_js_namespaceObject.getDefaultSessionStorage : void 0, (consent, previous)=>{
112
- if ('denied' === consent) {
113
- this._immediateAuthority = {};
114
- this._analytics?.purge();
115
- }
116
- this._consentChangePublisher.publish({
126
+ this._state = new state_js_namespaceObject.BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? state_js_namespaceObject.getDefaultSessionStorage : void 0, (consent, previous, explicit)=>{
127
+ if ('denied' !== consent) {
128
+ if (this._clearedChoiceRetainsWork) Promise.resolve().then(()=>this._analytics?.flush());
129
+ this._clearedChoiceRetainsWork = false;
130
+ } else if (explicit) this._revokeAdmittedWork();
131
+ else this._clearedChoiceRetainsWork = true;
132
+ const change = {
117
133
  current: consent,
118
134
  previous
119
- });
120
- });
135
+ };
136
+ if (this._heldConsentChanges) this._heldConsentChanges.push(change);
137
+ else this._consentChangePublisher.publish(change);
138
+ }, options.cookie);
121
139
  this._consentObservation = this._observeConsent(storage, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage);
122
140
  const apiHost = normalizeHost(options.apiHost ?? 'https://us.i.posthog.com');
123
141
  this._requestRuntime = [
@@ -166,7 +184,18 @@ class PostHog {
166
184
  this.onNewSession = this._analytics._newSessionPublisher.listener;
167
185
  this.onConsentChange = this._consentChangePublisher.listener;
168
186
  this.onSession = (listener)=>this.onNewSession((session)=>listener(session.sessionId));
187
+ this.onSessionId = (handler)=>{
188
+ const subscription = this._analytics._sessionIdPublisher.listener(handler);
189
+ const session = this._canMutate() ? this.session : void 0;
190
+ if (session) try {
191
+ handler(session);
192
+ } catch (error) {
193
+ this.logger.error('A session ID listener failed', error);
194
+ }
195
+ return subscription;
196
+ };
169
197
  this._registry = new registry_js_namespaceObject.ExtensionRegistry(this, this.logger, loaders, ()=>this._canMutate());
198
+ if (options.bootstrap) this._analytics.bootstrap(options.bootstrap);
170
199
  }
171
200
  get distinctId() {
172
201
  this._state.prepare();
@@ -206,8 +235,18 @@ class PostHog {
206
235
  identify(distinctId, set, setOnce) {
207
236
  this._analytics.identify(distinctId, set, setOnce);
208
237
  }
209
- reset() {
210
- this._analytics.reset();
238
+ reset(options) {
239
+ if (!this._canMutate()) return;
240
+ const held = this._heldConsentChanges = [];
241
+ let bootstrap;
242
+ try {
243
+ this.clearOptInOut();
244
+ bootstrap = this._analytics.reset(options);
245
+ } finally{
246
+ this._heldConsentChanges = void 0;
247
+ }
248
+ for (const change of held)this._consentChangePublisher.publish(change);
249
+ if (bootstrap) this.featureFlags?.bootstrap?.(bootstrap);
211
250
  }
212
251
  register(properties) {
213
252
  this._analytics.register(properties);
@@ -254,6 +293,9 @@ class PostHog {
254
293
  registerDynamicEventProperties(producer) {
255
294
  return this._analytics.registerDynamicEventProperties(producer);
256
295
  }
296
+ getPageViewId() {
297
+ return this._analytics._pageviewIdFor(this._state.activeSessionId);
298
+ }
257
299
  getExtension(name) {
258
300
  return this._registry.get(name);
259
301
  }
@@ -269,13 +311,25 @@ class PostHog {
269
311
  this._startInitialPageview();
270
312
  }
271
313
  optOut() {
272
- if (!this._disposed && this._state.optOut()) this._dispatchConsentChange();
314
+ if (this._disposed) return;
315
+ if (this._clearedChoiceRetainsWork) this._revokeAdmittedWork();
316
+ if (this._state.optOut()) this._dispatchConsentChange();
273
317
  }
274
318
  hasOptedOut() {
275
319
  return 'denied' === this._state.consent;
276
320
  }
321
+ getExplicitConsentStatus() {
322
+ return this._state.consentChoice ?? 'pending';
323
+ }
324
+ clearOptInOut() {
325
+ if (this._disposed) return;
326
+ if (this._state.clearConsent()) this._dispatchConsentChange();
327
+ }
277
328
  sendRequest(path, init) {
278
- return (0, request_js_namespaceObject.sendRequest)(this._requestRuntime, path, init, ()=>!this._blocked && !this.hasOptedOut());
329
+ const options = init ?? {};
330
+ const resolvedPath = resolveRequestPath(this._requestRuntime[0][options.target ?? 'api'], path);
331
+ const allowedWhileOptedOut = ('flags' === options.target ? '/flags/' === resolvedPath : EARLY_ACCESS_CATALOGUE_PATH.test(path) && (options.method ?? 'GET') === 'GET' && void 0 === options.body) && !options.query && !options.headers;
332
+ return (0, request_js_namespaceObject.sendRequest)(this._requestRuntime, path, options, ()=>!this._blocked && (allowedWhileOptedOut || !this.hasOptedOut()));
279
333
  }
280
334
  async getRemoteConfig() {
281
335
  if (this._closing || this._disposed) return;
@@ -349,6 +403,21 @@ class PostHog {
349
403
  }
350
404
  return this._remoteConfigPromise;
351
405
  }
406
+ setConfig(options) {
407
+ try {
408
+ const debug = options.debug;
409
+ if ('boolean' == typeof debug) this._logState.enabled = debug;
410
+ const personProfiles = options.analytics?.personProfiles;
411
+ if (void 0 !== personProfiles) this._analytics._personProfiles = (0, person_processing_js_namespaceObject.snapshotPersonProfileMode)(()=>personProfiles);
412
+ } catch (error) {
413
+ this.logger.error('Configuration update failed', error);
414
+ }
415
+ }
416
+ debug(enabled = true) {
417
+ this.setConfig({
418
+ debug: enabled
419
+ });
420
+ }
352
421
  resolveExtension(name) {
353
422
  return this._closing || this._disposed ? Promise.resolve(void 0) : this._registry.resolve(name);
354
423
  }
@@ -538,7 +607,12 @@ class PostHog {
538
607
  return !this._closing && !this._disposed;
539
608
  }
540
609
  _canDeliver() {
541
- return !this._disposed && !this._blocked && !this.hasOptedOut();
610
+ return !this._disposed && !this._blocked && (!this.hasOptedOut() || this._clearedChoiceRetainsWork && void 0 === this._state.consentChoice);
611
+ }
612
+ _revokeAdmittedWork() {
613
+ this._clearedChoiceRetainsWork = false;
614
+ this._immediateAuthority = {};
615
+ this._analytics?.purge();
542
616
  }
543
617
  }
544
618
  const selectConfiguredExtensions = (configured)=>{
@@ -5,6 +5,7 @@ import { isLikelyBot } from "./state/bot-filter.mjs";
5
5
  import { ExtensionRegistry } from "./extensions/registry.mjs";
6
6
  import { deepFreeze } from "../primitives/immutable.mjs";
7
7
  import { createLogger } from "../platform/logger.mjs";
8
+ import { snapshotPersonProfileMode } from "../products/analytics/properties/person-processing.mjs";
8
9
  import { sendRequest } from "../platform/request.mjs";
9
10
  import { BrowserState, CLIENT_KV_NAMESPACE, getDefaultSessionStorage, getDefaultStorage } from "./state/state.mjs";
10
11
  import { version } from "../primitives/version.mjs";
@@ -12,6 +13,16 @@ import * as __rspack_external__products_analytics_groups_mjs_441733a9 from "../p
12
13
  import * as __rspack_external__products_analytics_person_mjs_3dfa168e from "../products/analytics/person.mjs";
13
14
  const CONSENT_CHANGE_EVENT = '__posthog_browser_consent_change__';
14
15
  const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30000;
16
+ const EARLY_ACCESS_CATALOGUE_PATH = /^\/api\/early_access_features\/\?token=[^&#]*(&stage=(concept|alpha|beta|general-availability))*&?$/;
17
+ const resolveRequestPath = (host, path)=>{
18
+ try {
19
+ const base = new URL(`${host}/`);
20
+ const { pathname } = new URL(`.${path}`, base);
21
+ return pathname.startsWith(base.pathname) ? pathname.slice(base.pathname.length - 1) : void 0;
22
+ } catch {
23
+ return;
24
+ }
25
+ };
15
26
  const normalizeHost = (host)=>{
16
27
  let end = host.length;
17
28
  while(end > 0 && 47 === host.charCodeAt(end - 1))end--;
@@ -51,6 +62,7 @@ class PostHog {
51
62
  version: version
52
63
  });
53
64
  this._immediateAuthority = {};
65
+ this._clearedChoiceRetainsWork = false;
54
66
  this._closing = false;
55
67
  this._disposed = false;
56
68
  this._initialPageviewPending = true;
@@ -61,7 +73,10 @@ class PostHog {
61
73
  } catch {}
62
74
  this.projectToken = projectToken;
63
75
  this._capturePageview = options.capturePageview ?? true;
64
- this.logger = createLogger('[PostHog]', options.debug ?? false);
76
+ this._logState = {
77
+ enabled: options.debug ?? false
78
+ };
79
+ this.logger = createLogger('[PostHog]', this._logState);
65
80
  if (!projectToken) this.logger.error('A PostHog project token is required');
66
81
  const initialPersonProperties = options.initialPersonProperties;
67
82
  try {
@@ -76,16 +91,19 @@ class PostHog {
76
91
  this._blocked = !projectToken || !(options.disableBotDetection ?? false) && isLikelyBot(browserNavigator, options.blockedUserAgents ?? []);
77
92
  const requestedStorage = false === options.storage ? void 0 : options.storage ?? getDefaultStorage();
78
93
  const storage = this._blocked ? void 0 : requestedStorage;
79
- this._state = new BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? getDefaultSessionStorage : void 0, (consent, previous)=>{
80
- if ('denied' === consent) {
81
- this._immediateAuthority = {};
82
- this._analytics?.purge();
83
- }
84
- this._consentChangePublisher.publish({
94
+ this._state = new BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? getDefaultSessionStorage : void 0, (consent, previous, explicit)=>{
95
+ if ('denied' !== consent) {
96
+ if (this._clearedChoiceRetainsWork) Promise.resolve().then(()=>this._analytics?.flush());
97
+ this._clearedChoiceRetainsWork = false;
98
+ } else if (explicit) this._revokeAdmittedWork();
99
+ else this._clearedChoiceRetainsWork = true;
100
+ const change = {
85
101
  current: consent,
86
102
  previous
87
- });
88
- });
103
+ };
104
+ if (this._heldConsentChanges) this._heldConsentChanges.push(change);
105
+ else this._consentChangePublisher.publish(change);
106
+ }, options.cookie);
89
107
  this._consentObservation = this._observeConsent(storage, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage);
90
108
  const apiHost = normalizeHost(options.apiHost ?? 'https://us.i.posthog.com');
91
109
  this._requestRuntime = [
@@ -134,7 +152,18 @@ class PostHog {
134
152
  this.onNewSession = this._analytics._newSessionPublisher.listener;
135
153
  this.onConsentChange = this._consentChangePublisher.listener;
136
154
  this.onSession = (listener)=>this.onNewSession((session)=>listener(session.sessionId));
155
+ this.onSessionId = (handler)=>{
156
+ const subscription = this._analytics._sessionIdPublisher.listener(handler);
157
+ const session = this._canMutate() ? this.session : void 0;
158
+ if (session) try {
159
+ handler(session);
160
+ } catch (error) {
161
+ this.logger.error('A session ID listener failed', error);
162
+ }
163
+ return subscription;
164
+ };
137
165
  this._registry = new ExtensionRegistry(this, this.logger, loaders, ()=>this._canMutate());
166
+ if (options.bootstrap) this._analytics.bootstrap(options.bootstrap);
138
167
  }
139
168
  get distinctId() {
140
169
  this._state.prepare();
@@ -174,8 +203,18 @@ class PostHog {
174
203
  identify(distinctId, set, setOnce) {
175
204
  this._analytics.identify(distinctId, set, setOnce);
176
205
  }
177
- reset() {
178
- this._analytics.reset();
206
+ reset(options) {
207
+ if (!this._canMutate()) return;
208
+ const held = this._heldConsentChanges = [];
209
+ let bootstrap;
210
+ try {
211
+ this.clearOptInOut();
212
+ bootstrap = this._analytics.reset(options);
213
+ } finally{
214
+ this._heldConsentChanges = void 0;
215
+ }
216
+ for (const change of held)this._consentChangePublisher.publish(change);
217
+ if (bootstrap) this.featureFlags?.bootstrap?.(bootstrap);
179
218
  }
180
219
  register(properties) {
181
220
  this._analytics.register(properties);
@@ -222,6 +261,9 @@ class PostHog {
222
261
  registerDynamicEventProperties(producer) {
223
262
  return this._analytics.registerDynamicEventProperties(producer);
224
263
  }
264
+ getPageViewId() {
265
+ return this._analytics._pageviewIdFor(this._state.activeSessionId);
266
+ }
225
267
  getExtension(name) {
226
268
  return this._registry.get(name);
227
269
  }
@@ -237,13 +279,25 @@ class PostHog {
237
279
  this._startInitialPageview();
238
280
  }
239
281
  optOut() {
240
- if (!this._disposed && this._state.optOut()) this._dispatchConsentChange();
282
+ if (this._disposed) return;
283
+ if (this._clearedChoiceRetainsWork) this._revokeAdmittedWork();
284
+ if (this._state.optOut()) this._dispatchConsentChange();
241
285
  }
242
286
  hasOptedOut() {
243
287
  return 'denied' === this._state.consent;
244
288
  }
289
+ getExplicitConsentStatus() {
290
+ return this._state.consentChoice ?? 'pending';
291
+ }
292
+ clearOptInOut() {
293
+ if (this._disposed) return;
294
+ if (this._state.clearConsent()) this._dispatchConsentChange();
295
+ }
245
296
  sendRequest(path, init) {
246
- return sendRequest(this._requestRuntime, path, init, ()=>!this._blocked && !this.hasOptedOut());
297
+ const options = init ?? {};
298
+ const resolvedPath = resolveRequestPath(this._requestRuntime[0][options.target ?? 'api'], path);
299
+ const allowedWhileOptedOut = ('flags' === options.target ? '/flags/' === resolvedPath : EARLY_ACCESS_CATALOGUE_PATH.test(path) && (options.method ?? 'GET') === 'GET' && void 0 === options.body) && !options.query && !options.headers;
300
+ return sendRequest(this._requestRuntime, path, options, ()=>!this._blocked && (allowedWhileOptedOut || !this.hasOptedOut()));
247
301
  }
248
302
  async getRemoteConfig() {
249
303
  if (this._closing || this._disposed) return;
@@ -317,6 +371,21 @@ class PostHog {
317
371
  }
318
372
  return this._remoteConfigPromise;
319
373
  }
374
+ setConfig(options) {
375
+ try {
376
+ const debug = options.debug;
377
+ if ('boolean' == typeof debug) this._logState.enabled = debug;
378
+ const personProfiles = options.analytics?.personProfiles;
379
+ if (void 0 !== personProfiles) this._analytics._personProfiles = snapshotPersonProfileMode(()=>personProfiles);
380
+ } catch (error) {
381
+ this.logger.error('Configuration update failed', error);
382
+ }
383
+ }
384
+ debug(enabled = true) {
385
+ this.setConfig({
386
+ debug: enabled
387
+ });
388
+ }
320
389
  resolveExtension(name) {
321
390
  return this._closing || this._disposed ? Promise.resolve(void 0) : this._registry.resolve(name);
322
391
  }
@@ -506,7 +575,12 @@ class PostHog {
506
575
  return !this._closing && !this._disposed;
507
576
  }
508
577
  _canDeliver() {
509
- return !this._disposed && !this._blocked && !this.hasOptedOut();
578
+ return !this._disposed && !this._blocked && (!this.hasOptedOut() || this._clearedChoiceRetainsWork && void 0 === this._state.consentChoice);
579
+ }
580
+ _revokeAdmittedWork() {
581
+ this._clearedChoiceRetainsWork = false;
582
+ this._immediateAuthority = {};
583
+ this._analytics?.purge();
510
584
  }
511
585
  }
512
586
  const selectConfiguredExtensions = (configured)=>{