main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
import type { AppRouteHandlerFn, AppRouteHandlers } from '../module';
import { type HTTP_METHOD } from '../../../../web/http';
export declare function autoImplementMethods(handlers: AppRouteHandlers): Record<HTTP_METHOD, AppRouteHandlerFn>;

View File

@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "autoImplementMethods", {
enumerable: true,
get: function() {
return autoImplementMethods;
}
});
const _http = require("../../../../web/http");
const _responsehandlers = require("../../helpers/response-handlers");
const AUTOMATIC_ROUTE_METHODS = [
"HEAD",
"OPTIONS"
];
function autoImplementMethods(handlers) {
// Loop through all the HTTP methods to create the initial methods object.
// Each of the methods will be set to the the 405 response handler.
const methods = _http.HTTP_METHODS.reduce((acc, method)=>({
...acc,
// If the userland module implements the method, then use it. Otherwise,
// use the 405 response handler.
[method]: handlers[method] ?? _responsehandlers.handleMethodNotAllowedResponse
}), {});
// Get all the methods that could be automatically implemented that were not
// implemented by the userland module.
const implemented = new Set(_http.HTTP_METHODS.filter((method)=>handlers[method]));
const missing = AUTOMATIC_ROUTE_METHODS.filter((method)=>!implemented.has(method));
// Loop over the missing methods to automatically implement them if we can.
for (const method of missing){
// If the userland module doesn't implement the HEAD method, then
// we'll automatically implement it by calling the GET method (if it
// exists).
if (method === "HEAD") {
// If the userland module doesn't implement the GET method, then
// we're done.
if (!handlers.GET) break;
// Implement the HEAD method by calling the GET method.
methods.HEAD = handlers.GET;
// Mark it as implemented.
implemented.add("HEAD");
continue;
}
// If OPTIONS is not provided then implement it.
if (method === "OPTIONS") {
// TODO: check if HEAD is implemented, if so, use it to add more headers
// Get all the methods that were implemented by the userland module.
const allow = [
"OPTIONS",
...implemented
];
// If the list of methods doesn't include HEAD, but it includes GET, then
// add HEAD as it's automatically implemented.
if (!implemented.has("HEAD") && implemented.has("GET")) {
allow.push("HEAD");
}
// Sort and join the list with commas to create the `Allow` header. See:
// https://httpwg.org/specs/rfc9110.html#field.allow
const headers = {
Allow: allow.sort().join(", ")
};
// Implement the OPTIONS method by returning a 204 response with the
// `Allow` header.
methods.OPTIONS = ()=>new Response(null, {
status: 204,
headers
});
// Mark this method as implemented.
implemented.add("OPTIONS");
continue;
}
throw new Error(`Invariant: should handle all automatic implementable methods, got method: ${method}`);
}
return methods;
}
//# sourceMappingURL=auto-implement-methods.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/server/future/route-modules/app-route/helpers/auto-implement-methods.ts"],"names":["autoImplementMethods","AUTOMATIC_ROUTE_METHODS","handlers","methods","HTTP_METHODS","reduce","acc","method","handleMethodNotAllowedResponse","implemented","Set","filter","missing","has","GET","HEAD","add","allow","push","headers","Allow","sort","join","OPTIONS","Response","status","Error"],"mappings":";;;;+BAOgBA;;;eAAAA;;;sBAL+B;kCACA;AAE/C,MAAMC,0BAA0B;IAAC;IAAQ;CAAU;AAE5C,SAASD,qBACdE,QAA0B;IAE1B,0EAA0E;IAC1E,mEAAmE;IACnE,MAAMC,UAAkDC,kBAAY,CAACC,MAAM,CACzE,CAACC,KAAKC,SAAY,CAAA;YAChB,GAAGD,GAAG;YACN,wEAAwE;YACxE,gCAAgC;YAChC,CAACC,OAAO,EAAEL,QAAQ,CAACK,OAAO,IAAIC,gDAA8B;QAC9D,CAAA,GACA,CAAC;IAGH,4EAA4E;IAC5E,sCAAsC;IACtC,MAAMC,cAAc,IAAIC,IAAIN,kBAAY,CAACO,MAAM,CAAC,CAACJ,SAAWL,QAAQ,CAACK,OAAO;IAC5E,MAAMK,UAAUX,wBAAwBU,MAAM,CAC5C,CAACJ,SAAW,CAACE,YAAYI,GAAG,CAACN;IAG/B,2EAA2E;IAC3E,KAAK,MAAMA,UAAUK,QAAS;QAC5B,iEAAiE;QACjE,oEAAoE;QACpE,WAAW;QACX,IAAIL,WAAW,QAAQ;YACrB,gEAAgE;YAChE,cAAc;YACd,IAAI,CAACL,SAASY,GAAG,EAAE;YAEnB,uDAAuD;YACvDX,QAAQY,IAAI,GAAGb,SAASY,GAAG;YAE3B,0BAA0B;YAC1BL,YAAYO,GAAG,CAAC;YAEhB;QACF;QAEA,gDAAgD;QAChD,IAAIT,WAAW,WAAW;YACxB,wEAAwE;YAExE,oEAAoE;YACpE,MAAMU,QAAuB;gBAAC;mBAAcR;aAAY;YAExD,yEAAyE;YACzE,8CAA8C;YAC9C,IAAI,CAACA,YAAYI,GAAG,CAAC,WAAWJ,YAAYI,GAAG,CAAC,QAAQ;gBACtDI,MAAMC,IAAI,CAAC;YACb;YAEA,wEAAwE;YACxE,oDAAoD;YACpD,MAAMC,UAAU;gBAAEC,OAAOH,MAAMI,IAAI,GAAGC,IAAI,CAAC;YAAM;YAEjD,oEAAoE;YACpE,kBAAkB;YAClBnB,QAAQoB,OAAO,GAAG,IAAM,IAAIC,SAAS,MAAM;oBAAEC,QAAQ;oBAAKN;gBAAQ;YAElE,mCAAmC;YACnCV,YAAYO,GAAG,CAAC;YAEhB;QACF;QAEA,MAAM,IAAIU,MACR,CAAC,0EAA0E,EAAEnB,OAAO,CAAC;IAEzF;IAEA,OAAOJ;AACT"}

