Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/core/lib/CoreProcess.ts
1029 views
1
import { ChildProcess, fork } from 'child_process';
2
import ICoreConfigureOptions from '@secret-agent/interfaces/ICoreConfigureOptions';
3
4
const start = require.resolve('../start');
5
6
export default class CoreProcess {
7
private static child: ChildProcess;
8
private static coreHostPromise: Promise<string>;
9
10
public static spawn(options: ICoreConfigureOptions): Promise<string> {
11
this.coreHostPromise ??= new Promise<string>((resolve, reject) => {
12
this.child = fork(start, [JSON.stringify(options)], {
13
detached: false,
14
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
15
env: {
16
SA_TEMPORARY_CORE: 'true',
17
...process.env,
18
},
19
});
20
this.child.once('error', reject);
21
this.child.once('message', message => {
22
resolve(message as string);
23
this.child.disconnect();
24
this.child.off('error', reject);
25
});
26
// now that it's set, if Core shuts down, clear out the host promise
27
this.child.once('exit', () => {
28
this.child.removeAllListeners('message');
29
this.child.removeAllListeners('error');
30
this.coreHostPromise = null;
31
this.child = null;
32
});
33
});
34
return this.coreHostPromise;
35
}
36
37
public static kill(signal?: NodeJS.Signals) {
38
const child = this.child;
39
if (child) {
40
child.unref();
41
const closed = new Promise<void>(resolve => child.once('exit', () => setImmediate(resolve)));
42
if (!child.killed) {
43
child.kill(signal);
44
}
45
return closed;
46
}
47
}
48
}
49
50