posthog-js 1.76.0 → 1.77.1

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 (129) hide show
  1. package/dist/array.full.js +2 -2
  2. package/dist/array.full.js.map +1 -1
  3. package/dist/array.js +2 -2
  4. package/dist/array.js.map +1 -1
  5. package/dist/es.js +2 -2
  6. package/dist/es.js.map +1 -1
  7. package/dist/module.d.ts +38 -6
  8. package/dist/module.js +2 -2
  9. package/dist/module.js.map +1 -1
  10. package/lib/package.json +8 -6
  11. package/lib/src/autocapture-utils.d.ts +15 -0
  12. package/lib/src/autocapture-utils.js +303 -0
  13. package/lib/src/autocapture-utils.js.map +1 -0
  14. package/lib/src/autocapture.d.ts +27 -0
  15. package/lib/src/autocapture.js +290 -0
  16. package/lib/src/autocapture.js.map +1 -0
  17. package/lib/src/base-request-queue.d.ts +12 -0
  18. package/lib/src/base-request-queue.js +33 -0
  19. package/lib/src/base-request-queue.js.map +1 -0
  20. package/lib/src/compression.d.ts +3 -0
  21. package/lib/src/compression.js +35 -0
  22. package/lib/src/compression.js.map +1 -0
  23. package/lib/src/config.d.ts +5 -0
  24. package/lib/src/config.js +9 -0
  25. package/lib/src/config.js.map +1 -0
  26. package/lib/src/constants.d.ts +19 -0
  27. package/lib/src/constants.js +41 -0
  28. package/lib/src/constants.js.map +1 -0
  29. package/lib/src/decide.d.ts +8 -0
  30. package/lib/src/decide.js +118 -0
  31. package/lib/src/decide.js.map +1 -0
  32. package/lib/src/extensions/cloud.d.ts +1 -0
  33. package/lib/src/extensions/cloud.js +2 -0
  34. package/lib/src/extensions/cloud.js.map +1 -0
  35. package/lib/src/extensions/exceptions/error-conversion.d.ts +26 -0
  36. package/lib/src/extensions/exceptions/error-conversion.js +204 -0
  37. package/lib/src/extensions/exceptions/error-conversion.js.map +1 -0
  38. package/lib/src/extensions/exceptions/exception-autocapture.d.ts +24 -0
  39. package/lib/src/extensions/exceptions/exception-autocapture.js +164 -0
  40. package/lib/src/extensions/exceptions/exception-autocapture.js.map +1 -0
  41. package/lib/src/extensions/exceptions/stack-trace.d.ts +31 -0
  42. package/lib/src/extensions/exceptions/stack-trace.js +259 -0
  43. package/lib/src/extensions/exceptions/stack-trace.js.map +1 -0
  44. package/lib/src/extensions/exceptions/type-checking.d.ts +10 -0
  45. package/lib/src/extensions/exceptions/type-checking.js +43 -0
  46. package/lib/src/extensions/exceptions/type-checking.js.map +1 -0
  47. package/lib/src/extensions/rageclick.d.ts +10 -0
  48. package/lib/src/extensions/rageclick.js +33 -0
  49. package/lib/src/extensions/rageclick.js.map +1 -0
  50. package/lib/src/extensions/segment-integration.d.ts +44 -0
  51. package/lib/src/extensions/segment-integration.js +34 -0
  52. package/lib/src/extensions/segment-integration.js.map +1 -0
  53. package/lib/src/extensions/sentry-integration.d.ts +30 -0
  54. package/lib/src/extensions/sentry-integration.js +63 -0
  55. package/lib/src/extensions/sentry-integration.js.map +1 -0
  56. package/lib/src/extensions/sessionrecording-utils.d.ts +67 -0
  57. package/lib/src/extensions/sessionrecording-utils.js +192 -0
  58. package/lib/src/extensions/sessionrecording-utils.js.map +1 -0
  59. package/lib/src/extensions/sessionrecording.d.ts +45 -0
  60. package/lib/src/extensions/sessionrecording.js +430 -0
  61. package/lib/src/extensions/sessionrecording.js.map +1 -0
  62. package/lib/src/extensions/toolbar.d.ts +18 -0
  63. package/lib/src/extensions/toolbar.js +151 -0
  64. package/lib/src/extensions/toolbar.js.map +1 -0
  65. package/lib/src/extensions/web-performance.d.ts +20 -0
  66. package/lib/src/extensions/web-performance.js +245 -0
  67. package/lib/src/extensions/web-performance.js.map +1 -0
  68. package/lib/src/gdpr-utils.d.ts +80 -0
  69. package/lib/src/gdpr-utils.js +236 -0
  70. package/lib/src/gdpr-utils.js.map +1 -0
  71. package/lib/src/loader-globals-full.d.ts +1 -0
  72. package/lib/src/loader-globals-full.js +5 -0
  73. package/lib/src/loader-globals-full.js.map +1 -0
  74. package/lib/src/loader-globals.d.ts +1 -0
  75. package/lib/src/loader-globals.js +3 -0
  76. package/lib/src/loader-globals.js.map +1 -0
  77. package/lib/src/loader-module.d.ts +4 -0
  78. package/lib/src/loader-module.js +6 -0
  79. package/lib/src/loader-module.js.map +1 -0
  80. package/lib/src/loader-recorder-v2.d.ts +2 -0
  81. package/lib/src/loader-recorder-v2.js +15 -0
  82. package/lib/src/loader-recorder-v2.js.map +1 -0
  83. package/lib/src/loader-recorder.d.ts +2 -0
  84. package/lib/src/loader-recorder.js +15 -0
  85. package/lib/src/loader-recorder.js.map +1 -0
  86. package/lib/src/page-view.d.ts +38 -0
  87. package/lib/src/page-view.js +127 -0
  88. package/lib/src/page-view.js.map +1 -0
  89. package/lib/src/posthog-core.d.ts +701 -0
  90. package/lib/src/posthog-core.js +1916 -0
  91. package/lib/src/posthog-core.js.map +1 -0
  92. package/lib/src/posthog-featureflags.d.ts +70 -0
  93. package/lib/src/posthog-featureflags.js +438 -0
  94. package/lib/src/posthog-featureflags.js.map +1 -0
  95. package/lib/src/posthog-persistence.d.ts +57 -0
  96. package/lib/src/posthog-persistence.js +256 -0
  97. package/lib/src/posthog-persistence.js.map +1 -0
  98. package/lib/src/posthog-surveys.d.ts +57 -0
  99. package/lib/src/posthog-surveys.js +76 -0
  100. package/lib/src/posthog-surveys.js.map +1 -0
  101. package/lib/src/rate-limiter.d.ts +5 -0
  102. package/lib/src/rate-limiter.js +66 -0
  103. package/lib/src/rate-limiter.js.map +1 -0
  104. package/lib/src/request-queue.d.ts +10 -0
  105. package/lib/src/request-queue.js +146 -0
  106. package/lib/src/request-queue.js.map +1 -0
  107. package/lib/src/retry-queue.d.ts +28 -0
  108. package/lib/src/retry-queue.js +198 -0
  109. package/lib/src/retry-queue.js.map +1 -0
  110. package/lib/src/send-request.d.ts +6 -0
  111. package/lib/src/send-request.js +125 -0
  112. package/lib/src/send-request.js.map +1 -0
  113. package/lib/src/sessionid.d.ts +28 -0
  114. package/lib/src/sessionid.js +205 -0
  115. package/lib/src/sessionid.js.map +1 -0
  116. package/lib/src/storage.d.ts +7 -0
  117. package/lib/src/storage.js +291 -0
  118. package/lib/src/storage.js.map +1 -0
  119. package/lib/src/types.d.ts +294 -0
  120. package/lib/src/types.js +6 -0
  121. package/lib/src/types.js.map +1 -0
  122. package/lib/src/utils.d.ts +89 -0
  123. package/lib/src/utils.js +868 -0
  124. package/lib/src/utils.js.map +1 -0
  125. package/lib/src/uuidv7.d.ts +42 -0
  126. package/lib/src/uuidv7.js +228 -0
  127. package/lib/src/uuidv7.js.map +1 -0
  128. package/package.json +8 -6
  129. package/CHANGELOG.md +0 -1145
