@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.
Files changed (85) hide show
  1. package/ARCHITECTURE.md +36 -48
  2. package/README.md +97 -69
  3. package/dist/composition/npm/core.d.ts +3 -4
  4. package/dist/composition/npm/core.js +2 -1
  5. package/dist/composition/npm/core.mjs +2 -1
  6. package/dist/composition/npm/index.d.ts +4 -5
  7. package/dist/composition/npm/index.js +2 -1
  8. package/dist/composition/npm/index.mjs +2 -1
  9. package/dist/composition/npm/root-composition.d.ts +4 -4
  10. package/dist/composition/npm/root-composition.js +0 -16
  11. package/dist/composition/npm/root-composition.mjs +0 -16
  12. package/dist/core/context/browser-client.d.ts +4 -35
  13. package/dist/core/extensions/registry.d.ts +15 -36
  14. package/dist/core/extensions/registry.js +67 -198
  15. package/dist/core/extensions/registry.mjs +67 -198
  16. package/dist/core/posthog.d.ts +3 -2
  17. package/dist/core/posthog.js +190 -173
  18. package/dist/core/posthog.mjs +191 -174
  19. package/dist/core/state/state.d.ts +33 -3
  20. package/dist/core/state/state.js +122 -27
  21. package/dist/core/state/state.mjs +107 -27
  22. package/dist/core/types.d.ts +134 -14
  23. package/dist/persistence/cookie.d.ts +19 -0
  24. package/dist/persistence/cookie.js +273 -0
  25. package/dist/persistence/cookie.mjs +235 -0
  26. package/dist/platform/logger.d.ts +5 -1
  27. package/dist/platform/logger.js +3 -3
  28. package/dist/platform/logger.mjs +3 -3
  29. package/dist/primitives/id.d.ts +5 -0
  30. package/dist/primitives/id.js +10 -2
  31. package/dist/primitives/id.mjs +6 -1
  32. package/dist/primitives/version.js +1 -1
  33. package/dist/primitives/version.mjs +1 -1
  34. package/dist/products/analytics/analytics-core.d.ts +89 -0
  35. package/dist/products/analytics/analytics-core.js +563 -0
  36. package/dist/products/analytics/analytics-core.mjs +516 -0
  37. package/dist/products/analytics/analytics-internal.d.ts +16 -37
  38. package/dist/products/analytics/analytics-internal.js +2 -10
  39. package/dist/products/analytics/analytics-internal.mjs +1 -3
  40. package/dist/products/analytics/analytics-options.d.ts +0 -9
  41. package/dist/products/analytics/analytics-options.js +1 -38
  42. package/dist/products/analytics/analytics-options.mjs +1 -17
  43. package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
  44. package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
  45. package/dist/products/analytics/delivery/lane.d.ts +8 -1
  46. package/dist/products/analytics/delivery/lane.js +16 -4
  47. package/dist/products/analytics/delivery/lane.mjs +16 -4
  48. package/dist/products/analytics/groups.d.ts +8 -0
  49. package/dist/products/analytics/groups.js +84 -0
  50. package/dist/products/analytics/groups.mjs +40 -0
  51. package/dist/products/analytics/person.d.ts +11 -0
  52. package/dist/products/analytics/person.js +91 -0
  53. package/dist/products/analytics/person.mjs +41 -0
  54. package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
  55. package/dist/products/analytics/properties/analytics-properties.js +3 -0
  56. package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
  57. package/dist/products/autocapture/autocapture.js +2 -6
  58. package/dist/products/autocapture/autocapture.mjs +2 -6
  59. package/dist/products/flags/flags-internal.d.ts +4 -2
  60. package/dist/products/flags/flags-options.d.ts +16 -2
  61. package/dist/products/flags/flags-token.d.ts +31 -4
  62. package/dist/products/flags/flags.d.ts +1 -1
  63. package/dist/products/flags/flags.js +112 -11
  64. package/dist/products/flags/flags.mjs +112 -11
  65. package/dist/products/logs/logs.js +2 -5
  66. package/dist/products/logs/logs.mjs +2 -5
  67. package/dist/products/surveys/surveys-extension.js +78 -46
  68. package/dist/products/surveys/surveys-extension.mjs +80 -48
  69. package/dist/products/surveys/surveys-internal.d.ts +6 -0
  70. package/package.json +7 -7
  71. package/dist/products/analytics/analytics-api.d.ts +0 -32
  72. package/dist/products/analytics/analytics-api.js +0 -18
  73. package/dist/products/analytics/analytics-api.mjs +0 -1
  74. package/dist/products/analytics/analytics-buffer.d.ts +0 -4
  75. package/dist/products/analytics/analytics-buffer.js +0 -41
  76. package/dist/products/analytics/analytics-buffer.mjs +0 -3
  77. package/dist/products/analytics/analytics-extension.d.ts +0 -87
  78. package/dist/products/analytics/analytics-extension.js +0 -649
  79. package/dist/products/analytics/analytics-extension.mjs +0 -611
  80. package/dist/products/analytics/analytics.d.ts +0 -6
  81. package/dist/products/analytics/analytics.js +0 -42
  82. package/dist/products/analytics/analytics.mjs +0 -4
  83. package/dist/products/analytics/automatic-analytics.d.ts +0 -3
  84. package/dist/products/analytics/automatic-analytics.js +0 -44
  85. package/dist/products/analytics/automatic-analytics.mjs +0 -6
