Unverified Commit fafbea8b authored by Kiko Beats's avatar Kiko Beats Committed by GitHub

Use Edge Runtime for running Edge Functions locally (#37024)

This PR introduces [Edge Runtime](https://edge-runtime.vercel.app/) for emulating [Edge Functions](https://vercel.com/features/edge-functions) locally.

Every time you run a [middleware](https://nextjs.org/docs/advanced-features/middleware) locally via `next dev`, an isolated edge runtime context will be created.

These contexts have the same constraints as production servers, plus they don't pollute the global scope; Instead, all the code run in a vm on top of a Node.js process.

Additionally, `@edge-runtime/jest-environment` has been added to make easier testing Edge Functions in a programmatic way.

It dropped the following polyfills from Next.js codebase, since they are now part of Edge Runtime:

- abort-controller
- formdata
- uuid
- web-crypto
- web-streams
Co-authored-by: 's avatarGal Schlezinger <2054772+Schniz@users.noreply.github.com>
parent ec572b0b
const escape = require('shell-quote').quote
const { quote } = require('shell-quote')
const { ESLint } = require('eslint')
const eslint = new ESLint()
......@@ -26,3 +26,8 @@ module.exports = {
]
},
}
function escape(str) {
const escaped = quote(str)
return escaped.replace(/\\@/g, '@')
}
......@@ -54,6 +54,7 @@
"@babel/plugin-proposal-object-rest-spread": "7.14.7",
"@babel/preset-flow": "7.14.5",
"@babel/preset-react": "7.14.5",
"@edge-runtime/jest-environment": "1.0.1-beta.10",
"@fullhuman/postcss-purgecss": "1.3.0",
"@mdx-js/loader": "0.18.0",
"@next/bundle-analyzer": "workspace:*",
......@@ -191,7 +192,6 @@
"turbo": "1.2.9",
"typescript": "4.6.3",
"wait-port": "0.2.2",
"web-streams-polyfill": "2.1.1",
"webpack": "link:./node_modules/webpack5",
"webpack-bundle-analyzer": "4.3.0",
"worker-loader": "3.0.7"
......
This diff is collapsed.
{"name":"@edge-runtime/primitives","version":"1.0.1-beta.10","main":"./index.js","license":"MPLv2"}
{"name":"@peculiar/webcrypto","main":"webcrypto.js","author":"PeculiarVentures","license":"MIT"}
MIT License
Copyright (c) 2017 Toru Nagashima
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{"name":"abort-controller","main":"abort-controller.js","author":"Toru Nagashima (https://github.com/mysticatea)","license":"MIT"}
This diff is collapsed.
{"name":"edge-runtime","main":"index.js","license":"MPLv2"}
The MIT License (MIT)
Copyright (c) 2017-present Nick K.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{"name":"formdata-node","main":"index.js","author":"Nick K. <io@octetstream.me>","license":"MIT"}
{"name":"uuid","main":"index.js","license":"MIT"}
The MIT License (MIT)
Copyright (c) 2020 Mattias Buelens
Copyright (c) 2016 Diwank Singh Tomer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{"name":"web-streams-polyfill","main":"ponyfill.js","author":"Mattias Buelens <mattias@buelens.com>","license":"MIT"}
......@@ -115,6 +115,8 @@
"@babel/runtime": "7.15.4",
"@babel/traverse": "7.15.0",
"@babel/types": "7.15.0",
"@edge-runtime/primitives": "1.0.1-beta.10",
"@edge-runtime/vm": "1.0.1-beta.10",
"@hapi/accept": "5.0.2",
"@napi-rs/cli": "2.4.4",
"@napi-rs/triples": "1.1.0",
......@@ -123,7 +125,6 @@
"@next/react-dev-overlay": "12.1.7-canary.23",
"@next/react-refresh-utils": "12.1.7-canary.23",
"@next/swc": "12.1.7-canary.23",
"@peculiar/webcrypto": "1.3.1",
"@taskr/clear": "1.1.0",
"@taskr/esnext": "1.1.0",
"@taskr/watch": "1.1.0",
......@@ -192,11 +193,11 @@
"debug": "4.1.1",
"devalue": "2.0.1",
"domain-browser": "4.19.0",
"edge-runtime": "1.0.1-beta.10",
"etag": "1.8.1",
"events": "3.3.0",
"find-cache-dir": "3.3.1",
"find-up": "4.1.0",
"formdata-node": "4.3.0",
"fresh": "0.5.2",
"get-orientation": "1.1.2",
"glob": "7.1.7",
......@@ -268,7 +269,6 @@
"uuid": "8.3.2",
"vm-browserify": "1.1.2",
"watchpack": "2.3.1",
"web-streams-polyfill": "3.0.3",
"web-vitals": "2.1.0",
"webpack-sources1": "npm:webpack-sources@1.4.3",
"webpack-sources3": "npm:webpack-sources@3.2.3",
......
import Primitives from 'next/dist/compiled/@edge-runtime/primitives'
import type { IncomingMessage } from 'http'
import { Readable } from 'stream'
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
type BodyStream = ReadableStream<Uint8Array>
......@@ -8,7 +8,7 @@ type BodyStream = ReadableStream<Uint8Array>
* Creates a ReadableStream from a Node.js HTTP request
*/
function requestToBodyStream(request: IncomingMessage): BodyStream {
const transform = new TransformStream<Uint8Array, Uint8Array>({
const transform = new Primitives.TransformStream<Uint8Array, Uint8Array>({
start(controller) {
request.on('data', (chunk) => controller.enqueue(chunk))
request.on('end', () => controller.terminate())
......
import {
ReadableStream,
TransformStream,
} from 'next/dist/compiled/web-streams-polyfill'
import Primitives from 'next/dist/compiled/@edge-runtime/primitives'
// Polyfill Web Streams for the Node.js runtime.
if (!global.ReadableStream) {
global.ReadableStream = ReadableStream
global.ReadableStream = Primitives.ReadableStream
}
if (!global.TransformStream) {
global.TransformStream = TransformStream
global.TransformStream = Primitives.TransformStream
}
......@@ -5,7 +5,7 @@ import { fromNodeHeaders } from './utils'
import { NextFetchEvent } from './spec-extension/fetch-event'
import { NextRequest } from './spec-extension/request'
import { NextResponse } from './spec-extension/response'
import { waitUntilSymbol } from './spec-compliant/fetch-event'
import { waitUntilSymbol } from './spec-extension/fetch-event'
import { NextURL } from './next-url'
export async function adapter(params: {
......
import { isBlob } from './is'
import { streamToIterator } from './utils'
const carriage = '\r\n'
const dashes = '--'
const carriageLength = 2
function escape(str: string) {
return str.replace(/"/g, '\\"')
}
function getFooter(boundary: string) {
return `${dashes}${boundary}${dashes}${carriage.repeat(2)}`
}
function getHeader(boundary: string, name: string, field: FormDataEntryValue) {
let header = ''
header += `${dashes}${boundary}${carriage}`
header += `Content-Disposition: form-data; name="${escape(name)}"`
if (isBlob(field)) {
header += `; filename="${escape(field.name)}"${carriage}`
header += `Content-Type: ${field.type || 'application/octet-stream'}`
}
return `${header}${carriage.repeat(2)}`
}
export function getBoundary() {
const array = new Uint8Array(32)
crypto.getRandomValues(array)
let str = ''
for (var i = 0; i < array.length; i++) {
str += array[i].toString(16).padStart(2, '0')
}
return str
}
export async function* formDataIterator(
form: FormData,
boundary: string
): AsyncIterableIterator<Uint8Array> {
const encoder = new TextEncoder()
for (const [name, value] of form) {
yield encoder.encode(getHeader(boundary, name, value))
if (isBlob(value)) {
const stream: ReadableStream<Uint8Array> = value.stream()
yield* streamToIterator(stream)
} else {
yield encoder.encode(value)
}
yield encoder.encode(carriage)
}
yield encoder.encode(getFooter(boundary))
}
export function getFormDataLength(form: FormData, boundary: string) {
let length = 0
for (const [name, value] of form) {
length += Buffer.byteLength(getHeader(boundary, name, value))
length += isBlob(value) ? value.size : Buffer.byteLength(String(value))
length += carriageLength
}
length += Buffer.byteLength(getFooter(boundary))
return length
}
/**
* The ArrayBuffer object is used to represent a generic, fixed-length raw
* binary data buffer. It is an array of bytes, often referred to in other
* languages as a "byte array". You cannot directly manipulate the contents of
* an ArrayBuffer; instead, you create one of the typed array objects or a
* DataView object which represents the buffer in a specific format, and use
* that to read and write the contents of the buffer.
*/
export function isArrayBuffer(value: any): value is ArrayBuffer {
return ArrayBuffer.prototype.isPrototypeOf(value)
}
/**
* ArrayBufferView is a helper type representing any of the following JS
* TypedArray types which correspond to the list below. It is checked by duck
* typing the provided object.
*/
export function isArrayBufferView(value: any): value is ArrayBufferView {
return ArrayBuffer.isView(value)
}
/**
* The DataView view provides a low-level interface for reading and writing
* multiple number types in a binary ArrayBuffer, without having to care about
* the platform's endianness.
*/
export function isDataView(value: any): value is DataView {
return DataView.prototype.isPrototypeOf(value)
}
/**
* The URLSearchParams interface defines utility methods to work with the
* query string of a URL.
*/
export function isURLSearchParams(value: any): value is URLSearchParams {
return URLSearchParams.prototype.isPrototypeOf(value)
}
/**
* The Blob object represents a blob, which is a file-like object of immutable,
* raw data; they can be read as text or binary data. Blobs can represent data
* that isn't necessarily in a JavaScript-native format.
*/
export function isBlob(value: any): value is Blob {
return Blob.prototype.isPrototypeOf(value)
}
/**
* The FormData interface provides a way to easily construct a set of key/value
* pairs representing form fields and their values, which can then be easily
* sent using the XMLHttpRequest.send() method. It uses the same format a
* form would use if the encoding type were set to "multipart/form-data".
*/
export function isFormData(value: any): value is FormData {
return FormData.prototype.isPrototypeOf(value)
}
/**
* The ReadableStream interface of the Streams API represents a readable stream
* of byte data. Because we want to allow alternative implementations we also
* duck type here.
*/
export function isReadableStream(value: any): value is ReadableStream {
return (
value &&
(ReadableStream.prototype.isPrototypeOf(value) ||
(value.constructor.name === 'ReadableStream' && 'getReader' in value))
)
}
/**
* Checks in an object implements an Iterable interface
*/
export function isIterable(object: any): object is Iterable<unknown> {
return (
object &&
Symbol.iterator in object &&
typeof object[Symbol.iterator] === 'function'
)
}
This diff is collapsed.
import { Crypto as WebCrypto } from 'next/dist/compiled/@peculiar/webcrypto'
import { CryptoKey } from 'next/dist/compiled/@peculiar/webcrypto'
import { v4 as uuid } from 'next/dist/compiled/uuid'
import crypto from 'crypto'
export function atob(b64Encoded: string) {
return Buffer.from(b64Encoded, 'base64').toString('binary')
}
export function btoa(str: string) {
return Buffer.from(str, 'binary').toString('base64')
}
export { CryptoKey }
export class Crypto extends WebCrypto {
// @ts-ignore Remove once types are updated and we deprecate node 12
randomUUID = crypto.randomUUID || uuid
}
import type { Context } from 'vm'
import { dirname } from 'path'
import { readFileSync } from 'fs'
import { runInContext } from 'vm'
/**
* Allows to require a series of dependencies provided by their path
* into a provided module context. It fills and accepts a require
* cache to ensure each module is loaded once.
*/
export function requireDependencies(params: {
context: Context
requireCache: Map<string, any>
dependencies: {
mapExports: { [key: string]: string }
path: string
}[]
}) {
const { context, requireCache, dependencies } = params
const requireFn = createRequire(context, requireCache)
for (const { path, mapExports } of dependencies) {
const mod = requireFn(path, path)
for (const mapKey of Object.keys(mapExports)) {
context[mapExports[mapKey]] = mod[mapKey]
}
}
}
function createRequire(context: Context, cache: Map<string, any>) {
return function requireFn(referrer: string, specifier: string) {
const resolved = require.resolve(specifier, {
paths: [dirname(referrer)],
})
const cached = cache.get(resolved)
if (cached !== undefined) {
return cached.exports
}
const module = {
exports: {},
loaded: false,
id: resolved,
}
cache.set(resolved, module)
const fn = runInContext(
`(function(module,exports,require,__dirname,__filename) {${readFileSync(
resolved,
'utf-8'
)}\n})`,
context
)
try {
fn(
module,
module.exports,
requireFn.bind(null, resolved),
dirname(resolved),
resolved
)
} finally {
cache.delete(resolved)
}
module.loaded = true
return module.exports
}
}
......@@ -11,8 +11,8 @@ export async function run(params: {
useCache: boolean
wasm: WasmBinding[]
}): Promise<FetchEventResult> {
const { runInContext, context } = await getModuleContext({
module: params.name,
const { runtime, evaluateInContext } = await getModuleContext({
moduleName: params.name,
onWarning: params.onWarning,
useCache: params.useCache !== false,
env: params.env,
......@@ -20,7 +20,7 @@ export async function run(params: {
})
for (const paramPath of params.paths) {
runInContext(paramPath)
evaluateInContext(paramPath)
}
const subreq = params.request.headers[`x-middleware-subrequest`]
......@@ -28,7 +28,7 @@ export async function run(params: {
if (subrequests.includes(params.name)) {
return {
waitUntil: Promise.resolve(),
response: new context.Response(null, {
response: new runtime.context.Response(null, {
headers: {
'x-middleware-next': '1',
},
......@@ -36,7 +36,7 @@ export async function run(params: {
}
}
return context._ENTRIES[`middleware_${params.name}`].default({
return runtime.context._ENTRIES[`middleware_${params.name}`].default({
request: params.request,
})
}
import { formDataIterator, getBoundary } from '../form-data'
import { streamToIterator } from '../utils'
import * as util from '../is'
const INTERNALS = Symbol('internal body')
abstract class BaseBody implements Body {
abstract headers: Headers
[INTERNALS]: {
bodyInit?: BodyInit
boundary?: string
disturbed: boolean
stream?: ReadableStream<Uint8Array> | null
}
constructor(bodyInit?: BodyInit) {
this[INTERNALS] = {
bodyInit: bodyInit,
disturbed: false,
}
if (util.isFormData(bodyInit)) {
this[INTERNALS].boundary = getBoundary()
}
}
get body(): ReadableStream<Uint8Array> | null {
const body = this[INTERNALS].bodyInit
if (!body) {
return null
}
const that = this
if (!this[INTERNALS].stream) {
const readable = new ReadableStream({
async start(controller) {
if (typeof body === 'string') {
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(body))
} else if (util.isBlob(body)) {
const buffer = await body.arrayBuffer()
controller.enqueue(new Uint8Array(buffer))
} else if (util.isDataView(body)) {
controller.enqueue(body)
} else if (util.isArrayBuffer(body)) {
controller.enqueue(body)
} else if (util.isArrayBufferView(body)) {
controller.enqueue(body)
} else if (util.isURLSearchParams(body)) {
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(body.toString()))
} else if (util.isFormData(body)) {
for await (const chunk of formDataIterator(
body,
that[INTERNALS].boundary!
)) {
controller.enqueue(chunk)
}
} else if (util.isReadableStream(body)) {
for await (const chunk of streamToIterator(body)) {
if (chunk.length) {
controller.enqueue(chunk)
}
}
} else {
const text = Object.prototype.toString.call(body)
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(text))
}
controller.close()
},
})
// Spy on reading chunks to set the stream as disturbed
const getReader = readable.getReader.bind(readable)
readable.getReader = () => {
const reader = getReader()
const read = reader.read.bind(reader)
reader.read = () => {
this[INTERNALS].disturbed = true
return read()
}
return reader
}
this[INTERNALS].stream = readable
}
return this[INTERNALS].stream!
}
get bodyUsed(): boolean {
return this[INTERNALS].disturbed
}
_consume() {
if (this[INTERNALS].disturbed) {
return Promise.reject(
new TypeError(
`Body has already been used. It can only be used once. Use tee() first if you need to read it twice.`
)
)
}
this[INTERNALS].disturbed = true
const body = this.body
return new Promise<Uint8Array>((resolve, reject) => {
let buffer = new Uint8Array(0)
if (!body) {
return resolve(buffer)
}
const reader = body.getReader()
;(function pump() {
reader.read().then(({ value, done }) => {
if (done) {
return resolve(buffer)
} else if (value) {
const merge = new Uint8Array(buffer.length + value.length)
merge.set(buffer)
merge.set(value, buffer.length)
buffer = merge
}
pump()
}, reject)
})()
})
}
async arrayBuffer() {
const buffer = await this._consume()
const arrayBuffer = new ArrayBuffer(buffer.length)
const view = new Uint8Array(arrayBuffer)
for (let i = 0; i < buffer.length; ++i) {
view[i] = buffer[i]
}
return arrayBuffer
}
async blob() {
const buffer = await this._consume()
return new Blob([buffer])
}
async formData() {
const bodyInit = this[INTERNALS].bodyInit
if (util.isURLSearchParams(bodyInit)) {
const form = new FormData()
for (const [key, value] of bodyInit) {
form.append(key, value)
}
return form
} else if (util.isFormData(bodyInit)) {
return bodyInit
} else {
throw new TypeError(
`Unrecognized Content-Type header value. FormData can only parse the following MIME types: multipart/form-data, application/x-www-form-urlencoded.`
)
}
}
async text() {
const decoder = new TextDecoder()
const buffer = await this._consume()
return decoder.decode(buffer)
}
async json() {
const text = await this.text()
try {
return JSON.parse(text)
} catch (err: any) {
throw new TypeError(`invalid json body reason: ${err.message}`)
}
}
}
export { BaseBody as Body }
export type BodyInit =
| null
| string
| Blob
| BufferSource
| FormData
| URLSearchParams
| ReadableStream<Uint8Array>
export function extractContentType(instance: BaseBody) {
const body = instance[INTERNALS].bodyInit
if (typeof body === 'string') {
return 'text/plain;charset=UTF-8'
} else if (util.isBlob(body)) {
return body.type
} else if (util.isDataView(body)) {
return null
} else if (util.isArrayBuffer(body)) {
return null
} else if (util.isArrayBufferView(body)) {
return null
} else if (util.isURLSearchParams(body)) {
return 'application/x-www-form-urlencoded;charset=UTF-8'
} else if (util.isFormData(body)) {
return `multipart/form-data;boundary=${instance[INTERNALS].boundary}`
} else if (util.isReadableStream(body)) {
return null
} else {
return 'text/plain;charset=UTF-8'
}
}
export function cloneBody(instance: BaseBody) {
if (instance.bodyUsed) {
throw new Error('cannot clone body after it is used')
}
const body = instance[INTERNALS].bodyInit
if (util.isReadableStream(body)) {
const [r1, r2] = body.tee()
instance[INTERNALS].bodyInit = r1
return r2
}
return body || null
}
export function getInstanceBody(instance: BaseBody) {
return instance[INTERNALS].bodyInit
}
export const responseSymbol = Symbol('response')
export const passThroughSymbol = Symbol('passThrough')
export const waitUntilSymbol = Symbol('waitUntil')
export class FetchEvent {
readonly [waitUntilSymbol]: Promise<any>[] = [];
[responseSymbol]?: Promise<Response>;
[passThroughSymbol] = false
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(_request: Request) {}
respondWith(response: Response | Promise<Response>): void {
if (!this[responseSymbol]) {
this[responseSymbol] = Promise.resolve(response)
}
}
passThroughOnException(): void {
this[passThroughSymbol] = true
}
waitUntil(promise: Promise<any>): void {
this[waitUntilSymbol].push(promise)
}
}
import { isIterable } from '../is'
export type HeadersInit = Headers | string[][] | { [key: string]: string }
const MAP = Symbol('map')
const INTERNAL = Symbol('internal')
const INVALID_TOKEN_REGEX = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/
const INVALID_HEADER_CHAR_REGEX = /[^\t\x20-\x7e\x80-\xff]/
class BaseHeaders implements Headers {
[MAP]: { [k: string]: string[] } = {}
constructor(init?: HeadersInit) {
if (init instanceof BaseHeaders) {
const rawHeaders = init.raw()
for (const headerName of Object.keys(rawHeaders)) {
for (const value of rawHeaders[headerName]) {
this.append(headerName, value)
}
}
} else if (isIterable(init)) {
const pairs = []
for (const pair of init) {
if (!isIterable(pair)) {
throw new TypeError('Each header pair must be iterable')
}
pairs.push(Array.from(pair))
}
for (const pair of pairs) {
if (pair.length !== 2) {
throw new TypeError('Each header pair must be a name/value tuple')
}
this.append(pair[0], pair[1])
}
} else if (typeof init === 'object') {
for (const key of Object.keys(init)) {
this.append(key, init[key])
}
} else if (init) {
throw new TypeError('Provided initializer must be an object')
}
}
get(name: string) {
const _name = `${name}`
validateName(_name)
const key = find(this[MAP], _name)
if (key === undefined) {
return null
}
return this[MAP][key].join(', ')
}
forEach(
callback: (value: string, name: string, parent: BaseHeaders) => void,
thisArg: any = undefined
): void {
let pairs = getHeaders(this)
let i = 0
while (i < pairs.length) {
const [name, value] = pairs[i]
callback.call(thisArg, value, name, this)
pairs = getHeaders(this)
i++
}
}
set(name: string, value: string) {
name = `${name}`
value = `${value}`
validateName(name)
validateValue(value)
const key = find(this[MAP], name)
this[MAP][key !== undefined ? key : name] = [value]
}
append(name: string, value: string) {
name = `${name}`
value = `${value}`
validateName(name)
validateValue(value)
const key = find(this[MAP], name)
if (key !== undefined) {
this[MAP][key].push(value)
} else {
this[MAP][name] = [value]
}
}
has(name: string) {
name = `${name}`
validateName(name)
return find(this[MAP], name) !== undefined
}
delete(name: string) {
name = `${name}`
validateName(name)
const key = find(this[MAP], name)
if (key !== undefined) {
delete this[MAP][key]
}
}
raw() {
return this[MAP]
}
keys() {
return createHeadersIterator(this, 'key')
}
values() {
return createHeadersIterator(this, 'value')
}
entries() {
return createHeadersIterator(this, 'key+value')
}
[Symbol.iterator]() {
return createHeadersIterator(this, 'key+value')
}
}
function createHeadersIterator(
target: BaseHeaders,
kind: 'key' | 'value' | 'key+value'
) {
const iterator = Object.create(HeadersIteratorPrototype)
iterator[INTERNAL] = {
target,
kind,
index: 0,
}
return iterator
}
function validateName(name: string) {
name = `${name}`
if (INVALID_TOKEN_REGEX.test(name)) {
throw new TypeError(`${name} is not a legal HTTP header name`)
}
}
function validateValue(value: string) {
value = `${value}`
if (INVALID_HEADER_CHAR_REGEX.test(value)) {
throw new TypeError(`${value} is not a legal HTTP header value`)
}
}
function find(
map: { [k: string]: string[] },
name: string
): string | undefined {
name = name.toLowerCase()
for (const key in map) {
if (key.toLowerCase() === name) {
return key
}
}
return undefined
}
Object.defineProperty(BaseHeaders.prototype, Symbol.toStringTag, {
value: 'Headers',
writable: false,
enumerable: false,
configurable: true,
})
Object.defineProperties(BaseHeaders.prototype, {
append: { enumerable: true },
delete: { enumerable: true },
entries: { enumerable: true },
forEach: { enumerable: true },
get: { enumerable: true },
has: { enumerable: true },
keys: { enumerable: true },
raw: { enumerable: false },
set: { enumerable: true },
values: { enumerable: true },
})
function getHeaders(
headers: BaseHeaders,
kind: 'key' | 'value' | 'key+value' = 'key+value'
) {
const fn =
kind === 'key'
? (key: string) => key.toLowerCase()
: kind === 'value'
? (key: string) => headers[MAP][key].join(', ')
: (key: string) => [key.toLowerCase(), headers[MAP][key].join(', ')]
return Object.keys(headers[MAP])
.sort()
.map((key) => fn(key))
}
const HeadersIteratorPrototype = Object.setPrototypeOf(
{
next() {
if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
throw new TypeError('Value of `this` is not a HeadersIterator')
}
const { target, kind, index } = this[INTERNAL]
const values = getHeaders(target, kind)
const len = values.length
if (index >= len) {
return {
value: undefined,
done: true,
}
}
this[INTERNAL].index = index + 1
return {
value: values[index],
done: false,
}
},
},
Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
)
Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
value: 'HeadersIterator',
writable: false,
enumerable: false,
configurable: true,
})
export { BaseHeaders as Headers }
import { Body, cloneBody, extractContentType, getInstanceBody } from './body'
import { Headers as BaseHeaders } from './headers'
import { NextURL } from '../next-url'
import { notImplemented } from '../utils'
export const INTERNALS = Symbol('internal request')
class BaseRequest extends Body implements Request {
[INTERNALS]: {
credentials: RequestCredentials
headers: Headers
method: string
referrer: string
redirect: RequestRedirect
url: NextURL
}
constructor(input: BaseRequest | string, init: RequestInit = {}) {
const method =
init.method?.toUpperCase() ??
(input instanceof BaseRequest ? input.method?.toUpperCase() : 'GET')
if (
(method === 'GET' || method === 'HEAD') &&
(init.body || (input instanceof BaseRequest && getInstanceBody(input)))
) {
throw new TypeError('Request with GET/HEAD method cannot have body')
}
let inputBody: BodyInit | null = null
if (init.body) {
inputBody = init.body
} else if (input instanceof BaseRequest && getInstanceBody(input)) {
inputBody = cloneBody(input)
}
super(inputBody)
const headers = new BaseHeaders(
init.headers || getProp(input, 'headers') || {}
)
if (inputBody !== null) {
const contentType = extractContentType(this)
if (contentType !== null && !headers.has('Content-Type')) {
headers.append('Content-Type', contentType)
}
}
this[INTERNALS] = {
credentials:
init.credentials || getProp(input, 'credentials') || 'same-origin',
headers,
method,
referrer: init.referrer || 'about:client',
redirect: init.redirect || getProp(input, 'redirect') || 'follow',
url: new NextURL(typeof input === 'string' ? input : input.url),
}
}
get url() {
return this[INTERNALS].url.toString()
}
get credentials() {
return this[INTERNALS].credentials
}
get method() {
return this[INTERNALS].method
}
get referrer() {
return this[INTERNALS].referrer
}
get headers() {
return this[INTERNALS].headers
}
get redirect() {
return this[INTERNALS].redirect
}
public clone() {
return new BaseRequest(this)
}
get cache() {
return notImplemented('Request', 'cache')
}
get integrity() {
return notImplemented('Request', 'integrity')
}
get keepalive() {
return notImplemented('Request', 'keepalive')
}
get mode() {
return notImplemented('Request', 'mode')
}
get destination() {
return notImplemented('Request', 'destination')
}
get referrerPolicy() {
return notImplemented('Request', 'referrerPolicy')
}
get signal() {
return notImplemented('Request', 'signal')
}
get [Symbol.toStringTag]() {
return 'Request'
}
}
export { BaseRequest as Request }
function getProp<K extends keyof BaseRequest>(
input: BaseRequest | string,
key: K
): BaseRequest[K] | undefined {
return input instanceof BaseRequest ? input[key] : undefined
}
import { Body, BodyInit, cloneBody, extractContentType } from './body'
import { NextURL } from '../next-url'
import { validateURL } from '../utils'
const INTERNALS = Symbol('internal response')
const REDIRECTS = new Set([301, 302, 303, 307, 308])
class BaseResponse extends Body implements Response {
[INTERNALS]: {
headers: Headers
status: number
statusText: string
type: 'default' | 'error'
url?: NextURL
}
constructor(body?: BodyInit | null, init?: ResponseInit) {
super(body)
this[INTERNALS] = {
headers: new Headers(init?.headers),
status: init?.status || 200,
statusText: init?.statusText || '',
type: 'default',
url: init?.url ? new NextURL(init.url) : undefined,
}
if (this[INTERNALS].status < 200 || this[INTERNALS].status > 599) {
throw new RangeError(
`Responses may only be constructed with status codes in the range 200 to 599, inclusive.`
)
}
if (body !== null && !this[INTERNALS].headers.has('Content-Type')) {
const contentType = extractContentType(this)
if (contentType) {
this[INTERNALS].headers.append('Content-Type', contentType)
}
}
}
static redirect(url: string, status = 307) {
if (!REDIRECTS.has(status)) {
throw new RangeError(
'Failed to execute "redirect" on "response": Invalid status code'
)
}
return new Response(null, {
headers: { Location: validateURL(url) },
status,
})
}
static error() {
const response = new BaseResponse(null, { status: 0, statusText: '' })
response[INTERNALS].type = 'error'
return response
}
get url() {
return this[INTERNALS].url?.toString() || ''
}
get ok() {
return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300
}
get status() {
return this[INTERNALS].status
}
get statusText() {
return this[INTERNALS].statusText
}
get headers() {
return this[INTERNALS].headers
}
get redirected() {
return (
this[INTERNALS].status > 299 &&
this[INTERNALS].status < 400 &&
this[INTERNALS].headers.has('Location')
)
}
get type() {
return this[INTERNALS].type
}
clone() {
return new BaseResponse(cloneBody(this), {
headers: this.headers,
status: this.status,
statusText: this.statusText,
url: this.url,
})
}
get [Symbol.toStringTag]() {
return 'Response'
}
}
export interface ResponseInit {
headers?: HeadersInit
status?: number
statusText?: string
url?: string
}
export { BaseResponse as Response }
import { DeprecationError } from '../error'
import { FetchEvent } from '../spec-compliant/fetch-event'
import { NextRequest } from './request'
const responseSymbol = Symbol('response')
const passThroughSymbol = Symbol('passThrough')
export const waitUntilSymbol = Symbol('waitUntil')
class FetchEvent {
readonly [waitUntilSymbol]: Promise<any>[] = [];
[responseSymbol]?: Promise<Response>;
[passThroughSymbol] = false
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(_request: Request) {}
respondWith(response: Response | Promise<Response>): void {
if (!this[responseSymbol]) {
this[responseSymbol] = Promise.resolve(response)
}
}
passThroughOnException(): void {
this[passThroughSymbol] = true
}
waitUntil(promise: Promise<any>): void {
this[waitUntilSymbol].push(promise)
}
}
export class NextFetchEvent extends FetchEvent {
sourcePage: string
......
......@@ -2,7 +2,7 @@ import type { I18NConfig } from '../../config-shared'
import type { RequestData } from '../types'
import { NextURL } from '../next-url'
import { isBot } from '../../utils'
import { toNodeHeaders } from '../utils'
import { toNodeHeaders, validateURL } from '../utils'
import parseua from 'next/dist/compiled/ua-parser-js'
import { NextCookies } from './cookies'
......@@ -20,14 +20,15 @@ export class NextRequest extends Request {
}
constructor(input: Request | string, init: RequestInit = {}) {
const url = typeof input === 'string' ? input : input.url
validateURL(url)
super(input, init)
this[INTERNALS] = {
cookies: new NextCookies(this),
geo: init.geo || {},
ip: init.ip,
page: init.page,
url: new NextURL(typeof input === 'string' ? input : input.url, {
url: new NextURL(url, {
headers: toNodeHeaders(this.headers),
nextConfig: init.nextConfig,
}),
......
import type { NodeHeaders } from './types'
export async function* streamToIterator<T>(
readable: ReadableStream<T>
): AsyncIterableIterator<T> {
const reader = readable.getReader()
while (true) {
const { value, done } = await reader.read()
if (done) break
if (value) {
yield value
}
}
reader.releaseLock()
}
export function notImplemented(name: string, method: string): any {
throw new Error(
`Failed to get the '${method}' property on '${name}': the property is not implemented`
)
}
export function fromNodeHeaders(object: NodeHeaders): Headers {
const headers = new Headers()
for (let [key, value] of Object.entries(object)) {
......
......@@ -83,7 +83,6 @@ export const EDGE_UNSUPPORTED_NODE_APIS = [
'CountQueuingStrategy',
'DecompressionStream',
'DomException',
'Event',
'EventTarget',
'MessageChannel',
'MessageEvent',
......
......@@ -8,5 +8,15 @@ export function isPlainObject(value: any): boolean {
}
const prototype = Object.getPrototypeOf(value)
return prototype === null || prototype === Object.prototype
/**
* this used to be previously:
*
* `return prototype === null || prototype === Object.prototype`
*
* but Edge Runtime expose Object from vm, being that kind of type-checking wrongly fail.
*
* It was changed to the current implementation since it's resilient to serialization.
*/
return prototype === null || prototype.hasOwnProperty('isPrototypeOf')
}
......@@ -144,6 +144,39 @@ export async function ncc_acorn(task, opts) {
.target('compiled/acorn')
}
// eslint-disable-next-line camelcase
externals['@edge-runtime/primitives'] =
'next/dist/compiled/@edge-runtime/primitives'
export async function ncc_edge_runtime_primitives() {
// `@edge-runtime/primitives` is precompiled and pre-bundled
// so we vendor the package as it is.
const dest = 'compiled/@edge-runtime/primitives'
const pkg = await fs.readJson(
require.resolve('@edge-runtime/primitives/package.json')
)
await fs.remove(dest)
await fs.outputJson(join(dest, 'package.json'), {
name: '@edge-runtime/primitives',
version: pkg.version,
main: './index.js',
license: pkg.license,
})
await fs.copy(
require.resolve('@edge-runtime/primitives'),
join(dest, 'index.js')
)
}
// eslint-disable-next-line camelcase
externals['edge-runtime'] = 'next/dist/compiled/edge-runtime'
export async function ncc_edge_runtime(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('edge-runtime')))
.ncc({ packageName: 'edge-runtime', externals })
.target('compiled/edge-runtime')
}
// eslint-disable-next-line camelcase
export async function ncc_next__react_dev_overlay(task, opts) {
const overlayExternals = {
......@@ -1533,35 +1566,6 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
.target('compiled/mini-css-extract-plugin')
}
// eslint-disable-next-line camelcase
externals['web-streams-polyfill'] = 'next/dist/compiled/web-streams-polyfill'
export async function ncc_web_streams_polyfill(task, opts) {
await task
.source(
opts.src ||
relative(__dirname, require.resolve('web-streams-polyfill/ponyfill'))
)
.ncc({ packageName: 'web-streams-polyfill', externals })
.target('compiled/web-streams-polyfill')
}
// eslint-disable-next-line camelcase
externals['abort-controller'] = 'next/dist/compiled/abort-controller'
export async function ncc_abort_controller(task, opts) {
await task
.source(
opts.src || relative(__dirname, require.resolve('abort-controller'))
)
.ncc({ packageName: 'abort-controller', externals })
.target('compiled/abort-controller')
}
// eslint-disable-next-line camelcase
externals['formdata-node'] = 'next/dist/compiled/formdata-node'
export async function ncc_formdata_node(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('formdata-node')))
.ncc({ packageName: 'formdata-node', externals })
.target('compiled/formdata-node')
}
// eslint-disable-next-line camelcase
externals['ua-parser-js'] = 'next/dist/compiled/ua-parser-js'
export async function ncc_ua_parser_js(task, opts) {
await task
......@@ -1569,25 +1573,6 @@ export async function ncc_ua_parser_js(task, opts) {
.ncc({ packageName: 'ua-parser-js', externals })
.target('compiled/ua-parser-js')
}
// eslint-disable-next-line camelcase
externals['@peculiar/webcrypto'] = 'next/dist/compiled/@peculiar/webcrypto'
export async function ncc_webcrypto(task, opts) {
await task
.source(
opts.src || relative(__dirname, require.resolve('@peculiar/webcrypto'))
)
.ncc({ packageName: '@peculiar/webcrypto', externals })
.target('compiled/@peculiar/webcrypto')
}
// eslint-disable-next-line camelcase
externals['uuid'] = 'next/dist/compiled/uuid'
export async function ncc_uuid(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('uuid')))
.ncc({ packageName: 'uuid', externals })
.target('compiled/uuid')
}
// eslint-disable-next-line camelcase
export async function ncc_webpack_bundle5(task, opts) {
const bundleExternals = {
......@@ -1671,6 +1656,8 @@ export async function ncc(task, opts) {
'ncc_p_limit',
'ncc_raw_body',
'ncc_cssnano_simple',
'ncc_edge_runtime_primitives',
'ncc_edge_runtime',
'ncc_image_size',
'ncc_get_orientation',
'ncc_hapi_accept',
......@@ -1762,11 +1749,6 @@ export async function ncc(task, opts) {
'ncc_webpack_sources3',
'ncc_ws',
'ncc_ua_parser_js',
'ncc_webcrypto',
'ncc_uuid',
'ncc_formdata_node',
'ncc_web_streams_polyfill',
'ncc_abort_controller',
'ncc_minimatch',
'ncc_mini_css_extract_plugin',
],
......
......@@ -259,32 +259,10 @@ declare module 'next/dist/compiled/string-hash' {
import m from 'string-hash'
export = m
}
declare module 'next/dist/compiled/web-streams-polyfill' {
import m from 'web-streams-polyfill/ponyfill'
export = m
}
declare module 'next/dist/compiled/abort-controller' {
type BaseAbortController = typeof AbortController
type BaseAbortSignal = typeof AbortSignal
export { BaseAbortController as AbortController }
export { BaseAbortSignal as AbortSignal }
}
declare module 'next/dist/compiled/ua-parser-js' {
import m from 'ua-parser-js'
export = m
}
declare module 'next/dist/compiled/formdata-node' {
import m from 'formdata-node'
export = m
}
declare module 'next/dist/compiled/@peculiar/webcrypto' {
import m from '@peculiar/webcrypto'
export = m
}
declare module 'next/dist/compiled/uuid' {
import m from 'uuid'
export = m
}
declare module 'next/dist/compiled/strip-ansi' {
import m from 'strip-ansi'
export = m
......@@ -346,6 +324,16 @@ declare module 'next/dist/compiled/process' {
export = m
}
declare module 'next/dist/compiled/edge-runtime' {
import m from 'edge-runtime'
export = m
}
declare module 'next/dist/compiled/@edge-runtime/primitives' {
import * as m from '@edge-runtime/primitives'
export = m
}
declare module 'pnp-webpack-plugin' {
import webpack from 'webpack4'
......
This diff is collapsed.
// Use CJS format for represent next/dist/compiled/node-polyfill-web-streams.js
const Primitives =
require('next/dist/compiled/@edge-runtime/primitives').default
const {
WritableStreamDefaultWriter,
ReadableStream,
TransformStream,
} = require('next/dist/compiled/web-streams-polyfill')
const OriginWritableStreamWrite = WritableStreamDefaultWriter.prototype.write
const OriginWritableStreamWrite =
Primitives.WritableStreamDefaultWriter.prototype.write
// Override writable stream write method to validate chunk type.
// Currently CF workers only allow to write the encoded chunk in Uint8Array format.
WritableStreamDefaultWriter.prototype.write = function (chunk) {
Primitives.WritableStreamDefaultWriter.prototype.write = function (chunk) {
if (!(chunk instanceof Uint8Array)) {
throw new Error('Writing non-Uint8Array chunks in a stream is not allowed.')
}
return OriginWritableStreamWrite.call(this, chunk)
}
global.ReadableStream = ReadableStream
global.TransformStream = TransformStream
global.ReadableStream = Primitives.ReadableStream
global.TransformStream = Primitives.TransformStream
......@@ -189,18 +189,18 @@ function tests(context, locale = '') {
})
it(`should accept a URL instance for fetch`, async () => {
const res = await fetchViaHTTP(context.appPort, '/fetch-url')
const response = readMiddlewareJSON(res)
expect(response).toHaveProperty('error.name')
expect(response.error.name).not.toBe('TypeError')
const response = await fetchViaHTTP(context.appPort, '/fetch-url')
const { error } = readMiddlewareJSON(response)
expect(error).toBeTruthy()
expect(error.message).not.toContain("Failed to construct 'URL'")
})
it(`should allow to abort a fetch request`, async () => {
const res = await fetchViaHTTP(context.appPort, '/abort-controller')
const response = readMiddlewareJSON(res)
expect('error' in response).toBe(true)
expect(response.error.name).toBe('AbortError')
expect(response.error.message).toBe('The user aborted a request.')
const response = await fetchViaHTTP(context.appPort, '/abort-controller')
const payload = readMiddlewareJSON(response)
expect('error' in payload).toBe(true)
expect(payload.error.name).toBe('AbortError')
expect(payload.error.message).toBe('The operation was aborted')
})
it(`should validate & parse request url from any route`, async () => {
......@@ -250,16 +250,19 @@ function tests(context, locale = '') {
})
it('should throw when using Request with a relative URL', async () => {
const res = await fetchViaHTTP(context.appPort, `/url/relative-request`)
expect(readMiddlewareError(res)).toContain('Invalid URL')
const response = await fetchViaHTTP(
context.appPort,
`/url/relative-request`
)
expect(readMiddlewareError(response)).toContain(urlsError)
})
it('should throw when using NextRequest with a relative URL', async () => {
const res = await fetchViaHTTP(
const response = await fetchViaHTTP(
context.appPort,
`/url/relative-next-request`
)
expect(readMiddlewareError(res)).toContain('Invalid URL')
expect(readMiddlewareError(response)).toContain(urlsError)
})
it('should warn when using Response.redirect with a relative URL', async () => {
......
......@@ -36,9 +36,6 @@ export default function middleware({ nextUrl: { pathname } }) {
if (pathname === '/DomException') {
new DomException()
}
if (pathname === '/Event') {
new Event()
}
if (pathname === '/EventTarget') {
new EventTarget()
}
......
......@@ -27,7 +27,6 @@ const unsupportedClasses = [
'CountQueuingStrategy',
'DecompressionStream',
'DomException',
'Event',
'EventTarget',
'MessageChannel',
'MessageEvent',
......
......@@ -7,7 +7,7 @@ export const middleware: NextMiddleware = function (request) {
data: 'hello from middleware',
'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname,
'req-url-params': JSON.stringify(request.page.params),
'req-url-params': JSON.stringify(request.page.params) || '',
'req-url-page': request.page.name || '',
'req-url-query': request.nextUrl.searchParams.get('foo') || '',
'req-url-locale': request.nextUrl.locale,
......
/* eslint-env jest */
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Body } from 'next/dist/server/web/spec-compliant/body'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import { streamToIterator } from 'next/dist/server/web/utils'
import * as streams from 'web-streams-polyfill/ponyfill'
class Implementation extends Body {
headers: Headers
constructor(init: BodyInit) {
super(init)
this.headers = new Headers()
}
}
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
it('flags the body as used after reading it', async () => {
const { readable, writable } = new TransformStream()
const encoder = new TextEncoder()
const writer = writable.getWriter()
writer.write(encoder.encode(''))
writer.close()
const body = new Implementation(readable)
expect(body.bodyUsed).toEqual(false)
const reader = body.body.getReader()
expect(body.bodyUsed).toEqual(false)
while (true) {
const { done } = await reader.read()
if (done) break
}
reader.releaseLock()
expect(body.bodyUsed).toEqual(true)
})
it('throws when the body was directly consumed', async () => {
global['crypto'].getRandomValues = (array: number[]) => array
const object = { hello: 'world' }
const blob = new Blob([JSON.stringify(object, null, 2)], {
type: 'application/json',
})
const formData = new FormData()
formData.append('name', 'John')
formData.append('lastname', 'Doe')
formData.append('metadata', blob)
const body = new Implementation(formData)
// Read the body through the stream
for await (const item of streamToIterator(body.body)) {
expect(item).toBeTruthy()
}
// It allows to access again the already read stream
const reader = body.body.getReader()
const { done } = await reader.read()
expect(done).toBeTruthy()
const error = await body.text().catch((err) => err)
expect(error).toBeInstanceOf(TypeError)
expect(error.message).toEqual(
'Body has already been used. It can only be used once. Use tee() first if you need to read it twice.'
)
})
it('throws when the body was indirectly consumed', async () => {
global['crypto'].getRandomValues = (array: number[]) => array
const object = { hello: 'world' }
const blob = new Blob([JSON.stringify(object, null, 2)], {
type: 'application/json',
})
const formData = new FormData()
formData.append('name', 'John')
formData.append('lastname', 'Doe')
formData.append('metadata', blob)
const body = new Implementation(formData)
const text = await body.text()
expect(text).toBeTruthy()
const error = await body.text().catch((err) => err)
expect(error).toBeInstanceOf(TypeError)
expect(error.message).toEqual(
'Body has already been used. It can only be used once. Use tee() first if you need to read it twice.'
)
})
it('allows to read a FormData body as text', async () => {
global['crypto'].getRandomValues = (array: number[]) => array
const object = { hello: 'world' }
const blob = new Blob([JSON.stringify(object, null, 2)], {
type: 'application/json',
})
const formData = new FormData()
formData.append('name', 'John')
formData.append('lastname', 'Doe')
formData.append('metadata', blob)
const body = new Implementation(formData)
const text = await body.text()
expect(text).toMatchInlineSnapshot(`
"--0000000000000000000000000000000000000000000000000000000000000000
Content-Disposition: form-data; name=\\"name\\"
John
--0000000000000000000000000000000000000000000000000000000000000000
Content-Disposition: form-data; name=\\"lastname\\"
Doe
--0000000000000000000000000000000000000000000000000000000000000000
Content-Disposition: form-data; name=\\"metadata\\"; filename=\\"blob\\"
Content-Type: application/json
{
\\"hello\\": \\"world\\"
}
--0000000000000000000000000000000000000000000000000000000000000000--
"
`)
})
it('allows to read a null body as ArrayBuffer', async () => {
const body = new Implementation(null)
const value = await body.arrayBuffer()
expect(new Uint8Array(value)).toHaveLength(0)
})
it('allows to read a text body as ArrayBuffer', async () => {
const body = new Implementation('Hello world')
const enc = new TextEncoder()
const dec = new TextDecoder()
const value = await body.arrayBuffer()
const decoded = dec.decode(value)
expect(decoded).toEqual('Hello world')
expect(value).toEqual(enc.encode('Hello world').buffer)
})
it('allows to read a chunked body as ArrayBuffer', async () => {
const { readable, writable } = new TransformStream()
const encoder = new TextEncoder()
const writer = writable.getWriter()
writer.write(encoder.encode('Hello '))
writer.write(encoder.encode('world!'))
writer.close()
const body = new Implementation(readable)
const value = await body.arrayBuffer()
const decoder = new TextDecoder()
const decoded = decoder.decode(value)
expect(decoded).toEqual('Hello world!')
expect(value).toEqual(encoder.encode('Hello world!').buffer)
})
it('allows to read a URLSearchParams body as FormData', async () => {
const params = new URLSearchParams('q=URLUtils.searchParams&topic=api')
const body = new Implementation(params)
const formData = await body.formData()
expect(formData.get('topic')).toEqual('api')
})
it('allows to read a Blob body as Blob', async () => {
const object = { hello: 'world' }
const str = JSON.stringify(object, null, 2)
const body = new Implementation(new Blob([str]))
const blob = await body.blob()
const txt = await blob.text()
expect(txt).toEqual(str)
})
it('allows to read a text body as JSON', async () => {
const body = new Implementation(JSON.stringify({ message: 'hi', value: 10 }))
const value = await body.json()
expect(value).toEqual({ message: 'hi', value: 10 })
})
it('throws when reading a text body as JSON but it is invalid', async () => {
const body = new Implementation('{ hi: "there", ')
const error = await body.json().catch((err) => err)
expect(error).toBeInstanceOf(TypeError)
expect(error.message).toEqual(
'invalid json body reason: Unexpected token h in JSON at position 2'
)
})
/* eslint-env jest */
/**
* @jest-environment @edge-runtime/jest-environment
*/
import {
Cookies,
CookieSerializeOptions,
} from 'next/dist/server/web/spec-extension/cookies'
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import * as streams from 'web-streams-polyfill/ponyfill'
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
it('create a empty cookies bag', async () => {
const cookies = new Cookies()
expect(Object.entries(cookies)).toStrictEqual([])
expect(Object.entries(cookies)).toEqual([])
})
it('create a cookies bag from string', async () => {
const cookies = new Cookies('foo=bar; equation=E%3Dmc%5E2')
expect(Array.from(cookies.entries())).toStrictEqual([
expect(Array.from(cookies.entries())).toEqual([
['foo', 'foo=bar; Path=/'],
['equation', 'equation=E%3Dmc%5E2; Path=/'],
])
......@@ -45,9 +23,7 @@ it('create a cookies bag from string', async () => {
it('.set', async () => {
const cookies = new Cookies()
cookies.set('foo', 'bar')
expect(Array.from(cookies.entries())).toStrictEqual([
['foo', 'foo=bar; Path=/'],
])
expect(Array.from(cookies.entries())).toEqual([['foo', 'foo=bar; Path=/']])
})
it('.set with options', async () => {
......@@ -63,7 +39,7 @@ it('.set with options', async () => {
cookies.set('foo', 'bar', options)
expect(options).toStrictEqual({
expect(options).toEqual({
path: '/',
maxAge: 60 * 60 * 24 * 7,
httpOnly: true,
......@@ -76,7 +52,7 @@ it('.set with options', async () => {
expect(key).toBe('foo')
expect(values).toStrictEqual([
expect(values).toEqual([
'foo=bar',
'Max-Age=604800',
'Domain=example.com',
......@@ -91,7 +67,7 @@ it('.delete', async () => {
const cookies = new Cookies()
cookies.set('foo', 'bar')
cookies.delete('foo')
expect(Array.from(cookies.entries())).toStrictEqual([])
expect(Array.from(cookies.entries())).toEqual([])
})
it('.has', async () => {
......
/* eslint-env jest */
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Response } from 'next/dist/server/web/spec-compliant/response'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import * as streams from 'web-streams-polyfill/ponyfill'
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
global['Response'] = Response
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
/**
* @jest-environment @edge-runtime/jest-environment
*/
it('reflect .set into `set-cookie`', async () => {
const { NextResponse } = await import(
......
/**
* @jest-environment @edge-runtime/jest-environment
*/
import { NextResponse } from 'next/dist/server/web/spec-extension/response'
const toJSON = async (response) => ({
body: await response.json(),
contentType: response.headers.get('content-type'),
status: response.status,
})
it('automatically parses and formats JSON', async () => {
expect(await toJSON(NextResponse.json({ message: 'hello!' }))).toMatchObject({
contentType: 'application/json',
body: { message: 'hello!' },
})
expect(
await toJSON(NextResponse.json({ status: 'success' }, { status: 201 }))
).toMatchObject({
contentType: 'application/json',
body: { status: 'success' },
status: 201,
})
expect(
await toJSON(
NextResponse.json({ error: { code: 'bad_request' } }, { status: 400 })
)
).toMatchObject({
contentType: 'application/json',
body: { error: { code: 'bad_request' } },
status: 400,
})
expect(await toJSON(NextResponse.json(null))).toMatchObject({
contentType: 'application/json',
body: null,
})
expect(await toJSON(NextResponse.json(''))).toMatchObject({
contentType: 'application/json',
body: '',
})
})
/* eslint-env jest */
/**
* @jest-environment @edge-runtime/jest-environment
*/
import { NextURL } from 'next/dist/server/web/next-url'
// TODO Make NextURL extend URL
......
/* eslint-env jest */
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import { Request } from 'next/dist/server/web/spec-compliant/request'
import * as streams from 'web-streams-polyfill/ponyfill'
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
it('parses and reconstructs the URL alone', async () => {
const url = 'https://vercel.com/foo/bar?one=value'
const req = new Request(url)
expect(req.url).toEqual(url)
})
it('throws when the URL is malformed', async () => {
expect(() => new Request('meeeh')).toThrowError('Invalid URL')
})
it('Request.referrer is `about:client` by default', async () => {
const request = new Request('https://vercel.com')
expect(request.referrer).toBe('about:client')
})
it('Request.referrer can be customized', async () => {
const request = new Request('https://vercel.com', { referrer: 'client' })
expect(request.referrer).toBe('client')
})
it('Request copies over method', async () => {
const request = new Request('https://vercel.com', {
method: 'POST',
body: 'hello',
})
const clonedRequest = new Request(request)
expect(clonedRequest.method).toBe(request.method)
})
/* eslint-env jest */
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Response } from 'next/dist/server/web/spec-compliant/response'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import * as streams from 'web-streams-polyfill/ponyfill'
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
it('clones responses', async () => {
const { readable, writable } = new TransformStream()
const encoder = new TextEncoder()
const writer = writable.getWriter()
writer.write(encoder.encode('Hello '))
writer.write(encoder.encode('world!'))
writer.close()
const res1 = new Response(readable)
const res2 = res1.clone()
expect(await res1.text()).toEqual('Hello world!')
expect(await res2.text()).toEqual('Hello world!')
})
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