View File

@@ -0,0 +1,7 @@
/**
* Cleans a URL by stripping the protocol, host, and search params.
*
* @param urlString the url to clean
* @returns the cleaned url
*/
export declare function cleanURL(urlString: string): string;

View File

@@ -0,0 +1,24 @@
/**
* Cleans a URL by stripping the protocol, host, and search params.
*
* @param urlString the url to clean
* @returns the cleaned url
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "cleanURL", {
enumerable: true,
get: function() {
return cleanURL;
}
});
function cleanURL(urlString) {
const url = new URL(urlString);
url.host = "localhost:3000";
url.search = "";
url.protocol = "http";
return url.toString();
}
//# sourceMappingURL=clean-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/server/future/route-modules/app-route/helpers/clean-url.ts"],"names":["cleanURL","urlString","url","URL","host","search","protocol","toString"],"mappings":"AAAA;;;;;CAKC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,SAASC,SAAiB;IACxC,MAAMC,MAAM,IAAIC,IAAIF;IACpBC,IAAIE,IAAI,GAAG;IACXF,IAAIG,MAAM,GAAG;IACbH,IAAII,QAAQ,GAAG;IACf,OAAOJ,IAAIK,QAAQ;AACrB"}

View File

@@ -0,0 +1,10 @@
import type { HTTP_METHOD } from '../../../../web/http';
import type { AppRouteHandlers } from '../module';
/**
* Gets all the method names for handlers that are not considered static.
*
* @param handlers the handlers from the userland module
* @returns the method names that are not considered static or false if all
* methods are static
*/
export declare function getNonStaticMethods(handlers: AppRouteHandlers): ReadonlyArray<HTTP_METHOD> | false;

View File

@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getNonStaticMethods", {
enumerable: true,
get: function() {
return getNonStaticMethods;
}
});
const NON_STATIC_METHODS = [
"OPTIONS",
"POST",
"PUT",
"DELETE",
"PATCH"
];
function getNonStaticMethods(handlers) {
// We can currently only statically optimize if only GET/HEAD are used as
// prerender can't be used conditionally based on the method currently.
const methods = NON_STATIC_METHODS.filter((method)=>handlers[method]);
if (methods.length === 0) return false;
return methods;
}
//# sourceMappingURL=get-non-static-methods.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/server/future/route-modules/app-route/helpers/get-non-static-methods.ts"],"names":["getNonStaticMethods","NON_STATIC_METHODS","handlers","methods","filter","method","length"],"mappings":";;;;+BAkBgBA;;;eAAAA;;;AAfhB,MAAMC,qBAAqB;IACzB;IACA;IACA;IACA;IACA;CACD;AASM,SAASD,oBACdE,QAA0B;IAE1B,yEAAyE;IACzE,uEAAuE;IACvE,MAAMC,UAAUF,mBAAmBG,MAAM,CAAC,CAACC,SAAWH,QAAQ,CAACG,OAAO;IACtE,IAAIF,QAAQG,MAAM,KAAK,GAAG,OAAO;IAEjC,OAAOH;AACT"}

View File

