fix docker and nginx file

This commit is contained in:
2026-07-14 12:28:24 +05:30
parent fea3017013
commit 0d243fc174
2522 changed files with 745707 additions and 1 deletions

View File

@@ -0,0 +1,15 @@
// This is a minimal import that initializes the node
// environment, it is traced automatically for entries
// and can be used to ensure Node.js APIs are setup
// as expected without require `next-server`
"use strict";
if (process.env.NEXT_RUNTIME !== 'edge') {
// eslint-disable-next-line @next/internal/typechecked-require
require('next/dist/server/node-environment');
// eslint-disable-next-line @next/internal/typechecked-require
require('next/dist/server/require-hook');
// eslint-disable-next-line @next/internal/typechecked-require
require('next/dist/server/node-polyfill-crypto');
}
//# sourceMappingURL=setup-node-env.external.js.map

View File

@@ -0,0 +1,255 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getDefineEnv", {
enumerable: true,
get: function() {
return getDefineEnv;
}
});
const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
const _needsexperimentalreact = require("../lib/needs-experimental-react");
const _ppr = require("../server/lib/experimental/ppr");
const _staticenv = require("../lib/static-env");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION');
/**
* Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.
*/ function serializeDefineEnv(defineEnv) {
const defineEnvStringified = Object.fromEntries(Object.entries(defineEnv).map(([key, value])=>[
key,
typeof value === 'object' && DEFINE_ENV_EXPRESSION in value ? value[DEFINE_ENV_EXPRESSION] : JSON.stringify(value)
]));
return defineEnvStringified;
}
function getImageConfig(config, dev) {
var _config_images, _config_images1, _config_images2;
return {
'process.env.__NEXT_IMAGE_OPTS': {
deviceSizes: config.images.deviceSizes,
imageSizes: config.images.imageSizes,
qualities: config.images.qualities,
path: config.images.path,
loader: config.images.loader,
dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,
unoptimized: config == null ? void 0 : (_config_images = config.images) == null ? void 0 : _config_images.unoptimized,
...dev ? {
// additional config in dev to allow validating on the client
domains: config.images.domains,
remotePatterns: (_config_images1 = config.images) == null ? void 0 : _config_images1.remotePatterns,
localPatterns: (_config_images2 = config.images) == null ? void 0 : _config_images2.localPatterns,
output: config.output
} : {}
}
};
}
function getDefineEnv({ isTurbopack, clientRouterFilters, config, dev, distDir, projectPath, fetchCacheKeyPrefix, hasRewrites, isClient, isEdgeServer, isNodeServer, middlewareMatchers, omitNonDeterministic, rewrites }) {
var _config_experimental, _config_experimental1, _config_experimental_staleTimes, _config_experimental_staleTimes1, _config_experimental_staleTimes2, _config_experimental_staleTimes3, _config_i18n, _config_compiler;
const nextPublicEnv = (0, _staticenv.getNextPublicEnvironmentVariables)();
const nextConfigEnv = (0, _staticenv.getNextConfigEnv)(config);
const isPPREnabled = (0, _ppr.checkIsAppPPREnabled)(config.experimental.ppr);
const isCacheComponentsEnabled = !!config.cacheComponents;
const isUseCacheEnabled = !!config.experimental.useCache;
const defineEnv = {
// internal field to identify the plugin config
__NEXT_DEFINE_ENV: true,
...nextPublicEnv,
...nextConfigEnv,
...!isEdgeServer ? {} : {
EdgeRuntime: /**
* Cloud providers can set this environment variable to allow users
* and library authors to have different implementations based on
* the runtime they are running with, if it's not using `edge-runtime`
*/ process.env.NEXT_EDGE_RUNTIME_PROVIDER ?? 'edge-runtime',
// process should be only { env: {...} } for edge runtime.
// For ignore avoid warn on `process.emit` usage but directly omit it.
'process.emit': false
},
'process.turbopack': isTurbopack,
'process.env.TURBOPACK': isTurbopack,
'process.env.__NEXT_BUNDLER': isTurbopack ? 'Turbopack' : process.env.NEXT_RSPACK ? 'Rspack' : 'Webpack',
// TODO: enforce `NODE_ENV` on `process.env`, and add a test:
'process.env.NODE_ENV': dev || config.experimental.allowDevelopmentBuild ? 'development' : 'production',
'process.env.__NEXT_DEV_SERVER': dev ? '1' : '',
'process.env.NEXT_RUNTIME': isEdgeServer ? 'edge' : isNodeServer ? 'nodejs' : '',
'process.env.NEXT_MINIMAL': '',
'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(config.experimental.appNavFailHandling),
'process.env.__NEXT_APP_NEW_SCROLL_HANDLER': Boolean(config.experimental.appNewScrollHandler),
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(config.experimental.cachedNavigations),
'process.env.__NEXT_INSTANT_NAV_TOGGLE': !!config.experimental.instantNavigationDevToolsToggle,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
'process.env.NEXT_IMMUTABLE_ASSET_TOKEN': config.experimental.immutableAssetToken || '',
...((_config_experimental = config.experimental) == null ? void 0 : _config_experimental.useSkewCookie) || !config.deploymentId ? {
'process.env.NEXT_DEPLOYMENT_ID': false
} : isClient ? isTurbopack ? {
// This is set at runtime by packages/next/src/client/register-deployment-id-global.ts
'process.env.NEXT_DEPLOYMENT_ID': {
[DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID'
}
} : {
// For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID
// approach because we cannot forward this global variable to web workers easily.
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false
} : ((_config_experimental1 = config.experimental) == null ? void 0 : _config_experimental1.runtimeServerDeploymentId) ? {
} : {
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false
},
// Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment
// variable to the client.
'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING': process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING || false,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',
...isTurbopack ? {} : {
'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? []
},
'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH': config.experimental.manualClientBasePath ?? false,
'process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME': JSON.stringify(isNaN(Number((_config_experimental_staleTimes = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes.dynamic)) ? 0 : (_config_experimental_staleTimes1 = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes1.dynamic),
'process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME': JSON.stringify(isNaN(Number((_config_experimental_staleTimes2 = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes2.static)) ? 5 * 60 // 5 minutes
: (_config_experimental_staleTimes3 = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes3.static),
'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED': config.experimental.clientRouterFilter ?? true,
'process.env.__NEXT_CLIENT_ROUTER_S_FILTER': (clientRouterFilters == null ? void 0 : clientRouterFilters.staticFilter) ?? false,
'process.env.__NEXT_CLIENT_ROUTER_D_FILTER': (clientRouterFilters == null ? void 0 : clientRouterFilters.dynamicFilter) ?? false,
'process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS': Boolean(config.experimental.validateRSCRequestHeaders),
'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(config.experimental.dynamicOnHover),
'process.env.__NEXT_PREFETCH_INLINING': Boolean(config.experimental.prefetchInlining),
'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE': config.experimental.optimisticClientCache ?? true,
'process.env.__NEXT_MIDDLEWARE_PREFETCH': config.experimental.proxyPrefetch ?? 'flexible',
'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,
'process.browser': isClient,
'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
...dev && (isClient ?? isEdgeServer) ? {
'process.env.__NEXT_DIST_DIR': distDir
} : {},
// This is used in devtools to strip the project path in edge runtime,
// as there's only a dummy `dir` value (`.`) as edge runtime doesn't have concept of file system.
...dev && isEdgeServer ? {
'process.env.__NEXT_EDGE_PROJECT_DIR': isTurbopack ? _nodepath.default.relative(process.cwd(), projectPath) : projectPath
} : {},
'process.env.__NEXT_BASE_PATH': config.basePath,
'process.env.__NEXT_CASE_SENSITIVE_ROUTES': Boolean(config.experimental.caseSensitiveRoutes),
'process.env.__NEXT_REWRITES': rewrites,
'process.env.__NEXT_TRAILING_SLASH': config.trailingSlash,
'process.env.__NEXT_DEV_INDICATOR': config.devIndicators !== false,
'process.env.__NEXT_DEV_INDICATOR_POSITION': config.devIndicators === false ? 'bottom-left' // This will not be used as the indicator is disabled.
: config.devIndicators.position ?? 'bottom-left',
'process.env.__NEXT_STRICT_MODE': config.reactStrictMode === null ? false : config.reactStrictMode,
'process.env.__NEXT_STRICT_MODE_APP': // When next.config.js does not have reactStrictMode it's enabled by default.
config.reactStrictMode === null ? true : config.reactStrictMode,
'process.env.__NEXT_OPTIMIZE_CSS': (config.experimental.optimizeCss && !dev) ?? false,
'process.env.__NEXT_SCRIPT_WORKERS': (config.experimental.nextScriptWorkers && !dev) ?? false,
'process.env.__NEXT_SCROLL_RESTORATION': config.experimental.scrollRestoration ?? false,
...getImageConfig(config, dev),
'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,
'process.env.__NEXT_HAS_REWRITES': hasRewrites,
'process.env.__NEXT_CONFIG_OUTPUT': config.output,
'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,
'process.env.__NEXT_I18N_DOMAINS': ((_config_i18n = config.i18n) == null ? void 0 : _config_i18n.domains) ?? false,
'process.env.__NEXT_I18N_CONFIG': config.i18n || '',
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE': config.skipProxyUrlNormalize,
'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE': config.experimental.externalProxyRewritesResolve ?? false,
'process.env.__NEXT_MANUAL_TRAILING_SLASH': config.skipTrailingSlashRedirect,
'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION': (config.experimental.webVitalsAttribution && config.experimental.webVitalsAttribution.length > 0) ?? false,
'process.env.__NEXT_WEB_VITALS_ATTRIBUTION': config.experimental.webVitalsAttribution ?? false,
'process.env.__NEXT_LINK_NO_TOUCH_START': config.experimental.linkNoTouchStart ?? false,
'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,
'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS': !!config.experimental.authInterrupts,
'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(process.env.NEXT_TELEMETRY_DISABLED),
...isNodeServer || isEdgeServer ? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
// This is typically found in unmaintained modules from the
// pre-webpack era (common in server-side code)
'global.GENTLY': false
} : undefined,
...isNodeServer || isEdgeServer ? {
'process.env.__NEXT_EXPERIMENTAL_REACT': (0, _needsexperimentalreact.needsExperimentalReact)(config)
} : undefined,
'process.env.__NEXT_MULTI_ZONE_DRAFT_MODE': config.experimental.multiZoneDraftMode ?? false,
'process.env.__NEXT_TRUST_HOST_HEADER': config.experimental.trustHostHeader ?? false,
'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS': config.experimental.allowedRevalidateHeaderKeys ?? [],
...isNodeServer || isEdgeServer ? {
'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,
'process.env.__NEXT_RELATIVE_PROJECT_DIR': _nodepath.default.relative(process.cwd(), projectPath)
} : {},
'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(config.logging && config.logging.browserToTerminal || false),
'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer,
// The devtools need to know whether or not to show an option to clear the
// bundler cache. This option may be removed later once Turbopack's
// filesystem cache feature is more stable.
//
// This environment value is currently best-effort:
// - It's possible to disable the webpack filesystem cache, but it's
// unlikely for a user to do that.
// - Rspack's filesystem cache is unstable and requires a different
// configuration than webpack to enable (which we don't do).
//
// In the worst case we'll show an option to clear the cache, but it'll be a
// no-op that just restarts the development server.
'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE': !isTurbopack || (config.experimental.turbopackFileSystemCacheForDev ?? false),
'process.env.__NEXT_REACT_DEBUG_CHANNEL': config.experimental.reactDebugChannel ?? false,
'process.env.__NEXT_TRANSITION_INDICATOR': config.experimental.transitionIndicator ?? false,
'process.env.__NEXT_GESTURE_TRANSITION': config.experimental.gestureTransition ?? false,
'process.env.__NEXT_OPTIMISTIC_ROUTING': config.experimental.optimisticRouting ?? false,
'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,
'process.env.__NEXT_EXPOSE_TESTING_API': dev || config.experimental.exposeTestingApiInProductionBuild === true,
'process.env.__NEXT_CACHE_LIFE': config.cacheLife,
'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS': config.experimental.clientParamParsingOrigins || []
};
const userDefines = ((_config_compiler = config.compiler) == null ? void 0 : _config_compiler.define) ?? {};
for(const key in userDefines){
if (defineEnv.hasOwnProperty(key)) {
throw Object.defineProperty(new Error(`The \`compiler.define\` option is configured to replace the \`${key}\` variable. This variable is either part of a Next.js built-in or is already configured.`), "__NEXT_ERROR_CODE", {
value: "E688",
enumerable: false,
configurable: true
});
}
defineEnv[key] = userDefines[key];
}
if (isNodeServer || isEdgeServer) {
var _config_compiler1;
const userDefinesServer = ((_config_compiler1 = config.compiler) == null ? void 0 : _config_compiler1.defineServer) ?? {};
for(const key in userDefinesServer){
if (defineEnv.hasOwnProperty(key)) {
throw Object.defineProperty(new Error(`The \`compiler.defineServer\` option is configured to replace the \`${key}\` variable. This variable is either part of a Next.js built-in or is already configured.`), "__NEXT_ERROR_CODE", {
value: "E689",
enumerable: false,
configurable: true
});
}
defineEnv[key] = userDefinesServer[key];
}
}
const serializedDefineEnv = serializeDefineEnv(defineEnv);
// we delay inlining these values until after the build
// with flying shuttle enabled so we can update them
// without invalidating entries
if (!dev && omitNonDeterministic) {
// client uses window. instead of leaving process.env
// in case process isn't polyfilled on client already
// since by this point it won't be added by webpack
const safeKey = (key)=>isClient ? `window.${key.split('.').pop()}` : key;
for(const key in nextPublicEnv){
serializedDefineEnv[key] = safeKey(key);
}
for(const key in nextConfigEnv){
serializedDefineEnv[key] = safeKey(key);
}
if (!config.experimental.runtimeServerDeploymentId) {
for (const key of [
'process.env.NEXT_DEPLOYMENT_ID'
]){
serializedDefineEnv[key] = safeKey(key);
}
}
}
return serializedDefineEnv;
}
//# sourceMappingURL=define-env.js.map

View File

@@ -0,0 +1,99 @@
// Time thresholds in seconds
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
durationToString: null,
hrtimeBigIntDurationToString: null,
hrtimeDurationToString: null,
hrtimeToSeconds: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
durationToString: function() {
return durationToString;
},
hrtimeBigIntDurationToString: function() {
return hrtimeBigIntDurationToString;
},
hrtimeDurationToString: function() {
return hrtimeDurationToString;
},
hrtimeToSeconds: function() {
return hrtimeToSeconds;
}
});
const SECONDS_IN_MINUTE = 60;
const MINUTES_THRESHOLD_SECONDS = 120 // 2 minutes
;
const SECONDS_THRESHOLD_HIGH = 40;
const SECONDS_THRESHOLD_LOW = 2;
const MILLISECONDS_PER_SECOND = 1000;
// Time thresholds and conversion factors for nanoseconds
const NANOSECONDS_PER_SECOND = 1000000000;
const NANOSECONDS_PER_MILLISECOND = 1000000;
const NANOSECONDS_PER_MICROSECOND = 1000;
const NANOSECONDS_IN_MINUTE = 60000000000 // 60 * 1_000_000_000
;
const MINUTES_THRESHOLD_NANOSECONDS = 120000000000 // 2 minutes in nanoseconds
;
const SECONDS_THRESHOLD_HIGH_NANOSECONDS = 40000000000 // 40 seconds in nanoseconds
;
const SECONDS_THRESHOLD_LOW_NANOSECONDS = 2000000000 // 2 seconds in nanoseconds
;
const MILLISECONDS_THRESHOLD_NANOSECONDS = 2000000 // 2 milliseconds in nanoseconds
;
function durationToString(compilerDuration) {
if (compilerDuration > MINUTES_THRESHOLD_SECONDS) {
return `${(compilerDuration / SECONDS_IN_MINUTE).toFixed(1)}min`;
} else if (compilerDuration > SECONDS_THRESHOLD_HIGH) {
return `${compilerDuration.toFixed(0)}s`;
} else if (compilerDuration > SECONDS_THRESHOLD_LOW) {
return `${compilerDuration.toFixed(1)}s`;
} else {
return `${(compilerDuration * MILLISECONDS_PER_SECOND).toFixed(0)}ms`;
}
}
/**
* Converts a nanosecond duration to a human-readable string format.
* Formats duration based on magnitude for optimal readability:
* - >= 2 minutes: show in minutes with 1 decimal place (e.g., "2.5min")
* - >= 40 seconds: show in whole seconds (e.g., "45s")
* - >= 2 seconds: show in seconds with 1 decimal place (e.g., "3.2s")
* - >= 2 milliseconds: show in whole milliseconds (e.g., "250ms")
* - < 2 milliseconds: show in whole microseconds (e.g., "500µs")
*
* @param durationBigInt - Duration in nanoseconds as a BigInt
* @returns Formatted duration string with appropriate unit and precision
*/ function durationToStringWithNanoseconds(durationBigInt) {
const duration = Number(durationBigInt);
if (duration >= MINUTES_THRESHOLD_NANOSECONDS) {
return `${(duration / NANOSECONDS_IN_MINUTE).toFixed(1)}min`;
} else if (duration >= SECONDS_THRESHOLD_HIGH_NANOSECONDS) {
return `${(duration / NANOSECONDS_PER_SECOND).toFixed(0)}s`;
} else if (duration >= SECONDS_THRESHOLD_LOW_NANOSECONDS) {
return `${(duration / NANOSECONDS_PER_SECOND).toFixed(1)}s`;
} else if (duration >= MILLISECONDS_THRESHOLD_NANOSECONDS) {
return `${(duration / NANOSECONDS_PER_MILLISECOND).toFixed(0)}ms`;
} else {
return `${(duration / NANOSECONDS_PER_MICROSECOND).toFixed(0)}µs`;
}
}
function hrtimeToSeconds(hrtime) {
// hrtime is a tuple of [seconds, nanoseconds]
return hrtime[0] + hrtime[1] / NANOSECONDS_PER_SECOND;
}
function hrtimeBigIntDurationToString(hrtime) {
return durationToStringWithNanoseconds(hrtime);
}
function hrtimeDurationToString(hrtime) {
return durationToString(hrtimeToSeconds(hrtime));
}
//# sourceMappingURL=duration-to-string.js.map

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getSupportedBrowsers", {
enumerable: true,
get: function() {
return getSupportedBrowsers;
}
});
const _browserslist = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/browserslist"));
const _constants = require("../shared/lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getSupportedBrowsers(dir, isDevelopment) {
let browsers;
try {
const browsersListConfig = _browserslist.default.loadConfig({
path: dir,
env: isDevelopment ? 'development' : 'production'
});
// Running `browserslist` resolves `extends` and other config features into a list of browsers
if (browsersListConfig && browsersListConfig.length > 0) {
browsers = (0, _browserslist.default)(browsersListConfig);
}
} catch {}
// When user has browserslist use that target
if (browsers && browsers.length > 0) {
return browsers;
}
// Uses modern browsers as the default.
return _constants.MODERN_BROWSERSLIST_TARGET;
}
//# sourceMappingURL=get-supported-browsers.js.map

