• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

thoughtspot / visual-embed-sdk / #2385

07 Sep 2025 05:10PM UTC coverage: 93.936% (+0.03%) from 93.909%
#2385

push

adityamittal3107
update error.ts

1214 of 1377 branches covered (88.16%)

Branch coverage included in aggregate %.

2953 of 3059 relevant lines covered (96.53%)

83.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.69
/src/embed/ts-embed.ts
1
/**
2
 * Copyright (c) 2022
3
 *
4
 * Base classes
5
 * @summary Base classes
6
 * @author Ayon Ghosh <ayon.ghosh@thoughtspot.com>
7
 */
8

9
import isEqual from 'lodash/isEqual';
14✔
10
import isEmpty from 'lodash/isEmpty';
14✔
11
import isObject from 'lodash/isObject';
14✔
12
import {
13
    TriggerPayload,
14
    TriggerResponse,
15
    UIPassthroughArrayResponse,
16
    UIPassthroughEvent,
17
    UIPassthroughRequest,
18
} from './hostEventClient/contracts';
19
import { logger } from '../utils/logger';
14✔
20
import { getAuthenticationToken } from '../authToken';
14✔
21
import { AnswerService } from '../utils/graphql/answerService/answerService';
14✔
22
import {
14✔
23
    getEncodedQueryParamsString,
24
    getCssDimension,
25
    getOffsetTop,
26
    embedEventStatus,
27
    setAttributes,
28
    getCustomisations,
29
    getRuntimeFilters,
30
    getDOMNode,
31
    getFilterQuery,
32
    getQueryParamString,
33
    getRuntimeParameters,
34
    setStyleProperties,
35
    removeStyleProperties,
36
    isUndefined,
37
} from '../utils';
38
import { getCustomActions } from '../utils/custom-actions';
14✔
39
import {
14✔
40
    getThoughtSpotHost,
41
    URL_MAX_LENGTH,
42
    DEFAULT_EMBED_WIDTH,
43
    DEFAULT_EMBED_HEIGHT,
44
    getV2BasePath,
45
} from '../config';
46
import {
14✔
47
    AuthType,
48
    DOMSelector,
49
    HostEvent,
50
    EmbedEvent,
51
    MessageCallback,
52
    Action,
53
    Param,
54
    EmbedConfig,
55
    MessageOptions,
56
    MessageCallbackObj,
57
    ContextMenuTriggerOptions,
58
    DefaultAppInitData,
59
    AllEmbedViewConfig as ViewConfig,
60
} from '../types';
61
import { uploadMixpanelEvent, MIXPANEL_EVENT } from '../mixpanel-service';
14✔
62
import { processEventData, processAuthFailure } from '../utils/processData';
14✔
63
import pkgInfo from '../../package.json';
14✔
64
import {
14✔
65
    getAuthPromise, renderInQueue, handleAuth, notifyAuthFailure,
66
    getInitPromise,
67
    getIsInitCalled,
68
} from './base';
69
import { AuthFailureType } from '../auth';
14✔
70
import { getEmbedConfig } from './embedConfig';
14✔
71
import { ERROR_MESSAGE } from '../errors';
14✔
72
import { getPreauthInfo } from '../utils/sessionInfoService';
14✔
73
import { HostEventClient } from './hostEventClient/host-event-client';
14✔
74

75
const { version } = pkgInfo;
14✔
76

77
/**
78
 * Global prefix for all Thoughtspot postHash Params.
79
 */
80
export const THOUGHTSPOT_PARAM_PREFIX = 'ts-';
14✔
81
const TS_EMBED_ID = '_thoughtspot-embed';
14✔
82

83
/**
84
 * The event id map from v2 event names to v1 event id
85
 * v1 events are the classic embed events implemented in Blink v1
86
 * We cannot rename v1 event types to maintain backward compatibility
87
 * @internal
88
 */
89
const V1EventMap: Record<string, any> = {};
14✔
90

91
/**
92
 * Base class for embedding v2 experience
93
 * Note: the v2 version of ThoughtSpot Blink is built on the new stack:
94
 * React+GraphQL
95
 */
96
export class TsEmbed {
14✔
97
    /**
98
     * The DOM node which was inserted by the SDK to either
99
     * render the iframe or display an error message.
100
     * This is useful for removing the DOM node when the
101
     * embed instance is destroyed.
102
     */
103
    protected insertedDomEl: Node;
104

105
    /**
106
     * The DOM node where the ThoughtSpot app is to be embedded.
107
     */
108
    protected el: HTMLElement;
109

110
    /**
111
     * The key to store the embed instance in the DOM node
112
     */
113
    protected embedNodeKey = '__tsEmbed';
393✔
114

115
    protected isAppInitialized = false;
393✔
116

117
    /**
118
     * A reference to the iframe within which the ThoughtSpot app
119
     * will be rendered.
120
     */
121
    protected iFrame: HTMLIFrameElement;
122

123
    /**
124
     * Setter for the iframe element
125
     * @param {HTMLIFrameElement} iFrame HTMLIFrameElement
126
     */
127
    protected setIframeElement(iFrame: HTMLIFrameElement): void {
128
        this.iFrame = iFrame;
356✔
129
        this.hostEventClient.setIframeElement(iFrame);
356✔
130
    }
131

132
    protected viewConfig: ViewConfig & { visibleTabs?: string[], hiddenTabs?: string[], showAlerts?: boolean };
133

134
    protected embedConfig: EmbedConfig;
135

136
    /**
137
     * The ThoughtSpot hostname or IP address
138
     */
139
    protected thoughtSpotHost: string;
140

141
    /*
142
     * This is the base to access ThoughtSpot V2.
143
     */
144
    protected thoughtSpotV2Base: string;
145

146
    /**
147
     * A map of event handlers for particular message types triggered
148
     * by the embedded app; multiple event handlers can be registered
149
     * against a particular message type.
150
     */
151
    private eventHandlerMap: Map<string, MessageCallbackObj[]>;
152

153
    /**
154
     * A flag that is set to true post render.
155
     */
156
    protected isRendered: boolean;
157

158
    /**
159
     * A flag to mark if an error has occurred.
160
     */
161
    private isError: boolean;
162

163
    /**
164
     * A flag that is set to true post preRender.
165
     */
166
    private isPreRendered: boolean;
167

168
    /**
169
     * Should we encode URL Query Params using base64 encoding which thoughtspot
170
     * will generate for embedding. This provides additional security to
171
     * thoughtspot clusters against Cross site scripting attacks.
172
     * @default false
173
     */
174
    private shouldEncodeUrlQueryParams = false;
393✔
175

176
    private defaultHiddenActions = [Action.ReportError];
393✔
177

178
    private resizeObserver: ResizeObserver;
179

180
    protected hostEventClient: HostEventClient;
181

182
    protected isReadyForRenderPromise;
183

184
    /**
185
     * Handler for fullscreen change events
186
     */
187
    private fullscreenChangeHandler: (() => void) | null = null;
393✔
188

189
    constructor(domSelector: DOMSelector, viewConfig?: ViewConfig) {
190
        this.el = getDOMNode(domSelector);
393✔
191
        this.eventHandlerMap = new Map();
393✔
192
        this.isError = false;
393✔
193
        this.viewConfig = {
393✔
194
            excludeRuntimeFiltersfromURL: false,
195
            excludeRuntimeParametersfromURL: false,
196
            ...viewConfig,
197
        };
198
        this.registerAppInit();
393✔
199
        uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_EMBED_CREATE, {
393✔
200
            ...viewConfig,
201
        });
202
        this.hostEventClient = new HostEventClient(this.iFrame);
393✔
203

204
        this.isReadyForRenderPromise = getInitPromise().then(async () => {
393✔
205
            const embedConfig = getEmbedConfig();
393✔
206
            this.embedConfig = embedConfig;
393✔
207
            if (!embedConfig.authTriggerContainer && !embedConfig.useEventForSAMLPopup) {
393✔
208
                this.embedConfig.authTriggerContainer = domSelector;
74✔
209
            }
210
            this.thoughtSpotHost = getThoughtSpotHost(embedConfig);
393✔
211
            this.thoughtSpotV2Base = getV2BasePath(embedConfig);
393✔
212
            this.shouldEncodeUrlQueryParams = embedConfig.shouldEncodeUrlQueryParams;
393✔
213
        });
214
    }
215

216
    /**
217
     * Throws error encountered during initialization.
218
     */
219
    private throwInitError() {
220
        this.handleError('You need to init the ThoughtSpot SDK module first');
1✔
221
    }
222

223
    /**
224
     * Handles errors within the SDK
225
     * @param error The error message or object
226
     */
227
    protected handleError(error: string | Record<string, unknown>) {
228
        this.isError = true;
10✔
229
        this.executeCallbacks(EmbedEvent.Error, {
10✔
230
            error,
231
        });
232
        // Log error
233
        logger.error(error);
10✔
234
    }