@@ -0,0 +1,7 @@
/**
* Get pathname from absolute path.
*
* @param absolutePath the absolute path
* @returns the pathname
*/
export declare function getPathnameFromAbsolutePath(absolutePath: string): string;

View File

@@ -0,0 +1,29 @@
/**
* Get pathname from absolute path.
*
* @param absolutePath the absolute path
* @returns the pathname
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getPathnameFromAbsolutePath", {
enumerable: true,
get: function() {
return getPathnameFromAbsolutePath;
}
});
function getPathnameFromAbsolutePath(absolutePath) {
// Remove prefix including app dir
let appDir = "/app/";
if (!absolutePath.includes(appDir)) {
appDir = "\\app\\";
}
const [, ...parts] = absolutePath.split(appDir);
const relativePath = appDir[0] + parts.join(appDir);
// remove extension
const pathname = relativePath.split(".").slice(0, -1).join(".");
return pathname;
}
//# sourceMappingURL=get-pathname-from-absolute-path.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/server/future/route-modules/app-route/helpers/get-pathname-from-absolute-path.ts"],"names":["getPathnameFromAbsolutePath","absolutePath","appDir","includes","parts","split","relativePath","join","pathname","slice"],"mappings":"AAAA;;;;;CAKC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,4BAA4BC,YAAoB;IAC9D,kCAAkC;IAClC,IAAIC,SAAS;IACb,IAAI,CAACD,aAAaE,QAAQ,CAACD,SAAS;QAClCA,SAAS;IACX;IACA,MAAM,GAAG,GAAGE,MAAM,GAAGH,aAAaI,KAAK,CAACH;IACxC,MAAMI,eAAeJ,MAAM,CAAC,EAAE,GAAGE,MAAMG,IAAI,CAACL;IAE5C,mBAAmB;IACnB,MAAMM,WAAWF,aAAaD,KAAK,CAAC,KAAKI,KAAK,CAAC,GAAG,CAAC,GAAGF,IAAI,CAAC;IAC3D,OAAOC;AACT"}

View File

@@ -0,0 +1,9 @@
/// <reference types="node" />
import type { ParsedUrlQuery } from 'querystring';
/**
* Converts the query into params.
*
* @param query the query to convert to params
* @returns the params
*/
export declare function parsedUrlQueryToParams(query: ParsedUrlQuery): Record<string, string | string[]>;

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "parsedUrlQueryToParams", {
enumerable: true,
get: function() {
return parsedUrlQueryToParams;
}
});
function parsedUrlQueryToParams(query) {
const params = {};
for (const [key, value] of Object.entries(query)){
if (typeof value === "undefined") continue;
params[key] = value;
}
return params;
}
//# sourceMappingURL=parsed-url-query-to-params.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/server/future/route-modules/app-route/helpers/parsed-url-query-to-params.ts"],"names":["parsedUrlQueryToParams","query","params","key","value","Object","entries"],"mappings":";;;;+BAQgBA;;;eAAAA;;;AAAT,SAASA,uBACdC,KAAqB;IAErB,MAAMC,SAA4C,CAAC;IAEnD,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,OAAQ;QAChD,IAAI,OAAOG,UAAU,aAAa;QAClCF,MAAM,CAACC,IAAI,GAAGC;IAChB;IAEA,OAAOF;AACT"}

View File

@@ -0,0 +1,10 @@
import type * as ServerHooks from '../../../../../client/components/hooks-server-context';
import type * as HeaderHooks from '../../../../../client/components/headers';
import type { staticGenerationBailout as StaticGenerationBailout } from '../../../../../client/components/static-generation-bailout';
import type { AppRouteUserlandModule } from '../module';
import type { NextRequest } from '../../../../web/spec-extension/request';
export declare function proxyRequest(request: NextRequest, { dynamic }: Pick<AppRouteUserlandModule, 'dynamic'>, hooks: {
readonly serverHooks: typeof ServerHooks;
readonly headerHooks: typeof HeaderHooks;
readonly staticGenerationBailout: typeof StaticGenerationBailout;
}): NextRequest;

View File

