Initial commit

This commit is contained in:
bilulib
2025-04-13 00:18:57 +02:00
parent cff009bb7c
commit d894249e61
18301 changed files with 2905442 additions and 3845 deletions

View File

@@ -0,0 +1,23 @@
import type { RequestData, FetchEventResult } from './types';
import type { RequestInit } from './spec-extension/request';
import { NextFetchEvent } from './spec-extension/fetch-event';
import { NextRequest } from './spec-extension/request';
export declare class NextRequestHint extends NextRequest {
sourcePage: string;
fetchMetrics: FetchEventResult['fetchMetrics'] | undefined;
constructor(params: {
init: RequestInit;
input: Request | string;
page: string;
});
get request(): void;
respondWith(): void;
waitUntil(): void;
}
export type AdapterOptions = {
handler: (req: NextRequestHint, event: NextFetchEvent) => Promise<Response>;
page: string;
request: RequestData;
IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache;
};
export declare function adapter(params: AdapterOptions): Promise<FetchEventResult>;

View File

@@ -0,0 +1,366 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NextRequestHint: null,
adapter: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NextRequestHint: function() {
return NextRequestHint;
},
adapter: function() {
return adapter;
}
});
const _error = require("./error");
const _utils = require("./utils");
const _fetchevent = require("./spec-extension/fetch-event");
const _request = require("./spec-extension/request");
const _response = require("./spec-extension/response");
const _relativizeurl = require("../../shared/lib/router/utils/relativize-url");
const _nexturl = require("./next-url");
const _internalutils = require("../internal-utils");
const _apppaths = require("../../shared/lib/router/utils/app-paths");
const _approuterheaders = require("../../client/components/app-router-headers");
const _globals = require("./globals");
const _requeststore = require("../async-storage/request-store");
const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external");
const _workstore = require("../async-storage/work-store");
const _workasyncstorageexternal = require("../app-render/work-async-storage.external");
const _tracer = require("../lib/trace/tracer");
const _constants = require("../lib/trace/constants");
const _webonclose = require("./web-on-close");
const _getedgepreviewprops = require("./get-edge-preview-props");
const _builtinrequestcontext = require("../after/builtin-request-context");
const _implicittags = require("../lib/implicit-tags");
class NextRequestHint extends _request.NextRequest {
constructor(params){
super(params.input, params.init);
this.sourcePage = params.page;
}
get request() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
respondWith() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
waitUntil() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
}
const headersGetter = {
keys: (headers)=>Array.from(headers.keys()),
get: (headers, key)=>headers.get(key) ?? undefined
};
let propagator = (request, fn)=>{
const tracer = (0, _tracer.getTracer)();
return tracer.withPropagatedContext(request.headers, fn, headersGetter);
};
let testApisIntercepted = false;
function ensureTestApisIntercepted() {
if (!testApisIntercepted) {
testApisIntercepted = true;
if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') {
const { interceptTestApis, wrapRequestHandler } = require('next/dist/experimental/testmode/server-edge');
interceptTestApis();
propagator = wrapRequestHandler(propagator);
}
}
}
async function adapter(params) {
var _getBuiltinRequestContext;
ensureTestApisIntercepted();
await (0, _globals.ensureInstrumentationRegistered)();
// TODO-APP: use explicit marker for this
const isEdgeRendering = typeof globalThis.__BUILD_MANIFEST !== 'undefined';
params.request.url = (0, _apppaths.normalizeRscURL)(params.request.url);
const requestURL = new _nexturl.NextURL(params.request.url, {
headers: params.request.headers,
nextConfig: params.request.nextConfig
});
// Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator.
// Instead we use the keys before iteration.
const keys = [
...requestURL.searchParams.keys()
];
for (const key of keys){
const value = requestURL.searchParams.getAll(key);
const normalizedKey = (0, _utils.normalizeNextQueryParam)(key);
if (normalizedKey) {
requestURL.searchParams.delete(normalizedKey);
for (const val of value){
requestURL.searchParams.append(normalizedKey, val);
}
requestURL.searchParams.delete(key);
}
}
// Ensure users only see page requests, never data requests.
const buildId = requestURL.buildId;
requestURL.buildId = '';
const requestHeaders = (0, _utils.fromNodeOutgoingHttpHeaders)(params.request.headers);
const isNextDataRequest = requestHeaders.has('x-nextjs-data');
const isRSCRequest = requestHeaders.get(_approuterheaders.RSC_HEADER) === '1';
if (isNextDataRequest && requestURL.pathname === '/index') {
requestURL.pathname = '/';
}
const flightHeaders = new Map();
// Headers should only be stripped for middleware
if (!isEdgeRendering) {
for (const header of _approuterheaders.FLIGHT_HEADERS){
const key = header.toLowerCase();
const value = requestHeaders.get(key);
if (value !== null) {
flightHeaders.set(key, value);
requestHeaders.delete(key);
}
}
}
const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? new URL(params.request.url) : requestURL;
const request = new NextRequestHint({
page: params.page,
// Strip internal query parameters off the request.
input: (0, _internalutils.stripInternalSearchParams)(normalizeURL).toString(),
init: {
body: params.request.body,
headers: requestHeaders,
method: params.request.method,
nextConfig: params.request.nextConfig,
signal: params.request.signal
}
});
/**
* This allows to identify the request as a data request. The user doesn't
* need to know about this property neither use it. We add it for testing
* purposes.
*/ if (isNextDataRequest) {
Object.defineProperty(request, '__isData', {
enumerable: false,
value: true
});
}
if (!globalThis.__incrementalCache && params.IncrementalCache) {
;
globalThis.__incrementalCache = new params.IncrementalCache({
appDir: true,
fetchCache: true,
minimalMode: process.env.NODE_ENV !== 'development',
fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,
dev: process.env.NODE_ENV === 'development',
requestHeaders: params.request.headers,
requestProtocol: 'https',
getPrerenderManifest: ()=>{
return {
version: -1,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: (0, _getedgepreviewprops.getEdgePreviewProps)()
};
}
});
}
// if we're in an edge runtime sandbox, we should use the waitUntil
// that we receive from the enclosing NextServer
const outerWaitUntil = params.request.waitUntil ?? ((_getBuiltinRequestContext = (0, _builtinrequestcontext.getBuiltinRequestContext)()) == null ? void 0 : _getBuiltinRequestContext.waitUntil);
const event = new _fetchevent.NextFetchEvent({
request,
page: params.page,
context: outerWaitUntil ? {
waitUntil: outerWaitUntil
} : undefined
});
let response;
let cookiesFromResponse;
response = await propagator(request, ()=>{
// we only care to make async storage available for middleware
const isMiddleware = params.page === '/middleware' || params.page === '/src/middleware';
if (isMiddleware) {
// if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),
// so we have to inject it via DefinePlugin.
// in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).
const waitUntil = event.waitUntil.bind(event);
const closeController = new _webonclose.CloseController();
return (0, _tracer.getTracer)().trace(_constants.MiddlewareSpan.execute, {
spanName: `middleware ${request.method} ${request.nextUrl.pathname}`,
attributes: {
'http.target': request.nextUrl.pathname,
'http.method': request.method
}
}, async ()=>{
try {
var _params_request_nextConfig_experimental, _params_request_nextConfig, _params_request_nextConfig_experimental1, _params_request_nextConfig1;
const onUpdateCookies = (cookies)=>{
cookiesFromResponse = cookies;
};
const previewProps = (0, _getedgepreviewprops.getEdgePreviewProps)();
const page = '/' // Fake Work
;
const fallbackRouteParams = null;
const implicitTags = await (0, _implicittags.getImplicitTags)(page, request.nextUrl, fallbackRouteParams);
const requestStore = (0, _requeststore.createRequestStoreForAPI)(request, request.nextUrl, implicitTags, onUpdateCookies, previewProps);
const workStore = (0, _workstore.createWorkStore)({
page,
fallbackRouteParams,
renderOpts: {
cacheLifeProfiles: (_params_request_nextConfig = params.request.nextConfig) == null ? void 0 : (_params_request_nextConfig_experimental = _params_request_nextConfig.experimental) == null ? void 0 : _params_request_nextConfig_experimental.cacheLife,
experimental: {
isRoutePPREnabled: false,
dynamicIO: false,
authInterrupts: !!((_params_request_nextConfig1 = params.request.nextConfig) == null ? void 0 : (_params_request_nextConfig_experimental1 = _params_request_nextConfig1.experimental) == null ? void 0 : _params_request_nextConfig_experimental1.authInterrupts)
},
supportsDynamicResponse: true,
waitUntil,
onClose: closeController.onClose.bind(closeController),
onAfterTaskError: undefined
},
requestEndedState: {
ended: false
},
isPrefetchRequest: request.headers.has(_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER),
buildId: buildId ?? '',
previouslyRevalidatedTags: []
});
return await _workasyncstorageexternal.workAsyncStorage.run(workStore, ()=>_workunitasyncstorageexternal.workUnitAsyncStorage.run(requestStore, params.handler, request, event));
} finally{
// middleware cannot stream, so we can consider the response closed
// as soon as the handler returns.
// we can delay running it until a bit later --
// if it's needed, we'll have a `waitUntil` lock anyway.
setTimeout(()=>{
closeController.dispatchClose();
}, 0);
}
});
}
return params.handler(request, event);
});
// check if response is a Response object
if (response && !(response instanceof Response)) {
throw Object.defineProperty(new TypeError('Expected an instance of Response to be returned'), "__NEXT_ERROR_CODE", {
value: "E567",
enumerable: false,
configurable: true
});
}
if (response && cookiesFromResponse) {
response.headers.set('set-cookie', cookiesFromResponse);
}
/**
* For rewrites we must always include the locale in the final pathname
* so we re-create the NextURL forcing it to include it when the it is
* an internal rewrite. Also we make sure the outgoing rewrite URL is
* a data URL if the request was a data request.
*/ const rewrite = response == null ? void 0 : response.headers.get('x-middleware-rewrite');
if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {
const destination = new _nexturl.NextURL(rewrite, {
forceLocale: true,
headers: params.request.headers,
nextConfig: params.request.nextConfig
});
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {
if (destination.host === request.nextUrl.host) {
destination.buildId = buildId || destination.buildId;
response.headers.set('x-middleware-rewrite', String(destination));
}
}
/**
* When the request is a data request we must show if there was a rewrite
* with an internal header so the client knows which component to load
* from the data request.
*/ const { url: relativeDestination, isRelative } = (0, _relativizeurl.parseRelativeURL)(destination.toString(), requestURL.toString());
if (!isEdgeRendering && isNextDataRequest && // if the rewrite is external and external rewrite
// resolving config is enabled don't add this header
// so the upstream app can set it instead
!(process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE && relativeDestination.match(/http(s)?:\/\//))) {
response.headers.set('x-nextjs-rewrite', relativeDestination);
}
// If this is an RSC request, and the pathname or search has changed, and
// this isn't an external rewrite, we need to set the rewritten pathname and
// query headers.
if (isRSCRequest && isRelative) {
if (requestURL.pathname !== destination.pathname) {
response.headers.set(_approuterheaders.NEXT_REWRITTEN_PATH_HEADER, destination.pathname);
}
if (requestURL.search !== destination.search) {
response.headers.set(_approuterheaders.NEXT_REWRITTEN_QUERY_HEADER, // remove the leading ? from the search string
destination.search.slice(1));
}
}
}
/**
* For redirects we will not include the locale in case when it is the
* default and we must also make sure the outgoing URL is a data one if
* the incoming request was a data request.
*/ const redirect = response == null ? void 0 : response.headers.get('Location');
if (response && redirect && !isEdgeRendering) {
const redirectURL = new _nexturl.NextURL(redirect, {
forceLocale: false,
headers: params.request.headers,
nextConfig: params.request.nextConfig
});
/**
* Responses created from redirects have immutable headers so we have
* to clone the response to be able to modify it.
*/ response = new Response(response.body, response);
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
if (redirectURL.host === requestURL.host) {
redirectURL.buildId = buildId || redirectURL.buildId;
response.headers.set('Location', redirectURL.toString());
}
}
/**
* When the request is a data request we can't use the location header as
* it may end up with CORS error. Instead we map to an internal header so
* the client knows the destination.
*/ if (isNextDataRequest) {
response.headers.delete('Location');
response.headers.set('x-nextjs-redirect', (0, _relativizeurl.getRelativeURL)(redirectURL.toString(), requestURL.toString()));
}
}
const finalResponse = response ? response : _response.NextResponse.next();
// Flight headers are not overridable / removable so they are applied at the end.
const middlewareOverrideHeaders = finalResponse.headers.get('x-middleware-override-headers');
const overwrittenHeaders = [];
if (middlewareOverrideHeaders) {
for (const [key, value] of flightHeaders){
finalResponse.headers.set(`x-middleware-request-${key}`, value);
overwrittenHeaders.push(key);
}
if (overwrittenHeaders.length > 0) {
finalResponse.headers.set('x-middleware-override-headers', middlewareOverrideHeaders + ',' + overwrittenHeaders.join(','));
}
}
return {
response: finalResponse,
waitUntil: (0, _fetchevent.getWaitUntilPromiseFromEvent)(event) ?? Promise.resolve(),
fetchMetrics: request.fetchMetrics
};
}
//# sourceMappingURL=adapter.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
import type { AppRouteRouteModule } from '../route-modules/app-route/module';
import './globals';
import { type AdapterOptions } from './adapter';
import type { NextConfigComplete } from '../config-shared';
export interface WrapOptions {
nextConfig: NextConfigComplete;
}
/**
* EdgeRouteModuleWrapper is a wrapper around a route module.
*
* Note that this class should only be used in the edge runtime.
*/
export declare class EdgeRouteModuleWrapper {
private readonly routeModule;
private readonly nextConfig;
private readonly matcher;
/**
* The constructor is wrapped with private to ensure that it can only be
* constructed by the static wrap method.
*
* @param routeModule the route module to wrap
*/
private constructor();
/**
* This will wrap a module with the EdgeModuleWrapper and return a function
* that can be used as a handler for the edge runtime.
*
* @param module the module to wrap
* @param options any options that should be passed to the adapter and
* override the ones passed from the runtime
* @returns a function that can be used as a handler for the edge runtime
*/
static wrap(routeModule: AppRouteRouteModule, options: WrapOptions): (opts: AdapterOptions) => Promise<import("./types").FetchEventResult>;
private handler;
}

View File

@@ -0,0 +1,120 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "EdgeRouteModuleWrapper", {
enumerable: true,
get: function() {
return EdgeRouteModuleWrapper;
}
});
require("./globals");
const _adapter = require("./adapter");
const _incrementalcache = require("../lib/incremental-cache");
const _routematcher = require("../route-matchers/route-matcher");
const _internaledgewaituntil = require("./internal-edge-wait-until");
const _serverutils = require("../server-utils");
const _querystring = require("../../shared/lib/router/utils/querystring");
const _webonclose = require("./web-on-close");
const _getedgepreviewprops = require("./get-edge-preview-props");
class EdgeRouteModuleWrapper {
/**
* The constructor is wrapped with private to ensure that it can only be
* constructed by the static wrap method.
*
* @param routeModule the route module to wrap
*/ constructor(routeModule, nextConfig){
this.routeModule = routeModule;
this.nextConfig = nextConfig;
// TODO: (wyattjoh) possibly allow the module to define it's own matcher
this.matcher = new _routematcher.RouteMatcher(routeModule.definition);
}
/**
* This will wrap a module with the EdgeModuleWrapper and return a function
* that can be used as a handler for the edge runtime.
*
* @param module the module to wrap
* @param options any options that should be passed to the adapter and
* override the ones passed from the runtime
* @returns a function that can be used as a handler for the edge runtime
*/ static wrap(routeModule, options) {
// Create the module wrapper.
const wrapper = new EdgeRouteModuleWrapper(routeModule, options.nextConfig);
// Return the wrapping function.
return (opts)=>{
return (0, _adapter.adapter)({
...opts,
IncrementalCache: _incrementalcache.IncrementalCache,
// Bind the handler method to the wrapper so it still has context.
handler: wrapper.handler.bind(wrapper)
});
};
}
async handler(request, evt) {
const utils = (0, _serverutils.getUtils)({
pageIsDynamic: this.matcher.isDynamic,
page: this.matcher.definition.pathname,
basePath: request.nextUrl.basePath,
// We don't need the `handleRewrite` util, so can just pass an empty object
rewrites: {},
// only used for rewrites, so setting an arbitrary default value here
caseSensitive: false
});
const { params } = utils.normalizeDynamicRouteParams((0, _querystring.searchParamsToUrlQuery)(request.nextUrl.searchParams), false);
const waitUntil = evt.waitUntil.bind(evt);
const closeController = new _webonclose.CloseController();
const previewProps = (0, _getedgepreviewprops.getEdgePreviewProps)();
// Create the context for the handler. This contains the params from the
// match (if any).
const context = {
params,
prerenderManifest: {
version: 4,
routes: {},
dynamicRoutes: {},
preview: previewProps,
notFoundRoutes: []
},
renderOpts: {
supportsDynamicResponse: true,
waitUntil,
onClose: closeController.onClose.bind(closeController),
onAfterTaskError: undefined,
experimental: {
dynamicIO: !!process.env.__NEXT_DYNAMIC_IO,
authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
},
cacheLifeProfiles: this.nextConfig.experimental.cacheLife
},
sharedContext: {
buildId: ''
}
};
// Get the response from the handler.
let res = await this.routeModule.handle(request, context);
const waitUntilPromises = [
(0, _internaledgewaituntil.internal_getCurrentFunctionWaitUntil)()
];
if (context.renderOpts.pendingWaitUntil) {
waitUntilPromises.push(context.renderOpts.pendingWaitUntil);
}
evt.waitUntil(Promise.all(waitUntilPromises));
if (!res.body) {
// we can delay running it until a bit later --
// if it's needed, we'll have a `waitUntil` lock anyway.
setTimeout(()=>closeController.dispatchClose(), 0);
} else {
// NOTE: if this is a streaming response, onClose may be called later,
// so we can't rely on `closeController.listeners` -- it might be 0 at this point.
const trackedBody = (0, _webonclose.trackStreamConsumed)(res.body, ()=>closeController.dispatchClose());
res = new Response(trackedBody, {
status: res.status,
statusText: res.statusText,
headers: res.headers
});
}
return res;
}
}
//# sourceMappingURL=edge-route-module-wrapper.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
export declare class PageSignatureError extends Error {
constructor({ page }: {
page: string;
});
}
export declare class RemovedPageError extends Error {
constructor();
}
export declare class RemovedUAError extends Error {
constructor();
}

