UNPKG

video-ad-sdk

Version:

VAST/VPAID SDK that allows video ads to be played on top of any player

58 lines (57 loc) 2.37 kB
import { trackError, ErrorCode } from '../tracker'; import { createVideoAdContainer } from '../adContainer'; import { startVideoAd } from './helpers/startVideoAd'; /** * Will try to start video ad in the passed {@link VastChain} and return the started VideoAdUnit. * If there is an error starting the ad or it times out (by throw I mean that it will reject promise with the error). * * @param vastChain The {@link VastChain} with all the {@link VastResponse}s. * @param placeholder Element that will contain the video ad. * @param options - Options Map. * @returns The video ad unit. */ export const run = async (vastChain, placeholder, options) => { let videoAdContainer; try { const { timeout } = options; videoAdContainer = createVideoAdContainer(placeholder, options.videoElement); let adUnitPromise = startVideoAd(vastChain, videoAdContainer, options); if (typeof timeout === 'number') { let timedOut = false; let timeoutId; const timeoutPromise = new Promise((_resolve, reject) => { timeoutId = window.setTimeout(() => { const { tracker } = options; trackError(vastChain, { errorCode: ErrorCode.VAST_MEDIA_LOAD_TIMEOUT, tracker }); timedOut = true; reject(new Error('Timeout while starting the ad')); }, options.timeout); }); const waitAdUnit = async () => { const newAdUnit = await adUnitPromise; if (timedOut) { if (newAdUnit.isStarted()) { newAdUnit.cancel(); } } else { clearTimeout(timeoutId); } return newAdUnit; }; adUnitPromise = Promise.race([waitAdUnit(), timeoutPromise]); } const adUnit = await adUnitPromise; adUnit.onFinish(() => { videoAdContainer === null || videoAdContainer === void 0 ? void 0 : videoAdContainer.destroy(); }); return adUnit; } catch (error) { videoAdContainer === null || videoAdContainer === void 0 ? void 0 : videoAdContainer.destroy(); throw error; } };