@@ -0,0 +1,123 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "proxyRequest", {
enumerable: true,
get: function() {
return proxyRequest;
}
});
const _cookies = require("next/dist/compiled/@edge-runtime/cookies");
const _nexturl = require("../../../../web/next-url");
const _cleanurl = require("./clean-url");
function proxyRequest(request, { dynamic }, hooks) {
function handleNextUrlBailout(prop) {
switch(prop){
case "search":
case "searchParams":
case "toString":
case "href":
case "origin":
hooks.staticGenerationBailout(`nextUrl.${prop}`);
return;
default:
return;
}
}
const cache = {};
const handleForceStatic = (url, prop)=>{
switch(prop){
case "search":
return "";
case "searchParams":
if (!cache.searchParams) cache.searchParams = new URLSearchParams();
return cache.searchParams;
case "url":
case "href":
if (!cache.url) cache.url = (0, _cleanurl.cleanURL)(url);
return cache.url;
case "toJSON":
case "toString":
if (!cache.url) cache.url = (0, _cleanurl.cleanURL)(url);
if (!cache.toString) cache.toString = ()=>cache.url;
return cache.toString;
case "headers":
if (!cache.headers) cache.headers = new Headers();
return cache.headers;
case "cookies":
if (!cache.headers) cache.headers = new Headers();
if (!cache.cookies) cache.cookies = new _cookies.RequestCookies(cache.headers);
return cache.cookies;
case "clone":
if (!cache.url) cache.url = (0, _cleanurl.cleanURL)(url);
return ()=>new _nexturl.NextURL(cache.url);
default:
break;
}
};
const wrappedNextUrl = new Proxy(request.nextUrl, {
get (target, prop) {
handleNextUrlBailout(prop);
if (dynamic === "force-static" && typeof prop === "string") {
const result = handleForceStatic(target.href, prop);
if (result !== undefined) return result;
}
const value = target[prop];
if (typeof value === "function") {
return value.bind(target);
}
return value;
},
set (target, prop, value) {
handleNextUrlBailout(prop);
target[prop] = value;
return true;
}
});
const handleReqBailout = (prop)=>{
switch(prop){
case "headers":
hooks.headerHooks.headers();
return;
// if request.url is accessed directly instead of
// request.nextUrl we bail since it includes query
// values that can be relied on dynamically
case "url":
case "body":
case "blob":
case "json":
case "text":
case "arrayBuffer":
case "formData":
hooks.staticGenerationBailout(`request.${prop}`);
return;
default:
return;
}
};
return new Proxy(request, {
get (target, prop) {
handleReqBailout(prop);
if (prop === "nextUrl") {
return wrappedNextUrl;
}
if (dynamic === "force-static" && typeof prop === "string") {
const result = handleForceStatic(target.url, prop);
if (result !== undefined) return result;
}
const value = target[prop];
if (typeof value === "function") {
return value.bind(target);
}
return value;
},
set (target, prop, value) {
handleReqBailout(prop);
target[prop] = value;
return true;
}
});
}
//# sourceMappingURL=proxy-request.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/server/future/route-modules/app-route/helpers/proxy-request.ts"],"names":["proxyRequest","request","dynamic","hooks","handleNextUrlBailout","prop","staticGenerationBailout","cache","handleForceStatic","url","searchParams","URLSearchParams","cleanURL","toString","headers","Headers","cookies","RequestCookies","NextURL","wrappedNextUrl","Proxy","nextUrl","get","target","result","href","undefined","value","bind","set","handleReqBailout","headerHooks"],"mappings":"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"}

View File

@@ -0,0 +1 @@
export declare function resolveHandlerError(err: any): Response | false;

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "resolveHandlerError", {
enumerable: true,
get: function() {
return resolveHandlerError;
}
});
const _notfound = require("../../../../../client/components/not-found");
const _redirect = require("../../../../../client/components/redirect");
const _responsehandlers = require("../../helpers/response-handlers");
function resolveHandlerError(err) {
if ((0, _redirect.isRedirectError)(err)) {
const redirect = (0, _redirect.getURLFromRedirectError)(err);
if (!redirect) {
throw new Error("Invariant: Unexpected redirect url format");
}
// This is a redirect error! Send the redirect response.
return (0, _responsehandlers.handleTemporaryRedirectResponse)(redirect, err.mutableCookies);
}
if ((0, _notfound.isNotFoundError)(err)) {
// This is a not found error! Send the not found response.
return (0, _responsehandlers.handleNotFoundResponse)();
}
// Return false to indicate that this is not a handled error.
return false;
}
//# sourceMappingURL=resolve-handler-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/server/future/route-modules/app-route/helpers/resolve-handler-error.ts"],"names":["resolveHandlerError","err","isRedirectError","redirect","getURLFromRedirectError","Error","handleTemporaryRedirectResponse","mutableCookies","isNotFoundError","handleNotFoundResponse"],"mappings":";;;;+BAUgBA;;;eAAAA;;;0BAVgB;0BAIzB;kCAIA;AAEA,SAASA,oBAAoBC,GAAQ;IAC1C,IAAIC,IAAAA,yBAAe,EAACD,MAAM;QACxB,MAAME,WAAWC,IAAAA,iCAAuB,EAACH;QACzC,IAAI,CAACE,UAAU;YACb,MAAM,IAAIE,MAAM;QAClB;QAEA,wDAAwD;QACxD,OAAOC,IAAAA,iDAA+B,EAACH,UAAUF,IAAIM,cAAc;IACrE;IAEA,IAAIC,IAAAA,yBAAe,EAACP,MAAM;QACxB,0DAA0D;QAC1D,OAAOQ,IAAAA,wCAAsB;IAC/B;IAEA,6DAA6D;IAC7D,OAAO;AACT"}

