@sorbetai/tools-node 0.0.0-stage → 0.1.0-alpha.17

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.
@@ -0,0 +1,813 @@
1
+ import { win32 } from "node:path";
2
+ import { StringDecoder } from "node:string_decoder";
3
+ import { execa } from "execa";
4
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
5
+ import { resolveExecutable } from "@azure/core-process";
6
+
7
+ //#region src/environment/windows-native.ts
8
+ const ERROR_ALREADY_EXISTS = 183;
9
+ const ERROR_FILE_NOT_FOUND = 2;
10
+ const WAIT_OBJECT_0 = 0;
11
+ const WAIT_TIMEOUT = 258;
12
+ const CREATE_SUSPENDED = 4;
13
+ const CREATE_UNICODE_ENVIRONMENT = 1024;
14
+ const CREATE_NO_WINDOW = 134217728;
15
+ const STARTF_USESTDHANDLES = 256;
16
+ const HANDLE_FLAG_INHERIT = 1;
17
+ const JOB_OBJECT_QUERY = 4;
18
+ const JOB_OBJECT_TERMINATE = 8;
19
+ const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 8192;
20
+ const JOBOBJECT_EXTENDED_LIMIT_INFORMATION_CLASS = 9;
21
+ const JOBOBJECT_BASIC_ACCOUNTING_INFORMATION_CLASS = 1;
22
+ var Win32Error = class extends Error {
23
+ constructor(operation, code) {
24
+ super(`${operation} failed (Win32 ${code})`);
25
+ this.operation = operation;
26
+ this.code = code;
27
+ this.name = "Win32Error";
28
+ }
29
+ };
30
+ let cached;
31
+ function windowsApi() {
32
+ cached ??= loadWindowsApi();
33
+ return cached;
34
+ }
35
+ async function loadWindowsApi() {
36
+ if (process.platform !== "win32" || process.arch === "ia32") throw new Error("Windows Job backend unavailable");
37
+ const { default: koffi } = await import("koffi");
38
+ const kernel32 = koffi.load("kernel32.dll");
39
+ const PVOID = koffi.pointer("void");
40
+ const STARTUPINFOW = koffi.struct("SorbetStartupInfoW", {
41
+ cb: "uint32",
42
+ lpReserved: "str16",
43
+ lpDesktop: "str16",
44
+ lpTitle: "str16",
45
+ dwX: "uint32",
46
+ dwY: "uint32",
47
+ dwXSize: "uint32",
48
+ dwYSize: "uint32",
49
+ dwXCountChars: "uint32",
50
+ dwYCountChars: "uint32",
51
+ dwFillAttribute: "uint32",
52
+ dwFlags: "uint32",
53
+ wShowWindow: "uint16",
54
+ cbReserved2: "uint16",
55
+ lpReserved2: koffi.pointer("uint8"),
56
+ hStdInput: PVOID,
57
+ hStdOutput: PVOID,
58
+ hStdError: PVOID
59
+ });
60
+ const PROCESS_INFORMATION = koffi.struct("SorbetProcessInformation", {
61
+ hProcess: PVOID,
62
+ hThread: PVOID,
63
+ dwProcessId: "uint32",
64
+ dwThreadId: "uint32"
65
+ });
66
+ const SECURITY_ATTRIBUTES = koffi.struct("SorbetSecurityAttributes", {
67
+ nLength: "uint32",
68
+ lpSecurityDescriptor: PVOID,
69
+ bInheritHandle: "int"
70
+ });
71
+ const JOBOBJECT_BASIC_LIMIT_INFORMATION = koffi.struct("SorbetJobBasicLimits", {
72
+ PerProcessUserTimeLimit: "int64",
73
+ PerJobUserTimeLimit: "int64",
74
+ LimitFlags: "uint32",
75
+ MinimumWorkingSetSize: "uint64",
76
+ MaximumWorkingSetSize: "uint64",
77
+ ActiveProcessLimit: "uint32",
78
+ Affinity: "uint64",
79
+ PriorityClass: "uint32",
80
+ SchedulingClass: "uint32"
81
+ });
82
+ const IO_COUNTERS = koffi.struct("SorbetIoCounters", {
83
+ ReadOperationCount: "uint64",
84
+ WriteOperationCount: "uint64",
85
+ OtherOperationCount: "uint64",
86
+ ReadTransferCount: "uint64",
87
+ WriteTransferCount: "uint64",
88
+ OtherTransferCount: "uint64"
89
+ });
90
+ const JOBOBJECT_EXTENDED_LIMIT_INFORMATION = koffi.struct("SorbetJobExtendedLimitInformation", {
91
+ BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION,
92
+ IoInfo: IO_COUNTERS,
93
+ ProcessMemoryLimit: "uint64",
94
+ JobMemoryLimit: "uint64",
95
+ PeakProcessMemoryUsed: "uint64",
96
+ PeakJobMemoryUsed: "uint64"
97
+ });
98
+ const JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = koffi.struct("SorbetJobBasicAccountingInformation", {
99
+ TotalUserTime: "int64",
100
+ TotalKernelTime: "int64",
101
+ ThisPeriodTotalUserTime: "int64",
102
+ ThisPeriodTotalKernelTime: "int64",
103
+ TotalPageFaultCount: "uint32",
104
+ TotalProcesses: "uint32",
105
+ ActiveProcesses: "uint32",
106
+ TotalTerminatedProcesses: "uint32"
107
+ });
108
+ requireLayout(STARTUPINFOW, 104);
109
+ requireLayout(PROCESS_INFORMATION, 24);
110
+ requireLayout(SECURITY_ATTRIBUTES, 24);
111
+ requireLayout(JOBOBJECT_EXTENDED_LIMIT_INFORMATION, 144);
112
+ requireLayout(JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, 48);
113
+ const bind = (name, result, args) => kernel32.func("__stdcall", name, result, args);
114
+ const closeHandle = bind("CloseHandle", "int", [PVOID]);
115
+ const createJobObjectW = bind("CreateJobObjectW", PVOID, [PVOID, "str16"]);
116
+ const createPipeW = bind("CreatePipe", "int", [
117
+ koffi.out(koffi.pointer(PVOID)),
118
+ koffi.out(koffi.pointer(PVOID)),
119
+ PVOID,
120
+ "uint32"
121
+ ]);
122
+ const createProcessW = bind("CreateProcessW", "int", [
123
+ "str16",
124
+ PVOID,
125
+ PVOID,
126
+ PVOID,
127
+ "int",
128
+ "uint32",
129
+ PVOID,
130
+ "str16",
131
+ koffi.pointer(STARTUPINFOW),
132
+ koffi.pointer(PROCESS_INFORMATION)
133
+ ]);
134
+ const getExitCodeProcess = bind("GetExitCodeProcess", "int", [PVOID, koffi.pointer("uint32")]);
135
+ const getLastError = bind("GetLastError", "uint32", []);
136
+ const openJobObjectW = bind("OpenJobObjectW", PVOID, [
137
+ "uint32",
138
+ "int",
139
+ "str16"
140
+ ]);
141
+ const peekNamedPipe = bind("PeekNamedPipe", "int", [
142
+ PVOID,
143
+ PVOID,
144
+ "uint32",
145
+ PVOID,
146
+ koffi.pointer("uint32"),
147
+ PVOID
148
+ ]);
149
+ const queryInformationJobObject = bind("QueryInformationJobObject", "int", [
150
+ PVOID,
151
+ "int",
152
+ PVOID,
153
+ "uint32",
154
+ PVOID
155
+ ]);
156
+ const readFile = bind("ReadFile", "int", [
157
+ PVOID,
158
+ PVOID,
159
+ "uint32",
160
+ koffi.pointer("uint32"),
161
+ PVOID
162
+ ]);
163
+ const resumeThread = bind("ResumeThread", "uint32", [PVOID]);
164
+ const setHandleInformation = bind("SetHandleInformation", "int", [
165
+ PVOID,
166
+ "uint32",
167
+ "uint32"
168
+ ]);
169
+ const setInformationJobObject = bind("SetInformationJobObject", "int", [
170
+ PVOID,
171
+ "int",
172
+ PVOID,
173
+ "uint32"
174
+ ]);
175
+ const setLastError = bind("SetLastError", "void", ["uint32"]);
176
+ const terminateJobObject = bind("TerminateJobObject", "int", [PVOID, "uint32"]);
177
+ const terminateProcess = bind("TerminateProcess", "int", [PVOID, "uint32"]);
178
+ const waitForSingleObject = bind("WaitForSingleObject", "uint32", [PVOID, "uint32"]);
179
+ const writeFile = bind("WriteFile", "int", [
180
+ PVOID,
181
+ PVOID,
182
+ "uint32",
183
+ koffi.pointer("uint32"),
184
+ PVOID
185
+ ]);
186
+ const assignProcessToJobObject = bind("AssignProcessToJobObject", "int", [PVOID, PVOID]);
187
+ return {
188
+ createJob(name) {
189
+ setLastError(0);
190
+ const handle = createJobObjectW(null, name);
191
+ if (!handle) throw new Win32Error("CreateJobObjectW", getLastError());
192
+ return {
193
+ handle,
194
+ existing: name !== null && getLastError() === ERROR_ALREADY_EXISTS
195
+ };
196
+ },
197
+ openJob(name) {
198
+ const handle = openJobObjectW(JOB_OBJECT_QUERY | JOB_OBJECT_TERMINATE, 0, name);
199
+ if (handle) return handle;
200
+ const code = getLastError();
201
+ if (code === ERROR_FILE_NOT_FOUND) return null;
202
+ throw new Win32Error("OpenJobObjectW", code);
203
+ },
204
+ setKillOnClose(job) {
205
+ const limits = Buffer.alloc(JOBOBJECT_EXTENDED_LIMIT_INFORMATION.size);
206
+ limits.writeUInt32LE(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, koffi.offsetof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION, "BasicLimitInformation") + koffi.offsetof(JOBOBJECT_BASIC_LIMIT_INFORMATION, "LimitFlags"));
207
+ if (!setInformationJobObject(job, JOBOBJECT_EXTENDED_LIMIT_INFORMATION_CLASS, limits, limits.length)) throw new Win32Error("SetInformationJobObject", getLastError());
208
+ },
209
+ terminateJob(job, exitCode) {
210
+ if (!terminateJobObject(job, exitCode)) throw new Win32Error("TerminateJobObject", getLastError());
211
+ },
212
+ activeProcesses(job) {
213
+ const information = Buffer.alloc(JOBOBJECT_BASIC_ACCOUNTING_INFORMATION.size);
214
+ if (!queryInformationJobObject(job, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION_CLASS, information, information.length, null)) throw new Win32Error("QueryInformationJobObject", getLastError());
215
+ return koffi.decode(information, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION).ActiveProcesses;
216
+ },
217
+ createPipe() {
218
+ const attributes = Buffer.alloc(SECURITY_ATTRIBUTES.size);
219
+ koffi.encode(attributes, SECURITY_ATTRIBUTES, {
220
+ nLength: SECURITY_ATTRIBUTES.size,
221
+ bInheritHandle: 1
222
+ });
223
+ const read = [null];
224
+ const write = [null];
225
+ if (!createPipeW(read, write, attributes, 0)) throw new Win32Error("CreatePipe", getLastError());
226
+ if (read[0] === null || write[0] === null) throw new Win32Error("CreatePipe", getLastError());
227
+ return {
228
+ read: read[0],
229
+ write: write[0]
230
+ };
231
+ },
232
+ nonInheritable(handle) {
233
+ if (!setHandleInformation(handle, HANDLE_FLAG_INHERIT, 0)) throw new Win32Error("SetHandleInformation", getLastError());
234
+ },
235
+ createProcess(options) {
236
+ const startup = Buffer.alloc(STARTUPINFOW.size);
237
+ koffi.encode(startup, STARTUPINFOW, {
238
+ cb: STARTUPINFOW.size,
239
+ dwFlags: options.stdio ? STARTF_USESTDHANDLES : 0,
240
+ hStdInput: options.stdio?.stdin ?? 0n,
241
+ hStdOutput: options.stdio?.stdout ?? 0n,
242
+ hStdError: options.stdio?.stderr ?? 0n
243
+ });
244
+ const information = Buffer.alloc(PROCESS_INFORMATION.size);
245
+ if (!createProcessW(options.applicationName, options.commandLine, null, null, options.inheritHandles ? 1 : 0, options.flags, options.environment, options.cwd, startup, information)) throw new Win32Error("CreateProcessW", getLastError());
246
+ const process$1 = koffi.decode(information, PROCESS_INFORMATION);
247
+ return {
248
+ handle: process$1.hProcess,
249
+ thread: process$1.hThread,
250
+ pid: process$1.dwProcessId
251
+ };
252
+ },
253
+ async write(handle, data) {
254
+ const written = Buffer.alloc(4);
255
+ await new Promise((resolve$1, reject) => {
256
+ writeFile.async(handle, data, data.byteLength, written, null, (error, result) => {
257
+ if (error != null) {
258
+ reject(error);
259
+ return;
260
+ }
261
+ if (!result) {
262
+ reject(new Win32Error("WriteFile", getLastError()));
263
+ return;
264
+ }
265
+ resolve$1();
266
+ });
267
+ });
268
+ return written.readUInt32LE(0);
269
+ },
270
+ peek(handle) {
271
+ const available = Buffer.alloc(4);
272
+ if (!peekNamedPipe(handle, null, 0, null, available, null)) throw new Win32Error("PeekNamedPipe", getLastError());
273
+ return available.readUInt32LE(0);
274
+ },
275
+ read(handle, buffer) {
276
+ const read = Buffer.alloc(4);
277
+ if (!readFile(handle, buffer, buffer.byteLength, read, null)) throw new Win32Error("ReadFile", getLastError());
278
+ return read.readUInt32LE(0);
279
+ },
280
+ assignJob(job, process$1) {
281
+ if (!assignProcessToJobObject(job, process$1)) throw new Win32Error("AssignProcessToJobObject", getLastError());
282
+ },
283
+ resume(thread) {
284
+ if (resumeThread(thread) === 4294967295) throw new Win32Error("ResumeThread", getLastError());
285
+ },
286
+ terminateProcess(process$1, exitCode) {
287
+ if (!terminateProcess(process$1, exitCode)) throw new Win32Error("TerminateProcess", getLastError());
288
+ },
289
+ wait(handle, timeoutMs) {
290
+ const status = waitForSingleObject(handle, timeoutMs);
291
+ if (status === 4294967295) throw new Win32Error("WaitForSingleObject", getLastError());
292
+ return status;
293
+ },
294
+ exitCode(process$1) {
295
+ const code = Buffer.alloc(4);
296
+ if (!getExitCodeProcess(process$1, code)) throw new Win32Error("GetExitCodeProcess", getLastError());
297
+ return code.readUInt32LE();
298
+ },
299
+ close(handle) {
300
+ return closeHandle(handle) !== 0;
301
+ }
302
+ };
303
+ }
304
+ function requireLayout(type, expected) {
305
+ if (type.size !== expected) throw new Error(`${type.name} layout mismatch: ${type.size}, expected ${expected}`);
306
+ }
307
+
308
+ //#endregion
309
+ //#region src/environment/windows-job.ts
310
+ var WindowsJobCleanupError = class extends Error {
311
+ constructor(cleanupVerified) {
312
+ super("Windows command could not be started");
313
+ this.cleanupVerified = cleanupVerified;
314
+ this.name = "WindowsJobCleanupError";
315
+ }
316
+ };
317
+ const windowsJobName = (nonce) => `Local\\Sorbet-command-${nonce}`;
318
+ function create(api, name) {
319
+ const job = api.createJob(name);
320
+ if (job.existing) {
321
+ api.close(job.handle);
322
+ throw new Error("Windows Job already exists");
323
+ }
324
+ try {
325
+ api.setKillOnClose(job.handle);
326
+ } catch (error) {
327
+ api.close(job.handle);
328
+ throw error;
329
+ }
330
+ return job.handle;
331
+ }
332
+ async function terminate(api, job) {
333
+ api.terminateJob(job, 1);
334
+ const deadline = Date.now() + 5e3;
335
+ do {
336
+ if (api.activeProcesses(job) === 0) return true;
337
+ await setTimeout$1(20);
338
+ } while (Date.now() < deadline);
339
+ return false;
340
+ }
341
+ async function stopProcess(api, handle) {
342
+ api.terminateProcess(handle, 1);
343
+ const deadline = Date.now() + 5e3;
344
+ do {
345
+ const status = api.wait(handle, 0);
346
+ if (status === WAIT_OBJECT_0) return;
347
+ if (status !== WAIT_TIMEOUT) break;
348
+ await setTimeout$1(20);
349
+ } while (Date.now() < deadline);
350
+ throw new Error("Windows process termination could not be verified");
351
+ }
352
+ async function probeWindowsJob() {
353
+ const api = await windowsApi();
354
+ const job = create(api, null);
355
+ let processHandle = 0n;
356
+ let threadHandle = 0n;
357
+ try {
358
+ const probe = api.createProcess({
359
+ applicationName: process.execPath,
360
+ commandLine: Buffer.from(`${quoteWindowsArgument(process.execPath)}\0`, "utf16le"),
361
+ cwd: process.cwd(),
362
+ environment: null,
363
+ flags: CREATE_NO_WINDOW | CREATE_SUSPENDED,
364
+ inheritHandles: false
365
+ });
366
+ processHandle = probe.handle;
367
+ threadHandle = probe.thread;
368
+ api.assignJob(job, processHandle);
369
+ } finally {
370
+ try {
371
+ if (processHandle) await stopProcess(api, processHandle);
372
+ } finally {
373
+ if (threadHandle) api.close(threadHandle);
374
+ if (processHandle) api.close(processHandle);
375
+ api.close(job);
376
+ }
377
+ }
378
+ }
379
+ async function cleanupWindowsJob(name) {
380
+ const api = await windowsApi();
381
+ const job = api.openJob(name);
382
+ if (job === null) return true;
383
+ try {
384
+ return await terminate(api, job);
385
+ } finally {
386
+ api.close(job);
387
+ }
388
+ }
389
+ function quoteWindowsArgument(value) {
390
+ return `"${value.replace(/(\\*)"/g, "$1$1\\\"").replace(/(\\+)$/, "$1$1")}"`;
391
+ }
392
+ function buildWindowsCommandLine(executable, args) {
393
+ if (win32.basename(executable).toLowerCase() === "cmd.exe") {
394
+ const execute = args.findIndex((arg) => arg.toLowerCase() === "/c");
395
+ if (execute >= 0) {
396
+ const prefix = args.slice(0, execute + 1).join(" ");
397
+ const command = args.slice(execute + 1).join(" ");
398
+ return `${quoteWindowsArgument(executable)} ${prefix} "${command}"`;
399
+ }
400
+ }
401
+ return [executable, ...args].map(quoteWindowsArgument).join(" ");
402
+ }
403
+ function resolveCommandExecutable(command) {
404
+ const pathKey = Object.keys(command.env).find((key) => key.toUpperCase() === "PATH");
405
+ const path = pathKey === void 0 ? void 0 : command.env[pathKey];
406
+ const executable = resolveExecutable(command.executable, {
407
+ cwd: command.cwd,
408
+ env: path === void 0 ? {} : { PATH: path }
409
+ });
410
+ if (executable === void 0) throw new Error("Windows executable was not found");
411
+ return executable;
412
+ }
413
+ async function spawnWindowsJob(command) {
414
+ const api = await windowsApi();
415
+ const executable = resolveCommandExecutable(command);
416
+ const job = create(api, windowsJobName(command.workerNonce));
417
+ const open = new Set([job]);
418
+ const track = (handle) => {
419
+ open.add(handle);
420
+ return handle;
421
+ };
422
+ const release = (handle) => {
423
+ if (open.delete(handle)) api.close(handle);
424
+ };
425
+ let processHandle = 0n;
426
+ let stdinHandle = 0n;
427
+ let finished = false;
428
+ let closed = false;
429
+ try {
430
+ const stdin = api.createPipe();
431
+ track(stdin.read);
432
+ track(stdin.write);
433
+ const stdout = api.createPipe();
434
+ track(stdout.read);
435
+ track(stdout.write);
436
+ const stderr = api.createPipe();
437
+ track(stderr.read);
438
+ track(stderr.write);
439
+ api.nonInheritable(stdin.write);
440
+ api.nonInheritable(stdout.read);
441
+ api.nonInheritable(stderr.read);
442
+ const environment = Buffer.from(Object.entries(command.env).sort(([a], [b]) => a.toUpperCase().localeCompare(b.toUpperCase())).map(([key, value]) => `${key}=${value}`).join("\0") + "\0\0", "utf16le");
443
+ const process$1 = api.createProcess({
444
+ applicationName: executable,
445
+ commandLine: Buffer.from(buildWindowsCommandLine(executable, command.args) + "\0", "utf16le"),
446
+ cwd: command.cwd,
447
+ environment,
448
+ flags: CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED,
449
+ inheritHandles: true,
450
+ stdio: {
451
+ stdin: stdin.read,
452
+ stdout: stdout.write,
453
+ stderr: stderr.write
454
+ }
455
+ });
456
+ processHandle = process$1.handle;
457
+ track(processHandle);
458
+ track(process$1.thread);
459
+ api.assignJob(job, processHandle);
460
+ api.resume(process$1.thread);
461
+ release(stdin.read);
462
+ release(stdout.write);
463
+ release(stderr.write);
464
+ stdinHandle = stdin.write;
465
+ const input = (async () => {
466
+ try {
467
+ const data = command.input === void 0 ? void 0 : Buffer.from(command.input, "utf8");
468
+ if (data === void 0) return;
469
+ const length = data.length;
470
+ let offset = 0;
471
+ while (offset < length) {
472
+ if (!open.has(stdinHandle)) return;
473
+ const written = await api.write(stdinHandle, data.subarray(offset, offset + 65536));
474
+ if (written <= 0) return;
475
+ offset += written;
476
+ }
477
+ } catch {} finally {
478
+ release(stdinHandle);
479
+ }
480
+ })();
481
+ const output = (handle) => (async function* () {
482
+ try {
483
+ while (true) {
484
+ if (closed) break;
485
+ let available;
486
+ try {
487
+ available = api.peek(handle);
488
+ } catch {
489
+ if (closed) break;
490
+ throw new Error("Windows pipe inspection failed");
491
+ }
492
+ if (available > 0) {
493
+ const buffer = Buffer.alloc(Math.min(available, 65536));
494
+ const bytesRead = api.read(handle, buffer);
495
+ if (bytesRead > 0) {
496
+ yield buffer.subarray(0, bytesRead);
497
+ continue;
498
+ }
499
+ }
500
+ if (finished) {
501
+ if (api.peek(handle) === 0) break;
502
+ continue;
503
+ }
504
+ await setTimeout$1(10);
505
+ }
506
+ } finally {
507
+ release(handle);
508
+ }
509
+ })();
510
+ return {
511
+ pid: process$1.pid,
512
+ stdout: output(stdout.read),
513
+ stderr: output(stderr.read),
514
+ async wait() {
515
+ while (!closed && api.wait(processHandle, 0) === WAIT_TIMEOUT) await setTimeout$1(20);
516
+ if (closed) throw new Error("Windows Job closed");
517
+ return api.exitCode(processHandle);
518
+ },
519
+ async terminate() {
520
+ try {
521
+ return await terminate(api, job);
522
+ } finally {
523
+ finished = true;
524
+ }
525
+ },
526
+ async close() {
527
+ closed = true;
528
+ finished = true;
529
+ release(stdinHandle);
530
+ await Promise.race([input, setTimeout$1(1e3, void 0, { ref: false })]).catch(() => {});
531
+ for (const handle of [...open].reverse()) release(handle);
532
+ }
533
+ };
534
+ } catch {
535
+ let cleanupVerified = true;
536
+ try {
537
+ if (processHandle) await stopProcess(api, processHandle);
538
+ } catch {
539
+ cleanupVerified = false;
540
+ }
541
+ closed = true;
542
+ finished = true;
543
+ release(stdinHandle);
544
+ try {
545
+ for (const handle of [...open].reverse()) {
546
+ open.delete(handle);
547
+ if (!api.close(handle)) cleanupVerified = false;
548
+ }
549
+ } catch {
550
+ cleanupVerified = false;
551
+ }
552
+ throw new WindowsJobCleanupError(cleanupVerified);
553
+ }
554
+ }
555
+
556
+ //#endregion
557
+ //#region src/environment/windows-supervised-command.ts
558
+ async function runWindowsSupervisedCommand(command, controller, send, startedAt, stream, output) {
559
+ let job;
560
+ let timer;
561
+ let termination;
562
+ let errorCode;
563
+ let forced = false;
564
+ let cleanupVerified = true;
565
+ let waiting;
566
+ let exitCode;
567
+ let failCleanup = () => {};
568
+ const cleanupFailure = new Promise((_resolve, reject) => {
569
+ failCleanup = reject;
570
+ });
571
+ cleanupFailure.catch(() => {});
572
+ const terminate$1 = () => {
573
+ if (job) {
574
+ termination ??= job.terminate().then((drained) => {
575
+ cleanupVerified = drained;
576
+ if (!drained) {
577
+ errorCode ??= "spawn_error";
578
+ failCleanup(/* @__PURE__ */ new Error("Windows Job cleanup failed"));
579
+ }
580
+ return drained;
581
+ }, () => {
582
+ cleanupVerified = false;
583
+ errorCode ??= "spawn_error";
584
+ failCleanup(/* @__PURE__ */ new Error("Windows Job cleanup failed"));
585
+ return false;
586
+ });
587
+ termination.catch(() => {});
588
+ }
589
+ };
590
+ const abort = () => {
591
+ errorCode ??= "aborted";
592
+ forced = job !== void 0;
593
+ terminate$1();
594
+ };
595
+ try {
596
+ controller.signal.addEventListener("abort", abort, { once: true });
597
+ if (controller.signal.aborted) abort();
598
+ const timeout = () => {
599
+ errorCode ??= "timeout";
600
+ forced = job !== void 0;
601
+ terminate$1();
602
+ };
603
+ if (command.timeout !== void 0) {
604
+ const remaining = command.timeout - (Date.now() - startedAt);
605
+ if (remaining <= 0) timeout();
606
+ else timer = setTimeout(timeout, remaining);
607
+ }
608
+ if (errorCode !== void 0) throw new Error("Command cancelled before start");
609
+ job = await spawnWindowsJob(command);
610
+ cleanupVerified = false;
611
+ if (command.timeout !== void 0 && Date.now() - startedAt >= command.timeout) timeout();
612
+ if (errorCode !== void 0) {
613
+ forced = true;
614
+ terminate$1();
615
+ }
616
+ waiting = job.wait();
617
+ const settled = waiting.then(async (code) => {
618
+ terminate$1();
619
+ await termination;
620
+ clearTimeout(timer);
621
+ controller.signal.removeEventListener("abort", abort);
622
+ return code;
623
+ });
624
+ settled.catch(() => {});
625
+ await Promise.race([cleanupFailure, send({
626
+ kind: "started",
627
+ workerNonce: command.workerNonce,
628
+ pid: job.pid,
629
+ workerPid: process.pid,
630
+ startedAt
631
+ })]);
632
+ const drain = async (name, chunks) => {
633
+ const transform = stream(name);
634
+ for await (const chunk of chunks) for await (const ignored of transform.transform(chunk));
635
+ for await (const ignored of transform.final());
636
+ };
637
+ [exitCode] = await Promise.race([cleanupFailure, Promise.all([
638
+ settled,
639
+ drain("stdout", job.stdout),
640
+ drain("stderr", job.stderr)
641
+ ])]);
642
+ } catch (error) {
643
+ if (error instanceof WindowsJobCleanupError) cleanupVerified = error.cleanupVerified;
644
+ errorCode ??= "spawn_error";
645
+ forced = job !== void 0;
646
+ } finally {
647
+ clearTimeout(timer);
648
+ controller.signal.removeEventListener("abort", abort);
649
+ terminate$1();
650
+ await termination;
651
+ try {
652
+ if (cleanupVerified) exitCode ??= await waiting;
653
+ } catch {
654
+ errorCode ??= "spawn_error";
655
+ }
656
+ try {
657
+ await job?.close();
658
+ } catch {
659
+ cleanupVerified = false;
660
+ errorCode ??= "spawn_error";
661
+ }
662
+ }
663
+ const diagnostics = {
664
+ aborted: "Command aborted",
665
+ timeout: "Command timed out",
666
+ spawn_error: "Command could not be started"
667
+ };
668
+ await send({
669
+ kind: "exited",
670
+ result: {
671
+ workerNonce: command.workerNonce,
672
+ ...output(),
673
+ pid: job?.pid,
674
+ workerPid: process.pid,
675
+ startedAt,
676
+ exitedAt: Date.now(),
677
+ exitCode,
678
+ forced,
679
+ cleanupVerified,
680
+ errorCode,
681
+ message: errorCode === void 0 ? void 0 : diagnostics[errorCode]
682
+ }
683
+ });
684
+ }
685
+
686
+ //#endregion
687
+ //#region src/environment/supervised-command.ts
688
+ async function runSupervisedCommand(command, controller, send) {
689
+ const startedAt = Date.now();
690
+ let bytes = 0;
691
+ let textBytes = 0;
692
+ let sequence = 0;
693
+ let truncated = false;
694
+ const stream = (name) => {
695
+ const decoder = new StringDecoder("utf8");
696
+ const consume = async (text) => {
697
+ const encoded = Buffer.from(text);
698
+ const available = command.maxOutputBytes === void 0 ? encoded.byteLength : command.maxOutputBytes - textBytes;
699
+ if (encoded.byteLength > available) {
700
+ truncated = true;
701
+ text = new StringDecoder("utf8").write(encoded.subarray(0, available));
702
+ }
703
+ textBytes += Buffer.byteLength(text);
704
+ if (text) await send({
705
+ kind: "output",
706
+ stream: name,
707
+ text,
708
+ sequence: sequence++
709
+ });
710
+ };
711
+ return {
712
+ binary: true,
713
+ transform: async function* (chunk) {
714
+ const available = command.maxOutputBytes === void 0 ? chunk.byteLength : Math.max(0, command.maxOutputBytes - bytes);
715
+ const retained = chunk.subarray(0, available);
716
+ bytes += chunk.byteLength;
717
+ truncated ||= retained.byteLength < chunk.byteLength;
718
+ await consume(decoder.write(Buffer.from(retained)));
719
+ yield new Uint8Array();
720
+ },
721
+ final: async function* () {
722
+ const tail = decoder.end();
723
+ if (!truncated) await consume(tail);
724
+ yield new Uint8Array();
725
+ }
726
+ };
727
+ };
728
+ if (process.platform === "win32") {
729
+ await runWindowsSupervisedCommand(command, controller, send, startedAt, stream, () => ({
730
+ outputBytes: bytes,
731
+ truncated
732
+ }));
733
+ return;
734
+ }
735
+ try {
736
+ const child = execa(command.executable, command.args, {
737
+ cwd: command.cwd,
738
+ env: command.env,
739
+ extendEnv: false,
740
+ killDescendants: true,
741
+ cleanup: true,
742
+ windowsHide: true,
743
+ cancelSignal: controller.signal,
744
+ timeout: command.timeout,
745
+ killSignal: "SIGTERM",
746
+ forceKillAfterDelay: command.forceKillAfterDelayMs,
747
+ reject: false,
748
+ buffer: false,
749
+ input: command.input,
750
+ stdin: command.input === void 0 ? "ignore" : "pipe",
751
+ stdout: stream("stdout"),
752
+ stderr: stream("stderr")
753
+ });
754
+ child.nodeChildProcess.once("spawn", () => {
755
+ if (child.pid !== void 0) send({
756
+ kind: "started",
757
+ workerNonce: command.workerNonce,
758
+ pid: child.pid,
759
+ workerPid: process.pid,
760
+ startedAt
761
+ });
762
+ });
763
+ child.nodeChildProcess.once("exit", () => {
764
+ child.kill("SIGTERM");
765
+ });
766
+ const result = await child;
767
+ const forcedCleanup = child.kill("SIGKILL");
768
+ let errorCode;
769
+ if (result.timedOut) errorCode = "timeout";
770
+ else if (controller.signal.aborted) errorCode = "aborted";
771
+ else if (result.exitCode === void 0 && result.signal === void 0) errorCode = "spawn_error";
772
+ await send({
773
+ kind: "exited",
774
+ result: {
775
+ workerNonce: command.workerNonce,
776
+ outputBytes: bytes,
777
+ pid: child.pid,
778
+ workerPid: process.pid,
779
+ startedAt,
780
+ exitedAt: Date.now(),
781
+ exitCode: result.exitCode,
782
+ signal: result.signal,
783
+ forced: result.isForcefullyTerminated || forcedCleanup,
784
+ truncated,
785
+ errorCode,
786
+ message: errorCode === void 0 ? void 0 : {
787
+ aborted: "Command aborted",
788
+ timeout: "Command timed out",
789
+ spawn_error: "Command could not be started"
790
+ }[errorCode]
791
+ }
792
+ });
793
+ } catch {
794
+ await send({
795
+ kind: "exited",
796
+ result: {
797
+ workerNonce: command.workerNonce,
798
+ outputBytes: bytes,
799
+ workerPid: process.pid,
800
+ startedAt,
801
+ exitedAt: Date.now(),
802
+ forced: false,
803
+ truncated,
804
+ errorCode: "spawn_error",
805
+ message: "Command could not be started"
806
+ }
807
+ });
808
+ }
809
+ }
810
+
811
+ //#endregion
812
+ export { windowsJobName as i, cleanupWindowsJob as n, probeWindowsJob as r, runSupervisedCommand as t };
813
+ //# sourceMappingURL=supervised-command-DNcHAKrD.js.map