235

236
    /**
237
     * Extracts the type field from the event payload
238
     * @param event The window message event
239
     */
240
    private getEventType(event: MessageEvent) {
241

242
        return event.data?.type || event.data?.__type;
1,797!
243
    }
244

245
    /**
246
     * Extracts the port field from the event payload
247
     * @param event  The window message event
248
     * @returns
249
     */
250
    private getEventPort(event: MessageEvent) {
251
        if (event.ports.length && event.ports[0]) {
1,797✔
252
            return event.ports[0];
1,231✔
253
        }
254
        return null;
566✔
255
    }
256

257
    /**
258
     * Checks if preauth cache is enabled
259
     * from the view config and embed config
260
     * @returns boolean
261
     */
262
    private isPreAuthCacheEnabled() {
263
        // Disable preauth cache when:
264
        // 1. overrideOrgId is present since:
265
        //    - cached auth info would be for wrong org
266
        //    - info call response changes for each different overrideOrgId
267
        // 2. disablePreauthCache is explicitly set to true
268
        // 3. FullAppEmbed has primary navbar visible since:
269
        //    - primary navbar requires fresh auth state for navigation
270
        //    - cached auth may not reflect current user permissions
271
        const isDisabled = (
272
            this.viewConfig.overrideOrgId !== undefined
366✔
273
            || this.embedConfig.disablePreauthCache === true
274
            || this.isFullAppEmbedWithVisiblePrimaryNavbar()
275
        );
276
        return !isDisabled;
366✔
277
    }
278

279
    /**
280
     * Checks if current embed is FullAppEmbed with visible primary navbar
281
     * @returns boolean
282
     */
283
    private isFullAppEmbedWithVisiblePrimaryNavbar(): boolean {
284
        const appViewConfig = this.viewConfig as any;
364✔
285

286
        // Check if this is a FullAppEmbed (AppEmbed)
287
        // showPrimaryNavbar defaults to true if not explicitly set to false
288
        return (
364✔
289
            appViewConfig.embedComponentType === 'AppEmbed'
489✔
290
            && appViewConfig.showPrimaryNavbar === true
291
        );
292
    }
293

294
    /**
295
     * fix for ts7.sep.cl
296
     * will be removed for ts7.oct.cl
297
     * @param event
298
     * @param eventType
299
     * @hidden
300
     */
301
    private formatEventData(event: MessageEvent, eventType: string) {
302
        const eventData = {
1,797✔
303
            ...event.data,
304
            type: eventType,
305
        };
306
        if (!eventData.data) {
1,797✔
307
            eventData.data = event.data.payload;
362✔
308
        }
309
        return eventData;
1,797✔
310
    }
311

312
    private subscribedListeners: Record<string, any> = {};
393✔
313

314
    /**
315
     * Adds a global event listener to window for "message" events.
316
     * ThoughtSpot detects if a particular event is targeted to this
317
     * embed instance through an identifier contained in the payload,
318
     * and executes the registered callbacks accordingly.
319
     */
320
    private subscribeToEvents() {
321
        this.unsubscribeToEvents();
349✔
322
        const messageEventListener = (event: MessageEvent<any>) => {
349✔
323
            const eventType = this.getEventType(event);
1,797✔
324
            const eventPort = this.getEventPort(event);
1,797✔
325
            const eventData = this.formatEventData(event, eventType);
1,797✔
326
            if (event.source === this.iFrame.contentWindow) {
1,797✔
327
                this.executeCallbacks(
62✔
328
                    eventType,
329
                    processEventData(
330
                        eventType,
331
                        eventData,
332
                        this.thoughtSpotHost,
333
                        this.isPreRendered ? this.preRenderWrapper : this.el,
62✔
334
                    ),
335
                    eventPort,
336
                );
337
            }
338
        };
339
        window.addEventListener('message', messageEventListener);
349✔
340

341
        const onlineEventListener = (e: Event) => {
349✔
342
            this.trigger(HostEvent.Reload);
1✔
343
        };
344
        window.addEventListener('online', onlineEventListener);
349✔
345

346
        const offlineEventListener = (e: Event) => {
349✔
347
            const offlineWarning = 'Network not Detected. Embed is offline. Please reconnect and refresh';
×
348
            this.executeCallbacks(EmbedEvent.Error, {
×
349
                offlineWarning,
350
            });
351
            logger.warn(offlineWarning);
×
352
        };
353
        window.addEventListener('offline', offlineEventListener);
349✔
354

355
        this.subscribedListeners = {
349✔
356
            message: messageEventListener,
357
            online: onlineEventListener,
358
            offline: offlineEventListener,
359
        };
360
    }
361

362
    private unsubscribeToEvents() {
363
        Object.keys(this.subscribedListeners).forEach((key) => {
385✔
364
            window.removeEventListener(key, this.subscribedListeners[key]);
78✔
365
        });
366
    }
367

368
    protected async getAuthTokenForCookielessInit() {
369
        let authToken = '';
22✔
370
        if (this.embedConfig.authType !== AuthType.TrustedAuthTokenCookieless) return authToken;
22✔
371

372
        try {
8✔
373
            authToken = await getAuthenticationToken(this.embedConfig);
8✔
374
        } catch (e) {
375
            processAuthFailure(e, this.isPreRendered ? this.preRenderWrapper : this.el);
2✔
376
            throw e;
2✔
377
        }
378

379
        return authToken;
6✔
380
    }
381

382
    protected async getDefaultAppInitData(): Promise<DefaultAppInitData> {
383
        const authToken = await this.getAuthTokenForCookielessInit();
22✔
384
        const customActionsResult = getCustomActions([
20✔
385
            ...(this.viewConfig.customActions || []),
38✔
386
            ...(this.embedConfig.customActions || [])
40✔
387
        ]);
388
        if (customActionsResult.errors.length > 0) {
20✔
389
            this.handleError({
20✔
390
                type: 'CUSTOM_ACTION_VALIDATION',
2✔
391
                message: customActionsResult.errors,
392
            });
393
        }
394
        return {
20!
395
            customisations: getCustomisations(this.embedConfig, this.viewConfig),
×
396
            authToken,
397
            runtimeFilterParams: this.viewConfig.excludeRuntimeFiltersfromURL
398
                ? getRuntimeFilters(this.viewConfig.runtimeFilters)
399
                : null,
400
            runtimeParameterParams: this.viewConfig.excludeRuntimeParametersfromURL
20✔
401
                ? getRuntimeParameters(this.viewConfig.runtimeParameters || [])
402
                : null,
403
            hiddenHomepageModules: this.viewConfig.hiddenHomepageModules || [],
20✔
404
            reorderedHomepageModules: this.viewConfig.reorderedHomepageModules || [],
405
            hostConfig: this.embedConfig.hostConfig,
406
            hiddenHomeLeftNavItems: this.viewConfig?.hiddenHomeLeftNavItems
20✔
407
                ? this.viewConfig?.hiddenHomeLeftNavItems
1!
408
                : [],
409
            customVariablesForThirdPartyTools:
39✔
410
                this.embedConfig.customVariablesForThirdPartyTools || {},
39✔
411
            hiddenListColumns: this.viewConfig.hiddenListColumns || [],
412
            customActions: customActionsResult.actions,
80!
413
        };
3!
414
    }
415

416
    protected async getAppInitData() {
30✔
417
        return this.getDefaultAppInitData();
40✔
418
    }
419

420
    /**
421
     * Send Custom style as part of payload of APP_INIT
422
     * @param _
423
     * @param responder
22✔
424
     */
425
    private appInitCb = async (_: any, responder: any) => {
426
        try {
427
            const appInitData = await this.getAppInitData();
428
            this.isAppInitialized = true;
429
            responder({
430
                type: EmbedEvent.APP_INIT,
431
                data: appInitData,
393✔
432
            });
22✔
433
        } catch (e) {
22✔
434
            logger.error(`AppInit failed, Error : ${e?.message}`);
20✔
435
        }
20✔
436
    };
437

438
    /**
439
     * Sends updated auth token to the iFrame to avoid user logout
440
     * @param _
2!
441
     * @param responder
442
     */
