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

thoughtspot / visual-embed-sdk / #2933

07 Dec 2025 03:47AM UTC coverage: 94.303% (-0.01%) from 94.315%
#2933

Pull #372

shivam-kumar-ts
SCAL-273450 Refactor defaultHeight handling to prioritize minimumHeight in LiveboardEmbed
Pull Request #372: SCAL-273450 Added minimumHeight property to LiveboardViewConfig and updated defaultHeight handling

1350 of 1518 branches covered (88.93%)

Branch coverage included in aggregate %.

3 of 3 new or added lines in 2 files covered. (100.0%)

20 existing lines in 3 files now uncovered.

3169 of 3274 relevant lines covered (96.79%)

102.81 hits per line

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

93.12
/src/embed/base.ts
1
/* eslint-disable camelcase */
2
/* eslint-disable import/no-mutable-exports */
3
/**
4
 * Copyright (c) 2022
5
 *
6
 * Base classes
7
 * @summary Base classes
8
 * @author Ayon Ghosh <ayon.ghosh@thoughtspot.com>
9
 */
10
import EventEmitter from 'eventemitter3';
16✔
11
import { registerReportingObserver } from '../utils/reporting';
16✔
12
import { logger, setGlobalLogLevelOverride } from '../utils/logger';
16✔
13
import { tokenizedFetch } from '../tokenizedFetch';
16✔
14
import { EndPoints } from '../utils/authService/authService';
16✔
15
import { getThoughtSpotHost } from '../config';
16✔
16
import {
16✔
17
    AuthType, EmbedConfig, LogLevel, Param, PrefetchFeatures,
18
} from '../types';
19
import {
16✔
20
    authenticate,
21
    logout as _logout,
22
    AuthFailureType,
23
    AuthStatus,
24
    AuthEvent,
25
    notifyAuthFailure,
26
    notifyAuthSDKSuccess,
27
    notifyAuthSuccess,
28
    notifyLogout,
29
    setAuthEE,
30
    AuthEventEmitter,
31
    postLoginService,
32
} from '../auth';
33
import '../utils/with-resolvers-polyfill';
16✔
34
import { uploadMixpanelEvent, MIXPANEL_EVENT } from '../mixpanel-service';
16✔
35
import { getEmbedConfig, setEmbedConfig } from './embedConfig';
16✔
36
import { getQueryParamString, getValueFromWindow, storeValueInWindow } from '../utils';
16✔
37
import { resetAllCachedServices } from '../utils/resetServices';
16✔
38

39
const CONFIG_DEFAULTS: Partial<EmbedConfig> = {
16✔
40
    loginFailedMessage: 'Not logged in',
41
    authTriggerText: 'Authorize',
42
    authType: AuthType.None,
43
    logLevel: LogLevel.ERROR,
44
    waitForCleanupOnDestroy: false,
45
    cleanupTimeout: 5000,
46
};
47

48
export interface executeTMLInput {
49
    metadata_tmls: string[];
50
    import_policy?: 'PARTIAL' | 'ALL_OR_NONE' | 'VALIDATE_ONLY';
51
    create_new?: boolean;
52
}
53

54
export interface exportTMLInput {
55
    metadata: {
56
        identifier: string;
57
        type?: 'LIVEBOARD' | 'ANSWER' | 'LOGICAL_TABLE' | 'CONNECTION';
58
    }[];
59
    export_associated?: boolean;
60
    export_fqn?: boolean;
61
    edoc_format?: 'YAML' | 'JSON';
62
}
63

64
export let authPromise: Promise<boolean>;
65

66
export const getAuthPromise = (): Promise<boolean> => authPromise;
408✔
67

68
export {
69
    notifyAuthFailure, notifyAuthSDKSuccess, notifyAuthSuccess, notifyLogout,
24✔
70
};
71

72
/**
73
 * Perform authentication on the ThoughtSpot app as applicable.
74
 */
