Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .config/vitest.config.mts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { fileURLToPath } from 'node:url'

import { defineConfig } from 'vitest/config'
import type { UserConfig } from 'vitest/config'

import { resolveSnapshotPath } from './snapshot-path.mts'

export default defineConfig({
export default {
root: fileURLToPath(new URL('../', import.meta.url)),
resolve: {
preserveSymlinks: false,
Expand Down Expand Up @@ -59,4 +59,4 @@ export default defineConfig({
],
},
},
})
} satisfies UserConfig
6 changes: 3 additions & 3 deletions .config/vitest.e2e.config.mts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { fileURLToPath } from 'node:url'

import { defineConfig } from 'vitest/config'
import type { UserConfig } from 'vitest/config'

import { resolveSnapshotPath } from './snapshot-path.mts'

export default defineConfig({
export default {
root: fileURLToPath(new URL('../', import.meta.url)),
resolve: {
preserveSymlinks: false,
Expand Down Expand Up @@ -37,4 +37,4 @@ export default defineConfig({
],
},
},
})
} satisfies UserConfig
6 changes: 3 additions & 3 deletions .config/vitest.integration.config.mts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { fileURLToPath } from 'node:url'

import { defineConfig } from 'vitest/config'
import type { UserConfig } from 'vitest/config'

import { resolveSnapshotPath } from './snapshot-path.mts'

