@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
@@ -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
+ });
@@ -0,0 +1,235 @@
1
+ import { ENABLED_FEATURE_FLAGS, FLAG_CALL_REPORTED, PERSISTENCE_ACTIVE_FEATURE_FLAGS, PERSISTENCE_FEATURE_FLAG_DETAILS, PERSISTENCE_FEATURE_FLAG_ERRORS, PERSISTENCE_FEATURE_FLAG_EVALUATED_AT, PERSISTENCE_FEATURE_FLAG_PAYLOADS, PERSISTENCE_FEATURE_FLAG_REQUEST_ID, STORED_GROUP_PROPERTIES_KEY, STORED_PERSON_PROPERTIES_KEY } from "@posthog/browser-common/constants";
2
+ import { createId } from "../primitives/id.mjs";
3
+ import { CLIENT_KV_NAMESPACE, incrementRevision, isRecord, isTimestamp } from "../core/state/state.mjs";
4
+ import { isValidDistinctId } from "../products/analytics/analytics-core.mjs";
5
+ import { REGISTERED_PROPERTIES } from "../products/analytics/properties/analytics-properties.mjs";
6
+ const IDENTITY_BOUND_KEYS = [
7
+ STORED_PERSON_PROPERTIES_KEY,
8
+ PERSISTENCE_ACTIVE_FEATURE_FLAGS,
9
+ ENABLED_FEATURE_FLAGS,
10
+ PERSISTENCE_FEATURE_FLAG_DETAILS,
11
+ PERSISTENCE_FEATURE_FLAG_PAYLOADS,
12
+ PERSISTENCE_FEATURE_FLAG_REQUEST_ID,
13
+ PERSISTENCE_FEATURE_FLAG_EVALUATED_AT,
14
+ PERSISTENCE_FEATURE_FLAG_ERRORS,
15
+ FLAG_CALL_REPORTED
16
+ ];
17
+ const SHARED_HOSTING_DOMAINS = [
18
+ 'herokuapp.com',
19
+ 'vercel.app',
20
+ 'netlify.app'
21
+ ];
22
+ const REVISION = /^(0|[1-9]\d*)$/;
23
+ const getDocument = ()=>{
24
+ try {
25
+ return globalThis.document;
26
+ } catch {
27
+ return;
28
+ }
29
+ };
30
+ const readCookie = (name)=>{
31
+ try {
32
+ const prefix = `${name}=`;
33
+ for (const part of getDocument()?.cookie.split(';') ?? []){
34
+ const cookie = part.trim();
35
+ if (cookie.startsWith(prefix)) {
36
+ const value = JSON.parse(decodeURIComponent(cookie.slice(prefix.length)));
37
+ return isRecord(value) ? value : void 0;
38
+ }
39
+ }
40
+ } catch {}
41
+ };
42
+ const findSiteDomain = (document, hostname)=>{
43
+ if ('localhost' === hostname || /^[\d.]+$|:/.test(hostname)) return '';
44
+ const parts = hostname.split('.');
45
+ const probe = `dmn_chk_${createId()}`;
46
+ for(let length = 1; length <= Math.min(parts.length, 8); length++){
47
+ const candidate = parts.slice(-length).join('.');
48
+ const cookie = `${probe}=1; domain=.${candidate}; path=/`;
49
+ document.cookie = `${cookie}; max-age=3`;
50
+ if (document.cookie.includes(probe)) {
51
+ document.cookie = `${cookie}; max-age=0`;
52
+ return candidate;
53
+ }
54
+ }
55
+ return /[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i.exec(hostname)?.[0] ?? '';
56
+ };
57
+ const mergeCookie = (local, cookie)=>{
58
+ const distinctId = cookie?.distinct_id;
59
+ if (!cookie || !isValidDistinctId(distinctId)) return local;
60
+ let record;
61
+ try {
62
+ const parsed = local ? JSON.parse(local) : void 0;
63
+ record = isRecord(parsed) && 1 === parsed.version ? parsed : void 0;
64
+ } catch {
65
+ record = void 0;
66
+ }
67
+ const identified = 'identified' === cookie.$user_state || void 0 === cookie.$user_state && record?.distinctId === distinctId && true === record.isIdentified;
68
+ const sameUser = record?.distinctId === distinctId && true === record.isIdentified === identified;
69
+ const deviceId = 'string' == typeof cookie.$device_id && cookie.$device_id ? cookie.$device_id : 'string' == typeof record?.deviceId ? record.deviceId : distinctId;
70
+ const extensionData = isRecord(record?.extensionData) ? record.extensionData : {};
71
+ const data = isRecord(extensionData[CLIENT_KV_NAMESPACE]) ? extensionData[CLIENT_KV_NAMESPACE] : {};
72
+ extensionData[CLIENT_KV_NAMESPACE] = data;
73
+ const merged = {
74
+ groups: {},
75
+ ...record,
76
+ version: 1,
77
+ deviceId,
78
+ anonymousId: identified ? 'string' == typeof record?.anonymousId && (sameUser || true !== record.isIdentified) ? record.anonymousId : deviceId : distinctId,
79
+ distinctId,
80
+ isIdentified: identified,
81
+ extensionData
82
+ };
83
+ if (!sameUser) {
84
+ for (const key of IDENTITY_BOUND_KEYS)delete data[key];
85
+ if (!identified) {
86
+ merged.groups = {};
87
+ delete data[STORED_GROUP_PROPERTIES_KEY];
88
+ delete data[REGISTERED_PROPERTIES];
89
+ }
90
+ }
91
+ if (true === cookie.$epp) data.personProcessingEnabled = true;
92
+ else delete data.personProcessingEnabled;
93
+ delete merged.session;
94
+ delete merged.sessionReset;
95
+ const [lastActivityTimestamp, sessionId, start, revision] = Array.isArray(cookie.$sesid) ? cookie.$sesid : [];
96
+ const sessionStartTimestamp = start ?? lastActivityTimestamp;
97
+ const validRevision = 'string' == typeof revision && REVISION.test(revision) ? revision : void 0;
98
+ const knownSession = isRecord(record?.session) ? record.session : void 0;
99
+ const knownRevision = void 0 !== knownSession && knownSession.sessionId === sessionId && knownSession.sessionStartTimestamp === sessionStartTimestamp && 'string' == typeof knownSession.revision && REVISION.test(knownSession.revision) ? knownSession.revision : void 0;
100
+ if ('string' == typeof sessionId && sessionId && isTimestamp(lastActivityTimestamp) && isTimestamp(sessionStartTimestamp) && (validRevision || Number.isSafeInteger(sessionStartTimestamp))) merged.session = {
101
+ sessionId,
102
+ sessionStartTimestamp,
103
+ lastActivityTimestamp,
104
+ revision: validRevision ?? knownRevision ?? String(sessionStartTimestamp)
105
+ };
106
+ else if (validRevision) merged.sessionReset = validRevision;
107
+ else if (null === sessionId && 'string' == typeof knownSession?.revision && REVISION.test(knownSession.revision)) merged.sessionReset = incrementRevision(knownSession.revision);
108
+ return JSON.stringify(merged);
109
+ };
110
+ const sameIdentity = (cookie, identity)=>cookie.distinct_id === identity[0] && (void 0 === cookie.$user_state || 'identified' === cookie.$user_state === identity[1]);
111
+ const toCookie = (record, existing, stale, replaced)=>{
112
+ const identified = true === record.isIdentified;
113
+ const reset = !!existing && !sameIdentity(existing, [
114
+ record.distinctId,
115
+ identified
116
+ ]) && (!identified || replaced);
117
+ const value = existing && (stale || !reset) ? existing : {};
118
+ if (!stale) {
119
+ const processing = true === value.$epp && sameIdentity(value, [
120
+ record.distinctId,
121
+ identified
122
+ ]);
123
+ value.distinct_id = record.distinctId;
124
+ value.$device_id = record.deviceId;
125
+ value.$user_state = identified ? 'identified' : 'anonymous';
126
+ const extensionData = record.extensionData;
127
+ const data = isRecord(extensionData) ? extensionData[CLIENT_KV_NAMESPACE] : void 0;
128
+ if (processing || isRecord(data) && true === data.personProcessingEnabled) value.$epp = true;
129
+ else delete value.$epp;
130
+ }
131
+ const session = record.session;
132
+ value.$sesid = isRecord(session) ? [
133
+ session.lastActivityTimestamp,
134
+ session.sessionId,
135
+ session.sessionStartTimestamp,
136
+ session.revision
137
+ ] : [
138
+ null,
139
+ null,
140
+ null,
141
+ record.sessionReset ?? null
142
+ ];
143
+ return value;
144
+ };
145
+ const writeCookie = (document, name, value, settings, site)=>{
146
+ const attributes = `; SameSite=Lax; path=/${site ? `; domain=.${site}` : ''}${settings.secure ? '; secure' : ''}`;
147
+ 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}`;
148
+ };
149
+ const cookiePersistence = (options = {})=>{
150
+ let snapshot = {};
151
+ try {
152
+ snapshot = {
153
+ ...options
154
+ };
155
+ } catch {}
156
+ return {
157
+ wrap (storage, stateKey, projectToken) {
158
+ let hostname = '';
159
+ let https = false;
160
+ try {
161
+ const location = globalThis.location;
162
+ hostname = location?.hostname ?? '';
163
+ https = location?.protocol === 'https:';
164
+ } catch {}
165
+ const name = snapshot.name ?? `ph_${projectToken.replace(/\+/g, 'PL').replace(/\//g, 'SL').replace(/=/g, 'EQ')}_posthog`;
166
+ const settings = {
167
+ crossSubdomain: snapshot.crossSubdomain ?? !SHARED_HOSTING_DOMAINS.includes(hostname.split('.').slice(-2).join('.')),
168
+ secure: snapshot.secure ?? https,
169
+ expirationDays: snapshot.expirationDays ?? 365
170
+ };
171
+ let siteDomain;
172
+ const site = (document)=>siteDomain ??= findSiteDomain(document, hostname);
173
+ let known;
174
+ let anonymousId;
175
+ let scoped = false;
176
+ const write = (state)=>{
177
+ try {
178
+ const document = getDocument();
179
+ if (!document) return;
180
+ const existing = readCookie(name);
181
+ if (!scoped) {
182
+ scoped = true;
183
+ if (settings.crossSubdomain ? site(document) : existing && site(document)) writeCookie(document, name, void 0, settings, settings.crossSubdomain ? '' : site(document));
184
+ }
185
+ let value;
186
+ let identity;
187
+ if (void 0 !== state) {
188
+ const record = JSON.parse(state);
189
+ if (!isRecord(record) || 'string' != typeof record.distinctId) return;
190
+ identity = [
191
+ record.distinctId,
192
+ true === record.isIdentified
193
+ ];
194
+ const stale = !!existing && !!known && isValidDistinctId(existing.distinct_id) && !sameIdentity(existing, known) && identity[0] === known[0] && identity[1] === known[1];
195
+ if (stale) identity = void 0;
196
+ value = toCookie(record, existing, stale, record.anonymousId !== anonymousId);
197
+ anonymousId = record.anonymousId;
198
+ }
199
+ writeCookie(document, name, value, settings, settings.crossSubdomain ? site(document) : '');
200
+ const written = identity && readCookie(name);
201
+ if (identity && written && sameIdentity(written, identity)) known = identity;
202
+ } catch {}
203
+ };
204
+ return {
205
+ getItem: (key)=>{
206
+ if (key !== stateKey) return storage.getItem(key);
207
+ const merged = mergeCookie(storage.getItem(key), readCookie(name));
208
+ if (!known && merged) try {
209
+ const record = JSON.parse(merged);
210
+ if (isRecord(record)) {
211
+ known = [
212
+ record.distinctId,
213
+ true === record.isIdentified
214
+ ];
215
+ anonymousId = record.anonymousId;
216
+ }
217
+ } catch {}
218
+ return merged;
219
+ },
220
+ setItem: (key, value)=>{
221
+ if (key === stateKey) write(value);
222
+ storage.setItem(key, value);
223
+ },
224
+ removeItem: (key)=>{
225
+ if (key === stateKey) write(void 0);
226
+ storage.removeItem(key);
227
+ },
228
+ ...storage.subscribe ? {
229
+ subscribe: (key, listener)=>storage.subscribe(key, listener)
230
+ } : {}
231
+ };
232
+ }
233
+ };
234
+ };
235
+ export { cookiePersistence };
@@ -1,4 +1,8 @@
1
1
  import type { Client } from '@posthog/browser-common';
