@opennextjs/cloudflare 0.0.0-fd3c2b9 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -24,9 +25,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
25
  mod
25
26
  ));
26
27
 
27
- // ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
28
+ // ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
28
29
  var require_balanced_match = __commonJS({
29
- "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
30
+ "../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
30
31
  "use strict";
31
32
  module.exports = balanced;
32
33
  function balanced(a, b, str) {
@@ -82,9 +83,9 @@ var require_balanced_match = __commonJS({
82
83
  }
83
84
  });
84
85
 
85
- // ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
86
+ // ../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
86
87
  var require_brace_expansion = __commonJS({
87
- "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
88
+ "../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
88
89
  "use strict";
89
90
  var balanced = require_balanced_match();
90
91
  module.exports = expandTop;
@@ -233,68 +234,170 @@ var require_brace_expansion = __commonJS({
233
234
  }
234
235
  });
235
236
 
236
- // src/index.ts
237
- import { resolve as resolve2 } from "node:path";
238
-
239
- // src/args.ts
240
- import { mkdirSync, statSync } from "node:fs";
241
- import { parseArgs } from "node:util";
242
- import { resolve } from "node:path";
243
- function getArgs() {
244
- const {
245
- values: { skipBuild: skipBuild2, output }
246
- } = parseArgs({
247
- options: {
248
- skipBuild: {
249
- type: "boolean",
250
- short: "s",
251
- default: false
252
- },
253
- output: {
254
- type: "string",
255
- short: "o"
256
- }
257
- },
258
- allowPositionals: false
259
- });
260
- const outputDir2 = output ? resolve(output) : void 0;
261
- if (outputDir2) {
262
- assertDirArg(outputDir2, "output", true);
263
- }
237
+ // src/cli/config.ts
238
+ import path, { relative } from "node:path";
239
+ import { readdirSync, statSync } from "node:fs";
240
+ var PACKAGE_NAME = "@opennextjs/cloudflare";
241
+ function getConfig(appDir, outputDir2) {
242
+ const dotNext = path.join(outputDir2, ".next");
243
+ const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
244
+ const standaloneRoot = path.join(dotNext, "standalone");
245
+ const standaloneApp = path.join(standaloneRoot, appPath);
246
+ const standaloneAppDotNext = path.join(standaloneApp, ".next");
247
+ const standaloneAppServer = path.join(standaloneAppDotNext, "server");
248
+ const nodeModules = path.join(standaloneApp, "node_modules");
249
+ const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/"));
250
+ const internalTemplates = path.join(internalPackage, "cli", "templates");
251
+ process.env.__OPENNEXT_KV_BINDING_NAME ??= "NEXT_CACHE_WORKERS_KV";
264
252
  return {
265
- outputDir: outputDir2,
266
- skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
253
+ buildTimestamp: Date.now(),
254
+ paths: {
255
+ nextApp: appDir,
256
+ builderOutput: outputDir2,
257
+ dotNext,
258
+ standaloneRoot,
259
+ standaloneApp,
260
+ standaloneAppDotNext,
261
+ standaloneAppServer,
262
+ internalPackage,
263
+ internalTemplates
264
+ },
265
+ cache: {
266
+ kvBindingName: process.env.__OPENNEXT_KV_BINDING_NAME
267
+ },
268
+ internalPackageName: PACKAGE_NAME
267
269
  };
268
270
  }
269
- function assertDirArg(path6, argName, make) {
270
- let dirStats;
271
+ function containsDotNextDir(folder) {
271
272
  try {
272
- dirStats = statSync(path6);
273
+ return statSync(path.join(folder, ".next")).isDirectory();
273
274
  } catch {
274
- if (!make) {
275
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
275
+ return false;
276
+ }
277
+ }
278
+ function getNextjsApplicationPath(dotNextDir) {
279
+ const serverPath = findServerParentPath(dotNextDir);
280
+ if (!serverPath) {
281
+ throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
282
+ }
283
+ return relative(path.join(dotNextDir, "standalone"), serverPath);
284
+ }
285
+ function findServerParentPath(parentPath) {
286
+ try {
287
+ if (statSync(path.join(parentPath, ".next", "server")).isDirectory()) {
288
+ return parentPath;
276
289
  }
277
- mkdirSync(path6);
278
- return;
290
+ } catch {
279
291
  }
280
- if (!dirStats.isDirectory()) {
281
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
292
+ const folders = readdirSync(parentPath);
293
+ for (const folder of folders) {
294
+ const subFolder = path.join(parentPath, folder);
295
+ if (statSync(path.join(parentPath, folder)).isDirectory()) {
296
+ const dirServerPath = findServerParentPath(subFolder);
297
+ if (dirServerPath) {
298
+ return dirServerPath;
299
+ }
300
+ }
282
301
  }
283
302
  }
284
303
 
285
- // src/index.ts
286
- import { existsSync as existsSync3 } from "node:fs";
304
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/constants.mjs
305
+ var AGENTS = [
306
+ "npm",
307
+ "yarn",
308
+ "yarn@berry",
309
+ "pnpm",
310
+ "pnpm@6",
311
+ "bun"
312
+ ];
313
+ var LOCKS = {
314
+ "bun.lockb": "bun",
315
+ "pnpm-lock.yaml": "pnpm",
316
+ "yarn.lock": "yarn",
317
+ "package-lock.json": "npm",
318
+ "npm-shrinkwrap.json": "npm"
319
+ };
287
320
 
288
- // src/build/build.ts
289
- import { rm } from "node:fs/promises";
321
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/detect.mjs
322
+ import fs from "node:fs";
323
+ import fsPromises from "node:fs/promises";
324
+ import path2 from "node:path";
325
+ import process2 from "node:process";
326
+ async function detect({ cwd, onUnknown } = {}) {
327
+ for (const directory of lookup(cwd)) {
328
+ for (const lock of Object.keys(LOCKS)) {
329
+ if (await fileExists(path2.join(directory, lock))) {
330
+ const name = LOCKS[lock];
331
+ const result2 = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
332
+ if (result2)
333
+ return result2;
334
+ else
335
+ return { name, agent: name };
336
+ }
337
+ }
338
+ const result = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
339
+ if (result)
340
+ return result;
341
+ }
342
+ return null;
343
+ }
344
+ function* lookup(cwd = process2.cwd()) {
345
+ let directory = path2.resolve(cwd);
346
+ const { root } = path2.parse(directory);
347
+ while (directory && directory !== root) {
348
+ yield directory;
349
+ directory = path2.dirname(directory);
350
+ }
351
+ }
352
+ async function parsePackageJson(filepath, onUnknown) {
353
+ if (!filepath || !await fileExists(filepath))
354
+ return null;
355
+ try {
356
+ const pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
357
+ let agent;
358
+ if (typeof pkg.packageManager === "string") {
359
+ const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
360
+ let version = ver;
361
+ if (name === "yarn" && Number.parseInt(ver) > 1) {
362
+ agent = "yarn@berry";
363
+ version = "berry";
364
+ return { name, agent, version };
365
+ } else if (name === "pnpm" && Number.parseInt(ver) < 7) {
366
+ agent = "pnpm@6";
367
+ return { name, agent, version };
368
+ } else if (AGENTS.includes(name)) {
369
+ agent = name;
370
+ return { name, agent, version };
371
+ } else {
372
+ return onUnknown?.(pkg.packageManager) ?? null;
373
+ }
374
+ }
375
+ } catch {
376
+ }
377
+ return null;
378
+ }
379
+ async function fileExists(filePath) {
380
+ try {
381
+ const stats = await fsPromises.stat(filePath);
382
+ if (stats.isFile()) {
383
+ return true;
384
+ }
385
+ } catch {
386
+ }
387
+ return false;
388
+ }
290
389
 
291
- // src/build/build-next-app.ts
390
+ // src/cli/build/build-next-app.ts
292
391
  import { execSync } from "node:child_process";
293
- function buildNextjsApp(nextAppDir2) {
294
- runNextBuildCommand("pnpm", nextAppDir2);
392
+ async function buildNextjsApp(nextAppDir2) {
393
+ const pm = await detect();
394
+ if (!pm) {
395
+ throw new Error("Fatal Error: package manager detection failed, aborting");
396
+ }
397
+ runNextBuildCommand(pm.name, nextAppDir2);
295
398
  }
296
399
  function runNextBuildCommand(packager, nextAppDir2) {
297
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
400
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
298
401
  execSync(command, {
299
402
  stdio: "inherit",
300
403
  cwd: nextAppDir2,
@@ -307,34 +410,82 @@ function runNextBuildCommand(packager, nextAppDir2) {
307
410
  });
308
411
  }
309
412
 
310
- // src/build/build-worker.ts
311
- import { build } from "esbuild";
312
- import { readFileSync as readFileSync4 } from "node:fs";
413
+ // src/cli/build/build-worker.ts
414
+ import { build as build2 } from "esbuild";
313
415
  import { cp, readFile, writeFile } from "node:fs/promises";
416
+ import { existsSync as existsSync5, readFileSync as readFileSync7 } from "node:fs";
314
417
 
315
- // src/build/patches/investigated/patch-require.ts
316
- function patchRequire(code) {
317
- console.log("# patchRequire");
318
- return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
418
+ // src/cli/build/patches/investigated/copy-package-cli-files.ts
419
+ import { cpSync } from "node:fs";
420
+ import path3 from "node:path";
421
+ function copyPackageCliFiles(packageDistDir2, config) {
422
+ console.log("# copyPackageTemplateFiles");
423
+ const sourceDir = path3.join(packageDistDir2, "cli");
424
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
425
+ cpSync(sourceDir, destinationDir, { recursive: true });
319
426
  }
320
427
 
321
- // src/build/patches/investigated/copy-templates.ts
322
- import path from "node:path";
323
- import { cpSync } from "node:fs";
324
- function copyTemplates(srcDir, nextjsAppPaths) {
325
- console.log("# copyTemplates");
326
- const destDir = path.join(nextjsAppPaths.standaloneAppDir, "node_modules/cf/templates");
327
- cpSync(srcDir, destDir, { recursive: true });
328
- return destDir;
428
+ // src/cli/build/utils/ts-parse-file.ts
429
+ import * as ts from "ts-morph";
430
+ function tsParseFile(fileContent) {
431
+ const project = new ts.Project();
432
+ const sourceFile = project.createSourceFile("file.js", fileContent);
433
+ return sourceFile;
434
+ }
435
+
436
+ // src/cli/constants/incremental-cache.ts
437
+ var NEXT_META_SUFFIX = ".meta";
438
+ var SEED_DATA_DIR = "cdn-cgi/_cf_seed_data";
439
+
440
+ // src/cli/build/utils/copy-prerendered-routes.ts
441
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
442
+ import { dirname, join as join2 } from "node:path";
443
+
444
+ // src/cli/build/utils/read-paths-recursively.ts
445
+ import { join } from "node:path";
446
+ import { readdirSync as readdirSync2 } from "node:fs";
447
+ function readPathsRecursively(dir) {
448
+ try {
449
+ const files = readdirSync2(dir, { withFileTypes: true });
450
+ return files.flatMap((file) => {
451
+ const filePath = join(dir, file.name);
452
+ return file.isDirectory() ? readPathsRecursively(filePath) : filePath;
453
+ });
454
+ } catch {
455
+ return [];
456
+ }
457
+ }
458
+
459
+ // src/cli/build/utils/copy-prerendered-routes.ts
460
+ function copyPrerenderedRoutes(config) {
461
+ console.log("# copyPrerenderedRoutes");
462
+ const serverAppDirPath = join2(config.paths.standaloneAppServer, "app");
463
+ const prerenderManifestPath = join2(config.paths.standaloneAppDotNext, "prerender-manifest.json");
464
+ const outputPath = join2(config.paths.builderOutput, "assets", SEED_DATA_DIR);
465
+ const prerenderManifest = existsSync(prerenderManifestPath) ? JSON.parse(readFileSync(prerenderManifestPath, "utf8")) : {};
466
+ const prerenderedRoutes = Object.keys(prerenderManifest.routes);
467
+ const prerenderedAssets = readPathsRecursively(serverAppDirPath).map((fullPath) => ({ fullPath, relativePath: fullPath.replace(serverAppDirPath, "") })).filter(
468
+ ({ relativePath }) => prerenderedRoutes.includes(relativePath.replace(/\.\w+$/, "").replace(/^\/index$/, "/"))
469
+ );
470
+ prerenderedAssets.forEach(({ fullPath, relativePath }) => {
471
+ const destPath = join2(outputPath, relativePath);
472
+ mkdirSync(dirname(destPath), { recursive: true });
473
+ if (fullPath.endsWith(NEXT_META_SUFFIX)) {
474
+ const data = JSON.parse(readFileSync(fullPath, "utf8"));
475
+ writeFileSync(destPath, JSON.stringify({ ...data, lastModified: config.buildTimestamp }));
476
+ } else {
477
+ copyFileSync(fullPath, destPath);
478
+ }
479
+ });
329
480
  }
330
481
 
331
- // src/build/patches/to-investigate/patch-read-file.ts
332
- import { readFileSync } from "node:fs";
482
+ // src/cli/build/build-worker.ts
483
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
333
484
 
334
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
485
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
335
486
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
336
487
 
337
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/assert-valid-pattern.js
488
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/assert-valid-pattern.js
338
489
  var MAX_PATTERN_LENGTH = 1024 * 64;
339
490
  var assertValidPattern = (pattern) => {
340
491
  if (typeof pattern !== "string") {
@@ -345,7 +496,7 @@ var assertValidPattern = (pattern) => {
345
496
  }
346
497
  };
347
498
 
348
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/brace-expressions.js
499
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/brace-expressions.js
349
500
  var posixClasses = {
350
501
  "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
351
502
  "[:alpha:]": ["\\p{L}\\p{Nl}", true],
@@ -454,12 +605,12 @@ var parseClass = (glob2, position) => {
454
605
  return [comb, uflag, endPos - pos, true];
455
606
  };
456
607
 
457
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/unescape.js
608
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/unescape.js
458
609
  var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
459
610
  return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
460
611
  };
461
612
 
462
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/ast.js
613
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/ast.js
463
614
  var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
464
615
  var isExtglobType = (c) => types.has(c);
465
616
  var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
@@ -938,12 +1089,12 @@ var AST = class _AST {
938
1089
  }
939
1090
  };
940
1091
 
941
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/escape.js
1092
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/escape.js
942
1093
  var escape = (s, { windowsPathsNoEscape = false } = {}) => {
943
1094
  return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
944
1095
  };
945
1096
 
946
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
1097
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
947
1098
  var minimatch = (p, pattern, options = {}) => {
948
1099
  assertValidPattern(pattern);
949
1100
  if (!options.nocomment && pattern.charAt(0) === "#") {
@@ -1002,11 +1153,11 @@ var qmarksTestNoExtDot = ([$0]) => {
1002
1153
  return (f) => f.length === len && f !== "." && f !== "..";
1003
1154
  };
1004
1155
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
1005
- var path2 = {
1156
+ var path4 = {
1006
1157
  win32: { sep: "\\" },
1007
1158
  posix: { sep: "/" }
1008
1159
  };
1009
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1160
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
1010
1161
  minimatch.sep = sep;
1011
1162
  var GLOBSTAR = Symbol("globstar **");
1012
1163
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -1661,10 +1812,10 @@ minimatch.Minimatch = Minimatch;
1661
1812
  minimatch.escape = escape;
1662
1813
  minimatch.unescape = unescape;
1663
1814
 
1664
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
1815
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
1665
1816
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1666
1817
 
1667
- // ../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/dist/esm/index.js
1818
+ // ../../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/dist/esm/index.js
1668
1819
  var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
1669
1820
  var warned = /* @__PURE__ */ new Set();
1670
1821
  var PROCESS = typeof process === "object" && !!process ? process : {};
@@ -3033,14 +3184,14 @@ var LRUCache = class _LRUCache {
3033
3184
  }
3034
3185
  };
3035
3186
 
3036
- // ../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3187
+ // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3037
3188
  import { posix, win32 } from "node:path";
3038
3189
  import { fileURLToPath } from "node:url";
3039
- import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
3190
+ import { lstatSync, readdir as readdirCB, readdirSync as readdirSync3, readlinkSync, realpathSync as rps } from "fs";
3040
3191
  import * as actualFS from "node:fs";
3041
3192
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3042
3193
 
3043
- // ../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/dist/esm/index.js
3194
+ // ../../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/dist/esm/index.js
3044
3195
  import { EventEmitter } from "node:events";
3045
3196
  import Stream from "node:stream";
3046
3197
  import { StringDecoder } from "node:string_decoder";
@@ -3918,12 +4069,12 @@ var Minipass = class extends EventEmitter {
3918
4069
  }
3919
4070
  };
3920
4071
 
3921
- // ../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
4072
+ // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3922
4073
  var realpathSync = rps.native;
3923
4074
  var defaultFS = {
3924
4075
  lstatSync,
3925
4076
  readdir: readdirCB,
3926
- readdirSync,
4077
+ readdirSync: readdirSync3,
3927
4078
  readlinkSync,
3928
4079
  realpathSync,
3929
4080
  promises: {
@@ -4183,12 +4334,12 @@ var PathBase = class {
4183
4334
  /**
4184
4335
  * Get the Path object referenced by the string path, resolved from this Path
4185
4336
  */
4186
- resolve(path6) {
4187
- if (!path6) {
4337
+ resolve(path14) {
4338
+ if (!path14) {
4188
4339
  return this;
4189
4340
  }
4190
- const rootPath = this.getRootString(path6);
4191
- const dir = path6.substring(rootPath.length);
4341
+ const rootPath = this.getRootString(path14);
4342
+ const dir = path14.substring(rootPath.length);
4192
4343
  const dirParts = dir.split(this.splitSep);
4193
4344
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4194
4345
  return result;
@@ -4940,8 +5091,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4940
5091
  /**
4941
5092
  * @internal
4942
5093
  */
4943
- getRootString(path6) {
4944
- return win32.parse(path6).root;
5094
+ getRootString(path14) {
5095
+ return win32.parse(path14).root;
4945
5096
  }
4946
5097
  /**
4947
5098
  * @internal
@@ -4987,8 +5138,8 @@ var PathPosix = class _PathPosix extends PathBase {
4987
5138
  /**
4988
5139
  * @internal
4989
5140
  */
4990
- getRootString(path6) {
4991
- return path6.startsWith("/") ? "/" : "";
5141
+ getRootString(path14) {
5142
+ return path14.startsWith("/") ? "/" : "";
4992
5143
  }
4993
5144
  /**
4994
5145
  * @internal
@@ -5077,11 +5228,11 @@ var PathScurryBase = class {
5077
5228
  /**
5078
5229
  * Get the depth of a provided path, string, or the cwd
5079
5230
  */
5080
- depth(path6 = this.cwd) {
5081
- if (typeof path6 === "string") {
5082
- path6 = this.cwd.resolve(path6);
5231
+ depth(path14 = this.cwd) {
5232
+ if (typeof path14 === "string") {
5233
+ path14 = this.cwd.resolve(path14);
5083
5234
  }
5084
- return path6.depth();
5235
+ return path14.depth();
5085
5236
  }
5086
5237
  /**
5087
5238
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5460,7 +5611,7 @@ var PathScurryBase = class {
5460
5611
  const dirs = /* @__PURE__ */ new Set();
5461
5612
  const queue = [entry];
5462
5613
  let processing = 0;
5463
- const process2 = () => {
5614
+ const process3 = () => {
5464
5615
  let paused = false;
5465
5616
  while (!paused) {
5466
5617
  const dir = queue.shift();
@@ -5501,9 +5652,9 @@ var PathScurryBase = class {
5501
5652
  }
5502
5653
  }
5503
5654
  if (paused && !results.flowing) {
5504
- results.once("drain", process2);
5655
+ results.once("drain", process3);
5505
5656
  } else if (!sync2) {
5506
- process2();
5657
+ process3();
5507
5658
  }
5508
5659
  };
5509
5660
  let sync2 = true;
@@ -5511,7 +5662,7 @@ var PathScurryBase = class {
5511
5662
  sync2 = false;
5512
5663
  }
5513
5664
  };
5514
- process2();
5665
+ process3();
5515
5666
  return results;
5516
5667
  }
5517
5668
  streamSync(entry = this.cwd, opts = {}) {
@@ -5529,7 +5680,7 @@ var PathScurryBase = class {
5529
5680
  }
5530
5681
  const queue = [entry];
5531
5682
  let processing = 0;
5532
- const process2 = () => {
5683
+ const process3 = () => {
5533
5684
  let paused = false;
5534
5685
  while (!paused) {
5535
5686
  const dir = queue.shift();
@@ -5563,14 +5714,14 @@ var PathScurryBase = class {
5563
5714
  }
5564
5715
  }
5565
5716
  if (paused && !results.flowing)
5566
- results.once("drain", process2);
5717
+ results.once("drain", process3);
5567
5718
  };
5568
- process2();
5719
+ process3();
5569
5720
  return results;
5570
5721
  }
5571
- chdir(path6 = this.cwd) {
5722
+ chdir(path14 = this.cwd) {
5572
5723
  const oldCwd = this.cwd;
5573
- this.cwd = typeof path6 === "string" ? this.cwd.resolve(path6) : path6;
5724
+ this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
5574
5725
  this.cwd[setAsCwd](oldCwd);
5575
5726
  }
5576
5727
  };
@@ -5644,7 +5795,7 @@ var PathScurryDarwin = class extends PathScurryPosix {
5644
5795
  var Path = process.platform === "win32" ? PathWin32 : PathPosix;
5645
5796
  var PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
5646
5797
 
5647
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/pattern.js
5798
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/pattern.js
5648
5799
  var isPatternList = (pl) => pl.length >= 1;
5649
5800
  var isGlobList = (gl) => gl.length >= 1;
5650
5801
  var Pattern = class _Pattern {
@@ -5809,7 +5960,7 @@ var Pattern = class _Pattern {
5809
5960
  }
5810
5961
  };
5811
5962
 
5812
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/ignore.js
5963
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/ignore.js
5813
5964
  var defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
5814
5965
  var Ignore = class {
5815
5966
  relative;
@@ -5896,7 +6047,7 @@ var Ignore = class {
5896
6047
  }
5897
6048
  };
5898
6049
 
5899
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/processor.js
6050
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/processor.js
5900
6051
  var HasWalkedCache = class _HasWalkedCache {
5901
6052
  store;
5902
6053
  constructor(store = /* @__PURE__ */ new Map()) {
@@ -5926,8 +6077,8 @@ var MatchRecord = class {
5926
6077
  }
5927
6078
  // match, absolute, ifdir
5928
6079
  entries() {
5929
- return [...this.store.entries()].map(([path6, n]) => [
5930
- path6,
6080
+ return [...this.store.entries()].map(([path14, n]) => [
6081
+ path14,
5931
6082
  !!(n & 2),
5932
6083
  !!(n & 1)
5933
6084
  ]);
@@ -6117,7 +6268,7 @@ var Processor = class _Processor {
6117
6268
  }
6118
6269
  };
6119
6270
 
6120
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/walker.js
6271
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/walker.js
6121
6272
  var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
6122
6273
  var GlobUtil = class {
6123
6274
  path;
@@ -6132,9 +6283,9 @@ var GlobUtil = class {
6132
6283
  signal;
6133
6284
  maxDepth;
6134
6285
  includeChildMatches;
6135
- constructor(patterns, path6, opts) {
6286
+ constructor(patterns, path14, opts) {
6136
6287
  this.patterns = patterns;
6137
- this.path = path6;
6288
+ this.path = path14;
6138
6289
  this.opts = opts;
6139
6290
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6140
6291
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6153,11 +6304,11 @@ var GlobUtil = class {
6153
6304
  });
6154
6305
  }
6155
6306
  }
6156
- #ignored(path6) {
6157
- return this.seen.has(path6) || !!this.#ignore?.ignored?.(path6);
6307
+ #ignored(path14) {
6308
+ return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
6158
6309
  }
6159
- #childrenIgnored(path6) {
6160
- return !!this.#ignore?.childrenIgnored?.(path6);
6310
+ #childrenIgnored(path14) {
6311
+ return !!this.#ignore?.childrenIgnored?.(path14);
6161
6312
  }
6162
6313
  // backpressure mechanism
6163
6314
  pause() {
@@ -6372,8 +6523,8 @@ var GlobUtil = class {
6372
6523
  };
6373
6524
  var GlobWalker = class extends GlobUtil {
6374
6525
  matches = /* @__PURE__ */ new Set();
6375
- constructor(patterns, path6, opts) {
6376
- super(patterns, path6, opts);
6526
+ constructor(patterns, path14, opts) {
6527
+ super(patterns, path14, opts);
6377
6528
  }
6378
6529
  matchEmit(e) {
6379
6530
  this.matches.add(e);
@@ -6410,8 +6561,8 @@ var GlobWalker = class extends GlobUtil {
6410
6561
  };
6411
6562
  var GlobStream = class extends GlobUtil {
6412
6563
  results;
6413
- constructor(patterns, path6, opts) {
6414
- super(patterns, path6, opts);
6564
+ constructor(patterns, path14, opts) {
6565
+ super(patterns, path14, opts);
6415
6566
  this.results = new Minipass({
6416
6567
  signal: this.signal,
6417
6568
  objectMode: true
@@ -6444,7 +6595,7 @@ var GlobStream = class extends GlobUtil {
6444
6595
  }
6445
6596
  };
6446
6597
 
6447
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
6598
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
6448
6599
  var defaultPlatform3 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
6449
6600
  var Glob = class {
6450
6601
  absolute;
@@ -6644,7 +6795,7 @@ var Glob = class {
6644
6795
  }
6645
6796
  };
6646
6797
 
6647
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/has-magic.js
6798
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/has-magic.js
6648
6799
  var hasMagic = (pattern, options = {}) => {
6649
6800
  if (!Array.isArray(pattern)) {
6650
6801
  pattern = [pattern];
@@ -6656,7 +6807,7 @@ var hasMagic = (pattern, options = {}) => {
6656
6807
  return false;
6657
6808
  };
6658
6809
 
6659
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/index.js
6810
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/index.js
6660
6811
  function globStreamSync(pattern, options = {}) {
6661
6812
  return new Glob(pattern, options).streamSync();
6662
6813
  }
@@ -6704,60 +6855,63 @@ var glob = Object.assign(glob_, {
6704
6855
  });
6705
6856
  glob.glob = glob;
6706
6857
 
6707
- // src/build/patches/to-investigate/patch-read-file.ts
6708
- function patchReadFile(code, nextjsAppPaths) {
6709
- console.log("# patchReadFile");
6710
- code = code.replace(
6711
- "getBuildId() {",
6712
- `getBuildId() {
6713
- return ${JSON.stringify(readFileSync(`${nextjsAppPaths.standaloneAppDotNextDir}/BUILD_ID`, "utf-8"))};
6714
- `
6715
- );
6716
- const manifestJsons = globSync(`${nextjsAppPaths.standaloneAppDotNextDir}/**/*-manifest.json`).map(
6717
- (file) => file.replace(nextjsAppPaths.standaloneAppDir + "/", "")
6858
+ // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6859
+ import path5 from "node:path";
6860
+ function inlineEvalManifest(code, config) {
6861
+ console.log("# inlineEvalManifest");
6862
+ const manifestJss = globSync(
6863
+ path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js").replaceAll(path5.sep, path5.posix.sep)
6864
+ ).map(
6865
+ (file) => file.replaceAll(path5.sep, path5.posix.sep).replace(config.paths.standaloneApp.replaceAll(path5.sep, path5.posix.sep) + path5.posix.sep, "")
6718
6866
  );
6719
- code = code.replace(
6720
- /function loadManifest\((.+?), .+?\) {/,
6867
+ return code.replace(
6868
+ /function evalManifest\((.+?), .+?\) {/,
6721
6869
  `$&
6722
- ${manifestJsons.map(
6723
- (manifestJson) => `
6724
- if ($1.endsWith("${manifestJson}")) {
6725
- return ${readFileSync(`${nextjsAppPaths.standaloneAppDir}/${manifestJson}`, "utf-8")};
6726
- }
6727
- `
6870
+ ${manifestJss.map(
6871
+ (manifestJs) => `
6872
+ if ($1.endsWith("${manifestJs}")) {
6873
+ require(${JSON.stringify(path5.join(config.paths.standaloneApp, manifestJs))});
6874
+ return {
6875
+ __RSC_MANIFEST: {
6876
+ "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6877
+ },
6878
+ };
6879
+ }
6880
+ `
6728
6881
  ).join("\n")}
6729
- throw new Error("Unknown loadManifest: " + $1);
6730
- `
6882
+ throw new Error("Unknown evalManifest: " + $1);
6883
+ `
6731
6884
  );
6732
- return code;
6733
6885
  }
6734
6886
 
6735
- // src/build/patches/to-investigate/patch-find-dir.ts
6736
- import { existsSync } from "node:fs";
6737
- function patchFindDir(code, nextjsAppPaths) {
6738
- console.log("# patchFindDir");
6739
- return code.replace(
6740
- "function findDir(dir, name) {",
6741
- `function findDir(dir, name) {
6742
- if (dir.endsWith(".next/server")) {
6743
- if (name === "app") return ${existsSync(`${nextjsAppPaths.standaloneAppServerDir}/app`)};
6744
- if (name === "pages") return ${existsSync(`${nextjsAppPaths.standaloneAppServerDir}/pages`)};
6745
- }
6746
- throw new Error("Unknown findDir call: " + dir + " " + name);
6747
- `
6887
+ // src/cli/build/patches/to-investigate/inline-middleware-manifest-require.ts
6888
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
6889
+ import path6 from "node:path";
6890
+ function inlineMiddlewareManifestRequire(code, config) {
6891
+ console.log("# inlineMiddlewareManifestRequire");
6892
+ const middlewareManifestPath = path6.join(config.paths.standaloneAppServer, "middleware-manifest.json");
6893
+ const middlewareManifest = existsSync2(middlewareManifestPath) ? JSON.parse(readFileSync2(middlewareManifestPath, "utf-8")) : {};
6894
+ const patchedCode = code.replace(
6895
+ "require(this.middlewareManifestPath)",
6896
+ JSON.stringify(middlewareManifest)
6748
6897
  );
6898
+ if (patchedCode === code) {
6899
+ throw new Error("Patch `inlineMiddlewareManifestRequire` not applied");
6900
+ }
6901
+ return patchedCode;
6749
6902
  }
6750
6903
 
6751
- // src/build/patches/to-investigate/inline-next-require.ts
6752
- import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
6753
- function inlineNextRequire(code, nextjsAppPaths) {
6904
+ // src/cli/build/patches/to-investigate/inline-next-require.ts
6905
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
6906
+ import path7 from "node:path";
6907
+ function inlineNextRequire(code, config) {
6754
6908
  console.log("# inlineNextRequire");
6755
- const pagesManifestFile = `${nextjsAppPaths.standaloneAppServerDir}/pages-manifest.json`;
6756
- const appPathsManifestFile = `${nextjsAppPaths.standaloneAppServerDir}/app-paths-manifest.json`;
6757
- const pagesManifestFiles = existsSync2(pagesManifestFile) ? Object.values(JSON.parse(readFileSync2(pagesManifestFile, "utf-8"))).map(
6909
+ const pagesManifestFile = path7.join(config.paths.standaloneAppServer, "pages-manifest.json");
6910
+ const appPathsManifestFile = path7.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6911
+ const pagesManifestFiles = existsSync3(pagesManifestFile) ? Object.values(JSON.parse(readFileSync3(pagesManifestFile, "utf-8"))).map(
6758
6912
  (file) => ".next/server/" + file
6759
6913
  ) : [];
6760
- const appPathsManifestFiles = existsSync2(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync2(appPathsManifestFile, "utf-8"))).map(
6914
+ const appPathsManifestFiles = existsSync3(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync3(appPathsManifestFile, "utf-8"))).map(
6761
6915
  (file) => ".next/server/" + file
6762
6916
  ) : [];
6763
6917
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6769,14 +6923,14 @@ function inlineNextRequire(code, nextjsAppPaths) {
6769
6923
  ${htmlPages.map(
6770
6924
  (htmlPage) => `
6771
6925
  if (pagePath.endsWith("${htmlPage}")) {
6772
- return ${JSON.stringify(readFileSync2(`${nextjsAppPaths.standaloneAppDir}/${htmlPage}`, "utf-8"))};
6926
+ return ${JSON.stringify(readFileSync3(path7.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6773
6927
  }
6774
6928
  `
6775
6929
  ).join("\n")}
6776
6930
  ${pageModules.map(
6777
6931
  (module) => `
6778
6932
  if (pagePath.endsWith("${module}")) {
6779
- return require("${nextjsAppPaths.standaloneAppDir}/${module}");
6933
+ return require(${JSON.stringify(path7.join(config.paths.standaloneApp, module))});
6780
6934
  }
6781
6935
  `
6782
6936
  ).join("\n")}
@@ -6785,68 +6939,144 @@ function inlineNextRequire(code, nextjsAppPaths) {
6785
6939
  );
6786
6940
  }
6787
6941
 
6788
- // src/build/patches/to-investigate/inline-eval-manifest.ts
6789
- function inlineEvalManifest(code, nextjsAppPaths) {
6790
- console.log("# inlineEvalManifest");
6791
- const manifestJss = globSync(
6792
- `${nextjsAppPaths.standaloneAppDotNextDir}/**/*_client-reference-manifest.js`
6793
- ).map((file) => file.replace(`${nextjsAppPaths.standaloneAppDir}/`, ""));
6942
+ // src/cli/build/patches/investigated/patch-cache.ts
6943
+ import { build } from "esbuild";
6944
+ import { join as join3 } from "node:path";
6945
+ async function patchCache(code, config) {
6946
+ console.log("# patchCache");
6947
+ const cacheHandlerFileName = "cache-handler.mjs";
6948
+ const cacheHandlerEntrypoint = join3(config.paths.internalTemplates, "cache-handler", "index.ts");
6949
+ const cacheHandlerOutputFile = join3(config.paths.builderOutput, cacheHandlerFileName);
6950
+ await build({
6951
+ entryPoints: [cacheHandlerEntrypoint],
6952
+ bundle: true,
6953
+ outfile: cacheHandlerOutputFile,
6954
+ format: "esm",
6955
+ target: "esnext",
6956
+ minify: true,
6957
+ define: {
6958
+ "process.env.__OPENNEXT_KV_BINDING_NAME": `"${config.cache.kvBindingName}"`
6959
+ }
6960
+ });
6961
+ const patchedCode = code.replace(
6962
+ "const { cacheHandler } = this.nextConfig;",
6963
+ `const cacheHandler = null;
6964
+ CacheHandler = (await import('./${cacheHandlerFileName}')).OpenNextCacheHandler;
6965
+ `
6966
+ );
6967
+ if (patchedCode === code) {
6968
+ throw new Error("Patch `patchCache` not applied");
6969
+ }
6970
+ return patchedCode;
6971
+ }
6972
+
6973
+ // src/cli/build/patches/to-investigate/patch-exception-bubbling.ts
6974
+ function patchExceptionBubbling(code) {
6975
+ console.log("# patchExceptionBubbling");
6976
+ const patchedCode = code.replace('_nextBubbleNoFallback = "1"', "_nextBubbleNoFallback = undefined");
6977
+ if (patchedCode === code) {
6978
+ throw new Error("Patch `patchExceptionBubbling` not applied");
6979
+ }
6980
+ return patchedCode;
6981
+ }
6982
+
6983
+ // src/cli/build/patches/to-investigate/patch-find-dir.ts
6984
+ import { existsSync as existsSync4 } from "node:fs";
6985
+ import path8 from "node:path";
6986
+ function patchFindDir(code, config) {
6987
+ console.log("# patchFindDir");
6794
6988
  return code.replace(
6795
- /function evalManifest\((.+?), .+?\) {/,
6989
+ "function findDir(dir, name) {",
6990
+ `function findDir(dir, name) {
6991
+ if (dir.endsWith(".next/server")) {
6992
+ if (name === "app") {
6993
+ return ${existsSync4(`${path8.join(config.paths.standaloneAppServer, "app")}`)};
6994
+ }
6995
+ if (name === "pages") {
6996
+ return ${existsSync4(`${path8.join(config.paths.standaloneAppServer, "pages")}`)};
6997
+ }
6998
+ }
6999
+ throw new Error("Unknown findDir call: " + dir + " " + name);
7000
+ `
7001
+ );
7002
+ }
7003
+
7004
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
7005
+ import path9 from "node:path";
7006
+ import { readFileSync as readFileSync4 } from "node:fs";
7007
+ function patchReadFile(code, config) {
7008
+ console.log("# patchReadFile");
7009
+ code = code.replace(
7010
+ "getBuildId() {",
7011
+ `getBuildId() {
7012
+ return ${JSON.stringify(readFileSync4(path9.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
7013
+ `
7014
+ );
7015
+ const manifestJsons = globSync(
7016
+ path9.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json").replaceAll(path9.sep, path9.posix.sep)
7017
+ ).map(
7018
+ (file) => file.replaceAll(path9.sep, path9.posix.sep).replace(config.paths.standaloneApp.replaceAll(path9.sep, path9.posix.sep) + path9.posix.sep, "")
7019
+ );
7020
+ code = code.replace(
7021
+ /function loadManifest\((.+?), .+?\) {/,
6796
7022
  `$&
6797
- ${manifestJss.map(
6798
- (manifestJs) => `
6799
- if ($1.endsWith("${manifestJs}")) {
6800
- require("${nextjsAppPaths.standaloneAppDir}/${manifestJs}");
6801
- return {
6802
- __RSC_MANIFEST: {
6803
- "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6804
- },
6805
- };
6806
- }
6807
- `
7023
+ ${manifestJsons.map(
7024
+ (manifestJson) => `
7025
+ if ($1.endsWith("${manifestJson}")) {
7026
+ return ${readFileSync4(path9.join(config.paths.standaloneApp, manifestJson), "utf-8")};
7027
+ }
7028
+ `
6808
7029
  ).join("\n")}
6809
- throw new Error("Unknown evalManifest: " + $1);
6810
- `
7030
+ throw new Error("Unknown loadManifest: " + $1);
7031
+ `
6811
7032
  );
7033
+ return code;
6812
7034
  }
6813
7035
 
6814
- // src/build/patches/to-investigate/wrangler-deps.ts
6815
- import path3 from "node:path";
6816
- import fs, { writeFileSync } from "node:fs";
6817
- function patchWranglerDeps(paths) {
7036
+ // src/cli/build/patches/investigated/patch-require.ts
7037
+ function patchRequire(code) {
7038
+ console.log("# patchRequire");
7039
+ return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
7040
+ }
7041
+
7042
+ // src/cli/build/patches/to-investigate/wrangler-deps.ts
7043
+ import { readFileSync as readFileSync5, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
7044
+ import path10 from "node:path";
7045
+ function patchWranglerDeps(config) {
6818
7046
  console.log("# patchWranglerDeps");
6819
- console.log({ base: paths.standaloneAppDotNextDir });
6820
- const pagesRuntimeFile = path3.join(
6821
- paths.standaloneAppDir,
6822
- "node_modules",
6823
- "next",
6824
- "dist",
6825
- "compiled",
6826
- "next-server",
6827
- "pages.runtime.prod.js"
7047
+ const distPath = getDistPath(config);
7048
+ const pagesRuntimeFile = path10.join(distPath, "compiled", "next-server", "pages.runtime.prod.js");
7049
+ const patchedPagesRuntime = readFileSync5(pagesRuntimeFile, "utf-8").replace(
7050
+ `e.exports=require("critters")`,
7051
+ `e.exports={}`
6828
7052
  );
6829
- const patchedPagesRuntime = fs.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6830
- fs.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6831
- const tracerFile = path3.join(
6832
- paths.standaloneAppDir,
6833
- "node_modules",
6834
- "next",
6835
- "dist",
6836
- "server",
6837
- "lib",
6838
- "trace",
6839
- "tracer.js"
7053
+ writeFileSync2(pagesRuntimeFile, patchedPagesRuntime);
7054
+ const tracerFile = path10.join(distPath, "server", "lib", "trace", "tracer.js");
7055
+ const patchedTracer = readFileSync5(tracerFile, "utf-8").replaceAll(
7056
+ /\w+\s*=\s*require\([^/]*opentelemetry.*\)/g,
7057
+ `throw new Error("@opentelemetry/api")`
6840
7058
  );
6841
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6842
- writeFileSync(tracerFile, pacthedTracer);
7059
+ writeFileSync2(tracerFile, patchedTracer);
7060
+ }
7061
+ function getDistPath(config) {
7062
+ for (const root of [config.paths.standaloneApp, config.paths.standaloneRoot]) {
7063
+ try {
7064
+ const distPath = path10.join(root, "node_modules", "next", "dist");
7065
+ if (statSync2(distPath).isDirectory()) return distPath;
7066
+ } catch {
7067
+ }
7068
+ }
7069
+ throw new Error("Unexpected error: unable to detect the node_modules/next/dist directory");
6843
7070
  }
6844
7071
 
6845
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6846
- import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
7072
+ // src/cli/build/build-worker.ts
7073
+ import path12 from "node:path";
6847
7074
 
6848
- // src/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6849
- import * as ts from "ts-morph";
7075
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7076
+ import { readFileSync as readFileSync6, readdirSync as readdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
7077
+
7078
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
7079
+ import * as ts2 from "ts-morph";
6850
7080
  async function getChunkInstallationIdentifiers(sourceFile) {
6851
7081
  const installChunkDeclaration = getInstallChunkDeclaration(sourceFile);
6852
7082
  const installedChunksDeclaration = getInstalledChunksDeclaration(sourceFile, installChunkDeclaration);
@@ -6856,19 +7086,19 @@ async function getChunkInstallationIdentifiers(sourceFile) {
6856
7086
  };
6857
7087
  }
6858
7088
  function getInstallChunkDeclaration(sourceFile) {
6859
- const installChunkDeclaration = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration).find((declaration) => {
6860
- const arrowFunction = declaration.getInitializerIfKind(ts.SyntaxKind.ArrowFunction);
7089
+ const installChunkDeclaration = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.VariableDeclaration).find((declaration) => {
7090
+ const arrowFunction = declaration.getInitializerIfKind(ts2.SyntaxKind.ArrowFunction);
6861
7091
  if (!arrowFunction) return false;
6862
7092
  const functionParameters = arrowFunction.getParameters();
6863
7093
  if (functionParameters.length !== 1) return false;
6864
- const arrowFunctionBodyBlock = arrowFunction.getFirstChildByKind(ts.SyntaxKind.Block);
7094
+ const arrowFunctionBodyBlock = arrowFunction.getFirstChildByKind(ts2.SyntaxKind.Block);
6865
7095
  if (!arrowFunctionBodyBlock) return false;
6866
7096
  const statementKinds = arrowFunctionBodyBlock.getStatements().map((statement) => statement.getKind());
6867
- const forInStatements = statementKinds.filter((s) => s === ts.SyntaxKind.ForInStatement);
6868
- const forStatements = statementKinds.filter((s) => s === ts.SyntaxKind.ForStatement);
7097
+ const forInStatements = statementKinds.filter((s) => s === ts2.SyntaxKind.ForInStatement);
7098
+ const forStatements = statementKinds.filter((s) => s === ts2.SyntaxKind.ForStatement);
6869
7099
  if (forInStatements.length !== 1 || forStatements.length !== 1) return false;
6870
7100
  const parameterName = functionParameters[0].getText();
6871
- const functionParameterAccessedProperties = arrowFunctionBodyBlock.getDescendantsOfKind(ts.SyntaxKind.PropertyAccessExpression).filter(
7101
+ const functionParameterAccessedProperties = arrowFunctionBodyBlock.getDescendantsOfKind(ts2.SyntaxKind.PropertyAccessExpression).filter(
6872
7102
  (propertyAccessExpression) => propertyAccessExpression.getExpression().getText() === parameterName
6873
7103
  ).map((propertyAccessExpression) => propertyAccessExpression.getName());
6874
7104
  if (functionParameterAccessedProperties.join(", ") !== "modules, ids, runtime") return false;
@@ -6880,22 +7110,22 @@ function getInstallChunkDeclaration(sourceFile) {
6880
7110
  return installChunkDeclaration;
6881
7111
  }
6882
7112
  function getInstalledChunksDeclaration(sourceFile, installChunkDeclaration) {
6883
- const allVariableDeclarations = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration);
7113
+ const allVariableDeclarations = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.VariableDeclaration);
6884
7114
  const installChunkDeclarationIdx = allVariableDeclarations.findIndex(
6885
7115
  (declaration) => declaration === installChunkDeclaration
6886
7116
  );
6887
7117
  const installedChunksDeclaration = allVariableDeclarations[installChunkDeclarationIdx - 1];
6888
- if (!installedChunksDeclaration?.getInitializer()?.isKind(ts.SyntaxKind.ObjectLiteralExpression)) {
7118
+ if (!installedChunksDeclaration?.getInitializer()?.isKind(ts2.SyntaxKind.ObjectLiteralExpression)) {
6889
7119
  throw new Error("ERROR: unable to find the installedChunks declaration");
6890
7120
  }
6891
7121
  return installedChunksDeclaration;
6892
7122
  }
6893
7123
 
6894
- // src/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
6895
- import * as ts2 from "ts-morph";
7124
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
7125
+ import * as ts3 from "ts-morph";
6896
7126
  async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { installedChunks, installChunk }, chunks) {
6897
- const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.ArrowFunction).find((arrowFunction) => {
6898
- const binaryExpression = arrowFunction.getFirstAncestorByKind(ts2.SyntaxKind.BinaryExpression);
7127
+ const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts3.SyntaxKind.ArrowFunction).find((arrowFunction) => {
7128
+ const binaryExpression = arrowFunction.getFirstAncestorByKind(ts3.SyntaxKind.BinaryExpression);
6899
7129
  if (!binaryExpression) return false;
6900
7130
  const binaryExpressionLeft = binaryExpression.getLeft();
6901
7131
  if (!binaryExpressionLeft.getText().endsWith(".f.require")) return false;
@@ -6904,16 +7134,16 @@ async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { instal
6904
7134
  const binaryExpressionRight = binaryExpression.getRight();
6905
7135
  if (binaryExpressionRight !== arrowFunction) return false;
6906
7136
  const arrowFunctionBody = arrowFunction.getBody();
6907
- if (!arrowFunctionBody.isKind(ts2.SyntaxKind.Block)) return false;
7137
+ if (!arrowFunctionBody.isKind(ts3.SyntaxKind.Block)) return false;
6908
7138
  const arrowFunctionBodyText = arrowFunctionBody.getText();
6909
7139
  const functionUsesChunkInstallationVariables = arrowFunctionBodyText.includes(installChunk) && arrowFunctionBodyText.includes(installedChunks);
6910
7140
  if (!functionUsesChunkInstallationVariables) return false;
6911
7141
  const functionParameters = arrowFunction.getParameters();
6912
7142
  if (functionParameters.length !== 2) return false;
6913
- const callsInstallChunk = arrowFunctionBody.getDescendantsOfKind(ts2.SyntaxKind.CallExpression).some((callExpression) => callExpression.getExpression().getText() === installChunk);
7143
+ const callsInstallChunk = arrowFunctionBody.getDescendantsOfKind(ts3.SyntaxKind.CallExpression).some((callExpression) => callExpression.getExpression().getText() === installChunk);
6914
7144
  if (!callsInstallChunk) return false;
6915
7145
  const functionFirstParameterName = functionParameters[0]?.getName();
6916
- const accessesInstalledChunksUsingItsFirstParameter = arrowFunctionBody.getDescendantsOfKind(ts2.SyntaxKind.ElementAccessExpression).some((elementAccess) => {
7146
+ const accessesInstalledChunksUsingItsFirstParameter = arrowFunctionBody.getDescendantsOfKind(ts3.SyntaxKind.ElementAccessExpression).some((elementAccess) => {
6917
7147
  return elementAccess.getExpression().getText() === installedChunks && elementAccess.getArgumentExpression()?.getText() === functionFirstParameterName;
6918
7148
  });
6919
7149
  if (!accessesInstalledChunksUsingItsFirstParameter) return false;
@@ -6935,15 +7165,7 @@ if(${chunkId} === ${chunk}) return ${installChunk}(require("./chunks/${chunk}.js
6935
7165
  return sourceFile.print();
6936
7166
  }
6937
7167
 
6938
- // src/build/utils/ts-parse-file.ts
6939
- import * as ts3 from "ts-morph";
6940
- function tsParseFile(fileContent) {
6941
- const project = new ts3.Project();
6942
- const sourceFile = project.createSourceFile("file.js", fileContent);
6943
- return sourceFile;
6944
- }
6945
-
6946
- // src/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
7168
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
6947
7169
  async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6948
7170
  const tsSourceFile = tsParseFile(fileContent);
6949
7171
  const chunkInstallationIdentifiers = await getChunkInstallationIdentifiers(tsSourceFile);
@@ -6955,52 +7177,70 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6955
7177
  return updatedFileContent;
6956
7178
  }
6957
7179
 
6958
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6959
- async function updateWebpackChunksFile(nextjsAppPaths) {
7180
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7181
+ import path11 from "node:path";
7182
+ async function updateWebpackChunksFile(config) {
6960
7183
  console.log("# updateWebpackChunksFile");
6961
- const webpackRuntimeFile = `${nextjsAppPaths.standaloneAppServerDir}/webpack-runtime.js`;
6962
- const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6963
- const chunks = readdirSync2(`${nextjsAppPaths.standaloneAppServerDir}/chunks`).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
7184
+ const webpackRuntimeFile = path11.join(config.paths.standaloneAppServer, "webpack-runtime.js");
7185
+ const fileContent = readFileSync6(webpackRuntimeFile, "utf-8");
7186
+ const chunks = readdirSync4(path11.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6964
7187
  console.log(` - chunk ${chunk}`);
6965
7188
  return chunk.replace(/\.js$/, "");
6966
7189
  });
6967
7190
  const updatedFileContent = await getUpdatedWebpackChunksFileContent(fileContent, chunks);
6968
- writeFileSync2(webpackRuntimeFile, updatedFileContent);
7191
+ writeFileSync3(webpackRuntimeFile, updatedFileContent);
6969
7192
  }
6970
7193
 
6971
- // src/build/build-worker.ts
6972
- async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
6973
- const templateDir = copyTemplates(templateSrcDir, nextjsAppPaths);
6974
- const workerEntrypoint = `${templateDir}/worker.ts`;
6975
- const workerOutputFile = `${outputDir2}/index.mjs`;
6976
- const nextConfigStr = readFileSync4(nextjsAppPaths.standaloneAppDir + "/server.js", "utf8")?.match(
7194
+ // src/cli/build/build-worker.ts
7195
+ var packageDistDir = path12.join(path12.dirname(fileURLToPath3(import.meta.url)), "..");
7196
+ async function buildWorker(config) {
7197
+ console.log(`\x1B[35m\u2699\uFE0F Copying files...
7198
+ \x1B[0m`);
7199
+ await cp(
7200
+ path12.join(config.paths.dotNext, "static"),
7201
+ path12.join(config.paths.builderOutput, "assets", "_next", "static"),
7202
+ {
7203
+ recursive: true
7204
+ }
7205
+ );
7206
+ const publicDir = path12.join(config.paths.nextApp, "public");
7207
+ if (existsSync5(publicDir)) {
7208
+ await cp(publicDir, path12.join(config.paths.builderOutput, "assets"), {
7209
+ recursive: true
7210
+ });
7211
+ }
7212
+ copyPrerenderedRoutes(config);
7213
+ copyPackageCliFiles(packageDistDir, config);
7214
+ const workerEntrypoint = path12.join(config.paths.internalTemplates, "worker.ts");
7215
+ const workerOutputFile = path12.join(config.paths.builderOutput, "index.mjs");
7216
+ const nextConfigStr = readFileSync7(path12.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
6977
7217
  /const nextConfig = ({.+?})\n/
6978
7218
  )?.[1] ?? {};
6979
7219
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
6980
7220
  \x1B[0m`);
6981
- patchWranglerDeps(nextjsAppPaths);
6982
- updateWebpackChunksFile(nextjsAppPaths);
6983
- await build({
7221
+ patchWranglerDeps(config);
7222
+ updateWebpackChunksFile(config);
7223
+ await build2({
6984
7224
  entryPoints: [workerEntrypoint],
6985
7225
  bundle: true,
6986
7226
  outfile: workerOutputFile,
6987
7227
  format: "esm",
6988
7228
  target: "esnext",
6989
7229
  minify: false,
6990
- plugins: [createFixRequiresESBuildPlugin(templateDir)],
7230
+ plugins: [createFixRequiresESBuildPlugin(config)],
6991
7231
  alias: {
6992
7232
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
6993
7233
  // eval("require")("bufferutil");
6994
7234
  // eval("require")("utf-8-validate");
6995
- "next/dist/compiled/ws": `${templateDir}/shims/empty.ts`,
7235
+ "next/dist/compiled/ws": path12.join(config.paths.internalTemplates, "shims", "empty.ts"),
6996
7236
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
6997
7237
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
6998
7238
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
6999
7239
  // QUESTION: Why did I encountered this but mhart didn't?
7000
- "next/dist/compiled/edge-runtime": `${templateDir}/shims/empty.ts`,
7240
+ "next/dist/compiled/edge-runtime": path12.join(config.paths.internalTemplates, "shims", "empty.ts"),
7001
7241
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7002
7242
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7003
- "@next/env": `${templateDir}/shims/env.ts`
7243
+ "@next/env": path12.join(config.paths.internalTemplates, "shims", "env.ts")
7004
7244
  },
7005
7245
  define: {
7006
7246
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7010,10 +7250,6 @@ async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
7010
7250
  // Note: we need the __non_webpack_require__ variable declared as it is used by next-server:
7011
7251
  // https://github.com/vercel/next.js/blob/be0c3283/packages/next/src/server/next-server.ts#L116-L119
7012
7252
  __non_webpack_require__: "require",
7013
- // 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
7014
- // 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
7015
- // that's wht we enable it
7016
- "process.env.NEXT_PRIVATE_MINIMAL_MODE": "true",
7017
7253
  // Ask mhart if he can explain why the `define`s below are necessary
7018
7254
  "process.env.NEXT_RUNTIME": '"nodejs"',
7019
7255
  "process.env.NODE_ENV": '"production"',
@@ -7034,22 +7270,21 @@ async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
7034
7270
  // Do not crash on cache not supported
7035
7271
  // https://github.com/cloudflare/workerd/pull/2434
7036
7272
  // compatibility flag "cache_option_enabled" -> does not support "force-cache"
7037
- let isPatchedAlready = globalThis.fetch.__nextPatched;
7038
7273
  const curFetch = globalThis.fetch;
7039
7274
  globalThis.fetch = (input, init) => {
7040
- console.log("globalThis.fetch", input);
7041
- if (init) delete init.cache;
7275
+ if (init) {
7276
+ delete init.cache;
7277
+ }
7042
7278
  return curFetch(input, init);
7043
7279
  };
7044
7280
  import { Readable } from 'node:stream';
7045
- globalThis.fetch.__nextPatched = isPatchedAlready;
7046
7281
  fetch = globalThis.fetch;
7047
7282
  const CustomRequest = class extends globalThis.Request {
7048
7283
  constructor(input, init) {
7049
- console.log("CustomRequest", input);
7050
7284
  if (init) {
7051
7285
  delete init.cache;
7052
7286
  if (init.body?.__node_stream__ === true) {
7287
+ // https://github.com/cloudflare/workerd/issues/2746
7053
7288
  init.body = Readable.toWeb(init.body);
7054
7289
  }
7055
7290
  }
@@ -7058,131 +7293,119 @@ const CustomRequest = class extends globalThis.Request {
7058
7293
  };
7059
7294
  globalThis.Request = CustomRequest;
7060
7295
  Request = globalThis.Request;
7061
- `
7296
+ `
7062
7297
  }
7063
7298
  });
7064
- await updateWorkerBundledCode(workerOutputFile, nextjsAppPaths);
7065
- console.log(`\x1B[35m\u2699\uFE0F Copying asset files...
7066
- \x1B[0m`);
7067
- await cp(`${nextjsAppPaths.dotNextDir}/static`, `${outputDir2}/assets/_next/static`, {
7068
- recursive: true
7069
- });
7299
+ await updateWorkerBundledCode(workerOutputFile, config);
7070
7300
  console.log(`\x1B[35mWorker saved in \`${workerOutputFile}\` \u{1F680}
7071
7301
  \x1B[0m`);
7072
7302
  }
7073
- async function updateWorkerBundledCode(workerOutputFile, nextjsAppPaths) {
7303
+ async function updateWorkerBundledCode(workerOutputFile, config) {
7074
7304
  const originalCode = await readFile(workerOutputFile, "utf8");
7075
7305
  let patchedCode = originalCode;
7076
7306
  patchedCode = patchRequire(patchedCode);
7077
- patchedCode = patchReadFile(patchedCode, nextjsAppPaths);
7078
- patchedCode = inlineNextRequire(patchedCode, nextjsAppPaths);
7079
- patchedCode = patchFindDir(patchedCode, nextjsAppPaths);
7080
- patchedCode = inlineEvalManifest(patchedCode, nextjsAppPaths);
7307
+ patchedCode = patchReadFile(patchedCode, config);
7308
+ patchedCode = inlineNextRequire(patchedCode, config);
7309
+ patchedCode = patchFindDir(patchedCode, config);
7310
+ patchedCode = inlineEvalManifest(patchedCode, config);
7311
+ patchedCode = await patchCache(patchedCode, config);
7312
+ patchedCode = inlineMiddlewareManifestRequire(patchedCode, config);
7313
+ patchedCode = patchExceptionBubbling(patchedCode);
7081
7314
  await writeFile(workerOutputFile, patchedCode);
7082
7315
  }
7083
- function createFixRequiresESBuildPlugin(templateDir) {
7316
+ function createFixRequiresESBuildPlugin(config) {
7084
7317
  return {
7085
7318
  name: "replaceRelative",
7086
- setup(build3) {
7087
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7088
- path: `${templateDir}/shims/empty.ts`
7319
+ setup(build4) {
7320
+ build4.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7321
+ path: path12.join(config.paths.internalTemplates, "shims", "empty.ts")
7089
7322
  }));
7090
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7091
- path: `${templateDir}/shims/node-fs.ts`
7323
+ build4.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7324
+ path: path12.join(config.paths.internalTemplates, "shims", "empty.ts")
7092
7325
  }));
7093
7326
  }
7094
7327
  };
7095
7328
  }
7096
7329
 
7097
- // src/nextjs-paths.ts
7098
- import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
7099
- import path4, { relative } from "node:path";
7100
- function getNextjsAppPaths(nextAppDir2) {
7101
- const dotNextDir = getDotNextDirPath(nextAppDir2);
7102
- const appPath = getNextjsApplicationPath(dotNextDir).replace(/\/$/, "");
7103
- const standaloneAppDir = path4.join(dotNextDir, "standalone", appPath);
7330
+ // src/cli/build/index.ts
7331
+ import { cpSync as cpSync2 } from "node:fs";
7332
+ import path13 from "node:path";
7333
+ import { rm } from "node:fs/promises";
7334
+ async function build3(appDir, opts) {
7335
+ if (!opts.skipBuild) {
7336
+ await buildNextjsApp(appDir);
7337
+ }
7338
+ if (!containsDotNextDir(appDir)) {
7339
+ throw new Error(`.next folder not found in ${appDir}`);
7340
+ }
7341
+ const outputDir2 = path13.resolve(opts.outputDir ?? appDir, ".worker-next");
7342
+ await cleanDirectory(outputDir2);
7343
+ cpSync2(path13.join(appDir, ".next"), path13.join(outputDir2, ".next"), { recursive: true });
7344
+ const config = getConfig(appDir, outputDir2);
7345
+ await buildWorker(config);
7346
+ }
7347
+ async function cleanDirectory(path14) {
7348
+ return await rm(path14, { recursive: true, force: true });
7349
+ }
7350
+
7351
+ // src/cli/index.ts
7352
+ import { existsSync as existsSync6 } from "node:fs";
7353
+
7354
+ // src/cli/args.ts
7355
+ import { mkdirSync as mkdirSync2, statSync as statSync3 } from "node:fs";
7356
+ import { parseArgs } from "node:util";
7357
+ import { resolve } from "node:path";
7358
+ function getArgs() {
7359
+ const {
7360
+ values: { skipBuild: skipBuild2, output }
7361
+ } = parseArgs({
7362
+ options: {
7363
+ skipBuild: {
7364
+ type: "boolean",
7365
+ short: "s",
7366
+ default: false
7367
+ },
7368
+ output: {
7369
+ type: "string",
7370
+ short: "o"
7371
+ }
7372
+ },
7373
+ allowPositionals: false
7374
+ });
7375
+ const outputDir2 = output ? resolve(output) : void 0;
7376
+ if (outputDir2) {
7377
+ assertDirArg(outputDir2, "output", true);
7378
+ }
7104
7379
  return {
7105
- appDir: nextAppDir2,
7106
- dotNextDir,
7107
- standaloneAppDir,
7108
- standaloneAppDotNextDir: path4.join(standaloneAppDir, ".next"),
7109
- standaloneAppServerDir: path4.join(standaloneAppDir, ".next", "server")
7380
+ outputDir: outputDir2,
7381
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7110
7382
  };
7111
7383
  }
7112
- function getDotNextDirPath(nextAppDir2) {
7113
- const dotNextDirPath = `${nextAppDir2}/.next`;
7384
+ function assertDirArg(path14, argName, make) {
7385
+ let dirStats;
7114
7386
  try {
7115
- const dirStats = statSync2(dotNextDirPath);
7116
- if (!dirStats.isDirectory()) throw new Error();
7387
+ dirStats = statSync3(path14);
7117
7388
  } catch {
7118
- throw new Error(`Error: \`.next\` directory not found!`);
7119
- }
7120
- return dotNextDirPath;
7121
- }
7122
- function getNextjsApplicationPath(dotNextDir) {
7123
- const serverPath = findServerParentPath(dotNextDir);
7124
- if (!serverPath) {
7125
- throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7126
- }
7127
- return relative(`${dotNextDir}/standalone`, serverPath);
7128
- function findServerParentPath(path6) {
7129
- try {
7130
- if (statSync2(`${path6}/.next/server`).isDirectory()) {
7131
- return path6;
7132
- }
7133
- } catch {
7134
- }
7135
- const files = readdirSync3(path6);
7136
- for (const file of files) {
7137
- if (statSync2(`${path6}/${file}`).isDirectory()) {
7138
- const dirServerPath = findServerParentPath(`${path6}/${file}`);
7139
- if (dirServerPath) {
7140
- return dirServerPath;
7141
- }
7142
- }
7389
+ if (!make) {
7390
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7143
7391
  }
7392
+ mkdirSync2(path14);
7393
+ return;
7144
7394
  }
7145
- }
7146
-
7147
- // src/build/build.ts
7148
- import path5 from "node:path";
7149
- import { fileURLToPath as fileURLToPath3 } from "node:url";
7150
- import { cpSync as cpSync2, rmSync } from "node:fs";
7151
- var SAVE_DIR = ".save.next";
7152
- async function build2(inputNextAppDir, opts) {
7153
- if (!opts.skipBuild) {
7154
- buildNextjsApp(inputNextAppDir);
7155
- rmSync(`${inputNextAppDir}/${SAVE_DIR}`, {
7156
- recursive: true,
7157
- force: true
7158
- });
7159
- cpSync2(`${inputNextAppDir}/.next`, `${inputNextAppDir}/${SAVE_DIR}`, {
7160
- recursive: true
7161
- });
7162
- } else {
7163
- rmSync(`${inputNextAppDir}/.next`, { recursive: true, force: true });
7164
- cpSync2(`${inputNextAppDir}/${SAVE_DIR}`, `${inputNextAppDir}/.next`, {
7165
- recursive: true
7166
- });
7395
+ if (!dirStats.isDirectory()) {
7396
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7167
7397
  }
7168
- const outputDir2 = `${opts.outputDir ?? inputNextAppDir}/.worker-next`;
7169
- await cleanDirectory(outputDir2);
7170
- const nextjsAppPaths = getNextjsAppPaths(inputNextAppDir);
7171
- const templateDir = path5.join(path5.dirname(fileURLToPath3(import.meta.url)), "templates");
7172
- await buildWorker(outputDir2, nextjsAppPaths, templateDir);
7173
- }
7174
- async function cleanDirectory(path6) {
7175
- return await rm(path6, { recursive: true, force: true });
7176
7398
  }
7177
7399
 
7178
- // src/index.ts
7400
+ // src/cli/index.ts
7401
+ import { resolve as resolve2 } from "node:path";
7179
7402
  var nextAppDir = resolve2(".");
7180
7403
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7181
- if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync3(`./next.config.${ext2}`))) {
7404
+ if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync6(`./next.config.${ext2}`))) {
7182
7405
  throw new Error("Error: Not in a Next.js app project");
7183
7406
  }
7184
7407
  var { skipBuild, outputDir } = getArgs();
7185
- await build2(nextAppDir, {
7408
+ await build3(nextAppDir, {
7186
7409
  outputDir,
7187
7410
  skipBuild: !!skipBuild
7188
7411
  });