Initial boiler plate project

This commit is contained in:
2024-09-24 03:52:46 +00:00
parent 6120b2d6c3
commit 154b93e267
10034 changed files with 2079352 additions and 2 deletions

View File

@ -0,0 +1,23 @@
import type { Module } from '@swc/core';
export declare class NoSuchDeclarationError extends Error {
}
export declare class UnsupportedValueError extends Error {
/** @example `config.runtime[0].value` */
path?: string;
constructor(message: string, paths?: string[]);
}
/**
* Extracts the value of an exported const variable named `exportedName`
* (e.g. "export const config = { runtime: 'edge' }") from swc's AST.
* The value must be one of (or throws UnsupportedValueError):
* - string
* - boolean
* - number
* - null
* - undefined
* - array containing values listed in this list
* - object containing values listed in this list
*
* Throws NoSuchDeclarationError if the declaration is not found.
*/
export declare function extractExportedConstValue(module: Module, exportedName: string): any;

View File

@ -0,0 +1,200 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NoSuchDeclarationError: null,
UnsupportedValueError: null,
extractExportedConstValue: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NoSuchDeclarationError: function() {
return NoSuchDeclarationError;
},
UnsupportedValueError: function() {
return UnsupportedValueError;
},
extractExportedConstValue: function() {
return extractExportedConstValue;
}
});
class NoSuchDeclarationError extends Error {
}
function isExportDeclaration(node) {
return node.type === "ExportDeclaration";
}
function isVariableDeclaration(node) {
return node.type === "VariableDeclaration";
}
function isIdentifier(node) {
return node.type === "Identifier";
}
function isBooleanLiteral(node) {
return node.type === "BooleanLiteral";
}
function isNullLiteral(node) {
return node.type === "NullLiteral";
}
function isStringLiteral(node) {
return node.type === "StringLiteral";
}
function isNumericLiteral(node) {
return node.type === "NumericLiteral";
}
function isArrayExpression(node) {
return node.type === "ArrayExpression";
}
function isObjectExpression(node) {
return node.type === "ObjectExpression";
}
function isKeyValueProperty(node) {
return node.type === "KeyValueProperty";
}
function isRegExpLiteral(node) {
return node.type === "RegExpLiteral";
}
function isTemplateLiteral(node) {
return node.type === "TemplateLiteral";
}
class UnsupportedValueError extends Error {
constructor(message, paths){
super(message);
// Generating "path" that looks like "config.runtime[0].value"
let codePath;
if (paths) {
codePath = "";
for (const path of paths){
if (path[0] === "[") {
// "array" + "[0]"
codePath += path;
} else {
if (codePath === "") {
codePath = path;
} else {
// "object" + ".key"
codePath += `.${path}`;
}
}
}
}
this.path = codePath;
}
}
function extractValue(node, path) {
if (isNullLiteral(node)) {
return null;
} else if (isBooleanLiteral(node)) {
// e.g. true / false
return node.value;
} else if (isStringLiteral(node)) {
// e.g. "abc"
return node.value;
} else if (isNumericLiteral(node)) {
// e.g. 123
return node.value;
} else if (isRegExpLiteral(node)) {
// e.g. /abc/i
return new RegExp(node.pattern, node.flags);
} else if (isIdentifier(node)) {
switch(node.value){
case "undefined":
return undefined;
default:
throw new UnsupportedValueError(`Unknown identifier "${node.value}"`, path);
}
} else if (isArrayExpression(node)) {
// e.g. [1, 2, 3]
const arr = [];
for(let i = 0, len = node.elements.length; i < len; i++){
const elem = node.elements[i];
if (elem) {
if (elem.spread) {
// e.g. [ ...a ]
throw new UnsupportedValueError("Unsupported spread operator in the Array Expression", path);
}
arr.push(extractValue(elem.expression, path && [
...path,
`[${i}]`
]));
} else {
// e.g. [1, , 2]
// ^^
arr.push(undefined);
}
}
return arr;
} else if (isObjectExpression(node)) {
// e.g. { a: 1, b: 2 }
const obj = {};
for (const prop of node.properties){
if (!isKeyValueProperty(prop)) {
// e.g. { ...a }
throw new UnsupportedValueError("Unsupported spread operator in the Object Expression", path);
}
let key;
if (isIdentifier(prop.key)) {
// e.g. { a: 1, b: 2 }
key = prop.key.value;
} else if (isStringLiteral(prop.key)) {
// e.g. { "a": 1, "b": 2 }
key = prop.key.value;
} else {
throw new UnsupportedValueError(`Unsupported key type "${prop.key.type}" in the Object Expression`, path);
}
obj[key] = extractValue(prop.value, path && [
...path,
key
]);
}
return obj;
} else if (isTemplateLiteral(node)) {
// e.g. `abc`
if (node.expressions.length !== 0) {
// TODO: should we add support for `${'e'}d${'g'}'e'`?
throw new UnsupportedValueError("Unsupported template literal with expressions", path);
}
// When TemplateLiteral has 0 expressions, the length of quasis is always 1.
// Because when parsing TemplateLiteral, the parser yields the first quasi,
// then the first expression, then the next quasi, then the next expression, etc.,
// until the last quasi.
// Thus if there is no expression, the parser ends at the frst and also last quasis
//
// A "cooked" interpretation where backslashes have special meaning, while a
// "raw" interpretation where backslashes do not have special meaning
// https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
const [{ cooked, raw }] = node.quasis;
return cooked ?? raw;
} else {
throw new UnsupportedValueError(`Unsupported node type "${node.type}"`, path);
}
}
function extractExportedConstValue(module1, exportedName) {
for (const moduleItem of module1.body){
if (!isExportDeclaration(moduleItem)) {
continue;
}
const declaration = moduleItem.declaration;
if (!isVariableDeclaration(declaration)) {
continue;
}
if (declaration.kind !== "const") {
continue;
}
for (const decl of declaration.declarations){
if (isIdentifier(decl.id) && decl.id.value === exportedName && decl.init) {
return extractValue(decl.init, [
exportedName
]);
}
}
}
throw new NoSuchDeclarationError();
}
//# sourceMappingURL=extract-const-value.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/analysis/extract-const-value.ts"],"names":["NoSuchDeclarationError","UnsupportedValueError","extractExportedConstValue","Error","isExportDeclaration","node","type","isVariableDeclaration","isIdentifier","isBooleanLiteral","isNullLiteral","isStringLiteral","isNumericLiteral","isArrayExpression","isObjectExpression","isKeyValueProperty","isRegExpLiteral","isTemplateLiteral","constructor","message","paths","codePath","path","extractValue","value","RegExp","pattern","flags","undefined","arr","i","len","elements","length","elem","spread","push","expression","obj","prop","properties","key","expressions","cooked","raw","quasis","module","exportedName","moduleItem","body","declaration","kind","decl","declarations","id","init"],"mappings":";;;;;;;;;;;;;;;;IAiBaA,sBAAsB;eAAtBA;;IAkDAC,qBAAqB;eAArBA;;IAuJGC,yBAAyB;eAAzBA;;;AAzMT,MAAMF,+BAA+BG;AAAO;AAEnD,SAASC,oBAAoBC,IAAU;IACrC,OA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,CAAC3C,sBAAsB2C,cAAc;YACvC;QACF;QAEA,IAAIA,YAAYC,IAAI,KAAK,SAAS;YAChC;QACF;QAEA,KAAK,MAAMC,QAAQF,YAAYG,YAAY,CAAE;YAC3C,IACE7C,aAAa4C,KAAKE,EAAE,KACpBF,KAAKE,EAAE,CAAC9B,KAAK,KAAKuB,gBAClBK,KAAKG,IAAI,EACT;gBACA,OAAOhC,aAAa6B,KAAKG,IAAI,EAAE;oBAACR;iBAAa;YAC/C;QACF;IACF;IAEA,MAAM,IAAI/C;AACZ"}