export default defineConfig({
export default {
root: fileURLToPath(new URL('../', import.meta.url)),
resolve: {
preserveSymlinks: false,
Expand All @@ -29,4 +29,4 @@ export default defineConfig({
'test/fixtures/**',
],
},
})
} satisfies UserConfig
6 changes: 3 additions & 3 deletions .config/vitest.native.config.mts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { fileURLToPath } from 'node:url'

import { defineConfig } from 'vitest/config'
import type { UserConfig } from 'vitest/config'

import { resolveSnapshotPath } from './snapshot-path.mts'

export default defineConfig({
export default {
root: fileURLToPath(new URL('../', import.meta.url)),
resolve: {
preserveSymlinks: false,
Expand Down Expand Up @@ -32,4 +32,4 @@ export default defineConfig({
'test/fixtures/**',
],
},
})
} satisfies UserConfig
6 changes: 3 additions & 3 deletions .config/vitest.terminal.config.mts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { fileURLToPath } from 'node:url'

import { defineConfig } from 'vitest/config'
import type { UserConfig } from 'vitest/config'

import { resolveSnapshotPath } from './snapshot-path.mts'

export default defineConfig({
export default {
root: fileURLToPath(new URL('../', import.meta.url)),
resolve: { preserveSymlinks: false },
test: {
Expand All @@ -23,4 +23,4 @@ export default defineConfig({
],
exclude: ['**/node_modules/**', '**/dist/**', '.claude/worktrees/**'],
},
})
} satisfies UserConfig
66 changes: 43 additions & 23 deletions src/commands/npm/cmd-npm.mts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,48 @@ import constants, {
import { commonFlags, outputFlags } from '../../flags.mts'
import { filterFlags } from '../../utils/cmd.mts'
import { logger } from '../../utils/logger.mts'
import type {
CliCommandConfig,
CliCommandContext,
} from '../../utils/meow-with-subcommands.mts'
import { meowOrExit } from '../../utils/meow-with-subcommands.mts'
import { getFlagApiRequirementsOutput } from '../../utils/output-formatting.mts'
import type { SpawnResult } from '../../utils/spawn.mts'
import { isSpawnError } from '../../utils/spawn.mts'
import {
trackSubprocessExit,
trackSubprocessStart,
} from '../../utils/telemetry/integration.mts'

import type {
CliCommandConfig,
CliCommandContext,
} from '../../utils/meow-with-subcommands.mts'

const require = createRequire(import.meta.url)

type NpmSpawnOutcome = {
code: number | null
signal: NodeJS.Signals | null
}

export async function awaitNpmSpawn(
spawnPromise: SpawnResult,
startedAt: number,
trackExit = trackSubprocessExit,
): Promise<NpmSpawnOutcome> {
try {
await spawnPromise
} catch (error) {
const { exitCode, signalCode } = spawnPromise.process
const childExit =
(isSpawnError(error) && typeof exitCode === 'number' && exitCode >= 0) ||
!!signalCode
if (!childExit) {
throw error
}
}
const { exitCode, signalCode } = spawnPromise.process
const outcome = { code: exitCode, signal: signalCode }
await trackExit(NPM, startedAt, outcome.code)
return outcome
}

export const CMD_NAME = NPM

const description = 'Wraps npm with Socket security scanning'
Expand Down Expand Up @@ -97,23 +125,15 @@ async function run(
stdio: 'inherit',
})

// Handle exit codes and signals using event-based pattern.
// See https://nodejs.org/api/child_process.html#event-exit.
spawnPromise.process.on(
'exit',
(code: number | null, signalName: NodeJS.Signals | null) => {
// Track subprocess exit and flush telemetry before exiting.
// Use .then() to ensure telemetry completes before process.exit().
void trackSubprocessExit(NPM, subprocessStartTime, code).then(() => {
if (signalName) {
process.kill(process.pid, signalName)
} else if (typeof code === 'number') {
// eslint-disable-next-line n/no-process-exit
process.exit(code)
}
})
},
// Preserve the child's exit code or signal after telemetry has flushed.
const { code, signal } = await awaitNpmSpawn(
spawnPromise,
subprocessStartTime,
)

await spawnPromise
if (signal) {
process.kill(process.pid, signal)
} else if (typeof code === 'number') {
// eslint-disable-next-line n/no-process-exit
process.exit(code)
}
}
71 changes: 70 additions & 1 deletion src/commands/npm/cmd-npm.test.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { describe, expect } from 'vitest'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'

import constants, {
FLAG_CONFIG,
Expand All @@ -8,6 +10,73 @@ import constants, {
NPM,
} from '../../../src/constants.mts'
import { cmdit, spawnSocketCli } from '../../../test/utils.mts'
import { spawn } from '../../utils/spawn.mts'
import type { SpawnResult } from '../../utils/spawn.mts'
import { awaitNpmSpawn } from './cmd-npm.mts'

describe('awaitNpmSpawn', () => {
it('preserves JSON output from a nonzero child exit and waits for telemetry', async () => {
const json = '{"error":{"code":"E404"}}'
const spawnPromise = spawn(process.execPath, [
'-e',
`process.stdout.write(${JSON.stringify(json)}); process.exit(1)`,
])
const capturedStdout = spawnPromise.catch(error => error.stdout)
let telemetryFinished = false

const outcome = await awaitNpmSpawn(spawnPromise, 1, async () => {
await new Promise(resolve => setTimeout(resolve, 10))
telemetryFinished = true
})

expect(outcome).toMatchObject({ code: 1, signal: null })
expect(await capturedStdout).toBe(json)
expect(telemetryFinished).toBe(true)
})

it('preserves a child signal outcome', async () => {
const spawnPromise = spawn(process.execPath, [
'-e',
`process.kill(process.pid, 'SIGTERM')`,
])

await expect(
awaitNpmSpawn(spawnPromise, 1, async () => {}),
).resolves.toMatchObject(
process.platform === 'win32'
? { code: 1, signal: null }
: { code: null, signal: 'SIGTERM' },
)
})
Comment thread
jdalton marked this conversation as resolved.
Resolved

it('propagates launch failures', async () => {
const spawnPromise = spawn(
join(tmpdir(), `socket-missing-${process.pid}`),
[],
)

await expect(
awaitNpmSpawn(spawnPromise, 1, async () => {}),
).rejects.toMatchObject({
code: 'ENOENT',
})
})

it('propagates ENOENT when Windows reports exit code 1', async () => {
const launchError = Object.assign(new Error('spawn npm ENOENT'), {
code: 'ENOENT',
})
const spawnPromise = Promise.reject(launchError) as SpawnResult
Object.assign(spawnPromise, {
process: { exitCode: 1, signalCode: null },
stdin: null,
})

await expect(awaitNpmSpawn(spawnPromise, 1, async () => {})).rejects.toBe(
launchError,
)
})
})

describe('socket npm', async () => {
const { binCliPath } = constants
Expand Down
Loading