@@ -0,0 +1,1916 @@
1
+ var __assign = (this && this.__assign) || function () {
2
+ __assign = Object.assign || function(t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
+ t[p] = s[p];
7
+ }
8
+ return t;
9
+ };
10
+ return __assign.apply(this, arguments);
11
+ };
12
+ var __read = (this && this.__read) || function (o, n) {
13
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
14
+ if (!m) return o;
15
+ var i = m.call(o), r, ar = [], e;
16
+ try {
17
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
18
+ }
19
+ catch (error) { e = { error: error }; }
20
+ finally {
21
+ try {
22
+ if (r && !r.done && (m = i["return"])) m.call(i);
23
+ }
24
+ finally { if (e) throw e.error; }
25
+ }
26
+ return ar;
27
+ };
28
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
29
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
30
+ if (ar || !(i in from)) {
31
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
32
+ ar[i] = from[i];
33
+ }
34
+ }
35
+ return to.concat(ar || Array.prototype.slice.call(from));
36
+ };
37
+ import Config from './config';
38
+ import { _copyAndTruncateStrings, _each, _eachArray, _extend, _info, _isArray, _isBlockedUA, _isObject, _isUndefined, _register_event, _safewrap_class, document, logger, userAgent, window, } from './utils';
39
+ import { autocapture } from './autocapture';
40
+ import { PostHogFeatureFlags } from './posthog-featureflags';
41
+ import { PostHogPersistence } from './posthog-persistence';
42
+ import { ALIAS_ID_KEY, FLAG_CALL_REPORTED, PEOPLE_DISTINCT_ID_KEY } from './constants';
43
+ import { SessionRecording } from './extensions/sessionrecording';
44
+ import { WebPerformanceObserver } from './extensions/web-performance';
45
+ import { Decide } from './decide';
46
+ import { Toolbar } from './extensions/toolbar';
47
+ import { clearOptInOut, hasOptedIn, hasOptedOut, optIn, optOut, userOptedOut } from './gdpr-utils';
48
+ import { cookieStore, localStore } from './storage';
49
+ import { RequestQueue } from './request-queue';
50
+ import { compressData, decideCompression } from './compression';
51
+ import { addParamsToURL, encodePostData, xhr } from './send-request';
52
+ import { RetryQueue } from './retry-queue';
53
+ import { SessionIdManager } from './sessionid';
54
+ import { SentryIntegration } from './extensions/sentry-integration';
55
+ import { createSegmentIntegration } from './extensions/segment-integration';
56
+ import { PageViewManager } from './page-view';
57
+ import { ExceptionObserver } from './extensions/exceptions/exception-autocapture';
58
+ import { PostHogSurveys } from './posthog-surveys';
59
+ import { RateLimiter } from './rate-limiter';
60
+ import { uuidv7 } from './uuidv7';
61
+ /*
62
+ SIMPLE STYLE GUIDE:
63
+
64
+ this.x === public function
65
+ this._x === internal - only use within this file
66
+ this.__x === private - only use within the class
67
+
68
+ Globals should be all caps
69
+ */
70
+ var InitType;
71
+ (function (InitType) {
72
+ InitType[InitType["INIT_MODULE"] = 0] = "INIT_MODULE";
73
+ InitType[InitType["INIT_SNIPPET"] = 1] = "INIT_SNIPPET";
74
+ })(InitType || (InitType = {}));
75
+ var init_type;
76
+ // TODO: the type of this is very loose. Sometimes it's also PostHogLib itself
77
+ var posthog_master;
78
+ // some globals for comparisons
79
+ var __NOOP = function () { };
80
+ var __NOOPTIONS = {};
81
+ var PRIMARY_INSTANCE_NAME = 'posthog';
82
+ /*
83
+ * Dynamic... constants? Is that an oxymoron?
84
+ */
85
+ // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
86
+ // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
87
+ var USE_XHR = window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest();
88
+ // IE<10 does not support cross-origin XHR's but script tags
89
+ // with defer won't block window.onload; ENQUEUE_REQUESTS
90
+ // should only be true for Opera<12
91
+ var ENQUEUE_REQUESTS = !USE_XHR && userAgent.indexOf('MSIE') === -1 && userAgent.indexOf('Mozilla') === -1;
92
+ var defaultConfig = function () {
93
+ var _a, _b, _c;
94
+ return ({
95
+ api_host: 'https://app.posthog.com',
96
+ api_method: 'POST',
97
+ api_transport: 'XHR',
98
+ ui_host: null,
99
+ token: '',
100
+ autocapture: true,
101
+ rageclick: true,
102
+ cross_subdomain_cookie: ((_b = (_a = document === null || document === void 0 ? void 0 : document.location) === null || _a === void 0 ? void 0 : _a.hostname) === null || _b === void 0 ? void 0 : _b.indexOf('herokuapp.com')) === -1,
103
+ persistence: 'cookie',
104
+ persistence_name: '',
105
+ cookie_name: '',
106
+ loaded: __NOOP,
107
+ store_google: true,
108
+ custom_campaign_params: [],
109
+ save_referrer: true,
110
+ test: false,
111
+ verbose: false,
112
+ capture_pageview: true,
113
+ capture_pageleave: true,
114
+ debug: false,
115
+ cookie_expiration: 365,
116
+ upgrade: false,
117
+ disable_session_recording: false,
118
+ disable_persistence: false,
119
+ disable_cookie: false,
120
+ enable_recording_console_log: undefined,
121
+ secure_cookie: ((_c = window === null || window === void 0 ? void 0 : window.location) === null || _c === void 0 ? void 0 : _c.protocol) === 'https:',
122
+ ip: true,
123
+ opt_out_capturing_by_default: false,
124
+ opt_out_persistence_by_default: false,
125
+ opt_out_capturing_persistence_type: 'localStorage',
126
+ opt_out_capturing_cookie_prefix: null,
127
+ opt_in_site_apps: false,
128
+ property_blacklist: [],
129
+ respect_dnt: false,
130
+ sanitize_properties: null,
131
+ xhr_headers: {},
132
+ inapp_protocol: '//',
133
+ inapp_link_new_window: false,
134
+ request_batching: true,
135
+ properties_string_max_length: 65535,
136
+ session_recording: {},
137
+ mask_all_element_attributes: false,
138
+ mask_all_text: false,
139
+ advanced_disable_decide: false,
140
+ advanced_disable_feature_flags: false,
141
+ advanced_disable_feature_flags_on_first_load: false,
142
+ advanced_disable_toolbar_metrics: false,
143
+ on_xhr_error: function (req) {
144
+ var error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
145
+ console.error(error);
146
+ },
147
+ get_device_id: function (uuid) { return uuid; },
148
+ // Used for internal testing
149
+ _onCapture: __NOOP,
150
+ capture_performance: undefined,
151
+ name: 'posthog',
152
+ callback_fn: 'posthog._jsc',
153
+ bootstrap: {},
154
+ disable_compression: false,
155
+ session_idle_timeout_seconds: 30 * 60, // 30 minutes
156
+ });
157
+ };
158
+ /**
159
+ * create_phlib(token:string, config:object, name:string)
160
+ *
161
+ * This function is used by the init method of PostHogLib objects
162
+ * as well as the main initializer at the end of the JSLib (that
163
+ * initializes document.posthog as well as any additional instances
164
+ * declared before this file has loaded).
165
+ */
166
+ var create_phlib = function (token, config, name, createComplete) {
167
+ var instance;
168
+ var target = name === PRIMARY_INSTANCE_NAME || !posthog_master ? posthog_master : name ? posthog_master[name] : undefined;
169
+ var callbacksHandled = {
170
+ initComplete: false,
171
+ syncCode: false,
172
+ };
173
+ var handleCallback = function (callbackName) { return function (instance) {
174
+ if (!callbacksHandled[callbackName]) {
175
+ callbacksHandled[callbackName] = true;
176
+ if (callbacksHandled.initComplete && callbacksHandled.syncCode) {
177
+ createComplete === null || createComplete === void 0 ? void 0 : createComplete(instance);
178
+ }
179
+ }
180
+ }; };
181
+ if (target && init_type === InitType.INIT_MODULE) {
182
+ instance = target;
183
+ }
184
+ else {
185
+ if (target && !_isArray(target)) {
186
+ console.error('You have already initialized ' + name);
187
+ // TODO: throw something instead?
188
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
189
+ // @ts-ignore
190
+ return;
191
+ }
192
+ instance = new PostHog();
193
+ }
194
+ instance._init(token, config, name, handleCallback('initComplete'));
195
+ instance.toolbar.maybeLoadToolbar();
196
+ instance.sessionRecording = new SessionRecording(instance);
197
+ instance.sessionRecording.startRecordingIfEnabled();
198
+ instance.webPerformance = new WebPerformanceObserver(instance);
199
+ instance.webPerformance.startObservingIfEnabled();
200
+ if (instance.get_config('__preview_measure_pageview_stats')) {
201
+ instance.pageViewManager.startMeasuringScrollPosition();
202
+ }
203
+ instance.exceptionAutocapture = new ExceptionObserver(instance);
204
+ instance.__autocapture = instance.get_config('autocapture');
205
+ autocapture._setIsAutocaptureEnabled(instance);
206
+ if (autocapture._isAutocaptureEnabled) {
207
+ instance.__autocapture = instance.get_config('autocapture');
208
+ var num_buckets = 100;
209
+ var num_enabled_buckets = 100;
210
+ if (!autocapture.enabledForProject(instance.get_config('token'), num_buckets, num_enabled_buckets)) {
211
+ instance.__autocapture = false;
212
+ logger.log('Not in active bucket: disabling Automatic Event Collection.');
213
+ }
214
+ else if (!autocapture.isBrowserSupported()) {
215
+ instance.__autocapture = false;
216
+ logger.log('Disabling Automatic Event Collection because this browser is not supported');
217
+ }
218
+ else {
219
+ autocapture.init(instance);
220
+ }
221
+ }
222
+ // if any instance on the page has debug = true, we set the
223
+ // global debug to be true
224
+ Config.DEBUG = Config.DEBUG || instance.get_config('debug');
225
+ // if target is not defined, we called init after the lib already
226
+ // loaded, so there won't be an array of things to execute
227
+ if (typeof target !== 'undefined' && _isArray(target)) {
228
+ // Crunch through the people queue first - we queue this data up &
229
+ // flush on identify, so it's better to do all these operations first
230
+ instance._execute_array.call(instance.people, target.people);
231
+ instance._execute_array(target);
232
+ }
233
+ handleCallback('syncCode')(instance);
234
+ return instance;
235
+ };
236
+ /**
237
+ * PostHog Library Object
238
+ * @constructor
239
+ */
240
+ var PostHog = /** @class */ (function () {
241
+ function PostHog() {
242
+ var _this = this;
243
+ this.config = defaultConfig();
244
+ this.compression = {};
245
+ this.decideEndpointWasHit = false;
246
+ this.SentryIntegration = SentryIntegration;
247
+ this.segmentIntegration = function () { return createSegmentIntegration(_this); };
248
+ this.__captureHooks = [];
249
+ this.__request_queue = [];
250
+ this.__loaded = false;
251
+ this.__loaded_recorder_version = undefined;
252
+ this.__autocapture = undefined;
253
+ this._jsc = function () { };
254
+ this.featureFlags = new PostHogFeatureFlags(this);
255
+ this.toolbar = new Toolbar(this);
256
+ this.pageViewManager = new PageViewManager();
257
+ this.surveys = new PostHogSurveys(this);
258
+ this.rateLimiter = new RateLimiter();
259
+ // these are created in _init() after we have the config
260
+ this._requestQueue = undefined;
261
+ this._retryQueue = undefined;
262
+ this.persistence = undefined;
263
+ this.sessionPersistence = undefined;
264
+ this.sessionManager = undefined;
265
+ // NOTE: See the property definition for deprecation notice
266
+ this.people = {
267
+ set: function (prop, to, callback) {
268
+ var _a;
269
+ var setProps = typeof prop === 'string' ? (_a = {}, _a[prop] = to, _a) : prop;
270
+ _this.setPersonProperties(setProps);
271
+ callback === null || callback === void 0 ? void 0 : callback({});
272
+ },
273
+ set_once: function (prop, to, callback) {
274
+ var _a;
275
+ var setProps = typeof prop === 'string' ? (_a = {}, _a[prop] = to, _a) : prop;
276
+ _this.setPersonProperties(undefined, setProps);
277
+ callback === null || callback === void 0 ? void 0 : callback({});
278
+ },
279
+ };
280
+ }
281
+ // Initialization methods
282
+ /**
283
+ * This function initializes a new instance of the PostHog capturing object.
284
+ * All new instances are added to the main posthog object as sub properties (such as
285
+ * posthog.library_name) and also returned by this function. To define a
286
+ * second instance on the page, you would call:
287
+ *
288
+ * posthog.init('new token', { your: 'config' }, 'library_name');
289
+ *
290
+ * and use it like so:
291
+ *
292
+ * posthog.library_name.capture(...);
293
+ *
294
+ * @param {String} token Your PostHog API token
295
+ * @param {Object} [config] A dictionary of config options to override. <a href="https://github.com/posthog/posthog-js/blob/6e0e873/src/posthog-core.js#L57-L91">See a list of default config options</a>.
296
+ * @param {String} [name] The name for the new posthog instance that you want created
297
+ */
298
+ PostHog.prototype.init = function (token, config, name) {
299
+ if (_isUndefined(name)) {
300
+ console.error('You must name your new library: init(token, config, name)');
301
+ return;
302
+ }
303
+ if (name === PRIMARY_INSTANCE_NAME) {
304
+ console.error('You must initialize the main posthog object right after you include the PostHog js snippet');
305
+ return;
306
+ }
307
+ var instance = create_phlib(token, config, name, function (instance) {
308
+ posthog_master[name] = instance;
309
+ instance._loaded();
310
+ });
311
+ posthog_master[name] = instance;
312
+ return instance;
313
+ };
314
+ // posthog._init(token:string, config:object, name:string)
315
+ //
316
+ // This function sets up the current instance of the posthog
317
+ // library. The difference between this method and the init(...)
318
+ // method is this one initializes the actual instance, whereas the
319
+ // init(...) method sets up a new library and calls _init on it.
320
+ //
321
+ // Note that there are operations that can be asynchronous, so we
322
+ // accept a callback that is called when all the asynchronous work
323
+ // is done. Note that we do not use promises because we want to be
324
+ // IE11 compatible. We could use polyfills, which would make the
325
+ // code a bit cleaner, but will add some overhead.
326
+ //
327
+ PostHog.prototype._init = function (token, config, name, initComplete) {
328
+ var _this = this;
329
+ var _a, _b, _c, _d, _e, _f, _g;
330
+ if (config === void 0) { config = {}; }
331
+ this.__loaded = true;
332
+ this.config = {}; // will be set right below
333
+ this._triggered_notifs = [];
334
+ // To avoid using Promises and their helper functions, we instead keep
335
+ // track of which callbacks have been called, and then call initComplete
336
+ // when all of them have been called. To add additional async code, add
337
+ // to `callbacksHandled` and pass updateInitComplete as a callback to
338
+ // the async code.
339
+ var callbacksHandled = { segmentRegister: false, syncCode: false };
340
+ var updateInitComplete = function (callbackName) { return function () {
341
+ // Update the register of callbacks that have been called, and if
342
+ // they have all been called, then we are ready to call
343
+ // initComplete.
344
+ if (!callbacksHandled[callbackName]) {
345
+ callbacksHandled[callbackName] = true;
346
+ if (callbacksHandled.segmentRegister && callbacksHandled.syncCode) {
347
+ initComplete === null || initComplete === void 0 ? void 0 : initComplete(_this);
348
+ }
349
+ }
350
+ }; };
351
+ this.set_config(_extend({}, defaultConfig(), config, {
352
+ name: name,
353
+ token: token,
354
+ callback_fn: (name === PRIMARY_INSTANCE_NAME ? name : PRIMARY_INSTANCE_NAME + '.' + name) + '._jsc',
355
+ }));
356
+ this._jsc = function () { };
357
+ // Check if recorder.js is already loaded
358
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
359
+ // @ts-ignore
360
+ if (((_a = window === null || window === void 0 ? void 0 : window.rrweb) === null || _a === void 0 ? void 0 : _a.record) || (window === null || window === void 0 ? void 0 : window.rrwebRecord)) {
361
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
362
+ // @ts-ignore
363
+ this.__loaded_recorder_version = (_b = window === null || window === void 0 ? void 0 : window.rrweb) === null || _b === void 0 ? void 0 : _b.version;
364
+ }
365
+ this.persistence = new PostHogPersistence(this.config);
366
+ this._requestQueue = new RequestQueue(this._handle_queued_event.bind(this));
367
+ this._retryQueue = new RetryQueue(this.get_config('on_xhr_error'), this.rateLimiter);
368
+ this.__captureHooks = [];
369
+ this.__request_queue = [];
370
+ this.sessionManager = new SessionIdManager(this.config, this.persistence);
371
+ this.sessionPersistence =
372
+ this.config.persistence === 'sessionStorage'
373
+ ? this.persistence
374
+ : new PostHogPersistence(__assign(__assign({}, this.config), { persistence: 'sessionStorage' }));
375
+ this._gdpr_init();
376
+ if (config.segment) {
377
+ // Use segments anonymousId instead
378
+ this.config.get_device_id = function () { return config.segment.user().anonymousId(); };
379
+ // If a segment user ID exists, set it as the distinct_id
380
+ if (config.segment.user().id()) {
381
+ this.register({
382
+ distinct_id: config.segment.user().id(),
383
+ });
384
+ this.persistence.set_user_state('identified');
385
+ }
386
+ config.segment.register(this.segmentIntegration()).then(updateInitComplete('segmentRegister'));
387
+ }
388
+ else {
389
+ updateInitComplete('segmentRegister')();
390
+ }
391
+ if (((_c = config.bootstrap) === null || _c === void 0 ? void 0 : _c.distinctID) !== undefined) {
392
+ var uuid = this.get_config('get_device_id')(uuidv7());
393
+ var deviceID = ((_d = config.bootstrap) === null || _d === void 0 ? void 0 : _d.isIdentifiedID) ? uuid : config.bootstrap.distinctID;
394
+ this.persistence.set_user_state(((_e = config.bootstrap) === null || _e === void 0 ? void 0 : _e.isIdentifiedID) ? 'identified' : 'anonymous');
395
+ this.register({
396
+ distinct_id: config.bootstrap.distinctID,
397
+ $device_id: deviceID,
398
+ });
399
+ }
400
+ if (this._hasBootstrappedFeatureFlags()) {
401
+ var activeFlags_1 = Object.keys(((_f = config.bootstrap) === null || _f === void 0 ? void 0 : _f.featureFlags) || {})
402
+ .filter(function (flag) { var _a, _b; return !!((_b = (_a = config.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[flag]); })
403
+ .reduce(function (res, key) {
404
+ var _a, _b;
405
+ return ((res[key] = ((_b = (_a = config.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[key]) || false), res);
406
+ }, {});
407
+ var featureFlagPayloads = Object.keys(((_g = config.bootstrap) === null || _g === void 0 ? void 0 : _g.featureFlagPayloads) || {})
408
+ .filter(function (key) { return activeFlags_1[key]; })
409
+ .reduce(function (res, key) {
410
+ var _a, _b, _c, _d;
411
+ if ((_b = (_a = config.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlagPayloads) === null || _b === void 0 ? void 0 : _b[key]) {
412
+ res[key] = (_d = (_c = config.bootstrap) === null || _c === void 0 ? void 0 : _c.featureFlagPayloads) === null || _d === void 0 ? void 0 : _d[key];
413
+ }
414
+ return res;
415
+ }, {});
416
+ this.featureFlags.receivedFeatureFlags({ featureFlags: activeFlags_1, featureFlagPayloads: featureFlagPayloads });
417
+ }
418
+ if (!this.get_distinct_id()) {
419
+ // There is no need to set the distinct id
420
+ // or the device id if something was already stored
421
+ // in the persitence
422
+ var uuid = this.get_config('get_device_id')(uuidv7());
423
+ this.register_once({
424
+ distinct_id: uuid,
425
+ $device_id: uuid,
426
+ }, '');
427
+ // distinct id == $device_id is a proxy for anonymous user
428
+ this.persistence.set_user_state('anonymous');
429
+ }
430
+ // Set up event handler for pageleave
431
+ // Use `onpagehide` if available, see https://calendar.perfplanet.com/2020/beaconing-in-practice/#beaconing-reliability-avoiding-abandons
432
+ window.addEventListener &&
433
+ window.addEventListener('onpagehide' in self ? 'pagehide' : 'unload', this._handle_unload.bind(this));
434
+ // Make sure that we also call the initComplete callback at the end of
435
+ // the synchronous code as well.
436
+ updateInitComplete('syncCode')();
437
+ };
438
+ // Private methods
439
+ PostHog.prototype._loaded = function () {
440
+ // Pause `reloadFeatureFlags` calls in config.loaded callback.
441
+ // These feature flags are loaded in the decide call made right
442
+ // afterwards
443
+ this.featureFlags.setReloadingPaused(true);
444
+ try {
445
+ this.get_config('loaded')(this);
446
+ }
447
+ catch (err) {
448
+ console.error('`loaded` function failed', err);
449
+ }
450
+ this._start_queue_if_opted_in();
451
+ // this happens after so a user can call identify in
452
+ // the loaded callback
453
+ if (this.get_config('capture_pageview')) {
454
+ this.capture('$pageview', { title: document.title }, { send_instantly: true });
455
+ }
456
+ // Call decide to get what features are enabled and other settings.
457
+ // As a reminder, if the /decide endpoint is disabled, feature flags, toolbar, session recording, autocapture,
458
+ // and compression will not be available.
459
+ if (!this.get_config('advanced_disable_decide')) {
460
+ new Decide(this).call();
461
+ }
462
+ this.featureFlags.resetRequestQueue();
463
+ this.featureFlags.setReloadingPaused(false);
464
+ };
465
+ PostHog.prototype._start_queue_if_opted_in = function () {
466
+ if (!this.has_opted_out_capturing()) {
467
+ if (this.get_config('request_batching')) {
468
+ this._requestQueue.poll();
469
+ }
470
+ }
471
+ };
472
+ PostHog.prototype._dom_loaded = function () {
473
+ var _this = this;
474
+ if (!this.has_opted_out_capturing()) {
475
+ _eachArray(this.__request_queue, function (item) {
476
+ _this._send_request.apply(_this, __spreadArray([], __read(item), false));
477
+ });
478
+ }
479
+ this.__request_queue = [];
480
+ this._start_queue_if_opted_in();
481
+ };
482
+ /**
483
+ * _prepare_callback() should be called by callers of _send_request for use
484
+ * as the callback argument.
485
+ *
486
+ * If there is no callback, this returns null.
487
+ * If we are going to make XHR/XDR requests, this returns a function.
488
+ * If we are going to use script tags, this returns a string to use as the
489
+ * callback GET param.
490
+ */
491
+ // TODO: get rid of the "| string"
492
+ PostHog.prototype._prepare_callback = function (callback, data) {
493
+ if (_isUndefined(callback)) {
494
+ return null;
495
+ }
496
+ if (USE_XHR) {
497
+ return function (response) {
498
+ callback(response, data);
499
+ };
500
+ }
501
+ else {
502
+ // if the user gives us a callback, we store as a random
503
+ // property on this instances jsc function and update our
504
+ // callback string to reflect that.
505
+ var jsc_1 = this._jsc;
506
+ var randomized_cb_1 = '' + Math.floor(Math.random() * 100000000);
507
+ var callback_string = this.get_config('callback_fn') + '[' + randomized_cb_1 + ']';
508
+ jsc_1[randomized_cb_1] = function (response) {
509
+ delete jsc_1[randomized_cb_1];
510
+ callback(response, data);
511
+ };
512
+ return callback_string;
513
+ }
514
+ };
515
+ PostHog.prototype._handle_unload = function () {
516
+ if (!this.get_config('request_batching')) {
517
+ if (this.get_config('capture_pageview') && this.get_config('capture_pageleave')) {
518
+ this.capture('$pageleave', null, { transport: 'sendBeacon' });
519
+ }
520
+ return;
521
+ }
522
+ if (this.get_config('capture_pageview') && this.get_config('capture_pageleave')) {
523
+ this.capture('$pageleave');
524
+ }
525
+ this._requestQueue.unload();
526
+ this._retryQueue.unload();
527
+ };
528
+ PostHog.prototype._handle_queued_event = function (url, data, options) {
529
+ var jsonData = JSON.stringify(data);
530
+ this.__compress_and_send_json_request(url, jsonData, options || __NOOPTIONS, __NOOP);
531
+ };
532
+ PostHog.prototype.__compress_and_send_json_request = function (url, jsonData, options, callback) {
533
+ var _a = __read(compressData(decideCompression(this.compression), jsonData, options), 2), data = _a[0], _options = _a[1];
534
+ this._send_request(url, data, _options, callback);
535
+ };
536
+ PostHog.prototype._send_request = function (url, data, options, callback) {
537
+ var _a;
538
+ if (this.rateLimiter.isRateLimited(options._batchKey)) {
539
+ if (this.get_config('debug')) {
540
+ console.warn('[PostHog SendRequest] is quota limited. Dropping request.');
541
+ }
542
+ return;
543
+ }
544
+ if (ENQUEUE_REQUESTS) {
545
+ this.__request_queue.push([url, data, options, callback]);
546
+ return;
547
+ }
548
+ var DEFAULT_OPTIONS = {
549
+ method: this.get_config('api_method'),
550
+ transport: this.get_config('api_transport'),
551
+ verbose: this.get_config('verbose'),
552
+ };
553
+ options = _extend(DEFAULT_OPTIONS, options || {});
554
+ if (!USE_XHR) {
555
+ options.method = 'GET';
556
+ }
557
+ var useSendBeacon = 'sendBeacon' in window.navigator && options.transport === 'sendBeacon';
558
+ url = addParamsToURL(url, options.urlQueryArgs || {}, {
559
+ ip: this.get_config('ip'),
560
+ });
561
+ if (useSendBeacon) {
562
+ // beacon documentation https://w3c.github.io/beacon/
563
+ // beacons format the message and use the type property
564
+ try {
565
+ window.navigator.sendBeacon(url, encodePostData(data, __assign(__assign({}, options), { sendBeacon: true })));
566
+ }
567
+ catch (e) {
568
+ // send beacon is a best-effort, fire-and-forget mechanism on page unload,
569
+ // we don't want to throw errors here
570
+ }
571
+ }
572
+ else if (USE_XHR) {
573
+ try {
574
+ xhr({
575
+ url: url,
576
+ data: data,
577
+ headers: this.get_config('xhr_headers'),
578
+ options: options,
579
+ callback: callback,
580
+ retriesPerformedSoFar: 0,
581
+ retryQueue: this._retryQueue,
582
+ onXHRError: this.get_config('on_xhr_error'),
583
+ onRateLimited: this.rateLimiter.on429Response,
584
+ });
585
+ }
586
+ catch (e) {
587
+ console.error(e);
588
+ }
589
+ }
590
+ else {
591
+ var script = document.createElement('script');
592
+ script.type = 'text/javascript';
593
+ script.async = true;
594
+ script.defer = true;
595
+ script.src = url;
596
+ var s = document.getElementsByTagName('script')[0];
597
+ (_a = s.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(script, s);
598
+ }
599
+ };
600
+ /**
601
+ * _execute_array() deals with processing any posthog function
602
+ * calls that were called before the PostHog library were loaded
603
+ * (and are thus stored in an array so they can be called later)
604
+ *
605
+ * Note: we fire off all the posthog function calls && user defined
606
+ * functions BEFORE we fire off posthog capturing calls. This is so
607
+ * identify/register/set_config calls can properly modify early
608
+ * capturing calls.
609
+ *
610
+ * @param {Array} array
611
+ */
612
+ PostHog.prototype._execute_array = function (array) {
613
+ var _this = this;
614
+ var fn_name;
615
+ var alias_calls = [];
616
+ var other_calls = [];
617
+ var capturing_calls = [];
618
+ _eachArray(array, function (item) {
619
+ if (item) {
620
+ fn_name = item[0];
621
+ if (_isArray(fn_name)) {
622
+ capturing_calls.push(item); // chained call e.g. posthog.get_group().set()
623
+ }
624
+ else if (typeof item === 'function') {
625
+ ;
626
+ item.call(_this);
627
+ }
628
+ else if (_isArray(item) && fn_name === 'alias') {
629
+ alias_calls.push(item);
630
+ }
631
+ else if (_isArray(item) &&
632
+ fn_name.indexOf('capture') !== -1 &&
633
+ typeof _this[fn_name] === 'function') {
634
+ capturing_calls.push(item);
635
+ }
636
+ else {
637
+ other_calls.push(item);
638
+ }
639
+ }
640
+ });
641
+ var execute = function (calls, thisArg) {
642
+ _eachArray(calls, function (item) {
643
+ if (_isArray(item[0])) {
644
+ // chained call
645
+ var caller_1 = thisArg;
646
+ _each(item, function (call) {
647
+ caller_1 = caller_1[call[0]].apply(caller_1, call.slice(1));
648
+ });
649
+ }
650
+ else {
651
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
652
+ // @ts-ignore
653
+ this[item[0]].apply(this, item.slice(1));
654
+ }
655
+ }, thisArg);
656
+ };
657
+ execute(alias_calls, this);
658
+ execute(other_calls, this);
659
+ execute(capturing_calls, this);
660
+ };
661
+ PostHog.prototype._hasBootstrappedFeatureFlags = function () {
662
+ var _a, _b;
663
+ return ((((_a = this.config.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) && Object.keys((_b = this.config.bootstrap) === null || _b === void 0 ? void 0 : _b.featureFlags).length > 0) ||
664
+ false);
665
+ };
666
+ /**
667
+ * push() keeps the standard async-array-push
668
+ * behavior around after the lib is loaded.
669
+ * This is only useful for external integrations that
670
+ * do not wish to rely on our convenience methods
671
+ * (created in the snippet).
672
+ *
673
+ * ### Usage:
674
+ * posthog.push(['register', { a: 'b' }]);
675
+ *
676
+ * @param {Array} item A [function_name, args...] array to be executed
677
+ */
678
+ PostHog.prototype.push = function (item) {
679
+ this._execute_array([item]);
680
+ };
681
+ /*
682
+ * PostHog supports exception autocapture, however, this function
683
+ * is used to manually capture an exception
684
+ * and can be used to add more context to that exception
685
+ *
686
+ * Properties passed as the second option will be merged with the properties
687
+ * of the exception event.
688
+ * Where there is a key in both generated exception and passed properties,
689
+ * the generated exception property takes precedence.
690
+ */
691
+ PostHog.prototype.captureException = function (exception, properties) {
692
+ var _a;
693
+ (_a = this.exceptionAutocapture) === null || _a === void 0 ? void 0 : _a.captureException([exception.name, undefined, undefined, undefined, exception], properties);
694
+ };
695
+ /**
696
+ * Capture an event. This is the most important and
697
+ * frequently used PostHog function.
698
+ *
699
+ * ### Usage:
700
+ *
701
+ * // capture an event named 'Registered'
702
+ * posthog.capture('Registered', {'Gender': 'Male', 'Age': 21});
703
+ *
704
+ * // capture an event using navigator.sendBeacon
705
+ * posthog.capture('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
706
+ *
707
+ * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
708
+ * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
709
+ * @param {Object} [options] Optional configuration for this capture request.
710
+ * @param {String} [options.transport] Transport method for network request ('XHR' or 'sendBeacon').
711
+ * @param {Date} [options.timestamp] Timestamp is a Date object. If not set, it'll automatically be set to the current time.
712
+ */
713
+ PostHog.prototype.capture = function (event_name, properties, options) {
714
+ if (options === void 0) { options = __NOOPTIONS; }
715
+ // While developing, a developer might purposefully _not_ call init(),
716
+ // in this case, we would like capture to be a noop.
717
+ if (!this.__loaded) {
718
+ return;
719
+ }
720
+ if (userOptedOut(this, false)) {
721
+ return;
722
+ }
723
+ options = options || __NOOPTIONS;
724
+ var transport = options['transport']; // external API, don't minify 'transport' prop
725
+ if (transport) {
726
+ options.transport = transport; // 'transport' prop name can be minified internally
727
+ }
728
+ // typing doesn't prevent interesting data
729
+ if (_isUndefined(event_name) || typeof event_name !== 'string') {
730
+ console.error('No event name provided to posthog.capture');
731
+ return;
732
+ }
733
+ if (_isBlockedUA(userAgent)) {
734
+ return;
735
+ }
736
+ // update persistence
737
+ this.sessionPersistence.update_search_keyword();
738
+ if (this.get_config('store_google')) {
739
+ this.sessionPersistence.update_campaign_params();
740
+ }
741
+ if (this.get_config('save_referrer')) {
742
+ this.sessionPersistence.update_referrer_info();
743
+ }
744
+ var data = {
745
+ uuid: uuidv7(),
746
+ event: event_name,
747
+ properties: this._calculate_event_properties(event_name, properties || {}),
748
+ };
749
+ if (event_name === '$identify') {
750
+ data['$set'] = options['$set'];
751
+ data['$set_once'] = options['$set_once'];
752
+ }
753
+ data = _copyAndTruncateStrings(data, options._noTruncate ? null : this.get_config('properties_string_max_length'));
754
+ data.timestamp = options.timestamp || new Date();
755
+ if (this.get_config('debug')) {
756
+ logger.log('PostHog.js send', data);
757
+ }
758
+ var jsonData = JSON.stringify(data);
759
+ var url = this.get_config('api_host') + (options.endpoint || '/e/');
760
+ var has_unique_traits = options !== __NOOPTIONS;
761
+ if (this.get_config('request_batching') &&
762
+ (!has_unique_traits || options._batchKey) &&
763
+ !options.send_instantly) {
764
+ this._requestQueue.enqueue(url, data, options);
765
+ }
766
+ else {
767
+ this.__compress_and_send_json_request(url, jsonData, options);
768
+ }
769
+ this._invokeCaptureHooks(event_name, data);
770
+ return data;
771
+ };
772
+ PostHog.prototype._addCaptureHook = function (callback) {
773
+ this.__captureHooks.push(callback);
774
+ };
775
+ PostHog.prototype._invokeCaptureHooks = function (eventName, eventData) {
776
+ this.config._onCapture(eventName, eventData);
777
+ _each(this.__captureHooks, function (callback) { return callback(eventName); });
778
+ };
779
+ PostHog.prototype._calculate_event_properties = function (event_name, event_properties) {
780
+ // set defaults
781
+ var start_timestamp = this.persistence.remove_event_timer(event_name);
782
+ var properties = __assign({}, event_properties);
783
+ properties['token'] = this.get_config('token');
784
+ if (event_name === '$snapshot') {
785
+ var persistenceProps = __assign(__assign({}, this.persistence.properties()), this.sessionPersistence.properties());
786
+ properties['distinct_id'] = persistenceProps.distinct_id;
787
+ return properties;
788
+ }
789
+ var infoProperties = _info.properties();
790
+ if (this.sessionManager) {
791
+ var _a = this.sessionManager.checkAndGetSessionAndWindowId(), sessionId = _a.sessionId, windowId = _a.windowId;
792
+ properties['$session_id'] = sessionId;
793
+ properties['$window_id'] = windowId;
794
+ }
795
+ if (this.get_config('__preview_measure_pageview_stats')) {
796
+ var performanceProperties = {};
797
+ if (event_name === '$pageview') {
798
+ performanceProperties = this.pageViewManager.doPageView();
799
+ }
800
+ else if (event_name === '$pageleave') {
801
+ performanceProperties = this.pageViewManager.doPageLeave();
802
+ }
803
+ properties = _extend(properties, performanceProperties);
804
+ }
805
+ if (event_name === '$pageview') {
806
+ properties['title'] = document.title;
807
+ }
808
+ if (event_name === '$performance_event') {
809
+ var persistenceProps = this.persistence.properties();
810
+ // Early exit for $performance_event as we only need session and $current_url
811
+ properties['distinct_id'] = persistenceProps.distinct_id;
812
+ properties['$current_url'] = infoProperties.$current_url;
813
+ return properties;
814
+ }
815
+ // set $duration if time_event was previously called for this event
816
+ if (typeof start_timestamp !== 'undefined') {
817
+ var duration_in_ms = new Date().getTime() - start_timestamp;
818
+ properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
819
+ }
820
+ // note: extend writes to the first object, so lets make sure we
821
+ // don't write to the persistence properties object and info
822
+ // properties object by passing in a new object
823
+ // update properties with pageview info and super-properties
824
+ properties = _extend({}, _info.properties(), this.persistence.properties(), this.sessionPersistence.properties(), properties);
825
+ var property_blacklist = this.get_config('property_blacklist');
826
+ if (_isArray(property_blacklist)) {
827
+ _each(property_blacklist, function (blacklisted_prop) {
828
+ delete properties[blacklisted_prop];
829
+ });
830
+ }
831
+ else {
832
+ console.error('Invalid value for property_blacklist config: ' + property_blacklist);
833
+ }
834
+ var sanitize_properties = this.get_config('sanitize_properties');
835
+ if (sanitize_properties) {
836
+ properties = sanitize_properties(properties, event_name);
837
+ }
838
+ return properties;
839
+ };
840
+ /**
841
+ * Register a set of super properties, which are included with all
842
+ * events. This will overwrite previous super property values, except
843
+ * for session properties (see `register_for_session(properties)`).
844
+ *
845
+ * ### Usage:
846
+ *
847
+ * // register 'Gender' as a super property
848
+ * posthog.register({'Gender': 'Female'});
849
+ *
850
+ * // register several super properties when a user signs up
851
+ * posthog.register({
852
+ * 'Email': 'jdoe@example.com',
853
+ * 'Account Type': 'Free'
854
+ * });
855
+ *
856
+ * // Display the properties
857
+ * console.log(posthog.persistence.properties())
858
+ *
859
+ * @param {Object} properties An associative array of properties to store about the user
860
+ * @param {Number} [days] How many days since the user's last visit to store the super properties
861
+ */
862
+ PostHog.prototype.register = function (properties, days) {
863
+ this.persistence.register(properties, days);
864
+ };
865
+ /**
866
+ * Register a set of super properties only once. These will not
867
+ * overwrite previous super property values, unlike register().
868
+ *
869
+ * ### Usage:
870
+ *
871
+ * // register a super property for the first time only
872
+ * posthog.register_once({
873
+ * 'First Login Date': new Date().toISOString()
874
+ * });
875
+ *
876
+ * // Display the properties
877
+ * console.log(posthog.persistence.properties())
878
+ *
879
+ * ### Notes:
880
+ *
881
+ * If default_value is specified, current super properties
882
+ * with that value will be overwritten.
883
+ *
884
+ * @param {Object} properties An associative array of properties to store about the user
885
+ * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
886
+ * @param {Number} [days] How many days since the users last visit to store the super properties
887
+ */
888
+ PostHog.prototype.register_once = function (properties, default_value, days) {
889
+ this.persistence.register_once(properties, default_value, days);
890
+ };
891
+ /**
892
+ * Register a set of super properties, which are included with all events, but only
893
+ * for THIS SESSION. These will overwrite all other super property values.
894
+ *
895
+ * Unlike regular super properties, which last in LocalStorage for a long time,
896
+ * session super properties get cleared after a session ends.
897
+ *
898
+ * ### Usage:
899
+ *
900
+ * // register on all events this session
901
+ * posthog.register_for_session({'referer': customGetReferer()});
902
+ *
903
+ * // register several session super properties when a user signs up
904
+ * posthog.register_for_session({
905
+ * 'selectedPlan': 'pro',
906
+ * 'completedSteps': 4,
907
+ * });
908
+ *
909
+ * // Display the properties
910
+ * console.log(posthog.sessionPersistence.properties())
911
+ *
912
+ * @param {Object} properties An associative array of properties to store about the user
913
+ */
914
+ PostHog.prototype.register_for_session = function (properties) {
915
+ this.sessionPersistence.register(properties);
916
+ };
917
+ /**
918
+ * Delete a super property stored with the current user.
919
+ *
920
+ * @param {String} property The name of the super property to remove
921
+ */
922
+ PostHog.prototype.unregister = function (property) {
923
+ this.persistence.unregister(property);
924
+ };
925
+ /**
926
+ * Delete a session super property stored with the current user.
927
+ *
928
+ * @param {String} property The name of the session super property to remove
929
+ */
930
+ PostHog.prototype.unregister_for_session = function (property) {
931
+ this.sessionPersistence.unregister(property);
932
+ };
933
+ PostHog.prototype._register_single = function (prop, value) {
934
+ var _a;
935
+ this.register((_a = {}, _a[prop] = value, _a));
936
+ };
937
+ /*
938
+ * Get feature flag value for user (supports multivariate flags).
939
+ *
940
+ * ### Usage:
941
+ *
942
+ * if(posthog.getFeatureFlag('beta-feature') === 'some-value') { // do something }
943
+ *
944
+ * @param {Object|String} prop Key of the feature flag.
945
+ * @param {Object|String} options (optional) If {send_event: false}, we won't send an $feature_flag_call event to PostHog.
946
+ */
947
+ PostHog.prototype.getFeatureFlag = function (key, options) {
948
+ return this.featureFlags.getFeatureFlag(key, options);
949
+ };
950
+ /*
951
+ * Get feature flag payload value matching key for user (supports multivariate flags).
952
+ *
953
+ * ### Usage:
954
+ *
955
+ * if(posthog.getFeatureFlag('beta-feature') === 'some-value') {
956
+ * const someValue = posthog.getFeatureFlagPayload('beta-feature')
957
+ * // do something
958
+ * }
959
+ *
960
+ * @param {Object|String} prop Key of the feature flag.
961
+ */
962
+ PostHog.prototype.getFeatureFlagPayload = function (key) {
963
+ var payload = this.featureFlags.getFeatureFlagPayload(key);
964
+ try {
965
+ return JSON.parse(payload);
966
+ }
967
+ catch (_a) {
968
+ return payload;
969
+ }
970
+ };
971
+ /*
972
+ * See if feature flag is enabled for user.
973
+ *
974
+ * ### Usage:
975
+ *
976
+ * if(posthog.isFeatureEnabled('beta-feature')) { // do something }
977
+ *
978
+ * @param {Object|String} prop Key of the feature flag.
979
+ * @param {Object|String} options (optional) If {send_event: false}, we won't send an $feature_flag_call event to PostHog.
980
+ */
981
+ PostHog.prototype.isFeatureEnabled = function (key, options) {
982
+ return this.featureFlags.isFeatureEnabled(key, options);
983
+ };
984
+ PostHog.prototype.reloadFeatureFlags = function () {
985
+ this.featureFlags.reloadFeatureFlags();
986
+ };
987
+ /** Opt the user in or out of an early access feature. */
988
+ PostHog.prototype.updateEarlyAccessFeatureEnrollment = function (key, isEnrolled) {
989
+ this.featureFlags.updateEarlyAccessFeatureEnrollment(key, isEnrolled);
990
+ };
991
+ /** Get the list of early access features. To check enrollment status, use `isFeatureEnabled`. */
992
+ PostHog.prototype.getEarlyAccessFeatures = function (callback, force_reload) {
993
+ if (force_reload === void 0) { force_reload = false; }
994
+ return this.featureFlags.getEarlyAccessFeatures(callback, force_reload);
995
+ };
996
+ /*
997
+ * Register an event listener that runs when feature flags become available or when they change.
998
+ * If there are flags, the listener is called immediately in addition to being called on future changes.
999
+ *
1000
+ * ### Usage:
1001
+ *
1002
+ * posthog.onFeatureFlags(function(featureFlags) { // do something })
1003
+ *
1004
+ * @param {Function} [callback] The callback function will be called once the feature flags are ready or when they are updated.
1005
+ * It'll return a list of feature flags enabled for the user.
1006
+ * @returns {Function} A function that can be called to unsubscribe the listener. Used by useEffect when the component unmounts.
1007
+ */
1008
+ PostHog.prototype.onFeatureFlags = function (callback) {
1009
+ return this.featureFlags.onFeatureFlags(callback);
1010
+ };
1011
+ /*
1012
+ * Register an event listener that runs whenever the session id or window id change.
1013
+ * If there is already a session id, the listener is called immediately in addition to being called on future changes.
1014
+ *
1015
+ * Can be used, for example, to sync the PostHog session id with a backend session.
1016
+ *
1017
+ * ### Usage:
1018
+ *
1019
+ * posthog.onSessionId(function(sessionId, windowId) { // do something })
1020
+ *
1021
+ * @param {Function} [callback] The callback function will be called once a session id is present or when it or the window id are updated.
1022
+ * @returns {Function} A function that can be called to unsubscribe the listener. E.g. Used by useEffect when the component unmounts.
1023
+ */
1024
+ PostHog.prototype.onSessionId = function (callback) {
1025
+ return this.sessionManager.onSessionId(callback);
1026
+ };
1027
+ /** Get list of all surveys. */
1028
+ PostHog.prototype.getSurveys = function (callback, forceReload) {
1029
+ if (forceReload === void 0) { forceReload = false; }
1030
+ this.surveys.getSurveys(callback, forceReload);
1031
+ };
1032
+ /** Get surveys that should be enabled for the current user. */
1033
+ PostHog.prototype.getActiveMatchingSurveys = function (callback, forceReload) {
1034
+ if (forceReload === void 0) { forceReload = false; }
1035
+ this.surveys.getActiveMatchingSurveys(callback, forceReload);
1036
+ };
1037
+ /**
1038
+ * Identify a user with a unique ID instead of a PostHog
1039
+ * randomly generated distinct_id. If the method is never called,
1040
+ * then unique visitors will be identified by a UUID that is generated
1041
+ * the first time they visit the site.
1042
+ *
1043
+ * If user properties are passed, they are also sent to posthog.
1044
+ *
1045
+ * ### Usage:
1046
+ *
1047
+ * posthog.identify('[user unique id]')
1048
+ * posthog.identify('[user unique id]', { email: 'john@example.com' })
1049
+ * posthog.identify('[user unique id]', {}, { referral_code: '12345' })
1050
+ *
1051
+ * ### Notes:
1052
+ *
1053
+ * You can call this function to overwrite a previously set
1054
+ * unique ID for the current user.
1055
+ *
1056
+ * If the user has been identified ($user_state in persistence is set to 'identified'),
1057
+ * then capture of $identify is skipped to avoid merging users. For example,
1058
+ * if your system allows an admin user to impersonate another user.
1059
+ *
1060
+ * Then a single browser instance can have:
1061
+ *
1062
+ * `identify('a') -> capture(1) -> identify('b') -> capture(2)`
1063
+ *
1064
+ * and capture 1 and capture 2 will have the correct distinct_id.
1065
+ * but users a and b will NOT be merged in posthog.
1066
+ *
1067
+ * However, if reset is called then:
1068
+ *
1069
+ * `identify('a') -> capture(1) -> reset() -> capture(2) -> identify('b') -> capture(3)`
1070
+ *
1071
+ * users a and b are not merged.
1072
+ * Capture 1 is associated with user a.
1073
+ * A new distinct id is generated for capture 2.
1074
+ * which is merged with user b.
1075
+ * So, capture 2 and 3 are associated with user b.
1076
+ *
1077
+ * If you want to merge two identified users, you can call posthog.alias
1078
+ *
1079
+ * @param {String} [new_distinct_id] A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used.
1080
+ * @param {Object} [userPropertiesToSet] Optional: An associative array of properties to store about the user
1081
+ * @param {Object} [userPropertiesToSetOnce] Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.
1082
+ */
1083
+ PostHog.prototype.identify = function (new_distinct_id, userPropertiesToSet, userPropertiesToSetOnce) {
1084
+ //if the new_distinct_id has not been set ignore the identify event
1085
+ if (!new_distinct_id) {
1086
+ console.error('Unique user id has not been set in posthog.identify');
1087
+ return;
1088
+ }
1089
+ var previous_distinct_id = this.get_distinct_id();
1090
+ this.register({ $user_id: new_distinct_id });
1091
+ if (!this.get_property('$device_id')) {
1092
+ // The persisted distinct id might not actually be a device id at all
1093
+ // it might be a distinct id of the user from before
1094
+ var device_id = previous_distinct_id;
1095
+ this.register_once({
1096
+ $had_persisted_distinct_id: true,
1097
+ $device_id: device_id,
1098
+ }, '');
1099
+ }
1100
+ // if the previous distinct id had an alias stored, then we clear it
1101
+ if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {
1102
+ this.unregister(ALIAS_ID_KEY);
1103
+ this.register({ distinct_id: new_distinct_id });
1104
+ }
1105
+ var isKnownAnonymous = this.persistence.get_user_state() === 'anonymous';
1106
+ // send an $identify event any time the distinct_id is changing and the old ID is an anoymous ID
1107
+ // - logic on the server will determine whether or not to do anything with it.
1108
+ if (new_distinct_id !== previous_distinct_id && isKnownAnonymous) {
1109
+ this.persistence.set_user_state('identified');
1110
+ // Update current user properties
1111
+ this.setPersonPropertiesForFlags(userPropertiesToSet || {}, false);
1112
+ this.capture('$identify', {
1113
+ distinct_id: new_distinct_id,
1114
+ $anon_distinct_id: previous_distinct_id,
1115
+ }, { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} });
1116
+ // let the reload feature flag request know to send this previous distinct id
1117
+ // for flag consistency
1118
+ this.featureFlags.setAnonymousDistinctId(previous_distinct_id);
1119
+ }
1120
+ else if (userPropertiesToSet || userPropertiesToSetOnce) {
1121
+ // If the distinct_id is not changing, but we have user properties to set, we can go for a $set event
1122
+ this.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce);
1123
+ }
1124
+ // Reload active feature flags if the user identity changes.
1125
+ // Note we don't reload this on property changes as these get processed async
1126
+ if (new_distinct_id !== previous_distinct_id) {
1127
+ this.reloadFeatureFlags();
1128
+ // also clear any stored flag calls
1129
+ this.unregister(FLAG_CALL_REPORTED);
1130
+ }
1131
+ };
1132
+ /**
1133
+ * Sets properties for the Person associated with the current distinct_id.
1134
+ *
1135
+ *
1136
+ * @param {Object} [userPropertiesToSet] Optional: An associative array of properties to store about the user
1137
+ * @param {Object} [userPropertiesToSetOnce] Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value.
1138
+ */
1139
+ PostHog.prototype.setPersonProperties = function (userPropertiesToSet, userPropertiesToSetOnce) {
1140
+ if (!userPropertiesToSet && !userPropertiesToSetOnce) {
1141
+ return;
1142
+ }
1143
+ // Update current user properties
1144
+ this.setPersonPropertiesForFlags(userPropertiesToSet || {});
1145
+ this.capture('$set', { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} });
1146
+ };
1147
+ /**
1148
+ * Alpha feature: don't use unless you know what you're doing!
1149
+ *
1150
+ * Sets group analytics information for subsequent events and reloads feature flags.
1151
+ *
1152
+ * @param {String} groupType Group type (example: 'organization')
1153
+ * @param {String} groupKey Group key (example: 'org::5')
1154
+ * @param {Object} groupPropertiesToSet Optional properties to set for group
1155
+ */
1156
+ PostHog.prototype.group = function (groupType, groupKey, groupPropertiesToSet) {
1157
+ var _a, _b;
1158
+ if (!groupType || !groupKey) {
1159
+ console.error('posthog.group requires a group type and group key');
1160
+ return;
1161
+ }
1162
+ var existingGroups = this.getGroups();
1163
+ // if group key changes, remove stored group properties
1164
+ if (existingGroups[groupType] !== groupKey) {
1165
+ this.resetGroupPropertiesForFlags(groupType);
1166
+ }
1167
+ this.register({ $groups: __assign(__assign({}, existingGroups), (_a = {}, _a[groupType] = groupKey, _a)) });
1168
+ if (groupPropertiesToSet) {
1169
+ this.capture('$groupidentify', {
1170
+ $group_type: groupType,
1171
+ $group_key: groupKey,
1172
+ $group_set: groupPropertiesToSet,
1173
+ });
1174
+ this.setGroupPropertiesForFlags((_b = {}, _b[groupType] = groupPropertiesToSet, _b));
1175
+ }
1176
+ // If groups change and no properties change, reload feature flags.
1177
+ // The property change reload case is handled in setGroupPropertiesForFlags.
1178
+ if (existingGroups[groupType] !== groupKey && !groupPropertiesToSet) {
1179
+ this.reloadFeatureFlags();
1180
+ }
1181
+ };
1182
+ /**
1183
+ * Resets only the group properties of the user currently logged in.
1184
+ */
1185
+ PostHog.prototype.resetGroups = function () {
1186
+ this.register({ $groups: {} });
1187
+ this.resetGroupPropertiesForFlags();
1188
+ // If groups changed, reload feature flags.
1189
+ this.reloadFeatureFlags();
1190
+ };
1191
+ /**
1192
+ * Set override person properties for feature flags.
1193
+ * This is used when dealing with new persons / where you don't want to wait for ingestion
1194
+ * to update user properties.
1195
+ */
1196
+ PostHog.prototype.setPersonPropertiesForFlags = function (properties, reloadFeatureFlags) {
1197
+ if (reloadFeatureFlags === void 0) { reloadFeatureFlags = true; }
1198
+ this.featureFlags.setPersonPropertiesForFlags(properties, reloadFeatureFlags);
1199
+ };
1200
+ PostHog.prototype.resetPersonPropertiesForFlags = function () {
1201
+ this.featureFlags.resetPersonPropertiesForFlags();
1202
+ };
1203
+ /**
1204
+ * Set override group properties for feature flags.
1205
+ * This is used when dealing with new groups / where you don't want to wait for ingestion
1206
+ * to update properties.
1207
+ * Takes in an object, the key of which is the group type.
1208
+ * For example:
1209
+ * setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })
1210
+ */
1211
+ PostHog.prototype.setGroupPropertiesForFlags = function (properties, reloadFeatureFlags) {
1212
+ if (reloadFeatureFlags === void 0) { reloadFeatureFlags = true; }
1213
+ this.featureFlags.setGroupPropertiesForFlags(properties, reloadFeatureFlags);
1214
+ };
1215
+ PostHog.prototype.resetGroupPropertiesForFlags = function (group_type) {
1216
+ this.featureFlags.resetGroupPropertiesForFlags(group_type);
1217
+ };
1218
+ /**
1219
+ * Clears super properties and generates a new random distinct_id for this instance.
1220
+ * Useful for clearing data when a user logs out.
1221
+ */
1222
+ PostHog.prototype.reset = function (reset_device_id) {
1223
+ var device_id = this.get_property('$device_id');
1224
+ this.persistence.clear();
1225
+ this.sessionPersistence.clear();
1226
+ this.persistence.set_user_state('anonymous');
1227
+ this.sessionManager.resetSessionId();
1228
+ var uuid = this.get_config('get_device_id')(uuidv7());
1229
+ this.register_once({
1230
+ distinct_id: uuid,
1231
+ $device_id: reset_device_id ? uuid : device_id,
1232
+ }, '');
1233
+ };
1234
+ /**
1235
+ * Returns the current distinct id of the user. This is either the id automatically
1236
+ * generated by the library or the id that has been passed by a call to identify().
1237
+ *
1238
+ * ### Notes:
1239
+ *
1240
+ * get_distinct_id() can only be called after the PostHog library has finished loading.
1241
+ * init() has a loaded function available to handle this automatically. For example:
1242
+ *
1243
+ * // set distinct_id after the posthog library has loaded
1244
+ * posthog.init('YOUR PROJECT TOKEN', {
1245
+ * loaded: function(posthog) {
1246
+ * distinct_id = posthog.get_distinct_id();
1247
+ * }
1248
+ * });
1249
+ */
1250
+ PostHog.prototype.get_distinct_id = function () {
1251
+ return this.get_property('distinct_id');
1252
+ };
1253
+ PostHog.prototype.getGroups = function () {
1254
+ return this.get_property('$groups') || {};
1255
+ };
1256
+ /**
1257
+ * Returns the current session_id.
1258
+ *
1259
+ * NOTE: This should only be used for informative purposes.
1260
+ * Any actual internal use case for the session_id should be handled by the sessionManager.
1261
+ */
1262
+ PostHog.prototype.get_session_id = function () {
1263
+ return this.sessionManager.checkAndGetSessionAndWindowId(true).sessionId;
1264
+ };
1265
+ /**
1266
+ * Returns the Replay url for the current session.
1267
+ *
1268
+ * @param options Options for the url
1269
+ * @param options.withTimestamp Whether to include the timestamp in the url (defaults to false)
1270
+ * @param options.timestampLookBack How many seconds to look back for the timestamp (defaults to 10)
1271
+ */
1272
+ PostHog.prototype.get_session_replay_url = function (options) {
1273
+ var _a;
1274
+ var host = this.config.ui_host || this.config.api_host;
1275
+ var _b = this.sessionManager.checkAndGetSessionAndWindowId(true), sessionId = _b.sessionId, sessionStartTimestamp = _b.sessionStartTimestamp;
1276
+ var url = host + '/replay/' + sessionId;
1277
+ if ((options === null || options === void 0 ? void 0 : options.withTimestamp) && sessionStartTimestamp) {
1278
+ var LOOK_BACK = (_a = options.timestampLookBack) !== null && _a !== void 0 ? _a : 10;
1279
+ if (!sessionStartTimestamp) {
1280
+ return url;
1281
+ }
1282
+ var recordingStartTime = Math.max(Math.floor((new Date().getTime() - sessionStartTimestamp) / 1000) - LOOK_BACK, 0);
1283
+ url += "?t=".concat(recordingStartTime);
1284
+ }
1285
+ return url;
1286
+ };
1287
+ /**
1288
+ * Create an alias, which PostHog will use to link two distinct_ids going forward (not retroactively).
1289
+ * Multiple aliases can map to the same original ID, but not vice-versa. Aliases can also be chained - the
1290
+ * following is a valid scenario:
1291
+ *
1292
+ * posthog.alias('new_id', 'existing_id');
1293
+ * ...
1294
+ * posthog.alias('newer_id', 'new_id');
1295
+ *
1296
+ * If the original ID is not passed in, we will use the current distinct_id - probably the auto-generated GUID.
1297
+ *
1298
+ * ### Notes:
1299
+ *
1300
+ * The best practice is to call alias() when a unique ID is first created for a user
1301
+ * (e.g., when a user first registers for an account and provides an email address).
1302
+ * alias() should never be called more than once for a given user, except to
1303
+ * chain a newer ID to a previously new ID, as described above.
1304
+ *
1305
+ * @param {String} alias A unique identifier that you want to use for this user in the future.
1306
+ * @param {String} [original] The current identifier being used for this user.
1307
+ */
1308
+ PostHog.prototype.alias = function (alias, original) {
1309
+ // If the $people_distinct_id key exists in persistence, there has been a previous
1310
+ // posthog.people.identify() call made for this user. It is VERY BAD to make an alias with
1311
+ // this ID, as it will duplicate users.
1312
+ if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {
1313
+ logger.critical('Attempting to create alias for existing People user - aborting.');
1314
+ return -2;
1315
+ }
1316
+ if (_isUndefined(original)) {
1317
+ original = this.get_distinct_id();
1318
+ }
1319
+ if (alias !== original) {
1320
+ this._register_single(ALIAS_ID_KEY, alias);
1321
+ return this.capture('$create_alias', { alias: alias, distinct_id: original });
1322
+ }
1323
+ else {
1324
+ console.error('alias matches current distinct_id - skipping api call.');
1325
+ this.identify(alias);
1326
+ return -1;
1327
+ }
1328
+ };
1329
+ /**
1330
+ * Update the configuration of a posthog library instance.
1331
+ *
1332
+ * The default config is:
1333
+ *
1334
+ * {
1335
+ * // PostHog API host
1336
+ * api_host: 'https://app.posthog.com',
1337
+ *
1338
+ * // HTTP method for capturing requests
1339
+ * api_method: 'POST'
1340
+ *
1341
+ * // PostHog web app host, currently only used by the Sentry integration.
1342
+ * // This will only be different from api_host when using a reverse-proxied API host – in that case
1343
+ * // the original web app host needs to be passed here so that links to the web app are still convenient.
1344
+ * ui_host: 'https://app.posthog.com',
1345
+ *
1346
+ * // Automatically capture clicks, form submissions and change events
1347
+ * autocapture: true
1348
+ *
1349
+ * // Capture rage clicks
1350
+ * rageclick: true
1351
+ *
1352
+ * // transport for sending requests ('XHR' or 'sendBeacon')
1353
+ * // NB: sendBeacon should only be used for scenarios such as
1354
+ * // page unload where a "best-effort" attempt to send is
1355
+ * // acceptable; the sendBeacon API does not support callbacks
1356
+ * // or any way to know the result of the request. PostHog
1357
+ * // capturing via sendBeacon will not support any event-
1358
+ * // batching or retry mechanisms.
1359
+ * api_transport: 'XHR'
1360
+ *
1361
+ * // super properties cookie expiration (in days)
1362
+ * cookie_expiration: 365
1363
+ *
1364
+ * // super properties span subdomains
1365
+ * cross_subdomain_cookie: true
1366
+ *
1367
+ * // debug mode
1368
+ * debug: false
1369
+ *
1370
+ * // if this is true, the posthog cookie or localStorage entry
1371
+ * // will be deleted, and no user persistence will take place
1372
+ * disable_persistence: false
1373
+ *
1374
+ * // if this is true, PostHog will automatically determine
1375
+ * // City, Region and Country data using the IP address of
1376
+ * //the client
1377
+ * ip: true
1378
+ *
1379
+ * // opt users out of capturing by this PostHog instance by default
1380
+ * opt_out_capturing_by_default: false
1381
+ *
1382
+ * // opt users out of browser data storage by this PostHog instance by default
1383
+ * opt_out_persistence_by_default: false
1384
+ *
1385
+ * // persistence mechanism used by opt-in/opt-out methods - cookie
1386
+ * // or localStorage - falls back to cookie if localStorage is unavailable
1387
+ * opt_out_capturing_persistence_type: 'localStorage'
1388
+ *
1389
+ * // customize the name of cookie/localStorage set by opt-in/opt-out methods
1390
+ * opt_out_capturing_cookie_prefix: null
1391
+ *
1392
+ * // type of persistent store for super properties (cookie/
1393
+ * // localStorage) if set to 'localStorage', any existing
1394
+ * // posthog cookie value with the same persistence_name
1395
+ * // will be transferred to localStorage and deleted
1396
+ * persistence: 'cookie'
1397
+ *
1398
+ * // name for super properties persistent store
1399
+ * persistence_name: ''
1400
+ *
1401
+ * // names of properties/superproperties which should never
1402
+ * // be sent with capture() calls
1403
+ * property_blacklist: []
1404
+ *
1405
+ * // if this is true, posthog cookies will be marked as
1406
+ * // secure, meaning they will only be transmitted over https
1407
+ * secure_cookie: false
1408
+ *
1409
+ * // should we capture a page view on page load
1410
+ * capture_pageview: true
1411
+ *
1412
+ * // if you set upgrade to be true, the library will check for
1413
+ * // a cookie from our old js library and import super
1414
+ * // properties from it, then the old cookie is deleted
1415
+ * // The upgrade config option only works in the initialization,
1416
+ * // so make sure you set it when you create the library.
1417
+ * upgrade: false
1418
+ *
1419
+ * // if this is true, session recording is always disabled.
1420
+ * disable_session_recording: false,
1421
+ *
1422
+ * // extra HTTP request headers to set for each API request, in
1423
+ * // the format {'Header-Name': value}
1424
+ * xhr_headers: {}
1425
+ *
1426
+ * // protocol for fetching in-app message resources, e.g.
1427
+ * // 'https://' or 'http://'; defaults to '//' (which defers to the
1428
+ * // current page's protocol)
1429
+ * inapp_protocol: '//'
1430
+ *
1431
+ * // whether to open in-app message link in new tab/window
1432
+ * inapp_link_new_window: false
1433
+ *
1434
+ * // a set of rrweb config options that PostHog users can configure
1435
+ * // see https://github.com/rrweb-io/rrweb/blob/master/guide.md
1436
+ * session_recording: {
1437
+ * blockClass: 'ph-no-capture',
1438
+ * blockSelector: null,
1439
+ * ignoreClass: 'ph-ignore-input',
1440
+ * maskAllInputs: true,
1441
+ * maskInputOptions: {},
1442
+ * maskInputFn: null,
1443
+ * slimDOMOptions: {},
1444
+ * collectFonts: false
1445
+ * }
1446
+ *
1447
+ * // prevent autocapture from capturing any attribute names on elements
1448
+ * mask_all_element_attributes: false
1449
+ *
1450
+ * // prevent autocapture from capturing textContent on all elements
1451
+ * mask_all_text: false
1452
+ *
1453
+ * // Anonymous users get a random UUID as their device by default.
1454
+ * // This option allows overriding that option.
1455
+ * get_device_id: (uuid) => uuid
1456
+ * }
1457
+ *
1458
+ *
1459
+ * @param {Object} config A dictionary of new configuration values to update
1460
+ */
1461
+ PostHog.prototype.set_config = function (config) {
1462
+ var oldConfig = __assign({}, this.config);
1463
+ if (_isObject(config)) {
1464
+ _extend(this.config, config);
1465
+ if (!this.get_config('persistence_name')) {
1466
+ this.config.persistence_name = this.config.cookie_name;
1467
+ }
1468
+ if (!this.get_config('disable_persistence')) {
1469
+ this.config.disable_persistence = this.config.disable_cookie;
1470
+ }
1471
+ if (this.persistence) {
1472
+ this.persistence.update_config(this.config);
1473
+ }
1474
+ if (this.sessionPersistence) {
1475
+ this.sessionPersistence.update_config(this.config);
1476
+ }
1477
+ if (localStore.is_supported() && localStore.get('ph_debug') === 'true') {
1478
+ this.config.debug = true;
1479
+ }
1480
+ if (this.get_config('debug')) {
1481
+ Config.DEBUG = true;
1482
+ }
1483
+ if (this.sessionRecording && typeof config.disable_session_recording !== 'undefined') {
1484
+ if (oldConfig.disable_session_recording !== config.disable_session_recording) {
1485
+ if (config.disable_session_recording) {
1486
+ this.sessionRecording.stopRecording();
1487
+ }
1488
+ else {
1489
+ this.sessionRecording.startRecordingIfEnabled();
1490
+ }
1491
+ }
1492
+ }
1493
+ }
1494
+ };
1495
+ /**
1496
+ * turns session recording on, and updates the config option
1497
+ * disable_session_recording to false
1498
+ */
1499
+ PostHog.prototype.startSessionRecording = function () {
1500
+ this.set_config({ disable_session_recording: false });
1501
+ };
1502
+ /**
1503
+ * turns session recording off, and updates the config option
1504
+ * disable_session_recording to true
1505
+ */
1506
+ PostHog.prototype.stopSessionRecording = function () {
1507
+ this.set_config({ disable_session_recording: true });
1508
+ };
1509
+ /**
1510
+ * returns a boolean indicating whether session recording
1511
+ * is currently running
1512
+ */
1513
+ PostHog.prototype.sessionRecordingStarted = function () {
1514
+ var _a;
1515
+ return !!((_a = this.sessionRecording) === null || _a === void 0 ? void 0 : _a.started());
1516
+ };
1517
+ /**
1518
+ * returns a boolean indicating whether the toolbar loaded
1519
+ * @param toolbarParams
1520
+ */
1521
+ PostHog.prototype.loadToolbar = function (params) {
1522
+ return this.toolbar.loadToolbar(params);
1523
+ };
1524
+ /**
1525
+ * returns the current config object for the library.
1526
+ */
1527
+ PostHog.prototype.get_config = function (prop_name) {
1528
+ var _a;
1529
+ return (_a = this.config) === null || _a === void 0 ? void 0 : _a[prop_name];
1530
+ };
1531
+ /**
1532
+ * Returns the value of the super property named property_name. If no such
1533
+ * property is set, get_property() will return the undefined value.
1534
+ *
1535
+ * ### Notes:
1536
+ *
1537
+ * get_property() can only be called after the PostHog library has finished loading.
1538
+ * init() has a loaded function available to handle this automatically. For example:
1539
+ *
1540
+ * // grab value for '$user_id' after the posthog library has loaded
1541
+ * posthog.init('YOUR PROJECT TOKEN', {
1542
+ * loaded: function(posthog) {
1543
+ * user_id = posthog.get_property('$user_id');
1544
+ * }
1545
+ * });
1546
+ *
1547
+ * @param {String} property_name The name of the super property you want to retrieve
1548
+ */
1549
+ PostHog.prototype.get_property = function (property_name) {
1550
+ return this.persistence['props'][property_name];
1551
+ };
1552
+ /**
1553
+ * Returns the value of the session super property named property_name. If no such
1554
+ * property is set, getSessionProperty() will return the undefined value.
1555
+ *
1556
+ * ### Notes:
1557
+ *
1558
+ * This is based on browser-level `sessionStorage`, NOT the PostHog session.
1559
+ * getSessionProperty() can only be called after the PostHog library has finished loading.
1560
+ * init() has a loaded function available to handle this automatically. For example:
1561
+ *
1562
+ * // grab value for 'user_id' after the posthog library has loaded
1563
+ * posthog.init('YOUR PROJECT TOKEN', {
1564
+ * loaded: function(posthog) {
1565
+ * user_id = posthog.getSessionProperty('user_id');
1566
+ * }
1567
+ * });
1568
+ *
1569
+ * @param {String} property_name The name of the session super property you want to retrieve
1570
+ */
1571
+ PostHog.prototype.getSessionProperty = function (property_name) {
1572
+ return this.sessionPersistence['props'][property_name];
1573
+ };
1574
+ PostHog.prototype.toString = function () {
1575
+ var _a;
1576
+ var name = (_a = this.get_config('name')) !== null && _a !== void 0 ? _a : PRIMARY_INSTANCE_NAME;
1577
+ if (name !== PRIMARY_INSTANCE_NAME) {
1578
+ name = PRIMARY_INSTANCE_NAME + '.' + name;
1579
+ }
1580
+ return name;
1581
+ };
1582
+ // perform some housekeeping around GDPR opt-in/out state
1583
+ PostHog.prototype._gdpr_init = function () {
1584
+ var is_localStorage_requested = this.get_config('opt_out_capturing_persistence_type') === 'localStorage';
1585
+ // try to convert opt-in/out cookies to localStorage if possible
1586
+ if (is_localStorage_requested && localStore.is_supported()) {
1587
+ if (!this.has_opted_in_capturing() && this.has_opted_in_capturing({ persistence_type: 'cookie' })) {
1588
+ this.opt_in_capturing({ enable_persistence: false });
1589
+ }
1590
+ if (!this.has_opted_out_capturing() && this.has_opted_out_capturing({ persistence_type: 'cookie' })) {
1591
+ this.opt_out_capturing({ clear_persistence: false });
1592
+ }
1593
+ this.clear_opt_in_out_capturing({
1594
+ persistence_type: 'cookie',
1595
+ enable_persistence: false,
1596
+ });
1597
+ }
1598
+ // check whether the user has already opted out - if so, clear & disable persistence
1599
+ if (this.has_opted_out_capturing()) {
1600
+ this._gdpr_update_persistence({ clear_persistence: true });
1601
+ // check whether we should opt out by default
1602
+ // note: we don't clear persistence here by default since opt-out default state is often
1603
+ // used as an initial state while GDPR information is being collected
1604
+ }
1605
+ else if (!this.has_opted_in_capturing() &&
1606
+ (this.get_config('opt_out_capturing_by_default') || cookieStore.get('ph_optout'))) {
1607
+ cookieStore.remove('ph_optout');
1608
+ this.opt_out_capturing({
1609
+ clear_persistence: this.get_config('opt_out_persistence_by_default'),
1610
+ });
1611
+ }
1612
+ };
1613
+ /**
1614
+ * Enable or disable persistence based on options
1615
+ * only enable/disable if persistence is not already in this state
1616
+ * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it
1617
+ * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence
1618
+ */
1619
+ PostHog.prototype._gdpr_update_persistence = function (options) {
1620
+ var disabled;
1621
+ if (options && options['clear_persistence']) {
1622
+ disabled = true;
1623
+ }
1624
+ else if (options && options['enable_persistence']) {
1625
+ disabled = false;
1626
+ }
1627
+ else {
1628
+ return;
1629
+ }
1630
+ if (!this.get_config('disable_persistence') && this.persistence.disabled !== disabled) {
1631
+ this.persistence.set_disabled(disabled);
1632
+ }
1633
+ if (!this.get_config('disable_persistence') && this.sessionPersistence.disabled !== disabled) {
1634
+ this.sessionPersistence.set_disabled(disabled);
1635
+ }
1636
+ };
1637
+ // call a base gdpr function after constructing the appropriate token and options args
1638
+ PostHog.prototype._gdpr_call_func = function (func, options) {
1639
+ options = _extend({
1640
+ capture: this.capture.bind(this),
1641
+ persistence_type: this.get_config('opt_out_capturing_persistence_type'),
1642
+ cookie_prefix: this.get_config('opt_out_capturing_cookie_prefix'),
1643
+ cookie_expiration: this.get_config('cookie_expiration'),
1644
+ cross_subdomain_cookie: this.get_config('cross_subdomain_cookie'),
1645
+ secure_cookie: this.get_config('secure_cookie'),
1646
+ }, options || {});
1647
+ // check if localStorage can be used for recording opt out status, fall back to cookie if not
1648
+ if (!localStore.is_supported() && options['persistence_type'] === 'localStorage') {
1649
+ options['persistence_type'] = 'cookie';
1650
+ }
1651
+ return func(this.get_config('token'), {
1652
+ capture: options['capture'],
1653
+ captureEventName: options['capture_event_name'],
1654
+ captureProperties: options['capture_properties'],
1655
+ persistenceType: options['persistence_type'],
1656
+ persistencePrefix: options['cookie_prefix'],
1657
+ cookieExpiration: options['cookie_expiration'],
1658
+ crossSubdomainCookie: options['cross_subdomain_cookie'],
1659
+ secureCookie: options['secure_cookie'],
1660
+ });
1661
+ };
1662
+ /**
1663
+ * Opt the user in to data capturing and cookies/localstorage for this PostHog instance
1664
+ *
1665
+ * ### Usage
1666
+ *
1667
+ * // opt user in
1668
+ * posthog.opt_in_capturing();
1669
+ *
1670
+ * // opt user in with specific event name, properties, cookie configuration
1671
+ * posthog.opt_in_capturing({
1672
+ * capture_event_name: 'User opted in',
1673
+ * capture_event_properties: {
1674
+ * 'Email': 'jdoe@example.com'
1675
+ * },
1676
+ * cookie_expiration: 30,
1677
+ * secure_cookie: true
1678
+ * });
1679
+ *
1680
+ * @param {Object} [options] A dictionary of config options to override
1681
+ * @param {function} [options.capture] Function used for capturing a PostHog event to record the opt-in action (default is this PostHog instance's capture method)
1682
+ * @param {string} [options.capture_event_name=$opt_in] Event name to be used for capturing the opt-in action
1683
+ * @param {Object} [options.capture_properties] Set of properties to be captured along with the opt-in action
1684
+ * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
1685
+ * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
1686
+ * @param {string} [options.cookie_prefix=__ph_opt_in_out] Custom prefix to be used in the cookie/localstorage name
1687
+ * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this PostHog instance's config)
1688
+ * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this PostHog instance's config)
1689
+ * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this PostHog instance's config)
1690
+ */
1691
+ PostHog.prototype.opt_in_capturing = function (options) {
1692
+ options = _extend({
1693
+ enable_persistence: true,
1694
+ }, options || {});
1695
+ this._gdpr_call_func(optIn, options);
1696
+ this._gdpr_update_persistence(options);
1697
+ };
1698
+ /**
1699
+ * Opt the user out of data capturing and cookies/localstorage for this PostHog instance
1700
+ *
1701
+ * ### Usage
1702
+ *
1703
+ * // opt user out
1704
+ * posthog.opt_out_capturing();
1705
+ *
1706
+ * // opt user out with different cookie configuration from PostHog instance
1707
+ * posthog.opt_out_capturing({
1708
+ * cookie_expiration: 30,
1709
+ * secure_cookie: true
1710
+ * });
1711
+ *
1712
+ * @param {Object} [options] A dictionary of config options to override
1713
+ * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence
1714
+ * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
1715
+ * @param {string} [options.cookie_prefix=__ph_opt_in_out] Custom prefix to be used in the cookie/localstorage name
1716
+ * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this PostHog instance's config)
1717
+ * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this PostHog instance's config)
1718
+ * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this PostHog instance's config)
1719
+ */
1720
+ PostHog.prototype.opt_out_capturing = function (options) {
1721
+ var _options = _extend({
1722
+ clear_persistence: true,
1723
+ }, options || {});
1724
+ this._gdpr_call_func(optOut, _options);
1725
+ this._gdpr_update_persistence(_options);
1726
+ };
1727
+ /**
1728
+ * Check whether the user has opted in to data capturing and cookies/localstorage for this PostHog instance
1729
+ *
1730
+ * ### Usage
1731
+ *
1732
+ * const has_opted_in = posthog.has_opted_in_capturing();
1733
+ * // use has_opted_in value
1734
+ *
1735
+ * @param {Object} [options] A dictionary of config options to override
1736
+ * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
1737
+ * @param {string} [options.cookie_prefix=__ph_opt_in_out] Custom prefix to be used in the cookie/localstorage name
1738
+ * @returns {boolean} current opt-in status
1739
+ */
1740
+ PostHog.prototype.has_opted_in_capturing = function (options) {
1741
+ return this._gdpr_call_func(hasOptedIn, options);
1742
+ };
1743
+ /**
1744
+ * Check whether the user has opted out of data capturing and cookies/localstorage for this PostHog instance
1745
+ *
1746
+ * ### Usage
1747
+ *
1748
+ * const has_opted_out = posthog.has_opted_out_capturing();
1749
+ * // use has_opted_out value
1750
+ *
1751
+ * @param {Object} [options] A dictionary of config options to override
1752
+ * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
1753
+ * @param {string} [options.cookie_prefix=__ph_opt_in_out] Custom prefix to be used in the cookie/localstorage name
1754
+ * @returns {boolean} current opt-out status
1755
+ */
1756
+ PostHog.prototype.has_opted_out_capturing = function (options) {
1757
+ return this._gdpr_call_func(hasOptedOut, options);
1758
+ };
1759
+ /**
1760
+ * Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance
1761
+ *
1762
+ * ### Usage
1763
+ *
1764
+ * // clear user's opt-in/out status
1765
+ * posthog.clear_opt_in_out_capturing();
1766
+ *
1767
+ * // clear user's opt-in/out status with specific cookie configuration - should match
1768
+ * // configuration used when opt_in_capturing/opt_out_capturing methods were called.
1769
+ * posthog.clear_opt_in_out_capturing({
1770
+ * cookie_expiration: 30,
1771
+ * secure_cookie: true
1772
+ * });
1773
+ *
1774
+ * @param {Object} [options] A dictionary of config options to override
1775
+ * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
1776
+ * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
1777
+ * @param {string} [options.cookie_prefix=__ph_opt_in_out] Custom prefix to be used in the cookie/localstorage name
1778
+ * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this PostHog instance's config)
1779
+ * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this PostHog instance's config)
1780
+ * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this PostHog instance's config)
1781
+ */
1782
+ PostHog.prototype.clear_opt_in_out_capturing = function (options) {
1783
+ var _options = _extend({
1784
+ enable_persistence: true,
1785
+ }, options !== null && options !== void 0 ? options : {});
1786
+ this._gdpr_call_func(clearOptInOut, _options);
1787
+ this._gdpr_update_persistence(_options);
1788
+ };
1789
+ PostHog.prototype.debug = function (debug) {
1790
+ if (debug === false) {
1791
+ window.console.log("You've disabled debug mode.");
1792
+ localStorage && localStorage.removeItem('ph_debug');
1793
+ this.set_config({ debug: false });
1794
+ }
1795
+ else {
1796
+ window.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`.");
1797
+ localStorage && localStorage.setItem('ph_debug', 'true');
1798
+ this.set_config({ debug: true });
1799
+ }
1800
+ };
1801
+ return PostHog;
1802
+ }());
1803
+ export { PostHog };
1804
+ _safewrap_class(PostHog, ['identify']);
1805
+ var instances = {};
1806
+ var extend_mp = function () {
1807
+ // add all the sub posthog instances
1808
+ _each(instances, function (instance, name) {
1809
+ if (name !== PRIMARY_INSTANCE_NAME) {
1810
+ posthog_master[name] = instance;
1811
+ }
1812
+ });
1813
+ };
1814
+ var override_ph_init_func = function () {
1815
+ // we override the snippets init function to handle the case where a
1816
+ // user initializes the posthog library after the script loads & runs
1817
+ posthog_master['init'] = function (token, config, name) {
1818
+ if (name) {
1819
+ // initialize a sub library
1820
+ if (!posthog_master[name]) {
1821
+ posthog_master[name] = instances[name] = create_phlib(token || '', config || {}, name, function (instance) {
1822
+ posthog_master[name] = instances[name] = instance;
1823
+ instance._loaded();
1824
+ });
1825
+ }
1826
+ return posthog_master[name];
1827
+ }
1828
+ else {
1829
+ var instance = posthog_master;
1830
+ if (instances[PRIMARY_INSTANCE_NAME]) {
1831
+ // main posthog lib already initialized
1832
+ instance = instances[PRIMARY_INSTANCE_NAME];
1833
+ }
1834
+ else if (token) {
1835
+ // intialize the main posthog lib
1836
+ instance = create_phlib(token, config || {}, PRIMARY_INSTANCE_NAME, function (instance) {
1837
+ instances[PRIMARY_INSTANCE_NAME] = instance;
1838
+ instance._loaded();
1839
+ });
1840
+ instances[PRIMARY_INSTANCE_NAME] = instance;
1841
+ }
1842
+ ;
1843
+ posthog_master = instance;
1844
+ if (init_type === InitType.INIT_SNIPPET) {
1845
+ ;
1846
+ window[PRIMARY_INSTANCE_NAME] = posthog_master;
1847
+ }
1848
+ extend_mp();
1849
+ return instance;
1850
+ }
1851
+ };
1852
+ };
1853
+ var add_dom_loaded_handler = function () {
1854
+ // Cross browser DOM Loaded support
1855
+ function dom_loaded_handler() {
1856
+ // function flag since we only want to execute this once
1857
+ if (dom_loaded_handler.done) {
1858
+ return;
1859
+ }
1860
+ ;
1861
+ dom_loaded_handler.done = true;
1862
+ ENQUEUE_REQUESTS = false;
1863
+ _each(instances, function (inst) {
1864
+ inst._dom_loaded();
1865
+ });
1866
+ }
1867
+ if (document.addEventListener) {
1868
+ if (document.readyState === 'complete') {
1869
+ // safari 4 can fire the DOMContentLoaded event before loading all
1870
+ // external JS (including this file). you will see some copypasta
1871
+ // on the internet that checks for 'complete' and 'loaded', but
1872
+ // 'loaded' is an IE thing
1873
+ dom_loaded_handler();
1874
+ }
1875
+ else {
1876
+ document.addEventListener('DOMContentLoaded', dom_loaded_handler, false);
1877
+ }
1878
+ }
1879
+ // fallback handler, always will work
1880
+ _register_event(window, 'load', dom_loaded_handler, true);
1881
+ };
1882
+ export function init_from_snippet() {
1883
+ init_type = InitType.INIT_SNIPPET;
1884
+ if (_isUndefined(window.posthog)) {
1885
+ ;
1886
+ window.posthog = [];
1887
+ }
1888
+ posthog_master = window.posthog;
1889
+ if (posthog_master['__loaded'] || (posthog_master['config'] && posthog_master['persistence'])) {
1890
+ // lib has already been loaded at least once; we don't want to override the global object this time so bomb early
1891
+ console.error('PostHog library has already been downloaded at least once.');
1892
+ return;
1893
+ }
1894
+ // Load instances of the PostHog Library
1895
+ _each(posthog_master['_i'], function (item) {
1896
+ if (item && _isArray(item)) {
1897
+ instances[item[2]] = create_phlib.apply(void 0, __spreadArray([], __read(item), false));
1898
+ }
1899
+ });
1900
+ override_ph_init_func();
1901
+ posthog_master['init']();
1902
+ // Fire loaded events after updating the window's posthog object
1903
+ _each(instances, function (instance) {
1904
+ instance._loaded();
1905
+ });
1906
+ add_dom_loaded_handler();
1907
+ }
1908
+ export function init_as_module() {
1909
+ init_type = InitType.INIT_MODULE;
1910
+ posthog_master = new PostHog();
1911
+ override_ph_init_func();
1912
+ posthog_master['init']();
1913
+ add_dom_loaded_handler();
1914
+ return posthog_master;
1915
+ }
1916
+ //# sourceMappingURL=posthog-core.js.map