@opennextjs/cloudflare 1.16.6 → 1.17.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 (54) hide show
  1. package/dist/cli/build/build.js +1 -1
  2. package/dist/cli/build/bundle-server.js +3 -1
  3. package/dist/cli/build/open-next/compile-env-files.js +1 -1
  4. package/dist/cli/build/open-next/createServerBundle.js +1 -1
  5. package/dist/cli/build/patches/plugins/dynamic-requires.js +1 -1
  6. package/dist/cli/build/patches/plugins/instrumentation.js +1 -1
  7. package/dist/cli/build/patches/plugins/load-manifest.js +1 -1
  8. package/dist/cli/build/patches/plugins/next-server.js +1 -1
  9. package/dist/cli/build/patches/plugins/route-module.js +1 -1
  10. package/dist/cli/build/patches/plugins/wrangler-external.js +1 -1
  11. package/dist/cli/build/utils/index.d.ts +0 -6
  12. package/dist/cli/build/utils/index.js +1 -6
  13. package/dist/cli/commands/build.js +2 -2
  14. package/dist/cli/commands/deploy.d.ts +1 -1
  15. package/dist/cli/commands/deploy.js +9 -4
  16. package/dist/cli/commands/migrate.js +16 -8
  17. package/dist/cli/commands/populate-cache.d.ts +2 -2
  18. package/dist/cli/commands/populate-cache.js +19 -7
  19. package/dist/cli/commands/preview.d.ts +1 -1
  20. package/dist/cli/commands/preview.js +9 -4
  21. package/dist/cli/commands/skew-protection.d.ts +1 -1
  22. package/dist/cli/commands/upload.d.ts +1 -1
  23. package/dist/cli/commands/upload.js +9 -4
  24. package/dist/cli/commands/{helpers.js → utils/helpers.js} +1 -1
  25. package/dist/cli/commands/utils/run-wrangler.d.ts +44 -0
  26. package/dist/cli/{utils → commands/utils}/run-wrangler.js +46 -11
  27. package/dist/cli/commands/{utils.d.ts → utils/utils.d.ts} +1 -11
  28. package/dist/cli/commands/{utils.js → utils/utils.js} +2 -24
  29. package/dist/cli/project-options.d.ts +1 -1
  30. package/dist/cli/utils/ask-account-selection.d.ts +12 -0
  31. package/dist/cli/utils/ask-account-selection.js +23 -0
  32. package/dist/cli/{build/utils → utils}/create-config-files.d.ts +1 -1
  33. package/dist/cli/{build/utils → utils}/create-config-files.js +4 -4
  34. package/dist/cli/utils/create-open-next-config.d.ts +17 -0
  35. package/dist/cli/utils/create-open-next-config.js +50 -0
  36. package/dist/cli/utils/create-wrangler-config.d.ts +24 -0
  37. package/dist/cli/utils/create-wrangler-config.js +244 -0
  38. package/dist/cli/utils/nextjs-support.d.ts +10 -0
  39. package/dist/cli/utils/nextjs-support.js +24 -0
  40. package/package.json +3 -2
  41. package/templates/open-next.config.ts +1 -1
  42. package/templates/wrangler.jsonc +2 -2
  43. package/dist/cli/utils/open-next-config.d.ts +0 -14
  44. package/dist/cli/utils/open-next-config.js +0 -27
  45. package/dist/cli/utils/run-wrangler.d.ts +0 -12
  46. package/dist/cli/utils/wrangler-config.d.ts +0 -15
  47. package/dist/cli/utils/wrangler-config.js +0 -64
  48. /package/dist/cli/{build → commands}/utils/files.d.ts +0 -0
  49. /package/dist/cli/{build → commands}/utils/files.js +0 -0
  50. /package/dist/cli/commands/{helpers.d.ts → utils/helpers.d.ts} +0 -0
  51. /package/dist/cli/{build/utils → utils}/extract-project-env-vars.d.ts +0 -0
  52. /package/dist/cli/{build/utils → utils}/extract-project-env-vars.js +0 -0
  53. /package/dist/cli/{build/utils → utils}/normalize-path.d.ts +0 -0
  54. /package/dist/cli/{build/utils → utils}/normalize-path.js +0 -0
@@ -6,7 +6,7 @@ import * as buildHelper from "@opennextjs/aws/build/helper.js";
6
6
  import { patchOriginalNextConfig } from "@opennextjs/aws/build/patch/patches/index.js";
7
7
  import { printHeader } from "@opennextjs/aws/build/utils.js";
8
8
  import logger from "@opennextjs/aws/logger.js";
9
- import { ensureNextjsVersionSupported } from "../commands/utils.js";
9
+ import { ensureNextjsVersionSupported } from "../utils/nextjs-support.js";
10
10
  import { bundleServer } from "./bundle-server.js";
11
11
  import { compileCacheAssetsManifestSqlFile } from "./open-next/compile-cache-assets-manifest.js";
12
12
  import { compileEnvFiles } from "./open-next/compile-env-files.js";
