@opennextjs/cloudflare 0.0.0-e62af72 → 0.0.3

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.
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ NEXT_META_SUFFIX,
4
+ SEED_DATA_DIR,
3
5
  __commonJS,
4
6
  __toESM
5
- } from "./chunk-UJCSKKID.mjs";
7
+ } from "./chunk-F7LECSR5.mjs";
6
8
 
7
9
  // ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
8
10
  var require_balanced_match = __commonJS({
@@ -213,68 +215,172 @@ var require_brace_expansion = __commonJS({
213
215
  }
214
216
  });
215
217
 
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);
218
+ // src/cli/config.ts
219
+ import path, { relative } from "node:path";
220
+ import { readdirSync, statSync } from "node:fs";
221
+ var PACKAGE_NAME = "@opennextjs/cloudflare";
222
+ var UserConfig = {
223
+ cache: {
224
+ bindingName: "NEXT_CACHE_WORKERS_KV"
243
225
  }
226
+ };
227
+ function getConfig(appDir, outputDir2) {
228
+ const dotNext = path.join(outputDir2, ".next");
229
+ const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
230
+ const standaloneRoot = path.join(dotNext, "standalone");
231
+ const standaloneApp = path.join(standaloneRoot, appPath);
232
+ const standaloneAppDotNext = path.join(standaloneApp, ".next");
233
+ const standaloneAppServer = path.join(standaloneAppDotNext, "server");
234
+ const nodeModules = path.join(standaloneApp, "node_modules");
235
+ const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/"));
244
236
  return {
245
- outputDir: outputDir2,
246
- skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
237
+ buildTimestamp: Date.now(),
238
+ paths: {
239
+ nextApp: appDir,
240
+ builderOutput: outputDir2,
241
+ dotNext,
242
+ standaloneRoot,
243
+ standaloneApp,
244
+ standaloneAppDotNext,
245
+ standaloneAppServer,
246
+ internalPackage
247
+ },
248
+ cache: {
249
+ kvBindingName: UserConfig.cache.bindingName
250
+ },
251
+ internalPackageName: PACKAGE_NAME
247
252
  };
248
253
  }