View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
deregisterHook: null,
registerHook: null,
requireFromString: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
deregisterHook: function() {
return deregisterHook;
},
registerHook: function() {
return registerHook;
},
requireFromString: function() {
return requireFromString;
}
});
const _nodemodule = /*#__PURE__*/ _interop_require_default(require("node:module"));
const _nodefs = require("node:fs");
const _nodepath = require("node:path");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const oldJSHook = require.extensions['.js'];
const extensions = [
'.ts',
'.cts',
'.mts',
'.cjs',
'.mjs'
];
function registerHook(swcOptions) {
// lazy require swc since it loads React before even setting NODE_ENV
// resulting loading Development React on Production
const { transformSync } = require('../swc');
require.extensions['.js'] = function(mod, oldFilename) {
try {
return oldJSHook(mod, oldFilename);
} catch (error) {
if (error.code !== 'ERR_REQUIRE_ESM') {
throw error;
}
// calling oldJSHook throws ERR_REQUIRE_ESM, so run _compile manually
// TODO: investigate if we can remove readFileSync
const content = (0, _nodefs.readFileSync)(oldFilename, 'utf8');
const { code } = transformSync(content, swcOptions);
mod._compile(code, oldFilename);
}
};
for (const ext of extensions){
const oldHook = require.extensions[ext] ?? oldJSHook;
require.extensions[ext] = function(mod, oldFilename) {
const _compile = mod._compile;
mod._compile = function(code, filename) {
const swc = transformSync(code, swcOptions);
return _compile.call(this, swc.code, filename);
};
return oldHook(mod, oldFilename);
};
}
}
function deregisterHook() {
require.extensions['.js'] = oldJSHook;
extensions.forEach((ext)=>delete require.extensions[ext]);
}
function requireFromString(code, filename) {
const paths = _nodemodule.default._nodeModulePaths((0, _nodepath.dirname)(filename));
const m = new _nodemodule.default(filename, module.parent);
m.paths = paths;
m._compile(code, filename);
return m.exports;
}
//# sourceMappingURL=require-hook.js.map

View File

@@ -0,0 +1,251 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "transpileConfig", {
enumerable: true,
get: function() {
return transpileConfig;
}
});
const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
const _nodefs = require("node:fs");
const _nodeurl = require("node:url");
const _commentjson = /*#__PURE__*/ _interop_require_wildcard(require("next/dist/compiled/comment-json"));
const _requirehook = require("./require-hook");
const _log = require("../output/log");
const _utils = require("../../server/lib/utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function resolveSWCOptions(cwd, compilerOptions) {
var _process_versions, _process;
return {
jsc: {
parser: {
syntax: 'typescript'
},
...compilerOptions.paths ? {
paths: compilerOptions.paths
} : {},
...compilerOptions.baseUrl ? {
baseUrl: _nodepath.default.resolve(cwd, compilerOptions.baseUrl)
} : compilerOptions.paths ? {
baseUrl: cwd
} : {}
},
module: {
type: 'commonjs'
},
isModule: 'unknown',
env: {
targets: {
// Setting the Node.js version can reduce unnecessary code generation.
node: ((_process = process) == null ? void 0 : (_process_versions = _process.versions) == null ? void 0 : _process_versions.node) ?? '20.19.0'
}
}
};
}
function resolveExtends(extendsPath, currentConfigDir) {
// Relative paths are resolved relative to the current config's directory
if (extendsPath.startsWith('./') || extendsPath.startsWith('../') || _nodepath.default.isAbsolute(extendsPath)) {
const resolved = _nodepath.default.resolve(currentConfigDir, extendsPath);
// TypeScript allows omitting .json extension
if ((0, _nodefs.existsSync)(resolved)) {
return resolved;
}
if (!resolved.endsWith('.json') && (0, _nodefs.existsSync)(resolved + '.json')) {
return resolved + '.json';
}
return resolved;
}
// Package paths - use require.resolve to find the package
try {
// Try resolving as a direct path within the package
return require.resolve(extendsPath, {
paths: [
currentConfigDir
]
});
} catch {
// If that fails, try appending tsconfig.json for package names like "@tsconfig/node18"
try {
return require.resolve(extendsPath + '/tsconfig.json', {
paths: [
currentConfigDir
]
});
} catch {
// Return the original path and let it fail later with a clear error
return _nodepath.default.resolve(currentConfigDir, extendsPath);
}
}
}
function loadTsConfigFile(configPath, visited) {
const resolvedPath = _nodepath.default.resolve(configPath);
if (visited.has(resolvedPath)) {
return {};
}
visited.add(resolvedPath);
if (!(0, _nodefs.existsSync)(resolvedPath)) {
return {};
}
const configContent = (0, _nodefs.readFileSync)(resolvedPath, 'utf8');
const config = _commentjson.parse(configContent);
const configDir = _nodepath.default.dirname(resolvedPath);
let mergedOptions = {};
// Note that config options from `extends` should get overwritten, not merged
if (config.extends) {
const extendsList = Array.isArray(config.extends) ? config.extends : [
config.extends
];
for (const extendsPath of extendsList){
const parentConfigPath = resolveExtends(extendsPath, configDir);
const parentOptions = loadTsConfigFile(parentConfigPath, visited);
mergedOptions = {
...mergedOptions,
...parentOptions
};
}
}
const currentOptions = config.compilerOptions ?? {};
mergedOptions = {
...mergedOptions,
paths: currentOptions.paths ?? mergedOptions.paths,
baseUrl: currentOptions.baseUrl ?? mergedOptions.baseUrl
};
return mergedOptions;
}
async function loadTsConfig(dir) {
// NOTE: This doesn't fully cover the edge case for setting
// "typescript.tsconfigPath" in next config which is currently
// a restriction.
// It's a chicken-and-egg problem since we need to transpile
// the next config to get that value.
const resolvedTsConfigPath = _nodepath.default.join(dir, 'tsconfig.json');
if (!(0, _nodefs.existsSync)(resolvedTsConfigPath)) {
return {};
}
return loadTsConfigFile(resolvedTsConfigPath, new Set());
}
async function transpileConfig({ nextConfigPath, dir }) {
try {
// envs are passed to the workers and preserve the flag
if (process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED === 'true') {
try {
// Node.js v22.10.0+
// Value is 'strip' or 'transform' based on how the feature is enabled.
// https://nodejs.org/api/process.html#processfeaturestypescript
// TODO: Remove `as any` once we bump @types/node to v22.10.0+
if (process.features.typescript) {
// Run import() here to catch errors and fallback to legacy resolution.
return (await import((0, _nodeurl.pathToFileURL)(nextConfigPath).href)).default;
}
if ((0, _utils.getNodeOptionsArgs)().includes('--no-experimental-strip-types') || process.execArgv.includes('--no-experimental-strip-types')) {
(0, _log.warnOnce)(`Skipped resolving "${_nodepath.default.basename(nextConfigPath)}" using Node.js native TypeScript resolution because it was disabled by the "--no-experimental-strip-types" flag.` + ' Falling back to legacy resolution.' + ' Learn more: https://nextjs.org/docs/app/api-reference/config/typescript#using-nodejs-native-typescript-resolver-for-nextconfigts');
}
// Feature is not enabled, fallback to legacy resolution for current session.
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'false';
} catch (cause) {
(0, _log.warnOnce)(`Failed to import "${_nodepath.default.basename(nextConfigPath)}" using Node.js native TypeScript resolution.` + ' Falling back to legacy resolution.' + ' Learn more: https://nextjs.org/docs/app/api-reference/config/typescript#using-nodejs-native-typescript-resolver-for-nextconfigts', {
cause
});
// Once failed, fallback to legacy resolution for current session.
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'false';
}
}
const compilerOptions = await loadTsConfig(dir);
return handleCJS({
dir,
nextConfigPath,
compilerOptions
});
} catch (cause) {
throw Object.defineProperty(new Error(`Failed to transpile "${_nodepath.default.basename(nextConfigPath)}".`, {
cause
}), "__NEXT_ERROR_CODE", {
value: "E797",
enumerable: false,
configurable: true
});
}
}
async function handleCJS({ dir, nextConfigPath, compilerOptions }) {
const swcOptions = resolveSWCOptions(dir, compilerOptions);
let hasRequire = false;
try {
var _config_experimental;
const nextConfigString = (0, _nodefs.readFileSync)(nextConfigPath, 'utf8');
// lazy require swc since it loads React before even setting NODE_ENV
// resulting loading Development React on Production
const { loadBindings } = require('../swc');
const bindings = await loadBindings();
const { code } = await bindings.transform(nextConfigString, swcOptions);
// register require hook only if require exists
if (code.includes('require(')) {
(0, _requirehook.registerHook)(swcOptions);
hasRequire = true;
}
// filename & extension don't matter here
const config = (0, _requirehook.requireFromString)(code, _nodepath.default.resolve(dir, 'next.config.compiled.js'));
// At this point we have already loaded the bindings without this configuration setting due to the `transform` call above.
// Possibly we fell back to wasm in which case, it all works out but if not we need to warn
// that the configuration was ignored.
if ((config == null ? void 0 : (_config_experimental = config.experimental) == null ? void 0 : _config_experimental.useWasmBinary) && !bindings.isWasm) {
(0, _log.warn)('Using a next.config.ts file is incompatible with `experimental.useWasmBinary` unless ' + '`--experimental-next-config-strip-types` is also passed.\nSetting `useWasmBinary` to `false');
config.experimental.useWasmBinary = false;
}
return config;
} catch (error) {
throw error;
} finally{
if (hasRequire) {
(0, _requirehook.deregisterHook)();
}
}
}
//# sourceMappingURL=transpile-config.js.map

