import {RequestHandler} from 'express'; import * as polyfillLibrary from 'polyfill-library'; import {DefaultConfig, Logger, WaitForSync} from '.'; import {spawn, Thread, Worker} from 'threads'; import {WorkerFunction} from 'threads/dist/types/worker'; export type PolyfillFeatureList = { [featureName: string]: { flags?: string[] } }; export type PolyfillOptions = { minify: boolean, unknown: 'polyfill'|'ignore', features: PolyfillFeatureList, excludes: string[], uaString: string, rum: boolean, } function getRouter(fileToWatch: string, opts?: Partial): RequestHandler { const features = new WaitForSync(); (async () => { const worker = await spawn(new Worker('./polyfill-worker')); const feats = await worker(fileToWatch) as PolyfillFeatureList; await Thread.terminate(worker); return feats; })() .then(feats => { feats['fetch'] = {}; Logger.debug('Polyfill analysed:', Object.keys(feats)); features.setData(feats); }) .catch(err => features.setError(err)); const options: Partial = { minify: DefaultConfig.isProduction, unknown: 'polyfill', ...opts, }; return async (req, res) => { const polyfillBundle = await polyfillLibrary.getPolyfillString({ ...options, uaString: req.header('user-agent'), features: await features.resolve(), stream: false, }); res.setHeader('Content-Type', 'text/javascript'); res.send(polyfillBundle); }; } export const Polyfill = { getRouter: getRouter, };