@@ -7,6 +7,7 @@ import * as buildHelper from "@opennextjs/aws/build/helper.js";
7
7
  import { ContentUpdater } from "@opennextjs/aws/plugins/content-updater.js";
8
8
  import { build } from "esbuild";
9
9
  import { getOpenNextConfig } from "../../api/config.js";
10
+ import { normalizePath } from "../utils/normalize-path.js";
10
11
  import { patchVercelOgLibrary } from "./patches/ast/patch-vercel-og-library.js";
11
12
  import { patchWebpackRuntime } from "./patches/ast/webpack-runtime.js";
12
13
  import { inlineDynamicRequires } from "./patches/plugins/dynamic-requires.js";
@@ -23,7 +24,8 @@ import { shimRequireHook } from "./patches/plugins/require-hook.js";
23
24
  import { patchRouteModules } from "./patches/plugins/route-module.js";
24
25
  import { shimReact } from "./patches/plugins/shim-react.js";
25
26
  import { setWranglerExternal } from "./patches/plugins/wrangler-external.js";
26
- import { copyPackageCliFiles, needsExperimentalReact, normalizePath } from "./utils/index.js";
27
+ import { copyPackageCliFiles } from "./utils/copy-package-cli-files.js";
28
+ import { needsExperimentalReact } from "./utils/needs-experimental-react.js";
27
29
  /** The dist directory of the Cloudflare adapter package */
28
30
  const packageDistDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "../..");
29
31
  /**
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { extractProjectEnvVars } from "../utils/index.js";
3
+ import { extractProjectEnvVars } from "../../utils/extract-project-env-vars.js";
4
4
  /**
5
5
  * Compiles the values extracted from the project's env files to the output directory for use in the worker.
6
6
  */
@@ -19,10 +19,10 @@ import { openNextReplacementPlugin } from "@opennextjs/aws/plugins/replacement.j
19
19
  import { openNextResolvePlugin } from "@opennextjs/aws/plugins/resolve.js";
20
20
  import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
21
21
  import { getOpenNextConfig } from "../../../api/config.js";
22
+ import { normalizePath } from "../../utils/normalize-path.js";
22
23
  import { patchResRevalidate } from "../patches/plugins/res-revalidate.js";
23
24
  import { patchTurbopackRuntime } from "../patches/plugins/turbopack.js";
24
25
  import { patchUseCacheIO } from "../patches/plugins/use-cache.js";
25
- import { normalizePath } from "../utils/index.js";
26
26
  import { copyWorkerdPackages } from "../utils/workerd.js";