443
    private updateAuthToken = async (_: any, responder: any) => {
444
        const { authType } = this.embedConfig;
445
        let { autoLogin } = this.embedConfig;
446
        // Default autoLogin: true for cookieless if undefined/null, otherwise
447
        // false
448
        autoLogin = autoLogin ?? (authType === AuthType.TrustedAuthTokenCookieless);
449
        if (autoLogin && authType === AuthType.TrustedAuthTokenCookieless) {
393✔
450
            try {
10✔
451
                const authToken = await getAuthenticationToken(this.embedConfig);
10✔
452
                responder({
453
                    type: EmbedEvent.AuthExpire,
454
                    data: { authToken },
10✔
455
                });
10✔
456
            } catch (e) {
5✔
457
                logger.error(`${ERROR_MESSAGE.INVALID_TOKEN_ERROR} Error : ${e?.message}`);
5✔
458
                processAuthFailure(e, this.isPreRendered ? this.preRenderWrapper : this.el);
3✔
459
            }
460
        } else if (autoLogin) {
461
            handleAuth();
462
        }
463
        notifyAuthFailure(AuthFailureType.EXPIRY);
2!
464
    };
2✔
465

466
    /**
5✔
467
     * Auto Login and send updated authToken to the iFrame to avoid user session logout
2✔
468
     * @param _
469
     * @param responder
10✔
470
     */
471
    private idleSessionTimeout = (_: any, responder: any) => {
472
        handleAuth().then(async () => {
473
            let authToken = '';
474
            try {
475
                authToken = await getAuthenticationToken(this.embedConfig);
476
                responder({
477
                    type: EmbedEvent.IdleSessionTimeout,
393✔
478
                    data: { authToken },
3✔
479
                });
3✔
480
            } catch (e) {
3✔
481
                logger.error(`${ERROR_MESSAGE.INVALID_TOKEN_ERROR} Error : ${e?.message}`);
3✔
482
                processAuthFailure(e, this.isPreRendered ? this.preRenderWrapper : this.el);
2✔
483
            }
484
        }).catch((e) => {
485
            logger.error(`Auto Login failed, Error : ${e?.message}`);
486
        });
487
        notifyAuthFailure(AuthFailureType.IDLE_SESSION_TIMEOUT);
1!
488
    };
1!
489

490
    /**
491
     * Register APP_INIT event and sendback init payload
×
492
     */
493
    private registerAppInit = () => {
3✔
494
        this.on(EmbedEvent.APP_INIT, this.appInitCb, { start: false }, true);
495
        this.on(EmbedEvent.AuthExpire, this.updateAuthToken, { start: false }, true);
496
        this.on(EmbedEvent.IdleSessionTimeout, this.idleSessionTimeout, { start: false }, true);
497
        
498
        const embedListenerReadyHandler = this.createEmbedContainerHandler(EmbedEvent.EmbedListenerReady);  
499
        this.on(EmbedEvent.EmbedListenerReady, embedListenerReadyHandler, { start: false }, true);
393✔
500
        
393✔
501
        const authInitHandler = this.createEmbedContainerHandler(EmbedEvent.AuthInit);
393✔
502
        this.on(EmbedEvent.AuthInit, authInitHandler, { start: false }, true);
393✔
503
    };
504

393✔
505
    /**
393✔
506
     * Constructs the base URL string to load the ThoughtSpot app.
507
     * @param query
393✔
508
     */
393✔
509
    protected getEmbedBasePath(query: string): string {
510
        let queryString = query.startsWith('?') ? query : `?${query}`;
511
        if (this.shouldEncodeUrlQueryParams) {
512
            queryString = `?base64UrlEncodedFlags=${getEncodedQueryParamsString(
513
                queryString.substr(1),
514
            )}`;
515
        }
516
        const basePath = [this.thoughtSpotHost, this.thoughtSpotV2Base, queryString]
111✔
517
            .filter((x) => x.length > 0)
111✔
518
            .join('/');
1✔
519

520
        return `${basePath}#`;
521
    }
522

111✔
523
    /**
333✔
524
     * Common query params set for all the embed modes.
525
     * @param queryParams
526
     * @returns queryParams
111✔
527
     */
528
    protected getBaseQueryParams(queryParams: Record<any, any> = {}) {
529
        let hostAppUrl = window?.location?.host || '';
530

531
        // The below check is needed because TS Cloud firewall, blocks
532
        // localhost/127.0.0.1 in any url param.
533
        if (hostAppUrl.includes('localhost') || hostAppUrl.includes('127.0.0.1')) {
534
            hostAppUrl = 'local-host';
125✔
535
        }
357!
536
        const blockNonEmbedFullAppAccess = this.embedConfig.blockNonEmbedFullAppAccess ?? true;
537
        queryParams[Param.EmbedApp] = true;
538
        queryParams[Param.HostAppUrl] = encodeURIComponent(hostAppUrl);
539
        queryParams[Param.ViewPortHeight] = window.innerHeight;
357!
540
        queryParams[Param.ViewPortWidth] = window.innerWidth;
357✔
541
        queryParams[Param.Version] = version;
542
        queryParams[Param.AuthType] = this.embedConfig.authType;
357✔
543
        queryParams[Param.blockNonEmbedFullAppAccess] = blockNonEmbedFullAppAccess;
357✔
544
        queryParams[Param.AutoLogin] = this.embedConfig.autoLogin;
357✔
545
        if (this.embedConfig.disableLoginRedirect === true || this.embedConfig.autoLogin === true) {
357✔
546
            queryParams[Param.DisableLoginRedirect] = true;
357✔
547
        }
357✔
548
        if (this.embedConfig.authType === AuthType.EmbeddedSSO) {
357✔
549
            queryParams[Param.ForceSAMLAutoRedirect] = true;
357✔
550
        }
357✔
551
        if (this.embedConfig.authType === AuthType.TrustedAuthTokenCookieless) {
357✔
552
            queryParams[Param.cookieless] = true;
7✔
553
        }
554
        if (this.embedConfig.pendoTrackingKey) {
357!
555
            queryParams[Param.PendoTrackingKey] = this.embedConfig.pendoTrackingKey;
×
556
        }
557
        if (this.embedConfig.numberFormatLocale) {
357✔
558
            queryParams[Param.NumberFormatLocale] = this.embedConfig.numberFormatLocale;
17✔
559
        }
560
        if (this.embedConfig.dateFormatLocale) {
357✔
561
            queryParams[Param.DateFormatLocale] = this.embedConfig.dateFormatLocale;
1✔
562
        }
563
        if (this.embedConfig.currencyFormat) {
357✔
564
            queryParams[Param.CurrencyFormat] = this.embedConfig.currencyFormat;
13✔
565
        }
566

357✔
567
        const {
13✔
568
            disabledActions,
569
            disabledActionReason,
357✔
570
            hiddenActions,
13✔
571
            visibleActions,
572
            hiddenTabs,
573
            visibleTabs,
574
            showAlerts,
575
            additionalFlags: additionalFlagsFromView,
576
            locale,
577
            customizations,
578
            contextMenuTrigger,
579
            linkOverride,
580
            insertInToSlide,
581
            disableRedirectionLinksInNewTab,
582
            overrideOrgId,
583
            exposeTranslationIDs,
584
            primaryAction,
585
        } = this.viewConfig;
586

587
        const { additionalFlags: additionalFlagsFromInit } = this.embedConfig;
588

589
        const additionalFlags = {
590
            ...additionalFlagsFromInit,
591
            ...additionalFlagsFromView,
357✔
592
        };
593

357✔
594
        if (Array.isArray(visibleActions) && Array.isArray(hiddenActions)) {
595
            this.handleError('You cannot have both hidden actions and visible actions');
357✔
596
            return queryParams;
597
        }
598

599
        if (Array.isArray(visibleTabs) && Array.isArray(hiddenTabs)) {
600
            this.handleError('You cannot have both hidden Tabs and visible Tabs');
357✔
601
            return queryParams;
4✔
602
        }
4✔
603
        if (primaryAction) {
604
            queryParams[Param.PrimaryAction] = primaryAction;
605
        }
353✔
606

4✔
607
        if (disabledActions?.length) {
4✔
608
            queryParams[Param.DisableActions] = disabledActions;
609
        }
349!
610
        if (disabledActionReason) {
×
611
            queryParams[Param.DisableActionReason] = disabledActionReason;
612
        }
613
        if (exposeTranslationIDs) {
349✔
614
            queryParams[Param.ExposeTranslationIDs] = exposeTranslationIDs;
6✔
615
        }
616
        queryParams[Param.HideActions] = [...this.defaultHiddenActions, ...(hiddenActions ?? [])];
349✔
617
        if (Array.isArray(visibleActions)) {
6✔
618
            queryParams[Param.VisibleActions] = visibleActions;
619
        }
349✔
620
        if (Array.isArray(hiddenTabs)) {
1✔
621
            queryParams[Param.HiddenTabs] = hiddenTabs;
622
        }
349✔
623
        if (Array.isArray(visibleTabs)) {
349✔
624
            queryParams[Param.VisibleTabs] = visibleTabs;
5✔
625
        }
626
        /**
349✔
627
         * Default behavior for context menu will be left-click
2✔
628
         *  from version 9.2.0.cl the user have an option to override context
629
         *  menu click
349✔
630
         */
1✔
631
        if (contextMenuTrigger === ContextMenuTriggerOptions.LEFT_CLICK) {
632
            queryParams[Param.ContextMenuTrigger] = 'left';
633
        } else if (contextMenuTrigger === ContextMenuTriggerOptions.RIGHT_CLICK) {
634
            queryParams[Param.ContextMenuTrigger] = 'right';
635
        } else if (contextMenuTrigger === ContextMenuTriggerOptions.BOTH_CLICKS) {
636
            queryParams[Param.ContextMenuTrigger] = 'both';
637
        }
349✔
638

3✔
639
        const embedCustomizations = this.embedConfig.customizations;
346✔
640
        const spriteUrl = customizations?.iconSpriteUrl || embedCustomizations?.iconSpriteUrl;
2✔
641
        if (spriteUrl) {
344✔
642
            queryParams[Param.IconSpriteUrl] = spriteUrl.replace('https://', '');
2✔
643
        }
644

645
        const stringIDsUrl = customizations?.content?.stringIDsUrl
349✔
646
            || embedCustomizations?.content?.stringIDsUrl;
349✔
647
        if (stringIDsUrl) {
349✔
648
            queryParams[Param.StringIDsUrl] = stringIDsUrl;
1✔
649
        }
650

651
        if (showAlerts !== undefined) {
349✔
652
            queryParams[Param.ShowAlerts] = showAlerts;
2,094✔
653
        }
349✔
654
        if (locale !== undefined) {
2✔
655
            queryParams[Param.Locale] = locale;
656
        }
657

349✔
658
        if (linkOverride) {
1✔
659
            queryParams[Param.LinkOverride] = linkOverride;
660
        }
349✔
661
        if (insertInToSlide) {
1✔
662
            queryParams[Param.ShowInsertToSlide] = insertInToSlide;
663
        }
664
        if (disableRedirectionLinksInNewTab) {
349!
665
            queryParams[Param.DisableRedirectionLinksInNewTab] = disableRedirectionLinksInNewTab;
×
666
        }
667
        if (overrideOrgId !== undefined) {
349!
668
            queryParams[Param.OverrideOrgId] = overrideOrgId;
×
669
        }
670

349!
671
        if (this.isPreAuthCacheEnabled()) {
×
672
            queryParams[Param.preAuthCache] = true;
673
        }
349✔
674

3✔
675
        queryParams[Param.OverrideNativeConsole] = true;
676
        queryParams[Param.ClientLogLevel] = this.embedConfig.logLevel;
677

349✔
678
        if (isObject(additionalFlags) && !isEmpty(additionalFlags)) {
340✔
679
            Object.assign(queryParams, additionalFlags);
680
        }
681

349✔
682
        // Do not add any flags below this, as we want additional flags to
349✔
683
        // override other flags
684

349✔
685
        return queryParams;
8✔
686
    }