View File

@@ -0,0 +1,84 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
formatExpire: null,
formatRevalidate: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
formatExpire: function() {
return formatExpire;
},
formatRevalidate: function() {
return formatRevalidate;
}
});
const timeUnits = [
{
label: 'y',
seconds: 31536000
},
{
label: 'w',
seconds: 604800
},
{
label: 'd',
seconds: 86400
},
{
label: 'h',
seconds: 3600
},
{
label: 'm',
seconds: 60
},
{
label: 's',
seconds: 1
}
];
function humanReadableTimeRounded(seconds) {
// Find the largest fitting unit.
let candidateIndex = timeUnits.length - 1;
for(let i = 0; i < timeUnits.length; i++){
if (seconds >= timeUnits[i].seconds) {
candidateIndex = i;
break;
}
}
const candidate = timeUnits[candidateIndex];
const value = seconds / candidate.seconds;
const isExact = Number.isInteger(value);
// For days and weeks only, check if using the next smaller unit yields an
// exact result.
if (!isExact && (candidate.label === 'd' || candidate.label === 'w')) {
const nextUnit = timeUnits[candidateIndex + 1];
const nextValue = seconds / nextUnit.seconds;
if (Number.isInteger(nextValue)) {
return `${nextValue}${nextUnit.label}`;
}
}
if (isExact) {
return `${value}${candidate.label}`;
}
return `${Math.round(value)}${candidate.label}`;
}
function formatRevalidate(cacheControl) {
const { revalidate } = cacheControl;
return revalidate ? humanReadableTimeRounded(revalidate) : '';
}
function formatExpire(cacheControl) {
const { expire } = cacheControl;
return expire ? humanReadableTimeRounded(expire) : '';
}
//# sourceMappingURL=format.js.map

View File

@@ -0,0 +1,135 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
bootstrap: null,
error: null,
errorOnce: null,
event: null,
info: null,
prefixes: null,
ready: null,
trace: null,
wait: null,
warn: null,
warnOnce: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
bootstrap: function() {
return bootstrap;
},
error: function() {
return error;
},
errorOnce: function() {
return errorOnce;
},
event: function() {
return event;
},
info: function() {
return info;
},
prefixes: function() {
return prefixes;
},
ready: function() {
return ready;
},
trace: function() {
return trace;
},
wait: function() {
return wait;
},
warn: function() {
return warn;
},
warnOnce: function() {
return warnOnce;
}
});
const _picocolors = require("../../lib/picocolors");
const _lrucache = require("../../server/lib/lru-cache");
const prefixes = {
wait: (0, _picocolors.white)((0, _picocolors.bold)('○')),
error: (0, _picocolors.red)((0, _picocolors.bold)('')),
warn: (0, _picocolors.yellow)((0, _picocolors.bold)('⚠')),
ready: '▲',
info: (0, _picocolors.white)((0, _picocolors.bold)(' ')),
event: (0, _picocolors.green)((0, _picocolors.bold)('✓')),
trace: (0, _picocolors.magenta)((0, _picocolors.bold)('»'))
};
const LOGGING_METHOD = {
log: 'log',
warn: 'warn',
error: 'error'
};
function prefixedLog(prefixType, ...message) {
if ((message[0] === '' || message[0] === undefined) && message.length === 1) {
message.shift();
}
const consoleMethod = prefixType in LOGGING_METHOD ? LOGGING_METHOD[prefixType] : 'log';
const prefix = prefixes[prefixType];
// If there's no message, don't print the prefix but a new line
if (message.length === 0) {
console[consoleMethod]('');
} else {
// Ensure if there's ANSI escape codes it's concatenated into one string.
// Chrome DevTool can only handle color if it's in one string.
if (message.length === 1 && typeof message[0] === 'string') {
console[consoleMethod](prefix + ' ' + message[0]);
} else {
console[consoleMethod](prefix, ...message);
}
}
}
function bootstrap(message) {
console.log(message);
}
function wait(...message) {
prefixedLog('wait', ...message);
}
function error(...message) {
prefixedLog('error', ...message);
}
function warn(...message) {
prefixedLog('warn', ...message);
}
function ready(...message) {
prefixedLog('ready', ...message);
}
function info(...message) {
prefixedLog('info', ...message);
}
function event(...message) {
prefixedLog('event', ...message);
}
function trace(...message) {
prefixedLog('trace', ...message);
}
const warnOnceCache = new _lrucache.LRUCache(10000, (value)=>value.length);
function warnOnce(...message) {
const key = message.join(' ');
if (!warnOnceCache.has(key)) {
warnOnceCache.set(key, key);
warn(...message);
}
}
const errorOnceCache = new _lrucache.LRUCache(10000, (value)=>value.length);
function errorOnce(...message) {
const key = message.join(' ');
if (!errorOnceCache.has(key)) {
errorOnceCache.set(key, key);
error(...message);
}
}
//# sourceMappingURL=log.js.map

View File

@@ -0,0 +1,162 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
AppSegmentConfigSchemaKeys: null,
parseAppSegmentConfig: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
AppSegmentConfigSchemaKeys: function() {
return AppSegmentConfigSchemaKeys;
},
parseAppSegmentConfig: function() {
return parseAppSegmentConfig;
}
});
const _zod = require("next/dist/compiled/zod");
const _zod1 = require("../../../shared/lib/zod");
const CookieSchema = _zod.z.object({
name: _zod.z.string(),
value: _zod.z.string().or(_zod.z.null())
}).strict();
const RuntimeSampleSchema = _zod.z.object({
cookies: _zod.z.array(CookieSchema).optional(),
headers: _zod.z.array(_zod.z.tuple([
_zod.z.string(),
_zod.z.string().or(_zod.z.null())
])).optional(),
params: _zod.z.record(_zod.z.union([
_zod.z.string(),
_zod.z.array(_zod.z.string())
])).optional(),
searchParams: _zod.z.record(_zod.z.union([
_zod.z.string(),
_zod.z.array(_zod.z.string()),
_zod.z.null()
])).optional()
}).strict();
const InstantConfigStaticSchema = _zod.z.object({
prefetch: _zod.z.literal('static'),
samples: _zod.z.array(RuntimeSampleSchema).min(1).optional(),
from: _zod.z.array(_zod.z.string()).optional(),
unstable_disableValidation: _zod.z.literal(true).optional(),
unstable_disableDevValidation: _zod.z.literal(true).optional(),
unstable_disableBuildValidation: _zod.z.literal(true).optional()
}).strict();
const InstantConfigRuntimeSchema = _zod.z.object({
prefetch: _zod.z.literal('runtime'),
samples: _zod.z.array(RuntimeSampleSchema).min(1),
from: _zod.z.array(_zod.z.string()).optional(),
unstable_disableValidation: _zod.z.literal(true).optional(),
unstable_disableDevValidation: _zod.z.literal(true).optional(),
unstable_disableBuildValidation: _zod.z.literal(true).optional()
}).strict();
const InstantConfigSchema = _zod.z.union([
_zod.z.discriminatedUnion('prefetch', [
InstantConfigStaticSchema,
InstantConfigRuntimeSchema
]),
_zod.z.literal(false)
]);
/**
* The schema for configuration for a page.
*/ const AppSegmentConfigSchema = _zod.z.object({
/**
* The number of seconds to revalidate the page or false to disable revalidation.
*/ revalidate: _zod.z.union([
_zod.z.number().int().nonnegative(),
_zod.z.literal(false)
]).optional(),
/**
* Whether the page supports dynamic parameters.
*/ dynamicParams: _zod.z.boolean().optional(),
/**
* The dynamic behavior of the page.
*/ dynamic: _zod.z.enum([
'auto',
'error',
'force-static',
'force-dynamic'
]).optional(),
/**
* The caching behavior of the page.
*/ fetchCache: _zod.z.enum([
'auto',
'default-cache',
'only-cache',
'force-cache',
'force-no-store',
'default-no-store',
'only-no-store'
]).optional(),
/**
* How this segment should be prefetched.
*/ unstable_instant: InstantConfigSchema.optional(),
/**
* The stale time for dynamic responses in seconds.
* Controls how long the client-side router cache retains dynamic page data.
* Pages only — not allowed in layouts.
*/ unstable_dynamicStaleTime: _zod.z.number().int().nonnegative().optional(),
/**
* The preferred region for the page.
*/ preferredRegion: _zod.z.union([
_zod.z.string(),
_zod.z.array(_zod.z.string())
]).optional(),
/**
* The runtime to use for the page.
*/ runtime: _zod.z.enum([
'edge',
'nodejs'
]).optional(),
/**
* The maximum duration for the page in seconds.
*/ maxDuration: _zod.z.number().int().nonnegative().optional()
});
function parseAppSegmentConfig(data, route) {
const parsed = AppSegmentConfigSchema.safeParse(data, {
errorMap: (issue, ctx)=>{
if (issue.path.length === 1) {
switch(issue.path[0]){
case 'revalidate':
{
return {
message: `Invalid revalidate value ${JSON.stringify(ctx.data)} on "${route}", must be a non-negative number or false`
};
}
case 'unstable_instant':
{
return {
// @TODO replace this link with a link to the docs when they are written
message: `Invalid unstable_instant value ${JSON.stringify(ctx.data)} on "${route}", must be an object with \`prefetch: "static"\` or \`prefetch: "runtime"\`, or \`false\`. Read more at https://nextjs.org/docs/messages/invalid-instant-configuration`
};
}
case 'unstable_dynamicStaleTime':
{
return {
message: `Invalid unstable_dynamicStaleTime value ${JSON.stringify(ctx.data)} on "${route}", must be a non-negative number`
};
}
default:
}
}
return {
message: ctx.defaultError
};
}
});
if (!parsed.success) {
throw (0, _zod1.formatZodError)(`Invalid segment configuration options detected for "${route}". Read more at https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config`, parsed.error);
}
return parsed.data;
}
const AppSegmentConfigSchemaKeys = AppSegmentConfigSchema.keyof().options;
//# sourceMappingURL=app-segment-config.js.map

View File

