@opennextjs/cloudflare 0.0.0-fd3c2b9 → 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,32 +1,14 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
1
+ #!/usr/bin/env node
2
+ import {
3
+ NEXT_META_SUFFIX,
4
+ SEED_DATA_DIR,
5
+ __commonJS,
6
+ __toESM
7
+ } from "./chunk-F7LECSR5.mjs";
26
8
 
27
- // ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
9
+ // ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
28
10
  var require_balanced_match = __commonJS({
29
- "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
11
+ "../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
30
12
  "use strict";
31
13
  module.exports = balanced;
32
14
  function balanced(a, b, str) {
@@ -82,9 +64,9 @@ var require_balanced_match = __commonJS({
82
64
  }
83
65
  });
84
66
 
85
- // ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
67
+ // ../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
86
68
  var require_brace_expansion = __commonJS({
87
- "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
69
+ "../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
88
70
  "use strict";
89
71
  var balanced = require_balanced_match();
90
72
  module.exports = expandTop;
@@ -233,68 +215,172 @@ var require_brace_expansion = __commonJS({
233
215
  }
234
216
  });
235
217
 
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);
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"
263
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("/"));
264
236
  return {
265
- outputDir: outputDir2,
266
- 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
267
252
  };
268
253
  }
269
- function assertDirArg(path6, argName, make) {
270
- let dirStats;
254
+ function containsDotNextDir(folder) {
271
255
  try {
272
- dirStats = statSync(path6);
256
+ return statSync(path.join(folder, ".next")).isDirectory();
273
257
  } catch {
274
- if (!make) {
275
- 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;
276
272
  }
277
- mkdirSync(path6);
278
- return;
273
+ } catch {
279
274
  }
280
- if (!dirStats.isDirectory()) {
281
- 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
+ }
282
284
  }
283
285
  }
284
286
 
285
- // src/index.ts
286
- import { existsSync as existsSync3 } 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
+ };
287
303
 
288
- // src/build/build.ts
289
- 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
+ }
290
372
 
291
- // src/build/build-next-app.ts
373
+ // src/cli/build/build-next-app.ts
292
374
  import { execSync } from "node:child_process";
293
- function buildNextjsApp(nextAppDir2) {
294
- 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);
295
381
  }
296
382
  function runNextBuildCommand(packager, nextAppDir2) {
297
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
383
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
298
384
  execSync(command, {
299
385
  stdio: "inherit",
300
386
  cwd: nextAppDir2,
@@ -307,34 +393,78 @@ function runNextBuildCommand(packager, nextAppDir2) {
307
393
  });
308
394
  }
309
395
 
310
- // src/build/build-worker.ts
396
+ // src/cli/build/build-worker.ts
311
397
  import { build } from "esbuild";
312
- import { readFileSync as readFileSync4 } from "node:fs";
313
398
  import { cp, readFile, writeFile } from "node:fs/promises";
399
+ import { existsSync as existsSync5, readFileSync as readFileSync7 } from "node:fs";
314
400
 
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.");
401
+ // src/cli/build/patches/investigated/copy-package-cli-files.ts
402
+ import { cpSync } from "node:fs";
403
+ import path3 from "node:path";
404
+ function copyPackageCliFiles(packageDistDir2, config) {
405
+ console.log("# copyPackageTemplateFiles");
406
+ const sourceDir = path3.join(packageDistDir2, "cli");
407
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
408
+ cpSync(sourceDir, destinationDir, { recursive: true });
319
409
  }
320
410
 
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;
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;
329
417
  }
330
418
 
331
- // src/build/patches/to-investigate/patch-read-file.ts
332
- import { readFileSync } from "node:fs";
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";
333
422
 
334
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
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";
463
+
464
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
335
465
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
336
466
 
337
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/assert-valid-pattern.js
467
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/assert-valid-pattern.js
338
468
  var MAX_PATTERN_LENGTH = 1024 * 64;
339
469
  var assertValidPattern = (pattern) => {
340
470
  if (typeof pattern !== "string") {
@@ -345,7 +475,7 @@ var assertValidPattern = (pattern) => {
345
475
  }
346
476
  };
347
477
 
348
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/brace-expressions.js
478
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/brace-expressions.js
349
479
  var posixClasses = {
350
480
  "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
351
481
  "[:alpha:]": ["\\p{L}\\p{Nl}", true],
@@ -454,12 +584,12 @@ var parseClass = (glob2, position) => {
454
584
  return [comb, uflag, endPos - pos, true];
455
585
  };
456
586
 
457
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/unescape.js
587
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/unescape.js
458
588
  var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
459
589
  return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
460
590
  };
461
591
 
462
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/ast.js
592
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/ast.js
463
593
  var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
464
594
  var isExtglobType = (c) => types.has(c);
465
595
  var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
@@ -938,12 +1068,12 @@ var AST = class _AST {
938
1068
  }
939
1069
  };
