get-page-static-info.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getRSCModuleType = getRSCModuleType;
  6. exports.checkExports = checkExports;
  7. exports.getPageStaticInfo = getPageStaticInfo;
  8. var _configShared = require("../../server/config-shared");
  9. var _extractConstValue = require("./extract-const-value");
  10. var _parseModule = require("./parse-module");
  11. var _fs = require("fs");
  12. var _tryToParsePath = require("../../lib/try-to-parse-path");
  13. var Log = _interopRequireWildcard(require("../output/log"));
  14. var _constants = require("../../lib/constants");
  15. var _loadCustomRoutes = require("../../lib/load-custom-routes");
  16. var _micromatch = require("next/dist/compiled/micromatch");
  17. var _constants1 = require("../../shared/lib/constants");
  18. function _getRequireWildcardCache() {
  19. if (typeof WeakMap !== "function") return null;
  20. var cache = new WeakMap();
  21. _getRequireWildcardCache = function() {
  22. return cache;
  23. };
  24. return cache;
  25. }
  26. function _interopRequireWildcard(obj) {
  27. if (obj && obj.__esModule) {
  28. return obj;
  29. }
  30. if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
  31. return {
  32. default: obj
  33. };
  34. }
  35. var cache = _getRequireWildcardCache();
  36. if (cache && cache.has(obj)) {
  37. return cache.get(obj);
  38. }
  39. var newObj = {};
  40. var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  41. for(var key in obj){
  42. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  43. var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
  44. if (desc && (desc.get || desc.set)) {
  45. Object.defineProperty(newObj, key, desc);
  46. } else {
  47. newObj[key] = obj[key];
  48. }
  49. }
  50. }
  51. newObj.default = obj;
  52. if (cache) {
  53. cache.set(obj, newObj);
  54. }
  55. return newObj;
  56. }
  57. const CLIENT_MODULE_LABEL = `/* __next_internal_client_entry_do_not_use__ */`;
  58. function getRSCModuleType(source) {
  59. return source.includes(CLIENT_MODULE_LABEL) ? _constants1.RSC_MODULE_TYPES.client : _constants1.RSC_MODULE_TYPES.server;
  60. }
  61. function checkExports(swcAST) {
  62. if (Array.isArray(swcAST == null ? void 0 : swcAST.body)) {
  63. try {
  64. for (const node of swcAST.body){
  65. var ref6, ref1, ref2;
  66. if (node.type === "ExportDeclaration" && ((ref6 = node.declaration) == null ? void 0 : ref6.type) === "FunctionDeclaration" && [
  67. "getStaticProps",
  68. "getServerSideProps"
  69. ].includes((ref1 = node.declaration.identifier) == null ? void 0 : ref1.value)) {
  70. return {
  71. ssg: node.declaration.identifier.value === "getStaticProps",
  72. ssr: node.declaration.identifier.value === "getServerSideProps"
  73. };
  74. }
  75. if (node.type === "ExportDeclaration" && ((ref2 = node.declaration) == null ? void 0 : ref2.type) === "VariableDeclaration") {
  76. var ref3, ref4;
  77. const id = (ref4 = (ref3 = node.declaration) == null ? void 0 : ref3.declarations[0]) == null ? void 0 : ref4.id.value;
  78. if ([
  79. "getStaticProps",
  80. "getServerSideProps"
  81. ].includes(id)) {
  82. return {
  83. ssg: id === "getStaticProps",
  84. ssr: id === "getServerSideProps"
  85. };
  86. }
  87. }
  88. if (node.type === "ExportNamedDeclaration") {
  89. const values = node.specifiers.map((specifier)=>{
  90. var ref, ref5;
  91. return specifier.type === "ExportSpecifier" && ((ref = specifier.orig) == null ? void 0 : ref.type) === "Identifier" && ((ref5 = specifier.orig) == null ? void 0 : ref5.value);
  92. });
  93. return {
  94. ssg: values.some((value)=>[
  95. "getStaticProps"
  96. ].includes(value)),
  97. ssr: values.some((value)=>[
  98. "getServerSideProps"
  99. ].includes(value))
  100. };
  101. }
  102. }
  103. } catch (err) {}
  104. }
  105. return {
  106. ssg: false,
  107. ssr: false
  108. };
  109. }
  110. async function tryToReadFile(filePath, shouldThrow) {
  111. try {
  112. return await _fs.promises.readFile(filePath, {
  113. encoding: "utf8"
  114. });
  115. } catch (error) {
  116. if (shouldThrow) {
  117. throw error;
  118. }
  119. }
  120. }
  121. function getMiddlewareMatchers(matcherOrMatchers, nextConfig) {
  122. let matchers = [];
  123. if (Array.isArray(matcherOrMatchers)) {
  124. matchers = matcherOrMatchers;
  125. } else {
  126. matchers.push(matcherOrMatchers);
  127. }
  128. const { i18n } = nextConfig;
  129. let routes = matchers.map((m)=>typeof m === "string" ? {
  130. source: m
  131. } : m);
  132. // check before we process the routes and after to ensure
  133. // they are still valid
  134. (0, _loadCustomRoutes).checkCustomRoutes(routes, "middleware");
  135. routes = routes.map((r)=>{
  136. let { source } = r;
  137. const isRoot = source === "/";
  138. if ((i18n == null ? void 0 : i18n.locales) && r.locale !== false) {
  139. source = `/:nextInternalLocale([^/.]{1,})${isRoot ? "" : source}`;
  140. }
  141. source = `/:nextData(_next/data/[^/]{1,})?${source}${isRoot ? `(${nextConfig.i18n ? "|\\.json|" : ""}/?index|/?index\\.json)?` : "(.json)?"}`;
  142. if (nextConfig.basePath) {
  143. source = `${nextConfig.basePath}${source}`;
  144. }
  145. return {
  146. ...r,
  147. source
  148. };
  149. });
  150. (0, _loadCustomRoutes).checkCustomRoutes(routes, "middleware");
  151. return routes.map((r)=>{
  152. const { source , ...rest } = r;
  153. const parsedPage = (0, _tryToParsePath).tryToParsePath(source);
  154. if (parsedPage.error || !parsedPage.regexStr) {
  155. throw new Error(`Invalid source: ${source}`);
  156. }
  157. return {
  158. ...rest,
  159. regexp: parsedPage.regexStr
  160. };
  161. });
  162. }
  163. function getMiddlewareConfig(pageFilePath, config, nextConfig) {
  164. const result = {};
  165. if (config.matcher) {
  166. result.matchers = getMiddlewareMatchers(config.matcher, nextConfig);
  167. }
  168. if (typeof config.regions === "string" || Array.isArray(config.regions)) {
  169. result.regions = config.regions;
  170. } else if (typeof config.regions !== "undefined") {
  171. Log.warn(`The \`regions\` config was ignored: config must be empty, a string or an array of strings. (${pageFilePath})`);
  172. }
  173. if (config.unstable_allowDynamic) {
  174. result.unstable_allowDynamicGlobs = Array.isArray(config.unstable_allowDynamic) ? config.unstable_allowDynamic : [
  175. config.unstable_allowDynamic
  176. ];
  177. var _unstable_allowDynamicGlobs;
  178. for (const glob of (_unstable_allowDynamicGlobs = result.unstable_allowDynamicGlobs) != null ? _unstable_allowDynamicGlobs : []){
  179. try {
  180. (0, _micromatch).matcher(glob);
  181. } catch (err) {
  182. throw new Error(`${pageFilePath} exported 'config.unstable_allowDynamic' contains invalid pattern '${glob}': ${err.message}`);
  183. }
  184. }
  185. }
  186. return result;
  187. }
  188. let warnedAboutExperimentalEdgeApiFunctions = false;
  189. function warnAboutExperimentalEdgeApiFunctions() {
  190. if (warnedAboutExperimentalEdgeApiFunctions) {
  191. return;
  192. }
  193. Log.warn(`You are using an experimental edge runtime, the API might change.`);
  194. warnedAboutExperimentalEdgeApiFunctions = true;
  195. }
  196. const warnedUnsupportedValueMap = new Map();
  197. function warnAboutUnsupportedValue(pageFilePath, page, error) {
  198. if (warnedUnsupportedValueMap.has(pageFilePath)) {
  199. return;
  200. }
  201. 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");
  202. warnedUnsupportedValueMap.set(pageFilePath, true);
  203. }
  204. async function getPageStaticInfo(params) {
  205. var ref;
  206. const { isDev , pageFilePath , nextConfig , page } = params;
  207. const fileContent = await tryToReadFile(pageFilePath, !isDev) || "";
  208. if (/runtime|getStaticProps|getServerSideProps|matcher|unstable_allowDynamic|export const config/.test(fileContent)) {
  209. var ref10;
  210. const swcAST = await (0, _parseModule).parseModule(pageFilePath, fileContent);
  211. const { ssg , ssr } = checkExports(swcAST);
  212. const rsc = getRSCModuleType(fileContent);
  213. // default / failsafe value for config
  214. let config = {};
  215. try {
  216. config = (0, _extractConstValue).extractExportedConstValue(swcAST, "config");
  217. } catch (e) {
  218. if (e instanceof _extractConstValue.UnsupportedValueError) {
  219. warnAboutUnsupportedValue(pageFilePath, page, e);
  220. }
  221. // `export config` doesn't exist, or other unknown error throw by swc, silence them
  222. }
  223. if (typeof config.runtime !== "undefined" && !(0, _configShared).isServerRuntime(config.runtime)) {
  224. const options = Object.values(_constants.SERVER_RUNTIME).join(", ");
  225. if (typeof config.runtime !== "string") {
  226. Log.error(`The \`runtime\` config must be a string. Please leave it empty or choose one of: ${options}`);
  227. } else {
  228. Log.error(`Provided runtime "${config.runtime}" is not supported. Please leave it empty or choose one of: ${options}`);
  229. }
  230. if (!isDev) {
  231. process.exit(1);
  232. }
  233. }
  234. let runtime = _constants.SERVER_RUNTIME.edge === (config == null ? void 0 : config.runtime) ? _constants.SERVER_RUNTIME.edge : ssr || ssg ? (config == null ? void 0 : config.runtime) || ((ref10 = nextConfig.experimental) == null ? void 0 : ref10.runtime) : undefined;
  235. if (runtime === _constants.SERVER_RUNTIME.edge) {
  236. warnAboutExperimentalEdgeApiFunctions();
  237. }
  238. const middlewareConfig = getMiddlewareConfig(page != null ? page : "middleware/edge API route", config, nextConfig);
  239. return {
  240. ssr,
  241. ssg,
  242. rsc,
  243. ...middlewareConfig && {
  244. middleware: middlewareConfig
  245. },
  246. ...runtime && {
  247. runtime
  248. }
  249. };
  250. }
  251. return {
  252. ssr: false,
  253. ssg: false,
  254. rsc: _constants1.RSC_MODULE_TYPES.server,
  255. runtime: (ref = nextConfig.experimental) == null ? void 0 : ref.runtime
  256. };
  257. }
  258. //# sourceMappingURL=get-page-static-info.js.map