27
27
  export async function createServerBundle(options, codeCustomization) {
28
28
  const { config } = options;
@@ -3,7 +3,7 @@ import { join, posix, sep } from "node:path";
3
3
  import { getPackagePath } from "@opennextjs/aws/build/helper.js";
4
4
  import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
5
5
  import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
6
- import { normalizePath } from "../../utils/normalize-path.js";
6
+ import { normalizePath } from "../../../utils/normalize-path.js";
7
7
  async function getPagesManifests(serverDir) {
8
8
  try {
9
9
  return Object.values(JSON.parse(await readFile(join(serverDir, "pages-manifest.json"), "utf-8")));
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { getPackagePath } from "@opennextjs/aws/build/helper.js";
4
4
  import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
5
5
  import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
6
- import { normalizePath } from "../../utils/normalize-path.js";
6
+ import { normalizePath } from "../../../utils/normalize-path.js";
7
7
  export function patchInstrumentation(updater, buildOpts) {
8
8
  const builtInstrumentationPath = getBuiltInstrumentationPath(buildOpts);
9
9
  updater.updateContent("patch-instrumentation-next15-4", [
@@ -9,7 +9,7 @@ import { getPackagePath } from "@opennextjs/aws/build/helper.js";
9
9
  import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
10
10
  import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
11
11
  import { glob } from "glob";
12
- import { normalizePath } from "../../utils/normalize-path.js";
12
+ import { normalizePath } from "../../../utils/normalize-path.js";
13
13
  export function inlineLoadManifest(updater, buildOpts) {
14
14
  return updater.updateContent("inline-load-manifest", [
15
15
  {
@@ -10,7 +10,7 @@ import path from "node:path";
10
10
  import { getPackagePath } from "@opennextjs/aws/build/helper.js";
11
11
  import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
12
12
  import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
13
- import { normalizePath } from "../../utils/index.js";
13
+ import { normalizePath } from "../../../utils/normalize-path.js";
14
14
  export function patchNextServer(updater, buildOpts) {
15
15
  return updater.updateContent("next-server", [
16
16
  {
@@ -9,7 +9,7 @@ import path from "node:path";
9
9
  import { getPackagePath } from "@opennextjs/aws/build/helper.js";
10
10
  import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
11
11
  import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
12
- import { normalizePath } from "../../utils/index.js";
12
+ import { normalizePath } from "../../../utils/normalize-path.js";
13
13
  export function patchRouteModules(updater, buildOpts) {
14
14
  return updater.updateContent("route-module", [
15
15
  {
@@ -14,7 +14,7 @@
14
14
  * ref: https://developers.cloudflare.com/workers/wrangler/bundling/
15
15
  */
16
16
  import { dirname, resolve } from "node:path";
17
- import { normalizePath } from "../../utils/normalize-path.js";
17
+ import { normalizePath } from "../../../utils/normalize-path.js";
18
18
  export function setWranglerExternal() {
19
19
  return {
20
20
  name: "wrangler-externals",
@@ -1,6 +0,0 @@
1
- export * from "./copy-package-cli-files.js";
2
- export * from "./create-config-files.js";
3
- export * from "./ensure-cf-config.js";
4
- export * from "./extract-project-env-vars.js";
5
- export * from "./needs-experimental-react.js";
6
- export * from "./normalize-path.js";
@@ -1,6 +1 @@
1
- export * from "./copy-package-cli-files.js";
2
- export * from "./create-config-files.js";
3
- export * from "./ensure-cf-config.js";
4
- export * from "./extract-project-env-vars.js";
5
- export * from "./needs-experimental-react.js";
6
- export * from "./normalize-path.js";
1
+ "use strict";
@@ -1,6 +1,6 @@
1
1
  import { build as buildImpl } from "../build/build.js";
2
- import { createWranglerConfigIfNonExistent } from "../build/utils/index.js";
3
- import { compileConfig, getNormalizedOptions, nextAppDir, printHeaders, readWranglerConfig, withWranglerOptions, withWranglerPassthroughArgs, } from "./utils.js";
2
+ import { createWranglerConfigIfNonExistent } from "../utils/create-config-files.js";
3
+ import { compileConfig, getNormalizedOptions, nextAppDir, printHeaders, readWranglerConfig, withWranglerOptions, withWranglerPassthroughArgs, } from "./utils/utils.js";
4
4
  /**
5
5
  * Implementation of the `opennextjs-cloudflare build` command.
6
6
  *
@@ -1,5 +1,5 @@
1
1
  import type yargs from "yargs";
2
- import type { WithWranglerArgs } from "./utils.js";
2
+ import type { WithWranglerArgs } from "./utils/utils.js";
3
3
  /**
4
4
  * Implementation of the `opennextjs-cloudflare deploy` command.
5
5
  *
@@ -1,9 +1,10 @@
1
+ import logger from "@opennextjs/aws/logger.js";
1
2
  import { DEPLOYMENT_MAPPING_ENV_NAME } from "../templates/skew-protection.js";
2
- import { runWrangler } from "../utils/run-wrangler.js";
3
- import { getEnvFromPlatformProxy, quoteShellMeta } from "./helpers.js";
4
3
  import { populateCache, withPopulateCacheOptions } from "./populate-cache.js";
5
4
  import { getDeploymentMapping } from "./skew-protection.js";
6
- import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerPassthroughArgs, } from "./utils.js";
5
+ import { getEnvFromPlatformProxy, quoteShellMeta } from "./utils/helpers.js";
6
+ import { runWrangler } from "./utils/run-wrangler.js";
7
+ import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerPassthroughArgs, } from "./utils/utils.js";
7
8
  /**
8
9
  * Implementation of the `opennextjs-cloudflare deploy` command.
9
10
  *
@@ -23,7 +24,7 @@ export async function deployCommand(args) {
23
24
  shouldUsePreviewId: false,
24
25
  }, envVars);
25
26
  const deploymentMapping = await getDeploymentMapping(buildOpts, config, envVars);
26
- runWrangler(buildOpts, [
27
+ const result = runWrangler(buildOpts, [
27
28
  "deploy",
28
29
  ...args.wranglerArgs,
29
30
  ...(deploymentMapping
@@ -39,6 +40,10 @@ export async function deployCommand(args) {
39
40
  OPEN_NEXT_DEPLOY: "true",
40
41
  },
41
42
  });
43
+ if (!result.success) {
44
+ logger.error(`Wrangler deploy command failed${result.stderr ? `:\n${result.stderr}` : ""}`);
45
+ process.exit(1);
46
+ }
42
47
  }
43
48
  /**
44
49
  * Add the `deploy` command to yargs configuration.
@@ -4,11 +4,12 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { checkRunningInsideNextjsApp, findNextConfig, findPackagerAndRoot, getNextVersion, } from "@opennextjs/aws/build/helper.js";
6
6
  import logger from "@opennextjs/aws/logger.js";
7
- import { conditionalAppendFileSync } from "../build/utils/files.js";
8
7
  import { askConfirmation } from "../utils/ask-confirmation.js";
9
- import { createOpenNextConfigFile, findOpenNextConfig } from "../utils/open-next-config.js";
10
- import { createWranglerConfigFile, findWranglerConfig } from "../utils/wrangler-config.js";
11
- import { ensureNextjsVersionSupported, printHeaders } from "./utils.js";
8
+ import { createOpenNextConfigFile, findOpenNextConfig } from "../utils/create-open-next-config.js";
9
+ import { createWranglerConfigFile, findWranglerConfig } from "../utils/create-wrangler-config.js";
10
+ import { ensureNextjsVersionSupported } from "../utils/nextjs-support.js";
11
+ import { conditionalAppendFileSync } from "./utils/files.js";
12
+ import { printHeaders } from "./utils/utils.js";
12
13
  /**
13
14
  * Implementation of the `opennextjs-cloudflare migrate` command.
14
15
  *
@@ -54,9 +55,13 @@ async function migrateCommand(args) {
54
55
  process.exit(1);
55
56
  }
56
57
  printStepTitle("Creating wrangler.jsonc");
57
- await createWranglerConfigFile("./");
58
+ const { cachingEnabled } = await createWranglerConfigFile("./");
59
+ if (!cachingEnabled) {
60
+ logger.warn(`Failed to set up cache for your project.\n` +
61
+ `After the migration completes, please manually setup cache in wrangler.jsonc and open-next.config.ts files (for more details see: https://opennext.js.org/cloudflare/caching).\n`);
62
+ }
58
63
  printStepTitle("Creating open-next.config.ts");
59
- await createOpenNextConfigFile("./");
64
+ createOpenNextConfigFile("./", { cache: cachingEnabled });
60
65
  const devVarsExists = fs.existsSync(".dev.vars");
61
66
  printStepTitle(`${devVarsExists ? "Updating" : "Creating"} .dev.vars file`);
62
67
  conditionalAppendFileSync(".dev.vars", "NEXTJS_ENV=development\n", {
@@ -143,10 +148,13 @@ async function migrateCommand(args) {
143
148
  logger.info("🎉 OpenNext Cloudflare adapter complete!\n" +
144
149
  "\nNext steps:\n" +
145
150
  `- Run: "${packageManager.run} preview" to build and preview your Cloudflare application locally\n` +
146
- `- Run: "${packageManager.run} deploy" to deploy your application to Cloudflare Workers\n`);
151
+ `- Run: "${packageManager.run} deploy" to deploy your application to Cloudflare Workers\n` +
152
+ (cachingEnabled
153
+ ? ""
154
+ : `- ⚠️ Setup cache, see https://opennext.js.org/cloudflare/caching for more details\n`));
147
155
  }
148
156
  const packageManagers = {
149
- pnpm: { name: "pnpm", install: "pnpm add", installDev: "pnpm add -D", run: "pnpm" },
157
+ pnpm: { name: "pnpm", install: "pnpm add", installDev: "pnpm add -D", run: "pnpm run" },
150
158
  npm: { name: "npm", install: "npm install", installDev: "npm install --save-dev", run: "npm run" },
151
159
  bun: { name: "bun", install: "bun add", installDev: "bun add -D", run: "bun" },
152
160
  yarn: { name: "yarn", install: "yarn add", installDev: "yarn add -D", run: "yarn" },
@@ -2,8 +2,8 @@ import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
2
2
  import type { OpenNextConfig } from "@opennextjs/aws/types/open-next.js";
3
3
  import type { Unstable_Config as WranglerConfig } from "wrangler";
4
4
  import type yargs from "yargs";
5
- import type { WranglerTarget } from "../utils/run-wrangler.js";
6
- import { type WorkerEnvVar } from "./helpers.js";
5
+ import { type WorkerEnvVar } from "./utils/helpers.js";
6
+ import type { WranglerTarget } from "./utils/run-wrangler.js";
7
7
  export declare function populateCache(buildOpts: BuildOptions, config: OpenNextConfig, wranglerConfig: WranglerConfig, populateCacheOptions: PopulateCacheOptions, envVars: WorkerEnvVar): Promise<void>;
8
8
  export type CacheAsset = {
9
9
  isFetch: boolean;
@@ -10,10 +10,10 @@ import { BINDING_NAME as R2_CACHE_BINDING_NAME, NAME as R2_CACHE_NAME, PREFIX_EN
10
10
  import { CACHE_DIR as STATIC_ASSETS_CACHE_DIR, NAME as STATIC_ASSETS_CACHE_NAME, } from "../../api/overrides/incremental-cache/static-assets-incremental-cache.js";
11
11
  import { computeCacheKey } from "../../api/overrides/internal.js";
12
12
  import { BINDING_NAME as D1_TAG_BINDING_NAME, NAME as D1_TAG_NAME, } from "../../api/overrides/tag-cache/d1-next-tag-cache.js";
13
- import { normalizePath } from "../build/utils/normalize-path.js";
14
- import { runWrangler } from "../utils/run-wrangler.js";
15
- import { getEnvFromPlatformProxy, quoteShellMeta } from "./helpers.js";
16
- import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerOptions, withWranglerPassthroughArgs, } from "./utils.js";
13
+ import { normalizePath } from "../utils/normalize-path.js";
14
+ import { getEnvFromPlatformProxy, quoteShellMeta } from "./utils/helpers.js";
15
+ import { runWrangler } from "./utils/run-wrangler.js";
16
+ import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerOptions, withWranglerPassthroughArgs, } from "./utils/utils.js";
17
17
  /**
18
18
  * Implementation of the `opennextjs-cloudflare populateCache` command.
19
19
  *
@@ -131,7 +131,7 @@ async function populateR2IncrementalCache(buildOpts, config, populateCacheOption
131
131
  fs.writeFileSync(listFile, JSON.stringify(objectList));
132
132
  const concurrency = Math.max(1, populateCacheOptions.cacheChunkSize ?? 50);
133
133
  const jurisdiction = binding.jurisdiction ? `--jurisdiction ${binding.jurisdiction}` : "";
134
- runWrangler(buildOpts, [
134
+ const result = runWrangler(buildOpts, [
135
135
  "r2 bulk put",
136
136
  bucket,
137
137
  `--filename ${quoteShellMeta(listFile)}`,
@@ -146,6 +146,10 @@ async function populateR2IncrementalCache(buildOpts, config, populateCacheOption
146
146
  logging: "error",
147
147
  });
148
148
  fs.rmSync(listFile, { force: true });
149
+ if (!result.success) {
150
+ logger.error(`Wrangler r2 bulk put command failed${result.stderr ? `:\n${result.stderr}` : ""}`);
151
+ process.exit(1);
152
+ }
149
153
  logger.info(`Successfully populated cache with ${assets.length} assets`);
150
154
  }
151
155
  async function populateKVIncrementalCache(buildOpts, config, populateCacheOptions, envVars) {
@@ -173,7 +177,7 @@ async function populateKVIncrementalCache(buildOpts, config, populateCacheOption
173
177
  value: fs.readFileSync(fullPath, "utf8"),
174
178
  }));
175
179
  fs.writeFileSync(chunkPath, JSON.stringify(kvMapping));
176
- runWrangler(buildOpts, [
180
+ const result = runWrangler(buildOpts, [
177
181
  "kv bulk put",
178
182
  quoteShellMeta(chunkPath),
179
183
  `--binding ${KV_CACHE_BINDING_NAME}`,
@@ -185,6 +189,10 @@ async function populateKVIncrementalCache(buildOpts, config, populateCacheOption
185
189
  logging: "error",
186
190
  });
187
191
  fs.rmSync(chunkPath, { force: true });
192
+ if (!result.success) {
193
+ logger.error(`Wrangler kv bulk put command failed${result.stderr ? `:\n${result.stderr}` : ""}`);
194
+ process.exit(1);
195
+ }
188
196
  }
189
197
  logger.info(`Successfully populated cache with ${assets.length} assets`);
190
198
  }
@@ -194,7 +202,7 @@ function populateD1TagCache(buildOpts, config, populateCacheOptions) {
194
202
  if (!binding) {
195
203
  throw new Error(`No D1 binding ${JSON.stringify(D1_TAG_BINDING_NAME)} found!`);
196
204
  }
197
- runWrangler(buildOpts, [
205
+ const result = runWrangler(buildOpts, [
198
206
  "d1 execute",
199
207
  D1_TAG_BINDING_NAME,
200
208
  `--command "CREATE TABLE IF NOT EXISTS revalidations (tag TEXT NOT NULL, revalidatedAt INTEGER NOT NULL, UNIQUE(tag) ON CONFLICT REPLACE);"`,
@@ -205,6 +213,10 @@ function populateD1TagCache(buildOpts, config, populateCacheOptions) {
205
213
  configPath: populateCacheOptions.wranglerConfigPath,
206
214
  logging: "error",
207
215
  });
216
+ if (!result.success) {
217
+ logger.error(`Wrangler d1 execute command failed${result.stderr ? `:\n${result.stderr}` : ""}`);
218
+ process.exit(1);
219
+ }
208
220
  logger.info("\nSuccessfully created D1 table");
209
221
  }
210
222
  function populateStaticAssetsIncrementalCache(options) {
@@ -1,5 +1,5 @@
1
1
  import type yargs from "yargs";
2
- import type { WithWranglerArgs } from "./utils.js";
2
+ import type { WithWranglerArgs } from "./utils/utils.js";
3
3
  /**
4
4
  * Implementation of the `opennextjs-cloudflare preview` command.
5
5
  *
@@ -1,7 +1,8 @@
1
- import { runWrangler } from "../utils/run-wrangler.js";
2
- import { getEnvFromPlatformProxy } from "./helpers.js";
1
+ import logger from "@opennextjs/aws/logger.js";
3
2
  import { populateCache, withPopulateCacheOptions } from "./populate-cache.js";
4
- import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerPassthroughArgs, } from "./utils.js";
3
+ import { getEnvFromPlatformProxy } from "./utils/helpers.js";
4
+ import { runWrangler } from "./utils/run-wrangler.js";
5
+ import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerPassthroughArgs, } from "./utils/utils.js";
5
6
  /**
6
7
  * Implementation of the `opennextjs-cloudflare preview` command.
7
8
  *
@@ -20,7 +21,11 @@ export async function previewCommand(args) {
20
21
  cacheChunkSize: args.cacheChunkSize,
21
22
  shouldUsePreviewId: args.remote,
22
23
  }, envVars);
23
- runWrangler(buildOpts, ["dev", ...args.wranglerArgs], { logging: "all" });
24
+ const result = runWrangler(buildOpts, ["dev", ...args.wranglerArgs], { logging: "all" });
25
+ if (!result.success) {
26
+ logger.error(`Wrangler dev command failed${result.stderr ? `:\n${result.stderr}` : ""}`);
27
+ process.exit(1);
28
+ }
24
29
  }
25
30
  /**
26
31
  * Add the `preview` command to yargs configuration.
@@ -22,7 +22,7 @@
22
22
  import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
23
23
  import { Cloudflare } from "cloudflare";
24
24
  import type { OpenNextConfig } from "../../api/index.js";
25
- import type { WorkerEnvVar } from "./helpers.js";
25
+ import type { WorkerEnvVar } from "./utils/helpers.js";
26
26
  /**
27
27
  * Compute the deployment mapping for a deployment.
28
28
  *
@@ -1,5 +1,5 @@
1
1
  import type yargs from "yargs";
2
- import type { WithWranglerArgs } from "./utils.js";
2
+ import type { WithWranglerArgs } from "./utils/utils.js";
3
3
  /**
4
4
  * Implementation of the `opennextjs-cloudflare upload` command.
5
5
  *
@@ -1,9 +1,10 @@
1
+ import logger from "@opennextjs/aws/logger.js";
1
2
  import { DEPLOYMENT_MAPPING_ENV_NAME } from "../templates/skew-protection.js";
2
- import { runWrangler } from "../utils/run-wrangler.js";
3
- import { getEnvFromPlatformProxy, quoteShellMeta } from "./helpers.js";
4
3
  import { populateCache, withPopulateCacheOptions } from "./populate-cache.js";
5
4
  import { getDeploymentMapping } from "./skew-protection.js";
6
- import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerPassthroughArgs, } from "./utils.js";
5
+ import { getEnvFromPlatformProxy, quoteShellMeta } from "./utils/helpers.js";
6
+ import { runWrangler } from "./utils/run-wrangler.js";
7
+ import { getNormalizedOptions, printHeaders, readWranglerConfig, retrieveCompiledConfig, withWranglerPassthroughArgs, } from "./utils/utils.js";
7
8
  /**
8
9
  * Implementation of the `opennextjs-cloudflare upload` command.
9
10
  *
@@ -26,13 +27,17 @@ export async function uploadCommand(args) {
26
27
  cacheChunkSize: args.cacheChunkSize,
27
28
  shouldUsePreviewId: false,
28
29
  }, envVars);
29
- runWrangler(buildOpts, [
30
+ const result = runWrangler(buildOpts, [
30
31
  "versions upload",
31
32
  ...args.wranglerArgs,
32
33
  ...(deploymentMapping
33
34
  ? [`--var ${DEPLOYMENT_MAPPING_ENV_NAME}:${quoteShellMeta(JSON.stringify(deploymentMapping))}`]
34
35
  : []),
35
36
  ], { logging: "all" });
37
+ if (!result.success) {
38
+ logger.error(`Wrangler versions upload command failed${result.stderr ? `:\n${result.stderr}` : ""}`);
39
+ process.exit(1);
40
+ }
36
41
  }
37
42
  /**
38
43
  * Add the `upload` command to yargs configuration.
@@ -1,5 +1,5 @@
1
1
  import { getPlatformProxy } from "wrangler";
2
- import { extractProjectEnvVars } from "../build/utils/extract-project-env-vars.js";
2
+ import { extractProjectEnvVars } from "../../utils/extract-project-env-vars.js";
3
3
  /**
4
4
  * Returns the env vars to use by the CLI.
5
5
  *
@@ -0,0 +1,44 @@
1
+ export type PackagerDetails = {
2
+ /** The name of the package manager. */
3
+ packager: "npm" | "pnpm" | "yarn" | "bun";
4
+ /** The root directory of the monorepo, used to locate package.json. */
5
+ monorepoRoot: string;
6
+ };
7
+ export type WranglerTarget = "local" | "remote";
8
+ export type WranglerCommandResult = {
9
+ success: boolean;
10
+ stdout: string;
11
+ stderr: string;
12
+ };
13
+ type WranglerOptions = {
14
+ target?: WranglerTarget;
15
+ environment?: string;
16
+ configPath?: string;
17
+ logging?: "all" | "error" | "none";
18
+ env?: Record<string, string>;
19
+ };
20
+ /**
21
+ * Runs a wrangler command using the project's package manager.
22
+ *
23
+ * Spawns a synchronous child process, appending the provided arguments and any flags derived
24
+ * from the wrangler options.
25
+ *
26
+ * The `.env` file loading by wrangler is disabled to let the adapter handle environment variables.
27
+ *
28
+ * @param options The package manager details used to invoke wrangler.
29
+ * @param args The CLI arguments to pass to wrangler
30
+ * @param wranglerOpts Optional configuration for the wrangler invocation.
31
+ * @param wranglerOpts.target Whether to run wrangler in `"local"` or `"remote"` mode
32
+ * @param wranglerOpts.environment The wrangler environment name
33
+ * @param wranglerOpts.configPath Path to a wrangler configuration file
34
+ * @param wranglerOpts.logging Controls stdio behavior:
35
+ * - `"all"` inherits stdin/stdout for interactive use,
36
+ * - `"error"` pipes all output and only displays it on failure,
37
+ * - `"none"` suppresses all output.
38
+ * When not specified, behaves the same as `"all"`.
39
+ * @param wranglerOpts.env Additional environment variables to pass to the spawned process.
40
+ * @returns The command result
41
+ */
42
+ export declare function runWrangler(options: PackagerDetails, args: string[], wranglerOpts?: WranglerOptions): WranglerCommandResult;
43
+ export declare function isWranglerTarget(v: string | undefined): v is WranglerTarget;
44
+ export {};
@@ -2,15 +2,14 @@ import { spawnSync } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { compareSemver } from "@opennextjs/aws/build/helper.js";
5
- import logger from "@opennextjs/aws/logger.js";
6
5
  /**
7
6
  * Checks the package.json `packageManager` field to determine whether yarn modern is used.
8
7
  *
9
8
  * @param options Build options.
10
9
  * @returns Whether yarn modern is used.
11
10
  */
12
- function isYarnModern(options) {
13
- const packageJson = JSON.parse(readFileSync(path.join(options.monorepoRoot, "package.json"), "utf-8"));
11
+ function isYarnModern(monorepoRoot) {
12
+ const packageJson = JSON.parse(readFileSync(path.join(monorepoRoot, "package.json"), "utf-8"));
14
13
  if (!packageJson.packageManager?.startsWith("yarn"))
15
14
  return false;
16
15
  const [, version] = packageJson.packageManager.split("@");
@@ -27,7 +26,7 @@ function isYarnModern(options) {
27
26
  * @returns Arguments with a passthrough flag injected when needed.
28
27
  */
29
28
  function injectPassthroughFlagForArgs(options, args) {
30
- if (options.packager !== "npm" && (options.packager !== "yarn" || isYarnModern(options))) {
29
+ if (options.packager !== "npm" && (options.packager !== "yarn" || isYarnModern(options.monorepoRoot))) {
31
30
  return args;
32
31
  }
33
32
  const flagInArgsIndex = args.findIndex((v) => v.startsWith("--"));
@@ -36,7 +35,30 @@ function injectPassthroughFlagForArgs(options, args) {
36
35
  }
37
36
  return args;
38
37
  }
38
+ /**
39
+ * Runs a wrangler command using the project's package manager.
40
+ *
41
+ * Spawns a synchronous child process, appending the provided arguments and any flags derived
42
+ * from the wrangler options.
43
+ *
44
+ * The `.env` file loading by wrangler is disabled to let the adapter handle environment variables.
45
+ *
46
+ * @param options The package manager details used to invoke wrangler.
47
+ * @param args The CLI arguments to pass to wrangler
48
+ * @param wranglerOpts Optional configuration for the wrangler invocation.
49
+ * @param wranglerOpts.target Whether to run wrangler in `"local"` or `"remote"` mode
50
+ * @param wranglerOpts.environment The wrangler environment name
51
+ * @param wranglerOpts.configPath Path to a wrangler configuration file
52
+ * @param wranglerOpts.logging Controls stdio behavior:
53
+ * - `"all"` inherits stdin/stdout for interactive use,
54
+ * - `"error"` pipes all output and only displays it on failure,
55
+ * - `"none"` suppresses all output.
56
+ * When not specified, behaves the same as `"all"`.
57
+ * @param wranglerOpts.env Additional environment variables to pass to the spawned process.
58
+ * @returns The command result
59
+ */
39
60
  export function runWrangler(options, args, wranglerOpts = {}) {
61
+ const noLogs = wranglerOpts.logging === "none";
40
62
  const shouldPipeLogs = wranglerOpts.logging === "error";
41
63
  const result = spawnSync(options.packager, [
42
64
  options.packager === "bun" ? "x" : "exec",
@@ -50,7 +72,10 @@ export function runWrangler(options, args, wranglerOpts = {}) {
50
72
  ].filter((v) => !!v)),
51
73
  ], {
52
74
  shell: true,
53
- stdio: shouldPipeLogs ? ["ignore", "pipe", "pipe"] : "inherit",
75
+ // Always pipe stderr so that we can capture it for inspection.
76
+ // Keep stdin and stdout as "inherit" when not piping logs to maintain TTY detection
77
+ // (wrangler checks `process.stdin.isTTY && process.stdout.isTTY` for interactive mode).
78
+ stdio: shouldPipeLogs || noLogs ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "pipe"],
54
79
  env: {
55
80
  ...process.env,
56
81
  ...wranglerOpts.env,
@@ -60,14 +85,24 @@ export function runWrangler(options, args, wranglerOpts = {}) {
60
85
  CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV: "false",
61
86
  },
62
87
  });
63
- if (result.status !== 0) {
64
- if (shouldPipeLogs) {
65
- process.stdout.write(result.stdout.toString());
66
- process.stderr.write(result.stderr.toString());
88
+ const success = result.status === 0;
89
+ const stdout = result.stdout?.toString() ?? "";
90
+ const stderr = result.stderr?.toString() ?? "";
91
+ if (!noLogs) {
92
+ // When not piping logs, stderr is captured but should still be visible to the user
93
+ if (!shouldPipeLogs && stderr) {
94
+ process.stderr.write(stderr);
95
+ }
96
+ if (!success && shouldPipeLogs) {
97
+ process.stdout.write(stdout);
98
+ process.stderr.write(stderr);
67
99
  }
68
- logger.error("Wrangler command failed");
69
- process.exit(1);
70
100
  }
101
+ return {
102
+ success,
103
+ stdout,
104
+ stderr,
105
+ };
71
106
  }
72
107
  export function isWranglerTarget(v) {
73
108
  return !!v && ["local", "remote"].includes(v);
@@ -1,6 +1,5 @@
1
- import * as buildHelper from "@opennextjs/aws/build/helper.js";
2
1
  import type yargs from "yargs";
3
- import type { OpenNextConfig } from "../../api/config.js";
2
+ import type { OpenNextConfig } from "../../../api/config.js";
4
3
  export type WithWranglerArgs<T = unknown> = T & {
5
4
  wranglerArgs: string[];
6
5
  wranglerConfigPath: string | undefined;
@@ -13,15 +12,6 @@ export declare const nextAppDir: string;
13
12
  * @param command
14
13
  */
15
14
  export declare function printHeaders(command: string): void;
16
- /**
17
- * Validates that the Next.js version is supported and checks wrangler compatibility.
18
- *
19
- * Note: this function assumes that wrangler is installed.
20
- *
21
- * @param options.nextVersion The detected Next.js version string
22
- * @throws {Error} If the Next.js version is unsupported
23
- */
24
- export declare function ensureNextjsVersionSupported({ nextVersion, }: Pick<buildHelper.BuildOptions, "nextVersion">): Promise<void>;
25
15
  /**
26
16
  * Compile the OpenNext config.
27
17
  *
@@ -4,11 +4,11 @@ import path from "node:path";
4
4
  import url from "node:url";
5
5
  import { compileOpenNextConfig } from "@opennextjs/aws/build/compileConfig.js";
6
6
  import { normalizeOptions } from "@opennextjs/aws/build/helper.js";
7
- import * as buildHelper from "@opennextjs/aws/build/helper.js";
8
7
  import { printHeader, showWarningOnWindows } from "@opennextjs/aws/build/utils.js";
9
8
  import logger from "@opennextjs/aws/logger.js";
10
9
  import { unstable_readConfig } from "wrangler";
11
- import { createOpenNextConfigIfNotExistent, ensureCloudflareConfig } from "../build/utils/index.js";
10
+ import { ensureCloudflareConfig } from "../../build/utils/ensure-cf-config.js";
11
+ import { createOpenNextConfigIfNotExistent } from "../../utils/create-config-files.js";
12
12
  export const nextAppDir = process.cwd();
13
13
  /**
14
14
  * Print headers and warnings for the CLI.
@@ -19,28 +19,6 @@ export function printHeaders(command) {
19
19
  printHeader(`Cloudflare ${command}`);
20
20
  showWarningOnWindows();
21
21
  }
22
- /**
23
- * Validates that the Next.js version is supported and checks wrangler compatibility.
24
- *
25
- * Note: this function assumes that wrangler is installed.
26
- *
27
- * @param options.nextVersion The detected Next.js version string
28
- * @throws {Error} If the Next.js version is unsupported
29
- */
30
- export async function ensureNextjsVersionSupported({ nextVersion, }) {
31
- if (buildHelper.compareSemver(nextVersion, "<", "14.2.0")) {
32
- throw new Error("Next.js version unsupported, please upgrade to version 14.2 or greater.");
33
- }
34
- const { default: { version: wranglerVersion }, } = await import("wrangler/package.json", { with: { type: "json" } });
35
- // We need a version of workerd that has a fix for setImmediate for Next.js 16.1+
36
- // See:
37
- // - https://github.com/cloudflare/workerd/pull/5869
38
- // - https://github.com/opennextjs/opennextjs-cloudflare/issues/1049
39
- if (buildHelper.compareSemver(nextVersion, ">=", "16.1.0") &&
40
- buildHelper.compareSemver(wranglerVersion, "<", "4.59.2")) {
41
- logger.warn(`Next.js 16.1+ requires wrangler 4.59.2 or greater (${wranglerVersion} detected).`);
42
- }
43
- }
44
22
  /**
45
23
  * Compile the OpenNext config.
46
24
  *
@@ -1,4 +1,4 @@
1
- import type { WranglerTarget } from "./utils/run-wrangler.js";
1
+ import type { WranglerTarget } from "./commands/utils/run-wrangler.js";
2
2
  export type ProjectOptions = {
3
3
  sourceDir: string;
4
4
  skipNextBuild: boolean;