Skip to content
Closed
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
15 changes: 12 additions & 3 deletions packages/payload/bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ if (disableTranspile) {
await bin()
}

void start()
void start().catch((err) => {
console.error(err)
process.exit(1)
})
} else {
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
Expand All @@ -41,7 +44,10 @@ if (disableTranspile) {
await bin()
}

void start()
void start().catch((err) => {
console.error(err)
process.exit(1)
})
} else if (useSwc) {
const { register } = await import('node:module')
// Remove --use-swc from arguments
Expand All @@ -60,6 +66,9 @@ if (disableTranspile) {
await bin()
}

void start()
void start().catch((err) => {
console.error(err)
process.exit(1)
})
}
}
82 changes: 82 additions & 0 deletions packages/payload/src/bin/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const loadEnvMock = vi.fn()
const findConfigMock = vi.fn()
const migrateMock = vi.fn()

// Mock every collaborator so importing the bin entry stays isolated from the
// payload core and never touches the filesystem or a real config.
vi.mock('./loadEnv.js', () => ({ loadEnv: loadEnvMock }))
vi.mock('../config/find.js', () => ({ findConfig: findConfigMock }))
vi.mock('../index.js', () => ({ default: {}, getPayload: vi.fn() }))
vi.mock('croner', () => ({ Cron: vi.fn() }))
vi.mock('./build.js', () => ({ build: vi.fn() }))
vi.mock('./generateImportMap/index.js', () => ({ generateImportMap: vi.fn() }))
vi.mock('./generateTypes.js', () => ({ generateTypes: vi.fn() }))
vi.mock('./info.js', () => ({ info: vi.fn() }))
vi.mock('./migrate.js', () => ({
availableCommands: [
'migrate',
'migrate:create',
'migrate:down',
'migrate:refresh',
'migrate:reset',
'migrate:status',
'migrate:fresh',
],
migrate: migrateMock,
}))

// Imported after mocks are registered
const { bin } = await import('./index.js')

describe('bin', () => {
let exitMock: ReturnType<typeof vi.spyOn>
let errorSpy: ReturnType<typeof vi.spyOn>
let originalArgv: string[]
let originalExitCode: typeof process.exitCode

beforeEach(() => {
originalArgv = process.argv
originalExitCode = process.exitCode
process.exitCode = 0
loadEnvMock.mockReset()
findConfigMock.mockReset()
// Throw from the mock so control stops exactly where the real process.exit would.
exitMock = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
throw new Error(`process.exit:${code}`)
}) as never)
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.spyOn(console, 'log').mockImplementation(() => undefined)
})

afterEach(() => {
process.argv = originalArgv
process.exitCode = originalExitCode
vi.restoreAllMocks()
})

it('defaults process.exitCode to 1 at entry so a never-settling run reports failure', async () => {
// loadEnv is the first call after the guard; making it throw proves the guard
// is already in place before any work that could hang or be dropped runs.
loadEnvMock.mockImplementation(() => {
throw new Error('boom')
})
process.argv = ['node', 'payload', 'migrate']

await expect(bin()).rejects.toThrow('boom')
expect(process.exitCode).toBe(1)
})

it('exits 1 with a clear message when the config fails to load', async () => {
findConfigMock.mockImplementation(() => {
throw new Error('no config found')
})
process.argv = ['node', 'payload', 'migrate']

await expect(bin()).rejects.toThrow('process.exit:1')
expect(errorSpy).toHaveBeenCalledWith('Failed to load the Payload config.')
expect(exitMock).toHaveBeenCalledWith(1)
expect(process.exitCode).toBe(1)
})
})
22 changes: 17 additions & 5 deletions packages/payload/src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ const availableScripts = [
] as const

export const bin = async () => {
// Default to failure. A dropped or never-settling config import drains the event
// loop and lets Node exit before the explicit exit(0) below runs; without this the
// process would report success. The success paths set 0 explicitly.
process.exitCode = 1

loadEnv()
process.env.DISABLE_PAYLOAD_HMR = 'true'

Expand Down Expand Up @@ -104,11 +109,18 @@ async function runBinScript({
return {}
}

const configPath = findConfig()
const configPromise = await import(pathToFileURL(configPath).toString())
let config = await configPromise
if (config.default) {
config = await config.default
let config
try {
const configPath = findConfig()
const configModule = await import(pathToFileURL(configPath).toString())
config = await configModule
if (config.default) {
config = await config.default
}
} catch (err) {
console.error('Failed to load the Payload config.')
console.error(err)
process.exit(1)
}

const userBinScript = Array.isArray(config.bin)
Expand Down
Loading