249
- function assertDirArg(path13, argName, make) {
250
- let dirStats;
254
+ function containsDotNextDir(folder) {
251
255
  try {
252
- dirStats = statSync(path13);
256
+ return statSync(path.join(folder, ".next")).isDirectory();
253
257
  } catch {
254
- if (!make) {
255
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
258
+ return false;
259
+ }
260
+ }
261
+ function getNextjsApplicationPath(dotNextDir) {
262
+ const serverPath = findServerParentPath(dotNextDir);
263
+ if (!serverPath) {
264
+ throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
265
+ }
266
+ return relative(path.join(dotNextDir, "standalone"), serverPath);
267
+ }
268
+ function findServerParentPath(parentPath) {
269
+ try {
270
+ if (statSync(path.join(parentPath, ".next", "server")).isDirectory()) {
271
+ return parentPath;
256
272
  }
257
- mkdirSync(path13);
258
- return;
273
+ } catch {
259
274
  }
260
- if (!dirStats.isDirectory()) {
261
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
275
+ const folders = readdirSync(parentPath);
276
+ for (const folder of folders) {
277
+ const subFolder = path.join(parentPath, folder);
278
+ if (statSync(path.join(parentPath, folder)).isDirectory()) {
279
+ const dirServerPath = findServerParentPath(subFolder);
280
+ if (dirServerPath) {
281
+ return dirServerPath;
282
+ }
283
+ }
262
284
  }
263
285
  }
264
286
 
265
- // src/cli/index.ts
266
- import { existsSync as existsSync4 } from "node:fs";
287
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/constants.mjs
288
+ var AGENTS = [
289
+ "npm",
290
+ "yarn",
291
+ "yarn@berry",
292
+ "pnpm",
293
+ "pnpm@6",
294
+ "bun"
295
+ ];
296
+ var LOCKS = {
297
+ "bun.lockb": "bun",
298
+ "pnpm-lock.yaml": "pnpm",
299
+ "yarn.lock": "yarn",
300
+ "package-lock.json": "npm",
301
+ "npm-shrinkwrap.json": "npm"
302
+ };
267
303
 
268
- // src/cli/build/index.ts
269
- import { rm } from "node:fs/promises";
304
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/detect.mjs
305
+ import fs from "node:fs";
306
+ import fsPromises from "node:fs/promises";
307
+ import path2 from "node:path";
308
+ import process2 from "node:process";
309
+ async function detect({ cwd, onUnknown } = {}) {
310
+ for (const directory of lookup(cwd)) {
311
+ for (const lock of Object.keys(LOCKS)) {
312
+ if (await fileExists(path2.join(directory, lock))) {
313
+ const name = LOCKS[lock];
314
+ const result2 = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
315
+ if (result2)
316
+ return result2;
317
+ else
318
+ return { name, agent: name };
319
+ }
320
+ }
321
+ const result = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
322
+ if (result)
323
+ return result;
324
+ }
325
+ return null;
326
+ }
327
+ function* lookup(cwd = process2.cwd()) {
328
+ let directory = path2.resolve(cwd);
329
+ const { root } = path2.parse(directory);
330
+ while (directory && directory !== root) {
331
+ yield directory;
332
+ directory = path2.dirname(directory);
333
+ }
334
+ }
335
+ async function parsePackageJson(filepath, onUnknown) {
336
+ if (!filepath || !await fileExists(filepath))
337
+ return null;
338
+ try {
339
+ const pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
340
+ let agent;
341
+ if (typeof pkg.packageManager === "string") {
342
+ const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
343
+ let version = ver;
344
+ if (name === "yarn" && Number.parseInt(ver) > 1) {
345
+ agent = "yarn@berry";
346
+ version = "berry";
347
+ return { name, agent, version };
348
+ } else if (name === "pnpm" && Number.parseInt(ver) < 7) {
349
+ agent = "pnpm@6";
350
+ return { name, agent, version };
351
+ } else if (AGENTS.includes(name)) {
352
+ agent = name;
353
+ return { name, agent, version };
354
+ } else {
355
+ return onUnknown?.(pkg.packageManager) ?? null;
356
+ }
357
+ }
358
+ } catch {
359
+ }
360
+ return null;
361
+ }
362
+ async function fileExists(filePath) {
363
+ try {
364
+ const stats = await fsPromises.stat(filePath);
365
+ if (stats.isFile()) {
366
+ return true;
367
+ }
368
+ } catch {
369
+ }
370
+ return false;
371
+ }
270
372
 
271
373
  // src/cli/build/build-next-app.ts
272
374
  import { execSync } from "node:child_process";
273
- function buildNextjsApp(nextAppDir2) {
274
- runNextBuildCommand("pnpm", nextAppDir2);
375
+ async function buildNextjsApp(nextAppDir2) {
376
+ const pm = await detect();
377
+ if (!pm) {
378
+ throw new Error("Fatal Error: package manager detection failed, aborting");
379
+ }
380
+ runNextBuildCommand(pm.name, nextAppDir2);
275
381
  }
276
382
  function runNextBuildCommand(packager, nextAppDir2) {
277
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
383
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
278
384
  execSync(command, {
279
385
  stdio: "inherit",
280
386
  cwd: nextAppDir2,
@@ -289,29 +395,71 @@ function runNextBuildCommand(packager, nextAppDir2) {
289
395
 
290
396
  // src/cli/build/build-worker.ts
291
397
  import { build } from "esbuild";
292
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
293
398
  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
- }
399
+ import { existsSync as existsSync5, readFileSync as readFileSync7 } from "node:fs";
302
400
 
303
401
  // src/cli/build/patches/investigated/copy-package-cli-files.ts
304
402
  import { cpSync } from "node:fs";
305
- import path from "node:path";
403
+ import path3 from "node:path";
306
404
  function copyPackageCliFiles(packageDistDir2, config) {
307
405
  console.log("# copyPackageTemplateFiles");
308
- const sourceDir = path.join(packageDistDir2, "cli");
309
- const destinationDir = path.join(config.paths.internalPackage, "cli");
406
+ const sourceDir = path3.join(packageDistDir2, "cli");
407
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
310
408
  cpSync(sourceDir, destinationDir, { recursive: true });
311
409
  }
312
410
 
313
- // src/cli/build/patches/to-investigate/patch-read-file.ts
314
- import { readFileSync } from "node:fs";
411
+ // src/cli/build/utils/ts-parse-file.ts
412
+ import * as ts from "ts-morph";
413
+ function tsParseFile(fileContent) {
414
+ const project = new ts.Project();
415
+ const sourceFile = project.createSourceFile("file.js", fileContent);
416
+ return sourceFile;
417
+ }
418
+
419
+ // src/cli/build/utils/copy-prerendered-routes.ts
420
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
421
+ import { dirname, join as join2 } from "node:path";
422
+
423
+ // src/cli/build/utils/read-paths-recursively.ts
424
+ import { join } from "node:path";
425
+ import { readdirSync as readdirSync2 } from "node:fs";
426
+ function readPathsRecursively(dir) {
427
+ try {
428
+ const files = readdirSync2(dir, { withFileTypes: true });
429
+ return files.flatMap((file) => {
430
+ const filePath = join(dir, file.name);
431
+ return file.isDirectory() ? readPathsRecursively(filePath) : filePath;
432
+ });
433
+ } catch {
434
+ return [];
435
+ }
436
+ }
437
+
438
+ // src/cli/build/utils/copy-prerendered-routes.ts
439
+ function copyPrerenderedRoutes(config) {
440
+ console.log("# copyPrerenderedRoutes");
441
+ const serverAppDirPath = join2(config.paths.standaloneAppServer, "app");
442
+ const prerenderManifestPath = join2(config.paths.standaloneAppDotNext, "prerender-manifest.json");
443
+ const outputPath = join2(config.paths.builderOutput, "assets", SEED_DATA_DIR);
444
+ const prerenderManifest = existsSync(prerenderManifestPath) ? JSON.parse(readFileSync(prerenderManifestPath, "utf8")) : {};
445
+ const prerenderedRoutes = Object.keys(prerenderManifest.routes);
446
+ const prerenderedAssets = readPathsRecursively(serverAppDirPath).map((fullPath) => ({ fullPath, relativePath: fullPath.replace(serverAppDirPath, "") })).filter(
447
+ ({ relativePath }) => prerenderedRoutes.includes(relativePath.replace(/\.\w+$/, "").replace(/^\/index$/, "/"))
448
+ );
449
+ prerenderedAssets.forEach(({ fullPath, relativePath }) => {
450
+ const destPath = join2(outputPath, relativePath);
451
+ mkdirSync(dirname(destPath), { recursive: true });
452
+ if (fullPath.endsWith(NEXT_META_SUFFIX)) {
453
+ const data = JSON.parse(readFileSync(fullPath, "utf8"));
454
+ writeFileSync(destPath, JSON.stringify({ ...data, lastModified: config.buildTimestamp }));
455
+ } else {
456
+ copyFileSync(fullPath, destPath);
457
+ }
458
+ });
459
+ }
460
+
461
+ // src/cli/build/build-worker.ts
462
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
315
463
 
316
464
  // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
317
465
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
@@ -984,11 +1132,11 @@ var qmarksTestNoExtDot = ([$0]) => {
984
1132
  return (f) => f.length === len && f !== "." && f !== "..";
985
1133
  };
986
1134
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
987
- var path2 = {
1135
+ var path4 = {
988
1136
  win32: { sep: "\\" },
989
1137
  posix: { sep: "/" }
990
1138
  };
991
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1139
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
992
1140
  minimatch.sep = sep;
993
1141
  var GLOBSTAR = Symbol("globstar **");
994
1142
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -3018,7 +3166,7 @@ var LRUCache = class _LRUCache {
3018
3166
  // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3019
3167
  import { posix, win32 } from "node:path";
3020
3168
  import { fileURLToPath } from "node:url";
3021
- import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
3169
+ import { lstatSync, readdir as readdirCB, readdirSync as readdirSync3, readlinkSync, realpathSync as rps } from "fs";
3022
3170
  import * as actualFS from "node:fs";
3023
3171
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3024
3172
 
@@ -3905,7 +4053,7 @@ var realpathSync = rps.native;
3905
4053
  var defaultFS = {
3906
4054
  lstatSync,
3907
4055
  readdir: readdirCB,
3908
- readdirSync,
4056
+ readdirSync: readdirSync3,
3909
4057
  readlinkSync,
3910
4058
  realpathSync,
3911
4059
  promises: {
@@ -4165,12 +4313,12 @@ var PathBase = class {
4165
4313
  /**
4166
4314
  * Get the Path object referenced by the string path, resolved from this Path
4167
4315
  */
4168
- resolve(path13) {
4169
- if (!path13) {
4316
+ resolve(path15) {
4317
+ if (!path15) {
4170
4318
  return this;
4171
4319
  }
4172
- const rootPath = this.getRootString(path13);
4173
- const dir = path13.substring(rootPath.length);
4320
+ const rootPath = this.getRootString(path15);
4321
+ const dir = path15.substring(rootPath.length);
4174
4322
  const dirParts = dir.split(this.splitSep);
4175
4323
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4176
4324
  return result;
@@ -4922,8 +5070,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4922
5070
  /**
4923
5071
  * @internal
4924
5072
  */
4925
- getRootString(path13) {
4926
- return win32.parse(path13).root;
5073
+ getRootString(path15) {
5074
+ return win32.parse(path15).root;
4927
5075
  }
4928
5076
  /**
4929
5077
  * @internal
@@ -4969,8 +5117,8 @@ var PathPosix = class _PathPosix extends PathBase {
4969
5117
  /**
4970
5118
  * @internal
4971
5119
  */
4972
- getRootString(path13) {
4973
- return path13.startsWith("/") ? "/" : "";
5120
+ getRootString(path15) {
5121
+ return path15.startsWith("/") ? "/" : "";
4974
5122
  }
4975
5123
  /**
4976
5124
  * @internal
@@ -5059,11 +5207,11 @@ var PathScurryBase = class {
5059
5207
  /**
5060
5208
  * Get the depth of a provided path, string, or the cwd
5061
5209
  */
5062
- depth(path13 = this.cwd) {
5063
- if (typeof path13 === "string") {
5064
- path13 = this.cwd.resolve(path13);
5210
+ depth(path15 = this.cwd) {
5211
+ if (typeof path15 === "string") {
5212
+ path15 = this.cwd.resolve(path15);
5065
5213
  }
5066
- return path13.depth();
5214
+ return path15.depth();
5067
5215
  }
5068
5216
  /**
5069
5217
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5442,7 +5590,7 @@ var PathScurryBase = class {
5442
5590
  const dirs = /* @__PURE__ */ new Set();
5443
5591
  const queue = [entry];
5444
5592
  let processing = 0;
5445
- const process2 = () => {
5593
+ const process3 = () => {
5446
5594
  let paused = false;
5447
5595
  while (!paused) {
5448
5596
  const dir = queue.shift();
@@ -5483,9 +5631,9 @@ var PathScurryBase = class {
5483
5631
  }
5484
5632
  }
5485
5633
  if (paused && !results.flowing) {
5486
- results.once("drain", process2);
5634
+ results.once("drain", process3);
5487
5635
  } else if (!sync2) {
5488
- process2();
5636
+ process3();
5489
5637
  }
5490
5638
  };
5491
5639
  let sync2 = true;
@@ -5493,7 +5641,7 @@ var PathScurryBase = class {
5493
5641
  sync2 = false;
5494
5642
  }
5495
5643
  };
5496
- process2();
5644
+ process3();
5497
5645
  return results;
5498
5646
  }
5499
5647
  streamSync(entry = this.cwd, opts = {}) {
@@ -5511,7 +5659,7 @@ var PathScurryBase = class {
5511
5659
  }
5512
5660
  const queue = [entry];
5513
5661
  let processing = 0;
5514
- const process2 = () => {
5662
+ const process3 = () => {
5515
5663
  let paused = false;
5516
5664
  while (!paused) {
5517
5665
  const dir = queue.shift();
@@ -5545,14 +5693,14 @@ var PathScurryBase = class {
5545
5693
  }
5546
5694
  }
5547
5695
  if (paused && !results.flowing)
5548
- results.once("drain", process2);
5696
+ results.once("drain", process3);
5549
5697
  };
5550
- process2();
5698
+ process3();
5551
5699
  return results;
5552
5700
  }
5553
- chdir(path13 = this.cwd) {
5701
+ chdir(path15 = this.cwd) {
5554
5702
  const oldCwd = this.cwd;
5555
- this.cwd = typeof path13 === "string" ? this.cwd.resolve(path13) : path13;
5703
+ this.cwd = typeof path15 === "string" ? this.cwd.resolve(path15) : path15;
5556
5704
  this.cwd[setAsCwd](oldCwd);
5557
5705
  }
5558
5706
  };
@@ -5908,8 +6056,8 @@ var MatchRecord = class {
5908
6056
  }
5909
6057
  // match, absolute, ifdir
5910
6058
  entries() {
5911
- return [...this.store.entries()].map(([path13, n]) => [
5912
- path13,
6059
+ return [...this.store.entries()].map(([path15, n]) => [
6060
+ path15,
5913
6061
  !!(n & 2),
5914
6062
  !!(n & 1)
5915
6063
  ]);
@@ -6114,9 +6262,9 @@ var GlobUtil = class {
6114
6262
  signal;
6115
6263
  maxDepth;
6116
6264
  includeChildMatches;
6117
- constructor(patterns, path13, opts) {
6265
+ constructor(patterns, path15, opts) {
6118
6266
  this.patterns = patterns;
6119
- this.path = path13;
6267
+ this.path = path15;
6120
6268
  this.opts = opts;
6121
6269
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6122
6270
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6135,11 +6283,11 @@ var GlobUtil = class {
6135
6283
  });
6136
6284
  }
6137
6285
  }
6138
- #ignored(path13) {
6139
- return this.seen.has(path13) || !!this.#ignore?.ignored?.(path13);
6286
+ #ignored(path15) {
6287
+ return this.seen.has(path15) || !!this.#ignore?.ignored?.(path15);
6140
6288
  }
6141
- #childrenIgnored(path13) {
6142
- return !!this.#ignore?.childrenIgnored?.(path13);
6289
+ #childrenIgnored(path15) {
6290
+ return !!this.#ignore?.childrenIgnored?.(path15);
6143
6291
  }
6144
6292
  // backpressure mechanism
6145
6293
  pause() {
@@ -6354,8 +6502,8 @@ var GlobUtil = class {
6354
6502
  };
6355
6503
  var GlobWalker = class extends GlobUtil {
6356
6504
  matches = /* @__PURE__ */ new Set();
6357
- constructor(patterns, path13, opts) {
6358
- super(patterns, path13, opts);
6505
+ constructor(patterns, path15, opts) {
6506
+ super(patterns, path15, opts);
6359
6507
  }
6360
6508
  matchEmit(e) {
6361
6509
  this.matches.add(e);
@@ -6392,8 +6540,8 @@ var GlobWalker = class extends GlobUtil {
6392
6540
  };
6393
6541
  var GlobStream = class extends GlobUtil {
6394
6542
  results;
6395
- constructor(patterns, path13, opts) {
6396
- super(patterns, path13, opts);
6543
+ constructor(patterns, path15, opts) {
6544
+ super(patterns, path15, opts);
6397
6545
  this.results = new Minipass({
6398
6546
  signal: this.signal,
6399
6547
  objectMode: true
@@ -6686,67 +6834,61 @@ var glob = Object.assign(glob_, {
6686
6834
  });
6687
6835
  glob.glob = glob;
6688
6836
 
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\((.+?), .+?\) {/,
6837
+ // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6838
+ import path5 from "node:path";
6839
+ function inlineEvalManifest(code, config) {
6840
+ console.log("# inlineEvalManifest");
6841
+ const manifestJss = globSync(
6842
+ path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6843
+ ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6844
+ return code.replace(
6845
+ /function evalManifest\((.+?), .+?\) {/,
6704
6846
  `$&
6705
- ${manifestJsons.map(
6706
- (manifestJson) => `
6707
- if ($1.endsWith("${manifestJson}")) {
6708
- return ${readFileSync(path3.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6709
- }
6710
- `
6847
+ ${manifestJss.map(
6848
+ (manifestJs) => `
6849
+ if ($1.endsWith("${manifestJs}")) {
6850
+ require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6851
+ return {
6852
+ __RSC_MANIFEST: {
6853
+ "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6854
+ },
6855
+ };
6856
+ }
6857
+ `
6711
6858
  ).join("\n")}
6712
- throw new Error("Unknown loadManifest: " + $1);
6713
- `
6859
+ throw new Error("Unknown evalManifest: " + $1);
6860
+ `
6714
6861
  );
6715
- return code;
6716
6862
  }
6717
6863
 
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);
6735
- `
6864
+ // src/cli/build/patches/to-investigate/inline-middleware-manifest-require.ts
6865
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
6866
+ import path6 from "node:path";
6867
+ function inlineMiddlewareManifestRequire(code, config) {
6868
+ console.log("# inlineMiddlewareManifestRequire");
6869
+ const middlewareManifestPath = path6.join(config.paths.standaloneAppServer, "middleware-manifest.json");
6870
+ const middlewareManifest = existsSync2(middlewareManifestPath) ? JSON.parse(readFileSync2(middlewareManifestPath, "utf-8")) : {};
6871
+ const patchedCode = code.replace(
6872
+ "require(this.middlewareManifestPath)",
6873
+ JSON.stringify(middlewareManifest)
6736
6874
  );
6875
+ if (patchedCode === code) {
6876
+ throw new Error("Patch `inlineMiddlewareManifestRequire` not applied");
6877
+ }
6878
+ return patchedCode;
6737
6879
  }
6738
6880
 
6739
6881
  // 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";
6882
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
6883
+ import path7 from "node:path";
6742
6884
  function inlineNextRequire(code, config) {
6743
6885
  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(
6886
+ const pagesManifestFile = path7.join(config.paths.standaloneAppServer, "pages-manifest.json");
6887
+ const appPathsManifestFile = path7.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6888
+ const pagesManifestFiles = existsSync3(pagesManifestFile) ? Object.values(JSON.parse(readFileSync3(pagesManifestFile, "utf-8"))).map(
6747
6889
  (file) => ".next/server/" + file
6748
6890
  ) : [];
6749
- const appPathsManifestFiles = existsSync2(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync2(appPathsManifestFile, "utf-8"))).map(
6891
+ const appPathsManifestFiles = existsSync3(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync3(appPathsManifestFile, "utf-8"))).map(
6750
6892
  (file) => ".next/server/" + file
6751
6893
  ) : [];
6752
6894
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6758,14 +6900,14 @@ function inlineNextRequire(code, config) {
6758
6900
  ${htmlPages.map(
6759
6901
  (htmlPage) => `
6760
6902
  if (pagePath.endsWith("${htmlPage}")) {
6761
- return ${JSON.stringify(readFileSync2(path5.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6903
+ return ${JSON.stringify(readFileSync3(path7.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6762
6904
  }
6763
6905
  `
6764
6906
  ).join("\n")}
6765
6907
  ${pageModules.map(
6766
6908
  (module) => `
6767
6909
  if (pagePath.endsWith("${module}")) {
6768
- return require("${path5.join(config.paths.standaloneApp, module)}");
6910
+ return require("${path7.join(config.paths.standaloneApp, module)}");
6769
6911
  }
6770
6912
  `
6771
6913
  ).join("\n")}
@@ -6774,69 +6916,129 @@ function inlineNextRequire(code, config) {
6774
6916
  );
6775
6917
  }
6776
6918
 
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}/`, ""));
6919
+ // src/cli/build/patches/investigated/patch-cache.ts
6920
+ import path8 from "node:path";
6921
+ function patchCache(code, config) {
6922
+ console.log("# patchCache");
6923
+ const cacheHandler = path8.join(config.paths.internalPackage, "cli", "cache-handler", "index.mjs");
6924
+ const patchedCode = code.replace(
6925
+ "const { cacheHandler } = this.nextConfig;",
6926
+ `const cacheHandler = null;
6927
+ CacheHandler = (await import('${cacheHandler}')).OpenNextCacheHandler;
6928
+ CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6929
+ `
6930
+ );
6931
+ if (patchedCode === code) {
6932
+ throw new Error("Cache patch not applied");
6933
+ }
6934
+ return patchedCode;
6935
+ }
6936
+
6937
+ // src/cli/build/patches/to-investigate/patch-exception-bubbling.ts
6938
+ function patchExceptionBubbling(code) {
6939
+ console.log("# patchExceptionBubbling");
6940
+ const patchedCode = code.replace('_nextBubbleNoFallback = "1"', "_nextBubbleNoFallback = undefined");
6941
+ if (patchedCode === code) {
6942
+ throw new Error("Patch `patchExceptionBubbling` not applied");
6943
+ }
6944
+ return patchedCode;
6945
+ }
6946
+
6947
+ // src/cli/build/patches/to-investigate/patch-find-dir.ts
6948
+ import { existsSync as existsSync4 } from "node:fs";
6949
+ import path9 from "node:path";
6950
+ function patchFindDir(code, config) {
6951
+ console.log("# patchFindDir");
6784
6952
  return code.replace(
6785
- /function evalManifest\((.+?), .+?\) {/,
6953
+ "function findDir(dir, name) {",
6954
+ `function findDir(dir, name) {
6955
+ if (dir.endsWith(".next/server")) {
6956
+ if (name === "app") {
6957
+ return ${existsSync4(`${path9.join(config.paths.standaloneAppServer, "app")}`)};
6958
+ }
6959
+ if (name === "pages") {
6960
+ return ${existsSync4(`${path9.join(config.paths.standaloneAppServer, "pages")}`)};
6961
+ }
6962
+ }
6963
+ throw new Error("Unknown findDir call: " + dir + " " + name);
6964
+ `
6965
+ );
6966
+ }
6967
+
6968
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
6969
+ import path10 from "node:path";
6970
+ import { readFileSync as readFileSync4 } from "node:fs";
6971
+ function patchReadFile(code, config) {
6972
+ console.log("# patchReadFile");
6973
+ code = code.replace(
6974
+ "getBuildId() {",
6975
+ `getBuildId() {
6976
+ return ${JSON.stringify(readFileSync4(path10.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6977
+ `
6978
+ );
6979
+ const manifestJsons = globSync(path10.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6980
+ (file) => file.replace(config.paths.standaloneApp + "/", "")
6981
+ );
6982
+ code = code.replace(
6983
+ /function loadManifest\((.+?), .+?\) {/,
6786
6984
  `$&
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
- `
6985
+ ${manifestJsons.map(
6986
+ (manifestJson) => `
6987
+ if ($1.endsWith("${manifestJson}")) {
6988
+ return ${readFileSync4(path10.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6989
+ }
6990
+ `
6798
6991
  ).join("\n")}
6799
- throw new Error("Unknown evalManifest: " + $1);
6800
- `
6992
+ throw new Error("Unknown loadManifest: " + $1);
6993
+ `
6801
6994
  );
6995
+ return code;
6996
+ }
6997
+
6998
+ // src/cli/build/patches/investigated/patch-require.ts
6999
+ function patchRequire(code) {
7000
+ console.log("# patchRequire");
7001
+ return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
6802
7002
  }
6803
7003
 
6804
7004
  // src/cli/build/patches/to-investigate/wrangler-deps.ts
6805
- import path7 from "node:path";
6806
- import fs, { writeFileSync } from "node:fs";
7005
+ import { readFileSync as readFileSync5, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
7006
+ import path11 from "node:path";
6807
7007
  function patchWranglerDeps(config) {
6808
7008
  console.log("# patchWranglerDeps");
6809
- const pagesRuntimeFile = path7.join(
6810
- config.paths.standaloneApp,
6811
- "node_modules",
6812
- "next",
6813
- "dist",
6814
- "compiled",
6815
- "next-server",
6816
- "pages.runtime.prod.js"
7009
+ const distPath = getDistPath(config);
7010
+ const pagesRuntimeFile = path11.join(distPath, "compiled", "next-server", "pages.runtime.prod.js");
7011
+ const patchedPagesRuntime = readFileSync5(pagesRuntimeFile, "utf-8").replace(
7012
+ `e.exports=require("critters")`,
7013
+ `e.exports={}`
6817
7014
  );
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(
6821
- config.paths.standaloneApp,
6822
- "node_modules",
6823
- "next",
6824
- "dist",
6825
- "server",
6826
- "lib",
6827
- "trace",
6828
- "tracer.js"
7015
+ writeFileSync2(pagesRuntimeFile, patchedPagesRuntime);
7016
+ const tracerFile = path11.join(distPath, "server", "lib", "trace", "tracer.js");
7017
+ const patchedTracer = readFileSync5(tracerFile, "utf-8").replaceAll(
7018
+ /\w+\s*=\s*require\([^/]*opentelemetry.*\)/g,
7019
+ `throw new Error("@opentelemetry/api")`
6829
7020
  );
6830
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6831
- writeFileSync(tracerFile, pacthedTracer);
7021
+ writeFileSync2(tracerFile, patchedTracer);
7022
+ }
7023
+ function getDistPath(config) {
7024
+ for (const root of [config.paths.standaloneApp, config.paths.standaloneRoot]) {
7025
+ try {
7026
+ const distPath = path11.join(root, "node_modules", "next", "dist");
7027
+ if (statSync2(distPath).isDirectory()) return distPath;
7028
+ } catch {
7029
+ }
7030
+ }
7031
+ throw new Error("Unexpected error: unable to detect the node_modules/next/dist directory");
6832
7032
  }
6833
7033
 
7034
+ // src/cli/build/build-worker.ts
7035
+ import path13 from "node:path";
7036
+
6834
7037
  // 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";
7038
+ import { readFileSync as readFileSync6, readdirSync as readdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
6837
7039
 
6838
7040
  // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6839
- import * as ts from "ts-morph";
7041
+ import * as ts2 from "ts-morph";
6840
7042
  async function getChunkInstallationIdentifiers(sourceFile) {
6841
7043
  const installChunkDeclaration = getInstallChunkDeclaration(sourceFile);
6842
7044
  const installedChunksDeclaration = getInstalledChunksDeclaration(sourceFile, installChunkDeclaration);
@@ -6846,19 +7048,19 @@ async function getChunkInstallationIdentifiers(sourceFile) {
6846
7048
  };
6847
7049
  }
6848
7050
  function getInstallChunkDeclaration(sourceFile) {
6849
- const installChunkDeclaration = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration).find((declaration) => {
6850
- const arrowFunction = declaration.getInitializerIfKind(ts.SyntaxKind.ArrowFunction);
7051
+ const installChunkDeclaration = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.VariableDeclaration).find((declaration) => {
7052
+ const arrowFunction = declaration.getInitializerIfKind(ts2.SyntaxKind.ArrowFunction);
6851
7053
  if (!arrowFunction) return false;
6852
7054
  const functionParameters = arrowFunction.getParameters();
6853
7055
  if (functionParameters.length !== 1) return false;
6854
- const arrowFunctionBodyBlock = arrowFunction.getFirstChildByKind(ts.SyntaxKind.Block);
7056
+ const arrowFunctionBodyBlock = arrowFunction.getFirstChildByKind(ts2.SyntaxKind.Block);
6855
7057
  if (!arrowFunctionBodyBlock) return false;
6856
7058
  const statementKinds = arrowFunctionBodyBlock.getStatements().map((statement) => statement.getKind());
6857
- const forInStatements = statementKinds.filter((s) => s === ts.SyntaxKind.ForInStatement);
6858
- const forStatements = statementKinds.filter((s) => s === ts.SyntaxKind.ForStatement);
7059
+ const forInStatements = statementKinds.filter((s) => s === ts2.SyntaxKind.ForInStatement);
7060
+ const forStatements = statementKinds.filter((s) => s === ts2.SyntaxKind.ForStatement);
6859
7061
  if (forInStatements.length !== 1 || forStatements.length !== 1) return false;
6860
7062
  const parameterName = functionParameters[0].getText();
6861
- const functionParameterAccessedProperties = arrowFunctionBodyBlock.getDescendantsOfKind(ts.SyntaxKind.PropertyAccessExpression).filter(
7063
+ const functionParameterAccessedProperties = arrowFunctionBodyBlock.getDescendantsOfKind(ts2.SyntaxKind.PropertyAccessExpression).filter(
6862
7064
  (propertyAccessExpression) => propertyAccessExpression.getExpression().getText() === parameterName
6863
7065
  ).map((propertyAccessExpression) => propertyAccessExpression.getName());
6864
7066
  if (functionParameterAccessedProperties.join(", ") !== "modules, ids, runtime") return false;
@@ -6870,22 +7072,22 @@ function getInstallChunkDeclaration(sourceFile) {
6870
7072
  return installChunkDeclaration;
6871
7073
  }
6872
7074
  function getInstalledChunksDeclaration(sourceFile, installChunkDeclaration) {
6873
- const allVariableDeclarations = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration);
7075
+ const allVariableDeclarations = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.VariableDeclaration);
6874
7076
  const installChunkDeclarationIdx = allVariableDeclarations.findIndex(
6875
7077
  (declaration) => declaration === installChunkDeclaration
6876
7078
  );
6877
7079
  const installedChunksDeclaration = allVariableDeclarations[installChunkDeclarationIdx - 1];
6878
- if (!installedChunksDeclaration?.getInitializer()?.isKind(ts.SyntaxKind.ObjectLiteralExpression)) {
7080
+ if (!installedChunksDeclaration?.getInitializer()?.isKind(ts2.SyntaxKind.ObjectLiteralExpression)) {
6879
7081
  throw new Error("ERROR: unable to find the installedChunks declaration");
6880
7082
  }
6881
7083
  return installedChunksDeclaration;
6882
7084
  }
6883
7085
 
6884
7086
  // src/cli/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
6885
- import * as ts2 from "ts-morph";
7087
+ import * as ts3 from "ts-morph";
6886
7088
  async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { installedChunks, installChunk }, chunks) {
6887
- const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.ArrowFunction).find((arrowFunction) => {
6888
- const binaryExpression = arrowFunction.getFirstAncestorByKind(ts2.SyntaxKind.BinaryExpression);
7089
+ const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts3.SyntaxKind.ArrowFunction).find((arrowFunction) => {
7090
+ const binaryExpression = arrowFunction.getFirstAncestorByKind(ts3.SyntaxKind.BinaryExpression);
6889
7091
  if (!binaryExpression) return false;
6890
7092
  const binaryExpressionLeft = binaryExpression.getLeft();
6891
7093
  if (!binaryExpressionLeft.getText().endsWith(".f.require")) return false;
@@ -6894,16 +7096,16 @@ async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { instal
6894
7096
  const binaryExpressionRight = binaryExpression.getRight();
6895
7097
  if (binaryExpressionRight !== arrowFunction) return false;
6896
7098
  const arrowFunctionBody = arrowFunction.getBody();
6897
- if (!arrowFunctionBody.isKind(ts2.SyntaxKind.Block)) return false;
7099
+ if (!arrowFunctionBody.isKind(ts3.SyntaxKind.Block)) return false;
6898
7100
  const arrowFunctionBodyText = arrowFunctionBody.getText();
6899
7101
  const functionUsesChunkInstallationVariables = arrowFunctionBodyText.includes(installChunk) && arrowFunctionBodyText.includes(installedChunks);
6900
7102
  if (!functionUsesChunkInstallationVariables) return false;
6901
7103
  const functionParameters = arrowFunction.getParameters();
6902
7104
  if (functionParameters.length !== 2) return false;
6903
- const callsInstallChunk = arrowFunctionBody.getDescendantsOfKind(ts2.SyntaxKind.CallExpression).some((callExpression) => callExpression.getExpression().getText() === installChunk);
7105
+ const callsInstallChunk = arrowFunctionBody.getDescendantsOfKind(ts3.SyntaxKind.CallExpression).some((callExpression) => callExpression.getExpression().getText() === installChunk);
6904
7106
  if (!callsInstallChunk) return false;
6905
7107
  const functionFirstParameterName = functionParameters[0]?.getName();
6906
- const accessesInstalledChunksUsingItsFirstParameter = arrowFunctionBody.getDescendantsOfKind(ts2.SyntaxKind.ElementAccessExpression).some((elementAccess) => {
7108
+ const accessesInstalledChunksUsingItsFirstParameter = arrowFunctionBody.getDescendantsOfKind(ts3.SyntaxKind.ElementAccessExpression).some((elementAccess) => {
6907
7109
  return elementAccess.getExpression().getText() === installedChunks && elementAccess.getArgumentExpression()?.getText() === functionFirstParameterName;
6908
7110
  });
6909
7111
  if (!accessesInstalledChunksUsingItsFirstParameter) return false;
@@ -6925,14 +7127,6 @@ if(${chunkId} === ${chunk}) return ${installChunk}(require("./chunks/${chunk}.js
6925
7127
  return sourceFile.print();
6926
7128
  }
6927
7129
 
6928
- // src/cli/build/utils/ts-parse-file.ts
6929
- import * as ts3 from "ts-morph";
6930
- function tsParseFile(fileContent) {
6931
- const project = new ts3.Project();
6932
- const sourceFile = project.createSourceFile("file.js", fileContent);
6933
- return sourceFile;
6934
- }
6935
-
6936
7130
  // src/cli/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
6937
7131
  async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6938
7132
  const tsSourceFile = tsParseFile(fileContent);
@@ -6946,59 +7140,43 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6946
7140
  }
6947
7141
 
6948
7142
  // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7143
+ import path12 from "node:path";
6949
7144
  async function updateWebpackChunksFile(config) {
6950
7145
  console.log("# updateWebpackChunksFile");
6951
- const webpackRuntimeFile = path8.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6952
- const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6953
- const chunks = readdirSync2(path8.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
7146
+ const webpackRuntimeFile = path12.join(config.paths.standaloneAppServer, "webpack-runtime.js");
7147
+ const fileContent = readFileSync6(webpackRuntimeFile, "utf-8");
7148
+ const chunks = readdirSync4(path12.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6954
7149
  console.log(` - chunk ${chunk}`);
6955
7150
  return chunk.replace(/\.js$/, "");
6956
7151
  });
6957
7152
  const updatedFileContent = await getUpdatedWebpackChunksFileContent(fileContent, chunks);
6958
- writeFileSync2(webpackRuntimeFile, updatedFileContent);
6959
- }
6960
-
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;
7153
+ writeFileSync3(webpackRuntimeFile, updatedFileContent);
6977
7154
  }
6978
7155
 
6979
7156
  // src/cli/build/build-worker.ts
6980
- var packageDistDir = path10.join(path10.dirname(fileURLToPath3(import.meta.url)), "..");
7157
+ var packageDistDir = path13.join(path13.dirname(fileURLToPath3(import.meta.url)), "..");
6981
7158
  async function buildWorker(config) {
6982
7159
  console.log(`\x1B[35m\u2699\uFE0F Copying files...
6983
7160
  \x1B[0m`);
6984
7161
  await cp(
6985
- path10.join(config.paths.dotNext, "static"),
6986
- path10.join(config.paths.builderOutput, "assets", "_next", "static"),
7162
+ path13.join(config.paths.dotNext, "static"),
7163
+ path13.join(config.paths.builderOutput, "assets", "_next", "static"),
6987
7164
  {
6988
7165
  recursive: true
6989
7166
  }
6990
7167
  );
6991
- const publicDir = path10.join(config.paths.nextApp, "public");
6992
- if (existsSync3(publicDir)) {
6993
- await cp(publicDir, path10.join(config.paths.builderOutput, "assets"), {
7168
+ const publicDir = path13.join(config.paths.nextApp, "public");
7169
+ if (existsSync5(publicDir)) {
7170
+ await cp(publicDir, path13.join(config.paths.builderOutput, "assets"), {
6994
7171
  recursive: true
6995
7172
  });
6996
7173
  }
7174
+ copyPrerenderedRoutes(config);
6997
7175
  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(
7176
+ const templateDir = path13.join(config.paths.internalPackage, "cli", "templates");
7177
+ const workerEntrypoint = path13.join(templateDir, "worker.ts");
7178
+ const workerOutputFile = path13.join(config.paths.builderOutput, "index.mjs");
7179
+ const nextConfigStr = readFileSync7(path13.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
7002
7180
  /const nextConfig = ({.+?})\n/
7003
7181
  )?.[1] ?? {};
7004
7182
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
@@ -7017,15 +7195,15 @@ async function buildWorker(config) {
7017
7195
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
7018
7196
  // eval("require")("bufferutil");
7019
7197
  // eval("require")("utf-8-validate");
7020
- "next/dist/compiled/ws": path10.join(templateDir, "shims", "empty.ts"),
7198
+ "next/dist/compiled/ws": path13.join(templateDir, "shims", "empty.ts"),
7021
7199
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
7022
7200
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
7023
7201
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
7024
7202
  // QUESTION: Why did I encountered this but mhart didn't?
7025
- "next/dist/compiled/edge-runtime": path10.join(templateDir, "shims", "empty.ts"),
7203
+ "next/dist/compiled/edge-runtime": path13.join(templateDir, "shims", "empty.ts"),
7026
7204
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7027
7205
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7028
- "@next/env": path10.join(templateDir, "shims", "env.ts")
7206
+ "@next/env": path13.join(templateDir, "shims", "env.ts")
7029
7207
  },
7030
7208
  define: {
7031
7209
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7035,10 +7213,6 @@ async function buildWorker(config) {
7035
7213
  // Note: we need the __non_webpack_require__ variable declared as it is used by next-server:
7036
7214
  // https://github.com/vercel/next.js/blob/be0c3283/packages/next/src/server/next-server.ts#L116-L119
7037
7215
  __non_webpack_require__: "require",
7038
- // The next.js server can run in minimal mode: https://github.com/vercel/next.js/blob/aa90fe9bb/packages/next/src/server/base-server.ts#L510-L511
7039
- // this avoids some extra (/problematic) `require` calls, such as here: https://github.com/vercel/next.js/blob/aa90fe9bb/packages/next/src/server/next-server.ts#L1259
7040
- // that's wht we enable it
7041
- "process.env.NEXT_PRIVATE_MINIMAL_MODE": "true",
7042
7216
  // Ask mhart if he can explain why the `define`s below are necessary
7043
7217
  "process.env.NEXT_RUNTIME": '"nodejs"',
7044
7218
  "process.env.NODE_ENV": '"production"',
@@ -7098,112 +7272,99 @@ async function updateWorkerBundledCode(workerOutputFile, config) {
7098
7272
  patchedCode = patchFindDir(patchedCode, config);
7099
7273
  patchedCode = inlineEvalManifest(patchedCode, config);
7100
7274
  patchedCode = patchCache(patchedCode, config);
7275
+ patchedCode = inlineMiddlewareManifestRequire(patchedCode, config);
7276
+ patchedCode = patchExceptionBubbling(patchedCode);
7101
7277
  await writeFile(workerOutputFile, patchedCode);
7102
7278
  }
7103
7279
  function createFixRequiresESBuildPlugin(templateDir) {
7104
7280
  return {
7105
7281
  name: "replaceRelative",
7106
7282
  setup(build3) {
7107
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7108
- path: path10.join(templateDir, "shims", "empty.ts")
7283
+ build3.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7284
+ path: path13.join(templateDir, "shims", "empty.ts")
7109
7285
  }));
7110
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7111
- path: path10.join(templateDir, "shims", "empty.ts")
7286
+ build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7287
+ path: path13.join(templateDir, "shims", "empty.ts")
7112
7288
  }));
7113
7289
  }
7114
7290
  };
7115
7291
  }
7116
7292
 
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
7293
  // src/cli/build/index.ts
7184
7294
  import { cpSync as cpSync2 } from "node:fs";
7185
- import path12 from "node:path";
7295
+ import path14 from "node:path";
7296
+ import { rm } from "node:fs/promises";
7186
7297
  async function build2(appDir, opts) {
7187
7298
  if (!opts.skipBuild) {
7188
- buildNextjsApp(appDir);
7299
+ await buildNextjsApp(appDir);
7189
7300
  }
7190
7301
  if (!containsDotNextDir(appDir)) {
7191
7302
  throw new Error(`.next folder not found in ${appDir}`);
7192
7303
  }
7193
- const outputDir2 = path12.resolve(opts.outputDir ?? appDir, ".worker-next");
7304
+ const outputDir2 = path14.resolve(opts.outputDir ?? appDir, ".worker-next");
7194
7305
  await cleanDirectory(outputDir2);
7195
- cpSync2(path12.join(appDir, ".next"), path12.join(outputDir2, ".next"), { recursive: true });
7306
+ cpSync2(path14.join(appDir, ".next"), path14.join(outputDir2, ".next"), { recursive: true });
7196
7307
  const config = getConfig(appDir, outputDir2);
7197
7308
  await buildWorker(config);
7198
7309
  }
7199
- async function cleanDirectory(path13) {
7200
- return await rm(path13, { recursive: true, force: true });
7310
+ async function cleanDirectory(path15) {
7311
+ return await rm(path15, { recursive: true, force: true });
7201
7312
  }
7202
7313
 
7203
7314
  // src/cli/index.ts
7315
+ import { existsSync as existsSync6 } from "node:fs";
7316
+
7317
+ // src/cli/args.ts
7318
+ import { mkdirSync as mkdirSync2, statSync as statSync3 } from "node:fs";
7319
+ import { parseArgs } from "node:util";
7320
+ import { resolve } from "node:path";
7321
+ function getArgs() {
7322
+ const {
7323
+ values: { skipBuild: skipBuild2, output }
7324
+ } = parseArgs({
7325
+ options: {
7326
+ skipBuild: {
7327
+ type: "boolean",
7328
+ short: "s",
7329
+ default: false
7330
+ },
7331
+ output: {
7332
+ type: "string",
7333
+ short: "o"
7334
+ }
7335
+ },
7336
+ allowPositionals: false
7337
+ });
7338
+ const outputDir2 = output ? resolve(output) : void 0;
7339
+ if (outputDir2) {
7340
+ assertDirArg(outputDir2, "output", true);
7341
+ }
7342
+ return {
7343
+ outputDir: outputDir2,
7344
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7345
+ };
7346
+ }
7347
+ function assertDirArg(path15, argName, make) {
7348
+ let dirStats;
7349
+ try {
7350
+ dirStats = statSync3(path15);
7351
+ } catch {
7352
+ if (!make) {
7353
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7354
+ }
7355
+ mkdirSync2(path15);
7356
+ return;
7357
+ }
7358
+ if (!dirStats.isDirectory()) {
7359
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7360
+ }
7361
+ }
7362
+
7363
+ // src/cli/index.ts
7364
+ import { resolve as resolve2 } from "node:path";
7204
7365
  var nextAppDir = resolve2(".");
7205
7366
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7206
- if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {
7367
+ if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync6(`./next.config.${ext2}`))) {
7207
7368
  throw new Error("Error: Not in a Next.js app project");
7208
7369
  }
7209
7370
  var { skipBuild, outputDir } = getArgs();