@xenosystem/primitives 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/private-file/index.d.ts +41 -0
- package/dist/cjs/private-file/index.js +91 -0
- package/dist/cjs/process/here.d.ts +1 -0
- package/dist/cjs/process/here.js +3 -0
- package/dist/cjs/process/index.d.ts +50 -0
- package/dist/cjs/process/index.js +203 -0
- package/dist/esm/private-file/index.d.ts +41 -0
- package/dist/esm/private-file/index.js +86 -0
- package/dist/esm/process/here.d.ts +1 -0
- package/dist/esm/process/here.js +6 -0
- package/dist/esm/process/index.d.ts +50 -0
- package/dist/esm/process/index.js +199 -0
- package/native/THIRD_PARTY_NOTICES.md +1136 -0
- package/native/win32-x64/process.node +0 -0
- package/package.json +25 -3
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
|
|
3
|
+
*
|
|
4
|
+
* A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
|
|
5
|
+
* shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
|
|
6
|
+
* groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
|
|
7
|
+
* Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
|
|
8
|
+
* kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
|
|
9
|
+
* breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
|
|
10
|
+
*
|
|
11
|
+
* Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
|
|
12
|
+
* as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
|
|
13
|
+
* started anything yet; only then does it start the real command, with the same stdio.
|
|
14
|
+
*
|
|
15
|
+
* The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
|
|
16
|
+
* is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
|
|
17
|
+
* Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
|
|
18
|
+
* that needs the guarantee can refuse rather than assume it.
|
|
19
|
+
*/
|
|
20
|
+
import { spawn } from 'node:child_process';
|
|
21
|
+
import { existsSync } from 'node:fs';
|
|
22
|
+
import { createRequire } from 'node:module';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { moduleDir } from "./here.js";
|
|
25
|
+
let nativeCache;
|
|
26
|
+
/** The native job binding, or why it is not available. Windows only. */
|
|
27
|
+
function loadNative() {
|
|
28
|
+
if (nativeCache)
|
|
29
|
+
return nativeCache;
|
|
30
|
+
if (process.platform !== 'win32')
|
|
31
|
+
return (nativeCache = { reason: 'not Windows' });
|
|
32
|
+
const name = `win32-${process.arch}`;
|
|
33
|
+
// src/process (tests) and dist/{esm,cjs}/process (published) both sit under the package directory.
|
|
34
|
+
const candidates = [join(moduleDir, '..', '..', 'native', name, 'process.node'), join(moduleDir, '..', '..', '..', 'native', name, 'process.node')];
|
|
35
|
+
const file = candidates.find((p) => existsSync(p));
|
|
36
|
+
if (!file)
|
|
37
|
+
return (nativeCache = { reason: `no native binary for ${name}` });
|
|
38
|
+
try {
|
|
39
|
+
const binding = createRequire(file)(file);
|
|
40
|
+
if (typeof binding.ProcessJob !== 'function')
|
|
41
|
+
return (nativeCache = { reason: 'native binary has no ProcessJob' });
|
|
42
|
+
return (nativeCache = { ctor: binding.ProcessJob });
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
|
|
49
|
+
export function processGroupSupport() {
|
|
50
|
+
if (process.platform !== 'win32')
|
|
51
|
+
return { containment: 'process-group' };
|
|
52
|
+
const native = loadNative();
|
|
53
|
+
return native.ctor ? { containment: 'job' } : { containment: 'tree-walk', ...(native.reason ? { reason: native.reason } : {}) };
|
|
54
|
+
}
|
|
55
|
+
// The launcher: reads one JSON line of instructions from fd 3, then starts the real command with fds 0-2 inherited
|
|
56
|
+
// and exits with its exit code. A failure to start is reported back on fd 3 so the caller can raise `error`.
|
|
57
|
+
const LAUNCHER = [
|
|
58
|
+
"const fs=require('fs'),cp=require('child_process');",
|
|
59
|
+
"let t='';const b=Buffer.alloc(65536);",
|
|
60
|
+
"for(;;){const n=fs.readSync(3,b,0,b.length,null);if(n===0)process.exit(126);t+=b.toString('utf8',0,n);const i=t.indexOf('\\n');if(i>=0){t=t.slice(0,i);break}}",
|
|
61
|
+
'const s=JSON.parse(t);const env={...process.env};if(!s.keepRunAsNode)delete env.ELECTRON_RUN_AS_NODE;',
|
|
62
|
+
"const fail=(e)=>{try{fs.writeSync(3,JSON.stringify({error:{message:String(e&&e.message||e),code:e&&e.code}})+'\\n')}catch{}process.exit(127)};",
|
|
63
|
+
"let c;try{c=cp.spawn(s.command,s.args,{stdio:'inherit',windowsHide:s.windowsHide,windowsVerbatimArguments:s.verbatim,env})}catch(e){fail(e)}",
|
|
64
|
+
"c.on('error',fail);c.on('exit',(code)=>process.exit(code===null?1:code));",
|
|
65
|
+
].join('');
|
|
66
|
+
/**
|
|
67
|
+
* Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
|
|
68
|
+
* `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
|
|
69
|
+
*/
|
|
70
|
+
export function spawnProcessGroup(command, args, options = {}) {
|
|
71
|
+
const stdio = options.stdio ?? ['pipe', 'pipe', 'pipe'];
|
|
72
|
+
const env = options.env ?? process.env;
|
|
73
|
+
const base = { cwd: options.cwd, env, windowsHide: options.windowsHide ?? true, shell: false };
|
|
74
|
+
if (process.platform !== 'win32') {
|
|
75
|
+
const child = spawn(command, [...args], { ...base, stdio: [...stdio], detached: true });
|
|
76
|
+
return {
|
|
77
|
+
child,
|
|
78
|
+
containment: 'process-group',
|
|
79
|
+
stop(force = false) {
|
|
80
|
+
const pid = child.pid;
|
|
81
|
+
if (pid === undefined)
|
|
82
|
+
return;
|
|
83
|
+
try {
|
|
84
|
+
process.kill(-pid, force ? 'SIGKILL' : 'SIGTERM');
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
try {
|
|
88
|
+
child.kill(force ? 'SIGKILL' : 'SIGTERM');
|
|
89
|
+
}
|
|
90
|
+
catch { /* already gone */ }
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
activeProcesses: () => undefined,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const native = loadNative();
|
|
97
|
+
if (!native.ctor) {
|
|
98
|
+
const child = spawn(command, [...args], { ...base, stdio: [...stdio], windowsVerbatimArguments: options.windowsVerbatimArguments ?? false });
|
|
99
|
+
return {
|
|
100
|
+
child,
|
|
101
|
+
containment: 'tree-walk',
|
|
102
|
+
stop() {
|
|
103
|
+
const pid = child.pid;
|
|
104
|
+
if (pid === undefined)
|
|
105
|
+
return;
|
|
106
|
+
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
107
|
+
killer.on('error', () => { try {
|
|
108
|
+
child.kill();
|
|
109
|
+
}
|
|
110
|
+
catch { /* already gone */ } });
|
|
111
|
+
},
|
|
112
|
+
activeProcesses: () => undefined,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
const job = new native.ctor();
|
|
116
|
+
let jobOpen = true;
|
|
117
|
+
const endJob = (how) => {
|
|
118
|
+
if (!jobOpen)
|
|
119
|
+
return;
|
|
120
|
+
jobOpen = false;
|
|
121
|
+
try {
|
|
122
|
+
if (how === 'terminate')
|
|
123
|
+
job.close();
|
|
124
|
+
else
|
|
125
|
+
job.release();
|
|
126
|
+
}
|
|
127
|
+
catch { /* the handle is gone either way */ }
|
|
128
|
+
};
|
|
129
|
+
const runAsNode = process.versions.electron !== undefined;
|
|
130
|
+
const launcherEnv = runAsNode ? { ...env, ELECTRON_RUN_AS_NODE: '1' } : env;
|
|
131
|
+
const child = spawn(process.execPath, ['-e', LAUNCHER], { ...base, env: launcherEnv, stdio: [...stdio, 'pipe'] });
|
|
132
|
+
const control = child.stdio[3];
|
|
133
|
+
if (child.pid !== undefined && control) {
|
|
134
|
+
try {
|
|
135
|
+
job.assign(child.pid);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
// A command that is not in its group is not started: stopping it could not reach what it starts.
|
|
139
|
+
try {
|
|
140
|
+
child.kill();
|
|
141
|
+
}
|
|
142
|
+
catch { /* already gone */ }
|
|
143
|
+
endJob('terminate');
|
|
144
|
+
queueMicrotask(() => child.emit('error', new Error(`could not place the command in a job: ${error.message}`)));
|
|
145
|
+
return { child, containment: 'job', stop() { }, activeProcesses: () => undefined };
|
|
146
|
+
}
|
|
147
|
+
let received = '';
|
|
148
|
+
control.on('data', (chunk) => {
|
|
149
|
+
received += chunk.toString();
|
|
150
|
+
const line = received.split('\n')[0];
|
|
151
|
+
if (received.includes('\n') && line) {
|
|
152
|
+
try {
|
|
153
|
+
const message = JSON.parse(line);
|
|
154
|
+
if (message.error)
|
|
155
|
+
child.emit('error', Object.assign(new Error(message.error.message), message.error.code ? { code: message.error.code } : {}));
|
|
156
|
+
}
|
|
157
|
+
catch { /* not ours */ }
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
control.on('error', () => { });
|
|
161
|
+
control.write(JSON.stringify({
|
|
162
|
+
command,
|
|
163
|
+
args,
|
|
164
|
+
verbatim: options.windowsVerbatimArguments ?? false,
|
|
165
|
+
windowsHide: options.windowsHide ?? true,
|
|
166
|
+
keepRunAsNode: runAsNode && env.ELECTRON_RUN_AS_NODE !== undefined,
|
|
167
|
+
}) + '\n');
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
endJob('terminate');
|
|
171
|
+
}
|
|
172
|
+
// A command that ended on its own keeps today's behaviour for anything it left running; only stop() ends those.
|
|
173
|
+
child.once('close', () => endJob('release'));
|
|
174
|
+
child.once('error', () => { if (child.exitCode !== null || child.pid === undefined)
|
|
175
|
+
endJob('release'); });
|
|
176
|
+
return {
|
|
177
|
+
child,
|
|
178
|
+
containment: 'job',
|
|
179
|
+
stop() {
|
|
180
|
+
if (!jobOpen)
|
|
181
|
+
return;
|
|
182
|
+
try {
|
|
183
|
+
job.terminate(1);
|
|
184
|
+
}
|
|
185
|
+
catch { /* fall through: closing the handle ends every member too */ }
|
|
186
|
+
endJob('terminate');
|
|
187
|
+
},
|
|
188
|
+
activeProcesses() {
|
|
189
|
+
if (!jobOpen)
|
|
190
|
+
return 0;
|
|
191
|
+
try {
|
|
192
|
+
return job.activeProcesses();
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|