middleware-plugin.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.handleWebpackExtenalForEdgeRuntime = handleWebpackExtenalForEdgeRuntime;
  6. exports.default = void 0;
  7. var _routeRegex = require("../../../shared/lib/router/utils/route-regex");
  8. var _getModuleBuildInfo = require("../loaders/get-module-build-info");
  9. var _utils = require("../../../shared/lib/router/utils");
  10. var _webpack = require("next/dist/compiled/webpack/webpack");
  11. var _micromatch = require("next/dist/compiled/micromatch");
  12. var _constants = require("../../../shared/lib/constants");
  13. var _getPageStaticInfo = require("../../analysis/get-page-static-info");
  14. var _shared = require("../../../trace/shared");
  15. class MiddlewarePlugin {
  16. constructor({ dev , sriEnabled , allowMiddlewareResponseBody }){
  17. this.dev = dev;
  18. this.sriEnabled = sriEnabled;
  19. this.allowMiddlewareResponseBody = allowMiddlewareResponseBody;
  20. }
  21. apply(compiler) {
  22. compiler.hooks.compilation.tap(NAME, (compilation, params)=>{
  23. const { hooks } = params.normalModuleFactory;
  24. /**
  25. * This is the static code analysis phase.
  26. */ const codeAnalyzer = getCodeAnalyzer({
  27. dev: this.dev,
  28. compiler,
  29. compilation,
  30. allowMiddlewareResponseBody: this.allowMiddlewareResponseBody
  31. });
  32. hooks.parser.for("javascript/auto").tap(NAME, codeAnalyzer);
  33. hooks.parser.for("javascript/dynamic").tap(NAME, codeAnalyzer);
  34. hooks.parser.for("javascript/esm").tap(NAME, codeAnalyzer);
  35. /**
  36. * Extract all metadata for the entry points in a Map object.
  37. */ const metadataByEntry = new Map();
  38. compilation.hooks.finishModules.tapPromise(NAME, getExtractMetadata({
  39. compilation,
  40. compiler,
  41. dev: this.dev,
  42. metadataByEntry
  43. }));
  44. /**
  45. * Emit the middleware manifest.
  46. */ compilation.hooks.processAssets.tap({
  47. name: "NextJsMiddlewareManifest",
  48. stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
  49. }, getCreateAssets({
  50. compilation,
  51. metadataByEntry,
  52. opts: {
  53. sriEnabled: this.sriEnabled
  54. }
  55. }));
  56. });
  57. }
  58. }
  59. exports.default = MiddlewarePlugin;
  60. const NAME = "MiddlewarePlugin";
  61. /**
  62. * Checks the value of usingIndirectEval and when it is a set of modules it
  63. * check if any of the modules is actually being used. If the value is
  64. * simply truthy it will return true.
  65. */ function isUsingIndirectEvalAndUsedByExports(args) {
  66. const { moduleGraph , runtime , module , usingIndirectEval , wp } = args;
  67. if (typeof usingIndirectEval === "boolean") {
  68. return usingIndirectEval;
  69. }
  70. const exportsInfo = moduleGraph.getExportsInfo(module);
  71. for (const exportName of usingIndirectEval){
  72. if (exportsInfo.getUsed(exportName, runtime) !== wp.UsageState.Unused) {
  73. return true;
  74. }
  75. }
  76. return false;
  77. }
  78. function getEntryFiles(entryFiles, meta, opts) {
  79. const files = [];
  80. if (meta.edgeSSR) {
  81. if (meta.edgeSSR.isServerComponent) {
  82. files.push(`server/${_constants.FLIGHT_MANIFEST}.js`);
  83. files.push(`server/${_constants.FLIGHT_SERVER_CSS_MANIFEST}.js`);
  84. if (opts.sriEnabled) {
  85. files.push(`server/${_constants.SUBRESOURCE_INTEGRITY_MANIFEST}.js`);
  86. }
  87. files.push(...entryFiles.filter((file)=>file.startsWith("pages/") && !file.endsWith(".hot-update.js")).map((file)=>"server/" + // TODO-APP: seems this should be removed.
  88. file.replace(".js", _constants.NEXT_CLIENT_SSR_ENTRY_SUFFIX + ".js")));
  89. }
  90. files.push(`server/${_constants.MIDDLEWARE_BUILD_MANIFEST}.js`, `server/${_constants.MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`);
  91. }
  92. files.push(...entryFiles.filter((file)=>!file.endsWith(".hot-update.js")).map((file)=>"server/" + file));
  93. return files;
  94. }
  95. function getCreateAssets(params) {
  96. const { compilation , metadataByEntry , opts } = params;
  97. return (assets)=>{
  98. const middlewareManifest = {
  99. sortedMiddleware: [],
  100. middleware: {},
  101. functions: {},
  102. version: 2
  103. };
  104. for (const entrypoint of compilation.entrypoints.values()){
  105. var ref, ref1, ref2, ref3;
  106. if (!entrypoint.name) {
  107. continue;
  108. }
  109. // There should always be metadata for the entrypoint.
  110. const metadata = metadataByEntry.get(entrypoint.name);
  111. const page = (metadata == null ? void 0 : (ref = metadata.edgeMiddleware) == null ? void 0 : ref.page) || (metadata == null ? void 0 : (ref1 = metadata.edgeSSR) == null ? void 0 : ref1.page) || (metadata == null ? void 0 : (ref2 = metadata.edgeApiFunction) == null ? void 0 : ref2.page);
  112. if (!page) {
  113. continue;
  114. }
  115. const { namedRegex } = (0, _routeRegex).getNamedMiddlewareRegex(page, {
  116. catchAll: !metadata.edgeSSR && !metadata.edgeApiFunction
  117. });
  118. var ref4;
  119. const matchers = (ref4 = metadata == null ? void 0 : (ref3 = metadata.edgeMiddleware) == null ? void 0 : ref3.matchers) != null ? ref4 : [
  120. {
  121. regexp: namedRegex
  122. },
  123. ];
  124. const edgeFunctionDefinition = {
  125. env: Array.from(metadata.env),
  126. files: getEntryFiles(entrypoint.getFiles(), metadata, opts),
  127. name: entrypoint.name,
  128. page: page,
  129. matchers,
  130. wasm: Array.from(metadata.wasmBindings, ([name, filePath])=>({
  131. name,
  132. filePath
  133. })),
  134. assets: Array.from(metadata.assetBindings, ([name, filePath])=>({
  135. name,
  136. filePath
  137. })),
  138. ...metadata.regions && {
  139. regions: metadata.regions
  140. }
  141. };
  142. if (metadata.edgeApiFunction || metadata.edgeSSR) {
  143. middlewareManifest.functions[page] = edgeFunctionDefinition;
  144. } else {
  145. middlewareManifest.middleware[page] = edgeFunctionDefinition;
  146. }
  147. }
  148. middlewareManifest.sortedMiddleware = (0, _utils).getSortedRoutes(Object.keys(middlewareManifest.middleware));
  149. assets[_constants.MIDDLEWARE_MANIFEST] = new _webpack.sources.RawSource(JSON.stringify(middlewareManifest, null, 2));
  150. };
  151. }
  152. function buildWebpackError({ message , loc , compilation , entryModule , parser }) {
  153. const error = new compilation.compiler.webpack.WebpackError(message);
  154. error.name = NAME;
  155. const module = entryModule != null ? entryModule : parser == null ? void 0 : parser.state.current;
  156. if (module) {
  157. error.module = module;
  158. }
  159. error.loc = loc;
  160. return error;
  161. }
  162. function isInMiddlewareLayer(parser) {
  163. var ref;
  164. return ((ref = parser.state.module) == null ? void 0 : ref.layer) === "middleware";
  165. }
  166. function isInMiddlewareFile(parser) {
  167. var ref, ref5;
  168. return ((ref = parser.state.current) == null ? void 0 : ref.layer) === "middleware" && /middleware\.\w+$/.test((ref5 = parser.state.current) == null ? void 0 : ref5.rawRequest);
  169. }
  170. function isNullLiteral(expr) {
  171. return expr.value === null;
  172. }
  173. function isUndefinedIdentifier(expr) {
  174. return expr.name === "undefined";
  175. }
  176. function isProcessEnvMemberExpression(memberExpression) {
  177. var ref, ref6, ref7;
  178. return ((ref = memberExpression.object) == null ? void 0 : ref.type) === "Identifier" && memberExpression.object.name === "process" && (((ref6 = memberExpression.property) == null ? void 0 : ref6.type) === "Literal" && memberExpression.property.value === "env" || ((ref7 = memberExpression.property) == null ? void 0 : ref7.type) === "Identifier" && memberExpression.property.name === "env");
  179. }
  180. function isNodeJsModule(moduleName) {
  181. return require("module").builtinModules.includes(moduleName);
  182. }
  183. function isDynamicCodeEvaluationAllowed(fileName, edgeFunctionConfig, rootDir) {
  184. const name = fileName.replace(rootDir != null ? rootDir : "", "");
  185. var ref;
  186. return (0, _micromatch).isMatch(name, (ref = edgeFunctionConfig == null ? void 0 : edgeFunctionConfig.unstable_allowDynamicGlobs) != null ? ref : []);
  187. }
  188. function buildUnsupportedApiError({ apiName , loc , ...rest }) {
  189. return buildWebpackError({
  190. message: `A Node.js API is used (${apiName} at line: ${loc.start.line}) which is not supported in the Edge Runtime.
  191. Learn more: https://nextjs.org/docs/api-reference/edge-runtime`,
  192. loc,
  193. ...rest
  194. });
  195. }
  196. function registerUnsupportedApiHooks(parser, compilation) {
  197. for (const expression of _constants.EDGE_UNSUPPORTED_NODE_APIS){
  198. const warnForUnsupportedApi = (node)=>{
  199. if (!isInMiddlewareLayer(parser)) {
  200. return;
  201. }
  202. compilation.warnings.push(buildUnsupportedApiError({
  203. compilation,
  204. parser,
  205. apiName: expression,
  206. ...node
  207. }));
  208. return true;
  209. };
  210. parser.hooks.call.for(expression).tap(NAME, warnForUnsupportedApi);
  211. parser.hooks.expression.for(expression).tap(NAME, warnForUnsupportedApi);
  212. parser.hooks.callMemberChain.for(expression).tap(NAME, warnForUnsupportedApi);
  213. parser.hooks.expressionMemberChain.for(expression).tap(NAME, warnForUnsupportedApi);
  214. }
  215. const warnForUnsupportedProcessApi = (node, [callee])=>{
  216. if (!isInMiddlewareLayer(parser) || callee === "env") {
  217. return;
  218. }
  219. compilation.warnings.push(buildUnsupportedApiError({
  220. compilation,
  221. parser,
  222. apiName: `process.${callee}`,
  223. ...node
  224. }));
  225. return true;
  226. };
  227. parser.hooks.callMemberChain.for("process").tap(NAME, warnForUnsupportedProcessApi);
  228. parser.hooks.expressionMemberChain.for("process").tap(NAME, warnForUnsupportedProcessApi);
  229. }
  230. function getCodeAnalyzer(params) {
  231. return (parser)=>{
  232. const { dev , compiler: { webpack: wp } , compilation , allowMiddlewareResponseBody , } = params;
  233. const { hooks } = parser;
  234. /**
  235. * For an expression this will check the graph to ensure it is being used
  236. * by exports. Then it will store in the module buildInfo a boolean to
  237. * express that it contains dynamic code and, if it is available, the
  238. * module path that is using it.
  239. */ const handleExpression = ()=>{
  240. if (!isInMiddlewareLayer(parser)) {
  241. return;
  242. }
  243. wp.optimize.InnerGraph.onUsage(parser.state, (used = true)=>{
  244. const buildInfo = (0, _getModuleBuildInfo).getModuleBuildInfo(parser.state.module);
  245. if (buildInfo.usingIndirectEval === true || used === false) {
  246. return;
  247. }
  248. if (!buildInfo.usingIndirectEval || used === true) {
  249. buildInfo.usingIndirectEval = used;
  250. return;
  251. }
  252. buildInfo.usingIndirectEval = new Set([
  253. ...Array.from(buildInfo.usingIndirectEval),
  254. ...Array.from(used),
  255. ]);
  256. });
  257. };
  258. /**
  259. * This expression handler allows to wrap a dynamic code expression with a
  260. * function call where we can warn about dynamic code not being allowed
  261. * but actually execute the expression.
  262. */ const handleWrapExpression = (expr)=>{
  263. if (!isInMiddlewareLayer(parser)) {
  264. return;
  265. }
  266. const { ConstDependency } = wp.dependencies;
  267. const dep1 = new ConstDependency("__next_eval__(function() { return ", expr.range[0]);
  268. dep1.loc = expr.loc;
  269. parser.state.module.addPresentationalDependency(dep1);
  270. const dep2 = new ConstDependency("})", expr.range[1]);
  271. dep2.loc = expr.loc;
  272. parser.state.module.addPresentationalDependency(dep2);
  273. handleExpression();
  274. return true;
  275. };
  276. /**
  277. * This expression handler allows to wrap a WebAssembly.compile invocation with a
  278. * function call where we can warn about WASM code generation not being allowed
  279. * but actually execute the expression.
  280. */ const handleWrapWasmCompileExpression = (expr)=>{
  281. if (!isInMiddlewareLayer(parser)) {
  282. return;
  283. }
  284. const { ConstDependency } = wp.dependencies;
  285. const dep1 = new ConstDependency("__next_webassembly_compile__(function() { return ", expr.range[0]);
  286. dep1.loc = expr.loc;
  287. parser.state.module.addPresentationalDependency(dep1);
  288. const dep2 = new ConstDependency("})", expr.range[1]);
  289. dep2.loc = expr.loc;
  290. parser.state.module.addPresentationalDependency(dep2);
  291. handleExpression();
  292. };
  293. /**
  294. * This expression handler allows to wrap a WebAssembly.instatiate invocation with a
  295. * function call where we can warn about WASM code generation not being allowed
  296. * but actually execute the expression.
  297. *
  298. * Note that we don't update `usingIndirectEval`, i.e. we don't abort a production build
  299. * since we can't determine statically if the first parameter is a module (legit use) or
  300. * a buffer (dynamic code generation).
  301. */ const handleWrapWasmInstantiateExpression = (expr)=>{
  302. if (!isInMiddlewareLayer(parser)) {
  303. return;
  304. }
  305. if (dev) {
  306. const { ConstDependency } = wp.dependencies;
  307. const dep1 = new ConstDependency("__next_webassembly_instantiate__(function() { return ", expr.range[0]);
  308. dep1.loc = expr.loc;
  309. parser.state.module.addPresentationalDependency(dep1);
  310. const dep2 = new ConstDependency("})", expr.range[1]);
  311. dep2.loc = expr.loc;
  312. parser.state.module.addPresentationalDependency(dep2);
  313. }
  314. };
  315. /**
  316. * Declares an environment variable that is being used in this module
  317. * through this static analysis.
  318. */ const addUsedEnvVar = (envVarName)=>{
  319. const buildInfo = (0, _getModuleBuildInfo).getModuleBuildInfo(parser.state.module);
  320. if (buildInfo.nextUsedEnvVars === undefined) {
  321. buildInfo.nextUsedEnvVars = new Set();
  322. }
  323. buildInfo.nextUsedEnvVars.add(envVarName);
  324. };
  325. /**
  326. * A handler for calls to `process.env` where we identify the name of the
  327. * ENV variable being assigned and store it in the module info.
  328. */ const handleCallMemberChain = (_, members)=>{
  329. if (members.length >= 2 && members[0] === "env") {
  330. addUsedEnvVar(members[1]);
  331. if (!isInMiddlewareLayer(parser)) {
  332. return true;
  333. }
  334. }
  335. };
  336. /**
  337. * A handler for calls to `new Response()` so we can fail if user is setting the response's body.
  338. */ const handleNewResponseExpression = (node)=>{
  339. var ref;
  340. const firstParameter = node == null ? void 0 : (ref = node.arguments) == null ? void 0 : ref[0];
  341. if (isInMiddlewareFile(parser) && firstParameter && !isNullLiteral(firstParameter) && !isUndefinedIdentifier(firstParameter)) {
  342. const error = buildWebpackError({
  343. message: `Middleware is returning a response body (line: ${node.loc.start.line}), which is not supported.
  344. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware`,
  345. compilation,
  346. parser,
  347. ...node
  348. });
  349. if (dev) {
  350. compilation.warnings.push(error);
  351. } else {
  352. compilation.errors.push(error);
  353. }
  354. }
  355. };
  356. /**
  357. * Handler to store original source location of static and dynamic imports into module's buildInfo.
  358. */ const handleImport = (node)=>{
  359. var ref;
  360. if (isInMiddlewareLayer(parser) && ((ref = node.source) == null ? void 0 : ref.value) && (node == null ? void 0 : node.loc)) {
  361. var ref8;
  362. const { module , source } = parser.state;
  363. const buildInfo = (0, _getModuleBuildInfo).getModuleBuildInfo(module);
  364. if (!buildInfo.importLocByPath) {
  365. buildInfo.importLocByPath = new Map();
  366. }
  367. const importedModule = (ref8 = node.source.value) == null ? void 0 : ref8.toString();
  368. buildInfo.importLocByPath.set(importedModule, {
  369. sourcePosition: {
  370. ...node.loc.start,
  371. source: module.identifier()
  372. },
  373. sourceContent: source.toString()
  374. });
  375. if (!dev && isNodeJsModule(importedModule)) {
  376. compilation.warnings.push(buildWebpackError({
  377. message: `A Node.js module is loaded ('${importedModule}' at line ${node.loc.start.line}) which is not supported in the Edge Runtime.
  378. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`,
  379. compilation,
  380. parser,
  381. ...node
  382. }));
  383. }
  384. }
  385. };
  386. /**
  387. * A noop handler to skip analyzing some cases.
  388. * Order matters: for it to work, it must be registered first
  389. */ const skip = ()=>isInMiddlewareLayer(parser) ? true : undefined;
  390. for (const prefix of [
  391. "",
  392. "global."
  393. ]){
  394. hooks.expression.for(`${prefix}Function.prototype`).tap(NAME, skip);
  395. hooks.expression.for(`${prefix}Function.bind`).tap(NAME, skip);
  396. hooks.call.for(`${prefix}eval`).tap(NAME, handleWrapExpression);
  397. hooks.call.for(`${prefix}Function`).tap(NAME, handleWrapExpression);
  398. hooks.new.for(`${prefix}Function`).tap(NAME, handleWrapExpression);
  399. hooks.expression.for(`${prefix}eval`).tap(NAME, handleExpression);
  400. hooks.expression.for(`${prefix}Function`).tap(NAME, handleExpression);
  401. hooks.call.for(`${prefix}WebAssembly.compile`).tap(NAME, handleWrapWasmCompileExpression);
  402. hooks.call.for(`${prefix}WebAssembly.instantiate`).tap(NAME, handleWrapWasmInstantiateExpression);
  403. }
  404. if (!allowMiddlewareResponseBody) {
  405. hooks.new.for("Response").tap(NAME, handleNewResponseExpression);
  406. hooks.new.for("NextResponse").tap(NAME, handleNewResponseExpression);
  407. }
  408. hooks.callMemberChain.for("process").tap(NAME, handleCallMemberChain);
  409. hooks.expressionMemberChain.for("process").tap(NAME, handleCallMemberChain);
  410. hooks.importCall.tap(NAME, handleImport);
  411. hooks.import.tap(NAME, handleImport);
  412. /**
  413. * Support static analyzing environment variables through
  414. * destructuring `process.env` or `process["env"]`:
  415. *
  416. * const { MY_ENV, "MY-ENV": myEnv } = process.env
  417. * ^^^^^^ ^^^^^^
  418. */ hooks.declarator.tap(NAME, (declarator)=>{
  419. var ref, ref9;
  420. if (((ref = declarator.init) == null ? void 0 : ref.type) === "MemberExpression" && isProcessEnvMemberExpression(declarator.init) && ((ref9 = declarator.id) == null ? void 0 : ref9.type) === "ObjectPattern") {
  421. for (const property of declarator.id.properties){
  422. if (property.type === "RestElement") continue;
  423. if (property.key.type === "Literal" && typeof property.key.value === "string") {
  424. addUsedEnvVar(property.key.value);
  425. } else if (property.key.type === "Identifier") {
  426. addUsedEnvVar(property.key.name);
  427. }
  428. }
  429. if (!isInMiddlewareLayer(parser)) {
  430. return true;
  431. }
  432. }
  433. });
  434. if (!dev) {
  435. // do not issue compilation warning on dev: invoking code will provide details
  436. registerUnsupportedApiHooks(parser, compilation);
  437. }
  438. };
  439. }
  440. async function findEntryEdgeFunctionConfig(entryDependency, resolver) {
  441. var ref;
  442. if (entryDependency == null ? void 0 : (ref = entryDependency.request) == null ? void 0 : ref.startsWith("next-")) {
  443. var ref10;
  444. const absolutePagePath = (ref10 = new URL(entryDependency.request, "http://example.org").searchParams.get("absolutePagePath")) != null ? ref10 : "";
  445. const pageFilePath = await new Promise((resolve)=>resolver.resolve({}, "/", absolutePagePath, {}, (err, path)=>resolve(err || path)));
  446. if (typeof pageFilePath === "string") {
  447. return {
  448. file: pageFilePath,
  449. config: (await (0, _getPageStaticInfo).getPageStaticInfo({
  450. nextConfig: {},
  451. pageFilePath,
  452. isDev: false
  453. })).middleware
  454. };
  455. }
  456. }
  457. }
  458. function getExtractMetadata(params) {
  459. const { dev , compilation , metadataByEntry , compiler } = params;
  460. const { webpack: wp } = compiler;
  461. return async ()=>{
  462. metadataByEntry.clear();
  463. const resolver = compilation.resolverFactory.get("normal");
  464. const telemetry = _shared.traceGlobals.get("telemetry");
  465. for (const [entryName, entry] of compilation.entries){
  466. var ref;
  467. if (entry.options.runtime !== _constants.EDGE_RUNTIME_WEBPACK) {
  468. continue;
  469. }
  470. const entryDependency = (ref = entry.dependencies) == null ? void 0 : ref[0];
  471. const edgeFunctionConfig = await findEntryEdgeFunctionConfig(entryDependency, resolver);
  472. const { rootDir } = (0, _getModuleBuildInfo).getModuleBuildInfo(compilation.moduleGraph.getResolvedModule(entryDependency));
  473. const { moduleGraph } = compilation;
  474. const modules = new Set();
  475. const addEntriesFromDependency = (dependency)=>{
  476. const module = moduleGraph.getModule(dependency);
  477. if (module) {
  478. modules.add(module);
  479. }
  480. };
  481. entry.dependencies.forEach(addEntriesFromDependency);
  482. entry.includeDependencies.forEach(addEntriesFromDependency);
  483. const entryMetadata = {
  484. env: new Set(),
  485. wasmBindings: new Map(),
  486. assetBindings: new Map()
  487. };
  488. for (const module1 of modules){
  489. var ref11;
  490. const buildInfo = (0, _getModuleBuildInfo).getModuleBuildInfo(module1);
  491. /**
  492. * When building for production checks if the module is using `eval`
  493. * and in such case produces a compilation error. The module has to
  494. * be in use.
  495. */ if (!dev && buildInfo.usingIndirectEval && isUsingIndirectEvalAndUsedByExports({
  496. module: module1,
  497. moduleGraph,
  498. runtime: wp.util.runtime.getEntryRuntime(compilation, entryName),
  499. usingIndirectEval: buildInfo.usingIndirectEval,
  500. wp
  501. })) {
  502. var ref12;
  503. const id = module1.identifier();
  504. if (/node_modules[\\/]regenerator-runtime[\\/]runtime\.js/.test(id)) {
  505. continue;
  506. }
  507. if (edgeFunctionConfig == null ? void 0 : (ref12 = edgeFunctionConfig.config) == null ? void 0 : ref12.unstable_allowDynamicGlobs) {
  508. telemetry.record({
  509. eventName: "NEXT_EDGE_ALLOW_DYNAMIC_USED",
  510. payload: {
  511. ...edgeFunctionConfig,
  512. file: edgeFunctionConfig.file.replace(rootDir != null ? rootDir : "", ""),
  513. fileWithDynamicCode: module1.userRequest.replace(rootDir != null ? rootDir : "", "")
  514. }
  515. });
  516. }
  517. if (!isDynamicCodeEvaluationAllowed(module1.userRequest, edgeFunctionConfig == null ? void 0 : edgeFunctionConfig.config, rootDir)) {
  518. compilation.errors.push(buildWebpackError({
  519. message: `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime ${typeof buildInfo.usingIndirectEval !== "boolean" ? `\nUsed by ${Array.from(buildInfo.usingIndirectEval).join(", ")}` : ""}\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`,
  520. entryModule: module1,
  521. compilation
  522. }));
  523. }
  524. }
  525. if (edgeFunctionConfig == null ? void 0 : (ref11 = edgeFunctionConfig.config) == null ? void 0 : ref11.regions) {
  526. entryMetadata.regions = edgeFunctionConfig.config.regions;
  527. }
  528. /**
  529. * The entry module has to be either a page or a middleware and hold
  530. * the corresponding metadata.
  531. */ if (buildInfo == null ? void 0 : buildInfo.nextEdgeSSR) {
  532. entryMetadata.edgeSSR = buildInfo.nextEdgeSSR;
  533. } else if (buildInfo == null ? void 0 : buildInfo.nextEdgeMiddleware) {
  534. entryMetadata.edgeMiddleware = buildInfo.nextEdgeMiddleware;
  535. } else if (buildInfo == null ? void 0 : buildInfo.nextEdgeApiFunction) {
  536. entryMetadata.edgeApiFunction = buildInfo.nextEdgeApiFunction;
  537. }
  538. /**
  539. * If there are env vars found in the module, append them to the set
  540. * of env vars for the entry.
  541. */ if ((buildInfo == null ? void 0 : buildInfo.nextUsedEnvVars) !== undefined) {
  542. for (const envName of buildInfo.nextUsedEnvVars){
  543. entryMetadata.env.add(envName);
  544. }
  545. }
  546. /**
  547. * If the module is a WASM module we read the binding information and
  548. * append it to the entry wasm bindings.
  549. */ if (buildInfo == null ? void 0 : buildInfo.nextWasmMiddlewareBinding) {
  550. entryMetadata.wasmBindings.set(buildInfo.nextWasmMiddlewareBinding.name, buildInfo.nextWasmMiddlewareBinding.filePath);
  551. }
  552. if (buildInfo == null ? void 0 : buildInfo.nextAssetMiddlewareBinding) {
  553. entryMetadata.assetBindings.set(buildInfo.nextAssetMiddlewareBinding.name, buildInfo.nextAssetMiddlewareBinding.filePath);
  554. }
  555. /**
  556. * Append to the list of modules to process outgoingConnections from
  557. * the module that is being processed.
  558. */ for (const conn of moduleGraph.getOutgoingConnections(module1)){
  559. if (conn.module) {
  560. modules.add(conn.module);
  561. }
  562. }
  563. }
  564. metadataByEntry.set(entryName, entryMetadata);
  565. }
  566. };
  567. }
  568. async function handleWebpackExtenalForEdgeRuntime({ request , context , contextInfo , getResolve }) {
  569. if (contextInfo.issuerLayer === "middleware" && isNodeJsModule(request)) {
  570. // allows user to provide and use their polyfills, as we do with buffer.
  571. try {
  572. await getResolve()(context, request);
  573. } catch {
  574. return `root globalThis.__import_unsupported('${request}')`;
  575. }
  576. }
  577. }
  578. //# sourceMappingURL=middleware-plugin.js.map