Debian Codegraph @

new/packages/terser/src/worker.ts

raw
1 import { isMainThread, parentPort, workerData } from 'worker_threads';
2
3 import { hasOwnProperty, isObject } from 'smob';
4
5 import { minify } from 'terser';
6
7 import { workerPoolWorkerFlag } from './constants';
8
9 import type { WorkerContextSerialized, WorkerOutput } from './type';
10
11 /**
12 * Duck typing worker context.
13 *
14 * @param input
15 */
16 function isWorkerContextSerialized(input: unknown): input is WorkerContextSerialized {
17 return (
18 isObject(input) &&
19 hasOwnProperty(input, 'code') &&
20 typeof input.code === 'string' &&
21 hasOwnProperty(input, 'options') &&
22 typeof input.options === 'string'
23 );
24 }
25
26 export function runWorker() {
27 if (isMainThread || !parentPort || workerData !== workerPoolWorkerFlag) {
28 return;
29 }
30
31 // eslint-disable-next-line no-eval
32 const eval2 = eval;
33
34 parentPort.on('message', async (data: WorkerContextSerialized) => {
35 if (!isWorkerContextSerialized(data)) {
36 return;
37 }
38
39 const options = eval2(`(${data.options})`);
40
41 const result = await minify(data.code, options);
42
43 const output: WorkerOutput = {
44 code: result.code || data.code,
45 nameCache: options.nameCache
46 };
47
48 if (typeof result.map === 'string') {
49 output.sourceMap = JSON.parse(result.map);
50 }
51
52 if (isObject(result.map)) {
53 output.sourceMap = result.map;
54 }
55
56 parentPort?.postMessage(output);
57 });
58 }