-
Notifications
You must be signed in to change notification settings - Fork 131
/
posthog-core.ts
2310 lines (2062 loc) · 89.4 KB
/
posthog-core.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Config from './config'
import {
_copyAndTruncateStrings,
each,
eachArray,
extend,
includes,
registerEvent,
safewrapClass,
isCrossDomainCookie,
isDistinctIdStringLike,
} from './utils'
import { assignableWindow, document, location, navigator, userAgent, window } from './utils/globals'
import { PostHogFeatureFlags } from './posthog-featureflags'
import { PostHogPersistence } from './posthog-persistence'
import {
ALIAS_ID_KEY,
FLAG_CALL_REPORTED,
PEOPLE_DISTINCT_ID_KEY,
USER_STATE,
ENABLE_PERSON_PROCESSING,
} from './constants'
import { SessionRecording } from './extensions/replay/sessionrecording'
import { Decide } from './decide'
import { Toolbar } from './extensions/toolbar'
import { localStore } from './storage'
import { RequestQueue } from './request-queue'
import { RetryQueue } from './retry-queue'
import { SessionIdManager } from './sessionid'
import { RequestRouter, RequestRouterRegion } from './utils/request-router'
import {
CaptureOptions,
CaptureResult,
Compression,
DecideResponse,
EarlyAccessFeatureCallback,
EventName,
IsFeatureEnabledOptions,
JsonType,
PostHogConfig,
Properties,
Property,
QueuedRequestOptions,
RequestCallback,
SessionIdChangedCallback,
SnippetArrayItem,
ToolbarParams,
} from './types'
import { SentryIntegration, SentryIntegrationOptions, sentryIntegration } from './extensions/sentry-integration'
import { setupSegmentIntegration } from './extensions/segment-integration'
import { PageViewManager } from './page-view'
import { PostHogSurveys } from './posthog-surveys'
import { RateLimiter } from './rate-limiter'
import { uuidv7 } from './uuidv7'
import { Survey, SurveyCallback, SurveyQuestionBranchingType } from './posthog-surveys-types'
import {
isArray,
isEmptyObject,
isEmptyString,
isFunction,
isKnownUnsafeEditableEvent,
isNullish,
isNumber,
isObject,
isString,
isUndefined,
} from './utils/type-utils'
import { Info } from './utils/event-utils'
import { logger } from './utils/logger'
import { SessionPropsManager } from './session-props'
import { isLikelyBot } from './utils/blocked-uas'
import { extendURLParams, request, SUPPORTS_REQUEST } from './request'
import { Heatmaps } from './heatmaps'
import { ScrollManager } from './scroll-manager'
import { SimpleEventEmitter } from './utils/simple-event-emitter'
import { Autocapture } from './autocapture'
import { TracingHeaders } from './extensions/tracing-headers'
import { ConsentManager } from './consent'
import { ExceptionObserver } from './extensions/exception-autocapture'
import { WebVitalsAutocapture } from './extensions/web-vitals'
import { WebExperiments } from './web-experiments'
import { PostHogExceptions } from './posthog-exceptions'
import { DeadClicksAutocapture, isDeadClicksEnabledForAutocapture } from './extensions/dead-clicks-autocapture'
/*
SIMPLE STYLE GUIDE:
this.x === public function
this._x === internal - only use within this file
this.__x === private - only use within the class
Globals should be all caps
*/
/* posthog.init is called with `Partial<PostHogConfig>`
* and we want to ensure that only valid keys are passed to the config object.
* TypeScript does not enforce that the object passed does not have extra keys.
* So someone can call with { bootstrap: { distinctId: '123'} }
* which is not a valid key. They should have passed distinctID (upper case D).
* That's a really tricky mistake to spot.
* The OnlyValidKeys type ensures that only keys that are valid in the PostHogConfig type are allowed.
*/
type OnlyValidKeys<T, Shape> = T extends Shape ? (Exclude<keyof T, keyof Shape> extends never ? T : never) : never
const instances: Record<string, PostHog> = {}
// some globals for comparisons
const __NOOP = () => {}
const PRIMARY_INSTANCE_NAME = 'posthog'
/*
* Dynamic... constants? Is that an oxymoron?
*/
// http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
// https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
// IE<10 does not support cross-origin XHR's but script tags
// with defer won't block window.onload; ENQUEUE_REQUESTS
// should only be true for Opera<12
let ENQUEUE_REQUESTS = !SUPPORTS_REQUEST && userAgent?.indexOf('MSIE') === -1 && userAgent?.indexOf('Mozilla') === -1
export const defaultConfig = (): PostHogConfig => ({
api_host: 'https://us.i.posthog.com',
ui_host: null,
token: '',
autocapture: true,
rageclick: true,
cross_subdomain_cookie: isCrossDomainCookie(document?.location),
persistence: 'localStorage+cookie', // up to 1.92.0 this was 'cookie'. It's easy to migrate as 'localStorage+cookie' will migrate data from cookie storage
persistence_name: '',
loaded: __NOOP,
store_google: true,
custom_campaign_params: [],
custom_blocked_useragents: [],
save_referrer: true,
capture_pageview: true,
capture_pageleave: 'if_capture_pageview', // We'll only capture pageleave events if capture_pageview is also true
debug: (location && isString(location?.search) && location.search.indexOf('__posthog_debug=true') !== -1) || false,
verbose: false,
cookie_expiration: 365,
upgrade: false,
disable_session_recording: false,
disable_persistence: false,
disable_web_experiments: true, // disabled in beta.
disable_surveys: false,
enable_recording_console_log: undefined, // When undefined, it falls back to the server-side setting
secure_cookie: window?.location?.protocol === 'https:',
ip: true,
opt_out_capturing_by_default: false,
opt_out_persistence_by_default: false,
opt_out_useragent_filter: false,
opt_out_capturing_persistence_type: 'localStorage',
opt_out_capturing_cookie_prefix: null,
opt_in_site_apps: false,
property_denylist: [],
respect_dnt: false,
sanitize_properties: null,
request_headers: {}, // { header: value, header2: value }
inapp_protocol: '//',
inapp_link_new_window: false,
request_batching: true,
properties_string_max_length: 65535,
session_recording: {},
mask_all_element_attributes: false,
mask_all_text: false,
advanced_disable_decide: false,
advanced_disable_feature_flags: false,
advanced_disable_feature_flags_on_first_load: false,
advanced_disable_toolbar_metrics: false,
feature_flag_request_timeout_ms: 3000,
on_request_error: (res) => {
const error = 'Bad HTTP status: ' + res.statusCode + ' ' + res.text
logger.error(error)
},
get_device_id: (uuid) => uuid,
// Used for internal testing
_onCapture: __NOOP,
capture_performance: undefined,
name: 'posthog',
bootstrap: {},
disable_compression: false,
session_idle_timeout_seconds: 30 * 60, // 30 minutes
person_profiles: 'identified_only',
__add_tracing_headers: false,
before_send: undefined,
})
export const configRenames = (origConfig: Partial<PostHogConfig>): Partial<PostHogConfig> => {
const renames: Partial<PostHogConfig> = {}
if (!isUndefined(origConfig.process_person)) {
renames.person_profiles = origConfig.process_person
}
if (!isUndefined(origConfig.xhr_headers)) {
renames.request_headers = origConfig.xhr_headers
}
if (!isUndefined(origConfig.cookie_name)) {
renames.persistence_name = origConfig.cookie_name
}
if (!isUndefined(origConfig.disable_cookie)) {
renames.disable_persistence = origConfig.disable_cookie
}
// on_xhr_error is not present, as the type is different to on_request_error
// the original config takes priority over the renames
const newConfig = extend({}, renames, origConfig)
// merge property_blacklist into property_denylist
if (isArray(origConfig.property_blacklist)) {
if (isUndefined(origConfig.property_denylist)) {
newConfig.property_denylist = origConfig.property_blacklist
} else if (isArray(origConfig.property_denylist)) {
newConfig.property_denylist = [...origConfig.property_blacklist, ...origConfig.property_denylist]
} else {
logger.error('Invalid value for property_denylist config: ' + origConfig.property_denylist)
}
}
return newConfig
}
class DeprecatedWebPerformanceObserver {
get _forceAllowLocalhost(): boolean {
return this.__forceAllowLocalhost
}
set _forceAllowLocalhost(value: boolean) {
logger.error(
'WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`'
)
this.__forceAllowLocalhost = value
}
private __forceAllowLocalhost: boolean = false
}
/**
* PostHog Library Object
* @constructor
*/
export class PostHog {
__loaded: boolean
config: PostHogConfig
rateLimiter: RateLimiter
scrollManager: ScrollManager
pageViewManager: PageViewManager
featureFlags: PostHogFeatureFlags
surveys: PostHogSurveys
experiments: WebExperiments
toolbar: Toolbar
exceptions: PostHogExceptions
consent: ConsentManager
// These are instance-specific state created after initialisation
persistence?: PostHogPersistence
sessionPersistence?: PostHogPersistence
sessionManager?: SessionIdManager
sessionPropsManager?: SessionPropsManager
requestRouter: RequestRouter
autocapture?: Autocapture
heatmaps?: Heatmaps
webVitalsAutocapture?: WebVitalsAutocapture
exceptionObserver?: ExceptionObserver
deadClicksAutocapture?: DeadClicksAutocapture
_requestQueue?: RequestQueue
_retryQueue?: RetryQueue
sessionRecording?: SessionRecording
webPerformance = new DeprecatedWebPerformanceObserver()
_initialPageviewCaptured: boolean
_triggered_notifs: any
compression?: Compression
__request_queue: QueuedRequestOptions[]
decideEndpointWasHit: boolean
analyticsDefaultEndpoint: string
version = Config.LIB_VERSION
_initialPersonProfilesConfig: 'always' | 'never' | 'identified_only' | null
SentryIntegration: typeof SentryIntegration
sentryIntegration: (options?: SentryIntegrationOptions) => ReturnType<typeof sentryIntegration>
private _internalEventEmitter = new SimpleEventEmitter()
/** DEPRECATED: We keep this to support existing usage but now one should just call .setPersonProperties */
people: {
set: (prop: string | Properties, to?: string, callback?: RequestCallback) => void
set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => void
}
constructor() {
this.config = defaultConfig()
this.decideEndpointWasHit = false
this.SentryIntegration = SentryIntegration
this.sentryIntegration = (options?: SentryIntegrationOptions) => sentryIntegration(this, options)
this.__request_queue = []
this.__loaded = false
this.analyticsDefaultEndpoint = '/e/'
this._initialPageviewCaptured = false
this._initialPersonProfilesConfig = null
this.featureFlags = new PostHogFeatureFlags(this)
this.toolbar = new Toolbar(this)
this.scrollManager = new ScrollManager(this)
this.pageViewManager = new PageViewManager(this)
this.surveys = new PostHogSurveys(this)
this.experiments = new WebExperiments(this)
this.exceptions = new PostHogExceptions(this)
this.rateLimiter = new RateLimiter(this)
this.requestRouter = new RequestRouter(this)
this.consent = new ConsentManager(this)
// NOTE: See the property definition for deprecation notice
this.people = {
set: (prop: string | Properties, to?: string, callback?: RequestCallback) => {
const setProps = isString(prop) ? { [prop]: to } : prop
this.setPersonProperties(setProps)
callback?.({} as any)
},
set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => {
const setProps = isString(prop) ? { [prop]: to } : prop
this.setPersonProperties(undefined, setProps)
callback?.({} as any)
},
}
this.on('eventCaptured', (data) => logger.info(`send "${data?.event}"`, data))
}
// Initialization methods
/**
* This function initializes a new instance of the PostHog capturing object.
* All new instances are added to the main posthog object as sub properties (such as
* posthog.library_name) and also returned by this function. To define a
* second instance on the page, you would call:
*
* posthog.init('new token', { your: 'config' }, 'library_name');
*
* and use it like so:
*
* posthog.library_name.capture(...);
*
* @param {String} token Your PostHog API token
* @param {Object} [config] A dictionary of config options to override. <a href="https://github.com/posthog/posthog-js/blob/6e0e873/src/posthog-core.js#L57-L91">See a list of default config options</a>.
* @param {String} [name] The name for the new posthog instance that you want created
*/
init(
token: string,
config?: OnlyValidKeys<Partial<PostHogConfig>, Partial<PostHogConfig>>,
name?: string
): PostHog | undefined {
if (!name || name === PRIMARY_INSTANCE_NAME) {
// This means we are initializing the primary instance (i.e. this)
return this._init(token, config, name)
} else {
const namedPosthog = instances[name] ?? new PostHog()
namedPosthog._init(token, config, name)
instances[name] = namedPosthog
// Add as a property to the primary instance (this isn't type-safe but its how it was always done)
;(instances[PRIMARY_INSTANCE_NAME] as any)[name] = namedPosthog
return namedPosthog
}
}
// posthog._init(token:string, config:object, name:string)
//
// This function sets up the current instance of the posthog
// library. The difference between this method and the init(...)
// method is this one initializes the actual instance, whereas the
// init(...) method sets up a new library and calls _init on it.
//
// Note that there are operations that can be asynchronous, so we
// accept a callback that is called when all the asynchronous work
// is done. Note that we do not use promises because we want to be
// IE11 compatible. We could use polyfills, which would make the
// code a bit cleaner, but will add some overhead.
//
_init(token: string, config: Partial<PostHogConfig> = {}, name?: string): PostHog {
if (isUndefined(token) || isEmptyString(token)) {
logger.critical(
'PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()'
)
return this
}
if (this.__loaded) {
logger.warn('You have already initialized PostHog! Re-initializing is a no-op')
return this
}
this.__loaded = true
this.config = {} as PostHogConfig // will be set right below
this._triggered_notifs = []
if (config.person_profiles) {
this._initialPersonProfilesConfig = config.person_profiles
}
this.set_config(
extend({}, defaultConfig(), configRenames(config), {
name: name,
token: token,
})
)
if (this.config.on_xhr_error) {
logger.error('[posthog] on_xhr_error is deprecated. Use on_request_error instead')
}
this.compression = config.disable_compression ? undefined : Compression.GZipJS
this.persistence = new PostHogPersistence(this.config)
this.sessionPersistence =
this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory'
? this.persistence
: new PostHogPersistence({ ...this.config, persistence: 'sessionStorage' })
// should I store the initial person profiles config in persistence?
const initialPersistenceProps = { ...this.persistence.props }
const initialSessionProps = { ...this.sessionPersistence.props }
this._requestQueue = new RequestQueue((req) => this._send_retriable_request(req))
this._retryQueue = new RetryQueue(this)
this.__request_queue = []
this.sessionManager = new SessionIdManager(this.config, this.persistence)
this.sessionPropsManager = new SessionPropsManager(this.sessionManager, this.persistence)
new TracingHeaders(this).startIfEnabledOrStop()
this.sessionRecording = new SessionRecording(this)
this.sessionRecording.startIfEnabledOrStop()
if (!this.config.disable_scroll_properties) {
this.scrollManager.startMeasuringScrollPosition()
}
this.autocapture = new Autocapture(this)
this.autocapture.startIfEnabled()
this.surveys.loadIfEnabled()
this.heatmaps = new Heatmaps(this)
this.heatmaps.startIfEnabled()
this.webVitalsAutocapture = new WebVitalsAutocapture(this)
this.exceptionObserver = new ExceptionObserver(this)
this.exceptionObserver.startIfEnabled()
this.deadClicksAutocapture = new DeadClicksAutocapture(this, isDeadClicksEnabledForAutocapture)
this.deadClicksAutocapture.startIfEnabled()
// if any instance on the page has debug = true, we set the
// global debug to be true
Config.DEBUG = Config.DEBUG || this.config.debug
if (Config.DEBUG) {
logger.info('Starting in debug mode', {
this: this,
config,
thisC: { ...this.config },
p: initialPersistenceProps,
s: initialSessionProps,
})
}
this._sync_opt_out_with_persistence()
// isUndefined doesn't provide typehint here so wouldn't reduce bundle as we'd need to assign
// eslint-disable-next-line posthog-js/no-direct-undefined-check
if (config.bootstrap?.distinctID !== undefined) {
const uuid = this.config.get_device_id(uuidv7())
const deviceID = config.bootstrap?.isIdentifiedID ? uuid : config.bootstrap.distinctID
this.persistence.set_property(USER_STATE, config.bootstrap?.isIdentifiedID ? 'identified' : 'anonymous')
this.register({
distinct_id: config.bootstrap.distinctID,
$device_id: deviceID,
})
}
if (this._hasBootstrappedFeatureFlags()) {
const activeFlags = Object.keys(config.bootstrap?.featureFlags || {})
.filter((flag) => !!config.bootstrap?.featureFlags?.[flag])
.reduce(
(res: Record<string, string | boolean>, key) => (
(res[key] = config.bootstrap?.featureFlags?.[key] || false), res
),
{}
)
const featureFlagPayloads = Object.keys(config.bootstrap?.featureFlagPayloads || {})
.filter((key) => activeFlags[key])
.reduce((res: Record<string, JsonType>, key) => {
if (config.bootstrap?.featureFlagPayloads?.[key]) {
res[key] = config.bootstrap?.featureFlagPayloads?.[key]
}
return res
}, {})
this.featureFlags.receivedFeatureFlags({ featureFlags: activeFlags, featureFlagPayloads })
}
if (!this.get_distinct_id()) {
// There is no need to set the distinct id
// or the device id if something was already stored
// in the persitence
const uuid = this.config.get_device_id(uuidv7())
this.register_once(
{
distinct_id: uuid,
$device_id: uuid,
},
''
)
// distinct id == $device_id is a proxy for anonymous user
this.persistence.set_property(USER_STATE, 'anonymous')
}
// Set up event handler for pageleave
// Use `onpagehide` if available, see https://calendar.perfplanet.com/2020/beaconing-in-practice/#beaconing-reliability-avoiding-abandons
window?.addEventListener?.('onpagehide' in self ? 'pagehide' : 'unload', this._handle_unload.bind(this))
this.toolbar.maybeLoadToolbar()
// We want to avoid promises for IE11 compatibility, so we use callbacks here
if (config.segment) {
setupSegmentIntegration(this, () => this._loaded())
} else {
this._loaded()
}
if (isFunction(this.config._onCapture) && this.config._onCapture !== __NOOP) {
logger.warn('onCapture is deprecated. Please use `before_send` instead')
this.on('eventCaptured', (data) => this.config._onCapture(data.event, data))
}
return this
}
// Private methods
_afterDecideResponse(response: DecideResponse) {
this.compression = undefined
if (response.supportedCompression && !this.config.disable_compression) {
this.compression = includes(response['supportedCompression'], Compression.GZipJS)
? Compression.GZipJS
: includes(response['supportedCompression'], Compression.Base64)
? Compression.Base64
: undefined
}
if (response.analytics?.endpoint) {
this.analyticsDefaultEndpoint = response.analytics.endpoint
}
this.set_config({
person_profiles: this._initialPersonProfilesConfig
? this._initialPersonProfilesConfig
: response['defaultIdentifiedOnly']
? 'identified_only'
: 'always',
})
this.sessionRecording?.afterDecideResponse(response)
this.autocapture?.afterDecideResponse(response)
this.heatmaps?.afterDecideResponse(response)
this.experiments?.afterDecideResponse(response)
this.surveys?.afterDecideResponse(response)
this.webVitalsAutocapture?.afterDecideResponse(response)
this.exceptionObserver?.afterDecideResponse(response)
this.deadClicksAutocapture?.afterDecideResponse(response)
}
_loaded(): void {
// Pause `reloadFeatureFlags` calls in config.loaded callback.
// These feature flags are loaded in the decide call made right after
const disableDecide = this.config.advanced_disable_decide
if (!disableDecide) {
this.featureFlags.setReloadingPaused(true)
}
try {
this.config.loaded(this)
} catch (err) {
logger.critical('`loaded` function failed', err)
}
this._start_queue_if_opted_in()
// this happens after "loaded" so a user can call identify or any other things before the pageview fires
if (this.config.capture_pageview) {
// NOTE: We want to fire this on the next tick as the previous implementation had this side effect
// and some clients may rely on it
setTimeout(() => {
if (this.consent.isOptedIn()) {
this._captureInitialPageview()
}
}, 1)
}
// Call decide to get what features are enabled and other settings.
// As a reminder, if the /decide endpoint is disabled, feature flags, toolbar, session recording, autocapture,
// and compression will not be available.
if (!disableDecide) {
new Decide(this).call()
// TRICKY: Reset any decide reloads queued during config.loaded because they'll be
// covered by the decide call right above.
this.featureFlags.resetRequestQueue()
}
}
_start_queue_if_opted_in(): void {
if (!this.has_opted_out_capturing()) {
if (this.config.request_batching) {
this._requestQueue?.enable()
}
}
}
_dom_loaded(): void {
if (!this.has_opted_out_capturing()) {
eachArray(this.__request_queue, (item) => this._send_retriable_request(item))
}
this.__request_queue = []
this._start_queue_if_opted_in()
}
_handle_unload(): void {
if (!this.config.request_batching) {
if (this._shouldCapturePageleave()) {
this.capture('$pageleave', null, { transport: 'sendBeacon' })
}
return
}
if (this._shouldCapturePageleave()) {
this.capture('$pageleave')
}
this._requestQueue?.unload()
this._retryQueue?.unload()
}
_send_request(options: QueuedRequestOptions): void {
if (!this.__loaded) {
return
}
if (ENQUEUE_REQUESTS) {
this.__request_queue.push(options)
return
}
if (this.rateLimiter.isServerRateLimited(options.batchKey)) {
return
}
options.transport = options.transport || this.config.api_transport
options.url = extendURLParams(options.url, {
// Whether to detect ip info or not
ip: this.config.ip ? 1 : 0,
})
options.headers = {
...this.config.request_headers,
}
options.compression = options.compression === 'best-available' ? this.compression : options.compression
request({
...options,
callback: (response) => {
this.rateLimiter.checkForLimiting(response)
if (response.statusCode >= 400) {
this.config.on_request_error?.(response)
}
options.callback?.(response)
},
})
}
_send_retriable_request(options: QueuedRequestOptions): void {
if (this._retryQueue) {
this._retryQueue.retriableRequest(options)
} else {
this._send_request(options)
}
}
/**
* _execute_array() deals with processing any posthog function
* calls that were called before the PostHog library were loaded
* (and are thus stored in an array so they can be called later)
*
* Note: we fire off all the posthog function calls && user defined
* functions BEFORE we fire off posthog capturing calls. This is so
* identify/register/set_config calls can properly modify early
* capturing calls.
*
* @param {Array} array
*/
_execute_array(array: SnippetArrayItem[]): void {
let fn_name
const alias_calls: SnippetArrayItem[] = []
const other_calls: SnippetArrayItem[] = []
const capturing_calls: SnippetArrayItem[] = []
eachArray(array, (item) => {
if (item) {
fn_name = item[0]
if (isArray(fn_name)) {
capturing_calls.push(item) // chained call e.g. posthog.get_group().set()
} else if (isFunction(item)) {
;(item as any).call(this)
} else if (isArray(item) && fn_name === 'alias') {
alias_calls.push(item)
} else if (isArray(item) && fn_name.indexOf('capture') !== -1 && isFunction((this as any)[fn_name])) {
capturing_calls.push(item)
} else {
other_calls.push(item)
}
}
})
const execute = function (calls: SnippetArrayItem[], thisArg: any) {
eachArray(
calls,
function (item) {
if (isArray(item[0])) {
// chained call
let caller = thisArg
each(item, function (call) {
caller = caller[call[0]].apply(caller, call.slice(1))
})
} else {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this[item[0]].apply(this, item.slice(1))
}
},
thisArg
)
}
execute(alias_calls, this)
execute(other_calls, this)
execute(capturing_calls, this)
}
_hasBootstrappedFeatureFlags(): boolean {
return (
(this.config.bootstrap?.featureFlags && Object.keys(this.config.bootstrap?.featureFlags).length > 0) ||
false
)
}
/**
* push() keeps the standard async-array-push
* behavior around after the lib is loaded.
* This is only useful for external integrations that
* do not wish to rely on our convenience methods
* (created in the snippet).
*
* ### Usage:
* posthog.push(['register', { a: 'b' }]);
*
* @param {Array} item A [function_name, args...] array to be executed
*/
push(item: SnippetArrayItem): void {
this._execute_array([item])
}
/**
* Capture an event. This is the most important and
* frequently used PostHog function.
*
* ### Usage:
*
* // capture an event named 'Registered'
* posthog.capture('Registered', {'Gender': 'Male', 'Age': 21});
*
* // capture an event using navigator.sendBeacon
* posthog.capture('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
*
* @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
* @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
* @param {Object} [config] Optional configuration for this capture request.
* @param {String} [config.transport] Transport method for network request ('XHR' or 'sendBeacon').
* @param {Date} [config.timestamp] Timestamp is a Date object. If not set, it'll automatically be set to the current time.
*/
capture(
event_name: EventName,
properties?: Properties | null,
options?: CaptureOptions
): CaptureResult | undefined {
// While developing, a developer might purposefully _not_ call init(),
// in this case, we would like capture to be a noop.
if (!this.__loaded || !this.persistence || !this.sessionPersistence || !this._requestQueue) {
logger.uninitializedWarning('posthog.capture')
return
}
if (this.consent.isOptedOut()) {
return
}
// typing doesn't prevent interesting data
if (isUndefined(event_name) || !isString(event_name)) {
logger.error('No event name provided to posthog.capture')
return
}
if (!this.config.opt_out_useragent_filter && this._is_bot()) {
return
}
const clientRateLimitContext = !options?.skip_client_rate_limiting
? this.rateLimiter.clientRateLimitContext()
: undefined
if (clientRateLimitContext?.isRateLimited) {
logger.critical('This capture call is ignored due to client rate limiting.')
return
}
// update persistence
this.sessionPersistence.update_search_keyword()
// The initial campaign/referrer props need to be stored in the regular persistence, as they are there to mimic
// the person-initial props. The non-initial versions are stored in the sessionPersistence, as they are sent
// with every event and used by the session table to create session-initial props.
if (this.config.store_google) {
this.sessionPersistence.update_campaign_params()
}
if (this.config.save_referrer) {
this.sessionPersistence.update_referrer_info()
}
if (this.config.store_google || this.config.save_referrer) {
this.persistence.set_initial_person_info()
}
const systemTime = new Date()
const timestamp = options?.timestamp || systemTime
let data: CaptureResult = {
uuid: uuidv7(),
event: event_name,
properties: this._calculate_event_properties(event_name, properties || {}, timestamp),
}
if (clientRateLimitContext) {
data.properties['$lib_rate_limit_remaining_tokens'] = clientRateLimitContext.remainingTokens
}
const setProperties = options?.$set
if (setProperties) {
data.$set = options?.$set
}
const setOnceProperties = this._calculate_set_once_properties(options?.$set_once)
if (setOnceProperties) {
data.$set_once = setOnceProperties
}
data = _copyAndTruncateStrings(data, options?._noTruncate ? null : this.config.properties_string_max_length)
data.timestamp = timestamp
if (!isUndefined(options?.timestamp)) {
data.properties['$event_time_override_provided'] = true
data.properties['$event_time_override_system_time'] = systemTime
}
// Top-level $set overriding values from the one from properties is taken from the plugin-server normalizeEvent
// This doesn't handle $set_once, because posthog-people doesn't either
const finalSet = { ...data.properties['$set'], ...data['$set'] }
if (!isEmptyObject(finalSet)) {
this.setPersonPropertiesForFlags(finalSet)
}
if (!isNullish(this.config.before_send)) {
const beforeSendResult = this._runBeforeSend(data)
if (!beforeSendResult) {
return
} else {
data = beforeSendResult
}
}
this._internalEventEmitter.emit('eventCaptured', data)
const requestOptions: QueuedRequestOptions = {
method: 'POST',
url: options?._url ?? this.requestRouter.endpointFor('api', this.analyticsDefaultEndpoint),
data,
compression: 'best-available',
batchKey: options?._batchKey,
}
if (this.config.request_batching && (!options || options?._batchKey) && !options?.send_instantly) {
this._requestQueue.enqueue(requestOptions)
} else {
this._send_retriable_request(requestOptions)
}
return data
}
_addCaptureHook(callback: (eventName: string, eventPayload?: CaptureResult) => void): () => void {
return this.on('eventCaptured', (data) => callback(data.event, data))
}
_calculate_event_properties(event_name: string, event_properties: Properties, timestamp?: Date): Properties {
timestamp = timestamp || new Date()
if (!this.persistence || !this.sessionPersistence) {
return event_properties
}
// set defaults
const startTimestamp = this.persistence.remove_event_timer(event_name)
let properties = { ...event_properties }
properties['token'] = this.config.token
if (event_name === '$snapshot') {
const persistenceProps = { ...this.persistence.properties(), ...this.sessionPersistence.properties() }
properties['distinct_id'] = persistenceProps.distinct_id
if (
// we spotted one customer that was managing to send `false` for ~9k events a day
!(isString(properties['distinct_id']) || isNumber(properties['distinct_id'])) ||
isEmptyString(properties['distinct_id'])
) {
logger.error('Invalid distinct_id for replay event. This indicates a bug in your implementation')
}
return properties
}
const infoProperties = Info.properties()
if (this.sessionManager) {
const { sessionId, windowId } = this.sessionManager.checkAndGetSessionAndWindowId()
properties['$session_id'] = sessionId
properties['$window_id'] = windowId
}
if (this.requestRouter.region === RequestRouterRegion.CUSTOM) {
properties['$lib_custom_api_host'] = this.config.api_host
}
if (
this.sessionPropsManager &&
this.config.__preview_send_client_session_params &&
(event_name === '$pageview' || event_name === '$pageleave' || event_name === '$autocapture')
) {
const sessionProps = this.sessionPropsManager.getSessionProps()
properties = extend(properties, sessionProps)
}
if (!this.config.disable_scroll_properties) {
let performanceProperties: Record<string, any> = {}
if (event_name === '$pageview') {
performanceProperties = this.pageViewManager.doPageView(timestamp)
} else if (event_name === '$pageleave') {
performanceProperties = this.pageViewManager.doPageLeave(timestamp)
}
properties = extend(properties, performanceProperties)
}
if (event_name === '$pageview' && document) {
properties['title'] = document.title
}
// set $duration if time_event was previously called for this event
if (!isUndefined(startTimestamp)) {
const duration_in_ms = timestamp.getTime() - startTimestamp
properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3))
}
// this is only added when this.config.opt_out_useragent_filter is true,
// or it would always add "browser"
if (userAgent && this.config.opt_out_useragent_filter) {
properties['$browser_type'] = this._is_bot() ? 'bot' : 'browser'
}
// note: extend writes to the first object, so lets make sure we
// don't write to the persistence properties object and info
// properties object by passing in a new object
// update properties with pageview info and super-properties
properties = extend(
{},
infoProperties,
this.persistence.properties(),
this.sessionPersistence.properties(),
properties
)
properties['$is_identified'] = this._isIdentified()
if (isArray(this.config.property_denylist)) {
each(this.config.property_denylist, function (denylisted_prop) {
delete properties[denylisted_prop]