75
export const handleAuth = (): Promise<boolean> => {
16✔
76
    authPromise = authenticate(getEmbedConfig());
75✔
77
    authPromise.then(
75✔
78
        (isLoggedIn) => {
79
            if (!isLoggedIn) {
74✔
80
                notifyAuthFailure(AuthFailureType.SDK);
7✔
81
            } else {
82
                // Post login service is called after successful login.
83
                postLoginService();
67✔
84
                notifyAuthSDKSuccess();
67✔
85
            }
86
        },
87
        () => {
88
            notifyAuthFailure(AuthFailureType.SDK);
1✔
89
        },
90
    );
91
    return authPromise;
75✔
92
};
93

94
const hostUrlToFeatureUrl = {
16✔
95
    [PrefetchFeatures.SearchEmbed]: (url: string, flags: string) => `${url}v2/?${flags}#/embed/answer`,
2✔
96
    [PrefetchFeatures.LiveboardEmbed]: (url: string, flags: string) => `${url}?${flags}`,
2✔
97
    [PrefetchFeatures.FullApp]: (url: string, flags: string) => `${url}?${flags}`,
2✔
UNCOV
98
    [PrefetchFeatures.VizEmbed]: (url: string, flags: string) => `${url}?${flags}`,
×
99
};
100

101
/**
102
 * Prefetches static resources from the specified URL. Web browsers can then cache the
103
 * prefetched resources and serve them from the user's local disk to provide faster access
104
 * to your app.
105
 * @param url The URL provided for prefetch
106
 * @param prefetchFeatures Specify features which needs to be prefetched.
107
 * @param additionalFlags This can be used to add any URL flag.
108
 * @version SDK: 1.4.0 | ThoughtSpot: ts7.sep.cl, 7.2.1
109
 * @group Global methods
110
 */
111
export const prefetch = (
16✔
112
    url?: string,
113
    prefetchFeatures?: PrefetchFeatures[],
114
    additionalFlags?: { [key: string]: string | number | boolean },
115
): void => {
116
    if (url === '') {
5✔
117
        // eslint-disable-next-line no-console
118
        logger.warn('The prefetch method does not have a valid URL');
1✔
119
    } else {
120
        const features = prefetchFeatures || [PrefetchFeatures.FullApp];
4✔
121
        let hostUrl = url || getEmbedConfig().thoughtSpotHost;
4!
122
        const prefetchFlags = {
4✔
123
            [Param.EmbedApp]: true,
124
            ...getEmbedConfig()?.additionalFlags,
12!
125
            ...additionalFlags,
126
        };
127
        hostUrl = hostUrl[hostUrl.length - 1] === '/' ? hostUrl : `${hostUrl}/`;
4✔
128
        Array.from(
4✔
129
            new Set(features
130
                .map((feature) => hostUrlToFeatureUrl[feature](
6✔
131
                    hostUrl,
132
                    getQueryParamString(prefetchFlags),
133
                ))),
134
        )
135
            .forEach(
136
                (prefetchUrl, index) => {
137
                    const iFrame = document.createElement('iframe');
6✔
138
                    iFrame.src = prefetchUrl;
6✔
139
                    iFrame.style.width = '0';
6✔
140
                    iFrame.style.height = '0';
6✔
141
                    iFrame.style.border = '0';
6✔
142

143
                    // Make it 'fixed' to keep it in a different stacking context.
144
                    //   This should solve the focus behaviours inside the iframe from
145
                    //   interfering with main body.
146
                    iFrame.style.position = 'fixed';
6✔
147
                    // Push it out of viewport.
148
                    iFrame.style.top = '100vh';
6✔
149
                    iFrame.style.left = '100vw';
6✔
150

151
                    iFrame.classList.add('prefetchIframe');
6✔
152
                    iFrame.classList.add(`prefetchIframeNum-${index}`);
6✔
153
                    document.body.appendChild(iFrame);
6✔
154
                },
155
            );
156
    }
157
};
158

159
/**
160
 *
161
 * @param embedConfig
162
 */
163
function sanity(embedConfig: EmbedConfig) {
164
    if (embedConfig.thoughtSpotHost === undefined) {
117✔
165
        throw new Error('ThoughtSpot host not provided');
2✔
166
    }
167
    if (embedConfig.authType === AuthType.TrustedAuthToken) {
115✔
168
        if (!embedConfig.authEndpoint && typeof embedConfig.getAuthToken !== 'function') {
3✔
169
            throw new Error('Trusted auth should provide either authEndpoint or getAuthToken');
2✔
170
        }
171
    }
172
}
173

