Unverified Commit 99a4ea6e authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

feat(next/image): remove `sharp` for wasm variant (#22253)

This pull request removes the native `sharp` dependency (which doesn't work on some Linux variants, nor **M1 Mac**) and replaces it with a wasm equivalent.

It also reduces Next.js' installed size by 27.3 MB.

The code is adapted from the [Squoosh CLI](https://github.com/GoogleChromeLabs/squoosh).

This PR still supports:

- Rotation normalization
- Resizing
- PNG
- JPEG
- Webp

However, it (temporarily) removes support for:
- Resizing Gifs
- Resizing Tiff

(these formats still get served and rendered correctly by the image component)

---

Fixes #20456
Closes #20738
Closes #21762
parent 62803a9d
......@@ -91,6 +91,7 @@
"get-port": "5.1.1",
"glob": "7.1.6",
"gzip-size": "5.1.1",
"image-size": "0.9.3",
"is-animated": "2.0.0",
"isomorphic-unfetch": "3.0.0",
"jest-circus": "26.0.1",
......
......@@ -421,12 +421,7 @@ export default async function build(
]
.filter(nonNullable)
.map((file) => path.join(config.distDir, file)),
ignore: [
path.relative(
dir,
path.join(path.dirname(require.resolve('sharp')), '**/*')
),
],
ignore: [] as string[],
})
)
......
This source diff could not be displayed because it is too large. You can view the blob instead.
import nodeUrl, { UrlWithParsedQuery } from 'url'
import { IncomingMessage, ServerResponse } from 'http'
import { join } from 'path'
import { mediaType } from '@hapi/accept'
import { createReadStream, promises } from 'fs'
import { createHash } from 'crypto'
import Server from './next-server'
import { getContentType, getExtension } from './serve-static'
import { fileExists } from '../../lib/file-exists'
import { createReadStream, promises } from 'fs'
import { getOrientation, Orientation } from 'get-orientation'
import { IncomingMessage, ServerResponse } from 'http'
// @ts-ignore no types for is-animated
import isAnimated from 'next/dist/compiled/is-animated'
import { join } from 'path'
import Stream from 'stream'
import { sendEtagResponse } from './send-payload'
import nodeUrl, { UrlWithParsedQuery } from 'url'
import { fileExists } from '../../lib/file-exists'
import { ImageConfig, imageConfigDefault } from './image-config'
import ImageData from './lib/squoosh/image_data'
import {
decodeBuffer,
encodeJpeg,
encodePng,
encodeWebp,
resize,
rotate,
} from './lib/squoosh/main'
import Server from './next-server'
import { sendEtagResponse } from './send-payload'
import { getContentType, getExtension } from './serve-static'
let sharp: typeof import('sharp')
//const AVIF = 'image/avif'
const WEBP = 'image/webp'
const PNG = 'image/png'
......@@ -241,45 +250,42 @@ export async function imageOptimizer(
contentType = JPEG
}
if (!sharp) {
try {
// eslint-disable-next-line import/no-extraneous-dependencies
sharp = require('sharp')
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
error.message += '\n\nLearn more: https://err.sh/next.js/install-sharp'
server.logError(error)
sendResponse(req, res, upstreamType, upstreamBuffer)
return { finished: true }
}
throw error
}
}
try {
const transformer = sharp(upstreamBuffer)
transformer.rotate() // auto rotate based on EXIF data
const { width: metaWidth } = await transformer.metadata()
let bitmap: ImageData = await decodeBuffer(upstreamBuffer)
const orientation = await getOrientation(upstreamBuffer)
if (orientation === Orientation.RIGHT_TOP) {
bitmap = await rotate(bitmap, 1)
} else if (orientation === Orientation.BOTTOM_RIGHT) {
bitmap = await rotate(bitmap, 2)
} else if (orientation === Orientation.LEFT_BOTTOM) {
bitmap = await rotate(bitmap, 3)
} else {
// TODO: support more orientations
// eslint-disable-next-line @typescript-eslint/no-unused-vars
// const _: never = orientation
}
if (metaWidth && metaWidth > width) {
transformer.resize(width)
if (bitmap.width && bitmap.width > width) {
bitmap = await resize(bitmap, { width })
}
let optimizedBuffer: Buffer | undefined
//if (contentType === AVIF) {
// Soon https://github.com/lovell/sharp/issues/2289
//}
//} else
if (contentType === WEBP) {
transformer.webp({ quality })
optimizedBuffer = await encodeWebp(bitmap, { quality })
} else if (contentType === PNG) {
transformer.png({ quality })
optimizedBuffer = await encodePng(bitmap)
} else if (contentType === JPEG) {
transformer.jpeg({ quality })
optimizedBuffer = await encodeJpeg(bitmap, { quality })
}
const optimizedBuffer = await transformer.toBuffer()
await writeToCacheDir(hashDir, contentType, expireAt, optimizedBuffer)
sendResponse(req, res, contentType, optimizedBuffer)
if (optimizedBuffer) {
await writeToCacheDir(hashDir, contentType, expireAt, optimizedBuffer)
sendResponse(req, res, contentType, optimizedBuffer)
} else {
throw new Error('Unable to optimize buffer')
}
} catch (error) {
sendResponse(req, res, upstreamType, upstreamBuffer)
}
......
This diff is collapsed.
import { promises as fsp } from 'fs'
import * as path from 'path'
import { instantiateEmscriptenWasm, pathify } from './emscripten-utils.js'
import { execOnce } from '../../../lib/utils.js'
// MozJPEG
// @ts-ignore
import mozEnc from './mozjpeg/mozjpeg_node_enc.js'
const mozEncWasm = path.resolve(__dirname, './mozjpeg/mozjpeg_node_enc.wasm')
// @ts-ignore
import mozDec from './mozjpeg/mozjpeg_node_dec.js'
const mozDecWasm = path.resolve(__dirname, './mozjpeg/mozjpeg_node_dec.wasm')
// WebP
// @ts-ignore
import webpEnc from './webp/webp_node_enc.js'
const webpEncWasm = path.resolve(__dirname, './webp/webp_node_enc.wasm')
// @ts-ignore
import webpDec from './webp/webp_node_dec.js'
const webpDecWasm = path.resolve(__dirname, './webp/webp_node_dec.wasm')
// PNG
// @ts-ignore
import * as pngEncDec from './png/squoosh_png.js'
const pngEncDecWasm = path.resolve(__dirname, './png/squoosh_png_bg.wasm')
const pngEncDecInit = execOnce(() =>
pngEncDec.default(fsp.readFile(pathify(pngEncDecWasm)))
)
// OxiPNG
// @ts-ignore
import * as oxipng from './png/squoosh_oxipng.js'
const oxipngWasm = path.resolve(__dirname, './png/squoosh_oxipng_bg.wasm')
const oxipngInit = execOnce(() =>
oxipng.default(fsp.readFile(pathify(oxipngWasm)))
)
// Resize
// @ts-ignore
import * as resize from './resize/squoosh_resize.js'
const resizeWasm = path.resolve(__dirname, './resize/squoosh_resize_bg.wasm')
const resizeInit = execOnce(() =>
resize.default(fsp.readFile(pathify(resizeWasm)))
)
// rotate
const rotateWasm = path.resolve(__dirname, './rotate/rotate.wasm')
import ImageData from './image_data.js'
;(global as any).ImageData = ImageData // mandatory for wasm binaries
function resizeNameToIndex(
name: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3'
) {
switch (name) {
case 'triangle':
return 0
case 'catrom':
return 1
case 'mitchell':
return 2
case 'lanczos3':
return 3
default:
throw Error(`Unknown resize algorithm "${name}"`)
}
}
function resizeWithAspect({
input_width,
input_height,
target_width,
target_height,
}: {
input_width: number
input_height: number
target_width?: number
target_height?: number
}): { width: number; height: number } {
if (!target_width && !target_height) {
throw Error('Need to specify at least width or height when resizing')
}
if (target_width && target_height) {
return { width: target_width, height: target_height }
}
if (!target_width) {
return {
width: Math.round((input_width / input_height) * target_height!),
height: target_height!,
}
}
if (!target_height) {
return {
width: target_width,
height: Math.round((input_height / input_width) * target_width),
}
}
throw Error('invariant')
}
export const preprocessors = {
resize: {
name: 'Resize',
description: 'Resize the image before compressing',
instantiate: async () => {
await resizeInit()
return (
buffer: Buffer | Uint8Array,
input_width: number,
input_height: number,
{
width,
height,
method,
premultiply,
linearRGB,
}: {
width?: number
height?: number
method: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3'
premultiply: boolean
linearRGB: boolean
}
) => {
;({ width, height } = resizeWithAspect({
input_width,
input_height,
target_width: width,
target_height: height,
}))
return new ImageData(
resize.resize(
buffer,
input_width,
input_height,
width,
height,
resizeNameToIndex(method),
premultiply,
linearRGB
),
width,
height
)
}
},
defaultOptions: {
method: 'lanczos3',
fitMethod: 'stretch',
premultiply: true,
linearRGB: true,
},
},
rotate: {
name: 'Rotate',
description: 'Rotate image',
instantiate: async () => {
return async (
buffer: Buffer | Uint8Array,
width: number,
height: number,
{ numRotations }: { numRotations: number }
) => {
const degrees = (numRotations * 90) % 360
const sameDimensions = degrees === 0 || degrees === 180
const size = width * height * 4
const { instance } = await WebAssembly.instantiate(
await fsp.readFile(pathify(rotateWasm))
)
const exports = instance.exports as any
const { memory } = exports
const additionalPagesNeeded = Math.ceil(
(size * 2 - memory.buffer.byteLength + 8) / (64 * 1024)
)
if (additionalPagesNeeded > 0) {
memory.grow(additionalPagesNeeded)
}
const view = new Uint8ClampedArray(memory.buffer)
view.set(buffer, 8)
exports.rotate(width, height, degrees)
return new ImageData(
Buffer.from(view.slice(size + 8, size * 2 + 8)),
sameDimensions ? width : height,
sameDimensions ? height : width
)
}
},
defaultOptions: {
numRotations: 0,
},
},
} as const
export const codecs = {
mozjpeg: {
name: 'MozJPEG',
extension: 'jpg',
detectors: [/^\xFF\xD8\xFF/],
dec: () => instantiateEmscriptenWasm(mozDec, mozDecWasm),
enc: () => instantiateEmscriptenWasm(mozEnc, mozEncWasm),
defaultEncoderOptions: {
quality: 75,
baseline: false,
arithmetic: false,
progressive: true,
optimize_coding: true,
smoothing: 0,
color_space: 3 /*YCbCr*/,
quant_table: 3,
trellis_multipass: false,
trellis_opt_zero: false,
trellis_opt_table: false,
trellis_loops: 1,
auto_subsample: true,
chroma_subsample: 2,
separate_chroma_quality: false,
chroma_quality: 75,
},
autoOptimize: {
option: 'quality',
min: 0,
max: 100,
},
},
webp: {
name: 'WebP',
extension: 'webp',
detectors: [/^RIFF....WEBPVP8[LX ]/],
dec: () => instantiateEmscriptenWasm(webpDec, webpDecWasm),
enc: () => instantiateEmscriptenWasm(webpEnc, webpEncWasm),
defaultEncoderOptions: {
quality: 75,
target_size: 0,
target_PSNR: 0,
method: 4,
sns_strength: 50,
filter_strength: 60,
filter_sharpness: 0,
filter_type: 1,
partitions: 0,
segments: 4,
pass: 1,
show_compressed: 0,
preprocessing: 0,
autofilter: 0,
partition_limit: 0,
alpha_compression: 1,
alpha_filtering: 1,
alpha_quality: 100,
lossless: 0,
exact: 0,
image_hint: 0,
emulate_jpeg_size: 0,
thread_level: 0,
low_memory: 0,
near_lossless: 100,
use_delta_palette: 0,
use_sharp_yuv: 0,
},
autoOptimize: {
option: 'quality',
min: 0,
max: 100,
},
},
oxipng: {
name: 'OxiPNG',
extension: 'png',
// eslint-disable-next-line no-control-regex
detectors: [/^\x89PNG\x0D\x0A\x1A\x0A/],
dec: async () => {
await pngEncDecInit()
return { decode: pngEncDec.decode }
},
enc: async () => {
await pngEncDecInit()
await oxipngInit()
return {
encode: (
buffer: Buffer | Uint8Array,
width: number,
height: number,
opts: any
) => {
const simplePng = pngEncDec.encode(
new Uint8Array(buffer),
width,
height
)
return oxipng.optimise(simplePng, opts.level)
},
}
},
defaultEncoderOptions: {
level: 2,
},
autoOptimize: {
option: 'level',
min: 6,
max: 1,
},
},
} as const
import { fileURLToPath } from 'url'
export function pathify(path: string) {
if (path.startsWith('file://')) {
path = fileURLToPath(path)
}
return path
}
export function instantiateEmscriptenWasm(
factory: (args: {
locateFile: () => string
}) => {
decode?: (
buffer: Buffer | Uint8Array,
width: number,
height: number,
opts: any
) => Buffer
encode?: (
buffer: Buffer | Uint8Array,
width: number,
height: number,
opts: any
) => Buffer
},
path: string
) {
return factory({
locateFile() {
return pathify(path)
},
})
}
export default class ImageData {
static from(input: ImageData): ImageData {
return new ImageData(input.data || input._data, input.width, input.height)
}
private _data: Buffer | Uint8Array | Uint8ClampedArray
width: number
height: number
get data(): Buffer {
if (Object.prototype.toString.call(this._data) === '[object Object]') {
return Buffer.from(Object.values(this._data))
}
if (
this._data instanceof Buffer ||
this._data instanceof Uint8Array ||
this._data instanceof Uint8ClampedArray
) {
return Buffer.from(this._data)
}
throw new Error('invariant')
}
constructor(
data: Buffer | Uint8Array | Uint8ClampedArray,
width: number,
height: number
) {
this._data = data
this.width = width
this.height = height
}
}
import { codecs as supportedFormats, preprocessors } from './codecs'
import ImageData from './image_data'
export async function decodeBuffer(
_buffer: Buffer | Uint8Array
): Promise<ImageData> {
const buffer = Buffer.from(_buffer)
const firstChunk = buffer.slice(0, 16)
const firstChunkString = Array.from(firstChunk)
.map((v) => String.fromCodePoint(v))
.join('')
const key = Object.entries(supportedFormats).find(([, { detectors }]) =>
detectors.some((detector) => detector.exec(firstChunkString))
)?.[0] as keyof typeof supportedFormats
if (!key) {
throw Error(`Buffer has an unsupported format`)
}
const d = await supportedFormats[key].dec()
const rgba = d.decode(new Uint8Array(buffer))
return rgba
}
export async function rotate(
image: ImageData,
numRotations: number
): Promise<ImageData> {
image = ImageData.from(image)
const m = await preprocessors['rotate'].instantiate()
return await m(image.data, image.width, image.height, { numRotations })
}
export async function resize(image: ImageData, { width }: { width: number }) {
image = ImageData.from(image)
const p = preprocessors['resize']
const m = await p.instantiate()
return await m(image.data, image.width, image.height, {
...p.defaultOptions,
width,
})
}
export async function encodeJpeg(
image: ImageData,
{ quality }: { quality: number }
): Promise<Buffer | Uint8Array> {
image = ImageData.from(image)
const e = supportedFormats['mozjpeg']
const m = await e.enc()
const r = await m.encode!(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality,
})
return Buffer.from(r)
}
export async function encodeWebp(
image: ImageData,
{ quality }: { quality: number }
): Promise<Buffer | Uint8Array> {
image = ImageData.from(image)
const e = supportedFormats['webp']
const m = await e.enc()
const r = await m.encode!(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality,
})
return Buffer.from(r)
}
export async function encodePng(
image: ImageData
): Promise<Buffer | Uint8Array> {
image = ImageData.from(image)
const e = supportedFormats['oxipng']
const m = await e.enc()
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
})
return Buffer.from(r)
}
import JestWorker from 'jest-worker'
import * as path from 'path'
import { execOnce } from '../../../lib/utils'
import ImageData from './image_data'
const getWorker = execOnce(
() =>
new JestWorker(path.resolve(__dirname, 'impl'), {
enableWorkerThreads: true,
})
)
export async function decodeBuffer(buffer: Buffer): Promise<ImageData> {
const worker: typeof import('./impl') = getWorker() as any
return ImageData.from(await worker.decodeBuffer(buffer))
}
export async function rotate(
image: ImageData,
numRotations: number
): Promise<ImageData> {
const worker: typeof import('./impl') = getWorker() as any
return ImageData.from(await worker.rotate(image, numRotations))
}
export async function resize(
image: ImageData,
{ width }: { width: number }
): Promise<ImageData> {
const worker: typeof import('./impl') = getWorker() as any
return ImageData.from(await worker.resize(image, { width }))
}
export async function encodeJpeg(
image: ImageData,
{ quality }: { quality: number }
): Promise<Buffer> {
const worker: typeof import('./impl') = getWorker() as any
const o = await worker.encodeJpeg(image, { quality })
return Buffer.from(o)
}
export async function encodeWebp(
image: ImageData,
{ quality }: { quality: number }
): Promise<Buffer> {
const worker: typeof import('./impl') = getWorker() as any
const o = await worker.encodeWebp(image, { quality })
return Buffer.from(o)
}
export async function encodePng(image: ImageData): Promise<Buffer> {
const worker: typeof import('./impl') = getWorker() as any
const o = await worker.encodePng(image)
return Buffer.from(o)
}
import { TextDecoder } from '../text-decoder'
let wasm
let cachedTextDecoder = new TextDecoder('utf-8', {
ignoreBOM: true,
fatal: true,
})
cachedTextDecoder.decode()
let cachegetUint8Memory0 = null
function getUint8Memory0() {
if (
cachegetUint8Memory0 === null ||
cachegetUint8Memory0.buffer !== wasm.memory.buffer
) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer)
}
return cachegetUint8Memory0
}
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len))
}
let WASM_VECTOR_LEN = 0
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1)
getUint8Memory0().set(arg, ptr / 1)
WASM_VECTOR_LEN = arg.length
return ptr
}
let cachegetInt32Memory0 = null
function getInt32Memory0() {
if (
cachegetInt32Memory0 === null ||
cachegetInt32Memory0.buffer !== wasm.memory.buffer
) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer)
}
return cachegetInt32Memory0
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len)
}
/**
* @param {Uint8Array} data
* @param {number} level
* @returns {Uint8Array}
*/
export function optimise(data, level) {
try {
const retptr = wasm.__wbindgen_export_0.value - 16
wasm.__wbindgen_export_0.value = retptr
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc)
var len0 = WASM_VECTOR_LEN
wasm.optimise(retptr, ptr0, len0, level)
var r0 = getInt32Memory0()[retptr / 4 + 0]
var r1 = getInt32Memory0()[retptr / 4 + 1]
var v1 = getArrayU8FromWasm0(r0, r1).slice()
wasm.__wbindgen_free(r0, r1 * 1)
return v1
} finally {
wasm.__wbindgen_export_0.value += 16
}
}
async function load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports)
} catch (e) {
if (module.headers.get('Content-Type') !== 'application/wasm') {
console.warn(
'`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n',
e
)
} else {
throw e
}
}
}
const bytes = await module.arrayBuffer()
return await WebAssembly.instantiate(bytes, imports)
} else {
const instance = await WebAssembly.instantiate(module, imports)
if (instance instanceof WebAssembly.Instance) {
return { instance, module }
} else {
return instance
}
}
}
async function init(input) {
if (typeof input === 'undefined') {
// input = import.meta.url.replace(/\.js$/, '_bg.wasm')
throw new Error('invariant')
}
const imports = {}
imports.wbg = {}
imports.wbg.__wbindgen_throw = function (arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1))
}
if (
typeof input === 'string' ||
(typeof Request === 'function' && input instanceof Request) ||
(typeof URL === 'function' && input instanceof URL)
) {
input = fetch(input)
}
const { instance, module } = await load(await input, imports)
wasm = instance.exports
init.__wbindgen_wasm_module = module
return wasm
}
export default init
let wasm
let cachegetUint8ClampedMemory0 = null
function getUint8ClampedMemory0() {
if (
cachegetUint8ClampedMemory0 === null ||
cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer
) {
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer)
}
return cachegetUint8ClampedMemory0
}
function getClampedArrayU8FromWasm0(ptr, len) {
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len)
}
const heap = new Array(32).fill(undefined)
heap.push(undefined, null, true, false)
let heap_next = heap.length
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1)
const idx = heap_next
heap_next = heap[idx]
heap[idx] = obj
return idx
}
let cachegetUint8Memory0 = null
function getUint8Memory0() {
if (
cachegetUint8Memory0 === null ||
cachegetUint8Memory0.buffer !== wasm.memory.buffer
) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer)
}
return cachegetUint8Memory0
}
let WASM_VECTOR_LEN = 0
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1)
getUint8Memory0().set(arg, ptr / 1)
WASM_VECTOR_LEN = arg.length
return ptr
}
let cachegetInt32Memory0 = null
function getInt32Memory0() {
if (
cachegetInt32Memory0 === null ||
cachegetInt32Memory0.buffer !== wasm.memory.buffer
) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer)
}
return cachegetInt32Memory0
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len)
}
/**
* @param {Uint8Array} data
* @param {number} width
* @param {number} height
* @returns {Uint8Array}
*/
export function encode(data, width, height) {
try {
const retptr = wasm.__wbindgen_export_1.value - 16
wasm.__wbindgen_export_1.value = retptr
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc)
var len0 = WASM_VECTOR_LEN
wasm.encode(retptr, ptr0, len0, width, height)
var r0 = getInt32Memory0()[retptr / 4 + 0]
var r1 = getInt32Memory0()[retptr / 4 + 1]
var v1 = getArrayU8FromWasm0(r0, r1).slice()
wasm.__wbindgen_free(r0, r1 * 1)
return v1
} finally {
wasm.__wbindgen_export_1.value += 16
}
}
function getObject(idx) {
return heap[idx]
}
function dropObject(idx) {
if (idx < 36) return
heap[idx] = heap_next
heap_next = idx
}
function takeObject(idx) {
const ret = getObject(idx)
dropObject(idx)
return ret
}
/**
* @param {Uint8Array} data
* @returns {ImageData}
*/
export function decode(data) {
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc)
var len0 = WASM_VECTOR_LEN
var ret = wasm.decode(ptr0, len0)
return takeObject(ret)
}
async function load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports)
} catch (e) {
if (module.headers.get('Content-Type') !== 'application/wasm') {
console.warn(
'`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n',
e
)
} else {
throw e
}
}
}
const bytes = await module.arrayBuffer()
return await WebAssembly.instantiate(bytes, imports)
} else {
const instance = await WebAssembly.instantiate(module, imports)
if (instance instanceof WebAssembly.Instance) {
return { instance, module }
} else {
return instance
}
}
}
async function init(input) {
if (typeof input === 'undefined') {
// input = import.meta.url.replace(/\.js$/, '_bg.wasm')
throw new Error('invariant')
}
const imports = {}
imports.wbg = {}
imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 = function (
arg0,
arg1,
arg2,
arg3
) {
var v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice()
wasm.__wbindgen_free(arg0, arg1 * 1)
var ret = new ImageData(v0, arg2 >>> 0, arg3 >>> 0)
return addHeapObject(ret)
}
if (
typeof input === 'string' ||
(typeof Request === 'function' && input instanceof Request) ||
(typeof URL === 'function' && input instanceof URL)
) {
input = fetch(input)
}
const { instance, module } = await load(await input, imports)
wasm = instance.exports
init.__wbindgen_wasm_module = module
return wasm
}
export default init
let wasm
let cachegetUint8Memory0 = null
function getUint8Memory0() {
if (
cachegetUint8Memory0 === null ||
cachegetUint8Memory0.buffer !== wasm.memory.buffer
) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer)
}
return cachegetUint8Memory0
}
let WASM_VECTOR_LEN = 0
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1)
getUint8Memory0().set(arg, ptr / 1)
WASM_VECTOR_LEN = arg.length
return ptr
}
let cachegetInt32Memory0 = null
function getInt32Memory0() {
if (
cachegetInt32Memory0 === null ||
cachegetInt32Memory0.buffer !== wasm.memory.buffer
) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer)
}
return cachegetInt32Memory0
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len)
}
/**
* @param {Uint8Array} input_image
* @param {number} input_width
* @param {number} input_height
* @param {number} output_width
* @param {number} output_height
* @param {number} typ_idx
* @param {boolean} premultiply
* @param {boolean} color_space_conversion
* @returns {Uint8Array}
*/
export function resize(
input_image,
input_width,
input_height,
output_width,
output_height,
typ_idx,
premultiply,
color_space_conversion
) {
var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc)
var len0 = WASM_VECTOR_LEN
wasm.resize(
8,
ptr0,
len0,
input_width,
input_height,
output_width,
output_height,
typ_idx,
premultiply,
color_space_conversion
)
var r0 = getInt32Memory0()[8 / 4 + 0]
var r1 = getInt32Memory0()[8 / 4 + 1]
var v1 = getArrayU8FromWasm0(r0, r1).slice()
wasm.__wbindgen_free(r0, r1 * 1)
return v1
}
async function load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports)
} catch (e) {
if (module.headers.get('Content-Type') !== 'application/wasm') {
console.warn(
'`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n',
e
)
} else {
throw e
}
}
}
const bytes = await module.arrayBuffer()
return await WebAssembly.instantiate(bytes, imports)
} else {
const instance = await WebAssembly.instantiate(module, imports)
if (instance instanceof WebAssembly.Instance) {
return { instance, module }
} else {
return instance
}
}
}
async function init(input) {
if (typeof input === 'undefined') {
// input = import.meta.url.replace(/\.js$/, '_bg.wasm')
throw new Error('invariant')
}
const imports = {}
if (
typeof input === 'string' ||
(typeof Request === 'function' && input instanceof Request) ||
(typeof URL === 'function' && input instanceof URL)
) {
input = fetch(input)
}
const { instance, module } = await load(await input, imports)
wasm = instance.exports
init.__wbindgen_wasm_module = module
return wasm
}
export default init
const textDecoder =
typeof TextDecoder !== 'undefined' ? TextDecoder : require('util').TextDecoder
export { textDecoder as TextDecoder }
......@@ -77,6 +77,7 @@
"cssnano-simple": "1.2.2",
"etag": "1.8.1",
"find-cache-dir": "3.3.1",
"get-orientation": "1.1.2",
"jest-worker": "24.9.0",
"native-url": "0.3.4",
"node-fetch": "2.6.1",
......@@ -97,9 +98,6 @@
"vm-browserify": "1.1.2",
"watchpack": "2.0.0-beta.13"
},
"optionalDependencies": {
"sharp": "0.26.3"
},
"peerDependencies": {
"fibers": ">= 3.1.0",
"node-sass": "^4.0.0 || ^5.0.0",
......@@ -165,7 +163,6 @@
"@types/react-is": "16.7.1",
"@types/semver": "7.3.1",
"@types/send": "0.14.4",
"@types/sharp": "0.26.0",
"@types/styled-jsx": "2.2.8",
"@types/text-table": "0.2.1",
"@types/webpack-sources": "0.1.5",
......
......@@ -773,6 +773,7 @@ export async function compile(task, opts) {
'client',
'telemetry',
'nextserver',
'nextserver_wasm',
// we compile this each time so that fresh runtime data is pulled
// before each publish
'ncc_amp_optimizer',
......@@ -889,6 +890,7 @@ export default async function (task) {
await task.watch('cli/**/*.+(js|ts|tsx)', 'cli', opts)
await task.watch('telemetry/**/*.+(js|ts|tsx)', 'telemetry', opts)
await task.watch('next-server/**/*.+(js|ts|tsx)', 'nextserver', opts)
await task.watch('next-server/**/*.+(wasm)', 'nextserver_wasm', opts)
}
export async function nextserver(task, opts) {
......@@ -899,6 +901,13 @@ export async function nextserver(task, opts) {
notify('Compiled server files')
}
export async function nextserver_wasm(task, opts) {
await task
.source(opts.src || 'next-server/**/*.+(wasm)')
.target('dist/next-server')
notify('Moved server wasm files')
}
export async function release(task) {
await task.clear('dist').start('build')
}
......
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import isAnimated from 'next/dist/compiled/is-animated'
import sizeOf from 'image-size'
import {
killApp,
fetchViaHTTP,
File,
findPort,
killApp,
launchApp,
fetchViaHTTP,
nextBuild,
nextStart,
File,
waitFor,
} from 'next-test-utils'
import sharp from 'sharp'
import isAnimated from 'next/dist/compiled/is-animated'
import { join } from 'path'
jest.setTimeout(1000 * 60 * 2)
......@@ -40,8 +40,8 @@ async function fsToJson(dir, output = {}) {
async function expectWidth(res, w) {
const buffer = await res.buffer()
const meta = await sharp(buffer).metadata()
expect(meta.width).toBe(w)
const d = sizeOf(buffer)
expect(d.width).toBe(w)
}
function runTests({ w, isDev, domains }) {
......@@ -284,7 +284,7 @@ function runTests({ w, isDev, domains }) {
'public, max-age=0, must-revalidate'
)
expect(res.headers.get('etag')).toBeTruthy()
await expectWidth(res, w)
// FIXME: await expectWidth(res, w)
})
it('should resize relative url with invalid accept header as tiff', async () => {
......@@ -297,7 +297,7 @@ function runTests({ w, isDev, domains }) {
'public, max-age=0, must-revalidate'
)
expect(res.headers.get('etag')).toBeTruthy()
await expectWidth(res, w)
// FIXME: await expectWidth(res, w)
})
it('should resize relative url and Chrome accept header as webp', async () => {
......
This diff is collapsed.
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