View File

@@ -0,0 +1,14 @@
"use strict";
if (process.env.NEXT_RUNTIME === "edge") {
module.exports = require("next/dist/server/future/route-modules/app-route/module.js");
} else {
if (process.env.NODE_ENV === "development") {
module.exports = require("next/dist/compiled/next-server/app-route.runtime.dev.js");
} else if (process.env.TURBOPACK) {
module.exports = require("next/dist/compiled/next-server/app-route-turbo.runtime.prod.js");
} else {
module.exports = require("next/dist/compiled/next-server/app-route.runtime.prod.js");
}
}
//# sourceMappingURL=module.compiled.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/future/route-modules/app-route/module.compiled.ts"],"names":["process","env","NEXT_RUNTIME","module","exports","require","NODE_ENV","TURBOPACK"],"mappings":";AAAA,IAAIA,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCC,OAAOC,OAAO,GAAGC,QAAQ;AAC3B,OAAO;IACL,IAAIL,QAAQC,GAAG,CAACK,QAAQ,KAAK,eAAe;QAC1CH,OAAOC,OAAO,GAAGC,QAAQ;IAC3B,OAAO,IAAIL,QAAQC,GAAG,CAACM,SAAS,EAAE;QAChCJ,OAAOC,OAAO,GAAGC,QAAQ;IAC3B,OAAO;QACLF,OAAOC,OAAO,GAAGC,QAAQ;IAC3B;AACF"}

View File

@@ -0,0 +1,116 @@
import type { NextConfig } from '../../../config-shared';
import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition';
import type { AppConfig } from '../../../../build/utils';
import type { NextRequest } from '../../../web/spec-extension/request';
import type { PrerenderManifest } from '../../../../build';
import { RouteModule, type RouteModuleHandleContext, type RouteModuleOptions } from '../route-module';
import { type StaticGenerationContext } from '../../../async-storage/static-generation-async-storage-wrapper';
import { type HTTP_METHOD } from '../../../web/http';
import * as serverHooks from '../../../../client/components/hooks-server-context';
import * as headerHooks from '../../../../client/components/headers';
import * as sharedModules from './shared-modules';
/**
* AppRouteRouteHandlerContext is the context that is passed to the route
* handler for app routes.
*/
export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
staticGenerationContext: StaticGenerationContext['renderOpts'];
prerenderManifest: PrerenderManifest;
}
/**
* AppRouteHandlerFnContext is the context that is passed to the handler as the
* second argument.
*/
type AppRouteHandlerFnContext = {
params?: Record<string, string | string[]>;
};
/**
* Handler function for app routes. If a non-Response value is returned, an error
* will be thrown.
*/
export type AppRouteHandlerFn = (
/**
* Incoming request object.
*/
req: NextRequest,
/**
* Context properties on the request (including the parameters if this was a
* dynamic route).
*/
ctx: AppRouteHandlerFnContext) => unknown;
/**
* AppRouteHandlers describes the handlers for app routes that is provided by
* the userland module.
*/
export type AppRouteHandlers = {
[method in HTTP_METHOD]?: AppRouteHandlerFn;
};
/**
* AppRouteUserlandModule is the userland module that is provided for app
* routes. This contains all the user generated code.
*/
export type AppRouteUserlandModule = AppRouteHandlers & Pick<AppConfig, 'dynamic' | 'revalidate' | 'dynamicParams' | 'fetchCache'> & {
generateStaticParams?: any;
};
/**
* AppRouteRouteModuleOptions is the options that are passed to the app route
* module from the bundled code.
*/
export interface AppRouteRouteModuleOptions extends RouteModuleOptions<AppRouteRouteDefinition, AppRouteUserlandModule> {
readonly resolvedPagePath: string;
readonly nextConfigOutput: NextConfig['output'];
}
/**
* AppRouteRouteHandler is the handler for app routes.
*/
export declare class AppRouteRouteModule extends RouteModule<AppRouteRouteDefinition, AppRouteUserlandModule> {
/**
* A reference to the request async storage.
*/
readonly requestAsyncStorage: import("../../../../client/components/request-async-storage.external").RequestAsyncStorage;
/**
* A reference to the static generation async storage.
*/
readonly staticGenerationAsyncStorage: import("../../../../client/components/static-generation-async-storage.external").StaticGenerationAsyncStorage;
/**
* An interface to call server hooks which interact with the underlying
* storage.
*/
readonly serverHooks: typeof serverHooks;
/**
* An interface to call header hooks which interact with the underlying
* request storage.
*/
readonly headerHooks: typeof headerHooks;
/**
* An interface to call static generation bailout hooks which interact with
* the underlying static generation storage.
*/
readonly staticGenerationBailout: import("../../../../client/components/static-generation-bailout").StaticGenerationBailout;
static readonly sharedModules: typeof sharedModules;
/**
* A reference to the mutation related async storage, such as mutations of
* cookies.
*/
readonly actionAsyncStorage: import("../../../../client/components/action-async-storage.external").ActionAsyncStorage;
readonly resolvedPagePath: string;
readonly nextConfigOutput: NextConfig['output'] | undefined;
private readonly methods;
private readonly nonStaticMethods;
private readonly dynamic;
static is(route: RouteModule): route is AppRouteRouteModule;
constructor({ userland, definition, resolvedPagePath, nextConfigOutput, }: AppRouteRouteModuleOptions);
/**
* Resolves the handler function for the given method.
*
* @param method the requested method
* @returns the handler function for the given method
*/
private resolve;
/**
* Executes the route handler.
*/
private execute;
handle(request: NextRequest, context: AppRouteRouteHandlerContext): Promise<Response>;
}
export default AppRouteRouteModule;

