@opennextjs/cloudflare 1.6.5 → 1.7.1

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 (27) hide show
  1. package/dist/api/config.d.ts +3 -3
  2. package/dist/api/durable-objects/bucket-cache-purge.js +1 -1
  3. package/dist/api/durable-objects/queue.d.ts +1 -1
  4. package/dist/api/overrides/asset-resolver/index.d.ts +1 -1
  5. package/dist/api/overrides/cache-purge/index.d.ts +1 -1
  6. package/dist/api/overrides/cache-purge/index.js +3 -2
  7. package/dist/api/overrides/incremental-cache/regional-cache.d.ts +9 -0
  8. package/dist/api/overrides/incremental-cache/regional-cache.js +14 -1
  9. package/dist/api/overrides/internal.js +4 -3
  10. package/dist/api/overrides/queue/do-queue.d.ts +1 -1
  11. package/dist/api/overrides/queue/do-queue.js +1 -1
  12. package/dist/api/overrides/queue/memory-queue.js +2 -2
  13. package/dist/api/overrides/queue/queue-cache.d.ts +1 -1
  14. package/dist/api/overrides/tag-cache/do-sharded-tag-cache.js +2 -2
  15. package/dist/api/overrides/tag-cache/tag-cache-filter.d.ts +1 -1
  16. package/dist/cli/build/build.js +2 -1
  17. package/dist/cli/build/bundle-server.js +0 -2
  18. package/dist/cli/build/open-next/compile-skew-protection.d.ts +1 -1
  19. package/dist/cli/build/open-next/createServerBundle.js +1 -0
  20. package/dist/cli/build/patches/plugins/next-server.d.ts +20 -0
  21. package/dist/cli/build/patches/plugins/next-server.js +45 -0
  22. package/dist/cli/build/utils/needs-experimental-react.d.ts +1 -1
  23. package/dist/cli/commands/skew-protection.d.ts +1 -1
  24. package/dist/cli/templates/worker.js +1 -1
  25. package/package.json +2 -2
  26. package/dist/cli/build/patches/plugins/node-environment.d.ts +0 -9
  27. package/dist/cli/build/patches/plugins/node-environment.js +0 -26
@@ -1,6 +1,6 @@
1
- import type { BuildOptions } from "@opennextjs/aws/build/helper";
2
- import { BaseOverride, LazyLoadedOverride, OpenNextConfig as AwsOpenNextConfig, type RoutePreloadingBehavior } from "@opennextjs/aws/types/open-next";
3
- import type { CDNInvalidationHandler, IncrementalCache, Queue, TagCache } from "@opennextjs/aws/types/overrides";
1
+ import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
2
+ import { BaseOverride, LazyLoadedOverride, OpenNextConfig as AwsOpenNextConfig, type RoutePreloadingBehavior } from "@opennextjs/aws/types/open-next.js";
3
+ import type { CDNInvalidationHandler, IncrementalCache, Queue, TagCache } from "@opennextjs/aws/types/overrides.js";
4
4
  export type Override<T extends BaseOverride> = "dummy" | T | LazyLoadedOverride<T>;
