@linxiraos/pi-utils 1.4.4 → 1.4.7

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/src/postmortem.ts CHANGED
@@ -27,10 +27,26 @@ interface CleanupRegistration {
27
27
  id: string;
28
28
  callback: (reason: Reason) => Promise<void> | void;
29
29
  exitOnly: boolean;
30
+ /** How long a pass waits for this callback, when longer than {@link CLEANUP_DEADLINE_MS}. */
31
+ deadlineMs: number | undefined;
32
+ /** Printed to stderr when exit waits on this callback alone; see {@link CleanupRegistrationOptions.waitMessage}. */
33
+ waitMessage: string | undefined;
30
34
  cancelled: boolean;
31
35
  lastPass: number;
32
36
  }
33
37
 
38
+ /** The deadline of one cleanup pass, which callbacks with their own `deadlineMs` hold open. */
39
+ interface CleanupPassDeadline {
40
+ /**
41
+ * Keep the pass open until `pending` settles, for at most `deadlineMs`. A
42
+ * `waitMessage` is printed to stderr if the pass is still waiting on it once
43
+ * every other callback has finished.
44
+ */
45
+ extend(pending: Promise<unknown>, deadlineMs: number, waitMessage?: string): void;
46
+ /** Whether a callback with its own deadline still holds the pass open. */
47
+ extended(): boolean;
48
+ }
49
+
34
50
  // Active cleanup callbacks in registration order. Registrations survive
35
51
  // keep-alive passes; `lastPass` enforces at-most-once invocation per pass.
36
52
  const callbackList: CleanupRegistration[] = [];
@@ -42,6 +58,8 @@ let activeCleanupKeepAlive = false;
42
58
  // Promises of callbacks invoked late (registered while a pass runs), joined by
43
59
  // the active pass before it settles so `cleanup()`/signal exits await them.
44
60
  let activeLatePromises: Promise<void>[] | undefined;
61
+ // Deadline of the running pass, so callbacks invoked late can extend it too.
62
+ let activePassDeadline: CleanupPassDeadline | undefined;
45
63
  const CLEANUP_DEADLINE_MS = 10_000;
46
64
  /**
47
65
  * Symbol stamped by the extension-load guard onto the throwing replacement it
@@ -122,7 +140,7 @@ export function exitProcess(code: number): never {
122
140
  let cleanupPromise: Promise<void> | undefined;
123
141
  let stdioDisconnectRegistrations = 0;
124
142
 
125
- /** User-facing command printed before fatal cleanup so interrupted work can be resumed. */
143
+ /** User-facing command printed after fatal or SIGTERM cleanup so interrupted work can be resumed. */
126
144
  export interface FatalRecoveryHint {
127
145
  /** Stable label identifying the recoverable session or process. */
128
146
  label: string;
@@ -184,10 +202,75 @@ function runCleanup(reason: Reason, keepAlive = false): Promise<void> {
184
202
  }
185
203
  };
186
204
 
205
+ // The pass ends once every callback settles, or at the deadline: CLEANUP_DEADLINE_MS,
206
+ // held open while a callback with a longer `deadlineMs` is still pending.
207
+ const deadline = Promise.withResolvers<void>();
208
+ const deadlineTimers: NodeJS.Timeout[] = [];
209
+ let baseDeadlineElapsed = false;
210
+ let openExtensions = 0;
211
+ let passDone = false;
212
+ const expireIfDue = (): void => {
213
+ if (passDone || !baseDeadlineElapsed || openExtensions > 0) return;
214
+ passDone = true;
215
+ logger.error("Cleanup deadline exceeded; proceeding with exit", { reason });
216
+ settle();
217
+ deadline.resolve();
218
+ };
219
+ // Holds that still keep the pass open and have a message for the user. The
220
+ // message is printed once the pass waits on nothing else, so a terminal owner
221
+ // has already released the screen and the user sees why exit is slow.
222
+ const announced: { message: string; until: number; open: () => boolean }[] = [];
223
+ let othersSettled = false;
224
+ const announce = (): void => {
225
+ if (passDone || !othersSettled) return;
226
+ for (const hold of announced.splice(0)) {
227
+ if (!hold.open()) continue;
228
+ const seconds = Math.max(1, Math.ceil((hold.until - Date.now()) / 1000));
229
+ try {
230
+ fs.writeSync(2, `${hold.message} (up to ${seconds} s)…\n`);
231
+ } catch {}
232
+ }
233
+ };
234
+ const passDeadline: CleanupPassDeadline = {
235
+ extend(pending, deadlineMs, waitMessage) {
236
+ if (passDone || deadlineMs <= 0) return;
237
+ openExtensions++;
238
+ let open = true;
239
+ const close = (): void => {
240
+ if (!open) return;
241
+ open = false;
242
+ openExtensions--;
243
+ // Check on a later macrotask: when this was the last pending callback, the
244
+ // pass completes first and no deadline is reported.
245
+ deadlineTimers.push(setTimeout(expireIfDue, 0));
246
+ };
247
+ deadlineTimers.push(setTimeout(close, deadlineMs));
248
+ pending.then(close, close);
249
+ if (waitMessage !== undefined) {
250
+ announced.push({ message: waitMessage, until: Date.now() + deadlineMs, open: () => open });
251
+ // On a later macrotask, so a callback that is already done closes first.
252
+ if (othersSettled) deadlineTimers.push(setTimeout(announce, 0));
253
+ }
254
+ },
255
+ extended: () => !passDone && openExtensions > 0,
256
+ };
257
+ activePassDeadline = passDeadline;
258
+
187
259
  // Snapshot the pass. Registrations added while a keep-alive cleanup runs are