View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
PageSignatureError: null,
RemovedPageError: null,
RemovedUAError: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
PageSignatureError: function() {
return PageSignatureError;
},
RemovedPageError: function() {
return RemovedPageError;
},
RemovedUAError: function() {
return RemovedUAError;
}
});
class PageSignatureError extends Error {
constructor({ page }){
super(`The middleware "${page}" accepts an async API directly with the form:
export function middleware(request, event) {
return NextResponse.redirect('/new-location')
}
Read more: https://nextjs.org/docs/messages/middleware-new-signature
`);
}
}
class RemovedPageError extends Error {
constructor(){
super(`The request.page has been deprecated in favour of \`URLPattern\`.
Read more: https://nextjs.org/docs/messages/middleware-request-page
`);
}
}
class RemovedUAError extends Error {
constructor(){
super(`The request.ua has been removed in favour of \`userAgent\` function.
Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
`);
}
}
//# sourceMappingURL=error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/error.ts"],"sourcesContent":["export class PageSignatureError extends Error {\n constructor({ page }: { page: string }) {\n super(`The middleware \"${page}\" accepts an async API directly with the form:\n \n export function middleware(request, event) {\n return NextResponse.redirect('/new-location')\n }\n \n Read more: https://nextjs.org/docs/messages/middleware-new-signature\n `)\n }\n}\n\nexport class RemovedPageError extends Error {\n constructor() {\n super(`The request.page has been deprecated in favour of \\`URLPattern\\`.\n Read more: https://nextjs.org/docs/messages/middleware-request-page\n `)\n }\n}\n\nexport class RemovedUAError extends Error {\n constructor() {\n super(`The request.ua has been removed in favour of \\`userAgent\\` function.\n Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n `)\n }\n}\n"],"names":["PageSignatureError","RemovedPageError","RemovedUAError","Error","constructor","page"],"mappings":";;;;;;;;;;;;;;;;IAAaA,kBAAkB;eAAlBA;;IAaAC,gBAAgB;eAAhBA;;IAQAC,cAAc;eAAdA;;;AArBN,MAAMF,2BAA2BG;IACtCC,YAAY,EAAEC,IAAI,EAAoB,CAAE;QACtC,KAAK,CAAC,CAAC,gBAAgB,EAAEA,KAAK;;;;;;;EAOhC,CAAC;IACD;AACF;AAEO,MAAMJ,yBAAyBE;IACpCC,aAAc;QACZ,KAAK,CAAC,CAAC;;EAET,CAAC;IACD;AACF;AAEO,MAAMF,uBAAuBC;IAClCC,aAAc;QACZ,KAAK,CAAC,CAAC;;EAET,CAAC;IACD;AACF"}

View File

@@ -0,0 +1,8 @@
export { ImageResponse } from '../spec-extension/image-response';
export { NextRequest } from '../spec-extension/request';
export { NextResponse } from '../spec-extension/response';
export { userAgent, userAgentFromString } from '../spec-extension/user-agent';
export { URLPattern } from '../spec-extension/url-pattern';
export { after } from '../../after';
export { connection } from '../../request/connection';
export { unstable_rootParams } from '../../request/root-params';

View File

@@ -0,0 +1,61 @@
// Alias index file of next/server for edge runtime for tree-shaking purpose
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ImageResponse: null,
NextRequest: null,
NextResponse: null,
URLPattern: null,
after: null,
connection: null,
unstable_rootParams: null,
userAgent: null,
userAgentFromString: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ImageResponse: function() {
return _imageresponse.ImageResponse;
},
NextRequest: function() {
return _request.NextRequest;
},
NextResponse: function() {
return _response.NextResponse;
},
URLPattern: function() {
return _urlpattern.URLPattern;
},
after: function() {
return _after.after;
},
connection: function() {
return _connection.connection;
},
unstable_rootParams: function() {
return _rootparams.unstable_rootParams;
},
userAgent: function() {
return _useragent.userAgent;
},
userAgentFromString: function() {
return _useragent.userAgentFromString;
}
});
const _imageresponse = require("../spec-extension/image-response");
const _request = require("../spec-extension/request");
const _response = require("../spec-extension/response");
const _useragent = require("../spec-extension/user-agent");
const _urlpattern = require("../spec-extension/url-pattern");
const _after = require("../../after");
const _connection = require("../../request/connection");
const _rootparams = require("../../request/root-params");
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/index.ts"],"sourcesContent":["// Alias index file of next/server for edge runtime for tree-shaking purpose\n\nexport { ImageResponse } from '../spec-extension/image-response'\nexport { NextRequest } from '../spec-extension/request'\nexport { NextResponse } from '../spec-extension/response'\nexport { userAgent, userAgentFromString } from '../spec-extension/user-agent'\nexport { URLPattern } from '../spec-extension/url-pattern'\nexport { after } from '../../after'\nexport { connection } from '../../request/connection'\nexport { unstable_rootParams } from '../../request/root-params'\n"],"names":["ImageResponse","NextRequest","NextResponse","URLPattern","after","connection","unstable_rootParams","userAgent","userAgentFromString"],"mappings":"AAAA,4EAA4E;;;;;;;;;;;;;;;;;;;;;;;IAEnEA,aAAa;eAAbA,4BAAa;;IACbC,WAAW;eAAXA,oBAAW;;IACXC,YAAY;eAAZA,sBAAY;;IAEZC,UAAU;eAAVA,sBAAU;;IACVC,KAAK;eAALA,YAAK;;IACLC,UAAU;eAAVA,sBAAU;;IACVC,mBAAmB;eAAnBA,+BAAmB;;IAJnBC,SAAS;eAATA,oBAAS;;IAAEC,mBAAmB;eAAnBA,8BAAmB;;;+BAHT;yBACF;0BACC;2BACkB;4BACpB;uBACL;4BACK;4BACS"}

View File

@@ -0,0 +1,10 @@
/**
* In edge runtime, these props directly accessed from environment variables.
* - local: env vars will be injected through edge-runtime as runtime env vars
* - deployment: env vars will be replaced by edge build pipeline
*/
export declare function getEdgePreviewProps(): {
previewModeId: string;
previewModeSigningKey: string;
previewModeEncryptionKey: string;
};

View File

@@ -0,0 +1,23 @@
/**
* In edge runtime, these props directly accessed from environment variables.
* - local: env vars will be injected through edge-runtime as runtime env vars
* - deployment: env vars will be replaced by edge build pipeline
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getEdgePreviewProps", {
enumerable: true,
get: function() {
return getEdgePreviewProps;
}
});
function getEdgePreviewProps() {
return {
previewModeId: process.env.NODE_ENV === 'production' ? process.env.__NEXT_PREVIEW_MODE_ID : 'development-id',
previewModeSigningKey: process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY || '',
previewModeEncryptionKey: process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY || ''
};
}
//# sourceMappingURL=get-edge-preview-props.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/get-edge-preview-props.ts"],"sourcesContent":["/**\n * In edge runtime, these props directly accessed from environment variables.\n * - local: env vars will be injected through edge-runtime as runtime env vars\n * - deployment: env vars will be replaced by edge build pipeline\n */\nexport function getEdgePreviewProps() {\n return {\n previewModeId:\n process.env.NODE_ENV === 'production'\n ? process.env.__NEXT_PREVIEW_MODE_ID!\n : 'development-id',\n previewModeSigningKey: process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY || '',\n previewModeEncryptionKey:\n process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY || '',\n }\n}\n"],"names":["getEdgePreviewProps","previewModeId","process","env","NODE_ENV","__NEXT_PREVIEW_MODE_ID","previewModeSigningKey","__NEXT_PREVIEW_MODE_SIGNING_KEY","previewModeEncryptionKey","__NEXT_PREVIEW_MODE_ENCRYPTION_KEY"],"mappings":"AAAA;;;;CAIC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA;IACd,OAAO;QACLC,eACEC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eACrBF,QAAQC,GAAG,CAACE,sBAAsB,GAClC;QACNC,uBAAuBJ,QAAQC,GAAG,CAACI,+BAA+B,IAAI;QACtEC,0BACEN,QAAQC,GAAG,CAACM,kCAAkC,IAAI;IACtD;AACF"}

View File

@@ -0,0 +1,4 @@
import type { InstrumentationModule, InstrumentationOnRequestError } from '../instrumentation/types';
export declare function getEdgeInstrumentationModule(): Promise<InstrumentationModule | undefined>;
export declare function edgeInstrumentationOnRequestError(...args: Parameters<InstrumentationOnRequestError>): Promise<void>;
export declare function ensureInstrumentationRegistered(): Promise<void>;

View File

