@opennextjs/aws 3.1.5 → 3.2.0

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.
Files changed (144) hide show
  1. package/README.md +27 -22
  2. package/dist/adapters/binary.js +2 -0
  3. package/dist/adapters/cache.d.ts +3 -2
  4. package/dist/adapters/cache.js +2 -2
  5. package/dist/adapters/config/util.d.ts +2 -2
  6. package/dist/adapters/image-optimization-adapter.d.ts +2 -2
  7. package/dist/adapters/middleware.js +5 -52
  8. package/dist/adapters/plugins/image-optimization/image-optimization.d.ts +7 -4
  9. package/dist/adapters/plugins/image-optimization/image-optimization.js +2 -3
  10. package/dist/adapters/plugins/image-optimization/image-optimization.replacement.d.ts +3 -0
  11. package/dist/adapters/plugins/image-optimization/image-optimization.replacement.js +4 -7
  12. package/dist/adapters/warmer-function.js +2 -67
  13. package/dist/build/buildNextApp.d.ts +3 -0
  14. package/dist/build/buildNextApp.js +19 -0
  15. package/dist/build/bundleNextServer.js +2 -2
  16. package/dist/build/compileCache.d.ts +9 -0
  17. package/dist/build/compileCache.js +30 -0
  18. package/dist/build/compileConfig.d.ts +17 -3
  19. package/dist/build/compileConfig.js +56 -34
  20. package/dist/build/compileTagCacheProvider.d.ts +2 -0
  21. package/dist/build/compileTagCacheProvider.js +26 -0
  22. package/dist/build/createAssets.d.ts +11 -0
  23. package/dist/build/createAssets.js +161 -0
  24. package/dist/build/createImageOptimizationBundle.d.ts +2 -0
  25. package/dist/build/createImageOptimizationBundle.js +79 -0
  26. package/dist/build/createMiddleware.d.ts +10 -0
  27. package/dist/build/createMiddleware.js +55 -0
  28. package/dist/build/createRevalidationBundle.d.ts +2 -0
  29. package/dist/build/createRevalidationBundle.js +35 -0
  30. package/dist/build/createServerBundle.d.ts +2 -2
  31. package/dist/build/createServerBundle.js +27 -26
  32. package/dist/build/createWarmerBundle.d.ts +2 -0
  33. package/dist/build/createWarmerBundle.js +44 -0
  34. package/dist/build/edge/createEdgeBundle.d.ts +3 -3
  35. package/dist/build/edge/createEdgeBundle.js +3 -5
  36. package/dist/build/helper.d.ts +22 -5
  37. package/dist/build/helper.js +42 -11
  38. package/dist/build/installDeps.d.ts +2 -0
  39. package/dist/build/installDeps.js +36 -0
  40. package/dist/build/utils.d.ts +5 -0
  41. package/dist/build/utils.js +22 -0
  42. package/dist/build/validateConfig.d.ts +1 -1
  43. package/dist/build.d.ts +0 -4
  44. package/dist/build.js +26 -486
  45. package/dist/core/createMainHandler.d.ts +3 -3
  46. package/dist/core/requestHandler.d.ts +2 -2
  47. package/dist/core/requestHandler.js +1 -1
  48. package/dist/core/resolve.d.ts +13 -4
  49. package/dist/core/resolve.js +30 -5
  50. package/dist/core/routing/cacheInterceptor.d.ts +1 -1
  51. package/dist/core/routing/i18n/index.d.ts +1 -1
  52. package/dist/core/routing/i18n/index.js +3 -0
  53. package/dist/core/routing/matcher.d.ts +2 -1
  54. package/dist/core/routing/matcher.js +1 -1
  55. package/dist/core/routing/middleware.d.ts +6 -2
  56. package/dist/core/routing/middleware.js +7 -4
  57. package/dist/core/routing/util.d.ts +3 -2
  58. package/dist/core/routing/util.js +9 -3
  59. package/dist/core/routingHandler.d.ts +1 -1
  60. package/dist/helpers/withCloudflare.d.ts +1 -1
  61. package/dist/helpers/withSST.d.ts +1 -1
  62. package/dist/http/openNextResponse.d.ts +10 -2
  63. package/dist/http/openNextResponse.js +27 -0
  64. package/dist/http/request.d.ts +3 -2
  65. package/dist/http/util.d.ts +1 -1
  66. package/dist/{converters → overrides/converters}/aws-apigw-v1.d.ts +1 -1
  67. package/dist/{converters → overrides/converters}/aws-apigw-v1.js +2 -2
  68. package/dist/{converters → overrides/converters}/aws-apigw-v2.d.ts +1 -1
  69. package/dist/{converters → overrides/converters}/aws-apigw-v2.js +5 -4
  70. package/dist/{converters → overrides/converters}/aws-cloudfront.d.ts +1 -1
  71. package/dist/{converters → overrides/converters}/aws-cloudfront.js +6 -7
  72. package/dist/{converters → overrides/converters}/dummy.d.ts +1 -1
  73. package/dist/overrides/converters/edge.d.ts +6 -0
  74. package/dist/{converters → overrides/converters}/edge.js +1 -1
  75. package/dist/{converters → overrides/converters}/node.d.ts +1 -1
  76. package/dist/{converters → overrides/converters}/node.js +1 -1
  77. package/dist/overrides/converters/sqs-revalidate.d.ts +4 -0
  78. package/dist/overrides/imageLoader/dummy.d.ts +3 -0
  79. package/dist/overrides/imageLoader/dummy.js +8 -0
  80. package/dist/overrides/imageLoader/host.d.ts +1 -1
  81. package/dist/overrides/imageLoader/s3.d.ts +1 -1
  82. package/dist/overrides/incrementalCache/dummy.d.ts +3 -0
  83. package/dist/overrides/incrementalCache/dummy.js +13 -0
  84. package/dist/{cache/incremental → overrides/incrementalCache}/s3-lite.d.ts +1 -1
  85. package/dist/{cache/incremental → overrides/incrementalCache}/s3.d.ts +1 -1
  86. package/dist/{cache/incremental → overrides/incrementalCache}/types.d.ts +1 -1
  87. package/dist/overrides/originResolver/dummy.d.ts +3 -0
  88. package/dist/overrides/originResolver/dummy.js +7 -0
  89. package/dist/overrides/originResolver/pattern-env.d.ts +3 -0
  90. package/dist/overrides/originResolver/pattern-env.js +39 -0
  91. package/dist/overrides/queue/dummy.d.ts +3 -0
  92. package/dist/overrides/queue/dummy.js +7 -0
  93. package/dist/{queue → overrides/queue}/sqs-lite.d.ts +1 -1
  94. package/dist/{queue → overrides/queue}/sqs-lite.js +3 -3
  95. package/dist/{queue → overrides/queue}/sqs.d.ts +1 -1
  96. package/dist/{queue → overrides/queue}/sqs.js +1 -1
  97. package/dist/overrides/tagCache/dummy.d.ts +3 -0
  98. package/dist/overrides/tagCache/dummy.js +17 -0
  99. package/dist/{cache/tag → overrides/tagCache}/dynamodb-lite.d.ts +1 -1
  100. package/dist/{cache/tag → overrides/tagCache}/dynamodb-lite.js +1 -1
  101. package/dist/{cache/tag → overrides/tagCache}/dynamodb.d.ts +1 -1
  102. package/dist/{cache/tag → overrides/tagCache}/dynamodb.js +1 -1
  103. package/dist/overrides/warmer/aws-lambda.d.ts +3 -0
  104. package/dist/overrides/warmer/aws-lambda.js +59 -0
  105. package/dist/overrides/warmer/dummy.d.ts +3 -0
  106. package/dist/overrides/warmer/dummy.js +7 -0
  107. package/dist/overrides/wrappers/aws-lambda-streaming.d.ts +7 -0
  108. package/dist/{wrappers → overrides/wrappers}/aws-lambda-streaming.js +1 -1
  109. package/dist/overrides/wrappers/aws-lambda.d.ts +7 -0
  110. package/dist/{wrappers → overrides/wrappers}/cloudflare.d.ts +2 -2
  111. package/dist/overrides/wrappers/dummy.d.ts +7 -0
  112. package/dist/overrides/wrappers/dummy.js +6 -0
  113. package/dist/overrides/wrappers/node.d.ts +7 -0
  114. package/dist/{wrappers → overrides/wrappers}/node.js +1 -1
  115. package/dist/plugins/edge.d.ts +2 -2
  116. package/dist/plugins/replacement.d.ts +1 -1
  117. package/dist/plugins/resolve.d.ts +4 -2
  118. package/dist/plugins/resolve.js +32 -20
  119. package/dist/types/aws-lambda.d.ts +3 -2
  120. package/dist/{cache/next-types.d.ts → types/cache.d.ts} +1 -0
  121. package/dist/types/next-types.d.ts +3 -1
  122. package/dist/types/open-next.d.ts +39 -13
  123. package/package.json +3 -4
  124. package/dist/converters/edge.d.ts +0 -6
  125. package/dist/converters/sqs-revalidate.d.ts +0 -4
  126. package/dist/wrappers/aws-lambda-streaming.d.ts +0 -7
  127. package/dist/wrappers/aws-lambda.d.ts +0 -7
  128. package/dist/wrappers/node.d.ts +0 -7
  129. /package/dist/{converters → overrides/converters}/dummy.js +0 -0
  130. /package/dist/{converters → overrides/converters}/sqs-revalidate.js +0 -0
  131. /package/dist/{converters → overrides/converters}/utils.d.ts +0 -0
  132. /package/dist/{converters → overrides/converters}/utils.js +0 -0
  133. /package/dist/{cache/incremental → overrides/incrementalCache}/s3-lite.js +0 -0
  134. /package/dist/{cache/incremental → overrides/incrementalCache}/s3.js +0 -0
  135. /package/dist/{cache/incremental → overrides/incrementalCache}/types.js +0 -0
  136. /package/dist/{queue → overrides/queue}/types.d.ts +0 -0
  137. /package/dist/{cache/tag → overrides/queue}/types.js +0 -0
  138. /package/dist/{cache/tag → overrides/tagCache}/constants.d.ts +0 -0
  139. /package/dist/{cache/tag → overrides/tagCache}/constants.js +0 -0
  140. /package/dist/{cache/tag → overrides/tagCache}/types.d.ts +0 -0
  141. /package/dist/{queue → overrides/tagCache}/types.js +0 -0
  142. /package/dist/{wrappers → overrides/wrappers}/aws-lambda.js +0 -0
  143. /package/dist/{wrappers → overrides/wrappers}/cloudflare.js +0 -0
  144. /package/dist/{cache/next-types.js → types/cache.js} +0 -0
package/dist/build.js CHANGED
@@ -1,56 +1,48 @@
1
- import cp from "node:child_process";
2
- import fs, { readFileSync } from "node:fs";
3
- import { createRequire as topLevelCreateRequire } from "node:module";
4
- import os from "node:os";
5
- import path from "node:path";
6
1
  import url from "node:url";
7
- import { isBinaryContentType } from "./adapters/binary.js";
8
- import { compileOpenNextConfigEdge, compileOpenNextConfigNode, } from "./build/compileConfig.js";
2
+ import { buildNextjsApp, setStandaloneBuildMode, } from "./build/buildNextApp.js";
3
+ import { compileCache } from "./build/compileCache.js";
4
+ import { compileOpenNextConfig } from "./build/compileConfig.js";
5
+ import { compileTagCacheProvider } from "./build/compileTagCacheProvider.js";
6
+ import { createCacheAssets, createStaticAssets } from "./build/createAssets.js";
7
+ import { createImageOptimizationBundle } from "./build/createImageOptimizationBundle.js";
8
+ import { createMiddleware } from "./build/createMiddleware.js";
9
+ import { createRevalidationBundle } from "./build/createRevalidationBundle.js";
9
10
  import { createServerBundle } from "./build/createServerBundle.js";
10
- import { buildEdgeBundle } from "./build/edge/createEdgeBundle.js";
11
+ import { createWarmerBundle } from "./build/createWarmerBundle.js";
11
12
  import { generateOutput } from "./build/generateOutput.js";
12
- import { compareSemver, copyOpenNextConfig, esbuildAsync, esbuildSync, getBuildId, getHtmlPages, normalizeOptions, removeFiles, traverseFiles, } from "./build/helper.js";
13
- import { validateConfig } from "./build/validateConfig.js";
13
+ import * as buildHelper from "./build/helper.js";
14
+ import { printHeader, showWarningOnWindows } from "./build/utils.js";
14
15
  import logger from "./logger.js";
15
- import { openNextReplacementPlugin } from "./plugins/replacement.js";
16
- import { openNextResolvePlugin } from "./plugins/resolve.js";
17
- const require = topLevelCreateRequire(import.meta.url);
18
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
19
16
  export async function build(openNextConfigPath, nodeExternals) {
20
- showWindowsWarning();
21
- // Load open-next.config.ts
22
- const tempDir = initTempDir();
23
- let configPath = compileOpenNextConfigNode(tempDir, openNextConfigPath, nodeExternals);
24
- // On Windows, we need to use file:// protocol to load the config file using import()
25
- if (process.platform === "win32")
26
- configPath = `file://${configPath}`;
27
- const config = (await import(configPath)).default;
28
- if (!config || !config.default) {
29
- logger.error(`config.default cannot be empty, it should be at least {}, see more info here: https://open-next.js.org/config#configuration-file`);
30
- process.exit(1);
31
- }
32
- validateConfig(config);
33
- compileOpenNextConfigEdge(tempDir, config, openNextConfigPath);
17
+ showWarningOnWindows();
18
+ const baseDir = process.cwd();
19
+ const openNextDistDir = url.fileURLToPath(new URL(".", import.meta.url));
20
+ const { config, buildDir } = await compileOpenNextConfig(baseDir, openNextConfigPath, nodeExternals);
34
21
  // Initialize options
35
- const options = normalizeOptions(config);
22
+ const options = buildHelper.normalizeOptions(config, openNextDistDir, buildDir);
36
23
  logger.setLevel(options.debug ? "debug" : "info");
37
24
  // Pre-build validation
38
- checkRunningInsideNextjsApp(options);
39
- printNextjsVersion(options);
40
- printOpenNextVersion(options);
25
+ buildHelper.checkRunningInsideNextjsApp(options);
26
+ buildHelper.printNextjsVersion(options);
27
+ buildHelper.printOpenNextVersion(options);
41
28
  // Build Next.js app
42
29
  printHeader("Building Next.js app");
43
30
  setStandaloneBuildMode(options);
44
31
  buildNextjsApp(options);
45
32
  // Generate deployable bundle
46
33
  printHeader("Generating bundle");
47
- initOutputDir(tempDir, options);
34
+ buildHelper.initOutputDir(options);
48
35
  // Compile cache.ts
49
36
  compileCache(options);
50
37
  // Compile middleware
51
38
  await createMiddleware(options);
52
39
  createStaticAssets(options);
53
- await createCacheAssets(options);
40
+ if (config.dangerous?.disableIncrementalCache !== true) {
41
+ const { useTagCache } = createCacheAssets(options);
42
+ if (useTagCache) {
43
+ await compileTagCacheProvider(options);
44
+ }
45
+ }
54
46
  await createServerBundle(options);
55
47
  await createRevalidationBundle(options);
56
48
  await createImageOptimizationBundle(options);
@@ -58,455 +50,3 @@ export async function build(openNextConfigPath, nodeExternals) {
58
50
  await generateOutput(options);
59
51
  logger.info("OpenNext build complete.");
60
52
  }
61
- function showWindowsWarning() {
62
- if (os.platform() !== "win32")
63
- return;
64
- logger.warn("OpenNext is not fully compatible with Windows.");
65
- logger.warn("For optimal performance, it is recommended to use Windows Subsystem for Linux (WSL).");
66
- logger.warn("While OpenNext may function on Windows, it could encounter unpredictable failures during runtime.");
67
- }
68
- function initTempDir() {
69
- const dir = path.join(process.cwd(), ".open-next");
70
- const tempDir = path.join(dir, ".build");
71
- fs.rmSync(dir, { recursive: true, force: true });
72
- fs.mkdirSync(tempDir, { recursive: true });
73
- return tempDir;
74
- }
75
- function checkRunningInsideNextjsApp(options) {
76
- const { appPath } = options;
77
- const extension = ["js", "cjs", "mjs", "ts"].find((ext) => fs.existsSync(path.join(appPath, `next.config.${ext}`)));
78
- if (!extension) {
79
- logger.error("Error: next.config.js not found. Please make sure you are running this command inside a Next.js app.");
80
- process.exit(1);
81
- }
82
- }
83
- function setStandaloneBuildMode(options) {
84
- // Equivalent to setting `output: "standalone"` in next.config.js
85
- process.env.NEXT_PRIVATE_STANDALONE = "true";
86
- // Equivalent to setting `experimental.outputFileTracingRoot` in next.config.js
87
- process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT = options.monorepoRoot;
88
- }
89
- function buildNextjsApp(options) {
90
- const { config, packager } = options;
91
- const command = config.buildCommand ??
92
- (["bun", "npm"].includes(packager)
93
- ? `${packager} run build`
94
- : `${packager} build`);
95
- cp.execSync(command, {
96
- stdio: "inherit",
97
- cwd: path.dirname(options.appPackageJsonPath),
98
- });
99
- }
100
- function printHeader(header) {
101
- header = `OpenNext — ${header}`;
102
- logger.info([
103
- "",
104
- "┌" + "─".repeat(header.length + 2) + "┐",
105
- `│ ${header} │`,
106
- "└" + "─".repeat(header.length + 2) + "┘",
107
- "",
108
- ].join("\n"));
109
- }
110
- function printNextjsVersion(options) {
111
- logger.info(`Next.js version : ${options.nextVersion}`);
112
- }
113
- function printOpenNextVersion(options) {
114
- logger.info(`OpenNext v${options.openNextVersion}`);
115
- }
116
- function initOutputDir(srcTempDir, options) {
117
- // We need to get the build relative to the cwd to find the compiled config
118
- // This is needed for the case where the app is a single-version monorepo and the package.json is in the root of the monorepo
119
- // where the build is in the app directory, but the compiled config is in the root of the monorepo.
120
- const openNextConfig = readFileSync(path.join(srcTempDir, "open-next.config.mjs"), "utf8");
121
- let openNextConfigEdge = null;
122
- if (fs.existsSync(path.join(srcTempDir, "open-next.config.edge.mjs"))) {
123
- openNextConfigEdge = readFileSync(path.join(srcTempDir, "open-next.config.edge.mjs"), "utf8");
124
- }
125
- fs.rmSync(options.outputDir, { recursive: true, force: true });
126
- const destTempDir = options.tempDir;
127
- fs.mkdirSync(destTempDir, { recursive: true });
128
- fs.writeFileSync(path.join(destTempDir, "open-next.config.mjs"), openNextConfig);
129
- if (openNextConfigEdge) {
130
- fs.writeFileSync(path.join(destTempDir, "open-next.config.edge.mjs"), openNextConfigEdge);
131
- }
132
- }
133
- async function createWarmerBundle(options) {
134
- logger.info(`Bundling warmer function...`);
135
- const { config, outputDir } = options;
136
- // Create output folder
137
- const outputPath = path.join(outputDir, "warmer-function");
138
- fs.mkdirSync(outputPath, { recursive: true });
139
- // Copy open-next.config.mjs into the bundle
140
- copyOpenNextConfig(options.tempDir, outputPath);
141
- // Build Lambda code
142
- // note: bundle in OpenNext package b/c the adatper relys on the
143
- // "serverless-http" package which is not a dependency in user's
144
- // Next.js app.
145
- await esbuildAsync({
146
- entryPoints: [path.join(__dirname, "adapters", "warmer-function.js")],
147
- external: ["next"],
148
- outfile: path.join(outputPath, "index.mjs"),
149
- plugins: [
150
- openNextResolvePlugin({
151
- overrides: {
152
- converter: config.warmer?.override?.converter ?? "dummy",
153
- wrapper: config.warmer?.override?.wrapper,
154
- },
155
- fnName: "warmer",
156
- }),
157
- ],
158
- banner: {
159
- js: [
160
- "import { createRequire as topLevelCreateRequire } from 'module';",
161
- "const require = topLevelCreateRequire(import.meta.url);",
162
- "import bannerUrl from 'url';",
163
- "const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
164
- ].join(""),
165
- },
166
- }, options);
167
- }
168
- async function createRevalidationBundle(options) {
169
- logger.info(`Bundling revalidation function...`);
170
- const { appBuildOutputPath, config, outputDir } = options;
171
- // Create output folder
172
- const outputPath = path.join(outputDir, "revalidation-function");
173
- fs.mkdirSync(outputPath, { recursive: true });
174
- //Copy open-next.config.mjs into the bundle
175
- copyOpenNextConfig(options.tempDir, outputPath);
176
- // Build Lambda code
177
- await esbuildAsync({
178
- external: ["next", "styled-jsx", "react"],
179
- entryPoints: [path.join(__dirname, "adapters", "revalidate.js")],
180
- outfile: path.join(outputPath, "index.mjs"),
181
- plugins: [
182
- openNextResolvePlugin({
183
- fnName: "revalidate",
184
- overrides: {
185
- converter: config.revalidate?.override?.converter ?? "sqs-revalidate",
186
- wrapper: config.revalidate?.override?.wrapper,
187
- },
188
- }),
189
- ],
190
- }, options);
191
- // Copy over .next/prerender-manifest.json file
192
- fs.copyFileSync(path.join(appBuildOutputPath, ".next", "prerender-manifest.json"), path.join(outputPath, "prerender-manifest.json"));
193
- }
194
- async function createImageOptimizationBundle(options) {
195
- logger.info(`Bundling image optimization function...`);
196
- const { appPath, appBuildOutputPath, config, outputDir } = options;
197
- // Create output folder
198
- const outputPath = path.join(outputDir, "image-optimization-function");
199
- fs.mkdirSync(outputPath, { recursive: true });
200
- // Copy open-next.config.mjs into the bundle
201
- copyOpenNextConfig(options.tempDir, outputPath);
202
- const plugins = [
203
- openNextResolvePlugin({
204
- fnName: "imageOptimization",
205
- overrides: {
206
- converter: config.imageOptimization?.override?.converter,
207
- wrapper: config.imageOptimization?.override?.wrapper,
208
- imageLoader: config.imageOptimization?.loader,
209
- },
210
- }),
211
- ];
212
- if (compareSemver(options.nextVersion, "14.1.1") >= 0) {
213
- plugins.push(openNextReplacementPlugin({
214
- name: "opennext-14.1.1-image-optimization",
215
- target: /plugins(\/|\\)image-optimization(\/|\\)image-optimization\.js/g,
216
- replacements: [
217
- require.resolve("./adapters/plugins/image-optimization/image-optimization.replacement.js"),
218
- ],
219
- }));
220
- }
221
- // Build Lambda code (1st pass)
222
- // note: bundle in OpenNext package b/c the adapter relies on the
223
- // "@aws-sdk/client-s3" package which is not a dependency in user's
224
- // Next.js app.
225
- await esbuildAsync({
226
- entryPoints: [
227
- path.join(__dirname, "adapters", "image-optimization-adapter.js"),
228
- ],
229
- external: ["sharp", "next"],
230
- outfile: path.join(outputPath, "index.mjs"),
231
- plugins,
232
- }, options);
233
- // Build Lambda code (2nd pass)
234
- // note: bundle in user's Next.js app again b/c the adapter relies on the
235
- // "next" package. And the "next" package from user's app should
236
- // be used. We also set @opentelemetry/api as external because it seems to be
237
- // required by Next 15 even though it's not used.
238
- esbuildSync({
239
- entryPoints: [path.join(outputPath, "index.mjs")],
240
- external: ["sharp", "@opentelemetry/api"],
241
- allowOverwrite: true,
242
- outfile: path.join(outputPath, "index.mjs"),
243
- banner: {
244
- js: [
245
- "import { createRequire as topLevelCreateRequire } from 'module';",
246
- "const require = topLevelCreateRequire(import.meta.url);",
247
- "import bannerUrl from 'url';",
248
- "const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
249
- ].join("\n"),
250
- },
251
- }, options);
252
- // Copy over .next/required-server-files.json file and BUILD_ID
253
- fs.mkdirSync(path.join(outputPath, ".next"));
254
- fs.copyFileSync(path.join(appBuildOutputPath, ".next/required-server-files.json"), path.join(outputPath, ".next/required-server-files.json"));
255
- fs.copyFileSync(path.join(appBuildOutputPath, ".next/BUILD_ID"), path.join(outputPath, ".next/BUILD_ID"));
256
- // Sharp provides pre-build binaries for all platforms. https://github.com/lovell/sharp/blob/main/docs/install.md#cross-platform
257
- // Target should be same as used by Lambda, see https://github.com/sst/sst/blob/ca6f763fdfddd099ce2260202d0ce48c72e211ea/packages/sst/src/constructs/NextjsSite.ts#L114
258
- // For SHARP_IGNORE_GLOBAL_LIBVIPS see: https://github.com/lovell/sharp/blob/main/docs/install.md#aws-lambda
259
- const nodeOutputPath = path.resolve(outputPath);
260
- const sharpVersion = process.env.SHARP_VERSION ?? "0.32.6";
261
- const arch = config.imageOptimization?.arch ?? "arm64";
262
- const nodeVersion = config.imageOptimization?.nodeVersion ?? "18";
263
- //check if we are running in Windows environment then set env variables accordingly.
264
- try {
265
- cp.execSync(
266
- // We might want to change the arch args to cpu args, it seems to be the documented way
267
- `npm install --arch=${arch} --platform=linux --target=${nodeVersion} --libc=glibc --prefix="${nodeOutputPath}" sharp@${sharpVersion}`, {
268
- stdio: "pipe",
269
- cwd: appPath,
270
- env: {
271
- ...process.env,
272
- SHARP_IGNORE_GLOBAL_LIBVIPS: "1",
273
- },
274
- });
275
- }
276
- catch (e) {
277
- logger.error(e.stdout.toString());
278
- logger.error(e.stderr.toString());
279
- logger.error("Failed to install sharp.");
280
- }
281
- }
282
- function createStaticAssets(options) {
283
- logger.info(`Bundling static assets...`);
284
- const { appBuildOutputPath, appPublicPath, outputDir, appPath } = options;
285
- // Create output folder
286
- const outputPath = path.join(outputDir, "assets");
287
- fs.mkdirSync(outputPath, { recursive: true });
288
- // Next.js outputs assets into multiple files. Copy into the same directory.
289
- // Copy over:
290
- // - .next/BUILD_ID => _next/BUILD_ID
291
- // - .next/static => _next/static
292
- // - public/* => *
293
- // - app/favicon.ico or src/app/favicon.ico => favicon.ico
294
- fs.copyFileSync(path.join(appBuildOutputPath, ".next/BUILD_ID"), path.join(outputPath, "BUILD_ID"));
295
- fs.cpSync(path.join(appBuildOutputPath, ".next/static"), path.join(outputPath, "_next", "static"), { recursive: true });
296
- if (fs.existsSync(appPublicPath)) {
297
- fs.cpSync(appPublicPath, outputPath, { recursive: true });
298
- }
299
- const appSrcPath = fs.existsSync(path.join(appPath, "src"))
300
- ? "src/app"
301
- : "app";
302
- const faviconPath = path.join(appPath, appSrcPath, "favicon.ico");
303
- if (fs.existsSync(faviconPath)) {
304
- fs.copyFileSync(faviconPath, path.join(outputPath, "favicon.ico"));
305
- }
306
- }
307
- async function createCacheAssets(options) {
308
- const { config } = options;
309
- if (config.dangerous?.disableIncrementalCache)
310
- return;
311
- logger.info(`Bundling cache assets...`);
312
- const { appBuildOutputPath, outputDir } = options;
313
- const packagePath = path.relative(options.monorepoRoot, appBuildOutputPath);
314
- const buildId = getBuildId(appBuildOutputPath);
315
- // Copy pages to cache folder
316
- const dotNextPath = path.join(appBuildOutputPath, ".next/standalone", packagePath);
317
- const outputPath = path.join(outputDir, "cache", buildId);
318
- [".next/server/pages", ".next/server/app"]
319
- .map((dir) => path.join(dotNextPath, dir))
320
- .filter(fs.existsSync)
321
- .forEach((dir) => fs.cpSync(dir, outputPath, { recursive: true }));
322
- // Remove non-cache files
323
- const htmlPages = getHtmlPages(dotNextPath);
324
- removeFiles(outputPath, (file) => file.endsWith(".js") ||
325
- file.endsWith(".js.nft.json") ||
326
- (file.endsWith(".html") && htmlPages.has(file)));
327
- //merge cache files into a single file
328
- const cacheFilesPath = {};
329
- traverseFiles(outputPath, () => true, (filepath) => {
330
- const ext = path.extname(filepath);
331
- let newFilePath = ext !== "" ? filepath.replace(ext, ".cache") : `${filepath}.cache`;
332
- // Handle prefetch cache files for partial prerendering
333
- if (newFilePath.endsWith(".prefetch.cache")) {
334
- newFilePath = newFilePath.replace(".prefetch.cache", ".cache");
335
- }
336
- switch (ext) {
337
- case ".meta":
338
- case ".html":
339
- case ".json":
340
- case ".body":
341
- case ".rsc":
342
- cacheFilesPath[newFilePath] = {
343
- [ext.slice(1)]: filepath,
344
- ...cacheFilesPath[newFilePath],
345
- };
346
- break;
347
- case ".map":
348
- break;
349
- default:
350
- logger.warn(`Unknown file extension: ${ext}`);
351
- break;
352
- }
353
- });
354
- // Generate cache file
355
- Object.entries(cacheFilesPath).forEach(([cacheFilePath, files]) => {
356
- const cacheFileMeta = files.meta
357
- ? JSON.parse(fs.readFileSync(files.meta, "utf8"))
358
- : undefined;
359
- const cacheFileContent = {
360
- type: files.body ? "route" : files.json ? "page" : "app",
361
- meta: cacheFileMeta,
362
- html: files.html ? fs.readFileSync(files.html, "utf8") : undefined,
363
- json: files.json
364
- ? JSON.parse(fs.readFileSync(files.json, "utf8"))
365
- : undefined,
366
- rsc: files.rsc ? fs.readFileSync(files.rsc, "utf8") : undefined,
367
- body: files.body
368
- ? fs
369
- .readFileSync(files.body)
370
- .toString(isBinaryContentType(cacheFileMeta.headers["content-type"])
371
- ? "base64"
372
- : "utf8")
373
- : undefined,
374
- };
375
- fs.writeFileSync(cacheFilePath, JSON.stringify(cacheFileContent));
376
- });
377
- if (!config.dangerous?.disableTagCache) {
378
- // Generate dynamodb data
379
- // We need to traverse the cache to find every .meta file
380
- const metaFiles = [];
381
- // Compute dynamodb cache data
382
- // Traverse files inside cache to find all meta files and cache tags associated with them
383
- traverseFiles(outputPath, (file) => file.endsWith(".meta"), (filePath) => {
384
- const fileContent = fs.readFileSync(filePath, "utf8");
385
- const fileData = JSON.parse(fileContent);
386
- if (fileData.headers?.["x-next-cache-tags"]) {
387
- fileData.headers["x-next-cache-tags"]
388
- .split(",")
389
- .forEach((tag) => {
390
- // TODO: We should split the tag using getDerivedTags from next.js or maybe use an in house implementation
391
- metaFiles.push({
392
- tag: { S: path.posix.join(buildId, tag.trim()) },
393
- path: {
394
- S: path.posix.join(buildId, path.relative(outputPath, filePath).replace(".meta", "")),
395
- },
396
- // We don't care about the revalidation time here, we just need to make sure it's there
397
- revalidatedAt: { N: "1" },
398
- });
399
- });
400
- }
401
- });
402
- // Copy fetch-cache to cache folder
403
- const fetchCachePath = path.join(appBuildOutputPath, ".next/cache/fetch-cache");
404
- if (fs.existsSync(fetchCachePath)) {
405
- const fetchOutputPath = path.join(outputDir, "cache", "__fetch", buildId);
406
- fs.mkdirSync(fetchOutputPath, { recursive: true });
407
- fs.cpSync(fetchCachePath, fetchOutputPath, { recursive: true });
408
- traverseFiles(fetchCachePath, () => true, (filepath) => {
409
- const fileContent = fs.readFileSync(filepath, "utf8");
410
- const fileData = JSON.parse(fileContent);
411
- fileData?.tags?.forEach((tag) => {
412
- metaFiles.push({
413
- tag: { S: path.posix.join(buildId, tag) },
414
- path: {
415
- S: path.posix.join(buildId, path.relative(fetchCachePath, filepath)),
416
- },
417
- revalidatedAt: { N: "1" },
418
- });
419
- });
420
- });
421
- }
422
- if (metaFiles.length > 0) {
423
- const providerPath = path.join(outputDir, "dynamodb-provider");
424
- await esbuildAsync({
425
- external: ["@aws-sdk/client-dynamodb"],
426
- entryPoints: [path.join(__dirname, "adapters", "dynamo-provider.js")],
427
- outfile: path.join(providerPath, "index.mjs"),
428
- target: ["node18"],
429
- plugins: [
430
- openNextResolvePlugin({
431
- fnName: "initializationFunction",
432
- overrides: {
433
- converter: config.initializationFunction?.override?.converter ?? "dummy",
434
- wrapper: config.initializationFunction?.override?.wrapper,
435
- },
436
- }),
437
- ],
438
- }, options);
439
- //Copy open-next.config.mjs into the bundle
440
- copyOpenNextConfig(options.tempDir, providerPath);
441
- // TODO: check if metafiles doesn't contain duplicates
442
- fs.writeFileSync(path.join(providerPath, "dynamodb-cache.json"), JSON.stringify(metaFiles));
443
- }
444
- }
445
- // We need to remove files later because we need the metafiles for dynamodb tags cache
446
- removeFiles(outputPath, (file) => !file.endsWith(".cache"));
447
- }
448
- /***************************/
449
- /* Server Helper Functions */
450
- /***************************/
451
- export function compileCache(options, format = "cjs") {
452
- const { config } = options;
453
- const ext = format === "cjs" ? "cjs" : "mjs";
454
- const outfile = path.join(options.outputDir, ".build", `cache.${ext}`);
455
- const isAfter15 = compareSemver(options.nextVersion, "15.0.0") >= 0;
456
- esbuildSync({
457
- external: ["next", "styled-jsx", "react", "@aws-sdk/*"],
458
- entryPoints: [path.join(__dirname, "adapters", "cache.js")],
459
- outfile,
460
- target: ["node18"],
461
- format,
462
- banner: {
463
- js: [
464
- `globalThis.disableIncrementalCache = ${config.dangerous?.disableIncrementalCache ?? false};`,
465
- `globalThis.disableDynamoDBCache = ${config.dangerous?.disableTagCache ?? false};`,
466
- `globalThis.isNextAfter15 = ${isAfter15};`,
467
- ].join(""),
468
- },
469
- }, options);
470
- return outfile;
471
- }
472
- async function createMiddleware(options) {
473
- console.info(`Bundling middleware function...`);
474
- const { appBuildOutputPath, config, outputDir } = options;
475
- // Get middleware manifest
476
- const middlewareManifest = JSON.parse(readFileSync(path.join(appBuildOutputPath, ".next/server/middleware-manifest.json"), "utf8"));
477
- const entry = middlewareManifest.middleware["/"];
478
- if (!entry) {
479
- return;
480
- }
481
- // Create output folder
482
- let outputPath = path.join(outputDir, "server-function");
483
- const commonMiddlewareOptions = {
484
- middlewareInfo: entry,
485
- options,
486
- appBuildOutputPath,
487
- };
488
- if (config.middleware?.external) {
489
- outputPath = path.join(outputDir, "middleware");
490
- fs.mkdirSync(outputPath, { recursive: true });
491
- // Copy open-next.config.mjs
492
- copyOpenNextConfig(options.tempDir, outputPath, config.middleware.override?.wrapper === "cloudflare");
493
- // Bundle middleware
494
- await buildEdgeBundle({
495
- entrypoint: path.join(__dirname, "adapters", "middleware.js"),
496
- outfile: path.join(outputPath, "handler.mjs"),
497
- ...commonMiddlewareOptions,
498
- overrides: config.middleware?.override,
499
- defaultConverter: "aws-cloudfront",
500
- includeCache: config.dangerous?.enableCacheInterception,
501
- additionalExternals: config.edgeExternals,
502
- });
503
- }
504
- else {
505
- await buildEdgeBundle({
506
- entrypoint: path.join(__dirname, "core", "edgeFunctionHandler.js"),
507
- outfile: path.join(outputDir, ".build", "middleware.mjs"),
508
- ...commonMiddlewareOptions,
509
- onlyBuildOnce: true,
510
- });
511
- }
512
- }
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
2
  import type { AsyncLocalStorage } from "node:async_hooks";
3
- import { DetachedPromiseRunner } from "../utils/promise";
4
- import type { IncrementalCache } from "../cache/incremental/types";
5
- import type { Queue } from "../queue/types";
3
+ import type { DetachedPromiseRunner } from "../utils/promise";
4
+ import type { IncrementalCache } from "../overrides/incrementalCache/types";
5
+ import type { Queue } from "../overrides/queue/types";
6
6
  declare global {
7
7
  var queue: Queue;
8
8
  var incrementalCache: IncrementalCache;
@@ -1,3 +1,3 @@
1
- import { StreamCreator } from "../http/index.js";
2
- import { InternalEvent, InternalResult } from "../types/open-next";
1
+ import type { StreamCreator } from "../http/index.js";
2
+ import type { InternalEvent, InternalResult } from "../types/open-next";
3
3
  export declare function openNextHandler(internalEvent: InternalEvent, responseStreaming?: StreamCreator): Promise<InternalResult>;
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { IncomingMessage, } from "../http/index.js";
2
+ import { IncomingMessage } from "../http/index.js";
3
3
  import { DetachedPromiseRunner } from "../utils/promise";
4
4
  import { debug, error, warn } from "../adapters/logger";
5
5
  import { patchAsyncStorage } from "./patchAsyncStorage";
@@ -1,5 +1,5 @@
1
- import { BaseEventOrResult, Converter, DefaultOverrideOptions, ImageLoader, InternalEvent, InternalResult, LazyLoadedOverride, OverrideOptions, Wrapper } from "../types/open-next.js";
2
- import { TagCache } from "../cache/tag/types.js";
1
+ import type { BaseEventOrResult, Converter, DefaultOverrideOptions, ImageLoader, InternalEvent, InternalResult, LazyLoadedOverride, OriginResolver, OverrideOptions, Warmer, Wrapper } from "../types/open-next.js";
2
+ import type { TagCache } from "../overrides/tagCache/types.js";
3
3
  export declare function resolveConverter<E extends BaseEventOrResult = InternalEvent, R extends BaseEventOrResult = InternalResult>(converter: DefaultOverrideOptions<E, R>["converter"]): Promise<Converter<E, R>>;
4
4
  export declare function resolveWrapper<E extends BaseEventOrResult = InternalEvent, R extends BaseEventOrResult = InternalResult>(wrapper: DefaultOverrideOptions<E, R>["wrapper"]): Promise<Wrapper<E, R>>;
5
5
  /**
@@ -15,17 +15,26 @@ export declare function resolveTagCache(tagCache: OverrideOptions["tagCache"]):
15
15
  * @returns
16
16
  * @__PURE__
17
17
  */
18
- export declare function resolveQueue(queue: OverrideOptions["queue"]): Promise<import("../queue/types.js").Queue>;
18
+ export declare function resolveQueue(queue: OverrideOptions["queue"]): Promise<import("../overrides/queue/types.js").Queue>;
19
19
  /**
20
20
  *
21
21
  * @param incrementalCache
22
22
  * @returns
23
23
  * @__PURE__
24
24
  */
25
- export declare function resolveIncrementalCache(incrementalCache: OverrideOptions["incrementalCache"]): Promise<import("../cache/incremental/types.js").IncrementalCache>;
25
+ export declare function resolveIncrementalCache(incrementalCache: OverrideOptions["incrementalCache"]): Promise<import("../overrides/incrementalCache/types.js").IncrementalCache>;
26
26
  /**
27
27
  * @param imageLoader
28
28
  * @returns
29
29
  * @__PURE__
30
30
  */
31
31
  export declare function resolveImageLoader(imageLoader: LazyLoadedOverride<ImageLoader> | string): Promise<ImageLoader>;
32
+ /**
33
+ * @returns
34
+ * @__PURE__
35
+ */
36
+ export declare function resolveOriginResolver(originResolver?: LazyLoadedOverride<OriginResolver> | string): Promise<OriginResolver>;
37
+ /**
38
+ * @__PURE__
39
+ */
40
+ export declare function resolveWarmerInvoke(warmer?: LazyLoadedOverride<Warmer> | "aws-lambda"): Promise<Warmer>;