188
260
  // invoked by register() when appropriate and remain active for later passes.
189
- const promises = callbackList.toReversed().map(registration => {
190
- return Promise.try(() => invokeCleanup(registration, reason, keepAlive, pass));
261
+ const snapshot = callbackList.toReversed();
262
+ const promises = snapshot.map(registration => {
263
+ return Promise.try(() => {
264
+ const pending = invokeCleanup(registration, reason, keepAlive, pass);
265
+ if (pending && registration.deadlineMs !== undefined) {
266
+ passDeadline.extend(pending, registration.deadlineMs, registration.waitMessage);
267
+ }
268
+ return pending;
269
+ });
270
+ });
271
+ void Promise.allSettled(promises.filter((_, index) => snapshot[index]?.deadlineMs === undefined)).then(() => {
272
+ othersSettled = true;
273
+ deadlineTimers.push(setTimeout(announce, 0));
191
274
  });
192
275
 
193
276
  const cleanupSettled = Promise.allSettled(promises).then(async results => {
@@ -202,14 +285,20 @@ function runCleanup(reason: Reason, keepAlive = false): Promise<void> {
202
285
  while (late.length > 0) await Promise.allSettled(late.splice(0));
203
286
  settle();
204
287
  });
205
- const deadline = Promise.withResolvers<void>();
206
- const deadlineTimer = setTimeout(() => {
207
- logger.error("Cleanup deadline exceeded; proceeding with exit", { reason });
208
- settle();
209
- deadline.resolve();
210
- }, CLEANUP_DEADLINE_MS);
288
+ deadlineTimers.push(
289
+ setTimeout(() => {
290
+ baseDeadlineElapsed = true;
291
+ // The pass no longer waits on the other callbacks, so a hold still open is
292
+ // what exit waits on; terminal owners released the screen synchronously.
293
+ othersSettled = true;
294
+ announce();
295
+ expireIfDue();
296
+ }, CLEANUP_DEADLINE_MS),
297
+ );
211
298
  const passPromise = Promise.race([cleanupSettled, deadline.promise]).finally(() => {
212
- clearTimeout(deadlineTimer);
299
+ passDone = true;
300
+ for (const timer of deadlineTimers) clearTimeout(timer);
301
+ if (activePassDeadline === passDeadline) activePassDeadline = undefined;
213
302
  // A re-armed pass must drop only its own settled promise; an older
214
303
  // deadline-limited pass may finish after a newer one has already started.
215
304
  if (keepAlive && cleanupPass === pass && cleanupPromise === passPromise) cleanupPromise = undefined;
@@ -480,7 +569,10 @@ export function interceptUnhandledRejections(interceptor: (reason: unknown) => b
480
569
 
481
570
  /**
482
571
  * Register a synchronous recovery command to print when the process exits
483
- * through an uncaught exception or unhandled rejection.
572
+ * through an uncaught exception, an unhandled rejection, or SIGTERM.
573
+ *
574
+ * Providers are read once cleanup finishes (or hits its deadline), so they
575
+ * report what teardown left behind: a session it saved or one it dropped.
484
576
  */
485
577
  export function registerFatalRecoveryHint(provider: FatalRecoveryHintProvider): () => void {
486
578
  fatalRecoveryHintProviders.add(provider);
@@ -494,10 +586,10 @@ function escapeFatalHintText(value: string): string {
494
586
  });
495
587
  }
496
588
 
497
- function formatFatalRecoveryHints(): string {
589
+ function formatFatalRecoveryHints(providers: Iterable<FatalRecoveryHintProvider>): string {
498
590
  const lines: string[] = [];
499
591
  const seenCommands = new Set<string>();
500
- for (const provider of fatalRecoveryHintProviders) {
592
+ for (const provider of providers) {
501
593
  try {
502
594
  const hint = provider();
503
595
  if (!hint?.command || seenCommands.has(hint.command)) continue;
@@ -519,21 +611,54 @@ function formatFatalError(label: string, err: Error): string {
519
611
  return `\n[${label}] ${name}: ${message}${formattedStack}\n`;
520
612
  }
521
613
 
614
+ /** Write a final report to stderr once terminal owners have handed the terminal back. */
615
+ function writeTerminalReport(output: string): void {
616
+ restoreTerminalStderr();
617
+ // A revoked terminal can make stream writes raise another fatal error. Use
618
+ // the descriptor directly so failure stays synchronous and contained.
619
+ try {
620
+ fs.writeSync(2, output);
621
+ } catch {}
622
+ }
623
+
624
+ let recoveryHintsWritten = false;
625
+
626
+ /**
627
+ * Print the recovery commands at most once per process. Callers snapshot the
628
+ * providers before cleanup, because a session's own cleanup unregisters its
629
+ * provider, and call this after cleanup, because teardown can still save the
630
+ * session (an unsent draft, an aborted first reply) or drop an empty one.
631
+ */
632
+ function writeRecoveryHints(providers: readonly FatalRecoveryHintProvider[], heading = ""): void {
633
+ if (recoveryHintsWritten) return;
634
+ const hints = formatFatalRecoveryHints(providers);
635
+ if (!hints) return;
636
+ recoveryHintsWritten = true;
637
+ writeTerminalReport(`${heading}${hints}`);
638
+ }
639
+
522
640
  async function exitAfterFatal(output: string, logMessage: string, err: Error, reason: Reason): Promise<never> {
523
- const forcedExit = setTimeout(() => exitProcess(1), CLEANUP_DEADLINE_MS);
641
+ const hintProviders = [...fatalRecoveryHintProviders];
642
+ // The forced exit backs up the pass deadline, so it waits while a callback with
643
+ // its own `deadlineMs` holds the pass open; that pass still ends at its deadline.
644
+ const forceExit = (): void => {
645
+ if (activePassDeadline?.extended()) {
646
+ forcedExit = setTimeout(forceExit, CLEANUP_DEADLINE_MS);
647
+ return;
648
+ }
649
+ writeRecoveryHints(hintProviders);
650
+ exitProcess(1);
651
+ };
652
+ let forcedExit = setTimeout(forceExit, CLEANUP_DEADLINE_MS);
524
653
  try {
525
654
  // Cleanup callbacks are invoked synchronously before runCleanup returns its
526
655
  // completion promise. TUI owners therefore hand the cursor back before the
527
656
  // fatal report is written, while slower resource cleanup continues afterward.
528
657
  const cleanup = runCleanup(reason);
529
- restoreTerminalStderr();
530
- // A revoked terminal can make stream writes raise another fatal error. Use
531
- // the descriptor directly so failure stays synchronous and contained.
532
- try {
533
- fs.writeSync(2, output);
534
- } catch {}
658
+ writeTerminalReport(output);
535
659
  logger.error(logMessage, { err });
536
660
  await cleanup;
661
+ writeRecoveryHints(hintProviders);
537
662
  } finally {
538
663
  clearTimeout(forcedExit);
539
664
  exitProcess(1);
@@ -552,12 +677,12 @@ function handleWorkerSendEpipe(err: Error): boolean {
552
677
  */
553
678
  export async function fatal(error: unknown): Promise<never> {
554
679
  const err = error instanceof Error ? error : new Error(String(error));
555
- const output = `${Bun.inspect(error, { colors: process.stderr.isTTY === true })}\n${formatFatalRecoveryHints()}`;
680
+ const report = `${Bun.inspect(error, { colors: process.stderr.isTTY === true })}\n`;
556
681
  if (!Bun.isMainThread) {
557
- process.stderr.write(output);
682
+ process.stderr.write(`${report}${formatFatalRecoveryHints(fatalRecoveryHintProviders)}`);
558
683
  process.exit(1);
559
684
  }
560
- return exitAfterFatal(output, "Fatal error", err, Reason.UNHANDLED_REJECTION);
685
+ return exitAfterFatal(report, "Fatal error", err, Reason.UNHANDLED_REJECTION);
561
686
  }
562
687
 
563
688
  if (Bun.isMainThread) {
@@ -607,7 +732,7 @@ if (Bun.isMainThread) {
607
732
  return;
608
733
  }
609
734
  await exitAfterFatal(
610
- `${formatFatalError("Uncaught Exception", err)}${formatFatalRecoveryHints()}`,
735
+ formatFatalError("Uncaught Exception", err),
611
736
  "Uncaught exception",
612
737
  err,
613
738
  Reason.UNCAUGHT_EXCEPTION,
@@ -630,7 +755,7 @@ if (Bun.isMainThread) {
630
755
  }
631
756
  }
632
757
  await exitAfterFatal(
633
- `${formatFatalError("Unhandled Rejection", err)}${formatFatalRecoveryHints()}`,
758
+ formatFatalError("Unhandled Rejection", err),
634
759
  "Unhandled rejection",
635
760
  err,
636
761
  Reason.UNHANDLED_REJECTION,
@@ -640,7 +765,12 @@ if (Bun.isMainThread) {
640
765
  void runCleanup(Reason.EXIT); // fire and forget (exit imminent)
641
766
  })
642
767
  .on("SIGTERM", async () => {
768
+ // A stopped session otherwise leaves its last frame above the shell prompt,
769
+ // which reads as a crash. A repeated SIGTERM joins the same cleanup and the
770
+ // hints still print once.
771
+ const hintProviders = [...fatalRecoveryHintProviders];
643
772
  await runCleanup(Reason.SIGTERM);
773
+ writeRecoveryHints(hintProviders, "\n[Stopped by SIGTERM]");
644
774
  exitProcess(143); // 128 + SIGTERM (15)
645
775
  })
646
776
  .on("SIGHUP", async () => {
@@ -664,6 +794,20 @@ export interface CleanupRegistrationOptions {
664
794
  * The registration remains armed when a keep-alive pass skips it.
665
795
  */
666
796
  exitOnly?: boolean;
797
+ /**
798
+ * How long a pass waits for this callback, when that is longer than the
799
+ * default 10 s cleanup deadline. It extends the pass only while the callback
800
+ * is still pending: one that settles early ends its hold at once.
801
+ */
802
+ deadlineMs?: number;
803
+ /**
804
+ * With `deadlineMs`: a line printed to stderr, with the remaining wait
805
+ * appended, if exit is still waiting on this callback once every other
806
+ * callback has finished (a terminal owner has then released the screen), or
807
+ * at the default 10 s deadline when another callback is still running.
808
+ * Nothing is printed when the callback finishes first.
809
+ */
810
+ waitMessage?: string;
667
811
  }
668
812
 
669
813
  /**
@@ -690,6 +834,8 @@ export function register(
690
834
  id,
691
835
  callback,
692
836
  exitOnly: options.exitOnly ?? false,
837
+ deadlineMs: options.deadlineMs,
838
+ waitMessage: options.waitMessage,
693
839
  cancelled: false,
694
840
  lastPass: 0,
695
841
  };
@@ -709,6 +855,9 @@ export function register(
709
855
  // Join the active pass so cleanup()/signal exits await it; after a
710
856
  // completed exit pass there is nothing left to join.
711
857
  activeLatePromises?.push(tracked);
858
+ if (registration.deadlineMs !== undefined) {
859
+ activePassDeadline?.extend(tracked, registration.deadlineMs, registration.waitMessage);
860
+ }
712
861
  } catch (error) {
713
862
  const err = error instanceof Error ? error : new Error(String(error));
714
863
  logger.error("Cleanup callback failed", { err, id, stack: err.stack });
@@ -10,9 +10,11 @@
10
10
  * setter) and additionally drive `prctl` via `bun:ffi` on Linux, mirroring the
11
11
  * libc-FFI pattern in `ttyid.ts` / `stderr-guard.ts`.
12
12
  *
13
- * macOS has no clean userspace equivalent for the shebang-run path, and on
14
- * Windows / compiled binaries the kernel derives the name from the exec'd file,
15
- * so those paths already report correctly; there we only set `process.title`.
13
+ * macOS has no clean userspace equivalent for the shebang-run path, so there
14
+ * we only set `process.title`. Windows derives the name from the exec'd file,
15
+ * and there Bun's `process.title` setter is libuv's `SetConsoleTitleW`: every
16
+ * omp child attached to a pane's console (workers, `browser-relay`, servers)
17
+ * would overwrite that pane's tab title, so Windows skips it entirely.
16
18
  */
17
19
  import { dlopen, FFIType, ptr } from "bun:ffi";
18
20
  import * as os from "node:os";
@@ -21,17 +23,20 @@ import * as os from "node:os";
21
23
  const PR_SET_NAME = 15;
22
24
 
23
25
  /**
24
- * Set both the JS `process.title` and — on Linux — the kernel `comm` name.
26
+ * Set the JS `process.title` (except on Windows, see above) and — on Linux —
27
+ * the kernel `comm` name.
25
28
  *
26
29
  * Never throws: `bun:ffi` unavailability or a failed syscall degrades silently
27
30
  * to the `process.title`-only behavior, so it is safe to call at startup.
28
31
  */
29
32
  export function setProcessName(name: string): void {
33
+ const platform = os.platform();
34
+ if (platform === "win32") return;
30
35
  try {
31
36
  process.title = name;
32
37
  } catch {}
33
38
 
34
- if (os.platform() !== "linux") return;
39
+ if (platform !== "linux") return;
35
40
 
36
41
  // glibc first, then the generic soname for musl-style layouts (see stderr-guard.ts).
37
42
  for (const soname of ["libc.so.6", "libc.so"]) {
package/src/stream.ts CHANGED
@@ -2,6 +2,7 @@ const trailingEvents = new WeakSet<ServerSentEvent>();
2
2
 
3
3
  import { abortableSource } from "./abortable";
4
4
  import { parseStreamingJson } from "./json-parse";
5
+ import { isWhitespace } from "./json-lexer";
5
6
 
6
7
  const LF = 0x0a;
7
8
  const CR = 0x0d;
@@ -613,9 +614,11 @@ export async function* readSseEvents(
613
614
  */
614
615
  export function parseJsonlLenient<T>(buffer: string, options: { onMalformedRecord?: () => void } = {}): T[] {
615
616
  let entries: T[] | undefined;
617
+ let cursor = 0;
618
+ const len = buffer.length;
616
619
 
617
- while (buffer.length > 0) {
618
- const { values, error, read, done } = Bun.JSONL.parseChunk(buffer);
620
+ while (cursor < len) {
621
+ const { values, error, read, done } = Bun.JSONL.parseChunk(buffer, cursor);
619
622
  if (values.length > 0) {
620
623
  const ext = values as T[];
621
624
  if (!entries) {
@@ -625,18 +628,22 @@ export function parseJsonlLenient<T>(buffer: string, options: { onMalformedRecor
625
628
  }
626
629
  }
627
630
  if (error) {
628
- const nextNewline = buffer.indexOf("\n", read);
629
- const malformedEnd = nextNewline === -1 ? buffer.length : nextNewline;
630
- if (buffer.substring(read, malformedEnd).trim().length > 0) options.onMalformedRecord?.();
631
+ let malformedStart = read;
632
+ while (malformedStart < len && isWhitespace(buffer.charCodeAt(malformedStart))) {
633
+ malformedStart++;
634
+ }
635
+ const nextNewline = buffer.indexOf("\n", malformedStart);
636
+ const malformedEnd = nextNewline === -1 ? len : nextNewline;
637
+ if (buffer.substring(malformedStart, malformedEnd).trim().length > 0) options.onMalformedRecord?.();
631
638
  if (nextNewline === -1) break;
632
- buffer = buffer.substring(nextNewline + 1);
639
+ cursor = nextNewline + 1;
633
640
  continue;
634
641
  }
635
- if (read === 0) {
636
- if (buffer.trim().length > 0) options.onMalformedRecord?.();
642
+ if (read === cursor) {
643
+ if (buffer.substring(cursor).trim().length > 0) options.onMalformedRecord?.();
637
644
  break;
638
645
  }
639
- buffer = buffer.substring(read);
646
+ cursor = read;
640
647
  if (done) break;
641
648
  }
642
649
  return entries ?? [];
package/src/which.ts CHANGED
@@ -261,3 +261,30 @@ export function $which(command: string, options?: WhichOptions): string | null {
261
261
  }
262
262
  return result;
263
263
  }
264
+
265
+ /**
266
+ * Locate every match for `command` on PATH, in PATH order, uncached.
267
+ *
268
+ * Callers that probe candidates (e.g. the Python eval backend) use this so a broken
269
+ * first hit — a version-manager shim with no version selected, a Windows Store alias —
270
+ * does not hide a working binary further down PATH. On macOS the Xcode/CLT toolchain
271
+ * match is appended last, mirroring {@link $which}'s fallback.
272
+ *
273
+ * @param command - Binary name to resolve
274
+ * @param options - `PATH` (defaults to `process.env.PATH`) and `cwd` for relative entries
275
+ * @returns Distinct filesystem paths; empty when nothing matches
276
+ */
277
+ export function $whichAll(command: string, options?: Bun.WhichOptions): string[] {
278
+ const searchPath = options?.PATH ?? process.env.PATH ?? "";
279
+ const matches: string[] = [];
280
+ for (const dir of searchPath.split(path.delimiter)) {
281
+ if (!dir) continue;
282
+ const match = Bun.which(command, { cwd: options?.cwd, PATH: dir });
283
+ if (match && !matches.includes(match)) matches.push(match);
284
+ }
285
+ if (os.platform() === "darwin" && isXcodeBin(command)) {
286
+ const toolchainMatch = getMacosToolPaths().get(command);
287
+ if (toolchainMatch && !matches.includes(toolchainMatch)) matches.push(toolchainMatch);
288
+ }
289
+ return matches;
290
+ }
@@ -1,17 +0,0 @@
1
- /**
2
- * `fs.openSync` with close-on-exec, matching Node's default.
3
- *
4
- * libuv adds `O_CLOEXEC` inside `uv__fs_open`, so on Node every `fs` descriptor
5
- * dies at `exec`. Bun's `fs.open*` did not before 1.4.3 (still allowed by the
6
- * `bun@>=1.4` pin), and descriptors it returns survive
7
- * into any child spawned through a path that does not close strays itself — the
8
- * bash tool's shell `fork`/`exec`s user commands and hands them the lot. Use
9
- * this for every descriptor kept open past such a spawn (session transcripts,
10
- * logs, spools); a child must never hold a writable handle to them (#13224).
11
- *
12
- * Flags are numeric only: the bit cannot be OR-ed into `"a"`/`"w+"` strings.
13
- *
14
- * @example
15
- * const fd = openCloexecSync(logPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_APPEND);
16
- */
17
- export declare function openCloexecSync(filePath: string, flags: number, mode?: number): number;
package/src/fs-open.ts DELETED
@@ -1,32 +0,0 @@
1
- /** Close-on-exec file opens for descriptors held past a child spawn. */
2
- import * as fs from "node:fs";
3
-
4
- /**
5
- * `O_CLOEXEC`, which neither Node nor Bun exposes in `fs.constants`.
6
- *
7
- * Kernel ABI values: `0o2000000` on Linux, `0x0100_0000` on Darwin. Windows has
8
- * no `exec` and its CRT handles are inherited only when a spawn explicitly asks
9
- * for it, so the bit is 0 there — as it is on any other platform, where adding
10
- * an unknown flag bit would be worse than leaving the descriptor inheritable.
11
- */
12
- const O_CLOEXEC = process.platform === "linux" ? 0o2000000 : process.platform === "darwin" ? 0x0100_0000 : 0;
13
-
14
- /**
15
- * `fs.openSync` with close-on-exec, matching Node's default.
16
- *
17
- * libuv adds `O_CLOEXEC` inside `uv__fs_open`, so on Node every `fs` descriptor
18
- * dies at `exec`. Bun's `fs.open*` did not before 1.4.3 (still allowed by the
19
- * `bun@>=1.4` pin), and descriptors it returns survive
20
- * into any child spawned through a path that does not close strays itself — the
21
- * bash tool's shell `fork`/`exec`s user commands and hands them the lot. Use
22
- * this for every descriptor kept open past such a spawn (session transcripts,
23
- * logs, spools); a child must never hold a writable handle to them (#13224).
24
- *
25
- * Flags are numeric only: the bit cannot be OR-ed into `"a"`/`"w+"` strings.
26
- *
27
- * @example
28
- * const fd = openCloexecSync(logPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_APPEND);
29
- */
30
- export function openCloexecSync(filePath: string, flags: number, mode?: number): number {
31
- return fs.openSync(filePath, flags | O_CLOEXEC, mode);
32
- }