@@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
edgeInstrumentationOnRequestError: null,
ensureInstrumentationRegistered: null,
getEdgeInstrumentationModule: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
edgeInstrumentationOnRequestError: function() {
return edgeInstrumentationOnRequestError;
},
ensureInstrumentationRegistered: function() {
return ensureInstrumentationRegistered;
},
getEdgeInstrumentationModule: function() {
return getEdgeInstrumentationModule;
}
});
async function getEdgeInstrumentationModule() {
const instrumentation = '_ENTRIES' in globalThis && _ENTRIES.middleware_instrumentation && await _ENTRIES.middleware_instrumentation;
return instrumentation;
}
let instrumentationModulePromise = null;
async function registerInstrumentation() {
// Ensure registerInstrumentation is not called in production build
if (process.env.NEXT_PHASE === 'phase-production-build') return;
if (!instrumentationModulePromise) {
instrumentationModulePromise = getEdgeInstrumentationModule();
}
const instrumentation = await instrumentationModulePromise;
if (instrumentation == null ? void 0 : instrumentation.register) {
try {
await instrumentation.register();
} catch (err) {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`;
throw err;
}
}
}
async function edgeInstrumentationOnRequestError(...args) {
const instrumentation = await getEdgeInstrumentationModule();
try {
var _instrumentation_onRequestError;
await (instrumentation == null ? void 0 : (_instrumentation_onRequestError = instrumentation.onRequestError) == null ? void 0 : _instrumentation_onRequestError.call(instrumentation, ...args));
} catch (err) {
// Log the soft error and continue, since the original error has already been thrown
console.error('Error in instrumentation.onRequestError:', err);
}
}
let registerInstrumentationPromise = null;
function ensureInstrumentationRegistered() {
if (!registerInstrumentationPromise) {
registerInstrumentationPromise = registerInstrumentation();
}
return registerInstrumentationPromise;
}
function getUnsupportedModuleErrorMessage(module1) {
// warning: if you change these messages, you must adjust how react-dev-overlay's middleware detects modules not found
return `The edge runtime does not support Node.js '${module1}' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`;
}
function __import_unsupported(moduleName) {
const proxy = new Proxy(function() {}, {
get (_obj, prop) {
if (prop === 'then') {
return {};
}
throw Object.defineProperty(new Error(getUnsupportedModuleErrorMessage(moduleName)), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
},
construct () {
throw Object.defineProperty(new Error(getUnsupportedModuleErrorMessage(moduleName)), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
},
apply (_target, _this, args) {
if (typeof args[0] === 'function') {
return args[0](proxy);
}
throw Object.defineProperty(new Error(getUnsupportedModuleErrorMessage(moduleName)), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
});
return new Proxy({}, {
get: ()=>proxy
});
}
function enhanceGlobals() {
if (process.env.NEXT_RUNTIME !== 'edge') {
return;
}
// The condition is true when the "process" module is provided
if (process !== global.process) {
// prefer local process but global.process has correct "env"
process.env = global.process.env;
global.process = process;
}
// to allow building code that import but does not use node.js modules,
// webpack will expect this function to exist in global scope
Object.defineProperty(globalThis, '__import_unsupported', {
value: __import_unsupported,
enumerable: false,
configurable: false
});
// Eagerly fire instrumentation hook to make the startup faster.
void ensureInstrumentationRegistered();
}
enhanceGlobals();
//# sourceMappingURL=globals.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
/**
* List of valid HTTP methods that can be implemented by Next.js's Custom App
* Routes.
*/
export declare const HTTP_METHODS: readonly ["GET", "HEAD", "OPTIONS", "POST", "PUT", "DELETE", "PATCH"];
/**
* A type representing the valid HTTP methods that can be implemented by
* Next.js's Custom App Routes.
*/
export type HTTP_METHOD = (typeof HTTP_METHODS)[number];
/**
* Checks to see if the passed string is an HTTP method. Note that this is case
* sensitive.
*
* @param maybeMethod the string that may be an HTTP method
* @returns true if the string is an HTTP method
*/
export declare function isHTTPMethod(maybeMethod: string): maybeMethod is HTTP_METHOD;

View File

@@ -0,0 +1,39 @@
/**
* List of valid HTTP methods that can be implemented by Next.js's Custom App
* Routes.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
HTTP_METHODS: null,
isHTTPMethod: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
HTTP_METHODS: function() {
return HTTP_METHODS;
},
isHTTPMethod: function() {
return isHTTPMethod;
}
});
const HTTP_METHODS = [
'GET',
'HEAD',
'OPTIONS',
'POST',
'PUT',
'DELETE',
'PATCH'
];
function isHTTPMethod(maybeMethod) {
return HTTP_METHODS.includes(maybeMethod);
}
//# sourceMappingURL=http.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/http.ts"],"sourcesContent":["/**\n * List of valid HTTP methods that can be implemented by Next.js's Custom App\n * Routes.\n */\nexport const HTTP_METHODS = [\n 'GET',\n 'HEAD',\n 'OPTIONS',\n 'POST',\n 'PUT',\n 'DELETE',\n 'PATCH',\n] as const\n\n/**\n * A type representing the valid HTTP methods that can be implemented by\n * Next.js's Custom App Routes.\n */\nexport type HTTP_METHOD = (typeof HTTP_METHODS)[number]\n\n/**\n * Checks to see if the passed string is an HTTP method. Note that this is case\n * sensitive.\n *\n * @param maybeMethod the string that may be an HTTP method\n * @returns true if the string is an HTTP method\n */\nexport function isHTTPMethod(maybeMethod: string): maybeMethod is HTTP_METHOD {\n return HTTP_METHODS.includes(maybeMethod as HTTP_METHOD)\n}\n"],"names":["HTTP_METHODS","isHTTPMethod","maybeMethod","includes"],"mappings":"AAAA;;;CAGC;;;;;;;;;;;;;;;IACYA,YAAY;eAAZA;;IAuBGC,YAAY;eAAZA;;;AAvBT,MAAMD,eAAe;IAC1B;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAeM,SAASC,aAAaC,WAAmB;IAC9C,OAAOF,aAAaG,QAAQ,CAACD;AAC/B"}

View File

@@ -0,0 +1,2 @@
export declare function internal_getCurrentFunctionWaitUntil(): Promise<void> | null;
export declare function internal_runWithWaitUntil<T>(fn: () => T): T;

View File

@@ -0,0 +1,64 @@
// An internal module to expose the "waitUntil" API to Edge SSR and Edge Route Handler functions.
// This is highly experimental and subject to change.
// We still need a global key to bypass Webpack's layering of modules.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
internal_getCurrentFunctionWaitUntil: null,
internal_runWithWaitUntil: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
internal_getCurrentFunctionWaitUntil: function() {
return internal_getCurrentFunctionWaitUntil;
},
internal_runWithWaitUntil: function() {
return internal_runWithWaitUntil;
}
});
const GLOBAL_KEY = Symbol.for('__next_internal_waitUntil__');
const state = // @ts-ignore
globalThis[GLOBAL_KEY] || // @ts-ignore
(globalThis[GLOBAL_KEY] = {
waitUntilCounter: 0,
waitUntilResolve: undefined,
waitUntilPromise: null
});
// No matter how many concurrent requests are being handled, we want to make sure
// that the final promise is only resolved once all of the waitUntil promises have
// settled.
function resolveOnePromise() {
state.waitUntilCounter--;
if (state.waitUntilCounter === 0) {
state.waitUntilResolve();
state.waitUntilPromise = null;
}
}
function internal_getCurrentFunctionWaitUntil() {
return state.waitUntilPromise;
}
function internal_runWithWaitUntil(fn) {
const result = fn();
if (result && typeof result === 'object' && 'then' in result && 'finally' in result && typeof result.then === 'function' && typeof result.finally === 'function') {
if (!state.waitUntilCounter) {
// Create the promise for the next batch of waitUntil calls.
state.waitUntilPromise = new Promise((resolve)=>{
state.waitUntilResolve = resolve;
});
}
state.waitUntilCounter++;
return result.finally(()=>{
resolveOnePromise();
});
}
return result;
}
//# sourceMappingURL=internal-edge-wait-until.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/internal-edge-wait-until.ts"],"sourcesContent":["// An internal module to expose the \"waitUntil\" API to Edge SSR and Edge Route Handler functions.\n// This is highly experimental and subject to change.\n\n// We still need a global key to bypass Webpack's layering of modules.\nconst GLOBAL_KEY = Symbol.for('__next_internal_waitUntil__')\n\nconst state: {\n waitUntilCounter: number\n waitUntilResolve: () => void\n waitUntilPromise: Promise<void> | null\n} =\n // @ts-ignore\n globalThis[GLOBAL_KEY] ||\n // @ts-ignore\n (globalThis[GLOBAL_KEY] = {\n waitUntilCounter: 0,\n waitUntilResolve: undefined,\n waitUntilPromise: null,\n })\n\n// No matter how many concurrent requests are being handled, we want to make sure\n// that the final promise is only resolved once all of the waitUntil promises have\n// settled.\nfunction resolveOnePromise() {\n state.waitUntilCounter--\n if (state.waitUntilCounter === 0) {\n state.waitUntilResolve()\n state.waitUntilPromise = null\n }\n}\n\nexport function internal_getCurrentFunctionWaitUntil() {\n return state.waitUntilPromise\n}\n\nexport function internal_runWithWaitUntil<T>(fn: () => T): T {\n const result = fn()\n if (\n result &&\n typeof result === 'object' &&\n 'then' in result &&\n 'finally' in result &&\n typeof result.then === 'function' &&\n typeof result.finally === 'function'\n ) {\n if (!state.waitUntilCounter) {\n // Create the promise for the next batch of waitUntil calls.\n state.waitUntilPromise = new Promise<void>((resolve) => {\n state.waitUntilResolve = resolve\n })\n }\n state.waitUntilCounter++\n return result.finally(() => {\n resolveOnePromise()\n })\n }\n\n return result\n}\n"],"names":["internal_getCurrentFunctionWaitUntil","internal_runWithWaitUntil","GLOBAL_KEY","Symbol","for","state","globalThis","waitUntilCounter","waitUntilResolve","undefined","waitUntilPromise","resolveOnePromise","fn","result","then","finally","Promise","resolve"],"mappings":"AAAA,iGAAiG;AACjG,qDAAqD;AAErD,sEAAsE;;;;;;;;;;;;;;;;IA4BtDA,oCAAoC;eAApCA;;IAIAC,yBAAyB;eAAzBA;;;AA/BhB,MAAMC,aAAaC,OAAOC,GAAG,CAAC;AAE9B,MAAMC,QAKJ,aAAa;AACbC,UAAU,CAACJ,WAAW,IACtB,aAAa;AACZI,CAAAA,UAAU,CAACJ,WAAW,GAAG;IACxBK,kBAAkB;IAClBC,kBAAkBC;IAClBC,kBAAkB;AACpB,CAAA;AAEF,iFAAiF;AACjF,kFAAkF;AAClF,WAAW;AACX,SAASC;IACPN,MAAME,gBAAgB;IACtB,IAAIF,MAAME,gBAAgB,KAAK,GAAG;QAChCF,MAAMG,gBAAgB;QACtBH,MAAMK,gBAAgB,GAAG;IAC3B;AACF;AAEO,SAASV;IACd,OAAOK,MAAMK,gBAAgB;AAC/B;AAEO,SAAST,0BAA6BW,EAAW;IACtD,MAAMC,SAASD;IACf,IACEC,UACA,OAAOA,WAAW,YAClB,UAAUA,UACV,aAAaA,UACb,OAAOA,OAAOC,IAAI,KAAK,cACvB,OAAOD,OAAOE,OAAO,KAAK,YAC1B;QACA,IAAI,CAACV,MAAME,gBAAgB,EAAE;YAC3B,4DAA4D;YAC5DF,MAAMK,gBAAgB,GAAG,IAAIM,QAAc,CAACC;gBAC1CZ,MAAMG,gBAAgB,GAAGS;YAC3B;QACF;QACAZ,MAAME,gBAAgB;QACtB,OAAOM,OAAOE,OAAO,CAAC;YACpBJ;QACF;IACF;IAEA,OAAOE;AACT"}

View File

@@ -0,0 +1,57 @@
import type { OutgoingHttpHeaders } from 'http';
import type { DomainLocale, I18NConfig } from '../config-shared';
import type { I18NProvider } from '../lib/i18n-provider';
interface Options {
base?: string | URL;
headers?: OutgoingHttpHeaders;
forceLocale?: boolean;
nextConfig?: {
basePath?: string;
i18n?: I18NConfig | null;
trailingSlash?: boolean;
};
i18nProvider?: I18NProvider;
}
declare const Internal: unique symbol;
export declare class NextURL {
private [Internal];
constructor(input: string | URL, base?: string | URL, opts?: Options);
constructor(input: string | URL, opts?: Options);
private analyze;
private formatPathname;
private formatSearch;
get buildId(): string | undefined;
set buildId(buildId: string | undefined);
get locale(): string;
set locale(locale: string);
get defaultLocale(): string | undefined;
get domainLocale(): DomainLocale | undefined;
get searchParams(): URLSearchParams;
get host(): string;
set host(value: string);
get hostname(): string;
set hostname(value: string);
get port(): string;
set port(value: string);
get protocol(): string;
set protocol(value: string);
get href(): string;
set href(url: string);
get origin(): string;
get pathname(): string;
set pathname(value: string);
get hash(): string;
set hash(value: string);
get search(): string;
set search(value: string);
get password(): string;
set password(value: string);
get username(): string;
set username(value: string);
get basePath(): string;
set basePath(value: string);
toString(): string;
toJSON(): string;
clone(): NextURL;
}
export {};

View File

@@ -0,0 +1,195 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "NextURL", {
enumerable: true,
get: function() {
return NextURL;
}
});
const _detectdomainlocale = require("../../shared/lib/i18n/detect-domain-locale");
const _formatnextpathnameinfo = require("../../shared/lib/router/utils/format-next-pathname-info");
const _gethostname = require("../../shared/lib/get-hostname");
const _getnextpathnameinfo = require("../../shared/lib/router/utils/get-next-pathname-info");
const REGEX_LOCALHOST_HOSTNAME = /(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;
function parseURL(url, base) {
return new URL(String(url).replace(REGEX_LOCALHOST_HOSTNAME, 'localhost'), base && String(base).replace(REGEX_LOCALHOST_HOSTNAME, 'localhost'));
}
const Internal = Symbol('NextURLInternal');
class NextURL {
constructor(input, baseOrOpts, opts){
let base;
let options;
if (typeof baseOrOpts === 'object' && 'pathname' in baseOrOpts || typeof baseOrOpts === 'string') {
base = baseOrOpts;
options = opts || {};
} else {
options = opts || baseOrOpts || {};
}
this[Internal] = {
url: parseURL(input, base ?? options.base),
options: options,
basePath: ''
};
this.analyze();
}
analyze() {
var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig, _this_Internal_domainLocale, _this_Internal_options_nextConfig_i18n1, _this_Internal_options_nextConfig1;
const info = (0, _getnextpathnameinfo.getNextPathnameInfo)(this[Internal].url.pathname, {
nextConfig: this[Internal].options.nextConfig,
parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,
i18nProvider: this[Internal].options.i18nProvider
});
const hostname = (0, _gethostname.getHostname)(this[Internal].url, this[Internal].options.headers);
this[Internal].domainLocale = this[Internal].options.i18nProvider ? this[Internal].options.i18nProvider.detectDomainLocale(hostname) : (0, _detectdomainlocale.detectDomainLocale)((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.domains, hostname);
const defaultLocale = ((_this_Internal_domainLocale = this[Internal].domainLocale) == null ? void 0 : _this_Internal_domainLocale.defaultLocale) || ((_this_Internal_options_nextConfig1 = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n1 = _this_Internal_options_nextConfig1.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n1.defaultLocale);
this[Internal].url.pathname = info.pathname;
this[Internal].defaultLocale = defaultLocale;
this[Internal].basePath = info.basePath ?? '';
this[Internal].buildId = info.buildId;
this[Internal].locale = info.locale ?? defaultLocale;
this[Internal].trailingSlash = info.trailingSlash;
}
formatPathname() {
return (0, _formatnextpathnameinfo.formatNextPathnameInfo)({
basePath: this[Internal].basePath,
buildId: this[Internal].buildId,
defaultLocale: !this[Internal].options.forceLocale ? this[Internal].defaultLocale : undefined,
locale: this[Internal].locale,
pathname: this[Internal].url.pathname,
trailingSlash: this[Internal].trailingSlash
});
}
formatSearch() {
return this[Internal].url.search;
}
get buildId() {
return this[Internal].buildId;
}
set buildId(buildId) {
this[Internal].buildId = buildId;
}
get locale() {
return this[Internal].locale ?? '';
}
set locale(locale) {
var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig;
if (!this[Internal].locale || !((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.locales.includes(locale))) {
throw Object.defineProperty(new TypeError(`The NextURL configuration includes no locale "${locale}"`), "__NEXT_ERROR_CODE", {
value: "E597",
enumerable: false,
configurable: true
});
}
this[Internal].locale = locale;
}
get defaultLocale() {
return this[Internal].defaultLocale;
}
get domainLocale() {
return this[Internal].domainLocale;
}
get searchParams() {
return this[Internal].url.searchParams;
}
get host() {
return this[Internal].url.host;
}
set host(value) {
this[Internal].url.host = value;
}
get hostname() {
return this[Internal].url.hostname;
}
set hostname(value) {
this[Internal].url.hostname = value;
}
get port() {
return this[Internal].url.port;
}
set port(value) {
this[Internal].url.port = value;
}
get protocol() {
return this[Internal].url.protocol;
}
set protocol(value) {
this[Internal].url.protocol = value;
}
get href() {
const pathname = this.formatPathname();
const search = this.formatSearch();
return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`;
}
set href(url) {
this[Internal].url = parseURL(url);
this.analyze();
}
get origin() {
return this[Internal].url.origin;
}
get pathname() {
return this[Internal].url.pathname;
}
set pathname(value) {
this[Internal].url.pathname = value;
}
get hash() {
return this[Internal].url.hash;
}
set hash(value) {
this[Internal].url.hash = value;
}
get search() {
return this[Internal].url.search;
}
set search(value) {
this[Internal].url.search = value;
}
get password() {
return this[Internal].url.password;
}
set password(value) {
this[Internal].url.password = value;
}
get username() {
return this[Internal].url.username;
}
set username(value) {
this[Internal].url.username = value;
}
get basePath() {
return this[Internal].basePath;
}
set basePath(value) {
this[Internal].basePath = value.startsWith('/') ? value : `/${value}`;
}
toString() {
return this.href;
}
toJSON() {
return this.href;
}
[Symbol.for('edge-runtime.inspect.custom')]() {
return {
href: this.href,
origin: this.origin,
protocol: this.protocol,
username: this.username,
password: this.password,
host: this.host,
hostname: this.hostname,
port: this.port,
pathname: this.pathname,
search: this.search,
searchParams: this.searchParams,
hash: this.hash
};
}
clone() {
return new NextURL(String(this), this[Internal].options);
}
}
//# sourceMappingURL=next-url.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,41 @@
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin';
import { AsyncLocalStorage } from 'async_hooks';
import { EdgeRuntime } from 'next/dist/compiled/edge-runtime';
/**
* Same as clearModuleContext but for all module contexts.
*/
export declare function clearAllModuleContexts(): Promise<void>;
/**
* For a given path a context, this function checks if there is any module
* context that contains the path with an older content and, if that's the
* case, removes the context from the cache.
*
* This function also clears all intervals and timeouts created by the
* module context.
*/
export declare function clearModuleContext(path: string): Promise<void>;
export declare const requestStore: AsyncLocalStorage<{
headers: Headers;
}>;
export declare const edgeSandboxNextRequestContext: import("../../after/builtin-request-context").RunnableBuiltinRequestContext;
interface ModuleContextOptions {
moduleName: string;
onError: (err: unknown) => void;
onWarning: (warn: Error) => void;
useCache: boolean;
distDir: string;
edgeFunctionEntry: Pick<EdgeFunctionDefinition, 'assets' | 'wasm' | 'env'>;
}
/**
* For a given module name this function will get a cached module
* context or create it. It will return the module context along
* with a function that allows to run some code from a given
* filepath within the context.
*/
export declare function getModuleContext(options: ModuleContextOptions): Promise<{
evaluateInContext: (filepath: string) => void;
runtime: EdgeRuntime;
paths: Map<string, string>;
warnedEvals: Set<string>;
}>;
export {};

View File

@@ -0,0 +1,458 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
clearAllModuleContexts: null,
clearModuleContext: null,
edgeSandboxNextRequestContext: null,
getModuleContext: null,
requestStore: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
clearAllModuleContexts: function() {
return clearAllModuleContexts;
},
clearModuleContext: function() {
return clearModuleContext;
},
edgeSandboxNextRequestContext: function() {
return edgeSandboxNextRequestContext;
},
getModuleContext: function() {
return getModuleContext;
},
requestStore: function() {
return requestStore;
}
});
const _async_hooks = require("async_hooks");
const _constants = require("../../../shared/lib/constants");
const _edgeruntime = require("next/dist/compiled/edge-runtime");
const _fs = require("fs");
const _utils = require("../utils");
const _pick = require("../../../lib/pick");
const _fetchinlineassets = require("./fetch-inline-assets");
const _vm = require("vm");
const _nodebuffer = /*#__PURE__*/ _interop_require_default(require("node:buffer"));
const _nodeevents = /*#__PURE__*/ _interop_require_default(require("node:events"));
const _nodeassert = /*#__PURE__*/ _interop_require_default(require("node:assert"));
const _nodeutil = /*#__PURE__*/ _interop_require_default(require("node:util"));
const _nodeasync_hooks = /*#__PURE__*/ _interop_require_default(require("node:async_hooks"));
const _resourcemanagers = require("./resource-managers");
const _builtinrequestcontext = require("../../after/builtin-request-context");
const _patcherrorinspect = require("../../patch-error-inspect");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let getServerError;
let decorateServerError;
if (process.env.NODE_ENV === 'development') {
const middleware = require('../../../client/components/react-dev-overlay/server/middleware-webpack');
getServerError = middleware.getServerError;
decorateServerError = require('../../../shared/lib/error-source').decorateServerError;
} else {
getServerError = (error, _)=>error;
decorateServerError = (_, __)=>{};
}
/**
* A Map of cached module contexts indexed by the module name. It allows
* to have a different cache scoped per module name or depending on the
* provided module key on creation.
*/ const moduleContexts = new Map();
const pendingModuleCaches = new Map();
async function clearAllModuleContexts() {
_resourcemanagers.intervalsManager.removeAll();
_resourcemanagers.timeoutsManager.removeAll();
moduleContexts.clear();
pendingModuleCaches.clear();
}
async function clearModuleContext(path) {
_resourcemanagers.intervalsManager.removeAll();
_resourcemanagers.timeoutsManager.removeAll();
const handleContext = (key, cache, context)=>{
if (cache == null ? void 0 : cache.paths.has(path)) {
context.delete(key);
}
};
for (const [key, cache] of moduleContexts){
handleContext(key, cache, moduleContexts);
}
for (const [key, cache] of pendingModuleCaches){
handleContext(key, await cache, pendingModuleCaches);
}
}
async function loadWasm(wasm) {
const modules = {};
await Promise.all(wasm.map(async (binding)=>{
const module1 = await WebAssembly.compile(await _fs.promises.readFile(binding.filePath));
modules[binding.name] = module1;
}));
return modules;
}
function buildEnvironmentVariablesFrom(injectedEnvironments) {
const pairs = Object.keys(process.env).map((key)=>[
key,
process.env[key]
]);
const env = Object.fromEntries(pairs);
for (const key of Object.keys(injectedEnvironments)){
env[key] = injectedEnvironments[key];
}
env.NEXT_RUNTIME = 'edge';
return env;
}
function throwUnsupportedAPIError(name) {
const error = Object.defineProperty(new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`), "__NEXT_ERROR_CODE", {
value: "E97",
enumerable: false,
configurable: true
});
decorateServerError(error, _constants.COMPILER_NAMES.edgeServer);
throw error;
}
function createProcessPolyfill(env) {
const processPolyfill = {
env: buildEnvironmentVariablesFrom(env)
};
const overriddenValue = {};
for (const key of Object.keys(process)){
if (key === 'env') continue;
Object.defineProperty(processPolyfill, key, {
get () {
if (overriddenValue[key] !== undefined) {
return overriddenValue[key];
}
if (typeof process[key] === 'function') {
return ()=>throwUnsupportedAPIError(`process.${key}`);
}
return undefined;
},
set (value) {
overriddenValue[key] = value;
},
enumerable: false
});
}
return processPolyfill;
}
function addStub(context, name) {
Object.defineProperty(context, name, {
get () {
return function() {
throwUnsupportedAPIError(name);
};
},
enumerable: false
});
}
function getDecorateUnhandledError(runtime) {
const EdgeRuntimeError = runtime.evaluate(`Error`);
return (error)=>{
if (error instanceof EdgeRuntimeError) {
decorateServerError(error, _constants.COMPILER_NAMES.edgeServer);
}
};
}
function getDecorateUnhandledRejection(runtime) {
const EdgeRuntimeError = runtime.evaluate(`Error`);
return (rejected)=>{
if (rejected.reason instanceof EdgeRuntimeError) {
decorateServerError(rejected.reason, _constants.COMPILER_NAMES.edgeServer);
}
};
}
const NativeModuleMap = (()=>{
const mods = {
'node:buffer': (0, _pick.pick)(_nodebuffer.default, [
'constants',
'kMaxLength',
'kStringMaxLength',
'Buffer',
'SlowBuffer'
]),
'node:events': (0, _pick.pick)(_nodeevents.default, [
'EventEmitter',
'captureRejectionSymbol',
'defaultMaxListeners',
'errorMonitor',
'listenerCount',
'on',
'once'
]),
'node:async_hooks': (0, _pick.pick)(_nodeasync_hooks.default, [
'AsyncLocalStorage',
'AsyncResource'
]),
'node:assert': (0, _pick.pick)(_nodeassert.default, [
'AssertionError',
'deepEqual',
'deepStrictEqual',
'doesNotMatch',
'doesNotReject',
'doesNotThrow',
'equal',
'fail',
'ifError',
'match',
'notDeepEqual',
'notDeepStrictEqual',
'notEqual',
'notStrictEqual',
'ok',
'rejects',
'strict',
'strictEqual',
'throws'
]),
'node:util': (0, _pick.pick)(_nodeutil.default, [
'_extend',
'callbackify',
'format',
'inherits',
'promisify',
'types'
])
};
return new Map(Object.entries(mods));
})();
const requestStore = new _async_hooks.AsyncLocalStorage();
const edgeSandboxNextRequestContext = (0, _builtinrequestcontext.createLocalRequestContext)();
/**
* Create a module cache specific for the provided parameters. It includes
* a runtime context, require cache and paths cache.
*/ async function createModuleContext(options) {
const warnedEvals = new Set();
const warnedWasmCodegens = new Set();
const { edgeFunctionEntry } = options;
const wasm = await loadWasm(edgeFunctionEntry.wasm ?? []);
const runtime = new _edgeruntime.EdgeRuntime({
codeGeneration: process.env.NODE_ENV !== 'production' ? {
strings: true,
wasm: true
} : undefined,
extend: (context)=>{
context.process = createProcessPolyfill(edgeFunctionEntry.env);
Object.defineProperty(context, 'require', {
enumerable: false,
value: (id)=>{
const value = NativeModuleMap.get(id);
if (!value) {
throw Object.defineProperty(new TypeError('Native module not found: ' + id), "__NEXT_ERROR_CODE", {
value: "E546",
enumerable: false,
configurable: true
});
}
return value;
}
});
if (process.env.NODE_ENV !== 'production') {
context.__next_log_error__ = function(err) {
options.onError(err);
};
}
context.__next_eval__ = function __next_eval__(fn) {
const key = fn.toString();
if (!warnedEvals.has(key)) {
const warning = getServerError(Object.defineProperty(new Error(`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), "__NEXT_ERROR_CODE", {
value: "E149",
enumerable: false,
configurable: true
}), _constants.COMPILER_NAMES.edgeServer);
warning.name = 'DynamicCodeEvaluationWarning';
Error.captureStackTrace(warning, __next_eval__);
warnedEvals.add(key);
options.onWarning(warning);
}
return fn();
};
context.__next_webassembly_compile__ = function __next_webassembly_compile__(fn) {
const key = fn.toString();
if (!warnedWasmCodegens.has(key)) {
const warning = getServerError(Object.defineProperty(new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), "__NEXT_ERROR_CODE", {
value: "E184",
enumerable: false,
configurable: true
}), _constants.COMPILER_NAMES.edgeServer);
warning.name = 'DynamicWasmCodeGenerationWarning';
Error.captureStackTrace(warning, __next_webassembly_compile__);
warnedWasmCodegens.add(key);
options.onWarning(warning);
}
return fn();
};
context.__next_webassembly_instantiate__ = async function __next_webassembly_instantiate__(fn) {
const result = await fn();
// If a buffer is given, WebAssembly.instantiate returns an object
// containing both a module and an instance while it returns only an
// instance if a WASM module is given. Utilize the fact to determine
// if the WASM code generation happens.
//
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code
const instantiatedFromBuffer = result.hasOwnProperty('module');
const key = fn.toString();
if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {
const warning = getServerError(Object.defineProperty(new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), "__NEXT_ERROR_CODE", {
value: "E40",
enumerable: false,
configurable: true
}), _constants.COMPILER_NAMES.edgeServer);
warning.name = 'DynamicWasmCodeGenerationWarning';
Error.captureStackTrace(warning, __next_webassembly_instantiate__);
warnedWasmCodegens.add(key);
options.onWarning(warning);
}
return result;
};
const __fetch = context.fetch;
context.fetch = async (input, init = {})=>{
const callingError = Object.defineProperty(new Error('[internal]'), "__NEXT_ERROR_CODE", {
value: "E5",
enumerable: false,
configurable: true
});
const assetResponse = await (0, _fetchinlineassets.fetchInlineAsset)({
input,
assets: options.edgeFunctionEntry.assets,
distDir: options.distDir,
context
});
if (assetResponse) {
return assetResponse;
}
init.headers = new Headers(init.headers ?? {});
if (!init.headers.has('user-agent')) {
init.headers.set(`user-agent`, `Next.js Middleware`);
}
const response = typeof input === 'object' && 'url' in input ? __fetch(input.url, {
...(0, _pick.pick)(input, [
'method',
'body',
'cache',
'credentials',
'integrity',
'keepalive',
'mode',
'redirect',
'referrer',
'referrerPolicy',
'signal'
]),
...init,
headers: {
...Object.fromEntries(input.headers),
...Object.fromEntries(init.headers)
}
}) : __fetch(String(input), init);
return await response.catch((err)=>{
callingError.message = err.message;
err.stack = callingError.stack;
throw err;
});
};
const __Request = context.Request;
context.Request = class extends __Request {
constructor(input, init){
const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);
(0, _utils.validateURL)(url);
super(url, init);
this.next = init == null ? void 0 : init.next;
}
};
const __redirect = context.Response.redirect.bind(context.Response);
context.Response.redirect = (...args)=>{
(0, _utils.validateURL)(args[0]);
return __redirect(...args);
};
for (const name of _constants.EDGE_UNSUPPORTED_NODE_APIS){
addStub(context, name);
}
Object.assign(context, wasm);
context.performance = performance;
context.AsyncLocalStorage = _async_hooks.AsyncLocalStorage;
// @ts-ignore the timeouts have weird types in the edge runtime
context.setInterval = (...args)=>_resourcemanagers.intervalsManager.add(args);
// @ts-ignore the timeouts have weird types in the edge runtime
context.clearInterval = (interval)=>_resourcemanagers.intervalsManager.remove(interval);
// @ts-ignore the timeouts have weird types in the edge runtime
context.setTimeout = (...args)=>_resourcemanagers.timeoutsManager.add(args);
// @ts-ignore the timeouts have weird types in the edge runtime
context.clearTimeout = (timeout)=>_resourcemanagers.timeoutsManager.remove(timeout);
// Duplicated from packages/next/src/server/after/builtin-request-context.ts
// because we need to use the sandboxed `Symbol.for`, not the one from the outside
const NEXT_REQUEST_CONTEXT_SYMBOL = context.Symbol.for('@next/request-context');
Object.defineProperty(context, NEXT_REQUEST_CONTEXT_SYMBOL, {
enumerable: false,
value: edgeSandboxNextRequestContext
});
return context;
}
});
const decorateUnhandledError = getDecorateUnhandledError(runtime);
runtime.context.addEventListener('error', decorateUnhandledError);
const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime);
runtime.context.addEventListener('unhandledrejection', decorateUnhandledRejection);
(0, _patcherrorinspect.patchErrorInspectEdgeLite)(runtime.context.Error);
// An Error from within the Edge Runtime could also bubble up into the Node.js process.
// For example, uncaught errors are handled in the Node.js runtime.
(0, _patcherrorinspect.patchErrorInspectNodeJS)(runtime.context.Error);
return {
runtime,
paths: new Map(),
warnedEvals: new Set()
};
}
function getModuleContextShared(options) {
let deferredModuleContext = pendingModuleCaches.get(options.moduleName);
if (!deferredModuleContext) {
deferredModuleContext = createModuleContext(options);
pendingModuleCaches.set(options.moduleName, deferredModuleContext);
}
return deferredModuleContext;
}
async function getModuleContext(options) {
let lazyModuleContext;
if (options.useCache) {
lazyModuleContext = moduleContexts.get(options.moduleName) || await getModuleContextShared(options);
}
if (!lazyModuleContext) {
lazyModuleContext = await createModuleContext(options);
moduleContexts.set(options.moduleName, lazyModuleContext);
}
const moduleContext = lazyModuleContext;
const evaluateInContext = (filepath)=>{
if (!moduleContext.paths.has(filepath)) {
const content = (0, _fs.readFileSync)(filepath, 'utf-8');
try {
(0, _vm.runInContext)(content, moduleContext.runtime.context, {
filename: filepath
});
moduleContext.paths.set(filepath, content);
} catch (error) {
if (options.useCache) {
moduleContext == null ? void 0 : moduleContext.paths.delete(filepath);
}
throw error;
}
}
};
return {
...moduleContext,
evaluateInContext
};
}
//# sourceMappingURL=context.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin';
/**
* Short-circuits the `fetch` function
* to return a stream for a given asset, if a user used `new URL("file", import.meta.url)`.
* This allows to embed assets in Edge Runtime.
*/
export declare function fetchInlineAsset(options: {
input: RequestInfo | URL;
distDir: string;
assets: EdgeFunctionDefinition['assets'];
context: {
Response: typeof Response;
ReadableStream: typeof ReadableStream;
};
}): Promise<Response | undefined>;

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "fetchInlineAsset", {
enumerable: true,
get: function() {
return fetchInlineAsset;
}
});
const _fs = require("fs");
const _bodystreams = require("../../body-streams");
const _path = require("path");
async function fetchInlineAsset(options) {
const inputString = String(options.input);
if (!inputString.startsWith('blob:')) {
return;
}
const name = inputString.replace('blob:', '');
const asset = options.assets ? options.assets.find((x)=>x.name === name) : {
name,
filePath: name
};
if (!asset) {
return;
}
const filePath = (0, _path.resolve)(options.distDir, asset.filePath);
const fileIsReadable = await _fs.promises.access(filePath).then(()=>true, ()=>false);
if (fileIsReadable) {
const readStream = (0, _fs.createReadStream)(filePath);
return new options.context.Response((0, _bodystreams.requestToBodyStream)(options.context, Uint8Array, readStream));
}
}
//# sourceMappingURL=fetch-inline-assets.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/sandbox/fetch-inline-assets.ts"],"sourcesContent":["import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'\nimport { createReadStream, promises as fs } from 'fs'\nimport { requestToBodyStream } from '../../body-streams'\nimport { resolve } from 'path'\n\n/**\n * Short-circuits the `fetch` function\n * to return a stream for a given asset, if a user used `new URL(\"file\", import.meta.url)`.\n * This allows to embed assets in Edge Runtime.\n */\nexport async function fetchInlineAsset(options: {\n input: RequestInfo | URL\n distDir: string\n assets: EdgeFunctionDefinition['assets']\n context: { Response: typeof Response; ReadableStream: typeof ReadableStream }\n}): Promise<Response | undefined> {\n const inputString = String(options.input)\n if (!inputString.startsWith('blob:')) {\n return\n }\n\n const name = inputString.replace('blob:', '')\n const asset = options.assets\n ? options.assets.find((x) => x.name === name)\n : {\n name,\n filePath: name,\n }\n if (!asset) {\n return\n }\n\n const filePath = resolve(options.distDir, asset.filePath)\n const fileIsReadable = await fs.access(filePath).then(\n () => true,\n () => false\n )\n\n if (fileIsReadable) {\n const readStream = createReadStream(filePath)\n return new options.context.Response(\n requestToBodyStream(options.context, Uint8Array, readStream)\n )\n }\n}\n"],"names":["fetchInlineAsset","options","inputString","String","input","startsWith","name","replace","asset","assets","find","x","filePath","resolve","distDir","fileIsReadable","fs","access","then","readStream","createReadStream","context","Response","requestToBodyStream","Uint8Array"],"mappings":";;;;+BAUsBA;;;eAAAA;;;oBAT2B;6BACb;sBACZ;AAOjB,eAAeA,iBAAiBC,OAKtC;IACC,MAAMC,cAAcC,OAAOF,QAAQG,KAAK;IACxC,IAAI,CAACF,YAAYG,UAAU,CAAC,UAAU;QACpC;IACF;IAEA,MAAMC,OAAOJ,YAAYK,OAAO,CAAC,SAAS;IAC1C,MAAMC,QAAQP,QAAQQ,MAAM,GACxBR,QAAQQ,MAAM,CAACC,IAAI,CAAC,CAACC,IAAMA,EAAEL,IAAI,KAAKA,QACtC;QACEA;QACAM,UAAUN;IACZ;IACJ,IAAI,CAACE,OAAO;QACV;IACF;IAEA,MAAMI,WAAWC,IAAAA,aAAO,EAACZ,QAAQa,OAAO,EAAEN,MAAMI,QAAQ;IACxD,MAAMG,iBAAiB,MAAMC,YAAE,CAACC,MAAM,CAACL,UAAUM,IAAI,CACnD,IAAM,MACN,IAAM;IAGR,IAAIH,gBAAgB;QAClB,MAAMI,aAAaC,IAAAA,oBAAgB,EAACR;QACpC,OAAO,IAAIX,QAAQoB,OAAO,CAACC,QAAQ,CACjCC,IAAAA,gCAAmB,EAACtB,QAAQoB,OAAO,EAAEG,YAAYL;IAErD;AACF"}