View File

@@ -0,0 +1,331 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
AppRouteRouteModule: null,
default: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
AppRouteRouteModule: function() {
return AppRouteRouteModule;
},
default: function() {
return _default;
}
});
const _routemodule = require("../route-module");
const _requestasyncstoragewrapper = require("../../../async-storage/request-async-storage-wrapper");
const _staticgenerationasyncstoragewrapper = require("../../../async-storage/static-generation-async-storage-wrapper");
const _responsehandlers = require("../helpers/response-handlers");
const _http = require("../../../web/http");
const _patchfetch = require("../../../lib/patch-fetch");
const _tracer = require("../../../lib/trace/tracer");
const _constants = require("../../../lib/trace/constants");
const _getpathnamefromabsolutepath = require("./helpers/get-pathname-from-absolute-path");
const _proxyrequest = require("./helpers/proxy-request");
const _resolvehandlererror = require("./helpers/resolve-handler-error");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../../../build/output/log"));
const _autoimplementmethods = require("./helpers/auto-implement-methods");
const _getnonstaticmethods = require("./helpers/get-non-static-methods");
const _requestcookies = require("../../../web/spec-extension/adapters/request-cookies");
const _routekind = require("../../route-kind");
const _parsedurlquerytoparams = require("./helpers/parsed-url-query-to-params");
const _hooksservercontext = /*#__PURE__*/ _interop_require_wildcard(require("../../../../client/components/hooks-server-context"));
const _headers = /*#__PURE__*/ _interop_require_wildcard(require("../../../../client/components/headers"));
const _staticgenerationbailout = require("../../../../client/components/static-generation-bailout");
const _requestasyncstorageexternal = require("../../../../client/components/request-async-storage.external");
const _staticgenerationasyncstorageexternal = require("../../../../client/components/static-generation-async-storage.external");
const _actionasyncstorageexternal = require("../../../../client/components/action-async-storage.external");
const _sharedmodules = /*#__PURE__*/ _interop_require_wildcard(require("./shared-modules"));
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
class AppRouteRouteModule extends _routemodule.RouteModule {
static #_ = this.sharedModules = _sharedmodules;
static is(route) {
return route.definition.kind === _routekind.RouteKind.APP_ROUTE;
}
constructor({ userland, definition, resolvedPagePath, nextConfigOutput }){
super({
userland,
definition
});
/**
* A reference to the request async storage.
*/ this.requestAsyncStorage = _requestasyncstorageexternal.requestAsyncStorage;
/**
* A reference to the static generation async storage.
*/ this.staticGenerationAsyncStorage = _staticgenerationasyncstorageexternal.staticGenerationAsyncStorage;
/**
* An interface to call server hooks which interact with the underlying
* storage.
*/ this.serverHooks = _hooksservercontext;
/**
* An interface to call header hooks which interact with the underlying
* request storage.
*/ this.headerHooks = _headers;
/**
* An interface to call static generation bailout hooks which interact with
* the underlying static generation storage.
*/ this.staticGenerationBailout = _staticgenerationbailout.staticGenerationBailout;
/**
* A reference to the mutation related async storage, such as mutations of
* cookies.
*/ this.actionAsyncStorage = _actionasyncstorageexternal.actionAsyncStorage;
this.resolvedPagePath = resolvedPagePath;
this.nextConfigOutput = nextConfigOutput;
// Automatically implement some methods if they aren't implemented by the
// userland module.
this.methods = (0, _autoimplementmethods.autoImplementMethods)(userland);
// Get the non-static methods for this route.
this.nonStaticMethods = (0, _getnonstaticmethods.getNonStaticMethods)(userland);
// Get the dynamic property from the userland module.
this.dynamic = this.userland.dynamic;
if (this.nextConfigOutput === "export") {
if (!this.dynamic || this.dynamic === "auto") {
this.dynamic = "error";
} else if (this.dynamic === "force-dynamic") {
throw new Error(`export const dynamic = "force-dynamic" on page "${definition.pathname}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`);
}
}
// We only warn in development after here, so return if we're not in
// development.
if (process.env.NODE_ENV === "development") {
// Print error in development if the exported handlers are in lowercase, only
// uppercase handlers are supported.
const lowercased = _http.HTTP_METHODS.map((method)=>method.toLowerCase());
for (const method of lowercased){
if (method in this.userland) {
_log.error(`Detected lowercase method '${method}' in '${this.resolvedPagePath}'. Export the uppercase '${method.toUpperCase()}' method name to fix this error.`);
}
}
// Print error if the module exports a default handler, they must use named
// exports for each HTTP method.
if ("default" in this.userland) {
_log.error(`Detected default export in '${this.resolvedPagePath}'. Export a named export for each HTTP method instead.`);
}
// If there is no methods exported by this module, then return a not found
// response.
if (!_http.HTTP_METHODS.some((method)=>method in this.userland)) {
_log.error(`No HTTP methods exported in '${this.resolvedPagePath}'. Export a named export for each HTTP method.`);
}
}
}
/**
* Resolves the handler function for the given method.
*
* @param method the requested method
* @returns the handler function for the given method
*/ resolve(method) {
// Ensure that the requested method is a valid method (to prevent RCE's).
if (!(0, _http.isHTTPMethod)(method)) return _responsehandlers.handleBadRequestResponse;
// Return the handler.
return this.methods[method];
}
/**
* Executes the route handler.
*/ async execute(request, context) {
// Get the handler function for the given method.
const handler = this.resolve(request.method);
// Get the context for the request.
const requestContext = {
req: request
};
requestContext.renderOpts = {
previewProps: context.prerenderManifest.preview
};
// Get the context for the static generation.
const staticGenerationContext = {
urlPathname: request.nextUrl.pathname,
renderOpts: // If the staticGenerationContext is not provided then we default to
// the default values.
context.staticGenerationContext ?? {
supportsDynamicHTML: false,
originalPathname: this.definition.pathname
}
};
// Add the fetchCache option to the renderOpts.
staticGenerationContext.renderOpts.fetchCache = this.userland.fetchCache;
// Run the handler with the request AsyncLocalStorage to inject the helper
// support. We set this to `unknown` because the type is not known until
// runtime when we do a instanceof check below.
const response = await this.actionAsyncStorage.run({
isAppRoute: true
}, ()=>_requestasyncstoragewrapper.RequestAsyncStorageWrapper.wrap(this.requestAsyncStorage, requestContext, ()=>_staticgenerationasyncstoragewrapper.StaticGenerationAsyncStorageWrapper.wrap(this.staticGenerationAsyncStorage, staticGenerationContext, (staticGenerationStore)=>{
var _getTracer_getRootSpanAttributes;
// Check to see if we should bail out of static generation based on
// having non-static methods.
if (this.nonStaticMethods) {
this.staticGenerationBailout(`non-static methods used ${this.nonStaticMethods.join(", ")}`);
}
// Update the static generation store based on the dynamic property.
switch(this.dynamic){
case "force-dynamic":
// The dynamic property is set to force-dynamic, so we should
// force the page to be dynamic.
staticGenerationStore.forceDynamic = true;
this.staticGenerationBailout(`force-dynamic`, {
dynamic: this.dynamic
});
break;
case "force-static":
// The dynamic property is set to force-static, so we should
// force the page to be static.
staticGenerationStore.forceStatic = true;
break;
case "error":
// The dynamic property is set to error, so we should throw an
// error if the page is being statically generated.
staticGenerationStore.dynamicShouldError = true;
break;
default:
break;
}
// If the static generation store does not have a revalidate value
// set, then we should set it the revalidate value from the userland
// module or default to false.
staticGenerationStore.revalidate ??= this.userland.revalidate ?? false;
// Wrap the request so we can add additional functionality to cases
// that might change it's output or affect the rendering.
const wrappedRequest = (0, _proxyrequest.proxyRequest)(request, {
dynamic: this.dynamic
}, {
headerHooks: this.headerHooks,
serverHooks: this.serverHooks,
staticGenerationBailout: this.staticGenerationBailout
});
// TODO: propagate this pathname from route matcher
const route = (0, _getpathnamefromabsolutepath.getPathnameFromAbsolutePath)(this.resolvedPagePath);
(_getTracer_getRootSpanAttributes = (0, _tracer.getTracer)().getRootSpanAttributes()) == null ? void 0 : _getTracer_getRootSpanAttributes.set("next.route", route);
return (0, _tracer.getTracer)().trace(_constants.AppRouteRouteHandlersSpan.runHandler, {
spanName: `executing api route (app) ${route}`,
attributes: {
"next.route": route
}
}, async ()=>{
var _staticGenerationStore_tags;
// Patch the global fetch.
(0, _patchfetch.patchFetch)({
serverHooks: this.serverHooks,
staticGenerationAsyncStorage: this.staticGenerationAsyncStorage
});
const res = await handler(wrappedRequest, {
params: context.params ? (0, _parsedurlquerytoparams.parsedUrlQueryToParams)(context.params) : undefined
});
if (!(res instanceof Response)) {
throw new Error(`No response is returned from route handler '${this.resolvedPagePath}'. Ensure you return a \`Response\` or a \`NextResponse\` in all branches of your handler.`);
}
context.staticGenerationContext.fetchMetrics = staticGenerationStore.fetchMetrics;
await Promise.all(staticGenerationStore.pendingRevalidates || []);
(0, _patchfetch.addImplicitTags)(staticGenerationStore);
context.staticGenerationContext.fetchTags = (_staticGenerationStore_tags = staticGenerationStore.tags) == null ? void 0 : _staticGenerationStore_tags.join(",");
// It's possible cookies were set in the handler, so we need
// to merge the modified cookies and the returned response
// here.
const requestStore = this.requestAsyncStorage.getStore();
if (requestStore && requestStore.mutableCookies) {
const headers = new Headers(res.headers);
if ((0, _requestcookies.appendMutableCookies)(headers, requestStore.mutableCookies)) {
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers
});
}
}
return res;
});
})));
// If the handler did't return a valid response, then return the internal
// error response.
if (!(response instanceof Response)) {
// TODO: validate the correct handling behavior, maybe log something?
return (0, _responsehandlers.handleInternalServerErrorResponse)();
}
if (response.headers.has("x-middleware-rewrite")) {
// TODO: move this error into the `NextResponse.rewrite()` function.
// TODO-APP: re-enable support below when we can proxy these type of requests
throw new Error("NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue.");
// // This is a rewrite created via `NextResponse.rewrite()`. We need to send
// // the response up so it can be handled by the backing server.
// // If the server is running in minimal mode, we just want to forward the
// // response (including the rewrite headers) upstream so it can perform the
// // redirect for us, otherwise return with the special condition so this
// // server can perform a rewrite.
// if (!minimalMode) {
// return { response, condition: 'rewrite' }
// }
// // Relativize the url so it's relative to the base url. This is so the
// // outgoing headers upstream can be relative.
// const rewritePath = response.headers.get('x-middleware-rewrite')!
// const initUrl = getRequestMeta(req, '__NEXT_INIT_URL')!
// const { pathname } = parseUrl(relativizeURL(rewritePath, initUrl))
// response.headers.set('x-middleware-rewrite', pathname)
}
if (response.headers.get("x-middleware-next") === "1") {
// TODO: move this error into the `NextResponse.next()` function.
throw new Error("NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler");
}
return response;
}
async handle(request, context) {
try {
// Execute the route to get the response.
const response = await this.execute(request, context);
// The response was handled, return it.
return response;
} catch (err) {
// Try to resolve the error to a response, else throw it again.
const response = (0, _resolvehandlererror.resolveHandlerError)(err);
if (!response) throw err;
// The response was resolved, return it.
return response;
}
}
}
const _default = AppRouteRouteModule;
//# sourceMappingURL=module.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export * as appRouterContext from '../../../../shared/lib/app-router-context.shared-runtime';

View File

@@ -0,0 +1,54 @@
// the name of the export has to be the camelCase version of the file name (without the extension)
// TODO: remove this. We need it because using notFound from next/navigation imports this file :(
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "appRouterContext", {
enumerable: true,
get: function() {
return _approutercontextsharedruntime;
}
});
const _approutercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../shared/lib/app-router-context.shared-runtime"));
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
//# sourceMappingURL=shared-modules.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/future/route-modules/app-route/shared-modules.ts"],"names":["appRouterContext"],"mappings":"AAAA,kGAAkG;AAClG,iGAAiG;;;;;+BACrFA;;;;;;uFAAsB"}