687

688
    /**
689
     * Constructs the base URL string to load v1 of the ThoughtSpot app.
690
     * This is used for embedding Liveboards, visualizations, and full application.
691
     * @param queryString The query string to append to the URL.
349✔
692
     * @param isAppEmbed A Boolean parameter to specify if you are embedding
693
     * the full application.
694
     */
695
    protected getV1EmbedBasePath(queryString: string): string {
696
        const queryParams = this.shouldEncodeUrlQueryParams
697
            ? `?base64UrlEncodedFlags=${getEncodedQueryParamsString(queryString)}`
698
            : `?${queryString}`;
699
        const host = this.thoughtSpotHost;
700
        const path = `${host}/${queryParams}#`;
701
        return path;
702
    }
246✔
703

704
    protected getEmbedParams() {
705
        const queryParams = this.getBaseQueryParams();
246✔
706
        return getQueryParamString(queryParams);
246✔
707
    }
246✔
708

709
    protected getRootIframeSrc() {
710
        const query = this.getEmbedParams();
711
        return this.getEmbedBasePath(query);
×
712
    }
×
713

714
    protected createIframeEl(frameSrc: string): HTMLIFrameElement {
715
        const iFrame = document.createElement('iframe');
716

88✔
717
        iFrame.src = frameSrc;
88✔
718
        iFrame.id = TS_EMBED_ID;
719
        iFrame.setAttribute('data-ts-iframe', 'true');
720

721
        // according to screenfull.js documentation
337✔
722
        // allowFullscreen, webkitallowfullscreen and mozallowfullscreen must be
723
        // true
337✔
724
        iFrame.allowFullscreen = true;
337✔
725
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
337✔
726
        // @ts-ignore
727
        iFrame.webkitallowfullscreen = true;
728
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
729
        // @ts-ignore
730
        iFrame.mozallowfullscreen = true;
337✔
731
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
732
        // @ts-ignore
733
        iFrame.allow = 'clipboard-read; clipboard-write; fullscreen;';
337✔
734

735
        const frameParams = this.viewConfig.frameParams;
736
        const { height: frameHeight, width: frameWidth, ...restParams } = frameParams || {};
337✔
737
        const width = getCssDimension(frameWidth || DEFAULT_EMBED_WIDTH);
738
        const height = getCssDimension(frameHeight || DEFAULT_EMBED_HEIGHT);
739
        setAttributes(iFrame, restParams);
337✔
740

741
        iFrame.style.width = `${width}`;
337✔
742
        iFrame.style.height = `${height}`;
337✔
743
        // Set minimum height to the frame so that,
337✔
744
        // scaling down on the fullheight doesn't make it too small.
337✔
745
        iFrame.style.minHeight = `${height}`;
337✔
746
        iFrame.style.border = '0';
747
        iFrame.name = 'ThoughtSpot Embedded Analytics';
337✔
748
        return iFrame;
337✔
749
    }
750

751
    protected handleInsertionIntoDOM(child: string | Node): void {
337✔
752
        if (this.isPreRendered) {
337✔
753
            this.insertIntoDOMForPreRender(child);
337✔
754
        } else {
337✔
755
            this.insertIntoDOM(child);
756
        }
757
        if (this.insertedDomEl instanceof Node) {
758
            (this.insertedDomEl as any)[this.embedNodeKey] = this;
348✔
759
        }
10✔
760
    }
761

338✔
762
    /**
763
     * Renders the embedded ThoughtSpot app in an iframe and sets up
348✔
764
     * event listeners.
346✔
765
     * @param url - The URL of the embedded ThoughtSpot app.
766
     */
767
    protected async renderIFrame(url: string): Promise<any> {
768
        if (this.isError) {
769
            return null;
770
        }
771
        if (!this.thoughtSpotHost) {
772
            this.throwInitError();
773
        }
774
        if (url.length > URL_MAX_LENGTH) {
356✔
775
            // warn: The URL is too long
8✔
776
        }
777

348✔
778
        return renderInQueue((nextInQueue) => {
1✔
779
            const initTimestamp = Date.now();
780

348!
781
            this.executeCallbacks(EmbedEvent.Init, {
782
                data: {
783
                    timestamp: initTimestamp,
784
                },
348✔
785
                type: EmbedEvent.Init,
348✔
786
            });
787

348✔
788
            uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_RENDER_START);
789

790
            return getAuthPromise()
791
                ?.then((isLoggedIn: boolean) => {
792
                    if (!isLoggedIn) {
793
                        this.handleInsertionIntoDOM(this.embedConfig.loginFailedMessage);
794
                        return;
348✔
795
                    }
796

348!
797
                    this.setIframeElement(this.iFrame || this.createIframeEl(url));
798
                    this.iFrame.addEventListener('load', () => {
347✔
799
                        nextInQueue();
3✔
800
                        const loadTimestamp = Date.now();
3✔
801
                        this.executeCallbacks(EmbedEvent.Load, {
802
                            data: {
803
                                timestamp: loadTimestamp,
344✔
804
                            },
344✔
805
                            type: EmbedEvent.Load,
17✔
806
                        });
17✔
807
                        uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_RENDER_COMPLETE, {
17✔
808
                            elWidth: this.iFrame.clientWidth,
809
                            elHeight: this.iFrame.clientHeight,
810
                            timeTookToLoad: loadTimestamp - initTimestamp,
811
                        });
812
                        // Send info event  if preauth cache is enabled
813
                        if (this.isPreAuthCacheEnabled()) {
17✔
814
                            getPreauthInfo().then((data) => {
815
                                if (data?.info) {
816
                                    this.trigger(HostEvent.InfoSuccess, data);
817
                                }
818
                            });
819
                        }
17✔
820

13✔
821
                        // Setup fullscreen change handler after iframe is
13✔
822
                        // loaded and ready
5✔
823
                        this.setupFullscreenChangeHandler();
824
                    });
825
                    this.iFrame.addEventListener('error', () => {
826
                        nextInQueue();
827
                    });
828
                    this.handleInsertionIntoDOM(this.iFrame);
829
                    const prefetchIframe = document.querySelectorAll('.prefetchIframe');
17✔
830
                    if (prefetchIframe.length) {
831
                        prefetchIframe.forEach((el) => {
344✔
832
                            el.remove();
1✔
833
                        });
834
                    }
344✔
835
                    this.subscribeToEvents();
344✔
836
                })
344!
837
                .catch((error) => {
×
838
                    nextInQueue();
×
839
                    uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_RENDER_FAILED, {
840
                        error: JSON.stringify(error),
841
                    });
344✔
842
                    this.handleInsertionIntoDOM(this.embedConfig.loginFailedMessage);
843
                    this.handleError(error);
844
                });