5
5
  /**
6
6
  * Cloudflare specific overrides.
@@ -1,5 +1,5 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
- import { internalPurgeCacheByTags } from "../overrides/internal";
2
+ import { internalPurgeCacheByTags } from "../overrides/internal.js";
3
3
  const DEFAULT_BUFFER_TIME_IN_SECONDS = 5;
4
4
  // https://developers.cloudflare.com/cache/how-to/purge-cache/#hostname-tag-prefix-url-and-purge-everything-limits
5
5
  const MAX_NUMBER_OF_TAGS_PER_PURGE = 100;
@@ -1,4 +1,4 @@
1
- import type { QueueMessage } from "@opennextjs/aws/types/overrides";
1
+ import type { QueueMessage } from "@opennextjs/aws/types/overrides.js";
2
2
  import { DurableObject } from "cloudflare:workers";
3
3
  interface FailedState {
4
4
  msg: QueueMessage;
@@ -1,4 +1,4 @@
1
- import type { AssetResolver } from "@opennextjs/aws/types/overrides";
1
+ import type { AssetResolver } from "@opennextjs/aws/types/overrides.js";
2
2
  /**
3
3
  * Serves assets when `run_worker_first` is set to true.
4
4
  *
@@ -6,7 +6,7 @@ export declare const purgeCache: ({ type }: PurgeOptions) => {
6
6
  invalidatePaths(paths: {
7
7
  initialPath: string;
8
8
  rawPath: string;
9
- resolvedRoutes: import("@opennextjs/aws/types/open-next").ResolvedRoute[];
9
+ resolvedRoutes: import("@opennextjs/aws/types/open-next.js").ResolvedRoute[];
10
10
  }[]): Promise<void>;
11
11
  };
12
12
  export {};
@@ -1,4 +1,5 @@
1
- import { getCloudflareContext } from "../../cloudflare-context";
1
+ import { error } from "@opennextjs/aws/adapters/logger.js";
2
+ import { getCloudflareContext } from "../../cloudflare-context.js";
2
3
  import { debugCache, internalPurgeCacheByTags } from "../internal.js";
3
4
  export const purgeCache = ({ type = "direct" }) => {
4
5
  return {
@@ -13,7 +14,7 @@ export const purgeCache = ({ type = "direct" }) => {
13
14
  else {
14
15
  const durableObject = env.NEXT_CACHE_DO_PURGE;
15
16
  if (!durableObject) {
16
- debugCache("cdnInvalidation", "No durable object found. Skipping cache purge.");
17
+ error("Purge cache: NEXT_CACHE_DO_PURGE not found. Skipping cache purge.");
17
18
  return;
18
19
  }
19
20
  const id = durableObject.idFromName("cache-purge");
@@ -23,6 +23,14 @@ type Options = {
23
23
  * @default `false` for the `short-lived` mode, and `true` for the `long-lived` mode.
24
24
  */
25
25
  shouldLazilyUpdateOnCacheHit?: boolean;
26
+ /**
27
+ * Whether on cache hits the tagCache should be skipped or not. Skipping the tagCache allows requests to be
28
+ * handled faster, the downside of this is that you need to make sure that the cache gets correctly purged
29
+ * either by enabling the auto cache purging feature or doing that manually.
30
+ *
31
+ * @default `true` if the auto cache purging is enabled, `false` otherwise.
32
+ */
33
+ bypassTagCacheOnCacheHit?: boolean;
26
34
  };
27
35
  interface PutToCacheInput {
28
36
  key: string;
@@ -33,6 +41,7 @@ interface PutToCacheInput {
33
41
  * Wrapper adding a regional cache on an `IncrementalCache` implementation
34
42
  */
35
43
  declare class RegionalCache implements IncrementalCache {
44
+ #private;
36
45
  private store;
37
46
  private opts;
38
47
  name: string;
@@ -21,6 +21,15 @@ class RegionalCache {
21
21
  this.name = this.store.name;
22
22
  this.opts.shouldLazilyUpdateOnCacheHit ??= this.opts.mode === "long-lived";
23
23
  }
24
+ get #bypassTagCacheOnCacheHit() {
25
+ if (this.opts.bypassTagCacheOnCacheHit !== undefined) {
26
+ // If the bypassTagCacheOnCacheHit option is set we return that one
27
+ return this.opts.bypassTagCacheOnCacheHit;
28
+ }
29
+ // Otherwise we default to whether the automatic cache purging is enabled or not
30
+ const hasAutomaticCachePurging = !!getCloudflareContext().env.NEXT_CACHE_DO_PURGE;
31
+ return hasAutomaticCachePurging;
32
+ }
24
33
  async get(key, cacheType) {
25
34
  try {
26
35
  const cache = await this.getCacheInstance();
@@ -38,7 +47,11 @@ class RegionalCache {
38
47
  }
39
48
  }));
40
49
  }
41
- return cachedResponse.json();
50
+ const responseJson = await cachedResponse.json();
51
+ return {
52
+ ...responseJson,
53
+ shouldBypassTagCache: this.#bypassTagCacheOnCacheHit,
54
+ };
42
55
  }
