@opennextjs/cloudflare 0.0.0-42320e7 → 0.0.0-42bf0ff

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.
@@ -0,0 +1,48 @@
1
+ import "./chunk-UJCSKKID.mjs";
2
+
3
+ // src/cache-handler.ts
4
+ var CfWorkersKvCacheHandler = class _CfWorkersKvCacheHandler {
5
+ constructor(ctx) {
6
+ this.ctx = ctx;
7
+ }
8
+ static maybeKVNamespace = void 0;
9
+ async get(key) {
10
+ if (_CfWorkersKvCacheHandler.maybeKVNamespace === void 0) {
11
+ return null;
12
+ }
13
+ console.log(`[Cf] Getting cache[${key}]`);
14
+ try {
15
+ return await _CfWorkersKvCacheHandler.maybeKVNamespace.get(key, "json") ?? null;
16
+ } catch (e) {
17
+ console.error(`Failed to get value for key = ${key}: ${e}`);
18
+ return null;
19
+ }
20
+ }
21
+ async set(key, entry, ctx) {
22
+ if (_CfWorkersKvCacheHandler.maybeKVNamespace === void 0) {
23
+ return;
24
+ }
25
+ console.log(`[Cf] Setting cache[${key}]`);
26
+ try {
27
+ const data = {
28
+ lastModified: Date.now(),
29
+ value: entry
30
+ };
31
+ await _CfWorkersKvCacheHandler.maybeKVNamespace.put(key, JSON.stringify(data));
32
+ } catch (e) {
33
+ console.error(`Failed to set value for key = ${key}: ${e}`);
34
+ }
35
+ }
36
+ async revalidateTag(tags) {
37
+ if (_CfWorkersKvCacheHandler.maybeKVNamespace === void 0) {
38
+ return;
39
+ }
40
+ tags = [tags].flat();
41
+ console.log(`[Cf] revalidateTag ${JSON.stringify(tags)}}`);
42
+ }
43
+ resetRequestCache() {
44
+ }
45
+ };
46
+ export {
47
+ CfWorkersKvCacheHandler as default
48
+ };
@@ -0,0 +1,30 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ export {
28
+ __commonJS,
29
+ __toESM
30
+ };
package/dist/index.mjs CHANGED
@@ -1,29 +1,8 @@
1
1
  #!/usr/bin/env node
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
2
+ import {
3
+ __commonJS,
4
+ __toESM
5
+ } from "./chunk-UJCSKKID.mjs";
27
6
 
28
7
  // ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
