@vercel/next 4.7.0 → 4.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11783,7 +11783,10 @@ async function getSourceFilePathFromPage({
11783
11783
  }) {
11784
11784
  const usesSrcDir = await usesSrcDirectory(workPath);
11785
11785
  const extensionsToTry = pageExtensions || ["js", "jsx", "ts", "tsx"];
11786
- for (const pageType of ["pages", "app"]) {
11786
+ for (const pageType of [
11787
+ // middleware is not nested in pages/app
11788
+ ...page === "middleware" ? [""] : ["pages", "app"]
11789
+ ]) {
11787
11790
  let fsPath = import_path2.default.join(workPath, pageType, page);
11788
11791
  if (usesSrcDir) {
11789
11792
  fsPath = import_path2.default.join(workPath, "src", pageType, page);
@@ -12806,6 +12809,127 @@ function normalizeEdgeFunctionPath(shortPath, appPathRoutesManifest) {
12806
12809
  }
12807
12810
  return shortPath;
12808
12811
  }
12812
+ async function getNodeMiddleware({
12813
+ config,
12814
+ baseDir,
12815
+ projectDir,
12816
+ entryPath,
12817
+ nextVersion,
12818
+ nodeVersion,
12819
+ lstatSema,
12820
+ lstatResults,
12821
+ pageExtensions,
12822
+ routesManifest,
12823
+ outputDirectory,
12824
+ prerenderBypassToken,
12825
+ isCorrectMiddlewareOrder,
12826
+ functionsConfigManifest,
12827
+ requiredServerFilesManifest
12828
+ }) {
12829
+ const middlewareFunctionConfig = functionsConfigManifest?.functions["/_middleware"];
12830
+ if (!middlewareFunctionConfig || !middlewareFunctionConfig.matchers) {
12831
+ return null;
12832
+ }
12833
+ const routes = [];
12834
+ const routeMatchers = getRouteMatchers(
12835
+ { matchers: middlewareFunctionConfig.matchers },
12836
+ routesManifest
12837
+ );
12838
+ for (const matcher of routeMatchers) {
12839
+ const route = {
12840
+ continue: true,
12841
+ src: matcher.regexp,
12842
+ has: matcher.has,
12843
+ missing: [
12844
+ {
12845
+ type: "header",
12846
+ key: "x-prerender-revalidate",
12847
+ value: prerenderBypassToken
12848
+ },
12849
+ ...matcher.missing || []
12850
+ ]
12851
+ };
12852
+ route.middlewarePath = "/_middleware";
12853
+ route.middlewareRawSrc = matcher.originalSource ? [matcher.originalSource] : [];
12854
+ if (isCorrectMiddlewareOrder) {
12855
+ route.override = true;
12856
+ }
12857
+ routes.push(route);
12858
+ }
12859
+ const sourceFile = await getSourceFilePathFromPage({
12860
+ workPath: entryPath,
12861
+ page: normalizeSourceFilePageFromManifest("/middleware", "middleware", {}),
12862
+ pageExtensions
12863
+ });
12864
+ const vercelConfigOpts = await (0, import_build_utils.getLambdaOptionsFromFunction)({
12865
+ sourceFile,
12866
+ config
12867
+ });
12868
+ const middlewareFile = import_path2.default.join(
12869
+ entryPath,
12870
+ outputDirectory,
12871
+ "server",
12872
+ "middleware.js"
12873
+ );
12874
+ const middlewareTrace = `${middlewareFile}.nft.json`;
12875
+ const middlewareTraceDir = import_path2.default.dirname(middlewareTrace);
12876
+ const { files } = JSON.parse(await import_fs_extra3.default.readFile(middlewareTrace, "utf8"));
12877
+ const fileList = [];
12878
+ const normalizedBaseDir = `${baseDir}${baseDir.endsWith(import_path2.default.sep) ? "" : import_path2.default.sep}`;
12879
+ files.forEach((file) => {
12880
+ const absolutePath = import_path2.default.join(middlewareTraceDir, file);
12881
+ if (absolutePath.startsWith(normalizedBaseDir)) {
12882
+ fileList.push(import_path2.default.relative(baseDir, absolutePath));
12883
+ } else {
12884
+ console.log("outside base dir", absolutePath);
12885
+ }
12886
+ });
12887
+ const reasons = /* @__PURE__ */ new Map();
12888
+ const tracedFiles = {};
12889
+ await Promise.all(
12890
+ fileList.map(
12891
+ collectTracedFiles(baseDir, lstatResults, lstatSema, reasons, tracedFiles)
12892
+ )
12893
+ );
12894
+ const launcherData = (await import_fs_extra3.default.readFile(import_path2.default.join(__dirname, "middleware-launcher.js"), "utf8")).replace(
12895
+ /(?:var|const) conf = __NEXT_CONFIG__/,
12896
+ `const conf = ${JSON.stringify({
12897
+ ...requiredServerFilesManifest.config,
12898
+ distDir: import_path2.default.relative(
12899
+ projectDir,
12900
+ import_path2.default.join(entryPath, outputDirectory)
12901
+ )
12902
+ })}`
12903
+ ).replace("__NEXT_MIDDLEWARE_PATH__", `./.next/server/middleware.js`);
12904
+ const lambda = new import_build_utils.NodejsLambda({
12905
+ ...vercelConfigOpts,
12906
+ runtime: nodeVersion,
12907
+ handler: import_path2.default.join(
12908
+ import_path2.default.relative(baseDir, projectDir),
12909
+ "___next_launcher.cjs"
12910
+ ),
12911
+ useWebApi: true,
12912
+ shouldAddHelpers: false,
12913
+ shouldAddSourcemapSupport: false,
12914
+ framework: {
12915
+ slug: "nextjs",
12916
+ version: nextVersion
12917
+ },
12918
+ files: {
12919
+ ...tracedFiles,
12920
+ [import_path2.default.relative(baseDir, middlewareFile)]: new import_build_utils.FileFsRef({
12921
+ fsPath: middlewareFile
12922
+ }),
12923
+ [import_path2.default.join(import_path2.default.relative(baseDir, projectDir), "___next_launcher.cjs")]: new import_build_utils.FileBlob({ data: launcherData })
12924
+ }
12925
+ });
12926
+ return {
12927
+ routes,
12928
+ lambdas: {
12929
+ _middleware: lambda
12930
+ }
12931
+ };
12932
+ }
12809
12933
  async function getMiddlewareBundle({
12810
12934
  entryPath,
12811
12935
  outputDirectory,
@@ -14732,6 +14856,23 @@ ${JSON.stringify(
14732
14856
  true
14733
14857
  )];
14734
14858
  });
14859
+ const nodeMiddleware = await getNodeMiddleware({
14860
+ config,
14861
+ baseDir,
14862
+ projectDir,
14863
+ entryPath,
14864
+ nextVersion,
14865
+ nodeVersion: nodeVersion.runtime,
14866
+ lstatSema,
14867
+ lstatResults,
14868
+ pageExtensions: requiredServerFilesManifest.config.pageExtensions,
14869
+ routesManifest,
14870
+ outputDirectory,
14871
+ prerenderBypassToken: prerenderManifest.bypassToken,
14872
+ isCorrectMiddlewareOrder,
14873
+ functionsConfigManifest,
14874
+ requiredServerFilesManifest
14875
+ });
14735
14876
  const middleware = await getMiddlewareBundle({
14736
14877
  config,
14737
14878
  entryPath,
@@ -14742,7 +14883,7 @@ ${JSON.stringify(
14742
14883
  nextVersion,
14743
14884
  appPathRoutesManifest: appPathRoutesManifest || {}
14744
14885
  });
14745
- const isNextDataServerResolving = middleware.staticRoutes.length > 0 && import_semver3.default.gte(nextVersion, NEXT_DATA_MIDDLEWARE_RESOLVING_VERSION);
14886
+ const isNextDataServerResolving = (middleware.staticRoutes.length > 0 || nodeMiddleware) && import_semver3.default.gte(nextVersion, NEXT_DATA_MIDDLEWARE_RESOLVING_VERSION);
14746
14887
  const dynamicRoutes = await getDynamicRoutes({
14747
14888
  entryPath,
14748
14889
  entryDirectory,
@@ -14961,6 +15102,7 @@ ${JSON.stringify(
14961
15102
  ...staticDirectoryFiles,
14962
15103
  ...privateOutputs.files,
14963
15104
  ...middleware.edgeFunctions,
15105
+ ...nodeMiddleware?.lambdas,
14964
15106
  ...isNextDataServerResolving ? {
14965
15107
  __next_data_catchall: nextDataCatchallOutput
14966
15108
  } : {}
@@ -15093,7 +15235,7 @@ ${JSON.stringify(
15093
15235
  // middleware comes directly after redirects but before
15094
15236
  // beforeFiles rewrites as middleware is not a "file" route
15095
15237
  ...routesManifest?.skipMiddlewareUrlNormalize ? denormalizeNextDataRoute(true) : [],
15096
- ...isCorrectMiddlewareOrder ? middleware.staticRoutes : [],
15238
+ ...isCorrectMiddlewareOrder ? [...middleware.staticRoutes, ...nodeMiddleware?.routes || []] : [],
15097
15239
  ...routesManifest?.skipMiddlewareUrlNormalize ? normalizeNextDataRoute(true) : [],
15098
15240
  ...beforeFilesRewrites,
15099
15241
  // Make sure to 404 for the /404 path itself
@@ -15149,7 +15291,7 @@ ${JSON.stringify(
15149
15291
  // while middleware was in beta the order came right before
15150
15292
  // handle: 'filesystem' we maintain this for older versions
15151
15293
  // to prevent a local/deploy mismatch
15152
- ...!isCorrectMiddlewareOrder ? middleware.staticRoutes : [],
15294
+ ...!isCorrectMiddlewareOrder ? [...middleware.staticRoutes, ...nodeMiddleware?.routes || []] : [],
15153
15295
  ...appDir ? [
15154
15296
  ...isAppClientSegmentCacheEnabled && rscPrefetchHeader && prefetchSegmentHeader && prefetchSegmentDirSuffix && prefetchSegmentSuffix ? [
15155
15297
  {
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+
3
+ // src/vercel-request-context.ts
4
+ var SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
5
+ function getContext() {
6
+ const fromSymbol = globalThis;
7
+ return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
8
+ }
9
+
10
+ // src/next-request-context.ts
11
+ var import_async_hooks = require("async_hooks");
12
+ var name = "@next/request-context";
13
+ var NEXT_REQUEST_CONTEXT_SYMBOL = Symbol.for(name);
14
+ var INTERNAL_STORAGE_FIELD_SYMBOL = Symbol.for("internal.storage");
15
+ function getOrCreateContextSingleton() {
16
+ const _globalThis = globalThis;
17
+ if (!_globalThis[NEXT_REQUEST_CONTEXT_SYMBOL]) {
18
+ const storage = new import_async_hooks.AsyncLocalStorage();
19
+ const Context = {
20
+ get: () => storage.getStore(),
21
+ [INTERNAL_STORAGE_FIELD_SYMBOL]: storage
22
+ };
23
+ _globalThis[NEXT_REQUEST_CONTEXT_SYMBOL] = Context;
24
+ }
25
+ return _globalThis[NEXT_REQUEST_CONTEXT_SYMBOL];
26
+ }
27
+ var NextRequestContext = getOrCreateContextSingleton();
28
+ function withNextRequestContext(value, callback) {
29
+ const storage = NextRequestContext[INTERNAL_STORAGE_FIELD_SYMBOL];
30
+ return storage.run(value, callback);
31
+ }
32
+
33
+ // src/edge-function-source/to-plain-headers.ts
34
+ function toPlainHeaders(headers) {
35
+ const result = {};
36
+ if (!headers)
37
+ return result;
38
+ headers.forEach((value, key) => {
39
+ result[key] = value;
40
+ if (key.toLowerCase() === "set-cookie") {
41
+ result[key] = splitCookiesString(value);
42
+ }
43
+ });
44
+ return result;
45
+ }
46
+ function splitCookiesString(cookiesString) {
47
+ const cookiesStrings = [];
48
+ let pos = 0;
49
+ let start;
50
+ let ch;
51
+ let lastComma;
52
+ let nextStart;
53
+ let cookiesSeparatorFound;
54
+ function skipWhitespace() {
55
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos)))
56
+ pos += 1;
57
+ return pos < cookiesString.length;
58
+ }
59
+ function notSpecialChar() {
60
+ ch = cookiesString.charAt(pos);
61
+ return ch !== "=" && ch !== ";" && ch !== ",";
62
+ }
63
+ while (pos < cookiesString.length) {
64
+ start = pos;
65
+ cookiesSeparatorFound = false;
66
+ while (skipWhitespace()) {
67
+ ch = cookiesString.charAt(pos);
68
+ if (ch === ",") {
69
+ lastComma = pos;
70
+ pos += 1;
71
+ skipWhitespace();
72
+ nextStart = pos;
73
+ while (pos < cookiesString.length && notSpecialChar()) {
74
+ pos += 1;
75
+ }
76
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
77
+ cookiesSeparatorFound = true;
78
+ pos = nextStart;
79
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
80
+ start = pos;
81
+ } else {
82
+ pos = lastComma + 1;
83
+ }
84
+ } else {
85
+ pos += 1;
86
+ }
87
+ }
88
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
89
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
90
+ }
91
+ }
92
+ return cookiesStrings;
93
+ }
94
+
95
+ // src/middleware-launcher.ts
96
+ process.chdir(__dirname);
97
+ var region = process.env.VERCEL_REGION || process.env.NOW_REGION;
98
+ if (!process.env.NODE_ENV) {
99
+ process.env.NODE_ENV = region === "dev1" ? "development" : "production";
100
+ }
101
+ if (process.env.NODE_ENV !== "production" && region !== "dev1") {
102
+ console.warn(
103
+ `Warning: NODE_ENV was incorrectly set to "${process.env.NODE_ENV}", this value is being overridden to "production"`
104
+ );
105
+ process.env.NODE_ENV = "production";
106
+ }
107
+ var conf = __NEXT_CONFIG__;
108
+ globalThis.AsyncLocalStorage = require("async_hooks").AsyncLocalStorage;
109
+ var middlewareHandler = require("__NEXT_MIDDLEWARE_PATH__").default;
110
+ var serve = async (request) => {
111
+ try {
112
+ const context = getContext();
113
+ return await withNextRequestContext(
114
+ { waitUntil: context.waitUntil },
115
+ async () => {
116
+ const result = await middlewareHandler({
117
+ request: {
118
+ url: request.url,
119
+ method: request.method,
120
+ headers: toPlainHeaders(request.headers),
121
+ nextConfig: conf,
122
+ page: "/middleware",
123
+ body: request.method !== "GET" && request.method !== "HEAD" ? request.body : void 0,
124
+ waitUntil: context.waitUntil
125
+ }
126
+ });
127
+ if (result.waitUntil && context.waitUntil) {
128
+ context.waitUntil(result.waitUntil);
129
+ }
130
+ return result.response;
131
+ }
132
+ );
133
+ } catch (err) {
134
+ console.error(err);
135
+ process.exit(1);
136
+ }
137
+ };
138
+ module.exports = serve;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vercel/next",
3
- "version": "4.7.0",
3
+ "version": "4.7.2",
4
4
  "license": "Apache-2.0",
5
5
  "main": "./dist/index",
6
6
  "homepage": "https://vercel.com/docs/runtimes#official-runtimes/next-js",
@@ -30,7 +30,7 @@
30
30
  "@types/semver": "6.0.0",
31
31
  "@types/text-table": "0.2.1",
32
32
  "@types/webpack-sources": "3.2.0",
33
- "@vercel/build-utils": "10.2.0",
33
+ "@vercel/build-utils": "10.3.1",
34
34
  "@vercel/routing-utils": "5.0.4",
35
35
  "async-sema": "3.0.1",
36
36
  "buffer-crc32": "0.2.13",