43
56
  const rawEntry = await this.store.get(key, cacheType);
44
57
  const { value, lastModified } = rawEntry ?? {};
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { error } from "@opennextjs/aws/adapters/logger.js";
2
3
  import { getCloudflareContext } from "../cloudflare-context.js";
3
4
  export const debugCache = (name, ...args) => {
4
5
  if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
@@ -31,7 +32,7 @@ export async function purgeCacheByTags(tags) {
31
32
  export async function internalPurgeCacheByTags(env, tags) {
32
33
  if (!env.CACHE_PURGE_ZONE_ID && !env.CACHE_PURGE_API_TOKEN) {
33
34
  // THIS IS A NO-OP
34
- debugCache("purgeCacheByTags", "No cache zone ID or API token provided. Skipping cache purge.");
35
+ error("No cache zone ID or API token provided. Skipping cache purge.");
35
36
  return "missing-credentials";
36
37
  }
37
38
  let response;
@@ -48,12 +49,12 @@ export async function internalPurgeCacheByTags(env, tags) {
48
49
  });
49
50
  if (response.status === 429) {
50
51
  // Rate limit exceeded
51
- debugCache("purgeCacheByTags", "Rate limit exceeded. Skipping cache purge.");
52
+ error("purgeCacheByTags: Rate limit exceeded. Skipping cache purge.");
52
53
  return "rate-limit-exceeded";
53
54
  }
54
55
  const bodyResponse = (await response.json());
55
56
  if (!bodyResponse.success) {
56
- debugCache("purgeCacheByTags", "Cache purge failed. Errors:", bodyResponse.errors.map((error) => `${error.code}: ${error.message}`));
57
+ error("purgeCacheByTags: Cache purge failed. Errors:", bodyResponse.errors.map((error) => `${error.code}: ${error.message}`));
57
58
  return "purge-failed";
58
59
  }
59
60
  debugCache("purgeCacheByTags", "Cache purged successfully for tags:", tags);
@@ -1,4 +1,4 @@
1
- import type { QueueMessage } from "@opennextjs/aws/types/overrides";
1
+ import type { QueueMessage } from "@opennextjs/aws/types/overrides.js";
2
2
  declare const _default: {
3
3
  name: string;
4
4
  send: (msg: QueueMessage) => Promise<void>;
@@ -1,5 +1,5 @@
1
1
  import { IgnorableError } from "@opennextjs/aws/utils/error.js";
2
- import { getCloudflareContext } from "../../cloudflare-context";
2
+ import { getCloudflareContext } from "../../cloudflare-context.js";
3
3
  export default {
4
4
  name: "durable-queue",
5
5
  send: async (msg) => {
@@ -1,7 +1,7 @@
1
1
  import { error } from "@opennextjs/aws/adapters/logger.js";
2
2
  import { IgnorableError } from "@opennextjs/aws/utils/error.js";
3
- import { getCloudflareContext } from "../../cloudflare-context";
4
- import { debugCache } from "../internal";
3
+ import { getCloudflareContext } from "../../cloudflare-context.js";
4
+ import { debugCache } from "../internal.js";
5
5
  export const DEFAULT_REVALIDATION_TIMEOUT_MS = 10_000;
6
6
  /**
7
7
  * The Memory Queue offers basic ISR revalidation by directly requesting a revalidation of a route.
@@ -1,4 +1,4 @@
1
- import type { Queue, QueueMessage } from "@opennextjs/aws/types/overrides";
1
+ import type { Queue, QueueMessage } from "@opennextjs/aws/types/overrides.js";
2
2
  interface QueueCachingOptions {
3
3
  /**
4
4
  * The TTL for the regional cache in seconds.
@@ -1,8 +1,8 @@
1
1
  import { debug, error } from "@opennextjs/aws/adapters/logger.js";
2
2
  import { generateShardId } from "@opennextjs/aws/core/routing/queue.js";
3
3
  import { IgnorableError } from "@opennextjs/aws/utils/error.js";
4
- import { getCloudflareContext } from "../../cloudflare-context";
5
- import { debugCache, purgeCacheByTags } from "../internal";
4
+ import { getCloudflareContext } from "../../cloudflare-context.js";
5
+ import { debugCache, purgeCacheByTags } from "../internal.js";
6
6
  export const DEFAULT_WRITE_RETRIES = 3;
7
7
  export const DEFAULT_NUM_SHARDS = 4;
8
8
  export const NAME = "do-sharded-tag-cache";
@@ -1,4 +1,4 @@
1
- import { NextModeTagCache } from "@opennextjs/aws/types/overrides";
1
+ import { NextModeTagCache } from "@opennextjs/aws/types/overrides.js";
2
2
  interface WithFilterOptions {
3
3
  /**
4
4
  * The original tag cache.
@@ -35,6 +35,8 @@ export async function build(options, config, projectOpts, wranglerConfig) {
35
35
  const { aws, cloudflare } = getVersion();
36
36
  logger.info(`@opennextjs/cloudflare version: ${cloudflare}`);
37
37
  logger.info(`@opennextjs/aws version: ${aws}`);
38
+ // Clean the output directory before building the Next app.
39
+ buildHelper.initOutputDir(options);
38
40
  if (projectOpts.skipNextBuild) {
39
41
  logger.warn("Skipping Next.js build");
40
42
  }
@@ -46,7 +48,6 @@ export async function build(options, config, projectOpts, wranglerConfig) {
46
48
  }
47
49
  // Generate deployable bundle
48
50
  printHeader("Generating bundle");
49
- buildHelper.initOutputDir(options);
50
51
  compileCache(options);
51
52
  compileEnvFiles(options);
52
53
  compileInit(options, wranglerConfig);
@@ -13,7 +13,6 @@ import { inlineFindDir } from "./patches/plugins/find-dir.js";
13
13
  import { patchInstrumentation } from "./patches/plugins/instrumentation.js";
14
14
  import { inlineLoadManifest } from "./patches/plugins/load-manifest.js";
15
15
  import { patchNextServer } from "./patches/plugins/next-server.js";
16
- import { patchNodeEnvironment } from "./patches/plugins/node-environment.js";
17
16
  import { patchResolveCache } from "./patches/plugins/open-next.js";
18
17
  import { handleOptionalDependencies } from "./patches/plugins/optional-deps.js";
19
18
  import { patchPagesRouterContext } from "./patches/plugins/pages-router-context.js";
@@ -91,7 +90,6 @@ export async function bundleServer(buildOpts, projectOpts) {
91
90
  patchRouteModules(updater, buildOpts),
92
91
  patchDepdDeprecations(updater),
93
92
  patchResolveCache(updater, buildOpts),
94
- patchNodeEnvironment(updater),
95
93
  // Apply updater updates, must be the last plugin
96
94
  updater.plugin,
97
95
  ],
@@ -1,3 +1,3 @@
1
1
  import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
2
- import type { OpenNextConfig } from "../../../api";
2
+ import type { OpenNextConfig } from "../../../api/index.js";
3
3
  export declare function compileSkewProtection(options: BuildOptions, config: OpenNextConfig): Promise<void>;
@@ -138,6 +138,7 @@ async function generateBundle(name, options, fnOptions, codeCustomization) {
138
138
  awsPatches.patchNextServer,
139
139
  awsPatches.patchEnvVars,
140
140
  awsPatches.patchBackgroundRevalidation,
141
+ awsPatches.patchNodeEnvironment,
141
142
  // Cloudflare specific patches
142
143
  patchResRevalidate,
143
144
  patchUseCacheIO,
@@ -22,3 +22,23 @@ export declare const buildIdRule = "\nrule:\n pattern:\n selector: method_de
22
22
  */
23
23
  export declare function createCacheHandlerRule(handlerPath: string): string;
24
24
  export declare function createComposableCacheHandlersRule(handlerPath: string): string;
25
+ /**
26
+ * `attachRequestMeta` sets `initUrl` to always be with `https` cause this.fetchHostname && this.port is undefined in our case.
27
+ * this.nextConfig.experimental.trustHostHeader is also true.
28
+ *
29
+ * This patch checks if the original protocol was "http:" and rewrites the `initUrl` to reflect the actual host protocol.
30
+ * It will make `request.url` in route handlers end up with the correct protocol.
31
+ *
32
+ * Note: We cannot use the already defined `initURL` we passed in as requestMetaData to NextServer's request handler as pages router
33
+ * data routes would fail. It would miss the `_next/data` part in the path in that case.
34
+ *
35
+ * Therefor we just replace the protocol if necessary in the value from this template string:
36
+ * https://github.com/vercel/next.js/blob/ea08bf27/packages/next/src/server/next-server.ts#L1920
37
+ *
38
+ * Affected lines:
39
+ * https://github.com/vercel/next.js/blob/ea08bf27/packages/next/src/server/next-server.ts#L1916-L1923
40
+ *
41
+ * Callstack: handleRequest-> handleRequestImpl -> attachRequestMeta
42
+ *
43
+ */
44
+ export declare const attachRequestMetaRule = "\nrule:\n kind: identifier\n regex: ^initUrl$\n inside:\n kind: arguments\n all:\n - has: {kind: identifier, regex: ^req$}\n - has: {kind: string, regex: initURL}\n inside:\n kind: call_expression\n all:\n - has: {kind: parenthesized_expression, regex: '0'}\n - has: { regex: _requestmeta.addRequestMeta}\n inside:\n kind: expression_statement\n inside:\n kind: statement_block\n inside:\n kind: method_definition\n has:\n kind: property_identifier\n regex: ^attachRequestMeta$\nfix:\n 'req[Symbol.for(\"NextInternalRequestMeta\")]?.initProtocol === \"http:\" && initUrl.startsWith(\"https://\") ? `http://${initUrl.slice(8)}`: initUrl'";
@@ -28,6 +28,7 @@ export function patchNextServer(updater, buildOpts) {
28
28
  contents = patchCode(contents, createComposableCacheHandlersRule(composableCacheHandler));
29
29
  // Node middleware are not supported on Cloudflare yet
30
30
  contents = patchCode(contents, disableNodeMiddlewareRule);
31
+ contents = patchCode(contents, attachRequestMetaRule);
31
32
  return contents;
32
33
  },
33
34
  },
@@ -100,3 +101,47 @@ fix: |-
100
101
  globalThis[handlersSetSymbol] = new Set(globalThis[handlersMapSymbol].values());
101
102
  `;
102
103
  }
104
+ /**
105
+ * `attachRequestMeta` sets `initUrl` to always be with `https` cause this.fetchHostname && this.port is undefined in our case.
106
+ * this.nextConfig.experimental.trustHostHeader is also true.
107
+ *
108
+ * This patch checks if the original protocol was "http:" and rewrites the `initUrl` to reflect the actual host protocol.
109
+ * It will make `request.url` in route handlers end up with the correct protocol.
110
+ *
111
+ * Note: We cannot use the already defined `initURL` we passed in as requestMetaData to NextServer's request handler as pages router
112
+ * data routes would fail. It would miss the `_next/data` part in the path in that case.
113
+ *
114
+ * Therefor we just replace the protocol if necessary in the value from this template string:
115
+ * https://github.com/vercel/next.js/blob/ea08bf27/packages/next/src/server/next-server.ts#L1920
116
+ *
117
+ * Affected lines:
118
+ * https://github.com/vercel/next.js/blob/ea08bf27/packages/next/src/server/next-server.ts#L1916-L1923
119
+ *
120
+ * Callstack: handleRequest-> handleRequestImpl -> attachRequestMeta
121
+ *
122
+ */
123
+ export const attachRequestMetaRule = `
124
+ rule:
125
+ kind: identifier
126
+ regex: ^initUrl$
127
+ inside:
128
+ kind: arguments
129
+ all:
130
+ - has: {kind: identifier, regex: ^req$}
131
+ - has: {kind: string, regex: initURL}
132
+ inside:
133
+ kind: call_expression
134
+ all:
135
+ - has: {kind: parenthesized_expression, regex: '0'}
136
+ - has: { regex: _requestmeta.addRequestMeta}
137
+ inside:
138
+ kind: expression_statement
139
+ inside:
140
+ kind: statement_block
141
+ inside:
142
+ kind: method_definition
143
+ has:
144
+ kind: property_identifier
145
+ regex: ^attachRequestMeta$
146
+ fix:
147
+ 'req[Symbol.for("NextInternalRequestMeta")]?.initProtocol === "http:" && initUrl.startsWith("https://") ? \`http://\${initUrl.slice(8)}\`: initUrl'`;
@@ -1,4 +1,4 @@
1
- import type { NextConfig } from "@opennextjs/aws/types/next-types";
1
+ import type { NextConfig } from "@opennextjs/aws/types/next-types.js";
2
2
  interface ExtendedNextConfig extends NextConfig {
3
3
  experimental: {
4
4
  ppr?: boolean;
@@ -21,7 +21,7 @@
21
21
  */
22
22
  import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
23
23
  import { Cloudflare } from "cloudflare";
24
- import type { OpenNextConfig } from "../../api";
24
+ import type { OpenNextConfig } from "../../api/index.js";
25
25
  import type { WorkerEnvVar } from "./helpers.js";
26
26
  /**
27
27
  * Compute the deployment mapping for a deployment.
@@ -44,7 +44,7 @@ export default {
44
44
  }
45
45
  // @ts-expect-error: resolved by wrangler build
46
46
  const { handler } = await import("./server-functions/default/handler.mjs");
47
- return handler(reqOrResp, env, ctx);
47
+ return handler(reqOrResp, env, ctx, request.signal);
48
48
  });
49
49
  },
50
50
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@opennextjs/cloudflare",
3
3
  "description": "Cloudflare builder for next apps",
4
- "version": "1.6.5",
4
+ "version": "1.7.1",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "opennextjs-cloudflare": "dist/cli/index.js"
@@ -43,7 +43,7 @@
43
43
  "homepage": "https://github.com/opennextjs/opennextjs-cloudflare",
44
44
  "dependencies": {
45
45
  "@dotenvx/dotenvx": "1.31.0",
46
- "@opennextjs/aws": "3.7.4",
46
+ "@opennextjs/aws": "3.7.6",
47
47
  "cloudflare": "^4.4.1",
48
48
  "enquirer": "^2.4.1",
49
49
  "glob": "^11.0.0",
@@ -1,9 +0,0 @@
1
- /**
2
- * Remove a dependency on Babel by dropping the require of error-inspect
3
- */
4
- import type { ContentUpdater, Plugin } from "@opennextjs/aws/plugins/content-updater.js";
5
- export declare function patchNodeEnvironment(updater: ContentUpdater): Plugin;
6
- /**
7
- * Drops `require("./node-environment-extensions/error-inspect");`
8
- */
9
- export declare const errorInspectRule = "\nrule:\n pattern: require(\"./node-environment-extensions/error-inspect\");\nfix: |-\n // Removed by OpenNext\n // require(\"./node-environment-extensions/error-inspect\");\n";
@@ -1,26 +0,0 @@
1
- /**
2
- * Remove a dependency on Babel by dropping the require of error-inspect
3
- */
4
- import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
5
- import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
6
- export function patchNodeEnvironment(updater) {
7
- return updater.updateContent("node-environment", [
8
- {
9
- filter: getCrossPlatformPathRegex(String.raw `/next/dist/server/node-environment\.js$`, {
10
- escape: false,
11
- }),
12
- contentFilter: /error-inspect/,
13
- callback: async ({ contents }) => patchCode(contents, errorInspectRule),
14
- },
15
- ]);
16
- }
17
- /**
18
- * Drops `require("./node-environment-extensions/error-inspect");`
19
- */
20
- export const errorInspectRule = `
21
- rule:
22
- pattern: require("./node-environment-extensions/error-inspect");
23
- fix: |-
24
- // Removed by OpenNext
25
- // require("./node-environment-extensions/error-inspect");
26
- `;