@@ -0,0 +1,137 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "collectSegments", {
enumerable: true,
get: function() {
return collectSegments;
}
});
const _appsegmentconfig = require("./app-segment-config");
const _invarianterror = require("../../../shared/lib/invariant-error");
const _checks = require("../../../server/route-modules/checks");
const _clientandserverreferences = require("../../../lib/client-and-server-references");
const _getsegmentparam = require("../../../shared/lib/router/utils/get-segment-param");
const _appdirmodule = require("../../../server/lib/app-dir-module");
/**
* Parses the app config and attaches it to the segment.
*/ function attach(segment, userland, route) {
// If the userland is not an object, then we can't do anything with it.
if (typeof userland !== 'object' || userland === null) {
return;
}
// Try to parse the application configuration.
const config = (0, _appsegmentconfig.parseAppSegmentConfig)(userland, route);
// If there was any keys on the config, then attach it to the segment.
if (Object.keys(config).length > 0) {
segment.config = config;
}
if ('generateStaticParams' in userland && typeof userland.generateStaticParams === 'function') {
var _segment_config;
segment.generateStaticParams = userland.generateStaticParams;
// Validate that `generateStaticParams` makes sense in this context.
if (((_segment_config = segment.config) == null ? void 0 : _segment_config.runtime) === 'edge') {
throw Object.defineProperty(new Error('Edge runtime is not supported with `generateStaticParams`.'), "__NEXT_ERROR_CODE", {
value: "E502",
enumerable: false,
configurable: true
});
}
}
}
/**
* Walks the loader tree and collects the generate parameters for each segment.
*
* @param routeModule the app page route module
* @returns the segments for the app page route module
*/ async function collectAppPageSegments(routeModule) {
// We keep track of unique segments, since with parallel routes, it's possible
// to see the same segment multiple times.
const segments = [];
// Queue will store loader trees.
const queue = [
routeModule.userland.loaderTree
];
while(queue.length > 0){
const loaderTree = queue.shift();
const [name, parallelRoutes] = loaderTree;
// Process current node
const { mod: userland, filePath } = await (0, _appdirmodule.getLayoutOrPageModule)(loaderTree);
const isClientComponent = userland && (0, _clientandserverreferences.isClientReference)(userland);
const param = (0, _getsegmentparam.getSegmentParam)(name);
const segment = {
name,
paramName: param == null ? void 0 : param.paramName,
paramType: param == null ? void 0 : param.paramType,
filePath,
config: undefined,
generateStaticParams: undefined
};
// Only server components can have app segment configurations
if (!isClientComponent) {
attach(segment, userland, routeModule.definition.pathname);
}
// If this segment doesn't already exist, then add it to the segments array.
// The list of segments is short so we just use a list traversal to check
// for duplicates and spare us needing to maintain the string key.
if (segments.every((s)=>s.name !== segment.name || s.paramName !== segment.paramName || s.paramType !== segment.paramType || s.filePath !== segment.filePath)) {
segments.push(segment);
}
// Add all parallel routes to the queue
for (const parallelRoute of Object.values(parallelRoutes)){
queue.push(parallelRoute);
}
}
return segments;
}
/**
* Collects the segments for a given app route module.
*
* @param routeModule the app route module
* @returns the segments for the app route module
*/ function collectAppRouteSegments(routeModule) {
// Get the pathname parts, slice off the first element (which is empty).
const parts = routeModule.definition.pathname.split('/').slice(1);
if (parts.length === 0) {
throw Object.defineProperty(new _invarianterror.InvariantError('Expected at least one segment'), "__NEXT_ERROR_CODE", {
value: "E580",
enumerable: false,
configurable: true
});
}
// Generate all the segments.
const segments = parts.map((name)=>{
const param = (0, _getsegmentparam.getSegmentParam)(name);
return {
name,
paramName: param == null ? void 0 : param.paramName,
paramType: param == null ? void 0 : param.paramType,
filePath: undefined,
config: undefined,
generateStaticParams: undefined
};
});
// We know we have at least one, we verified this above. We should get the
// last segment which represents the root route module.
const segment = segments[segments.length - 1];
segment.filePath = routeModule.definition.filename;
// Extract the segment config from the userland module.
attach(segment, routeModule.userland, routeModule.definition.pathname);
return segments;
}
function collectSegments(routeModule) {
if ((0, _checks.isAppRouteRouteModule)(routeModule)) {
return collectAppRouteSegments(routeModule);
}
if ((0, _checks.isAppPageRouteModule)(routeModule)) {
return collectAppPageSegments(routeModule);
}
throw Object.defineProperty(new _invarianterror.InvariantError('Expected a route module to be one of app route or page'), "__NEXT_ERROR_CODE", {
value: "E568",
enumerable: false,
configurable: true
});
}
//# sourceMappingURL=app-segments.js.map

View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "collectRootParamKeys", {
enumerable: true,
get: function() {
return collectRootParamKeys;
}
});
const _getsegmentparam = require("../../../shared/lib/router/utils/get-segment-param");
const _checks = require("../../../server/route-modules/checks");
const _invarianterror = require("../../../shared/lib/invariant-error");
function collectAppPageRootParamKeys(routeModule) {
let rootParams = [];
let current = routeModule.userland.loaderTree;
while(current){
var _getSegmentParam;
const [name, parallelRoutes, modules] = current;
// If this is a dynamic segment, then we collect the param.
const paramName = (_getSegmentParam = (0, _getsegmentparam.getSegmentParam)(name)) == null ? void 0 : _getSegmentParam.paramName;
if (paramName) {
rootParams.push(paramName);
}
// If this has a layout module, then we've found the root layout because
// we return once we found the first layout.
if (typeof modules.layout !== 'undefined') {
return rootParams;
}
// This didn't include a root layout, so we need to continue. We don't need
// to collect from other parallel routes because we can't have a parallel
// route above a root layout.
current = parallelRoutes.children;
}
// If we didn't find a root layout, then we don't have any params.
return [];
}
function collectRootParamKeys(routeModule) {
if ((0, _checks.isAppRouteRouteModule)(routeModule)) {
return [];
}
if ((0, _checks.isAppPageRouteModule)(routeModule)) {
return collectAppPageRootParamKeys(routeModule);
}
throw Object.defineProperty(new _invarianterror.InvariantError('Expected a route module to be one of app route or page'), "__NEXT_ERROR_CODE", {
value: "E568",
enumerable: false,
configurable: true
});
}
//# sourceMappingURL=collect-root-param-keys.js.map

View File

