11/* eslint-disable n/no-process-exit */
2- import { CLIError , spawnTelemetryWorker , TelemetryGlobal } from './telemetry-utils.js'
2+ /* eslint-disable no-var */
3+ import {
4+ CLIError , spawnTelemetryWorker , telemetryDebug , TelemetryGlobal ,
5+ } from './telemetry-utils.js'
36
47// Extend global with telemetry property
58declare global {
6- // eslint-disable-next-line no-var
79 var cliTelemetry : TelemetryGlobal [ 'cliTelemetry' ]
10+ var telemetrySent : TelemetryGlobal [ 'telemetrySent' ]
811}
912
1013interface SetupTelemetryOptions {
@@ -14,17 +17,31 @@ interface SetupTelemetryOptions {
1417}
1518
1619/**
17- * Setup telemetry handlers for signal handlers
18- * Note: Normal command completion telemetry is handled by the postrun hook.
19- * This only handles SIGINT/SIGTERM cases where hooks don't run.
20+ * Setup telemetry handlers for beforeExit and signal handlers
21+ * - beforeExit: Fallback for commands where postrun hook doesn't run (e.g., version, --help flags)
22+ * - postrun hook: Handles regular commands (sets telemetrySent flag to prevent duplicates)
23+ * - SIGINT/SIGTERM: Handles interrupted commands
2024 */
2125export function setupTelemetryHandlers ( options : SetupTelemetryOptions ) : void {
2226 const { cliStartTime, computeDuration, enableTelemetry} = options
2327
2428 if ( ! enableTelemetry ) return
2529
26- // Note: beforeExit handler removed to avoid duplicate telemetry sends.
27- // The postrun hook now handles normal command completion telemetry.
30+ // Fallback handler for commands that don't trigger postrun hook
31+ // (e.g., version, --version, --help flags handled by oclif)
32+ process . once ( 'beforeExit' , code => {
33+ // Only send if telemetry wasn't already sent by postrun hook
34+ if ( global . cliTelemetry && ! global . telemetrySent ) {
35+ telemetryDebug ( 'Telemetry enabled: beforeExit spawning worker to send telemetry for command: %s (postrun did not run)' , global . cliTelemetry . command )
36+ const cmdStartTime = global . cliTelemetry . commandRunDuration
37+ global . cliTelemetry . commandRunDuration = computeDuration ( cmdStartTime )
38+ global . cliTelemetry . exitCode = code
39+ global . cliTelemetry . cliRunDuration = computeDuration ( cliStartTime )
40+
41+ spawnTelemetryWorker ( global . cliTelemetry )
42+ global . telemetrySent = true
43+ }
44+ } )
2845
2946 process . on ( 'SIGINT' , ( ) => {
3047 // Spawn background process to send telemetry
0 commit comments