View File

@@ -0,0 +1,2 @@
export * from './sandbox';
export { clearModuleContext } from './context';

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "clearModuleContext", {
enumerable: true,
get: function() {
return _context.clearModuleContext;
}
});
0 && __export(require("./sandbox"));
_export_star(require("./sandbox"), exports);
const _context = require("./context");
function _export_star(from, to) {
Object.keys(from).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
Object.defineProperty(to, k, {
enumerable: true,
get: function() {
return from[k];
}
});
}
});
return from;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/sandbox/index.ts"],"sourcesContent":["export * from './sandbox'\nexport { clearModuleContext } from './context'\n"],"names":["clearModuleContext"],"mappings":";;;;+BACSA;;;eAAAA,2BAAkB;;;;qBADb;yBACqB"}

View File

@@ -0,0 +1,19 @@
declare abstract class ResourceManager<T, Args> {
private resources;
abstract create(resourceArgs: Args): T;
abstract destroy(resource: T): void;
add(resourceArgs: Args): T;
remove(resource: T): void;
removeAll(): void;
}
declare class IntervalsManager extends ResourceManager<number, Parameters<typeof setInterval>> {
create(args: Parameters<typeof setInterval>): number;
destroy(interval: number): void;
}
declare class TimeoutsManager extends ResourceManager<number, Parameters<typeof setTimeout>> {
create(args: Parameters<typeof setTimeout>): number;
destroy(timeout: number): void;
}
export declare const intervalsManager: IntervalsManager;
export declare const timeoutsManager: TimeoutsManager;
export {};

View File

@@ -0,0 +1,88 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
intervalsManager: null,
timeoutsManager: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
intervalsManager: function() {
return intervalsManager;
},
timeoutsManager: function() {
return timeoutsManager;
}
});
class ResourceManager {
add(resourceArgs) {
const resource = this.create(resourceArgs);
this.resources.push(resource);
return resource;
}
remove(resource) {
this.resources = this.resources.filter((r)=>r !== resource);
this.destroy(resource);
}
removeAll() {
this.resources.forEach(this.destroy);
this.resources = [];
}
constructor(){
this.resources = [];
}
}
class IntervalsManager extends ResourceManager {
create(args) {
// TODO: use the edge runtime provided `setInterval` instead
return webSetIntervalPolyfill(...args);
}
destroy(interval) {
clearInterval(interval);
}
}
class TimeoutsManager extends ResourceManager {
create(args) {
// TODO: use the edge runtime provided `setTimeout` instead
return webSetTimeoutPolyfill(...args);
}
destroy(timeout) {
clearTimeout(timeout);
}
}
function webSetIntervalPolyfill(callback, ms, ...args) {
return setInterval(()=>{
// node's `setInterval` sets `this` to the `Timeout` instance it returned,
// but web `setInterval` always sets `this` to `window`
// see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem
return callback.apply(globalThis, args);
}, ms)[Symbol.toPrimitive]();
}
function webSetTimeoutPolyfill(callback, ms, ...args) {
const wrappedCallback = ()=>{
try {
// node's `setTimeout` sets `this` to the `Timeout` instance it returned,
// but web `setTimeout` always sets `this` to `window`
// see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem
return callback.apply(globalThis, args);
} finally{
// On certain older node versions (<20.16.0, <22.4.0),
// a `setTimeout` whose Timeout was converted to a primitive will leak.
// See: https://github.com/nodejs/node/issues/53335
// We can work around this by explicitly calling `clearTimeout` after the callback runs.
clearTimeout(timeout);
}
};
const timeout = setTimeout(wrappedCallback, ms);
return timeout[Symbol.toPrimitive]();
}
const intervalsManager = new IntervalsManager();
const timeoutsManager = new TimeoutsManager();
//# sourceMappingURL=resource-managers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/sandbox/resource-managers.ts"],"sourcesContent":["abstract class ResourceManager<T, Args> {\n private resources: T[] = []\n\n abstract create(resourceArgs: Args): T\n abstract destroy(resource: T): void\n\n add(resourceArgs: Args) {\n const resource = this.create(resourceArgs)\n this.resources.push(resource)\n return resource\n }\n\n remove(resource: T) {\n this.resources = this.resources.filter((r) => r !== resource)\n this.destroy(resource)\n }\n\n removeAll() {\n this.resources.forEach(this.destroy)\n this.resources = []\n }\n}\n\nclass IntervalsManager extends ResourceManager<\n number,\n Parameters<typeof setInterval>\n> {\n create(args: Parameters<typeof setInterval>) {\n // TODO: use the edge runtime provided `setInterval` instead\n return webSetIntervalPolyfill(...args)\n }\n\n destroy(interval: number) {\n clearInterval(interval)\n }\n}\n\nclass TimeoutsManager extends ResourceManager<\n number,\n Parameters<typeof setTimeout>\n> {\n create(args: Parameters<typeof setTimeout>) {\n // TODO: use the edge runtime provided `setTimeout` instead\n return webSetTimeoutPolyfill(...args)\n }\n\n destroy(timeout: number) {\n clearTimeout(timeout)\n }\n}\n\nfunction webSetIntervalPolyfill<TArgs extends any[]>(\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n return setInterval(() => {\n // node's `setInterval` sets `this` to the `Timeout` instance it returned,\n // but web `setInterval` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem\n return callback.apply(globalThis, args)\n }, ms)[Symbol.toPrimitive]()\n}\n\nfunction webSetTimeoutPolyfill<TArgs extends any[]>(\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n const wrappedCallback = () => {\n try {\n // node's `setTimeout` sets `this` to the `Timeout` instance it returned,\n // but web `setTimeout` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem\n return callback.apply(globalThis, args)\n } finally {\n // On certain older node versions (<20.16.0, <22.4.0),\n // a `setTimeout` whose Timeout was converted to a primitive will leak.\n // See: https://github.com/nodejs/node/issues/53335\n // We can work around this by explicitly calling `clearTimeout` after the callback runs.\n clearTimeout(timeout)\n }\n }\n const timeout = setTimeout(wrappedCallback, ms)\n return timeout[Symbol.toPrimitive]()\n}\n\nexport const intervalsManager = new IntervalsManager()\nexport const timeoutsManager = new TimeoutsManager()\n"],"names":["intervalsManager","timeoutsManager","ResourceManager","add","resourceArgs","resource","create","resources","push","remove","filter","r","destroy","removeAll","forEach","IntervalsManager","args","webSetIntervalPolyfill","interval","clearInterval","TimeoutsManager","webSetTimeoutPolyfill","timeout","clearTimeout","callback","ms","setInterval","apply","globalThis","Symbol","toPrimitive","wrappedCallback","setTimeout"],"mappings":";;;;;;;;;;;;;;;IAuFaA,gBAAgB;eAAhBA;;IACAC,eAAe;eAAfA;;;AAxFb,MAAeC;IAMbC,IAAIC,YAAkB,EAAE;QACtB,MAAMC,WAAW,IAAI,CAACC,MAAM,CAACF;QAC7B,IAAI,CAACG,SAAS,CAACC,IAAI,CAACH;QACpB,OAAOA;IACT;IAEAI,OAAOJ,QAAW,EAAE;QAClB,IAAI,CAACE,SAAS,GAAG,IAAI,CAACA,SAAS,CAACG,MAAM,CAAC,CAACC,IAAMA,MAAMN;QACpD,IAAI,CAACO,OAAO,CAACP;IACf;IAEAQ,YAAY;QACV,IAAI,CAACN,SAAS,CAACO,OAAO,CAAC,IAAI,CAACF,OAAO;QACnC,IAAI,CAACL,SAAS,GAAG,EAAE;IACrB;;aAnBQA,YAAiB,EAAE;;AAoB7B;AAEA,MAAMQ,yBAAyBb;IAI7BI,OAAOU,IAAoC,EAAE;QAC3C,4DAA4D;QAC5D,OAAOC,0BAA0BD;IACnC;IAEAJ,QAAQM,QAAgB,EAAE;QACxBC,cAAcD;IAChB;AACF;AAEA,MAAME,wBAAwBlB;IAI5BI,OAAOU,IAAmC,EAAE;QAC1C,2DAA2D;QAC3D,OAAOK,yBAAyBL;IAClC;IAEAJ,QAAQU,OAAe,EAAE;QACvBC,aAAaD;IACf;AACF;AAEA,SAASL,uBACPO,QAAkC,EAClCC,EAAW,EACX,GAAGT,IAAW;IAEd,OAAOU,YAAY;QACjB,0EAA0E;QAC1E,uDAAuD;QACvD,4FAA4F;QAC5F,OAAOF,SAASG,KAAK,CAACC,YAAYZ;IACpC,GAAGS,GAAG,CAACI,OAAOC,WAAW,CAAC;AAC5B;AAEA,SAAST,sBACPG,QAAkC,EAClCC,EAAW,EACX,GAAGT,IAAW;IAEd,MAAMe,kBAAkB;QACtB,IAAI;YACF,yEAAyE;YACzE,sDAAsD;YACtD,2FAA2F;YAC3F,OAAOP,SAASG,KAAK,CAACC,YAAYZ;QACpC,SAAU;YACR,sDAAsD;YACtD,uEAAuE;YACvE,mDAAmD;YACnD,wFAAwF;YACxFO,aAAaD;QACf;IACF;IACA,MAAMA,UAAUU,WAAWD,iBAAiBN;IAC5C,OAAOH,OAAO,CAACO,OAAOC,WAAW,CAAC;AACpC;AAEO,MAAM9B,mBAAmB,IAAIe;AAC7B,MAAMd,kBAAkB,IAAImB"}

View File

@@ -0,0 +1,21 @@
import type { NodejsRequestData, FetchEventResult } from '../types';
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin';
import type { EdgeRuntime } from 'next/dist/compiled/edge-runtime';
import type { ServerComponentsHmrCache } from '../../response-cache';
export declare const ErrorSource: unique symbol;
interface RunnerFnParams {
name: string;
onError?: (err: unknown) => void;
onWarning?: (warn: Error) => void;
paths: string[];
request: NodejsRequestData;
useCache: boolean;
edgeFunctionEntry: Pick<EdgeFunctionDefinition, 'assets' | 'wasm' | 'env'>;
distDir: string;
incrementalCache?: any;
serverComponentsHmrCache?: ServerComponentsHmrCache;
}
type RunnerFn = (params: RunnerFnParams) => Promise<FetchEventResult>;
export declare function getRuntimeContext(params: Omit<RunnerFnParams, 'request'>): Promise<EdgeRuntime<any>>;
export declare const run: RunnerFn;
export {};

View File

