@leanbase-giangnd/js 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +143 -0
  2. package/dist/index.cjs +6012 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.ts +1484 -0
  5. package/dist/index.mjs +6010 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/leanbase.iife.js +13431 -0
  8. package/dist/leanbase.iife.js.map +1 -0
  9. package/package.json +48 -0
  10. package/src/autocapture-utils.ts +550 -0
  11. package/src/autocapture.ts +415 -0
  12. package/src/config.ts +8 -0
  13. package/src/constants.ts +108 -0
  14. package/src/extensions/rageclick.ts +34 -0
  15. package/src/extensions/replay/external/config.ts +278 -0
  16. package/src/extensions/replay/external/denylist.ts +32 -0
  17. package/src/extensions/replay/external/lazy-loaded-session-recorder.ts +1376 -0
  18. package/src/extensions/replay/external/mutation-throttler.ts +109 -0
  19. package/src/extensions/replay/external/network-plugin.ts +701 -0
  20. package/src/extensions/replay/external/sessionrecording-utils.ts +141 -0
  21. package/src/extensions/replay/external/triggerMatching.ts +422 -0
  22. package/src/extensions/replay/rrweb-plugins/patch.ts +39 -0
  23. package/src/extensions/replay/session-recording.ts +285 -0
  24. package/src/extensions/replay/types/rrweb-types.ts +575 -0
  25. package/src/extensions/replay/types/rrweb.ts +114 -0
  26. package/src/extensions/sampling.ts +26 -0
  27. package/src/iife.ts +87 -0
  28. package/src/index.ts +2 -0
  29. package/src/leanbase-logger.ts +26 -0
  30. package/src/leanbase-persistence.ts +374 -0
  31. package/src/leanbase.ts +457 -0
  32. package/src/page-view.ts +124 -0
  33. package/src/scroll-manager.ts +103 -0
  34. package/src/session-props.ts +114 -0
  35. package/src/sessionid.ts +330 -0
  36. package/src/storage.ts +410 -0
  37. package/src/types/fflate.d.ts +5 -0
  38. package/src/types/rrweb-record.d.ts +8 -0
  39. package/src/types.ts +807 -0
  40. package/src/utils/blocked-uas.ts +162 -0
  41. package/src/utils/element-utils.ts +50 -0
  42. package/src/utils/event-utils.ts +304 -0
  43. package/src/utils/index.ts +222 -0
  44. package/src/utils/logger.ts +26 -0
  45. package/src/utils/request-utils.ts +128 -0
  46. package/src/utils/simple-event-emitter.ts +27 -0
  47. package/src/utils/user-agent-utils.ts +357 -0
  48. package/src/uuidv7.ts +268 -0
  49. package/src/version.ts +1 -0
