Unverified Commit 14463ddd authored by Javi Velasco's avatar Javi Velasco Committed by GitHub

Update Edge Runtime (#38862)

This PR updates the Edge Runtime to use a new version that loads dependencies differently. This addresses https://github.com/vercel/next.js/pull/38766 so `instanceof` works as expected.

It involved a few code changes, mostly regarding to types. The most important change is that the `Runner` function in the sandbox doesn't take a `ReadableStream` as `body` anymore since this implies creating the instance on "node land" and makes the runtime `fetch` function not to be able to compare with `ReadableStream` using `instanceof`.  Instead we introduce a "clonable body" abstraction that allows to create the `ReadableStream` from `Readable` by using the edge runtime primitive which would hold the correct prototype.

Also, this PR changes the way we pre-compile the Edge Runtime to adapt it to the new version.
parent fe4b7113
...@@ -56,7 +56,7 @@ ...@@ -56,7 +56,7 @@
"@babel/plugin-proposal-object-rest-spread": "7.14.7", "@babel/plugin-proposal-object-rest-spread": "7.14.7",
"@babel/preset-flow": "7.14.5", "@babel/preset-flow": "7.14.5",
"@babel/preset-react": "7.14.5", "@babel/preset-react": "7.14.5",
"@edge-runtime/jest-environment": "1.1.0-beta.11", "@edge-runtime/jest-environment": "1.1.0-beta.17",
"@fullhuman/postcss-purgecss": "1.3.0", "@fullhuman/postcss-purgecss": "1.3.0",
"@mdx-js/loader": "0.18.0", "@mdx-js/loader": "0.18.0",
"@next/bundle-analyzer": "workspace:*", "@next/bundle-analyzer": "workspace:*",
......
This diff is collapsed.
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/primitives/cache.js
var cache_exports = {};
__export(cache_exports, {
Cache: () => CacheFromStorage,
CacheStorage: () => CacheStorage,
caches: () => caches,
createCaches: () => createCaches
});
module.exports = __toCommonJS(cache_exports);
var import_fetch = require("./fetch");
function createCaches() {
const getKey = /* @__PURE__ */ __name((request) => new URL(request.url).toString(), "getKey");
const normalizeRequest = /* @__PURE__ */ __name((input, { invokeName }) => {
if (typeof proxy === "object" && proxy.__normalized__)
return input;
const request = input instanceof import_fetch.Request ? input : new import_fetch.Request(input);
if (request.method !== "GET") {
throw new TypeError(`Failed to execute '${invokeName}' on 'Cache': Request method '${request.method}' is unsupported`);
}
if (!request.url.startsWith("http")) {
throw new TypeError(`Failed to execute '${invokeName}' on 'Cache': Request scheme '${request.url.split(":")[0]}' is unsupported`);
}
Object.defineProperty(request, "__normalized__", {
enumerable: false,
writable: false,
value: true
});
return request;
}, "normalizeRequest");
class Cache2 {
constructor(Storage = Map) {
Object.defineProperty(this, "store", {
enumerable: false,
writable: false,
value: new Storage()
});
}
async add(request) {
const response = await (0, import_fetch.fetch)(normalizeRequest(request, { invokeName: "add" }));
if (!response.ok) {
throw new TypeError("Failed to execute 'add' on 'Cache': Request failed");
}
return this.put(request, response);
}
async addAll(requests) {
await Promise.all(requests.map((request) => this.add(request)));
}
async match(request) {
const key = getKey(normalizeRequest(request, { invokeName: "match" }));
const cached = this.store.get(key);
return cached ? new import_fetch.Response(cached.body, cached.init) : void 0;
}
async delete(request) {
const key = getKey(normalizeRequest(request, { invokeName: "delete" }));
return this.store.delete(key);
}
async put(request, response) {
if (response.status === 206) {
throw new TypeError("Failed to execute 'put' on 'Cache': Partial response (status code 206) is unsupported");
}
const vary = response.headers.get("vary");
if (vary !== null && vary.includes("*")) {
throw new TypeError("Failed to execute 'put' on 'Cache': Vary header contains *");
}
request = normalizeRequest(request, { invokeName: "put" });
try {
this.store.set(getKey(request), {
body: new Uint8Array(await response.arrayBuffer()),
init: {
status: response.status,
headers: [...response.headers]
}
});
} catch (error) {
if (error.message === "disturbed") {
throw new TypeError("Failed to execute 'put' on 'Cache': Response body is already used");
}
throw error;
}
}
}
__name(Cache2, "Cache");
const cacheStorage = /* @__PURE__ */ __name((Storage = Map) => {
const caches2 = new Storage();
const open = /* @__PURE__ */ __name(async (cacheName) => {
let cache = caches2.get(cacheName);
if (cache === void 0) {
cache = new Cache2(Storage);
caches2.set(cacheName, cache);
}
return cache;
}, "open");
const has = /* @__PURE__ */ __name((cacheName) => Promise.resolve(caches2.has(cacheName)), "has");
const keys = /* @__PURE__ */ __name(() => Promise.resolve(caches2.keys()), "keys");
const _delete = /* @__PURE__ */ __name((cacheName) => Promise.resolve(caches2.delete(cacheName)), "_delete");
const match = /* @__PURE__ */ __name(async (request, options) => {
for (const cache of caches2.values()) {
const cached = await cache.match(request, options);
if (cached !== void 0)
return cached;
}
}, "match");
return {
open,
has,
keys,
delete: _delete,
match
};
}, "cacheStorage");
return { Cache: Cache2, cacheStorage };
}
__name(createCaches, "createCaches");
function CacheStorage() {
if (!(this instanceof CacheStorage))
return new CacheStorage();
throw TypeError("Illegal constructor");
}
__name(CacheStorage, "CacheStorage");
function CacheStorageToString() {
return "function CacheStorage() { [native code] }";
}
__name(CacheStorageToString, "CacheStorageToString");
Object.defineProperty(CacheStorageToString, "name", {
configurable: true,
enumerable: false,
value: "toString() { [native code] }",
writable: true
});
Object.defineProperty(CacheStorage, "toString", {
configurable: true,
enumerable: false,
value: CacheStorageToString,
writable: true
});
function Cache() {
if (!(this instanceof Cache))
return new Cache();
throw TypeError("Illegal constructor");
}
__name(Cache, "Cache");
function CacheToString() {
return "function Cache() { [native code] }";
}
__name(CacheToString, "CacheToString");
Object.defineProperty(CacheToString, "name", {
configurable: true,
enumerable: false,
value: "toString() { [native code] }",
writable: true
});
Object.defineProperty(Cache, "toString", {
configurable: true,
enumerable: false,
value: CacheToString,
writable: true
});
var cachesStorage = createCaches();
var CacheFromStorage = cachesStorage.Cache;
var caches = cachesStorage.cacheStorage();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Cache,
CacheStorage,
caches,
createCaches
});
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
{"name":"@edge-runtime/primitives","version":"1.1.0-beta.11","main":"./index.js","license":"MPLv2"} {"name":"@edge-runtime/primitives","version":"1.1.0-beta.17","main":"./index.js","license":"MPLv2"}
This diff is collapsed.
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/primitives/structured-clone.js
var structured_clone_exports = {};
__export(structured_clone_exports, {
structuredClone: () => esm_default
});
module.exports = __toCommonJS(structured_clone_exports);
// ../../node_modules/.pnpm/@ungap+structured-clone@1.0.1/node_modules/@ungap/structured-clone/esm/types.js
var VOID = -1;
var PRIMITIVE = 0;
var ARRAY = 1;
var OBJECT = 2;
var DATE = 3;
var REGEXP = 4;
var MAP = 5;
var SET = 6;
var ERROR = 7;
var BIGINT = 8;
// ../../node_modules/.pnpm/@ungap+structured-clone@1.0.1/node_modules/@ungap/structured-clone/esm/deserialize.js
var env = typeof self === "object" ? self : globalThis;
var deserializer = /* @__PURE__ */ __name(($, _) => {
const as = /* @__PURE__ */ __name((out, index) => {
$.set(index, out);
return out;
}, "as");
const unpair = /* @__PURE__ */ __name((index) => {
if ($.has(index))
return $.get(index);
const [type, value] = _[index];
switch (type) {
case PRIMITIVE:
case VOID:
return as(value, index);
case ARRAY: {
const arr = as([], index);
for (const index2 of value)
arr.push(unpair(index2));
return arr;
}
case OBJECT: {
const object = as({}, index);
for (const [key, index2] of value)
object[unpair(key)] = unpair(index2);
return object;
}
case DATE:
return as(new Date(value), index);
case REGEXP: {
const { source, flags } = value;
return as(new RegExp(source, flags), index);
}
case MAP: {
const map = as(/* @__PURE__ */ new Map(), index);
for (const [key, index2] of value)
map.set(unpair(key), unpair(index2));
return map;
}
case SET: {
const set = as(/* @__PURE__ */ new Set(), index);
for (const index2 of value)
set.add(unpair(index2));
return set;
}
case ERROR: {
const { name, message } = value;
return as(new env[name](message), index);
}
case BIGINT:
return as(BigInt(value), index);
case "BigInt":
return as(Object(BigInt(value)), index);
}
return as(new env[type](value), index);
}, "unpair");
return unpair;
}, "deserializer");
var deserialize = /* @__PURE__ */ __name((serialized) => deserializer(/* @__PURE__ */ new Map(), serialized)(0), "deserialize");
// ../../node_modules/.pnpm/@ungap+structured-clone@1.0.1/node_modules/@ungap/structured-clone/esm/serialize.js
var EMPTY = "";
var { toString } = {};
var { keys } = Object;
var typeOf = /* @__PURE__ */ __name((value) => {
const type = typeof value;
if (type !== "object" || !value)
return [PRIMITIVE, type];
const asString = toString.call(value).slice(8, -1);
switch (asString) {
case "Array":
return [ARRAY, EMPTY];
case "Object":
return [OBJECT, EMPTY];
case "Date":
return [DATE, EMPTY];
case "RegExp":
return [REGEXP, EMPTY];
case "Map":
return [MAP, EMPTY];
case "Set":
return [SET, EMPTY];
}
if (asString.includes("Array"))
return [ARRAY, asString];
if (asString.includes("Error"))
return [ERROR, asString];
return [OBJECT, asString];
}, "typeOf");
var shouldSkip = /* @__PURE__ */ __name(([TYPE, type]) => TYPE === PRIMITIVE && (type === "function" || type === "symbol"), "shouldSkip");
var serializer = /* @__PURE__ */ __name((strict, json, $, _) => {
const as = /* @__PURE__ */ __name((out, value) => {
const index = _.push(out) - 1;
$.set(value, index);
return index;
}, "as");
const pair = /* @__PURE__ */ __name((value) => {
if ($.has(value))
return $.get(value);
let [TYPE, type] = typeOf(value);
switch (TYPE) {
case PRIMITIVE: {
let entry = value;
switch (type) {
case "bigint":
TYPE = BIGINT;
entry = value.toString();
break;
case "function":
case "symbol":
if (strict)
throw new TypeError("unable to serialize " + type);
entry = null;
break;
case "undefined":
return as([VOID], value);
}
return as([TYPE, entry], value);
}
case ARRAY: {
if (type)
return as([type, [...value]], value);
const arr = [];
const index = as([TYPE, arr], value);
for (const entry of value)
arr.push(pair(entry));
return index;
}
case OBJECT: {
if (type) {
switch (type) {
case "BigInt":
return as([type, value.toString()], value);
case "Boolean":
case "Number":
case "String":
return as([type, value.valueOf()], value);
}
}
if (json && "toJSON" in value)
return pair(value.toJSON());
const entries = [];
const index = as([TYPE, entries], value);
for (const key of keys(value)) {
if (strict || !shouldSkip(typeOf(value[key])))
entries.push([pair(key), pair(value[key])]);
}
return index;
}
case DATE:
return as([TYPE, value.toISOString()], value);
case REGEXP: {
const { source, flags } = value;
return as([TYPE, { source, flags }], value);
}
case MAP: {
const entries = [];
const index = as([TYPE, entries], value);
for (const [key, entry] of value) {
if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
entries.push([pair(key), pair(entry)]);
}
return index;
}
case SET: {
const entries = [];
const index = as([TYPE, entries], value);
for (const entry of value) {
if (strict || !shouldSkip(typeOf(entry)))
entries.push(pair(entry));
}
return index;
}
}
const { message } = value;
return as([TYPE, { name: type, message }], value);
}, "pair");
return pair;
}, "serializer");
var serialize = /* @__PURE__ */ __name((value, { json, lossy } = {}) => {
const _ = [];
return serializer(!(json || lossy), !!json, /* @__PURE__ */ new Map(), _)(value), _;
}, "serialize");
// ../../node_modules/.pnpm/@ungap+structured-clone@1.0.1/node_modules/@ungap/structured-clone/esm/index.js
var esm_default = typeof structuredClone === "function" ? (any, options) => options && ("json" in options || "lossy" in options) ? deserialize(serialize(any, options)) : structuredClone(any) : (any, options) => deserialize(serialize(any, options));
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
structuredClone
});
This diff is collapsed.
...@@ -117,7 +117,7 @@ ...@@ -117,7 +117,7 @@
"@babel/runtime": "7.15.4", "@babel/runtime": "7.15.4",
"@babel/traverse": "7.18.0", "@babel/traverse": "7.18.0",
"@babel/types": "7.18.0", "@babel/types": "7.18.0",
"@edge-runtime/primitives": "1.1.0-beta.11", "@edge-runtime/primitives": "1.1.0-beta.17",
"@hapi/accept": "5.0.2", "@hapi/accept": "5.0.2",
"@napi-rs/cli": "2.4.4", "@napi-rs/cli": "2.4.4",
"@napi-rs/triples": "1.1.0", "@napi-rs/triples": "1.1.0",
...@@ -194,7 +194,7 @@ ...@@ -194,7 +194,7 @@
"debug": "4.1.1", "debug": "4.1.1",
"devalue": "2.0.1", "devalue": "2.0.1",
"domain-browser": "4.19.0", "domain-browser": "4.19.0",
"edge-runtime": "1.1.0-beta.11", "edge-runtime": "1.1.0-beta.17",
"events": "3.3.0", "events": "3.3.0",
"find-cache-dir": "3.3.1", "find-cache-dir": "3.3.1",
"find-up": "4.1.0", "find-up": "4.1.0",
......
...@@ -80,6 +80,7 @@ import { getHostname } from '../shared/lib/get-hostname' ...@@ -80,6 +80,7 @@ import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url' import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { getClonableBody } from './body-streams'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -433,6 +434,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -433,6 +434,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
addRequestMeta(req, '__NEXT_INIT_URL', initUrl) addRequestMeta(req, '__NEXT_INIT_URL', initUrl)
addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query }) addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query })
addRequestMeta(req, '_protocol', protocol) addRequestMeta(req, '_protocol', protocol)
addRequestMeta(req, '__NEXT_CLONABLE_BODY', getClonableBody(req.body))
const domainLocale = detectDomainLocale( const domainLocale = detectDomainLocale(
this.nextConfig.i18n?.domains, this.nextConfig.i18n?.domains,
......
import Primitives from 'next/dist/compiled/@edge-runtime/primitives'
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import { Readable } from 'stream' import { PassThrough, Readable } from 'stream'
type BodyStream = ReadableStream<Uint8Array> export function requestToBodyStream(
context: { ReadableStream: typeof ReadableStream },
/** stream: Readable
* Creates a ReadableStream from a Node.js HTTP request ) {
*/ return new context.ReadableStream({
export function requestToBodyStream(request: Readable): BodyStream {
const transform = new Primitives.TransformStream<Uint8Array, Uint8Array>({
start(controller) { start(controller) {
request.on('data', (chunk) => controller.enqueue(chunk)) stream.on('data', (chunk) => controller.enqueue(chunk))
request.on('end', () => controller.terminate()) stream.on('end', () => controller.close())
request.on('error', (err) => controller.error(err)) stream.on('error', (err) => controller.error(err))
}, },
}) })
return transform.readable as unknown as ReadableStream<Uint8Array>
} }
export function bodyStreamToNodeStream(bodyStream: BodyStream): Readable { export function bodyStreamToNodeStream(
bodyStream: ReadableStream<Uint8Array>
): Readable {
const reader = bodyStream.getReader() const reader = bodyStream.getReader()
return Readable.from( return Readable.from(
(async function* () { (async function* () {
...@@ -49,18 +46,19 @@ function replaceRequestBody<T extends IncomingMessage>( ...@@ -49,18 +46,19 @@ function replaceRequestBody<T extends IncomingMessage>(
return base return base
} }
/** export interface ClonableBody {
* An interface that encapsulates body stream cloning finalize(): Promise<void>
* of an incoming request. cloneBodyStream(): Readable
*/ }
export function clonableBodyForRequest<T extends IncomingMessage>(
incomingMessage: T export function getClonableBody<T extends IncomingMessage>(
) { readable: T
let bufferedBodyStream: BodyStream | null = null ): ClonableBody {
let buffered: Readable | null = null
const endPromise = new Promise((resolve, reject) => { const endPromise = new Promise((resolve, reject) => {
incomingMessage.on('end', resolve) readable.on('end', resolve)
incomingMessage.on('error', reject) readable.on('error', reject)
}) })
return { return {
...@@ -70,24 +68,24 @@ export function clonableBodyForRequest<T extends IncomingMessage>( ...@@ -70,24 +68,24 @@ export function clonableBodyForRequest<T extends IncomingMessage>(
* we can't read it again. * we can't read it again.
*/ */
async finalize(): Promise<void> { async finalize(): Promise<void> {
if (bufferedBodyStream) { if (buffered) {
await endPromise await endPromise
replaceRequestBody( replaceRequestBody(readable, buffered)
incomingMessage, buffered = readable
bodyStreamToNodeStream(bufferedBodyStream)
)
} }
}, },
/** /**
* Clones the body stream * Clones the body stream
* to pass into a middleware * to pass into a middleware
*/ */
cloneBodyStream(): BodyStream { cloneBodyStream() {
const originalStream = const input = buffered ?? readable
bufferedBodyStream ?? requestToBodyStream(incomingMessage) const p1 = new PassThrough()
const [stream1, stream2] = originalStream.tee() const p2 = new PassThrough()
bufferedBodyStream = stream1 input.pipe(p1)
return stream2 input.pipe(p2)
buffered = p2
return p1
}, },
} }
} }
...@@ -80,11 +80,7 @@ import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring' ...@@ -80,11 +80,7 @@ import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'
import ResponseCache from '../server/response-cache' import ResponseCache from '../server/response-cache'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { import { bodyStreamToNodeStream } from './body-streams'
bodyStreamToNodeStream,
clonableBodyForRequest,
requestToBodyStream,
} from './body-streams'
import { checkIsManualRevalidate } from './api-utils' import { checkIsManualRevalidate } from './api-utils'
import { isDynamicRoute } from '../shared/lib/router/utils' import { isDynamicRoute } from '../shared/lib/router/utils'
import { shouldUseReactRoot } from './utils' import { shouldUseReactRoot } from './utils'
...@@ -1205,10 +1201,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -1205,10 +1201,6 @@ export default class NextNodeServer extends BaseServer {
const allHeaders = new Headers() const allHeaders = new Headers()
let result: FetchEventResult | null = null let result: FetchEventResult | null = null
const method = (params.request.method || 'GET').toUpperCase() const method = (params.request.method || 'GET').toUpperCase()
let originalBody =
method !== 'GET' && method !== 'HEAD'
? clonableBodyForRequest(params.request.body)
: undefined
const middlewareList = this.getMiddleware() const middlewareList = this.getMiddleware()
for (const middleware of middlewareList) { for (const middleware of middlewareList) {
...@@ -1244,7 +1236,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1244,7 +1236,7 @@ export default class NextNodeServer extends BaseServer {
}, },
url: url, url: url,
page: page, page: page,
body: originalBody?.cloneBodyStream(), body: getRequestMeta(params.request, '__NEXT_CLONABLE_BODY'),
}, },
useCache: !this.nextConfig.experimental.runtime, useCache: !this.nextConfig.experimental.runtime,
onWarning: params.onWarning, onWarning: params.onWarning,
...@@ -1277,7 +1269,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -1277,7 +1269,6 @@ export default class NextNodeServer extends BaseServer {
} }
} }
await originalBody?.finalize()
return result return result
} }
...@@ -1552,8 +1543,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -1552,8 +1543,6 @@ export default class NextNodeServer extends BaseServer {
) )
} }
const nodeReq = params.req as NodeNextRequest
const result = await run({ const result = await run({
distDir: this.distDir, distDir: this.distDir,
name: middlewareInfo.name, name: middlewareInfo.name,
...@@ -1573,11 +1562,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1573,11 +1562,7 @@ export default class NextNodeServer extends BaseServer {
name: params.page, name: params.page,
...(params.params && { params: params.params }), ...(params.params && { params: params.params }),
}, },
body: body: getRequestMeta(params.req, '__NEXT_CLONABLE_BODY'),
['GET', 'HEAD'].includes(params.req.method) ||
!nodeReq.originalRequest
? undefined
: requestToBodyStream(nodeReq.originalRequest),
}, },
useCache: !this.nextConfig.experimental.runtime, useCache: !this.nextConfig.experimental.runtime,
onWarning: params.onWarning, onWarning: params.onWarning,
......
import Primitives from 'next/dist/compiled/@edge-runtime/primitives' import {
ReadableStream,
TransformStream,
} from 'next/dist/compiled/@edge-runtime/primitives/streams'
// Polyfill Web Streams for the Node.js runtime. // Polyfill Web Streams for the Node.js runtime.
if (!global.ReadableStream) { if (!global.ReadableStream) {
global.ReadableStream = Primitives.ReadableStream global.ReadableStream = ReadableStream
} }
if (!global.TransformStream) { if (!global.TransformStream) {
global.TransformStream = Primitives.TransformStream global.TransformStream = TransformStream
} }
...@@ -3,6 +3,7 @@ import type { IncomingMessage } from 'http' ...@@ -3,6 +3,7 @@ import type { IncomingMessage } from 'http'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import type { BaseNextRequest } from './base-http' import type { BaseNextRequest } from './base-http'
import type { ClonableBody } from './body-streams'
export const NEXT_REQUEST_META = Symbol('NextRequestMeta') export const NEXT_REQUEST_META = Symbol('NextRequestMeta')
...@@ -13,6 +14,7 @@ export type NextIncomingMessage = (BaseNextRequest | IncomingMessage) & { ...@@ -13,6 +14,7 @@ export type NextIncomingMessage = (BaseNextRequest | IncomingMessage) & {
export interface RequestMeta { export interface RequestMeta {
__NEXT_INIT_QUERY?: ParsedUrlQuery __NEXT_INIT_QUERY?: ParsedUrlQuery
__NEXT_INIT_URL?: string __NEXT_INIT_URL?: string
__NEXT_CLONABLE_BODY?: ClonableBody
__nextHadTrailingSlash?: boolean __nextHadTrailingSlash?: boolean
__nextIsLocaleDomain?: boolean __nextIsLocaleDomain?: boolean
__nextStrippedLocale?: boolean __nextStrippedLocale?: boolean
......
import type { Primitives } from 'next/dist/compiled/@edge-runtime/primitives'
import type { AssetBinding } from '../../../build/webpack/loaders/get-module-build-info' import type { AssetBinding } from '../../../build/webpack/loaders/get-module-build-info'
import { import {
decorateServerError, decorateServerError,
...@@ -16,7 +15,7 @@ const WEBPACK_HASH_REGEX = ...@@ -16,7 +15,7 @@ const WEBPACK_HASH_REGEX =
/__webpack_require__\.h = function\(\) \{ return "[0-9a-f]+"; \}/g /__webpack_require__\.h = function\(\) \{ return "[0-9a-f]+"; \}/g
interface ModuleContext { interface ModuleContext {
runtime: EdgeRuntime<Primitives> runtime: EdgeRuntime
paths: Map<string, string> paths: Map<string, string>
warnedEvals: Set<string> warnedEvals: Set<string>
} }
...@@ -71,7 +70,12 @@ function getModuleContextShared(options: ModuleContextOptions) { ...@@ -71,7 +70,12 @@ function getModuleContextShared(options: ModuleContextOptions) {
* with a function that allows to run some code from a given * with a function that allows to run some code from a given
* filepath within the context. * filepath within the context.
*/ */
export async function getModuleContext(options: ModuleContextOptions) { export async function getModuleContext(options: ModuleContextOptions): Promise<{
evaluateInContext: (filepath: string) => void
runtime: EdgeRuntime
paths: Map<string, string>
warnedEvals: Set<string>
}> {
let moduleContext = options.useCache let moduleContext = options.useCache
? moduleContexts.get(options.moduleName) ? moduleContexts.get(options.moduleName)
: await getModuleContextShared(options) : await getModuleContextShared(options)
...@@ -110,7 +114,7 @@ async function createModuleContext(options: ModuleContextOptions) { ...@@ -110,7 +114,7 @@ async function createModuleContext(options: ModuleContextOptions) {
const runtime = new EdgeRuntime({ const runtime = new EdgeRuntime({
codeGeneration: codeGeneration:
process.env.NODE_ENV !== 'production' process.env.NODE_ENV !== 'production'
? { strings: true, wasm: false } ? { strings: true, wasm: true }
: undefined, : undefined,
extend: (context) => { extend: (context) => {
context.process = createProcessPolyfill(options) context.process = createProcessPolyfill(options)
...@@ -177,7 +181,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation ...@@ -177,7 +181,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation
} }
const __fetch = context.fetch const __fetch = context.fetch
context.fetch = async (input: RequestInfo, init: RequestInit = {}) => { context.fetch = async (input, init = {}) => {
const assetResponse = await fetchInlineAsset({ const assetResponse = await fetchInlineAsset({
input, input,
assets: options.edgeFunctionEntry.assets, assets: options.edgeFunctionEntry.assets,
...@@ -226,10 +230,13 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation ...@@ -226,10 +230,13 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation
const __Request = context.Request const __Request = context.Request
context.Request = class extends __Request { context.Request = class extends __Request {
constructor(input: RequestInfo, init?: RequestInit | undefined) { constructor(input: URL | RequestInfo, init?: RequestInit | undefined) {
const url = typeof input === 'string' ? input : input.url const url =
typeof input !== 'string' && 'url' in input
? input.url
: String(input)
validateURL(url) validateURL(url)
super(input, init) super(url, init)
} }
} }
...@@ -249,6 +256,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation ...@@ -249,6 +256,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation
}, },
}) })
const decorateUnhandledError = getDecorateUnhandledError(runtime)
runtime.context.addEventListener('unhandledrejection', decorateUnhandledError) runtime.context.addEventListener('unhandledrejection', decorateUnhandledError)
runtime.context.addEventListener('error', decorateUnhandledError) runtime.context.addEventListener('error', decorateUnhandledError)
...@@ -311,7 +319,7 @@ function createProcessPolyfill(options: Pick<ModuleContextOptions, 'env'>) { ...@@ -311,7 +319,7 @@ function createProcessPolyfill(options: Pick<ModuleContextOptions, 'env'>) {
return processPolyfill return processPolyfill
} }
function addStub(context: Primitives, name: string) { function addStub(context: EdgeRuntime['context'], name: string) {
Object.defineProperty(context, name, { Object.defineProperty(context, name, {
get() { get() {
return function () { return function () {
...@@ -330,8 +338,11 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) ...@@ -330,8 +338,11 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
throw error throw error
} }
function decorateUnhandledError(error: any) { function getDecorateUnhandledError(runtime: EdgeRuntime) {
if (error instanceof Error) { const EdgeRuntimeError = runtime.evaluate(`Error`)
decorateServerError(error, 'edge-server') return (error: any) => {
if (error instanceof EdgeRuntimeError) {
decorateServerError(error, 'edge-server')
}
} }
} }
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'
import { createReadStream, promises as fs } from 'fs' import { createReadStream, promises as fs } from 'fs'
import path from 'path'
import { requestToBodyStream } from '../../body-streams' import { requestToBodyStream } from '../../body-streams'
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin' import { resolve } from 'path'
/** /**
* Short-circuits the `fetch` function * Short-circuits the `fetch` function
...@@ -9,10 +9,10 @@ import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/midd ...@@ -9,10 +9,10 @@ import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/midd
* This allows to embed assets in Edge Runtime. * This allows to embed assets in Edge Runtime.
*/ */
export async function fetchInlineAsset(options: { export async function fetchInlineAsset(options: {
input: RequestInfo input: RequestInfo | URL
distDir: string distDir: string
assets: EdgeFunctionDefinition['assets'] assets: EdgeFunctionDefinition['assets']
context: { Response: any } context: { Response: typeof Response; ReadableStream: typeof ReadableStream }
}): Promise<Response | undefined> { }): Promise<Response | undefined> {
const inputString = String(options.input) const inputString = String(options.input)
if (!inputString.startsWith('blob:')) { if (!inputString.startsWith('blob:')) {
...@@ -25,8 +25,7 @@ export async function fetchInlineAsset(options: { ...@@ -25,8 +25,7 @@ export async function fetchInlineAsset(options: {
return return
} }
const filePath = path.resolve(options.distDir, asset.filePath) const filePath = resolve(options.distDir, asset.filePath)
const fileIsReadable = await fs.access(filePath).then( const fileIsReadable = await fs.access(filePath).then(
() => true, () => true,
() => false () => false
...@@ -34,6 +33,8 @@ export async function fetchInlineAsset(options: { ...@@ -34,6 +33,8 @@ export async function fetchInlineAsset(options: {
if (fileIsReadable) { if (fileIsReadable) {
const readStream = createReadStream(filePath) const readStream = createReadStream(filePath)
return new options.context.Response(requestToBodyStream(readStream)) return new options.context.Response(
requestToBodyStream(options.context, readStream)
)
} }
} }
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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