@netlify/plugin-nextjs 4.0.0-rc.1 → 4.0.0-rc.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/lib/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DIVIDER = exports.MINIMUM_REVALIDATE_SECONDS = exports.DYNAMIC_PARAMETER_REGEX = exports.OPTIONAL_CATCH_ALL_REGEX = exports.CATCH_ALL_REGEX = exports.DEFAULT_FUNCTIONS_SRC = exports.HANDLER_FUNCTION_PATH = exports.ODB_FUNCTION_PATH = exports.HIDDEN_PATHS = exports.IMAGE_FUNCTION_NAME = exports.ODB_FUNCTION_NAME = exports.HANDLER_FUNCTION_NAME = void 0;
3
+ exports.DIVIDER = exports.LAMBDA_MAX_SIZE = exports.MINIMUM_REVALIDATE_SECONDS = exports.DYNAMIC_PARAMETER_REGEX = exports.OPTIONAL_CATCH_ALL_REGEX = exports.CATCH_ALL_REGEX = exports.DEFAULT_FUNCTIONS_SRC = exports.HANDLER_FUNCTION_PATH = exports.ODB_FUNCTION_PATH = exports.HIDDEN_PATHS = exports.IMAGE_FUNCTION_NAME = exports.ODB_FUNCTION_NAME = exports.HANDLER_FUNCTION_NAME = void 0;
4
4
  exports.HANDLER_FUNCTION_NAME = '___netlify-handler';
5
5
  exports.ODB_FUNCTION_NAME = '___netlify-odb-handler';
6
6
  exports.IMAGE_FUNCTION_NAME = '_ipx';
@@ -23,6 +23,8 @@ exports.CATCH_ALL_REGEX = /\/\[\.{3}(.*)](.json)?$/;
23
23
  exports.OPTIONAL_CATCH_ALL_REGEX = /\/\[{2}\.{3}(.*)]{2}(.json)?$/;
24
24
  exports.DYNAMIC_PARAMETER_REGEX = /\/\[(.*?)]/g;
25
25
  exports.MINIMUM_REVALIDATE_SECONDS = 60;
26
+ // 50MB, which is the documented max, though the hard max seems to be higher
27
+ exports.LAMBDA_MAX_SIZE = 1024 * 1024 * 50;
26
28
  exports.DIVIDER = `
27
29
  ────────────────────────────────────────────────────────────────
28
30
  `;
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.saveCache = exports.restoreCache = void 0;
4
4
  const path_1 = require("path");
