All files / src login.ts

13.04% Statements 3/23
54.54% Branches 6/11
20% Functions 1/5
13.04% Lines 3/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5720x   1x   2x                                                                                                        
import {UserInterfaceTranslateOptions} from '@wharfkit/session'
import {WAXCloudWalletLoginResponse} from './types'
import {isValidEvent, registerCloseListener} from './utils'
 
export async function popupLogin(
    t: (key: string, options?: UserInterfaceTranslateOptions) => string,
    urlString: URL | string,
    timeout = 300000
): Promise<WAXCloudWalletLoginResponse> {
    // Open the popup window
    const url = new URL(urlString)
    const popup = await window.open(url, 'WalletPluginCloudWalletPopup', 'height=800,width=600')
    Iif (!popup) {
        throw new Error(
            t('error.popup', {
                default:
                    'Unable to open the popup window. Check your browser settings and try again.',
            })
        )
    }
    // Return a promise that either times out or resolves when the popup resolves
    return new Promise<WAXCloudWalletLoginResponse>((resolve, reject) => {
        const closeListener = registerCloseListener(t, popup, reject)
        // Event handler awaiting response from the Cloud Wallet
        const handleEvent = (event: MessageEvent) => {
            Iif (!isValidEvent(event, url, popup)) {
                return
            }
            try {
                resolve(event.data)
            } catch (e) {
                reject(e)
            } finally {
                window.removeEventListener('message', handleEvent)
                clearTimeout(autoCancel)
                clearInterval(closeListener)
            }
        }
        // Automatically cancel request after 5 minutes to cleanup windows/promises
        const autoCancel = setTimeout(() => {
            popup.close()
            window.removeEventListener('message', handleEvent)
            reject(
                new Error(
                    t('error.timeout', {
                        default:
                            'The request has timed out after {{timeout}} seconds. Please try again.',
                        timeout: timeout / 1000,
                    })
                )
            )
        }, timeout)
        // Add event listener awaiting Cloud Wallet Response
        window.addEventListener('message', handleEvent)
    })
}