View File

@ -0,0 +1,58 @@
import type { NextConfig } from '../../server/config-shared';
import type { RouteHas } from '../../lib/load-custom-routes';
import type { ServerRuntime } from 'next/types';
import type { RSCMeta } from '../webpack/loaders/get-module-build-info';
import { PAGE_TYPES } from '../../lib/page-types';
export interface MiddlewareConfigParsed extends Omit<MiddlewareConfig, 'matcher'> {
matchers?: MiddlewareMatcher[];
}
/**
* This interface represents the exported `config` object in a `middleware.ts` file.
*
* Read more: [Next.js Docs: Middleware `config` object](https://nextjs.org/docs/app/api-reference/file-conventions/middleware#config-object-optional)
*/
export interface MiddlewareConfig {
/**
* Read more: [Next.js Docs: Middleware `matcher`](https://nextjs.org/docs/app/api-reference/file-conventions/middleware#matcher),
* [Next.js Docs: Middleware matching paths](https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths)
*/
matcher?: string | string[] | MiddlewareMatcher[];
unstable_allowDynamicGlobs?: string[];
regions?: string[] | string;
}
export interface MiddlewareMatcher {
regexp: string;
locale?: false;
has?: RouteHas[];
missing?: RouteHas[];
originalSource: string;
}
export interface PageStaticInfo {
runtime?: ServerRuntime;
preferredRegion?: string | string[];
ssg?: boolean;
ssr?: boolean;
rsc?: RSCModuleType;
generateStaticParams?: boolean;
middleware?: MiddlewareConfigParsed;
amp?: boolean | 'hybrid';
extraConfig?: Record<string, any>;
}
export type RSCModuleType = 'server' | 'client';
export declare function getRSCModuleInformation(source: string, isReactServerLayer: boolean): RSCMeta;
export declare function getMiddlewareMatchers(matcherOrMatchers: unknown, nextConfig: NextConfig): MiddlewareMatcher[];
export declare function isDynamicMetadataRoute(pageFilePath: string): Promise<boolean>;
/**
* For a given pageFilePath and nextConfig, if the config supports it, this
* function will read the file and return the runtime that should be used.
* It will look into the file content only if the page *requires* a runtime
* to be specified, that is, when gSSP or gSP is used.
* Related discussion: https://github.com/vercel/next.js/discussions/34179
*/
export declare function getPageStaticInfo(params: {
pageFilePath: string;
nextConfig: Partial<NextConfig>;
isDev?: boolean;
page?: string;
pageType: PAGE_TYPES;
}): Promise<PageStaticInfo>;