@@ -0,0 +1,736 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
assignStaticShellMetadata: null,
buildAppStaticPaths: null,
calculateFallbackMode: null,
filterUniqueParams: null,
generateAllParamCombinations: null,
generateRouteStaticParams: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
assignStaticShellMetadata: function() {
return assignStaticShellMetadata;
},
buildAppStaticPaths: function() {
return buildAppStaticPaths;
},
calculateFallbackMode: function() {
return calculateFallbackMode;
},
filterUniqueParams: function() {
return filterUniqueParams;
},
generateAllParamCombinations: function() {
return generateAllParamCombinations;
},
generateRouteStaticParams: function() {
return generateRouteStaticParams;
}
});
const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
const _runwithafter = require("../../server/after/run-with-after");
const _workstore = require("../../server/async-storage/work-store");
const _fallback = require("../../lib/fallback");
const _utils = require("./utils");
const _escapepathdelimiters = /*#__PURE__*/ _interop_require_default(require("../../shared/lib/router/utils/escape-path-delimiters"));
const _createincrementalcache = require("../../export/helpers/create-incremental-cache");
const _getsegmentparam = require("../../shared/lib/router/utils/get-segment-param");
const _emptygeneratestaticparamserror = require("../../shared/lib/errors/empty-generate-static-params-error");
const _interceptionprefixfromparamtype = require("../../shared/lib/router/utils/interception-prefix-from-param-type");
const _implicittags = require("../../server/lib/implicit-tags");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function filterUniqueParams(childrenRouteParams, routeParams) {
// A Map is used to store unique parameter combinations. The key of the Map
// is a string representation of the parameter combination, and the value
// is the actual `Params` object.
const unique = new Map();
// Iterate over each parameter object in the input array.
for (const params of routeParams){
let key = '' // Initialize an empty string to build the unique key for the current `params` object.
;
// Iterate through the `routeParamKeys` (which are assumed to be sorted).
// This consistent order is crucial for generating a stable and unique key
// for each parameter combination.
for (const { paramName: paramKey } of childrenRouteParams){
const value = params[paramKey];
// Construct a part of the key using the parameter key and its value.
// A type prefix (`A:` for Array, `S:` for String, `U:` for undefined) is added to the value
// to prevent collisions. For example, `['a', 'b']` and `'a,b'` would
// otherwise generate the same string representation, leading to incorrect
// deduplication. This ensures that different types with the same string
// representation are treated as distinct.
let valuePart;
if (Array.isArray(value)) {
valuePart = `A:${value.join(',')}`;
} else if (value === undefined) {
valuePart = `U:undefined`;
} else {
valuePart = `S:${value}`;
}
key += `${paramKey}:${valuePart}|`;
}
// If the generated key is not already in the `unique` Map, it means this
// parameter combination is unique so far. Add it to the Map.
if (!unique.has(key)) {
unique.set(key, params);
}
}
// Convert the Map's values (the unique `Params` objects) back into an array
// and return it.
return Array.from(unique.values());
}
function generateAllParamCombinations(childrenRouteParams, routeParams, rootParamKeys) {
// A Map is used to store unique combinations of Route Parameters.
// The key of the Map is a string representation of the Route Parameter
// combination, and the value is the `Params` object containing only
// the Route Parameters.
const combinations = new Map();
// Determine the minimum index where all Root Parameters are included.
// This optimization ensures we only generate combinations that include
// a complete set of Root Parameters, preventing invalid Static Shells.
//
// For example, if rootParamKeys = ['lang', 'region'] and routeParamKeys = ['lang', 'region', 'slug']:
// - 'lang' is at index 0, 'region' is at index 1
// - minIndexForCompleteRootParams = max(0, 1) = 1
// - We'll only generate combinations starting from index 1 (which includes both lang and region)
let minIndexForCompleteRootParams = -1;
if (rootParamKeys.length > 0) {
// Find the index of the last Root Parameter in routeParamKeys.
// This tells us the minimum combination length needed to include all Root Parameters.
for (const rootParamKey of rootParamKeys){
const index = childrenRouteParams.findIndex((param)=>param.paramName === rootParamKey);
if (index === -1) {
// Root Parameter not found in Route Parameters - this shouldn't happen in normal cases
// but we handle it gracefully by treating it as if there are no Root Parameters.
// This allows the function to fall back to generating all sub-combinations.
minIndexForCompleteRootParams = -1;
break;
}
// Track the highest index among all Root Parameters.
// This ensures all Root Parameters are included in any generated combination.
minIndexForCompleteRootParams = Math.max(minIndexForCompleteRootParams, index);
}
}
// Iterate over each Static Parameter object in the input array.
// Each params object represents one potential route combination (e.g., { lang: 'en', region: 'US', slug: 'home' })
for (const params of routeParams){
// Generate all possible prefix combinations for this Static Parameter set.
// For routeParamKeys = ['lang', 'region', 'slug'], we'll generate combinations at:
// - i=0: { lang: 'en' }
// - i=1: { lang: 'en', region: 'US' }
// - i=2: { lang: 'en', region: 'US', slug: 'home' }
//
// The iteration order is crucial for generating stable and unique keys
// for each Route Parameter combination.
for(let i = 0; i < childrenRouteParams.length; i++){
// Skip generating combinations that don't include all Root Parameters.
// This prevents creating invalid Static Shells that are missing required Root Parameters.
//
// For example, if Root Parameters are ['lang', 'region'] and minIndexForCompleteRootParams = 1:
// - Skip i=0 (would only include 'lang', missing 'region')
// - Process i=1 and higher (includes both 'lang' and 'region')
if (minIndexForCompleteRootParams >= 0 && i < minIndexForCompleteRootParams) {
continue;
}
// Initialize data structures for building this specific combination
const combination = {};
const keyParts = [];
let hasAllRootParams = true;
// Build the sub-combination with parameters from index 0 to i (inclusive).
// This creates a prefix of the full parameter set, building up combinations incrementally.
//
// For example, if routeParamKeys = ['lang', 'region', 'slug'] and i = 1:
// - j=0: Add 'lang' parameter
// - j=1: Add 'region' parameter
// Result: { lang: 'en', region: 'US' }
for(let j = 0; j <= i; j++){
const { paramName: routeKey } = childrenRouteParams[j];
// Check if the parameter exists in the original params object and has a defined value.
// This handles cases where generateStaticParams doesn't provide all possible parameters,
// or where some parameters are optional/undefined.
if (!params.hasOwnProperty(routeKey) || params[routeKey] === undefined) {
// If this missing parameter is a Root Parameter, mark the combination as invalid.
// Root Parameters are required for Static Shells, so we can't generate partial combinations without them.
if (rootParamKeys.includes(routeKey)) {
hasAllRootParams = false;
}
break;
}
const value = params[routeKey];
combination[routeKey] = value;
// Construct a unique key part for this parameter to enable deduplication.
// We use type prefixes to prevent collisions between different value types
// that might have the same string representation.
//
// Examples:
// - Array ['foo', 'bar'] becomes "A:foo,bar"
// - String "foo,bar" becomes "S:foo,bar"
// - This prevents collisions between ['foo', 'bar'] and "foo,bar"
let valuePart;
if (Array.isArray(value)) {
valuePart = `A:${value.join(',')}`;
} else {
valuePart = `S:${value}`;
}
keyParts.push(`${routeKey}:${valuePart}`);
}
// Build the final unique key by joining all parameter parts.
// This key is used for deduplication in the combinations Map.
// Format: "lang:S:en|region:S:US|slug:A:home,about"
const currentKey = keyParts.join('|');
// Only add the combination if it meets our criteria:
// 1. hasAllRootParams: Contains all required Root Parameters
// 2. !combinations.has(currentKey): Is not a duplicate of an existing combination
//
// This ensures we only generate valid, unique parameter combinations for Static Shells.
if (hasAllRootParams && !combinations.has(currentKey)) {
combinations.set(currentKey, combination);
}
}
}
// Convert the Map's values back into an array and return the final result.
// The Map ensures all combinations are unique, and we return only the
// parameter objects themselves, discarding the internal deduplication keys.
return Array.from(combinations.values());
}
function calculateFallbackMode(dynamicParams, fallbackRootParams, baseFallbackMode) {
return dynamicParams ? // perform a blocking static render.
fallbackRootParams.length > 0 ? _fallback.FallbackMode.BLOCKING_STATIC_RENDER : baseFallbackMode ?? _fallback.FallbackMode.NOT_FOUND : _fallback.FallbackMode.NOT_FOUND;
}
/**
* Validates the parameters to ensure they're accessible and have the correct
* types.
*
* @param page - The page to validate.
* @param regex - The route regex.
* @param isRoutePPREnabled - Whether the route has partial prerendering enabled.
* @param pathnameSegments - The keys of the parameters.
* @param rootParamKeys - The keys of the root params.
* @param routeParams - The list of parameters to validate.
* @returns The list of validated parameters.
*/ function validateParams(page, isRoutePPREnabled, pathnameSegments, rootParamKeys, routeParams) {
const valid = [];
// Validate that if there are any root params, that the user has provided at
// least one value for them only if we're using partial prerendering.
if (isRoutePPREnabled && rootParamKeys.length > 0) {
if (routeParams.length === 0 || rootParamKeys.some((key)=>routeParams.some((params)=>!(key in params)))) {
if (rootParamKeys.length === 1) {
throw Object.defineProperty(new Error(`A required root parameter (${rootParamKeys[0]}) was not provided in generateStaticParams for ${page}, please provide at least one value.`), "__NEXT_ERROR_CODE", {
value: "E622",
enumerable: false,
configurable: true
});
}
throw Object.defineProperty(new Error(`Required root params (${rootParamKeys.join(', ')}) were not provided in generateStaticParams for ${page}, please provide at least one value for each.`), "__NEXT_ERROR_CODE", {
value: "E621",
enumerable: false,
configurable: true
});
}
}
for (const params of routeParams){
const item = {};
for (const { paramName: key, paramType } of pathnameSegments){
const { repeat, optional } = (0, _getsegmentparam.getParamProperties)(paramType);
let paramValue = params[key];
if (optional && params.hasOwnProperty(key) && (paramValue === null || paramValue === undefined || paramValue === false)) {
paramValue = [];
}
// A parameter is missing, so the rest of the params are not accessible.
// We only support this when the route has partial prerendering enabled.
// This will make it so that the remaining params are marked as missing so
// we can generate a fallback route for them.
if (!paramValue && isRoutePPREnabled) {
break;
}
// Perform validation for the parameter based on whether it's a repeat
// parameter or not.
if (repeat) {
if (!Array.isArray(paramValue)) {
throw Object.defineProperty(new Error(`A required parameter (${key}) was not provided as an array received ${typeof paramValue} in generateStaticParams for ${page}`), "__NEXT_ERROR_CODE", {
value: "E618",
enumerable: false,
configurable: true
});
}
} else {
if (typeof paramValue !== 'string') {
throw Object.defineProperty(new Error(`A required parameter (${key}) was not provided as a string received ${typeof paramValue} in generateStaticParams for ${page}`), "__NEXT_ERROR_CODE", {
value: "E617",
enumerable: false,
configurable: true
});
}
}
item[key] = paramValue;
}
valid.push(item);
}
return valid;
}
function assignStaticShellMetadata(prerenderedRoutes, pathnameSegments, computeRemainingPrerenderableParams) {
// If there are no routes to process, exit early.
if (prerenderedRoutes.length === 0) {
return;
}
// Initialize the root of the Trie. This node represents the starting point
// before any parameters have been considered.
const root = {
children: new Map(),
routes: []
};
// Phase 1: Build the Trie.
// Iterate over each prerendered route and insert it into the Trie.
// Each route's concrete parameter values form a path in the Trie.
for (const route of prerenderedRoutes){
let currentNode = root // Start building the path from the root for each route.
;
// Iterate through the sorted parameter keys. The order of keys is crucial
// for ensuring that routes with the same concrete parameters follow the
// same path in the Trie, regardless of the original order of properties
// in the `params` object.
for (const { paramName: key } of pathnameSegments){
// Check if the current route actually has a concrete value for this parameter.
// If a dynamic segment is not filled (i.e., it's a fallback), it won't have
// this property, and we stop building the path for this route at this point.
if (route.params.hasOwnProperty(key)) {
const value = route.params[key];
// Generate a unique key for the parameter's value. This is critical
// to prevent collisions between different data types that might have
// the same string representation (e.g., `['a', 'b']` vs `'a,b'`).
// A type prefix (`A:` for Array, `S:` for String, `U:` for undefined)
// is added to the value to prevent collisions. This ensures that
// different types with the same string representation are treated as
// distinct.
let valueKey;
if (Array.isArray(value)) {
valueKey = `A:${value.join(',')}`;
} else if (value === undefined) {
valueKey = `U:undefined`;
} else {
valueKey = `S:${value}`;
}
// Look for a child node corresponding to this `valueKey` from the `currentNode`.
let childNode = currentNode.children.get(valueKey);
if (!childNode) {
// If the child node doesn't exist, create a new one and add it to
// the current node's children.
childNode = {
children: new Map(),
routes: []
};
currentNode.children.set(valueKey, childNode);
}
// Move deeper into the Trie to the `childNode` for the next parameter.
currentNode = childNode;
}
}
// After processing all concrete parameters for the route, add the full
// `PrerenderedRoute` object to the `routes` array of the `currentNode`.
// This node represents the unique concrete parameter combination for this route.
currentNode.routes.push(route);
}
// Phase 2: Traverse the Trie to assign the `throwOnEmptyStaticShell` property.
// This is done using an iterative Depth-First Search (DFS) approach with an
// explicit stack to avoid JavaScript's recursion depth limits (stack overflow)
// for very deep routing structures.
const stack = [
root
] // Initialize the stack with the root node.
;
while(stack.length > 0){
const node = stack.pop()// Pop the next node to process from the stack.
;
// `hasChildren` indicates if this node has any more specific concrete
// parameter combinations branching off from it. If true, it means this
// node represents a prefix for other, more specific routes.
const hasChildren = node.children.size > 0;
// If the current node has routes associated with it (meaning, routes whose
// concrete parameters lead to this node's path in the Trie).
if (node.routes.length > 0) {
// Determine the minimum number of fallback parameters among all routes
// that are associated with this current Trie node. This is used to
// identify if a route should not throw on empty static shell relative to another route *at the same level*
// of concrete parameters, but with fewer fallback parameters.
let minFallbacks = Infinity;
for (const r of node.routes){
// `fallbackRouteParams?.length ?? 0` handles cases where `fallbackRouteParams`
// might be `undefined` or `null`, treating them as 0 length.
minFallbacks = Math.min(minFallbacks, r.fallbackRouteParams ? r.fallbackRouteParams.length : 0);
}
// Now, for each `PrerenderedRoute` associated with this node:
for (const route of node.routes){
// A route is ok not to throw on an empty static shell (and thus
// `throwOnEmptyStaticShell` should be `false`) if either of the
// following conditions is met:
// 1. `hasChildren` is true: This node has further concrete parameter children.
// This means the current route is a parent to more specific routes (e.g.,
// `/blog/[slug]` should not throw when concrete routes like `/blog/first-post` exist).
// OR
// 2. `route.fallbackRouteParams.length > minFallbacks`: This route has
// more fallback parameters than another route at the same Trie node.
// This implies the current route is a more general version that should not throw
// compared to a more specific route that has fewer fallback parameters
// (e.g., `/1234/[...slug]` should not throw relative to `/[id]/[...slug]`).
if (hasChildren || route.fallbackRouteParams && route.fallbackRouteParams.length > minFallbacks) {
route.throwOnEmptyStaticShell = false // Should not throw on empty static shell.
;
} else {
route.throwOnEmptyStaticShell = true // Should throw on empty static shell.
;
}
if (computeRemainingPrerenderableParams && route.fallbackRouteParams && route.fallbackRouteParams.length > 0) {
const fallbackRouteParamsByName = new Map(route.fallbackRouteParams.map((param)=>[
param.paramName,
param
]));
const remainingPrerenderableParams = [];
// Only unresolved pathname params that can still be filled by
// generateStaticParams belong here. Once we hit an unresolved param
// that is purely dynamic, the rest of the shell also stays dynamic
// and cannot be completed into a more specific prerendered shell.
for (const segment of pathnameSegments){
if (route.params.hasOwnProperty(segment.paramName)) {
continue;
}
if (!segment.hasGenerateStaticParams) {
break;
}
const fallbackRouteParam = fallbackRouteParamsByName.get(segment.paramName);
if (!fallbackRouteParam) {
break;
}
remainingPrerenderableParams.push(fallbackRouteParam);
}
route.remainingPrerenderableParams = remainingPrerenderableParams.length > 0 ? remainingPrerenderableParams : undefined;
}
}
}
// Add all children of the current node to the stack. This ensures that
// the traversal continues to explore deeper paths in the Trie.
for (const child of node.children.values()){
stack.push(child);
}
}
}
/**
* Calls a single generateStaticParams function within a WorkUnitStore context,
* making root param getters available during static param generation.
*/ async function callGenerateStaticParams(generateStaticParams, workUnitAsyncStorage, parentParams, rootParamKeys, implicitTags) {
const rootParams = {};
for (const key of rootParamKeys){
if (key in parentParams) {
rootParams[key] = parentParams[key];
}
}
const workUnitStore = {
type: 'generate-static-params',
phase: 'render',
implicitTags,
rootParams
};
return workUnitAsyncStorage.run(workUnitStore, generateStaticParams, {
params: parentParams
});
}
async function generateRouteStaticParams(segments, store, workUnitAsyncStorage, isRoutePPREnabled, rootParamKeys) {
// Early return if no segments to process
if (segments.length === 0) return [];
const implicitTags = await (0, _implicittags.getImplicitTags)(store.page, store.page, null);
const queue = [
{
segmentIndex: 0,
params: []
}
];
let currentParams = [];
while(queue.length > 0){
var _current_config;
const { segmentIndex, params } = queue.shift();
// If we've processed all segments, this is our final result
if (segmentIndex >= segments.length) {
currentParams = params;
break;
}
const current = segments[segmentIndex];
// Skip segments without generateStaticParams and continue to next
if (typeof current.generateStaticParams !== 'function') {
queue.push({
segmentIndex: segmentIndex + 1,
params
});
continue;
}
// Configure fetchCache if specified
if (((_current_config = current.config) == null ? void 0 : _current_config.fetchCache) !== undefined) {
store.fetchCache = current.config.fetchCache;
}
const nextParams = [];
// If there are parent params, we need to process them.
if (params.length > 0) {
// Process each parent parameter combination
for (const parentParams of params){
const result = await callGenerateStaticParams(current.generateStaticParams, workUnitAsyncStorage, parentParams, rootParamKeys, implicitTags);
if (result.length > 0) {
// Merge parent params with each result item
for (const item of result){
nextParams.push({
...parentParams,
...item
});
}
} else if (isRoutePPREnabled) {
(0, _emptygeneratestaticparamserror.throwEmptyGenerateStaticParamsError)();
} else {
// No results, just pass through parent params
nextParams.push(parentParams);
}
}
} else {
// No parent params, call generateStaticParams with empty object
const result = await callGenerateStaticParams(current.generateStaticParams, workUnitAsyncStorage, {}, rootParamKeys, implicitTags);
if (result.length === 0 && isRoutePPREnabled) {
(0, _emptygeneratestaticparamserror.throwEmptyGenerateStaticParamsError)();
}
nextParams.push(...result);
}
// Add next segment to work queue
queue.push({
segmentIndex: segmentIndex + 1,
params: nextParams
});
}
return currentParams;
}
function createReplacements(segment, paramValue) {
// Determine the prefix to use for the interception marker.
let prefix;
if (segment.paramType) {
prefix = (0, _interceptionprefixfromparamtype.interceptionPrefixFromParamType)(segment.paramType) ?? '';
} else {
prefix = '';
}
return {
pathname: prefix + (0, _utils.encodeParam)(paramValue, (value)=>// Only escape path delimiters if the value is a string, the following
// version will URL encode the value.
(0, _escapepathdelimiters.default)(value, true)),
encodedPathname: prefix + (0, _utils.encodeParam)(paramValue, // URL encode the value.
encodeURIComponent)
};
}
async function buildAppStaticPaths({ dir, page, route, distDir, cacheComponents, authInterrupts, segments, isrFlushToDisk, cacheHandler, cacheLifeProfiles, requestHeaders, cacheHandlers, cacheMaxMemorySize, fetchCacheKeyPrefix, nextConfigOutput, ComponentMod, isRoutePPREnabled = false, partialFallbacksEnabled = false, buildId, deploymentId, rootParamKeys }) {
if (segments.some((generate)=>{
var _generate_config;
return ((_generate_config = generate.config) == null ? void 0 : _generate_config.dynamicParams) === true;
}) && nextConfigOutput === 'export') {
throw Object.defineProperty(new Error('"dynamicParams: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/app/building-your-application/deploying/static-exports'), "__NEXT_ERROR_CODE", {
value: "E393",
enumerable: false,
configurable: true
});
}
ComponentMod.patchFetch();
const incrementalCache = await (0, _createincrementalcache.createIncrementalCache)({
dir,
distDir,
cacheHandler,
cacheHandlers,
requestHeaders,
fetchCacheKeyPrefix,
flushToDisk: isrFlushToDisk,
cacheMaxMemorySize
});
// Extract segments that contribute to the pathname.
// For AppPageRouteModule: Traverses the loader tree to find all segments (including
// interception routes in parallel slots) that match the pathname
// For AppRouteRouteModule: Filters the segments array to get non-parallel route params
const pathnameRouteParamSegments = (0, _utils.extractPathnameRouteParamSegments)(ComponentMod.routeModule, segments, route);
const afterRunner = new _runwithafter.AfterRunner();
const store = (0, _workstore.createWorkStore)({
page,
renderOpts: {
incrementalCache,
cacheLifeProfiles,
supportsDynamicResponse: true,
cacheComponents,
experimental: {
authInterrupts
},
waitUntil: afterRunner.context.waitUntil,
onClose: afterRunner.context.onClose,
onAfterTaskError: afterRunner.context.onTaskError
},
buildId,
deploymentId,
previouslyRevalidatedTags: []
});
const routeParams = await ComponentMod.workAsyncStorage.run(store, generateRouteStaticParams, segments, store, ComponentMod.workUnitAsyncStorage, isRoutePPREnabled, rootParamKeys);
const generatedParamNames = new Set();
for (const params of routeParams){
for (const paramName of Object.keys(params)){
generatedParamNames.add(paramName);
}
}
const prerenderablePathSegments = pathnameRouteParamSegments.map((segment)=>({
paramName: segment.paramName,
hasGenerateStaticParams: generatedParamNames.has(segment.paramName)
}));
await afterRunner.executeAfter();
let lastDynamicSegmentHadGenerateStaticParams = false;
for (const segment of segments){
var _segment_config;
// Check to see if there are any missing params for segments that have
// dynamicParams set to false.
if (segment.paramName && segment.paramType && ((_segment_config = segment.config) == null ? void 0 : _segment_config.dynamicParams) === false) {
for (const params of routeParams){
if (segment.paramName in params) continue;
const relative = segment.filePath ? _nodepath.default.relative(dir, segment.filePath) : undefined;
throw Object.defineProperty(new Error(`Segment "${relative}" exports "dynamicParams: false" but the param "${segment.paramName}" is missing from the generated route params.`), "__NEXT_ERROR_CODE", {
value: "E280",
enumerable: false,
configurable: true
});
}
}
if (segment.paramName && segment.paramType && typeof segment.generateStaticParams !== 'function') {
lastDynamicSegmentHadGenerateStaticParams = false;
} else if (typeof segment.generateStaticParams === 'function') {
lastDynamicSegmentHadGenerateStaticParams = true;
}
}
// Determine if all the segments have had their parameters provided.
const hadAllParamsGenerated = pathnameRouteParamSegments.length === 0 || routeParams.length > 0 && routeParams.every((params)=>{
for (const { paramName } of pathnameRouteParamSegments){
if (paramName in params) continue;
return false;
}
return true;
});
// TODO: dynamic params should be allowed to be granular per segment but
// we need additional information stored/leveraged in the prerender
// manifest to allow this behavior.
const dynamicParams = segments.every((segment)=>{
var _segment_config;
return ((_segment_config = segment.config) == null ? void 0 : _segment_config.dynamicParams) !== false;
});
const supportsRoutePreGeneration = hadAllParamsGenerated || !process.env.__NEXT_DEV_SERVER;
const fallbackMode = dynamicParams ? supportsRoutePreGeneration ? isRoutePPREnabled ? _fallback.FallbackMode.PRERENDER : _fallback.FallbackMode.BLOCKING_STATIC_RENDER : undefined : _fallback.FallbackMode.NOT_FOUND;
const prerenderedRoutesByPathname = new Map();
// Convert rootParamKeys to Set for O(1) lookup.
const rootParamSet = new Set(rootParamKeys);
if (hadAllParamsGenerated || isRoutePPREnabled) {
let paramsToProcess = routeParams;
if (isRoutePPREnabled) {
// Discover all unique combinations of the routeParams so we can generate
// routes that won't throw on empty static shell for each of them if
// they're available.
paramsToProcess = generateAllParamCombinations(pathnameRouteParamSegments, routeParams, rootParamKeys);
// Collect all the fallback route params for the segments.
const fallbackRouteParams = [];
for (const segment of segments){
if (!segment.paramName || !segment.paramType) continue;
fallbackRouteParams.push({
paramName: segment.paramName,
paramType: segment.paramType
});
}
// Add the base route, this is the route with all the placeholders as it's
// derived from the `page` string.
prerenderedRoutesByPathname.set(page, {
params: {},
pathname: page,
encodedPathname: page,
fallbackRouteParams,
fallbackMode: calculateFallbackMode(dynamicParams, rootParamKeys, fallbackMode),
fallbackRootParams: rootParamKeys,
throwOnEmptyStaticShell: true
});
}
filterUniqueParams(pathnameRouteParamSegments, validateParams(page, isRoutePPREnabled, pathnameRouteParamSegments, rootParamKeys, paramsToProcess)).forEach((params)=>{
let pathname = page;
let encodedPathname = page;
const fallbackRouteParams = [];
for (const { name, paramName, paramType } of pathnameRouteParamSegments){
const paramValue = params[paramName];
if (!paramValue) {
if (isRoutePPREnabled) {
// Mark remaining params as fallback params.
fallbackRouteParams.push({
paramName,
paramType
});
for(let i = pathnameRouteParamSegments.findIndex((param)=>param.paramName === paramName) + 1; i < pathnameRouteParamSegments.length; i++){
fallbackRouteParams.push({
paramName: pathnameRouteParamSegments[i].paramName,
paramType: pathnameRouteParamSegments[i].paramType
});
}
break;
} else {
// This route is not complete, and we aren't performing a partial
// prerender, so we should return, skipping this route.
return;
}
}
const replacements = createReplacements({
paramType
}, paramValue);
pathname = pathname.replace(name, // We're replacing the segment name with the replacement pathname
// which will include the interception marker prefix if it exists.
replacements.pathname);
encodedPathname = encodedPathname.replace(name, // We're replacing the segment name with the replacement encoded
// pathname which will include the encoded param value.
replacements.encodedPathname);
}
// Resolve all route params from the loader tree if this is from an
// app page. This processes both regular route params and parallel route params.
if ('loaderTree' in ComponentMod.routeModule.userland && Array.isArray(ComponentMod.routeModule.userland.loaderTree)) {
(0, _utils.resolveRouteParamsFromTree)(ComponentMod.routeModule.userland.loaderTree, params, route, fallbackRouteParams);
}
const fallbackRootParams = [];
for (const { paramName } of fallbackRouteParams){
// If the param is a root param then we can add it to the fallback
// root params.
if (rootParamSet.has(paramName)) {
fallbackRootParams.push(paramName);
}
}
pathname = (0, _utils.normalizePathname)(pathname);
prerenderedRoutesByPathname.set(pathname, {
params,
pathname,
encodedPathname: (0, _utils.normalizePathname)(encodedPathname),
fallbackRouteParams,
fallbackMode: calculateFallbackMode(dynamicParams, fallbackRootParams, fallbackMode),
fallbackRootParams,
throwOnEmptyStaticShell: true
});
});
}
const prerenderedRoutes = prerenderedRoutesByPathname.size > 0 || lastDynamicSegmentHadGenerateStaticParams ? [
...prerenderedRoutesByPathname.values()
] : undefined;
// Now we have to set the throwOnEmptyStaticShell for each of the routes.
if (prerenderedRoutes && cacheComponents) {
assignStaticShellMetadata(prerenderedRoutes, prerenderablePathSegments, partialFallbacksEnabled);
}
return {
fallbackMode,
prerenderedRoutes
};
}
//# sourceMappingURL=app.js.map

