@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,649 +0,0 @@
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
- Analytics: ()=>Analytics
32
- });
33
- const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
34
- const event_buffer_js_namespaceObject = require("./admission/event-buffer.js");
35
- const capture_summary_js_namespaceObject = require("./admission/capture-summary.js");
36
- const id_js_namespaceObject = require("../../primitives/id.js");
37
- const immutable_js_namespaceObject = require("../../primitives/immutable.js");
38
- const rate_limiter_js_namespaceObject = require("./admission/rate-limiter.js");
39
- const capture_properties_js_namespaceObject = require("./admission/capture-properties.js");
40
- const analytics_session_properties_js_namespaceObject = require("./properties/analytics-session-properties.js");
41
- const analytics_properties_js_namespaceObject = require("./properties/analytics-properties.js");
42
- const person_processing_js_namespaceObject = require("./properties/person-processing.js");
43
- const version_js_namespaceObject = require("../../primitives/version.js");
44
- const utf8_js_namespaceObject = require("../../primitives/utf8.js");
45
- const numberOption = (read, fallback, minimum, maximum)=>{
46
- try {
47
- const value = read();
48
- return Math.max(minimum, Math.min(maximum, Math.floor('number' == typeof value && Number.isFinite(value) ? value : fallback)));
49
- } catch {
50
- return fallback;
51
- }
52
- };
53
- const CLIENT_RATE_LIMIT_WARNING = '$$client_ingestion_warning';
54
- const isNonEmptyString = (value)=>'string' == typeof value && value.trim().length > 0;
55
- const isValidDistinctId = (value)=>isNonEmptyString(value) && ![
56
- '$posthog_cookieless',
57
- 'distinct_id',
58
- 'distinctid',
59
- 'undefined',
60
- 'null'
61
- ].includes(value.toLowerCase());
62
- const isValidGroupKey = (value)=>isNonEmptyString(value) || Number.isFinite(value);
63
- const eventTimestamp = (timestamp)=>{
64
- try {
65
- return (timestamp ?? new Date()).toISOString();
66
- } catch {
67
- return new Date().toISOString();
68
- }
69
- };
70
- class Analytics {
71
- constructor(options = {}, load, deliveryFactory){
72
- this.name = external_analytics_internal_js_namespaceObject.Analytics;
73
- this._disposed = false;
74
- this._isTearingDown = false;
75
- this._failures = 0;
76
- this._dynamicEventProperties = [];
77
- this._disposalWaiters = new Set();
78
- this._teardownCallbacks = new Set();
79
- this.bindCaptureHost = (host)=>{
80
- this._host = host;
81
- this._sessionProperties = new analytics_session_properties_js_namespaceObject.SessionRegisteredProperties(host.sessionKv);
82
- };
83
- this.setup = (value)=>{
84
- this._client = value.sharedClient;
85
- this._kv = value.kv;
86
- this._registeredProperties = new analytics_properties_js_namespaceObject.RegisteredProperties(value.kv);
87
- };
88
- this.initialize = (host)=>{
89
- this._deliveryHost = host;
90
- if (this._deliveryFactory) this._driver = this._deliveryFactory(this._buffer, this._client, host, this._scheduling, this._beforeTeardown);
91
- };
92
- this.start = ()=>this._eager ? this._ensureDelivery('eager') : Promise.resolve();
93
- this.onBeforeTeardown = (callback)=>{
94
- if (!this._disposed) this._teardownCallbacks.add(callback);
95
- const instance = this;
96
- return {
97
- get deliveryAvailable () {
98
- return !instance._disposed && !!instance._driver;
99
- },
100
- dispose: ()=>{
101
- this._teardownCallbacks.delete(callback);
102
- }
103
- };
104
- };
105
- this.flush = async (reason = 'flush')=>{
106
- if (this._disposed) return;
107
- if ('shutdown' === reason && this._loading) await this._loading;
108
- else if (this._buffer.hasPending()) await this._ensureDelivery(reason);
109
- await this._driver?.flush();
110
- };
111
- this.purge = ()=>this._buffer.purge();
112
- this.dispose = ()=>{
113
- this._disposed = true;
114
- this._registeredProperties = void 0;
115
- this._sessionProperties = void 0;
116
- this._dynamicEventProperties.splice(0);
117
- for (const release of this._disposalWaiters)release();
118
- this._disposalWaiters.clear();
119
- this._teardownCallbacks.clear();
120
- if (this._driver) return this._driver.dispose();
121
- this._buffer.dispose();
122
- };
123
- this._beforeTeardown = ()=>{
124
- this._isTearingDown = true;
125
- try {
126
- for (const callback of this._teardownCallbacks)try {
127
- callback();
128
- } catch (error) {
129
- try {
130
- this._deliveryHost.reportFailure(error);
131
- } catch {}
132
- }
133
- } finally{
134
- this._isTearingDown = false;
135
- }
136
- };
137
- this.onEvent = (listener)=>!this._disposed && this._host?.onEvent(listener) || {
138
- dispose () {}
139
- };
140
- this.captureInitialPageview = ()=>this._capture('$pageview');
141
- this.capture = (event, properties = null, options = {})=>{
142
- try {
143
- if ('unload' === options.delivery && !this._isTearingDown) return this._captureUnload(event, properties, options);
144
- } catch (error) {
145
- this._host?.logger.error('Unload capture failed', error);
146
- return true;
147
- }
148
- return this._capture(event, properties, options) || !this._rateLimiter.limited;
149
- };
150
- this.captureImmediate = async (event, properties = null, options = {})=>{
151
- try {
152
- const authority = this._host?.authority();
153
- const message = this._admitCapture(event, properties, options, false, true);
154
- if (!message) return capture_summary_js_namespaceObject.EMPTY_CAPTURE_SUMMARY;
155
- return await this._deliverImmediate(message, ()=>this._host?.authority() === authority);
156
- } catch (error) {
157
- return (0, capture_summary_js_namespaceObject.captureFailure)(error);
158
- }
159
- };
160
- this.createPersonProfile = ()=>{
161
- const host = this._host;
162
- if (this._disposed || !host?.canMutate()) return;
163
- host.state.prepare();
164
- if (this._hasPersonProcessing()) return;
165
- const properties = (0, person_processing_js_namespaceObject.snapshotPersonProperties)(host.state.distinctId, {}, {});
166
- if (properties) this._setPersonProperties(properties);
167
- };
168
- this.setPersonProperties = (set, setOnce)=>{
169
- const host = this._host;
170
- if (this._disposed || !host?.canMutate()) return;
171
- host.state.prepare();
172
- const properties = (0, person_processing_js_namespaceObject.snapshotPersonProperties)(host.state.distinctId, set, setOnce);
173
- if (!properties) return void host.logger.warn('Person properties must be JSON-serializable objects');
174
- if (!(Object.keys(properties.set).length || Object.keys(properties.setOnce).length)) return;
175
- this._setPersonProperties(properties);
176
- };
177
- this.unsetPersonProperties = (names)=>{
178
- const host = this._host;
179
- if (this._disposed || !host?.canMutate()) return;
180
- const properties = (0, person_processing_js_namespaceObject.personPropertyNames)(names);
181
- if (!properties.length || !this._requirePersonProcessing()) return;
182
- host.state.prepare();
183
- this._lastPersonProperties = void 0;
184
- host.publishChangeProperties({
185
- unset: properties
186
- });
187
- this._capture('$set', {
188
- $unset: properties
189
- }, {}, false, {
190
- signature: void 0
191
- });
192
- };
193
- this.setInternalOrTestUser = ()=>{
194
- this.setPersonProperties({
195
- $internal_or_test_user: true
196
- });
197
- };
198
- this.identify = async (distinctId, set, setOnce)=>{
199
- const host = this._host;
200
- if (!isValidDistinctId(distinctId) || this._disposed || !host?.canMutate()) return;
201
- host.state.prepare();
202
- if (!this._requirePersonProcessing()) return;
203
- const previousDistinctId = host.state.distinctId;
204
- const wasIdentified = host.state.isIdentified;
205
- const hasProperties = !!set || !!setOnce;
206
- if (distinctId !== previousDistinctId || !wasIdentified) host.state.identify(distinctId);
207
- const properties = (0, person_processing_js_namespaceObject.snapshotPersonProperties)(distinctId, set, setOnce);
208
- if (!properties) {
209
- host.logger.warn('Person properties must be JSON-serializable objects');
210
- if (distinctId !== previousDistinctId || !wasIdentified || hasProperties) host.publishIdentify({
211
- distinctId,
212
- previousDistinctId,
213
- wasIdentified,
214
- set,
215
- setOnce
216
- });
217
- return;
218
- }
219
- const options = this._identifyOptions(properties, !!set, !!setOnce);
220
- if (distinctId === previousDistinctId && wasIdentified) {
221
- if (hasProperties) this._setPersonProperties(properties, options, {
222
- distinctId,
223
- previousDistinctId,
224
- wasIdentified,
225
- set: options.set,
226
- setOnce: options.setOnce
227
- });
228
- return;
229
- }
230
- this._lastPersonProperties = void 0;
231
- if (hasProperties) host.publishChangeProperties({
232
- set: options.set,
233
- setOnce: options.setOnce
234
- });
235
- host.publishIdentify({
236
- distinctId,
237
- previousDistinctId,
238
- wasIdentified,
239
- set: options.set,
240
- setOnce: options.setOnce
241
- });
242
- this._captureIdentification(distinctId, previousDistinctId, wasIdentified, properties, options, hasProperties);
243
- };
244
- this.alias = (alias)=>{
245
- const host = this._host;
246
- if (!isValidDistinctId(alias) || this._disposed || !host?.canCapture() || !host.state.prepare()) return;
247
- if (!this._requirePersonProcessing()) return;
248
- this._capture('$create_alias', {
249
- alias
250
- });
251
- };
252
- this.group = async (type, key, properties)=>{
253
- if (!isNonEmptyString(type) || !isNonEmptyString(key) || this._disposed || !this._host?.canMutate() || 'never' === this._personProfiles) return;
254
- this._host.state.prepare();
255
- const changed = this._host.state.group(type, key);
256
- if (!changed && !properties) return;
257
- this._host.publishGroup({
258
- type,
259
- key,
260
- changed,
261
- properties
262
- });
263
- if (!this._hasPersonProcessing()) return;
264
- this.capture('$groupidentify', {
265
- $group_type: type,
266
- $group_key: key,
267
- ...properties ? {
268
- $group_set: properties
269
- } : {}
270
- });
271
- };
272
- this.groupIdentify = (type, key, properties = {}, options = {})=>{
273
- const host = this._host;
274
- if (this._disposed || !host?.canCapture()) return;
275
- if (!isNonEmptyString(type) || !isValidGroupKey(key)) return void host.logger.warn('Group identify requires a non-empty type and a string or finite numeric key');
276
- if (!host.state.prepare() || !this._requirePersonProcessing()) return;
277
- this.capture('$groupidentify', {
278
- $group_type: type,
279
- $group_key: key,
280
- $group_set: properties
281
- }, options);
282
- };
283
- this.resetGroups = ()=>{
284
- const host = this._host;
285
- if (this._disposed || !host?.canMutate()) return;
286
- host.state.prepare();
287
- host.state.resetGroups();
288
- host.publishGroupsReset();
289
- };
290
- this.reset = ()=>{
291
- if (this._disposed || !this._host?.canMutate()) return;
292
- this._host.state.prepare();
293
- this._host.state.reset();
294
- this._lastPersonProperties = void 0;
295
- this._sessionProperties?.clear();
296
- this._host.publishReset(void 0);
297
- };
298
- this.register = (properties)=>{
299
- const registration = this._prepareRegistration(properties);
300
- registration?.store.register(registration.properties);
301
- };
302
- this.registerOnce = (properties, defaultValue = 'None')=>{
303
- const registration = this._prepareRegistration(properties);
304
- registration?.store.registerOnce(registration.properties, defaultValue);
305
- };
306
- this.registerForSession = (properties)=>{
307
- const registration = this._prepareRegistration(properties);
308
- if (registration) this._sessionProperties?.register(registration.properties, this._host?.state.activeSessionId);
309
- };
310
- this.unregisterForSession = (property)=>{
311
- if (this._propertyStore()) this._sessionProperties?.unregister(property, this._host?.state.activeSessionId);
312
- };
313
- this.unregister = (property)=>{
314
- this._propertyStore()?.unregister(property);
315
- };
316
- this.getProperty = (property)=>this._propertyStore()?.get(property);
317
- this.registerDynamicEventProperties = (producer)=>{
318
- if (this._disposed || !this._host || this._host.isDisposed()) return {
319
- dispose () {}
320
- };
321
- this._dynamicEventProperties.push(producer);
322
- let active = true;
323
- return {
324
- dispose: ()=>{
325
- if (!active) return;
326
- active = false;
327
- const index = this._dynamicEventProperties.indexOf(producer);
328
- if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
329
- }
330
- };
331
- };
332
- this._load = load;
333
- this._deliveryFactory = deliveryFactory;
334
- let eager = false;
335
- if (load) try {
336
- eager = 'eager' === options.load;
337
- } catch {}
338
- this._eager = eager;
339
- this._scheduling = {
340
- flushAt: numberOption(()=>options.flushAt, 20, 1, external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BATCH_EVENTS),
341
- flushInterval: numberOption(()=>options.flushInterval, 3000, 0, Number.MAX_SAFE_INTEGER)
342
- };
343
- this._buffer = new event_buffer_js_namespaceObject.EventBuffer(1000, (total, count = 1, reason = 'overflow')=>this._deliveryHost.reportWarning(`Analytics queue dropped ${count} ${reason} event${1 === count ? '' : 's'} (${total} total)`), external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES, 3600000);
344
- this._personProfiles = (0, person_processing_js_namespaceObject.snapshotPersonProfileMode)(()=>options.personProfiles);
345
- this._rateLimiter = new rate_limiter_js_namespaceObject.ClientRateLimiter();
346
- Object.defineProperty(this, 'isRateLimited', {
347
- configurable: true,
348
- enumerable: true,
349
- get: ()=>this._rateLimiter.wouldLimit
350
- });
351
- }
352
- async _ensureDelivery(reason, retryAfterPending = true) {
353
- const load = this._load;
354
- if (!load || this._disposed || this._driver) return;
355
- if (this._loading) {
356
- if ('capture' === reason || !retryAfterPending) return this._loading;
357
- const previousFailures = this._failures;
358
- await this._loading;
359
- if (this._failures > previousFailures && this._buffer.hasPending()) await this._ensureDelivery(reason, false);
360
- return;
361
- }
362
- if ('capture' === reason && this._failures > 0) return;
363
- const loadDelivery = async ()=>{
364
- await Promise.resolve();
365
- try {
366
- const createDelivery = await load();
367
- if (this._disposed) return;
368
- this._driver = createDelivery(this._buffer, this._client, this._deliveryHost, this._scheduling, this._beforeTeardown);
369
- } catch (error) {
370
- if (!this._driver) {
371
- this._failures++;
372
- this._client.logger.error('Automatic analytics loading failed', error);
373
- }
374
- } finally{
375
- if (this._loading === pending) this._loading = void 0;
376
- }
377
- };
378
- const pending = loadDelivery();
379
- this._loading = pending;
380
- return pending;
381
- }
382
- async _deliverImmediate(message, canContinue) {
383
- let release;
384
- const disposal = new Promise((resolve)=>{
385
- release = resolve;
386
- this._disposalWaiters.add(resolve);
387
- });
388
- try {
389
- await Promise.race([
390
- this._ensureDelivery('immediate'),
391
- disposal
392
- ]);
393
- } finally{
394
- this._disposalWaiters.delete(release);
395
- }
396
- let deliverImmediate;
397
- try {
398
- deliverImmediate = this._driver?.deliverImmediate;
399
- } catch {
400
- deliverImmediate = void 0;
401
- }
402
- if (!canContinue()) return (0, capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery was cancelled'));
403
- if (!this._driver || 'function' != typeof deliverImmediate || this._disposed) return (0, capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery is unavailable'));
404
- return deliverImmediate.call(this._driver, [
405
- message
406
- ], canContinue);
407
- }
408
- _deliverUnload(message, canContinue) {
409
- const send = ()=>{
410
- if (this._disposed || !canContinue()) return;
411
- try {
412
- this._driver?.deliverUnload([
413
- message
414
- ]);
415
- } catch (error) {
416
- this._deliveryHost.reportFailure(error);
417
- }
418
- };
419
- if (this._driver) send();
420
- else this._ensureDelivery('immediate').then(send, (error)=>this._deliveryHost.reportFailure(error));
421
- }
422
- _captureUnload(event, properties, options) {
423
- const authority = this._host?.authority();
424
- const message = this._admitCapture(event, properties, options, false, true);
425
- if (message) this._deliverUnload(message, ()=>this._host?.authority() === authority);
426
- return !!message || !this._rateLimiter.limited;
427
- }
428
- _capture(event, properties = null, options = {}, skipRateLimit = false, personProperties) {
429
- return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false, personProperties);
430
- }
431
- _admitCapture(event, properties, options, skipRateLimit, immediate, personProperties) {
432
- if (!isNonEmptyString(event) || this._disposed || !this._host?.canCapture() || !this._host.state.prepare()) return;
433
- if (!this._acceptRateLimit(skipRateLimit)) return;
434
- const snapshot = this._snapshotProperties(properties, options);
435
- if (!snapshot) return;
436
- const candidate = this._prepareCapture(event, snapshot, this._host);
437
- return candidate ? this._commitCapture(candidate, immediate, this._host, personProperties) : void 0;
438
- }
439
- _acceptRateLimit(skipRateLimit) {
440
- if (skipRateLimit) return true;
441
- const rateLimit = this._rateLimiter.consume();
442
- if (rateLimit.allowed) return true;
443
- if (void 0 !== rateLimit.reportDropped) this._reportRateLimit(rateLimit.reportDropped);
444
- return false;
445
- }
446
- _reportRateLimit(dropped) {
447
- const warning = `${dropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
448
- this._host?.logger.warn(`PostHog client rate limited: ${warning}`);
449
- if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
450
- $$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
451
- }, {}, true)) this._rateLimiter.reported();
452
- }
453
- _dynamicProperties() {
454
- const properties = {};
455
- for (const producer of this._dynamicEventProperties.slice())try {
456
- Object.assign(properties, producer());
457
- } catch (error) {
458
- this._host?.logger.error('An event property producer failed', error);
459
- }
460
- return properties;
461
- }
462
- _snapshotProperties(properties, options) {
463
- const dynamic = this._dynamicProperties();
464
- try {
465
- return (0, capture_properties_js_namespaceObject.snapshotCaptureProperties)(this._registeredProperties?.values(), dynamic, properties, options);
466
- } catch (error) {
467
- this._host?.logger.error('Event properties are not JSON-serializable', error);
468
- return;
469
- }
470
- }
471
- _prepareCapture(event, snapshot, host) {
472
- const processPersonProfile = this._hasPersonProcessing();
473
- if (processPersonProfile) this._requirePersonProcessing();
474
- const preparedSession = host.state.prepareSessionForEvent();
475
- const session = preparedSession.context;
476
- const distinctId = host.state.distinctId;
477
- const deviceId = host.state.deviceId;
478
- const groups = host.state.groups;
479
- const metadata = {
480
- token: host.projectToken,
481
- distinct_id: distinctId,
482
- $device_id: deviceId,
483
- $groups: groups,
484
- $session_id: session.sessionId,
485
- $window_id: session.windowId,
486
- $lib: 'web',
487
- $lib_version: version_js_namespaceObject.version,
488
- $process_person_profile: processPersonProfile
489
- };
490
- const message = {
491
- uuid: snapshot.uuid ?? (0, id_js_namespaceObject.createId)(),
492
- event,
493
- distinct_id: distinctId,
494
- properties: {
495
- ...snapshot.message,
496
- ...metadata
497
- },
498
- timestamp: eventTimestamp(snapshot.timestamp)
499
- };
500
- const bytes = this._enrichAndMeasure(message, snapshot, metadata, session.sessionId);
501
- if (void 0 === bytes) return;
502
- return {
503
- message,
504
- bytes,
505
- preparedSession,
506
- observedProperties: {
507
- ...snapshot.observed,
508
- ...metadata,
509
- $groups: {
510
- ...groups
511
- }
512
- }
513
- };
514
- }
515
- _enrichAndMeasure(message, snapshot, metadata, sessionId) {
516
- try {
517
- let bytes = (0, utf8_js_namespaceObject.utf8Bytes)(JSON.stringify(message));
518
- if (!this._fitsUnavoidableProperties(message, snapshot, metadata, bytes)) return;
519
- const changed = (0, capture_properties_js_namespaceObject.applySessionProperties)(snapshot, this._sessionProperties?.values(sessionId) ?? {});
520
- message.properties = {
521
- ...snapshot.message,
522
- ...metadata
523
- };
524
- if (changed) bytes = (0, utf8_js_namespaceObject.utf8Bytes)(JSON.stringify(message));
525
- return bytes;
526
- } catch (error) {
527
- this._host?.logger.error('The finalized event could not be measured', error);
528
- return;
529
- }
530
- }
531
- _fitsUnavoidableProperties(message, snapshot, metadata, bytes) {
532
- if (bytes <= external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) return true;
533
- const minimum = (0, utf8_js_namespaceObject.utf8Bytes)(JSON.stringify({
534
- ...message,
535
- properties: (0, capture_properties_js_namespaceObject.unavoidableProperties)(snapshot, metadata)
536
- }));
537
- if (minimum <= external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) return true;
538
- this._warnOversized(message.event, bytes);
539
- return false;
540
- }
541
- _warnOversized(event, bytes) {
542
- this._host?.logger.warn(`Event "${event}" (${bytes} bytes) exceeds the local analytics limit and was dropped`);
543
- }
544
- _enqueueCapture(candidate, immediate) {
545
- const { message, bytes } = candidate;
546
- if (immediate ? bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES : !this._buffer.enqueue(message, bytes)) {
547
- if (bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) this._warnOversized(message.event, bytes);
548
- return false;
549
- }
550
- return true;
551
- }
552
- _commitCapture(candidate, immediate, host, personProperties) {
553
- if (!this._enqueueCapture(candidate, immediate)) return;
554
- if (!host.state.sessionAdmitted(candidate.preparedSession)) {
555
- if (!immediate) this._buffer.discardQueued(candidate.message);
556
- return;
557
- }
558
- if (personProperties) this._lastPersonProperties = personProperties.signature;
559
- else if (Object.hasOwn(candidate.message.properties, '$set') || Object.hasOwn(candidate.message.properties, '$set_once') || Object.hasOwn(candidate.message.properties, '$unset')) this._lastPersonProperties = void 0;
560
- this._sessionProperties?.admitted(candidate.preparedSession.context.sessionId);
561
- this._publishCapture(candidate, host);
562
- if (!immediate) this._ensureDelivery('capture');
563
- return candidate.message;
564
- }
565
- _publishCapture(candidate, host) {
566
- const { preparedSession, message, observedProperties } = candidate;
567
- const session = preparedSession.context;
568
- if (preparedSession.reason) host.publishNewSession({
569
- ...session,
570
- reason: preparedSession.reason
571
- });
572
- host.publishEvent((0, immutable_js_namespaceObject.deepFreeze)({
573
- event: message.event,
574
- properties: observedProperties
575
- }));
576
- }
577
- _hasPersonProcessing() {
578
- const host = this._host;
579
- if (!host) return false;
580
- const enabled = this._kv?.get('personProcessingEnabled') === true;
581
- return (0, person_processing_js_namespaceObject.shouldProcessPerson)(this._personProfiles, host.state.isIdentified, Object.keys(host.state.groups).length > 0, enabled);
582
- }
583
- _requirePersonProcessing() {
584
- if ('never' === this._personProfiles) {
585
- this._host?.logger.warn('Person processing is disabled by analytics configuration');
586
- return false;
587
- }
588
- if (this._kv?.get('personProcessingEnabled') !== true) this._kv?.set('personProcessingEnabled', true);
589
- return true;
590
- }
591
- _setPersonProperties(properties, options = {
592
- set: properties.set,
593
- setOnce: properties.setOnce
594
- }, identification) {
595
- const host = this._host;
596
- if (!host || !this._requirePersonProcessing() || this._lastPersonProperties === properties.signature) return;
597
- this._lastPersonProperties = void 0;
598
- host.publishChangeProperties({
599
- set: options.set,
600
- setOnce: options.setOnce
601
- });
602
- if (identification) host.publishIdentify(identification);
603
- this._capture('$set', null, options, false, {
604
- signature: properties.signature
605
- });
606
- }
607
- _identifyOptions(properties, hasSet, hasSetOnce) {
608
- const options = {};
609
- if (hasSet) options.set = properties.set;
610
- if (hasSetOnce) options.setOnce = properties.setOnce;
611
- return options;
612
- }
613
- _captureIdentification(distinctId, previousDistinctId, wasIdentified, properties, options, hasProperties) {
614
- const personProperties = {
615
- signature: properties.signature
616
- };
617
- if (!wasIdentified && distinctId !== previousDistinctId) return this._capture('$identify', {
618
- $anon_distinct_id: previousDistinctId
619
- }, options, false, personProperties);
620
- if (distinctId === previousDistinctId) return this._capture('$set', null, {
621
- set: properties.set,
622
- setOnce: properties.setOnce
623
- }, false, personProperties);
624
- return hasProperties ? this._capture('$set', null, options, false, personProperties) : false;
625
- }
626
- _propertyStore() {
627
- const host = this._host;
628
- if (this._disposed || !host?.canMutate() || !host.state.prepare()) return;
629
- return this._registeredProperties;
630
- }
631
- _prepareRegistration(properties) {
632
- const store = this._propertyStore();
633
- if (!store) return;
634
- const snapshot = (0, analytics_properties_js_namespaceObject.snapshotRegisteredProperties)(properties);
635
- if (this._propertyStore() !== store) return;
636
- if (!snapshot) return void this._host?.logger.warn('Super properties must serialize to an object');
637
- return {
638
- store,
639
- properties: snapshot
640
- };
641
- }
642
- }
643
- exports.Analytics = __webpack_exports__.Analytics;
644
- for(var __rspack_i in __webpack_exports__)if (-1 === [
645
- "Analytics"
646
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
647
- Object.defineProperty(exports, '__esModule', {
648
- value: true
649
- });