1✔
845
        });
1✔
846
    }
847

848
    protected createPreRenderWrapper(): HTMLDivElement {
1✔
849
        const preRenderIds = this.getPreRenderIds();
1✔
850

851
        document.getElementById(preRenderIds.wrapper)?.remove();
852

853
        const preRenderWrapper = document.createElement('div');
854
        preRenderWrapper.id = preRenderIds.wrapper;
855
        const initialPreRenderWrapperStyle = {
10✔
856
            position: 'absolute',
857
            width: '100vw',
10!
858
            height: '100vh',
859
        };
10✔
860
        setStyleProperties(preRenderWrapper, initialPreRenderWrapperStyle);
10✔
861

10✔
862
        return preRenderWrapper;
863
    }
864

865
    protected preRenderWrapper: HTMLElement;
866

10✔
867
    protected preRenderChild: HTMLElement;
868

10✔
869
    protected connectPreRendered(): boolean {
870
        const preRenderIds = this.getPreRenderIds();
871
        const preRenderWrapperElement = document.getElementById(preRenderIds.wrapper);
872
        this.preRenderWrapper = this.preRenderWrapper || preRenderWrapperElement;
873

874
        this.preRenderChild = this.preRenderChild || document.getElementById(preRenderIds.child);
875

876
        if (this.preRenderWrapper && this.preRenderChild) {
4✔
877
            this.isPreRendered = true;
4✔
878
            if (this.preRenderChild instanceof HTMLIFrameElement) {
4✔
879
                this.setIframeElement(this.preRenderChild);
880
            }
4✔
881
            this.insertedDomEl = this.preRenderWrapper;
882
            this.isRendered = true;
4✔
883
        }
3✔
884

3✔
885
        return this.isPreRenderAvailable();
3✔
886
    }
887

3✔
888
    protected isPreRenderAvailable(): boolean {
3✔
889
        return (
890
            this.isRendered
891
            && this.isPreRendered
4✔
892
            && Boolean(this.preRenderWrapper && this.preRenderChild)
893
        );
894
    }
895

27✔
896
    protected createPreRenderChild(child: string | Node): HTMLElement {
67✔
897
        const preRenderIds = this.getPreRenderIds();
898

40✔
899
        document.getElementById(preRenderIds.child)?.remove();
900

901
        if (child instanceof HTMLElement) {
902
            child.id = preRenderIds.child;
903
            return child;
10✔
904
        }
905

10!
906
        const divChildNode = document.createElement('div');
907
        setStyleProperties(divChildNode, { width: '100%', height: '100%' });
10✔
908
        divChildNode.id = preRenderIds.child;
9✔
909

9✔
910
        if (typeof child === 'string') {
911
            divChildNode.innerHTML = child;
912
        } else {
1✔
913
            divChildNode.appendChild(child);
1✔
914
        }
1✔
915

916
        return divChildNode;
1!
917
    }
1✔
918

919
    protected insertIntoDOMForPreRender(child: string | Node): void {
×
920
        const preRenderChild = this.createPreRenderChild(child);
921
        const preRenderWrapper = this.createPreRenderWrapper();
922
        preRenderWrapper.appendChild(preRenderChild);
1✔
923

924
        this.preRenderChild = preRenderChild;
925
        this.preRenderWrapper = preRenderWrapper;
926

10✔
927
        if (preRenderChild instanceof HTMLIFrameElement) {
10✔
928
            this.setIframeElement(preRenderChild);
10✔
929
        }
930
        this.insertedDomEl = preRenderWrapper;
10✔
931

10✔
932
        if (this.showPreRenderByDefault) {
933
            this.showPreRender();
10✔
934
        } else {
9✔
935
            this.hidePreRender();
936
        }
10✔
937

938
        document.body.appendChild(preRenderWrapper);
10✔
939
    }
1✔
940

941
    private showPreRenderByDefault = false;
9✔
942

943
    protected insertIntoDOM(child: string | Node): void {
944
        if (this.viewConfig.insertAsSibling) {
10✔
945
            if (typeof child === 'string') {
946
                const div = document.createElement('div');
947
                div.innerHTML = child;
393✔
948
                div.id = TS_EMBED_ID;
949

950
                child = div;
338✔
951
            }
12✔
952
            if (this.el.nextElementSibling?.id === TS_EMBED_ID) {
1✔
953
                this.el.nextElementSibling.remove();
1✔
954
            }
1✔
955
            this.el.parentElement.insertBefore(child, this.el.nextSibling);
956
            this.insertedDomEl = child;
1✔
957
        } else if (typeof child === 'string') {
958
            this.el.innerHTML = child;
12✔
959
            this.insertedDomEl = this.el.children[0];
1✔
960
        } else {
961
            this.el.innerHTML = '';
12✔
962
            this.el.appendChild(child);
12✔
963
            this.insertedDomEl = child;
326✔
964
        }
2✔
965
    }
2✔
966

967
    /**
324✔
968
     * Sets the height of the iframe
324✔
969
     * @param height The height in pixels
324✔
970
     */
971
    protected setIFrameHeight(height: number | string): void {
972
        this.iFrame.style.height = getCssDimension(height);
973
    }
974

975
    /**
976
     * Executes all registered event handlers for a particular event type
977
     * @param eventType The event type
978
     * @param data The payload invoked with the event handler
2✔
979
     * @param eventPort The event Port for a specific MessageChannel
980
     */
981
    protected executeCallbacks(
982
        eventType: EmbedEvent,
983
        data: any,
984
        eventPort?: MessagePort | void,
985
    ): void {
986
        const eventHandlers = this.eventHandlerMap.get(eventType) || [];
987
        const allHandlers = this.eventHandlerMap.get(EmbedEvent.ALL) || [];
988
        const callbacks = [...eventHandlers, ...allHandlers];
989
        const dataStatus = data?.status || embedEventStatus.END;
990
        callbacks.forEach((callbackObj) => {
991
            if (
992
                // When start status is true it trigger only start releated
438✔
993
                // payload
438✔
994
                (callbackObj.options.start && dataStatus === embedEventStatus.START)
438✔
995
                // When start status is false it trigger only end releated
438!
996
                // payload
438✔
997
                || (!callbackObj.options.start && dataStatus === embedEventStatus.END)
60✔
998
            ) {
999
                callbackObj.callback(data, (payload) => {
1000
                    this.triggerEventOnPort(eventPort, payload);
179✔
1001
                });
1002
            }
1003
        });
1004
    }
1005

59✔
1006
    /**
29✔
1007
     * Returns the ThoughtSpot hostname or IP address.
1008
     */
1009
    protected getThoughtSpotHost(): string {
1010
        return this.thoughtSpotHost;
1011
    }
1012

1013
    /**
1014
     * Gets the v1 event type (if applicable) for the EmbedEvent type
1015
     * @param eventType The v2 event type
1016
     * @returns The corresponding v1 event type if one exists
×
1017
     * or else the v2 event type itself
1018
     */
1019
    protected getCompatibleEventType(eventType: EmbedEvent): EmbedEvent {
1020
        return V1EventMap[eventType] || eventType;
1021
    }
1022

1023
    /**
1024
     * Calculates the iframe center for the current visible viewPort
1025
     * of iframe using Scroll position of Host App, offsetTop for iframe
1026
     * in Host app. ViewPort height of the tab.
1,406✔
1027
     * @returns iframe Center in visible viewport,
1028
     *  Iframe height,
1029
     *  View port height.
1030
     */