View File

@@ -0,0 +1,137 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "extractPathnameRouteParamSegmentsFromLoaderTree", {
enumerable: true,
get: function() {
return extractPathnameRouteParamSegmentsFromLoaderTree;
}
});
const _app = require("../../../shared/lib/router/routes/app");
const _parseloadertree = require("../../../shared/lib/router/utils/parse-loader-tree");
const _resolveparamvalue = require("../../../shared/lib/router/utils/resolve-param-value");
/**
* Validates that the static segments in currentPath match the corresponding
* segments in targetSegments. This ensures we only extract dynamic parameters
* that are part of the target pathname structure.
*
* Segments are compared literally - interception markers like "(.)photo" are
* part of the pathname and must match exactly.
*
* @example
* // Matching paths
* currentPath: ['blog', '(.)photo']
* targetSegments: ['blog', '(.)photo', '[id]']
* → Returns true (both static segments match exactly)
*
* @example
* // Non-matching paths
* currentPath: ['blog', '(.)photo']
* targetSegments: ['blog', 'photo', '[id]']
* → Returns false (segments don't match - marker is part of pathname)
*
* @param currentPath - The accumulated path segments from the loader tree
* @param targetSegments - The target pathname split into segments
* @returns true if all static segments match, false otherwise
*/ function validatePrefixMatch(currentPath, route) {
for(let i = 0; i < currentPath.length; i++){
const pathSegment = currentPath[i];
const targetPathSegment = route.segments[i];
// Type mismatch - one is static, one is dynamic
if (pathSegment.type !== targetPathSegment.type) {
return false;
}
// One has an interception marker, the other doesn't.
if (pathSegment.interceptionMarker !== targetPathSegment.interceptionMarker) {
return false;
}
// Both are static but names don't match
if (pathSegment.type === 'static' && targetPathSegment.type === 'static' && pathSegment.name !== targetPathSegment.name) {
return false;
} else if (pathSegment.type === 'dynamic' && targetPathSegment.type === 'dynamic' && pathSegment.param.paramType !== targetPathSegment.param.paramType && pathSegment.param.paramName !== targetPathSegment.param.paramName) {
return false;
}
}
return true;
}
function extractPathnameRouteParamSegmentsFromLoaderTree(loaderTree, route) {
const pathnameRouteParamSegments = [];
const params = {};
// BFS traversal with depth and path tracking
const queue = [
{
tree: loaderTree,
depth: 0,
currentPath: []
}
];
while(queue.length > 0){
const { tree, depth, currentPath } = queue.shift();
const { segment, parallelRoutes } = (0, _parseloadertree.parseLoaderTree)(tree);
// Build the path for the current node
let updatedPath = currentPath;
let nextDepth = depth;
const appSegment = (0, _app.parseAppRouteSegment)(segment);
// Only add to path if it's a real segment that appears in the URL
// Route groups and parallel markers don't contribute to URL pathname
if (appSegment && appSegment.type !== 'route-group' && appSegment.type !== 'parallel-route') {
updatedPath = [
...currentPath,
appSegment
];
nextDepth = depth + 1;
}
// Check if this segment has a param and matches the target pathname at this depth
if ((appSegment == null ? void 0 : appSegment.type) === 'dynamic') {
const { paramName, paramType } = appSegment.param;
// Check if this segment is at the correct depth in the target pathname
// A segment matches if:
// 1. There's a dynamic segment at this depth in the pathname
// 2. The parameter names match (e.g., [id] matches [id], not [category])
// 3. The static segments leading up to this point match (prefix check)
if (depth < route.segments.length) {
const targetSegment = route.segments[depth];
// Match if the target pathname has a dynamic segment at this depth
if (targetSegment.type === 'dynamic') {
// Check that parameter names match exactly
// This prevents [category] from matching against /[id]
if (paramName !== targetSegment.param.paramName) {
continue; // Different param names, skip this segment
}
// Validate that the path leading up to this dynamic segment matches
// the target pathname. This prevents false matches like extracting
// [slug] from "/news/[slug]" when the tree has "/blog/[slug]"
if (validatePrefixMatch(currentPath, route)) {
pathnameRouteParamSegments.push({
name: segment,
paramName,
paramType
});
}
}
}
// Resolve parameter value if it's not already known.
if (!params.hasOwnProperty(paramName)) {
const paramValue = (0, _resolveparamvalue.resolveParamValue)(paramName, paramType, depth, route, params);
if (paramValue !== undefined) {
params[paramName] = paramValue;
}
}
}
// Continue traversing all parallel routes to find matching segments
for (const parallelRoute of Object.values(parallelRoutes)){
queue.push({
tree: parallelRoute,
depth: nextDepth,
currentPath: updatedPath
});
}
}
return {
pathnameRouteParamSegments,
params
};
}
//# sourceMappingURL=extract-pathname-route-param-segments-from-loader-tree.js.map

View File