View File

@ -0,0 +1,494 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getMiddlewareMatchers: null,
getPageStaticInfo: null,
getRSCModuleInformation: null,
isDynamicMetadataRoute: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getMiddlewareMatchers: function() {
return getMiddlewareMatchers;
},
getPageStaticInfo: function() {
return getPageStaticInfo;
},
getRSCModuleInformation: function() {
return getRSCModuleInformation;
},
isDynamicMetadataRoute: function() {
return isDynamicMetadataRoute;
}
});
const _fs = require("fs");
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _picomatch = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/picomatch"));
const _extractconstvalue = require("./extract-const-value");
const _parsemodule = require("./parse-module");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../output/log"));
const _constants = require("../../lib/constants");
const _loadcustomroutes = require("../../lib/load-custom-routes");
const _trytoparsepath = require("../../lib/try-to-parse-path");
const _isapiroute = require("../../lib/is-api-route");
const _isedgeruntime = require("../../lib/is-edge-runtime");
const _constants1 = require("../../shared/lib/constants");
const _pagetypes = require("../../lib/page-types");
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;
}
// TODO: migrate preferredRegion here
// Don't forget to update the next-types-plugin file as well
const AUTHORIZED_EXTRA_ROUTER_PROPS = [
"maxDuration"
];
const CLIENT_MODULE_LABEL = /\/\* __next_internal_client_entry_do_not_use__ ([^ ]*) (cjs|auto) \*\//;
const ACTION_MODULE_LABEL = /\/\* __next_internal_action_entry_do_not_use__ (\{[^}]+\}) \*\//;
const CLIENT_DIRECTIVE = "use client";
const SERVER_ACTION_DIRECTIVE = "use server";
function getRSCModuleInformation(source, isReactServerLayer) {
var _clientInfoMatch_;
const actionsJson = source.match(ACTION_MODULE_LABEL);
const actions = actionsJson ? Object.values(JSON.parse(actionsJson[1])) : undefined;
const clientInfoMatch = source.match(CLIENT_MODULE_LABEL);
const isClientRef = !!clientInfoMatch;
if (!isReactServerLayer) {
return {
type: _constants1.RSC_MODULE_TYPES.client,
actions,
isClientRef
};
}
const clientRefs = clientInfoMatch == null ? void 0 : (_clientInfoMatch_ = clientInfoMatch[1]) == null ? void 0 : _clientInfoMatch_.split(",");
const clientEntryType = clientInfoMatch == null ? void 0 : clientInfoMatch[2];
const type = clientRefs ? _constants1.RSC_MODULE_TYPES.client : _constants1.RSC_MODULE_TYPES.server;
return {
type,
actions,
clientRefs,
clientEntryType,
isClientRef
};
}
const warnedInvalidValueMap = {
runtime: new Map(),
preferredRegion: new Map()
};
function warnInvalidValue(pageFilePath, key, message) {
if (warnedInvalidValueMap[key].has(pageFilePath)) return;
_log.warn(`Next.js can't recognize the exported \`${key}\` field in "${pageFilePath}" as ${message}.` + "\n" + "The default runtime will be used instead.");
warnedInvalidValueMap[key].set(pageFilePath, true);
}
/**
* Receives a parsed AST from SWC and checks if it belongs to a module that
* requires a runtime to be specified. Those are:
* - Modules with `export function getStaticProps | getServerSideProps`
* - Modules with `export { getStaticProps | getServerSideProps } <from ...>`
* - Modules with `export const runtime = ...`
*/ function checkExports(swcAST, pageFilePath) {
const exportsSet = new Set([
"getStaticProps",
"getServerSideProps",
"generateImageMetadata",
"generateSitemaps",
"generateStaticParams"
]);
if (Array.isArray(swcAST == null ? void 0 : swcAST.body)) {
try {
let runtime;
let preferredRegion;
let ssr = false;
let ssg = false;
let generateImageMetadata = false;
let generateSitemaps = false;
let generateStaticParams = false;
let extraProperties = new Set();
let directives = new Set();
let hasLeadingNonDirectiveNode = false;
for (const node of swcAST.body){
var _node_declaration, _node_declaration1, _node_declaration_identifier, _node_declaration2;
// There should be no non-string literals nodes before directives
if (node.type === "ExpressionStatement" && node.expression.type === "StringLiteral") {
if (!hasLeadingNonDirectiveNode) {
const directive = node.expression.value;
if (CLIENT_DIRECTIVE === directive) {
directives.add("client");
}
if (SERVER_ACTION_DIRECTIVE === directive) {
directives.add("server");
}
}
} else {
hasLeadingNonDirectiveNode = true;
}
if (node.type === "ExportDeclaration" && ((_node_declaration = node.declaration) == null ? void 0 : _node_declaration.type) === "VariableDeclaration") {
var _node_declaration3;
for (const declaration of (_node_declaration3 = node.declaration) == null ? void 0 : _node_declaration3.declarations){
if (declaration.id.value === "runtime") {
runtime = declaration.init.value;
} else if (declaration.id.value === "preferredRegion") {
if (declaration.init.type === "ArrayExpression") {
const elements = [];
for (const element of declaration.init.elements){
const { expression } = element;
if (expression.type !== "StringLiteral") {
continue;
}
elements.push(expression.value);
}
preferredRegion = elements;
} else {
preferredRegion = declaration.init.value;
}
} else {
extraProperties.add(declaration.id.value);
}
}
}
if (node.type === "ExportDeclaration" && ((_node_declaration1 = node.declaration) == null ? void 0 : _node_declaration1.type) === "FunctionDeclaration" && exportsSet.has((_node_declaration_identifier = node.declaration.identifier) == null ? void 0 : _node_declaration_identifier.value)) {
const id = node.declaration.identifier.value;
ssg = id === "getStaticProps";
ssr = id === "getServerSideProps";
generateImageMetadata = id === "generateImageMetadata";
generateSitemaps = id === "generateSitemaps";
generateStaticParams = id === "generateStaticParams";
}
if (node.type === "ExportDeclaration" && ((_node_declaration2 = node.declaration) == null ? void 0 : _node_declaration2.type) === "VariableDeclaration") {
var _node_declaration_declarations_, _node_declaration4;
const id = (_node_declaration4 = node.declaration) == null ? void 0 : (_node_declaration_declarations_ = _node_declaration4.declarations[0]) == null ? void 0 : _node_declaration_declarations_.id.value;
if (exportsSet.has(id)) {
ssg = id === "getStaticProps";
ssr = id === "getServerSideProps";
generateImageMetadata = id === "generateImageMetadata";
generateSitemaps = id === "generateSitemaps";
generateStaticParams = id === "generateStaticParams";
}
}
if (node.type === "ExportNamedDeclaration") {
const values = node.specifiers.map((specifier)=>{
var _specifier_orig, _specifier_orig1;
return specifier.type === "ExportSpecifier" && ((_specifier_orig = specifier.orig) == null ? void 0 : _specifier_orig.type) === "Identifier" && ((_specifier_orig1 = specifier.orig) == null ? void 0 : _specifier_orig1.value);
});
for (const value of values){
if (!ssg && value === "getStaticProps") ssg = true;
if (!ssr && value === "getServerSideProps") ssr = true;
if (!generateImageMetadata && value === "generateImageMetadata") generateImageMetadata = true;
if (!generateSitemaps && value === "generateSitemaps") generateSitemaps = true;
if (!generateStaticParams && value === "generateStaticParams") generateStaticParams = true;
if (!runtime && value === "runtime") warnInvalidValue(pageFilePath, "runtime", "it was not assigned to a string literal");
if (!preferredRegion && value === "preferredRegion") warnInvalidValue(pageFilePath, "preferredRegion", "it was not assigned to a string literal or an array of string literals");
}
}
}
return {
ssr,
ssg,
runtime,
preferredRegion,
generateImageMetadata,
generateSitemaps,
generateStaticParams,
extraProperties,
directives
};
} catch (err) {}
}
return {
ssg: false,
ssr: false,
runtime: undefined,
preferredRegion: undefined,
generateImageMetadata: false,
generateSitemaps: false,
generateStaticParams: false,
extraProperties: undefined,
directives: undefined
};
}
async function tryToReadFile(filePath, shouldThrow) {
try {
return await _fs.promises.readFile(filePath, {
encoding: "utf8"
});
} catch (error) {
if (shouldThrow) {
error.message = `Next.js ERROR: Failed to read file ${filePath}:\n${error.message}`;
throw error;
}
}
}
function getMiddlewareMatchers(matcherOrMatchers, nextConfig) {
let matchers = [];
if (Array.isArray(matcherOrMatchers)) {
matchers = matcherOrMatchers;
} else {
matchers.push(matcherOrMatchers);
}
const { i18n } = nextConfig;
const originalSourceMap = new Map();
let routes = matchers.map((m)=>{
let middleware = typeof m === "string" ? {
source: m
} : m;
if (middleware) {
originalSourceMap.set(middleware, middleware.source);
}
return middleware;
});
// check before we process the routes and after to ensure
// they are still valid
(0, _loadcustomroutes.checkCustomRoutes)(routes, "middleware");
routes = routes.map((r)=>{
let { source } = r;
const isRoot = source === "/";
if ((i18n == null ? void 0 : i18n.locales) && r.locale !== false) {
source = `/:nextInternalLocale((?!_next/)[^/.]{1,})${isRoot ? "" : source}`;
}
source = `/:nextData(_next/data/[^/]{1,})?${source}${isRoot ? `(${nextConfig.i18n ? "|\\.json|" : ""}/?index|/?index\\.json)?` : "(.json)?"}`;
if (nextConfig.basePath) {
source = `${nextConfig.basePath}${source}`;
}
r.source = source;
return r;
});
(0, _loadcustomroutes.checkCustomRoutes)(routes, "middleware");
return routes.map((r)=>{
const { source, ...rest } = r;
const parsedPage = (0, _trytoparsepath.tryToParsePath)(source);
if (parsedPage.error || !parsedPage.regexStr) {
throw new Error(`Invalid source: ${source}`);
}
const originalSource = originalSourceMap.get(r);
return {
...rest,
regexp: parsedPage.regexStr,
originalSource: originalSource || source
};
});
}
function getMiddlewareConfig(pageFilePath, config, nextConfig) {
const result = {};
if (config.matcher) {
result.matchers = getMiddlewareMatchers(config.matcher, nextConfig);
}
if (typeof config.regions === "string" || Array.isArray(config.regions)) {
result.regions = config.regions;
} else if (typeof config.regions !== "undefined") {
_log.warn(`The \`regions\` config was ignored: config must be empty, a string or an array of strings. (${pageFilePath})`);
}
if (config.unstable_allowDynamic) {
result.unstable_allowDynamicGlobs = Array.isArray(config.unstable_allowDynamic) ? config.unstable_allowDynamic : [
config.unstable_allowDynamic
];
for (const glob of result.unstable_allowDynamicGlobs ?? []){
try {
(0, _picomatch.default)(glob);
} catch (err) {
throw new Error(`${pageFilePath} exported 'config.unstable_allowDynamic' contains invalid pattern '${glob}': ${err.message}`);
}
}
}
return result;
}
const apiRouteWarnings = new _lrucache.default({
max: 250
});
function warnAboutExperimentalEdge(apiRoute) {
if (process.env.NODE_ENV === "production" && process.env.NEXT_PRIVATE_BUILD_WORKER === "1") {
return;
}
if (apiRouteWarnings.has(apiRoute)) {
return;
}
_log.warn(apiRoute ? `${apiRoute} provided runtime 'experimental-edge'. It can be updated to 'edge' instead.` : `You are using an experimental edge runtime, the API might change.`);
apiRouteWarnings.set(apiRoute, 1);
}
const warnedUnsupportedValueMap = new _lrucache.default({
max: 250
});
function warnAboutUnsupportedValue(pageFilePath, page, error) {
if (warnedUnsupportedValueMap.has(pageFilePath)) {
return;
}
_log.warn(`Next.js can't recognize the exported \`config\` field in ` + (page ? `route "${page}"` : `"${pageFilePath}"`) + ":\n" + error.message + (error.path ? ` at "${error.path}"` : "") + ".\n" + "The default config will be used instead.\n" + "Read More - https://nextjs.org/docs/messages/invalid-page-config");
warnedUnsupportedValueMap.set(pageFilePath, true);
}
async function isDynamicMetadataRoute(pageFilePath) {
const fileContent = await tryToReadFile(pageFilePath, true) || "";
if (/generateImageMetadata|generateSitemaps/.test(fileContent)) {
const swcAST = await (0, _parsemodule.parseModule)(pageFilePath, fileContent);
const exportsInfo = checkExports(swcAST, pageFilePath);
return !!(exportsInfo.generateImageMetadata || exportsInfo.generateSitemaps);
}
return false;
}
async function getPageStaticInfo(params) {
const { isDev, pageFilePath, nextConfig, page, pageType } = params;
const fileContent = await tryToReadFile(pageFilePath, !isDev) || "";
if (/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const/.test(fileContent)) {
const swcAST = await (0, _parsemodule.parseModule)(pageFilePath, fileContent);
const { ssg, ssr, runtime, preferredRegion, generateStaticParams, extraProperties, directives } = checkExports(swcAST, pageFilePath);
const rscInfo = getRSCModuleInformation(fileContent, true);
const rsc = rscInfo.type;
// default / failsafe value for config
let config// TODO: type this as unknown
;
try {
config = (0, _extractconstvalue.extractExportedConstValue)(swcAST, "config");
} catch (e) {
if (e instanceof _extractconstvalue.UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e);
}
// `export config` doesn't exist, or other unknown error thrown by swc, silence them
}
const extraConfig = {};
if (extraProperties && pageType === _pagetypes.PAGE_TYPES.APP) {
for (const prop of extraProperties){
if (!AUTHORIZED_EXTRA_ROUTER_PROPS.includes(prop)) continue;
try {
extraConfig[prop] = (0, _extractconstvalue.extractExportedConstValue)(swcAST, prop);
} catch (e) {
if (e instanceof _extractconstvalue.UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e);
}
}
}
} else if (pageType === _pagetypes.PAGE_TYPES.PAGES) {
for(const key in config){
if (!AUTHORIZED_EXTRA_ROUTER_PROPS.includes(key)) continue;
extraConfig[key] = config[key];
}
}
if (pageType === _pagetypes.PAGE_TYPES.APP) {
if (config) {
let message = `Page config in ${pageFilePath} is deprecated. Replace \`export const config=…\` with the following:`;
if (config.runtime) {
message += `\n - \`export const runtime = ${JSON.stringify(config.runtime)}\``;
}
if (config.regions) {
message += `\n - \`export const preferredRegion = ${JSON.stringify(config.regions)}\``;
}
message += `\nVisit https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config for more information.`;
if (isDev) {
_log.warnOnce(message);
} else {
throw new Error(message);
}
config = {};
}
}
if (!config) config = {};
// We use `export const config = { runtime: '...' }` to specify the page runtime for pages/.
// In the new app directory, we prefer to use `export const runtime = '...'`
// and deprecate the old way. To prevent breaking changes for `pages`, we use the exported config
// as the fallback value.
let resolvedRuntime;
if (pageType === _pagetypes.PAGE_TYPES.APP) {
resolvedRuntime = runtime;
} else {
resolvedRuntime = runtime || config.runtime;
}
if (typeof resolvedRuntime !== "undefined" && resolvedRuntime !== _constants.SERVER_RUNTIME.nodejs && !(0, _isedgeruntime.isEdgeRuntime)(resolvedRuntime)) {
const options = Object.values(_constants.SERVER_RUNTIME).join(", ");
const message = typeof resolvedRuntime !== "string" ? `The \`runtime\` config must be a string. Please leave it empty or choose one of: ${options}` : `Provided runtime "${resolvedRuntime}" is not supported. Please leave it empty or choose one of: ${options}`;
if (isDev) {
_log.error(message);
} else {
throw new Error(message);
}
}
const requiresServerRuntime = ssr || ssg || pageType === _pagetypes.PAGE_TYPES.APP;
const isAnAPIRoute = (0, _isapiroute.isAPIRoute)(page == null ? void 0 : page.replace(/^(?:\/src)?\/pages\//, "/"));
resolvedRuntime = (0, _isedgeruntime.isEdgeRuntime)(resolvedRuntime) || requiresServerRuntime ? resolvedRuntime : undefined;
if (resolvedRuntime === _constants.SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page : null);
}
if (resolvedRuntime === _constants.SERVER_RUNTIME.edge && pageType === _pagetypes.PAGE_TYPES.PAGES && page && !isAnAPIRoute) {
const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`;
if (isDev) {
_log.error(message);
} else {
throw new Error(message);
}
}
const middlewareConfig = getMiddlewareConfig(page ?? "middleware/edge API route", config, nextConfig);
if (pageType === _pagetypes.PAGE_TYPES.APP && (directives == null ? void 0 : directives.has("client")) && generateStaticParams) {
throw new Error(`Page "${page}" cannot use both "use client" and export function "generateStaticParams()".`);
}
return {
ssr,
ssg,
rsc,
generateStaticParams,
amp: config.amp || false,
...middlewareConfig && {
middleware: middlewareConfig
},
...resolvedRuntime && {
runtime: resolvedRuntime
},
preferredRegion,
extraConfig
};
}
return {
ssr: false,
ssg: false,
rsc: _constants1.RSC_MODULE_TYPES.server,
generateStaticParams: false,
amp: false,
runtime: undefined
};
}
//# sourceMappingURL=get-page-static-info.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
/**
* Parses a module with SWC using an LRU cache where the parsed module will
* be indexed by a sha of its content holding up to 500 entries.
*/
export declare const parseModule: (_: string, content: string) => Promise<any>;

27
node_modules/next/dist/build/analysis/parse-module.js generated vendored Normal file
View File

@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "parseModule", {
enumerable: true,
get: function() {
return parseModule;
}
});
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _withpromisecache = require("../../lib/with-promise-cache");
const _crypto = require("crypto");
const _swc = require("../swc");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const parseModule = (0, _withpromisecache.withPromiseCache)(new _lrucache.default({
max: 500
}), async (filename, content)=>(0, _swc.parse)(content, {
isModule: "unknown",
filename
}).catch(()=>null), (_, content)=>(0, _crypto.createHash)("sha1").update(content).digest("hex"));
//# sourceMappingURL=parse-module.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/analysis/parse-module.ts"],"names":["parseModule","withPromiseCache","LRUCache","max","filename","content","parse","isModule","catch","_","createHash","update","digest"],"mappings":";;;;+BASaA;;;eAAAA;;;iEATQ;kCACY;wBACN;qBACL;;;;;;AAMf,MAAMA,cAAcC,IAAAA,kCAAgB,EACzC,IAAIC,iBAAQ,CAAc;IAAEC,KAAK;AAAI,IACrC,OAAOC,UAAkBC,UACvBC,IAAAA,UAAK,EAACD,SAAS;QAAEE,UAAU;QAAWH;IAAS,GAAGI,KAAK,CAAC,IAAM,OAChE,CAACC,GAAGJ,UAAYK,IAAAA,kBAAU,EAAC,QAAQC,MAAM,CAACN,SAASO,MAAM,CAAC"}