-
Notifications
You must be signed in to change notification settings - Fork 122
/
wrap.js
executable file
·65 lines (53 loc) · 2.18 KB
/
wrap.js
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
const { dirname, extname } = require('path');
const childProcess = require('child_process');
const { sync: resolve } = require('resolve');
const { getConfig } = require('./cfg');
const hook = require('./hook');
const { relay, send } = require('./ipc');
const resolveMain = require('./resolve-main');
const script = process.argv[1];
const { extensions, fork, vm } = getConfig(script);
if (process.env.NODE_DEV_PRELOAD) {
require(process.env.NODE_DEV_PRELOAD);
}
require('./suppress-experimental');
// We want to exit on SIGTERM, but defer to existing SIGTERM handlers.
process.once('SIGTERM', () => process.listenerCount('SIGTERM') || process.exit(0));
if (fork) {
// Overwrite child_process.fork() so that we can hook into forked processes
// too. We also need to relay messages about required files to the parent.
const originalFork = childProcess.fork;
childProcess.fork = (modulePath, args, options) => {
const child = originalFork(modulePath, args, options);
relay(child);
return child;
};
}
// Error handler that displays a notification and logs the stack to stderr:
process.on('uncaughtException', err => {
// Sometimes uncaught exceptions are not errors
const { message, name, stack } =
err instanceof Error ? err : new Error(`uncaughtException ${err}`);
console.error(stack);
// If there's a custom uncaughtException handler expect it to terminate
// the process.
const willTerminate = process.listenerCount('uncaughtException') > 1;
send({ error: name, message, willTerminate });
});
// Hook into require() and notify the parent process about required files
hook(vm, required => send({ required }));
// Check if a module is registered for this extension
const main = resolveMain(script);
const ext = extname(main).slice(1);
const mod = extensions[ext];
const basedir = dirname(main);
// Support extensions where 'require' returns a function that accepts options
if (typeof mod === 'object' && mod.name) {
const fn = require(resolve(mod.name, { basedir }));
if (typeof fn === 'function' && mod.options) {
// require returned a function, call it with options
fn(mod.options);
}
} else if (typeof mod === 'string') {
require(resolve(mod, { basedir }));
}