940
1070
 
941
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/escape.js
1071
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/escape.js
942
1072
  var escape = (s, { windowsPathsNoEscape = false } = {}) => {
943
1073
  return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
944
1074
  };
945
1075
 
946
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
1076
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
947
1077
  var minimatch = (p, pattern, options = {}) => {
948
1078
  assertValidPattern(pattern);
949
1079
  if (!options.nocomment && pattern.charAt(0) === "#") {
@@ -1002,11 +1132,11 @@ var qmarksTestNoExtDot = ([$0]) => {
1002
1132
  return (f) => f.length === len && f !== "." && f !== "..";
1003
1133
  };
1004
1134
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
1005
- var path2 = {
1135
+ var path4 = {
1006
1136
  win32: { sep: "\\" },
1007
1137
  posix: { sep: "/" }
1008
1138
  };
1009
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1139
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
1010
1140
  minimatch.sep = sep;
1011
1141
  var GLOBSTAR = Symbol("globstar **");
1012
1142
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -1661,10 +1791,10 @@ minimatch.Minimatch = Minimatch;
1661
1791
  minimatch.escape = escape;
1662
1792
  minimatch.unescape = unescape;
1663
1793
 
1664
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
1794
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
1665
1795
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1666
1796
 
1667
- // ../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/dist/esm/index.js
1797
+ // ../../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/dist/esm/index.js
1668
1798
  var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
1669
1799
  var warned = /* @__PURE__ */ new Set();
1670
1800
  var PROCESS = typeof process === "object" && !!process ? process : {};
@@ -3033,14 +3163,14 @@ var LRUCache = class _LRUCache {
3033
3163
  }
3034
3164
  };
3035
3165
 
3036
- // ../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3166
+ // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3037
3167
  import { posix, win32 } from "node:path";
3038
3168
  import { fileURLToPath } from "node:url";
3039
- 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";
3040
3170
  import * as actualFS from "node:fs";
3041
3171
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3042
3172
 
3043
- // ../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/dist/esm/index.js
3173
+ // ../../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/dist/esm/index.js
3044
3174
  import { EventEmitter } from "node:events";
3045
3175
  import Stream from "node:stream";
3046
3176
  import { StringDecoder } from "node:string_decoder";
@@ -3918,12 +4048,12 @@ var Minipass = class extends EventEmitter {
3918
4048
  }
3919
4049
  };
3920
4050
 
3921
- // ../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
4051
+ // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3922
4052
  var realpathSync = rps.native;
3923
4053
  var defaultFS = {
3924
4054
  lstatSync,
3925
4055
  readdir: readdirCB,
3926
- readdirSync,
4056
+ readdirSync: readdirSync3,
3927
4057
  readlinkSync,
3928
4058
  realpathSync,
3929
4059
  promises: {
@@ -4183,12 +4313,12 @@ var PathBase = class {
4183
4313
  /**
4184
4314
  * Get the Path object referenced by the string path, resolved from this Path
4185
4315
  */
4186
- resolve(path6) {
4187
- if (!path6) {
4316
+ resolve(path15) {
4317
+ if (!path15) {
4188
4318
  return this;
4189
4319
  }
4190
- const rootPath = this.getRootString(path6);
4191
- const dir = path6.substring(rootPath.length);
4320
+ const rootPath = this.getRootString(path15);
4321
+ const dir = path15.substring(rootPath.length);
4192
4322
  const dirParts = dir.split(this.splitSep);
4193
4323
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4194
4324
  return result;
@@ -4940,8 +5070,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4940
5070
  /**
4941
5071
  * @internal
4942
5072
  */
4943
- getRootString(path6) {
4944
- return win32.parse(path6).root;
5073
+ getRootString(path15) {
5074
+ return win32.parse(path15).root;
4945
5075
  }
4946
5076
  /**
4947
5077
  * @internal
@@ -4987,8 +5117,8 @@ var PathPosix = class _PathPosix extends PathBase {
4987
5117
  /**
4988
5118
  * @internal
4989
5119
  */
4990
- getRootString(path6) {
4991
- return path6.startsWith("/") ? "/" : "";
5120
+ getRootString(path15) {
5121
+ return path15.startsWith("/") ? "/" : "";
4992
5122
  }
4993
5123
  /**
4994
5124
  * @internal
@@ -5077,11 +5207,11 @@ var PathScurryBase = class {
5077
5207
  /**
5078
5208
  * Get the depth of a provided path, string, or the cwd
5079
5209
  */
5080
- depth(path6 = this.cwd) {
5081
- if (typeof path6 === "string") {
5082
- path6 = this.cwd.resolve(path6);
5210
+ depth(path15 = this.cwd) {
5211
+ if (typeof path15 === "string") {
5212
+ path15 = this.cwd.resolve(path15);
5083
5213
  }
5084
- return path6.depth();
5214
+ return path15.depth();
5085
5215
  }
5086
5216
  /**
5087
5217
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5460,7 +5590,7 @@ var PathScurryBase = class {
5460
5590
  const dirs = /* @__PURE__ */ new Set();
5461
5591
  const queue = [entry];
5462
5592
  let processing = 0;
5463
- const process2 = () => {
5593
+ const process3 = () => {
5464
5594
  let paused = false;
5465
5595
  while (!paused) {
5466
5596
  const dir = queue.shift();
@@ -5501,9 +5631,9 @@ var PathScurryBase = class {
5501
5631
  }
5502
5632
  }
5503
5633
  if (paused && !results.flowing) {
5504
- results.once("drain", process2);
5634
+ results.once("drain", process3);
5505
5635
  } else if (!sync2) {
5506
- process2();
5636
+ process3();
5507
5637
  }
5508
5638
  };
5509
5639
  let sync2 = true;
@@ -5511,7 +5641,7 @@ var PathScurryBase = class {
5511
5641
  sync2 = false;
5512
5642
  }
5513
5643
  };
5514
- process2();
5644
+ process3();
5515
5645
  return results;
5516
5646
  }
5517
5647
  streamSync(entry = this.cwd, opts = {}) {
@@ -5529,7 +5659,7 @@ var PathScurryBase = class {
5529
5659
  }
5530
5660
  const queue = [entry];
5531
5661
  let processing = 0;
5532
- const process2 = () => {
5662
+ const process3 = () => {
5533
5663
  let paused = false;
5534
5664
  while (!paused) {
5535
5665
  const dir = queue.shift();
@@ -5563,14 +5693,14 @@ var PathScurryBase = class {
5563
5693
  }
5564
5694
  }
5565
5695
  if (paused && !results.flowing)
5566
- results.once("drain", process2);
5696
+ results.once("drain", process3);
5567
5697
  };
5568
- process2();
5698
+ process3();
5569
5699
  return results;
5570
5700
  }
5571
- chdir(path6 = this.cwd) {
5701
+ chdir(path15 = this.cwd) {
5572
5702
  const oldCwd = this.cwd;
5573
- this.cwd = typeof path6 === "string" ? this.cwd.resolve(path6) : path6;
5703
+ this.cwd = typeof path15 === "string" ? this.cwd.resolve(path15) : path15;
5574
5704
  this.cwd[setAsCwd](oldCwd);
5575
5705
  }
5576
5706
  };
@@ -5644,7 +5774,7 @@ var PathScurryDarwin = class extends PathScurryPosix {
5644
5774
  var Path = process.platform === "win32" ? PathWin32 : PathPosix;
5645
5775
  var PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
5646
5776
 
5647
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/pattern.js
5777
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/pattern.js
5648
5778
  var isPatternList = (pl) => pl.length >= 1;
5649
5779
  var isGlobList = (gl) => gl.length >= 1;
5650
5780
  var Pattern = class _Pattern {
@@ -5809,7 +5939,7 @@ var Pattern = class _Pattern {
5809
5939
  }
5810
5940
  };
5811
5941
 
5812
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/ignore.js
5942
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/ignore.js
5813
5943
  var defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
5814
5944
  var Ignore = class {
5815
5945
  relative;
@@ -5896,7 +6026,7 @@ var Ignore = class {
5896
6026
  }
5897
6027
  };
5898
6028
 
5899
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/processor.js
6029
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/processor.js
5900
6030
  var HasWalkedCache = class _HasWalkedCache {
5901
6031
  store;
5902
6032
  constructor(store = /* @__PURE__ */ new Map()) {
@@ -5926,8 +6056,8 @@ var MatchRecord = class {
5926
6056
  }
5927
6057
  // match, absolute, ifdir
5928
6058
  entries() {
5929
- return [...this.store.entries()].map(([path6, n]) => [
5930
- path6,
6059
+ return [...this.store.entries()].map(([path15, n]) => [
6060
+ path15,
5931
6061
  !!(n & 2),
5932
6062
  !!(n & 1)
5933
6063
  ]);
@@ -6117,7 +6247,7 @@ var Processor = class _Processor {
6117
6247
  }
6118
6248
  };
6119
6249
 
6120
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/walker.js
6250
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/walker.js
6121
6251
  var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
6122
6252
  var GlobUtil = class {
6123
6253
  path;
@@ -6132,9 +6262,9 @@ var GlobUtil = class {
6132
6262
  signal;
6133
6263
  maxDepth;
6134
6264
  includeChildMatches;
6135
- constructor(patterns, path6, opts) {
6265
+ constructor(patterns, path15, opts) {
6136
6266
  this.patterns = patterns;
6137
- this.path = path6;
6267
+ this.path = path15;
6138
6268
  this.opts = opts;
6139
6269
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6140
6270
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6153,11 +6283,11 @@ var GlobUtil = class {
6153
6283
  });
6154
6284
  }
6155
6285
  }
6156
- #ignored(path6) {
6157
- return this.seen.has(path6) || !!this.#ignore?.ignored?.(path6);
6286
+ #ignored(path15) {
6287
+ return this.seen.has(path15) || !!this.#ignore?.ignored?.(path15);
6158
6288
  }
6159
- #childrenIgnored(path6) {
6160
- return !!this.#ignore?.childrenIgnored?.(path6);
6289
+ #childrenIgnored(path15) {
6290
+ return !!this.#ignore?.childrenIgnored?.(path15);
6161
6291
  }
6162
6292
  // backpressure mechanism
6163
6293
  pause() {
@@ -6372,8 +6502,8 @@ var GlobUtil = class {
6372
6502
  };
6373
6503
  var GlobWalker = class extends GlobUtil {
6374
6504
  matches = /* @__PURE__ */ new Set();
6375
- constructor(patterns, path6, opts) {
6376
- super(patterns, path6, opts);
6505
+ constructor(patterns, path15, opts) {
6506
+ super(patterns, path15, opts);
6377
6507
  }
6378
6508
  matchEmit(e) {
6379
6509
  this.matches.add(e);
@@ -6410,8 +6540,8 @@ var GlobWalker = class extends GlobUtil {
6410
6540
  };
6411
6541
  var GlobStream = class extends GlobUtil {
6412
6542
  results;
6413
- constructor(patterns, path6, opts) {
6414
- super(patterns, path6, opts);
6543
+ constructor(patterns, path15, opts) {
6544
+ super(patterns, path15, opts);
6415
6545
  this.results = new Minipass({
6416
6546
  signal: this.signal,
6417
6547
  objectMode: true
@@ -6444,7 +6574,7 @@ var GlobStream = class extends GlobUtil {
6444
6574
  }
6445
6575
  };
6446
6576
 
6447
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
6577
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
6448
6578
  var defaultPlatform3 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
6449
6579
  var Glob = class {
6450
6580
  absolute;
@@ -6644,7 +6774,7 @@ var Glob = class {
6644
6774
  }
6645
6775
  };
6646
6776
 
6647
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/has-magic.js
6777
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/has-magic.js
6648
6778
  var hasMagic = (pattern, options = {}) => {
6649
6779
  if (!Array.isArray(pattern)) {
6650
6780
  pattern = [pattern];
@@ -6656,7 +6786,7 @@ var hasMagic = (pattern, options = {}) => {
6656
6786
  return false;
6657
6787
  };
6658
6788
 
6659
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/index.js
6789
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/index.js
6660
6790
  function globStreamSync(pattern, options = {}) {
6661
6791
  return new Glob(pattern, options).streamSync();
6662
6792
  }
@@ -6704,60 +6834,61 @@ var glob = Object.assign(glob_, {
6704
6834
  });
6705
6835
  glob.glob = glob;
6706
6836
 
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 + "/", "")
6718
- );
6719
- code = code.replace(
6720
- /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\((.+?), .+?\) {/,
6721
6846
  `$&
6722
- ${manifestJsons.map(
6723
- (manifestJson) => `
6724
- if ($1.endsWith("${manifestJson}")) {
6725
- return ${readFileSync(`${nextjsAppPaths.standaloneAppDir}/${manifestJson}`, "utf-8")};
6726
- }
6727
- `
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
+ `
6728
6858
  ).join("\n")}
6729
- throw new Error("Unknown loadManifest: " + $1);
6730
- `
6859
+ throw new Error("Unknown evalManifest: " + $1);
6860
+ `
6731
6861
  );
6732
- return code;
6733
6862
  }
6734
6863
 
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
- `
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)
6748
6874
  );
6875
+ if (patchedCode === code) {
6876
+ throw new Error("Patch `inlineMiddlewareManifestRequire` not applied");
6877
+ }
6878
+ return patchedCode;
6749
6879
  }
6750
6880
 
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) {
6881
+ // src/cli/build/patches/to-investigate/inline-next-require.ts
6882
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
6883
+ import path7 from "node:path";
6884
+ function inlineNextRequire(code, config) {
6754
6885
  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(
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(
6758
6889
  (file) => ".next/server/" + file
6759
6890
  ) : [];
6760
- 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(
6761
6892
  (file) => ".next/server/" + file
6762
6893
  ) : [];
6763
6894
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6769,14 +6900,14 @@ function inlineNextRequire(code, nextjsAppPaths) {
6769
6900
  ${htmlPages.map(
6770
6901
  (htmlPage) => `
6771
6902
  if (pagePath.endsWith("${htmlPage}")) {
6772
- return ${JSON.stringify(readFileSync2(`${nextjsAppPaths.standaloneAppDir}/${htmlPage}`, "utf-8"))};
6903
+ return ${JSON.stringify(readFileSync3(path7.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6773
6904
  }
6774
6905
  `
6775
6906
  ).join("\n")}
6776
6907
  ${pageModules.map(
6777
6908
  (module) => `
6778
6909
  if (pagePath.endsWith("${module}")) {
6779
- return require("${nextjsAppPaths.standaloneAppDir}/${module}");
6910
+ return require("${path7.join(config.paths.standaloneApp, module)}");
6780
6911
  }
6781
6912
  `
6782
6913
  ).join("\n")}
@@ -6785,68 +6916,129 @@ function inlineNextRequire(code, nextjsAppPaths) {
6785
6916
  );
6786
6917
  }
6787
6918
 
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}/`, ""));
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");
6794
6952
  return code.replace(
6795
- /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\((.+?), .+?\) {/,
6796
6984
  `$&
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
- `
6985
+ ${manifestJsons.map(
6986
+ (manifestJson) => `
6987
+ if ($1.endsWith("${manifestJson}")) {
6988
+ return ${readFileSync4(path10.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6989
+ }
6990
+ `
6808
6991
  ).join("\n")}
6809
- throw new Error("Unknown evalManifest: " + $1);
6810
- `
6992
+ throw new Error("Unknown loadManifest: " + $1);
6993
+ `
6811
6994
  );
6995
+ return code;
6812
6996
  }
6813
6997
 
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) {
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.");
7002
+ }
7003
+
7004
+ // src/cli/build/patches/to-investigate/wrangler-deps.ts
7005
+ import { readFileSync as readFileSync5, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
7006
+ import path11 from "node:path";
7007
+ function patchWranglerDeps(config) {
6818
7008
  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"
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={}`
6828
7014
  );
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"
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")`
6840
7020
  );
6841
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6842
- 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");
6843
7032
  }
6844
7033
 
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";
7034
+ // src/cli/build/build-worker.ts
7035
+ import path13 from "node:path";
6847
7036
 
6848
- // src/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6849
- import * as ts from "ts-morph";
7037
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7038
+ import { readFileSync as readFileSync6, readdirSync as readdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
7039
+
7040
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
7041
+ import * as ts2 from "ts-morph";
6850
7042
  async function getChunkInstallationIdentifiers(sourceFile) {
6851
7043
  const installChunkDeclaration = getInstallChunkDeclaration(sourceFile);
6852
7044
  const installedChunksDeclaration = getInstalledChunksDeclaration(sourceFile, installChunkDeclaration);
@@ -6856,19 +7048,19 @@ async function getChunkInstallationIdentifiers(sourceFile) {
6856
7048
  };
6857
7049
  }
6858
7050
  function getInstallChunkDeclaration(sourceFile) {
6859
- const installChunkDeclaration = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration).find((declaration) => {
6860
- 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);
6861
7053
  if (!arrowFunction) return false;
6862
7054
  const functionParameters = arrowFunction.getParameters();
6863
7055
  if (functionParameters.length !== 1) return false;
6864
- const arrowFunctionBodyBlock = arrowFunction.getFirstChildByKind(ts.SyntaxKind.Block);
7056
+ const arrowFunctionBodyBlock = arrowFunction.getFirstChildByKind(ts2.SyntaxKind.Block);
6865
7057
  if (!arrowFunctionBodyBlock) return false;
6866
7058
  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);
7059
+ const forInStatements = statementKinds.filter((s) => s === ts2.SyntaxKind.ForInStatement);
7060
+ const forStatements = statementKinds.filter((s) => s === ts2.SyntaxKind.ForStatement);
6869
7061
  if (forInStatements.length !== 1 || forStatements.length !== 1) return false;
6870
7062
  const parameterName = functionParameters[0].getText();
6871
- const functionParameterAccessedProperties = arrowFunctionBodyBlock.getDescendantsOfKind(ts.SyntaxKind.PropertyAccessExpression).filter(
7063
+ const functionParameterAccessedProperties = arrowFunctionBodyBlock.getDescendantsOfKind(ts2.SyntaxKind.PropertyAccessExpression).filter(
6872
7064
  (propertyAccessExpression) => propertyAccessExpression.getExpression().getText() === parameterName
6873
7065
  ).map((propertyAccessExpression) => propertyAccessExpression.getName());
6874
7066
  if (functionParameterAccessedProperties.join(", ") !== "modules, ids, runtime") return false;
@@ -6880,22 +7072,22 @@ function getInstallChunkDeclaration(sourceFile) {
6880
7072
  return installChunkDeclaration;
6881
7073
  }
6882
7074
  function getInstalledChunksDeclaration(sourceFile, installChunkDeclaration) {
6883
- const allVariableDeclarations = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration);
7075
+ const allVariableDeclarations = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.VariableDeclaration);
6884
7076
  const installChunkDeclarationIdx = allVariableDeclarations.findIndex(
6885
7077
  (declaration) => declaration === installChunkDeclaration
6886
7078
  );
6887
7079
  const installedChunksDeclaration = allVariableDeclarations[installChunkDeclarationIdx - 1];
6888
- if (!installedChunksDeclaration?.getInitializer()?.isKind(ts.SyntaxKind.ObjectLiteralExpression)) {
7080
+ if (!installedChunksDeclaration?.getInitializer()?.isKind(ts2.SyntaxKind.ObjectLiteralExpression)) {
6889
7081
  throw new Error("ERROR: unable to find the installedChunks declaration");
6890
7082
  }
6891
7083
  return installedChunksDeclaration;
6892
7084
  }
6893
7085
 
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";
7086
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
7087
+ import * as ts3 from "ts-morph";
6896
7088
  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);
7089
+ const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts3.SyntaxKind.ArrowFunction).find((arrowFunction) => {
7090
+ const binaryExpression = arrowFunction.getFirstAncestorByKind(ts3.SyntaxKind.BinaryExpression);
6899
7091
  if (!binaryExpression) return false;
6900
7092
  const binaryExpressionLeft = binaryExpression.getLeft();
6901
7093
  if (!binaryExpressionLeft.getText().endsWith(".f.require")) return false;
@@ -6904,16 +7096,16 @@ async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { instal
6904
7096
  const binaryExpressionRight = binaryExpression.getRight();
6905
7097
  if (binaryExpressionRight !== arrowFunction) return false;
6906
7098
  const arrowFunctionBody = arrowFunction.getBody();
6907
- if (!arrowFunctionBody.isKind(ts2.SyntaxKind.Block)) return false;
7099
+ if (!arrowFunctionBody.isKind(ts3.SyntaxKind.Block)) return false;
6908
7100
  const arrowFunctionBodyText = arrowFunctionBody.getText();
6909
7101
  const functionUsesChunkInstallationVariables = arrowFunctionBodyText.includes(installChunk) && arrowFunctionBodyText.includes(installedChunks);
6910
7102
  if (!functionUsesChunkInstallationVariables) return false;
6911
7103
  const functionParameters = arrowFunction.getParameters();
6912
7104
  if (functionParameters.length !== 2) return false;
6913
- 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);
6914
7106
  if (!callsInstallChunk) return false;
6915
7107
  const functionFirstParameterName = functionParameters[0]?.getName();
6916
- const accessesInstalledChunksUsingItsFirstParameter = arrowFunctionBody.getDescendantsOfKind(ts2.SyntaxKind.ElementAccessExpression).some((elementAccess) => {
7108
+ const accessesInstalledChunksUsingItsFirstParameter = arrowFunctionBody.getDescendantsOfKind(ts3.SyntaxKind.ElementAccessExpression).some((elementAccess) => {
6917
7109
  return elementAccess.getExpression().getText() === installedChunks && elementAccess.getArgumentExpression()?.getText() === functionFirstParameterName;
6918
7110
  });
6919
7111
  if (!accessesInstalledChunksUsingItsFirstParameter) return false;
@@ -6935,15 +7127,7 @@ if(${chunkId} === ${chunk}) return ${installChunk}(require("./chunks/${chunk}.js
6935
7127
  return sourceFile.print();
6936
7128
  }
6937
7129
 
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
7130
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
6947
7131
  async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6948
7132
  const tsSourceFile = tsParseFile(fileContent);
6949
7133
  const chunkInstallationIdentifiers = await getChunkInstallationIdentifiers(tsSourceFile);
@@ -6955,31 +7139,50 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6955
7139
  return updatedFileContent;
6956
7140
  }
6957
7141
 
6958
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6959
- async function updateWebpackChunksFile(nextjsAppPaths) {
7142
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7143
+ import path12 from "node:path";
7144
+ async function updateWebpackChunksFile(config) {
6960
7145
  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) => {
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) => {
6964
7149
  console.log(` - chunk ${chunk}`);
6965
7150
  return chunk.replace(/\.js$/, "");
6966
7151
  });
6967
7152
  const updatedFileContent = await getUpdatedWebpackChunksFileContent(fileContent, chunks);
6968
- writeFileSync2(webpackRuntimeFile, updatedFileContent);
7153
+ writeFileSync3(webpackRuntimeFile, updatedFileContent);
6969
7154
  }
6970
7155
 
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(
7156
+ // src/cli/build/build-worker.ts
7157
+ var packageDistDir = path13.join(path13.dirname(fileURLToPath3(import.meta.url)), "..");
7158
+ async function buildWorker(config) {
7159
+ console.log(`\x1B[35m\u2699\uFE0F Copying files...
7160
+ \x1B[0m`);
7161
+ await cp(
7162
+ path13.join(config.paths.dotNext, "static"),
7163
+ path13.join(config.paths.builderOutput, "assets", "_next", "static"),
7164
+ {
7165
+ recursive: true
7166
+ }
7167
+ );
7168
+ const publicDir = path13.join(config.paths.nextApp, "public");
7169
+ if (existsSync5(publicDir)) {
7170
+ await cp(publicDir, path13.join(config.paths.builderOutput, "assets"), {
7171
+ recursive: true
7172
+ });
7173
+ }
7174
+ copyPrerenderedRoutes(config);
7175
+ copyPackageCliFiles(packageDistDir, config);
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(
6977
7180
  /const nextConfig = ({.+?})\n/
6978
7181
  )?.[1] ?? {};
6979
7182
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
6980
7183
  \x1B[0m`);
6981
- patchWranglerDeps(nextjsAppPaths);
6982
- updateWebpackChunksFile(nextjsAppPaths);
7184
+ patchWranglerDeps(config);
7185
+ updateWebpackChunksFile(config);
6983
7186
  await build({
6984
7187
  entryPoints: [workerEntrypoint],
6985
7188
  bundle: true,
@@ -6992,15 +7195,15 @@ async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
6992
7195
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
6993
7196
  // eval("require")("bufferutil");
6994
7197
  // eval("require")("utf-8-validate");
6995
- "next/dist/compiled/ws": `${templateDir}/shims/empty.ts`,
7198
+ "next/dist/compiled/ws": path13.join(templateDir, "shims", "empty.ts"),
6996
7199
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
6997
7200
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
6998
7201
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
6999
7202
  // QUESTION: Why did I encountered this but mhart didn't?
7000
- "next/dist/compiled/edge-runtime": `${templateDir}/shims/empty.ts`,
7203
+ "next/dist/compiled/edge-runtime": path13.join(templateDir, "shims", "empty.ts"),
7001
7204
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7002
7205
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7003
- "@next/env": `${templateDir}/shims/env.ts`
7206
+ "@next/env": path13.join(templateDir, "shims", "env.ts")
7004
7207
  },
7005
7208
  define: {
7006
7209
  // 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 +7213,6 @@ async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
7010
7213
  // Note: we need the __non_webpack_require__ variable declared as it is used by next-server:
7011
7214
  // https://github.com/vercel/next.js/blob/be0c3283/packages/next/src/server/next-server.ts#L116-L119
7012
7215
  __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
7216
  // Ask mhart if he can explain why the `define`s below are necessary
7018
7217
  "process.env.NEXT_RUNTIME": '"nodejs"',
7019
7218
  "process.env.NODE_ENV": '"production"',
@@ -7034,22 +7233,21 @@ async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
7034
7233
  // Do not crash on cache not supported
7035
7234
  // https://github.com/cloudflare/workerd/pull/2434
7036
7235
  // compatibility flag "cache_option_enabled" -> does not support "force-cache"
7037
- let isPatchedAlready = globalThis.fetch.__nextPatched;
7038
7236
  const curFetch = globalThis.fetch;
7039
7237
  globalThis.fetch = (input, init) => {
7040
- console.log("globalThis.fetch", input);
7041
- if (init) delete init.cache;
7238
+ if (init) {
7239
+ delete init.cache;
7240
+ }
7042
7241
  return curFetch(input, init);
7043
7242
  };
7044
7243
  import { Readable } from 'node:stream';
7045
- globalThis.fetch.__nextPatched = isPatchedAlready;
7046
7244
  fetch = globalThis.fetch;
7047
7245
  const CustomRequest = class extends globalThis.Request {
7048
7246
  constructor(input, init) {
7049
- console.log("CustomRequest", input);
7050
7247
  if (init) {
7051
7248
  delete init.cache;
7052
7249
  if (init.body?.__node_stream__ === true) {
7250
+ // https://github.com/cloudflare/workerd/issues/2746
7053
7251
  init.body = Readable.toWeb(init.body);
7054
7252
  }
7055
7253
  }
@@ -7058,127 +7256,115 @@ const CustomRequest = class extends globalThis.Request {
7058
7256
  };
7059
7257
  globalThis.Request = CustomRequest;
7060
7258
  Request = globalThis.Request;
7061
- `
7259
+ `
7062
7260
  }
7063
7261
  });
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
- });
7262
+ await updateWorkerBundledCode(workerOutputFile, config);
7070
7263
  console.log(`\x1B[35mWorker saved in \`${workerOutputFile}\` \u{1F680}
7071
7264
  \x1B[0m`);
7072
7265
  }
7073
- async function updateWorkerBundledCode(workerOutputFile, nextjsAppPaths) {
7266
+ async function updateWorkerBundledCode(workerOutputFile, config) {
7074
7267
  const originalCode = await readFile(workerOutputFile, "utf8");
7075
7268
  let patchedCode = originalCode;
7076
7269
  patchedCode = patchRequire(patchedCode);
7077
- patchedCode = patchReadFile(patchedCode, nextjsAppPaths);
7078
- patchedCode = inlineNextRequire(patchedCode, nextjsAppPaths);
7079
- patchedCode = patchFindDir(patchedCode, nextjsAppPaths);
7080
- patchedCode = inlineEvalManifest(patchedCode, nextjsAppPaths);
7270
+ patchedCode = patchReadFile(patchedCode, config);
7271
+ patchedCode = inlineNextRequire(patchedCode, config);
7272
+ patchedCode = patchFindDir(patchedCode, config);
7273
+ patchedCode = inlineEvalManifest(patchedCode, config);
7274
+ patchedCode = patchCache(patchedCode, config);
7275
+ patchedCode = inlineMiddlewareManifestRequire(patchedCode, config);
7276
+ patchedCode = patchExceptionBubbling(patchedCode);
7081
7277
  await writeFile(workerOutputFile, patchedCode);
7082
7278
  }
7083
7279
  function createFixRequiresESBuildPlugin(templateDir) {
7084
7280
  return {
7085
7281
  name: "replaceRelative",
7086
7282
  setup(build3) {
7087
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7088
- path: `${templateDir}/shims/empty.ts`
7283
+ build3.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7284
+ path: path13.join(templateDir, "shims", "empty.ts")
7089
7285
  }));
7090
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7091
- path: `${templateDir}/shims/node-fs.ts`
7286
+ build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7287
+ path: path13.join(templateDir, "shims", "empty.ts")
7092
7288
  }));
7093
7289
  }
7094
7290
  };
7095
7291
  }
7096
7292
 
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);
7293
+ // src/cli/build/index.ts
7294
+ import { cpSync as cpSync2 } from "node:fs";
7295
+ import path14 from "node:path";
7296
+ import { rm } from "node:fs/promises";
7297
+ async function build2(appDir, opts) {
7298
+ if (!opts.skipBuild) {
7299
+ await buildNextjsApp(appDir);
7300
+ }
7301
+ if (!containsDotNextDir(appDir)) {
7302
+ throw new Error(`.next folder not found in ${appDir}`);
7303
+ }
7304
+ const outputDir2 = path14.resolve(opts.outputDir ?? appDir, ".worker-next");
7305
+ await cleanDirectory(outputDir2);
7306
+ cpSync2(path14.join(appDir, ".next"), path14.join(outputDir2, ".next"), { recursive: true });
7307
+ const config = getConfig(appDir, outputDir2);
7308
+ await buildWorker(config);
7309
+ }
7310
+ async function cleanDirectory(path15) {
7311
+ return await rm(path15, { recursive: true, force: true });
7312
+ }
7313
+
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
+ }
7104
7342
  return {
7105
- appDir: nextAppDir2,
7106
- dotNextDir,
7107
- standaloneAppDir,
7108
- standaloneAppDotNextDir: path4.join(standaloneAppDir, ".next"),
7109
- standaloneAppServerDir: path4.join(standaloneAppDir, ".next", "server")
7343
+ outputDir: outputDir2,
7344
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7110
7345
  };
7111
7346
  }
7112
- function getDotNextDirPath(nextAppDir2) {
7113
- const dotNextDirPath = `${nextAppDir2}/.next`;
7347
+ function assertDirArg(path15, argName, make) {
7348
+ let dirStats;
7114
7349
  try {
7115
- const dirStats = statSync2(dotNextDirPath);
7116
- if (!dirStats.isDirectory()) throw new Error();
7350
+ dirStats = statSync3(path15);
7117
7351
  } 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
- }
7352
+ if (!make) {
7353
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7143
7354
  }
7355
+ mkdirSync2(path15);
7356
+ return;
7144
7357
  }
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
- });
7358
+ if (!dirStats.isDirectory()) {
7359
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7167
7360
  }
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
7361
  }
7177
7362
 
7178
- // src/index.ts
7363
+ // src/cli/index.ts
7364
+ import { resolve as resolve2 } from "node:path";
7179
7365
  var nextAppDir = resolve2(".");
7180
7366
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7181
- if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync3(`./next.config.${ext2}`))) {
7367
+ if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync6(`./next.config.${ext2}`))) {
7182
7368
  throw new Error("Error: Not in a Next.js app project");
7183
7369
  }
7184
7370
  var { skipBuild, outputDir } = getArgs();