Debian Codegraph @

process-on-spawn/index.js

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 'use strict';
2
3 /* Drop this dependency once node.js 12 is required. */
•4 const fromEntries = Object.fromEntries;
5
6 const state = getState(1);
7
8 function getState(version) {
9 const stateId = Symbol.for('process-on-spawn@*:singletonId');
10
11 /* istanbul ignore next: cannot cover this once nyc depends on this module */
12 if (stateId in global === false) {
13 /* Hopefully version and unwrap forward compatibility is never actually needed */
14 Object.defineProperty(global, stateId, {
15 writable: true,
16 value: {
17 version,
18 listeners: [],
19 unwrap: wrapSpawnFunctions()
20 }
21 });
22 }
23
24 return global[stateId];
25 }
26
27 function wrappedSpawnFunction(fn) {
28 return function (options) {
29 let env = fromEntries(
30 options.envPairs.map(nvp => nvp.split(/^([^=]*)=/).slice(1))
31 );
32
33 const opts = Object.create(null, {
34 env: {
35 enumerable: true,
36 get() {
37 return env;
38 },
39 set(value) {
40 if (!value || typeof value !== 'object') {
41 throw new TypeError('env must be an object');
42 }
43
44 env = value;
45 }
46 },
47 cwd: {
48 enumerable: true,
49 get() {
50 return options.cwd || process.cwd();
51 }
52 }
53 });
54
55 const args = [...options.args];
56 Object.freeze(args);
57 Object.assign(opts, {
58 execPath: options.file,
59 args,
60 detached: Boolean(options.detached),
61 uid: options.uid,
62 gid: options.gid,
63 windowsVerbatimArguments: Boolean(options.windowsVerbatimArguments),
64 windowsHide: Boolean(options.windowsHide)
65 });
66 Object.freeze(opts);
67
68 state.listeners.forEach(listener => {
69 listener(opts);
70 });
71
72 options.envPairs = Object.entries(opts.env).map(([name, value]) => `${name}=${value}`);
73
74 return fn.call(this, options);
75 };
76 }
77
78 function wrapSpawnFunctions() {
79 const {ChildProcess} = require('child_process');
80
81 /* eslint-disable-next-line node/no-deprecated-api */
82 const spawnSyncBinding = process.binding('spawn_sync');
83 const originalSync = spawnSyncBinding.spawn;
84 const originalAsync = ChildProcess.prototype.spawn;
85
86 spawnSyncBinding.spawn = wrappedSpawnFunction(spawnSyncBinding.spawn);
87 ChildProcess.prototype.spawn = wrappedSpawnFunction(ChildProcess.prototype.spawn);
88
89 /* istanbul ignore next: forward compatibility code */
90 return () => {
91 spawnSyncBinding.spawn = originalSync;
92 ChildProcess.prototype.spawn = originalAsync;
93 };
94 }
95
96 module.exports = {
97 addListener(listener) {
98 state.listeners.push(listener);
99 },
100 prependListener(listener) {
101 state.listeners.unshift(listener);
102 },
103 removeListener(listener) {
104 const idx = state.listeners.indexOf(listener);
105 if (idx !== -1) {
106 state.listeners.splice(idx, 1);
107 }
108 },
109 removeAllListeners() {
110 state.listeners = [];
111 }
112 };