@xenosystem/primitives 0.3.2 → 0.5.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/README.md +1 -0
- package/dist/cjs/live/index.d.ts +137 -0
- package/dist/cjs/live/index.js +261 -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/live/index.d.ts +137 -0
- package/dist/esm/live/index.js +256 -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,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xenosystem/primitives/live` — the client every XENO app uses to be live with others on a shared thing.
|
|
3
|
+
*
|
|
4
|
+
* Owner, 2026-10-28: multiplayer is "a proper service at XENO level that we will inherit on all our apps". The service
|
|
5
|
+
* is XENO Multiplayer (repo xeno-multiplayer, `wss://live.xenosystem.ai`); its protocol, `xeno-live.v1`, is its SPEC.md.
|
|
6
|
+
* This family is the ONE client for it, so presence, the shared document, leases and signals cannot be implemented
|
|
7
|
+
* differently per app.
|
|
8
|
+
*
|
|
9
|
+
* Dependency-free like the rest of this package: the app passes its own Yjs module (one copy per app; Yjs breaks when
|
|
10
|
+
* two copies meet), its own WebSocket where the platform has none built in, and a function that asks the platform for
|
|
11
|
+
* a ticket. Nothing here stores a ticket.
|
|
12
|
+
*
|
|
13
|
+
* What you join is the shared thing itself, `<type>/<id>` (`spawn.canvas/<uuid>`) — no "room" or "space".
|
|
14
|
+
*
|
|
15
|
+
* Reconnection is automatic, with a fresh ticket each time; on every join both sides exchange state vectors, so a
|
|
16
|
+
* returning client downloads only what it lacks and sends the edits it made offline. It stops for good when access
|
|
17
|
+
* ended (4403), when the request is malformed or too large (4400, 4413), when tickets keep being refused, or on close().
|
|
18
|
+
*/
|
|
19
|
+
/** The slice of a Yjs `Doc` this uses. */
|
|
20
|
+
export interface LiveDoc {
|
|
21
|
+
on(event: 'update', fn: (update: Uint8Array, origin: unknown) => void): void;
|
|
22
|
+
off(event: 'update', fn: (update: Uint8Array, origin: unknown) => void): void;
|
|
23
|
+
}
|
|
24
|
+
/** The slice of the Yjs module this uses. Pass the app's own `import * as Y from 'yjs'`. */
|
|
25
|
+
export interface LiveYjs<D extends LiveDoc = LiveDoc> {
|
|
26
|
+
Doc: new () => D;
|
|
27
|
+
applyUpdate(doc: D, update: Uint8Array, origin?: unknown): void;
|
|
28
|
+
encodeStateVector(doc: D): Uint8Array;
|
|
29
|
+
encodeStateAsUpdate(doc: D, stateVector?: Uint8Array): Uint8Array;
|
|
30
|
+
}
|
|
31
|
+
/** The slice of a WebSocket this uses (the browser's, Node's built-in one, or the `ws` package). */
|
|
32
|
+
export interface LiveSocket {
|
|
33
|
+
binaryType: string;
|
|
34
|
+
readyState: number;
|
|
35
|
+
send(data: string | Uint8Array): void;
|
|
36
|
+
close(code?: number, reason?: string): void;
|
|
37
|
+
onopen: ((ev: unknown) => void) | null;
|
|
38
|
+
onmessage: ((ev: {
|
|
39
|
+
data: unknown;
|
|
40
|
+
}) => void) | null;
|
|
41
|
+
onclose: ((ev: {
|
|
42
|
+
code: number;
|
|
43
|
+
reason: string;
|
|
44
|
+
}) => void) | null;
|
|
45
|
+
onerror: ((ev: unknown) => void) | null;
|
|
46
|
+
}
|
|
47
|
+
export type LiveSocketConstructor = new (url: string, protocols: string[]) => LiveSocket;
|
|
48
|
+
export interface LiveParticipant {
|
|
49
|
+
conn: string;
|
|
50
|
+
sub: string;
|
|
51
|
+
name: string;
|
|
52
|
+
kind: 'human' | 'agent' | 'service';
|
|
53
|
+
/** For an agent: the person it acts for. */
|
|
54
|
+
act: {
|
|
55
|
+
sub: string;
|
|
56
|
+
} | null;
|
|
57
|
+
role: 'owner' | 'editor' | 'viewer';
|
|
58
|
+
state: unknown;
|
|
59
|
+
}
|
|
60
|
+
export type LiveStatus = 'connecting' | 'open' | 'reconnecting' | 'ended';
|
|
61
|
+
export interface LiveEnd {
|
|
62
|
+
code: number;
|
|
63
|
+
reason: string;
|
|
64
|
+
}
|
|
65
|
+
export interface LiveOptions<D extends LiveDoc = LiveDoc> {
|
|
66
|
+
/** The kind of shared thing, `<app>.<kind>`: `spawn.canvas`, `docs.doc`. */
|
|
67
|
+
type: string;
|
|
68
|
+
/** The thing's own stable id. */
|
|
69
|
+
id: string;
|
|
70
|
+
/** Asks the platform for a join ticket for `<type>/<id>`; called before every connection. */
|
|
71
|
+
ticket: (resource: string) => Promise<string>;
|
|
72
|
+
/** The app's own Yjs module. */
|
|
73
|
+
Y: LiveYjs<D>;
|
|
74
|
+
/** The document to keep live; a new one is made if omitted. */
|
|
75
|
+
doc?: D;
|
|
76
|
+
/** Default `wss://live.xenosystem.ai`. */
|
|
77
|
+
url?: string;
|
|
78
|
+
/** Default the platform's own `WebSocket`. */
|
|
79
|
+
WebSocket?: LiveSocketConstructor;
|
|
80
|
+
/** Reconnection back-off. */
|
|
81
|
+
retry?: {
|
|
82
|
+
minMs?: number;
|
|
83
|
+
maxMs?: number;
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export interface LiveEvents {
|
|
87
|
+
status: LiveStatus;
|
|
88
|
+
participants: LiveParticipant[];
|
|
89
|
+
leases: Record<string, LiveParticipant>;
|
|
90
|
+
'lease.refused': {
|
|
91
|
+
key: string;
|
|
92
|
+
holder: LiveParticipant | null;
|
|
93
|
+
};
|
|
94
|
+
/** `takenFrom` is set when someone took a lease over from someone else. */
|
|
95
|
+
'lease.taken': {
|
|
96
|
+
key: string;
|
|
97
|
+
holder: LiveParticipant;
|
|
98
|
+
takenFrom: LiveParticipant;
|
|
99
|
+
};
|
|
100
|
+
signal: {
|
|
101
|
+
from: LiveParticipant;
|
|
102
|
+
data: unknown;
|
|
103
|
+
};
|
|
104
|
+
error: {
|
|
105
|
+
code: string;
|
|
106
|
+
message: string;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
export interface LiveConnection<D extends LiveDoc = LiveDoc> {
|
|
110
|
+
readonly doc: D;
|
|
111
|
+
readonly status: LiveStatus;
|
|
112
|
+
/** This connection as the others see it, once open. */
|
|
113
|
+
readonly self: LiveParticipant | null;
|
|
114
|
+
/** Why it ended, once `status` is `ended`. */
|
|
115
|
+
readonly ended: LiveEnd | null;
|
|
116
|
+
/** Everyone else here now, with their presence. */
|
|
117
|
+
participants(): LiveParticipant[];
|
|
118
|
+
/** Who holds each lease now. */
|
|
119
|
+
leases(): Record<string, LiveParticipant>;
|
|
120
|
+
/** Replaces this connection's presence (cursor, selection, viewport…); kept across reconnects. */
|
|
121
|
+
setPresence(state: unknown): void;
|
|
122
|
+
/** Sends an ephemeral app event to everyone, or to one connection. Dropped while offline. */
|
|
123
|
+
signal(data: unknown, to?: string): void;
|
|
124
|
+
requestLease(key: string): void;
|
|
125
|
+
releaseLease(key: string): void;
|
|
126
|
+
/** Takes a held lease over; the previous holder is told. */
|
|
127
|
+
takeLease(key: string): void;
|
|
128
|
+
on<E extends keyof LiveEvents>(event: E, fn: (value: LiveEvents[E]) => void): () => void;
|
|
129
|
+
/** Leaves for good. */
|
|
130
|
+
close(): void;
|
|
131
|
+
}
|
|
132
|
+
export declare const LIVE_PROTOCOL = "xeno-live.v1";
|
|
133
|
+
export declare const LIVE_URL = "wss://live.xenosystem.ai";
|
|
134
|
+
/** A human-readable reason for a close code (SPEC §5). */
|
|
135
|
+
export declare function liveCloseReason(code: number): string;
|
|
136
|
+
/** Join a shared thing and keep it live until `close()`. */
|
|
137
|
+
export declare function joinLive<D extends LiveDoc>(options: LiveOptions<D>): LiveConnection<D>;
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xenosystem/primitives/live` — the client every XENO app uses to be live with others on a shared thing.
|
|
3
|
+
*
|
|
4
|
+
* Owner, 2026-10-28: multiplayer is "a proper service at XENO level that we will inherit on all our apps". The service
|
|
5
|
+
* is XENO Multiplayer (repo xeno-multiplayer, `wss://live.xenosystem.ai`); its protocol, `xeno-live.v1`, is its SPEC.md.
|
|
6
|
+
* This family is the ONE client for it, so presence, the shared document, leases and signals cannot be implemented
|
|
7
|
+
* differently per app.
|
|
8
|
+
*
|
|
9
|
+
* Dependency-free like the rest of this package: the app passes its own Yjs module (one copy per app; Yjs breaks when
|
|
10
|
+
* two copies meet), its own WebSocket where the platform has none built in, and a function that asks the platform for
|
|
11
|
+
* a ticket. Nothing here stores a ticket.
|
|
12
|
+
*
|
|
13
|
+
* What you join is the shared thing itself, `<type>/<id>` (`spawn.canvas/<uuid>`) — no "room" or "space".
|
|
14
|
+
*
|
|
15
|
+
* Reconnection is automatic, with a fresh ticket each time; on every join both sides exchange state vectors, so a
|
|
16
|
+
* returning client downloads only what it lacks and sends the edits it made offline. It stops for good when access
|
|
17
|
+
* ended (4403), when the request is malformed or too large (4400, 4413), when tickets keep being refused, or on close().
|
|
18
|
+
*/
|
|
19
|
+
export const LIVE_PROTOCOL = 'xeno-live.v1';
|
|
20
|
+
export const LIVE_URL = 'wss://live.xenosystem.ai';
|
|
21
|
+
const SYNC_REQUEST = 0x00, UPDATE = 0x01, STATE = 0x02, VECTOR = 0x03;
|
|
22
|
+
const TYPE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
|
|
23
|
+
const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
24
|
+
/** Close codes after which reconnecting cannot help. */
|
|
25
|
+
const FINAL = new Set([4400, 4403, 4413]);
|
|
26
|
+
const MAX_REFUSALS = 3;
|
|
27
|
+
/** A human-readable reason for a close code (SPEC §5). */
|
|
28
|
+
export function liveCloseReason(code) {
|
|
29
|
+
switch (code) {
|
|
30
|
+
case 4400: return 'the request was not understood';
|
|
31
|
+
case 4401: return 'the platform did not admit this connection';
|
|
32
|
+
case 4403: return 'your access to this has ended';
|
|
33
|
+
case 4413: return 'too large';
|
|
34
|
+
case 4429: return 'too many messages';
|
|
35
|
+
default: return 'the connection was lost';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Join a shared thing and keep it live until `close()`. */
|
|
39
|
+
export function joinLive(options) {
|
|
40
|
+
const { type, id, ticket, Y } = options;
|
|
41
|
+
if (!TYPE.test(type))
|
|
42
|
+
throw new TypeError(`not a shared-thing type: ${JSON.stringify(type)} (expected <app>.<kind>)`);
|
|
43
|
+
if (!ID.test(id))
|
|
44
|
+
throw new TypeError(`not a shared-thing id: ${JSON.stringify(id)}`);
|
|
45
|
+
const found = options.WebSocket ?? globalThis.WebSocket;
|
|
46
|
+
if (!found)
|
|
47
|
+
throw new TypeError('no WebSocket: pass one as options.WebSocket');
|
|
48
|
+
const Socket = found;
|
|
49
|
+
const resource = `${type}/${id}`;
|
|
50
|
+
const endpoint = `${(options.url ?? LIVE_URL).replace(/\/+$/, '')}/v1/${resource}`;
|
|
51
|
+
const minMs = options.retry?.minMs ?? 500, maxMs = options.retry?.maxMs ?? 30_000;
|
|
52
|
+
const doc = options.doc ?? new Y.Doc();
|
|
53
|
+
const REMOTE = Symbol('xeno-live-remote');
|
|
54
|
+
let status = 'connecting';
|
|
55
|
+
let ended = null;
|
|
56
|
+
let self = null;
|
|
57
|
+
let socket = null;
|
|
58
|
+
let presence = null;
|
|
59
|
+
let attempt = 0, refusals = 0;
|
|
60
|
+
let timer = null;
|
|
61
|
+
let closedByUs = false;
|
|
62
|
+
const people = new Map();
|
|
63
|
+
let held = {};
|
|
64
|
+
const listeners = new Map();
|
|
65
|
+
function emit(event, value) {
|
|
66
|
+
for (const fn of listeners.get(event) ?? []) {
|
|
67
|
+
try {
|
|
68
|
+
fn(value);
|
|
69
|
+
}
|
|
70
|
+
catch { /* a listener's failure is its own */ }
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const setStatus = (s) => { if (status !== s) {
|
|
74
|
+
status = s;
|
|
75
|
+
emit('status', s);
|
|
76
|
+
} };
|
|
77
|
+
const emitPeople = () => emit('participants', [...people.values()]);
|
|
78
|
+
const open = () => socket !== null && socket.readyState === 1;
|
|
79
|
+
const sendJson = (m) => { if (open())
|
|
80
|
+
socket.send(JSON.stringify(m)); };
|
|
81
|
+
const frame = (t, body) => { const f = new Uint8Array(body.byteLength + 1); f[0] = t; f.set(body, 1); return f; };
|
|
82
|
+
const onLocalUpdate = (update, origin) => {
|
|
83
|
+
// While offline nothing is queued here: the next join's state-vector exchange sends exactly what the service lacks.
|
|
84
|
+
if (origin !== REMOTE && open() && self && self.role !== 'viewer')
|
|
85
|
+
socket.send(frame(UPDATE, update));
|
|
86
|
+
};
|
|
87
|
+
doc.on('update', onLocalUpdate);
|
|
88
|
+
function end(code, reason) {
|
|
89
|
+
if (status === 'ended')
|
|
90
|
+
return;
|
|
91
|
+
ended = { code, reason };
|
|
92
|
+
if (timer)
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
doc.off('update', onLocalUpdate);
|
|
95
|
+
people.clear();
|
|
96
|
+
held = {};
|
|
97
|
+
self = null;
|
|
98
|
+
setStatus('ended');
|
|
99
|
+
}
|
|
100
|
+
function scheduleReconnect() {
|
|
101
|
+
setStatus('reconnecting');
|
|
102
|
+
const delay = Math.min(maxMs, minMs * 2 ** attempt) * (0.8 + Math.random() * 0.4);
|
|
103
|
+
attempt++;
|
|
104
|
+
timer = setTimeout(() => { timer = null; void connect(); }, delay);
|
|
105
|
+
}
|
|
106
|
+
async function connect() {
|
|
107
|
+
if (status === 'ended')
|
|
108
|
+
return;
|
|
109
|
+
let jwt;
|
|
110
|
+
try {
|
|
111
|
+
jwt = await ticket(resource);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// The platform could not be asked (offline, signed out): try again later; nothing is lost.
|
|
115
|
+
return scheduleReconnect();
|
|
116
|
+
}
|
|
117
|
+
// close() may have run while the ticket was being fetched
|
|
118
|
+
if (status === 'ended')
|
|
119
|
+
return;
|
|
120
|
+
const ws = new Socket(endpoint, [LIVE_PROTOCOL, `ticket.${jwt}`]);
|
|
121
|
+
ws.binaryType = 'arraybuffer';
|
|
122
|
+
socket = ws;
|
|
123
|
+
let welcomed = false;
|
|
124
|
+
ws.onmessage = (ev) => {
|
|
125
|
+
if (socket !== ws)
|
|
126
|
+
return;
|
|
127
|
+
if (typeof ev.data === 'string')
|
|
128
|
+
return onControl(ev.data, () => { welcomed = true; });
|
|
129
|
+
const bytes = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data instanceof Uint8Array ? ev.data : null;
|
|
130
|
+
if (!bytes || bytes.byteLength < 1)
|
|
131
|
+
return;
|
|
132
|
+
const body = bytes.subarray(1);
|
|
133
|
+
if (bytes[0] === VECTOR) {
|
|
134
|
+
ws.send(frame(SYNC_REQUEST, Y.encodeStateVector(doc)));
|
|
135
|
+
if (self?.role !== 'viewer') {
|
|
136
|
+
const lacks = Y.encodeStateAsUpdate(doc, body);
|
|
137
|
+
if (lacks.byteLength > 2)
|
|
138
|
+
ws.send(frame(UPDATE, lacks));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
else if (bytes[0] === STATE || bytes[0] === UPDATE) {
|
|
142
|
+
Y.applyUpdate(doc, body, REMOTE);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
ws.onclose = (ev) => {
|
|
146
|
+
if (socket !== ws)
|
|
147
|
+
return;
|
|
148
|
+
socket = null;
|
|
149
|
+
people.clear();
|
|
150
|
+
if (Object.keys(held).length) {
|
|
151
|
+
held = {};
|
|
152
|
+
emit('leases', {});
|
|
153
|
+
}
|
|
154
|
+
emitPeople();
|
|
155
|
+
if (closedByUs)
|
|
156
|
+
return end(1000, 'closed');
|
|
157
|
+
if (FINAL.has(ev.code))
|
|
158
|
+
return end(ev.code, ev.reason || liveCloseReason(ev.code));
|
|
159
|
+
if (ev.code === 4401 && !welcomed && ++refusals >= MAX_REFUSALS)
|
|
160
|
+
return end(4401, ev.reason || liveCloseReason(4401));
|
|
161
|
+
scheduleReconnect();
|
|
162
|
+
};
|
|
163
|
+
ws.onerror = () => { };
|
|
164
|
+
}
|
|
165
|
+
function onControl(text, onWelcome) {
|
|
166
|
+
let m;
|
|
167
|
+
try {
|
|
168
|
+
m = JSON.parse(text);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
switch (m.t) {
|
|
174
|
+
case 'welcome': {
|
|
175
|
+
onWelcome();
|
|
176
|
+
attempt = 0;
|
|
177
|
+
refusals = 0;
|
|
178
|
+
self = m.self;
|
|
179
|
+
people.clear();
|
|
180
|
+
for (const p of m.participants)
|
|
181
|
+
people.set(p.conn, p);
|
|
182
|
+
held = { ...m.leases };
|
|
183
|
+
setStatus('open');
|
|
184
|
+
if (presence !== null)
|
|
185
|
+
sendJson({ t: 'presence', state: presence });
|
|
186
|
+
emitPeople();
|
|
187
|
+
emit('leases', { ...held });
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
case 'join': {
|
|
191
|
+
const p = m.participant;
|
|
192
|
+
people.set(p.conn, p);
|
|
193
|
+
return emitPeople();
|
|
194
|
+
}
|
|
195
|
+
case 'leave': {
|
|
196
|
+
people.delete(m.conn);
|
|
197
|
+
return emitPeople();
|
|
198
|
+
}
|
|
199
|
+
case 'presence': {
|
|
200
|
+
const p = people.get(m.conn);
|
|
201
|
+
if (p) {
|
|
202
|
+
p.state = m.state;
|
|
203
|
+
emitPeople();
|
|
204
|
+
}
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
case 'lease': {
|
|
208
|
+
const key = m.key, holder = m.holder;
|
|
209
|
+
if (holder)
|
|
210
|
+
held[key] = holder;
|
|
211
|
+
else
|
|
212
|
+
delete held[key];
|
|
213
|
+
emit('leases', { ...held });
|
|
214
|
+
if (holder && m.takenFrom)
|
|
215
|
+
emit('lease.taken', { key, holder, takenFrom: m.takenFrom });
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
case 'lease.refused': return emit('lease.refused', { key: m.key, holder: m.holder ?? null });
|
|
219
|
+
case 'signal': return emit('signal', { from: m.from, data: m.data });
|
|
220
|
+
case 'error': return emit('error', { code: String(m.code), message: String(m.message) });
|
|
221
|
+
default: return;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
void connect();
|
|
225
|
+
return {
|
|
226
|
+
doc,
|
|
227
|
+
get status() { return status; },
|
|
228
|
+
get self() { return self; },
|
|
229
|
+
get ended() { return ended; },
|
|
230
|
+
participants: () => [...people.values()],
|
|
231
|
+
leases: () => ({ ...held }),
|
|
232
|
+
setPresence(state) { presence = state ?? null; sendJson({ t: 'presence', state: presence }); },
|
|
233
|
+
signal(data, to) { sendJson(to === undefined ? { t: 'signal', data } : { t: 'signal', data, to }); },
|
|
234
|
+
requestLease(key) { sendJson({ t: 'lease.request', key }); },
|
|
235
|
+
releaseLease(key) { sendJson({ t: 'lease.release', key }); },
|
|
236
|
+
takeLease(key) { sendJson({ t: 'lease.take', key }); },
|
|
237
|
+
on(event, fn) {
|
|
238
|
+
let set = listeners.get(event);
|
|
239
|
+
if (!set)
|
|
240
|
+
listeners.set(event, (set = new Set()));
|
|
241
|
+
set.add(fn);
|
|
242
|
+
return () => { set.delete(fn); };
|
|
243
|
+
},
|
|
244
|
+
close() {
|
|
245
|
+
closedByUs = true;
|
|
246
|
+
if (timer) {
|
|
247
|
+
clearTimeout(timer);
|
|
248
|
+
timer = null;
|
|
249
|
+
}
|
|
250
|
+
if (socket)
|
|
251
|
+
socket.close(1000, 'closed');
|
|
252
|
+
else
|
|
253
|
+
end(1000, 'closed');
|
|
254
|
+
},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const moduleDir: string;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
// This module's own directory, used to find the bundled native binary. The CommonJS build replaces this file with
|
|
4
|
+
// `exports.moduleDir = __dirname` (scripts/build-ts.mjs), because CommonJS cannot parse `import.meta`.
|
|
5
|
+
// @ts-ignore TS1343 in the CommonJS compile only; that emitted file is overwritten.
|
|
6
|
+
export const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -0,0 +1,50 @@
|
|
|
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 { type ChildProcess } from 'node:child_process';
|
|
21
|
+
/** How stopping reaches the command's descendants. */
|
|
22
|
+
export type Containment = 'job' | 'process-group' | 'tree-walk';
|
|
23
|
+
export interface ProcessGroupOptions {
|
|
24
|
+
cwd?: string;
|
|
25
|
+
env?: NodeJS.ProcessEnv;
|
|
26
|
+
windowsHide?: boolean;
|
|
27
|
+
/** Pass argv to the program exactly as given (needed when the program is `cmd.exe`, which has its own parser). */
|
|
28
|
+
windowsVerbatimArguments?: boolean;
|
|
29
|
+
/** stdin, stdout, stderr. Default: all piped. */
|
|
30
|
+
stdio?: readonly ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit'];
|
|
31
|
+
}
|
|
32
|
+
export interface ProcessGroup {
|
|
33
|
+
/** The process that was started. On Windows with a job, this is the launcher; its exit code is the command's. */
|
|
34
|
+
readonly child: ChildProcess;
|
|
35
|
+
readonly containment: Containment;
|
|
36
|
+
/** Stop the command and everything it started. `force` matters on POSIX only (SIGKILL instead of SIGTERM). */
|
|
37
|
+
stop(force?: boolean): void;
|
|
38
|
+
/** Processes still running in the group, where the platform can count them (Windows job only). */
|
|
39
|
+
activeProcesses(): number | undefined;
|
|
40
|
+
}
|
|
41
|
+
/** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
|
|
42
|
+
export declare function processGroupSupport(): {
|
|
43
|
+
containment: Containment;
|
|
44
|
+
reason?: string;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
|
|
48
|
+
* `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
|
|
49
|
+
*/
|
|
50
|
+
export declare function spawnProcessGroup(command: string, args: readonly string[], options?: ProcessGroupOptions): ProcessGroup;
|
|
@@ -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
|
+
}
|