All files / nodejs/lib make-synchronous-wrapper.ts

0% Statements 0/17
0% Branches 0/6
0% Functions 0/2
0% Lines 0/17

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 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                                                                                         
import { Buffer } from 'buffer';
import childProcess from 'child_process';
import v8 from 'v8';
import process from 'process';
import Subsume from 'subsume';
 
const HUNDRED_MEGABYTES = 1000 * 1000 * 100;
 
export default function makeSynchronous(function_) {
	return (...arguments_) => {
		const serializedArguments = v8.serialize(arguments_).toString('hex');
		const subsume = new Subsume();
 
		// TODO: Use top-level await here when targeting Node.js 14.
		const input = `
			import v8 from 'node:v8';
			import Subsume from 'subsume';
 
			const subsume = new Subsume('${subsume.id}');
 
			const send = value => {
				const serialized = v8.serialize(value).toString('hex');
				process.stdout.write(subsume.compose(serialized));
			};
 
			(async () => {
				try {
					const arguments_ = v8.deserialize(Buffer.from('${serializedArguments}', 'hex'));
					const result = await (${function_})(...arguments_);
					send({result});
				} catch (error) {
					send({error});
				}
			})();
		`;
 
		const { error: subprocessError, stdout, stderr } = childProcess.spawnSync(process.execPath, ['--input-type=module', '-'], {
			input,
			encoding: 'utf8',
			maxBuffer: HUNDRED_MEGABYTES,
			env: {
				...process.env,
				ELECTRON_RUN_AS_NODE: '1',
			},
		});
 
		if (subprocessError) {
			throw subprocessError;
		}
 
		const { data, rest } = subsume.parse(stdout);
 
		process.stdout.write(rest);
		process.stderr.write(stderr);
 
		if (!data) {
			return;
		}
 
		const { error, result } = v8.deserialize(Buffer.from(data, 'hex'));
 
		if (error) {
			throw error;
		}
 
		return result;
	};
}