29
8
  var require_balanced_match = __commonJS({
@@ -235,7 +214,7 @@ var require_brace_expansion = __commonJS({
235
214
  });
236
215
 
237
216
  // src/index.ts
238
- import { resolve as resolve3 } from "node:path";
217
+ import { resolve as resolve2 } from "node:path";
239
218
 
240
219
  // src/args.ts
241
220
  import { mkdirSync, statSync } from "node:fs";
@@ -267,15 +246,15 @@ function getArgs() {
267
246
  skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
268
247
  };
269
248
  }
270
- function assertDirArg(path6, argName, make) {
249
+ function assertDirArg(path12, argName, make) {
271
250
  let dirStats;
272
251
  try {
273
- dirStats = statSync(path6);
252
+ dirStats = statSync(path12);
274
253
  } catch {
275
254
  if (!make) {
276
255
  throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
277
256
  }
278
- mkdirSync(path6);
257
+ mkdirSync(path12);
279
258
  return;
280
259
  }
281
260
  if (!dirStats.isDirectory()) {
@@ -312,7 +291,7 @@ function runNextBuildCommand(packager, nextAppDir2) {
312
291
  import { build } from "esbuild";
313
292
  import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
314
293
  import { cp, readFile, writeFile } from "node:fs/promises";
315
- import path4 from "node:path";
294
+ import path9 from "node:path";
316
295
  import { fileURLToPath as fileURLToPath3 } from "node:url";
317
296
 
318
297
  // src/build/patches/investigated/patch-require.ts
@@ -321,14 +300,11 @@ function patchRequire(code) {
321
300
  return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
322
301
  }
323
302
 
324
- // src/build/patches/investigated/copy-templates.ts
325
- import path from "node:path";
303
+ // src/build/patches/investigated/copy-package.ts
326
304
  import { cpSync } from "node:fs";
327
- function copyTemplates(srcDir, nextjsAppPaths) {
328
- console.log("# copyTemplates");
329
- const destDir = path.join(nextjsAppPaths.standaloneAppDir, "node_modules/cf/templates");
330
- cpSync(srcDir, destDir, { recursive: true });
331
- return destDir;
305
+ function copyPackage(srcDir, config) {
306
+ console.log("# copyPackage");
307
+ cpSync(srcDir, config.paths.internalPackage, { recursive: true });
332
308
  }
333
309
 
334
310
  // src/build/patches/to-investigate/patch-read-file.ts
@@ -1005,11 +981,11 @@ var qmarksTestNoExtDot = ([$0]) => {
1005
981
  return (f) => f.length === len && f !== "." && f !== "..";
1006
982
  };
1007
983
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
1008
- var path2 = {
984
+ var path = {
1009
985
  win32: { sep: "\\" },
1010
986
  posix: { sep: "/" }
1011
987
  };
1012
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
988
+ var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
1013
989
  minimatch.sep = sep;
1014
990
  var GLOBSTAR = Symbol("globstar **");
1015
991
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -3772,10 +3748,10 @@ var Minipass = class extends EventEmitter {
3772
3748
  * Return a void Promise that resolves once the stream ends.
3773
3749
  */
3774
3750
  async promise() {
3775
- return new Promise((resolve4, reject) => {
3751
+ return new Promise((resolve3, reject) => {
3776
3752
  this.on(DESTROYED, () => reject(new Error("stream destroyed")));
3777
3753
  this.on("error", (er) => reject(er));
3778
- this.on("end", () => resolve4());
3754
+ this.on("end", () => resolve3());
3779
3755
  });
3780
3756
  }
3781
3757
  /**
@@ -3799,7 +3775,7 @@ var Minipass = class extends EventEmitter {
3799
3775
  return Promise.resolve({ done: false, value: res });
3800
3776
  if (this[EOF])
3801
3777
  return stop();
3802
- let resolve4;
3778
+ let resolve3;
3803
3779
  let reject;
3804
3780
  const onerr = (er) => {
3805
3781
  this.off("data", ondata);
@@ -3813,19 +3789,19 @@ var Minipass = class extends EventEmitter {
3813
3789
  this.off("end", onend);
3814
3790
  this.off(DESTROYED, ondestroy);
3815
3791
  this.pause();
3816
- resolve4({ value, done: !!this[EOF] });
3792
+ resolve3({ value, done: !!this[EOF] });
3817
3793
  };
3818
3794
  const onend = () => {
3819
3795
  this.off("error", onerr);
3820
3796
  this.off("data", ondata);
3821
3797
  this.off(DESTROYED, ondestroy);
3822
3798
  stop();
3823
- resolve4({ done: true, value: void 0 });
3799
+ resolve3({ done: true, value: void 0 });
3824
3800
  };
3825
3801
  const ondestroy = () => onerr(new Error("stream destroyed"));
3826
3802
  return new Promise((res2, rej) => {
3827
3803
  reject = rej;
3828
- resolve4 = res2;
3804
+ resolve3 = res2;
3829
3805
  this.once(DESTROYED, ondestroy);
3830
3806
  this.once("error", onerr);
3831
3807
  this.once("end", onend);
@@ -4186,12 +4162,12 @@ var PathBase = class {
4186
4162
  /**
4187
4163
  * Get the Path object referenced by the string path, resolved from this Path
4188
4164
  */
4189
- resolve(path6) {
4190
- if (!path6) {
4165
+ resolve(path12) {
4166
+ if (!path12) {
4191
4167
  return this;
4192
4168
  }
4193
- const rootPath = this.getRootString(path6);
4194
- const dir = path6.substring(rootPath.length);
4169
+ const rootPath = this.getRootString(path12);
4170
+ const dir = path12.substring(rootPath.length);
4195
4171
  const dirParts = dir.split(this.splitSep);
4196
4172
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4197
4173
  return result;
@@ -4795,9 +4771,9 @@ var PathBase = class {
4795
4771
  if (this.#asyncReaddirInFlight) {
4796
4772
  await this.#asyncReaddirInFlight;
4797
4773
  } else {
4798
- let resolve4 = () => {
4774
+ let resolve3 = () => {
4799
4775
  };
4800
- this.#asyncReaddirInFlight = new Promise((res) => resolve4 = res);
4776
+ this.#asyncReaddirInFlight = new Promise((res) => resolve3 = res);
4801
4777
  try {
4802
4778
  for (const e of await this.#fs.promises.readdir(fullpath, {
4803
4779
  withFileTypes: true
@@ -4810,7 +4786,7 @@ var PathBase = class {
4810
4786
  children.provisional = 0;
4811
4787
  }
4812
4788
  this.#asyncReaddirInFlight = void 0;
4813
- resolve4();
4789
+ resolve3();
4814
4790
  }
4815
4791
  return children.slice(0, children.provisional);
4816
4792
  }
@@ -4943,8 +4919,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4943
4919
  /**
4944
4920
  * @internal
4945
4921
  */
4946
- getRootString(path6) {
4947
- return win32.parse(path6).root;
4922
+ getRootString(path12) {
4923
+ return win32.parse(path12).root;
4948
4924
  }
4949
4925
  /**
4950
4926
  * @internal
@@ -4990,8 +4966,8 @@ var PathPosix = class _PathPosix extends PathBase {
4990
4966
  /**
4991
4967
  * @internal
4992
4968
  */
4993
- getRootString(path6) {
4994
- return path6.startsWith("/") ? "/" : "";
4969
+ getRootString(path12) {
4970
+ return path12.startsWith("/") ? "/" : "";
4995
4971
  }
4996
4972
  /**
4997
4973
  * @internal
@@ -5080,11 +5056,11 @@ var PathScurryBase = class {
5080
5056
  /**
5081
5057
  * Get the depth of a provided path, string, or the cwd
5082
5058
  */
5083
- depth(path6 = this.cwd) {
5084
- if (typeof path6 === "string") {
5085
- path6 = this.cwd.resolve(path6);
5059
+ depth(path12 = this.cwd) {
5060
+ if (typeof path12 === "string") {
5061
+ path12 = this.cwd.resolve(path12);
5086
5062
  }
5087
- return path6.depth();
5063
+ return path12.depth();
5088
5064
  }
5089
5065
  /**
5090
5066
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5571,9 +5547,9 @@ var PathScurryBase = class {
5571
5547
  process2();
5572
5548
  return results;
5573
5549
  }
5574
- chdir(path6 = this.cwd) {
5550
+ chdir(path12 = this.cwd) {
5575
5551
  const oldCwd = this.cwd;
5576
- this.cwd = typeof path6 === "string" ? this.cwd.resolve(path6) : path6;
5552
+ this.cwd = typeof path12 === "string" ? this.cwd.resolve(path12) : path12;
5577
5553
  this.cwd[setAsCwd](oldCwd);
5578
5554
  }
5579
5555
  };
@@ -5929,8 +5905,8 @@ var MatchRecord = class {
5929
5905
  }
5930
5906
  // match, absolute, ifdir
5931
5907
  entries() {
5932
- return [...this.store.entries()].map(([path6, n]) => [
5933
- path6,
5908
+ return [...this.store.entries()].map(([path12, n]) => [
5909
+ path12,
5934
5910
  !!(n & 2),
5935
5911
  !!(n & 1)
5936
5912
  ]);
@@ -6135,9 +6111,9 @@ var GlobUtil = class {
6135
6111
  signal;
6136
6112
  maxDepth;
6137
6113
  includeChildMatches;
6138
- constructor(patterns, path6, opts) {
6114
+ constructor(patterns, path12, opts) {
6139
6115
  this.patterns = patterns;
6140
- this.path = path6;
6116
+ this.path = path12;
6141
6117
  this.opts = opts;
6142
6118
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6143
6119
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6156,11 +6132,11 @@ var GlobUtil = class {
6156
6132
  });
6157
6133
  }
6158
6134
  }
6159
- #ignored(path6) {
6160
- return this.seen.has(path6) || !!this.#ignore?.ignored?.(path6);
6135
+ #ignored(path12) {
6136
+ return this.seen.has(path12) || !!this.#ignore?.ignored?.(path12);
6161
6137
  }
6162
- #childrenIgnored(path6) {
6163
- return !!this.#ignore?.childrenIgnored?.(path6);
6138
+ #childrenIgnored(path12) {
6139
+ return !!this.#ignore?.childrenIgnored?.(path12);
6164
6140
  }
6165
6141
  // backpressure mechanism
6166
6142
  pause() {
@@ -6375,8 +6351,8 @@ var GlobUtil = class {
6375
6351
  };
6376
6352
  var GlobWalker = class extends GlobUtil {
6377
6353
  matches = /* @__PURE__ */ new Set();
6378
- constructor(patterns, path6, opts) {
6379
- super(patterns, path6, opts);
6354
+ constructor(patterns, path12, opts) {
6355
+ super(patterns, path12, opts);
6380
6356
  }
6381
6357
  matchEmit(e) {
6382
6358
  this.matches.add(e);
@@ -6413,8 +6389,8 @@ var GlobWalker = class extends GlobUtil {
6413
6389
  };
6414
6390
  var GlobStream = class extends GlobUtil {
6415
6391
  results;
6416
- constructor(patterns, path6, opts) {
6417
- super(patterns, path6, opts);
6392
+ constructor(patterns, path12, opts) {
6393
+ super(patterns, path12, opts);
6418
6394
  this.results = new Minipass({
6419
6395
  signal: this.signal,
6420
6396
  objectMode: true
@@ -6708,16 +6684,17 @@ var glob = Object.assign(glob_, {
6708
6684
  glob.glob = glob;
6709
6685
 
6710
6686
  // src/build/patches/to-investigate/patch-read-file.ts
6711
- function patchReadFile(code, nextjsAppPaths) {
6687
+ import path2 from "node:path";
6688
+ function patchReadFile(code, config) {
6712
6689
  console.log("# patchReadFile");
6713
6690
  code = code.replace(
6714
6691
  "getBuildId() {",
6715
6692
  `getBuildId() {
6716
- return ${JSON.stringify(readFileSync(`${nextjsAppPaths.standaloneAppDotNextDir}/BUILD_ID`, "utf-8"))};
6693
+ return ${JSON.stringify(readFileSync(path2.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6717
6694
  `
6718
6695
  );
6719
- const manifestJsons = globSync(`${nextjsAppPaths.standaloneAppDotNextDir}/**/*-manifest.json`).map(
6720
- (file) => file.replace(nextjsAppPaths.standaloneAppDir + "/", "")
6696
+ const manifestJsons = globSync(path2.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6697
+ (file) => file.replace(config.paths.standaloneApp + "/", "")
6721
6698
  );
6722
6699
  code = code.replace(
6723
6700
  /function loadManifest\((.+?), .+?\) {/,
@@ -6725,7 +6702,7 @@ function patchReadFile(code, nextjsAppPaths) {
6725
6702
  ${manifestJsons.map(
6726
6703
  (manifestJson) => `
6727
6704
  if ($1.endsWith("${manifestJson}")) {
6728
- return ${readFileSync(`${nextjsAppPaths.standaloneAppDir}/${manifestJson}`, "utf-8")};
6705
+ return ${readFileSync(path2.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6729
6706
  }
6730
6707
  `
6731
6708
  ).join("\n")}
@@ -6736,15 +6713,20 @@ function patchReadFile(code, nextjsAppPaths) {
6736
6713
  }
6737
6714
 
6738
6715
  // src/build/patches/to-investigate/patch-find-dir.ts
6716
+ import path3 from "node:path";
6739
6717
  import { existsSync } from "node:fs";
6740
- function patchFindDir(code, nextjsAppPaths) {
6718
+ function patchFindDir(code, config) {
6741
6719
  console.log("# patchFindDir");
6742
6720
  return code.replace(
6743
6721
  "function findDir(dir, name) {",
6744
6722
  `function findDir(dir, name) {
6745
6723
  if (dir.endsWith(".next/server")) {
6746
- if (name === "app") return ${existsSync(`${nextjsAppPaths.standaloneAppServerDir}/app`)};
6747
- if (name === "pages") return ${existsSync(`${nextjsAppPaths.standaloneAppServerDir}/pages`)};
6724
+ if (name === "app") {
6725
+ return ${existsSync(`${path3.join(config.paths.standaloneAppServer, "app")}`)};
6726
+ }
6727
+ if (name === "pages") {
6728
+ return ${existsSync(`${path3.join(config.paths.standaloneAppServer, "pages")}`)};
6729
+ }
6748
6730
  }
6749
6731
  throw new Error("Unknown findDir call: " + dir + " " + name);
6750
6732
  `
@@ -6753,10 +6735,11 @@ function patchFindDir(code, nextjsAppPaths) {
6753
6735
 
6754
6736
  // src/build/patches/to-investigate/inline-next-require.ts
6755
6737
  import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
6756
- function inlineNextRequire(code, nextjsAppPaths) {
6738
+ import path4 from "node:path";
6739
+ function inlineNextRequire(code, config) {
6757
6740
  console.log("# inlineNextRequire");
6758
- const pagesManifestFile = `${nextjsAppPaths.standaloneAppServerDir}/pages-manifest.json`;
6759
- const appPathsManifestFile = `${nextjsAppPaths.standaloneAppServerDir}/app-paths-manifest.json`;
6741
+ const pagesManifestFile = path4.join(config.paths.standaloneAppServer, "pages-manifest.json");
6742
+ const appPathsManifestFile = path4.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6760
6743
  const pagesManifestFiles = existsSync2(pagesManifestFile) ? Object.values(JSON.parse(readFileSync2(pagesManifestFile, "utf-8"))).map(
6761
6744
  (file) => ".next/server/" + file
6762
6745
  ) : [];
@@ -6772,14 +6755,14 @@ function inlineNextRequire(code, nextjsAppPaths) {
6772
6755
  ${htmlPages.map(
6773
6756
  (htmlPage) => `
6774
6757
  if (pagePath.endsWith("${htmlPage}")) {
6775
- return ${JSON.stringify(readFileSync2(`${nextjsAppPaths.standaloneAppDir}/${htmlPage}`, "utf-8"))};
6758
+ return ${JSON.stringify(readFileSync2(path4.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6776
6759
  }
6777
6760
  `
6778
6761
  ).join("\n")}
6779
6762
  ${pageModules.map(
6780
6763
  (module) => `
6781
6764
  if (pagePath.endsWith("${module}")) {
6782
- return require("${nextjsAppPaths.standaloneAppDir}/${module}");
6765
+ return require("${path4.join(config.paths.standaloneApp, module)}");
6783
6766
  }
6784
6767
  `
6785
6768
  ).join("\n")}
@@ -6789,18 +6772,19 @@ function inlineNextRequire(code, nextjsAppPaths) {
6789
6772
  }
6790
6773
 
6791
6774
  // src/build/patches/to-investigate/inline-eval-manifest.ts
6792
- function inlineEvalManifest(code, nextjsAppPaths) {
6775
+ import path5 from "node:path";
6776
+ function inlineEvalManifest(code, config) {
6793
6777
  console.log("# inlineEvalManifest");
6794
6778
  const manifestJss = globSync(
6795
- `${nextjsAppPaths.standaloneAppDotNextDir}/**/*_client-reference-manifest.js`
6796
- ).map((file) => file.replace(`${nextjsAppPaths.standaloneAppDir}/`, ""));
6779
+ path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6780
+ ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6797
6781
  return code.replace(
6798
6782
  /function evalManifest\((.+?), .+?\) {/,
6799
6783
  `$&
6800
6784
  ${manifestJss.map(
6801
6785
  (manifestJs) => `
6802
6786
  if ($1.endsWith("${manifestJs}")) {
6803
- require("${nextjsAppPaths.standaloneAppDir}/${manifestJs}");
6787
+ require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6804
6788
  return {
6805
6789
  __RSC_MANIFEST: {
6806
6790
  "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
@@ -6815,13 +6799,12 @@ function inlineEvalManifest(code, nextjsAppPaths) {
6815
6799
  }
6816
6800
 
6817
6801
  // src/build/patches/to-investigate/wrangler-deps.ts
6818
- import path3 from "node:path";
6802
+ import path6 from "node:path";
6819
6803
  import fs, { writeFileSync } from "node:fs";
6820
- function patchWranglerDeps(paths) {
6804
+ function patchWranglerDeps(config) {
6821
6805
  console.log("# patchWranglerDeps");
6822
- console.log({ base: paths.standaloneAppDotNextDir });
6823
- const pagesRuntimeFile = path3.join(
6824
- paths.standaloneAppDir,
6806
+ const pagesRuntimeFile = path6.join(
6807
+ config.paths.standaloneApp,
6825
6808
  "node_modules",
6826
6809
  "next",
6827
6810
  "dist",
@@ -6831,8 +6814,8 @@ function patchWranglerDeps(paths) {
6831
6814
  );
6832
6815
  const patchedPagesRuntime = fs.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6833
6816
  fs.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6834
- const tracerFile = path3.join(
6835
- paths.standaloneAppDir,
6817
+ const tracerFile = path6.join(
6818
+ config.paths.standaloneApp,
6836
6819
  "node_modules",
6837
6820
  "next",
6838
6821
  "dist",
@@ -6847,6 +6830,7 @@ function patchWranglerDeps(paths) {
6847
6830
 
6848
6831
  // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6849
6832
  import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
6833
+ import path7 from "node:path";
6850
6834
 
6851
6835
  // src/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6852
6836
  import * as ts from "ts-morph";
@@ -6959,11 +6943,11 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6959
6943
  }
6960
6944
 
6961
6945
  // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6962
- async function updateWebpackChunksFile(nextjsAppPaths) {
6946
+ async function updateWebpackChunksFile(config) {
6963
6947
  console.log("# updateWebpackChunksFile");
6964
- const webpackRuntimeFile = `${nextjsAppPaths.standaloneAppServerDir}/webpack-runtime.js`;
6948
+ const webpackRuntimeFile = path7.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6965
6949
  const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6966
- const chunks = readdirSync2(`${nextjsAppPaths.standaloneAppServerDir}/chunks`).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6950
+ const chunks = readdirSync2(path7.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6967
6951
  console.log(` - chunk ${chunk}`);
6968
6952
  return chunk.replace(/\.js$/, "");
6969
6953
  });
@@ -6971,19 +6955,53 @@ async function updateWebpackChunksFile(nextjsAppPaths) {
6971
6955
  writeFileSync2(webpackRuntimeFile, updatedFileContent);
6972
6956
  }
6973
6957
 
6958
+ // src/build/patches/investigated/patch-cache.ts
6959
+ import path8 from "node:path";
6960
+ function patchCache(code, config) {
6961
+ console.log("# patchCached");
6962
+ const cacheHandler = path8.join(config.paths.internalPackage, "cache-handler.mjs");
6963
+ const patchedCode = code.replace(
6964
+ "const { cacheHandler } = this.nextConfig;",
6965
+ `const cacheHandler = null;
6966
+ CacheHandler = (await import('${cacheHandler}')).default;
6967
+ CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6968
+ `
6969
+ );
6970
+ if (patchedCode === code) {
6971
+ throw new Error("Cache patch not applied");
6972
+ }
6973
+ return patchedCode;
6974
+ }
6975
+
6974
6976
  // src/build/build-worker.ts
6975
- var templateSrcDir = path4.join(path4.dirname(fileURLToPath3(import.meta.url)), "templates");
6976
- async function buildWorker(appDir, outputDir2, nextjsAppPaths) {
6977
- const templateDir = copyTemplates(templateSrcDir, nextjsAppPaths);
6978
- const workerEntrypoint = `${templateDir}/worker.ts`;
6979
- const workerOutputFile = `${outputDir2}/index.mjs`;
6980
- const nextConfigStr = readFileSync4(nextjsAppPaths.standaloneAppDir + "/server.js", "utf8")?.match(
6977
+ var packageDir = path9.dirname(fileURLToPath3(import.meta.url));
6978
+ async function buildWorker(config) {
6979
+ console.log(`\x1B[35m\u2699\uFE0F Copying files...
6980
+ \x1B[0m`);
6981
+ await cp(
6982
+ path9.join(config.paths.dotNext, "static"),
6983
+ path9.join(config.paths.builderOutput, "assets", "_next", "static"),
6984
+ {
6985
+ recursive: true
6986
+ }
6987
+ );
6988
+ const publicDir = path9.join(config.paths.nextApp, "public");
6989
+ if (existsSync3(publicDir)) {
6990
+ await cp(publicDir, path9.join(config.paths.builderOutput, "assets"), {
6991
+ recursive: true
6992
+ });
6993
+ }
6994
+ copyPackage(packageDir, config);
6995
+ const templateDir = path9.join(config.paths.internalPackage, "templates");
6996
+ const workerEntrypoint = path9.join(templateDir, "worker.ts");
6997
+ const workerOutputFile = path9.join(config.paths.builderOutput, "index.mjs");
6998
+ const nextConfigStr = readFileSync4(path9.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
6981
6999
  /const nextConfig = ({.+?})\n/
6982
7000
  )?.[1] ?? {};
6983
7001
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
6984
7002
  \x1B[0m`);
6985
- patchWranglerDeps(nextjsAppPaths);
6986
- updateWebpackChunksFile(nextjsAppPaths);
7003
+ patchWranglerDeps(config);
7004
+ updateWebpackChunksFile(config);
6987
7005
  await build({
6988
7006
  entryPoints: [workerEntrypoint],
6989
7007
  bundle: true,
@@ -6996,15 +7014,15 @@ async function buildWorker(appDir, outputDir2, nextjsAppPaths) {
6996
7014
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
6997
7015
  // eval("require")("bufferutil");
6998
7016
  // eval("require")("utf-8-validate");
6999
- "next/dist/compiled/ws": `${templateDir}/shims/empty.ts`,
7017
+ "next/dist/compiled/ws": path9.join(templateDir, "shims", "empty.ts"),
7000
7018
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
7001
7019
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
7002
7020
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
7003
7021
  // QUESTION: Why did I encountered this but mhart didn't?
7004
- "next/dist/compiled/edge-runtime": `${templateDir}/shims/empty.ts`,
7022
+ "next/dist/compiled/edge-runtime": path9.join(templateDir, "shims", "empty.ts"),
7005
7023
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7006
7024
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7007
- "@next/env": `${templateDir}/shims/env.ts`
7025
+ "@next/env": path9.join(templateDir, "shims", "env.ts")
7008
7026
  },
7009
7027
  define: {
7010
7028
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7038,22 +7056,21 @@ async function buildWorker(appDir, outputDir2, nextjsAppPaths) {
7038
7056
  // Do not crash on cache not supported
7039
7057
  // https://github.com/cloudflare/workerd/pull/2434
7040
7058
  // compatibility flag "cache_option_enabled" -> does not support "force-cache"
7041
- let isPatchedAlready = globalThis.fetch.__nextPatched;
7042
7059
  const curFetch = globalThis.fetch;
7043
7060
  globalThis.fetch = (input, init) => {
7044
- console.log("globalThis.fetch", input);
7045
- if (init) delete init.cache;
7061
+ if (init) {
7062
+ delete init.cache;
7063
+ }
7046
7064
  return curFetch(input, init);
7047
7065
  };
7048
7066
  import { Readable } from 'node:stream';
7049
- globalThis.fetch.__nextPatched = isPatchedAlready;
7050
7067
  fetch = globalThis.fetch;
7051
7068
  const CustomRequest = class extends globalThis.Request {
7052
7069
  constructor(input, init) {
7053
- console.log("CustomRequest", input);
7054
7070
  if (init) {
7055
7071
  delete init.cache;
7056
7072
  if (init.body?.__node_stream__ === true) {
7073
+ // https://github.com/cloudflare/workerd/issues/2746
7057
7074
  init.body = Readable.toWeb(init.body);
7058
7075
  }
7059
7076
  }
@@ -7062,31 +7079,22 @@ const CustomRequest = class extends globalThis.Request {
7062
7079
  };
7063
7080
  globalThis.Request = CustomRequest;
7064
7081
  Request = globalThis.Request;
7065
- `
7082
+ `
7066
7083
  }
7067
7084
  });
7068
- await updateWorkerBundledCode(workerOutputFile, nextjsAppPaths);
7069
- console.log(`\x1B[35m\u2699\uFE0F Copying asset files...
7070
- \x1B[0m`);
7071
- await cp(`${nextjsAppPaths.dotNextDir}/static`, `${outputDir2}/assets/_next/static`, {
7072
- recursive: true
7073
- });
7074
- if (existsSync3(`${appDir}/public`)) {
7075
- await cp(`${appDir}/public`, `${outputDir2}/assets`, {
7076
- recursive: true
7077
- });
7078
- }
7085
+ await updateWorkerBundledCode(workerOutputFile, config);
7079
7086
  console.log(`\x1B[35mWorker saved in \`${workerOutputFile}\` \u{1F680}
7080
7087
  \x1B[0m`);
7081
7088
  }
7082
- async function updateWorkerBundledCode(workerOutputFile, nextjsAppPaths) {
7089
+ async function updateWorkerBundledCode(workerOutputFile, config) {
7083
7090
  const originalCode = await readFile(workerOutputFile, "utf8");
7084
7091
  let patchedCode = originalCode;
7085
7092
  patchedCode = patchRequire(patchedCode);
7086
- patchedCode = patchReadFile(patchedCode, nextjsAppPaths);
7087
- patchedCode = inlineNextRequire(patchedCode, nextjsAppPaths);
7088
- patchedCode = patchFindDir(patchedCode, nextjsAppPaths);
7089
- patchedCode = inlineEvalManifest(patchedCode, nextjsAppPaths);
7093
+ patchedCode = patchReadFile(patchedCode, config);
7094
+ patchedCode = inlineNextRequire(patchedCode, config);
7095
+ patchedCode = patchFindDir(patchedCode, config);
7096
+ patchedCode = inlineEvalManifest(patchedCode, config);
7097
+ patchedCode = patchCache(patchedCode, config);
7090
7098
  await writeFile(workerOutputFile, patchedCode);
7091
7099
  }
7092
7100
  function createFixRequiresESBuildPlugin(templateDir) {
@@ -7094,83 +7102,103 @@ function createFixRequiresESBuildPlugin(templateDir) {
7094
7102
  name: "replaceRelative",
7095
7103
  setup(build3) {
7096
7104
  build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7097
- path: `${templateDir}/shims/empty.ts`
7105
+ path: path9.join(templateDir, "shims", "empty.ts")
7098
7106
  }));
7099
7107
  build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7100
- path: `${templateDir}/shims/node-fs.ts`
7108
+ path: path9.join(templateDir, "shims", "empty.ts")
7101
7109
  }));
7102
7110
  }
7103
7111
  };
7104
7112
  }
7105
7113
 
7106
- // src/nextjs-paths.ts
7114
+ // src/config.ts
7107
7115
  import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
7108
- import path5, { relative } from "node:path";
7109
- function getNextjsAppPaths(baseDir) {
7110
- const dotNextDir = getDotNextDirPath(baseDir);
7111
- const appPath = getNextjsApplicationPath(dotNextDir).replace(/\/$/, "");
7112
- const standaloneAppDir = path5.join(dotNextDir, "standalone", appPath);
7116
+ import path10, { relative } from "node:path";
7117
+ var PACKAGE_NAME = "@opennextjs/cloudflare";
7118
+ var UserConfig = {
7119
+ cache: {
7120
+ bindingName: "NEXT_CACHE_WORKERS_KV"
7121
+ }
7122
+ };
7123
+ function getConfig(appDir, outputDir2) {
7124
+ const dotNext = path10.join(outputDir2, ".next");
7125
+ const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
7126
+ const standaloneApp = path10.join(dotNext, "standalone", appPath);
7127
+ const standaloneAppDotNext = path10.join(standaloneApp, ".next");
7128
+ const standaloneAppServer = path10.join(standaloneAppDotNext, "server");
7129
+ const nodeModules = path10.join(standaloneApp, "node_modules");
7130
+ const internalPackage = path10.join(nodeModules, ...PACKAGE_NAME.split("/"));
7113
7131
  return {
7114
- dotNextDir,
7115
- standaloneAppDir,
7116
- standaloneAppDotNextDir: path5.join(standaloneAppDir, ".next"),
7117
- standaloneAppServerDir: path5.join(standaloneAppDir, ".next", "server")
7132
+ paths: {
7133
+ nextApp: appDir,
7134
+ builderOutput: outputDir2,
7135
+ dotNext,
7136
+ standaloneApp,
7137
+ standaloneAppDotNext,
7138
+ standaloneAppServer,
7139
+ internalPackage
7140
+ },
7141
+ cache: {
7142
+ kvBindingName: UserConfig.cache.bindingName
7143
+ },
7144
+ internalPackageName: PACKAGE_NAME
7118
7145
  };
7119
7146
  }
7120
- function getDotNextDirPath(nextAppDir2) {
7121
- const dotNextDirPath = `${nextAppDir2}/.next`;
7147
+ function containsDotNextDir(folder) {
7122
7148
  try {
7123
- const dirStats = statSync2(dotNextDirPath);
7124
- if (!dirStats.isDirectory()) throw new Error();
7125
- } catch {
7126
- throw new Error(`Error: \`.next\` directory not found!`);
7149
+ return statSync2(path10.join(folder, ".next")).isDirectory();
7150
+ } catch (e) {
7151
+ return false;
7127
7152
  }
7128
- return dotNextDirPath;
7129
7153
  }
7130
7154
  function getNextjsApplicationPath(dotNextDir) {
7131
7155
  const serverPath = findServerParentPath(dotNextDir);
7132
7156
  if (!serverPath) {
7133
7157
  throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7134
7158
  }
7135
- return relative(`${dotNextDir}/standalone`, serverPath);
7136
- function findServerParentPath(path6) {
7137
- try {
7138
- if (statSync2(`${path6}/.next/server`).isDirectory()) {
7139
- return path6;
7140
- }
7141
- } catch {
7159
+ return relative(path10.join(dotNextDir, "standalone"), serverPath);
7160
+ }
7161
+ function findServerParentPath(parentPath) {
7162
+ try {
7163
+ if (statSync2(path10.join(parentPath, ".next", "server")).isDirectory()) {
7164
+ return parentPath;
7142
7165
  }
7143
- const files = readdirSync3(path6);
7144
- for (const file of files) {
7145
- if (statSync2(`${path6}/${file}`).isDirectory()) {
7146
- const dirServerPath = findServerParentPath(`${path6}/${file}`);
7147
- if (dirServerPath) {
7148
- return dirServerPath;
7149
- }
7166
+ } catch {
7167
+ }
7168
+ const folders = readdirSync3(parentPath);
7169
+ for (const folder of folders) {
7170
+ const subFolder = path10.join(parentPath, folder);
7171
+ if (statSync2(path10.join(parentPath, folder)).isDirectory()) {
7172
+ const dirServerPath = findServerParentPath(subFolder);
7173
+ if (dirServerPath) {
7174
+ return dirServerPath;
7150
7175
  }
7151
7176
  }
7152
7177
  }
7153
7178
  }
7154
7179
 
7155
7180
  // src/build/build.ts
7156
- import { cpSync as cpSync2 } from "node:fs";
7157
- import { resolve as resolve2 } from "node:path";
7181
+ import { cpSync as cpSync3 } from "node:fs";
7182
+ import path11 from "node:path";
7158
7183
  async function build2(appDir, opts) {
7159
7184
  if (!opts.skipBuild) {
7160
7185
  buildNextjsApp(appDir);
7161
7186
  }
7162
- const outputDir2 = resolve2(opts.outputDir ?? appDir, ".worker-next");
7187
+ if (!containsDotNextDir(appDir)) {
7188
+ throw new Error(`.next folder not found in ${appDir}`);
7189
+ }
7190
+ const outputDir2 = path11.resolve(opts.outputDir ?? appDir, ".worker-next");
7163
7191
  await cleanDirectory(outputDir2);
7164
- cpSync2(resolve2(`${appDir}/.next`), resolve2(`${outputDir2}/.next`), { recursive: true });
7165
- const nextjsAppPaths = getNextjsAppPaths(outputDir2);
7166
- await buildWorker(appDir, outputDir2, nextjsAppPaths);
7192
+ cpSync3(path11.join(appDir, ".next"), path11.join(outputDir2, ".next"), { recursive: true });
7193
+ const config = getConfig(appDir, outputDir2);
7194
+ await buildWorker(config);
7167
7195
  }
7168
- async function cleanDirectory(path6) {
7169
- return await rm(path6, { recursive: true, force: true });
7196
+ async function cleanDirectory(path12) {
7197
+ return await rm(path12, { recursive: true, force: true });
7170
7198
  }
7171
7199
 
7172
7200
  // src/index.ts
7173
- var nextAppDir = resolve3(".");
7201
+ var nextAppDir = resolve2(".");
7174
7202
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7175
7203
  if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {
7176
7204
  throw new Error("Error: Not in a Next.js app project");
@@ -102,7 +102,6 @@ function getWrappedStreams(request: Request, ctx: any) {
102
102
  },
103
103
  set: function (val) {
104
104
  if (this.finished || this.headersSent) {
105
- console.error("headers already sent");
106
105
  return;
107
106
  }
108
107
  statusCode = val;
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-42320e7",
4
+ "version": "0.0.0-42bf0ff",
5
5
  "bin": "dist/index.mjs",
6
6
  "files": [
7
7
  "README.md",
@@ -23,9 +23,11 @@
23
23
  },
24
24
  "homepage": "https://github.com/opennextjs/opennextjs-cloudflare",
25
25
  "devDependencies": {
26
+ "@cloudflare/workers-types": "^4.20240919.0",
26
27
  "@types/node": "^22.2.0",
27
28
  "esbuild": "^0.23.0",
28
29
  "glob": "^11.0.0",
30
+ "next": "14.2.11",
29
31
  "tsup": "^8.2.4",
30
32
  "typescript": "^5.5.4",
31
33
  "vitest": "^2.1.1"