@@ -0,0 +1,130 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ErrorSource: null,
getRuntimeContext: null,
run: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ErrorSource: function() {
return ErrorSource;
},
getRuntimeContext: function() {
return getRuntimeContext;
},
run: function() {
return run;
}
});
const _context = require("./context");
const _bodystreams = require("../../body-streams");
const _approuterheaders = require("../../../client/components/app-router-headers");
const _builtinrequestcontext = require("../../after/builtin-request-context");
const ErrorSource = Symbol('SandboxError');
const FORBIDDEN_HEADERS = [
'content-length',
'content-encoding',
'transfer-encoding'
];
/**
* Decorates the runner function making sure all errors it can produce are
* tagged with `edge-server` so they can properly be rendered in dev.
*/ function withTaggedErrors(fn) {
if (process.env.NODE_ENV === 'development') {
const { getServerError } = require('../../../client/components/react-dev-overlay/server/middleware-webpack');
return (params)=>fn(params).then((result)=>{
var _result_waitUntil;
return {
...result,
waitUntil: result == null ? void 0 : (_result_waitUntil = result.waitUntil) == null ? void 0 : _result_waitUntil.catch((error)=>{
// TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.
throw getServerError(error, 'edge-server');
})
};
}).catch((error)=>{
// TODO: used COMPILER_NAMES.edgeServer instead
throw getServerError(error, 'edge-server');
});
}
return fn;
}
async function getRuntimeContext(params) {
const { runtime, evaluateInContext } = await (0, _context.getModuleContext)({
moduleName: params.name,
onWarning: params.onWarning ?? (()=>{}),
onError: params.onError ?? (()=>{}),
useCache: params.useCache !== false,
edgeFunctionEntry: params.edgeFunctionEntry,
distDir: params.distDir
});
if (params.incrementalCache) {
runtime.context.globalThis.__incrementalCache = params.incrementalCache;
}
if (params.serverComponentsHmrCache) {
runtime.context.globalThis.__serverComponentsHmrCache = params.serverComponentsHmrCache;
}
for (const paramPath of params.paths){
evaluateInContext(paramPath);
}
return runtime;
}
const run = withTaggedErrors(async function runWithTaggedErrors(params) {
var _params_request_body;
const runtime = await getRuntimeContext(params);
const edgeFunction = (await runtime.context._ENTRIES[`middleware_${params.name}`]).default;
const cloned = ![
'HEAD',
'GET'
].includes(params.request.method) ? (_params_request_body = params.request.body) == null ? void 0 : _params_request_body.cloneBodyStream() : undefined;
const KUint8Array = runtime.evaluate('Uint8Array');
const urlInstance = new URL(params.request.url);
urlInstance.searchParams.delete(_approuterheaders.NEXT_RSC_UNION_QUERY);
params.request.url = urlInstance.toString();
const headers = new Headers();
for (const [key, value] of Object.entries(params.request.headers)){
headers.set(key, (value == null ? void 0 : value.toString()) ?? '');
}
try {
let result = undefined;
const builtinRequestCtx = {
...(0, _builtinrequestcontext.getBuiltinRequestContext)(),
// FIXME(after):
// arguably, this is an abuse of "@next/request-context" --
// it'd make more sense to simply forward its existing value into the sandbox (in `createModuleContext`)
// but here we're using it to just pass in `waitUntil` regardless if we were running in this context or not.
waitUntil: params.request.waitUntil
};
await _context.edgeSandboxNextRequestContext.run(builtinRequestCtx, ()=>_context.requestStore.run({
headers
}, async ()=>{
result = await edgeFunction({
request: {
...params.request,
body: cloned && (0, _bodystreams.requestToBodyStream)(runtime.context, KUint8Array, cloned)
}
});
for (const headerName of FORBIDDEN_HEADERS){
result.response.headers.delete(headerName);
}
}));
if (!result) throw Object.defineProperty(new Error('Edge function did not return a response'), "__NEXT_ERROR_CODE", {
value: "E332",
enumerable: false,
configurable: true
});
return result;
} finally{
var _params_request_body1;
await ((_params_request_body1 = params.request.body) == null ? void 0 : _params_request_body1.finalize());
}
});
//# sourceMappingURL=sandbox.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,43 @@
import type { IncomingHttpHeaders } from 'http';
export type ReadonlyHeaders = Headers & {
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
append(...args: any[]): void;
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
set(...args: any[]): void;
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */
delete(...args: any[]): void;
};
export declare class HeadersAdapter extends Headers {
private readonly headers;
constructor(headers: IncomingHttpHeaders);
/**
* Seals a Headers instance to prevent modification by throwing an error when
* any mutating method is called.
*/
static seal(headers: Headers): ReadonlyHeaders;
/**
* Merges a header value into a string. This stores multiple values as an
* array, so we need to merge them into a string.
*
* @param value a header value
* @returns a merged header value (a string)
*/
private merge;
/**
* Creates a Headers instance from a plain object or a Headers instance.
*
* @param headers a plain object or a Headers instance
* @returns a headers instance
*/
static from(headers: IncomingHttpHeaders | Headers): Headers;
append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
forEach(callbackfn: (value: string, name: string, parent: Headers) => void, thisArg?: any): void;
entries(): HeadersIterator<[string, string]>;
keys(): HeadersIterator<string>;
values(): HeadersIterator<string>;
[Symbol.iterator](): HeadersIterator<[string, string]>;
}

View File

@@ -0,0 +1,192 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
HeadersAdapter: null,
ReadonlyHeadersError: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
HeadersAdapter: function() {
return HeadersAdapter;
},
ReadonlyHeadersError: function() {
return ReadonlyHeadersError;
}
});
const _reflect = require("./reflect");
class ReadonlyHeadersError extends Error {
constructor(){
super('Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers');
}
static callable() {
throw new ReadonlyHeadersError();
}
}
class HeadersAdapter extends Headers {
constructor(headers){
// We've already overridden the methods that would be called, so we're just
// calling the super constructor to ensure that the instanceof check works.
super();
this.headers = new Proxy(headers, {
get (target, prop, receiver) {
// Because this is just an object, we expect that all "get" operations
// are for properties. If it's a "get" for a symbol, we'll just return
// the symbol.
if (typeof prop === 'symbol') {
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, return undefined.
if (typeof original === 'undefined') return;
// If the original casing exists, return the value.
return _reflect.ReflectAdapter.get(target, original, receiver);
},
set (target, prop, value, receiver) {
if (typeof prop === 'symbol') {
return _reflect.ReflectAdapter.set(target, prop, value, receiver);
}
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, use the prop as the key.
return _reflect.ReflectAdapter.set(target, original ?? prop, value, receiver);
},
has (target, prop) {
if (typeof prop === 'symbol') return _reflect.ReflectAdapter.has(target, prop);
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, return false.
if (typeof original === 'undefined') return false;
// If the original casing exists, return true.
return _reflect.ReflectAdapter.has(target, original);
},
deleteProperty (target, prop) {
if (typeof prop === 'symbol') return _reflect.ReflectAdapter.deleteProperty(target, prop);
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, return true.
if (typeof original === 'undefined') return true;
// If the original casing exists, delete the property.
return _reflect.ReflectAdapter.deleteProperty(target, original);
}
});
}
/**
* Seals a Headers instance to prevent modification by throwing an error when
* any mutating method is called.
*/ static seal(headers) {
return new Proxy(headers, {
get (target, prop, receiver) {
switch(prop){
case 'append':
case 'delete':
case 'set':
return ReadonlyHeadersError.callable;
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
}
/**
* Merges a header value into a string. This stores multiple values as an
* array, so we need to merge them into a string.
*
* @param value a header value
* @returns a merged header value (a string)
*/ merge(value) {
if (Array.isArray(value)) return value.join(', ');
return value;
}
/**
* Creates a Headers instance from a plain object or a Headers instance.
*
* @param headers a plain object or a Headers instance
* @returns a headers instance
*/ static from(headers) {
if (headers instanceof Headers) return headers;
return new HeadersAdapter(headers);
}
append(name, value) {
const existing = this.headers[name];
if (typeof existing === 'string') {
this.headers[name] = [
existing,
value
];
} else if (Array.isArray(existing)) {
existing.push(value);
} else {
this.headers[name] = value;
}
}
delete(name) {
delete this.headers[name];
}
get(name) {
const value = this.headers[name];
if (typeof value !== 'undefined') return this.merge(value);
return null;
}
has(name) {
return typeof this.headers[name] !== 'undefined';
}
set(name, value) {
this.headers[name] = value;
}
forEach(callbackfn, thisArg) {
for (const [name, value] of this.entries()){
callbackfn.call(thisArg, value, name, this);
}
}
*entries() {
for (const key of Object.keys(this.headers)){
const name = key.toLowerCase();
// We assert here that this is a string because we got it from the
// Object.keys() call above.
const value = this.get(name);
yield [
name,
value
];
}
}
*keys() {
for (const key of Object.keys(this.headers)){
const name = key.toLowerCase();
yield name;
}
}
*values() {
for (const key of Object.keys(this.headers)){
// We assert here that this is a string because we got it from the
// Object.keys() call above.
const value = this.get(key);
yield value;
}
}
[Symbol.iterator]() {
return this.entries();
}
}
//# sourceMappingURL=headers.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import type { BaseNextRequest } from '../../../base-http';
import type { NodeNextRequest } from '../../../base-http/node';
import type { WebNextRequest } from '../../../base-http/web';
import type { Writable } from 'node:stream';
import { NextRequest } from '../request';
export declare const ResponseAbortedName = "ResponseAborted";
export declare class ResponseAborted extends Error {
readonly name = "ResponseAborted";
}
/**
* Creates an AbortController tied to the closing of a ServerResponse (or other
* appropriate Writable).
*
* If the `close` event is fired before the `finish` event, then we'll send the
* `abort` signal.
*/
export declare function createAbortController(response: Writable): AbortController;
/**
* Creates an AbortSignal tied to the closing of a ServerResponse (or other
* appropriate Writable).
*
* This cannot be done with the request (IncomingMessage or Readable) because
* the `abort` event will not fire if to data has been fully read (because that
* will "close" the readable stream and nothing fires after that).
*/
export declare function signalFromNodeResponse(response: Writable): AbortSignal;
export declare class NextRequestAdapter {
static fromBaseNextRequest(request: BaseNextRequest, signal: AbortSignal): NextRequest;
static fromNodeNextRequest(request: NodeNextRequest, signal: AbortSignal): NextRequest;
static fromWebNextRequest(request: WebNextRequest): NextRequest;
}

View File

@@ -0,0 +1,142 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NextRequestAdapter: null,
ResponseAborted: null,
ResponseAbortedName: null,
createAbortController: null,
signalFromNodeResponse: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NextRequestAdapter: function() {
return NextRequestAdapter;
},
ResponseAborted: function() {
return ResponseAborted;
},
ResponseAbortedName: function() {
return ResponseAbortedName;
},
createAbortController: function() {
return createAbortController;
},
signalFromNodeResponse: function() {
return signalFromNodeResponse;
}
});
const _requestmeta = require("../../../request-meta");
const _utils = require("../../utils");
const _request = require("../request");
const _helpers = require("../../../base-http/helpers");
const ResponseAbortedName = 'ResponseAborted';
class ResponseAborted extends Error {
constructor(...args){
super(...args), this.name = ResponseAbortedName;
}
}
function createAbortController(response) {
const controller = new AbortController();
// If `finish` fires first, then `res.end()` has been called and the close is
// just us finishing the stream on our side. If `close` fires first, then we
// know the client disconnected before we finished.
response.once('close', ()=>{
if (response.writableFinished) return;
controller.abort(new ResponseAborted());
});
return controller;
}
function signalFromNodeResponse(response) {
const { errored, destroyed } = response;
if (errored || destroyed) {
return AbortSignal.abort(errored ?? new ResponseAborted());
}
const { signal } = createAbortController(response);
return signal;
}
class NextRequestAdapter {
static fromBaseNextRequest(request, signal) {
if (// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME === 'edge' && (0, _helpers.isWebNextRequest)(request)) {
return NextRequestAdapter.fromWebNextRequest(request);
} else if (// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextRequest)(request)) {
return NextRequestAdapter.fromNodeNextRequest(request, signal);
} else {
throw Object.defineProperty(new Error('Invariant: Unsupported NextRequest type'), "__NEXT_ERROR_CODE", {
value: "E345",
enumerable: false,
configurable: true
});
}
}
static fromNodeNextRequest(request, signal) {
// HEAD and GET requests can not have a body.
let body = null;
if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) {
// @ts-expect-error - this is handled by undici, when streams/web land use it instead
body = request.body;
}
let url;
if (request.url.startsWith('http')) {
url = new URL(request.url);
} else {
// Grab the full URL from the request metadata.
const base = (0, _requestmeta.getRequestMeta)(request, 'initURL');
if (!base || !base.startsWith('http')) {
// Because the URL construction relies on the fact that the URL provided
// is absolute, we need to provide a base URL. We can't use the request
// URL because it's relative, so we use a dummy URL instead.
url = new URL(request.url, 'http://n');
} else {
url = new URL(request.url, base);
}
}
return new _request.NextRequest(url, {
method: request.method,
headers: (0, _utils.fromNodeOutgoingHttpHeaders)(request.headers),
duplex: 'half',
signal,
// geo
// ip
// nextConfig
// body can not be passed if request was aborted
// or we get a Request body was disturbed error
...signal.aborted ? {} : {
body
}
});
}
static fromWebNextRequest(request) {
// HEAD and GET requests can not have a body.
let body = null;
if (request.method !== 'GET' && request.method !== 'HEAD') {
body = request.body;
}
return new _request.NextRequest(request.url, {
method: request.method,
headers: (0, _utils.fromNodeOutgoingHttpHeaders)(request.headers),
duplex: 'half',
signal: request.request.signal,
// geo
// ip
// nextConfig
// body can not be passed if request was aborted
// or we get a Request body was disturbed error
...request.request.signal.aborted ? {} : {
body
}
});
}
}
//# sourceMappingURL=next-request.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
export declare class ReflectAdapter {
static get<T extends object>(target: T, prop: string | symbol, receiver: unknown): any;
static set<T extends object>(target: T, prop: string | symbol, value: any, receiver: any): boolean;
static has<T extends object>(target: T, prop: string | symbol): boolean;
static deleteProperty<T extends object>(target: T, prop: string | symbol): boolean;
}

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ReflectAdapter", {
enumerable: true,
get: function() {
return ReflectAdapter;
}
});
class ReflectAdapter {
static get(target, prop, receiver) {
const value = Reflect.get(target, prop, receiver);
if (typeof value === 'function') {
return value.bind(target);
}
return value;
}
static set(target, prop, value, receiver) {
return Reflect.set(target, prop, value, receiver);
}
static has(target, prop) {
return Reflect.has(target, prop);
}
static deleteProperty(target, prop) {
return Reflect.deleteProperty(target, prop);
}
}
//# sourceMappingURL=reflect.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/reflect.ts"],"sourcesContent":["export class ReflectAdapter {\n static get<T extends object>(\n target: T,\n prop: string | symbol,\n receiver: unknown\n ): any {\n const value = Reflect.get(target, prop, receiver)\n if (typeof value === 'function') {\n return value.bind(target)\n }\n\n return value\n }\n\n static set<T extends object>(\n target: T,\n prop: string | symbol,\n value: any,\n receiver: any\n ): boolean {\n return Reflect.set(target, prop, value, receiver)\n }\n\n static has<T extends object>(target: T, prop: string | symbol): boolean {\n return Reflect.has(target, prop)\n }\n\n static deleteProperty<T extends object>(\n target: T,\n prop: string | symbol\n ): boolean {\n return Reflect.deleteProperty(target, prop)\n }\n}\n"],"names":["ReflectAdapter","get","target","prop","receiver","value","Reflect","bind","set","has","deleteProperty"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA;IACX,OAAOC,IACLC,MAAS,EACTC,IAAqB,EACrBC,QAAiB,EACZ;QACL,MAAMC,QAAQC,QAAQL,GAAG,CAACC,QAAQC,MAAMC;QACxC,IAAI,OAAOC,UAAU,YAAY;YAC/B,OAAOA,MAAME,IAAI,CAACL;QACpB;QAEA,OAAOG;IACT;IAEA,OAAOG,IACLN,MAAS,EACTC,IAAqB,EACrBE,KAAU,EACVD,QAAa,EACJ;QACT,OAAOE,QAAQE,GAAG,CAACN,QAAQC,MAAME,OAAOD;IAC1C;IAEA,OAAOK,IAAsBP,MAAS,EAAEC,IAAqB,EAAW;QACtE,OAAOG,QAAQG,GAAG,CAACP,QAAQC;IAC7B;IAEA,OAAOO,eACLR,MAAS,EACTC,IAAqB,EACZ;QACT,OAAOG,QAAQI,cAAc,CAACR,QAAQC;IACxC;AACF"}

View File

@@ -0,0 +1,17 @@
import { RequestCookies } from '../cookies';
import { ResponseCookies } from '../cookies';
import { type RequestStore } from '../../../app-render/work-unit-async-storage.external';
export type { ResponseCookies };
export type ReadonlyRequestCookies = Omit<RequestCookies, 'set' | 'clear' | 'delete'> & Pick<ResponseCookies, 'set' | 'delete'>;
export declare class RequestCookiesAdapter {
static seal(cookies: RequestCookies): ReadonlyRequestCookies;
}
export declare function getModifiedCookieValues(cookies: ResponseCookies): ResponseCookie[];
export declare function appendMutableCookies(headers: Headers, mutableCookies: ResponseCookies): boolean;
type ResponseCookie = NonNullable<ReturnType<InstanceType<typeof ResponseCookies>['get']>>;
export declare class MutableRequestCookiesAdapter {
static wrap(cookies: RequestCookies, onUpdateCookies?: (cookies: string[]) => void): ResponseCookies;
}
export declare function wrapWithMutableAccessCheck(responseCookies: ResponseCookies): ResponseCookies;
export declare function areCookiesMutableInCurrentPhase(requestStore: RequestStore): boolean;
export declare function responseCookiesToRequestCookies(responseCookies: ResponseCookies): RequestCookies;

View File

