Skip to content
This repository has been archived by the owner on Jun 21, 2023. It is now read-only.

Commit

Permalink
Workaround for Node.js 16+ on Apple Silicon M1 (vercel#27031)
Browse files Browse the repository at this point in the history
This PR is a workaround for vercel#24421 by adding an artificial delay when Apple M1 + buggy Node.js is detected.

Node.js 14 is unaffected because it M1 still reports `arch=x64`. Starting in Node.js 16, M1 reports `arch=arm64`.

V8 Bug: https://crbug.com/1224882

Node.js Issue: nodejs/node#39327
  • Loading branch information
styfle committed Jul 12, 2021
1 parent 8bdccdb commit 3ebf526
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/next/server/lib/squoosh/impl.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import semver from 'next/dist/compiled/semver'
import { codecs as supportedFormats, preprocessors } from './codecs'
import ImageData from './image_data'

// Fixed in Node.js 16.5.0 and newer.
// See https://github.com/nodejs/node/pull/39337
// Eventually, remove this delay when engines is updated.
// See https://git.io/JCTr0
const FIXED_VERSION = '16.5.0'
const DELAY_MS = 1000
let _promise: Promise<void> | undefined

function delayOnce(ms: number): Promise<void> {
if (!_promise) {
_promise = new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
return _promise
}

function maybeDelay(): Promise<void> {
const isAppleM1 = process.arch === 'arm64' && process.platform === 'darwin'
if (isAppleM1 && semver.lt(process.version, FIXED_VERSION)) {
return delayOnce(DELAY_MS)
}
return Promise.resolve()
}

export async function decodeBuffer(
_buffer: Buffer | Uint8Array
): Promise<ImageData> {
Expand Down Expand Up @@ -39,6 +65,7 @@ export async function resize({ image, width, height }: ResizeOpts) {

const p = preprocessors['resize']
const m = await p.instantiate()
await maybeDelay()
return await m(image.data, image.width, image.height, {
...p.defaultOptions,
width,
Expand All @@ -54,6 +81,7 @@ export async function encodeJpeg(

const e = supportedFormats['mozjpeg']
const m = await e.enc()
await maybeDelay()
const r = await m.encode!(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality,
Expand All @@ -69,6 +97,7 @@ export async function encodeWebp(

const e = supportedFormats['webp']
const m = await e.enc()
await maybeDelay()
const r = await m.encode!(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality,
Expand All @@ -83,6 +112,7 @@ export async function encodePng(

const e = supportedFormats['oxipng']
const m = await e.enc()
await maybeDelay()
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
})
Expand Down

0 comments on commit 3ebf526

Please sign in to comment.