1031
    protected getIframeCenter() {
1032
        const offsetTopClient = getOffsetTop(this.iFrame);
1033
        const scrollTopClient = window.scrollY;
1034
        const viewPortHeight = window.innerHeight;
1035
        const iframeHeight = this.iFrame.offsetHeight;
1036
        const iframeScrolled = scrollTopClient - offsetTopClient;
1037
        let iframeVisibleViewPort;
1038
        let iframeOffset;
4✔
1039

4✔
1040
        if (iframeScrolled < 0) {
4✔
1041
            iframeVisibleViewPort = viewPortHeight - (offsetTopClient - scrollTopClient);
4✔
1042
            iframeVisibleViewPort = Math.min(iframeHeight, iframeVisibleViewPort);
4✔
1043
            iframeOffset = 0;
1044
        } else {
1045
            iframeVisibleViewPort = Math.min(iframeHeight - iframeScrolled, viewPortHeight);
1046
            iframeOffset = iframeScrolled;
4!
1047
        }
×
1048
        const iframeCenter = iframeOffset + iframeVisibleViewPort / 2;
×
1049
        return {
×
1050
            iframeCenter,
1051
            iframeScrolled,
4✔
1052
            iframeHeight,
4✔
1053
            viewPortHeight,
1054
            iframeVisibleViewPort,
4✔
1055
        };
4✔
1056
    }
1057

1058
    /**
1059
     * Registers an event listener to trigger an alert when the ThoughtSpot app
1060
     * sends an event of a particular message type to the host application.
1061
     * @param messageType The message type
1062
     * @param callback A callback as a function
1063
     * @param options The message options
1064
     * @param isSelf
1065
     * @param isRegisteredBySDK
1066
     * @example
1067
     * ```js
1068
     * tsEmbed.on(EmbedEvent.Error, (data) => {
1069
     *   console.error(data);
1070
     * });
1071
     * ```
1072
     * @example
1073
     * ```js
1074
     * tsEmbed.on(EmbedEvent.Save, (data) => {
1075
     *   console.log("Answer save clicked", data);
1076
     * }, {
1077
     *   start: true // This will trigger the callback on start of save
1078
     * });
1079
     * ```
1080
     */
1081
    public on(
1082
        messageType: EmbedEvent,
1083
        callback: MessageCallback,
1084
        options: MessageOptions = { start: false },
1085
        isRegisteredBySDK = false,
1086
    ): typeof TsEmbed.prototype {
1087
        uploadMixpanelEvent(`${MIXPANEL_EVENT.VISUAL_SDK_ON}-${messageType}`, {
1088
            isRegisteredBySDK,
1089
        });
1090
        if (this.isRendered) {
14✔
1091
            logger.warn('Please register event handlers before calling render');
1,422✔
1092
        }
1093
        const callbacks = this.eventHandlerMap.get(messageType) || [];
2,072✔
1094
        callbacks.push({ options, callback });
1095
        this.eventHandlerMap.set(messageType, callbacks);
1096
        return this;
2,072✔
1097
    }
2✔
1098

1099
    /**
2,072✔
1100
     * Removes an event listener for a particular event type.
2,072✔
1101
     * @param messageType The message type
2,072✔
1102
     * @param callback The callback to remove
2,072✔
1103
     * @example
1104
     * ```js
1105
     * const errorHandler = (data) => { console.error(data); };
1106
     * tsEmbed.on(EmbedEvent.Error, errorHandler);
1107
     * tsEmbed.off(EmbedEvent.Error, errorHandler);
1108
     * ```
1109
     */
1110
    public off(messageType: EmbedEvent, callback: MessageCallback): typeof TsEmbed.prototype {
1111
        const callbacks = this.eventHandlerMap.get(messageType) || [];
1112
        const index = callbacks.findIndex((cb) => cb.callback === callback);
1113
        if (index > -1) {
1114
            callbacks.splice(index, 1);
1115
        }
1116
        return this;
1117
    }
1!
1118

1✔
1119
    /**
1✔
1120
     * Triggers an event on specific Port registered against
1✔
1121
     * for the EmbedEvent
1122
     * @param eventType The message type
1✔
1123
     * @param data The payload to send
1124
     * @param eventPort
1125
     * @param payload
1126
     */
1127
    private triggerEventOnPort(eventPort: MessagePort | void, payload: any) {
1128
        if (eventPort) {
1129
            try {
1130
                eventPort.postMessage({
1131
                    type: payload.type,
1132
                    data: payload.data,
1133
                });
1134
            } catch (e) {
29✔
1135
                eventPort.postMessage({ error: e });
25✔
1136
                logger.log(e);
25✔
1137
            }
1138
        } else {
1139
            logger.log('Event Port is not defined');
1140
        }
1141
    }
×
1142

×
1143
    /**
1144
     * @hidden
1145
     * Internal state to track if the embed container is loaded.
4✔
1146
     * This is used to trigger events after the embed container is loaded.
1147
     */
1148
    public isEmbedContainerLoaded = false;
1149

1150
    /**
1151
     * @hidden
1152
     * Internal state to track the callbacks to be executed after the embed container 
1153
     * is loaded.
1154
     * This is used to trigger events after the embed container is loaded.
393✔
1155
     */
1156
    private embedContainerReadyCallbacks: Array<() => void> = [];
1157

1158
    protected getPreRenderObj<T extends TsEmbed>(): T {
1159
        const embedObj = (this.insertedDomEl as any)?.[this.embedNodeKey] as T;
1160
        if (embedObj === (this as any)) {
1161
            logger.info('embedObj is same as this');
1162
        }
393✔
1163
        return embedObj;
1164
    }
1165

26✔
1166
    private checkEmbedContainerLoaded() {
26✔
1167
        if (this.isEmbedContainerLoaded) return true;
5✔
1168

1169
        const preRenderObj = this.getPreRenderObj<TsEmbed>();
26✔
1170
        if (preRenderObj && preRenderObj.isEmbedContainerLoaded) {
1171
            this.isEmbedContainerLoaded = true;
1172
        }
1173

24✔
1174
        return this.isEmbedContainerLoaded;
1175
    }
19✔
1176
    private executeEmbedContainerReadyCallbacks() {
19✔
1177
        logger.debug('executePendingEvents', this.embedContainerReadyCallbacks);
2✔
1178
        this.embedContainerReadyCallbacks.forEach((callback) => {
1179
            callback?.();
1180
        });
19✔
1181
        this.embedContainerReadyCallbacks = [];
1182
    }
1183

12✔
1184
    /**
12✔
1185
     * Executes a callback after the embed container is loaded.
11!
1186
     * @param callback The callback to execute
1187
     */
12✔
1188
    protected executeAfterEmbedContainerLoaded(callback: () => void) {
1189
        if (this.checkEmbedContainerLoaded()) {
1190
            callback?.();
1191
        } else {
1192
            logger.debug('pushing callback to embedContainerReadyCallbacks', callback);
1193
            this.embedContainerReadyCallbacks.push(callback);
1194
          }
1195
    }
23✔
1196

6!
1197
    protected createEmbedContainerHandler = (source: EmbedEvent.AuthInit | EmbedEvent.EmbedListenerReady) => () => {
1198
        const processEmbedContainerReady = () => {
17✔
1199
            logger.debug('processEmbedContainerReady');
17✔
1200
            this.isEmbedContainerLoaded = true;
1201
            this.executeEmbedContainerReadyCallbacks();
1202
        }
1203
        if (source === EmbedEvent.AuthInit) {
788✔
1204
            const AUTH_INIT_FALLBACK_DELAY = 1000;
8✔
1205
            // Wait for 1 second to ensure the embed container is loaded
7✔
1206
            // This is a workaround to ensure the embed container is loaded
7✔
1207
            // this is needed until all clusters have EmbedListenerReady event
7✔
1208
            setTimeout(processEmbedContainerReady, AUTH_INIT_FALLBACK_DELAY);
1209
        } else if (source === EmbedEvent.EmbedListenerReady) {
8✔
1210
            processEmbedContainerReady();
5✔
1211
        }
1212
    }
1213

1214
    /**
5✔
1215
     * Triggers an event to the embedded app
3✔
1216
     * @param {HostEvent} messageType The event type
3✔
1217
     * @param {any} data The payload to send with the message
1218
     * @returns A promise that resolves with the response from the embedded app
1219
     */
1220
    public async trigger<HostEventT extends HostEvent, PayloadT>(
1221
        messageType: HostEventT,
1222
        data: TriggerPayload<PayloadT, HostEventT> = {} as any,
1223
    ): Promise<TriggerResponse<PayloadT, HostEventT>> {
1224
        uploadMixpanelEvent(`${MIXPANEL_EVENT.VISUAL_SDK_TRIGGER}-${messageType}`);
1225

1226
        if (!this.isRendered) {
1227
            this.handleError('Please call render before triggering events');
1228
            return null;
1✔
1229
        }
1230

27✔
1231
        if (!messageType) {
1232
            this.handleError('Host event type is undefined');
27!
1233
            return null;
×
1234
        }
×
1235
        // send an empty object, this is needed for liveboard default handlers
1236
        return this.hostEventClient.triggerHostEvent(messageType, data);
1237
    }
27!
1238

