@opennextjs/cloudflare 1.7.1 → 1.8.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.
@@ -9,4 +9,4 @@ export declare const purgeCache: ({ type }: PurgeOptions) => {
9
9
  resolvedRoutes: import("@opennextjs/aws/types/open-next.js").ResolvedRoute[];
10
10
  }[]): Promise<void>;
11
11
  };
12
- export {};
12
+ export default purgeCache;
@@ -25,3 +25,4 @@ export const purgeCache = ({ type = "direct" }) => {
25
25
  },
26
26
  };
27
27
  };
28
+ export default purgeCache;
@@ -20,13 +20,15 @@ type Options = {
20
20
  * Whether the regional cache entry should be updated in the background or not when it experiences
21
21
  * a cache hit.
22
22
  *
23
- * @default `false` for the `short-lived` mode, and `true` for the `long-lived` mode.
23
+ * @default `true` in `long-lived` mode when cache purge is not used, `false` otherwise.
24
24
  */
25
25
  shouldLazilyUpdateOnCacheHit?: boolean;
26
26
  /**
27
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.
28
+ * handled faster,
29
+ *
30
+ * Note: When this is enabled, make sure that the cache gets purged
31
+ * either by enabling the auto cache purging feature or manually.
30
32
  *
31
33
  * @default `true` if the auto cache purging is enabled, `false` otherwise.
32
34
  */
@@ -38,7 +40,16 @@ interface PutToCacheInput {
38
40
  entry: IncrementalCacheEntry<CacheEntryType>;
39
41
  }
40
42
  /**
41
- * Wrapper adding a regional cache on an `IncrementalCache` implementation
43
+ * Wrapper adding a regional cache on an `IncrementalCache` implementation.
44
+ *
45
+ * Using a the `RegionalCache` does not directly improves the performance much.
46
+ * However it allows bypassing the tag cache (see `bypassTagCacheOnCacheHit`) on hits.
47
+ * That's where bigger perf gain happens.
48
+ *
49
+ * We recommend using cache purge.
50
+ * When cache purge is not enabled, there is a possibility that the Cache API (local to a Data Center)
51
+ * is out of sync with the cache store (i.e. R2). That's why when cache purge is not enabled the Cache
52
+ * API is refreshed from the cache store on cache hits (for the long-lived mode).
42
53
  */
43
54
  declare class RegionalCache implements IncrementalCache {
44
55
  #private;
@@ -5,7 +5,16 @@ import { NAME as KV_CACHE_NAME } from "./kv-incremental-cache.js";
5
5
  const ONE_MINUTE_IN_SECONDS = 60;
6
6
  const THIRTY_MINUTES_IN_SECONDS = ONE_MINUTE_IN_SECONDS * 30;
7
7
  /**
8
- * Wrapper adding a regional cache on an `IncrementalCache` implementation
8
+ * Wrapper adding a regional cache on an `IncrementalCache` implementation.
9
+ *
10
+ * Using a the `RegionalCache` does not directly improves the performance much.
11
+ * However it allows bypassing the tag cache (see `bypassTagCacheOnCacheHit`) on hits.
12
+ * That's where bigger perf gain happens.
13
+ *
14
+ * We recommend using cache purge.
15
+ * When cache purge is not enabled, there is a possibility that the Cache API (local to a Data Center)
16
+ * is out of sync with the cache store (i.e. R2). That's why when cache purge is not enabled the Cache
17
+ * API is refreshed from the cache store on cache hits (for the long-lived mode).
9
18
  */
10
19
  class RegionalCache {
11
20
  store;
@@ -19,7 +28,8 @@ class RegionalCache {
19
28
  throw new Error("The KV incremental cache does not need a regional cache.");
20
29
  }
21
30
  this.name = this.store.name;
22
- this.opts.shouldLazilyUpdateOnCacheHit ??= this.opts.mode === "long-lived";
31
+ this.opts.shouldLazilyUpdateOnCacheHit ??=
32
+ this.opts.mode === "long-lived" && !this.#hasAutomaticCachePurging;
23
33
  }
24
34
  get #bypassTagCacheOnCacheHit() {
25
35
  if (this.opts.bypassTagCacheOnCacheHit !== undefined) {
@@ -27,8 +37,11 @@ class RegionalCache {
27
37
  return this.opts.bypassTagCacheOnCacheHit;
28
38
  }
29
39
  // 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;
40
+ return this.#hasAutomaticCachePurging;
41
+ }
42
+ get #hasAutomaticCachePurging() {
43
+ const cdnInvalidation = globalThis.openNextConfig.default?.override?.cdnInvalidation;
44
+ return cdnInvalidation !== undefined && cdnInvalidation !== "dummy";
32
45
  }
33
46
  async get(key, cacheType) {
34
47
  try {
@@ -38,7 +51,8 @@ class RegionalCache {
38
51
  const cachedResponse = await cache.match(urlKey);
39
52
  if (cachedResponse) {
40
53
  debugCache("Get - cached response");
41
- // Re-fetch from the store and update the regional cache in the background
54
+ // Re-fetch from the store and update the regional cache in the background.
55
+ // Note: this is only useful when the Cache API is not purged automatically.
42
56
  if (this.opts.shouldLazilyUpdateOnCacheHit) {
43
57
  getCloudflareContext().ctx.waitUntil(this.store.get(key, cacheType).then(async (rawEntry) => {
44
58
  const { value, lastModified } = rawEntry ?? {};
@@ -30,7 +30,7 @@ export async function purgeCacheByTags(tags) {
30
30
  }
31
31
  }
32
32
  export async function internalPurgeCacheByTags(env, tags) {
33
- if (!env.CACHE_PURGE_ZONE_ID && !env.CACHE_PURGE_API_TOKEN) {
33
+ if (!env.CACHE_PURGE_ZONE_ID || !env.CACHE_PURGE_API_TOKEN) {
34
34
  // THIS IS A NO-OP
35
35
  error("No cache zone ID or API token provided. Skipping cache purge.");
36
36
  return "missing-credentials";
@@ -12,6 +12,7 @@ export async function compileInit(options, wranglerConfig) {
12
12
  const nextConfig = loadConfig(path.join(options.appBuildOutputPath, ".next"));
13
13
  const basePath = nextConfig.basePath ?? "";
14
14
  const deploymentId = nextConfig.deploymentId ?? "";
15
+ const trailingSlash = nextConfig.trailingSlash ?? false;
15
16
  await build({
16
17
  entryPoints: [initPath],
17
18
  outdir: path.join(options.outputDir, "cloudflare"),
@@ -25,6 +26,7 @@ export async function compileInit(options, wranglerConfig) {
25
26
  __NEXT_BASE_PATH__: JSON.stringify(basePath),
26
27
  __ASSETS_RUN_WORKER_FIRST__: JSON.stringify(wranglerConfig.assets?.run_worker_first ?? false),
27
28
  __DEPLOYMENT_ID__: JSON.stringify(deploymentId),
29
+ __TRAILING_SLASH__: JSON.stringify(trailingSlash),
28
30
  },
29
31
  });
30
32
  }
@@ -15,5 +15,6 @@ export declare function getLatestCompatDate(): Promise<string | undefined>;
15
15
  * If the user refuses an error is thrown (since the file is mandatory).
16
16
  *
17
17
  * @param sourceDir The source directory for the project
18
+ * @return The path to the created source file
18
19
  */
19
- export declare function createOpenNextConfigIfNotExistent(sourceDir: string): Promise<void>;
20
+ export declare function createOpenNextConfigIfNotExistent(sourceDir: string): Promise<string>;
@@ -67,6 +67,7 @@ export async function getLatestCompatDate() {
67
67
  * If the user refuses an error is thrown (since the file is mandatory).
68
68
  *
69
69
  * @param sourceDir The source directory for the project
70
+ * @return The path to the created source file
70
71
  */
71
72
  export async function createOpenNextConfigIfNotExistent(sourceDir) {
72
73
  const openNextConfigPath = join(sourceDir, "open-next.config.ts");
@@ -77,4 +78,5 @@ export async function createOpenNextConfigIfNotExistent(sourceDir) {
77
78
  }
78
79
  cpSync(join(getPackageTemplatesDirPath(), "open-next.config.ts"), openNextConfigPath);
79
80
  }
81
+ return openNextConfigPath;
80
82
  }
@@ -7,7 +7,7 @@ import { compileConfig, getNormalizedOptions, nextAppDir, printHeaders, readWran
7
7
  */
8
8
  async function buildCommand(args) {
9
9
  printHeaders("build");
10
- const { config, buildDir } = await compileConfig();
10
+ const { config, buildDir } = await compileConfig(args.openNextConfigPath);
11
11
  const options = getNormalizedOptions(config, buildDir);
12
12
  const wranglerConfig = readWranglerConfig(args);
13
13
  await buildImpl(options, config, { ...args, minify: !args.noMinify, sourceDir: nextAppDir }, wranglerConfig);
@@ -34,5 +34,9 @@ export function addBuildCommand(y) {
34
34
  type: "boolean",
35
35
  default: ["1", "true", "yes"].includes(String(process.env.SKIP_WRANGLER_CONFIG_CHECK)),
36
36
  desc: "Skip checking for a Wrangler config",
37
+ })
38
+ .option("openNextConfigPath", {
39
+ type: "string",
40
+ desc: "Path to the OpenNext configuration file",
37
41
  }), (args) => buildCommand(withWranglerPassthroughArgs(args)));
38
42
  }
@@ -15,14 +15,14 @@ export async function deployCommand(args) {
15
15
  const options = getNormalizedOptions(config);
16
16
  const wranglerConfig = readWranglerConfig(args);
17
17
  const envVars = await getEnvFromPlatformProxy({
18
- configPath: args.configPath,
18
+ configPath: args.wranglerConfigPath,
19
19
  environment: args.env,
20
20
  });
21
21
  const deploymentMapping = await getDeploymentMapping(options, config, envVars);
22
22
  await populateCache(options, config, wranglerConfig, {
23
23
  target: "remote",
24
24
  environment: args.env,
25
- configPath: args.configPath,
25
+ wranglerConfigPath: args.wranglerConfigPath,
26
26
  cacheChunkSize: args.cacheChunkSize,
27
27
  });
28
28
  runWrangler(options, [
@@ -13,7 +13,7 @@ export declare function getCacheAssets(opts: BuildOptions): CacheAsset[];
13
13
  type PopulateCacheOptions = {
14
14
  target: WranglerTarget;
15
15
  environment?: string;
16
- configPath?: string;
16
+ wranglerConfigPath?: string;
17
17
  cacheChunkSize?: number;
18
18
  };
19
19
  export declare function populateCache(options: BuildOptions, config: OpenNextConfig, wranglerConfig: WranglerConfig, populateCacheOptions: PopulateCacheOptions): Promise<void>;
@@ -24,6 +24,8 @@ export declare function populateCache(options: BuildOptions, config: OpenNextCon
24
24
  */
25
25
  export declare function addPopulateCacheCommand<T extends yargs.Argv>(y: T): yargs.Argv<{}>;
26
26
  export declare function withPopulateCacheOptions<T extends yargs.Argv>(args: T): yargs.Argv<{
27
+ config: string | undefined;
28
+ } & {
27
29
  configPath: string | undefined;
28
30
  } & {
29
31
  env: string | undefined;
@@ -76,7 +76,7 @@ async function populateR2IncrementalCache(options, config, populateCacheOptions)
76
76
  `--file ${quoteShellMeta(fullPath)}`,
77
77
  ], {
78
78
  target: populateCacheOptions.target,
79
- configPath: populateCacheOptions.configPath,
79
+ configPath: populateCacheOptions.wranglerConfigPath,
80
80
  // R2 does not support the environment flag and results in the following error:
81
81
  // Incorrect type for the 'cacheExpiry' field on 'HttpMetadata': the provided value is not of type 'date'.
82
82
  environment: undefined,
@@ -113,7 +113,7 @@ async function populateKVIncrementalCache(options, config, populateCacheOptions)
113
113
  runWrangler(options, ["kv bulk put", quoteShellMeta(chunkPath), `--binding ${KV_CACHE_BINDING_NAME}`], {
114
114
  target: populateCacheOptions.target,
115
115
  environment: populateCacheOptions.environment,
116
- configPath: populateCacheOptions.configPath,
116
+ configPath: populateCacheOptions.wranglerConfigPath,
117
117
  logging: "error",
118
118
  });
119
119
  rmSync(chunkPath);
@@ -133,7 +133,7 @@ function populateD1TagCache(options, config, populateCacheOptions) {
133
133
  ], {
134
134
  target: populateCacheOptions.target,
135
135
  environment: populateCacheOptions.environment,
136
- configPath: populateCacheOptions.configPath,
136
+ configPath: populateCacheOptions.wranglerConfigPath,
137
137
  logging: "error",
138
138
  });
139
139
  logger.info("\nSuccessfully created D1 table");
@@ -189,7 +189,7 @@ async function populateCacheCommand(target, args) {
189
189
  await populateCache(options, config, wranglerConfig, {
190
190
  target,
191
191
  environment: args.env,
192
- configPath: args.configPath,
192
+ wranglerConfigPath: args.wranglerConfigPath,
193
193
  cacheChunkSize: args.cacheChunkSize,
194
194
  });
195
195
  }
@@ -14,7 +14,7 @@ export async function previewCommand(args) {
14
14
  await populateCache(options, config, wranglerConfig, {
15
15
  target: "local",
16
16
  environment: args.env,
17
- configPath: args.configPath,
17
+ wranglerConfigPath: args.wranglerConfigPath,
18
18
  cacheChunkSize: args.cacheChunkSize,
19
19
  });
20
20
  runWrangler(options, ["dev", ...args.wranglerArgs], { logging: "all" });
@@ -15,14 +15,14 @@ export async function uploadCommand(args) {
15
15
  const options = getNormalizedOptions(config);
16
16
  const wranglerConfig = readWranglerConfig(args);
17
17
  const envVars = await getEnvFromPlatformProxy({
18
- configPath: args.configPath,
18
+ configPath: args.wranglerConfigPath,
19
19
  environment: args.env,
20
20
  });
21
21
  const deploymentMapping = await getDeploymentMapping(options, config, envVars);
22
22
  await populateCache(options, config, wranglerConfig, {
23
23
  target: "remote",
24
24
  environment: args.env,
25
- configPath: args.configPath,
25
+ wranglerConfigPath: args.wranglerConfigPath,
26
26
  cacheChunkSize: args.cacheChunkSize,
27
27
  });
28
28
  runWrangler(options, [
@@ -2,7 +2,7 @@ import type yargs from "yargs";
2
2
  import type { OpenNextConfig } from "../../api/config.js";
3
3
  export type WithWranglerArgs<T = unknown> = T & {
4
4
  wranglerArgs: string[];
5
- configPath: string | undefined;
5
+ wranglerConfigPath: string | undefined;
6
6
  env: string | undefined;
7
7
  };
8
8
  export declare const nextAppDir: string;
@@ -13,11 +13,17 @@ export declare const nextAppDir: string;
13
13
  */
14
14
  export declare function printHeaders(command: string): void;
15
15
  /**
16
- * Compile the OpenNext config, and ensure it is for Cloudflare.
16
+ * Compile the OpenNext config.
17
+ *
18
+ * When users do not specify a custom config file (using `--openNextConfigPath`),
19
+ * the CLI will offer to create one.
20
+ *
21
+ * When users specify a custom config file but it doesn't exist, we throw an Error.
17
22
  *
23
+ * @param configPath Optional path to the config file. Absolute or relative to cwd.
18
24
  * @returns OpenNext config.
19
25
  */
20
- export declare function compileConfig(): Promise<{
26
+ export declare function compileConfig(configPath: string | undefined): Promise<{
21
27
  config: import("@opennextjs/aws/types/open-next.js").OpenNextConfig;
22
28
  buildDir: string;
23
29
  }>;
@@ -64,18 +70,21 @@ export declare function readWranglerConfig(args: WithWranglerArgs): import("wran
64
70
  * Adds flags for the wrangler config path and environment to the yargs configuration.
65
71
  */
66
72
  export declare function withWranglerOptions<T extends yargs.Argv>(args: T): yargs.Argv<{
73
+ config: string | undefined;
74
+ } & {
67
75
  configPath: string | undefined;
68
76
  } & {
69
77
  env: string | undefined;
70
78
  }>;
79
+ type WranglerInputArgs = {
80
+ configPath: string | undefined;
81
+ config: string | undefined;
82
+ env: string | undefined;
83
+ };
71
84
  /**
72
85
  *
73
86
  * @param args
74
87
  * @returns The inputted args, and an array of arguments that can be given to wrangler commands, including the `--config` and `--env` args.
75
88
  */
76
- export declare function withWranglerPassthroughArgs<T extends yargs.ArgumentsCamelCase<{
77
- configPath: string | undefined;
78
- env: string | undefined;
79
- }>>(args: T): T & {
80
- wranglerArgs: string[];
81
- };
89
+ export declare function withWranglerPassthroughArgs<T extends yargs.ArgumentsCamelCase<WranglerInputArgs>>(args: T): WithWranglerArgs<T>;
90
+ export {};
@@ -18,13 +18,25 @@ export function printHeaders(command) {
18
18
  showWarningOnWindows();
19
19
  }
20
20
  /**
21
- * Compile the OpenNext config, and ensure it is for Cloudflare.
21
+ * Compile the OpenNext config.
22
22
  *
23
+ * When users do not specify a custom config file (using `--openNextConfigPath`),
24
+ * the CLI will offer to create one.
25
+ *
26
+ * When users specify a custom config file but it doesn't exist, we throw an Error.
27
+ *
28
+ * @param configPath Optional path to the config file. Absolute or relative to cwd.
23
29
  * @returns OpenNext config.
24
30
  */
25
- export async function compileConfig() {
26
- await createOpenNextConfigIfNotExistent(nextAppDir);
27
- const { config, buildDir } = await compileOpenNextConfig(nextAppDir, undefined, { compileEdge: true });
31
+ export async function compileConfig(configPath) {
32
+ if (configPath && !existsSync(configPath)) {
33
+ throw new Error(`Custom config file not found at ${configPath}`);
34
+ }
35
+ if (!configPath) {
36
+ configPath = await createOpenNextConfigIfNotExistent(nextAppDir);
37
+ }
38
+ // TODO: remove the hack passing the `configPath` as the `baseDir` when https://github.com/opennextjs/opennextjs-aws/pull/972 is merged
39
+ const { config, buildDir } = await compileOpenNextConfig(configPath, "", { compileEdge: true });
28
40
  ensureCloudflareConfig(config);
29
41
  return { config, buildDir };
30
42
  }
@@ -64,19 +76,24 @@ export function getNormalizedOptions(config, buildDir = nextAppDir) {
64
76
  * @returns Wrangler config.
65
77
  */
66
78
  export function readWranglerConfig(args) {
67
- return unstable_readConfig({ env: args.env, config: args.configPath });
79
+ return unstable_readConfig({ env: args.env, config: args.wranglerConfigPath });
68
80
  }
69
81
  /**
70
82
  * Adds flags for the wrangler config path and environment to the yargs configuration.
71
83
  */
72
84
  export function withWranglerOptions(args) {
73
85
  return args
74
- .options("configPath", {
86
+ .option("config", {
75
87
  type: "string",
76
- alias: ["config", "c"],
88
+ alias: "c",
77
89
  desc: "Path to Wrangler configuration file",
78
90
  })
79
- .options("env", {
91
+ .option("configPath", {
92
+ type: "string",
93
+ desc: "Path to Wrangler configuration file",
94
+ deprecated: true,
95
+ })
96
+ .option("env", {
80
97
  type: "string",
81
98
  alias: "e",
82
99
  desc: "Wrangler environment to use for operations",
@@ -88,8 +105,16 @@ export function withWranglerOptions(args) {
88
105
  * @returns An array of arguments that can be given to wrangler commands, including the `--config` and `--env` args.
89
106
  */
90
107
  function getWranglerArgs(args) {
108
+ if (args.configPath) {
109
+ logger.warn("The `--configPath` flag is deprecated, please use `--config` instead.");
110
+ if (args.config) {
111
+ logger.error("Multiple config flags found. Please use the `--config` flag for your Wrangler config path.");
112
+ process.exit(1);
113
+ }
114
+ }
91
115
  return [
92
116
  ...(args.configPath ? ["--config", args.configPath] : []),
117
+ ...(args.config ? ["--config", args.config] : []),
93
118
  ...(args.env ? ["--env", args.env] : []),
94
119
  // Note: the first args in `_` will be the commands.
95
120
  ...args._.slice(args._[0] === "populateCache" ? 2 : 1).map((a) => `${a}`),
@@ -101,5 +126,9 @@ function getWranglerArgs(args) {
101
126
  * @returns The inputted args, and an array of arguments that can be given to wrangler commands, including the `--config` and `--env` args.
102
127
  */
103
128
  export function withWranglerPassthroughArgs(args) {
104
- return { ...args, wranglerArgs: getWranglerArgs(args) };
129
+ return {
130
+ ...args,
131
+ wranglerConfigPath: args.config ?? args.configPath,
132
+ wranglerArgs: getWranglerArgs(args),
133
+ };
105
134
  }
@@ -12,4 +12,5 @@ declare global {
12
12
  var __NEXT_BASE_PATH__: string;
13
13
  var __ASSETS_RUN_WORKER_FIRST__: boolean | string[] | undefined;
14
14
  var __DEPLOYMENT_ID__: string;
15
+ var __TRAILING_SLASH__: boolean;
15
16
  }
@@ -76,6 +76,7 @@ function initRuntime() {
76
76
  __BUILD_TIMESTAMP_MS__,
77
77
  __NEXT_BASE_PATH__,
78
78
  __ASSETS_RUN_WORKER_FIRST__,
79
+ __TRAILING_SLASH__,
79
80
  // The external middleware will use the convertTo function of the `edge` converter
80
81
  // by default it will try to fetch the request, but since we are running everything in the same worker
81
82
  // we need to use the request as is.
@@ -33,7 +33,8 @@ export default {
33
33
  : env.ASSETS?.fetch(new URL(`/${imageUrl}`, url));
34
34
  }
35
35
  // Fallback for the Next default image loader.
36
- if (url.pathname === `${globalThis.__NEXT_BASE_PATH__}/_next/image`) {
36
+ if (url.pathname ===
37
+ `${globalThis.__NEXT_BASE_PATH__}/_next/image${globalThis.__TRAILING_SLASH__ ? "/" : ""}`) {
37
38
  const imageUrl = url.searchParams.get("url") ?? "";
38
39
  return await fetchImage(env.ASSETS, imageUrl, ctx);
39
40
  }
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.7.1",
4
+ "version": "1.8.1",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "opennextjs-cloudflare": "dist/cli/index.js"