@@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "buildPagesStaticPaths", {
enumerable: true,
get: function() {
return buildPagesStaticPaths;
}
});
const _normalizelocalepath = require("../../shared/lib/i18n/normalize-locale-path");
const _fallback = require("../../lib/fallback");
const _escapepathdelimiters = /*#__PURE__*/ _interop_require_default(require("../../shared/lib/router/utils/escape-path-delimiters"));
const _removetrailingslash = require("../../shared/lib/router/utils/remove-trailing-slash");
const _routematcher = require("../../shared/lib/router/utils/route-matcher");
const _routeregex = require("../../shared/lib/router/utils/route-regex");
const _utils = require("./utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function buildPagesStaticPaths({ page, getStaticPaths, configFileName, locales, defaultLocale }) {
const prerenderedRoutesByPathname = new Map();
const _routeRegex = (0, _routeregex.getRouteRegex)(page);
const _routeMatcher = (0, _routematcher.getRouteMatcher)(_routeRegex);
// Get the default list of allowed params.
const routeParameterKeys = Object.keys(_routeMatcher(page));
const staticPathsResult = await getStaticPaths({
// We create a copy here to avoid having the types of `getStaticPaths`
// change. This ensures that users can't mutate this array and have it
// poison the reference.
locales: [
...locales ?? []
],
defaultLocale
});
const expectedReturnVal = `Expected: { paths: [], fallback: boolean }\n` + `See here for more info: https://nextjs.org/docs/messages/invalid-getstaticpaths-value`;
if (!staticPathsResult || typeof staticPathsResult !== 'object' || Array.isArray(staticPathsResult)) {
throw Object.defineProperty(new Error(`Invalid value returned from getStaticPaths in ${page}. Received ${typeof staticPathsResult} ${expectedReturnVal}`), "__NEXT_ERROR_CODE", {
value: "E1004",
enumerable: false,
configurable: true
});
}
const invalidStaticPathKeys = Object.keys(staticPathsResult).filter((key)=>!(key === 'paths' || key === 'fallback'));
if (invalidStaticPathKeys.length > 0) {
throw Object.defineProperty(new Error(`Extra keys returned from getStaticPaths in ${page} (${invalidStaticPathKeys.join(', ')}) ${expectedReturnVal}`), "__NEXT_ERROR_CODE", {
value: "E1047",
enumerable: false,
configurable: true
});
}
if (!(typeof staticPathsResult.fallback === 'boolean' || staticPathsResult.fallback === 'blocking')) {
throw Object.defineProperty(new Error(`The \`fallback\` key must be returned from getStaticPaths in ${page}.\n` + expectedReturnVal), "__NEXT_ERROR_CODE", {
value: "E1034",
enumerable: false,
configurable: true
});
}
const toPrerender = staticPathsResult.paths;
if (!Array.isArray(toPrerender)) {
throw Object.defineProperty(new Error(`Invalid \`paths\` value returned from getStaticPaths in ${page}.\n` + `\`paths\` must be an array of strings or objects of shape { params: [key: string]: string }`), "__NEXT_ERROR_CODE", {
value: "E83",
enumerable: false,
configurable: true
});
}
toPrerender.forEach((entry)=>{
// For a string-provided path, we must make sure it matches the dynamic
// route.
if (typeof entry === 'string') {
entry = (0, _removetrailingslash.removeTrailingSlash)(entry);
const localePathResult = (0, _normalizelocalepath.normalizeLocalePath)(entry, locales);
let cleanedEntry = entry;
if (localePathResult.detectedLocale) {
cleanedEntry = entry.slice(localePathResult.detectedLocale.length + 1);
} else if (defaultLocale) {
entry = `/${defaultLocale}${entry}`;
}
const params = _routeMatcher(cleanedEntry);
if (!params) {
throw Object.defineProperty(new Error(`The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.`), "__NEXT_ERROR_CODE", {
value: "E481",
enumerable: false,
configurable: true
});
}
// If leveraging the string paths variant the entry should already be
// encoded so we decode the segments ensuring we only escape path
// delimiters
const pathname = entry.split('/').map((segment)=>(0, _escapepathdelimiters.default)(decodeURIComponent(segment), true)).join('/');
if (!prerenderedRoutesByPathname.has(pathname)) {
prerenderedRoutesByPathname.set(pathname, {
params,
pathname,
encodedPathname: entry,
fallbackRouteParams: undefined,
fallbackMode: (0, _fallback.parseStaticPathsResult)(staticPathsResult.fallback),
fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined
});
}
} else {
const invalidKeys = Object.keys(entry).filter((key)=>key !== 'params' && key !== 'locale');
if (invalidKeys.length) {
throw Object.defineProperty(new Error(`Additional keys were returned from \`getStaticPaths\` in page "${page}". ` + `URL Parameters intended for this dynamic route must be nested under the \`params\` key, i.e.:` + `\n\n\treturn { params: { ${routeParameterKeys.map((k)=>`${k}: ...`).join(', ')} } }` + `\n\nKeys that need to be moved: ${invalidKeys.join(', ')}.\n`), "__NEXT_ERROR_CODE", {
value: "E322",
enumerable: false,
configurable: true
});
}
const { params = {} } = entry;
let builtPage = page;
let encodedBuiltPage = page;
routeParameterKeys.forEach((validParamKey)=>{
const { repeat, optional } = _routeRegex.groups[validParamKey];
let paramValue = params[validParamKey];
if (optional && params.hasOwnProperty(validParamKey) && (paramValue === null || paramValue === undefined || paramValue === false)) {
paramValue = [];
}
if (repeat && !Array.isArray(paramValue) || !repeat && typeof paramValue !== 'string' || typeof paramValue === 'undefined') {
throw Object.defineProperty(new Error(`A required parameter (${validParamKey}) was not provided as ${repeat ? 'an array' : 'a string'} received ${typeof paramValue} in getStaticPaths for ${page}`), "__NEXT_ERROR_CODE", {
value: "E620",
enumerable: false,
configurable: true
});
}
let replaced = `[${repeat ? '...' : ''}${validParamKey}]`;
if (optional) {
replaced = `[${replaced}]`;
}
builtPage = builtPage.replace(replaced, (0, _utils.encodeParam)(paramValue, (value)=>(0, _escapepathdelimiters.default)(value, true)));
encodedBuiltPage = encodedBuiltPage.replace(replaced, (0, _utils.encodeParam)(paramValue, encodeURIComponent));
});
if (!builtPage && !encodedBuiltPage) {
return;
}
if (entry.locale && !(locales == null ? void 0 : locales.includes(entry.locale))) {
throw Object.defineProperty(new Error(`Invalid locale returned from getStaticPaths for ${page}, the locale ${entry.locale} is not specified in ${configFileName}`), "__NEXT_ERROR_CODE", {
value: "E358",
enumerable: false,
configurable: true
});
}
const curLocale = entry.locale || defaultLocale || '';
const pathname = (0, _utils.normalizePathname)(`${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}`);
if (!prerenderedRoutesByPathname.has(pathname)) {
prerenderedRoutesByPathname.set(pathname, {
params,
pathname,
encodedPathname: (0, _utils.normalizePathname)(`${curLocale ? `/${curLocale}` : ''}${curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage}`),
fallbackRouteParams: undefined,
fallbackMode: (0, _fallback.parseStaticPathsResult)(staticPathsResult.fallback),
fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined
});
}
}
});
return {
fallbackMode: (0, _fallback.parseStaticPathsResult)(staticPathsResult.fallback),
prerenderedRoutes: [
...prerenderedRoutesByPathname.values()
]
};
}
//# sourceMappingURL=pages.js.map

View File

@@ -0,0 +1,119 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
encodeParam: null,
extractPathnameRouteParamSegments: null,
extractPathnameRouteParamSegmentsFromSegments: null,
normalizePathname: null,
resolveRouteParamsFromTree: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
encodeParam: function() {
return encodeParam;
},
extractPathnameRouteParamSegments: function() {
return extractPathnameRouteParamSegments;
},
extractPathnameRouteParamSegmentsFromSegments: function() {
return extractPathnameRouteParamSegmentsFromSegments;
},
normalizePathname: function() {
return normalizePathname;
},
resolveRouteParamsFromTree: function() {
return resolveRouteParamsFromTree;
}
});
const _checks = require("../../server/route-modules/checks");
const _app = require("../../shared/lib/router/routes/app");
const _parseloadertree = require("../../shared/lib/router/utils/parse-loader-tree");
const _extractpathnamerouteparamsegmentsfromloadertree = require("./app/extract-pathname-route-param-segments-from-loader-tree");
const _resolveparamvalue = require("../../shared/lib/router/utils/resolve-param-value");
function encodeParam(value, encoder) {
let replaceValue;
if (Array.isArray(value)) {
replaceValue = value.map(encoder).join('/');
} else {
replaceValue = encoder(value);
}
return replaceValue;
}
function normalizePathname(pathname) {
return pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, '');
}
function extractPathnameRouteParamSegments(routeModule, segments, route) {
// For AppPageRouteModule, use the loaderTree traversal approach
if ((0, _checks.isAppPageRouteModule)(routeModule)) {
const { pathnameRouteParamSegments } = (0, _extractpathnamerouteparamsegmentsfromloadertree.extractPathnameRouteParamSegmentsFromLoaderTree)(routeModule.userland.loaderTree, route);
return pathnameRouteParamSegments;
}
return extractPathnameRouteParamSegmentsFromSegments(segments);
}
function extractPathnameRouteParamSegmentsFromSegments(segments) {
// TODO: should we consider what values are already present in the page?
// For AppRouteRouteModule, filter the segments array to get the route params
// that contribute to the pathname.
const result = [];
for (const segment of segments){
// Skip segments without param info.
if (!segment.paramName || !segment.paramType) continue;
// Collect all the route param keys that contribute to the pathname.
result.push({
name: segment.name,
paramName: segment.paramName,
paramType: segment.paramType
});
}
return result;
}
function resolveRouteParamsFromTree(loaderTree, params, route, fallbackRouteParams) {
// Stack-based traversal with depth tracking
const stack = [
{
tree: loaderTree,
depth: 0
}
];
while(stack.length > 0){
const { tree, depth } = stack.pop();
const { segment, parallelRoutes } = (0, _parseloadertree.parseLoaderTree)(tree);
const appSegment = (0, _app.parseAppRouteSegment)(segment);
// If this segment is a route parameter, then we should process it if it's
// not already known and is not already marked as a fallback route param.
if ((appSegment == null ? void 0 : appSegment.type) === 'dynamic' && !params.hasOwnProperty(appSegment.param.paramName) && !fallbackRouteParams.some((param)=>param.paramName === appSegment.param.paramName)) {
const { paramName, paramType } = appSegment.param;
const paramValue = (0, _resolveparamvalue.resolveParamValue)(paramName, paramType, depth, route, params);
if (paramValue !== undefined) {
params[paramName] = paramValue;
} else if (paramType !== 'optional-catchall') {
// If we couldn't resolve the param, mark it as a fallback
fallbackRouteParams.push({
paramName,
paramType
});
}
}
// Calculate next depth - increment if this is not a route group and not empty
let nextDepth = depth;
if (appSegment && appSegment.type !== 'route-group' && appSegment.type !== 'parallel-route') {
nextDepth++;
}
// Add all parallel routes to the stack for processing.
for (const parallelRoute of Object.values(parallelRoutes)){
stack.push({
tree: parallelRoute,
depth: nextDepth
});
}
}
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__nextjs_pure", {
enumerable: true,
get: function() {
return __nextjs_pure;
}
});
function __nextjs_pure(expr) {
return expr;
}
//# sourceMappingURL=helpers.js.map

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
/**
* This module provides a way to install SWC bindings without eagerly loading the entire swc/index module.
*
* The swc/index module can transitively load other modules (like webpack-config) that import React,
* and React's entry point checks process.env.NODE_ENV at require time to decide whether to load
* the development or production bundle. By deferring the require of swc/index until this function
* is called, we ensure NODE_ENV is set before React is loaded.
*/ /**
* Loads and caches the native bindings. This is idempotent and should be called early so bindings
* can be accessed synchronously later.
*
* @param useWasmBinary - Whether to use WASM bindings instead of native bindings
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "installBindings", {
enumerable: true,
get: function() {
return installBindings;
}
});
async function installBindings(useWasmBinary = false) {
// Lazy require to avoid loading swc/index (and transitively webpack-config/React)
// before NODE_ENV is set
const { loadBindings } = require('./index');
await loadBindings(useWasmBinary);
}
//# sourceMappingURL=install-bindings.js.map

View File

@@ -0,0 +1,76 @@
/*
Copyright (c) 2021 The swc Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
const _vm = /*#__PURE__*/ _interop_require_default(require("vm"));
const _index = require("./index");
const _options = require("./options");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
// Jest use the `vm` [Module API](https://nodejs.org/api/vm.html#vm_class_vm_module) for ESM.
// see https://github.com/facebook/jest/issues/9430
const isSupportEsm = 'Module' in _vm.default;
function getJestConfig(jestConfig) {
return 'config' in jestConfig ? jestConfig.config : jestConfig;
}
function isEsm(isEsmProject, filename, jestConfig) {
var _jestConfig_extensionsToTreatAsEsm;
return /\.jsx?$/.test(filename) && isEsmProject || ((_jestConfig_extensionsToTreatAsEsm = jestConfig.extensionsToTreatAsEsm) == null ? void 0 : _jestConfig_extensionsToTreatAsEsm.some((ext)=>filename.endsWith(ext)));
}
const createTransformer = (inputOptions)=>({
process (src, filename, jestOptions) {
const jestConfig = getJestConfig(jestOptions);
const swcTransformOpts = (0, _options.getJestSWCOptions)({
isServer: jestConfig.testEnvironment === 'node' || jestConfig.testEnvironment.includes('jest-environment-node'),
filename,
jsConfig: inputOptions == null ? void 0 : inputOptions.jsConfig,
resolvedBaseUrl: inputOptions == null ? void 0 : inputOptions.resolvedBaseUrl,
pagesDir: inputOptions == null ? void 0 : inputOptions.pagesDir,
serverComponents: inputOptions == null ? void 0 : inputOptions.serverComponents,
modularizeImports: inputOptions == null ? void 0 : inputOptions.modularizeImports,
swcPlugins: inputOptions == null ? void 0 : inputOptions.swcPlugins,
compilerOptions: inputOptions == null ? void 0 : inputOptions.compilerOptions,
imageConfig: inputOptions == null ? void 0 : inputOptions.imageConfig,
serverReferenceHashSalt: '',
esm: isSupportEsm && isEsm(Boolean(inputOptions == null ? void 0 : inputOptions.isEsmProject), filename, jestConfig)
});
return (0, _index.transformSync)(src, {
...swcTransformOpts,
filename
});
}
});
module.exports = {
createTransformer
};
//# sourceMappingURL=jest-transformer.js.map

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "runLoaderWorkerPool", {
enumerable: true,
get: function() {
return runLoaderWorkerPool;
}
});
const _worker_threads = require("worker_threads");
const loaderWorkers = {};
function getPoolId(cwd, filename) {
return `${cwd}:${filename}`;
}
async function runLoaderWorkerPool(bindings, bindingPath) {
bindings.registerWorkerScheduler((creation)=>{
const { options: { filename, cwd } } = creation;
const poolId = getPoolId(cwd, filename);
const worker = new _worker_threads.Worker(/* turbopackIgnore: true*/ filename, {
workerData: {
bindingPath,
cwd
}
});
// This will cause handing when run in jest worker, but not as a first level thread of nodejs thread
// worker.unref()
const workers = loaderWorkers[poolId] || (loaderWorkers[poolId] = new Map());
workers.set(worker.threadId, worker);
}, (termination)=>{
var _workers_get;
const { options: { filename, cwd }, workerId } = termination;
const poolId = getPoolId(cwd, filename);
const workers = loaderWorkers[poolId];
(_workers_get = workers.get(workerId)) == null ? void 0 : _workers_get.terminate();
workers.delete(workerId);
});
}
//# sourceMappingURL=loaderWorkerPool.js.map

View File

