@opennextjs/cloudflare 0.0.0-9a03245 → 0.0.0-9aff12e

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Deploy Next.js apps to Cloudflare!
4
4
 
5
- OpenNext for Cloudflare is Cloudflare specific adapter that enables deployment of Next.js applications to Cloudflare.
5
+ [OpenNext for Cloudflare](https://opennext.js.org/cloudflare) is Cloudflare specific adapter that enables deployment of Next.js applications to Cloudflare.
6
6
 
7
7
  ## Getting started
8
8
 
@@ -13,7 +13,13 @@ You can use [`create-next-app`](https://nextjs.org/docs/pages/api-reference/cli/
13
13
  - add the following `devDependencies` to the `package.json`:
14
14
 
15
15
  ```bash
16
+ npm add -D wrangler@latest @opennextjs/cloudflare
17
+ # or
16
18
  pnpm add -D wrangler@latest @opennextjs/cloudflare
19
+ # or
20
+ yarn add -D wrangler@latest @opennextjs/cloudflare
21
+ # or
22
+ bun add -D wrangler@latest @opennextjs/cloudflare
17
23
  ```
18
24
 
19
25
  - add a `wrangler.toml` at the root of your project
@@ -27,7 +33,7 @@ You can use [`create-next-app`](https://nextjs.org/docs/pages/api-reference/cli/
27
33
  compatibility_flags = ["nodejs_compat"]
28
34
 
29
35
  # Use the new Workers + Assets to host the static frontend files
30
- experimental_assets = { directory = ".worker-next/assets", binding = "ASSETS" }
36
+ assets = { directory = ".worker-next/assets", binding = "ASSETS" }
31
37
  ```
32
38
 
33
39
  You can enable Incremental Static Regeneration ([ISR](https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration)) by adding a KV binding named `NEXT_CACHE_WORKERS_KV` to your `wrangler.toml`:
@@ -36,6 +42,12 @@ You can enable Incremental Static Regeneration ([ISR](https://nextjs.org/docs/ap
36
42
 
37
43
  ```bash
38
44
  npx wrangler kv namespace create NEXT_CACHE_WORKERS_KV
45
+ # or
46
+ pnpm wrangler kv namespace create NEXT_CACHE_WORKERS_KV
47
+ # or
48
+ yarn wrangler kv namespace create NEXT_CACHE_WORKERS_KV
49
+ # or
50
+ bun wrangler kv namespace create NEXT_CACHE_WORKERS_KV
39
51
  ```
40
52
 
41
53
  - Paste the snippet to your `wrangler.toml`:
@@ -60,13 +72,25 @@ Run the following commands to preview the production build of your application l
60
72
  - build the app and adapt it for Cloudflare
61
73
 
62
74
  ```bash
63
- pnpx cloudflare
75
+ npx cloudflare
76
+ # or
77
+ pnpm cloudflare
78
+ # or
79
+ yarn cloudflare
80
+ # or
81
+ bun cloudflare
64
82
  ```
65
83
 
66
84
  - Preview the app in Wrangler
67
85
 
68
86
  ```bash
87
+ npx wrangler dev
88
+ # or
69
89
  pnpm wrangler dev
90
+ # or
91
+ yarn wrangler dev
92
+ # or
93
+ bun wrangler dev
70
94
  ```
71
95
 
72
96
  ## Deploy your app
@@ -76,9 +100,11 @@ Deploy your application to production with the following:
76
100
  - build the app and adapt it for Cloudflare
77
101
 
78
102
  ```bash
79
- pnpx cloudflare
80
- ```
81
-
82
- ```bash
83
- pnpm wrangler deploy
103
+ npx cloudflare && npx wrangler deploy
104
+ # or
105
+ pnpm cloudflare && pnpm wrangler deploy
106
+ # or
107
+ yarn cloudflare && yarn wrangler deploy
108
+ # or
109
+ bun cloudflare && bun wrangler deploy
84
110
  ```
@@ -18,7 +18,7 @@ var CfWorkersKvCacheHandler = class _CfWorkersKvCacheHandler {
18
18
  return null;
19
19
  }
20
20
  }
21
- async set(key, entry, ctx) {
21
+ async set(key, entry, _ctx) {
22
22
  if (_CfWorkersKvCacheHandler.maybeKVNamespace === void 0) {
23
23
  return;
24
24
  }
@@ -213,68 +213,169 @@ var require_brace_expansion = __commonJS({
213
213
  }
214
214
  });
215
215
 
216
- // src/cli/index.ts
217
- import { resolve as resolve2 } from "node:path";
218
-
219
- // src/cli/args.ts
220
- import { mkdirSync, statSync } from "node:fs";
221
- import { parseArgs } from "node:util";
222
- import { resolve } from "node:path";
223
- function getArgs() {
224
- const {
225
- values: { skipBuild: skipBuild2, output }
226
- } = parseArgs({
227
- options: {
228
- skipBuild: {
229
- type: "boolean",
230
- short: "s",
231
- default: false
232
- },
233
- output: {
234
- type: "string",
235
- short: "o"
236
- }
237
- },
238
- allowPositionals: false
239
- });
240
- const outputDir2 = output ? resolve(output) : void 0;
241
- if (outputDir2) {
242
- assertDirArg(outputDir2, "output", true);
216
+ // src/cli/config.ts
217
+ import path, { relative } from "node:path";
218
+ import { readdirSync, statSync } from "node:fs";
219
+ var PACKAGE_NAME = "@opennextjs/cloudflare";
220
+ var UserConfig = {
221
+ cache: {
222
+ bindingName: "NEXT_CACHE_WORKERS_KV"
243
223
  }
224
+ };
225
+ function getConfig(appDir, outputDir2) {
226
+ const dotNext = path.join(outputDir2, ".next");
227
+ const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
228
+ const standaloneApp = path.join(dotNext, "standalone", appPath);
229
+ const standaloneAppDotNext = path.join(standaloneApp, ".next");
230
+ const standaloneAppServer = path.join(standaloneAppDotNext, "server");
231
+ const nodeModules = path.join(standaloneApp, "node_modules");
232
+ const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/"));
244
233
  return {
245
- outputDir: outputDir2,
246
- skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
234
+ paths: {
235
+ nextApp: appDir,
236
+ builderOutput: outputDir2,
237
+ dotNext,
238
+ standaloneApp,
239
+ standaloneAppDotNext,
240
+ standaloneAppServer,
241
+ internalPackage
242
+ },
243
+ cache: {
244
+ kvBindingName: UserConfig.cache.bindingName
245
+ },
246
+ internalPackageName: PACKAGE_NAME
247
247
  };
248
248
  }
249
- function assertDirArg(path13, argName, make) {
250
- let dirStats;
249
+ function containsDotNextDir(folder) {
251
250
  try {
252
- dirStats = statSync(path13);
251
+ return statSync(path.join(folder, ".next")).isDirectory();
253
252
  } catch {
254
- if (!make) {
255
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
253
+ return false;
254
+ }
255
+ }
256
+ function getNextjsApplicationPath(dotNextDir) {
257
+ const serverPath = findServerParentPath(dotNextDir);
258
+ if (!serverPath) {
259
+ throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
260
+ }
261
+ return relative(path.join(dotNextDir, "standalone"), serverPath);
262
+ }
263
+ function findServerParentPath(parentPath) {
264
+ try {
265
+ if (statSync(path.join(parentPath, ".next", "server")).isDirectory()) {
266
+ return parentPath;
256
267
  }
257
- mkdirSync(path13);
258
- return;
268
+ } catch {
259
269
  }
260
- if (!dirStats.isDirectory()) {
261
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
270
+ const folders = readdirSync(parentPath);
271
+ for (const folder of folders) {
272
+ const subFolder = path.join(parentPath, folder);
273
+ if (statSync(path.join(parentPath, folder)).isDirectory()) {
274
+ const dirServerPath = findServerParentPath(subFolder);
275
+ if (dirServerPath) {
276
+ return dirServerPath;
277
+ }
278
+ }
262
279
  }
263
280
  }
264
281
 
265
- // src/cli/index.ts
266
- import { existsSync as existsSync4 } from "node:fs";
282
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/constants.mjs
283
+ var AGENTS = [
284
+ "npm",
285
+ "yarn",
286
+ "yarn@berry",
287
+ "pnpm",
288
+ "pnpm@6",
289
+ "bun"
290
+ ];
291
+ var LOCKS = {
292
+ "bun.lockb": "bun",
293
+ "pnpm-lock.yaml": "pnpm",
294
+ "yarn.lock": "yarn",
295
+ "package-lock.json": "npm",
296
+ "npm-shrinkwrap.json": "npm"
297
+ };
267
298
 
268
- // src/cli/build/index.ts
269
- import { rm } from "node:fs/promises";
299
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/detect.mjs
300
+ import fs from "node:fs";
301
+ import fsPromises from "node:fs/promises";
302
+ import path2 from "node:path";
303
+ import process2 from "node:process";
304
+ async function detect({ cwd, onUnknown } = {}) {
305
+ for (const directory of lookup(cwd)) {
306
+ for (const lock of Object.keys(LOCKS)) {
307
+ if (await fileExists(path2.join(directory, lock))) {
308
+ const name = LOCKS[lock];
309
+ const result2 = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
310
+ if (result2)
311
+ return result2;
312
+ else
313
+ return { name, agent: name };
314
+ }
315
+ }
316
+ const result = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
317
+ if (result)
318
+ return result;
319
+ }
320
+ return null;
321
+ }
322
+ function* lookup(cwd = process2.cwd()) {
323
+ let directory = path2.resolve(cwd);
324
+ const { root } = path2.parse(directory);
325
+ while (directory && directory !== root) {
326
+ yield directory;
327
+ directory = path2.dirname(directory);
328
+ }
329
+ }
330
+ async function parsePackageJson(filepath, onUnknown) {
331
+ if (!filepath || !await fileExists(filepath))
332
+ return null;
333
+ try {
334
+ const pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
335
+ let agent;
336
+ if (typeof pkg.packageManager === "string") {
337
+ const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
338
+ let version = ver;
339
+ if (name === "yarn" && Number.parseInt(ver) > 1) {
340
+ agent = "yarn@berry";
341
+ version = "berry";
342
+ return { name, agent, version };
343
+ } else if (name === "pnpm" && Number.parseInt(ver) < 7) {
344
+ agent = "pnpm@6";
345
+ return { name, agent, version };
346
+ } else if (AGENTS.includes(name)) {
347
+ agent = name;
348
+ return { name, agent, version };
349
+ } else {
350
+ return onUnknown?.(pkg.packageManager) ?? null;
351
+ }
352
+ }
353
+ } catch {
354
+ }
355
+ return null;
356
+ }
357
+ async function fileExists(filePath) {
358
+ try {
359
+ const stats = await fsPromises.stat(filePath);
360
+ if (stats.isFile()) {
361
+ return true;
362
+ }
363
+ } catch {
364
+ }
365
+ return false;
366
+ }
270
367
 
271
368
  // src/cli/build/build-next-app.ts
272
369
  import { execSync } from "node:child_process";
273
- function buildNextjsApp(nextAppDir2) {
274
- runNextBuildCommand("pnpm", nextAppDir2);
370
+ async function buildNextjsApp(nextAppDir2) {
371
+ const pm = await detect();
372
+ if (!pm) {
373
+ throw new Error("Fatal Error: package manager detection failed, aborting");
374
+ }
375
+ runNextBuildCommand(pm.name, nextAppDir2);
275
376
  }
276
377
  function runNextBuildCommand(packager, nextAppDir2) {
277
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
378
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
278
379
  execSync(command, {
279
380
  stdio: "inherit",
280
381
  cwd: nextAppDir2,
@@ -289,29 +390,21 @@ function runNextBuildCommand(packager, nextAppDir2) {
289
390
 
290
391
  // src/cli/build/build-worker.ts
291
392
  import { build } from "esbuild";
292
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
293
393
  import { cp, readFile, writeFile } from "node:fs/promises";
294
- import path10 from "node:path";
295
- import { fileURLToPath as fileURLToPath3 } from "node:url";
296
-
297
- // src/cli/build/patches/investigated/patch-require.ts
298
- function patchRequire(code) {
299
- console.log("# patchRequire");
300
- return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
301
- }
394
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
302
395
 
303
396
  // src/cli/build/patches/investigated/copy-package-cli-files.ts
304
397
  import { cpSync } from "node:fs";
305
- import path from "node:path";
398
+ import path3 from "node:path";
306
399
  function copyPackageCliFiles(packageDistDir2, config) {
307
400
  console.log("# copyPackageTemplateFiles");
308
- const sourceDir = path.join(packageDistDir2, "cli");
309
- const destinationDir = path.join(config.paths.internalPackage, "cli");
401
+ const sourceDir = path3.join(packageDistDir2, "cli");
402
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
310
403
  cpSync(sourceDir, destinationDir, { recursive: true });
311
404
  }
312
405
 
313
- // src/cli/build/patches/to-investigate/patch-read-file.ts
314
- import { readFileSync } from "node:fs";
406
+ // src/cli/build/build-worker.ts
407
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
315
408
 
316
409
  // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
317
410
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
@@ -984,11 +1077,11 @@ var qmarksTestNoExtDot = ([$0]) => {
984
1077
  return (f) => f.length === len && f !== "." && f !== "..";
985
1078
  };
986
1079
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
987
- var path2 = {
1080
+ var path4 = {
988
1081
  win32: { sep: "\\" },
989
1082
  posix: { sep: "/" }
990
1083
  };
991
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1084
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
992
1085
  minimatch.sep = sep;
993
1086
  var GLOBSTAR = Symbol("globstar **");
994
1087
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -3018,7 +3111,7 @@ var LRUCache = class _LRUCache {
3018
3111
  // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3019
3112
  import { posix, win32 } from "node:path";
3020
3113
  import { fileURLToPath } from "node:url";
3021
- import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
3114
+ import { lstatSync, readdir as readdirCB, readdirSync as readdirSync2, readlinkSync, realpathSync as rps } from "fs";
3022
3115
  import * as actualFS from "node:fs";
3023
3116
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3024
3117
 
@@ -3905,7 +3998,7 @@ var realpathSync = rps.native;
3905
3998
  var defaultFS = {
3906
3999
  lstatSync,
3907
4000
  readdir: readdirCB,
3908
- readdirSync,
4001
+ readdirSync: readdirSync2,
3909
4002
  readlinkSync,
3910
4003
  realpathSync,
3911
4004
  promises: {
@@ -4165,12 +4258,12 @@ var PathBase = class {
4165
4258
  /**
4166
4259
  * Get the Path object referenced by the string path, resolved from this Path
4167
4260
  */
4168
- resolve(path13) {
4169
- if (!path13) {
4261
+ resolve(path14) {
4262
+ if (!path14) {
4170
4263
  return this;
4171
4264
  }
4172
- const rootPath = this.getRootString(path13);
4173
- const dir = path13.substring(rootPath.length);
4265
+ const rootPath = this.getRootString(path14);
4266
+ const dir = path14.substring(rootPath.length);
4174
4267
  const dirParts = dir.split(this.splitSep);
4175
4268
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4176
4269
  return result;
@@ -4922,8 +5015,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4922
5015
  /**
4923
5016
  * @internal
4924
5017
  */
4925
- getRootString(path13) {
4926
- return win32.parse(path13).root;
5018
+ getRootString(path14) {
5019
+ return win32.parse(path14).root;
4927
5020
  }
4928
5021
  /**
4929
5022
  * @internal
@@ -4969,8 +5062,8 @@ var PathPosix = class _PathPosix extends PathBase {
4969
5062
  /**
4970
5063
  * @internal
4971
5064
  */
4972
- getRootString(path13) {
4973
- return path13.startsWith("/") ? "/" : "";
5065
+ getRootString(path14) {
5066
+ return path14.startsWith("/") ? "/" : "";
4974
5067
  }
4975
5068
  /**
4976
5069
  * @internal
@@ -5019,8 +5112,8 @@ var PathScurryBase = class {
5019
5112
  *
5020
5113
  * @internal
5021
5114
  */
5022
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
5023
- this.#fs = fsFromOption(fs2);
5115
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs3 = defaultFS } = {}) {
5116
+ this.#fs = fsFromOption(fs3);
5024
5117
  if (cwd instanceof URL || cwd.startsWith("file://")) {
5025
5118
  cwd = fileURLToPath(cwd);
5026
5119
  }
@@ -5059,11 +5152,11 @@ var PathScurryBase = class {
5059
5152
  /**
5060
5153
  * Get the depth of a provided path, string, or the cwd
5061
5154
  */
5062
- depth(path13 = this.cwd) {
5063
- if (typeof path13 === "string") {
5064
- path13 = this.cwd.resolve(path13);
5155
+ depth(path14 = this.cwd) {
5156
+ if (typeof path14 === "string") {
5157
+ path14 = this.cwd.resolve(path14);
5065
5158
  }
5066
- return path13.depth();
5159
+ return path14.depth();
5067
5160
  }
5068
5161
  /**
5069
5162
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5442,7 +5535,7 @@ var PathScurryBase = class {
5442
5535
  const dirs = /* @__PURE__ */ new Set();
5443
5536
  const queue = [entry];
5444
5537
  let processing = 0;
5445
- const process2 = () => {
5538
+ const process3 = () => {
5446
5539
  let paused = false;
5447
5540
  while (!paused) {
5448
5541
  const dir = queue.shift();
@@ -5483,9 +5576,9 @@ var PathScurryBase = class {
5483
5576
  }
5484
5577
  }
5485
5578
  if (paused && !results.flowing) {
5486
- results.once("drain", process2);
5579
+ results.once("drain", process3);
5487
5580
  } else if (!sync2) {
5488
- process2();
5581
+ process3();
5489
5582
  }
5490
5583
  };
5491
5584
  let sync2 = true;
@@ -5493,7 +5586,7 @@ var PathScurryBase = class {
5493
5586
  sync2 = false;
5494
5587
  }
5495
5588
  };
5496
- process2();
5589
+ process3();
5497
5590
  return results;
5498
5591
  }
5499
5592
  streamSync(entry = this.cwd, opts = {}) {
@@ -5511,7 +5604,7 @@ var PathScurryBase = class {
5511
5604
  }
5512
5605
  const queue = [entry];
5513
5606
  let processing = 0;
5514
- const process2 = () => {
5607
+ const process3 = () => {
5515
5608
  let paused = false;
5516
5609
  while (!paused) {
5517
5610
  const dir = queue.shift();
@@ -5545,14 +5638,14 @@ var PathScurryBase = class {
5545
5638
  }
5546
5639
  }
5547
5640
  if (paused && !results.flowing)
5548
- results.once("drain", process2);
5641
+ results.once("drain", process3);
5549
5642
  };
5550
- process2();
5643
+ process3();
5551
5644
  return results;
5552
5645
  }
5553
- chdir(path13 = this.cwd) {
5646
+ chdir(path14 = this.cwd) {
5554
5647
  const oldCwd = this.cwd;
5555
- this.cwd = typeof path13 === "string" ? this.cwd.resolve(path13) : path13;
5648
+ this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
5556
5649
  this.cwd[setAsCwd](oldCwd);
5557
5650
  }
5558
5651
  };
@@ -5578,8 +5671,8 @@ var PathScurryWin32 = class extends PathScurryBase {
5578
5671
  /**
5579
5672
  * @internal
5580
5673
  */
5581
- newRoot(fs2) {
5582
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5674
+ newRoot(fs3) {
5675
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5583
5676
  }
5584
5677
  /**
5585
5678
  * Return true if the provided path string is an absolute path
@@ -5607,8 +5700,8 @@ var PathScurryPosix = class extends PathScurryBase {
5607
5700
  /**
5608
5701
  * @internal
5609
5702
  */
5610
- newRoot(fs2) {
5611
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5703
+ newRoot(fs3) {
5704
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5612
5705
  }
5613
5706
  /**
5614
5707
  * Return true if the provided path string is an absolute path
@@ -5908,8 +6001,8 @@ var MatchRecord = class {
5908
6001
  }
5909
6002
  // match, absolute, ifdir
5910
6003
  entries() {
5911
- return [...this.store.entries()].map(([path13, n]) => [
5912
- path13,
6004
+ return [...this.store.entries()].map(([path14, n]) => [
6005
+ path14,
5913
6006
  !!(n & 2),
5914
6007
  !!(n & 1)
5915
6008
  ]);
@@ -6114,9 +6207,9 @@ var GlobUtil = class {
6114
6207
  signal;
6115
6208
  maxDepth;
6116
6209
  includeChildMatches;
6117
- constructor(patterns, path13, opts) {
6210
+ constructor(patterns, path14, opts) {
6118
6211
  this.patterns = patterns;
6119
- this.path = path13;
6212
+ this.path = path14;
6120
6213
  this.opts = opts;
6121
6214
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6122
6215
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6135,11 +6228,11 @@ var GlobUtil = class {
6135
6228
  });
6136
6229
  }
6137
6230
  }
6138
- #ignored(path13) {
6139
- return this.seen.has(path13) || !!this.#ignore?.ignored?.(path13);
6231
+ #ignored(path14) {
6232
+ return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
6140
6233
  }
6141
- #childrenIgnored(path13) {
6142
- return !!this.#ignore?.childrenIgnored?.(path13);
6234
+ #childrenIgnored(path14) {
6235
+ return !!this.#ignore?.childrenIgnored?.(path14);
6143
6236
  }
6144
6237
  // backpressure mechanism
6145
6238
  pause() {
@@ -6354,8 +6447,8 @@ var GlobUtil = class {
6354
6447
  };
6355
6448
  var GlobWalker = class extends GlobUtil {
6356
6449
  matches = /* @__PURE__ */ new Set();
6357
- constructor(patterns, path13, opts) {
6358
- super(patterns, path13, opts);
6450
+ constructor(patterns, path14, opts) {
6451
+ super(patterns, path14, opts);
6359
6452
  }
6360
6453
  matchEmit(e) {
6361
6454
  this.matches.add(e);
@@ -6392,8 +6485,8 @@ var GlobWalker = class extends GlobUtil {
6392
6485
  };
6393
6486
  var GlobStream = class extends GlobUtil {
6394
6487
  results;
6395
- constructor(patterns, path13, opts) {
6396
- super(patterns, path13, opts);
6488
+ constructor(patterns, path14, opts) {
6489
+ super(patterns, path14, opts);
6397
6490
  this.results = new Minipass({
6398
6491
  signal: this.signal,
6399
6492
  objectMode: true
@@ -6686,67 +6779,44 @@ var glob = Object.assign(glob_, {
6686
6779
  });
6687
6780
  glob.glob = glob;
6688
6781
 
6689
- // src/cli/build/patches/to-investigate/patch-read-file.ts
6690
- import path3 from "node:path";
6691
- function patchReadFile(code, config) {
6692
- console.log("# patchReadFile");
6693
- code = code.replace(
6694
- "getBuildId() {",
6695
- `getBuildId() {
6696
- return ${JSON.stringify(readFileSync(path3.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6697
- `
6698
- );
6699
- const manifestJsons = globSync(path3.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6700
- (file) => file.replace(config.paths.standaloneApp + "/", "")
6701
- );
6702
- code = code.replace(
6703
- /function loadManifest\((.+?), .+?\) {/,
6782
+ // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6783
+ import path5 from "node:path";
6784
+ function inlineEvalManifest(code, config) {
6785
+ console.log("# inlineEvalManifest");
6786
+ const manifestJss = globSync(
6787
+ path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6788
+ ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6789
+ return code.replace(
6790
+ /function evalManifest\((.+?), .+?\) {/,
6704
6791
  `$&
6705
- ${manifestJsons.map(
6706
- (manifestJson) => `
6707
- if ($1.endsWith("${manifestJson}")) {
6708
- return ${readFileSync(path3.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6709
- }
6710
- `
6792
+ ${manifestJss.map(
6793
+ (manifestJs) => `
6794
+ if ($1.endsWith("${manifestJs}")) {
6795
+ require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6796
+ return {
6797
+ __RSC_MANIFEST: {
6798
+ "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6799
+ },
6800
+ };
6801
+ }
6802
+ `
6711
6803
  ).join("\n")}
6712
- throw new Error("Unknown loadManifest: " + $1);
6713
- `
6714
- );
6715
- return code;
6716
- }
6717
-
6718
- // src/cli/build/patches/to-investigate/patch-find-dir.ts
6719
- import path4 from "node:path";
6720
- import { existsSync } from "node:fs";
6721
- function patchFindDir(code, config) {
6722
- console.log("# patchFindDir");
6723
- return code.replace(
6724
- "function findDir(dir, name) {",
6725
- `function findDir(dir, name) {
6726
- if (dir.endsWith(".next/server")) {
6727
- if (name === "app") {
6728
- return ${existsSync(`${path4.join(config.paths.standaloneAppServer, "app")}`)};
6729
- }
6730
- if (name === "pages") {
6731
- return ${existsSync(`${path4.join(config.paths.standaloneAppServer, "pages")}`)};
6732
- }
6733
- }
6734
- throw new Error("Unknown findDir call: " + dir + " " + name);
6804
+ throw new Error("Unknown evalManifest: " + $1);
6735
6805
  `
6736
6806
  );
6737
6807
  }
6738
6808
 
6739
6809
  // src/cli/build/patches/to-investigate/inline-next-require.ts
6740
- import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
6741
- import path5 from "node:path";
6810
+ import { existsSync, readFileSync } from "node:fs";
6811
+ import path6 from "node:path";
6742
6812
  function inlineNextRequire(code, config) {
6743
6813
  console.log("# inlineNextRequire");
6744
- const pagesManifestFile = path5.join(config.paths.standaloneAppServer, "pages-manifest.json");
6745
- const appPathsManifestFile = path5.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6746
- const pagesManifestFiles = existsSync2(pagesManifestFile) ? Object.values(JSON.parse(readFileSync2(pagesManifestFile, "utf-8"))).map(
6814
+ const pagesManifestFile = path6.join(config.paths.standaloneAppServer, "pages-manifest.json");
6815
+ const appPathsManifestFile = path6.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6816
+ const pagesManifestFiles = existsSync(pagesManifestFile) ? Object.values(JSON.parse(readFileSync(pagesManifestFile, "utf-8"))).map(
6747
6817
  (file) => ".next/server/" + file
6748
6818
  ) : [];
6749
- const appPathsManifestFiles = existsSync2(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync2(appPathsManifestFile, "utf-8"))).map(
6819
+ const appPathsManifestFiles = existsSync(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync(appPathsManifestFile, "utf-8"))).map(
6750
6820
  (file) => ".next/server/" + file
6751
6821
  ) : [];
6752
6822
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6758,14 +6828,14 @@ function inlineNextRequire(code, config) {
6758
6828
  ${htmlPages.map(
6759
6829
  (htmlPage) => `
6760
6830
  if (pagePath.endsWith("${htmlPage}")) {
6761
- return ${JSON.stringify(readFileSync2(path5.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6831
+ return ${JSON.stringify(readFileSync(path6.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6762
6832
  }
6763
6833
  `
6764
6834
  ).join("\n")}
6765
6835
  ${pageModules.map(
6766
6836
  (module) => `
6767
6837
  if (pagePath.endsWith("${module}")) {
6768
- return require("${path5.join(config.paths.standaloneApp, module)}");
6838
+ return require("${path6.join(config.paths.standaloneApp, module)}");
6769
6839
  }
6770
6840
  `
6771
6841
  ).join("\n")}
@@ -6774,39 +6844,87 @@ function inlineNextRequire(code, config) {
6774
6844
  );
6775
6845
  }
6776
6846
 
6777
- // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6778
- import path6 from "node:path";
6779
- function inlineEvalManifest(code, config) {
6780
- console.log("# inlineEvalManifest");
6781
- const manifestJss = globSync(
6782
- path6.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6783
- ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6847
+ // src/cli/build/patches/investigated/patch-cache.ts
6848
+ import path7 from "node:path";
6849
+ function patchCache(code, config) {
6850
+ console.log("# patchCached");
6851
+ const cacheHandler = path7.join(config.paths.internalPackage, "cli", "cache-handler.mjs");
6852
+ const patchedCode = code.replace(
6853
+ "const { cacheHandler } = this.nextConfig;",
6854
+ `const cacheHandler = null;
6855
+ CacheHandler = (await import('${cacheHandler}')).default;
6856
+ CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6857
+ `
6858
+ );
6859
+ if (patchedCode === code) {
6860
+ throw new Error("Cache patch not applied");
6861
+ }
6862
+ return patchedCode;
6863
+ }
6864
+
6865
+ // src/cli/build/patches/to-investigate/patch-find-dir.ts
6866
+ import { existsSync as existsSync2 } from "node:fs";
6867
+ import path8 from "node:path";
6868
+ function patchFindDir(code, config) {
6869
+ console.log("# patchFindDir");
6784
6870
  return code.replace(
6785
- /function evalManifest\((.+?), .+?\) {/,
6871
+ "function findDir(dir, name) {",
6872
+ `function findDir(dir, name) {
6873
+ if (dir.endsWith(".next/server")) {
6874
+ if (name === "app") {
6875
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "app")}`)};
6876
+ }
6877
+ if (name === "pages") {
6878
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "pages")}`)};
6879
+ }
6880
+ }
6881
+ throw new Error("Unknown findDir call: " + dir + " " + name);
6882
+ `
6883
+ );
6884
+ }
6885
+
6886
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
6887
+ import path9 from "node:path";
6888
+ import { readFileSync as readFileSync2 } from "node:fs";
6889
+ function patchReadFile(code, config) {
6890
+ console.log("# patchReadFile");
6891
+ code = code.replace(
6892
+ "getBuildId() {",
6893
+ `getBuildId() {
6894
+ return ${JSON.stringify(readFileSync2(path9.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6895
+ `
6896
+ );
6897
+ const manifestJsons = globSync(path9.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6898
+ (file) => file.replace(config.paths.standaloneApp + "/", "")
6899
+ );
6900
+ code = code.replace(
6901
+ /function loadManifest\((.+?), .+?\) {/,
6786
6902
  `$&
6787
- ${manifestJss.map(
6788
- (manifestJs) => `
6789
- if ($1.endsWith("${manifestJs}")) {
6790
- require("${path6.join(config.paths.standaloneApp, manifestJs)}");
6791
- return {
6792
- __RSC_MANIFEST: {
6793
- "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6794
- },
6795
- };
6796
- }
6797
- `
6903
+ ${manifestJsons.map(
6904
+ (manifestJson) => `
6905
+ if ($1.endsWith("${manifestJson}")) {
6906
+ return ${readFileSync2(path9.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6907
+ }
6908
+ `
6798
6909
  ).join("\n")}
6799
- throw new Error("Unknown evalManifest: " + $1);
6800
- `
6910
+ throw new Error("Unknown loadManifest: " + $1);
6911
+ `
6801
6912
  );
6913
+ return code;
6914
+ }
6915
+
6916
+ // src/cli/build/patches/investigated/patch-require.ts
6917
+ function patchRequire(code) {
6918
+ console.log("# patchRequire");
6919
+ return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
6802
6920
  }
6803
6921
 
6804
6922
  // src/cli/build/patches/to-investigate/wrangler-deps.ts
6805
- import path7 from "node:path";
6806
- import fs, { writeFileSync } from "node:fs";
6923
+ import fs2, { writeFileSync } from "node:fs";
6924
+ import path10 from "node:path";
6807
6925
  function patchWranglerDeps(config) {
6808
6926
  console.log("# patchWranglerDeps");
6809
- const pagesRuntimeFile = path7.join(
6927
+ const pagesRuntimeFile = path10.join(
6810
6928
  config.paths.standaloneApp,
6811
6929
  "node_modules",
6812
6930
  "next",
@@ -6815,9 +6933,9 @@ function patchWranglerDeps(config) {
6815
6933
  "next-server",
6816
6934
  "pages.runtime.prod.js"
6817
6935
  );
6818
- const patchedPagesRuntime = fs.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6819
- fs.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6820
- const tracerFile = path7.join(
6936
+ const patchedPagesRuntime = fs2.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6937
+ fs2.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6938
+ const tracerFile = path10.join(
6821
6939
  config.paths.standaloneApp,
6822
6940
  "node_modules",
6823
6941
  "next",
@@ -6827,13 +6945,15 @@ function patchWranglerDeps(config) {
6827
6945
  "trace",
6828
6946
  "tracer.js"
6829
6947
  );
6830
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6948
+ const pacthedTracer = fs2.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6831
6949
  writeFileSync(tracerFile, pacthedTracer);
6832
6950
  }
6833
6951
 
6952
+ // src/cli/build/build-worker.ts
6953
+ import path12 from "node:path";
6954
+
6834
6955
  // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
6835
- import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
6836
- import path8 from "node:path";
6956
+ import { readFileSync as readFileSync3, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
6837
6957
 
6838
6958
  // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6839
6959
  import * as ts from "ts-morph";
@@ -6946,11 +7066,12 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6946
7066
  }
6947
7067
 
6948
7068
  // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7069
+ import path11 from "node:path";
6949
7070
  async function updateWebpackChunksFile(config) {
6950
7071
  console.log("# updateWebpackChunksFile");
6951
- const webpackRuntimeFile = path8.join(config.paths.standaloneAppServer, "webpack-runtime.js");
7072
+ const webpackRuntimeFile = path11.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6952
7073
  const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6953
- const chunks = readdirSync2(path8.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
7074
+ const chunks = readdirSync3(path11.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6954
7075
  console.log(` - chunk ${chunk}`);
6955
7076
  return chunk.replace(/\.js$/, "");
6956
7077
  });
@@ -6958,47 +7079,29 @@ async function updateWebpackChunksFile(config) {
6958
7079
  writeFileSync2(webpackRuntimeFile, updatedFileContent);
6959
7080
  }
6960
7081
 
6961
- // src/cli/build/patches/investigated/patch-cache.ts
6962
- import path9 from "node:path";
6963
- function patchCache(code, config) {
6964
- console.log("# patchCached");
6965
- const cacheHandler = path9.join(config.paths.internalPackage, "cli", "cache-handler.mjs");
6966
- const patchedCode = code.replace(
6967
- "const { cacheHandler } = this.nextConfig;",
6968
- `const cacheHandler = null;
6969
- CacheHandler = (await import('${cacheHandler}')).default;
6970
- CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6971
- `
6972
- );
6973
- if (patchedCode === code) {
6974
- throw new Error("Cache patch not applied");
6975
- }
6976
- return patchedCode;
6977
- }
6978
-
6979
7082
  // src/cli/build/build-worker.ts
6980
- var packageDistDir = path10.join(path10.dirname(fileURLToPath3(import.meta.url)), "..");
7083
+ var packageDistDir = path12.join(path12.dirname(fileURLToPath3(import.meta.url)), "..");
6981
7084
  async function buildWorker(config) {
6982
7085
  console.log(`\x1B[35m\u2699\uFE0F Copying files...
6983
7086
  \x1B[0m`);
6984
7087
  await cp(
6985
- path10.join(config.paths.dotNext, "static"),
6986
- path10.join(config.paths.builderOutput, "assets", "_next", "static"),
7088
+ path12.join(config.paths.dotNext, "static"),
7089
+ path12.join(config.paths.builderOutput, "assets", "_next", "static"),
6987
7090
  {
6988
7091
  recursive: true
6989
7092
  }
6990
7093
  );
6991
- const publicDir = path10.join(config.paths.nextApp, "public");
7094
+ const publicDir = path12.join(config.paths.nextApp, "public");
6992
7095
  if (existsSync3(publicDir)) {
6993
- await cp(publicDir, path10.join(config.paths.builderOutput, "assets"), {
7096
+ await cp(publicDir, path12.join(config.paths.builderOutput, "assets"), {
6994
7097
  recursive: true
6995
7098
  });
6996
7099
  }
6997
7100
  copyPackageCliFiles(packageDistDir, config);
6998
- const templateDir = path10.join(config.paths.internalPackage, "cli", "templates");
6999
- const workerEntrypoint = path10.join(templateDir, "worker.ts");
7000
- const workerOutputFile = path10.join(config.paths.builderOutput, "index.mjs");
7001
- const nextConfigStr = readFileSync4(path10.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
7101
+ const templateDir = path12.join(config.paths.internalPackage, "cli", "templates");
7102
+ const workerEntrypoint = path12.join(templateDir, "worker.ts");
7103
+ const workerOutputFile = path12.join(config.paths.builderOutput, "index.mjs");
7104
+ const nextConfigStr = readFileSync4(path12.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
7002
7105
  /const nextConfig = ({.+?})\n/
7003
7106
  )?.[1] ?? {};
7004
7107
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
@@ -7017,15 +7120,15 @@ async function buildWorker(config) {
7017
7120
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
7018
7121
  // eval("require")("bufferutil");
7019
7122
  // eval("require")("utf-8-validate");
7020
- "next/dist/compiled/ws": path10.join(templateDir, "shims", "empty.ts"),
7123
+ "next/dist/compiled/ws": path12.join(templateDir, "shims", "empty.ts"),
7021
7124
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
7022
7125
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
7023
7126
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
7024
7127
  // QUESTION: Why did I encountered this but mhart didn't?
7025
- "next/dist/compiled/edge-runtime": path10.join(templateDir, "shims", "empty.ts"),
7128
+ "next/dist/compiled/edge-runtime": path12.join(templateDir, "shims", "empty.ts"),
7026
7129
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7027
7130
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7028
- "@next/env": path10.join(templateDir, "shims", "env.ts")
7131
+ "@next/env": path12.join(templateDir, "shims", "env.ts")
7029
7132
  },
7030
7133
  define: {
7031
7134
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7104,103 +7207,88 @@ function createFixRequiresESBuildPlugin(templateDir) {
7104
7207
  return {
7105
7208
  name: "replaceRelative",
7106
7209
  setup(build3) {
7107
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7108
- path: path10.join(templateDir, "shims", "empty.ts")
7210
+ build3.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7211
+ path: path12.join(templateDir, "shims", "empty.ts")
7109
7212
  }));
7110
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7111
- path: path10.join(templateDir, "shims", "empty.ts")
7213
+ build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7214
+ path: path12.join(templateDir, "shims", "empty.ts")
7112
7215
  }));
7113
7216
  }
7114
7217
  };
7115
7218
  }
7116
7219
 
7117
- // src/cli/config.ts
7118
- import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
7119
- import path11, { relative } from "node:path";
7120
- var PACKAGE_NAME = "@opennextjs/cloudflare";
7121
- var UserConfig = {
7122
- cache: {
7123
- bindingName: "NEXT_CACHE_WORKERS_KV"
7124
- }
7125
- };
7126
- function getConfig(appDir, outputDir2) {
7127
- const dotNext = path11.join(outputDir2, ".next");
7128
- const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
7129
- const standaloneApp = path11.join(dotNext, "standalone", appPath);
7130
- const standaloneAppDotNext = path11.join(standaloneApp, ".next");
7131
- const standaloneAppServer = path11.join(standaloneAppDotNext, "server");
7132
- const nodeModules = path11.join(standaloneApp, "node_modules");
7133
- const internalPackage = path11.join(nodeModules, ...PACKAGE_NAME.split("/"));
7134
- return {
7135
- paths: {
7136
- nextApp: appDir,
7137
- builderOutput: outputDir2,
7138
- dotNext,
7139
- standaloneApp,
7140
- standaloneAppDotNext,
7141
- standaloneAppServer,
7142
- internalPackage
7143
- },
7144
- cache: {
7145
- kvBindingName: UserConfig.cache.bindingName
7146
- },
7147
- internalPackageName: PACKAGE_NAME
7148
- };
7149
- }
7150
- function containsDotNextDir(folder) {
7151
- try {
7152
- return statSync2(path11.join(folder, ".next")).isDirectory();
7153
- } catch (e) {
7154
- return false;
7155
- }
7156
- }
7157
- function getNextjsApplicationPath(dotNextDir) {
7158
- const serverPath = findServerParentPath(dotNextDir);
7159
- if (!serverPath) {
7160
- throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7161
- }
7162
- return relative(path11.join(dotNextDir, "standalone"), serverPath);
7163
- }
7164
- function findServerParentPath(parentPath) {
7165
- try {
7166
- if (statSync2(path11.join(parentPath, ".next", "server")).isDirectory()) {
7167
- return parentPath;
7168
- }
7169
- } catch {
7170
- }
7171
- const folders = readdirSync3(parentPath);
7172
- for (const folder of folders) {
7173
- const subFolder = path11.join(parentPath, folder);
7174
- if (statSync2(path11.join(parentPath, folder)).isDirectory()) {
7175
- const dirServerPath = findServerParentPath(subFolder);
7176
- if (dirServerPath) {
7177
- return dirServerPath;
7178
- }
7179
- }
7180
- }
7181
- }
7182
-
7183
7220
  // src/cli/build/index.ts
7184
7221
  import { cpSync as cpSync2 } from "node:fs";
7185
- import path12 from "node:path";
7222
+ import path13 from "node:path";
7223
+ import { rm } from "node:fs/promises";
7186
7224
  async function build2(appDir, opts) {
7187
7225
  if (!opts.skipBuild) {
7188
- buildNextjsApp(appDir);
7226
+ await buildNextjsApp(appDir);
7189
7227
  }
7190
7228
  if (!containsDotNextDir(appDir)) {
7191
7229
  throw new Error(`.next folder not found in ${appDir}`);
7192
7230
  }
7193
- const outputDir2 = path12.resolve(opts.outputDir ?? appDir, ".worker-next");
7231
+ const outputDir2 = path13.resolve(opts.outputDir ?? appDir, ".worker-next");
7194
7232
  await cleanDirectory(outputDir2);
7195
- cpSync2(path12.join(appDir, ".next"), path12.join(outputDir2, ".next"), { recursive: true });
7233
+ cpSync2(path13.join(appDir, ".next"), path13.join(outputDir2, ".next"), { recursive: true });
7196
7234
  const config = getConfig(appDir, outputDir2);
7197
7235
  await buildWorker(config);
7198
7236
  }
7199
- async function cleanDirectory(path13) {
7200
- return await rm(path13, { recursive: true, force: true });
7237
+ async function cleanDirectory(path14) {
7238
+ return await rm(path14, { recursive: true, force: true });
7201
7239
  }
7202
7240
 
7203
7241
  // src/cli/index.ts
7242
+ import { existsSync as existsSync4 } from "node:fs";
7243
+
7244
+ // src/cli/args.ts
7245
+ import { mkdirSync, statSync as statSync2 } from "node:fs";
7246
+ import { parseArgs } from "node:util";
7247
+ import { resolve } from "node:path";
7248
+ function getArgs() {
7249
+ const {
7250
+ values: { skipBuild: skipBuild2, output }
7251
+ } = parseArgs({
7252
+ options: {
7253
+ skipBuild: {
7254
+ type: "boolean",
7255
+ short: "s",
7256
+ default: false
7257
+ },
7258
+ output: {
7259
+ type: "string",
7260
+ short: "o"
7261
+ }
7262
+ },
7263
+ allowPositionals: false
7264
+ });
7265
+ const outputDir2 = output ? resolve(output) : void 0;
7266
+ if (outputDir2) {
7267
+ assertDirArg(outputDir2, "output", true);
7268
+ }
7269
+ return {
7270
+ outputDir: outputDir2,
7271
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7272
+ };
7273
+ }
7274
+ function assertDirArg(path14, argName, make) {
7275
+ let dirStats;
7276
+ try {
7277
+ dirStats = statSync2(path14);
7278
+ } catch {
7279
+ if (!make) {
7280
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7281
+ }
7282
+ mkdirSync(path14);
7283
+ return;
7284
+ }
7285
+ if (!dirStats.isDirectory()) {
7286
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7287
+ }
7288
+ }
7289
+
7290
+ // src/cli/index.ts
7291
+ import { resolve as resolve2 } from "node:path";
7204
7292
  var nextAppDir = resolve2(".");
7205
7293
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7206
7294
  if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {
@@ -17,7 +17,7 @@ function existsSync(path: string) {
17
17
  return FILES.has(path);
18
18
  }
19
19
 
20
- async function readFile(path: string, options: unknown): Promise<any> {
20
+ async function readFile(path: string, options: unknown): Promise<unknown> {
21
21
  console.log(
22
22
  "readFile",
23
23
  { path, options }
@@ -1,17 +1,18 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import Stream from "node:stream";
3
- import type { NextConfig } from "next";
4
- import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
5
- import { MockedResponse } from "next/dist/server/lib/mock-request";
6
1
  import NextNodeServer, { NodeRequestHandler } from "next/dist/server/next-server";
7
- import type { IncomingMessage } from "node:http";
2
+ import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
8
4
  import { type CloudflareContext } from "../../api";
5
+ import type { IncomingMessage } from "node:http";
6
+ import { MockedResponse } from "next/dist/server/lib/mock-request";
7
+ import type { NextConfig } from "next";
8
+ import Stream from "node:stream";
9
9
 
10
10
  const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);
11
11
 
12
12
  const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
13
13
 
14
14
  // Note: this symbol needs to be kept in sync with the one defined in `src/api/get-cloudflare-context.ts`
15
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
16
  (globalThis as any)[Symbol.for("__cloudflare-context__")] = new Proxy(
16
17
  {},
17
18
  {
@@ -29,6 +30,7 @@ const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_
29
30
  let requestHandler: NodeRequestHandler | null = null;
30
31
 
31
32
  export default {
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
34
  async fetch(request: Request & { cf: IncomingRequestCfProperties }, env: any, ctx: any) {
33
35
  return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
34
36
  if (requestHandler == null) {
@@ -45,12 +47,13 @@ export default {
45
47
  const url = new URL(request.url);
46
48
 
47
49
  if (url.pathname === "/_next/image") {
48
- let imageUrl =
50
+ const imageUrl =
49
51
  url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
50
52
  if (imageUrl.startsWith("/")) {
51
53
  return env.ASSETS.fetch(new URL(imageUrl, request.url));
52
54
  }
53
- return fetch(imageUrl, { cf: { cacheEverything: true } } as any);
55
+ // @ts-ignore
56
+ return fetch(imageUrl, { cf: { cacheEverything: true } } as unknown);
54
57
  }
55
58
 
56
59
  const { req, res, webResponse } = getWrappedStreams(request, ctx);
@@ -62,12 +65,12 @@ export default {
62
65
  },
63
66
  };
64
67
 
65
- function getWrappedStreams(request: Request, ctx: any) {
68
+ function getWrappedStreams(request: Request, ctx: ExecutionContext) {
66
69
  const url = new URL(request.url);
67
70
 
68
- const req = (
69
- request.body ? Stream.Readable.fromWeb(request.body as any) : Stream.Readable.from([])
70
- ) as IncomingMessage;
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ const reqBody = request.body && Stream.Readable.fromWeb(request.body as any);
73
+ const req = (reqBody ?? Stream.Readable.from([])) as IncomingMessage;
71
74
  req.httpVersion = "1.0";
72
75
  req.httpVersionMajor = 1;
73
76
  req.httpVersionMinor = 0;
@@ -94,7 +97,7 @@ function getWrappedStreams(request: Request, ctx: any) {
94
97
 
95
98
  const res = new MockedResponse({
96
99
  resWriter: (chunk) => {
97
- resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err: any) => {
100
+ resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err) => {
98
101
  if (
99
102
  err.message.includes("WritableStream has been closed") ||
100
103
  err.message.includes("Network connection lost")
@@ -110,6 +113,7 @@ function getWrappedStreams(request: Request, ctx: any) {
110
113
  });
111
114
 
112
115
  // It's implemented as a no-op, but really it should mark the headers as done
116
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
113
117
  res.flushHeaders = () => (res as any).headPromiseResolve();
114
118
 
115
119
  // Only allow statusCode to be modified if not sent
@@ -127,6 +131,7 @@ function getWrappedStreams(request: Request, ctx: any) {
127
131
  });
128
132
 
129
133
  // Make sure the writer is eventually closed
134
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
130
135
  ctx.waitUntil((res as any).hasStreamed.finally(() => resBodyWriter.close().catch(() => {})));
131
136
 
132
137
  return {
@@ -138,6 +143,7 @@ function getWrappedStreams(request: Request, ctx: any) {
138
143
  res.setHeader("content-encoding", "identity");
139
144
  return new Response(NON_BODY_RESPONSES.has(res.statusCode) ? null : readable, {
140
145
  status: res.statusCode,
146
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
141
147
  headers: (res as any).headers,
142
148
  });
143
149
  },
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": "0.0.0-9a03245",
4
+ "version": "0.0.0-9aff12e",
5
5
  "bin": "dist/cli/index.mjs",
6
6
  "main": "./dist/api/index.mjs",
7
7
  "types": "./dist/api/index.d.mts",
@@ -31,24 +31,32 @@
31
31
  },
32
32
  "homepage": "https://github.com/opennextjs/opennextjs-cloudflare",
33
33
  "devDependencies": {
34
- "@cloudflare/workers-types": "^4.20240919.0",
34
+ "@cloudflare/workers-types": "^4.20240925.0",
35
+ "@eslint/js": "^9.11.1",
35
36
  "@types/node": "^22.2.0",
36
37
  "esbuild": "^0.23.0",
38
+ "eslint": "^9.11.1",
39
+ "eslint-plugin-unicorn": "^55.0.0",
37
40
  "glob": "^11.0.0",
41
+ "globals": "^15.9.0",
38
42
  "next": "14.2.11",
43
+ "package-manager-detector": "^0.2.0",
39
44
  "tsup": "^8.2.4",
40
45
  "typescript": "^5.5.4",
46
+ "typescript-eslint": "^8.7.0",
41
47
  "vitest": "^2.1.1"
42
48
  },
43
49
  "dependencies": {
44
50
  "ts-morph": "^23.0.0"
45
51
  },
46
52
  "peerDependencies": {
47
- "wrangler": "^3.78.6"
53
+ "wrangler": "^3.78.10"
48
54
  },
49
55
  "scripts": {
50
56
  "build": "tsup",
51
57
  "build:watch": "tsup --watch src",
58
+ "lint:check": "eslint",
59
+ "lint:fix": "eslint --fix",
52
60
  "test": "vitest --run",
53
61
  "test:watch": "vitest"
54
62
  }