@@ -1,10 +1,10 @@
1
- import type { FlagsConfiguration } from '../products/flags/flags-options';
2
- import type { ICoreCapabilities, BrowserExtensionAccess, BrowserExtension as Extension } from './context/browser-client';
1
+ import type { FlagsConfiguration, FlagsOptions } from '../products/flags/flags-options';
2
+ import type { BrowserExtension as Extension, BrowserProducts, ChangePropertiesInfo, ConsentChangeInfo, GroupInfo, IdentifyInfo } from './context/browser-client';
3
3
  import type { LogsConfiguration } from '../products/logs/logs-options';
4
4
  import type { SurveysConfiguration } from '../products/surveys/surveys-options';
5
5
  import type { AutocaptureConfiguration } from '../products/autocapture/autocapture-options';
6
- import type { AnalyticsConfiguration, AnalyticsOptions, AutomaticAnalyticsOptions, LoadStrategy, PersonProfileMode } from '../products/analytics/analytics-options';
7
- import type { ApiResponse, CaptureOptions, Disposable, Listener, RemoteConfig, SendRequestInit, SessionContext } from '@posthog/browser-common';
6
+ import type { AnalyticsOptions, PersonProfileMode } from '../products/analytics/analytics-options';
7
+ import type { ApiResponse, CaptureOptions, Client, Disposable, ExtensionToken, Listener, RemoteConfig, SendRequestInit, SessionContext } from '@posthog/browser-common';
8
8
  export interface StorageLike {
9
9
  getItem(key: string): string | null;
10
10
  setItem(key: string, value: string): void;
@@ -23,6 +23,38 @@ export type NewSessionReason = 'idleTimeout' | 'maxLength' | 'reset';
23
23
  export interface NewSessionInfo extends SessionContext {
24
24
  readonly reason: NewSessionReason;
25
25
  }
26
+ /** Whether the user explicitly opted in, explicitly opted out, or has not chosen. */
27
+ export type ExplicitConsentStatus = 'granted' | 'denied' | 'pending';
28
+ /** Identity and session values to use instead of generated ones. */
29
+ export interface BootstrapOptions {
30
+ /** Distinct ID to use when no identity is stored. An identified ID also identifies a stored anonymous user. */
31
+ distinctId?: string;
32
+ /** Whether `distinctId` identifies a known person rather than an anonymous user. */
33
+ isIdentifiedId?: boolean;
34
+ /**
35
+ * UUIDv7 session ID to continue, such as one passed from another domain. Like a generated session, it starts with
36
+ * the first admitted event, so `session` and `onSessionId` report it from then on.
37
+ */
38
+ sessionId?: string;
39
+ }
40
+ export interface ResetOptions {
41
+ /** Also replace the device ID. */
42
+ resetDeviceId?: boolean;
43
+ /**
44
+ * Seed the new identity and next session instead of generating them. With feature flags, `featureFlags` and
45
+ * `featureFlagPayloads` are served for the new identity until flags load.
46
+ */
47
+ bootstrap?: BootstrapOptions & FlagsOptions['bootstrap'];
48
+ }
49
+ /**
50
+ * Shares identity and session state through a cookie. Create one with `cookiePersistence()` from
51
+ * `@posthog/browser/persistence/cookie`; only instances it returns are supported. `wrap` and the state record it
52
+ * reads and writes are internal, so their shape can change in any release.
53
+ */
54
+ export interface CookiePersistence {
55
+ /** Wraps the state storage so the identity record also reads from and writes to the cookie. */
56
+ wrap(storage: StorageLike, stateKey: string, projectToken: string): StorageLike;
57
+ }
26
58
  export interface PostHogOptions {
27
59
  /** PostHog project token. */
28
60
  projectToken: string;
@@ -34,13 +66,20 @@ export interface PostHogOptions {
34
66
  storage?: StorageLike | false;
35
67
  /** Override the storage key. */
36
68
  persistenceKey?: string;
69
+ /** Also persist identity and session state in a cookie, sharing them across subdomains. */
70
+ cookie?: CookiePersistence;
71
+ /**
72
+ * Identity and session values to use instead of generated ones. A stored identity takes precedence, except that an
73
+ * identified bootstrap ID identifies a stored anonymous user, as in posthog-js.
74
+ */
75
+ bootstrap?: BootstrapOptions;
37
76
  /** Override the consent key verbatim. Defaults to `__ph_opt_in_out_<projectToken>`. */
38
77
  consentPersistenceName?: string;
39
78
  /** Fetch implementation. Pass `false` to disable network requests. */
40
79
  fetch?: BrowserFetch | false;
41
80
  /** Navigator implementation. Pass `false` to disable navigator capabilities. */
42
81
  navigator?: BrowserNavigator | false;
43
- /** Start with capture disabled until `optIn()` runs. */
82
+ /** Start with capture disabled until `optIn()` runs. Feature flags still load, as in posthog-js. */
44
83
  optOutByDefault?: boolean;
45
84
  /** Capture one initial `$pageview` after configured extensions install. Defaults to `true`. */
46
85
  capturePageview?: boolean;
@@ -56,11 +95,8 @@ export interface PostHogOptions {
56
95
  remoteConfig?: RemoteConfig;
57
96
  /** Stop waiting for remote configuration after this duration in milliseconds. Defaults to 10,000. */
58
97
  remoteConfigTimeoutMs?: number;
59
- /**
60
- * First-party analytics acquisition. Defaults to on-demand loading through resolution, product dependencies,
61
- * or the initial pageview. Pass `false` to omit implicit analytics; explicit instances take precedence.
62
- */
63
- analytics?: AnalyticsConfiguration;
98
+ /** Capture scheduling and person-processing policy. */
99
+ analytics?: AnalyticsOptions;
64
100
  /** Acquire DOM autocapture from saved/fresh signals, or during initialization when configured explicitly. */
65
101
  autocapture?: AutocaptureConfiguration;
66
102
  /** Dynamically include flags by default. Explicit extensions take precedence over this option. */
@@ -72,8 +108,18 @@ export interface PostHogOptions {
72
108
  /** Install extensions before the factory resolves. Explicit instances take precedence over automatic product options. */
73
109
  extensions?: readonly Extension[];
74
110
  }
111
+ /** Options that `setConfig()` can change after creation. Omitted options keep their current values. */
112
+ export interface RuntimeOptions {
113
+ /** Enable or disable SDK diagnostic logs, including loggers that extensions already created. */
114
+ debug?: boolean;
115
+ /**
116
+ * Analytics policy applied to subsequent captures. As in `posthog-js`, downgrading `personProfiles` from `'always'`
117
+ * to `'identified_only'` keeps person processing for a visitor whose events were already processed; `'never'` stops it.
118
+ */
119
+ analytics?: Pick<AnalyticsOptions, 'personProfiles'>;
120
+ }
75
121
  /** Options for the manually composed `@posthog/browser/core` entrypoint. */
76
- export type CorePostHogOptions = Omit<PostHogOptions, 'analytics' | 'flags' | 'logs' | 'surveys' | 'autocapture'>;
122
+ export type CorePostHogOptions = Omit<PostHogOptions, 'flags' | 'logs' | 'surveys' | 'autocapture'>;
77
123
  /** Capture V1's terminal verdict for one reported event. */
78
124
  export type CaptureOutcomeStatus = 'ok' | 'warning' | 'drop' | 'retry';
79
125
  /** A backend-reported Capture V1 event verdict. */
@@ -94,15 +140,89 @@ export interface CaptureSummary {
94
140
  /** Operation-level failure, with any known partial results retained. Errors always set `allPersisted` to false. */
95
141
  readonly error?: Error;
96
142
  }
97
- /** Consumer-facing SDK contract; product controls use their public interfaces. */
98
- export interface IPostHog extends ICoreCapabilities, BrowserExtensionAccess, Disposable {
143
+ /** The one browser client: the shared `Client` contract plus browser lifecycle, identity and product access. */
144
+ export interface IPostHog extends Client, Readonly<Partial<BrowserProducts>>, Disposable {
145
+ readonly isRateLimited: boolean;
146
+ captureImmediate(event: string, properties?: Record<string, unknown> | null, options?: CaptureOptions): Promise<CaptureSummary>;
147
+ identify(distinctId: string, set?: Record<string, unknown>, setOnce?: Record<string, unknown>): void;
148
+ /**
149
+ * Starts a new anonymous identity and session, and forgets the stored consent choice. Pass `true`, as in
150
+ * posthog-js, or `{ resetDeviceId: true }` to also replace the device ID.
151
+ *
152
+ * With `optOutByDefault`, capture returns to the default (opted out), so calling `reset()` after `optIn()` stops
153
+ * capture. Reset first, then opt in again if needed: `posthog.reset(); posthog.optIn()`. Events captured before
154
+ * the reset, in this or another tab, are still delivered. Consent listeners hear of the forgotten choice after the
155
+ * new identity is in place and `onReset` listeners have run.
156
+ */
157
+ reset(options?: boolean | ResetOptions): void;
158
+ register(properties: Record<string, unknown>): void;
159
+ registerOnce(properties: Record<string, unknown>, defaultValue?: unknown): void;
160
+ unregister(property: string): void;
161
+ getProperty(property: string): unknown;
162
+ /** The UUID of the last `$pageview` captured in the current session, sent on events as `$pageview_id`. */
163
+ getPageViewId(): string | undefined;
164
+ registerForSession(properties: Record<string, unknown>): void;
165
+ unregisterForSession(property: string): void;
166
+ /** Links another distinct ID to the current person without changing the current identity. */
167
+ alias(aliasId: string): void;
168
+ /** Associates future events with a group and, when person processing is enabled, records its properties. */
169
+ group(type: string, key: string, properties?: Record<string, unknown>): void;
170
+ /** Sends a group-profile update without changing group membership. */
171
+ groupIdentify(type: string, key: string | number, properties?: Record<string, unknown>, options?: CaptureOptions): void;
172
+ /** Clears group memberships, retaining identity, sessions and registered properties. */
173
+ resetGroups(): void;
174
+ /** Enables person processing for the current identity without identifying it. */
175
+ createPersonProfile(): void;
176
+ /** Sets person properties for the current identity. */
177
+ setPersonProperties(set?: Record<string, unknown>, setOnce?: Record<string, unknown>): void;
178
+ /** Removes person properties from the current identity. */
179
+ unsetPersonProperties(names: string | readonly string[]): void;
180
+ /** Marks the current person as an internal or test user. */
181
+ setInternalOrTestUser(): void;
99
182
  readonly onNewSession: Listener<NewSessionInfo>;
183
+ /**
184
+ * Fires with the current session immediately when one exists, then whenever this tab's session or window ID
185
+ * changes, including when it adopts a sibling tab's session. Sessions start with admitted events, not subscriptions.
186
+ */
187
+ readonly onSessionId: Listener<SessionContext>;
188
+ /** Fires when consent changes, including changes observed from another tab. Does not replay. */
189
+ readonly onConsentChange: Listener<ConsentChangeInfo>;
190
+ /**
191
+ * Fires after identification, independently of capture consent, including an identification this client adopts
192
+ * from another subdomain through cookie persistence. Does not replay.
193
+ */
194
+ readonly onIdentify: Listener<IdentifyInfo>;
195
+ /** Local person-property changes, independently of capture consent. Does not replay. */
196
+ readonly onChangeProperties: Listener<ChangePropertiesInfo>;
197
+ /** Fires after group membership or property updates, independently of capture consent. Does not replay. */
198
+ readonly onGroup: Listener<GroupInfo>;
199
+ /** Fires after group-only reset clears local membership. Does not replay. */
200
+ readonly onGroupsReset: Listener<void>;
201
+ /**
202
+ * Fires after local identity and persisted extension state are reset, including a reset this client adopts from
203
+ * another subdomain through cookie persistence. Does not replay.
204
+ */
205
+ readonly onReset: Listener<void>;
206
+ resolveExtension<T extends Extension>(token: ExtensionToken<T>): Promise<T | undefined>;
207
+ resolveExtension<Name extends keyof BrowserProducts>(name: Name): Promise<BrowserProducts[Name] | undefined>;
208
+ resolveExtension<T extends Extension = Extension>(name: string): Promise<T | undefined>;
100
209
  flush(): Promise<void>;
101
210
  shutdown(shutdownTimeoutMs?: number): Promise<void>;
102
211
  dispose(): Promise<void>;
103
212
  optIn(): void;
104
213
  optOut(): void;
105
214
  hasOptedOut(): boolean;
215
+ /** The stored opt-in or opt-out choice, independently of `optOutByDefault`. */
216
+ getExplicitConsentStatus(): ExplicitConsentStatus;
217
+ /**
218
+ * Forgets the stored opt-in or opt-out choice, returning consent to the configured default. Events captured before
219
+ * the call are still delivered.
220
+ */
221
+ clearOptInOut(): void;
106
222
  getRemoteConfig(): Promise<RemoteConfig | undefined>;
223
+ /** Change the options in `RuntimeOptions`. Other creation options are fixed for the client's lifetime. */
224
+ setConfig(options: RuntimeOptions): void;
225
+ /** Enable SDK diagnostic logs, or disable them with `debug(false)`. Equivalent to `setConfig({ debug })`. */
226
+ debug(enabled?: boolean): void;
107
227
  }
108
- export type { AnalyticsConfiguration, AnalyticsOptions, AutomaticAnalyticsOptions, LoadStrategy, PersonProfileMode, ApiResponse, CaptureOptions, Disposable, Extension, RemoteConfig, SendRequestInit, SessionContext, };
228
+ export type { AnalyticsOptions, PersonProfileMode, ApiResponse, CaptureOptions, Disposable, Extension, RemoteConfig, SendRequestInit, SessionContext, };
@@ -0,0 +1,19 @@
1
+ import type { CookiePersistence } from '../core/types';
2
+ export type { CookiePersistence };
3
+ export interface CookiePersistenceOptions {
4
+ /** Share the cookie with every subdomain of the site. Defaults to `true`, except on herokuapp.com, vercel.app and netlify.app. */
5
+ crossSubdomain?: boolean;
6
+ /** Send the cookie only over HTTPS. Defaults to `true` on HTTPS pages. */
7
+ secure?: boolean;
8
+ /** Days until the cookie expires. Each write renews it. Defaults to 365. */
9
+ expirationDays?: number;
10
+ /** Cookie name. Defaults to `ph_<project token>_posthog`, the name `posthog-js` uses. */
11
+ name?: string;
12
+ }
13
+ /**
14
+ * Persists identity and session state in a cookie as well as local storage, so subdomains of a site share one
15
+ * identity. An open page adopts an identify or reset from another subdomain before its next event or identity
16
+ * operation. The cookie uses the `posthog-js` name and keys, so identities continue across a migration and between
17
+ * sites that use either SDK. Consent stays in local storage, as in `posthog-js`.
18
+ */
19
+ export declare const cookiePersistence: (options?: CookiePersistenceOptions) => CookiePersistence;
@@ -0,0 +1,273 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ cookiePersistence: ()=>cookiePersistence
32
+ });
33
+ const constants_namespaceObject = require("@posthog/browser-common/constants");
34
+ const id_js_namespaceObject = require("../primitives/id.js");
35
+ const state_js_namespaceObject = require("../core/state/state.js");
36
+ const analytics_core_js_namespaceObject = require("../products/analytics/analytics-core.js");
37
+ const analytics_properties_js_namespaceObject = require("../products/analytics/properties/analytics-properties.js");
38
+ const IDENTITY_BOUND_KEYS = [
39
+ constants_namespaceObject.STORED_PERSON_PROPERTIES_KEY,
40
+ constants_namespaceObject.PERSISTENCE_ACTIVE_FEATURE_FLAGS,
41
+ constants_namespaceObject.ENABLED_FEATURE_FLAGS,
42
+ constants_namespaceObject.PERSISTENCE_FEATURE_FLAG_DETAILS,
43
+ constants_namespaceObject.PERSISTENCE_FEATURE_FLAG_PAYLOADS,
44
+ constants_namespaceObject.PERSISTENCE_FEATURE_FLAG_REQUEST_ID,
45
+ constants_namespaceObject.PERSISTENCE_FEATURE_FLAG_EVALUATED_AT,
46
+ constants_namespaceObject.PERSISTENCE_FEATURE_FLAG_ERRORS,
47
+ constants_namespaceObject.FLAG_CALL_REPORTED
48
+ ];
49
+ const SHARED_HOSTING_DOMAINS = [
50
+ 'herokuapp.com',
51
+ 'vercel.app',
52
+ 'netlify.app'
53
+ ];
54
+ const REVISION = /^(0|[1-9]\d*)$/;
55
+ const getDocument = ()=>{
56
+ try {
57
+ return globalThis.document;
58
+ } catch {
59
+ return;
60
+ }
61
+ };
62
+ const readCookie = (name)=>{
63
+ try {
64
+ const prefix = `${name}=`;
65
+ for (const part of getDocument()?.cookie.split(';') ?? []){
66
+ const cookie = part.trim();
67
+ if (cookie.startsWith(prefix)) {
68
+ const value = JSON.parse(decodeURIComponent(cookie.slice(prefix.length)));
69
+ return (0, state_js_namespaceObject.isRecord)(value) ? value : void 0;
70
+ }
71
+ }
72
+ } catch {}
73
+ };
74
+ const findSiteDomain = (document, hostname)=>{
75
+ if ('localhost' === hostname || /^[\d.]+$|:/.test(hostname)) return '';
76
+ const parts = hostname.split('.');
77
+ const probe = `dmn_chk_${(0, id_js_namespaceObject.createId)()}`;
78
+ for(let length = 1; length <= Math.min(parts.length, 8); length++){
79
+ const candidate = parts.slice(-length).join('.');
80
+ const cookie = `${probe}=1; domain=.${candidate}; path=/`;
81
+ document.cookie = `${cookie}; max-age=3`;
82
+ if (document.cookie.includes(probe)) {
83
+ document.cookie = `${cookie}; max-age=0`;
84
+ return candidate;
85
+ }
86
+ }
87
+ return /[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i.exec(hostname)?.[0] ?? '';
88
+ };
89
+ const mergeCookie = (local, cookie)=>{
90
+ const distinctId = cookie?.distinct_id;
91
+ if (!cookie || !(0, analytics_core_js_namespaceObject.isValidDistinctId)(distinctId)) return local;
92
+ let record;
93
+ try {
94
+ const parsed = local ? JSON.parse(local) : void 0;
95
+ record = (0, state_js_namespaceObject.isRecord)(parsed) && 1 === parsed.version ? parsed : void 0;
96
+ } catch {
97
+ record = void 0;
98
+ }
99
+ const identified = 'identified' === cookie.$user_state || void 0 === cookie.$user_state && record?.distinctId === distinctId && true === record.isIdentified;
100
+ const sameUser = record?.distinctId === distinctId && true === record.isIdentified === identified;
101
+ const deviceId = 'string' == typeof cookie.$device_id && cookie.$device_id ? cookie.$device_id : 'string' == typeof record?.deviceId ? record.deviceId : distinctId;
102
+ const extensionData = (0, state_js_namespaceObject.isRecord)(record?.extensionData) ? record.extensionData : {};
103
+ const data = (0, state_js_namespaceObject.isRecord)(extensionData[state_js_namespaceObject.CLIENT_KV_NAMESPACE]) ? extensionData[state_js_namespaceObject.CLIENT_KV_NAMESPACE] : {};
104
+ extensionData[state_js_namespaceObject.CLIENT_KV_NAMESPACE] = data;
105
+ const merged = {
106
+ groups: {},
107
+ ...record,
108
+ version: 1,
109
+ deviceId,
110
+ anonymousId: identified ? 'string' == typeof record?.anonymousId && (sameUser || true !== record.isIdentified) ? record.anonymousId : deviceId : distinctId,
111
+ distinctId,
112
+ isIdentified: identified,
113
+ extensionData
114
+ };
115
+ if (!sameUser) {
116
+ for (const key of IDENTITY_BOUND_KEYS)delete data[key];
117
+ if (!identified) {
118
+ merged.groups = {};
119
+ delete data[constants_namespaceObject.STORED_GROUP_PROPERTIES_KEY];
120
+ delete data[analytics_properties_js_namespaceObject.REGISTERED_PROPERTIES];
121
+ }
122
+ }
123
+ if (true === cookie.$epp) data.personProcessingEnabled = true;
124
+ else delete data.personProcessingEnabled;
125
+ delete merged.session;
126
+ delete merged.sessionReset;
127
+ const [lastActivityTimestamp, sessionId, start, revision] = Array.isArray(cookie.$sesid) ? cookie.$sesid : [];
128
+ const sessionStartTimestamp = start ?? lastActivityTimestamp;
129
+ const validRevision = 'string' == typeof revision && REVISION.test(revision) ? revision : void 0;
130
+ const knownSession = (0, state_js_namespaceObject.isRecord)(record?.session) ? record.session : void 0;
131
+ const knownRevision = void 0 !== knownSession && knownSession.sessionId === sessionId && knownSession.sessionStartTimestamp === sessionStartTimestamp && 'string' == typeof knownSession.revision && REVISION.test(knownSession.revision) ? knownSession.revision : void 0;
132
+ if ('string' == typeof sessionId && sessionId && (0, state_js_namespaceObject.isTimestamp)(lastActivityTimestamp) && (0, state_js_namespaceObject.isTimestamp)(sessionStartTimestamp) && (validRevision || Number.isSafeInteger(sessionStartTimestamp))) merged.session = {
133
+ sessionId,
134
+ sessionStartTimestamp,
135
+ lastActivityTimestamp,
136
+ revision: validRevision ?? knownRevision ?? String(sessionStartTimestamp)
137
+ };
138
+ else if (validRevision) merged.sessionReset = validRevision;
139
+ else if (null === sessionId && 'string' == typeof knownSession?.revision && REVISION.test(knownSession.revision)) merged.sessionReset = (0, state_js_namespaceObject.incrementRevision)(knownSession.revision);
140
+ return JSON.stringify(merged);
141
+ };
142
+ const sameIdentity = (cookie, identity)=>cookie.distinct_id === identity[0] && (void 0 === cookie.$user_state || 'identified' === cookie.$user_state === identity[1]);
143
+ const toCookie = (record, existing, stale, replaced)=>{
144
+ const identified = true === record.isIdentified;
145
+ const reset = !!existing && !sameIdentity(existing, [
146
+ record.distinctId,
147
+ identified
148
+ ]) && (!identified || replaced);
149
+ const value = existing && (stale || !reset) ? existing : {};
150
+ if (!stale) {
151
+ const processing = true === value.$epp && sameIdentity(value, [
152
+ record.distinctId,
153
+ identified
154
+ ]);
155
+ value.distinct_id = record.distinctId;
156
+ value.$device_id = record.deviceId;
157
+ value.$user_state = identified ? 'identified' : 'anonymous';
158
+ const extensionData = record.extensionData;
159
+ const data = (0, state_js_namespaceObject.isRecord)(extensionData) ? extensionData[state_js_namespaceObject.CLIENT_KV_NAMESPACE] : void 0;
160
+ if (processing || (0, state_js_namespaceObject.isRecord)(data) && true === data.personProcessingEnabled) value.$epp = true;
161
+ else delete value.$epp;
162
+ }
163
+ const session = record.session;
164
+ value.$sesid = (0, state_js_namespaceObject.isRecord)(session) ? [
165
+ session.lastActivityTimestamp,
166
+ session.sessionId,
167
+ session.sessionStartTimestamp,
168
+ session.revision
169
+ ] : [
170
+ null,
171
+ null,
172
+ null,
173
+ record.sessionReset ?? null
174
+ ];
175
+ return value;
176
+ };
177
+ const writeCookie = (document, name, value, settings, site)=>{
178
+ const attributes = `; SameSite=Lax; path=/${site ? `; domain=.${site}` : ''}${settings.secure ? '; secure' : ''}`;
179
+ document.cookie = value ? `${name}=${encodeURIComponent(JSON.stringify(value))}; expires=${new Date(Date.now() + 86400000 * settings.expirationDays).toUTCString()}${attributes}` : `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT${attributes}`;
180
+ };
181
+ const cookiePersistence = (options = {})=>{
182
+ let snapshot = {};
183
+ try {
184
+ snapshot = {
185
+ ...options
186
+ };
187
+ } catch {}
188
+ return {
189
+ wrap (storage, stateKey, projectToken) {
190
+ let hostname = '';
191
+ let https = false;
192
+ try {
193
+ const location = globalThis.location;
194
+ hostname = location?.hostname ?? '';
195
+ https = location?.protocol === 'https:';
196
+ } catch {}
197
+ const name = snapshot.name ?? `ph_${projectToken.replace(/\+/g, 'PL').replace(/\//g, 'SL').replace(/=/g, 'EQ')}_posthog`;
198
+ const settings = {
199
+ crossSubdomain: snapshot.crossSubdomain ?? !SHARED_HOSTING_DOMAINS.includes(hostname.split('.').slice(-2).join('.')),
200
+ secure: snapshot.secure ?? https,
201
+ expirationDays: snapshot.expirationDays ?? 365
202
+ };
203
+ let siteDomain;
204
+ const site = (document)=>siteDomain ??= findSiteDomain(document, hostname);
205
+ let known;
206
+ let anonymousId;
207
+ let scoped = false;
208
+ const write = (state)=>{
209
+ try {
210
+ const document = getDocument();
211
+ if (!document) return;
212
+ const existing = readCookie(name);
213
+ if (!scoped) {
214
+ scoped = true;
215
+ if (settings.crossSubdomain ? site(document) : existing && site(document)) writeCookie(document, name, void 0, settings, settings.crossSubdomain ? '' : site(document));
216
+ }
217
+ let value;
218
+ let identity;
219
+ if (void 0 !== state) {
220
+ const record = JSON.parse(state);
221
+ if (!(0, state_js_namespaceObject.isRecord)(record) || 'string' != typeof record.distinctId) return;
222
+ identity = [
223
+ record.distinctId,
224
+ true === record.isIdentified
225
+ ];
226
+ const stale = !!existing && !!known && (0, analytics_core_js_namespaceObject.isValidDistinctId)(existing.distinct_id) && !sameIdentity(existing, known) && identity[0] === known[0] && identity[1] === known[1];
227
+ if (stale) identity = void 0;
228
+ value = toCookie(record, existing, stale, record.anonymousId !== anonymousId);
229
+ anonymousId = record.anonymousId;
230
+ }
231
+ writeCookie(document, name, value, settings, settings.crossSubdomain ? site(document) : '');
232
+ const written = identity && readCookie(name);
233
+ if (identity && written && sameIdentity(written, identity)) known = identity;
234
+ } catch {}
235
+ };
236
+ return {
237
+ getItem: (key)=>{
238
+ if (key !== stateKey) return storage.getItem(key);
239
+ const merged = mergeCookie(storage.getItem(key), readCookie(name));
240
+ if (!known && merged) try {
241
+ const record = JSON.parse(merged);
242
+ if ((0, state_js_namespaceObject.isRecord)(record)) {
243
+ known = [
244
+ record.distinctId,
245
+ true === record.isIdentified
246
+ ];
247
+ anonymousId = record.anonymousId;
248
+ }
249
+ } catch {}
250
+ return merged;
251
+ },
252
+ setItem: (key, value)=>{
253
+ if (key === stateKey) write(value);
254
+ storage.setItem(key, value);
255
+ },
256
+ removeItem: (key)=>{
257
+ if (key === stateKey) write(void 0);
258
+ storage.removeItem(key);
259
+ },
260
+ ...storage.subscribe ? {
261
+ subscribe: (key, listener)=>storage.subscribe(key, listener)
262
+ } : {}
263
+ };
264
+ }
265
+ };
266
+ };
267
+ exports.cookiePersistence = __webpack_exports__.cookiePersistence;
268
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
269
+ "cookiePersistence"
270
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
271
+ Object.defineProperty(exports, '__esModule', {
272
+ value: true
273
+ });