×
1239
    /**
×
1240
     * Triggers an event to the embedded app, skipping the UI flow.
1241
     * @param {UIPassthroughEvent} apiName - The name of the API to be triggered.
1242
     * @param {UIPassthroughRequest} parameters - The parameters to be passed to the API.
27✔
1243
     * @returns {Promise<UIPassthroughRequest>} - A promise that resolves with the response
1244
     * from the embedded app.
1245
     */
1246
    public async triggerUIPassThrough<UIPassthroughEventT extends UIPassthroughEvent>(
1247
        apiName: UIPassthroughEventT,
1248
        parameters: UIPassthroughRequest<UIPassthroughEventT>,
1249
    ): Promise<UIPassthroughArrayResponse<UIPassthroughEventT>> {
1250
        const response = this.hostEventClient.triggerUIPassthroughApi(apiName, parameters);
1251
        return response;
1252
    }
1253

1254
    /**
1255
     * Marks the ThoughtSpot object to have been rendered
1256
     * Needs to be overridden by subclasses to do the actual
1✔
1257
     * rendering of the iframe.
1✔
1258
     * @param args
1259
     */
1260
    public async render(): Promise<TsEmbed> {
1261
        if (!getIsInitCalled()) {
1262
            logger.error(ERROR_MESSAGE.RENDER_CALLED_BEFORE_INIT);
1263
        }
1264
        await this.isReadyForRenderPromise;
1265
        this.isRendered = true;
1266

1267
        return this;
352✔
1268
    }
2✔
1269

1270
    public getIframeSrc(): string {
352✔
1271
        return '';
352✔
1272
    }
1273

352✔
1274
    protected handleRenderForPrerender() {
1275
        return this.render();
1276
    }
1277

×
1278
    /**
1279
     * Creates the preRender shell
1280
     * @param showPreRenderByDefault - Show the preRender after render, hidden by default
1281
     */
7✔
1282
    public async preRender(showPreRenderByDefault = false): Promise<TsEmbed> {
1283
        if (!this.viewConfig.preRenderId) {
1284
            logger.error(ERROR_MESSAGE.PRERENDER_ID_MISSING);
1285
            return this;
1286
        }
1287
        this.isPreRendered = true;
1288
        this.showPreRenderByDefault = showPreRenderByDefault;
10✔
1289
        return this.handleRenderForPrerender();
11✔
1290
    }
1✔
1291

1✔
1292
    /**
1293
     * Get the Post Url Params for THOUGHTSPOT from the current
10✔
1294
     * host app URL.
10✔
1295
     * THOUGHTSPOT URL params starts with a prefix "ts-"
10✔
1296
     * @version SDK: 1.14.0 | ThoughtSpot: 8.4.0.cl, 8.4.1-sw
1297
     */
1298
    public getThoughtSpotPostUrlParams(
1299
        additionalParams: { [key: string]: string | number } = {},
1300
    ): string {
1301
        const urlHash = window.location.hash;
1302
        const queryParams = window.location.search;
1303
        const postHashParams = urlHash.split('?');
1304
        const postURLParams = postHashParams[postHashParams.length - 1];
1305
        const queryParamsObj = new URLSearchParams(queryParams);
338✔
1306
        const postURLParamsObj = new URLSearchParams(postURLParams);
1307
        const params = new URLSearchParams();
357✔
1308

357✔
1309
        const addKeyValuePairCb = (value: string, key: string): void => {
357✔
1310
            if (key.startsWith(THOUGHTSPOT_PARAM_PREFIX)) {
357✔
1311
                params.append(key, value);
357✔
1312
            }
357✔
1313
        };
357✔
1314
        queryParamsObj.forEach(addKeyValuePairCb);
1315
        postURLParamsObj.forEach(addKeyValuePairCb);
357✔
1316
        Object.entries(additionalParams).forEach(([k, v]) => params.append(k, v as string));
8✔
1317

5✔
1318
        let tsParams = params.toString();
1319
        tsParams = tsParams ? `?${tsParams}` : '';
1320

357✔
1321
        return tsParams;
357✔
1322
    }
357✔
1323

1324
    /**
357✔
1325
     * Destroys the ThoughtSpot embed, and remove any nodes from the DOM.
357✔
1326
     * @version SDK: 1.19.1 | ThoughtSpot: *
1327
     */
357✔
1328
    public destroy(): void {
1329
        try {
1330
            this.removeFullscreenChangeHandler();
1331
            this.insertedDomEl?.parentNode.removeChild(this.insertedDomEl);
1332
            this.unsubscribeToEvents();
1333
        } catch (e) {
1334
            logger.log('Error destroying TS Embed', e);
1335
        }
26✔
1336
    }
26✔
1337

26✔
1338
    public getUnderlyingFrameElement(): HTMLIFrameElement {
26✔
1339
        return this.iFrame;
1340
    }
×
1341

1342
    /**
1343
     * Prerenders a generic instance of the TS component.
1344
     * This means without the path but with the flags already applied.
1345
     * This is useful for prerendering the component in the background.
1✔
1346
     * @version SDK: 1.22.0
1347
     * @returns
1348
     */
1349
    public async prerenderGeneric(): Promise<any> {
1350
        if (!getIsInitCalled()) {
1351
            logger.error(ERROR_MESSAGE.RENDER_CALLED_BEFORE_INIT);
1352
        }
1353
        await this.isReadyForRenderPromise;
1354

1355
        const prerenderFrameSrc = this.getRootIframeSrc();
1356
        this.isRendered = true;
6✔
1357
        return this.renderIFrame(prerenderFrameSrc);
1✔
1358
    }
1359

6✔
1360
    protected beforePrerenderVisible(): void {
1361
        // Override in subclass
6✔
1362
    }
6✔
1363

6✔
1364
    private validatePreRenderViewConfig = (viewConfig: ViewConfig) => {
1365
        const preRenderAllowedKeys = ['preRenderId', 'vizId', 'liveboardId'];
1366
        const preRenderedObject = (this.insertedDomEl as any)?.[this.embedNodeKey] as TsEmbed;
1367
        if (!preRenderedObject) return;
1368
        if (viewConfig.preRenderId) {
1369
            const allOtherKeys = Object.keys(viewConfig).filter(
1370
                (key) => !preRenderAllowedKeys.includes(key) && !key.startsWith('on'),
393✔
1371
            );
3✔
1372

3!
1373
            allOtherKeys.forEach((key: keyof ViewConfig) => {
3!
1374
                if (
3✔
1375
                    !isUndefined(viewConfig[key])
3✔
1376
                    && !isEqual(viewConfig[key], preRenderedObject.viewConfig[key])
18✔
1377
                ) {
1378
                    logger.warn(
1379
                        `${viewConfig.embedComponentType || 'Component'} was pre-rendered with `
3✔
1380
                        + `"${key}" as "${JSON.stringify(preRenderedObject.viewConfig[key])}" `
10✔
1381
                        + `but a different value "${JSON.stringify(viewConfig[key])}" `
20✔
1382
                        + 'was passed to the Embed component. '
1383
                        + 'The new value provided is ignored, the value provided during '
1384
                        + 'preRender is used.',
4✔
1385
                    );
4!
1386
                }
1387
            });
1388
        }
1389
    };
1390

1391
    /**
1392
     * Displays the PreRender component.
1393
     * If the component is not preRendered, it attempts to create and render it.
1394
     * Also, synchronizes the style of the PreRender component with the embedding
1395
     * element.
1396
     */
1397
    public async showPreRender(): Promise<TsEmbed> {
1398
        if (!this.viewConfig.preRenderId) {
1399
            logger.error(ERROR_MESSAGE.PRERENDER_ID_MISSING);
1400
            return this;
1401
        }
1402
        if (!this.isPreRenderAvailable()) {
1403
            const isAvailable = this.connectPreRendered();
1404

7✔
1405
            if (!isAvailable) {
1✔
1406
                // if the Embed component is not preRendered , Render it now and
1✔
1407
                return this.preRender(true);
1408
            }
6✔
1409
            this.validatePreRenderViewConfig(this.viewConfig);
4✔
1410
        }
1411

4✔
1412
        if (this.el) {
1413
            this.syncPreRenderStyle();
1✔
1414
            if (!this.viewConfig.doNotTrackPreRenderSize) {
1415
                this.resizeObserver = new ResizeObserver((entries) => {
3✔
1416
                    entries.forEach((entry) => {
1417
                        if (entry.contentRect && entry.target === this.el) {
1418
                            setStyleProperties(this.preRenderWrapper, {
5✔
1419
                                width: `${entry.contentRect.width}px`,
5✔
1420
                                height: `${entry.contentRect.height}px`,
5✔
1421
                            });
5✔
1422
                        }
1✔
1423
                    });
1✔
1424
                });
1✔
1425
                this.resizeObserver.observe(this.el);
1426
            }
1427
        }
1428

1429
        this.beforePrerenderVisible();
1430

1431
        removeStyleProperties(this.preRenderWrapper, ['z-index', 'opacity', 'pointer-events']);
5✔
1432

1433
        this.subscribeToEvents();
1434

1435
        // Setup fullscreen change handler for prerendered components
5✔
1436
        if (this.iFrame) {
1437
            this.setupFullscreenChangeHandler();
5✔
1438
        }
1439

5✔
1440
        return this;
1441
    }
