323 lines
11 KiB
JavaScript
323 lines
11 KiB
JavaScript
"use strict";
|
|
var __defProp = Object.defineProperty;
|
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
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);
|
|
var node_handler_exports = {};
|
|
__export(node_handler_exports, {
|
|
getHandlerSource: () => getHandlerSource
|
|
});
|
|
module.exports = __toCommonJS(node_handler_exports);
|
|
const getHandlerSource = (ctx) => `
|
|
process.env.NODE_ENV = 'production';
|
|
require('next/dist/server/node-environment');
|
|
require('next/dist/server/node-polyfill-crypto');
|
|
|
|
try {
|
|
// this can fail to install if styled-jsx is not discoverable
|
|
// but this is tolerable as the require-hook is handling edge cases
|
|
require('next/dist/server/require-hook');
|
|
} catch (_) {}
|
|
|
|
process.chdir(__dirname);
|
|
|
|
const _n_handler = (${ctx.isMiddleware ? () => {
|
|
const path = require("path");
|
|
const relativeDistDir = process.env.__PRIVATE_RELATIVE_DIST_DIR;
|
|
const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
|
|
function getRequestContext() {
|
|
const fromSymbol = globalThis;
|
|
return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
|
|
}
|
|
return async function handler(request) {
|
|
console.log("middleware handler", request);
|
|
let middlewareHandler = await require("./" + path.posix.join(relativeDistDir, "server", "middleware.js"));
|
|
middlewareHandler = middlewareHandler.handler || middlewareHandler;
|
|
const context = getRequestContext();
|
|
const response = await middlewareHandler(request, {
|
|
waitUntil: context.waitUntil,
|
|
requestMeta: {
|
|
// we use '.' for relative project dir since we process.chdir
|
|
// to the same directory as the handler file so everything is
|
|
// relative to that/project dir
|
|
relativeProjectDir: "."
|
|
}
|
|
});
|
|
return response;
|
|
};
|
|
} : (() => {
|
|
const path = require("path");
|
|
const relativeDistDir = process.env.__PRIVATE_RELATIVE_DIST_DIR;
|
|
const prerenderFallbackFalseMap = process.env.__PRIVATE_PRERENDER_FALLBACK_MAP;
|
|
const {
|
|
dynamicRoutes: dynamicRoutesRaw,
|
|
staticRoutes: staticRoutesRaw,
|
|
i18n
|
|
} = require("./" + path.posix.join(relativeDistDir, "routes-manifest.json"));
|
|
const hydrateRoutesManifestItem = (item) => {
|
|
return {
|
|
...item,
|
|
namedRegex: new RegExp(item.namedRegex || item.regex)
|
|
};
|
|
};
|
|
const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
|
|
function escapeStringRegexp(str) {
|
|
return str.replace(matchOperatorsRegex, "\\$&");
|
|
}
|
|
const dynamicRoutes = dynamicRoutesRaw.map(hydrateRoutesManifestItem);
|
|
const staticRoutes = staticRoutesRaw.map((route) => {
|
|
return {
|
|
...route,
|
|
namedRegex: new RegExp(
|
|
"^" + escapeStringRegexp(route.page) + "$"
|
|
)
|
|
};
|
|
});
|
|
let appPathRoutesManifest = {};
|
|
try {
|
|
appPathRoutesManifest = require("./" + path.posix.join(
|
|
relativeDistDir,
|
|
"app-path-routes-manifest.json"
|
|
));
|
|
} catch (_) {
|
|
}
|
|
const inversedAppRoutesManifest = Object.entries(
|
|
appPathRoutesManifest
|
|
).reduce(
|
|
(manifest, [originalKey, normalizedKey]) => {
|
|
manifest[normalizedKey] = originalKey;
|
|
return manifest;
|
|
},
|
|
{}
|
|
);
|
|
function normalizeLocalePath(pathname, locales) {
|
|
if (!locales) return { pathname };
|
|
const lowercasedLocales = locales.map(
|
|
(locale) => locale.toLowerCase()
|
|
);
|
|
const segments = pathname.split("/", 2);
|
|
if (!segments[1]) return { pathname };
|
|
const segment = segments[1].toLowerCase();
|
|
const index = lowercasedLocales.indexOf(segment);
|
|
if (index < 0) return { pathname };
|
|
const detectedLocale = locales[index];
|
|
pathname = pathname.slice(detectedLocale.length + 1) || "/";
|
|
return { pathname, locale: detectedLocale };
|
|
}
|
|
function normalizeDataPath(pathname) {
|
|
if (!(pathname || "/").startsWith("/_next/data")) {
|
|
return pathname;
|
|
}
|
|
pathname = pathname.replace(/\/_next\/data\/[^/]{1,}/, "").replace(/\.json$/, "");
|
|
if (pathname === "/index") {
|
|
return "/";
|
|
}
|
|
return pathname;
|
|
}
|
|
function matchUrlToPage(urlPathname) {
|
|
urlPathname = normalizeDataPath(urlPathname);
|
|
console.log("before normalize", urlPathname);
|
|
for (const suffixRegex of [
|
|
/\.segments(\/.*)\.segment\.rsc$/,
|
|
/\.rsc$/
|
|
]) {
|
|
urlPathname = urlPathname.replace(suffixRegex, "");
|
|
}
|
|
const urlPathnameWithLocale = urlPathname;
|
|
const normalizeResult = normalizeLocalePath(
|
|
urlPathname,
|
|
i18n?.locales
|
|
);
|
|
urlPathname = normalizeResult.pathname;
|
|
console.log("after normalize", normalizeResult);
|
|
urlPathname = urlPathname.replace(/\/$/, "") || "/";
|
|
const combinedRoutes = [...staticRoutes, ...dynamicRoutes];
|
|
for (const route of combinedRoutes) {
|
|
if (route.page === urlPathname) {
|
|
console.log("matched direct page", route);
|
|
return {
|
|
matchedPathname: inversedAppRoutesManifest[route.page] || route.page,
|
|
locale: normalizeResult.locale
|
|
};
|
|
}
|
|
}
|
|
for (const route of [...staticRoutes, ...dynamicRoutes]) {
|
|
console.log("testing", route.namedRegex, "against", urlPathname);
|
|
const matches = urlPathname.match(route.namedRegex);
|
|
if (matches || urlPathname === "/index" && route.namedRegex.test("/")) {
|
|
const fallbackFalseMap = prerenderFallbackFalseMap[route.page];
|
|
if (fallbackFalseMap && !(fallbackFalseMap.includes(urlPathname) || fallbackFalseMap.includes(urlPathnameWithLocale))) {
|
|
console.log("fallback: false but not prerendered", {
|
|
page: route.page,
|
|
urlPathname,
|
|
urlPathnameWithLocale,
|
|
paths: Object.values(fallbackFalseMap)
|
|
});
|
|
continue;
|
|
}
|
|
console.log("matched route", route, urlPathname, matches);
|
|
return {
|
|
matchedPathname: inversedAppRoutesManifest[route.page] || route.page,
|
|
locale: normalizeResult.locale,
|
|
matches
|
|
};
|
|
}
|
|
}
|
|
return {
|
|
matchedPathname: inversedAppRoutesManifest[urlPathname] || urlPathname,
|
|
locale: normalizeResult.locale
|
|
};
|
|
}
|
|
const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
|
|
function getRequestContext() {
|
|
const fromSymbol = globalThis;
|
|
return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
|
|
}
|
|
const RouterServerContextSymbol = Symbol.for(
|
|
"@next/router-server-methods"
|
|
);
|
|
const routerServerGlobal = globalThis;
|
|
if (!routerServerGlobal[RouterServerContextSymbol]) {
|
|
routerServerGlobal[RouterServerContextSymbol] = {};
|
|
}
|
|
routerServerGlobal[RouterServerContextSymbol]["."] = {
|
|
async render404(req, res) {
|
|
let mod;
|
|
try {
|
|
try {
|
|
mod = await require("./" + path.posix.join(
|
|
relativeDistDir,
|
|
"server",
|
|
"app",
|
|
`_not-found`,
|
|
"page.js"
|
|
));
|
|
console.log("using _not-found.js for render404");
|
|
} catch {
|
|
}
|
|
if (!mod) {
|
|
mod = await require("./" + path.posix.join(
|
|
relativeDistDir,
|
|
"server",
|
|
"pages",
|
|
`404.js`
|
|
));
|
|
console.log("using 404.js for render404");
|
|
}
|
|
} catch (_) {
|
|
mod = await require("./" + path.posix.join(
|
|
relativeDistDir,
|
|
"server",
|
|
"pages",
|
|
`_error.js`
|
|
));
|
|
console.log("using _error for render404");
|
|
}
|
|
res.statusCode = 404;
|
|
if (mod) {
|
|
await mod.handler(req, res, {
|
|
waitUntil: getRequestContext().waitUntil
|
|
});
|
|
} else {
|
|
console.log(
|
|
"failed to find 404 module",
|
|
await require("fs").promises.readdir(
|
|
path.posix.join(relativeDistDir, "server", "pages")
|
|
).catch((err) => err)
|
|
);
|
|
res.end("This page could not be found");
|
|
}
|
|
}
|
|
};
|
|
return async function handler(req, res, internalMetadata) {
|
|
try {
|
|
const parsedUrl = new URL(req.url || "/", "http://n");
|
|
let urlPathname = req.headers["x-matched-path"];
|
|
if (typeof urlPathname !== "string") {
|
|
console.log("no x-matched-path", { url: req.url });
|
|
urlPathname = parsedUrl.pathname || "/";
|
|
}
|
|
const {
|
|
matchedPathname: page,
|
|
locale,
|
|
matches
|
|
} = matchUrlToPage(urlPathname);
|
|
const isAppDir = page.match(/\/(page|route)$/);
|
|
let addedMatchesToUrl = false;
|
|
for (const matchKey in matches?.groups || {}) {
|
|
const matchValue = matches?.groups?.[matchKey];
|
|
if (!parsedUrl.searchParams.has(matchKey) && matchValue) {
|
|
parsedUrl.searchParams.set(matchKey, matchValue);
|
|
addedMatchesToUrl = true;
|
|
}
|
|
}
|
|
if (addedMatchesToUrl) {
|
|
console.log("updating URL with new matches", matches, req.url);
|
|
req.url = `${parsedUrl.pathname}${parsedUrl.searchParams.size > 0 ? "?" : ""}${parsedUrl.searchParams.toString()}`;
|
|
}
|
|
console.log("invoking handler", {
|
|
page,
|
|
url: req.url,
|
|
matchedPath: req.headers["x-matched-path"]
|
|
});
|
|
const mod = await require("./" + path.posix.join(
|
|
relativeDistDir,
|
|
"server",
|
|
isAppDir ? "app" : "pages",
|
|
`${page === "/" ? "index" : page}.js`
|
|
));
|
|
await mod.handler(req, res, {
|
|
waitUntil: getRequestContext().waitUntil,
|
|
requestMeta: {
|
|
...internalMetadata,
|
|
minimalMode: true,
|
|
// we use '.' for relative project dir since we process.chdir
|
|
// to the same directory as the handler file so everything is
|
|
// relative to that/project dir
|
|
relativeProjectDir: ".",
|
|
locale
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error(`Failed to handle ${req.url}`, error);
|
|
throw error;
|
|
}
|
|
};
|
|
}).toString()})()
|
|
|
|
module.exports = _n_handler
|
|
|
|
${ctx.isMiddleware ? "" : `
|
|
module.exports.getRequestHandlerWithMetadata = (metadata) => {
|
|
console.log('using getRequestHandlerWithMetadata', metadata)
|
|
return (req, res) => _n_handler(req, res, metadata)
|
|
}
|
|
`}
|
|
|
|
`.replaceAll(
|
|
"process.env.__PRIVATE_RELATIVE_DIST_DIR",
|
|
`"${ctx.projectRelativeDistDir}"`
|
|
).replaceAll(
|
|
"process.env.__PRIVATE_PRERENDER_FALLBACK_MAP",
|
|
JSON.stringify(ctx.prerenderFallbackFalseMap)
|
|
).replaceAll(
|
|
"process.env.__PRIVATE_NEXT_CONFIG",
|
|
JSON.stringify(ctx.nextConfig)
|
|
);
|
|
// Annotate the CommonJS export names for ESM import in node:
|
|
0 && (module.exports = {
|
|
getHandlerSource
|
|
});
|