174
/**
175
 *
176
 * @param embedConfig
177
 */
178
function backwardCompat(embedConfig: EmbedConfig): EmbedConfig {
179
    const newConfig = { ...embedConfig };
108✔
180
    if (embedConfig.noRedirect !== undefined && embedConfig.inPopup === undefined) {
108✔
181
        newConfig.inPopup = embedConfig.noRedirect;
1✔
182
    }
183
    return newConfig;
108✔
184
}
185

186
type InitFlagStore = {
187
  initPromise: Promise<ReturnType<typeof init>>;
188
  isInitCalled: boolean;
189
  initPromiseResolve: (value: ReturnType<typeof init>) => void;
190
}
191
const initFlagKey = 'initFlagKey';
16✔
192

193
export const createAndSetInitPromise = (): void => {
16✔
194
    const {
195
        promise: initPromise,
196
        resolve: initPromiseResolve,
197
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
198
        // @ts-ignore
199
    } = Promise.withResolvers<AuthEventEmitter>();
19✔
200
    const initFlagStore: InitFlagStore = {
19✔
201
        initPromise,
202
        isInitCalled: false,
203
        initPromiseResolve,
204
    };
205
    storeValueInWindow(initFlagKey, initFlagStore, {
19✔
206
        // In case of diff imports the promise might be already set
207
        ignoreIfAlreadyExists: true,
208
    });
209
};
210

211
createAndSetInitPromise();
16✔
212

213
export const getInitPromise = ():
16✔
214
    Promise<
215
      ReturnType<typeof init>
216
    > => getValueFromWindow<InitFlagStore>(initFlagKey)?.initPromise;
445!
217

218
export const getIsInitCalled = (): boolean => !!getValueFromWindow(initFlagKey)?.isInitCalled;
410!
219

220
/**
221
 * Initializes the Visual Embed SDK globally and perform
222
 * authentication if applicable. This function needs to be called before any ThoughtSpot
223
 * component like Liveboard etc can be embedded. But need not wait for AuthEvent.SUCCESS
224
 * to actually embed. That is handled internally.
225
 * @param embedConfig The configuration object containing ThoughtSpot host,
226
 * authentication mechanism and so on.
227
 * @example
228
 * ```js
229
 *   const authStatus = init({
230
 *     thoughtSpotHost: 'https://my.thoughtspot.cloud',
231
 *     authType: AuthType.None,
232
 *   });
233
 *   authStatus.on(AuthStatus.FAILURE, (reason) => { // do something here });
234
 * ```
235
 * @returns {@link AuthEventEmitter} event emitter which emits events on authentication success,
236
 *      failure and logout. See {@link AuthStatus}
237
 * @version SDK: 1.0.0 | ThoughtSpot ts7.april.cl, 7.2.1
238
 * @group Authentication / Init
239
 */
240
export const init = (embedConfig: EmbedConfig): AuthEventEmitter => {
16✔
241
    sanity(embedConfig);
111✔
242
    resetAllCachedServices();
108✔
243
    embedConfig = setEmbedConfig(
108✔
244
        backwardCompat({
245
            ...CONFIG_DEFAULTS,
246
            ...embedConfig,
247
            thoughtSpotHost: getThoughtSpotHost(embedConfig),
248
        }),
249
    );
250

251
    setGlobalLogLevelOverride(embedConfig.logLevel);
108✔
252
    registerReportingObserver();
108✔
253

254
    const authEE = new EventEmitter<AuthStatus | AuthEvent>();
108✔
255
    setAuthEE(authEE);
108✔
256
    handleAuth();
108✔
257

258
    const { password, ...configToTrack } = getEmbedConfig();
108✔
259
    uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_CALLED_INIT, {
108✔
260
        ...configToTrack,
261
        usedCustomizationSheet: embedConfig.customizations?.style?.customCSSUrl != null,
648✔
262
        usedCustomizationVariables: embedConfig.customizations?.style?.customCSS?.variables != null,
972✔
263
        usedCustomizationRules:
264
            embedConfig.customizations?.style?.customCSS?.rules_UNSTABLE != null,
972✔
265
        usedCustomizationStrings: !!embedConfig.customizations?.content?.strings,
648✔
266
        usedCustomizationIconSprite: !!embedConfig.customizations?.iconSpriteUrl,
324✔
267
    });
