next-middleware-loader.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = middlewareLoader;
  6. exports.encodeMatchers = encodeMatchers;
  7. exports.decodeMatchers = decodeMatchers;
  8. var _getModuleBuildInfo = require("./get-module-build-info");
  9. var _stringifyRequest = require("../stringify-request");
  10. var _constants = require("../../../lib/constants");
  11. function middlewareLoader() {
  12. const { absolutePagePath , page , rootDir , matchers: encodedMatchers , } = this.getOptions();
  13. const matchers = encodedMatchers ? decodeMatchers(encodedMatchers) : undefined;
  14. const stringifiedPagePath = (0, _stringifyRequest).stringifyRequest(this, absolutePagePath);
  15. const buildInfo = (0, _getModuleBuildInfo).getModuleBuildInfo(this._module);
  16. buildInfo.nextEdgeMiddleware = {
  17. matchers,
  18. page: page.replace(new RegExp(`/${_constants.MIDDLEWARE_LOCATION_REGEXP}$`), "") || "/"
  19. };
  20. buildInfo.rootDir = rootDir;
  21. return `
  22. import { adapter, blockUnallowedResponse, enhanceGlobals } from 'next/dist/server/web/adapter'
  23. enhanceGlobals()
  24. var mod = require(${stringifiedPagePath})
  25. var handler = mod.middleware || mod.default;
  26. if (typeof handler !== 'function') {
  27. throw new Error('The Middleware "pages${page}" must export a \`middleware\` or a \`default\` function');
  28. }
  29. export default function (opts) {
  30. return blockUnallowedResponse(adapter({
  31. ...opts,
  32. page: ${JSON.stringify(page)},
  33. handler,
  34. }))
  35. }
  36. `;
  37. }
  38. function encodeMatchers(matchers) {
  39. return Buffer.from(JSON.stringify(matchers)).toString("base64");
  40. }
  41. function decodeMatchers(encodedMatchers) {
  42. return JSON.parse(Buffer.from(encodedMatchers, "base64").toString());
  43. }
  44. //# sourceMappingURL=next-middleware-loader.js.map