5
5
  const restoreCache = async ({ cache, publish }) => {
6
- const cacheDir = path_1.posix.join(publish, 'cache');
6
+ const cacheDir = path_1.join(publish, 'cache');
7
7
  if (await cache.restore(cacheDir)) {
8
8
  console.log('Next.js cache restored.');
9
9
  }
@@ -13,8 +13,8 @@ const restoreCache = async ({ cache, publish }) => {
13
13
  };
14
14
  exports.restoreCache = restoreCache;
15
15
  const saveCache = async ({ cache, publish }) => {
16
- const cacheDir = path_1.posix.join(publish, 'cache');
17
- const buildManifest = path_1.posix.join(publish, 'build-manifest.json');
16
+ const cacheDir = path_1.join(publish, 'cache');
17
+ const buildManifest = path_1.join(publish, 'build-manifest.json');
18
18
  if (await cache.save(cacheDir, { digests: [buildManifest] })) {
19
19
  console.log('Next.js cache saved.');
20
20
  }
@@ -1,15 +1,22 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.movePublicFiles = exports.unpatchNextFiles = exports.patchNextFiles = exports.moveStaticPages = exports.matchesRewrite = exports.matchesRedirect = exports.matchMiddleware = exports.stripLocale = exports.isDynamicRoute = void 0;
1
7
  /* eslint-disable max-lines */
2
- const { cpus } = require('os');
3
- const { yellowBright } = require('chalk');
4
- const { existsSync, readJson, move, copy, writeJson, readFile, writeFile, ensureDir, readFileSync, } = require('fs-extra');
5
- const globby = require('globby');
6
- const { outdent } = require('outdent');
7
- const pLimit = require('p-limit');
8
- const { join } = require('pathe');
9
- const slash = require('slash');
10
- const { MINIMUM_REVALIDATE_SECONDS, DIVIDER } = require('../constants');
8
+ const os_1 = require("os");
9
+ const chalk_1 = require("chalk");
10
+ const fs_extra_1 = require("fs-extra");
11
+ const globby_1 = __importDefault(require("globby"));
12
+ const outdent_1 = require("outdent");
13
+ const p_limit_1 = __importDefault(require("p-limit"));
14
+ const pathe_1 = require("pathe");
15
+ const slash_1 = __importDefault(require("slash"));
16
+ const constants_1 = require("../constants");
11
17
  const TEST_ROUTE = /(|\/)\[[^/]+?](\/|\.html|$)/;
12
18
  const isDynamicRoute = (route) => TEST_ROUTE.test(route);
19
+ exports.isDynamicRoute = isDynamicRoute;
13
20
  const stripLocale = (rawPath, locales = []) => {
14
21
  const [locale, ...segments] = rawPath.split('/');
15
22
  if (locales.includes(locale)) {
@@ -17,8 +24,10 @@ const stripLocale = (rawPath, locales = []) => {
17
24
  }
18
25
  return rawPath;
19
26
  };
27
+ exports.stripLocale = stripLocale;
20
28
  const matchMiddleware = (middleware, filePath) => (middleware === null || middleware === void 0 ? void 0 : middleware.includes('')) ||
21
29
  (middleware === null || middleware === void 0 ? void 0 : middleware.find((middlewarePath) => filePath === middlewarePath || filePath === `${middlewarePath}.html` || filePath.startsWith(`${middlewarePath}/`)));
30
+ exports.matchMiddleware = matchMiddleware;
22
31
  const matchesRedirect = (file, redirects) => {
23
32
  if (!Array.isArray(redirects)) {
24
33
  return false;
@@ -31,39 +40,36 @@ const matchesRedirect = (file, redirects) => {
31
40
  return new RegExp(redirect.regex).test(`/${file.slice(0, -5)}`);
32
41
  });
33
42
  };
43
+ exports.matchesRedirect = matchesRedirect;
34
44
  const matchesRewrite = (file, rewrites) => {
35
45
  if (Array.isArray(rewrites)) {
36
- return matchesRedirect(file, rewrites);
46
+ return exports.matchesRedirect(file, rewrites);
37
47
  }
38
48
  if (!Array.isArray(rewrites === null || rewrites === void 0 ? void 0 : rewrites.beforeFiles)) {
39
49
  return false;
40
50
  }
41
- return matchesRedirect(file, rewrites.beforeFiles);
51
+ return exports.matchesRedirect(file, rewrites.beforeFiles);
42
52
  };
43
- exports.matchesRedirect = matchesRedirect;
44
53
  exports.matchesRewrite = matchesRewrite;
45
- exports.matchMiddleware = matchMiddleware;
46
- exports.stripLocale = stripLocale;
47
- exports.isDynamicRoute = isDynamicRoute;
48
54
  // eslint-disable-next-line max-lines-per-function
49
- exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
55
+ const moveStaticPages = async ({ netlifyConfig, target, i18n, }) => {
50
56
  console.log('Moving static page files to serve from CDN...');
51
- const outputDir = join(netlifyConfig.build.publish, target === 'server' ? 'server' : 'serverless');
52
- const root = join(outputDir, 'pages');
53
- const buildId = readFileSync(join(netlifyConfig.build.publish, 'BUILD_ID'), 'utf8').trim();
54
- const dataDir = join('_next', 'data', buildId);
55
- await ensureDir(dataDir);
57
+ const outputDir = pathe_1.join(netlifyConfig.build.publish, target === 'server' ? 'server' : 'serverless');
58
+ const root = pathe_1.join(outputDir, 'pages');
59
+ const buildId = fs_extra_1.readFileSync(pathe_1.join(netlifyConfig.build.publish, 'BUILD_ID'), 'utf8').trim();
60
+ const dataDir = pathe_1.join('_next', 'data', buildId);
61
+ await fs_extra_1.ensureDir(dataDir);
56
62
  // Load the middleware manifest so we can check if a file matches it before moving
57
63
  let middleware;
58
- const manifestPath = join(outputDir, 'middleware-manifest.json');
59
- if (existsSync(manifestPath)) {
60
- const manifest = await readJson(manifestPath);
64
+ const manifestPath = pathe_1.join(outputDir, 'middleware-manifest.json');
65
+ if (fs_extra_1.existsSync(manifestPath)) {
66
+ const manifest = await fs_extra_1.readJson(manifestPath);
61
67
  if (manifest === null || manifest === void 0 ? void 0 : manifest.middleware) {
62
68
  middleware = Object.keys(manifest.middleware).map((path) => path.slice(1));
63
69
  }
64
70
  }
65
- const prerenderManifest = await readJson(join(netlifyConfig.build.publish, 'prerender-manifest.json'));
66
- const { redirects, rewrites } = await readJson(join(netlifyConfig.build.publish, 'routes-manifest.json'));
71
+ const prerenderManifest = await fs_extra_1.readJson(pathe_1.join(netlifyConfig.build.publish, 'prerender-manifest.json'));
72
+ const { redirects, rewrites } = await fs_extra_1.readJson(pathe_1.join(netlifyConfig.build.publish, 'routes-manifest.json'));
67
73
  const isrFiles = new Set();
68
74
  const shortRevalidateRoutes = [];
69
75
  Object.entries(prerenderManifest.routes).forEach(([route, { initialRevalidateSeconds }]) => {
@@ -72,7 +78,7 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
72
78
  const trimmedPath = route.slice(1);
73
79
  isrFiles.add(`${trimmedPath}.html`);
74
80
  isrFiles.add(`${trimmedPath}.json`);
75
- if (initialRevalidateSeconds < MINIMUM_REVALIDATE_SECONDS) {
81
+ if (initialRevalidateSeconds < constants_1.MINIMUM_REVALIDATE_SECONDS) {
76
82
  shortRevalidateRoutes.push({ Route: route, Revalidate: initialRevalidateSeconds });
77
83
  }
78
84
  }
@@ -81,20 +87,20 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
81
87
  const filesManifest = {};
82
88
  const moveFile = async (file) => {
83
89
  const isData = file.endsWith('.json');
84
- const source = join(root, file);
85
- const targetFile = isData ? join(dataDir, file) : file;
90
+ const source = pathe_1.join(root, file);
91
+ const targetFile = isData ? pathe_1.join(dataDir, file) : file;
86
92
  files.push(file);
87
93
  filesManifest[file] = targetFile;
88
- const dest = join(netlifyConfig.build.publish, targetFile);
94
+ const dest = pathe_1.join(netlifyConfig.build.publish, targetFile);
89
95
  try {
90
- await move(source, dest);
96
+ await fs_extra_1.move(source, dest);
91
97
  }
92
98
  catch (error) {
93
99
  console.warn('Error moving file', source, error);
94
100
  }
95
101
  };
96
102
  // Move all static files, except error documents and nft manifests
97
- const pages = await globby(['**/*.{html,json}', '!**/(500|404|*.js.nft).{html,json}'], {
103
+ const pages = await globby_1.default(['**/*.{html,json}', '!**/(500|404|*.js.nft).{html,json}'], {
98
104
  cwd: root,
99
105
  dot: true,
100
106
  });
@@ -103,27 +109,27 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
103
109
  const matchedRedirects = new Set();
104
110
  const matchedRewrites = new Set();
105
111
  // Limit concurrent file moves to number of cpus or 2 if there is only 1
106
- const limit = pLimit(Math.max(2, cpus().length));
112
+ const limit = p_limit_1.default(Math.max(2, os_1.cpus().length));
107
113
  const promises = pages.map((rawPath) => {
108
- const filePath = slash(rawPath);
114
+ const filePath = slash_1.default(rawPath);
109
115
  // Don't move ISR files, as they're used for the first request
110
116
  if (isrFiles.has(filePath)) {
111
117
  return;
112
118
  }
113
- if (isDynamicRoute(filePath)) {
119
+ if (exports.isDynamicRoute(filePath)) {
114
120
  return;
115
121
  }
116
- if (matchesRedirect(filePath, redirects)) {
122
+ if (exports.matchesRedirect(filePath, redirects)) {
117
123
  matchedRedirects.add(filePath);
118
124
  return;
119
125
  }
120
- if (matchesRewrite(filePath, rewrites)) {
126
+ if (exports.matchesRewrite(filePath, rewrites)) {
121
127
  matchedRewrites.add(filePath);
122
128
  return;
123
129
  }
124
130
  // Middleware matches against the unlocalised path
125
- const unlocalizedPath = stripLocale(rawPath, i18n === null || i18n === void 0 ? void 0 : i18n.locales);
126
- const middlewarePath = matchMiddleware(middleware, unlocalizedPath);
131
+ const unlocalizedPath = exports.stripLocale(rawPath, i18n === null || i18n === void 0 ? void 0 : i18n.locales);
132
+ const middlewarePath = exports.matchMiddleware(middleware, unlocalizedPath);
127
133
  // If a file matches middleware it can't be offloaded to the CDN, and needs to stay at the origin to be served by next/server
128
134
  if (middlewarePath) {
129
135
  matchingMiddleware.add(middlewarePath);
@@ -135,69 +141,69 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
135
141
  await Promise.all(promises);
136
142
  console.log(`Moved ${files.length} files`);
137
143
  if (matchedPages.size !== 0) {
138
- console.log(yellowBright(outdent `
144
+ console.log(chalk_1.yellowBright(outdent_1.outdent `
139
145
  Skipped moving ${matchedPages.size} ${matchedPages.size === 1 ? 'file because it matches' : 'files because they match'} middleware, so cannot be deployed to the CDN and will be served from the origin instead.
140
146
  This is fine, but we're letting you know because it may not be what you expect.
141
147
  `));
142
- console.log(outdent `
148
+ console.log(outdent_1.outdent `
143
149
  The following middleware matched statically-rendered pages:
144
150
 
145
- ${yellowBright([...matchingMiddleware].map((mid) => `- /${mid}/_middleware`).join('\n'))}
146
- ${DIVIDER}
151
+ ${chalk_1.yellowBright([...matchingMiddleware].map((mid) => `- /${mid}/_middleware`).join('\n'))}
152
+ ${constants_1.DIVIDER}
147
153
  `);
148
154
  // There could potentially be thousands of matching pages, so we don't want to spam the console with this
149
155
  if (matchedPages.size < 50) {
150
- console.log(outdent `
156
+ console.log(outdent_1.outdent `
151
157
  The following files matched middleware and were not moved to the CDN:
152
158
 
153
- ${yellowBright([...matchedPages].map((mid) => `- ${mid}`).join('\n'))}
154
- ${DIVIDER}
159
+ ${chalk_1.yellowBright([...matchedPages].map((mid) => `- ${mid}`).join('\n'))}
160
+ ${constants_1.DIVIDER}
155
161
  `);
156
162
  }
157
163
  }
158
164
  if (matchedRedirects.size !== 0 || matchedRewrites.size !== 0) {
159
- console.log(yellowBright(outdent `
165
+ console.log(chalk_1.yellowBright(outdent_1.outdent `
160
166
  Skipped moving ${matchedRedirects.size + matchedRewrites.size} files because they match redirects or beforeFiles rewrites, so cannot be deployed to the CDN and will be served from the origin instead.
161
167
  `));
162
168
  if (matchedRedirects.size < 50 && matchedRedirects.size !== 0) {
163
- console.log(outdent `
169
+ console.log(outdent_1.outdent `
164
170
  The following files matched redirects and were not moved to the CDN:
165
171
 
166
- ${yellowBright([...matchedRedirects].map((mid) => `- ${mid}`).join('\n'))}
167
- ${DIVIDER}
172
+ ${chalk_1.yellowBright([...matchedRedirects].map((mid) => `- ${mid}`).join('\n'))}
173
+ ${constants_1.DIVIDER}
168
174
  `);
169
175
  }
170
176
  if (matchedRewrites.size < 50 && matchedRewrites.size !== 0) {
171
- console.log(outdent `
177
+ console.log(outdent_1.outdent `
172
178
  The following files matched beforeFiles rewrites and were not moved to the CDN:
173
179
 
174
- ${yellowBright([...matchedRewrites].map((mid) => `- ${mid}`).join('\n'))}
175
- ${DIVIDER}
180
+ ${chalk_1.yellowBright([...matchedRewrites].map((mid) => `- ${mid}`).join('\n'))}
181
+ ${constants_1.DIVIDER}
176
182
  `);
177
183
  }
178
184
  }
179
185
  // Write the manifest for use in the serverless functions
180
- await writeJson(join(netlifyConfig.build.publish, 'static-manifest.json'), Object.entries(filesManifest));
186
+ await fs_extra_1.writeJson(pathe_1.join(netlifyConfig.build.publish, 'static-manifest.json'), Object.entries(filesManifest));
181
187
  if (i18n === null || i18n === void 0 ? void 0 : i18n.defaultLocale) {
182
188
  // Copy the default locale into the root
183
- const defaultLocaleDir = join(netlifyConfig.build.publish, i18n.defaultLocale);
184
- if (existsSync(defaultLocaleDir)) {
185
- await copy(defaultLocaleDir, `${netlifyConfig.build.publish}/`);
189
+ const defaultLocaleDir = pathe_1.join(netlifyConfig.build.publish, i18n.defaultLocale);
190
+ if (fs_extra_1.existsSync(defaultLocaleDir)) {
191
+ await fs_extra_1.copy(defaultLocaleDir, `${netlifyConfig.build.publish}/`);
186
192
  }
187
- const defaultLocaleIndex = join(netlifyConfig.build.publish, `${i18n.defaultLocale}.html`);
188
- const indexHtml = join(netlifyConfig.build.publish, 'index.html');
189
- if (existsSync(defaultLocaleIndex) && !existsSync(indexHtml)) {
193
+ const defaultLocaleIndex = pathe_1.join(netlifyConfig.build.publish, `${i18n.defaultLocale}.html`);
194
+ const indexHtml = pathe_1.join(netlifyConfig.build.publish, 'index.html');
195
+ if (fs_extra_1.existsSync(defaultLocaleIndex) && !fs_extra_1.existsSync(indexHtml)) {
190
196
  try {
191
- await copy(defaultLocaleIndex, indexHtml, { overwrite: false });
192
- await copy(join(netlifyConfig.build.publish, `${i18n.defaultLocale}.json`), join(netlifyConfig.build.publish, 'index.json'), { overwrite: false });
197
+ await fs_extra_1.copy(defaultLocaleIndex, indexHtml, { overwrite: false });
198
+ await fs_extra_1.copy(pathe_1.join(netlifyConfig.build.publish, `${i18n.defaultLocale}.json`), pathe_1.join(netlifyConfig.build.publish, 'index.json'), { overwrite: false });
193
199
  }
194
200
  catch { }
195
201
  }
196
202
  }
197
203
  if (shortRevalidateRoutes.length !== 0) {
198
- console.log(outdent `
199
- The following routes use "revalidate" values of under ${MINIMUM_REVALIDATE_SECONDS} seconds, which is not supported.
200
- They will use a revalidate time of ${MINIMUM_REVALIDATE_SECONDS} seconds instead.
204
+ console.log(outdent_1.outdent `
205
+ The following routes use "revalidate" values of under ${constants_1.MINIMUM_REVALIDATE_SECONDS} seconds, which is not supported.
206
+ They will use a revalidate time of ${constants_1.MINIMUM_REVALIDATE_SECONDS} seconds instead.
201
207
  `);
202
208
  console.table(shortRevalidateRoutes);
203
209
  // TODO: add these docs
@@ -209,17 +215,18 @@ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
209
215
  // )
210
216
  }
211
217
  };
218
+ exports.moveStaticPages = moveStaticPages;
212
219
  const patchFile = async ({ file, from, to }) => {
213
- if (!existsSync(file)) {
220
+ if (!fs_extra_1.existsSync(file)) {
214
221
  return;
215
222
  }
216
- const content = await readFile(file, 'utf8');
223
+ const content = await fs_extra_1.readFile(file, 'utf8');
217
224
  if (content.includes(to)) {
218
225
  return;
219
226
  }
220
227
  const newContent = content.replace(from, to);
221
- await writeFile(`${file}.orig`, content);
222
- await writeFile(file, newContent);
228
+ await fs_extra_1.writeFile(`${file}.orig`, content);
229
+ await fs_extra_1.writeFile(file, newContent);
223
230
  };
224
231
  const getServerFile = (root) => {
225
232
  let serverFile;
@@ -240,7 +247,7 @@ const getServerFile = (root) => {
240
247
  }
241
248
  return serverFile;
242
249
  };
243
- exports.patchNextFiles = async (root) => {
250
+ const patchNextFiles = async (root) => {
244
251
  const serverFile = getServerFile(root);
245
252
  console.log(`Patching ${serverFile}`);
246
253
  if (serverFile) {
@@ -251,23 +258,26 @@ exports.patchNextFiles = async (root) => {
251
258
  });
252
259
  }
253
260
  };
254
- exports.unpatchNextFiles = async (root) => {
261
+ exports.patchNextFiles = patchNextFiles;
262
+ const unpatchNextFiles = async (root) => {
255
263
  const serverFile = getServerFile(root);
256
264
  const origFile = `${serverFile}.orig`;
257
- if (existsSync(origFile)) {
258
- await move(origFile, serverFile, { overwrite: true });
265
+ if (fs_extra_1.existsSync(origFile)) {
266
+ await fs_extra_1.move(origFile, serverFile, { overwrite: true });
259
267
  }
260
268
  };
261
- exports.movePublicFiles = async ({ appDir, outdir, publish }) => {
269
+ exports.unpatchNextFiles = unpatchNextFiles;
270
+ const movePublicFiles = async ({ appDir, outdir, publish, }) => {
262
271
  // `outdir` is a config property added when using Next.js with Nx. It's typically
263
272
  // a relative path outside of the appDir, e.g. '../../dist/apps/<app-name>', and
264
273
  // the parent directory of the .next directory.
265
274
  // If it exists, copy the files from the public folder there in order to include
266
275
  // any files that were generated during the build. Otherwise, copy the public
267
276
  // directory from the original app directory.
268
- const publicDir = outdir ? join(appDir, outdir, 'public') : join(appDir, 'public');
269
- if (existsSync(publicDir)) {
270
- await copy(publicDir, `${publish}/`);
277
+ const publicDir = outdir ? pathe_1.join(appDir, outdir, 'public') : pathe_1.join(appDir, 'public');
278
+ if (fs_extra_1.existsSync(publicDir)) {
279
+ await fs_extra_1.copy(publicDir, `${publish}/`);
271
280
  }
272
281
  };
282
+ exports.movePublicFiles = movePublicFiles;
273
283
  /* eslint-enable max-lines */
@@ -26,10 +26,10 @@ exports.generateFunctions = generateFunctions;
26
26
  * Writes a file in each function directory that contains references to every page entrypoint.
27
27
  * This is just so that the nft bundler knows about them. We'll eventually do this better.
28
28
  */
29
- const generatePagesResolver = async ({ constants: { INTERNAL_FUNCTIONS_SRC, FUNCTIONS_SRC = constants_1.DEFAULT_FUNCTIONS_SRC }, netlifyConfig, target, }) => {
29
+ const generatePagesResolver = async ({ constants: { INTERNAL_FUNCTIONS_SRC, FUNCTIONS_SRC = constants_1.DEFAULT_FUNCTIONS_SRC, PUBLISH_DIR }, target, }) => {
30
30
  const functionsPath = INTERNAL_FUNCTIONS_SRC || FUNCTIONS_SRC;
31
31
  const jsSource = await getPageResolver_1.getPageResolver({
32
- netlifyConfig,
32
+ publish: PUBLISH_DIR,
33
33
  target,
34
34
  });
35
35
  await fs_extra_1.writeFile(pathe_1.join(functionsPath, constants_1.ODB_FUNCTION_NAME, 'pages.js'), jsSource);
@@ -1,94 +1,123 @@
1
- const { existsSync, promises } = require('fs');
2
- const path = require('path');
3
- const { relative } = require('path');
4
- const { yellowBright, greenBright, blueBright, redBright, reset } = require('chalk');
5
- const { async: StreamZip } = require('node-stream-zip');
6
- const outdent = require('outdent');
7
- const prettyBytes = require('pretty-bytes');
8
- const { satisfies } = require('semver');
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.logBetaMessage = exports.checkZipSize = exports.checkForRootPublish = exports.checkNextSiteHasBuilt = exports.checkForOldFunctions = exports.verifyNetlifyBuildVersion = void 0;
26
+ const fs_1 = require("fs");
27
+ const path_1 = __importStar(require("path"));
28
+ const chalk_1 = require("chalk");
29
+ const node_stream_zip_1 = require("node-stream-zip");
30
+ const outdent_1 = require("outdent");
31
+ const pretty_bytes_1 = __importDefault(require("pretty-bytes"));
32
+ const semver_1 = require("semver");
33
+ const constants_1 = require("../constants");
9
34
  // This is when nft support was added
10
35
  const REQUIRED_BUILD_VERSION = '>=18.16.0';
11
- exports.verifyNetlifyBuildVersion = ({ IS_LOCAL, NETLIFY_BUILD_VERSION, failBuild }) => {
36
+ const verifyNetlifyBuildVersion = ({ IS_LOCAL, NETLIFY_BUILD_VERSION, failBuild, }) => {
12
37
  // We check for build version because that's what's available to us, but prompt about the cli because that's what they can upgrade
13
- if (IS_LOCAL && !satisfies(NETLIFY_BUILD_VERSION, REQUIRED_BUILD_VERSION, { includePrerelease: true })) {
14
- return failBuild(outdent `
38
+ if (IS_LOCAL && !semver_1.satisfies(NETLIFY_BUILD_VERSION, REQUIRED_BUILD_VERSION, { includePrerelease: true })) {
39
+ return failBuild(outdent_1.outdent `
15
40
  This version of the Essential Next.js plugin requires netlify-cli@6.12.4 or higher. Please upgrade and try again.
16
41
  You can do this by running: "npm install -g netlify-cli@latest" or "yarn global add netlify-cli@latest"
17
42
  `);
18
43
  }
19
44
  };
20
- exports.checkForOldFunctions = async ({ functions }) => {
45
+ exports.verifyNetlifyBuildVersion = verifyNetlifyBuildVersion;
46
+ const checkForOldFunctions = async ({ functions }) => {
21
47
  const allOldFunctions = await functions.list();
22
48
  const oldFunctions = allOldFunctions.filter(({ name }) => name.startsWith('next_'));
23
49
  if (oldFunctions.length !== 0) {
24
- console.log(yellowBright(outdent `
50
+ console.log(chalk_1.yellowBright(outdent_1.outdent `
25
51
  We have found the following functions in your site that seem to be left over from the old Next.js plugin (v3). We have guessed this because the name starts with "next_".
26
52
 
27
- ${reset(oldFunctions.map(({ name }) => `- ${name}`).join('\n'))}
53
+ ${chalk_1.reset(oldFunctions.map(({ name }) => `- ${name}`).join('\n'))}
28
54
 
29
55
  If they were created by the old plugin, these functions are likely to cause errors so should be removed. You can do this by deleting the following directories:
30
56
 
31
- ${reset(oldFunctions.map(({ mainFile }) => `- ${path.relative(process.cwd(), path.dirname(mainFile))}`).join('\n'))}
57
+ ${chalk_1.reset(oldFunctions.map(({ mainFile }) => `- ${path_1.default.relative(process.cwd(), path_1.default.dirname(mainFile))}`).join('\n'))}
32
58
  `));
33
59
  }
34
60
  };
35
- exports.checkNextSiteHasBuilt = ({ publish, failBuild }) => {
36
- if (!existsSync(path.join(publish, 'BUILD_ID'))) {
37
- return failBuild(outdent `
38
- The directory "${path.relative(process.cwd(), publish)}" does not contain a Next.js production build. Perhaps the build command was not run, or you specified the wrong publish directory.
61
+ exports.checkForOldFunctions = checkForOldFunctions;
62
+ const checkNextSiteHasBuilt = ({ publish, failBuild, }) => {
63
+ if (!fs_1.existsSync(path_1.default.join(publish, 'BUILD_ID'))) {
64
+ return failBuild(outdent_1.outdent `
65
+ The directory "${path_1.default.relative(process.cwd(), publish)}" does not contain a Next.js production build. Perhaps the build command was not run, or you specified the wrong publish directory.
39
66
  In most cases it should be set to the site's ".next" directory path, unless you have chosen a custom "distDir" in your Next config.
40
67
  If you are using "next export" then the Essential Next.js plugin should be removed. See https://ntl.fyi/remove-plugin for details.
41
68
  `);
42
69
  }
43
- if (existsSync(path.join(publish, 'export-detail.json'))) {
44
- failBuild(outdent `
70
+ if (fs_1.existsSync(path_1.default.join(publish, 'export-detail.json'))) {
71
+ failBuild(outdent_1.outdent `
45
72
  Detected that "next export" was run, but site is incorrectly publishing the ".next" directory.
46
73
  This plugin is not needed for "next export" so should be removed, and publish directory set to "out".
47
74
  See https://ntl.fyi/remove-plugin for more details on how to remove this plugin.
48
75
  `);
49
76
  }
50
77
  };
51
- exports.checkForRootPublish = ({ publish, failBuild }) => {
52
- if (path.resolve(publish) === path.resolve('.')) {
53
- failBuild(outdent `
78
+ exports.checkNextSiteHasBuilt = checkNextSiteHasBuilt;
79
+ const checkForRootPublish = ({ publish, failBuild, }) => {
80
+ if (path_1.default.resolve(publish) === path_1.default.resolve('.')) {
81
+ failBuild(outdent_1.outdent `
54
82
  Your publish directory is pointing to the base directory of your site. This is not supported for Next.js sites, and is probably a mistake.
55
83
  In most cases it should be set to ".next", unless you have chosen a custom "distDir" in your Next config, or the Next site is in a subdirectory.
56
84
  `);
57
85
  }
58
86
  };
59
- // 50MB, which is the documented max, though the hard max seems to be higher
60
- const LAMBDA_MAX_SIZE = 1024 * 1024 * 50;
61
- exports.checkZipSize = async (file, maxSize = LAMBDA_MAX_SIZE) => {
62
- if (!existsSync(file)) {
87
+ exports.checkForRootPublish = checkForRootPublish;
88
+ const checkZipSize = async (file, maxSize = constants_1.LAMBDA_MAX_SIZE) => {
89
+ if (!fs_1.existsSync(file)) {
63
90
  console.warn(`Could not check zip size because ${file} does not exist`);
64
91
  return;
65
92
  }
66
- const fileSize = await promises.stat(file).then(({ size }) => size);
93
+ const fileSize = await fs_1.promises.stat(file).then(({ size }) => size);
67
94
  if (fileSize < maxSize) {
68
95
  return;
69
96
  }
70
97
  // We don't fail the build, because the actual hard max size is larger so it might still succeed
71
- console.log(redBright(outdent `
72
- The function zip ${yellowBright(relative(process.cwd(), file))} size is ${prettyBytes(fileSize)}, which is larger than the maximum supported size of ${prettyBytes(maxSize)}.
98
+ console.log(chalk_1.redBright(outdent_1.outdent `
99
+ The function zip ${chalk_1.yellowBright(path_1.relative(process.cwd(), file))} size is ${pretty_bytes_1.default(fileSize)}, which is larger than the maximum supported size of ${pretty_bytes_1.default(maxSize)}.
73
100
  There are a few reasons this could happen. You may have accidentally bundled a large dependency, or you might have a
74
101
  large number of pre-rendered pages included.
75
102
  `));
76
- const zip = new StreamZip({ file });
103
+ const zip = new node_stream_zip_1.async({ file });
77
104
  console.log(`Contains ${await zip.entriesCount} files`);
78
105
  const sortedFiles = Object.values(await zip.entries()).sort((a, b) => b.size - a.size);
79
106
  const largest = {};
80
107
  for (let i = 0; i < 10 && i < sortedFiles.length; i++) {
81
108
  largest[`${i + 1}`] = {
82
109
  File: sortedFiles[i].name,
83
- 'Compressed Size': prettyBytes(sortedFiles[i].compressedSize),
84
- 'Uncompressed Size': prettyBytes(sortedFiles[i].size),
110
+ 'Compressed Size': pretty_bytes_1.default(sortedFiles[i].compressedSize),
111
+ 'Uncompressed Size': pretty_bytes_1.default(sortedFiles[i].size),
85
112
  };
86
113
  }
87
- console.log(yellowBright `\n\nThese are the largest files in the zip:`);
114
+ console.log(chalk_1.yellowBright `\n\nThese are the largest files in the zip:`);
88
115
  console.table(largest);
89
- console.log(greenBright `\n\nFor more information on fixing this, see ${blueBright `https://ntl.fyi/large-next-functions`}`);
116
+ console.log(chalk_1.greenBright `\n\nFor more information on fixing this, see ${chalk_1.blueBright `https://ntl.fyi/large-next-functions`}`);
90
117
  };
91
- exports.logBetaMessage = () => console.log(greenBright(outdent `
118
+ exports.checkZipSize = checkZipSize;
119
+ const logBetaMessage = () => console.log(chalk_1.greenBright(outdent_1.outdent `
92
120
  Thank you for trying the Essential Next.js beta plugin.
93
- Please share feedback (both good and bad) at ${blueBright `https://ntl.fyi/next-beta-feedback`}
121
+ Please share feedback (both good and bad) at ${chalk_1.blueBright `https://ntl.fyi/next-beta-feedback`}
94
122
  `));
123
+ exports.logBetaMessage = logBetaMessage;
package/lib/index.js CHANGED
@@ -1,58 +1,60 @@
1
- const { join, relative } = require('path');
2
- const { ODB_FUNCTION_NAME } = require('./constants');
3
- const { restoreCache, saveCache } = require('./helpers/cache');
4
- const { getNextConfig, configureHandlerFunctions } = require('./helpers/config');
5
- const { moveStaticPages, movePublicFiles, patchNextFiles, unpatchNextFiles } = require('./helpers/files');
6
- const { generateFunctions, setupImageFunction, generatePagesResolver } = require('./helpers/functions');
7
- const { generateRedirects } = require('./helpers/redirects');
8
- const { verifyNetlifyBuildVersion, checkNextSiteHasBuilt, checkForRootPublish, logBetaMessage, checkZipSize, checkForOldFunctions, } = require('./helpers/verification');
9
- /** @type import("@netlify/build").NetlifyPlugin */
10
- module.exports = {
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path_1 = require("path");
4
+ const constants_1 = require("./constants");
5
+ const cache_1 = require("./helpers/cache");
6
+ const config_1 = require("./helpers/config");
7
+ const files_1 = require("./helpers/files");
8
+ const functions_1 = require("./helpers/functions");
9
+ const redirects_1 = require("./helpers/redirects");
10
+ const verification_1 = require("./helpers/verification");
11
+ const plugin = {
11
12
  async onPreBuild({ constants, netlifyConfig, utils: { build: { failBuild }, cache, }, }) {
12
13
  var _a;
13
- logBetaMessage();
14
+ verification_1.logBetaMessage();
14
15
  const { publish } = netlifyConfig.build;
15
- checkForRootPublish({ publish, failBuild });
16
- verifyNetlifyBuildVersion({ failBuild, ...constants });
17
- await restoreCache({ cache, publish });
16
+ verification_1.checkForRootPublish({ publish, failBuild });
17
+ verification_1.verifyNetlifyBuildVersion({ failBuild, ...constants });
18
+ await cache_1.restoreCache({ cache, publish });
18
19
  (_a = netlifyConfig.build).environment || (_a.environment = {});
19
20
  // eslint-disable-next-line unicorn/consistent-destructuring
20
21
  netlifyConfig.build.environment.NEXT_PRIVATE_TARGET = 'server';
21
22
  },
22
23
  async onBuild({ constants, netlifyConfig, utils: { build: { failBuild }, }, }) {
23
24
  const { publish } = netlifyConfig.build;
24
- checkNextSiteHasBuilt({ publish, failBuild });
25
- const { appDir, basePath, i18n, images, target, ignore, trailingSlash, outdir } = await getNextConfig({
25
+ verification_1.checkNextSiteHasBuilt({ publish, failBuild });
26
+ const { appDir, basePath, i18n, images, target, ignore, trailingSlash, outdir } = await config_1.getNextConfig({
26
27
  publish,
27
28
  failBuild,
28
29
  });
29
- configureHandlerFunctions({ netlifyConfig, ignore, publish: relative(process.cwd(), publish) });
30
- await generateFunctions(constants, appDir);
31
- await generatePagesResolver({ netlifyConfig, target, constants });
32
- await movePublicFiles({ appDir, outdir, publish });
30
+ config_1.configureHandlerFunctions({ netlifyConfig, ignore, publish: path_1.relative(process.cwd(), publish) });
31
+ await functions_1.generateFunctions(constants, appDir);
32
+ await functions_1.generatePagesResolver({ target, constants });
33
+ await files_1.movePublicFiles({ appDir, outdir, publish });
33
34
  if (process.env.EXPERIMENTAL_ODB_TTL) {
34
- await patchNextFiles(basePath);
35
+ await files_1.patchNextFiles(basePath);
35
36
  }
36
37
  if (process.env.EXPERIMENTAL_MOVE_STATIC_PAGES) {
37
38
  console.log("The flag 'EXPERIMENTAL_MOVE_STATIC_PAGES' is no longer required, as it is now the default. To disable this behavior, set the env var 'SERVE_STATIC_FILES_FROM_ORIGIN' to 'true'");
38
39
  }
39
40
  if (!process.env.SERVE_STATIC_FILES_FROM_ORIGIN) {
40
- await moveStaticPages({ target, failBuild, netlifyConfig, i18n });
41
+ await files_1.moveStaticPages({ target, netlifyConfig, i18n });
41
42
  }
42
- await setupImageFunction({ constants, imageconfig: images, netlifyConfig, basePath });
43
- await generateRedirects({
43
+ await functions_1.setupImageFunction({ constants, imageconfig: images, netlifyConfig, basePath });
44
+ await redirects_1.generateRedirects({
44
45
  netlifyConfig,
45
46
  nextConfig: { basePath, i18n, trailingSlash, appDir },
46
47
  });
47
48
  },
48
- async onPostBuild({ netlifyConfig, utils: { cache, functions, failBuild }, constants: { FUNCTIONS_DIST } }) {
49
- await saveCache({ cache, publish: netlifyConfig.build.publish });
50
- await checkForOldFunctions({ functions });
51
- await checkZipSize(join(FUNCTIONS_DIST, `${ODB_FUNCTION_NAME}.zip`));
52
- const { basePath } = await getNextConfig({ publish: netlifyConfig.build.publish, failBuild });
53
- await unpatchNextFiles(basePath);
49
+ async onPostBuild({ netlifyConfig, utils: { cache, functions, build: { failBuild }, }, constants: { FUNCTIONS_DIST }, }) {
50
+ await cache_1.saveCache({ cache, publish: netlifyConfig.build.publish });
51
+ await verification_1.checkForOldFunctions({ functions });
52
+ await verification_1.checkZipSize(path_1.join(FUNCTIONS_DIST, `${constants_1.ODB_FUNCTION_NAME}.zip`));
53
+ const { basePath } = await config_1.getNextConfig({ publish: netlifyConfig.build.publish, failBuild });
54
+ await files_1.unpatchNextFiles(basePath);
54
55
  },
55
56
  onEnd() {
56
- logBetaMessage();
57
+ verification_1.logBetaMessage();
57
58
  },
58
59
  };
60
+ module.exports = plugin;
@@ -48,7 +48,7 @@ const makeHandler = () =>
48
48
  var _a, _b, _c;
49
49
  let requestMode = mode;
50
50
  // Ensure that paths are encoded - but don't double-encode them
51
- event.path = new URL(event.path, event.rawUrl).pathname;
51
+ event.path = new URL(event.rawUrl).pathname;
52
52
  // Next expects to be able to parse the query from the URL
53
53
  const query = new URLSearchParams(event.queryStringParameters).toString();
54
54
  event.path = query ? `${event.path}?${query}` : event.path;
@@ -11,9 +11,9 @@ const tiny_glob_1 = __importDefault(require("tiny-glob"));
11
11
  const constants_1 = require("../constants");
12
12
  // Generate a file full of require.resolve() calls for all the pages in the
13
13
  // build. This is used by the nft bundler to find all the pages.
14
- const getPageResolver = async ({ netlifyConfig, target }) => {
14
+ const getPageResolver = async ({ publish, target }) => {
15
15
  const functionDir = path_1.posix.resolve(path_1.posix.join('.netlify', 'functions', constants_1.HANDLER_FUNCTION_NAME));
16
- const root = path_1.posix.join(netlifyConfig.build.publish, target === 'server' ? 'server' : 'serverless', 'pages');
16
+ const root = path_1.posix.resolve(slash_1.default(publish), target === 'server' ? 'server' : 'serverless', 'pages');
17
17
  const pages = await tiny_glob_1.default('**/*.js', {
18
18
  cwd: root,
19
19
  dot: true,
@@ -117,7 +117,7 @@ const augmentFsModule = ({ promises, staticManifest, pageRoot, getBase, }) => {
117
117
  }
118
118
  return readfileOrig(file, options);
119
119
  });
120
- promises.stat = (async (file, options) => {
120
+ promises.stat = ((file, options) => {
121
121
  // We only care about page files
122
122
  if (file.startsWith(pageRoot)) {
123
123
  // We only want the part after `pages/`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netlify/plugin-nextjs",
3
- "version": "4.0.0-rc.1",
3
+ "version": "4.0.0-rc.2",
4
4
  "description": "Run Next.js seamlessly on Netlify",
5
5
  "main": "lib/index.js",
6
6
  "files": [
@@ -10,7 +10,6 @@
10
10
  "scripts": {
11
11
  "build:demo": "next build demos/default",
12
12
  "cy:open": "cypress open --config-file cypress/config/all.json",
13
- "cy:run": "cypress run --config-file ../../cypress/config/ci.json",
14
13
  "dev:demo": "next dev demos/default",
15
14
  "format": "run-s format:check-fix:*",
16
15
  "format:ci": "run-s format:check:*",
@@ -34,8 +33,8 @@
34
33
  "watch": "tsc --watch"
35
34
  },
36
35
  "config": {
37
- "eslint": "--cache --format=codeframe --max-warnings=0 \"{src,scripts,tests,.github}/**/*.{js,md,html}\" \"*.{js,md,html}\" \".*.{js,md,html}\"",
38
- "prettier": "--loglevel=warn \"{src,scripts,tests,.github}/**/*.{js,md,yml,json,html}\" \"*.{js,yml,json,html}\" \".*.{js,yml,json,html}\" \"!package-lock.json\""
36
+ "eslint": "--cache --format=codeframe --max-warnings=0 \"{src,scripts,tests,.github}/**/*.{ts,js,md,html}\" \"*.{ts,js,md,html}\" \".*.{ts,js,md,html}\"",
37
+ "prettier": "--loglevel=warn \"{src,scripts,tests,.github}/**/*.{ts,js,md,yml,json,html}\" \"*.{ts,js,yml,json,html}\" \".*.{ts,js,yml,json,html}\" \"!package-lock.json\""
39
38
  },
40
39
  "repository": {
41
40
  "type": "git",
@@ -75,7 +74,7 @@
75
74
  "@babel/core": "^7.15.8",
76
75
  "@babel/preset-env": "^7.15.8",
77
76
  "@babel/preset-typescript": "^7.16.0",
78
- "@netlify/build": "^20.1.0",
77
+ "@netlify/build": "^20.2.0",
79
78
  "@netlify/eslint-config-node": "^4.0.0",
80
79
  "@testing-library/cypress": "^8.0.1",
81
80
  "@types/fs-extra": "^9.0.13",