268

269
    if (getEmbedConfig().callPrefetch) {
108✔
270
        prefetch(getEmbedConfig().thoughtSpotHost);
2✔
271
    }
272

273
    // Resolves the promise created in the initPromiseKey
274
    getValueFromWindow<InitFlagStore>(initFlagKey).initPromiseResolve(authEE);
108✔
275
    getValueFromWindow<InitFlagStore>(initFlagKey).isInitCalled = true;
108✔
276

277
    return authEE as AuthEventEmitter;
108✔
278
};
279

280
/**
281
 *
282
 */
283
export function disableAutoLogin(): void {
16✔
284
    getEmbedConfig().autoLogin = false;
3✔
285
}
286

287
/**
288
 * Logs out from ThoughtSpot. This also sets the autoLogin flag to false, to
289
 * prevent the SDK from automatically logging in again.
290
 *
291
 * You can call the `init` method again to re login, if autoLogin is set to
292
 * true in this second call it will be honored.
293
 * @param doNotDisableAutoLogin This flag when passed will not disable autoLogin
294
 * @returns Promise which resolves when logout completes.
295
 * @version SDK: 1.10.1 | ThoughtSpot: 8.2.0.cl, 8.4.1-sw
296
 * @group Global methods
297
 */
298
export const logout = (doNotDisableAutoLogin = false): Promise<boolean> => {
16✔
299
    if (!doNotDisableAutoLogin) {
2✔
300
        disableAutoLogin();
2✔
301
    }
302
    return _logout(getEmbedConfig()).then((isLoggedIn) => {
2✔
303
        notifyLogout();
2✔
304
        return isLoggedIn;
2✔
305
    });
306
};
307

308
let renderQueue: Promise<any> = Promise.resolve();
16✔
309

310
/**
311
 * Renders functions in a queue, resolves to next function only after the callback next
312
 * is called
313
 * @param fn The function being registered
314
 */
315
export const renderInQueue = (fn: (next?: (val?: any) => void) => Promise<any>): Promise<any> => {
16✔
316
    const { queueMultiRenders = false } = getEmbedConfig();
400✔
317
    if (queueMultiRenders) {
400!
UNCOV
318
        renderQueue = renderQueue.then(() => new Promise((res) => fn(res)));
×
319
        return renderQueue;
×
320
    }
321
    // Sending an empty function to keep it consistent with the above usage.
322
    return fn(() => {}); // eslint-disable-line @typescript-eslint/no-empty-function
400✔
323
};
324

325
/**
326
 * Imports TML representation of the metadata objects into ThoughtSpot.
327
 * @param data
328
 * @returns imports TML data into ThoughtSpot
329
 * @example
330
 * ```js
331
 *  executeTML({
332
 * //Array of metadata Tmls in string format
333
 *      metadata_tmls: [
334
 *          "'\''{\"guid\":\"9bd202f5-d431-44bf-9a07-b4f7be372125\",
335
 *          \"liveboard\":{\"name\":\"Parameters Liveboard\"}}'\''"
336
 *      ],
337
 *      import_policy: 'PARTIAL', // Specifies the import policy for the TML import.
338
 *      create_new: false, // If selected, creates TML objects with new GUIDs.
339
 *  }).then(result => {
340
 *      console.log(result);
341
 *  }).catch(error => {
342
 *      console.error(error);
343
 *  });
344
 *```
345
 * @version SDK: 1.23.0 | ThoughtSpot: 9.4.0.cl
346
 * @group Global methods
347
 */
