@leanbase-giangnd/js 0.0.7 → 0.1.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.
- package/dist/index.cjs +2791 -265
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +5439 -172
- package/dist/index.mjs +2792 -266
- package/dist/index.mjs.map +1 -1
- package/dist/leanbase.iife.js +3427 -276
- package/dist/leanbase.iife.js.map +1 -1
- package/package.json +6 -5
- package/src/extensions/replay/extension-shim.ts +35 -0
- package/src/extensions/replay/external/config.ts +33 -25
- package/src/extensions/replay/external/lazy-loaded-session-recorder.ts +78 -71
- package/src/extensions/replay/external/mutation-throttler.ts +4 -1
- package/src/extensions/replay/external/network-plugin.ts +10 -3
- package/src/extensions/replay/external/triggerMatching.ts +13 -13
- package/src/extensions/replay/rrweb-plugins/patch.ts +0 -7
- package/src/extensions/replay/session-recording.ts +29 -58
- package/src/leanbase.ts +35 -48
- package/src/types/fflate.d.ts +5 -0
- package/src/types/rrweb-record.d.ts +8 -0
- package/src/types.ts +130 -117
- package/src/utils/logger.ts +13 -51
- package/src/version.ts +1 -1
- package/src/extensions/replay/external/README.md +0 -5
- package/src/extensions/utils/stylesheet-loader.ts +0 -27
- package/src/posthog-core.ts +0 -12
- package/src/utils/globals.ts +0 -239
- package/src/utils/request-router.ts +0 -77
- package/src/utils/type-utils.ts +0 -139
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var core = require('@posthog/core');
|
|
4
|
+
var record = require('@rrweb/record');
|
|
5
|
+
var fflate = require('fflate');
|
|
4
6
|
|
|
5
7
|
const breaker = {};
|
|
6
8
|
const ArrayProto = Array.prototype;
|
|
@@ -10,7 +12,7 @@ const win = typeof window !== 'undefined' ? window : undefined;
|
|
|
10
12
|
const global = typeof globalThis !== 'undefined' ? globalThis : win;
|
|
11
13
|
const navigator$1 = global?.navigator;
|
|
12
14
|
const document = global?.document;
|
|
13
|
-
const location = global?.location;
|
|
15
|
+
const location$1 = global?.location;
|
|
14
16
|
global?.fetch;
|
|
15
17
|
global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined;
|
|
16
18
|
global?.AbortController;
|
|
@@ -197,10 +199,13 @@ const EVENT_TIMERS_KEY = '__timers';
|
|
|
197
199
|
const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side';
|
|
198
200
|
const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side';
|
|
199
201
|
const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules';
|
|
202
|
+
const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config';
|
|
200
203
|
// @deprecated can be removed along with eager loaded replay
|
|
201
204
|
const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side';
|
|
202
205
|
const SESSION_ID = '$sesid';
|
|
203
206
|
const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled';
|
|
207
|
+
const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session';
|
|
208
|
+
const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session';
|
|
204
209
|
const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags';
|
|
205
210
|
const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features';
|
|
206
211
|
const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details';
|
|
@@ -225,7 +230,7 @@ core.PostHogPersistedProperty.Queue, core.PostHogPersistedProperty.FeatureFlagDe
|
|
|
225
230
|
|
|
226
231
|
/* eslint-disable no-console */
|
|
227
232
|
const PREFIX = '[Leanbase]';
|
|
228
|
-
const logger = {
|
|
233
|
+
const logger$3 = {
|
|
229
234
|
info: (...args) => {
|
|
230
235
|
if (typeof console !== 'undefined') {
|
|
231
236
|
console.log(PREFIX, ...args);
|
|
@@ -523,7 +528,7 @@ function chooseCookieDomain(hostname, cross_subdomain) {
|
|
|
523
528
|
if (!matchedSubDomain) {
|
|
524
529
|
const originalMatch = originalCookieDomainFn(hostname);
|
|
525
530
|
if (originalMatch !== matchedSubDomain) {
|
|
526
|
-
logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
|
|
531
|
+
logger$3.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
|
|
527
532
|
}
|
|
528
533
|
matchedSubDomain = originalMatch;
|
|
529
534
|
}
|
|
@@ -535,7 +540,7 @@ function chooseCookieDomain(hostname, cross_subdomain) {
|
|
|
535
540
|
const cookieStore = {
|
|
536
541
|
_is_supported: () => !!document,
|
|
537
542
|
_error: function (msg) {
|
|
538
|
-
logger.error('cookieStore error: ' + msg);
|
|
543
|
+
logger$3.error('cookieStore error: ' + msg);
|
|
539
544
|
},
|
|
540
545
|
_get: function (name) {
|
|
541
546
|
if (!document) {
|
|
@@ -584,7 +589,7 @@ const cookieStore = {
|
|
|
584
589
|
const new_cookie_val = name + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; SameSite=Lax; path=/' + cdomain + secure;
|
|
585
590
|
// 4096 bytes is the size at which some browsers (e.g. firefox) will not store a cookie, warn slightly before that
|
|
586
591
|
if (new_cookie_val.length > 4096 * 0.9) {
|
|
587
|
-
logger.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length);
|
|
592
|
+
logger$3.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length);
|
|
588
593
|
}
|
|
589
594
|
document.cookie = new_cookie_val;
|
|
590
595
|
return new_cookie_val;
|
|
@@ -626,13 +631,13 @@ const localStore = {
|
|
|
626
631
|
supported = false;
|
|
627
632
|
}
|
|
628
633
|
if (!supported) {
|
|
629
|
-
logger.error('localStorage unsupported; falling back to cookie store');
|
|
634
|
+
logger$3.error('localStorage unsupported; falling back to cookie store');
|
|
630
635
|
}
|
|
631
636
|
_localStorage_supported = supported;
|
|
632
637
|
return supported;
|
|
633
638
|
},
|
|
634
639
|
_error: function (msg) {
|
|
635
|
-
logger.error('localStorage error: ' + msg);
|
|
640
|
+
logger$3.error('localStorage error: ' + msg);
|
|
636
641
|
},
|
|
637
642
|
_get: function (name) {
|
|
638
643
|
try {
|
|
@@ -718,7 +723,7 @@ const memoryStore = {
|
|
|
718
723
|
return true;
|
|
719
724
|
},
|
|
720
725
|
_error: function (msg) {
|
|
721
|
-
logger.error('memoryStorage error: ' + msg);
|
|
726
|
+
logger$3.error('memoryStorage error: ' + msg);
|
|
722
727
|
},
|
|
723
728
|
_get: function (name) {
|
|
724
729
|
return memoryStorage[name] || null;
|
|
@@ -759,7 +764,7 @@ const sessionStore = {
|
|
|
759
764
|
return sessionStorageSupported;
|
|
760
765
|
},
|
|
761
766
|
_error: function (msg) {
|
|
762
|
-
logger.error('sessionStorage error: ', msg);
|
|
767
|
+
logger$3.error('sessionStorage error: ', msg);
|
|
763
768
|
},
|
|
764
769
|
_get: function (name) {
|
|
765
770
|
try {
|
|
@@ -793,6 +798,7 @@ const sessionStore = {
|
|
|
793
798
|
}
|
|
794
799
|
};
|
|
795
800
|
|
|
801
|
+
const localDomains = ['localhost', '127.0.0.1'];
|
|
796
802
|
/**
|
|
797
803
|
* IE11 doesn't support `new URL`
|
|
798
804
|
* so we can create an anchor element and use that to parse the URL
|
|
@@ -807,6 +813,21 @@ const convertToURL = url => {
|
|
|
807
813
|
location.href = url;
|
|
808
814
|
return location;
|
|
809
815
|
};
|
|
816
|
+
const formDataToQuery = function (formdata, arg_separator = '&') {
|
|
817
|
+
let use_val;
|
|
818
|
+
let use_key;
|
|
819
|
+
const tph_arr = [];
|
|
820
|
+
each(formdata, function (val, key) {
|
|
821
|
+
// the key might be literally the string undefined for e.g. if {undefined: 'something'}
|
|
822
|
+
if (core.isUndefined(val) || core.isUndefined(key) || key === 'undefined') {
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
use_val = encodeURIComponent(core.isFile(val) ? val.name : val.toString());
|
|
826
|
+
use_key = encodeURIComponent(key);
|
|
827
|
+
tph_arr[tph_arr.length] = use_key + '=' + use_val;
|
|
828
|
+
});
|
|
829
|
+
return tph_arr.join(arg_separator);
|
|
830
|
+
};
|
|
810
831
|
// NOTE: Once we get rid of IE11/op_mini we can start using URLSearchParams
|
|
811
832
|
const getQueryParam = function (url, param) {
|
|
812
833
|
const withoutHash = url.split('#')[0] || '';
|
|
@@ -830,7 +851,7 @@ const getQueryParam = function (url, param) {
|
|
|
830
851
|
try {
|
|
831
852
|
result = decodeURIComponent(result);
|
|
832
853
|
} catch {
|
|
833
|
-
logger.error('Skipping decoding for malformed query param: ' + result);
|
|
854
|
+
logger$3.error('Skipping decoding for malformed query param: ' + result);
|
|
834
855
|
}
|
|
835
856
|
return result.replace(/\+/g, ' ');
|
|
836
857
|
}
|
|
@@ -869,6 +890,9 @@ const maskQueryParams = function (url, maskedParams, mask) {
|
|
|
869
890
|
}
|
|
870
891
|
return result;
|
|
871
892
|
};
|
|
893
|
+
const isLocalhost = () => {
|
|
894
|
+
return localDomains.includes(location.hostname);
|
|
895
|
+
};
|
|
872
896
|
|
|
873
897
|
/**
|
|
874
898
|
* this device detection code is (at time of writing) about 3% of the size of the entire library
|
|
@@ -1161,7 +1185,7 @@ const detectDeviceType = function (user_agent) {
|
|
|
1161
1185
|
}
|
|
1162
1186
|
};
|
|
1163
1187
|
|
|
1164
|
-
var version = "0.
|
|
1188
|
+
var version = "0.1.1";
|
|
1165
1189
|
var packageInfo = {
|
|
1166
1190
|
version: version};
|
|
1167
1191
|
|
|
@@ -1311,7 +1335,7 @@ function getReferrerInfo() {
|
|
|
1311
1335
|
}
|
|
1312
1336
|
function getPersonInfo(maskPersonalDataProperties, customPersonalDataProperties) {
|
|
1313
1337
|
const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
|
|
1314
|
-
const url = location?.href.substring(0, 1000);
|
|
1338
|
+
const url = location$1?.href.substring(0, 1000);
|
|
1315
1339
|
// we're being a bit more economical with bytes here because this is stored in the cookie
|
|
1316
1340
|
return {
|
|
1317
1341
|
r: getReferrer().substring(0, 1000),
|
|
@@ -1379,9 +1403,9 @@ function getEventProperties(maskPersonalDataProperties, customPersonalDataProper
|
|
|
1379
1403
|
$timezone: getTimezone(),
|
|
1380
1404
|
$timezone_offset: getTimezoneOffset()
|
|
1381
1405
|
}), {
|
|
1382
|
-
$current_url: maskQueryParams(location?.href, paramsToMask, MASKED),
|
|
1383
|
-
$host: location?.host,
|
|
1384
|
-
$pathname: location?.pathname,
|
|
1406
|
+
$current_url: maskQueryParams(location$1?.href, paramsToMask, MASKED),
|
|
1407
|
+
$host: location$1?.host,
|
|
1408
|
+
$pathname: location$1?.pathname,
|
|
1385
1409
|
$raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,
|
|
1386
1410
|
$browser_version: detectBrowserVersion(userAgent, navigator.vendor),
|
|
1387
1411
|
$browser_language: getBrowserLanguage(),
|
|
@@ -1426,7 +1450,7 @@ class LeanbasePersistence {
|
|
|
1426
1450
|
this._storage = this._buildStorage(config);
|
|
1427
1451
|
this.load();
|
|
1428
1452
|
if (config.debug) {
|
|
1429
|
-
logger.info('Persistence loaded', config['persistence'], {
|
|
1453
|
+
logger$3.info('Persistence loaded', config['persistence'], {
|
|
1430
1454
|
...this.props
|
|
1431
1455
|
});
|
|
1432
1456
|
}
|
|
@@ -1442,7 +1466,7 @@ class LeanbasePersistence {
|
|
|
1442
1466
|
}
|
|
1443
1467
|
_buildStorage(config) {
|
|
1444
1468
|
if (CASE_INSENSITIVE_PERSISTENCE_TYPES.indexOf(config['persistence'].toLowerCase()) === -1) {
|
|
1445
|
-
logger.info('Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie');
|
|
1469
|
+
logger$3.info('Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie');
|
|
1446
1470
|
config['persistence'] = 'localStorage+cookie';
|
|
1447
1471
|
}
|
|
1448
1472
|
let store;
|
|
@@ -2078,7 +2102,7 @@ function getNestedSpanText(target) {
|
|
|
2078
2102
|
text = `${text} ${getNestedSpanText(child)}`.trim();
|
|
2079
2103
|
}
|
|
2080
2104
|
} catch (e) {
|
|
2081
|
-
logger.error('[AutoCapture]', e);
|
|
2105
|
+
logger$3.error('[AutoCapture]', e);
|
|
2082
2106
|
}
|
|
2083
2107
|
}
|
|
2084
2108
|
});
|
|
@@ -2380,7 +2404,7 @@ class Autocapture {
|
|
|
2380
2404
|
}
|
|
2381
2405
|
_addDomEventHandlers() {
|
|
2382
2406
|
if (!this.isBrowserSupported()) {
|
|
2383
|
-
logger.info('Disabling Automatic Event Collection because this browser is not supported');
|
|
2407
|
+
logger$3.info('Disabling Automatic Event Collection because this browser is not supported');
|
|
2384
2408
|
return;
|
|
2385
2409
|
}
|
|
2386
2410
|
if (!win || !document) {
|
|
@@ -2391,7 +2415,7 @@ class Autocapture {
|
|
|
2391
2415
|
try {
|
|
2392
2416
|
this._captureEvent(e);
|
|
2393
2417
|
} catch (error) {
|
|
2394
|
-
logger.error('Failed to capture event', error);
|
|
2418
|
+
logger$3.error('Failed to capture event', error);
|
|
2395
2419
|
}
|
|
2396
2420
|
};
|
|
2397
2421
|
addEventListener(document, 'submit', handler, {
|
|
@@ -2576,7 +2600,7 @@ class SessionIdManager {
|
|
|
2576
2600
|
this._windowIdGenerator = windowIdGenerator || uuidv7;
|
|
2577
2601
|
const persistenceName = this._config['persistence_name'] || this._config['token'];
|
|
2578
2602
|
const desiredTimeout = this._config['session_idle_timeout_seconds'] || DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS;
|
|
2579
|
-
this._sessionTimeoutMs = core.clampToRange(desiredTimeout, MIN_SESSION_IDLE_TIMEOUT_SECONDS, MAX_SESSION_IDLE_TIMEOUT_SECONDS, logger, DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS) * 1000;
|
|
2603
|
+
this._sessionTimeoutMs = core.clampToRange(desiredTimeout, MIN_SESSION_IDLE_TIMEOUT_SECONDS, MAX_SESSION_IDLE_TIMEOUT_SECONDS, logger$3, DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS) * 1000;
|
|
2580
2604
|
instance.register({
|
|
2581
2605
|
$configured_session_timeout_ms: this._sessionTimeoutMs
|
|
2582
2606
|
});
|
|
@@ -2603,7 +2627,7 @@ class SessionIdManager {
|
|
|
2603
2627
|
const sessionStartTimestamp = uuid7ToTimestampMs(this._config.bootstrap.sessionID);
|
|
2604
2628
|
this._setSessionId(this._config.bootstrap.sessionID, new Date().getTime(), sessionStartTimestamp);
|
|
2605
2629
|
} catch (e) {
|
|
2606
|
-
logger.error('Invalid sessionID in bootstrap', e);
|
|
2630
|
+
logger$3.error('Invalid sessionID in bootstrap', e);
|
|
2607
2631
|
}
|
|
2608
2632
|
}
|
|
2609
2633
|
this._listenToReloadWindow();
|
|
@@ -2744,7 +2768,7 @@ class SessionIdManager {
|
|
|
2744
2768
|
if (noSessionId || activityTimeout || sessionPastMaximumLength) {
|
|
2745
2769
|
sessionId = this._sessionIdGenerator();
|
|
2746
2770
|
windowId = this._windowIdGenerator();
|
|
2747
|
-
logger.info('new session ID generated', {
|
|
2771
|
+
logger$3.info('new session ID generated', {
|
|
2748
2772
|
sessionId,
|
|
2749
2773
|
windowId,
|
|
2750
2774
|
changeReason: {
|
|
@@ -2873,67 +2897,6 @@ class SessionPropsManager {
|
|
|
2873
2897
|
}
|
|
2874
2898
|
}
|
|
2875
2899
|
|
|
2876
|
-
var RequestRouterRegion;
|
|
2877
|
-
(function (RequestRouterRegion) {
|
|
2878
|
-
RequestRouterRegion["US"] = "us";
|
|
2879
|
-
RequestRouterRegion["EU"] = "eu";
|
|
2880
|
-
RequestRouterRegion["CUSTOM"] = "custom";
|
|
2881
|
-
})(RequestRouterRegion || (RequestRouterRegion = {}));
|
|
2882
|
-
const ingestionDomain = 'i.posthog.com';
|
|
2883
|
-
class RequestRouter {
|
|
2884
|
-
constructor(instance) {
|
|
2885
|
-
this._regionCache = {};
|
|
2886
|
-
this.instance = instance;
|
|
2887
|
-
}
|
|
2888
|
-
get apiHost() {
|
|
2889
|
-
const host = this.instance.config.api_host.trim().replace(/\/$/, '');
|
|
2890
|
-
if (host === 'https://app.posthog.com') {
|
|
2891
|
-
return 'https://us.i.posthog.com';
|
|
2892
|
-
}
|
|
2893
|
-
return host;
|
|
2894
|
-
}
|
|
2895
|
-
get uiHost() {
|
|
2896
|
-
let host = this.instance.config.ui_host?.replace(/\/$/, '');
|
|
2897
|
-
if (!host) {
|
|
2898
|
-
host = this.apiHost.replace(`.${ingestionDomain}`, '.posthog.com');
|
|
2899
|
-
}
|
|
2900
|
-
if (host === 'https://app.posthog.com') {
|
|
2901
|
-
return 'https://us.posthog.com';
|
|
2902
|
-
}
|
|
2903
|
-
return host;
|
|
2904
|
-
}
|
|
2905
|
-
get region() {
|
|
2906
|
-
if (!this._regionCache[this.apiHost]) {
|
|
2907
|
-
if (/https:\/\/(app|us|us-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)) {
|
|
2908
|
-
this._regionCache[this.apiHost] = RequestRouterRegion.US;
|
|
2909
|
-
} else if (/https:\/\/(eu|eu-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)) {
|
|
2910
|
-
this._regionCache[this.apiHost] = RequestRouterRegion.EU;
|
|
2911
|
-
} else {
|
|
2912
|
-
this._regionCache[this.apiHost] = RequestRouterRegion.CUSTOM;
|
|
2913
|
-
}
|
|
2914
|
-
}
|
|
2915
|
-
return this._regionCache[this.apiHost];
|
|
2916
|
-
}
|
|
2917
|
-
endpointFor(target, path = '') {
|
|
2918
|
-
if (path) {
|
|
2919
|
-
path = path[0] === '/' ? path : `/${path}`;
|
|
2920
|
-
}
|
|
2921
|
-
if (target === 'ui') {
|
|
2922
|
-
return this.uiHost + path;
|
|
2923
|
-
}
|
|
2924
|
-
if (this.region === RequestRouterRegion.CUSTOM) {
|
|
2925
|
-
return this.apiHost + path;
|
|
2926
|
-
}
|
|
2927
|
-
const suffix = ingestionDomain + path;
|
|
2928
|
-
switch (target) {
|
|
2929
|
-
case 'assets':
|
|
2930
|
-
return `https://${this.region}-assets.${suffix}`;
|
|
2931
|
-
case 'api':
|
|
2932
|
-
return `https://${this.region}.${suffix}`;
|
|
2933
|
-
}
|
|
2934
|
-
}
|
|
2935
|
-
}
|
|
2936
|
-
|
|
2937
2900
|
// This keeps track of the PageView state (such as the previous PageView's path, timestamp, id, and scroll properties).
|
|
2938
2901
|
// We store the state in memory, which means that for non-SPA sites, the state will be lost on page reload. This means
|
|
2939
2902
|
// that non-SPA sites should always send a $pageleave event on any navigation, before the page unloads. For SPA sites,
|
|
@@ -2994,10 +2957,10 @@ class PageViewManager {
|
|
|
2994
2957
|
lastContentY = Math.ceil(lastContentY);
|
|
2995
2958
|
maxContentY = Math.ceil(maxContentY);
|
|
2996
2959
|
// if the maximum scroll height is near 0, then the percentage is 1
|
|
2997
|
-
const lastScrollPercentage = maxScrollHeight <= 1 ? 1 : core.clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger);
|
|
2998
|
-
const maxScrollPercentage = maxScrollHeight <= 1 ? 1 : core.clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger);
|
|
2999
|
-
const lastContentPercentage = maxContentHeight <= 1 ? 1 : core.clampToRange(lastContentY / maxContentHeight, 0, 1, logger);
|
|
3000
|
-
const maxContentPercentage = maxContentHeight <= 1 ? 1 : core.clampToRange(maxContentY / maxContentHeight, 0, 1, logger);
|
|
2960
|
+
const lastScrollPercentage = maxScrollHeight <= 1 ? 1 : core.clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger$3);
|
|
2961
|
+
const maxScrollPercentage = maxScrollHeight <= 1 ? 1 : core.clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger$3);
|
|
2962
|
+
const lastContentPercentage = maxContentHeight <= 1 ? 1 : core.clampToRange(lastContentY / maxContentHeight, 0, 1, logger$3);
|
|
2963
|
+
const maxContentPercentage = maxContentHeight <= 1 ? 1 : core.clampToRange(maxContentY / maxContentHeight, 0, 1, logger$3);
|
|
3001
2964
|
properties = extend(properties, {
|
|
3002
2965
|
$prev_pageview_last_scroll: lastScrollY,
|
|
3003
2966
|
$prev_pageview_last_scroll_percentage: lastScrollPercentage,
|
|
@@ -3160,206 +3123,2762 @@ const isLikelyBot = function (navigator, customBlockedUserAgents) {
|
|
|
3160
3123
|
// It would be very bad if posthog-js caused a permission prompt to appear on every page load.
|
|
3161
3124
|
};
|
|
3162
3125
|
|
|
3163
|
-
const
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
save_campaign_params: true,
|
|
3185
|
-
save_referrer: true,
|
|
3186
|
-
opt_out_useragent_filter: false,
|
|
3187
|
-
properties_string_max_length: 65535,
|
|
3188
|
-
loaded: () => {},
|
|
3189
|
-
session_recording: {}
|
|
3190
|
-
});
|
|
3191
|
-
class Leanbase extends core.PostHogCore {
|
|
3192
|
-
constructor(token, config) {
|
|
3193
|
-
const mergedConfig = extend(defaultConfig(), config || {}, {
|
|
3194
|
-
token
|
|
3195
|
-
});
|
|
3196
|
-
super(token, mergedConfig);
|
|
3197
|
-
this.personProcessingSetOncePropertiesSent = false;
|
|
3198
|
-
this.isLoaded = false;
|
|
3199
|
-
this.config = mergedConfig;
|
|
3200
|
-
this.visibilityStateListener = null;
|
|
3201
|
-
this.initialPageviewCaptured = false;
|
|
3202
|
-
this.scrollManager = new ScrollManager(this);
|
|
3203
|
-
this.pageViewManager = new PageViewManager(this);
|
|
3204
|
-
this.requestRouter = new RequestRouter(this);
|
|
3205
|
-
this.init(token, mergedConfig);
|
|
3206
|
-
}
|
|
3207
|
-
init(token, config) {
|
|
3208
|
-
this.setConfig(extend(defaultConfig(), config, {
|
|
3209
|
-
token
|
|
3210
|
-
}));
|
|
3211
|
-
this.isLoaded = true;
|
|
3212
|
-
this.persistence = new LeanbasePersistence(this.config);
|
|
3213
|
-
this.replayAutocapture = new Autocapture(this);
|
|
3214
|
-
this.replayAutocapture.startIfEnabled();
|
|
3215
|
-
// Initialize session manager and props before session recording (matches browser behavior)
|
|
3216
|
-
if (this.config.cookieless_mode !== 'always') {
|
|
3217
|
-
if (!this.sessionManager) {
|
|
3218
|
-
this.sessionManager = new SessionIdManager(this);
|
|
3219
|
-
this.sessionPropsManager = new SessionPropsManager(this, this.sessionManager, this.persistence);
|
|
3220
|
-
}
|
|
3221
|
-
// runtime require to lazy-load replay code; allowed for browser parity
|
|
3222
|
-
// @ts-expect-error - runtime import only available in browser build
|
|
3223
|
-
const {
|
|
3224
|
-
SessionRecording
|
|
3225
|
-
} = require('./extensions/replay/session-recording'); // eslint-disable-line @typescript-eslint/no-require-imports
|
|
3226
|
-
this.sessionRecording = new SessionRecording(this);
|
|
3227
|
-
this.sessionRecording.startIfEnabledOrStop();
|
|
3228
|
-
}
|
|
3229
|
-
if (this.config.preloadFeatureFlags !== false) {
|
|
3230
|
-
this.reloadFeatureFlags();
|
|
3126
|
+
const _createLogger = prefix => {
|
|
3127
|
+
return {
|
|
3128
|
+
info: (...args) => logger$3.info(prefix, ...args),
|
|
3129
|
+
warn: (...args) => logger$3.warn(prefix, ...args),
|
|
3130
|
+
error: (...args) => logger$3.error(prefix, ...args),
|
|
3131
|
+
critical: (...args) => logger$3.critical(prefix, ...args),
|
|
3132
|
+
uninitializedWarning: methodName => {
|
|
3133
|
+
logger$3.error(prefix, `You must initialize Leanbase before calling ${methodName}`);
|
|
3134
|
+
},
|
|
3135
|
+
createLogger: additionalPrefix => _createLogger(`${prefix} ${additionalPrefix}`)
|
|
3136
|
+
};
|
|
3137
|
+
};
|
|
3138
|
+
const logger$2 = _createLogger('[Leanbase]');
|
|
3139
|
+
const createLogger = _createLogger;
|
|
3140
|
+
|
|
3141
|
+
function patch(source, name, replacement) {
|
|
3142
|
+
try {
|
|
3143
|
+
if (!(name in source)) {
|
|
3144
|
+
return () => {
|
|
3145
|
+
//
|
|
3146
|
+
};
|
|
3231
3147
|
}
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3148
|
+
const original = source[name];
|
|
3149
|
+
const wrapped = replacement(original);
|
|
3150
|
+
if (core.isFunction(wrapped)) {
|
|
3151
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
3152
|
+
wrapped.prototype = wrapped.prototype || {};
|
|
3153
|
+
Object.defineProperties(wrapped, {
|
|
3154
|
+
__posthog_wrapped__: {
|
|
3155
|
+
enumerable: false,
|
|
3156
|
+
value: true
|
|
3237
3157
|
}
|
|
3238
|
-
}
|
|
3158
|
+
});
|
|
3239
3159
|
}
|
|
3240
|
-
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3160
|
+
source[name] = wrapped;
|
|
3161
|
+
return () => {
|
|
3162
|
+
source[name] = original;
|
|
3163
|
+
};
|
|
3164
|
+
} catch {
|
|
3165
|
+
return () => {
|
|
3166
|
+
//
|
|
3167
|
+
};
|
|
3246
3168
|
}
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
if (
|
|
3252
|
-
|
|
3253
|
-
this.visibilityStateListener = this.captureInitialPageview.bind(this);
|
|
3254
|
-
addEventListener(document, 'visibilitychange', this.visibilityStateListener);
|
|
3255
|
-
}
|
|
3256
|
-
return;
|
|
3169
|
+
}
|
|
3170
|
+
|
|
3171
|
+
function hostnameFromURL(url) {
|
|
3172
|
+
try {
|
|
3173
|
+
if (typeof url === 'string') {
|
|
3174
|
+
return new URL(url).hostname;
|
|
3257
3175
|
}
|
|
3258
|
-
if (
|
|
3259
|
-
|
|
3260
|
-
this.capture('$pageview', {
|
|
3261
|
-
title: document.title
|
|
3262
|
-
});
|
|
3263
|
-
if (this.visibilityStateListener) {
|
|
3264
|
-
document.removeEventListener('visibilitychange', this.visibilityStateListener);
|
|
3265
|
-
this.visibilityStateListener = null;
|
|
3266
|
-
}
|
|
3176
|
+
if ('url' in url) {
|
|
3177
|
+
return new URL(url.url).hostname;
|
|
3267
3178
|
}
|
|
3179
|
+
return url.hostname;
|
|
3180
|
+
} catch {
|
|
3181
|
+
return null;
|
|
3268
3182
|
}
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3183
|
+
}
|
|
3184
|
+
function isHostOnDenyList(url, options) {
|
|
3185
|
+
const hostname = hostnameFromURL(url);
|
|
3186
|
+
const defaultNotDenied = {
|
|
3187
|
+
hostname,
|
|
3188
|
+
isHostDenied: false
|
|
3189
|
+
};
|
|
3190
|
+
if (!options.payloadHostDenyList?.length || !hostname?.trim().length) {
|
|
3191
|
+
return defaultNotDenied;
|
|
3192
|
+
}
|
|
3193
|
+
for (const deny of options.payloadHostDenyList) {
|
|
3194
|
+
if (hostname.endsWith(deny)) {
|
|
3195
|
+
return {
|
|
3196
|
+
hostname,
|
|
3197
|
+
isHostDenied: true
|
|
3198
|
+
};
|
|
3276
3199
|
}
|
|
3277
3200
|
}
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3201
|
+
return defaultNotDenied;
|
|
3202
|
+
}
|
|
3203
|
+
|
|
3204
|
+
const LOGGER_PREFIX$2 = '[SessionRecording]';
|
|
3205
|
+
const REDACTED = 'redacted';
|
|
3206
|
+
const defaultNetworkOptions = {
|
|
3207
|
+
initiatorTypes: ['audio', 'beacon', 'body', 'css', 'early-hints', 'embed', 'fetch', 'frame', 'iframe', 'image', 'img', 'input', 'link', 'navigation', 'object', 'ping', 'script', 'track', 'video', 'xmlhttprequest'],
|
|
3208
|
+
maskRequestFn: data => data,
|
|
3209
|
+
recordHeaders: false,
|
|
3210
|
+
recordBody: false,
|
|
3211
|
+
recordInitialRequests: false,
|
|
3212
|
+
recordPerformance: false,
|
|
3213
|
+
performanceEntryTypeToObserve: [
|
|
3214
|
+
// 'event', // This is too noisy as it covers all browser events
|
|
3215
|
+
'first-input',
|
|
3216
|
+
// 'mark', // Mark is used too liberally. We would need to filter for specific marks
|
|
3217
|
+
// 'measure', // Measure is used too liberally. We would need to filter for specific measures
|
|
3218
|
+
'navigation', 'paint', 'resource'],
|
|
3219
|
+
payloadSizeLimitBytes: 1000000,
|
|
3220
|
+
payloadHostDenyList: ['.lr-ingest.io', '.ingest.sentry.io', '.clarity.ms',
|
|
3221
|
+
// NB no leading dot here
|
|
3222
|
+
'analytics.google.com', 'bam.nr-data.net']
|
|
3223
|
+
};
|
|
3224
|
+
const HEADER_DENY_LIST = ['authorization', 'x-forwarded-for', 'authorization', 'cookie', 'set-cookie', 'x-api-key', 'x-real-ip', 'remote-addr', 'forwarded', 'proxy-authorization', 'x-csrf-token', 'x-csrftoken', 'x-xsrf-token'];
|
|
3225
|
+
const PAYLOAD_CONTENT_DENY_LIST = ['password', 'secret', 'passwd', 'api_key', 'apikey', 'auth', 'credentials', 'mysql_pwd', 'privatekey', 'private_key', 'token'];
|
|
3226
|
+
// we always remove headers on the deny list because we never want to capture this sensitive data
|
|
3227
|
+
const removeAuthorizationHeader = data => {
|
|
3228
|
+
const headers = data.requestHeaders;
|
|
3229
|
+
if (!core.isNullish(headers)) {
|
|
3230
|
+
const mutableHeaders = core.isArray(headers) ? Object.fromEntries(headers) : headers;
|
|
3231
|
+
each(Object.keys(mutableHeaders ?? {}), header => {
|
|
3232
|
+
if (HEADER_DENY_LIST.includes(header.toLowerCase())) {
|
|
3233
|
+
mutableHeaders[header] = REDACTED;
|
|
3283
3234
|
}
|
|
3284
|
-
}
|
|
3235
|
+
});
|
|
3236
|
+
data.requestHeaders = mutableHeaders;
|
|
3285
3237
|
}
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3238
|
+
return data;
|
|
3239
|
+
};
|
|
3240
|
+
const POSTHOG_PATHS_TO_IGNORE = ['/s/', '/e/', '/i/'];
|
|
3241
|
+
// want to ignore posthog paths when capturing requests, or we can get trapped in a loop
|
|
3242
|
+
// because calls to PostHog would be reported using a call to PostHog which would be reported....
|
|
3243
|
+
const ignorePostHogPaths = (data, apiHostConfig) => {
|
|
3244
|
+
const url = convertToURL(data.name);
|
|
3245
|
+
const host = apiHostConfig || '';
|
|
3246
|
+
let replaceValue = host.indexOf('http') === 0 ? convertToURL(host)?.pathname : host;
|
|
3247
|
+
if (replaceValue === '/') {
|
|
3248
|
+
replaceValue = '';
|
|
3249
|
+
}
|
|
3250
|
+
const pathname = url?.pathname.replace(replaceValue || '', '');
|
|
3251
|
+
if (url && pathname && POSTHOG_PATHS_TO_IGNORE.some(path => pathname.indexOf(path) === 0)) {
|
|
3252
|
+
return undefined;
|
|
3295
3253
|
}
|
|
3296
|
-
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3254
|
+
return data;
|
|
3255
|
+
};
|
|
3256
|
+
function estimateBytes(payload) {
|
|
3257
|
+
return new Blob([payload]).size;
|
|
3258
|
+
}
|
|
3259
|
+
function enforcePayloadSizeLimit(payload, headers, limit, description) {
|
|
3260
|
+
if (core.isNullish(payload)) {
|
|
3261
|
+
return payload;
|
|
3262
|
+
}
|
|
3263
|
+
let requestContentLength = headers?.['content-length'] || estimateBytes(payload);
|
|
3264
|
+
if (core.isString(requestContentLength)) {
|
|
3265
|
+
requestContentLength = parseInt(requestContentLength);
|
|
3266
|
+
}
|
|
3267
|
+
if (requestContentLength > limit) {
|
|
3268
|
+
return LOGGER_PREFIX$2 + ` ${description} body too large to record (${requestContentLength} bytes)`;
|
|
3269
|
+
}
|
|
3270
|
+
return payload;
|
|
3271
|
+
}
|
|
3272
|
+
// people can have arbitrarily large payloads on their site, but we don't want to ingest them
|
|
3273
|
+
const limitPayloadSize = options => {
|
|
3274
|
+
// the smallest of 1MB or the specified limit if there is one
|
|
3275
|
+
const limit = Math.min(1000000, options.payloadSizeLimitBytes ?? 1000000);
|
|
3276
|
+
return data => {
|
|
3277
|
+
if (data?.requestBody) {
|
|
3278
|
+
data.requestBody = enforcePayloadSizeLimit(data.requestBody, data.requestHeaders, limit, 'Request');
|
|
3279
|
+
}
|
|
3280
|
+
if (data?.responseBody) {
|
|
3281
|
+
data.responseBody = enforcePayloadSizeLimit(data.responseBody, data.responseHeaders, limit, 'Response');
|
|
3282
|
+
}
|
|
3283
|
+
return data;
|
|
3284
|
+
};
|
|
3285
|
+
};
|
|
3286
|
+
function scrubPayload(payload, label) {
|
|
3287
|
+
if (core.isNullish(payload)) {
|
|
3288
|
+
return payload;
|
|
3289
|
+
}
|
|
3290
|
+
let scrubbed = payload;
|
|
3291
|
+
if (!shouldCaptureValue(scrubbed, false)) {
|
|
3292
|
+
scrubbed = LOGGER_PREFIX$2 + ' ' + label + ' body ' + REDACTED;
|
|
3293
|
+
}
|
|
3294
|
+
each(PAYLOAD_CONTENT_DENY_LIST, text => {
|
|
3295
|
+
if (scrubbed?.length && scrubbed?.indexOf(text) !== -1) {
|
|
3296
|
+
scrubbed = LOGGER_PREFIX$2 + ' ' + label + ' body ' + REDACTED + ' as might contain: ' + text;
|
|
3300
3297
|
}
|
|
3301
|
-
|
|
3298
|
+
});
|
|
3299
|
+
return scrubbed;
|
|
3300
|
+
}
|
|
3301
|
+
function scrubPayloads(capturedRequest) {
|
|
3302
|
+
if (core.isUndefined(capturedRequest)) {
|
|
3303
|
+
return undefined;
|
|
3302
3304
|
}
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3305
|
+
capturedRequest.requestBody = scrubPayload(capturedRequest.requestBody, 'Request');
|
|
3306
|
+
capturedRequest.responseBody = scrubPayload(capturedRequest.responseBody, 'Response');
|
|
3307
|
+
return capturedRequest;
|
|
3308
|
+
}
|
|
3309
|
+
/**
|
|
3310
|
+
* whether a maskRequestFn is provided or not,
|
|
3311
|
+
* we ensure that we remove the denied header from requests
|
|
3312
|
+
* we _never_ want to record that header by accident
|
|
3313
|
+
* if someone complains then we'll add an opt-in to let them override it
|
|
3314
|
+
*/
|
|
3315
|
+
const buildNetworkRequestOptions = (instanceConfig, remoteNetworkOptions = {}) => {
|
|
3316
|
+
const remoteOptions = remoteNetworkOptions || {};
|
|
3317
|
+
const config = {
|
|
3318
|
+
payloadSizeLimitBytes: defaultNetworkOptions.payloadSizeLimitBytes,
|
|
3319
|
+
performanceEntryTypeToObserve: [...defaultNetworkOptions.performanceEntryTypeToObserve],
|
|
3320
|
+
payloadHostDenyList: [...(remoteOptions.payloadHostDenyList || []), ...defaultNetworkOptions.payloadHostDenyList]
|
|
3321
|
+
};
|
|
3322
|
+
// client can always disable despite remote options
|
|
3323
|
+
const sessionRecordingConfig = instanceConfig.session_recording || {};
|
|
3324
|
+
const capturePerformanceConfig = instanceConfig.capture_performance;
|
|
3325
|
+
const userPerformanceOptIn = core.isBoolean(capturePerformanceConfig) ? capturePerformanceConfig : !!capturePerformanceConfig?.network_timing;
|
|
3326
|
+
const canRecordHeaders = sessionRecordingConfig.recordHeaders === true && !!remoteOptions.recordHeaders;
|
|
3327
|
+
const canRecordBody = sessionRecordingConfig.recordBody === true && !!remoteOptions.recordBody;
|
|
3328
|
+
const canRecordPerformance = userPerformanceOptIn && !!remoteOptions.recordPerformance;
|
|
3329
|
+
const payloadLimiter = limitPayloadSize(config);
|
|
3330
|
+
const enforcedCleaningFn = d => payloadLimiter(ignorePostHogPaths(removeAuthorizationHeader(d), instanceConfig.host || ''));
|
|
3331
|
+
const hasDeprecatedMaskFunction = core.isFunction(sessionRecordingConfig.maskNetworkRequestFn);
|
|
3332
|
+
if (hasDeprecatedMaskFunction && core.isFunction(sessionRecordingConfig.maskCapturedNetworkRequestFn)) {
|
|
3333
|
+
logger$2.warn('Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored.');
|
|
3334
|
+
}
|
|
3335
|
+
if (hasDeprecatedMaskFunction) {
|
|
3336
|
+
sessionRecordingConfig.maskCapturedNetworkRequestFn = data => {
|
|
3337
|
+
const cleanedURL = sessionRecordingConfig.maskNetworkRequestFn({
|
|
3338
|
+
url: data.name
|
|
3339
|
+
});
|
|
3340
|
+
return {
|
|
3341
|
+
...data,
|
|
3342
|
+
name: cleanedURL?.url
|
|
3343
|
+
};
|
|
3306
3344
|
};
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3345
|
+
}
|
|
3346
|
+
config.maskRequestFn = core.isFunction(sessionRecordingConfig.maskCapturedNetworkRequestFn) ? data => {
|
|
3347
|
+
const cleanedRequest = enforcedCleaningFn(data);
|
|
3348
|
+
return cleanedRequest ? sessionRecordingConfig.maskCapturedNetworkRequestFn?.(cleanedRequest) ?? undefined : undefined;
|
|
3349
|
+
} : data => scrubPayloads(enforcedCleaningFn(data));
|
|
3350
|
+
return {
|
|
3351
|
+
...defaultNetworkOptions,
|
|
3352
|
+
...config,
|
|
3353
|
+
recordHeaders: canRecordHeaders,
|
|
3354
|
+
recordBody: canRecordBody,
|
|
3355
|
+
recordPerformance: canRecordPerformance,
|
|
3356
|
+
recordInitialRequests: canRecordPerformance
|
|
3357
|
+
};
|
|
3358
|
+
};
|
|
3359
|
+
|
|
3360
|
+
/// <reference lib="dom" />
|
|
3361
|
+
const logger$1 = createLogger('[Recorder]');
|
|
3362
|
+
const isNavigationTiming = entry => entry.entryType === 'navigation';
|
|
3363
|
+
const isResourceTiming = entry => entry.entryType === 'resource';
|
|
3364
|
+
function findLast(array, predicate) {
|
|
3365
|
+
const length = array.length;
|
|
3366
|
+
for (let i = length - 1; i >= 0; i -= 1) {
|
|
3367
|
+
if (predicate(array[i])) {
|
|
3368
|
+
return array[i];
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
return undefined;
|
|
3372
|
+
}
|
|
3373
|
+
function isDocument(value) {
|
|
3374
|
+
return !!value && typeof value === 'object' && 'nodeType' in value && value.nodeType === 9;
|
|
3375
|
+
}
|
|
3376
|
+
function initPerformanceObserver(cb, win, options) {
|
|
3377
|
+
// if we are only observing timings then we could have a single observer for all types, with buffer true,
|
|
3378
|
+
// but we are going to filter by initiatorType _if we are wrapping fetch and xhr as the wrapped functions
|
|
3379
|
+
// will deal with those.
|
|
3380
|
+
// so we have a block which captures requests from before fetch/xhr is wrapped
|
|
3381
|
+
// these are marked `isInitial` so playback can display them differently if needed
|
|
3382
|
+
// they will never have method/status/headers/body because they are pre-wrapping that provides that
|
|
3383
|
+
if (options.recordInitialRequests) {
|
|
3384
|
+
const initialPerformanceEntries = win.performance.getEntries().filter(entry => isNavigationTiming(entry) || isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType));
|
|
3385
|
+
cb({
|
|
3386
|
+
requests: initialPerformanceEntries.flatMap(entry => prepareRequest({
|
|
3387
|
+
entry,
|
|
3388
|
+
method: undefined,
|
|
3389
|
+
status: undefined,
|
|
3390
|
+
networkRequest: {},
|
|
3391
|
+
isInitial: true
|
|
3392
|
+
})),
|
|
3393
|
+
isInitial: true
|
|
3316
3394
|
});
|
|
3317
3395
|
}
|
|
3318
|
-
|
|
3319
|
-
|
|
3396
|
+
const observer = new win.PerformanceObserver(entries => {
|
|
3397
|
+
// if recordBody or recordHeaders is true then we don't want to record fetch or xhr here
|
|
3398
|
+
// as the wrapped functions will do that. Otherwise, this filter becomes a noop
|
|
3399
|
+
// because we do want to record them here
|
|
3400
|
+
const wrappedInitiatorFilter = entry => options.recordBody || options.recordHeaders ? entry.initiatorType !== 'xmlhttprequest' && entry.initiatorType !== 'fetch' : true;
|
|
3401
|
+
const performanceEntries = entries.getEntries().filter(entry => isNavigationTiming(entry) || isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType) &&
|
|
3402
|
+
// TODO if we are _only_ capturing timing we don't want to filter initiator here
|
|
3403
|
+
wrappedInitiatorFilter(entry));
|
|
3404
|
+
cb({
|
|
3405
|
+
requests: performanceEntries.flatMap(entry => prepareRequest({
|
|
3406
|
+
entry,
|
|
3407
|
+
method: undefined,
|
|
3408
|
+
status: undefined,
|
|
3409
|
+
networkRequest: {}
|
|
3410
|
+
}))
|
|
3411
|
+
});
|
|
3412
|
+
});
|
|
3413
|
+
// compat checked earlier
|
|
3414
|
+
// eslint-disable-next-line compat/compat
|
|
3415
|
+
const entryTypes = PerformanceObserver.supportedEntryTypes.filter(x => options.performanceEntryTypeToObserve.includes(x));
|
|
3416
|
+
// initial records are gathered above, so we don't need to observe and buffer each type separately
|
|
3417
|
+
observer.observe({
|
|
3418
|
+
entryTypes
|
|
3419
|
+
});
|
|
3420
|
+
return () => {
|
|
3421
|
+
observer.disconnect();
|
|
3422
|
+
};
|
|
3423
|
+
}
|
|
3424
|
+
function shouldRecordHeaders(type, recordHeaders) {
|
|
3425
|
+
return !!recordHeaders && (core.isBoolean(recordHeaders) || recordHeaders[type]);
|
|
3426
|
+
}
|
|
3427
|
+
function shouldRecordBody({
|
|
3428
|
+
type,
|
|
3429
|
+
recordBody,
|
|
3430
|
+
headers,
|
|
3431
|
+
url
|
|
3432
|
+
}) {
|
|
3433
|
+
function matchesContentType(contentTypes) {
|
|
3434
|
+
const contentTypeHeader = Object.keys(headers).find(key => key.toLowerCase() === 'content-type');
|
|
3435
|
+
const contentType = contentTypeHeader && headers[contentTypeHeader];
|
|
3436
|
+
return contentTypes.some(ct => contentType?.includes(ct));
|
|
3320
3437
|
}
|
|
3321
|
-
|
|
3322
|
-
|
|
3438
|
+
/**
|
|
3439
|
+
* particularly in canvas applications we see many requests to blob URLs
|
|
3440
|
+
* e.g. blob:https://video_url
|
|
3441
|
+
* these blob/object URLs are local to the browser, we can never capture that body
|
|
3442
|
+
* so we can just return false here
|
|
3443
|
+
*/
|
|
3444
|
+
function isBlobURL(url) {
|
|
3445
|
+
try {
|
|
3446
|
+
if (typeof url === 'string') {
|
|
3447
|
+
return url.startsWith('blob:');
|
|
3448
|
+
}
|
|
3449
|
+
if (url instanceof URL) {
|
|
3450
|
+
return url.protocol === 'blob:';
|
|
3451
|
+
}
|
|
3452
|
+
if (url instanceof Request) {
|
|
3453
|
+
return isBlobURL(url.url);
|
|
3454
|
+
}
|
|
3455
|
+
return false;
|
|
3456
|
+
} catch {
|
|
3457
|
+
return false;
|
|
3458
|
+
}
|
|
3323
3459
|
}
|
|
3324
|
-
|
|
3325
|
-
|
|
3460
|
+
if (!recordBody) return false;
|
|
3461
|
+
if (isBlobURL(url)) return false;
|
|
3462
|
+
if (core.isBoolean(recordBody)) return true;
|
|
3463
|
+
if (core.isArray(recordBody)) return matchesContentType(recordBody);
|
|
3464
|
+
const recordBodyType = recordBody[type];
|
|
3465
|
+
if (core.isBoolean(recordBodyType)) return recordBodyType;
|
|
3466
|
+
return matchesContentType(recordBodyType);
|
|
3467
|
+
}
|
|
3468
|
+
async function getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt = 0) {
|
|
3469
|
+
if (attempt > 10) {
|
|
3470
|
+
logger$1.warn('Failed to get performance entry for request', {
|
|
3471
|
+
url,
|
|
3472
|
+
initiatorType
|
|
3473
|
+
});
|
|
3474
|
+
return null;
|
|
3326
3475
|
}
|
|
3327
|
-
|
|
3328
|
-
|
|
3476
|
+
const urlPerformanceEntries = win.performance.getEntriesByName(url);
|
|
3477
|
+
const performanceEntry = findLast(urlPerformanceEntries, entry => isResourceTiming(entry) && entry.initiatorType === initiatorType && (core.isUndefined(start) || entry.startTime >= start) && (core.isUndefined(end) || entry.startTime <= end));
|
|
3478
|
+
if (!performanceEntry) {
|
|
3479
|
+
await new Promise(resolve => setTimeout(resolve, 50 * attempt));
|
|
3480
|
+
return getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt + 1);
|
|
3329
3481
|
}
|
|
3330
|
-
|
|
3331
|
-
|
|
3482
|
+
return performanceEntry;
|
|
3483
|
+
}
|
|
3484
|
+
/**
|
|
3485
|
+
* According to MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response
|
|
3486
|
+
* xhr response is typed as any but can be an ArrayBuffer, a Blob, a Document, a JavaScript object,
|
|
3487
|
+
* or a string, depending on the value of XMLHttpRequest.responseType, that contains the response entity body.
|
|
3488
|
+
*
|
|
3489
|
+
* XHR request body is Document | XMLHttpRequestBodyInit | null | undefined
|
|
3490
|
+
*/
|
|
3491
|
+
function _tryReadXHRBody({
|
|
3492
|
+
body,
|
|
3493
|
+
options,
|
|
3494
|
+
url
|
|
3495
|
+
}) {
|
|
3496
|
+
if (core.isNullish(body)) {
|
|
3497
|
+
return null;
|
|
3332
3498
|
}
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3499
|
+
const {
|
|
3500
|
+
hostname,
|
|
3501
|
+
isHostDenied
|
|
3502
|
+
} = isHostOnDenyList(url, options);
|
|
3503
|
+
if (isHostDenied) {
|
|
3504
|
+
return hostname + ' is in deny list';
|
|
3336
3505
|
}
|
|
3337
|
-
|
|
3338
|
-
|
|
3506
|
+
if (core.isString(body)) {
|
|
3507
|
+
return body;
|
|
3339
3508
|
}
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
if (core.isFunction(this.registerForSession)) {
|
|
3343
|
-
this.registerForSession(properties);
|
|
3344
|
-
return;
|
|
3345
|
-
}
|
|
3346
|
-
// fallback: store properties in sessionPersistence
|
|
3347
|
-
if (this.sessionPersistence) {
|
|
3348
|
-
Object.keys(properties).forEach(k => this.sessionPersistence?.set_property(k, properties[k]));
|
|
3349
|
-
}
|
|
3509
|
+
if (isDocument(body)) {
|
|
3510
|
+
return body.textContent;
|
|
3350
3511
|
}
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
this.unregisterForSession(property);
|
|
3354
|
-
return;
|
|
3355
|
-
}
|
|
3356
|
-
if (this.sessionPersistence) {
|
|
3357
|
-
this.sessionPersistence.set_property(property, null);
|
|
3358
|
-
}
|
|
3512
|
+
if (core.isFormData(body)) {
|
|
3513
|
+
return formDataToQuery(body);
|
|
3359
3514
|
}
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
return
|
|
3515
|
+
if (core.isObject(body)) {
|
|
3516
|
+
try {
|
|
3517
|
+
return JSON.stringify(body);
|
|
3518
|
+
} catch {
|
|
3519
|
+
return '[SessionReplay] Failed to stringify response object';
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
return '[SessionReplay] Cannot read body of type ' + toString.call(body);
|
|
3523
|
+
}
|
|
3524
|
+
function initXhrObserver(cb, win, options) {
|
|
3525
|
+
if (!options.initiatorTypes.includes('xmlhttprequest')) {
|
|
3526
|
+
return () => {
|
|
3527
|
+
//
|
|
3528
|
+
};
|
|
3529
|
+
}
|
|
3530
|
+
const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders);
|
|
3531
|
+
const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders);
|
|
3532
|
+
const restorePatch = patch(win.XMLHttpRequest.prototype, 'open',
|
|
3533
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
3534
|
+
// @ts-ignore
|
|
3535
|
+
originalOpen => {
|
|
3536
|
+
return function (method, url, async = true, username, password) {
|
|
3537
|
+
// because this function is returned in its actual context `this` _is_ an XMLHttpRequest
|
|
3538
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
3539
|
+
// @ts-ignore
|
|
3540
|
+
const xhr = this;
|
|
3541
|
+
// check IE earlier than this, we only initialize if Request is present
|
|
3542
|
+
// eslint-disable-next-line compat/compat
|
|
3543
|
+
const req = new Request(url);
|
|
3544
|
+
const networkRequest = {};
|
|
3545
|
+
let start;
|
|
3546
|
+
let end;
|
|
3547
|
+
const requestHeaders = {};
|
|
3548
|
+
const originalSetRequestHeader = xhr.setRequestHeader.bind(xhr);
|
|
3549
|
+
xhr.setRequestHeader = (header, value) => {
|
|
3550
|
+
requestHeaders[header] = value;
|
|
3551
|
+
return originalSetRequestHeader(header, value);
|
|
3552
|
+
};
|
|
3553
|
+
if (recordRequestHeaders) {
|
|
3554
|
+
networkRequest.requestHeaders = requestHeaders;
|
|
3555
|
+
}
|
|
3556
|
+
const originalSend = xhr.send.bind(xhr);
|
|
3557
|
+
xhr.send = body => {
|
|
3558
|
+
if (shouldRecordBody({
|
|
3559
|
+
type: 'request',
|
|
3560
|
+
headers: requestHeaders,
|
|
3561
|
+
url,
|
|
3562
|
+
recordBody: options.recordBody
|
|
3563
|
+
})) {
|
|
3564
|
+
networkRequest.requestBody = _tryReadXHRBody({
|
|
3565
|
+
body,
|
|
3566
|
+
options,
|
|
3567
|
+
url
|
|
3568
|
+
});
|
|
3569
|
+
}
|
|
3570
|
+
start = win.performance.now();
|
|
3571
|
+
return originalSend(body);
|
|
3572
|
+
};
|
|
3573
|
+
const readyStateListener = () => {
|
|
3574
|
+
if (xhr.readyState !== xhr.DONE) {
|
|
3575
|
+
return;
|
|
3576
|
+
}
|
|
3577
|
+
// Clean up the listener immediately when done to prevent memory leaks
|
|
3578
|
+
xhr.removeEventListener('readystatechange', readyStateListener);
|
|
3579
|
+
end = win.performance.now();
|
|
3580
|
+
const responseHeaders = {};
|
|
3581
|
+
const rawHeaders = xhr.getAllResponseHeaders();
|
|
3582
|
+
const headers = rawHeaders.trim().split(/[\r\n]+/);
|
|
3583
|
+
headers.forEach(line => {
|
|
3584
|
+
const parts = line.split(': ');
|
|
3585
|
+
const header = parts.shift();
|
|
3586
|
+
const value = parts.join(': ');
|
|
3587
|
+
if (header) {
|
|
3588
|
+
responseHeaders[header] = value;
|
|
3589
|
+
}
|
|
3590
|
+
});
|
|
3591
|
+
if (recordResponseHeaders) {
|
|
3592
|
+
networkRequest.responseHeaders = responseHeaders;
|
|
3593
|
+
}
|
|
3594
|
+
if (shouldRecordBody({
|
|
3595
|
+
type: 'response',
|
|
3596
|
+
headers: responseHeaders,
|
|
3597
|
+
url,
|
|
3598
|
+
recordBody: options.recordBody
|
|
3599
|
+
})) {
|
|
3600
|
+
networkRequest.responseBody = _tryReadXHRBody({
|
|
3601
|
+
body: xhr.response,
|
|
3602
|
+
options,
|
|
3603
|
+
url
|
|
3604
|
+
});
|
|
3605
|
+
}
|
|
3606
|
+
getRequestPerformanceEntry(win, 'xmlhttprequest', req.url, start, end).then(entry => {
|
|
3607
|
+
const requests = prepareRequest({
|
|
3608
|
+
entry,
|
|
3609
|
+
method: method,
|
|
3610
|
+
status: xhr?.status,
|
|
3611
|
+
networkRequest,
|
|
3612
|
+
start,
|
|
3613
|
+
end,
|
|
3614
|
+
url: url.toString(),
|
|
3615
|
+
initiatorType: 'xmlhttprequest'
|
|
3616
|
+
});
|
|
3617
|
+
cb({
|
|
3618
|
+
requests
|
|
3619
|
+
});
|
|
3620
|
+
}).catch(() => {
|
|
3621
|
+
//
|
|
3622
|
+
});
|
|
3623
|
+
};
|
|
3624
|
+
// This is very tricky code, and making it passive won't bring many performance benefits,
|
|
3625
|
+
// so let's ignore the rule here.
|
|
3626
|
+
// eslint-disable-next-line posthog-js/no-add-event-listener
|
|
3627
|
+
xhr.addEventListener('readystatechange', readyStateListener);
|
|
3628
|
+
originalOpen.call(xhr, method, url, async, username, password);
|
|
3629
|
+
};
|
|
3630
|
+
});
|
|
3631
|
+
return () => {
|
|
3632
|
+
restorePatch();
|
|
3633
|
+
};
|
|
3634
|
+
}
|
|
3635
|
+
/**
|
|
3636
|
+
* Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming
|
|
3637
|
+
* NB PerformanceNavigationTiming extends PerformanceResourceTiming
|
|
3638
|
+
* Here we don't care which interface it implements as both expose `serverTimings`
|
|
3639
|
+
*/
|
|
3640
|
+
const exposesServerTiming = event => !core.isNull(event) && (event.entryType === 'navigation' || event.entryType === 'resource');
|
|
3641
|
+
function prepareRequest({
|
|
3642
|
+
entry,
|
|
3643
|
+
method,
|
|
3644
|
+
status,
|
|
3645
|
+
networkRequest,
|
|
3646
|
+
isInitial,
|
|
3647
|
+
start,
|
|
3648
|
+
end,
|
|
3649
|
+
url,
|
|
3650
|
+
initiatorType
|
|
3651
|
+
}) {
|
|
3652
|
+
start = entry ? entry.startTime : start;
|
|
3653
|
+
end = entry ? entry.responseEnd : end;
|
|
3654
|
+
// kudos to sentry javascript sdk for excellent background on why to use Date.now() here
|
|
3655
|
+
// https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70
|
|
3656
|
+
// can't start observer if performance.now() is not available
|
|
3657
|
+
// eslint-disable-next-line compat/compat
|
|
3658
|
+
const timeOrigin = Math.floor(Date.now() - performance.now());
|
|
3659
|
+
// clickhouse can't ingest timestamps that are floats
|
|
3660
|
+
// (in this case representing fractions of a millisecond we don't care about anyway)
|
|
3661
|
+
// use timeOrigin if we really can't gather a start time
|
|
3662
|
+
const timestamp = Math.floor(timeOrigin + (start || 0));
|
|
3663
|
+
const entryJSON = entry ? entry.toJSON() : {
|
|
3664
|
+
name: url
|
|
3665
|
+
};
|
|
3666
|
+
const requests = [{
|
|
3667
|
+
...entryJSON,
|
|
3668
|
+
startTime: core.isUndefined(start) ? undefined : Math.round(start),
|
|
3669
|
+
endTime: core.isUndefined(end) ? undefined : Math.round(end),
|
|
3670
|
+
timeOrigin,
|
|
3671
|
+
timestamp,
|
|
3672
|
+
method: method,
|
|
3673
|
+
initiatorType: initiatorType ? initiatorType : entry ? entry.initiatorType : undefined,
|
|
3674
|
+
status,
|
|
3675
|
+
requestHeaders: networkRequest.requestHeaders,
|
|
3676
|
+
requestBody: networkRequest.requestBody,
|
|
3677
|
+
responseHeaders: networkRequest.responseHeaders,
|
|
3678
|
+
responseBody: networkRequest.responseBody,
|
|
3679
|
+
isInitial
|
|
3680
|
+
}];
|
|
3681
|
+
if (exposesServerTiming(entry)) {
|
|
3682
|
+
for (const timing of entry.serverTiming || []) {
|
|
3683
|
+
requests.push({
|
|
3684
|
+
timeOrigin,
|
|
3685
|
+
timestamp,
|
|
3686
|
+
startTime: Math.round(entry.startTime),
|
|
3687
|
+
name: timing.name,
|
|
3688
|
+
duration: timing.duration,
|
|
3689
|
+
// the spec has a closed list of possible types
|
|
3690
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType
|
|
3691
|
+
// but, we need to know this was a server timing so that we know to
|
|
3692
|
+
// match it to the appropriate navigation or resource timing
|
|
3693
|
+
// that matching will have to be on timestamp and $current_url
|
|
3694
|
+
entryType: 'serverTiming'
|
|
3695
|
+
});
|
|
3696
|
+
}
|
|
3697
|
+
}
|
|
3698
|
+
return requests;
|
|
3699
|
+
}
|
|
3700
|
+
const contentTypePrefixDenyList = ['video/', 'audio/'];
|
|
3701
|
+
function _checkForCannotReadResponseBody({
|
|
3702
|
+
r,
|
|
3703
|
+
options,
|
|
3704
|
+
url
|
|
3705
|
+
}) {
|
|
3706
|
+
if (r.headers.get('Transfer-Encoding') === 'chunked') {
|
|
3707
|
+
return 'Chunked Transfer-Encoding is not supported';
|
|
3708
|
+
}
|
|
3709
|
+
// `get` and `has` are case-insensitive
|
|
3710
|
+
// but return the header value with the casing that was supplied
|
|
3711
|
+
const contentType = r.headers.get('Content-Type')?.toLowerCase();
|
|
3712
|
+
const contentTypeIsDenied = contentTypePrefixDenyList.some(prefix => contentType?.startsWith(prefix));
|
|
3713
|
+
if (contentType && contentTypeIsDenied) {
|
|
3714
|
+
return `Content-Type ${contentType} is not supported`;
|
|
3715
|
+
}
|
|
3716
|
+
const {
|
|
3717
|
+
hostname,
|
|
3718
|
+
isHostDenied
|
|
3719
|
+
} = isHostOnDenyList(url, options);
|
|
3720
|
+
if (isHostDenied) {
|
|
3721
|
+
return hostname + ' is in deny list';
|
|
3722
|
+
}
|
|
3723
|
+
return null;
|
|
3724
|
+
}
|
|
3725
|
+
function _tryReadBody(r) {
|
|
3726
|
+
// there are now already multiple places where we're using Promise...
|
|
3727
|
+
// eslint-disable-next-line compat/compat
|
|
3728
|
+
return new Promise((resolve, reject) => {
|
|
3729
|
+
const timeout = setTimeout(() => resolve('[SessionReplay] Timeout while trying to read body'), 500);
|
|
3730
|
+
try {
|
|
3731
|
+
r.clone().text().then(txt => resolve(txt), reason => reject(reason)).finally(() => clearTimeout(timeout));
|
|
3732
|
+
} catch {
|
|
3733
|
+
clearTimeout(timeout);
|
|
3734
|
+
resolve('[SessionReplay] Failed to read body');
|
|
3735
|
+
}
|
|
3736
|
+
});
|
|
3737
|
+
}
|
|
3738
|
+
async function _tryReadRequestBody({
|
|
3739
|
+
r,
|
|
3740
|
+
options,
|
|
3741
|
+
url
|
|
3742
|
+
}) {
|
|
3743
|
+
const {
|
|
3744
|
+
hostname,
|
|
3745
|
+
isHostDenied
|
|
3746
|
+
} = isHostOnDenyList(url, options);
|
|
3747
|
+
if (isHostDenied) {
|
|
3748
|
+
return Promise.resolve(hostname + ' is in deny list');
|
|
3749
|
+
}
|
|
3750
|
+
return _tryReadBody(r);
|
|
3751
|
+
}
|
|
3752
|
+
async function _tryReadResponseBody({
|
|
3753
|
+
r,
|
|
3754
|
+
options,
|
|
3755
|
+
url
|
|
3756
|
+
}) {
|
|
3757
|
+
const cannotReadBodyReason = _checkForCannotReadResponseBody({
|
|
3758
|
+
r,
|
|
3759
|
+
options,
|
|
3760
|
+
url
|
|
3761
|
+
});
|
|
3762
|
+
if (!core.isNull(cannotReadBodyReason)) {
|
|
3763
|
+
return Promise.resolve(cannotReadBodyReason);
|
|
3764
|
+
}
|
|
3765
|
+
return _tryReadBody(r);
|
|
3766
|
+
}
|
|
3767
|
+
function initFetchObserver(cb, win, options) {
|
|
3768
|
+
if (!options.initiatorTypes.includes('fetch')) {
|
|
3769
|
+
return () => {
|
|
3770
|
+
//
|
|
3771
|
+
};
|
|
3772
|
+
}
|
|
3773
|
+
const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders);
|
|
3774
|
+
const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders);
|
|
3775
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
3776
|
+
// @ts-ignore
|
|
3777
|
+
const restorePatch = patch(win, 'fetch', originalFetch => {
|
|
3778
|
+
return async function (url, init) {
|
|
3779
|
+
// check IE earlier than this, we only initialize if Request is present
|
|
3780
|
+
// eslint-disable-next-line compat/compat
|
|
3781
|
+
const req = new Request(url, init);
|
|
3782
|
+
let res;
|
|
3783
|
+
const networkRequest = {};
|
|
3784
|
+
let start;
|
|
3785
|
+
let end;
|
|
3786
|
+
try {
|
|
3787
|
+
const requestHeaders = {};
|
|
3788
|
+
req.headers.forEach((value, header) => {
|
|
3789
|
+
requestHeaders[header] = value;
|
|
3790
|
+
});
|
|
3791
|
+
if (recordRequestHeaders) {
|
|
3792
|
+
networkRequest.requestHeaders = requestHeaders;
|
|
3793
|
+
}
|
|
3794
|
+
if (shouldRecordBody({
|
|
3795
|
+
type: 'request',
|
|
3796
|
+
headers: requestHeaders,
|
|
3797
|
+
url,
|
|
3798
|
+
recordBody: options.recordBody
|
|
3799
|
+
})) {
|
|
3800
|
+
networkRequest.requestBody = await _tryReadRequestBody({
|
|
3801
|
+
r: req,
|
|
3802
|
+
options,
|
|
3803
|
+
url
|
|
3804
|
+
});
|
|
3805
|
+
}
|
|
3806
|
+
start = win.performance.now();
|
|
3807
|
+
res = await originalFetch(req);
|
|
3808
|
+
end = win.performance.now();
|
|
3809
|
+
const responseHeaders = {};
|
|
3810
|
+
res.headers.forEach((value, header) => {
|
|
3811
|
+
responseHeaders[header] = value;
|
|
3812
|
+
});
|
|
3813
|
+
if (recordResponseHeaders) {
|
|
3814
|
+
networkRequest.responseHeaders = responseHeaders;
|
|
3815
|
+
}
|
|
3816
|
+
if (shouldRecordBody({
|
|
3817
|
+
type: 'response',
|
|
3818
|
+
headers: responseHeaders,
|
|
3819
|
+
url,
|
|
3820
|
+
recordBody: options.recordBody
|
|
3821
|
+
})) {
|
|
3822
|
+
networkRequest.responseBody = await _tryReadResponseBody({
|
|
3823
|
+
r: res,
|
|
3824
|
+
options,
|
|
3825
|
+
url
|
|
3826
|
+
});
|
|
3827
|
+
}
|
|
3828
|
+
return res;
|
|
3829
|
+
} finally {
|
|
3830
|
+
getRequestPerformanceEntry(win, 'fetch', req.url, start, end).then(entry => {
|
|
3831
|
+
const requests = prepareRequest({
|
|
3832
|
+
entry,
|
|
3833
|
+
method: req.method,
|
|
3834
|
+
status: res?.status,
|
|
3835
|
+
networkRequest,
|
|
3836
|
+
start,
|
|
3837
|
+
end,
|
|
3838
|
+
url: req.url,
|
|
3839
|
+
initiatorType: 'fetch'
|
|
3840
|
+
});
|
|
3841
|
+
cb({
|
|
3842
|
+
requests
|
|
3843
|
+
});
|
|
3844
|
+
}).catch(() => {
|
|
3845
|
+
//
|
|
3846
|
+
});
|
|
3847
|
+
}
|
|
3848
|
+
};
|
|
3849
|
+
});
|
|
3850
|
+
return () => {
|
|
3851
|
+
restorePatch();
|
|
3852
|
+
};
|
|
3853
|
+
}
|
|
3854
|
+
let initialisedHandler = null;
|
|
3855
|
+
function initNetworkObserver(callback, win,
|
|
3856
|
+
// top window or in an iframe
|
|
3857
|
+
options) {
|
|
3858
|
+
if (!('performance' in win)) {
|
|
3859
|
+
return () => {
|
|
3860
|
+
//
|
|
3861
|
+
};
|
|
3862
|
+
}
|
|
3863
|
+
if (initialisedHandler) {
|
|
3864
|
+
logger$1.warn('Network observer already initialised, doing nothing');
|
|
3865
|
+
return () => {
|
|
3866
|
+
// the first caller should already have this handler and will be responsible for teardown
|
|
3867
|
+
};
|
|
3868
|
+
}
|
|
3869
|
+
const networkOptions = options ? Object.assign({}, defaultNetworkOptions, options) : defaultNetworkOptions;
|
|
3870
|
+
const cb = data => {
|
|
3871
|
+
const requests = [];
|
|
3872
|
+
data.requests.forEach(request => {
|
|
3873
|
+
const maskedRequest = networkOptions.maskRequestFn(request);
|
|
3874
|
+
if (maskedRequest) {
|
|
3875
|
+
requests.push(maskedRequest);
|
|
3876
|
+
}
|
|
3877
|
+
});
|
|
3878
|
+
if (requests.length > 0) {
|
|
3879
|
+
callback({
|
|
3880
|
+
...data,
|
|
3881
|
+
requests
|
|
3882
|
+
});
|
|
3883
|
+
}
|
|
3884
|
+
};
|
|
3885
|
+
const performanceObserver = initPerformanceObserver(cb, win, networkOptions);
|
|
3886
|
+
// only wrap fetch and xhr if headers or body are being recorded
|
|
3887
|
+
let xhrObserver = () => {};
|
|
3888
|
+
let fetchObserver = () => {};
|
|
3889
|
+
if (networkOptions.recordHeaders || networkOptions.recordBody) {
|
|
3890
|
+
xhrObserver = initXhrObserver(cb, win, networkOptions);
|
|
3891
|
+
fetchObserver = initFetchObserver(cb, win, networkOptions);
|
|
3892
|
+
}
|
|
3893
|
+
const teardown = () => {
|
|
3894
|
+
performanceObserver();
|
|
3895
|
+
xhrObserver();
|
|
3896
|
+
fetchObserver();
|
|
3897
|
+
// allow future observers to initialize after cleanup
|
|
3898
|
+
initialisedHandler = null;
|
|
3899
|
+
};
|
|
3900
|
+
initialisedHandler = teardown;
|
|
3901
|
+
return teardown;
|
|
3902
|
+
}
|
|
3903
|
+
// use the plugin name so that when this functionality is adopted into rrweb
|
|
3904
|
+
// we can remove this plugin and use the core functionality with the same data
|
|
3905
|
+
const NETWORK_PLUGIN_NAME = 'rrweb/network@1';
|
|
3906
|
+
// TODO how should this be typed?
|
|
3907
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
3908
|
+
// @ts-ignore
|
|
3909
|
+
const getRecordNetworkPlugin = options => {
|
|
3910
|
+
return {
|
|
3911
|
+
name: NETWORK_PLUGIN_NAME,
|
|
3912
|
+
observer: initNetworkObserver,
|
|
3913
|
+
options: options
|
|
3914
|
+
};
|
|
3915
|
+
};
|
|
3916
|
+
// rrweb/networ@1 ends
|
|
3917
|
+
|
|
3918
|
+
// Use a safe global target (prefer `win`, fallback to globalThis)
|
|
3919
|
+
const _target = win ?? globalThis;
|
|
3920
|
+
_target.__PosthogExtensions__ = _target.__PosthogExtensions__ || {};
|
|
3921
|
+
// Expose rrweb.record under the same contract
|
|
3922
|
+
_target.__PosthogExtensions__.rrweb = _target.__PosthogExtensions__.rrweb || {
|
|
3923
|
+
record: record.record
|
|
3924
|
+
};
|
|
3925
|
+
// Provide initSessionRecording if not present — return a new LazyLoadedSessionRecording when called
|
|
3926
|
+
_target.__PosthogExtensions__.initSessionRecording = _target.__PosthogExtensions__.initSessionRecording || (instance => {
|
|
3927
|
+
return new LazyLoadedSessionRecording(instance);
|
|
3928
|
+
});
|
|
3929
|
+
// Provide a no-op loadExternalDependency that calls the callback immediately (since rrweb is bundled)
|
|
3930
|
+
_target.__PosthogExtensions__.loadExternalDependency = _target.__PosthogExtensions__.loadExternalDependency || ((instance, scriptName, cb) => {
|
|
3931
|
+
if (cb) cb(undefined);
|
|
3932
|
+
});
|
|
3933
|
+
// Provide rrwebPlugins object with network plugin factory if not present
|
|
3934
|
+
_target.__PosthogExtensions__.rrwebPlugins = _target.__PosthogExtensions__.rrwebPlugins || {};
|
|
3935
|
+
_target.__PosthogExtensions__.rrwebPlugins.getRecordNetworkPlugin = _target.__PosthogExtensions__.rrwebPlugins.getRecordNetworkPlugin || (() => getRecordNetworkPlugin);
|
|
3936
|
+
|
|
3937
|
+
// Type definitions copied from @rrweb/types@2.0.0-alpha.17 and rrweb-snapshot@2.0.0-alpha.17
|
|
3938
|
+
// Both packages are MIT licensed: https://github.com/rrweb-io/rrweb
|
|
3939
|
+
//
|
|
3940
|
+
// These types are copied here to avoid requiring users to install peer dependencies
|
|
3941
|
+
// solely for TypeScript type information.
|
|
3942
|
+
//
|
|
3943
|
+
// Original sources:
|
|
3944
|
+
// - @rrweb/types: https://github.com/rrweb-io/rrweb/tree/main/packages/@rrweb/types
|
|
3945
|
+
// - rrweb-snapshot: https://github.com/rrweb-io/rrweb/tree/main/packages/rrweb-snapshot
|
|
3946
|
+
var NodeType;
|
|
3947
|
+
(function (NodeType) {
|
|
3948
|
+
NodeType[NodeType["Document"] = 0] = "Document";
|
|
3949
|
+
NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
|
|
3950
|
+
NodeType[NodeType["Element"] = 2] = "Element";
|
|
3951
|
+
NodeType[NodeType["Text"] = 3] = "Text";
|
|
3952
|
+
NodeType[NodeType["CDATA"] = 4] = "CDATA";
|
|
3953
|
+
NodeType[NodeType["Comment"] = 5] = "Comment";
|
|
3954
|
+
})(NodeType || (NodeType = {}));
|
|
3955
|
+
var EventType;
|
|
3956
|
+
(function (EventType) {
|
|
3957
|
+
EventType[EventType["DomContentLoaded"] = 0] = "DomContentLoaded";
|
|
3958
|
+
EventType[EventType["Load"] = 1] = "Load";
|
|
3959
|
+
EventType[EventType["FullSnapshot"] = 2] = "FullSnapshot";
|
|
3960
|
+
EventType[EventType["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
|
|
3961
|
+
EventType[EventType["Meta"] = 4] = "Meta";
|
|
3962
|
+
EventType[EventType["Custom"] = 5] = "Custom";
|
|
3963
|
+
EventType[EventType["Plugin"] = 6] = "Plugin";
|
|
3964
|
+
})(EventType || (EventType = {}));
|
|
3965
|
+
var IncrementalSource;
|
|
3966
|
+
(function (IncrementalSource) {
|
|
3967
|
+
IncrementalSource[IncrementalSource["Mutation"] = 0] = "Mutation";
|
|
3968
|
+
IncrementalSource[IncrementalSource["MouseMove"] = 1] = "MouseMove";
|
|
3969
|
+
IncrementalSource[IncrementalSource["MouseInteraction"] = 2] = "MouseInteraction";
|
|
3970
|
+
IncrementalSource[IncrementalSource["Scroll"] = 3] = "Scroll";
|
|
3971
|
+
IncrementalSource[IncrementalSource["ViewportResize"] = 4] = "ViewportResize";
|
|
3972
|
+
IncrementalSource[IncrementalSource["Input"] = 5] = "Input";
|
|
3973
|
+
IncrementalSource[IncrementalSource["TouchMove"] = 6] = "TouchMove";
|
|
3974
|
+
IncrementalSource[IncrementalSource["MediaInteraction"] = 7] = "MediaInteraction";
|
|
3975
|
+
IncrementalSource[IncrementalSource["StyleSheetRule"] = 8] = "StyleSheetRule";
|
|
3976
|
+
IncrementalSource[IncrementalSource["CanvasMutation"] = 9] = "CanvasMutation";
|
|
3977
|
+
IncrementalSource[IncrementalSource["Font"] = 10] = "Font";
|
|
3978
|
+
IncrementalSource[IncrementalSource["Log"] = 11] = "Log";
|
|
3979
|
+
IncrementalSource[IncrementalSource["Drag"] = 12] = "Drag";
|
|
3980
|
+
IncrementalSource[IncrementalSource["StyleDeclaration"] = 13] = "StyleDeclaration";
|
|
3981
|
+
IncrementalSource[IncrementalSource["Selection"] = 14] = "Selection";
|
|
3982
|
+
IncrementalSource[IncrementalSource["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
|
|
3983
|
+
IncrementalSource[IncrementalSource["CustomElement"] = 16] = "CustomElement";
|
|
3984
|
+
})(IncrementalSource || (IncrementalSource = {}));
|
|
3985
|
+
var MouseInteractions;
|
|
3986
|
+
(function (MouseInteractions) {
|
|
3987
|
+
MouseInteractions[MouseInteractions["MouseUp"] = 0] = "MouseUp";
|
|
3988
|
+
MouseInteractions[MouseInteractions["MouseDown"] = 1] = "MouseDown";
|
|
3989
|
+
MouseInteractions[MouseInteractions["Click"] = 2] = "Click";
|
|
3990
|
+
MouseInteractions[MouseInteractions["ContextMenu"] = 3] = "ContextMenu";
|
|
3991
|
+
MouseInteractions[MouseInteractions["DblClick"] = 4] = "DblClick";
|
|
3992
|
+
MouseInteractions[MouseInteractions["Focus"] = 5] = "Focus";
|
|
3993
|
+
MouseInteractions[MouseInteractions["Blur"] = 6] = "Blur";
|
|
3994
|
+
MouseInteractions[MouseInteractions["TouchStart"] = 7] = "TouchStart";
|
|
3995
|
+
MouseInteractions[MouseInteractions["TouchMove_Departed"] = 8] = "TouchMove_Departed";
|
|
3996
|
+
MouseInteractions[MouseInteractions["TouchEnd"] = 9] = "TouchEnd";
|
|
3997
|
+
MouseInteractions[MouseInteractions["TouchCancel"] = 10] = "TouchCancel";
|
|
3998
|
+
})(MouseInteractions || (MouseInteractions = {}));
|
|
3999
|
+
var PointerTypes;
|
|
4000
|
+
(function (PointerTypes) {
|
|
4001
|
+
PointerTypes[PointerTypes["Mouse"] = 0] = "Mouse";
|
|
4002
|
+
PointerTypes[PointerTypes["Pen"] = 1] = "Pen";
|
|
4003
|
+
PointerTypes[PointerTypes["Touch"] = 2] = "Touch";
|
|
4004
|
+
})(PointerTypes || (PointerTypes = {}));
|
|
4005
|
+
var MediaInteractions;
|
|
4006
|
+
(function (MediaInteractions) {
|
|
4007
|
+
MediaInteractions[MediaInteractions["Play"] = 0] = "Play";
|
|
4008
|
+
MediaInteractions[MediaInteractions["Pause"] = 1] = "Pause";
|
|
4009
|
+
MediaInteractions[MediaInteractions["Seeked"] = 2] = "Seeked";
|
|
4010
|
+
MediaInteractions[MediaInteractions["VolumeChange"] = 3] = "VolumeChange";
|
|
4011
|
+
MediaInteractions[MediaInteractions["RateChange"] = 4] = "RateChange";
|
|
4012
|
+
})(MediaInteractions || (MediaInteractions = {}));
|
|
4013
|
+
var CanvasContext;
|
|
4014
|
+
(function (CanvasContext) {
|
|
4015
|
+
CanvasContext[CanvasContext["2D"] = 0] = "2D";
|
|
4016
|
+
CanvasContext[CanvasContext["WebGL"] = 1] = "WebGL";
|
|
4017
|
+
CanvasContext[CanvasContext["WebGL2"] = 2] = "WebGL2";
|
|
4018
|
+
})(CanvasContext || (CanvasContext = {}));
|
|
4019
|
+
|
|
4020
|
+
const DISABLED = 'disabled';
|
|
4021
|
+
const SAMPLED = 'sampled';
|
|
4022
|
+
const ACTIVE = 'active';
|
|
4023
|
+
const BUFFERING = 'buffering';
|
|
4024
|
+
const PAUSED = 'paused';
|
|
4025
|
+
const LAZY_LOADING = 'lazy_loading';
|
|
4026
|
+
const TRIGGER = 'trigger';
|
|
4027
|
+
const TRIGGER_ACTIVATED = TRIGGER + '_activated';
|
|
4028
|
+
const TRIGGER_PENDING = TRIGGER + '_pending';
|
|
4029
|
+
const TRIGGER_DISABLED = TRIGGER + '_' + DISABLED;
|
|
4030
|
+
function sessionRecordingUrlTriggerMatches(url, triggers) {
|
|
4031
|
+
return triggers.some(trigger => {
|
|
4032
|
+
switch (trigger.matching) {
|
|
4033
|
+
case 'regex':
|
|
4034
|
+
return new RegExp(trigger.url).test(url);
|
|
4035
|
+
default:
|
|
4036
|
+
return false;
|
|
4037
|
+
}
|
|
4038
|
+
});
|
|
4039
|
+
}
|
|
4040
|
+
class OrTriggerMatching {
|
|
4041
|
+
constructor(_matchers) {
|
|
4042
|
+
this._matchers = _matchers;
|
|
4043
|
+
}
|
|
4044
|
+
triggerStatus(sessionId) {
|
|
4045
|
+
const statuses = this._matchers.map(m => m.triggerStatus(sessionId));
|
|
4046
|
+
if (statuses.includes(TRIGGER_ACTIVATED)) {
|
|
4047
|
+
return TRIGGER_ACTIVATED;
|
|
4048
|
+
}
|
|
4049
|
+
if (statuses.includes(TRIGGER_PENDING)) {
|
|
4050
|
+
return TRIGGER_PENDING;
|
|
4051
|
+
}
|
|
4052
|
+
return TRIGGER_DISABLED;
|
|
4053
|
+
}
|
|
4054
|
+
stop() {
|
|
4055
|
+
this._matchers.forEach(m => m.stop());
|
|
4056
|
+
}
|
|
4057
|
+
}
|
|
4058
|
+
class AndTriggerMatching {
|
|
4059
|
+
constructor(_matchers) {
|
|
4060
|
+
this._matchers = _matchers;
|
|
4061
|
+
}
|
|
4062
|
+
triggerStatus(sessionId) {
|
|
4063
|
+
const statuses = new Set();
|
|
4064
|
+
for (const matcher of this._matchers) {
|
|
4065
|
+
statuses.add(matcher.triggerStatus(sessionId));
|
|
4066
|
+
}
|
|
4067
|
+
// trigger_disabled means no config
|
|
4068
|
+
statuses.delete(TRIGGER_DISABLED);
|
|
4069
|
+
switch (statuses.size) {
|
|
4070
|
+
case 0:
|
|
4071
|
+
return TRIGGER_DISABLED;
|
|
4072
|
+
case 1:
|
|
4073
|
+
return Array.from(statuses)[0];
|
|
4074
|
+
default:
|
|
4075
|
+
return TRIGGER_PENDING;
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
stop() {
|
|
4079
|
+
this._matchers.forEach(m => m.stop());
|
|
4080
|
+
}
|
|
4081
|
+
}
|
|
4082
|
+
class PendingTriggerMatching {
|
|
4083
|
+
triggerStatus() {
|
|
4084
|
+
return TRIGGER_PENDING;
|
|
4085
|
+
}
|
|
4086
|
+
stop() {
|
|
4087
|
+
// no-op
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
4090
|
+
const isEagerLoadedConfig = x => {
|
|
4091
|
+
return 'sessionRecording' in x;
|
|
4092
|
+
};
|
|
4093
|
+
class URLTriggerMatching {
|
|
4094
|
+
constructor(_instance) {
|
|
4095
|
+
this._instance = _instance;
|
|
4096
|
+
this._urlTriggers = [];
|
|
4097
|
+
this._urlBlocklist = [];
|
|
4098
|
+
this.urlBlocked = false;
|
|
4099
|
+
}
|
|
4100
|
+
onConfig(config) {
|
|
4101
|
+
this._urlTriggers = (isEagerLoadedConfig(config) ? core.isObject(config.sessionRecording) ? config.sessionRecording?.urlTriggers : [] : config?.urlTriggers) || [];
|
|
4102
|
+
this._urlBlocklist = (isEagerLoadedConfig(config) ? core.isObject(config.sessionRecording) ? config.sessionRecording?.urlBlocklist : [] : config?.urlBlocklist) || [];
|
|
4103
|
+
}
|
|
4104
|
+
/**
|
|
4105
|
+
* @deprecated Use onConfig instead
|
|
4106
|
+
*/
|
|
4107
|
+
onRemoteConfig(response) {
|
|
4108
|
+
this.onConfig(response);
|
|
4109
|
+
}
|
|
4110
|
+
_urlTriggerStatus(sessionId) {
|
|
4111
|
+
if (this._urlTriggers.length === 0) {
|
|
4112
|
+
return TRIGGER_DISABLED;
|
|
4113
|
+
}
|
|
4114
|
+
const currentTriggerSession = this._instance?.get_property(SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION);
|
|
4115
|
+
return currentTriggerSession === sessionId ? TRIGGER_ACTIVATED : TRIGGER_PENDING;
|
|
4116
|
+
}
|
|
4117
|
+
triggerStatus(sessionId) {
|
|
4118
|
+
const urlTriggerStatus = this._urlTriggerStatus(sessionId);
|
|
4119
|
+
const eitherIsActivated = urlTriggerStatus === TRIGGER_ACTIVATED;
|
|
4120
|
+
const eitherIsPending = urlTriggerStatus === TRIGGER_PENDING;
|
|
4121
|
+
const result = eitherIsActivated ? TRIGGER_ACTIVATED : eitherIsPending ? TRIGGER_PENDING : TRIGGER_DISABLED;
|
|
4122
|
+
this._instance.registerForSession({
|
|
4123
|
+
$sdk_debug_replay_url_trigger_status: result
|
|
4124
|
+
});
|
|
4125
|
+
return result;
|
|
4126
|
+
}
|
|
4127
|
+
checkUrlTriggerConditions(onPause, onResume, onActivate) {
|
|
4128
|
+
if (typeof win === 'undefined' || !win.location.href) {
|
|
4129
|
+
return;
|
|
4130
|
+
}
|
|
4131
|
+
const url = win.location.href;
|
|
4132
|
+
const wasBlocked = this.urlBlocked;
|
|
4133
|
+
const isNowBlocked = sessionRecordingUrlTriggerMatches(url, this._urlBlocklist);
|
|
4134
|
+
if (wasBlocked && isNowBlocked) {
|
|
4135
|
+
// if the url is blocked and was already blocked, do nothing
|
|
4136
|
+
return;
|
|
4137
|
+
} else if (isNowBlocked && !wasBlocked) {
|
|
4138
|
+
onPause();
|
|
4139
|
+
} else if (!isNowBlocked && wasBlocked) {
|
|
4140
|
+
onResume();
|
|
4141
|
+
}
|
|
4142
|
+
if (sessionRecordingUrlTriggerMatches(url, this._urlTriggers)) {
|
|
4143
|
+
onActivate('url');
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
stop() {
|
|
4147
|
+
// no-op
|
|
4148
|
+
}
|
|
4149
|
+
}
|
|
4150
|
+
class LinkedFlagMatching {
|
|
4151
|
+
constructor(_instance) {
|
|
4152
|
+
this._instance = _instance;
|
|
4153
|
+
this.linkedFlag = null;
|
|
4154
|
+
this.linkedFlagSeen = false;
|
|
4155
|
+
this._flagListenerCleanup = () => {};
|
|
4156
|
+
}
|
|
4157
|
+
triggerStatus() {
|
|
4158
|
+
let result = TRIGGER_PENDING;
|
|
4159
|
+
if (core.isNullish(this.linkedFlag)) {
|
|
4160
|
+
result = TRIGGER_DISABLED;
|
|
4161
|
+
}
|
|
4162
|
+
if (this.linkedFlagSeen) {
|
|
4163
|
+
result = TRIGGER_ACTIVATED;
|
|
4164
|
+
}
|
|
4165
|
+
this._instance.registerForSession({
|
|
4166
|
+
$sdk_debug_replay_linked_flag_trigger_status: result
|
|
4167
|
+
});
|
|
4168
|
+
return result;
|
|
4169
|
+
}
|
|
4170
|
+
onConfig(config, onStarted) {
|
|
4171
|
+
this.linkedFlag = (isEagerLoadedConfig(config) ? core.isObject(config.sessionRecording) ? config.sessionRecording?.linkedFlag : null : config?.linkedFlag) || null;
|
|
4172
|
+
if (!core.isNullish(this.linkedFlag) && !this.linkedFlagSeen) {
|
|
4173
|
+
const linkedFlag = core.isString(this.linkedFlag) ? this.linkedFlag : this.linkedFlag.flag;
|
|
4174
|
+
const linkedVariant = core.isString(this.linkedFlag) ? null : this.linkedFlag.variant;
|
|
4175
|
+
this._flagListenerCleanup = this._instance.onFeatureFlags(flags => {
|
|
4176
|
+
const flagIsPresent = core.isObject(flags) && linkedFlag in flags;
|
|
4177
|
+
let linkedFlagMatches = false;
|
|
4178
|
+
if (flagIsPresent) {
|
|
4179
|
+
const variantForFlagKey = flags[linkedFlag];
|
|
4180
|
+
if (core.isBoolean(variantForFlagKey)) {
|
|
4181
|
+
linkedFlagMatches = variantForFlagKey === true;
|
|
4182
|
+
} else if (linkedVariant) {
|
|
4183
|
+
linkedFlagMatches = variantForFlagKey === linkedVariant;
|
|
4184
|
+
} else {
|
|
4185
|
+
// then this is a variant flag and we want to match any string
|
|
4186
|
+
linkedFlagMatches = !!variantForFlagKey;
|
|
4187
|
+
}
|
|
4188
|
+
}
|
|
4189
|
+
this.linkedFlagSeen = linkedFlagMatches;
|
|
4190
|
+
if (linkedFlagMatches) {
|
|
4191
|
+
onStarted(linkedFlag, linkedVariant);
|
|
4192
|
+
}
|
|
4193
|
+
});
|
|
4194
|
+
}
|
|
4195
|
+
}
|
|
4196
|
+
/**
|
|
4197
|
+
* @deprecated Use onConfig instead
|
|
4198
|
+
*/
|
|
4199
|
+
onRemoteConfig(response, onStarted) {
|
|
4200
|
+
this.onConfig(response, onStarted);
|
|
4201
|
+
}
|
|
4202
|
+
stop() {
|
|
4203
|
+
this._flagListenerCleanup();
|
|
4204
|
+
}
|
|
4205
|
+
}
|
|
4206
|
+
class EventTriggerMatching {
|
|
4207
|
+
constructor(_instance) {
|
|
4208
|
+
this._instance = _instance;
|
|
4209
|
+
this._eventTriggers = [];
|
|
4210
|
+
}
|
|
4211
|
+
onConfig(config) {
|
|
4212
|
+
this._eventTriggers = (isEagerLoadedConfig(config) ? core.isObject(config.sessionRecording) ? config.sessionRecording?.eventTriggers : [] : config?.eventTriggers) || [];
|
|
4213
|
+
}
|
|
4214
|
+
/**
|
|
4215
|
+
* @deprecated Use onConfig instead
|
|
4216
|
+
*/
|
|
4217
|
+
onRemoteConfig(response) {
|
|
4218
|
+
this.onConfig(response);
|
|
4219
|
+
}
|
|
4220
|
+
_eventTriggerStatus(sessionId) {
|
|
4221
|
+
if (this._eventTriggers.length === 0) {
|
|
4222
|
+
return TRIGGER_DISABLED;
|
|
4223
|
+
}
|
|
4224
|
+
const currentTriggerSession = this._instance?.get_property(SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION);
|
|
4225
|
+
return currentTriggerSession === sessionId ? TRIGGER_ACTIVATED : TRIGGER_PENDING;
|
|
4226
|
+
}
|
|
4227
|
+
triggerStatus(sessionId) {
|
|
4228
|
+
const eventTriggerStatus = this._eventTriggerStatus(sessionId);
|
|
4229
|
+
const result = eventTriggerStatus === TRIGGER_ACTIVATED ? TRIGGER_ACTIVATED : eventTriggerStatus === TRIGGER_PENDING ? TRIGGER_PENDING : TRIGGER_DISABLED;
|
|
4230
|
+
this._instance.registerForSession({
|
|
4231
|
+
$sdk_debug_replay_event_trigger_status: result
|
|
4232
|
+
});
|
|
4233
|
+
return result;
|
|
4234
|
+
}
|
|
4235
|
+
stop() {
|
|
4236
|
+
// no-op
|
|
4237
|
+
}
|
|
4238
|
+
}
|
|
4239
|
+
// we need a no-op matcher before we can lazy-load the other matches, since all matchers wait on remote config anyway
|
|
4240
|
+
function nullMatchSessionRecordingStatus(triggersStatus) {
|
|
4241
|
+
if (!triggersStatus.isRecordingEnabled) {
|
|
4242
|
+
return DISABLED;
|
|
4243
|
+
}
|
|
4244
|
+
return BUFFERING;
|
|
4245
|
+
}
|
|
4246
|
+
function anyMatchSessionRecordingStatus(triggersStatus) {
|
|
4247
|
+
if (!triggersStatus.receivedFlags) {
|
|
4248
|
+
return BUFFERING;
|
|
4249
|
+
}
|
|
4250
|
+
if (!triggersStatus.isRecordingEnabled) {
|
|
4251
|
+
return DISABLED;
|
|
4252
|
+
}
|
|
4253
|
+
if (triggersStatus.urlTriggerMatching.urlBlocked) {
|
|
4254
|
+
return PAUSED;
|
|
4255
|
+
}
|
|
4256
|
+
const sampledActive = triggersStatus.isSampled === true;
|
|
4257
|
+
const triggerMatches = new OrTriggerMatching([triggersStatus.eventTriggerMatching, triggersStatus.urlTriggerMatching, triggersStatus.linkedFlagMatching]).triggerStatus(triggersStatus.sessionId);
|
|
4258
|
+
if (sampledActive) {
|
|
4259
|
+
return SAMPLED;
|
|
4260
|
+
}
|
|
4261
|
+
if (triggerMatches === TRIGGER_ACTIVATED) {
|
|
4262
|
+
return ACTIVE;
|
|
4263
|
+
}
|
|
4264
|
+
if (triggerMatches === TRIGGER_PENDING) {
|
|
4265
|
+
// even if sampled active is false, we should still be buffering
|
|
4266
|
+
// since a pending trigger could override it
|
|
4267
|
+
return BUFFERING;
|
|
4268
|
+
}
|
|
4269
|
+
// if sampling is set and the session is already decided to not be sampled
|
|
4270
|
+
// then we should never be active
|
|
4271
|
+
if (triggersStatus.isSampled === false) {
|
|
4272
|
+
return DISABLED;
|
|
4273
|
+
}
|
|
4274
|
+
return ACTIVE;
|
|
4275
|
+
}
|
|
4276
|
+
function allMatchSessionRecordingStatus(triggersStatus) {
|
|
4277
|
+
if (!triggersStatus.receivedFlags) {
|
|
4278
|
+
return BUFFERING;
|
|
4279
|
+
}
|
|
4280
|
+
if (!triggersStatus.isRecordingEnabled) {
|
|
4281
|
+
return DISABLED;
|
|
4282
|
+
}
|
|
4283
|
+
if (triggersStatus.urlTriggerMatching.urlBlocked) {
|
|
4284
|
+
return PAUSED;
|
|
4285
|
+
}
|
|
4286
|
+
const andTriggerMatch = new AndTriggerMatching([triggersStatus.eventTriggerMatching, triggersStatus.urlTriggerMatching, triggersStatus.linkedFlagMatching]);
|
|
4287
|
+
const currentTriggerStatus = andTriggerMatch.triggerStatus(triggersStatus.sessionId);
|
|
4288
|
+
const hasTriggersConfigured = currentTriggerStatus !== TRIGGER_DISABLED;
|
|
4289
|
+
const hasSamplingConfigured = core.isBoolean(triggersStatus.isSampled);
|
|
4290
|
+
if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_PENDING) {
|
|
4291
|
+
return BUFFERING;
|
|
4292
|
+
}
|
|
4293
|
+
if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_DISABLED) {
|
|
4294
|
+
return DISABLED;
|
|
4295
|
+
}
|
|
4296
|
+
// sampling can't ever cause buffering, it's always determined right away or not configured
|
|
4297
|
+
if (hasSamplingConfigured && !triggersStatus.isSampled) {
|
|
4298
|
+
return DISABLED;
|
|
4299
|
+
}
|
|
4300
|
+
// If sampling is configured and set to true, return sampled
|
|
4301
|
+
if (triggersStatus.isSampled === true) {
|
|
4302
|
+
return SAMPLED;
|
|
4303
|
+
}
|
|
4304
|
+
return ACTIVE;
|
|
4305
|
+
}
|
|
4306
|
+
|
|
4307
|
+
// taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#circular_references
|
|
4308
|
+
function circularReferenceReplacer() {
|
|
4309
|
+
const ancestors = [];
|
|
4310
|
+
return function (_key, value) {
|
|
4311
|
+
if (core.isObject(value)) {
|
|
4312
|
+
// `this` is the object that value is contained in,
|
|
4313
|
+
// i.e., its direct parent.
|
|
4314
|
+
while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {
|
|
4315
|
+
ancestors.pop();
|
|
4316
|
+
}
|
|
4317
|
+
if (ancestors.includes(value)) {
|
|
4318
|
+
return '[Circular]';
|
|
4319
|
+
}
|
|
4320
|
+
ancestors.push(value);
|
|
4321
|
+
return value;
|
|
4322
|
+
} else {
|
|
4323
|
+
return value;
|
|
4324
|
+
}
|
|
4325
|
+
};
|
|
4326
|
+
}
|
|
4327
|
+
function estimateSize(sizeable) {
|
|
4328
|
+
return JSON.stringify(sizeable, circularReferenceReplacer())?.length || 0;
|
|
4329
|
+
}
|
|
4330
|
+
const INCREMENTAL_SNAPSHOT_EVENT_TYPE = 3;
|
|
4331
|
+
const PLUGIN_EVENT_TYPE = 6;
|
|
4332
|
+
const MUTATION_SOURCE_TYPE = 0;
|
|
4333
|
+
const CONSOLE_LOG_PLUGIN_NAME = 'rrweb/console@1'; // The name of the rr-web plugin that emits console logs
|
|
4334
|
+
// Console logs can be really large. This function truncates large logs
|
|
4335
|
+
// It's a simple function that just truncates long strings.
|
|
4336
|
+
// TODO: Ideally this function would have better handling of objects + lists,
|
|
4337
|
+
// so they could still be rendered in a pretty way after truncation.
|
|
4338
|
+
function truncateLargeConsoleLogs(_event) {
|
|
4339
|
+
const event = _event;
|
|
4340
|
+
const MAX_STRING_SIZE = 2000; // Maximum number of characters allowed in a string
|
|
4341
|
+
const MAX_STRINGS_PER_LOG = 10; // A log can consist of multiple strings (e.g. consol.log('string1', 'string2'))
|
|
4342
|
+
if (event && core.isObject(event) && event.type === PLUGIN_EVENT_TYPE && core.isObject(event.data) && event.data.plugin === CONSOLE_LOG_PLUGIN_NAME) {
|
|
4343
|
+
// Note: event.data.payload.payload comes from rr-web, and is an array of strings
|
|
4344
|
+
if (event.data.payload.payload.length > MAX_STRINGS_PER_LOG) {
|
|
4345
|
+
event.data.payload.payload = event.data.payload.payload.slice(0, MAX_STRINGS_PER_LOG);
|
|
4346
|
+
event.data.payload.payload.push('...[truncated]');
|
|
4347
|
+
}
|
|
4348
|
+
const updatedPayload = [];
|
|
4349
|
+
for (let i = 0; i < event.data.payload.payload.length; i++) {
|
|
4350
|
+
if (event.data.payload.payload[i] &&
|
|
4351
|
+
// Value can be null
|
|
4352
|
+
event.data.payload.payload[i].length > MAX_STRING_SIZE) {
|
|
4353
|
+
updatedPayload.push(event.data.payload.payload[i].slice(0, MAX_STRING_SIZE) + '...[truncated]');
|
|
4354
|
+
} else {
|
|
4355
|
+
updatedPayload.push(event.data.payload.payload[i]);
|
|
4356
|
+
}
|
|
4357
|
+
}
|
|
4358
|
+
event.data.payload.payload = updatedPayload;
|
|
4359
|
+
// Return original type
|
|
4360
|
+
return _event;
|
|
4361
|
+
}
|
|
4362
|
+
return _event;
|
|
4363
|
+
}
|
|
4364
|
+
|
|
4365
|
+
class MutationThrottler {
|
|
4366
|
+
constructor(_rrweb, _options = {}) {
|
|
4367
|
+
this._rrweb = _rrweb;
|
|
4368
|
+
this._options = _options;
|
|
4369
|
+
this._loggedTracker = {};
|
|
4370
|
+
this._onNodeRateLimited = key => {
|
|
4371
|
+
if (!this._loggedTracker[key]) {
|
|
4372
|
+
this._loggedTracker[key] = true;
|
|
4373
|
+
const node = this._getNode(key);
|
|
4374
|
+
this._options.onBlockedNode?.(key, node);
|
|
4375
|
+
}
|
|
4376
|
+
};
|
|
4377
|
+
this._getNodeOrRelevantParent = id => {
|
|
4378
|
+
// For some nodes we know they are part of a larger tree such as an SVG.
|
|
4379
|
+
// For those we want to block the entire node, not just the specific attribute
|
|
4380
|
+
const node = this._getNode(id);
|
|
4381
|
+
// Check if the node is an Element and then find the closest parent that is an SVG
|
|
4382
|
+
if (node?.nodeName !== 'svg' && node instanceof Element) {
|
|
4383
|
+
const closestSVG = node.closest('svg');
|
|
4384
|
+
if (closestSVG) {
|
|
4385
|
+
return [this._rrweb.mirror.getId(closestSVG), closestSVG];
|
|
4386
|
+
}
|
|
4387
|
+
}
|
|
4388
|
+
return [id, node];
|
|
4389
|
+
};
|
|
4390
|
+
this._getNode = id => this._rrweb.mirror.getNode(id);
|
|
4391
|
+
this._numberOfChanges = data => {
|
|
4392
|
+
return (data.removes?.length ?? 0) + (data.attributes?.length ?? 0) + (data.texts?.length ?? 0) + (data.adds?.length ?? 0);
|
|
4393
|
+
};
|
|
4394
|
+
this.throttleMutations = event => {
|
|
4395
|
+
if (event.type !== INCREMENTAL_SNAPSHOT_EVENT_TYPE || event.data.source !== MUTATION_SOURCE_TYPE) {
|
|
4396
|
+
return event;
|
|
4397
|
+
}
|
|
4398
|
+
const data = event.data;
|
|
4399
|
+
const initialMutationCount = this._numberOfChanges(data);
|
|
4400
|
+
if (data.attributes) {
|
|
4401
|
+
// Most problematic mutations come from attrs where the style or minor properties are changed rapidly
|
|
4402
|
+
data.attributes = data.attributes.filter(attr => {
|
|
4403
|
+
const [nodeId] = this._getNodeOrRelevantParent(attr.id);
|
|
4404
|
+
const isRateLimited = this._rateLimiter.consumeRateLimit(nodeId);
|
|
4405
|
+
if (isRateLimited) {
|
|
4406
|
+
return false;
|
|
4407
|
+
}
|
|
4408
|
+
return attr;
|
|
4409
|
+
});
|
|
4410
|
+
}
|
|
4411
|
+
// Check if every part of the mutation is empty in which case there is nothing to do
|
|
4412
|
+
const mutationCount = this._numberOfChanges(data);
|
|
4413
|
+
if (mutationCount === 0 && initialMutationCount !== mutationCount) {
|
|
4414
|
+
// If we have modified the mutation count and the remaining count is 0, then we don't need the event.
|
|
4415
|
+
return;
|
|
4416
|
+
}
|
|
4417
|
+
return event;
|
|
4418
|
+
};
|
|
4419
|
+
const configuredBucketSize = this._options.bucketSize ?? 100;
|
|
4420
|
+
const effectiveBucketSize = Math.max(configuredBucketSize - 1, 1);
|
|
4421
|
+
this._rateLimiter = new core.BucketedRateLimiter({
|
|
4422
|
+
bucketSize: effectiveBucketSize,
|
|
4423
|
+
refillRate: this._options.refillRate ?? 10,
|
|
4424
|
+
refillInterval: 1000,
|
|
4425
|
+
// one second
|
|
4426
|
+
_onBucketRateLimited: this._onNodeRateLimited,
|
|
4427
|
+
_logger: logger$2
|
|
4428
|
+
});
|
|
4429
|
+
}
|
|
4430
|
+
reset() {
|
|
4431
|
+
this._loggedTracker = {};
|
|
4432
|
+
}
|
|
4433
|
+
stop() {
|
|
4434
|
+
this._rateLimiter.stop();
|
|
4435
|
+
this.reset();
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
4438
|
+
|
|
4439
|
+
function simpleHash(str) {
|
|
4440
|
+
let hash = 0;
|
|
4441
|
+
for (let i = 0; i < str.length; i++) {
|
|
4442
|
+
hash = (hash << 5) - hash + str.charCodeAt(i); // (hash * 31) + char code
|
|
4443
|
+
hash |= 0; // Convert to 32bit integer
|
|
4444
|
+
}
|
|
4445
|
+
return Math.abs(hash);
|
|
4446
|
+
}
|
|
4447
|
+
/*
|
|
4448
|
+
* receives percent as a number between 0 and 1
|
|
4449
|
+
*/
|
|
4450
|
+
function sampleOnProperty(prop, percent) {
|
|
4451
|
+
return simpleHash(prop) % 100 < core.clampToRange(percent * 100, 0, 100, logger$2);
|
|
4452
|
+
}
|
|
4453
|
+
|
|
4454
|
+
const BASE_ENDPOINT = '/s/';
|
|
4455
|
+
const DEFAULT_CANVAS_QUALITY = 0.4;
|
|
4456
|
+
const DEFAULT_CANVAS_FPS = 4;
|
|
4457
|
+
const MAX_CANVAS_FPS = 12;
|
|
4458
|
+
const MAX_CANVAS_QUALITY = 1;
|
|
4459
|
+
const TWO_SECONDS = 2000;
|
|
4460
|
+
const ONE_KB = 1024;
|
|
4461
|
+
const ONE_MINUTE = 1000 * 60;
|
|
4462
|
+
const FIVE_MINUTES = ONE_MINUTE * 5;
|
|
4463
|
+
const RECORDING_IDLE_THRESHOLD_MS = FIVE_MINUTES;
|
|
4464
|
+
const RECORDING_MAX_EVENT_SIZE = ONE_KB * ONE_KB * 0.9; // ~1mb (with some wiggle room)
|
|
4465
|
+
const RECORDING_BUFFER_TIMEOUT = 2000; // 2 seconds
|
|
4466
|
+
const SESSION_RECORDING_BATCH_KEY = 'recordings';
|
|
4467
|
+
const LOGGER_PREFIX$1 = '[SessionRecording]';
|
|
4468
|
+
const logger = createLogger(LOGGER_PREFIX$1);
|
|
4469
|
+
const ACTIVE_SOURCES = [IncrementalSource.MouseMove, IncrementalSource.MouseInteraction, IncrementalSource.Scroll, IncrementalSource.ViewportResize, IncrementalSource.Input, IncrementalSource.TouchMove, IncrementalSource.MediaInteraction, IncrementalSource.Drag];
|
|
4470
|
+
const newQueuedEvent = rrwebMethod => ({
|
|
4471
|
+
rrwebMethod,
|
|
4472
|
+
enqueuedAt: Date.now(),
|
|
4473
|
+
attempt: 1
|
|
4474
|
+
});
|
|
4475
|
+
function getRRWebRecord() {
|
|
4476
|
+
try {
|
|
4477
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
4478
|
+
const ext = globalThis.__PosthogExtensions__;
|
|
4479
|
+
if (ext && ext.rrweb && ext.rrweb.record) {
|
|
4480
|
+
return ext.rrweb.record;
|
|
4481
|
+
}
|
|
4482
|
+
} catch {
|
|
4483
|
+
// ignore
|
|
4484
|
+
}
|
|
4485
|
+
return record.record;
|
|
4486
|
+
}
|
|
4487
|
+
function gzipToString(data) {
|
|
4488
|
+
return fflate.strFromU8(fflate.gzipSync(fflate.strToU8(JSON.stringify(data))), true);
|
|
4489
|
+
}
|
|
4490
|
+
/**
|
|
4491
|
+
* rrweb's packer takes an event and returns a string or the reverse on `unpack`.
|
|
4492
|
+
* but we want to be able to inspect metadata during ingestion.
|
|
4493
|
+
* and don't want to compress the entire event,
|
|
4494
|
+
* so we have a custom packer that only compresses part of some events
|
|
4495
|
+
*/
|
|
4496
|
+
function compressEvent(event) {
|
|
4497
|
+
try {
|
|
4498
|
+
if (event.type === EventType.FullSnapshot) {
|
|
4499
|
+
return {
|
|
4500
|
+
...event,
|
|
4501
|
+
data: gzipToString(event.data),
|
|
4502
|
+
cv: '2024-10'
|
|
4503
|
+
};
|
|
4504
|
+
}
|
|
4505
|
+
if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.Mutation) {
|
|
4506
|
+
return {
|
|
4507
|
+
...event,
|
|
4508
|
+
cv: '2024-10',
|
|
4509
|
+
data: {
|
|
4510
|
+
...event.data,
|
|
4511
|
+
texts: gzipToString(event.data.texts),
|
|
4512
|
+
attributes: gzipToString(event.data.attributes),
|
|
4513
|
+
removes: gzipToString(event.data.removes),
|
|
4514
|
+
adds: gzipToString(event.data.adds)
|
|
4515
|
+
}
|
|
4516
|
+
};
|
|
4517
|
+
}
|
|
4518
|
+
if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.StyleSheetRule) {
|
|
4519
|
+
return {
|
|
4520
|
+
...event,
|
|
4521
|
+
cv: '2024-10',
|
|
4522
|
+
data: {
|
|
4523
|
+
...event.data,
|
|
4524
|
+
adds: event.data.adds ? gzipToString(event.data.adds) : undefined,
|
|
4525
|
+
removes: event.data.removes ? gzipToString(event.data.removes) : undefined
|
|
4526
|
+
}
|
|
4527
|
+
};
|
|
4528
|
+
}
|
|
4529
|
+
} catch (e) {
|
|
4530
|
+
logger.error('could not compress event - will use uncompressed event', e);
|
|
4531
|
+
}
|
|
4532
|
+
return event;
|
|
4533
|
+
}
|
|
4534
|
+
function isSessionIdleEvent(e) {
|
|
4535
|
+
return e.type === EventType.Custom && e.data.tag === 'sessionIdle';
|
|
4536
|
+
}
|
|
4537
|
+
/** When we put the recording into a paused state, we add a custom event.
|
|
4538
|
+
* However, in the paused state, events are dropped and never make it to the buffer,
|
|
4539
|
+
* so we need to manually let this one through */
|
|
4540
|
+
function isRecordingPausedEvent(e) {
|
|
4541
|
+
return e.type === EventType.Custom && e.data.tag === 'recording paused';
|
|
4542
|
+
}
|
|
4543
|
+
const SEVEN_MEGABYTES = 1024 * 1024 * 7 * 0.9; // ~7mb (with some wiggle room)
|
|
4544
|
+
// recursively splits large buffers into smaller ones
|
|
4545
|
+
// uses a pretty high size limit to avoid splitting too much
|
|
4546
|
+
function splitBuffer(buffer, sizeLimit = SEVEN_MEGABYTES) {
|
|
4547
|
+
if (buffer.size >= sizeLimit && buffer.data.length > 1) {
|
|
4548
|
+
const half = Math.floor(buffer.data.length / 2);
|
|
4549
|
+
const firstHalf = buffer.data.slice(0, half);
|
|
4550
|
+
const secondHalf = buffer.data.slice(half);
|
|
4551
|
+
return [splitBuffer({
|
|
4552
|
+
size: estimateSize(firstHalf),
|
|
4553
|
+
data: firstHalf,
|
|
4554
|
+
sessionId: buffer.sessionId,
|
|
4555
|
+
windowId: buffer.windowId
|
|
4556
|
+
}), splitBuffer({
|
|
4557
|
+
size: estimateSize(secondHalf),
|
|
4558
|
+
data: secondHalf,
|
|
4559
|
+
sessionId: buffer.sessionId,
|
|
4560
|
+
windowId: buffer.windowId
|
|
4561
|
+
})].flatMap(x => x);
|
|
4562
|
+
} else {
|
|
4563
|
+
return [buffer];
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
4566
|
+
class LazyLoadedSessionRecording {
|
|
4567
|
+
get sessionId() {
|
|
4568
|
+
return this._sessionId;
|
|
4569
|
+
}
|
|
4570
|
+
get _sessionManager() {
|
|
4571
|
+
if (!this._instance.sessionManager) {
|
|
4572
|
+
throw new Error(LOGGER_PREFIX$1 + ' must be started with a valid sessionManager.');
|
|
4573
|
+
}
|
|
4574
|
+
return this._instance.sessionManager;
|
|
4575
|
+
}
|
|
4576
|
+
get _sessionIdleThresholdMilliseconds() {
|
|
4577
|
+
return this._instance.config.session_recording?.session_idle_threshold_ms || RECORDING_IDLE_THRESHOLD_MS;
|
|
4578
|
+
}
|
|
4579
|
+
get _isSampled() {
|
|
4580
|
+
const currentValue = this._instance.get_property(SESSION_RECORDING_IS_SAMPLED);
|
|
4581
|
+
// originally we would store `true` or `false` or nothing,
|
|
4582
|
+
// but that would mean sometimes we would carry on recording on session id change
|
|
4583
|
+
return core.isBoolean(currentValue) ? currentValue : core.isString(currentValue) ? currentValue === this.sessionId : null;
|
|
4584
|
+
}
|
|
4585
|
+
get _sampleRate() {
|
|
4586
|
+
const rate = this._remoteConfig?.sampleRate;
|
|
4587
|
+
return core.isNumber(rate) ? rate : null;
|
|
4588
|
+
}
|
|
4589
|
+
get _minimumDuration() {
|
|
4590
|
+
const duration = this._remoteConfig?.minimumDurationMilliseconds;
|
|
4591
|
+
return core.isNumber(duration) ? duration : null;
|
|
4592
|
+
}
|
|
4593
|
+
constructor(_instance) {
|
|
4594
|
+
this._instance = _instance;
|
|
4595
|
+
this._endpoint = BASE_ENDPOINT;
|
|
4596
|
+
/**
|
|
4597
|
+
* Util to help developers working on this feature manually override
|
|
4598
|
+
*/
|
|
4599
|
+
this._forceAllowLocalhostNetworkCapture = false;
|
|
4600
|
+
this._stopRrweb = undefined;
|
|
4601
|
+
this._lastActivityTimestamp = Date.now();
|
|
4602
|
+
/**
|
|
4603
|
+
* and a queue - that contains rrweb events that we want to send to rrweb, but rrweb wasn't able to accept them yet
|
|
4604
|
+
*/
|
|
4605
|
+
this._queuedRRWebEvents = [];
|
|
4606
|
+
this._isIdle = 'unknown';
|
|
4607
|
+
// we need to be able to check the state of the event and url triggers separately
|
|
4608
|
+
// as we make some decisions based on them without referencing LinkedFlag etc
|
|
4609
|
+
this._triggerMatching = new PendingTriggerMatching();
|
|
4610
|
+
this._removePageViewCaptureHook = undefined;
|
|
4611
|
+
this._removeEventTriggerCaptureHook = undefined;
|
|
4612
|
+
this._statusMatcher = nullMatchSessionRecordingStatus;
|
|
4613
|
+
this._onSessionIdListener = undefined;
|
|
4614
|
+
this._onSessionIdleResetForcedListener = undefined;
|
|
4615
|
+
this._samplingSessionListener = undefined;
|
|
4616
|
+
this._forceIdleSessionIdListener = undefined;
|
|
4617
|
+
this._onSessionIdCallback = (sessionId, windowId, changeReason) => {
|
|
4618
|
+
if (changeReason) {
|
|
4619
|
+
this._tryAddCustomEvent('$session_id_change', {
|
|
4620
|
+
sessionId,
|
|
4621
|
+
windowId,
|
|
4622
|
+
changeReason
|
|
4623
|
+
});
|
|
4624
|
+
this._clearConditionalRecordingPersistence();
|
|
4625
|
+
if (!this._stopRrweb) {
|
|
4626
|
+
this.start('session_id_changed');
|
|
4627
|
+
}
|
|
4628
|
+
if (core.isNumber(this._sampleRate) && core.isNullish(this._samplingSessionListener)) {
|
|
4629
|
+
this._makeSamplingDecision(sessionId);
|
|
4630
|
+
}
|
|
4631
|
+
}
|
|
4632
|
+
};
|
|
4633
|
+
this._onBeforeUnload = () => {
|
|
4634
|
+
this._flushBuffer();
|
|
4635
|
+
};
|
|
4636
|
+
this._onOffline = () => {
|
|
4637
|
+
this._tryAddCustomEvent('browser offline', {});
|
|
4638
|
+
};
|
|
4639
|
+
this._onOnline = () => {
|
|
4640
|
+
this._tryAddCustomEvent('browser online', {});
|
|
4641
|
+
};
|
|
4642
|
+
this._onVisibilityChange = () => {
|
|
4643
|
+
if (document?.visibilityState) {
|
|
4644
|
+
const label = 'window ' + document.visibilityState;
|
|
4645
|
+
this._tryAddCustomEvent(label, {});
|
|
4646
|
+
}
|
|
4647
|
+
};
|
|
4648
|
+
// we know there's a sessionManager, so don't need to start without a session id
|
|
4649
|
+
const {
|
|
4650
|
+
sessionId,
|
|
4651
|
+
windowId
|
|
4652
|
+
} = this._sessionManager.checkAndGetSessionAndWindowId();
|
|
4653
|
+
this._sessionId = sessionId;
|
|
4654
|
+
this._windowId = windowId;
|
|
4655
|
+
this._linkedFlagMatching = new LinkedFlagMatching(this._instance);
|
|
4656
|
+
this._urlTriggerMatching = new URLTriggerMatching(this._instance);
|
|
4657
|
+
this._eventTriggerMatching = new EventTriggerMatching(this._instance);
|
|
4658
|
+
this._buffer = this._clearBuffer();
|
|
4659
|
+
if (this._sessionIdleThresholdMilliseconds >= this._sessionManager.sessionTimeoutMs) {
|
|
4660
|
+
logger.warn(`session_idle_threshold_ms (${this._sessionIdleThresholdMilliseconds}) is greater than the session timeout (${this._sessionManager.sessionTimeoutMs}). Session will never be detected as idle`);
|
|
4661
|
+
}
|
|
4662
|
+
}
|
|
4663
|
+
get _masking() {
|
|
4664
|
+
const masking_server_side = this._remoteConfig?.masking;
|
|
4665
|
+
const masking_client_side = {
|
|
4666
|
+
maskAllInputs: this._instance.config.session_recording?.maskAllInputs,
|
|
4667
|
+
maskTextSelector: this._instance.config.session_recording?.maskTextSelector,
|
|
4668
|
+
blockSelector: this._instance.config.session_recording?.blockSelector
|
|
4669
|
+
};
|
|
4670
|
+
const maskAllInputs = masking_client_side?.maskAllInputs ?? masking_server_side?.maskAllInputs;
|
|
4671
|
+
const maskTextSelector = masking_client_side?.maskTextSelector ?? masking_server_side?.maskTextSelector;
|
|
4672
|
+
const blockSelector = masking_client_side?.blockSelector ?? masking_server_side?.blockSelector;
|
|
4673
|
+
return !core.isUndefined(maskAllInputs) || !core.isUndefined(maskTextSelector) || !core.isUndefined(blockSelector) ? {
|
|
4674
|
+
maskAllInputs: maskAllInputs ?? true,
|
|
4675
|
+
maskTextSelector,
|
|
4676
|
+
blockSelector
|
|
4677
|
+
} : undefined;
|
|
4678
|
+
}
|
|
4679
|
+
get _canvasRecording() {
|
|
4680
|
+
const canvasRecording_client_side = this._instance.config.session_recording?.captureCanvas;
|
|
4681
|
+
const canvasRecording_server_side = this._remoteConfig?.canvasRecording;
|
|
4682
|
+
const enabled = canvasRecording_client_side?.recordCanvas ?? canvasRecording_server_side?.enabled ?? false;
|
|
4683
|
+
const fps = canvasRecording_client_side?.canvasFps ?? canvasRecording_server_side?.fps ?? DEFAULT_CANVAS_FPS;
|
|
4684
|
+
let quality = canvasRecording_client_side?.canvasQuality ?? canvasRecording_server_side?.quality ?? DEFAULT_CANVAS_QUALITY;
|
|
4685
|
+
if (typeof quality === 'string') {
|
|
4686
|
+
const parsed = parseFloat(quality);
|
|
4687
|
+
quality = isNaN(parsed) ? 0.4 : parsed;
|
|
4688
|
+
}
|
|
4689
|
+
return {
|
|
4690
|
+
enabled,
|
|
4691
|
+
fps: core.clampToRange(fps, 0, MAX_CANVAS_FPS, createLogger('canvas recording fps'), DEFAULT_CANVAS_FPS),
|
|
4692
|
+
quality: core.clampToRange(quality, 0, MAX_CANVAS_QUALITY, createLogger('canvas recording quality'), DEFAULT_CANVAS_QUALITY)
|
|
4693
|
+
};
|
|
4694
|
+
}
|
|
4695
|
+
get _isConsoleLogCaptureEnabled() {
|
|
4696
|
+
const enabled_server_side = !!this._remoteConfig?.consoleLogRecordingEnabled;
|
|
4697
|
+
const enabled_client_side = this._instance.config.enable_recording_console_log;
|
|
4698
|
+
return enabled_client_side ?? enabled_server_side;
|
|
4699
|
+
}
|
|
4700
|
+
// network payload capture config has three parts
|
|
4701
|
+
// each can be configured server side or client side
|
|
4702
|
+
get _networkPayloadCapture() {
|
|
4703
|
+
const networkPayloadCapture_server_side = this._remoteConfig?.networkPayloadCapture;
|
|
4704
|
+
const networkPayloadCapture_client_side = {
|
|
4705
|
+
recordHeaders: this._instance.config.session_recording?.recordHeaders,
|
|
4706
|
+
recordBody: this._instance.config.session_recording?.recordBody
|
|
4707
|
+
};
|
|
4708
|
+
const headersOptIn = networkPayloadCapture_client_side?.recordHeaders === true;
|
|
4709
|
+
const bodyOptIn = networkPayloadCapture_client_side?.recordBody === true;
|
|
4710
|
+
const clientPerformanceConfig = this._instance.config.capture_performance;
|
|
4711
|
+
const clientPerformanceOptIn = core.isObject(clientPerformanceConfig) ? !!clientPerformanceConfig.network_timing : !!clientPerformanceConfig;
|
|
4712
|
+
const serverAllowsHeaders = networkPayloadCapture_server_side?.recordHeaders ?? true;
|
|
4713
|
+
const serverAllowsBody = networkPayloadCapture_server_side?.recordBody ?? true;
|
|
4714
|
+
const capturePerfResponse = networkPayloadCapture_server_side?.capturePerformance;
|
|
4715
|
+
const serverAllowsPerformance = (() => {
|
|
4716
|
+
if (core.isObject(capturePerfResponse)) {
|
|
4717
|
+
return !!capturePerfResponse.network_timing;
|
|
4718
|
+
}
|
|
4719
|
+
return capturePerfResponse ?? true;
|
|
4720
|
+
})();
|
|
4721
|
+
const headersEnabled = headersOptIn && serverAllowsHeaders;
|
|
4722
|
+
const bodyEnabled = bodyOptIn && serverAllowsBody;
|
|
4723
|
+
const networkTimingEnabled = clientPerformanceOptIn && serverAllowsPerformance;
|
|
4724
|
+
if (!headersEnabled && !bodyEnabled && !networkTimingEnabled) {
|
|
4725
|
+
return undefined;
|
|
4726
|
+
}
|
|
4727
|
+
return {
|
|
4728
|
+
recordHeaders: headersEnabled,
|
|
4729
|
+
recordBody: bodyEnabled,
|
|
4730
|
+
recordPerformance: networkTimingEnabled,
|
|
4731
|
+
payloadHostDenyList: networkPayloadCapture_server_side?.payloadHostDenyList
|
|
4732
|
+
};
|
|
4733
|
+
}
|
|
4734
|
+
_gatherRRWebPlugins() {
|
|
4735
|
+
const plugins = [];
|
|
4736
|
+
if (this._isConsoleLogCaptureEnabled) {
|
|
4737
|
+
logger.info('Console log capture requested but console plugin is not bundled in this build yet.');
|
|
4738
|
+
}
|
|
4739
|
+
if (this._networkPayloadCapture) {
|
|
4740
|
+
const canRecordNetwork = !isLocalhost() || this._forceAllowLocalhostNetworkCapture;
|
|
4741
|
+
if (canRecordNetwork) {
|
|
4742
|
+
plugins.push(getRecordNetworkPlugin(buildNetworkRequestOptions(this._instance.config, this._networkPayloadCapture)));
|
|
4743
|
+
} else {
|
|
4744
|
+
logger.info('NetworkCapture not started because we are on localhost.');
|
|
4745
|
+
}
|
|
4746
|
+
}
|
|
4747
|
+
return plugins;
|
|
4748
|
+
}
|
|
4749
|
+
_maskUrl(url) {
|
|
4750
|
+
const userSessionRecordingOptions = this._instance.config.session_recording || {};
|
|
4751
|
+
if (userSessionRecordingOptions.maskNetworkRequestFn) {
|
|
4752
|
+
let networkRequest = {
|
|
4753
|
+
url
|
|
4754
|
+
};
|
|
4755
|
+
// TODO we should deprecate this and use the same function for this masking and the rrweb/network plugin
|
|
4756
|
+
// TODO or deprecate this and provide a new clearer name so this would be `maskURLPerformanceFn` or similar
|
|
4757
|
+
networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest);
|
|
4758
|
+
return networkRequest?.url;
|
|
4759
|
+
}
|
|
4760
|
+
return url;
|
|
4761
|
+
}
|
|
4762
|
+
_tryRRWebMethod(queuedRRWebEvent) {
|
|
4763
|
+
try {
|
|
4764
|
+
queuedRRWebEvent.rrwebMethod();
|
|
4765
|
+
return true;
|
|
4766
|
+
} catch (e) {
|
|
4767
|
+
// Sometimes a race can occur where the recorder is not fully started yet
|
|
4768
|
+
if (this._queuedRRWebEvents.length < 10) {
|
|
4769
|
+
this._queuedRRWebEvents.push({
|
|
4770
|
+
enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),
|
|
4771
|
+
attempt: queuedRRWebEvent.attempt + 1,
|
|
4772
|
+
rrwebMethod: queuedRRWebEvent.rrwebMethod
|
|
4773
|
+
});
|
|
4774
|
+
} else {
|
|
4775
|
+
logger.warn('could not emit queued rrweb event.', e, queuedRRWebEvent);
|
|
4776
|
+
}
|
|
4777
|
+
return false;
|
|
4778
|
+
}
|
|
4779
|
+
}
|
|
4780
|
+
_tryAddCustomEvent(tag, payload) {
|
|
4781
|
+
return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord().addCustomEvent(tag, payload)));
|
|
4782
|
+
}
|
|
4783
|
+
_pageViewFallBack() {
|
|
4784
|
+
try {
|
|
4785
|
+
if (this._instance.config.capture_pageview || !win) {
|
|
4786
|
+
return;
|
|
4787
|
+
}
|
|
4788
|
+
// Strip hash parameters from URL since they often aren't helpful
|
|
4789
|
+
// Use URL constructor for proper parsing to handle edge cases
|
|
4790
|
+
// recording doesn't run in IE11, so we don't need compat here
|
|
4791
|
+
// eslint-disable-next-line compat/compat
|
|
4792
|
+
const url = new URL(win.location.href);
|
|
4793
|
+
const hrefWithoutHash = url.origin + url.pathname + url.search;
|
|
4794
|
+
const currentUrl = this._maskUrl(hrefWithoutHash);
|
|
4795
|
+
if (this._lastHref !== currentUrl) {
|
|
4796
|
+
this._lastHref = currentUrl;
|
|
4797
|
+
this._tryAddCustomEvent('$url_changed', {
|
|
4798
|
+
href: currentUrl
|
|
4799
|
+
});
|
|
4800
|
+
}
|
|
4801
|
+
} catch {
|
|
4802
|
+
// If URL processing fails, don't capture anything
|
|
4803
|
+
}
|
|
4804
|
+
}
|
|
4805
|
+
_processQueuedEvents() {
|
|
4806
|
+
if (this._queuedRRWebEvents.length) {
|
|
4807
|
+
// if rrweb isn't ready to accept events earlier, then we queued them up.
|
|
4808
|
+
// now that `emit` has been called rrweb should be ready to accept them.
|
|
4809
|
+
// so, before we process this event, we try our queued events _once_ each
|
|
4810
|
+
// we don't want to risk queuing more things and never exiting this loop!
|
|
4811
|
+
// if they fail here, they'll be pushed into a new queue
|
|
4812
|
+
// and tried on the next loop.
|
|
4813
|
+
// there is a risk of this queue growing in an uncontrolled manner.
|
|
4814
|
+
// so its length is limited elsewhere
|
|
4815
|
+
// for now this is to help us ensure we can capture events that happen
|
|
4816
|
+
// and try to identify more about when it is failing
|
|
4817
|
+
const itemsToProcess = [...this._queuedRRWebEvents];
|
|
4818
|
+
this._queuedRRWebEvents = [];
|
|
4819
|
+
itemsToProcess.forEach(queuedRRWebEvent => {
|
|
4820
|
+
if (Date.now() - queuedRRWebEvent.enqueuedAt <= TWO_SECONDS) {
|
|
4821
|
+
this._tryRRWebMethod(queuedRRWebEvent);
|
|
4822
|
+
}
|
|
4823
|
+
});
|
|
4824
|
+
}
|
|
4825
|
+
}
|
|
4826
|
+
_tryTakeFullSnapshot() {
|
|
4827
|
+
return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord().takeFullSnapshot()));
|
|
4828
|
+
}
|
|
4829
|
+
get _fullSnapshotIntervalMillis() {
|
|
4830
|
+
if (this._triggerMatching.triggerStatus(this.sessionId) === TRIGGER_PENDING && !['sampled', 'active'].includes(this.status)) {
|
|
4831
|
+
return ONE_MINUTE;
|
|
4832
|
+
}
|
|
4833
|
+
return this._instance.config.session_recording?.full_snapshot_interval_millis ?? FIVE_MINUTES;
|
|
4834
|
+
}
|
|
4835
|
+
_scheduleFullSnapshot() {
|
|
4836
|
+
if (this._fullSnapshotTimer) {
|
|
4837
|
+
clearInterval(this._fullSnapshotTimer);
|
|
4838
|
+
}
|
|
4839
|
+
// we don't schedule snapshots while idle
|
|
4840
|
+
if (this._isIdle === true) {
|
|
4841
|
+
return;
|
|
4842
|
+
}
|
|
4843
|
+
const interval = this._fullSnapshotIntervalMillis;
|
|
4844
|
+
if (!interval) {
|
|
4845
|
+
return;
|
|
4846
|
+
}
|
|
4847
|
+
this._fullSnapshotTimer = setInterval(() => {
|
|
4848
|
+
this._tryTakeFullSnapshot();
|
|
4849
|
+
}, interval);
|
|
4850
|
+
}
|
|
4851
|
+
_pauseRecording() {
|
|
4852
|
+
// we check _urlBlocked not status, since more than one thing can affect status
|
|
4853
|
+
if (this._urlTriggerMatching.urlBlocked) {
|
|
4854
|
+
return;
|
|
4855
|
+
}
|
|
4856
|
+
// we can't flush the buffer here since someone might be starting on a blocked page.
|
|
4857
|
+
// and we need to be sure that we don't record that page,
|
|
4858
|
+
// so we might not get the below custom event, but events will report the paused status.
|
|
4859
|
+
// which will allow debugging of sessions that start on blocked pages
|
|
4860
|
+
this._urlTriggerMatching.urlBlocked = true;
|
|
4861
|
+
// Clear the snapshot timer since we don't want new snapshots while paused
|
|
4862
|
+
clearInterval(this._fullSnapshotTimer);
|
|
4863
|
+
logger.info('recording paused due to URL blocker');
|
|
4864
|
+
this._tryAddCustomEvent('recording paused', {
|
|
4865
|
+
reason: 'url blocker'
|
|
4866
|
+
});
|
|
4867
|
+
}
|
|
4868
|
+
_resumeRecording() {
|
|
4869
|
+
// we check _urlBlocked not status, since more than one thing can affect status
|
|
4870
|
+
if (!this._urlTriggerMatching.urlBlocked) {
|
|
4871
|
+
return;
|
|
4872
|
+
}
|
|
4873
|
+
this._urlTriggerMatching.urlBlocked = false;
|
|
4874
|
+
this._tryTakeFullSnapshot();
|
|
4875
|
+
this._scheduleFullSnapshot();
|
|
4876
|
+
this._tryAddCustomEvent('recording resumed', {
|
|
4877
|
+
reason: 'left blocked url'
|
|
4878
|
+
});
|
|
4879
|
+
logger.info('recording resumed');
|
|
4880
|
+
}
|
|
4881
|
+
_activateTrigger(triggerType) {
|
|
4882
|
+
if (this._triggerMatching.triggerStatus(this.sessionId) === TRIGGER_PENDING) {
|
|
4883
|
+
// status is stored separately for URL and event triggers
|
|
4884
|
+
this._instance?.persistence?.register({
|
|
4885
|
+
[triggerType === 'url' ? SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION : SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION]: this._sessionId
|
|
4886
|
+
});
|
|
4887
|
+
this._flushBuffer();
|
|
4888
|
+
this._reportStarted(triggerType + '_trigger_matched');
|
|
4889
|
+
}
|
|
4890
|
+
}
|
|
4891
|
+
get isStarted() {
|
|
4892
|
+
return !!this._stopRrweb;
|
|
4893
|
+
}
|
|
4894
|
+
get _remoteConfig() {
|
|
4895
|
+
const persistedConfig = this._instance.get_property(SESSION_RECORDING_REMOTE_CONFIG);
|
|
4896
|
+
if (!persistedConfig) {
|
|
4897
|
+
return undefined;
|
|
4898
|
+
}
|
|
4899
|
+
const parsedConfig = core.isObject(persistedConfig) ? persistedConfig : JSON.parse(persistedConfig);
|
|
4900
|
+
return parsedConfig;
|
|
4901
|
+
}
|
|
4902
|
+
start(startReason) {
|
|
4903
|
+
const config = this._remoteConfig;
|
|
4904
|
+
if (!config) {
|
|
4905
|
+
logger.info('remote config must be stored in persistence before recording can start');
|
|
4906
|
+
return;
|
|
4907
|
+
}
|
|
4908
|
+
// We want to ensure the sessionManager is reset if necessary on loading the recorder
|
|
4909
|
+
this._sessionManager.checkAndGetSessionAndWindowId();
|
|
4910
|
+
if (config?.endpoint) {
|
|
4911
|
+
this._endpoint = config?.endpoint;
|
|
4912
|
+
}
|
|
4913
|
+
if (config?.triggerMatchType === 'any') {
|
|
4914
|
+
this._statusMatcher = anyMatchSessionRecordingStatus;
|
|
4915
|
+
this._triggerMatching = new OrTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching]);
|
|
4916
|
+
} else {
|
|
4917
|
+
// either the setting is "ALL"
|
|
4918
|
+
// or we default to the most restrictive
|
|
4919
|
+
this._statusMatcher = allMatchSessionRecordingStatus;
|
|
4920
|
+
this._triggerMatching = new AndTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching]);
|
|
4921
|
+
}
|
|
4922
|
+
this._instance.registerForSession({
|
|
4923
|
+
$sdk_debug_replay_remote_trigger_matching_config: config?.triggerMatchType ?? null
|
|
4924
|
+
});
|
|
4925
|
+
this._urlTriggerMatching.onConfig(config);
|
|
4926
|
+
this._eventTriggerMatching.onConfig(config);
|
|
4927
|
+
this._removeEventTriggerCaptureHook?.();
|
|
4928
|
+
this._addEventTriggerListener();
|
|
4929
|
+
this._linkedFlagMatching.onConfig(config, (flag, variant) => {
|
|
4930
|
+
this._reportStarted('linked_flag_matched', {
|
|
4931
|
+
flag,
|
|
4932
|
+
variant
|
|
4933
|
+
});
|
|
4934
|
+
});
|
|
4935
|
+
this._makeSamplingDecision(this.sessionId);
|
|
4936
|
+
this._startRecorder();
|
|
4937
|
+
// calling addEventListener multiple times is safe and will not add duplicates
|
|
4938
|
+
addEventListener(win, 'beforeunload', this._onBeforeUnload);
|
|
4939
|
+
addEventListener(win, 'offline', this._onOffline);
|
|
4940
|
+
addEventListener(win, 'online', this._onOnline);
|
|
4941
|
+
addEventListener(win, 'visibilitychange', this._onVisibilityChange);
|
|
4942
|
+
if (!this._onSessionIdListener) {
|
|
4943
|
+
this._onSessionIdListener = this._sessionManager.onSessionId(this._onSessionIdCallback);
|
|
4944
|
+
}
|
|
4945
|
+
if (!this._onSessionIdleResetForcedListener) {
|
|
4946
|
+
this._onSessionIdleResetForcedListener = this._sessionManager.on('forcedIdleReset', () => {
|
|
4947
|
+
// a session was forced to reset due to idle timeout and lack of activity
|
|
4948
|
+
this._clearConditionalRecordingPersistence();
|
|
4949
|
+
this._isIdle = 'unknown';
|
|
4950
|
+
this.stop();
|
|
4951
|
+
// then we want a session id listener to restart the recording when a new session starts
|
|
4952
|
+
this._forceIdleSessionIdListener = this._sessionManager.onSessionId((sessionId, windowId, changeReason) => {
|
|
4953
|
+
// this should first unregister itself
|
|
4954
|
+
this._forceIdleSessionIdListener?.();
|
|
4955
|
+
this._forceIdleSessionIdListener = undefined;
|
|
4956
|
+
this._onSessionIdCallback(sessionId, windowId, changeReason);
|
|
4957
|
+
});
|
|
4958
|
+
});
|
|
4959
|
+
}
|
|
4960
|
+
if (core.isNullish(this._removePageViewCaptureHook)) {
|
|
4961
|
+
// :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.
|
|
4962
|
+
// Dropping the initial event is fine (it's always captured by rrweb).
|
|
4963
|
+
this._removePageViewCaptureHook = this._instance.on('eventCaptured', event => {
|
|
4964
|
+
// If anything could go wrong here,
|
|
4965
|
+
// it has the potential to block the main loop,
|
|
4966
|
+
// so we catch all errors.
|
|
4967
|
+
try {
|
|
4968
|
+
if (event.event === '$pageview') {
|
|
4969
|
+
const href = event?.properties.$current_url ? this._maskUrl(event?.properties.$current_url) : '';
|
|
4970
|
+
if (!href) {
|
|
4971
|
+
return;
|
|
4972
|
+
}
|
|
4973
|
+
this._tryAddCustomEvent('$pageview', {
|
|
4974
|
+
href
|
|
4975
|
+
});
|
|
4976
|
+
}
|
|
4977
|
+
} catch (e) {
|
|
4978
|
+
logger.error('Could not add $pageview to rrweb session', e);
|
|
4979
|
+
}
|
|
4980
|
+
});
|
|
4981
|
+
}
|
|
4982
|
+
if (this.status === ACTIVE) {
|
|
4983
|
+
this._reportStarted(startReason || 'recording_initialized');
|
|
4984
|
+
}
|
|
4985
|
+
}
|
|
4986
|
+
stop() {
|
|
4987
|
+
win?.removeEventListener('beforeunload', this._onBeforeUnload);
|
|
4988
|
+
win?.removeEventListener('offline', this._onOffline);
|
|
4989
|
+
win?.removeEventListener('online', this._onOnline);
|
|
4990
|
+
win?.removeEventListener('visibilitychange', this._onVisibilityChange);
|
|
4991
|
+
this._clearBuffer();
|
|
4992
|
+
clearInterval(this._fullSnapshotTimer);
|
|
4993
|
+
this._clearFlushBufferTimer();
|
|
4994
|
+
this._removePageViewCaptureHook?.();
|
|
4995
|
+
this._removePageViewCaptureHook = undefined;
|
|
4996
|
+
this._removeEventTriggerCaptureHook?.();
|
|
4997
|
+
this._removeEventTriggerCaptureHook = undefined;
|
|
4998
|
+
this._onSessionIdListener?.();
|
|
4999
|
+
this._onSessionIdListener = undefined;
|
|
5000
|
+
this._onSessionIdleResetForcedListener?.();
|
|
5001
|
+
this._onSessionIdleResetForcedListener = undefined;
|
|
5002
|
+
this._samplingSessionListener?.();
|
|
5003
|
+
this._samplingSessionListener = undefined;
|
|
5004
|
+
this._forceIdleSessionIdListener?.();
|
|
5005
|
+
this._forceIdleSessionIdListener = undefined;
|
|
5006
|
+
this._eventTriggerMatching.stop();
|
|
5007
|
+
this._urlTriggerMatching.stop();
|
|
5008
|
+
this._linkedFlagMatching.stop();
|
|
5009
|
+
this._mutationThrottler?.stop();
|
|
5010
|
+
// Clear any queued rrweb events to prevent memory leaks from closures
|
|
5011
|
+
this._queuedRRWebEvents = [];
|
|
5012
|
+
this._stopRrweb?.();
|
|
5013
|
+
this._stopRrweb = undefined;
|
|
5014
|
+
logger.info('stopped');
|
|
5015
|
+
}
|
|
5016
|
+
onRRwebEmit(rawEvent) {
|
|
5017
|
+
this._processQueuedEvents();
|
|
5018
|
+
if (!rawEvent || !core.isObject(rawEvent)) {
|
|
5019
|
+
return;
|
|
5020
|
+
}
|
|
5021
|
+
if (rawEvent.type === EventType.Meta) {
|
|
5022
|
+
const href = this._maskUrl(rawEvent.data.href);
|
|
5023
|
+
this._lastHref = href;
|
|
5024
|
+
if (!href) {
|
|
5025
|
+
return;
|
|
5026
|
+
}
|
|
5027
|
+
rawEvent.data.href = href;
|
|
5028
|
+
} else {
|
|
5029
|
+
this._pageViewFallBack();
|
|
5030
|
+
}
|
|
5031
|
+
// Check if the URL matches any trigger patterns
|
|
5032
|
+
this._urlTriggerMatching.checkUrlTriggerConditions(() => this._pauseRecording(), () => this._resumeRecording(), triggerType => this._activateTrigger(triggerType));
|
|
5033
|
+
// always have to check if the URL is blocked really early,
|
|
5034
|
+
// or you risk getting stuck in a loop
|
|
5035
|
+
if (this._urlTriggerMatching.urlBlocked && !isRecordingPausedEvent(rawEvent)) {
|
|
5036
|
+
return;
|
|
5037
|
+
}
|
|
5038
|
+
// we're processing a full snapshot, so we should reset the timer
|
|
5039
|
+
if (rawEvent.type === EventType.FullSnapshot) {
|
|
5040
|
+
this._scheduleFullSnapshot();
|
|
5041
|
+
// Full snapshots reset rrweb's node IDs, so clear any logged node tracking
|
|
5042
|
+
this._mutationThrottler?.reset();
|
|
5043
|
+
}
|
|
5044
|
+
// Clear the buffer if waiting for a trigger and only keep data from after the current full snapshot
|
|
5045
|
+
// we always start trigger pending so need to wait for flags before we know if we're really pending
|
|
5046
|
+
if (rawEvent.type === EventType.FullSnapshot && this._triggerMatching.triggerStatus(this.sessionId) === TRIGGER_PENDING) {
|
|
5047
|
+
this._clearBufferBeforeMostRecentMeta();
|
|
5048
|
+
}
|
|
5049
|
+
const throttledEvent = this._mutationThrottler ? this._mutationThrottler.throttleMutations(rawEvent) : rawEvent;
|
|
5050
|
+
if (!throttledEvent) {
|
|
5051
|
+
return;
|
|
5052
|
+
}
|
|
5053
|
+
// TODO: Re-add ensureMaxMessageSize once we are confident in it
|
|
5054
|
+
const event = truncateLargeConsoleLogs(throttledEvent);
|
|
5055
|
+
this._updateWindowAndSessionIds(event);
|
|
5056
|
+
// When in an idle state we keep recording but don't capture the events,
|
|
5057
|
+
// we don't want to return early if idle is 'unknown'
|
|
5058
|
+
if (this._isIdle === true && !isSessionIdleEvent(event)) {
|
|
5059
|
+
return;
|
|
5060
|
+
}
|
|
5061
|
+
if (isSessionIdleEvent(event)) {
|
|
5062
|
+
// session idle events have a timestamp when rrweb sees them
|
|
5063
|
+
// which can artificially lengthen a session
|
|
5064
|
+
// we know when we detected it based on the payload and can correct the timestamp
|
|
5065
|
+
const payload = event.data.payload;
|
|
5066
|
+
if (payload) {
|
|
5067
|
+
const lastActivity = payload.lastActivityTimestamp;
|
|
5068
|
+
const threshold = payload.threshold;
|
|
5069
|
+
event.timestamp = lastActivity + threshold;
|
|
5070
|
+
}
|
|
5071
|
+
}
|
|
5072
|
+
const eventToSend = this._instance.config.session_recording?.compress_events ?? true ? compressEvent(event) : event;
|
|
5073
|
+
const size = estimateSize(eventToSend);
|
|
5074
|
+
const properties = {
|
|
5075
|
+
$snapshot_bytes: size,
|
|
5076
|
+
$snapshot_data: eventToSend,
|
|
5077
|
+
$session_id: this._sessionId,
|
|
5078
|
+
$window_id: this._windowId
|
|
5079
|
+
};
|
|
5080
|
+
if (this.status === DISABLED) {
|
|
5081
|
+
this._clearBuffer();
|
|
5082
|
+
return;
|
|
5083
|
+
}
|
|
5084
|
+
this._captureSnapshotBuffered(properties);
|
|
5085
|
+
}
|
|
5086
|
+
get status() {
|
|
5087
|
+
return this._statusMatcher({
|
|
5088
|
+
// can't get here without recording being enabled...
|
|
5089
|
+
receivedFlags: true,
|
|
5090
|
+
isRecordingEnabled: true,
|
|
5091
|
+
// things that do still vary
|
|
5092
|
+
isSampled: this._isSampled,
|
|
5093
|
+
urlTriggerMatching: this._urlTriggerMatching,
|
|
5094
|
+
eventTriggerMatching: this._eventTriggerMatching,
|
|
5095
|
+
linkedFlagMatching: this._linkedFlagMatching,
|
|
5096
|
+
sessionId: this.sessionId
|
|
5097
|
+
});
|
|
5098
|
+
}
|
|
5099
|
+
log(message, level = 'log') {
|
|
5100
|
+
this._instance.sessionRecording?.onRRwebEmit({
|
|
5101
|
+
type: 6,
|
|
5102
|
+
data: {
|
|
5103
|
+
plugin: 'rrweb/console@1',
|
|
5104
|
+
payload: {
|
|
5105
|
+
level,
|
|
5106
|
+
trace: [],
|
|
5107
|
+
// Even though it is a string, we stringify it as that's what rrweb expects
|
|
5108
|
+
payload: [JSON.stringify(message)]
|
|
5109
|
+
}
|
|
5110
|
+
},
|
|
5111
|
+
timestamp: Date.now()
|
|
5112
|
+
});
|
|
5113
|
+
}
|
|
5114
|
+
overrideLinkedFlag() {
|
|
5115
|
+
this._linkedFlagMatching.linkedFlagSeen = true;
|
|
5116
|
+
this._tryTakeFullSnapshot();
|
|
5117
|
+
this._reportStarted('linked_flag_overridden');
|
|
5118
|
+
}
|
|
5119
|
+
/**
|
|
5120
|
+
* this ignores the sampling config and (if other conditions are met) causes capture to start
|
|
5121
|
+
*
|
|
5122
|
+
* It is not usual to call this directly,
|
|
5123
|
+
* instead call `posthog.startSessionRecording({sampling: true})`
|
|
5124
|
+
* */
|
|
5125
|
+
overrideSampling() {
|
|
5126
|
+
this._instance.persistence?.register({
|
|
5127
|
+
// short-circuits the `makeSamplingDecision` function in the session recording module
|
|
5128
|
+
[SESSION_RECORDING_IS_SAMPLED]: this.sessionId
|
|
5129
|
+
});
|
|
5130
|
+
this._tryTakeFullSnapshot();
|
|
5131
|
+
this._reportStarted('sampling_overridden');
|
|
5132
|
+
}
|
|
5133
|
+
/**
|
|
5134
|
+
* this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start
|
|
5135
|
+
*
|
|
5136
|
+
* It is not usual to call this directly,
|
|
5137
|
+
* instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`
|
|
5138
|
+
* */
|
|
5139
|
+
overrideTrigger(triggerType) {
|
|
5140
|
+
this._activateTrigger(triggerType);
|
|
5141
|
+
}
|
|
5142
|
+
_clearFlushBufferTimer() {
|
|
5143
|
+
if (this._flushBufferTimer) {
|
|
5144
|
+
clearTimeout(this._flushBufferTimer);
|
|
5145
|
+
this._flushBufferTimer = undefined;
|
|
5146
|
+
}
|
|
5147
|
+
}
|
|
5148
|
+
_flushBuffer() {
|
|
5149
|
+
this._clearFlushBufferTimer();
|
|
5150
|
+
const minimumDuration = this._minimumDuration;
|
|
5151
|
+
const sessionDuration = this._sessionDuration;
|
|
5152
|
+
// if we have old data in the buffer but the session has rotated, then the
|
|
5153
|
+
// session duration might be negative. In that case we want to flush the buffer
|
|
5154
|
+
const isPositiveSessionDuration = core.isNumber(sessionDuration) && sessionDuration >= 0;
|
|
5155
|
+
const isBelowMinimumDuration = core.isNumber(minimumDuration) && isPositiveSessionDuration && sessionDuration < minimumDuration;
|
|
5156
|
+
if (this.status === BUFFERING || this.status === PAUSED || this.status === DISABLED || isBelowMinimumDuration) {
|
|
5157
|
+
this._flushBufferTimer = setTimeout(() => {
|
|
5158
|
+
this._flushBuffer();
|
|
5159
|
+
}, RECORDING_BUFFER_TIMEOUT);
|
|
5160
|
+
return this._buffer;
|
|
5161
|
+
}
|
|
5162
|
+
if (this._buffer.data.length > 0) {
|
|
5163
|
+
const snapshotEvents = splitBuffer(this._buffer);
|
|
5164
|
+
snapshotEvents.forEach(snapshotBuffer => {
|
|
5165
|
+
this._captureSnapshot({
|
|
5166
|
+
$snapshot_bytes: snapshotBuffer.size,
|
|
5167
|
+
$snapshot_data: snapshotBuffer.data,
|
|
5168
|
+
$session_id: snapshotBuffer.sessionId,
|
|
5169
|
+
$window_id: snapshotBuffer.windowId,
|
|
5170
|
+
$lib: 'web',
|
|
5171
|
+
$lib_version: Config.LIB_VERSION
|
|
5172
|
+
});
|
|
5173
|
+
});
|
|
5174
|
+
}
|
|
5175
|
+
// buffer is empty, we clear it in case the session id has changed
|
|
5176
|
+
return this._clearBuffer();
|
|
5177
|
+
}
|
|
5178
|
+
_captureSnapshotBuffered(properties) {
|
|
5179
|
+
const additionalBytes = 2 + (this._buffer?.data.length || 0); // 2 bytes for the array brackets and 1 byte for each comma
|
|
5180
|
+
if (!this._isIdle && (
|
|
5181
|
+
// we never want to flush when idle
|
|
5182
|
+
this._buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE || this._buffer.sessionId !== this._sessionId)) {
|
|
5183
|
+
this._buffer = this._flushBuffer();
|
|
5184
|
+
}
|
|
5185
|
+
this._buffer.size += properties.$snapshot_bytes;
|
|
5186
|
+
this._buffer.data.push(properties.$snapshot_data);
|
|
5187
|
+
if (!this._flushBufferTimer && !this._isIdle) {
|
|
5188
|
+
this._flushBufferTimer = setTimeout(() => {
|
|
5189
|
+
this._flushBuffer();
|
|
5190
|
+
}, RECORDING_BUFFER_TIMEOUT);
|
|
5191
|
+
}
|
|
5192
|
+
}
|
|
5193
|
+
_captureSnapshot(properties) {
|
|
5194
|
+
// :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.
|
|
5195
|
+
this._instance.capture('$snapshot', properties, {
|
|
5196
|
+
_url: this._instance.requestRouter.endpointFor('api', this._endpoint),
|
|
5197
|
+
_noTruncate: true,
|
|
5198
|
+
_batchKey: SESSION_RECORDING_BATCH_KEY,
|
|
5199
|
+
skip_client_rate_limiting: true
|
|
5200
|
+
});
|
|
5201
|
+
}
|
|
5202
|
+
_snapshotUrl() {
|
|
5203
|
+
const host = this._instance.config.host || '';
|
|
5204
|
+
try {
|
|
5205
|
+
// eslint-disable-next-line compat/compat
|
|
5206
|
+
return new URL(this._endpoint, host).href;
|
|
5207
|
+
} catch {
|
|
5208
|
+
const normalizedHost = host.endsWith('/') ? host.slice(0, -1) : host;
|
|
5209
|
+
const normalizedEndpoint = this._endpoint.startsWith('/') ? this._endpoint.slice(1) : this._endpoint;
|
|
5210
|
+
return `${normalizedHost}/${normalizedEndpoint}`;
|
|
5211
|
+
}
|
|
5212
|
+
}
|
|
5213
|
+
get _sessionDuration() {
|
|
5214
|
+
const mostRecentSnapshot = this._buffer?.data[this._buffer?.data.length - 1];
|
|
5215
|
+
const {
|
|
5216
|
+
sessionStartTimestamp
|
|
5217
|
+
} = this._sessionManager.checkAndGetSessionAndWindowId(true);
|
|
5218
|
+
return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null;
|
|
5219
|
+
}
|
|
5220
|
+
_clearBufferBeforeMostRecentMeta() {
|
|
5221
|
+
if (!this._buffer || this._buffer.data.length === 0) {
|
|
5222
|
+
return this._clearBuffer();
|
|
5223
|
+
}
|
|
5224
|
+
// Find the last meta event index by iterating backwards
|
|
5225
|
+
let lastMetaIndex = -1;
|
|
5226
|
+
for (let i = this._buffer.data.length - 1; i >= 0; i--) {
|
|
5227
|
+
if (this._buffer.data[i].type === EventType.Meta) {
|
|
5228
|
+
lastMetaIndex = i;
|
|
5229
|
+
break;
|
|
5230
|
+
}
|
|
5231
|
+
}
|
|
5232
|
+
if (lastMetaIndex >= 0) {
|
|
5233
|
+
this._buffer.data = this._buffer.data.slice(lastMetaIndex);
|
|
5234
|
+
this._buffer.size = this._buffer.data.reduce((acc, curr) => acc + estimateSize(curr), 0);
|
|
5235
|
+
return this._buffer;
|
|
5236
|
+
} else {
|
|
5237
|
+
return this._clearBuffer();
|
|
5238
|
+
}
|
|
5239
|
+
}
|
|
5240
|
+
_clearBuffer() {
|
|
5241
|
+
this._buffer = {
|
|
5242
|
+
size: 0,
|
|
5243
|
+
data: [],
|
|
5244
|
+
sessionId: this._sessionId,
|
|
5245
|
+
windowId: this._windowId
|
|
5246
|
+
};
|
|
5247
|
+
return this._buffer;
|
|
5248
|
+
}
|
|
5249
|
+
_reportStarted(startReason, tagPayload) {
|
|
5250
|
+
this._instance.registerForSession({
|
|
5251
|
+
$session_recording_start_reason: startReason
|
|
5252
|
+
});
|
|
5253
|
+
logger.info(startReason.replace('_', ' '), tagPayload);
|
|
5254
|
+
if (!core.includes(['recording_initialized', 'session_id_changed'], startReason)) {
|
|
5255
|
+
this._tryAddCustomEvent(startReason, tagPayload);
|
|
5256
|
+
}
|
|
5257
|
+
}
|
|
5258
|
+
_isInteractiveEvent(event) {
|
|
5259
|
+
return event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE && ACTIVE_SOURCES.indexOf(event.data?.source) !== -1;
|
|
5260
|
+
}
|
|
5261
|
+
_updateWindowAndSessionIds(event) {
|
|
5262
|
+
// Some recording events are triggered by non-user events (e.g. "X minutes ago" text updating on the screen).
|
|
5263
|
+
// We don't want to extend the session or trigger a new session in these cases. These events are designated by event
|
|
5264
|
+
// type -> incremental update, and source -> mutation.
|
|
5265
|
+
const isUserInteraction = this._isInteractiveEvent(event);
|
|
5266
|
+
if (!isUserInteraction && !this._isIdle) {
|
|
5267
|
+
// We check if the lastActivityTimestamp is old enough to go idle
|
|
5268
|
+
const timeSinceLastActivity = event.timestamp - this._lastActivityTimestamp;
|
|
5269
|
+
if (timeSinceLastActivity > this._sessionIdleThresholdMilliseconds) {
|
|
5270
|
+
// we mark as idle right away,
|
|
5271
|
+
// or else we get multiple idle events
|
|
5272
|
+
// if there are lots of non-user activity events being emitted
|
|
5273
|
+
this._isIdle = true;
|
|
5274
|
+
// don't take full snapshots while idle
|
|
5275
|
+
clearInterval(this._fullSnapshotTimer);
|
|
5276
|
+
this._tryAddCustomEvent('sessionIdle', {
|
|
5277
|
+
eventTimestamp: event.timestamp,
|
|
5278
|
+
lastActivityTimestamp: this._lastActivityTimestamp,
|
|
5279
|
+
threshold: this._sessionIdleThresholdMilliseconds,
|
|
5280
|
+
bufferLength: this._buffer.data.length,
|
|
5281
|
+
bufferSize: this._buffer.size
|
|
5282
|
+
});
|
|
5283
|
+
// proactively flush the buffer in case the session is idle for a long time
|
|
5284
|
+
this._flushBuffer();
|
|
5285
|
+
}
|
|
5286
|
+
}
|
|
5287
|
+
let returningFromIdle = false;
|
|
5288
|
+
if (isUserInteraction) {
|
|
5289
|
+
this._lastActivityTimestamp = event.timestamp;
|
|
5290
|
+
if (this._isIdle) {
|
|
5291
|
+
const idleWasUnknown = this._isIdle === 'unknown';
|
|
5292
|
+
// Remove the idle state
|
|
5293
|
+
this._isIdle = false;
|
|
5294
|
+
// if the idle state was unknown, we don't want to add an event, since we're just in bootup
|
|
5295
|
+
// whereas if it was true, we know we've been idle for a while, and we can mark ourselves as returning from idle
|
|
5296
|
+
if (!idleWasUnknown) {
|
|
5297
|
+
this._tryAddCustomEvent('sessionNoLongerIdle', {
|
|
5298
|
+
reason: 'user activity',
|
|
5299
|
+
type: event.type
|
|
5300
|
+
});
|
|
5301
|
+
returningFromIdle = true;
|
|
5302
|
+
}
|
|
5303
|
+
}
|
|
5304
|
+
}
|
|
5305
|
+
if (this._isIdle) {
|
|
5306
|
+
return;
|
|
5307
|
+
}
|
|
5308
|
+
// We only want to extend the session if it is an interactive event.
|
|
5309
|
+
const {
|
|
5310
|
+
windowId,
|
|
5311
|
+
sessionId
|
|
5312
|
+
} = this._sessionManager.checkAndGetSessionAndWindowId(!isUserInteraction, event.timestamp);
|
|
5313
|
+
const sessionIdChanged = this._sessionId !== sessionId;
|
|
5314
|
+
const windowIdChanged = this._windowId !== windowId;
|
|
5315
|
+
this._windowId = windowId;
|
|
5316
|
+
this._sessionId = sessionId;
|
|
5317
|
+
if (sessionIdChanged || windowIdChanged) {
|
|
5318
|
+
this.stop();
|
|
5319
|
+
this.start('session_id_changed');
|
|
5320
|
+
} else if (returningFromIdle) {
|
|
5321
|
+
this._scheduleFullSnapshot();
|
|
5322
|
+
}
|
|
5323
|
+
}
|
|
5324
|
+
_clearConditionalRecordingPersistence() {
|
|
5325
|
+
this._instance?.persistence?.unregister(SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION);
|
|
5326
|
+
this._instance?.persistence?.unregister(SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION);
|
|
5327
|
+
this._instance?.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED);
|
|
5328
|
+
}
|
|
5329
|
+
_makeSamplingDecision(sessionId) {
|
|
5330
|
+
const sessionIdChanged = this._sessionId !== sessionId;
|
|
5331
|
+
// capture the current sample rate
|
|
5332
|
+
// because it is re-used multiple times
|
|
5333
|
+
// and the bundler won't minimize any of the references
|
|
5334
|
+
const currentSampleRate = this._sampleRate;
|
|
5335
|
+
if (!core.isNumber(currentSampleRate)) {
|
|
5336
|
+
this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED);
|
|
5337
|
+
return;
|
|
5338
|
+
}
|
|
5339
|
+
const storedIsSampled = this._isSampled;
|
|
5340
|
+
/**
|
|
5341
|
+
* if we get this far, then we should make a sampling decision.
|
|
5342
|
+
* When the session id changes or there is no stored sampling decision for this session id
|
|
5343
|
+
* then we should make a new decision.
|
|
5344
|
+
*
|
|
5345
|
+
* Otherwise, we should use the stored decision.
|
|
5346
|
+
*/
|
|
5347
|
+
const makeDecision = sessionIdChanged || !core.isBoolean(storedIsSampled);
|
|
5348
|
+
const shouldSample = makeDecision ? sampleOnProperty(sessionId, currentSampleRate) : storedIsSampled;
|
|
5349
|
+
if (makeDecision) {
|
|
5350
|
+
if (shouldSample) {
|
|
5351
|
+
this._reportStarted(SAMPLED);
|
|
5352
|
+
} else {
|
|
5353
|
+
logger.warn(`Sample rate (${currentSampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`);
|
|
5354
|
+
}
|
|
5355
|
+
this._tryAddCustomEvent('samplingDecisionMade', {
|
|
5356
|
+
sampleRate: currentSampleRate,
|
|
5357
|
+
isSampled: shouldSample
|
|
5358
|
+
});
|
|
5359
|
+
}
|
|
5360
|
+
this._instance.persistence?.register({
|
|
5361
|
+
[SESSION_RECORDING_IS_SAMPLED]: shouldSample ? sessionId : false
|
|
5362
|
+
});
|
|
5363
|
+
}
|
|
5364
|
+
_addEventTriggerListener() {
|
|
5365
|
+
if (this._eventTriggerMatching._eventTriggers.length === 0 || !core.isNullish(this._removeEventTriggerCaptureHook)) {
|
|
5366
|
+
return;
|
|
5367
|
+
}
|
|
5368
|
+
this._removeEventTriggerCaptureHook = this._instance.on('eventCaptured', event => {
|
|
5369
|
+
// If anything could go wrong here, it has the potential to block the main loop,
|
|
5370
|
+
// so we catch all errors.
|
|
5371
|
+
try {
|
|
5372
|
+
if (this._eventTriggerMatching._eventTriggers.includes(event.event)) {
|
|
5373
|
+
this._activateTrigger('event');
|
|
5374
|
+
}
|
|
5375
|
+
} catch (e) {
|
|
5376
|
+
logger.error('Could not activate event trigger', e);
|
|
5377
|
+
}
|
|
5378
|
+
});
|
|
5379
|
+
}
|
|
5380
|
+
get sdkDebugProperties() {
|
|
5381
|
+
const {
|
|
5382
|
+
sessionStartTimestamp
|
|
5383
|
+
} = this._sessionManager.checkAndGetSessionAndWindowId(true);
|
|
5384
|
+
return {
|
|
5385
|
+
$recording_status: this.status,
|
|
5386
|
+
$sdk_debug_replay_internal_buffer_length: this._buffer.data.length,
|
|
5387
|
+
$sdk_debug_replay_internal_buffer_size: this._buffer.size,
|
|
5388
|
+
$sdk_debug_current_session_duration: this._sessionDuration,
|
|
5389
|
+
$sdk_debug_session_start: sessionStartTimestamp
|
|
5390
|
+
};
|
|
5391
|
+
}
|
|
5392
|
+
_startRecorder() {
|
|
5393
|
+
if (this._stopRrweb) {
|
|
5394
|
+
return;
|
|
5395
|
+
}
|
|
5396
|
+
// rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28
|
|
5397
|
+
const sessionRecordingOptions = {
|
|
5398
|
+
// a limited set of the rrweb config options that we expose to our users.
|
|
5399
|
+
// see https://github.com/rrweb-io/rrweb/blob/master/guide.md
|
|
5400
|
+
blockClass: 'ph-no-capture',
|
|
5401
|
+
blockSelector: undefined,
|
|
5402
|
+
ignoreClass: 'ph-ignore-input',
|
|
5403
|
+
maskTextClass: 'ph-mask',
|
|
5404
|
+
maskTextSelector: undefined,
|
|
5405
|
+
maskTextFn: undefined,
|
|
5406
|
+
maskAllInputs: true,
|
|
5407
|
+
maskInputOptions: {
|
|
5408
|
+
password: true
|
|
5409
|
+
},
|
|
5410
|
+
maskInputFn: undefined,
|
|
5411
|
+
slimDOMOptions: {},
|
|
5412
|
+
collectFonts: false,
|
|
5413
|
+
inlineStylesheet: true,
|
|
5414
|
+
recordCrossOriginIframes: false
|
|
5415
|
+
};
|
|
5416
|
+
// only allows user to set our allowlisted options
|
|
5417
|
+
const userSessionRecordingOptions = this._instance.config.session_recording;
|
|
5418
|
+
for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {
|
|
5419
|
+
if (key in sessionRecordingOptions) {
|
|
5420
|
+
if (key === 'maskInputOptions') {
|
|
5421
|
+
// ensure password config is set if not included
|
|
5422
|
+
sessionRecordingOptions.maskInputOptions = {
|
|
5423
|
+
password: true,
|
|
5424
|
+
...value
|
|
5425
|
+
};
|
|
5426
|
+
} else {
|
|
5427
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
5428
|
+
// @ts-ignore
|
|
5429
|
+
sessionRecordingOptions[key] = value;
|
|
5430
|
+
}
|
|
5431
|
+
}
|
|
5432
|
+
}
|
|
5433
|
+
if (this._canvasRecording && this._canvasRecording.enabled) {
|
|
5434
|
+
sessionRecordingOptions.recordCanvas = true;
|
|
5435
|
+
sessionRecordingOptions.sampling = {
|
|
5436
|
+
canvas: this._canvasRecording.fps
|
|
5437
|
+
};
|
|
5438
|
+
sessionRecordingOptions.dataURLOptions = {
|
|
5439
|
+
type: 'image/webp',
|
|
5440
|
+
quality: this._canvasRecording.quality
|
|
5441
|
+
};
|
|
5442
|
+
}
|
|
5443
|
+
if (this._masking) {
|
|
5444
|
+
sessionRecordingOptions.maskAllInputs = this._masking.maskAllInputs ?? true;
|
|
5445
|
+
sessionRecordingOptions.maskTextSelector = this._masking.maskTextSelector ?? undefined;
|
|
5446
|
+
sessionRecordingOptions.blockSelector = this._masking.blockSelector ?? undefined;
|
|
5447
|
+
}
|
|
5448
|
+
const rrwebRecord = getRRWebRecord();
|
|
5449
|
+
if (!rrwebRecord) {
|
|
5450
|
+
logger.error('_startRecorder was called but rrwebRecord is not available. This indicates something has gone wrong.');
|
|
5451
|
+
return;
|
|
5452
|
+
}
|
|
5453
|
+
this._mutationThrottler = this._mutationThrottler ?? new MutationThrottler(rrwebRecord, {
|
|
5454
|
+
refillRate: this._instance.config.session_recording?.__mutationThrottlerRefillRate,
|
|
5455
|
+
bucketSize: this._instance.config.session_recording?.__mutationThrottlerBucketSize,
|
|
5456
|
+
onBlockedNode: (id, node) => {
|
|
5457
|
+
const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`;
|
|
5458
|
+
logger.info(message, {
|
|
5459
|
+
node: node
|
|
5460
|
+
});
|
|
5461
|
+
this.log(LOGGER_PREFIX$1 + ' ' + message, 'warn');
|
|
5462
|
+
}
|
|
5463
|
+
});
|
|
5464
|
+
const activePlugins = this._gatherRRWebPlugins();
|
|
5465
|
+
this._stopRrweb = rrwebRecord({
|
|
5466
|
+
emit: event => {
|
|
5467
|
+
this.onRRwebEmit(event);
|
|
5468
|
+
},
|
|
5469
|
+
plugins: activePlugins,
|
|
5470
|
+
...sessionRecordingOptions
|
|
5471
|
+
});
|
|
5472
|
+
// We reset the last activity timestamp, resetting the idle timer
|
|
5473
|
+
this._lastActivityTimestamp = Date.now();
|
|
5474
|
+
// stay unknown if we're not sure if we're idle or not
|
|
5475
|
+
this._isIdle = core.isBoolean(this._isIdle) ? this._isIdle : 'unknown';
|
|
5476
|
+
this.tryAddCustomEvent('$remote_config_received', this._remoteConfig);
|
|
5477
|
+
this._tryAddCustomEvent('$session_options', {
|
|
5478
|
+
sessionRecordingOptions,
|
|
5479
|
+
activePlugins: activePlugins.map(p => p?.name)
|
|
5480
|
+
});
|
|
5481
|
+
this._tryAddCustomEvent('$posthog_config', {
|
|
5482
|
+
config: this._instance.config
|
|
5483
|
+
});
|
|
5484
|
+
}
|
|
5485
|
+
tryAddCustomEvent(tag, payload) {
|
|
5486
|
+
return this._tryAddCustomEvent(tag, payload);
|
|
5487
|
+
}
|
|
5488
|
+
}
|
|
5489
|
+
|
|
5490
|
+
const LOGGER_PREFIX = '[SessionRecording]';
|
|
5491
|
+
const log = {
|
|
5492
|
+
info: (...args) => logger$3.info(LOGGER_PREFIX, ...args),
|
|
5493
|
+
warn: (...args) => logger$3.warn(LOGGER_PREFIX, ...args),
|
|
5494
|
+
error: (...args) => logger$3.error(LOGGER_PREFIX, ...args)
|
|
5495
|
+
};
|
|
5496
|
+
class SessionRecording {
|
|
5497
|
+
get started() {
|
|
5498
|
+
return !!this._lazyLoadedSessionRecording?.isStarted;
|
|
5499
|
+
}
|
|
5500
|
+
/**
|
|
5501
|
+
* defaults to buffering mode until a flags response is received
|
|
5502
|
+
* once a flags response is received status can be disabled, active or sampled
|
|
5503
|
+
*/
|
|
5504
|
+
get status() {
|
|
5505
|
+
if (this._lazyLoadedSessionRecording) {
|
|
5506
|
+
return this._lazyLoadedSessionRecording.status;
|
|
5507
|
+
}
|
|
5508
|
+
if (this._receivedFlags && !this._isRecordingEnabled) {
|
|
5509
|
+
return DISABLED;
|
|
5510
|
+
}
|
|
5511
|
+
return LAZY_LOADING;
|
|
5512
|
+
}
|
|
5513
|
+
constructor(_instance) {
|
|
5514
|
+
this._instance = _instance;
|
|
5515
|
+
this._forceAllowLocalhostNetworkCapture = false;
|
|
5516
|
+
this._receivedFlags = false;
|
|
5517
|
+
this._serverRecordingEnabled = false;
|
|
5518
|
+
this._persistFlagsOnSessionListener = undefined;
|
|
5519
|
+
if (!this._instance.sessionManager) {
|
|
5520
|
+
log.error('started without valid sessionManager');
|
|
5521
|
+
throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.');
|
|
5522
|
+
}
|
|
5523
|
+
if (this._instance.config.cookieless_mode === 'always') {
|
|
5524
|
+
throw new Error(LOGGER_PREFIX + ' cannot be used with cookieless_mode="always"');
|
|
5525
|
+
}
|
|
5526
|
+
}
|
|
5527
|
+
get _isRecordingEnabled() {
|
|
5528
|
+
const enabled_server_side = !!this._instance.get_property(SESSION_RECORDING_REMOTE_CONFIG)?.enabled;
|
|
5529
|
+
const enabled_client_side = !this._instance.config.disable_session_recording;
|
|
5530
|
+
const isDisabled = this._instance.config.disable_session_recording || this._instance.consent?.isOptedOut?.();
|
|
5531
|
+
return win && enabled_server_side && enabled_client_side && !isDisabled;
|
|
5532
|
+
}
|
|
5533
|
+
startIfEnabledOrStop(startReason) {
|
|
5534
|
+
if (this._isRecordingEnabled && this._lazyLoadedSessionRecording?.isStarted) {
|
|
5535
|
+
return;
|
|
5536
|
+
}
|
|
5537
|
+
const canRunReplay = !core.isUndefined(Object.assign) && !core.isUndefined(Array.from);
|
|
5538
|
+
if (this._isRecordingEnabled && canRunReplay) {
|
|
5539
|
+
this._lazyLoadAndStart(startReason);
|
|
5540
|
+
log.info('starting');
|
|
5541
|
+
} else {
|
|
5542
|
+
this.stopRecording();
|
|
5543
|
+
}
|
|
5544
|
+
}
|
|
5545
|
+
/**
|
|
5546
|
+
* session recording waits until it receives remote config before loading the script
|
|
5547
|
+
* this is to ensure we can control the script name remotely
|
|
5548
|
+
* and because we wait until we have local and remote config to determine if we should start at all
|
|
5549
|
+
* if start is called and there is no remote config then we wait until there is
|
|
5550
|
+
*/
|
|
5551
|
+
_lazyLoadAndStart(startReason) {
|
|
5552
|
+
// by checking `_isRecordingEnabled` here we know that
|
|
5553
|
+
// we have stored remote config and client config to read
|
|
5554
|
+
// replay waits for both local and remote config before starting
|
|
5555
|
+
if (!this._isRecordingEnabled) {
|
|
5556
|
+
return;
|
|
5557
|
+
}
|
|
5558
|
+
this._onScriptLoaded(startReason);
|
|
5559
|
+
}
|
|
5560
|
+
stopRecording() {
|
|
5561
|
+
this._persistFlagsOnSessionListener?.();
|
|
5562
|
+
this._persistFlagsOnSessionListener = undefined;
|
|
5563
|
+
this._lazyLoadedSessionRecording?.stop();
|
|
5564
|
+
}
|
|
5565
|
+
_resetSampling() {
|
|
5566
|
+
this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED);
|
|
5567
|
+
}
|
|
5568
|
+
_persistRemoteConfig(response) {
|
|
5569
|
+
if (this._instance.persistence) {
|
|
5570
|
+
const persistence = this._instance.persistence;
|
|
5571
|
+
const persistResponse = () => {
|
|
5572
|
+
const sessionRecordingConfigResponse = response.sessionRecording === false ? undefined : response.sessionRecording;
|
|
5573
|
+
const receivedSampleRate = sessionRecordingConfigResponse?.sampleRate;
|
|
5574
|
+
const parsedSampleRate = core.isNullish(receivedSampleRate) ? null : parseFloat(receivedSampleRate);
|
|
5575
|
+
if (core.isNullish(parsedSampleRate)) {
|
|
5576
|
+
this._resetSampling();
|
|
5577
|
+
}
|
|
5578
|
+
const receivedMinimumDuration = sessionRecordingConfigResponse?.minimumDurationMilliseconds;
|
|
5579
|
+
persistence.register({
|
|
5580
|
+
[SESSION_RECORDING_REMOTE_CONFIG]: {
|
|
5581
|
+
enabled: !!sessionRecordingConfigResponse,
|
|
5582
|
+
...sessionRecordingConfigResponse,
|
|
5583
|
+
networkPayloadCapture: {
|
|
5584
|
+
capturePerformance: response.capturePerformance,
|
|
5585
|
+
...sessionRecordingConfigResponse?.networkPayloadCapture
|
|
5586
|
+
},
|
|
5587
|
+
canvasRecording: {
|
|
5588
|
+
enabled: sessionRecordingConfigResponse?.recordCanvas,
|
|
5589
|
+
fps: sessionRecordingConfigResponse?.canvasFps,
|
|
5590
|
+
quality: sessionRecordingConfigResponse?.canvasQuality
|
|
5591
|
+
},
|
|
5592
|
+
sampleRate: parsedSampleRate,
|
|
5593
|
+
minimumDurationMilliseconds: core.isUndefined(receivedMinimumDuration) ? null : receivedMinimumDuration,
|
|
5594
|
+
endpoint: sessionRecordingConfigResponse?.endpoint,
|
|
5595
|
+
triggerMatchType: sessionRecordingConfigResponse?.triggerMatchType,
|
|
5596
|
+
masking: sessionRecordingConfigResponse?.masking,
|
|
5597
|
+
urlTriggers: sessionRecordingConfigResponse?.urlTriggers
|
|
5598
|
+
}
|
|
5599
|
+
});
|
|
5600
|
+
};
|
|
5601
|
+
persistResponse();
|
|
5602
|
+
// in case we see multiple flags responses, we should only use the response from the most recent one
|
|
5603
|
+
this._persistFlagsOnSessionListener?.();
|
|
5604
|
+
// we 100% know there is a session manager by this point
|
|
5605
|
+
this._persistFlagsOnSessionListener = this._instance.sessionManager?.onSessionId(persistResponse);
|
|
5606
|
+
}
|
|
5607
|
+
}
|
|
5608
|
+
_clearRemoteConfig() {
|
|
5609
|
+
this._instance.persistence?.unregister(SESSION_RECORDING_REMOTE_CONFIG);
|
|
5610
|
+
this._resetSampling();
|
|
5611
|
+
}
|
|
5612
|
+
onRemoteConfig(response) {
|
|
5613
|
+
if (!('sessionRecording' in response)) {
|
|
5614
|
+
// if sessionRecording is not in the response, we do nothing
|
|
5615
|
+
log.info('skipping remote config with no sessionRecording', response);
|
|
5616
|
+
return;
|
|
5617
|
+
}
|
|
5618
|
+
this._receivedFlags = true;
|
|
5619
|
+
if (response.sessionRecording === false) {
|
|
5620
|
+
this._serverRecordingEnabled = false;
|
|
5621
|
+
this._clearRemoteConfig();
|
|
5622
|
+
this.stopRecording();
|
|
5623
|
+
return;
|
|
5624
|
+
}
|
|
5625
|
+
this._serverRecordingEnabled = true;
|
|
5626
|
+
this._persistRemoteConfig(response);
|
|
5627
|
+
this.startIfEnabledOrStop();
|
|
5628
|
+
}
|
|
5629
|
+
log(message, level = 'log') {
|
|
5630
|
+
if (this._lazyLoadedSessionRecording?.log) {
|
|
5631
|
+
this._lazyLoadedSessionRecording.log(message, level);
|
|
5632
|
+
} else {
|
|
5633
|
+
logger$3.warn('log called before recorder was ready');
|
|
5634
|
+
}
|
|
5635
|
+
}
|
|
5636
|
+
_onScriptLoaded(startReason) {
|
|
5637
|
+
if (!this._lazyLoadedSessionRecording) {
|
|
5638
|
+
this._lazyLoadedSessionRecording = new LazyLoadedSessionRecording(this._instance);
|
|
5639
|
+
this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture = this._forceAllowLocalhostNetworkCapture;
|
|
5640
|
+
}
|
|
5641
|
+
this._lazyLoadedSessionRecording.start(startReason);
|
|
5642
|
+
}
|
|
5643
|
+
/**
|
|
5644
|
+
* this is maintained on the public API only because it has always been on the public API
|
|
5645
|
+
* if you are calling this directly you are certainly doing something wrong
|
|
5646
|
+
* @deprecated
|
|
5647
|
+
*/
|
|
5648
|
+
onRRwebEmit(rawEvent) {
|
|
5649
|
+
this._lazyLoadedSessionRecording?.onRRwebEmit?.(rawEvent);
|
|
5650
|
+
}
|
|
5651
|
+
/**
|
|
5652
|
+
* this ignores the linked flag config and (if other conditions are met) causes capture to start
|
|
5653
|
+
*
|
|
5654
|
+
* It is not usual to call this directly,
|
|
5655
|
+
* instead call `posthog.startSessionRecording({linked_flag: true})`
|
|
5656
|
+
* */
|
|
5657
|
+
overrideLinkedFlag() {
|
|
5658
|
+
// TODO what if this gets called before lazy loading is done
|
|
5659
|
+
this._lazyLoadedSessionRecording?.overrideLinkedFlag();
|
|
5660
|
+
}
|
|
5661
|
+
/**
|
|
5662
|
+
* this ignores the sampling config and (if other conditions are met) causes capture to start
|
|
5663
|
+
*
|
|
5664
|
+
* It is not usual to call this directly,
|
|
5665
|
+
* instead call `posthog.startSessionRecording({sampling: true})`
|
|
5666
|
+
* */
|
|
5667
|
+
overrideSampling() {
|
|
5668
|
+
// TODO what if this gets called before lazy loading is done
|
|
5669
|
+
this._lazyLoadedSessionRecording?.overrideSampling();
|
|
5670
|
+
}
|
|
5671
|
+
/**
|
|
5672
|
+
* this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start
|
|
5673
|
+
*
|
|
5674
|
+
* It is not usual to call this directly,
|
|
5675
|
+
* instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`
|
|
5676
|
+
* */
|
|
5677
|
+
overrideTrigger(triggerType) {
|
|
5678
|
+
// TODO what if this gets called before lazy loading is done
|
|
5679
|
+
this._lazyLoadedSessionRecording?.overrideTrigger(triggerType);
|
|
5680
|
+
}
|
|
5681
|
+
/*
|
|
5682
|
+
* whenever we capture an event, we add these properties to the event
|
|
5683
|
+
* these are used to debug issues with the session recording
|
|
5684
|
+
* when looking at the event feed for a session
|
|
5685
|
+
*/
|
|
5686
|
+
get sdkDebugProperties() {
|
|
5687
|
+
return this._lazyLoadedSessionRecording?.sdkDebugProperties || {
|
|
5688
|
+
$recording_status: this.status
|
|
5689
|
+
};
|
|
5690
|
+
}
|
|
5691
|
+
/**
|
|
5692
|
+
* This adds a custom event to the session recording
|
|
5693
|
+
*
|
|
5694
|
+
* It is not intended for arbitrary public use - playback only displays known custom events
|
|
5695
|
+
* And is exposed on the public interface only so that other parts of the SDK are able to use it
|
|
5696
|
+
*
|
|
5697
|
+
* if you are calling this from client code, you're probably looking for `posthog.capture('$custom_event', {...})`
|
|
5698
|
+
*/
|
|
5699
|
+
tryAddCustomEvent(tag, payload) {
|
|
5700
|
+
return !!this._lazyLoadedSessionRecording?.tryAddCustomEvent(tag, payload);
|
|
5701
|
+
}
|
|
5702
|
+
}
|
|
5703
|
+
|
|
5704
|
+
const defaultConfig = () => ({
|
|
5705
|
+
host: 'https://i.leanbase.co',
|
|
5706
|
+
token: '',
|
|
5707
|
+
autocapture: true,
|
|
5708
|
+
rageclick: true,
|
|
5709
|
+
disable_session_recording: false,
|
|
5710
|
+
session_recording: {
|
|
5711
|
+
// Force-enable session recording locally unless explicitly disabled via config
|
|
5712
|
+
forceClientRecording: true
|
|
5713
|
+
},
|
|
5714
|
+
enable_recording_console_log: undefined,
|
|
5715
|
+
persistence: 'localStorage+cookie',
|
|
5716
|
+
capture_pageview: 'history_change',
|
|
5717
|
+
capture_pageleave: 'if_capture_pageview',
|
|
5718
|
+
persistence_name: '',
|
|
5719
|
+
mask_all_element_attributes: false,
|
|
5720
|
+
cookie_expiration: 365,
|
|
5721
|
+
cross_subdomain_cookie: isCrossDomainCookie(document?.location),
|
|
5722
|
+
custom_campaign_params: [],
|
|
5723
|
+
custom_personal_data_properties: [],
|
|
5724
|
+
disable_persistence: false,
|
|
5725
|
+
mask_personal_data_properties: false,
|
|
5726
|
+
secure_cookie: window?.location?.protocol === 'https:',
|
|
5727
|
+
mask_all_text: false,
|
|
5728
|
+
bootstrap: {},
|
|
5729
|
+
session_idle_timeout_seconds: 30 * 60,
|
|
5730
|
+
save_campaign_params: true,
|
|
5731
|
+
save_referrer: true,
|
|
5732
|
+
opt_out_useragent_filter: false,
|
|
5733
|
+
properties_string_max_length: 65535,
|
|
5734
|
+
loaded: () => {}
|
|
5735
|
+
});
|
|
5736
|
+
class Leanbase extends core.PostHogCore {
|
|
5737
|
+
constructor(token, config) {
|
|
5738
|
+
const mergedConfig = extend(defaultConfig(), config || {}, {
|
|
5739
|
+
token
|
|
5740
|
+
});
|
|
5741
|
+
super(token, mergedConfig);
|
|
5742
|
+
this.personProcessingSetOncePropertiesSent = false;
|
|
5743
|
+
this.isLoaded = false;
|
|
5744
|
+
this.config = mergedConfig;
|
|
5745
|
+
this.visibilityStateListener = null;
|
|
5746
|
+
this.initialPageviewCaptured = false;
|
|
5747
|
+
this.scrollManager = new ScrollManager(this);
|
|
5748
|
+
this.pageViewManager = new PageViewManager(this);
|
|
5749
|
+
this.init(token, mergedConfig);
|
|
5750
|
+
}
|
|
5751
|
+
init(token, config) {
|
|
5752
|
+
this.setConfig(extend(defaultConfig(), config, {
|
|
5753
|
+
token
|
|
5754
|
+
}));
|
|
5755
|
+
this.isLoaded = true;
|
|
5756
|
+
this.persistence = new LeanbasePersistence(this.config);
|
|
5757
|
+
if (this.config.cookieless_mode !== 'always') {
|
|
5758
|
+
this.sessionManager = new SessionIdManager(this);
|
|
5759
|
+
this.sessionPropsManager = new SessionPropsManager(this, this.sessionManager, this.persistence);
|
|
5760
|
+
}
|
|
5761
|
+
this.replayAutocapture = new Autocapture(this);
|
|
5762
|
+
this.replayAutocapture.startIfEnabled();
|
|
5763
|
+
if (this.sessionManager && this.config.cookieless_mode !== 'always') {
|
|
5764
|
+
this.sessionRecording = new SessionRecording(this);
|
|
5765
|
+
this.sessionRecording.startIfEnabledOrStop();
|
|
5766
|
+
}
|
|
5767
|
+
if (this.config.preloadFeatureFlags !== false) {
|
|
5768
|
+
this.reloadFeatureFlags();
|
|
5769
|
+
}
|
|
5770
|
+
this.config.loaded?.(this);
|
|
5771
|
+
if (this.config.capture_pageview) {
|
|
5772
|
+
setTimeout(() => {
|
|
5773
|
+
if (this.config.cookieless_mode === 'always') {
|
|
5774
|
+
this.captureInitialPageview();
|
|
5775
|
+
}
|
|
5776
|
+
}, 1);
|
|
5777
|
+
}
|
|
5778
|
+
addEventListener(document, 'DOMContentLoaded', () => {
|
|
5779
|
+
this.loadRemoteConfig();
|
|
5780
|
+
});
|
|
5781
|
+
addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this.capturePageLeave.bind(this), {
|
|
5782
|
+
passive: false
|
|
5783
|
+
});
|
|
5784
|
+
}
|
|
5785
|
+
captureInitialPageview() {
|
|
5786
|
+
if (!document) {
|
|
5787
|
+
return;
|
|
5788
|
+
}
|
|
5789
|
+
if (document.visibilityState !== 'visible') {
|
|
5790
|
+
if (!this.visibilityStateListener) {
|
|
5791
|
+
this.visibilityStateListener = this.captureInitialPageview.bind(this);
|
|
5792
|
+
addEventListener(document, 'visibilitychange', this.visibilityStateListener);
|
|
5793
|
+
}
|
|
5794
|
+
return;
|
|
5795
|
+
}
|
|
5796
|
+
if (!this.initialPageviewCaptured) {
|
|
5797
|
+
this.initialPageviewCaptured = true;
|
|
5798
|
+
this.capture('$pageview', {
|
|
5799
|
+
title: document.title
|
|
5800
|
+
});
|
|
5801
|
+
if (this.visibilityStateListener) {
|
|
5802
|
+
document.removeEventListener('visibilitychange', this.visibilityStateListener);
|
|
5803
|
+
this.visibilityStateListener = null;
|
|
5804
|
+
}
|
|
5805
|
+
}
|
|
5806
|
+
}
|
|
5807
|
+
capturePageLeave() {
|
|
5808
|
+
const {
|
|
5809
|
+
capture_pageleave,
|
|
5810
|
+
capture_pageview
|
|
5811
|
+
} = this.config;
|
|
5812
|
+
if (capture_pageleave === true || capture_pageleave === 'if_capture_pageview' && (capture_pageview === true || capture_pageview === 'history_change')) {
|
|
5813
|
+
this.capture('$pageleave');
|
|
5814
|
+
}
|
|
5815
|
+
}
|
|
5816
|
+
async loadRemoteConfig() {
|
|
5817
|
+
if (!this.isRemoteConfigLoaded) {
|
|
5818
|
+
const remoteConfig = await this.reloadRemoteConfigAsync();
|
|
5819
|
+
if (remoteConfig) {
|
|
5820
|
+
this.onRemoteConfig(remoteConfig);
|
|
5821
|
+
}
|
|
5822
|
+
}
|
|
5823
|
+
}
|
|
5824
|
+
onRemoteConfig(config) {
|
|
5825
|
+
if (!(document && document.body)) {
|
|
5826
|
+
setTimeout(() => {
|
|
5827
|
+
this.onRemoteConfig(config);
|
|
5828
|
+
}, 500);
|
|
5829
|
+
return;
|
|
5830
|
+
}
|
|
5831
|
+
this.isRemoteConfigLoaded = true;
|
|
5832
|
+
this.replayAutocapture?.onRemoteConfig(config);
|
|
5833
|
+
this.sessionRecording?.onRemoteConfig(config);
|
|
5834
|
+
}
|
|
5835
|
+
fetch(url, options) {
|
|
5836
|
+
const fetchFn = core.getFetch();
|
|
5837
|
+
if (!fetchFn) {
|
|
5838
|
+
return Promise.reject(new Error('Fetch API is not available in this environment.'));
|
|
5839
|
+
}
|
|
5840
|
+
return fetchFn(url, options);
|
|
5841
|
+
}
|
|
5842
|
+
setConfig(config) {
|
|
5843
|
+
const oldConfig = {
|
|
5844
|
+
...this.config
|
|
5845
|
+
};
|
|
5846
|
+
if (core.isObject(config)) {
|
|
5847
|
+
extend(this.config, config);
|
|
5848
|
+
if (!this.config.api_host && this.config.host) {
|
|
5849
|
+
this.config.api_host = this.config.host;
|
|
5850
|
+
}
|
|
5851
|
+
this.persistence?.update_config(this.config, oldConfig);
|
|
5852
|
+
this.replayAutocapture?.startIfEnabled();
|
|
5853
|
+
this.sessionRecording?.startIfEnabledOrStop();
|
|
5854
|
+
}
|
|
5855
|
+
const isTempStorage = this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory';
|
|
5856
|
+
this.sessionPersistence = isTempStorage ? this.persistence : new LeanbasePersistence({
|
|
5857
|
+
...this.config,
|
|
5858
|
+
persistence: 'sessionStorage'
|
|
5859
|
+
});
|
|
5860
|
+
}
|
|
5861
|
+
getLibraryId() {
|
|
5862
|
+
return 'leanbase';
|
|
5863
|
+
}
|
|
5864
|
+
getLibraryVersion() {
|
|
5865
|
+
return Config.LIB_VERSION;
|
|
5866
|
+
}
|
|
5867
|
+
getCustomUserAgent() {
|
|
5868
|
+
return;
|
|
5869
|
+
}
|
|
5870
|
+
getPersistedProperty(key) {
|
|
5871
|
+
return this.persistence?.get_property(key);
|
|
5872
|
+
}
|
|
5873
|
+
get_property(key) {
|
|
5874
|
+
return this.persistence?.get_property(key);
|
|
5875
|
+
}
|
|
5876
|
+
setPersistedProperty(key, value) {
|
|
5877
|
+
this.persistence?.set_property(key, value);
|
|
5878
|
+
}
|
|
5879
|
+
calculateEventProperties(eventName, eventProperties, timestamp, uuid, readOnly) {
|
|
5880
|
+
if (!this.persistence || !this.sessionPersistence) {
|
|
5881
|
+
return eventProperties;
|
|
3363
5882
|
}
|
|
3364
5883
|
timestamp = timestamp || new Date();
|
|
3365
5884
|
const startTimestamp = readOnly ? undefined : this.persistence?.remove_event_timer(eventName);
|
|
@@ -3376,7 +5895,7 @@ class Leanbase extends core.PostHogCore {
|
|
|
3376
5895
|
};
|
|
3377
5896
|
properties['distinct_id'] = persistenceProps.distinct_id;
|
|
3378
5897
|
if (!(core.isString(properties['distinct_id']) || core.isNumber(properties['distinct_id'])) || core.isEmptyString(properties['distinct_id'])) {
|
|
3379
|
-
logger.error('Invalid distinct_id for replay event. This indicates a bug in your implementation');
|
|
5898
|
+
logger$3.error('Invalid distinct_id for replay event. This indicates a bug in your implementation');
|
|
3380
5899
|
}
|
|
3381
5900
|
return properties;
|
|
3382
5901
|
}
|
|
@@ -3392,6 +5911,13 @@ class Leanbase extends core.PostHogCore {
|
|
|
3392
5911
|
if (this.sessionPropsManager) {
|
|
3393
5912
|
extend(properties, this.sessionPropsManager.getSessionProps());
|
|
3394
5913
|
}
|
|
5914
|
+
try {
|
|
5915
|
+
if (this.sessionRecording) {
|
|
5916
|
+
extend(properties, this.sessionRecording.sdkDebugProperties);
|
|
5917
|
+
}
|
|
5918
|
+
} catch (e) {
|
|
5919
|
+
properties['$sdk_debug_error_capturing_properties'] = String(e);
|
|
5920
|
+
}
|
|
3395
5921
|
let pageviewProperties = this.pageViewManager.doEvent();
|
|
3396
5922
|
if (eventName === '$pageview' && !readOnly) {
|
|
3397
5923
|
pageviewProperties = this.pageViewManager.doPageView(timestamp, uuid);
|
|
@@ -3444,11 +5970,11 @@ class Leanbase extends core.PostHogCore {
|
|
|
3444
5970
|
return;
|
|
3445
5971
|
}
|
|
3446
5972
|
if (core.isUndefined(event) || !core.isString(event)) {
|
|
3447
|
-
logger.error('No event name provided to posthog.capture');
|
|
5973
|
+
logger$3.error('No event name provided to posthog.capture');
|
|
3448
5974
|
return;
|
|
3449
5975
|
}
|
|
3450
5976
|
if (properties?.$current_url && !core.isString(properties?.$current_url)) {
|
|
3451
|
-
logger.error('Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.');
|
|
5977
|
+
logger$3.error('Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.');
|
|
3452
5978
|
delete properties?.$current_url;
|
|
3453
5979
|
}
|
|
3454
5980
|
this.sessionPersistence.update_search_keyword();
|