@@ -0,0 +1,403 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getJestSWCOptions: null,
getLoaderSWCOptions: null,
getParserOptions: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getJestSWCOptions: function() {
return getJestSWCOptions;
},
getLoaderSWCOptions: function() {
return getLoaderSWCOptions;
},
getParserOptions: function() {
return getParserOptions;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _constants = require("../../lib/constants");
const _utils = require("../utils");
const _escaperegexp = require("../../shared/lib/escape-regexp");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const nextDirname = _path.default.dirname(require.resolve('next/package.json'));
const nextDistPath = new RegExp(`${(0, _escaperegexp.escapeStringRegexp)(nextDirname)}[\\/]dist[\\/](shared[\\/]lib|client|pages)`);
const nodeModulesPath = /[\\/]node_modules[\\/]/;
const regeneratorRuntimePath = require.resolve('next/dist/compiled/regenerator-runtime');
function isTypeScriptFile(filename) {
return filename.endsWith('.ts') || filename.endsWith('.tsx');
}
function isCommonJSFile(filename) {
return filename.endsWith('.cjs');
}
// Ensure Next.js internals and .cjs files are output as CJS modules,
// By default all modules are output as ESM or will treated as CJS if next-swc/auto-cjs plugin detects file is CJS.
function shouldOutputCommonJs(filename) {
return isCommonJSFile(filename) || nextDistPath.test(filename);
}
function getParserOptions({ filename, jsConfig, ...rest }) {
var _jsConfig_compilerOptions;
const isTSFile = filename.endsWith('.ts');
const hasTsSyntax = isTypeScriptFile(filename);
const enableDecorators = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.experimentalDecorators);
return {
...rest,
syntax: hasTsSyntax ? 'typescript' : 'ecmascript',
dynamicImport: true,
decorators: enableDecorators,
// Exclude regular TypeScript files from React transformation to prevent e.g. generic parameters and angle-bracket type assertion from being interpreted as JSX tags.
[hasTsSyntax ? 'tsx' : 'jsx']: !isTSFile,
importAssertions: true
};
}
function getBaseSWCOptions({ filename, jest, development, hasReactRefresh, globalWindow, esm, modularizeImports, swcPlugins, compilerOptions, resolvedBaseUrl, jsConfig, supportedBrowsers, swcCacheDir, serverComponents, serverReferenceHashSalt, bundleLayer, isCacheComponents, cacheHandlers, useCacheEnabled, taintEnabled, trackDynamicImports, pageExtensions }) {
var _jsConfig_compilerOptions, _jsConfig_compilerOptions1, _jsConfig_compilerOptions2, _jsConfig_compilerOptions3, _jsConfig_compilerOptions4, _jsConfig_experimental;
const isReactServerLayer = (0, _utils.shouldUseReactServerCondition)(bundleLayer);
const isAppRouterPagesLayer = (0, _utils.isWebpackAppPagesLayer)(bundleLayer);
const parserConfig = getParserOptions({
filename,
jsConfig
});
const paths = jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.paths;
const enableDecorators = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions1 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions1.experimentalDecorators);
const emitDecoratorMetadata = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions2 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions2.emitDecoratorMetadata);
const useDefineForClassFields = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions3 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions3.useDefineForClassFields);
const plugins = (swcPlugins ?? []).filter(Array.isArray).map(([name, options])=>[
require.resolve(name),
options
]);
return {
jsc: {
...resolvedBaseUrl && paths ? {
baseUrl: resolvedBaseUrl.baseUrl,
paths
} : {},
externalHelpers: !process.versions.pnp && !jest,
parser: parserConfig,
experimental: {
keepImportAttributes: true,
emitAssertForImportAttributes: true,
plugins,
cacheRoot: swcCacheDir
},
transform: {
// Enables https://github.com/swc-project/swc/blob/0359deb4841be743d73db4536d4a22ac797d7f65/crates/swc_ecma_ext_transforms/src/jest.rs
...jest ? {
hidden: {
jest: true
}
} : {},
legacyDecorator: enableDecorators,
decoratorMetadata: emitDecoratorMetadata,
useDefineForClassFields: useDefineForClassFields,
react: {
importSource: (jsConfig == null ? void 0 : (_jsConfig_compilerOptions4 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions4.jsxImportSource) ?? ((compilerOptions == null ? void 0 : compilerOptions.emotion) && !isReactServerLayer ? '@emotion/react' : 'react'),
runtime: 'automatic',
pragmaFrag: 'React.Fragment',
throwIfNamespace: true,
development: !!development,
useBuiltins: true,
refresh: !!hasReactRefresh
},
optimizer: {
simplify: false,
globals: jest ? undefined : {
typeofs: {
window: globalWindow ? 'object' : 'undefined'
},
envs: {
NODE_ENV: development ? '"development"' : '"production"'
}
}
},
regenerator: {
importPath: regeneratorRuntimePath
}
}
},
sourceMaps: jest ? 'inline' : undefined,
removeConsole: compilerOptions == null ? void 0 : compilerOptions.removeConsole,
// disable "reactRemoveProperties" when "jest" is true
// otherwise the setting from next.config.js will be used
reactRemoveProperties: jest ? false : compilerOptions == null ? void 0 : compilerOptions.reactRemoveProperties,
// Map the k-v map to an array of pairs.
modularizeImports: modularizeImports ? Object.fromEntries(Object.entries(modularizeImports).map(([mod, config])=>[
mod,
{
...config,
transform: typeof config.transform === 'string' ? config.transform : Object.entries(config.transform).map(([key, value])=>[
key,
value
])
}
])) : undefined,
relay: compilerOptions == null ? void 0 : compilerOptions.relay,
// Always transform styled-jsx and error when `client-only` condition is triggered
styledJsx: (compilerOptions == null ? void 0 : compilerOptions.styledJsx) ?? {
useLightningcss: (jsConfig == null ? void 0 : (_jsConfig_experimental = jsConfig.experimental) == null ? void 0 : _jsConfig_experimental.useLightningcss) ?? false
},
// Disable css-in-js libs (without client-only integration) transform on server layer for server components
...!isReactServerLayer && {
emotion: getEmotionOptions(compilerOptions == null ? void 0 : compilerOptions.emotion, development),
styledComponents: getStyledComponentsOptions(compilerOptions == null ? void 0 : compilerOptions.styledComponents, development)
},
serverComponents: serverComponents && !jest ? {
isReactServerLayer,
cacheComponentsEnabled: isCacheComponents,
useCacheEnabled,
taintEnabled,
pageExtensions: pageExtensions || []
} : undefined,
serverActions: isAppRouterPagesLayer && !jest ? {
isReactServerLayer,
isDevelopment: development,
useCacheEnabled,
hashSalt: serverReferenceHashSalt,
cacheKinds: [
'default',
'remote',
'private'
].concat(cacheHandlers ? Object.keys(cacheHandlers) : [])
} : undefined,
// For app router we prefer to bundle ESM,
// On server side of pages router we prefer CJS.
preferEsm: esm,
lintCodemodComments: true,
trackDynamicImports: trackDynamicImports,
debugFunctionName: development,
...supportedBrowsers && supportedBrowsers.length > 0 ? {
cssEnv: {
targets: supportedBrowsers
}
} : {}
};
}
function getStyledComponentsOptions(styledComponentsConfig, development) {
if (!styledComponentsConfig) {
return null;
} else if (typeof styledComponentsConfig === 'object') {
return {
...styledComponentsConfig,
displayName: styledComponentsConfig.displayName ?? Boolean(development)
};
} else {
return {
displayName: Boolean(development)
};
}
}
function getEmotionOptions(emotionConfig, development) {
if (!emotionConfig) {
return null;
}
let autoLabel = !!development;
if (typeof emotionConfig === 'object' && emotionConfig.autoLabel) {
switch(emotionConfig.autoLabel){
case 'never':
autoLabel = false;
break;
case 'always':
autoLabel = true;
break;
case 'dev-only':
break;
default:
emotionConfig.autoLabel;
}
}
return {
enabled: true,
autoLabel,
sourcemap: development,
...typeof emotionConfig === 'object' && {
importMap: emotionConfig.importMap,
labelFormat: emotionConfig.labelFormat,
sourcemap: development && emotionConfig.sourceMap
}
};
}
function getJestSWCOptions({ isServer, filename, esm, modularizeImports, swcPlugins, compilerOptions, jsConfig, resolvedBaseUrl, pagesDir, imageConfig, serverReferenceHashSalt }) {
let baseOptions = getBaseSWCOptions({
filename,
jest: true,
development: false,
hasReactRefresh: false,
globalWindow: !isServer,
modularizeImports,
swcPlugins,
compilerOptions,
jsConfig,
resolvedBaseUrl,
supportedBrowsers: undefined,
esm,
// Don't apply server layer transformations for Jest
// Disable server / client graph assertions for Jest
bundleLayer: undefined,
serverComponents: false,
serverReferenceHashSalt
});
// In production, webpack DefinePlugin replaces process.env.__NEXT_IMAGE_OPTS
// with an object literal at compile time. Emulate that here by enabling
// SWC's optimizer globals.envs so the same compile-time replacement happens
// during Jest transforms.
if (imageConfig) {
var _baseOptions_jsc_transform_optimizer_globals;
baseOptions.jsc.transform.optimizer.globals = {
envs: {
...(_baseOptions_jsc_transform_optimizer_globals = baseOptions.jsc.transform.optimizer.globals) == null ? void 0 : _baseOptions_jsc_transform_optimizer_globals.envs,
__NEXT_IMAGE_OPTS: JSON.stringify(imageConfig)
}
};
}
const useCjsModules = shouldOutputCommonJs(filename);
return {
...baseOptions,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node
}
},
module: {
type: esm && !useCjsModules ? 'es6' : 'commonjs'
},
disableNextSsg: true,
pagesDir
};
}
function getLoaderSWCOptions({ // This is not passed yet as "paths" resolving is handled by webpack currently.
// resolvedBaseUrl,
filename, development, isServer, pagesDir, appDir, isPageFile, isCacheComponents, hasReactRefresh, modularizeImports, optimizeServerReact, optimizePackageImports, swcPlugins, compilerOptions, jsConfig, supportedBrowsers, swcCacheDir, relativeFilePathFromRoot, serverComponents, serverReferenceHashSalt, bundleLayer, esm, cacheHandlers, useCacheEnabled, taintEnabled, trackDynamicImports, pageExtensions }) {
let baseOptions = getBaseSWCOptions({
filename,
development,
globalWindow: !isServer,
hasReactRefresh,
modularizeImports,
swcPlugins,
compilerOptions,
jsConfig,
// resolvedBaseUrl,
supportedBrowsers,
swcCacheDir,
bundleLayer,
serverComponents,
serverReferenceHashSalt,
esm: !!esm,
isCacheComponents,
cacheHandlers,
useCacheEnabled,
taintEnabled,
trackDynamicImports,
pageExtensions
});
baseOptions.fontLoaders = {
fontLoaders: [
'next/font/local',
'next/font/google'
],
relativeFilePathFromRoot
};
baseOptions.cjsRequireOptimizer = {
packages: {
'next/server': {
transforms: {
NextRequest: 'next/dist/server/web/spec-extension/request',
NextResponse: 'next/dist/server/web/spec-extension/response',
ImageResponse: 'next/dist/server/web/spec-extension/image-response',
userAgentFromString: 'next/dist/server/web/spec-extension/user-agent',
userAgent: 'next/dist/server/web/spec-extension/user-agent'
}
}
}
};
if (optimizeServerReact && isServer && !development) {
baseOptions.optimizeServerReact = {
optimize_use_state: false
};
}
// Modularize import optimization for barrel files
if (optimizePackageImports) {
baseOptions.autoModularizeImports = {
packages: optimizePackageImports
};
}
const isNodeModules = nodeModulesPath.test(filename);
const isAppBrowserLayer = bundleLayer === _constants.WEBPACK_LAYERS.appPagesBrowser;
const moduleResolutionConfig = shouldOutputCommonJs(filename) ? {
module: {
type: 'commonjs'
}
} : {};
let options;
if (isServer) {
options = {
...baseOptions,
...moduleResolutionConfig,
// Disables getStaticProps/getServerSideProps tree shaking on the server compilation for pages
disableNextSsg: true,
isDevelopment: development,
isServerCompiler: isServer,
pagesDir,
appDir,
preferEsm: !!esm,
isPageFile,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node
}
}
};
} else {
options = {
...baseOptions,
...moduleResolutionConfig,
disableNextSsg: !isPageFile,
isDevelopment: development,
isServerCompiler: isServer,
pagesDir,
appDir,
isPageFile,
...supportedBrowsers && supportedBrowsers.length > 0 ? {
env: {
targets: supportedBrowsers
}
} : {}
};
if (!options.env) {
// Matches default @babel/preset-env behavior
options.jsc.target = 'es5';
}
}
// For node_modules in app browser layer, we don't need to do any server side transformation.
// Only keep server actions transform to discover server actions from client components.
if (isAppBrowserLayer && isNodeModules) {
var _options_jsc_transform_optimizer_globals;
options.disableNextSsg = true;
options.isPageFile = false;
options.optimizeServerReact = undefined;
options.cjsRequireOptimizer = undefined;
// Disable optimizer for node_modules in app browser layer, to avoid unnecessary replacement.
// e.g. typeof window could result differently in js worker or browser.
if (((_options_jsc_transform_optimizer_globals = options.jsc.transform.optimizer.globals) == null ? void 0 : _options_jsc_transform_optimizer_globals.typeofs) && !filename.includes(nextDirname)) {
delete options.jsc.transform.optimizer.globals.typeofs.window;
}
}
return options;
}
//# sourceMappingURL=options.js.map

View File

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

1216
.next/standalone/node_modules/next/dist/build/utils.js generated vendored Normal file

File diff suppressed because it is too large Load Diff