2
2
  type Logger = Client['logger'];
3
- export declare const createLogger: (prefix: string, enabled: boolean) => Logger;
3
+ /** Shared output switch, so a runtime change reaches child loggers that extensions already created. */
4
+ export interface LogState {
5
+ enabled: boolean;
6
+ }
7
+ export declare const createLogger: (prefix: string, state: LogState) => Logger;
4
8
  export {};
@@ -31,9 +31,9 @@ __webpack_require__.d(__webpack_exports__, {
31
31
  createLogger: ()=>createLogger
32
32
  });
33
33
  const console_original_namespaceObject = require("@posthog/browser-common/utils/console-original");
34
- const createLogger = (prefix, enabled)=>{
34
+ const createLogger = (prefix, state)=>{
35
35
  const write = (level, args)=>{
36
- if (!enabled) return;
36
+ if (!state.enabled) return;
37
37
  try {
38
38
  const console = globalThis.console;
39
39
  (0, console_original_namespaceObject.originalConsoleMethod)(console?.[level])?.call(console, prefix, ...args);
@@ -45,7 +45,7 @@ const createLogger = (prefix, enabled)=>{
45
45
  warn: (...args)=>write('warn', args),
46
46
  error: (...args)=>write('error', args),
47
47
  critical: (...args)=>write('error', args),
48
- createLogger: (childPrefix)=>createLogger(`${prefix} ${childPrefix}`, enabled)
48
+ createLogger: (childPrefix)=>createLogger(`${prefix} ${childPrefix}`, state)
49
49
  };
50
50
  };
51
51
  exports.createLogger = __webpack_exports__.createLogger;
@@ -1,7 +1,7 @@
1
1
  import { originalConsoleMethod } from "@posthog/browser-common/utils/console-original";
2
- const createLogger = (prefix, enabled)=>{
2
+ const createLogger = (prefix, state)=>{
3
3
  const write = (level, args)=>{
4
- if (!enabled) return;
4
+ if (!state.enabled) return;
5
5
  try {
6
6
  const console = globalThis.console;
7
7
  originalConsoleMethod(console?.[level])?.call(console, prefix, ...args);
@@ -13,7 +13,7 @@ const createLogger = (prefix, enabled)=>{
13
13
  warn: (...args)=>write('warn', args),
14
14
  error: (...args)=>write('error', args),
15
15
  critical: (...args)=>write('error', args),
16
- createLogger: (childPrefix)=>createLogger(`${prefix} ${childPrefix}`, enabled)
16
+ createLogger: (childPrefix)=>createLogger(`${prefix} ${childPrefix}`, state)
17
17
  };
18
18
  };
19
19
  export { createLogger };
@@ -1 +1,6 @@
1
1
  export declare const createId: () => string;
2
+ /**
3
+ * A UUIDv7 that encodes `timestamp`, for session and window IDs, which PostHog sessions and posthog-js require to be
4
+ * v7. A local primitive, because the shared generator imports `@posthog/core` and reads its own clock.
5
+ */
6
+ export declare const createTimeId: (timestamp: number) => string;
@@ -49,12 +49,20 @@ const createId = ()=>{
49
49
  return ('x' === character ? random : 3 & random | 8).toString(16);
50
50
  });
51
51
  };
52
+ const createTimeId = (timestamp)=>{
53
+ const time = Number.isFinite(timestamp) ? Math.min(Math.max(Math.floor(timestamp), 0), 0xffffffffffff) : 0;
54
+ const hex = time.toString(16).padStart(12, '0');
55
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7${createId().slice(15)}`;
56
+ };
52
57
  __webpack_require__.d(__webpack_exports__, {}, {
53
- createId: createId
58
+ createId: createId,
59
+ createTimeId: createTimeId
54
60
  });
55
61
  exports.createId = __webpack_exports__.createId;
62
+ exports.createTimeId = __webpack_exports__.createTimeId;
56
63
  for(var __rspack_i in __webpack_exports__)if (-1 === [
57
- "createId"
64
+ "createId",
65
+ "createTimeId"
58
66
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
59
67
  Object.defineProperty(exports, '__esModule', {
60
68
  value: true
@@ -20,4 +20,9 @@ const createId = ()=>{
20
20
  return ('x' === character ? random : 3 & random | 8).toString(16);
21
21
  });
22
22
  };
23
- export { createId };
23
+ const createTimeId = (timestamp)=>{
24
+ const time = Number.isFinite(timestamp) ? Math.min(Math.max(Math.floor(timestamp), 0), 0xffffffffffff) : 0;
25
+ const hex = time.toString(16).padStart(12, '0');
26
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7${createId().slice(15)}`;
27
+ };
28
+ export { createId, createTimeId };
@@ -27,7 +27,7 @@ var __webpack_require__ = {};
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
- const version = "0.5.0";
30
+ const version = "0.6.0";
31
31
  __webpack_require__.d(__webpack_exports__, {}, {
32
32
  version: version
33
33
  });
@@ -1,2 +1,2 @@
1
- const version = "0.5.0";
1
+ const version = "0.6.0";
2
2
  export { version };