1442

5✔
1443
    /**
5✔
1444
     * Synchronizes the style properties of the PreRender component with the embedding
1445
     * element. This function adjusts the position, width, and height of the PreRender
1446
     * component
5✔
1447
     * to match the dimensions and position of the embedding element.
1448
     * @throws {Error} Throws an error if the embedding element (passed as domSelector)
1449
     * is not defined or not found.
1450
     */
1451
    public syncPreRenderStyle(): void {
1452
        if (!this.isPreRenderAvailable() || !this.el) {
1453
            logger.error(ERROR_MESSAGE.SYNC_STYLE_CALLED_BEFORE_RENDER);
1454
            return;
1455
        }
1456
        const elBoundingClient = this.el.getBoundingClientRect();
1457

1458
        setStyleProperties(this.preRenderWrapper, {
6✔
1459
            top: `${elBoundingClient.y + window.scrollY}px`,
1✔
1460
            left: `${elBoundingClient.x + window.scrollX}px`,
1✔
1461
            width: `${elBoundingClient.width}px`,
1462
            height: `${elBoundingClient.height}px`,
5✔
1463
        });
1464
    }
5✔
1465

1466
    /**
1467
     * Hides the PreRender component if it is available.
1468
     * If the component is not preRendered, it issues a warning.
1469
     */
1470
    public hidePreRender(): void {
1471
        if (!this.isPreRenderAvailable()) {
1472
            // if the embed component is not preRendered , nothing to hide
1473
            logger.warn('PreRender should be called before hiding it using hidePreRender.');
1474
            return;
1475
        }
1476
        const preRenderHideStyles = {
1477
            opacity: '0',
11✔
1478
            pointerEvents: 'none',
1479
            zIndex: '-1000',
1✔
1480
            position: 'absolute ',
1✔
1481
        };
1482
        setStyleProperties(this.preRenderWrapper, preRenderHideStyles);
10✔
1483

1484
        if (this.resizeObserver) {
1485
            this.resizeObserver.disconnect();
1486
        }
1487

1488
        this.unsubscribeToEvents();
10✔
1489
    }
1490

10✔
1491
    /**
1✔
1492
     * Retrieves unique HTML element IDs for PreRender-related elements.
1493
     * These IDs are constructed based on the provided 'preRenderId' from 'viewConfig'.
1494
     * @returns {object} An object containing the IDs for the PreRender elements.
10✔
1495
     * @property {string} wrapper - The HTML element ID for the PreRender wrapper.
1496
     * @property {string} child - The HTML element ID for the PreRender child.
1497
     */
1498
    public getPreRenderIds() {
1499
        return {
1500
            wrapper: `tsEmbed-pre-render-wrapper-${this.viewConfig.preRenderId}`,
1501
            child: `tsEmbed-pre-render-child-${this.viewConfig.preRenderId}`,
1502
        };
1503
    }
1504

1505
    /**
33✔
1506
     * Returns the answerService which can be used to make arbitrary graphql calls on top
1507
     * session.
1508
     * @param vizId [Optional] to get for a specific viz in case of a Liveboard.
1509
     * @version SDK: 1.25.0 / ThoughtSpot 9.10.0
1510
     */
1511
    public async getAnswerService(vizId?: string): Promise<AnswerService> {
1512
        const { session } = await this.trigger(HostEvent.GetAnswerSession, vizId ? { vizId } : {});
1513
        return new AnswerService(session, null, this.embedConfig.thoughtSpotHost);
1514
    }
1515

1516
    /**
1517
     * Set up fullscreen change detection to automatically trigger ExitPresentMode
1518
     * when user exits fullscreen mode
1!
1519
     */
1✔
1520
    private setupFullscreenChangeHandler() {
1521
        const embedConfig = getEmbedConfig();
1522
        const disableFullscreenPresentation = embedConfig?.disableFullscreenPresentation ?? true;
1523

1524
        if (disableFullscreenPresentation) {
1525
            return;
1526
        }
1527

24✔
1528
        if (this.fullscreenChangeHandler) {
24!
1529
            document.removeEventListener('fullscreenchange', this.fullscreenChangeHandler);
1530
        }
24✔
1531

23✔
1532
        this.fullscreenChangeHandler = () => {
1533
            const isFullscreen = !!document.fullscreenElement;
1534
            if (!isFullscreen) {
1!
1535
                logger.info('Exited fullscreen mode - triggering ExitPresentMode');
×
1536
                // Only trigger if iframe is available and contentWindow is
1537
                // accessible
1538
                if (this.iFrame && this.iFrame.contentWindow) {
1✔
1539
                    this.trigger(HostEvent.ExitPresentMode);
×
1540
                } else {
×
1541
                    logger.debug('Skipping ExitPresentMode - iframe contentWindow not available');
×
1542
                }
1543
            }
1544
        };
×
1545

×
1546
        document.addEventListener('fullscreenchange', this.fullscreenChangeHandler);
1547
    }
×
1548

1549
    /**
1550
     * Remove fullscreen change handler
1551
     */
1552
    private removeFullscreenChangeHandler() {
1✔
1553
        if (this.fullscreenChangeHandler) {
1554
            document.removeEventListener('fullscreenchange', this.fullscreenChangeHandler);
1555
            this.fullscreenChangeHandler = null;
1556
        }
1557
    }
1558
}
1559

27!
1560
/**
×
1561
 * Base class for embedding v1 experience
×
1562
 * Note: The v1 version of ThoughtSpot Blink works on the AngularJS stack
1563
 * which is currently under migration to v2
1564
 * @inheritdoc
1565
 */
1566
export class V1Embed extends TsEmbed {
1567
    protected viewConfig: ViewConfig;
1568

1569
    constructor(domSelector: DOMSelector, viewConfig: ViewConfig) {
1570
        super(domSelector, viewConfig);
1571
        this.viewConfig = { excludeRuntimeFiltersfromURL: false, ...viewConfig };
1572
    }
14✔
1573

1574
    /**
1575
     * Render the app in an iframe and set up event handlers
1576
     * @param iframeSrc
263✔
1577
     */
263✔
1578
    protected renderV1Embed(iframeSrc: string): Promise<any> {
1579
        return this.renderIFrame(iframeSrc);
1580
    }
1581

1582
    protected getRootIframeSrc(): string {
1583
        const queryParams = this.getEmbedParams();
1584
        let queryString = queryParams;
1585

240✔
1586
        if (!this.viewConfig.excludeRuntimeParametersfromURL) {
1587
            const runtimeParameters = this.viewConfig.runtimeParameters;
1588
            const parameterQuery = getRuntimeParameters(runtimeParameters || []);
1589
            queryString = [parameterQuery, queryParams].filter(Boolean).join('&');
247✔
1590
        }
247✔
1591

1592
        if (!this.viewConfig.excludeRuntimeFiltersfromURL) {
247✔
1593
            const runtimeFilters = this.viewConfig.runtimeFilters;
246✔
1594

246✔
1595
            const filterQuery = getFilterQuery(runtimeFilters || []);
246✔
1596
            queryString = [filterQuery, queryString].filter(Boolean).join('&');
1597
        }
1598
        return this.viewConfig.enableV2Shell_experimental
247✔
1599
            ? this.getEmbedBasePath(queryString)
245✔
1600
            : this.getV1EmbedBasePath(queryString);
1601
    }
245✔
1602

245✔
1603
    /**
1604
     * @inheritdoc
247✔
1605
     * @example
1606
     * ```js
1607
     * tsEmbed.on(EmbedEvent.Error, (data) => {
1608
     *   console.error(data);
1609
     * });
1610
     * ```
1611
     * @example
1612
     * ```js
1613
     * tsEmbed.on(EmbedEvent.Save, (data) => {
1614
     *   console.log("Answer save clicked", data);
1615
     * }, {
1616
     *   start: true // This will trigger the callback on start of save
1617
     * });
1618
     * ```
1619
     */
1620
    public on(
1621
        messageType: EmbedEvent,
1622
        callback: MessageCallback,
1623
        options: MessageOptions = { start: false },
1624
    ): typeof TsEmbed.prototype {
1625
        const eventType = this.getCompatibleEventType(messageType);
1626
        return super.on(eventType, callback, options);
1627
    }
1628

1629
    /**
126✔
1630
     * Only for testing purposes.
1631
     * @hidden
1,406✔
1632
     */
1,406✔
1633

1634
    public test__executeCallbacks = this.executeCallbacks;
1635
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc