Unverified Commit 5a12867c authored by jgeschwendt's avatar jgeschwendt Committed by GitHub

fix: capture promisified setImmediate separately (#88346)

### What?

Capture `setImmediate[promisify.custom]` at module initialization
instead of lazily accessing it when needed.

```
    RangeError: Maximum call stack size exceeded

      at patchedSetImmediatePromise (node_modules/.pnpm/next@16.1.1_@babel+core@7.28.5_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/next/src/server/node-environment-extensions/fast-set-immediate.external.ts:626:27)
      at originalPromisify (node_modules/.pnpm/next@16.1.1_@babel+core@7.28.5_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/next/src/server/node-environment-extensions/fast-set-immediate.external.ts:627:12)
```

  This was discovered upgrading from `16.0.10` to `16.1.0`

  ### Why?

When `util.promisify(setImmediate)` is called and `currentExecution ===
null`, the code was accessing `originalSetImmediate[promisify.custom]`
at call time. However, `promisify.custom` can get lost or return
`undefined` after the module patches `setImmediate`, causing
`promisify(setImmediate)` to fail. Specifically, when used with `jest`.

Reproduction:
https://github.com/jgeschwendt/nextjs-setimmediate-promisify-repro
- Failing:
https://github.com/jgeschwendt/nextjs-setimmediate-promisify-repro/actions/runs/20864170776
- Passing (with fix):
https://github.com/jgeschwendt/nextjs-setimmediate-promisify-repro/actions/runs/20864380068
-
https://github.com/jgeschwendt/nextjs-setimmediate-promisify-repro/pull/1

  ### How?

Move the capture of `originalSetImmediate[promisify.custom]` to module
initialization time (alongside `originalSetImmediate`,
`originalClearImmediate`, and `originalNextTick`), ensuring the original
promisified implementation is preserved before any patching occurs.
parent d3b3e3a3
......@@ -22,6 +22,9 @@ let currentExecution: Execution | null = null
const originalSetImmediate = globalThis.setImmediate
const originalClearImmediate = globalThis.clearImmediate
const originalNextTick = process.nextTick
const originalSetImmediatePromisify: (typeof setImmediate)['__promisify__'] =
// @ts-expect-error: the types for `promisify.custom` are strange
originalSetImmediate[promisify.custom]
export { originalSetImmediate as unpatchedSetImmediate }
......@@ -621,10 +624,7 @@ function patchedSetImmediatePromise<T = void>(
options?: import('node:timers').TimerOptions
): Promise<T> {
if (currentExecution === null) {
const originalPromisify: (typeof setImmediate)['__promisify__'] =
// @ts-expect-error: the types for `promisify.custom` are strange
originalSetImmediate[promisify.custom]
return originalPromisify(value, options)
return originalSetImmediatePromisify(value, options)
}
return new Promise<T>((resolve, reject) => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment