@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
@@ -0,0 +1,11 @@
1
+ import * as buildHelper from "./helper.js";
2
+ export declare function createStaticAssets(options: buildHelper.BuildOptions): void;
3
+ /**
4
+ * Create the cache assets.
5
+ *
6
+ * @param options Build options.
7
+ * @returns Whether tag cache is used.
8
+ */
9
+ export declare function createCacheAssets(options: buildHelper.BuildOptions): {
10
+ useTagCache: boolean;
11
+ };
@@ -0,0 +1,161 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isBinaryContentType } from "../adapters/binary.js";
4
+ import logger from "../logger.js";
5
+ import * as buildHelper from "./helper.js";
6
+ export function createStaticAssets(options) {
7
+ logger.info(`Bundling static assets...`);
8
+ const { appBuildOutputPath, appPublicPath, outputDir, appPath } = options;
9
+ // Create output folder
10
+ const outputPath = path.join(outputDir, "assets");
11
+ fs.mkdirSync(outputPath, { recursive: true });
12
+ // Next.js outputs assets into multiple files. Copy into the same directory.
13
+ // Copy over:
14
+ // - .next/BUILD_ID => _next/BUILD_ID
15
+ // - .next/static => _next/static
16
+ // - public/* => *
17
+ // - app/favicon.ico or src/app/favicon.ico => favicon.ico
18
+ fs.copyFileSync(path.join(appBuildOutputPath, ".next/BUILD_ID"), path.join(outputPath, "BUILD_ID"));
19
+ fs.cpSync(path.join(appBuildOutputPath, ".next/static"), path.join(outputPath, "_next", "static"), { recursive: true });
20
+ if (fs.existsSync(appPublicPath)) {
21
+ fs.cpSync(appPublicPath, outputPath, { recursive: true });
22
+ }
23
+ const appSrcPath = fs.existsSync(path.join(appPath, "src"))
24
+ ? "src/app"
25
+ : "app";
26
+ const faviconPath = path.join(appPath, appSrcPath, "favicon.ico");
27
+ if (fs.existsSync(faviconPath)) {
28
+ fs.copyFileSync(faviconPath, path.join(outputPath, "favicon.ico"));
29
+ }
30
+ }
31
+ /**
32
+ * Create the cache assets.
33
+ *
34
+ * @param options Build options.
35
+ * @returns Whether tag cache is used.
36
+ */
37
+ export function createCacheAssets(options) {
38
+ logger.info(`Bundling cache assets...`);
39
+ const { appBuildOutputPath, outputDir } = options;
40
+ const packagePath = path.relative(options.monorepoRoot, appBuildOutputPath);
41
+ const buildId = buildHelper.getBuildId(appBuildOutputPath);
42
+ let useTagCache = false;
43
+ // Copy pages to cache folder
44
+ const dotNextPath = path.join(appBuildOutputPath, ".next/standalone", packagePath);
45
+ const outputPath = path.join(outputDir, "cache", buildId);
46
+ [".next/server/pages", ".next/server/app"]
47
+ .map((dir) => path.join(dotNextPath, dir))
48
+ .filter(fs.existsSync)
49
+ .forEach((dir) => fs.cpSync(dir, outputPath, { recursive: true }));
50
+ // Remove non-cache files
51
+ const htmlPages = buildHelper.getHtmlPages(dotNextPath);
52
+ buildHelper.removeFiles(outputPath, (file) => file.endsWith(".js") ||
53
+ file.endsWith(".js.nft.json") ||
54
+ (file.endsWith(".html") && htmlPages.has(file)));
55
+ // Merge cache files into a single file
56
+ const cacheFilesPath = {};
57
+ buildHelper.traverseFiles(outputPath, () => true, (filepath) => {
58
+ const ext = path.extname(filepath);
59
+ switch (ext) {
60
+ case ".meta":
61
+ case ".html":
62
+ case ".json":
63
+ case ".body":
64
+ case ".rsc":
65
+ const newFilePath = filepath
66
+ .substring(0, filepath.length - ext.length)
67
+ .replace(/\.prefetch$/, "") + ".cache";
68
+ cacheFilesPath[newFilePath] = {
69
+ [ext.slice(1)]: filepath,
70
+ ...cacheFilesPath[newFilePath],
71
+ };
72
+ break;
73
+ case ".map":
74
+ break;
75
+ default:
76
+ logger.warn(`Unknown file extension: ${ext}`);
77
+ break;
78
+ }
79
+ });
80
+ // Generate cache file
81
+ Object.entries(cacheFilesPath).forEach(([cacheFilePath, files]) => {
82
+ const cacheFileMeta = files.meta
83
+ ? JSON.parse(fs.readFileSync(files.meta, "utf8"))
84
+ : undefined;
85
+ const cacheFileContent = {
86
+ type: files.body ? "route" : files.json ? "page" : "app",
87
+ meta: cacheFileMeta,
88
+ html: files.html ? fs.readFileSync(files.html, "utf8") : undefined,
89
+ json: files.json
90
+ ? JSON.parse(fs.readFileSync(files.json, "utf8"))
91
+ : undefined,
92
+ rsc: files.rsc ? fs.readFileSync(files.rsc, "utf8") : undefined,
93
+ body: files.body
94
+ ? fs
95
+ .readFileSync(files.body)
96
+ .toString(isBinaryContentType(cacheFileMeta.headers["content-type"])
97
+ ? "base64"
98
+ : "utf8")
99
+ : undefined,
100
+ };
101
+ fs.writeFileSync(cacheFilePath, JSON.stringify(cacheFileContent));
102
+ });
103
+ if (!options.config.dangerous?.disableTagCache) {
104
+ // Generate dynamodb data
105
+ // We need to traverse the cache to find every .meta file
106
+ const metaFiles = [];
107
+ // Compute dynamodb cache data
108
+ // Traverse files inside cache to find all meta files and cache tags associated with them
109
+ buildHelper.traverseFiles(outputPath, (file) => file.endsWith(".meta"), (filePath) => {
110
+ const fileContent = fs.readFileSync(filePath, "utf8");
111
+ const fileData = JSON.parse(fileContent);
112
+ if (fileData.headers?.["x-next-cache-tags"]) {
113
+ fileData.headers["x-next-cache-tags"]
114
+ .split(",")
115
+ .forEach((tag) => {
116
+ // TODO: We should split the tag using getDerivedTags from next.js or maybe use an in house implementation
117
+ metaFiles.push({
118
+ tag: { S: path.posix.join(buildId, tag.trim()) },
119
+ path: {
120
+ S: path.posix.join(buildId, path.relative(outputPath, filePath).replace(".meta", "")),
121
+ },
122
+ // We don't care about the revalidation time here, we just need to make sure it's there
123
+ revalidatedAt: { N: "1" },
124
+ });
125
+ });
126
+ }
127
+ });
128
+ // Copy fetch-cache to cache folder
129
+ const fetchCachePath = path.join(appBuildOutputPath, ".next/cache/fetch-cache");
130
+ if (fs.existsSync(fetchCachePath)) {
131
+ const fetchOutputPath = path.join(outputDir, "cache", "__fetch", buildId);
132
+ fs.mkdirSync(fetchOutputPath, { recursive: true });
133
+ fs.cpSync(fetchCachePath, fetchOutputPath, { recursive: true });
134
+ buildHelper.traverseFiles(fetchCachePath, () => true, (filepath) => {
135
+ const fileContent = fs.readFileSync(filepath, "utf8");
136
+ const fileData = JSON.parse(fileContent);
137
+ fileData?.tags?.forEach((tag) => {
138
+ metaFiles.push({
139
+ tag: { S: path.posix.join(buildId, tag) },
140
+ path: {
141
+ S: path.posix.join(buildId, path.relative(fetchCachePath, filepath)),
142
+ },
143
+ revalidatedAt: { N: "1" },
144
+ });
145
+ });
146
+ });
147
+ }
148
+ if (metaFiles.length > 0) {
149
+ useTagCache = true;
150
+ const providerPath = path.join(outputDir, "dynamodb-provider");
151
+ //Copy open-next.config.mjs into the bundle
152
+ fs.mkdirSync(providerPath, { recursive: true });
153
+ buildHelper.copyOpenNextConfig(options.buildDir, providerPath);
154
+ // TODO: check if metafiles doesn't contain duplicates
155
+ fs.writeFileSync(path.join(providerPath, "dynamodb-cache.json"), JSON.stringify(metaFiles));
156
+ }
157
+ }
158
+ // We need to remove files later because we need the metafiles for dynamodb tags cache
159
+ buildHelper.removeFiles(outputPath, (file) => !file.endsWith(".cache"));
160
+ return { useTagCache };
161
+ }
@@ -0,0 +1,2 @@
1
+ import * as buildHelper from "./helper.js";
2
+ export declare function createImageOptimizationBundle(options: buildHelper.BuildOptions): Promise<void>;
@@ -0,0 +1,79 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import logger from "../logger.js";
5
+ import { openNextReplacementPlugin } from "../plugins/replacement.js";
6
+ import { openNextResolvePlugin } from "../plugins/resolve.js";
7
+ import * as buildHelper from "./helper.js";
8
+ import { installDependencies } from "./installDeps.js";
9
+ const require = createRequire(import.meta.url);
10
+ export async function createImageOptimizationBundle(options) {
11
+ logger.info(`Bundling image optimization function...`);
12
+ const { appBuildOutputPath, config, outputDir } = options;
13
+ // Create output folder
14
+ const outputPath = path.join(outputDir, "image-optimization-function");
15
+ fs.mkdirSync(outputPath, { recursive: true });
16
+ // Copy open-next.config.mjs into the bundle
17
+ buildHelper.copyOpenNextConfig(options.buildDir, outputPath);
18
+ const plugins = [
19
+ openNextResolvePlugin({
20
+ fnName: "imageOptimization",
21
+ overrides: {
22
+ converter: config.imageOptimization?.override?.converter,
23
+ wrapper: config.imageOptimization?.override?.wrapper,
24
+ imageLoader: config.imageOptimization?.loader,
25
+ },
26
+ }),
27
+ ];
28
+ if (buildHelper.compareSemver(options.nextVersion, "14.1.1") >= 0) {
29
+ plugins.push(openNextReplacementPlugin({
30
+ name: "opennext-14.1.1-image-optimization",
31
+ target: /plugins(\/|\\)image-optimization(\/|\\)image-optimization\.js/g,
32
+ replacements: [
33
+ require.resolve("../adapters/plugins/image-optimization/image-optimization.replacement.js"),
34
+ ],
35
+ }));
36
+ }
37
+ // Build Lambda code (1st pass)
38
+ // note: bundle in OpenNext package b/c the adapter relies on the
39
+ // "@aws-sdk/client-s3" package which is not a dependency in user's
40
+ // Next.js app.
41
+ await buildHelper.esbuildAsync({
42
+ entryPoints: [
43
+ path.join(options.openNextDistDir, "adapters", "image-optimization-adapter.js"),
44
+ ],
45
+ external: ["sharp", "next"],
46
+ outfile: path.join(outputPath, "index.mjs"),
47
+ plugins,
48
+ }, options);
49
+ // Build Lambda code (2nd pass)
50
+ // note: bundle in user's Next.js app again b/c the adapter relies on the
51
+ // "next" package. And the "next" package from user's app should
52
+ // be used. We also set @opentelemetry/api as external because it seems to be
53
+ // required by Next 15 even though it's not used.
54
+ buildHelper.esbuildSync({
55
+ entryPoints: [path.join(outputPath, "index.mjs")],
56
+ external: ["sharp", "@opentelemetry/api"],
57
+ allowOverwrite: true,
58
+ outfile: path.join(outputPath, "index.mjs"),
59
+ banner: {
60
+ js: [
61
+ "import { createRequire as topLevelCreateRequire } from 'module';",
62
+ "const require = topLevelCreateRequire(import.meta.url);",
63
+ "import bannerUrl from 'url';",
64
+ "const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
65
+ ].join("\n"),
66
+ },
67
+ }, options);
68
+ // Copy over .next/required-server-files.json file and BUILD_ID
69
+ fs.mkdirSync(path.join(outputPath, ".next"));
70
+ fs.copyFileSync(path.join(appBuildOutputPath, ".next/required-server-files.json"), path.join(outputPath, ".next/required-server-files.json"));
71
+ fs.copyFileSync(path.join(appBuildOutputPath, ".next/BUILD_ID"), path.join(outputPath, ".next/BUILD_ID"));
72
+ // Sharp provides pre-build binaries for all platforms. https://github.com/lovell/sharp/blob/main/docs/install.md#cross-platform
73
+ // Target should be same as used by Lambda, see https://github.com/sst/sst/blob/ca6f763fdfddd099ce2260202d0ce48c72e211ea/packages/sst/src/constructs/NextjsSite.ts#L114
74
+ // For SHARP_IGNORE_GLOBAL_LIBVIPS see: https://github.com/lovell/sharp/blob/main/docs/install.md#aws-lambda
75
+ const sharpVersion = process.env.SHARP_VERSION ?? "0.32.6";
76
+ installDependencies(outputPath, config.imageOptimization?.install ?? {
77
+ packages: [`sharp@${sharpVersion}`],
78
+ });
79
+ }
@@ -0,0 +1,10 @@
1
+ import * as buildHelper from "./helper.js";
2
+ /**
3
+ * Compiles the middleware bundle.
4
+ *
5
+ * @param options Build Options.
6
+ * @returns Whether the app uses a Middleware.
7
+ */
8
+ export declare function createMiddleware(options: buildHelper.BuildOptions): Promise<{
9
+ useMiddleware: boolean;
10
+ }>;
@@ -0,0 +1,55 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import logger from "../logger.js";
4
+ import { buildEdgeBundle } from "./edge/createEdgeBundle.js";
5
+ import * as buildHelper from "./helper.js";
6
+ import { installDependencies } from "./installDeps.js";
7
+ /**
8
+ * Compiles the middleware bundle.
9
+ *
10
+ * @param options Build Options.
11
+ * @returns Whether the app uses a Middleware.
12
+ */
13
+ export async function createMiddleware(options) {
14
+ logger.info(`Bundling middleware function...`);
15
+ const { appBuildOutputPath, config, outputDir } = options;
16
+ // Get middleware manifest
17
+ const middlewareManifest = JSON.parse(fs.readFileSync(path.join(appBuildOutputPath, ".next/server/middleware-manifest.json"), "utf8"));
18
+ const entry = middlewareManifest.middleware["/"];
19
+ if (!entry) {
20
+ return { useMiddleware: false };
21
+ }
22
+ // Create output folder
23
+ let outputPath = path.join(outputDir, "server-function");
24
+ const commonMiddlewareOptions = {
25
+ middlewareInfo: entry,
26
+ options,
27
+ appBuildOutputPath,
28
+ };
29
+ if (config.middleware?.external) {
30
+ outputPath = path.join(outputDir, "middleware");
31
+ fs.mkdirSync(outputPath, { recursive: true });
32
+ // Copy open-next.config.mjs
33
+ buildHelper.copyOpenNextConfig(options.buildDir, outputPath, config.middleware.override?.wrapper === "cloudflare");
34
+ // Bundle middleware
35
+ await buildEdgeBundle({
36
+ entrypoint: path.join(options.openNextDistDir, "adapters", "middleware.js"),
37
+ outfile: path.join(outputPath, "handler.mjs"),
38
+ ...commonMiddlewareOptions,
39
+ overrides: config.middleware?.override,
40
+ defaultConverter: "aws-cloudfront",
41
+ includeCache: config.dangerous?.enableCacheInterception,
42
+ additionalExternals: config.edgeExternals,
43
+ });
44
+ installDependencies(outputPath, config.middleware?.install);
45
+ }
46
+ else {
47
+ await buildEdgeBundle({
48
+ entrypoint: path.join(options.openNextDistDir, "core", "edgeFunctionHandler.js"),
49
+ outfile: path.join(options.buildDir, "middleware.mjs"),
50
+ ...commonMiddlewareOptions,
51
+ onlyBuildOnce: true,
52
+ });
53
+ }
54
+ return { useMiddleware: true };
55
+ }
@@ -0,0 +1,2 @@
1
+ import * as buildHelper from "./helper.js";
2
+ export declare function createRevalidationBundle(options: buildHelper.BuildOptions): Promise<void>;
@@ -0,0 +1,35 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import logger from "../logger.js";
4
+ import { openNextResolvePlugin } from "../plugins/resolve.js";
5
+ import * as buildHelper from "./helper.js";
6
+ import { installDependencies } from "./installDeps.js";
7
+ export async function createRevalidationBundle(options) {
8
+ logger.info(`Bundling revalidation function...`);
9
+ const { appBuildOutputPath, config, outputDir } = options;
10
+ // Create output folder
11
+ const outputPath = path.join(outputDir, "revalidation-function");
12
+ fs.mkdirSync(outputPath, { recursive: true });
13
+ //Copy open-next.config.mjs into the bundle
14
+ buildHelper.copyOpenNextConfig(options.buildDir, outputPath);
15
+ // Build Lambda code
16
+ await buildHelper.esbuildAsync({
17
+ external: ["next", "styled-jsx", "react"],
18
+ entryPoints: [
19
+ path.join(options.openNextDistDir, "adapters", "revalidate.js"),
20
+ ],
21
+ outfile: path.join(outputPath, "index.mjs"),
22
+ plugins: [
23
+ openNextResolvePlugin({
24
+ fnName: "revalidate",
25
+ overrides: {
26
+ converter: config.revalidate?.override?.converter ?? "sqs-revalidate",
27
+ wrapper: config.revalidate?.override?.wrapper,
28
+ },
29
+ }),
30
+ ],
31
+ }, options);
32
+ installDependencies(outputPath, config.revalidate?.install);
33
+ // Copy over .next/prerender-manifest.json file
34
+ fs.copyFileSync(path.join(appBuildOutputPath, ".next", "prerender-manifest.json"), path.join(outputPath, "prerender-manifest.json"));
35
+ }
@@ -1,2 +1,2 @@
1
- import type { BuildOptions } from "./helper.js";
2
- export declare function createServerBundle(options: BuildOptions): Promise<void>;
1
+ import * as buildHelper from "./helper.js";
2
+ export declare function createServerBundle(options: buildHelper.BuildOptions): Promise<void>;
@@ -1,19 +1,17 @@
1
- import { existsSync } from "node:fs";
2
- import { createRequire as topLevelCreateRequire } from "node:module";
3
- import fs from "fs";
4
- import path from "path";
5
- import url from "url";
6
- import { compileCache } from "../build.js";
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
7
4
  import logger from "../logger.js";
8
5
  import { minifyAll } from "../minimize-js.js";
9
6
  import { openNextReplacementPlugin } from "../plugins/replacement.js";
10
7
  import { openNextResolvePlugin } from "../plugins/resolve.js";
11
8
  import { bundleNextServer } from "./bundleNextServer.js";
9
+ import { compileCache } from "./compileCache.js";
12
10
  import { copyTracedFiles } from "./copyTracedFiles.js";
13
11
  import { generateEdgeBundle } from "./edge/createEdgeBundle.js";
14
- import { compareSemver, copyEnvFile, copyOpenNextConfig, esbuildAsync, traverseFiles, } from "./helper.js";
15
- const require = topLevelCreateRequire(import.meta.url);
16
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
12
+ import * as buildHelper from "./helper.js";
13
+ import { installDependencies } from "./installDeps.js";
14
+ const require = createRequire(import.meta.url);
17
15
  export async function createServerBundle(options) {
18
16
  const { config } = options;
19
17
  const foundRoutes = new Set();
@@ -44,9 +42,9 @@ export async function createServerBundle(options) {
44
42
  // Find remaining routes
45
43
  const serverPath = path.join(appBuildOutputPath, ".next", "standalone", packagePath, ".next", "server");
46
44
  // Find app dir routes
47
- if (existsSync(path.join(serverPath, "app"))) {
45
+ if (fs.existsSync(path.join(serverPath, "app"))) {
48
46
  const appPath = path.join(serverPath, "app");
49
- traverseFiles(appPath, (file) => {
47
+ buildHelper.traverseFiles(appPath, (file) => {
50
48
  if (file.endsWith("page.js") || file.endsWith("route.js")) {
51
49
  const route = `app/${file.replace(/\.js$/, "")}`;
52
50
  if (!foundRoutes.has(route)) {
@@ -57,9 +55,9 @@ export async function createServerBundle(options) {
57
55
  }, () => { });
58
56
  }
59
57
  // Find pages dir routes
60
- if (existsSync(path.join(serverPath, "pages"))) {
58
+ if (fs.existsSync(path.join(serverPath, "pages"))) {
61
59
  const pagePath = path.join(serverPath, "pages");
62
- traverseFiles(pagePath, (file) => {
60
+ buildHelper.traverseFiles(pagePath, (file) => {
63
61
  if (file.endsWith(".js")) {
64
62
  const route = `pages/${file.replace(/\.js$/, "")}`;
65
63
  if (!foundRoutes.has(route)) {
@@ -91,7 +89,7 @@ async function generateBundle(name, config, options, fnOptions) {
91
89
  const packagePath = path.relative(monorepoRoot, appBuildOutputPath);
92
90
  fs.mkdirSync(path.join(outputPath, packagePath), { recursive: true });
93
91
  const ext = fnOptions.runtime === "deno" ? "mjs" : "cjs";
94
- fs.copyFileSync(path.join(outputDir, ".build", `cache.${ext}`), path.join(outputPath, packagePath, "cache.cjs"));
92
+ fs.copyFileSync(path.join(options.buildDir, `cache.${ext}`), path.join(outputPath, packagePath, "cache.cjs"));
95
93
  if (fnOptions.runtime === "deno") {
96
94
  addDenoJson(outputPath, packagePath);
97
95
  }
@@ -100,26 +98,26 @@ async function generateBundle(name, config, options, fnOptions) {
100
98
  if (isBundled) {
101
99
  await bundleNextServer(path.join(outputPath, packagePath), appPath);
102
100
  }
103
- // // Copy middleware
101
+ // Copy middleware
104
102
  if (!config.middleware?.external &&
105
- existsSync(path.join(outputDir, ".build", "middleware.mjs"))) {
106
- fs.copyFileSync(path.join(outputDir, ".build", "middleware.mjs"), path.join(outputPath, packagePath, "middleware.mjs"));
103
+ fs.existsSync(path.join(options.buildDir, "middleware.mjs"))) {
104
+ fs.copyFileSync(path.join(options.buildDir, "middleware.mjs"), path.join(outputPath, packagePath, "middleware.mjs"));
107
105
  }
108
106
  // Copy open-next.config.mjs
109
- copyOpenNextConfig(path.join(outputDir, ".build"), path.join(outputPath, packagePath));
110
- //Copy env files
111
- copyEnvFile(appBuildOutputPath, packagePath, outputPath);
107
+ buildHelper.copyOpenNextConfig(options.buildDir, path.join(outputPath, packagePath));
108
+ // Copy env files
109
+ buildHelper.copyEnvFile(appBuildOutputPath, packagePath, outputPath);
112
110
  // Copy all necessary traced files
113
111
  await copyTracedFiles(appBuildOutputPath, packagePath, outputPath, fnOptions.routes ?? ["app/page.tsx"], isBundled);
114
112
  // Build Lambda code
115
113
  // note: bundle in OpenNext package b/c the adapter relies on the
116
114
  // "serverless-http" package which is not a dependency in user's
117
115
  // Next.js app.
118
- const disableNextPrebundledReact = compareSemver(options.nextVersion, "13.5.1") >= 0 ||
119
- compareSemver(options.nextVersion, "13.4.1") <= 0;
116
+ const disableNextPrebundledReact = buildHelper.compareSemver(options.nextVersion, "13.5.1") >= 0 ||
117
+ buildHelper.compareSemver(options.nextVersion, "13.4.1") <= 0;
120
118
  const overrides = fnOptions.override ?? {};
121
- const isBefore13413 = compareSemver(options.nextVersion, "13.4.13") <= 0;
122
- const isAfter141 = compareSemver(options.nextVersion, "14.0.4") >= 0;
119
+ const isBefore13413 = buildHelper.compareSemver(options.nextVersion, "13.4.13") <= 0;
120
+ const isAfter141 = buildHelper.compareSemver(options.nextVersion, "14.0.4") >= 0;
123
121
  const disableRouting = isBefore13413 || config.middleware?.external;
124
122
  const plugins = [
125
123
  openNextReplacementPlugin({
@@ -154,8 +152,10 @@ async function generateBundle(name, config, options, fnOptions) {
154
152
  .join(",")}] for Next version: ${options.nextVersion}`);
155
153
  }
156
154
  const outfileExt = fnOptions.runtime === "deno" ? "ts" : "mjs";
157
- await esbuildAsync({
158
- entryPoints: [path.join(__dirname, "../adapters", "server-adapter.js")],
155
+ await buildHelper.esbuildAsync({
156
+ entryPoints: [
157
+ path.join(options.openNextDistDir, "adapters", "server-adapter.js"),
158
+ ],
159
159
  external: ["next", "./middleware.mjs", "./next-server.runtime.prod.js"],
160
160
  outfile: path.join(outputPath, packagePath, `index.${outfileExt}`),
161
161
  banner: {
@@ -180,6 +180,7 @@ async function generateBundle(name, config, options, fnOptions) {
180
180
  if (isMonorepo) {
181
181
  addMonorepoEntrypoint(outputPath, packagePath);
182
182
  }
183
+ installDependencies(outputPath, fnOptions.install);
183
184
  if (fnOptions.minify) {
184
185
  await minifyServerBundle(outputPath);
185
186
  }
@@ -0,0 +1,2 @@
1
+ import * as buildHelper from "./helper.js";
2
+ export declare function createWarmerBundle(options: buildHelper.BuildOptions): Promise<void>;
@@ -0,0 +1,44 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import logger from "../logger.js";
4
+ import { openNextResolvePlugin } from "../plugins/resolve.js";
5
+ import * as buildHelper from "./helper.js";
6
+ import { installDependencies } from "./installDeps.js";
7
+ export async function createWarmerBundle(options) {
8
+ logger.info(`Bundling warmer function...`);
9
+ const { config, outputDir } = options;
10
+ // Create output folder
11
+ const outputPath = path.join(outputDir, "warmer-function");
12
+ fs.mkdirSync(outputPath, { recursive: true });
13
+ // Copy open-next.config.mjs into the bundle
14
+ buildHelper.copyOpenNextConfig(options.buildDir, outputPath);
15
+ // Build Lambda code
16
+ // note: bundle in OpenNext package b/c the adatper relys on the
17
+ // "serverless-http" package which is not a dependency in user's
18
+ // Next.js app.
19
+ await buildHelper.esbuildAsync({
20
+ entryPoints: [
21
+ path.join(options.openNextDistDir, "adapters", "warmer-function.js"),
22
+ ],
23
+ external: ["next"],
24
+ outfile: path.join(outputPath, "index.mjs"),
25
+ plugins: [
26
+ openNextResolvePlugin({
27
+ overrides: {
28
+ converter: config.warmer?.override?.converter ?? "dummy",
29
+ wrapper: config.warmer?.override?.wrapper,
30
+ },
31
+ fnName: "warmer",
32
+ }),
33
+ ],
34
+ banner: {
35
+ js: [
36
+ "import { createRequire as topLevelCreateRequire } from 'module';",
37
+ "const require = topLevelCreateRequire(import.meta.url);",
38
+ "import bannerUrl from 'url';",
39
+ "const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
40
+ ].join(""),
41
+ },
42
+ }, options);
43
+ installDependencies(outputPath, config.warmer?.install);
44
+ }
@@ -1,6 +1,6 @@
1
- import { MiddlewareInfo } from "../../types/next-types";
2
- import { IncludedConverter, OpenNextConfig, OverrideOptions, SplittedFunctionOptions } from "../../types/open-next";
3
- import { BuildOptions } from "../helper.js";
1
+ import type { MiddlewareInfo } from "../../types/next-types";
2
+ import type { IncludedConverter, OpenNextConfig, OverrideOptions, SplittedFunctionOptions } from "../../types/open-next";
3
+ import type { BuildOptions } from "../helper.js";
4
4
  interface BuildEdgeBundleOptions {
5
5
  appBuildOutputPath: string;
6
6
  middlewareInfo: MiddlewareInfo;
@@ -1,5 +1,4 @@
1
1
  import { mkdirSync } from "node:fs";
2
- import url from "node:url";
3
2
  import { build } from "esbuild";
4
3
  import fs from "fs";
5
4
  import path from "path";
@@ -8,7 +7,6 @@ import { openNextEdgePlugins } from "../../plugins/edge.js";
8
7
  import { openNextReplacementPlugin } from "../../plugins/replacement.js";
9
8
  import { openNextResolvePlugin } from "../../plugins/resolve.js";
10
9
  import { copyOpenNextConfig, esbuildAsync } from "../helper.js";
11
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
12
10
  export async function buildEdgeBundle({ appBuildOutputPath, middlewareInfo, entrypoint, outfile, options, defaultConverter, overrides, additionalInject, includeCache, additionalExternals, onlyBuildOnce, }) {
13
11
  const isInCloudfare = typeof overrides?.wrapper === "string"
14
12
  ? overrides.wrapper === "cloudflare"
@@ -53,7 +51,7 @@ export async function buildEdgeBundle({ appBuildOutputPath, middlewareInfo, entr
53
51
  openNextEdgePlugins({
54
52
  middlewareInfo,
55
53
  nextDir: path.join(appBuildOutputPath, ".next"),
56
- edgeFunctionHandlerPath: path.join(__dirname, "../../core", "edgeFunctionHandler.js"),
54
+ edgeFunctionHandlerPath: path.join(options.openNextDistDir, "core", "edgeFunctionHandler.js"),
57
55
  isInCloudfare,
58
56
  }),
59
57
  ],
@@ -116,7 +114,7 @@ export async function generateEdgeBundle(name, config, options, fnOptions) {
116
114
  const outputPath = path.join(outputDir, "server-functions", name);
117
115
  fs.mkdirSync(outputPath, { recursive: true });
118
116
  // Copy open-next.config.mjs
119
- copyOpenNextConfig(path.join(outputDir, ".build"), outputPath, true);
117
+ copyOpenNextConfig(options.buildDir, outputPath, true);
120
118
  // Load middleware manifest
121
119
  const middlewareManifest = JSON.parse(fs.readFileSync(path.join(appBuildOutputPath, ".next/server/middleware-manifest.json"), "utf8"));
122
120
  // Find functions
@@ -140,7 +138,7 @@ export async function generateEdgeBundle(name, config, options, fnOptions) {
140
138
  await buildEdgeBundle({
141
139
  appBuildOutputPath,
142
140
  middlewareInfo: fn,
143
- entrypoint: path.join(__dirname, "../../adapters", "edge-adapter.js"),
141
+ entrypoint: path.join(options.openNextDistDir, "adapters", "edge-adapter.js"),
144
142
  outfile: path.join(outputPath, "index.mjs"),
145
143
  options,
146
144
  overrides: fnOptions.override,
@@ -1,19 +1,21 @@
1
- import { BuildOptions as ESBuildOptions } from "esbuild";
2
- import { OpenNextConfig } from "../types/open-next.js";
1
+ import type { BuildOptions as ESBuildOptions } from "esbuild";
2
+ import type { OpenNextConfig } from "../types/open-next.js";
3
3
  export type BuildOptions = ReturnType<typeof normalizeOptions>;
4
- export declare function normalizeOptions(config: OpenNextConfig): {
4
+ export declare function normalizeOptions(config: OpenNextConfig, distDir: string, tempBuildDir: string): {
5
5
  appBuildOutputPath: string;
6
6
  appPackageJsonPath: string;
7
7
  appPath: string;
8
8
  appPublicPath: string;
9
+ buildDir: string;
9
10
  config: OpenNextConfig;
10
11
  debug: boolean;
11
12
  monorepoRoot: string;
12
13
  nextVersion: string;
13
14
  openNextVersion: string;
15
+ openNextDistDir: string;
14
16
  outputDir: string;
15
17
  packager: "npm" | "yarn" | "pnpm" | "bun";
16
- tempDir: string;
18
+ tempBuildDir: string;
17
19
  };
18
20
  export declare function esbuildSync(esbuildOptions: ESBuildOptions, options: BuildOptions): void;
19
21
  export declare function esbuildAsync(esbuildOptions: ESBuildOptions, options: BuildOptions): Promise<void>;
@@ -31,5 +33,20 @@ export declare function getBuildId(dotNextPath: string): string;
31
33
  export declare function getOpenNextVersion(): string;
32
34
  export declare function getNextVersion(appPath: string): string;
33
35
  export declare function compareSemver(v1: string, v2: string): number;
34
- export declare function copyOpenNextConfig(tempDir: string, outputPath: string, isEdge?: boolean): void;
36
+ export declare function copyOpenNextConfig(inputDir: string, outputDir: string, isEdge?: boolean): void;
35
37
  export declare function copyEnvFile(appPath: string, packagePath: string, outputPath: string): void;
38
+ /**
39
+ * Check we are in a Nextjs app by looking for the Nextjs config file.
40
+ */
41
+ export declare function checkRunningInsideNextjsApp(options: BuildOptions): void;
42
+ export declare function printNextjsVersion(options: BuildOptions): void;
43
+ export declare function printOpenNextVersion(options: BuildOptions): void;
44
+ /**
45
+ * Populates the build directory with the compiled configuration files.
46
+ *
47
+ * We need to get the build relative to the cwd to find the compiled config.
48
+ * This is needed for the case where the app is a single-version monorepo
49
+ * and the package.json is in the root of the monorepo where the build is in
50
+ * the app directory, but the compiled config is in the root of the monorepo.
51
+ */
52
+ export declare function initOutputDir(options: BuildOptions): void;