@@ -0,0 +1,212 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
MutableRequestCookiesAdapter: null,
ReadonlyRequestCookiesError: null,
RequestCookiesAdapter: null,
appendMutableCookies: null,
areCookiesMutableInCurrentPhase: null,
getModifiedCookieValues: null,
responseCookiesToRequestCookies: null,
wrapWithMutableAccessCheck: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
MutableRequestCookiesAdapter: function() {
return MutableRequestCookiesAdapter;
},
ReadonlyRequestCookiesError: function() {
return ReadonlyRequestCookiesError;
},
RequestCookiesAdapter: function() {
return RequestCookiesAdapter;
},
appendMutableCookies: function() {
return appendMutableCookies;
},
areCookiesMutableInCurrentPhase: function() {
return areCookiesMutableInCurrentPhase;
},
getModifiedCookieValues: function() {
return getModifiedCookieValues;
},
responseCookiesToRequestCookies: function() {
return responseCookiesToRequestCookies;
},
wrapWithMutableAccessCheck: function() {
return wrapWithMutableAccessCheck;
}
});
const _cookies = require("../cookies");
const _reflect = require("./reflect");
const _workasyncstorageexternal = require("../../../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../../../app-render/work-unit-async-storage.external");
class ReadonlyRequestCookiesError extends Error {
constructor(){
super('Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options');
}
static callable() {
throw new ReadonlyRequestCookiesError();
}
}
class RequestCookiesAdapter {
static seal(cookies) {
return new Proxy(cookies, {
get (target, prop, receiver) {
switch(prop){
case 'clear':
case 'delete':
case 'set':
return ReadonlyRequestCookiesError.callable;
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
}
}
const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies');
function getModifiedCookieValues(cookies) {
const modified = cookies[SYMBOL_MODIFY_COOKIE_VALUES];
if (!modified || !Array.isArray(modified) || modified.length === 0) {
return [];
}
return modified;
}
function appendMutableCookies(headers, mutableCookies) {
const modifiedCookieValues = getModifiedCookieValues(mutableCookies);
if (modifiedCookieValues.length === 0) {
return false;
}
// Return a new response that extends the response with
// the modified cookies as fallbacks. `res` cookies
// will still take precedence.
const resCookies = new _cookies.ResponseCookies(headers);
const returnedCookies = resCookies.getAll();
// Set the modified cookies as fallbacks.
for (const cookie of modifiedCookieValues){
resCookies.set(cookie);
}
// Set the original cookies as the final values.
for (const cookie of returnedCookies){
resCookies.set(cookie);
}
return true;
}
class MutableRequestCookiesAdapter {
static wrap(cookies, onUpdateCookies) {
const responseCookies = new _cookies.ResponseCookies(new Headers());
for (const cookie of cookies.getAll()){
responseCookies.set(cookie);
}
let modifiedValues = [];
const modifiedCookies = new Set();
const updateResponseCookies = ()=>{
// TODO-APP: change method of getting workStore
const workStore = _workasyncstorageexternal.workAsyncStorage.getStore();
if (workStore) {
workStore.pathWasRevalidated = true;
}
const allCookies = responseCookies.getAll();
modifiedValues = allCookies.filter((c)=>modifiedCookies.has(c.name));
if (onUpdateCookies) {
const serializedCookies = [];
for (const cookie of modifiedValues){
const tempCookies = new _cookies.ResponseCookies(new Headers());
tempCookies.set(cookie);
serializedCookies.push(tempCookies.toString());
}
onUpdateCookies(serializedCookies);
}
};
const wrappedCookies = new Proxy(responseCookies, {
get (target, prop, receiver) {
switch(prop){
// A special symbol to get the modified cookie values
case SYMBOL_MODIFY_COOKIE_VALUES:
return modifiedValues;
// TODO: Throw error if trying to set a cookie after the response
// headers have been set.
case 'delete':
return function(...args) {
modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name);
try {
target.delete(...args);
return wrappedCookies;
} finally{
updateResponseCookies();
}
};
case 'set':
return function(...args) {
modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name);
try {
target.set(...args);
return wrappedCookies;
} finally{
updateResponseCookies();
}
};
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
return wrappedCookies;
}
}
function wrapWithMutableAccessCheck(responseCookies) {
const wrappedCookies = new Proxy(responseCookies, {
get (target, prop, receiver) {
switch(prop){
case 'delete':
return function(...args) {
ensureCookiesAreStillMutable('cookies().delete');
target.delete(...args);
return wrappedCookies;
};
case 'set':
return function(...args) {
ensureCookiesAreStillMutable('cookies().set');
target.set(...args);
return wrappedCookies;
};
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
return wrappedCookies;
}
function areCookiesMutableInCurrentPhase(requestStore) {
return requestStore.phase === 'action';
}
/** Ensure that cookies() starts throwing on mutation
* if we changed phases and can no longer mutate.
*
* This can happen when going:
* 'render' -> 'after'
* 'action' -> 'render'
* */ function ensureCookiesAreStillMutable(callingExpression) {
const requestStore = (0, _workunitasyncstorageexternal.getExpectedRequestStore)(callingExpression);
if (!areCookiesMutableInCurrentPhase(requestStore)) {
// TODO: maybe we can give a more precise error message based on callingExpression?
throw new ReadonlyRequestCookiesError();
}
}
function responseCookiesToRequestCookies(responseCookies) {
const requestCookies = new _cookies.RequestCookies(new Headers());
for (const cookie of responseCookies.getAll()){
requestCookies.set(cookie);
}
return requestCookies;
}
//# sourceMappingURL=request-cookies.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export { RequestCookies, ResponseCookies, stringifyCookie, } from 'next/dist/compiled/@edge-runtime/cookies';

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
RequestCookies: null,
ResponseCookies: null,
stringifyCookie: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
RequestCookies: function() {
return _cookies.RequestCookies;
},
ResponseCookies: function() {
return _cookies.ResponseCookies;
},
stringifyCookie: function() {
return _cookies.stringifyCookie;
}
});
const _cookies = require("next/dist/compiled/@edge-runtime/cookies");
//# sourceMappingURL=cookies.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/cookies.ts"],"sourcesContent":["export {\n RequestCookies,\n ResponseCookies,\n stringifyCookie,\n} from 'next/dist/compiled/@edge-runtime/cookies'\n"],"names":["RequestCookies","ResponseCookies","stringifyCookie"],"mappings":";;;;;;;;;;;;;;;;IACEA,cAAc;eAAdA,uBAAc;;IACdC,eAAe;eAAfA,wBAAe;;IACfC,eAAe;eAAfA,wBAAe;;;yBACV"}

View File

@@ -0,0 +1,44 @@
import type { WaitUntil } from '../../after/builtin-request-context';
import type { NextRequest } from './request';
declare const responseSymbol: unique symbol;
declare const passThroughSymbol: unique symbol;
declare const waitUntilSymbol: unique symbol;
declare class FetchEvent {
readonly [waitUntilSymbol]: {
kind: 'internal';
promises: Promise<any>[];
} | {
kind: 'external';
function: WaitUntil;
};
[responseSymbol]?: Promise<Response>;
[passThroughSymbol]: boolean;
constructor(_request: Request, waitUntil?: WaitUntil);
respondWith(response: Response | Promise<Response>): void;
passThroughOnException(): void;
waitUntil(promise: Promise<any>): void;
}
export declare function getWaitUntilPromiseFromEvent(event: FetchEvent): Promise<void> | undefined;
export declare class NextFetchEvent extends FetchEvent {
sourcePage: string;
constructor(params: {
request: NextRequest;
page: string;
context: {
waitUntil: WaitUntil;
} | undefined;
});
/**
* @deprecated The `request` is now the first parameter and the API is now async.
*
* Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/
get request(): void;
/**
* @deprecated Using `respondWith` is no longer needed.
*
* Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/
respondWith(): void;
}
export {};

View File

@@ -0,0 +1,98 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NextFetchEvent: null,
getWaitUntilPromiseFromEvent: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NextFetchEvent: function() {
return NextFetchEvent;
},
getWaitUntilPromiseFromEvent: function() {
return getWaitUntilPromiseFromEvent;
}
});
const _error = require("../error");
const responseSymbol = Symbol('response');
const passThroughSymbol = Symbol('passThrough');
const waitUntilSymbol = Symbol('waitUntil');
class FetchEvent {
constructor(_request, waitUntil){
this[passThroughSymbol] = false;
this[waitUntilSymbol] = waitUntil ? {
kind: 'external',
function: waitUntil
} : {
kind: 'internal',
promises: []
};
}
// TODO: is this dead code? NextFetchEvent never lets this get called
respondWith(response) {
if (!this[responseSymbol]) {
this[responseSymbol] = Promise.resolve(response);
}
}
// TODO: is this dead code? passThroughSymbol is unused
passThroughOnException() {
this[passThroughSymbol] = true;
}
waitUntil(promise) {
if (this[waitUntilSymbol].kind === 'external') {
// if we received an external waitUntil, we delegate to it
// TODO(after): this will make us not go through `getServerError(error, 'edge-server')` in `sandbox`
const waitUntil = this[waitUntilSymbol].function;
return waitUntil(promise);
} else {
// if we didn't receive an external waitUntil, we make it work on our own
// (and expect the caller to do something with the promises)
this[waitUntilSymbol].promises.push(promise);
}
}
}
function getWaitUntilPromiseFromEvent(event) {
return event[waitUntilSymbol].kind === 'internal' ? Promise.all(event[waitUntilSymbol].promises).then(()=>{}) : undefined;
}
class NextFetchEvent extends FetchEvent {
constructor(params){
var _params_context;
super(params.request, (_params_context = params.context) == null ? void 0 : _params_context.waitUntil);
this.sourcePage = params.page;
}
/**
* @deprecated The `request` is now the first parameter and the API is now async.
*
* Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/ get request() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
/**
* @deprecated Using `respondWith` is no longer needed.
*
* Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/ respondWith() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
}
//# sourceMappingURL=fetch-event.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/fetch-event.ts"],"sourcesContent":["import type { WaitUntil } from '../../after/builtin-request-context'\nimport { PageSignatureError } from '../error'\nimport type { NextRequest } from './request'\n\nconst responseSymbol = Symbol('response')\nconst passThroughSymbol = Symbol('passThrough')\nconst waitUntilSymbol = Symbol('waitUntil')\n\nclass FetchEvent {\n // TODO(after): get rid of the 'internal' variant and always use an external waitUntil\n // (this means removing `FetchEventResult.waitUntil` which also requires a builder change)\n readonly [waitUntilSymbol]:\n | { kind: 'internal'; promises: Promise<any>[] }\n | { kind: 'external'; function: WaitUntil };\n\n [responseSymbol]?: Promise<Response>;\n [passThroughSymbol] = false\n\n constructor(_request: Request, waitUntil?: WaitUntil) {\n this[waitUntilSymbol] = waitUntil\n ? { kind: 'external', function: waitUntil }\n : { kind: 'internal', promises: [] }\n }\n\n // TODO: is this dead code? NextFetchEvent never lets this get called\n respondWith(response: Response | Promise<Response>): void {\n if (!this[responseSymbol]) {\n this[responseSymbol] = Promise.resolve(response)\n }\n }\n\n // TODO: is this dead code? passThroughSymbol is unused\n passThroughOnException(): void {\n this[passThroughSymbol] = true\n }\n\n waitUntil(promise: Promise<any>): void {\n if (this[waitUntilSymbol].kind === 'external') {\n // if we received an external waitUntil, we delegate to it\n // TODO(after): this will make us not go through `getServerError(error, 'edge-server')` in `sandbox`\n const waitUntil = this[waitUntilSymbol].function\n return waitUntil(promise)\n } else {\n // if we didn't receive an external waitUntil, we make it work on our own\n // (and expect the caller to do something with the promises)\n this[waitUntilSymbol].promises.push(promise)\n }\n }\n}\n\nexport function getWaitUntilPromiseFromEvent(\n event: FetchEvent\n): Promise<void> | undefined {\n return event[waitUntilSymbol].kind === 'internal'\n ? Promise.all(event[waitUntilSymbol].promises).then(() => {})\n : undefined\n}\n\nexport class NextFetchEvent extends FetchEvent {\n sourcePage: string\n\n constructor(params: {\n request: NextRequest\n page: string\n context: { waitUntil: WaitUntil } | undefined\n }) {\n super(params.request, params.context?.waitUntil)\n this.sourcePage = params.page\n }\n\n /**\n * @deprecated The `request` is now the first parameter and the API is now async.\n *\n * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n */\n get request() {\n throw new PageSignatureError({\n page: this.sourcePage,\n })\n }\n\n /**\n * @deprecated Using `respondWith` is no longer needed.\n *\n * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n */\n respondWith() {\n throw new PageSignatureError({\n page: this.sourcePage,\n })\n }\n}\n"],"names":["NextFetchEvent","getWaitUntilPromiseFromEvent","responseSymbol","Symbol","passThroughSymbol","waitUntilSymbol","FetchEvent","constructor","_request","waitUntil","kind","function","promises","respondWith","response","Promise","resolve","passThroughOnException","promise","push","event","all","then","undefined","params","request","context","sourcePage","page","PageSignatureError"],"mappings":";;;;;;;;;;;;;;;IA0DaA,cAAc;eAAdA;;IARGC,4BAA4B;eAA5BA;;;uBAjDmB;AAGnC,MAAMC,iBAAiBC,OAAO;AAC9B,MAAMC,oBAAoBD,OAAO;AACjC,MAAME,kBAAkBF,OAAO;AAE/B,MAAMG;IAUJC,YAAYC,QAAiB,EAAEC,SAAqB,CAAE;YAFtD,CAACL,kBAAkB,GAAG;QAGpB,IAAI,CAACC,gBAAgB,GAAGI,YACpB;YAAEC,MAAM;YAAYC,UAAUF;QAAU,IACxC;YAAEC,MAAM;YAAYE,UAAU,EAAE;QAAC;IACvC;IAEA,qEAAqE;IACrEC,YAAYC,QAAsC,EAAQ;QACxD,IAAI,CAAC,IAAI,CAACZ,eAAe,EAAE;YACzB,IAAI,CAACA,eAAe,GAAGa,QAAQC,OAAO,CAACF;QACzC;IACF;IAEA,uDAAuD;IACvDG,yBAA+B;QAC7B,IAAI,CAACb,kBAAkB,GAAG;IAC5B;IAEAK,UAAUS,OAAqB,EAAQ;QACrC,IAAI,IAAI,CAACb,gBAAgB,CAACK,IAAI,KAAK,YAAY;YAC7C,0DAA0D;YAC1D,oGAAoG;YACpG,MAAMD,YAAY,IAAI,CAACJ,gBAAgB,CAACM,QAAQ;YAChD,OAAOF,UAAUS;QACnB,OAAO;YACL,yEAAyE;YACzE,4DAA4D;YAC5D,IAAI,CAACb,gBAAgB,CAACO,QAAQ,CAACO,IAAI,CAACD;QACtC;IACF;AACF;AAEO,SAASjB,6BACdmB,KAAiB;IAEjB,OAAOA,KAAK,CAACf,gBAAgB,CAACK,IAAI,KAAK,aACnCK,QAAQM,GAAG,CAACD,KAAK,CAACf,gBAAgB,CAACO,QAAQ,EAAEU,IAAI,CAAC,KAAO,KACzDC;AACN;AAEO,MAAMvB,uBAAuBM;IAGlCC,YAAYiB,MAIX,CAAE;YACqBA;QAAtB,KAAK,CAACA,OAAOC,OAAO,GAAED,kBAAAA,OAAOE,OAAO,qBAAdF,gBAAgBf,SAAS;QAC/C,IAAI,CAACkB,UAAU,GAAGH,OAAOI,IAAI;IAC/B;IAEA;;;;GAIC,GACD,IAAIH,UAAU;QACZ,MAAM,qBAEJ,CAFI,IAAII,yBAAkB,CAAC;YAC3BD,MAAM,IAAI,CAACD,UAAU;QACvB,IAFM,qBAAA;mBAAA;wBAAA;0BAAA;QAEL;IACH;IAEA;;;;GAIC,GACDd,cAAc;QACZ,MAAM,qBAEJ,CAFI,IAAIgB,yBAAkB,CAAC;YAC3BD,MAAM,IAAI,CAACD,UAAU;QACvB,IAFM,qBAAA;mBAAA;wBAAA;0BAAA;QAEL;IACH;AACF"}

View File

@@ -0,0 +1,5 @@
/**
* @deprecated ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead.
* Migration with codemods: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#next-og-import
*/
export declare function ImageResponse(): never;

View File

@@ -0,0 +1,22 @@
/**
* @deprecated ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead.
* Migration with codemods: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#next-og-import
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ImageResponse", {
enumerable: true,
get: function() {
return ImageResponse;
}
});
function ImageResponse() {
throw Object.defineProperty(new Error('ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead'), "__NEXT_ERROR_CODE", {
value: "E183",
enumerable: false,
configurable: true
});
}
//# sourceMappingURL=image-response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/image-response.ts"],"sourcesContent":["/**\n * @deprecated ImageResponse moved from \"next/server\" to \"next/og\" since Next.js 14, please import from \"next/og\" instead.\n * Migration with codemods: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#next-og-import\n */\nexport function ImageResponse(): never {\n throw new Error(\n 'ImageResponse moved from \"next/server\" to \"next/og\" since Next.js 14, please import from \"next/og\" instead'\n )\n}\n"],"names":["ImageResponse","Error"],"mappings":"AAAA;;;CAGC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA;IACd,MAAM,qBAEL,CAFK,IAAIC,MACR,+GADI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF"}

View File

@@ -0,0 +1,41 @@
import type { I18NConfig } from '../../config-shared';
import { NextURL } from '../next-url';
import { RequestCookies } from './cookies';
export declare const INTERNALS: unique symbol;
/**
* This class extends the [Web `Request` API](https://developer.mozilla.org/docs/Web/API/Request) with additional convenience methods.
*
* Read more: [Next.js Docs: `NextRequest`](https://nextjs.org/docs/app/api-reference/functions/next-request)
*/
export declare class NextRequest extends Request {
[INTERNALS]: {
cookies: RequestCookies;
url: string;
nextUrl: NextURL;
};
constructor(input: URL | RequestInfo, init?: RequestInit);
get cookies(): RequestCookies;
get nextUrl(): NextURL;
/**
* @deprecated
* `page` has been deprecated in favour of `URLPattern`.
* Read more: https://nextjs.org/docs/messages/middleware-request-page
*/
get page(): void;
/**
* @deprecated
* `ua` has been removed in favour of \`userAgent\` function.
* Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
*/
get ua(): void;
get url(): string;
}
export interface RequestInit extends globalThis.RequestInit {
nextConfig?: {
basePath?: string;
i18n?: I18NConfig | null;
trailingSlash?: boolean;
};
signal?: AbortSignal;
duplex?: 'half';
}

View File

@@ -0,0 +1,99 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
INTERNALS: null,
NextRequest: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
INTERNALS: function() {
return INTERNALS;
},
NextRequest: function() {
return NextRequest;
}
});
const _nexturl = require("../next-url");
const _utils = require("../utils");
const _error = require("../error");
const _cookies = require("./cookies");
const INTERNALS = Symbol('internal request');
class NextRequest extends Request {
constructor(input, init = {}){
const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);
(0, _utils.validateURL)(url);
// node Request instance requires duplex option when a body
// is present or it errors, we don't handle this for
// Request being passed in since it would have already
// errored if this wasn't configured
if (process.env.NEXT_RUNTIME !== 'edge') {
if (init.body && init.duplex !== 'half') {
init.duplex = 'half';
}
}
if (input instanceof Request) super(input, init);
else super(url, init);
const nextUrl = new _nexturl.NextURL(url, {
headers: (0, _utils.toNodeOutgoingHttpHeaders)(this.headers),
nextConfig: init.nextConfig
});
this[INTERNALS] = {
cookies: new _cookies.RequestCookies(this.headers),
nextUrl,
url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? url : nextUrl.toString()
};
}
[Symbol.for('edge-runtime.inspect.custom')]() {
return {
cookies: this.cookies,
nextUrl: this.nextUrl,
url: this.url,
// rest of props come from Request
bodyUsed: this.bodyUsed,
cache: this.cache,
credentials: this.credentials,
destination: this.destination,
headers: Object.fromEntries(this.headers),
integrity: this.integrity,
keepalive: this.keepalive,
method: this.method,
mode: this.mode,
redirect: this.redirect,
referrer: this.referrer,
referrerPolicy: this.referrerPolicy,
signal: this.signal
};
}
get cookies() {
return this[INTERNALS].cookies;
}
get nextUrl() {
return this[INTERNALS].nextUrl;
}
/**
* @deprecated
* `page` has been deprecated in favour of `URLPattern`.
* Read more: https://nextjs.org/docs/messages/middleware-request-page
*/ get page() {
throw new _error.RemovedPageError();
}
/**
* @deprecated
* `ua` has been removed in favour of \`userAgent\` function.
* Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
*/ get ua() {
throw new _error.RemovedUAError();
}
get url() {
return this[INTERNALS].url;
}
}
//# sourceMappingURL=request.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,43 @@
import type { I18NConfig } from '../../config-shared';
import { NextURL } from '../next-url';
import { ResponseCookies } from './cookies';
declare const INTERNALS: unique symbol;
/**
* This class extends the [Web `Response` API](https://developer.mozilla.org/docs/Web/API/Response) with additional convenience methods.
*
* Read more: [Next.js Docs: `NextResponse`](https://nextjs.org/docs/app/api-reference/functions/next-response)
*/
export declare class NextResponse<Body = unknown> extends Response {
[INTERNALS]: {
cookies: ResponseCookies;
url?: NextURL;
body?: Body;
};
constructor(body?: BodyInit | null, init?: ResponseInit);
get cookies(): ResponseCookies;
static json<JsonBody>(body: JsonBody, init?: ResponseInit): NextResponse<JsonBody>;
static redirect(url: string | NextURL | URL, init?: number | ResponseInit): NextResponse<unknown>;
static rewrite(destination: string | NextURL | URL, init?: MiddlewareResponseInit): NextResponse<unknown>;
static next(init?: MiddlewareResponseInit): NextResponse<unknown>;
}
interface ResponseInit extends globalThis.ResponseInit {
nextConfig?: {
basePath?: string;
i18n?: I18NConfig;
trailingSlash?: boolean;
};
url?: string;
}
interface ModifiedRequest {
/**
* If this is set, the request headers will be overridden with this value.
*/
headers?: Headers;
}
interface MiddlewareResponseInit extends globalThis.ResponseInit {
/**
* These fields will override the request from clients.
*/
request?: ModifiedRequest;
}
export {};

View File

@@ -0,0 +1,136 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "NextResponse", {
enumerable: true,
get: function() {
return NextResponse;
}
});
const _cookies = require("../../web/spec-extension/cookies");
const _nexturl = require("../next-url");
const _utils = require("../utils");
const _reflect = require("./adapters/reflect");
const _cookies1 = require("./cookies");
const INTERNALS = Symbol('internal response');
const REDIRECTS = new Set([
301,
302,
303,
307,
308
]);
function handleMiddlewareField(init, headers) {
var _init_request;
if (init == null ? void 0 : (_init_request = init.request) == null ? void 0 : _init_request.headers) {
if (!(init.request.headers instanceof Headers)) {
throw Object.defineProperty(new Error('request.headers must be an instance of Headers'), "__NEXT_ERROR_CODE", {
value: "E119",
enumerable: false,
configurable: true
});
}
const keys = [];
for (const [key, value] of init.request.headers){
headers.set('x-middleware-request-' + key, value);
keys.push(key);
}
headers.set('x-middleware-override-headers', keys.join(','));
}
}
class NextResponse extends Response {
constructor(body, init = {}){
super(body, init);
const headers = this.headers;
const cookies = new _cookies1.ResponseCookies(headers);
const cookiesProxy = new Proxy(cookies, {
get (target, prop, receiver) {
switch(prop){
case 'delete':
case 'set':
{
return (...args)=>{
const result = Reflect.apply(target[prop], target, args);
const newHeaders = new Headers(headers);
if (result instanceof _cookies1.ResponseCookies) {
headers.set('x-middleware-set-cookie', result.getAll().map((cookie)=>(0, _cookies.stringifyCookie)(cookie)).join(','));
}
handleMiddlewareField(init, newHeaders);
return result;
};
}
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
this[INTERNALS] = {
cookies: cookiesProxy,
url: init.url ? new _nexturl.NextURL(init.url, {
headers: (0, _utils.toNodeOutgoingHttpHeaders)(headers),
nextConfig: init.nextConfig
}) : undefined
};
}
[Symbol.for('edge-runtime.inspect.custom')]() {
return {
cookies: this.cookies,
url: this.url,
// rest of props come from Response
body: this.body,
bodyUsed: this.bodyUsed,
headers: Object.fromEntries(this.headers),
ok: this.ok,
redirected: this.redirected,
status: this.status,
statusText: this.statusText,
type: this.type
};
}
get cookies() {
return this[INTERNALS].cookies;
}
static json(body, init) {
const response = Response.json(body, init);
return new NextResponse(response.body, response);
}
static redirect(url, init) {
const status = typeof init === 'number' ? init : (init == null ? void 0 : init.status) ?? 307;
if (!REDIRECTS.has(status)) {
throw Object.defineProperty(new RangeError('Failed to execute "redirect" on "response": Invalid status code'), "__NEXT_ERROR_CODE", {
value: "E529",
enumerable: false,
configurable: true
});
}
const initObj = typeof init === 'object' ? init : {};
const headers = new Headers(initObj == null ? void 0 : initObj.headers);
headers.set('Location', (0, _utils.validateURL)(url));
return new NextResponse(null, {
...initObj,
headers,
status
});
}
static rewrite(destination, init) {
const headers = new Headers(init == null ? void 0 : init.headers);
headers.set('x-middleware-rewrite', (0, _utils.validateURL)(destination));
handleMiddlewareField(init, headers);
return new NextResponse(null, {
...init,
headers
});
}
static next(init) {
const headers = new Headers(init == null ? void 0 : init.headers);
headers.set('x-middleware-next', '1');
handleMiddlewareField(init, headers);
return new NextResponse(null, {
...init,
headers
});
}
}
//# sourceMappingURL=response.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,24 @@
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
*
* Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)
*/
export declare function revalidateTag(tag: string): void;
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.
*
* Read more: [Next.js Docs: `unstable_expirePath`](https://nextjs.org/docs/app/api-reference/functions/unstable_expirePath)
*/
export declare function unstable_expirePath(originalPath: string, type?: 'layout' | 'page'): void;
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
*
* Read more: [Next.js Docs: `unstable_expireTag`](https://nextjs.org/docs/app/api-reference/functions/unstable_expireTag)
*/
export declare function unstable_expireTag(...tags: string[]): void;
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.
*
* Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)
*/
export declare function revalidatePath(originalPath: string, type?: 'layout' | 'page'): void;

View File

@@ -0,0 +1,144 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
revalidatePath: null,
revalidateTag: null,
unstable_expirePath: null,
unstable_expireTag: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
revalidatePath: function() {
return revalidatePath;
},
revalidateTag: function() {
return revalidateTag;
},
unstable_expirePath: function() {
return unstable_expirePath;
},
unstable_expireTag: function() {
return unstable_expireTag;
}
});
const _dynamicrendering = require("../../app-render/dynamic-rendering");
const _utils = require("../../../shared/lib/router/utils");
const _constants = require("../../../lib/constants");
const _workasyncstorageexternal = require("../../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
const _hooksservercontext = require("../../../client/components/hooks-server-context");
function revalidateTag(tag) {
return revalidate([
tag
], `revalidateTag ${tag}`);
}
function unstable_expirePath(originalPath, type) {
if (originalPath.length > _constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {
console.warn(`Warning: expirePath received "${originalPath}" which exceeded max length of ${_constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/unstable_expirePath`);
return;
}
let normalizedPath = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${originalPath}`;
if (type) {
normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`;
} else if ((0, _utils.isDynamicRoute)(originalPath)) {
console.warn(`Warning: a dynamic page path "${originalPath}" was passed to "expirePath", but the "type" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/unstable_expirePath`);
}
return revalidate([
normalizedPath
], `unstable_expirePath ${originalPath}`);
}
function unstable_expireTag(...tags) {
return revalidate(tags, `unstable_expireTag ${tags.join(', ')}`);
}
function revalidatePath(originalPath, type) {
if (originalPath.length > _constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {
console.warn(`Warning: revalidatePath received "${originalPath}" which exceeded max length of ${_constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);
return;
}
let normalizedPath = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${originalPath}`;
if (type) {
normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`;
} else if ((0, _utils.isDynamicRoute)(originalPath)) {
console.warn(`Warning: a dynamic page path "${originalPath}" was passed to "revalidatePath", but the "type" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);
}
return revalidate([
normalizedPath
], `revalidatePath ${originalPath}`);
}
function revalidate(tags, expression) {
const store = _workasyncstorageexternal.workAsyncStorage.getStore();
if (!store || !store.incrementalCache) {
throw Object.defineProperty(new Error(`Invariant: static generation store missing in ${expression}`), "__NEXT_ERROR_CODE", {
value: "E263",
enumerable: false,
configurable: true
});
}
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw Object.defineProperty(new Error(`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`), "__NEXT_ERROR_CODE", {
value: "E181",
enumerable: false,
configurable: true
});
} else if (workUnitStore.type === 'unstable-cache') {
throw Object.defineProperty(new Error(`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`), "__NEXT_ERROR_CODE", {
value: "E306",
enumerable: false,
configurable: true
});
}
if (workUnitStore.phase === 'render') {
throw Object.defineProperty(new Error(`Route ${store.route} used "${expression}" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`), "__NEXT_ERROR_CODE", {
value: "E7",
enumerable: false,
configurable: true
});
}
if (workUnitStore.type === 'prerender') {
// dynamicIO Prerender
const error = Object.defineProperty(new Error(`Route ${store.route} used ${expression} without first calling \`await connection()\`.`), "__NEXT_ERROR_CODE", {
value: "E406",
enumerable: false,
configurable: true
});
(0, _dynamicrendering.abortAndThrowOnSynchronousRequestDataAccess)(store.route, expression, error, workUnitStore);
} else if (workUnitStore.type === 'prerender-ppr') {
// PPR Prerender
(0, _dynamicrendering.postponeWithTracking)(store.route, expression, workUnitStore.dynamicTracking);
} else if (workUnitStore.type === 'prerender-legacy') {
// legacy Prerender
workUnitStore.revalidate = 0;
const err = Object.defineProperty(new _hooksservercontext.DynamicServerError(`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`), "__NEXT_ERROR_CODE", {
value: "E558",
enumerable: false,
configurable: true
});
store.dynamicUsageDescription = expression;
store.dynamicUsageStack = err.stack;
throw err;
} else if (process.env.NODE_ENV === 'development' && workUnitStore && workUnitStore.type === 'request') {
workUnitStore.usedDynamic = true;
}
}
if (!store.pendingRevalidatedTags) {
store.pendingRevalidatedTags = [];
}
for (const tag of tags){
if (!store.pendingRevalidatedTags.includes(tag)) {
store.pendingRevalidatedTags.push(tag);
}
}
// TODO: only revalidate if the path matches
store.pathWasRevalidated = true;
}
//# sourceMappingURL=revalidate.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,14 @@
type Callback = (...args: any[]) => Promise<any>;
/**
* This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.
*
* Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)
*/
export declare function unstable_cache<T extends Callback>(cb: T, keyParts?: string[], options?: {
/**
* The revalidation interval in seconds.
*/
revalidate?: number | false;
tags?: string[];
}): T;
export {};

View File

@@ -0,0 +1,224 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "unstable_cache", {
enumerable: true,
get: function() {
return unstable_cache;
}
});
const _constants = require("../../../lib/constants");
const _patchfetch = require("../../lib/patch-fetch");
const _workasyncstorageexternal = require("../../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
const _responsecache = require("../../response-cache");
let noStoreFetchIdx = 0;
async function cacheNewResult(result, incrementalCache, cacheKey, tags, revalidate, fetchIdx, fetchUrl) {
await incrementalCache.set(cacheKey, {
kind: _responsecache.CachedRouteKind.FETCH,
data: {
headers: {},
// TODO: handle non-JSON values?
body: JSON.stringify(result),
status: 200,
url: ''
},
revalidate: typeof revalidate !== 'number' ? _constants.CACHE_ONE_YEAR : revalidate
}, {
fetchCache: true,
tags,
fetchIdx,
fetchUrl
});
return;
}
function unstable_cache(cb, keyParts, options = {}) {
if (options.revalidate === 0) {
throw Object.defineProperty(new Error(`Invariant revalidate: 0 can not be passed to unstable_cache(), must be "false" or "> 0" ${cb.toString()}`), "__NEXT_ERROR_CODE", {
value: "E57",
enumerable: false,
configurable: true
});
}
// Validate the tags provided are valid
const tags = options.tags ? (0, _patchfetch.validateTags)(options.tags, `unstable_cache ${cb.toString()}`) : [];
// Validate the revalidate options
(0, _patchfetch.validateRevalidate)(options.revalidate, `unstable_cache ${cb.name || cb.toString()}`);
// Stash the fixed part of the key at construction time. The invocation key will combine
// the fixed key with the arguments when actually called
// @TODO if cb.toString() is long we should hash it
// @TODO come up with a collision-free way to combine keyParts
// @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees
// and the error produced by accidentally using something that cannot be safely coerced is likely
// hard to debug
const fixedKey = `${cb.toString()}-${Array.isArray(keyParts) && keyParts.join(',')}`;
const cachedCb = async (...args)=>{
const workStore = _workasyncstorageexternal.workAsyncStorage.getStore();
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
// We must be able to find the incremental cache otherwise we throw
const maybeIncrementalCache = (workStore == null ? void 0 : workStore.incrementalCache) || globalThis.__incrementalCache;
if (!maybeIncrementalCache) {
throw Object.defineProperty(new Error(`Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`), "__NEXT_ERROR_CODE", {
value: "E469",
enumerable: false,
configurable: true
});
}
const incrementalCache = maybeIncrementalCache;
const cacheSignal = workUnitStore && workUnitStore.type === 'prerender' ? workUnitStore.cacheSignal : null;
if (cacheSignal) {
cacheSignal.beginRead();
}
try {
// If there's no request store, we aren't in a request (or we're not in app
// router) and if there's no static generation store, we aren't in app
// router. Default to an empty pathname and search params when there's no
// request store or static generation store available.
const requestStore = workUnitStore && workUnitStore.type === 'request' ? workUnitStore : undefined;
const pathname = (requestStore == null ? void 0 : requestStore.url.pathname) ?? (workStore == null ? void 0 : workStore.route) ?? '';
const searchParams = new URLSearchParams((requestStore == null ? void 0 : requestStore.url.search) ?? '');
const sortedSearchKeys = [
...searchParams.keys()
].sort((a, b)=>{
return a.localeCompare(b);
});
const sortedSearch = sortedSearchKeys.map((key)=>`${key}=${searchParams.get(key)}`).join('&');
// Construct the complete cache key for this function invocation
// @TODO stringify is likely not safe here. We will coerce undefined to null which will make
// the keyspace smaller than the execution space
const invocationKey = `${fixedKey}-${JSON.stringify(args)}`;
const cacheKey = await incrementalCache.generateCacheKey(invocationKey);
// $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse
const fetchUrl = `unstable_cache ${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch} ${cb.name ? ` ${cb.name}` : cacheKey}`;
const fetchIdx = (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1;
const implicitTags = workUnitStore == null ? void 0 : workUnitStore.implicitTags;
const innerCacheStore = {
type: 'unstable-cache',
phase: 'render',
implicitTags,
draftMode: workUnitStore && workStore && (0, _workunitasyncstorageexternal.getDraftModeProviderForCacheScope)(workStore, workUnitStore)
};
if (workStore) {
workStore.nextFetchId = fetchIdx + 1;
// We are in an App Router context. We try to return the cached entry if it exists and is valid
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
// the background. If the entry is missing or invalid we generate a new entry and return it.
// We update the store's revalidate property if the option.revalidate is a higher precedence
if (workUnitStore && (workUnitStore.type === 'cache' || workUnitStore.type === 'prerender' || workUnitStore.type === 'prerender-ppr' || workUnitStore.type === 'prerender-legacy')) {
// options.revalidate === undefined doesn't affect timing.
// options.revalidate === false doesn't shrink timing. it stays at the maximum.
if (typeof options.revalidate === 'number') {
if (workUnitStore.revalidate < options.revalidate) {
// The store is already revalidating on a shorter time interval, leave it alone
} else {
workUnitStore.revalidate = options.revalidate;
}
}
// We need to accumulate the tags for this invocation within the store
const collectedTags = workUnitStore.tags;
if (collectedTags === null) {
workUnitStore.tags = tags.slice();
} else {
for (const tag of tags){
// @TODO refactor tags to be a set to avoid this O(n) lookup
if (!collectedTags.includes(tag)) {
collectedTags.push(tag);
}
}
}
}
const isNestedUnstableCache = workUnitStore && workUnitStore.type === 'unstable-cache';
if (// when we are nested inside of other unstable_cache's
// we should bypass cache similar to fetches
!isNestedUnstableCache && workStore.fetchCache !== 'force-no-store' && !workStore.isOnDemandRevalidate && !incrementalCache.isOnDemandRevalidate && !workStore.isDraftMode) {
// We attempt to get the current cache entry from the incremental cache.
const cacheEntry = await incrementalCache.get(cacheKey, {
kind: _responsecache.IncrementalCacheKind.FETCH,
revalidate: options.revalidate,
tags,
softTags: implicitTags == null ? void 0 : implicitTags.tags,
fetchIdx,
fetchUrl
});
if (cacheEntry && cacheEntry.value) {
// The entry exists and has a value
if (cacheEntry.value.kind !== _responsecache.CachedRouteKind.FETCH) {
// The entry is invalid and we need a special warning
// @TODO why do we warn this way? Should this just be an error? How are these errors surfaced
// so bugs can be reported
// @TODO the invocation key can have sensitive data in it. we should not log this entire object
console.error(`Invariant invalid cacheEntry returned for ${invocationKey}`);
// will fall through to generating a new cache entry below
} else {
// We have a valid cache entry so we will be returning it. We also check to see if we need
// to background revalidate it by checking if it is stale.
const cachedResponse = cacheEntry.value.data.body !== undefined ? JSON.parse(cacheEntry.value.data.body) : undefined;
if (cacheEntry.isStale) {
// In App Router we return the stale result and revalidate in the background
if (!workStore.pendingRevalidates) {
workStore.pendingRevalidates = {};
}
// We run the cache function asynchronously and save the result when it completes
workStore.pendingRevalidates[invocationKey] = _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args).then((result)=>{
return cacheNewResult(result, incrementalCache, cacheKey, tags, options.revalidate, fetchIdx, fetchUrl);
})// @TODO This error handling seems wrong. We swallow the error?
.catch((err)=>console.error(`revalidating cache with key: ${invocationKey}`, err));
}
// We had a valid cache entry so we return it here
return cachedResponse;
}
}
}
// If we got this far then we had an invalid cache entry and need to generate a new one
const result = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args);
if (!workStore.isDraftMode) {
cacheNewResult(result, incrementalCache, cacheKey, tags, options.revalidate, fetchIdx, fetchUrl);
}
return result;
} else {
noStoreFetchIdx += 1;
// We are in Pages Router or were called outside of a render. We don't have a store
// so we just call the callback directly when it needs to run.
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
// the background. If the entry is missing or invalid we generate a new entry and return it.
if (!incrementalCache.isOnDemandRevalidate) {
// We aren't doing an on demand revalidation so we check use the cache if valid
const cacheEntry = await incrementalCache.get(cacheKey, {
kind: _responsecache.IncrementalCacheKind.FETCH,
revalidate: options.revalidate,
tags,
fetchIdx,
fetchUrl,
softTags: implicitTags == null ? void 0 : implicitTags.tags
});
if (cacheEntry && cacheEntry.value) {
// The entry exists and has a value
if (cacheEntry.value.kind !== _responsecache.CachedRouteKind.FETCH) {
// The entry is invalid and we need a special warning
// @TODO why do we warn this way? Should this just be an error? How are these errors surfaced
// so bugs can be reported
console.error(`Invariant invalid cacheEntry returned for ${invocationKey}`);
// will fall through to generating a new cache entry below
} else if (!cacheEntry.isStale) {
// We have a valid cache entry and it is fresh so we return it
return cacheEntry.value.data.body !== undefined ? JSON.parse(cacheEntry.value.data.body) : undefined;
}
}
}
// If we got this far then we had an invalid cache entry and need to generate a new one
const result = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args);
cacheNewResult(result, incrementalCache, cacheKey, tags, options.revalidate, fetchIdx, fetchUrl);
return result;
}
} finally{
if (cacheSignal) {
cacheSignal.endRead();
}
}
};
// TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary
return cachedCb;
}
//# sourceMappingURL=unstable-cache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,16 @@
/**
* This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.
*
* It marks the current scope as dynamic.
*
* - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render
* halt and mark the page as dynamic.
* - In PPR cases this will postpone the render at this location.
*
* If we are inside a cache scope then this function does nothing.
*
* @note It expects to be called within App Router and will error otherwise.
*
* Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)
*/
export declare function unstable_noStore(): void;

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "unstable_noStore", {
enumerable: true,
get: function() {
return unstable_noStore;
}
});
const _workasyncstorageexternal = require("../../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
const _dynamicrendering = require("../../app-render/dynamic-rendering");
function unstable_noStore() {
const callingExpression = 'unstable_noStore()';
const store = _workasyncstorageexternal.workAsyncStorage.getStore();
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
if (!store) {
// This generally implies we are being called in Pages router. We should probably not support
// unstable_noStore in contexts outside of `react-server` condition but since we historically
// have not errored here previously, we maintain that behavior for now.
return;
} else if (store.forceStatic) {
return;
} else {
store.isUnstableNoStore = true;
if (workUnitStore && workUnitStore.type === 'prerender') {
// unstable_noStore() is a noop in Dynamic I/O.
} else {
(0, _dynamicrendering.markCurrentScopeAsDynamic)(store, workUnitStore, callingExpression);
}
}
}
//# sourceMappingURL=unstable-no-store.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-no-store.ts"],"sourcesContent":["import { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'\n\n/**\n * This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.\n *\n * It marks the current scope as dynamic.\n *\n * - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render\n * halt and mark the page as dynamic.\n * - In PPR cases this will postpone the render at this location.\n *\n * If we are inside a cache scope then this function does nothing.\n *\n * @note It expects to be called within App Router and will error otherwise.\n *\n * Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)\n */\nexport function unstable_noStore() {\n const callingExpression = 'unstable_noStore()'\n const store = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!store) {\n // This generally implies we are being called in Pages router. We should probably not support\n // unstable_noStore in contexts outside of `react-server` condition but since we historically\n // have not errored here previously, we maintain that behavior for now.\n return\n } else if (store.forceStatic) {\n return\n } else {\n store.isUnstableNoStore = true\n if (workUnitStore && workUnitStore.type === 'prerender') {\n // unstable_noStore() is a noop in Dynamic I/O.\n } else {\n markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)\n }\n }\n}\n"],"names":["unstable_noStore","callingExpression","store","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","forceStatic","isUnstableNoStore","type","markCurrentScopeAsDynamic"],"mappings":";;;;+BAmBgBA;;;eAAAA;;;0CAnBiB;8CACI;kCACK;AAiBnC,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,QAAQC,0CAAgB,CAACC,QAAQ;IACvC,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAI,CAACF,OAAO;QACV,6FAA6F;QAC7F,6FAA6F;QAC7F,uEAAuE;QACvE;IACF,OAAO,IAAIA,MAAMK,WAAW,EAAE;QAC5B;IACF,OAAO;QACLL,MAAMM,iBAAiB,GAAG;QAC1B,IAAIH,iBAAiBA,cAAcI,IAAI,KAAK,aAAa;QACvD,+CAA+C;QACjD,OAAO;YACLC,IAAAA,2CAAyB,EAACR,OAAOG,eAAeJ;QAClD;IACF;AACF"}

View File

@@ -0,0 +1,2 @@
declare const GlobalURLPattern: any;
export { GlobalURLPattern as URLPattern };

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "URLPattern", {
enumerable: true,
get: function() {
return GlobalURLPattern;
}
});
const GlobalURLPattern = // @ts-expect-error: URLPattern is not available in Node.js
typeof URLPattern === 'undefined' ? undefined : URLPattern;
//# sourceMappingURL=url-pattern.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/url-pattern.ts"],"sourcesContent":["const GlobalURLPattern =\n // @ts-expect-error: URLPattern is not available in Node.js\n typeof URLPattern === 'undefined' ? undefined : URLPattern\n\nexport { GlobalURLPattern as URLPattern }\n"],"names":["URLPattern","GlobalURLPattern","undefined"],"mappings":";;;;+BAI6BA;;;eAApBC;;;AAJT,MAAMA,mBACJ,2DAA2D;AAC3D,OAAOD,eAAe,cAAcE,YAAYF"}

View File

@@ -0,0 +1,31 @@
interface UserAgent {
isBot: boolean;
ua: string;
browser: {
name?: string;
version?: string;
major?: string;
};
device: {
model?: string;
type?: string;
vendor?: string;
};
engine: {
name?: string;
version?: string;
};
os: {
name?: string;
version?: string;
};
cpu: {
architecture?: string;
};
}
export declare function isBot(input: string): boolean;
export declare function userAgentFromString(input: string | undefined): UserAgent;
export declare function userAgent({ headers }: {
headers: Headers;
}): UserAgent;
export {};

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
isBot: null,
userAgent: null,
userAgentFromString: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
isBot: function() {
return isBot;
},
userAgent: function() {
return userAgent;
},
userAgentFromString: function() {
return userAgentFromString;
}
});
const _uaparserjs = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/ua-parser-js"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function isBot(input) {
return /Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(input);
}
function userAgentFromString(input) {
return {
...(0, _uaparserjs.default)(input),
isBot: input === undefined ? false : isBot(input)
};
}
function userAgent({ headers }) {
return userAgentFromString(headers.get('user-agent') || undefined);
}
//# sourceMappingURL=user-agent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/user-agent.ts"],"sourcesContent":["import parseua from 'next/dist/compiled/ua-parser-js'\n\ninterface UserAgent {\n isBot: boolean\n ua: string\n browser: {\n name?: string\n version?: string\n major?: string\n }\n device: {\n model?: string\n type?: string\n vendor?: string\n }\n engine: {\n name?: string\n version?: string\n }\n os: {\n name?: string\n version?: string\n }\n cpu: {\n architecture?: string\n }\n}\n\nexport function isBot(input: string): boolean {\n return /Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(\n input\n )\n}\n\nexport function userAgentFromString(input: string | undefined): UserAgent {\n return {\n ...parseua(input),\n isBot: input === undefined ? false : isBot(input),\n }\n}\n\nexport function userAgent({ headers }: { headers: Headers }): UserAgent {\n return userAgentFromString(headers.get('user-agent') || undefined)\n}\n"],"names":["isBot","userAgent","userAgentFromString","input","test","parseua","undefined","headers","get"],"mappings":";;;;;;;;;;;;;;;;IA4BgBA,KAAK;eAALA;;IAaAC,SAAS;eAATA;;IAPAC,mBAAmB;eAAnBA;;;mEAlCI;;;;;;AA4Bb,SAASF,MAAMG,KAAa;IACjC,OAAO,0WAA0WC,IAAI,CACnXD;AAEJ;AAEO,SAASD,oBAAoBC,KAAyB;IAC3D,OAAO;QACL,GAAGE,IAAAA,mBAAO,EAACF,MAAM;QACjBH,OAAOG,UAAUG,YAAY,QAAQN,MAAMG;IAC7C;AACF;AAEO,SAASF,UAAU,EAAEM,OAAO,EAAwB;IACzD,OAAOL,oBAAoBK,QAAQC,GAAG,CAAC,iBAAiBF;AAC1D"}

View File

@@ -0,0 +1,47 @@
import type { ExperimentalConfig, I18NConfig } from '../config-shared';
import type { NextRequest } from './spec-extension/request';
import type { NextFetchEvent } from './spec-extension/fetch-event';
import type { NextResponse } from './spec-extension/response';
import type { CloneableBody } from '../body-streams';
import type { OutgoingHttpHeaders } from 'http';
import type { FetchMetrics } from '../base-http';
export type { MiddlewareConfigInput as MiddlewareConfig } from '../../build/segment-config/middleware/middleware-config';
export interface RequestData {
headers: OutgoingHttpHeaders;
method: string;
nextConfig?: {
basePath?: string;
i18n?: I18NConfig | null;
trailingSlash?: boolean;
experimental?: Pick<ExperimentalConfig, 'cacheLife' | 'authInterrupts'>;
};
page?: {
name?: string;
params?: {
[key: string]: string | string[] | undefined;
};
};
url: string;
body?: ReadableStream<Uint8Array>;
signal: AbortSignal;
/** passed in when running in edge runtime sandbox */
waitUntil?: (promise: Promise<any>) => void;
}
export type NodejsRequestData = Omit<RequestData, 'body'> & {
body?: CloneableBody;
};
export interface FetchEventResult {
response: Response;
waitUntil: Promise<any>;
fetchMetrics?: FetchMetrics;
}
export type NextMiddlewareResult = NextResponse | Response | null | undefined | void;
/**
* Middleware allows you to run code before a request is completed.
* Then, based on the incoming request, you can modify the response
* by rewriting, redirecting, modifying the request or response headers,
* or responding directly.
*
* Read more: [Next.js Docs: Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware)
*/
export type NextMiddleware = (request: NextRequest, event: NextFetchEvent) => NextMiddlewareResult | Promise<NextMiddlewareResult>;

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":""}

View File

@@ -0,0 +1,29 @@
import type { OutgoingHttpHeaders } from 'http';
/**
* Converts a Node.js IncomingHttpHeaders object to a Headers object. Any
* headers with multiple values will be joined with a comma and space. Any
* headers that have an undefined value will be ignored and others will be
* coerced to strings.
*
* @param nodeHeaders the headers object to convert
* @returns the converted headers object
*/
export declare function fromNodeOutgoingHttpHeaders(nodeHeaders: OutgoingHttpHeaders): Headers;
export declare function splitCookiesString(cookiesString: string): string[];
/**
* Converts a Headers object to a Node.js OutgoingHttpHeaders object. This is
* required to support the set-cookie header, which may have multiple values.
*
* @param headers the headers object to convert
* @returns the converted headers object
*/
export declare function toNodeOutgoingHttpHeaders(headers: Headers): OutgoingHttpHeaders;
/**
* Validate the correctness of a user-provided URL.
*/
export declare function validateURL(url: string | URL): string;
/**
* Normalizes `nxtP` and `nxtI` query param values to remove the prefix.
* This function does not mutate the input key.
*/
export declare function normalizeNextQueryParam(key: string): null | string;

View File

@@ -0,0 +1,151 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
fromNodeOutgoingHttpHeaders: null,
normalizeNextQueryParam: null,
splitCookiesString: null,
toNodeOutgoingHttpHeaders: null,
validateURL: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
fromNodeOutgoingHttpHeaders: function() {
return fromNodeOutgoingHttpHeaders;
},
normalizeNextQueryParam: function() {
return normalizeNextQueryParam;
},
splitCookiesString: function() {
return splitCookiesString;
},
toNodeOutgoingHttpHeaders: function() {
return toNodeOutgoingHttpHeaders;
},
validateURL: function() {
return validateURL;
}
});
const _constants = require("../../lib/constants");
function fromNodeOutgoingHttpHeaders(nodeHeaders) {
const headers = new Headers();
for (let [key, value] of Object.entries(nodeHeaders)){
const values = Array.isArray(value) ? value : [
value
];
for (let v of values){
if (typeof v === 'undefined') continue;
if (typeof v === 'number') {
v = v.toString();
}
headers.append(key, v);
}
}
return headers;
}
function splitCookiesString(cookiesString) {
var cookiesStrings = [];
var pos = 0;
var start;
var ch;
var lastComma;
var nextStart;
var cookiesSeparatorFound;
function skipWhitespace() {
while(pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))){
pos += 1;
}
return pos < cookiesString.length;
}
function notSpecialChar() {
ch = cookiesString.charAt(pos);
return ch !== '=' && ch !== ';' && ch !== ',';
}
while(pos < cookiesString.length){
start = pos;
cookiesSeparatorFound = false;
while(skipWhitespace()){
ch = cookiesString.charAt(pos);
if (ch === ',') {
// ',' is a cookie separator if we have later first '=', not ';' or ','
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while(pos < cookiesString.length && notSpecialChar()){
pos += 1;
}
// currently special character
if (pos < cookiesString.length && cookiesString.charAt(pos) === '=') {
// we found cookies separator
cookiesSeparatorFound = true;
// pos is inside the next cookie, so back up and return it.
pos = nextStart;
cookiesStrings.push(cookiesString.substring(start, lastComma));
start = pos;
} else {
// in param ',' or param separator ';',
// we continue from that comma
pos = lastComma + 1;
}
} else {
pos += 1;
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
}
}
return cookiesStrings;
}
function toNodeOutgoingHttpHeaders(headers) {
const nodeHeaders = {};
const cookies = [];
if (headers) {
for (const [key, value] of headers.entries()){
if (key.toLowerCase() === 'set-cookie') {
// We may have gotten a comma joined string of cookies, or multiple
// set-cookie headers. We need to merge them into one header array
// to represent all the cookies.
cookies.push(...splitCookiesString(value));
nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies;
} else {
nodeHeaders[key] = value;
}
}
}
return nodeHeaders;
}
function validateURL(url) {
try {
return String(new URL(String(url)));
} catch (error) {
throw Object.defineProperty(new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, {
cause: error
}), "__NEXT_ERROR_CODE", {
value: "E61",
enumerable: false,
configurable: true
});
}
}
function normalizeNextQueryParam(key) {
const prefixes = [
_constants.NEXT_QUERY_PARAM_PREFIX,
_constants.NEXT_INTERCEPTION_MARKER_PREFIX
];
for (const prefix of prefixes){
if (key !== prefix && key.startsWith(prefix)) {
return key.substring(prefix.length);
}
}
return null;
}
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
/** Monitor when the consumer finishes reading the response body.
that's as close as we can get to `res.on('close')` using web APIs.
*/
export declare function trackBodyConsumed(body: string | ReadableStream, onEnd: () => void): BodyInit;
export declare function trackStreamConsumed<TChunk>(stream: ReadableStream<TChunk>, onEnd: () => void): ReadableStream<TChunk>;
export declare class CloseController {
private target;
listeners: number;
isClosed: boolean;
onClose(callback: () => void): void;
dispatchClose(): void;
}

