/ src / runtime-detect.ts
runtime-detect.ts
 1  /**
 2   * Runtime detection — identify whether opencli is running under Node.js or Bun.
 3   *
 4   * Bun injects `globalThis.Bun` at startup, making detection trivial.
 5   * This module centralises the check so other code can adapt behaviour
 6   * (e.g. logging, diagnostics) without littering runtime sniffing everywhere.
 7   */
 8  
 9  export type Runtime = 'bun' | 'node';
10  
11  /** Shape of `globalThis` when running under Bun. */
12  interface BunGlobal {
13    Bun?: { version: string };
14  }
15  
16  /**
17   * Detect the current JavaScript runtime.
18   */
19  export function detectRuntime(): Runtime {
20    // Bun always exposes globalThis.Bun (including Bun.version)
21    return (globalThis as BunGlobal).Bun !== undefined ? 'bun' : 'node';
22  }
23  
24  /**
25   * Return a human-readable version string for the current runtime.
26   * Examples: "v22.13.0" (Node), "1.1.42" (Bun)
27   */
28  export function getRuntimeVersion(): string {
29    const bun = (globalThis as BunGlobal).Bun;
30    return bun ? bun.version : process.version;
31  }
32  
33  /**
34   * Return a combined label like "node v22.13.0" or "bun 1.1.42".
35   */
36  export function getRuntimeLabel(): string {
37    return `${detectRuntime()} ${getRuntimeVersion()}`;
38  }