@@ -0,0 +1,1484 @@
1
+ import { PostHogCoreOptions, FeatureFlagValue, JsonType, PostHogCore, PostHogFetchOptions, PostHogFetchResponse, PostHogPersistedProperty, PostHogEventProperties } from '@posthog/core';
2
+
3
+ interface IMirror<TNode> {
4
+ getId(n: TNode | undefined | null): number;
5
+ getNode(id: number): TNode | null;
6
+ getIds(): number[];
7
+ getMeta(n: TNode): serializedNodeWithId | null;
8
+ removeNodeFromMap(n: TNode): void;
9
+ has(id: number): boolean;
10
+ hasNode(node: TNode): boolean;
11
+ add(n: TNode, meta: serializedNodeWithId): void;
12
+ replace(id: number, n: TNode): void;
13
+ reset(): void;
14
+ }
15
+ declare class Mirror implements IMirror<Node> {
16
+ private idNodeMap;
17
+ private nodeMetaMap;
18
+ getId(n: Node | undefined | null): number;
19
+ getNode(id: number): Node | null;
20
+ getIds(): number[];
21
+ getMeta(n: Node): serializedNodeWithId | null;
22
+ removeNodeFromMap(n: Node): void;
23
+ has(id: number): boolean;
24
+ hasNode(node: Node): boolean;
25
+ add(n: Node, meta: serializedNodeWithId): void;
26
+ replace(id: number, n: Node): void;
27
+ reset(): void;
28
+ }
29
+ type attributes = {
30
+ [key: string]: string | number | true | null;
31
+ };
32
+ declare enum NodeType {
33
+ Document = 0,
34
+ DocumentType = 1,
35
+ Element = 2,
36
+ Text = 3,
37
+ CDATA = 4,
38
+ Comment = 5
39
+ }
40
+ type documentNode = {
41
+ type: NodeType.Document;
42
+ childNodes: serializedNodeWithId[];
43
+ compatMode?: string;
44
+ };
45
+ type documentTypeNode = {
46
+ type: NodeType.DocumentType;
47
+ name: string;
48
+ publicId: string;
49
+ systemId: string;
50
+ };
51
+ type elementNode = {
52
+ type: NodeType.Element;
53
+ tagName: string;
54
+ attributes: attributes;
55
+ childNodes: serializedNodeWithId[];
56
+ isSVG?: true;
57
+ needBlock?: boolean;
58
+ isCustom?: true;
59
+ };
60
+ type textNode = {
61
+ type: NodeType.Text;
62
+ textContent: string;
63
+ isStyle?: true;
64
+ };
65
+ type cdataNode = {
66
+ type: NodeType.CDATA;
67
+ textContent: '';
68
+ };
69
+ type commentNode = {
70
+ type: NodeType.Comment;
71
+ textContent: string;
72
+ };
73
+ type serializedNode = (documentNode | documentTypeNode | elementNode | textNode | cdataNode | commentNode) & {
74
+ rootId?: number;
75
+ isShadowHost?: boolean;
76
+ isShadow?: boolean;
77
+ };
78
+ type serializedNodeWithId = serializedNode & {
79
+ id: number;
80
+ };
81
+ type blockClass = string | RegExp;
82
+ type maskTextClass = string | RegExp;
83
+ type IWindow = Window & typeof globalThis;
84
+ type listenerHandler = () => void;
85
+ type KeepIframeSrcFn = (src: string) => boolean;
86
+ type PackFn = (event: eventWithTime) => string;
87
+ declare enum EventType {
88
+ DomContentLoaded = 0,
89
+ Load = 1,
90
+ FullSnapshot = 2,
91
+ IncrementalSnapshot = 3,
92
+ Meta = 4,
93
+ Custom = 5,
94
+ Plugin = 6
95
+ }
96
+ declare enum IncrementalSource {
97
+ Mutation = 0,
98
+ MouseMove = 1,
99
+ MouseInteraction = 2,
100
+ Scroll = 3,
101
+ ViewportResize = 4,
102
+ Input = 5,
103
+ TouchMove = 6,
104
+ MediaInteraction = 7,
105
+ StyleSheetRule = 8,
106
+ CanvasMutation = 9,
107
+ Font = 10,
108
+ Log = 11,
109
+ Drag = 12,
110
+ StyleDeclaration = 13,
111
+ Selection = 14,
112
+ AdoptedStyleSheet = 15,
113
+ CustomElement = 16
114
+ }
115
+ type domContentLoadedEvent = {
116
+ type: EventType.DomContentLoaded;
117
+ data: unknown;
118
+ };
119
+ type loadedEvent = {
120
+ type: EventType.Load;
121
+ data: unknown;
122
+ };
123
+ type fullSnapshotEvent = {
124
+ type: EventType.FullSnapshot;
125
+ data: {
126
+ node: serializedNodeWithId;
127
+ initialOffset: {
128
+ top: number;
129
+ left: number;
130
+ };
131
+ };
132
+ };
133
+ type metaEvent = {
134
+ type: EventType.Meta;
135
+ data: {
136
+ href: string;
137
+ width: number;
138
+ height: number;
139
+ };
140
+ };
141
+ type customEvent<T = unknown> = {
142
+ type: EventType.Custom;
143
+ data: {
144
+ tag: string;
145
+ payload: T;
146
+ };
147
+ };
148
+ type pluginEvent<T = unknown> = {
149
+ type: EventType.Plugin;
150
+ data: {
151
+ plugin: string;
152
+ payload: T;
153
+ };
154
+ };
155
+ type styleOMValue = {
156
+ [key: string]: styleValueWithPriority | string | false;
157
+ };
158
+ type styleValueWithPriority = [string, string];
159
+ type textMutation = {
160
+ id: number;
161
+ value: string | null;
162
+ };
163
+ type attributeMutation = {
164
+ id: number;
165
+ attributes: {
166
+ [key: string]: string | styleOMValue | null;
167
+ };
168
+ };
169
+ type removedNodeMutation = {
170
+ parentId: number;
171
+ id: number;
172
+ isShadow?: boolean;
173
+ };
174
+ type addedNodeMutation = {
175
+ parentId: number;
176
+ previousId?: number | null;
177
+ nextId: number | null;
178
+ node: serializedNodeWithId;
179
+ };
180
+ type mutationCallbackParam = {
181
+ texts: textMutation[];
182
+ attributes: attributeMutation[];
183
+ removes: removedNodeMutation[];
184
+ adds: addedNodeMutation[];
185
+ isAttachIframe?: true;
186
+ };
187
+ type mutationData = {
188
+ source: IncrementalSource.Mutation;
189
+ } & mutationCallbackParam;
190
+ type mousePosition = {
191
+ x: number;
192
+ y: number;
193
+ id: number;
194
+ timeOffset: number;
195
+ };
196
+ declare enum MouseInteractions {
197
+ MouseUp = 0,
198
+ MouseDown = 1,
199
+ Click = 2,
200
+ ContextMenu = 3,
201
+ DblClick = 4,
202
+ Focus = 5,
203
+ Blur = 6,
204
+ TouchStart = 7,
205
+ TouchMove_Departed = 8,
206
+ TouchEnd = 9,
207
+ TouchCancel = 10
208
+ }
209
+ declare enum PointerTypes {
210
+ Mouse = 0,
211
+ Pen = 1,
212
+ Touch = 2
213
+ }
214
+ type mouseInteractionParam = {
215
+ type: MouseInteractions;
216
+ id: number;
217
+ x?: number;
218
+ y?: number;
219
+ pointerType?: PointerTypes;
220
+ };
221
+ type mouseInteractionData = {
222
+ source: IncrementalSource.MouseInteraction;
223
+ } & mouseInteractionParam;
224
+ type mousemoveData = {
225
+ source: IncrementalSource.MouseMove | IncrementalSource.TouchMove | IncrementalSource.Drag;
226
+ positions: mousePosition[];
227
+ };
228
+ type scrollPosition = {
229
+ id: number;
230
+ x: number;
231
+ y: number;
232
+ };
233
+ type scrollData = {
234
+ source: IncrementalSource.Scroll;
235
+ } & scrollPosition;
236
+ type viewportResizeDimension = {
237
+ width: number;
238
+ height: number;
239
+ };
240
+ type viewportResizeData = {
241
+ source: IncrementalSource.ViewportResize;
242
+ } & viewportResizeDimension;
243
+ type inputValue = {
244
+ text: string;
245
+ isChecked: boolean;
246
+ userTriggered?: boolean;
247
+ };
248
+ type inputData = {
249
+ source: IncrementalSource.Input;
250
+ id: number;
251
+ } & inputValue;
252
+ declare enum MediaInteractions {
253
+ Play = 0,
254
+ Pause = 1,
255
+ Seeked = 2,
256
+ VolumeChange = 3,
257
+ RateChange = 4
258
+ }
259
+ type mediaInteractionParam = {
260
+ type: MediaInteractions;
261
+ id: number;
262
+ currentTime?: number;
263
+ volume?: number;
264
+ muted?: boolean;
265
+ loop?: boolean;
266
+ playbackRate?: number;
267
+ };
268
+ type mediaInteractionData = {
269
+ source: IncrementalSource.MediaInteraction;
270
+ } & mediaInteractionParam;
271
+ type styleSheetAddRule = {
272
+ rule: string;
273
+ index?: number | number[];
274
+ };
275
+ type styleSheetDeleteRule = {
276
+ index: number | number[];
277
+ };
278
+ type styleSheetRuleParam = {
279
+ id?: number;
280
+ styleId?: number;
281
+ removes?: styleSheetDeleteRule[];
282
+ adds?: styleSheetAddRule[];
283
+ replace?: string;
284
+ replaceSync?: string;
285
+ };
286
+ type styleSheetRuleData = {
287
+ source: IncrementalSource.StyleSheetRule;
288
+ } & styleSheetRuleParam;
289
+ declare enum CanvasContext {
290
+ '2D' = 0,
291
+ WebGL = 1,
292
+ WebGL2 = 2
293
+ }
294
+ type canvasMutationCommand = {
295
+ property: string;
296
+ args: Array<unknown>;
297
+ setter?: true;
298
+ };
299
+ type canvasMutationParam = {
300
+ id: number;
301
+ type: CanvasContext;
302
+ commands: canvasMutationCommand[];
303
+ } | ({
304
+ id: number;
305
+ type: CanvasContext;
306
+ } & canvasMutationCommand);
307
+ type canvasMutationData = {
308
+ source: IncrementalSource.CanvasMutation;
309
+ } & canvasMutationParam;
310
+ type fontParam = {
311
+ family: string;
312
+ fontSource: string;
313
+ buffer: boolean;
314
+ descriptors?: FontFaceDescriptors;
315
+ };
316
+ type fontData = {
317
+ source: IncrementalSource.Font;
318
+ } & fontParam;
319
+ type SelectionRange = {
320
+ start: number;
321
+ startOffset: number;
322
+ end: number;
323
+ endOffset: number;
324
+ };
325
+ type selectionParam = {
326
+ ranges: Array<SelectionRange>;
327
+ };
328
+ type selectionData = {
329
+ source: IncrementalSource.Selection;
330
+ } & selectionParam;
331
+ type styleDeclarationParam = {
332
+ id?: number;
333
+ styleId?: number;
334
+ index: number[];
335
+ set?: {
336
+ property: string;
337
+ value: string | null;
338
+ priority: string | undefined;
339
+ };
340
+ remove?: {
341
+ property: string;
342
+ };
343
+ };
344
+ type styleDeclarationData = {
345
+ source: IncrementalSource.StyleDeclaration;
346
+ } & styleDeclarationParam;
347
+ type adoptedStyleSheetParam = {
348
+ id: number;
349
+ styles?: {
350
+ styleId: number;
351
+ rules: styleSheetAddRule[];
352
+ }[];
353
+ styleIds: number[];
354
+ };
355
+ type adoptedStyleSheetData = {
356
+ source: IncrementalSource.AdoptedStyleSheet;
357
+ } & adoptedStyleSheetParam;
358
+ type customElementParam = {
359
+ define?: {
360
+ name: string;
361
+ };
362
+ };
363
+ type customElementData = {
364
+ source: IncrementalSource.CustomElement;
365
+ } & customElementParam;
366
+ type incrementalData = mutationData | mousemoveData | mouseInteractionData | scrollData | viewportResizeData | inputData | mediaInteractionData | styleSheetRuleData | canvasMutationData | fontData | selectionData | styleDeclarationData | adoptedStyleSheetData | customElementData;
367
+ type incrementalSnapshotEvent = {
368
+ type: EventType.IncrementalSnapshot;
369
+ data: incrementalData;
370
+ };
371
+ type eventWithoutTime = domContentLoadedEvent | loadedEvent | fullSnapshotEvent | incrementalSnapshotEvent | metaEvent | customEvent | pluginEvent;
372
+ type eventWithTime = eventWithoutTime & {
373
+ timestamp: number;
374
+ delay?: number;
375
+ };
376
+ type mutationCallBack = (m: mutationCallbackParam) => void;
377
+ type mousemoveCallBack = (p: mousePosition[], source: IncrementalSource.MouseMove | IncrementalSource.TouchMove | IncrementalSource.Drag) => void;
378
+ type mouseInteractionCallBack = (d: mouseInteractionParam) => void;
379
+ type scrollCallback = (p: scrollPosition) => void;
380
+ type viewportResizeCallback = (d: viewportResizeDimension) => void;
381
+ type inputCallback = (v: inputValue & {
382
+ id: number;
383
+ }) => void;
384
+ type mediaInteractionCallback = (p: mediaInteractionParam) => void;
385
+ type styleSheetRuleCallback = (s: styleSheetRuleParam) => void;
386
+ type styleDeclarationCallback = (s: styleDeclarationParam) => void;
387
+ type canvasMutationCallback = (p: canvasMutationParam) => void;
388
+ type fontCallback = (p: fontParam) => void;
389
+ type selectionCallback = (p: selectionParam) => void;
390
+ type customElementCallback = (c: customElementParam) => void;
391
+ type hooksParam = {
392
+ mutation?: mutationCallBack;
393
+ mousemove?: mousemoveCallBack;
394
+ mouseInteraction?: mouseInteractionCallBack;
395
+ scroll?: scrollCallback;
396
+ viewportResize?: viewportResizeCallback;
397
+ input?: inputCallback;
398
+ mediaInteaction?: mediaInteractionCallback;
399
+ styleSheetRule?: styleSheetRuleCallback;
400
+ styleDeclaration?: styleDeclarationCallback;
401
+ canvasMutation?: canvasMutationCallback;
402
+ font?: fontCallback;
403
+ selection?: selectionCallback;
404
+ customElement?: customElementCallback;
405
+ };
406
+ type SamplingStrategy = Partial<{
407
+ mousemove: boolean | number;
408
+ mousemoveCallback: number;
409
+ mouseInteraction: boolean | Record<string, boolean | undefined>;
410
+ scroll: number;
411
+ media: number;
412
+ input: 'all' | 'last';
413
+ canvas: 'all' | number;
414
+ }>;
415
+ interface ICrossOriginIframeMirror {
416
+ getId(iframe: HTMLIFrameElement, remoteId: number, parentToRemoteMap?: Map<number, number>, remoteToParentMap?: Map<number, number>): number;
417
+ getIds(iframe: HTMLIFrameElement, remoteId: number[]): number[];
418
+ getRemoteId(iframe: HTMLIFrameElement, parentId: number, map?: Map<number, number>): number;
419
+ getRemoteIds(iframe: HTMLIFrameElement, parentId: number[]): number[];
420
+ reset(iframe?: HTMLIFrameElement): void;
421
+ }
422
+ type RecordPlugin<TOptions = unknown> = {
423
+ name: string;
424
+ observer?: (cb: (...args: Array<unknown>) => void, win: IWindow, options: TOptions) => listenerHandler;
425
+ eventProcessor?: <TExtend>(event: eventWithTime) => eventWithTime & TExtend;
426
+ getMirror?: (mirrors: {
427
+ nodeMirror: Mirror;
428
+ crossOriginIframeMirror: ICrossOriginIframeMirror;
429
+ crossOriginIframeStyleMirror: ICrossOriginIframeMirror;
430
+ }) => void;
431
+ options: TOptions;
432
+ };
433
+
434
+ type MaskInputOptions = Partial<{
435
+ color: boolean;
436
+ date: boolean;
437
+ 'datetime-local': boolean;
438
+ email: boolean;
439
+ month: boolean;
440
+ number: boolean;
441
+ range: boolean;
442
+ search: boolean;
443
+ tel: boolean;
444
+ text: boolean;
445
+ time: boolean;
446
+ url: boolean;
447
+ week: boolean;
448
+ textarea: boolean;
449
+ select: boolean;
450
+ password: boolean;
451
+ }>;
452
+ type MaskInputFn = (text: string, element: HTMLElement) => string;
453
+ type MaskTextFn = (text: string, element: HTMLElement | null) => string;
454
+ type SlimDOMOptions = Partial<{
455
+ script: boolean;
456
+ comment: boolean;
457
+ headFavicon: boolean;
458
+ headWhitespace: boolean;
459
+ headMetaDescKeywords: boolean;
460
+ headMetaSocial: boolean;
461
+ headMetaRobots: boolean;
462
+ headMetaHttpEquiv: boolean;
463
+ headMetaAuthorship: boolean;
464
+ headMetaVerification: boolean;
465
+ headTitleMutations: boolean;
466
+ }>;
467
+ type DataURLOptions = Partial<{
468
+ type: string;
469
+ quality: number;
470
+ }>;
471
+ type ErrorHandler = (error: unknown) => void | boolean;
472
+ type recordOptions = {
473
+ emit?: (e: eventWithTime, isCheckout?: boolean) => void;
474
+ checkoutEveryNth?: number;
475
+ checkoutEveryNms?: number;
476
+ blockClass?: blockClass;
477
+ blockSelector?: string;
478
+ ignoreClass?: string;
479
+ ignoreSelector?: string;
480
+ maskTextClass?: maskTextClass;
481
+ maskTextSelector?: string;
482
+ maskAllInputs?: boolean;
483
+ maskInputOptions?: MaskInputOptions;
484
+ maskInputFn?: MaskInputFn;
485
+ maskTextFn?: MaskTextFn;
486
+ slimDOMOptions?: SlimDOMOptions | 'all' | true;
487
+ ignoreCSSAttributes?: Set<string>;
488
+ inlineStylesheet?: boolean;
489
+ hooks?: hooksParam;
490
+ packFn?: PackFn;
491
+ sampling?: SamplingStrategy;
492
+ dataURLOptions?: DataURLOptions;
493
+ recordDOM?: boolean;
494
+ recordCanvas?: boolean;
495
+ recordCrossOriginIframes?: boolean;
496
+ recordAfter?: 'DOMContentLoaded' | 'load';
497
+ userTriggeredOnInput?: boolean;
498
+ collectFonts?: boolean;
499
+ inlineImages?: boolean;
500
+ plugins?: RecordPlugin[];
501
+ mousemoveWait?: number;
502
+ keepIframeSrcFn?: KeepIframeSrcFn;
503
+ errorHandler?: ErrorHandler;
504
+ };
505
+
506
+ type Property = any;
507
+ type Properties = Record<string, Property>;
508
+ type AutocaptureCompatibleElement = 'a' | 'button' | 'form' | 'input' | 'select' | 'textarea' | 'label';
509
+ type DomAutocaptureEvents = 'click' | 'change' | 'submit';
510
+ interface BootstrapConfig {
511
+ distinctId?: string;
512
+ isIdentifiedId?: boolean;
513
+ featureFlags?: Record<string, FeatureFlagValue>;
514
+ featureFlagPayloads?: Record<string, JsonType>;
515
+ /**
516
+ * Optionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be:
517
+ * - unique to this user
518
+ * - a valid UUID v7
519
+ * - the timestamp part must be <= the timestamp of the first event in the session
520
+ * - the timestamp of the last event in the session must be < the timestamp part + 24 hours
521
+ * **/
522
+ sessionID?: string;
523
+ }
524
+ /**
525
+ * If an array is passed for an allowlist, autocapture events will only be sent for elements matching
526
+ * at least one of the elements in the array. Multiple allowlists can be used
527
+ */
528
+ interface AutocaptureConfig {
529
+ /**
530
+ * List of URLs to allow autocapture on, can be strings to match
531
+ * or regexes e.g. ['https://example.com', 'test.com/.*']
532
+ * this is useful when you want to autocapture on specific pages only
533
+ *
534
+ * if you set both url_allowlist and url_ignorelist,
535
+ * we check the allowlist first and then the ignorelist.
536
+ * the ignorelist can override the allowlist
537
+ */
538
+ url_allowlist?: (string | RegExp)[];
539
+ /**
540
+ * List of URLs to not allow autocapture on, can be strings to match
541
+ * or regexes e.g. ['https://example.com', 'test.com/.*']
542
+ * this is useful when you want to autocapture on most pages but not some specific ones
543
+ *
544
+ * if you set both url_allowlist and url_ignorelist,
545
+ * we check the allowlist first and then the ignorelist.
546
+ * the ignorelist can override the allowlist
547
+ */
548
+ url_ignorelist?: (string | RegExp)[];
549
+ /**
550
+ * List of DOM events to allow autocapture on e.g. ['click', 'change', 'submit']
551
+ */
552
+ dom_event_allowlist?: DomAutocaptureEvents[];
553
+ /**
554
+ * List of DOM elements to allow autocapture on
555
+ * e.g. ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']
556
+ *
557
+ * We consider the tree of elements from the root to the target element of the click event
558
+ * so for the tree `div > div > button > svg`
559
+ * if the allowlist has `button` then we allow the capture when the `button` or the `svg` is the click target
560
+ * but not if either of the `div`s are detected as the click target
561
+ */
562
+ element_allowlist?: AutocaptureCompatibleElement[];
563
+ /**
564
+ * List of CSS selectors to allow autocapture on
565
+ * e.g. ['[ph-capture]']
566
+ * we consider the tree of elements from the root to the target element of the click event
567
+ * so for the tree div > div > button > svg
568
+ * and allow list config `['[id]']`
569
+ * we will capture the click if the click-target or its parents has any id
570
+ *
571
+ * Everything is allowed when there's no allowlist
572
+ */
573
+ css_selector_allowlist?: string[];
574
+ /**
575
+ * Exclude certain element attributes from autocapture
576
+ * E.g. ['aria-label'] or [data-attr-pii]
577
+ */
578
+ element_attribute_ignorelist?: string[];
579
+ /**
580
+ * When set to true, autocapture will capture the text of any element that is cut or copied.
581
+ */
582
+ capture_copied_text?: boolean;
583
+ }
584
+ interface LeanbaseConfig extends Partial<PostHogCoreOptions> {
585
+ /**
586
+ * API host for Leanbase
587
+ * @default 'https://i.leanbase.co'
588
+ */
589
+ host?: string;
590
+ /**
591
+ * The token for your Leanbase project.
592
+ * It should NOT be provided manually in the config, but rather passed as the first parameter to `leanbase.init()`.
593
+ */
594
+ token: string;
595
+ /**
596
+ * Enables debug mode, which provides more verbose logging for development purposes.
597
+ * @default false
598
+ */
599
+ debug?: boolean;
600
+ /**
601
+ * Determines whether Leanbase should autocapture events.
602
+ * This setting does not affect capturing pageview events (see `capture_pageview`).
603
+ *
604
+ * by default autocapture is ignored on elements that match a `ph-no-capture` css class on the element or a parent
605
+ * @default true
606
+ */
607
+ autocapture: boolean | AutocaptureConfig;
608
+ /**
609
+ * Enables or disables session recording. When true, session recording is disabled on the client.
610
+ * @default false
611
+ */
612
+ disable_session_recording?: boolean;
613
+ /**
614
+ * Session recording configuration
615
+ */
616
+ session_recording?: SessionRecordingOptions;
617
+ /**
618
+ * Enable console.log recording for session replay (can be controlled remotely). Undefined defers to server.
619
+ */
620
+ enable_recording_console_log?: boolean;
621
+ /**
622
+ * Determines whether Leanbase should capture pageview events automatically.
623
+ * Can be:
624
+ * - `true`: Capture regular pageviews (default)
625
+ * - `false`: Don't capture any pageviews
626
+ * - `'history_change'`: Only capture pageviews on history API changes (pushState, replaceState, popstate)
627
+ *
628
+ * @default true
629
+ */
630
+ capture_pageview: boolean | 'history_change';
631
+ /**
632
+ * Enables performance capture. When true, network performance timing can be forwarded to replay when enabled.
633
+ */
634
+ capture_performance?: boolean | {
635
+ network_timing?: boolean;
636
+ };
637
+ /**
638
+ * Determines the session idle timeout in seconds.
639
+ * Any new event that's happened after this timeout will create a new session.
640
+ *
641
+ * @default 30 * 60 -- 30 minutes
642
+ */
643
+ session_idle_timeout_seconds: number;
644
+ /**
645
+ * An object containing the `distinctID`, `isIdentifiedID`, and `featureFlags` keys,
646
+ * where `distinctID` is a string, and `featureFlags` is an object of key-value pairs.
647
+ *
648
+ * Since there is a delay between initializing PostHog and fetching feature flags,
649
+ * feature flags are not always available immediately.
650
+ * This makes them unusable if you want to do something like redirecting a user
651
+ * to a different page based on a feature flag.
652
+ *
653
+ * You can, therefore, fetch the feature flags in your server and pre-fill them here,
654
+ * allowing PostHog to know the feature flag values immediately.
655
+ *
656
+ * After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones.
657
+ *
658
+ * @default {}
659
+ */
660
+ bootstrap: BootstrapConfig;
661
+ /**
662
+ * Determines whether Leanbase should capture pageleave events.
663
+ * If set to `true`, it will capture pageleave events for all pages.
664
+ * If set to `'if_capture_pageview'`, it will only capture pageleave events if `capture_pageview` is also set to `true` or `'history_change'`.
665
+ *
666
+ * @default 'if_capture_pageview'
667
+ */
668
+ capture_pageleave: boolean | 'if_capture_pageview';
669
+ /**
670
+ * Determines whether Leanbase should capture rage clicks.
671
+ *
672
+ * by default rageclicks are ignored on elements that match a `ph-no-capture` or `ph-no-rageclick` css class on the element or a parent
673
+ * @default true
674
+ */
675
+ rageclick: boolean | RageclickConfig;
676
+ /**
677
+ * Determines where to store the Leanbase persistence information.
678
+ */
679
+ persistence: 'localStorage' | 'cookie' | 'memory' | 'localStorage+cookie' | 'sessionStorage';
680
+ /**
681
+ * The name for the super properties persistent store
682
+ *
683
+ * @default ''
684
+ */
685
+ persistence_name: string;
686
+ /**
687
+ * Prevent autocapture from capturing any attribute names on elements.
688
+ *
689
+ * @default false
690
+ */
691
+ mask_all_element_attributes: boolean;
692
+ /**
693
+ * Prevent autocapture from capturing `textContent` on elements.
694
+ *
695
+ * @default false
696
+ */
697
+ mask_all_text: boolean;
698
+ /**
699
+ * Used to extend the list of campaign parameters that are saved by default.
700
+ *
701
+ * @see {CAMPAIGN_PARAMS} from './utils/event-utils' - Default campaign parameters like utm_source, utm_medium, etc.
702
+ * @default []
703
+ */
704
+ custom_campaign_params: string[];
705
+ /**
706
+ * Mask personal data properties from the current URL.
707
+ * This will mask personal data properties such as advertising IDs (gclid, fbclid, etc.), and you can also add
708
+ * custom properties to mask with `custom_personal_data_properties`.
709
+ * @default false
710
+ * @see {PERSONAL_DATA_CAMPAIGN_PARAMS} - Default campaign parameters that are masked by default.
711
+ * @see {LeanbaseConfig.custom_personal_data_properties} - Custom list of personal data properties to mask.
712
+ */
713
+ mask_personal_data_properties: boolean;
714
+ /**
715
+ * Custom list of personal data properties to mask.
716
+ *
717
+ * E.g. if you added `email` to this list, then any `email` property in the URL will be masked.
718
+ * https://www.example.com/login?email=john.doe%40example.com => https://www.example.com/login?email=<MASKED>
719
+ *
720
+ * @default []
721
+ * @see {LeanbaseConfig.mask_personal_data_properties} - Must be enabled for this to take effect.
722
+ */
723
+ custom_personal_data_properties: string[];
724
+ /**
725
+ * Determines the number of days to store cookies for.
726
+ *
727
+ * @default 365
728
+ */
729
+ cookie_expiration: number;
730
+ /**
731
+ * Determines whether Leanbase should use secure cookies.
732
+ * If this is `true`, Leanbase cookies will be marked as secure,
733
+ * meaning they will only be transmitted over HTTPS.
734
+ *
735
+ * @default window.location.protocol === 'https:'
736
+ */
737
+ secure_cookie: boolean;
738
+ /**
739
+ * Determines if cookie should be set on the top level domain (example.com).
740
+ * If leanbase-js is loaded on a subdomain (test.example.com), and `cross_subdomain_cookie` is set to false,
741
+ * it'll set the cookie on the subdomain only (test.example.com).
742
+ *
743
+ * NOTE: It will be set to `false` if we detect that the domain is a subdomain of a platform that is excluded from cross-subdomain cookie setting.
744
+ * The current list of excluded platforms is `herokuapp.com`, `vercel.app`, and `netlify.app`.
745
+ *
746
+ * @see `isCrossDomainCookie`
747
+ * @default true
748
+ */
749
+ cross_subdomain_cookie: boolean;
750
+ /**
751
+ * Determines whether Leanbase should disable persistence.
752
+ * If set to `true`, the library will not save any data to the browser. It will also delete any data previously saved to the browser.
753
+ *
754
+ * @default false
755
+ */
756
+ disable_persistence: boolean;
757
+ /**
758
+ * Enables cookieless mode. In this mode, Leanbase will not set any cookies, or use session or local storage. User
759
+ * identity is handled by generating a privacy-preserving hash on Leanbase's servers.
760
+ * - 'always' - enable cookieless mode immediately on startup, use this if you do not intend to show a cookie banner
761
+ * - 'on_reject' - enable cookieless mode only if the user rejects cookies, use this if you want to show a cookie banner. If the user accepts cookies, cookieless mode will not be used, and PostHog will use cookies and local storage as usual.
762
+ *
763
+ * Note that you MUST enable cookieless mode in your Leanbase project's settings, otherwise all your cookieless events will be ignored. We plan to remove this requirement in the future.
764
+ * */
765
+ cookieless_mode?: 'always' | 'on_reject';
766
+ /**
767
+ * Determines whether PostHog should save referrer information.
768
+ *
769
+ * @default true
770
+ */
771
+ save_referrer: boolean;
772
+ /**
773
+ * Determines whether PostHog should save marketing parameters.
774
+ * These are `utm_*` paramaters and friends.
775
+ *
776
+ * @see {CAMPAIGN_PARAMS} from './utils/event-utils' - Default campaign parameters like utm_source, utm_medium, etc.
777
+ * @default true
778
+ */
779
+ save_campaign_params: boolean;
780
+ /**
781
+ * Determines whether to disable scroll properties.
782
+ * These allow you to keep track of how far down someone scrolled in your website.
783
+ *
784
+ * @default false
785
+ */
786
+ disable_scroll_properties?: boolean;
787
+ /**
788
+ * Let the pageview scroll stats use a custom css selector for the root element, e.g. `main`
789
+ * It will use `window.document.documentElement` if not specified.
790
+ */
791
+ scroll_root_selector?: string | string[];
792
+ /**
793
+ * Determines if users should be opted out of user agent filtering such as googlebot or other bots.
794
+ * If this is set to `true`, PostHog will set `$browser_type` to either `bot` or `browser` for all events,
795
+ * but will process all events as if they were from a browser.
796
+ *
797
+ * @default false
798
+ */
799
+ opt_out_useragent_filter: boolean;
800
+ /**
801
+ * Determines the maximum length of the properties string that can be sent with capture calls.
802
+ *
803
+ * @default 65535
804
+ */
805
+ properties_string_max_length: number;
806
+ /**
807
+ * A function to be called once the Leanbase scripts have loaded successfully.
808
+ *
809
+ * @param instance - The Leanbase instance that has been loaded.
810
+ */
811
+ loaded: (instance: Leanbase) => void;
812
+ }
813
+ type SessionRecordingCanvasOptions = {
814
+ recordCanvas?: boolean | null;
815
+ canvasFps?: number | null;
816
+ canvasQuality?: string | null;
817
+ };
818
+ interface SessionRecordingOptions {
819
+ blockClass?: string | RegExp;
820
+ blockSelector?: string | null;
821
+ ignoreClass?: string | RegExp;
822
+ maskTextClass?: string | RegExp;
823
+ maskTextSelector?: string | null;
824
+ maskTextFn?: ((text: string, element?: HTMLElement) => string) | null;
825
+ maskAllInputs?: boolean;
826
+ maskInputOptions?: recordOptions['maskInputOptions'];
827
+ maskInputFn?: ((text: string, element?: HTMLElement) => string) | null;
828
+ slimDOMOptions?: recordOptions['slimDOMOptions'];
829
+ collectFonts?: boolean;
830
+ inlineStylesheet?: boolean;
831
+ recordCrossOriginIframes?: boolean;
832
+ recordHeaders?: boolean;
833
+ recordBody?: boolean;
834
+ captureCanvas?: SessionRecordingCanvasOptions;
835
+ maskCapturedNetworkRequestFn?: ((data: CapturedNetworkRequest) => CapturedNetworkRequest | null | undefined) | null;
836
+ maskNetworkRequestFn?: ((data: NetworkRequest) => NetworkRequest | null | undefined) | null;
837
+ full_snapshot_interval_millis?: number;
838
+ compress_events?: boolean;
839
+ session_idle_threshold_ms?: number;
840
+ __mutationThrottlerRefillRate?: number;
841
+ __mutationThrottlerBucketSize?: number;
842
+ /**
843
+ * Force-enable session recording locally even if remote config disables it.
844
+ * Useful for dev/testing when the backend has sessionRecording set to false.
845
+ */
846
+ forceClientRecording?: boolean;
847
+ }
848
+ type SessionRecordingRemoteConfig = SessionRecordingCanvasOptions & {
849
+ endpoint?: string;
850
+ consoleLogRecordingEnabled?: boolean;
851
+ sampleRate?: string | null;
852
+ minimumDurationMilliseconds?: number;
853
+ linkedFlag?: string | {
854
+ flag: string;
855
+ variant: string;
856
+ } | null;
857
+ networkPayloadCapture?: Pick<NetworkRecordOptions, 'recordBody' | 'recordHeaders' | 'payloadHostDenyList'>;
858
+ masking?: Pick<SessionRecordingOptions, 'maskAllInputs' | 'maskTextSelector' | 'blockSelector'>;
859
+ urlTriggers?: SessionRecordingUrlTrigger[];
860
+ scriptConfig?: {
861
+ script?: string | undefined;
862
+ };
863
+ urlBlocklist?: SessionRecordingUrlTrigger[];
864
+ eventTriggers?: string[];
865
+ triggerMatchType?: 'any' | 'all';
866
+ };
867
+ interface RageclickConfig {
868
+ /**
869
+ * List of CSS selectors to ignore rageclicks on
870
+ * e.g. ['.my-calendar-button']
871
+ * we consider the tree of elements from the root to the target element of the click event
872
+ * so for the tree div > div > button > svg
873
+ * and ignore list config `['[id]']`
874
+ * we will ignore the rageclick if the click-target or its parents has any id
875
+ *
876
+ * Nothing is ignored when there's an empty ignorelist, e.g. []
877
+ * If no ignorelist is set, we default to ignoring .ph-no-rageclick
878
+ * If an element has .ph-no-capture, it will always be ignored by rageclick and autocapture
879
+ */
880
+ css_selector_ignorelist?: string[];
881
+ }
882
+ type PropertyMatchType = 'regex' | 'not_regex' | 'exact' | 'is_not' | 'icontains' | 'not_icontains';
883
+ interface ErrorTrackingSuppressionRule {
884
+ type: 'AND' | 'OR';
885
+ values: ErrorTrackingSuppressionRuleValue[];
886
+ }
887
+ interface ErrorTrackingSuppressionRuleValue {
888
+ key: '$exception_types' | '$exception_values';
889
+ operator: PropertyMatchType;
890
+ value: string | string[];
891
+ type: string;
892
+ }
893
+ declare enum Compression {
894
+ GZipJS = "gzip-js",
895
+ Base64 = "base64"
896
+ }
897
+ type SupportedWebVitalsMetrics = 'LCP' | 'CLS' | 'FCP' | 'INP';
898
+ interface PerformanceCaptureConfig {
899
+ /**
900
+ * Works with session replay to use the browser's native performance observer to capture performance metrics
901
+ */
902
+ network_timing?: boolean;
903
+ /**
904
+ * Use chrome's web vitals library to wrap fetch and capture web vitals
905
+ */
906
+ web_vitals?: boolean;
907
+ /**
908
+ * We observe very large values reported by the Chrome web vitals library
909
+ * These outliers are likely not real, useful values, and we exclude them
910
+ * You can set this to 0 in order to include all values, NB this is not recommended
911
+ *
912
+ * @default 15 * 60 * 1000 (15 minutes)
913
+ */
914
+ __web_vitals_max_value?: number;
915
+ /**
916
+ * By default all 4 metrics are captured
917
+ * You can set this config to restrict which metrics are captured
918
+ * e.g. ['CLS', 'FCP'] to only capture those two metrics
919
+ * NB setting this does not override whether the capture is enabled
920
+ *
921
+ * @default ['LCP', 'CLS', 'FCP', 'INP']
922
+ */
923
+ web_vitals_allowed_metrics?: SupportedWebVitalsMetrics[];
924
+ /**
925
+ * We delay flushing web vitals metrics to reduce the number of events we send
926
+ * This is the maximum time we will wait before sending the metrics
927
+ *
928
+ * @default 5000
929
+ */
930
+ web_vitals_delayed_flush_ms?: number;
931
+ }
932
+ /**
933
+ * Remote configuration for the Leanbase instance
934
+ *
935
+ * All of these settings can be configured directly in your Leanbase instance
936
+ * Any configuration set in the client overrides the information from the server
937
+ */
938
+ interface RemoteConfig {
939
+ /**
940
+ * Supported compression algorithms
941
+ */
942
+ supportedCompression: Compression[];
943
+ /**
944
+ * If set, disables autocapture
945
+ */
946
+ autocapture_opt_out?: boolean;
947
+ /**
948
+ * originally capturePerformance was replay only and so boolean true
949
+ * is equivalent to { network_timing: true }
950
+ * now capture performance can be separately enabled within replay
951
+ * and as a standalone web vitals tracker
952
+ * people can have them enabled separately
953
+ * they work standalone but enhance each other
954
+ * TODO: deprecate this so we make a new config that doesn't need this explanation
955
+ */
956
+ capturePerformance?: boolean | PerformanceCaptureConfig;
957
+ /**
958
+ * Whether we should use a custom endpoint for analytics
959
+ *
960
+ * @default { endpoint: "/e" }
961
+ */
962
+ analytics?: {
963
+ endpoint?: string;
964
+ };
965
+ /**
966
+ * Whether the `$elements_chain` property should be sent as a string or as an array
967
+ *
968
+ * @default false
969
+ */
970
+ elementsChainAsString?: boolean;
971
+ /**
972
+ * Error tracking configuration options
973
+ */
974
+ errorTracking?: {
975
+ autocaptureExceptions?: boolean;
976
+ captureExtensionExceptions?: boolean;
977
+ suppressionRules?: ErrorTrackingSuppressionRule[];
978
+ };
979
+ /**
980
+ * This is currently in development and may have breaking changes without a major version bump
981
+ */
982
+ autocaptureExceptions?: boolean | {
983
+ endpoint?: string;
984
+ };
985
+ /**
986
+ * Session recording configuration options
987
+ */
988
+ sessionRecording?: SessionRecordingRemoteConfig | false;
989
+ /**
990
+ * @deprecated, moved to toolbarParams
991
+ */
992
+ toolbarVersion: 'toolbar';
993
+ /**
994
+ * Whether the user is authenticated
995
+ */
996
+ isAuthenticated: boolean;
997
+ /**
998
+ * List of site apps with their IDs and URLs
999
+ */
1000
+ siteApps: {
1001
+ id: string;
1002
+ url: string;
1003
+ }[];
1004
+ /**
1005
+ * Whether heatmaps are enabled
1006
+ */
1007
+ heatmaps?: boolean;
1008
+ /**
1009
+ * Whether to only capture identified users by default
1010
+ */
1011
+ defaultIdentifiedOnly?: boolean;
1012
+ /**
1013
+ * Whether to capture dead clicks
1014
+ */
1015
+ captureDeadClicks?: boolean;
1016
+ /**
1017
+ * Indicates if the team has any flags enabled (if not we don't need to load them)
1018
+ */
1019
+ hasFeatureFlags?: boolean;
1020
+ }
1021
+ interface RequestResponse {
1022
+ statusCode: number;
1023
+ text?: string;
1024
+ json?: any;
1025
+ }
1026
+ type RequestCallback = (response: RequestResponse) => void;
1027
+ type NextOptions = {
1028
+ revalidate: false | 0 | number;
1029
+ tags: string[];
1030
+ };
1031
+ interface RequestWithOptions {
1032
+ url: string;
1033
+ data?: Record<string, any> | Record<string, any>[];
1034
+ headers?: Record<string, any>;
1035
+ transport?: 'XHR' | 'fetch' | 'sendBeacon';
1036
+ method?: 'POST' | 'GET';
1037
+ urlQueryArgs?: {
1038
+ compression: Compression;
1039
+ };
1040
+ callback?: RequestCallback;
1041
+ timeout?: number;
1042
+ noRetries?: boolean;
1043
+ disableTransport?: ('XHR' | 'fetch' | 'sendBeacon')[];
1044
+ disableXHRCredentials?: boolean;
1045
+ compression?: Compression | 'best-available';
1046
+ fetchOptions?: {
1047
+ cache?: RequestInit['cache'];
1048
+ next?: NextOptions;
1049
+ };
1050
+ }
1051
+ type InitiatorType = 'audio' | 'beacon' | 'body' | 'css' | 'early-hints' | 'embed' | 'fetch' | 'frame' | 'iframe' | 'image' | 'img' | 'input' | 'link' | 'navigation' | 'object' | 'ping' | 'script' | 'track' | 'video' | 'xmlhttprequest';
1052
+ type NetworkRecordOptions = {
1053
+ initiatorTypes?: InitiatorType[];
1054
+ maskRequestFn?: (data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined;
1055
+ recordHeaders?: boolean | {
1056
+ request: boolean;
1057
+ response: boolean;
1058
+ };
1059
+ recordBody?: boolean | string[] | {
1060
+ request: boolean | string[];
1061
+ response: boolean | string[];
1062
+ };
1063
+ recordInitialRequests?: boolean;
1064
+ recordPerformance?: boolean;
1065
+ performanceEntryTypeToObserve: string[];
1066
+ payloadSizeLimitBytes: number;
1067
+ payloadHostDenyList?: string[];
1068
+ };
1069
+ type NetworkRequest = {
1070
+ url: string;
1071
+ };
1072
+ type Headers = Record<string, any>;
1073
+ type Writable<T> = {
1074
+ -readonly [P in keyof T]: T[P];
1075
+ };
1076
+ type CapturedNetworkRequest = Writable<Omit<PerformanceEntry, 'toJSON'>> & {
1077
+ method?: string;
1078
+ initiatorType?: InitiatorType;
1079
+ status?: number;
1080
+ timeOrigin?: number;
1081
+ timestamp?: number;
1082
+ startTime?: number;
1083
+ endTime?: number;
1084
+ requestHeaders?: Headers;
1085
+ requestBody?: string | null;
1086
+ responseHeaders?: Headers;
1087
+ responseBody?: string | null;
1088
+ isInitial?: boolean;
1089
+ };
1090
+ interface SessionRecordingUrlTrigger {
1091
+ url: string;
1092
+ matching: 'regex';
1093
+ }
1094
+ type SessionStartReason = 'sampling_overridden' | 'recording_initialized' | 'linked_flag_matched' | 'linked_flag_overridden' | 'sampled' | 'session_id_changed' | 'url_trigger_matched' | 'event_trigger_matched';
1095
+ type SessionIdChangedCallback = (sessionId: string, windowId: string | null | undefined, changeReason?: {
1096
+ noSessionId: boolean;
1097
+ activityTimeout: boolean;
1098
+ sessionPastMaximumLength: boolean;
1099
+ }) => void;
1100
+ type LeanbasegCaptureOptions = {
1101
+ /** If provided overrides the auto-generated event ID */
1102
+ uuid?: string;
1103
+ disableGeoip?: boolean;
1104
+ /**
1105
+ * Used when `$identify` is called
1106
+ * Will set person properties overriding previous values
1107
+ */
1108
+ $set?: Properties;
1109
+ /**
1110
+ * Used when `$identify` is called
1111
+ * Will set person properties but only once, it will NOT override previous values
1112
+ */
1113
+ $set_once?: Properties;
1114
+ /**
1115
+ * Used to override the desired endpoint for the captured event
1116
+ */
1117
+ _url?: string;
1118
+ /**
1119
+ * key of queue, e.g. 'sessionRecording' vs 'event'
1120
+ */
1121
+ _batchKey?: string;
1122
+ /**
1123
+ * If set, overrides and disables config.properties_string_max_length
1124
+ */
1125
+ _noTruncate?: boolean;
1126
+ /**
1127
+ * If set, skips the batched queue
1128
+ */
1129
+ send_instantly?: boolean;
1130
+ /**
1131
+ * If set, skips the client side rate limiting
1132
+ */
1133
+ skip_client_rate_limiting?: boolean;
1134
+ /**
1135
+ * If set, overrides the desired transport method
1136
+ */
1137
+ transport?: RequestWithOptions['transport'];
1138
+ /**
1139
+ * If set, overrides the current timestamp
1140
+ */
1141
+ timestamp?: Date;
1142
+ };
1143
+
1144
+ /**
1145
+ * Leanbase Persistence Object
1146
+ * @constructor
1147
+ */
1148
+ declare class LeanbasePersistence {
1149
+ private _config;
1150
+ props: Properties;
1151
+ private _storage;
1152
+ private _campaign_params_saved;
1153
+ private readonly _name;
1154
+ _disabled: boolean | undefined;
1155
+ private _secure;
1156
+ private _expire_days;
1157
+ private _default_expiry;
1158
+ private _cross_subdomain;
1159
+ /**
1160
+ * @param {LeanbaseConfig} config initial PostHog configuration
1161
+ * @param {boolean=} isDisabled should persistence be disabled (e.g. because of consent management)
1162
+ */
1163
+ constructor(config: LeanbaseConfig, isDisabled?: boolean);
1164
+ /**
1165
+ * Returns whether persistence is disabled. Only available in SDKs > 1.257.1. Do not use on extensions, otherwise
1166
+ * it'll break backwards compatibility for any version before 1.257.1.
1167
+ */
1168
+ isDisabled?(): boolean;
1169
+ private _buildStorage;
1170
+ properties(): Properties;
1171
+ load(): void;
1172
+ /**
1173
+ * NOTE: Saving frequently causes issues with Recordings and Consent Management Platform (CMP) tools which
1174
+ * observe cookie changes, and modify their UI, often causing infinite loops.
1175
+ * As such callers of this should ideally check that the data has changed beforehand
1176
+ */
1177
+ save(): void;
1178
+ remove(): void;
1179
+ clear(): void;
1180
+ /**
1181
+ * @param {Object} props
1182
+ * @param {*=} default_value
1183
+ * @param {number=} days
1184
+ */
1185
+ register_once(props: Properties, default_value: any, days?: number): boolean;
1186
+ /**
1187
+ * @param {Object} props
1188
+ * @param {number=} days
1189
+ */
1190
+ register(props: Properties, days?: number): boolean;
1191
+ unregister(prop: string): void;
1192
+ update_campaign_params(): void;
1193
+ update_search_keyword(): void;
1194
+ update_referrer_info(): void;
1195
+ set_initial_person_info(): void;
1196
+ get_initial_props(): Properties;
1197
+ safe_merge(props: Properties): Properties;
1198
+ update_config(config: LeanbaseConfig, oldConfig: LeanbaseConfig, isDisabled?: boolean): void;
1199
+ set_disabled(disabled: boolean): void;
1200
+ set_cross_subdomain(cross_subdomain: boolean): void;
1201
+ set_secure(secure: boolean): void;
1202
+ set_event_timer(event_name: string, timestamp: number): void;
1203
+ remove_event_timer(event_name: string): number;
1204
+ get_property(prop: string): any;
1205
+ set_property(prop: string, to: any): void;
1206
+ }
1207
+
1208
+ declare class RageClick {
1209
+ clicks: {
1210
+ x: number;
1211
+ y: number;
1212
+ timestamp: number;
1213
+ }[];
1214
+ constructor();
1215
+ isRageClick(x: number, y: number, timestamp: number): boolean;
1216
+ }
1217
+
1218
+ declare class Autocapture {
1219
+ instance: Leanbase;
1220
+ _initialized: boolean;
1221
+ _isDisabledServerSide: boolean | null;
1222
+ _elementSelectors: Set<string> | null;
1223
+ rageclicks: RageClick;
1224
+ _elementsChainAsString: boolean;
1225
+ constructor(instance: Leanbase);
1226
+ private get _config();
1227
+ _addDomEventHandlers(): void;
1228
+ startIfEnabled(): void;
1229
+ onRemoteConfig(response: RemoteConfig): void;
1230
+ setElementSelectors(selectors: Set<string>): void;
1231
+ getElementSelectors(element: Element | null): string[] | null;
1232
+ get isEnabled(): boolean;
1233
+ private _captureEvent;
1234
+ isBrowserSupported(): boolean;
1235
+ }
1236
+
1237
+ declare class SessionIdManager {
1238
+ private readonly _sessionIdGenerator;
1239
+ private readonly _windowIdGenerator;
1240
+ private _config;
1241
+ private _persistence;
1242
+ private _windowId;
1243
+ private _sessionId;
1244
+ private readonly _window_id_storage_key;
1245
+ private readonly _primary_window_exists_storage_key;
1246
+ private _sessionStartTimestamp;
1247
+ private _sessionActivityTimestamp;
1248
+ private _sessionIdChangedHandlers;
1249
+ private readonly _sessionTimeoutMs;
1250
+ private _enforceIdleTimeout;
1251
+ private _beforeUnloadListener;
1252
+ private _eventEmitter;
1253
+ on(event: 'forcedIdleReset', handler: () => void): () => void;
1254
+ constructor(instance: Leanbase, sessionIdGenerator?: () => string, windowIdGenerator?: () => string);
1255
+ get sessionTimeoutMs(): number;
1256
+ onSessionId(callback: SessionIdChangedCallback): () => void;
1257
+ private _canUseSessionStorage;
1258
+ private _setWindowId;
1259
+ private _getWindowId;
1260
+ private _setSessionId;
1261
+ private _getSessionId;
1262
+ resetSessionId(): void;
1263
+ /**
1264
+ * Cleans up resources used by SessionIdManager.
1265
+ * Should be called when the SessionIdManager is no longer needed to prevent memory leaks.
1266
+ */
1267
+ destroy(): void;
1268
+ private _listenToReloadWindow;
1269
+ private _sessionHasBeenIdleTooLong;
1270
+ checkAndGetSessionAndWindowId(readOnly?: boolean, _timestamp?: number | null): {
1271
+ sessionId: string;
1272
+ windowId: string;
1273
+ sessionStartTimestamp: number;
1274
+ changeReason: {
1275
+ noSessionId: boolean;
1276
+ activityTimeout: boolean;
1277
+ sessionPastMaximumLength: boolean;
1278
+ } | undefined;
1279
+ lastActivityTimestamp: number;
1280
+ };
1281
+ private _resetIdleTimer;
1282
+ }
1283
+
1284
+ interface LegacySessionSourceProps {
1285
+ initialPathName: string;
1286
+ referringDomain: string;
1287
+ utm_medium?: string;
1288
+ utm_source?: string;
1289
+ utm_campaign?: string;
1290
+ utm_content?: string;
1291
+ utm_term?: string;
1292
+ }
1293
+ interface CurrentSessionSourceProps {
1294
+ r: string;
1295
+ u: string | undefined;
1296
+ }
1297
+ interface StoredSessionSourceProps {
1298
+ sessionId: string;
1299
+ props: LegacySessionSourceProps | CurrentSessionSourceProps;
1300
+ }
1301
+ declare class SessionPropsManager {
1302
+ private readonly _instance;
1303
+ private readonly _sessionIdManager;
1304
+ private readonly _persistence;
1305
+ private readonly _sessionSourceParamGenerator;
1306
+ constructor(instance: Leanbase, sessionIdManager: SessionIdManager, persistence: LeanbasePersistence, sessionSourceParamGenerator?: (instance?: Leanbase) => LegacySessionSourceProps | CurrentSessionSourceProps);
1307
+ _getStored(): StoredSessionSourceProps | undefined;
1308
+ _onSessionIdCallback: (sessionId: string) => void;
1309
+ getSetOnceProps(): Record<string, any>;
1310
+ getSessionProps(): Record<string, any>;
1311
+ }
1312
+
1313
+ interface PageViewEventProperties {
1314
+ $pageview_id?: string;
1315
+ $prev_pageview_id?: string;
1316
+ $prev_pageview_pathname?: string;
1317
+ $prev_pageview_duration?: number;
1318
+ $prev_pageview_last_scroll?: number;
1319
+ $prev_pageview_last_scroll_percentage?: number;
1320
+ $prev_pageview_max_scroll?: number;
1321
+ $prev_pageview_max_scroll_percentage?: number;
1322
+ $prev_pageview_last_content?: number;
1323
+ $prev_pageview_last_content_percentage?: number;
1324
+ $prev_pageview_max_content?: number;
1325
+ $prev_pageview_max_content_percentage?: number;
1326
+ }
1327
+ declare class PageViewManager {
1328
+ _currentPageview?: {
1329
+ timestamp: Date;
1330
+ pageViewId: string | undefined;
1331
+ pathname: string | undefined;
1332
+ };
1333
+ _instance: Leanbase;
1334
+ constructor(instance: Leanbase);
1335
+ doPageView(timestamp: Date, pageViewId?: string): PageViewEventProperties;
1336
+ doPageLeave(timestamp: Date): PageViewEventProperties;
1337
+ doEvent(): PageViewEventProperties;
1338
+ private _previousPageViewProperties;
1339
+ }
1340
+
1341
+ interface ScrollContext {
1342
+ maxScrollHeight?: number;
1343
+ maxScrollY?: number;
1344
+ lastScrollY?: number;
1345
+ maxContentHeight?: number;
1346
+ maxContentY?: number;
1347
+ lastContentY?: number;
1348
+ }
1349
+ declare class ScrollManager {
1350
+ private _instance;
1351
+ private _context;
1352
+ constructor(_instance: Leanbase);
1353
+ getContext(): ScrollContext | undefined;
1354
+ resetContext(): ScrollContext | undefined;
1355
+ private _updateScrollData;
1356
+ startMeasuringScrollPosition(): void;
1357
+ scrollElement(): Element | undefined;
1358
+ scrollY(): number;
1359
+ scrollX(): number;
1360
+ }
1361
+
1362
+ type TriggerType = 'url' | 'event';
1363
+ /**
1364
+ * Session recording starts in buffering mode while waiting for "flags response".
1365
+ * Once the response is received, it might be disabled, active or sampled.
1366
+ * When "sampled" that means a sample rate is set, and the last time the session ID rotated
1367
+ * the sample rate determined this session should be sent to the server.
1368
+ */
1369
+ declare const sessionRecordingStatuses: readonly ["disabled", "sampled", "active", "buffering", "paused", "lazy_loading"];
1370
+ type SessionRecordingStatus = (typeof sessionRecordingStatuses)[number];
1371
+
1372
+ declare class SessionRecording {
1373
+ private readonly _instance;
1374
+ _forceAllowLocalhostNetworkCapture: boolean;
1375
+ private _receivedFlags;
1376
+ private _serverRecordingEnabled;
1377
+ private _persistFlagsOnSessionListener;
1378
+ private _lazyLoadedSessionRecording;
1379
+ get started(): boolean;
1380
+ /**
1381
+ * defaults to buffering mode until a flags response is received
1382
+ * once a flags response is received status can be disabled, active or sampled
1383
+ */
1384
+ get status(): SessionRecordingStatus;
1385
+ constructor(_instance: Leanbase);
1386
+ private get _isRecordingEnabled();
1387
+ startIfEnabledOrStop(startReason?: SessionStartReason): void;
1388
+ /**
1389
+ * session recording waits until it receives remote config before loading the script
1390
+ * this is to ensure we can control the script name remotely
1391
+ * and because we wait until we have local and remote config to determine if we should start at all
1392
+ * if start is called and there is no remote config then we wait until there is
1393
+ */
1394
+ private _lazyLoadAndStart;
1395
+ stopRecording(): void;
1396
+ private _resetSampling;
1397
+ private _persistRemoteConfig;
1398
+ private _clearRemoteConfig;
1399
+ onRemoteConfig(response: RemoteConfig): void;
1400
+ log(message: string, level?: 'log' | 'warn' | 'error'): void;
1401
+ private _onScriptLoaded;
1402
+ /**
1403
+ * this is maintained on the public API only because it has always been on the public API
1404
+ * if you are calling this directly you are certainly doing something wrong
1405
+ * @deprecated
1406
+ */
1407
+ onRRwebEmit(rawEvent: eventWithTime): void;
1408
+ /**
1409
+ * this ignores the linked flag config and (if other conditions are met) causes capture to start
1410
+ *
1411
+ * It is not usual to call this directly,
1412
+ * instead call `posthog.startSessionRecording({linked_flag: true})`
1413
+ * */
1414
+ overrideLinkedFlag(): void;
1415
+ /**
1416
+ * this ignores the sampling config and (if other conditions are met) causes capture to start
1417
+ *
1418
+ * It is not usual to call this directly,
1419
+ * instead call `posthog.startSessionRecording({sampling: true})`
1420
+ * */
1421
+ overrideSampling(): void;
1422
+ /**
1423
+ * this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start
1424
+ *
1425
+ * It is not usual to call this directly,
1426
+ * instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`
1427
+ * */
1428
+ overrideTrigger(triggerType: TriggerType): void;
1429
+ get sdkDebugProperties(): Properties;
1430
+ /**
1431
+ * This adds a custom event to the session recording
1432
+ *
1433
+ * It is not intended for arbitrary public use - playback only displays known custom events
1434
+ * And is exposed on the public interface only so that other parts of the SDK are able to use it
1435
+ *
1436
+ * if you are calling this from client code, you're probably looking for `posthog.capture('$custom_event', {...})`
1437
+ */
1438
+ tryAddCustomEvent(tag: string, payload: any): boolean;
1439
+ }
1440
+
1441
+ declare class Leanbase extends PostHogCore {
1442
+ config: LeanbaseConfig;
1443
+ scrollManager: ScrollManager;
1444
+ pageViewManager: PageViewManager;
1445
+ replayAutocapture?: Autocapture;
1446
+ persistence?: LeanbasePersistence;
1447
+ sessionPersistence?: LeanbasePersistence;
1448
+ sessionManager?: SessionIdManager;
1449
+ sessionPropsManager?: SessionPropsManager;
1450
+ sessionRecording?: SessionRecording;
1451
+ isRemoteConfigLoaded?: boolean;
1452
+ personProcessingSetOncePropertiesSent: boolean;
1453
+ isLoaded: boolean;
1454
+ initialPageviewCaptured: boolean;
1455
+ visibilityStateListener: (() => void) | null;
1456
+ constructor(token: string, config?: Partial<LeanbaseConfig>);
1457
+ init(token: string, config: Partial<LeanbaseConfig>): void;
1458
+ captureInitialPageview(): void;
1459
+ capturePageLeave(): void;
1460
+ loadRemoteConfig(): Promise<void>;
1461
+ onRemoteConfig(config: RemoteConfig): void;
1462
+ fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
1463
+ setConfig(config: Partial<LeanbaseConfig>): void;
1464
+ getLibraryId(): string;
1465
+ getLibraryVersion(): string;
1466
+ getCustomUserAgent(): void;
1467
+ getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined;
1468
+ get_property<T = any>(key: string): T | undefined;
1469
+ setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void;
1470
+ calculateEventProperties(eventName: string, eventProperties: PostHogEventProperties, timestamp: Date, uuid: string, readOnly?: boolean): Properties;
1471
+ isIdentified(): boolean;
1472
+ /**
1473
+ * Add additional set_once properties to the event when creating a person profile. This allows us to create the
1474
+ * profile with mostly-accurate properties, despite earlier events not setting them. We do this by storing them in
1475
+ * persistence.
1476
+ * @param dataSetOnce
1477
+ */
1478
+ calculateSetOnceProperties(dataSetOnce?: Properties): Properties | undefined;
1479
+ capture(event: string, properties?: PostHogEventProperties, options?: LeanbasegCaptureOptions): void;
1480
+ identify(distinctId?: string, properties?: PostHogEventProperties, options?: LeanbasegCaptureOptions): void;
1481
+ destroy(): void;
1482
+ }
1483
+
1484
+ export { Leanbase, type LeanbaseConfig as LeanbaseOptions };