View File

@@ -0,0 +1,87 @@
/** Monitor when the consumer finishes reading the response body.
that's as close as we can get to `res.on('close')` using web APIs.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
CloseController: null,
trackBodyConsumed: null,
trackStreamConsumed: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
CloseController: function() {
return CloseController;
},
trackBodyConsumed: function() {
return trackBodyConsumed;
},
trackStreamConsumed: function() {
return trackStreamConsumed;
}
});
function trackBodyConsumed(body, onEnd) {
if (typeof body === 'string') {
const generator = async function* generate() {
const encoder = new TextEncoder();
yield encoder.encode(body);
onEnd();
};
// @ts-expect-error BodyInit typings doesn't seem to include AsyncIterables even though it's supported in practice
return generator();
} else {
return trackStreamConsumed(body, onEnd);
}
}
function trackStreamConsumed(stream, onEnd) {
// NOTE: This function must handle `stream` being aborted or cancelled,
// so it can't just be this:
//
// return stream.pipeThrough(new TransformStream({ flush() { onEnd() } }))
//
// because that doesn't handle cancellations.
// (and cancellation handling via `Transformer.cancel` is only available in node >20)
const dest = new TransformStream();
const runOnEnd = ()=>onEnd();
stream.pipeTo(dest.writable).then(runOnEnd, runOnEnd);
return dest.readable;
}
class CloseController {
onClose(callback) {
if (this.isClosed) {
throw Object.defineProperty(new Error('Cannot subscribe to a closed CloseController'), "__NEXT_ERROR_CODE", {
value: "E365",
enumerable: false,
configurable: true
});
}
this.target.addEventListener('close', callback);
this.listeners++;
}
dispatchClose() {
if (this.isClosed) {
throw Object.defineProperty(new Error('Cannot close a CloseController multiple times'), "__NEXT_ERROR_CODE", {
value: "E229",
enumerable: false,
configurable: true
});
}
if (this.listeners > 0) {
this.target.dispatchEvent(new Event('close'));
}
this.isClosed = true;
}
constructor(){
this.target = new EventTarget();
this.listeners = 0;
this.isClosed = false;
}
}
//# sourceMappingURL=web-on-close.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/web-on-close.ts"],"sourcesContent":["/** Monitor when the consumer finishes reading the response body.\nthat's as close as we can get to `res.on('close')` using web APIs.\n*/\nexport function trackBodyConsumed(\n body: string | ReadableStream,\n onEnd: () => void\n): BodyInit {\n if (typeof body === 'string') {\n const generator = async function* generate() {\n const encoder = new TextEncoder()\n yield encoder.encode(body)\n onEnd()\n }\n // @ts-expect-error BodyInit typings doesn't seem to include AsyncIterables even though it's supported in practice\n return generator()\n } else {\n return trackStreamConsumed(body, onEnd)\n }\n}\n\nexport function trackStreamConsumed<TChunk>(\n stream: ReadableStream<TChunk>,\n onEnd: () => void\n): ReadableStream<TChunk> {\n // NOTE: This function must handle `stream` being aborted or cancelled,\n // so it can't just be this:\n //\n // return stream.pipeThrough(new TransformStream({ flush() { onEnd() } }))\n //\n // because that doesn't handle cancellations.\n // (and cancellation handling via `Transformer.cancel` is only available in node >20)\n const dest = new TransformStream()\n const runOnEnd = () => onEnd()\n stream.pipeTo(dest.writable).then(runOnEnd, runOnEnd)\n return dest.readable\n}\n\nexport class CloseController {\n private target = new EventTarget()\n listeners = 0\n isClosed = false\n\n onClose(callback: () => void) {\n if (this.isClosed) {\n throw new Error('Cannot subscribe to a closed CloseController')\n }\n\n this.target.addEventListener('close', callback)\n this.listeners++\n }\n\n dispatchClose() {\n if (this.isClosed) {\n throw new Error('Cannot close a CloseController multiple times')\n }\n if (this.listeners > 0) {\n this.target.dispatchEvent(new Event('close'))\n }\n this.isClosed = true\n }\n}\n"],"names":["CloseController","trackBodyConsumed","trackStreamConsumed","body","onEnd","generator","generate","encoder","TextEncoder","encode","stream","dest","TransformStream","runOnEnd","pipeTo","writable","then","readable","onClose","callback","isClosed","Error","target","addEventListener","listeners","dispatchClose","dispatchEvent","Event","EventTarget"],"mappings":"AAAA;;AAEA;;;;;;;;;;;;;;;;IAmCaA,eAAe;eAAfA;;IAlCGC,iBAAiB;eAAjBA;;IAiBAC,mBAAmB;eAAnBA;;;AAjBT,SAASD,kBACdE,IAA6B,EAC7BC,KAAiB;IAEjB,IAAI,OAAOD,SAAS,UAAU;QAC5B,MAAME,YAAY,gBAAgBC;YAChC,MAAMC,UAAU,IAAIC;YACpB,MAAMD,QAAQE,MAAM,CAACN;YACrBC;QACF;QACA,kHAAkH;QAClH,OAAOC;IACT,OAAO;QACL,OAAOH,oBAAoBC,MAAMC;IACnC;AACF;AAEO,SAASF,oBACdQ,MAA8B,EAC9BN,KAAiB;IAEjB,uEAAuE;IACvE,4BAA4B;IAC5B,EAAE;IACF,4EAA4E;IAC5E,EAAE;IACF,6CAA6C;IAC7C,qFAAqF;IACrF,MAAMO,OAAO,IAAIC;IACjB,MAAMC,WAAW,IAAMT;IACvBM,OAAOI,MAAM,CAACH,KAAKI,QAAQ,EAAEC,IAAI,CAACH,UAAUA;IAC5C,OAAOF,KAAKM,QAAQ;AACtB;AAEO,MAAMjB;IAKXkB,QAAQC,QAAoB,EAAE;QAC5B,IAAI,IAAI,CAACC,QAAQ,EAAE;YACjB,MAAM,qBAAyD,CAAzD,IAAIC,MAAM,iDAAV,qBAAA;uBAAA;4BAAA;8BAAA;YAAwD;QAChE;QAEA,IAAI,CAACC,MAAM,CAACC,gBAAgB,CAAC,SAASJ;QACtC,IAAI,CAACK,SAAS;IAChB;IAEAC,gBAAgB;QACd,IAAI,IAAI,CAACL,QAAQ,EAAE;YACjB,MAAM,qBAA0D,CAA1D,IAAIC,MAAM,kDAAV,qBAAA;uBAAA;4BAAA;8BAAA;YAAyD;QACjE;QACA,IAAI,IAAI,CAACG,SAAS,GAAG,GAAG;YACtB,IAAI,CAACF,MAAM,CAACI,aAAa,CAAC,IAAIC,MAAM;QACtC;QACA,IAAI,CAACP,QAAQ,GAAG;IAClB;;aArBQE,SAAS,IAAIM;aACrBJ,YAAY;aACZJ,WAAW;;AAoBb"}