348
export const executeTML = async (data: executeTMLInput): Promise<any> => {
16✔
349
    try {
4✔
350
        sanity(getEmbedConfig());
4✔
351
    } catch (err) {
352
        return Promise.reject(err);
1✔
353
    }
354

355
    const { thoughtSpotHost, authType } = getEmbedConfig();
3✔
356
    const headers: Record<string, string | undefined> = {
3✔
357
        'Content-Type': 'application/json',
358
        'x-requested-by': 'ThoughtSpot',
359
    };
360

361
    const payload = {
3✔
362
        metadata_tmls: data.metadata_tmls,
363
        import_policy: data.import_policy || 'PARTIAL',
3!
364
        create_new: data.create_new || false,
6✔
365
    };
366
    return tokenizedFetch(`${thoughtSpotHost}${EndPoints.EXECUTE_TML}`, {
3✔
367
        method: 'POST',
368
        headers,
369
        body: JSON.stringify(payload),
370
        credentials: 'include',
371
    })
372
        .then((response) => {
373
            if (!response.ok) {
2!
UNCOV
374
                throw new Error(
×
375
                    `Failed to import TML data: ${response.status} - ${response.statusText}`,
376
                );
377
            }
378
            return response.json();
2✔
379
        })
380
        .catch((error) => {
381
            throw error;
1✔
382
        });
383
};
384

385
/**
386
 * Exports TML representation of the metadata objects from ThoughtSpot in JSON or YAML
387
 * format.
388
 * @param data
389
 * @returns exports TML data
390
 * @example
391
 * ```js
392
 * exportTML({
393
 *   metadata: [
394
 *     {
395
 *       type: "LIVEBOARD", //Metadata Type
396
 *       identifier: "9bd202f5-d431-44bf-9a07-b4f7be372125" //Metadata Id
397
 *     }
398
 *   ],
399
 *   export_associated: false,//indicates whether to export associated metadata objects
400
 *   export_fqn: false, //Adds FQNs of the referenced objects.For example, if you are
401
 *                      //exporting a Liveboard and its associated objects, the API
402
 *                      //returns the Liveboard TML data with the FQNs of the referenced
403
 *                      //worksheet. If the exported TML data includes FQNs, you don't need
404
 *                      //to manually add FQNs of the referenced objects during TML import.
405
 *   edoc_format: "JSON" //It takes JSON or YAML value
406
 * }).then(result => {
407
 *   console.log(result);
408
 * }).catch(error => {
409
 *   console.error(error);
410
 * });
411
 * ```
412
 * @version SDK: 1.23.0 | ThoughtSpot: 9.4.0.cl
413
 * @group Global methods
414
 */
415
export const exportTML = async (data: exportTMLInput): Promise<any> => {
16✔
416
    const { thoughtSpotHost, authType } = getEmbedConfig();
2✔
417
    try {
2✔
418
        sanity(getEmbedConfig());
2✔
419
    } catch (err) {
UNCOV
420
        return Promise.reject(err);
×
421
    }
422
    const payload = {
2✔
423
        metadata: data.metadata,
424
        export_associated: data.export_associated || false,
4✔
425
        export_fqn: data.export_fqn || false,
4✔
426
        edoc_format: data.edoc_format || 'YAML',
2!
427
    };
428

429
    const headers: Record<string, string | undefined> = {
2✔
430
        'Content-Type': 'application/json',
431
        'x-requested-by': 'ThoughtSpot',
432
    };
433

434
    return tokenizedFetch(`${thoughtSpotHost}${EndPoints.EXPORT_TML}`, {
2✔
435
        method: 'POST',
436
        headers,
437
        body: JSON.stringify(payload),
438
        credentials: 'include',
439
    })
440
        .then((response) => {
441
            if (!response.ok) {
1!
UNCOV
442
                throw new Error(
×
443
                    `Failed to export TML: ${response.status} - ${response.statusText}`,
444
                );
445
            }
446
            return response.json();
1✔
447
        })
448
        .catch((error) => {
449
            throw error;
1✔
450
        });
451
};
452

453
// For testing purposes only
454
/**
455
 *
456
 */
457
export function reset(): void {
16✔
458
    setEmbedConfig({} as any);
10✔
459
    setAuthEE(null);
10✔
460
    authPromise = null;
10✔
461
}
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