@opennextjs/cloudflare 0.0.0-5454280 → 0.0.0-59a1d9e

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,12 @@
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
+ __commonJS,
4
+ __toESM
5
+ } from "./chunk-UJCSKKID.mjs";
26
6
 
27
- // ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
7
+ // ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
28
8
  var require_balanced_match = __commonJS({
29
- "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
9
+ "../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
30
10
  "use strict";
31
11
  module.exports = balanced;
32
12
  function balanced(a, b, str) {
@@ -82,9 +62,9 @@ var require_balanced_match = __commonJS({
82
62
  }
83
63
  });
84
64
 
85
- // ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
65
+ // ../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
86
66
  var require_brace_expansion = __commonJS({
87
- "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
67
+ "../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
88
68
  "use strict";
89
69
  var balanced = require_balanced_match();
90
70
  module.exports = expandTop;
@@ -233,68 +213,171 @@ var require_brace_expansion = __commonJS({
233
213
  }
234
214
  });
235
215
 
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);
216
+ // src/cli/config.ts
217
+ import path, { relative } from "node:path";
218
+ import { readdirSync, statSync } from "node:fs";
219
+ var PACKAGE_NAME = "@opennextjs/cloudflare";
220
+ var UserConfig = {
221
+ cache: {
222
+ bindingName: "NEXT_CACHE_WORKERS_KV"
263
223
  }
224
+ };
225
+ function getConfig(appDir, outputDir2) {
226
+ const dotNext = path.join(outputDir2, ".next");
227
+ const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
228
+ const standaloneRoot = path.join(dotNext, "standalone");
229
+ const standaloneApp = path.join(standaloneRoot, appPath);
230
+ const standaloneAppDotNext = path.join(standaloneApp, ".next");
231
+ const standaloneAppServer = path.join(standaloneAppDotNext, "server");
232
+ const nodeModules = path.join(standaloneApp, "node_modules");
233
+ const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/"));
264
234
  return {
265
- outputDir: outputDir2,
266
- skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
235
+ paths: {
236
+ nextApp: appDir,
237
+ builderOutput: outputDir2,
238
+ dotNext,
239
+ standaloneRoot,
240
+ standaloneApp,
241
+ standaloneAppDotNext,
242
+ standaloneAppServer,
243
+ internalPackage
244
+ },
245
+ cache: {
246
+ kvBindingName: UserConfig.cache.bindingName
247
+ },
248
+ internalPackageName: PACKAGE_NAME
267
249
  };
268
250
  }
269
- function assertDirArg(path6, argName, make) {
270
- let dirStats;
251
+ function containsDotNextDir(folder) {
271
252
  try {
272
- dirStats = statSync(path6);
253
+ return statSync(path.join(folder, ".next")).isDirectory();
273
254
  } catch {
274
- if (!make) {
275
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
255
+ return false;
256
+ }
257
+ }
258
+ function getNextjsApplicationPath(dotNextDir) {
259
+ const serverPath = findServerParentPath(dotNextDir);
260
+ if (!serverPath) {
261
+ throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
262
+ }
263
+ return relative(path.join(dotNextDir, "standalone"), serverPath);
264
+ }
265
+ function findServerParentPath(parentPath) {
266
+ try {
267
+ if (statSync(path.join(parentPath, ".next", "server")).isDirectory()) {
268
+ return parentPath;
276
269
  }
277
- mkdirSync(path6);
278
- return;
270
+ } catch {
279
271
  }
280
- if (!dirStats.isDirectory()) {
281
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
272
+ const folders = readdirSync(parentPath);
273
+ for (const folder of folders) {
274
+ const subFolder = path.join(parentPath, folder);
275
+ if (statSync(path.join(parentPath, folder)).isDirectory()) {
276
+ const dirServerPath = findServerParentPath(subFolder);
277
+ if (dirServerPath) {
278
+ return dirServerPath;
279
+ }
280
+ }
282
281
  }
283
282
  }
284
283
 
285
- // src/index.ts
286
- import { existsSync as existsSync3 } from "node:fs";
284
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/constants.mjs
285
+ var AGENTS = [
286
+ "npm",
287
+ "yarn",
288
+ "yarn@berry",
289
+ "pnpm",
290
+ "pnpm@6",
291
+ "bun"
292
+ ];
293
+ var LOCKS = {
294
+ "bun.lockb": "bun",
295
+ "pnpm-lock.yaml": "pnpm",
296
+ "yarn.lock": "yarn",
297
+ "package-lock.json": "npm",
298
+ "npm-shrinkwrap.json": "npm"
299
+ };
287
300
 
288
- // src/build/build.ts
289
- import { rm } from "node:fs/promises";
301
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/detect.mjs
302
+ import fs from "node:fs";
303
+ import fsPromises from "node:fs/promises";
304
+ import path2 from "node:path";
305
+ import process2 from "node:process";
306
+ async function detect({ cwd, onUnknown } = {}) {
307
+ for (const directory of lookup(cwd)) {
308
+ for (const lock of Object.keys(LOCKS)) {
309
+ if (await fileExists(path2.join(directory, lock))) {
310
+ const name = LOCKS[lock];
311
+ const result2 = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
312
+ if (result2)
313
+ return result2;
314
+ else
315
+ return { name, agent: name };
316
+ }
317
+ }
318
+ const result = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
319
+ if (result)
320
+ return result;
321
+ }
322
+ return null;
323
+ }
324
+ function* lookup(cwd = process2.cwd()) {
325
+ let directory = path2.resolve(cwd);
326
+ const { root } = path2.parse(directory);
327
+ while (directory && directory !== root) {
328
+ yield directory;
329
+ directory = path2.dirname(directory);
330
+ }
331
+ }
332
+ async function parsePackageJson(filepath, onUnknown) {
333
+ if (!filepath || !await fileExists(filepath))
334
+ return null;
335
+ try {
336
+ const pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
337
+ let agent;
338
+ if (typeof pkg.packageManager === "string") {
339
+ const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
340
+ let version = ver;
341
+ if (name === "yarn" && Number.parseInt(ver) > 1) {
342
+ agent = "yarn@berry";
343
+ version = "berry";
344
+ return { name, agent, version };
345
+ } else if (name === "pnpm" && Number.parseInt(ver) < 7) {
346
+ agent = "pnpm@6";
347
+ return { name, agent, version };
348
+ } else if (AGENTS.includes(name)) {
349
+ agent = name;
350
+ return { name, agent, version };
351
+ } else {
352
+ return onUnknown?.(pkg.packageManager) ?? null;
353
+ }
354
+ }
355
+ } catch {
356
+ }
357
+ return null;
358
+ }
359
+ async function fileExists(filePath) {
360
+ try {
361
+ const stats = await fsPromises.stat(filePath);
362
+ if (stats.isFile()) {
363
+ return true;
364
+ }
365
+ } catch {
366
+ }
367
+ return false;
368
+ }
290
369
 
291
- // src/build/build-next-app.ts
370
+ // src/cli/build/build-next-app.ts
292
371
  import { execSync } from "node:child_process";
293
- function buildNextjsApp(nextAppDir2) {
294
- runNextBuildCommand("pnpm", nextAppDir2);
372
+ async function buildNextjsApp(nextAppDir2) {
373
+ const pm = await detect();
374
+ if (!pm) {
375
+ throw new Error("Fatal Error: package manager detection failed, aborting");
376
+ }
377
+ runNextBuildCommand(pm.name, nextAppDir2);
295
378
  }
296
379
  function runNextBuildCommand(packager, nextAppDir2) {
297
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
380
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
298
381
  execSync(command, {
299
382
  stdio: "inherit",
300
383
  cwd: nextAppDir2,
@@ -307,34 +390,28 @@ function runNextBuildCommand(packager, nextAppDir2) {
307
390
  });
308
391
  }
309
392
 
310
- // src/build/build-worker.ts
393
+ // src/cli/build/build-worker.ts
311
394
  import { build } from "esbuild";
312
- import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
313
395
  import { cp, readFile, writeFile } from "node:fs/promises";
396
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
314
397
 
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.");
319
- }
320
-
321
- // src/build/patches/investigated/copy-templates.ts
322
- import path from "node:path";
398
+ // src/cli/build/patches/investigated/copy-package-cli-files.ts
323
399
  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;
400
+ import path3 from "node:path";
401
+ function copyPackageCliFiles(packageDistDir2, config) {
402
+ console.log("# copyPackageTemplateFiles");
403
+ const sourceDir = path3.join(packageDistDir2, "cli");
404
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
405
+ cpSync(sourceDir, destinationDir, { recursive: true });
329
406
  }
330
407
 
331
- // src/build/patches/to-investigate/patch-read-file.ts
332
- import { readFileSync } from "node:fs";
408
+ // src/cli/build/build-worker.ts
409
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
333
410
 
334
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
411
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
335
412
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
336
413
 
337
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/assert-valid-pattern.js
414
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/assert-valid-pattern.js
338
415
  var MAX_PATTERN_LENGTH = 1024 * 64;
339
416
  var assertValidPattern = (pattern) => {
340
417
  if (typeof pattern !== "string") {
@@ -345,7 +422,7 @@ var assertValidPattern = (pattern) => {
345
422
  }
346
423
  };
347
424
 
348
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/brace-expressions.js
425
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/brace-expressions.js
349
426
  var posixClasses = {
350
427
  "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
351
428
  "[:alpha:]": ["\\p{L}\\p{Nl}", true],
@@ -454,12 +531,12 @@ var parseClass = (glob2, position) => {
454
531
  return [comb, uflag, endPos - pos, true];
455
532
  };
456
533
 
457
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/unescape.js
534
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/unescape.js
458
535
  var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
459
536
  return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
460
537
  };
461
538
 
462
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/ast.js
539
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/ast.js
463
540
  var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
464
541
  var isExtglobType = (c) => types.has(c);
465
542
  var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
@@ -938,12 +1015,12 @@ var AST = class _AST {
938
1015
  }
939
1016
  };
940
1017
 
941
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/escape.js
1018
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/escape.js
942
1019
  var escape = (s, { windowsPathsNoEscape = false } = {}) => {
943
1020
  return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
944
1021
  };
945
1022
 
946
- // ../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
1023
+ // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
947
1024
  var minimatch = (p, pattern, options = {}) => {
948
1025
  assertValidPattern(pattern);
949
1026
  if (!options.nocomment && pattern.charAt(0) === "#") {
@@ -1002,11 +1079,11 @@ var qmarksTestNoExtDot = ([$0]) => {
1002
1079
  return (f) => f.length === len && f !== "." && f !== "..";
1003
1080
  };
1004
1081
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
1005
- var path2 = {
1082
+ var path4 = {
1006
1083
  win32: { sep: "\\" },
1007
1084
  posix: { sep: "/" }
1008
1085
  };
1009
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1086
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
1010
1087
  minimatch.sep = sep;
1011
1088
  var GLOBSTAR = Symbol("globstar **");
1012
1089
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -1661,10 +1738,10 @@ minimatch.Minimatch = Minimatch;
1661
1738
  minimatch.escape = escape;
1662
1739
  minimatch.unescape = unescape;
1663
1740
 
1664
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
1741
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
1665
1742
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1666
1743
 
1667
- // ../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/dist/esm/index.js
1744
+ // ../../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/dist/esm/index.js
1668
1745
  var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
1669
1746
  var warned = /* @__PURE__ */ new Set();
1670
1747
  var PROCESS = typeof process === "object" && !!process ? process : {};
@@ -3033,14 +3110,14 @@ var LRUCache = class _LRUCache {
3033
3110
  }
3034
3111
  };
3035
3112
 
3036
- // ../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3113
+ // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3037
3114
  import { posix, win32 } from "node:path";
3038
3115
  import { fileURLToPath } from "node:url";
3039
- import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
3116
+ import { lstatSync, readdir as readdirCB, readdirSync as readdirSync2, readlinkSync, realpathSync as rps } from "fs";
3040
3117
  import * as actualFS from "node:fs";
3041
3118
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3042
3119
 
3043
- // ../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/dist/esm/index.js
3120
+ // ../../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/dist/esm/index.js
3044
3121
  import { EventEmitter } from "node:events";
3045
3122
  import Stream from "node:stream";
3046
3123
  import { StringDecoder } from "node:string_decoder";
@@ -3918,12 +3995,12 @@ var Minipass = class extends EventEmitter {
3918
3995
  }
3919
3996
  };
3920
3997
 
3921
- // ../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3998
+ // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3922
3999
  var realpathSync = rps.native;
3923
4000
  var defaultFS = {
3924
4001
  lstatSync,
3925
4002
  readdir: readdirCB,
3926
- readdirSync,
4003
+ readdirSync: readdirSync2,
3927
4004
  readlinkSync,
3928
4005
  realpathSync,
3929
4006
  promises: {
@@ -4183,12 +4260,12 @@ var PathBase = class {
4183
4260
  /**
4184
4261
  * Get the Path object referenced by the string path, resolved from this Path
4185
4262
  */
4186
- resolve(path6) {
4187
- if (!path6) {
4263
+ resolve(path14) {
4264
+ if (!path14) {
4188
4265
  return this;
4189
4266
  }
4190
- const rootPath = this.getRootString(path6);
4191
- const dir = path6.substring(rootPath.length);
4267
+ const rootPath = this.getRootString(path14);
4268
+ const dir = path14.substring(rootPath.length);
4192
4269
  const dirParts = dir.split(this.splitSep);
4193
4270
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4194
4271
  return result;
@@ -4940,8 +5017,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4940
5017
  /**
4941
5018
  * @internal
4942
5019
  */
4943
- getRootString(path6) {
4944
- return win32.parse(path6).root;
5020
+ getRootString(path14) {
5021
+ return win32.parse(path14).root;
4945
5022
  }
4946
5023
  /**
4947
5024
  * @internal
@@ -4987,8 +5064,8 @@ var PathPosix = class _PathPosix extends PathBase {
4987
5064
  /**
4988
5065
  * @internal
4989
5066
  */
4990
- getRootString(path6) {
4991
- return path6.startsWith("/") ? "/" : "";
5067
+ getRootString(path14) {
5068
+ return path14.startsWith("/") ? "/" : "";
4992
5069
  }
4993
5070
  /**
4994
5071
  * @internal
@@ -5037,8 +5114,8 @@ var PathScurryBase = class {
5037
5114
  *
5038
5115
  * @internal
5039
5116
  */
5040
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
5041
- this.#fs = fsFromOption(fs2);
5117
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs3 = defaultFS } = {}) {
5118
+ this.#fs = fsFromOption(fs3);
5042
5119
  if (cwd instanceof URL || cwd.startsWith("file://")) {
5043
5120
  cwd = fileURLToPath(cwd);
5044
5121
  }
@@ -5077,11 +5154,11 @@ var PathScurryBase = class {
5077
5154
  /**
5078
5155
  * Get the depth of a provided path, string, or the cwd
5079
5156
  */
5080
- depth(path6 = this.cwd) {
5081
- if (typeof path6 === "string") {
5082
- path6 = this.cwd.resolve(path6);
5157
+ depth(path14 = this.cwd) {
5158
+ if (typeof path14 === "string") {
5159
+ path14 = this.cwd.resolve(path14);
5083
5160
  }
5084
- return path6.depth();
5161
+ return path14.depth();
5085
5162
  }
5086
5163
  /**
5087
5164
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5460,7 +5537,7 @@ var PathScurryBase = class {
5460
5537
  const dirs = /* @__PURE__ */ new Set();
5461
5538
  const queue = [entry];
5462
5539
  let processing = 0;
5463
- const process2 = () => {
5540
+ const process3 = () => {
5464
5541
  let paused = false;
5465
5542
  while (!paused) {
5466
5543
  const dir = queue.shift();
@@ -5501,9 +5578,9 @@ var PathScurryBase = class {
5501
5578
  }
5502
5579
  }
5503
5580
  if (paused && !results.flowing) {
5504
- results.once("drain", process2);
5581
+ results.once("drain", process3);
5505
5582
  } else if (!sync2) {
5506
- process2();
5583
+ process3();
5507
5584
  }
5508
5585
  };
5509
5586
  let sync2 = true;
@@ -5511,7 +5588,7 @@ var PathScurryBase = class {
5511
5588
  sync2 = false;
5512
5589
  }
5513
5590
  };
5514
- process2();
5591
+ process3();
5515
5592
  return results;
5516
5593
  }
5517
5594
  streamSync(entry = this.cwd, opts = {}) {
@@ -5529,7 +5606,7 @@ var PathScurryBase = class {
5529
5606
  }
5530
5607
  const queue = [entry];
5531
5608
  let processing = 0;
5532
- const process2 = () => {
5609
+ const process3 = () => {
5533
5610
  let paused = false;
5534
5611
  while (!paused) {
5535
5612
  const dir = queue.shift();
@@ -5563,14 +5640,14 @@ var PathScurryBase = class {
5563
5640
  }
5564
5641
  }
5565
5642
  if (paused && !results.flowing)
5566
- results.once("drain", process2);
5643
+ results.once("drain", process3);
5567
5644
  };
5568
- process2();
5645
+ process3();
5569
5646
  return results;
5570
5647
  }
5571
- chdir(path6 = this.cwd) {
5648
+ chdir(path14 = this.cwd) {
5572
5649
  const oldCwd = this.cwd;
5573
- this.cwd = typeof path6 === "string" ? this.cwd.resolve(path6) : path6;
5650
+ this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
5574
5651
  this.cwd[setAsCwd](oldCwd);
5575
5652
  }
5576
5653
  };
@@ -5596,8 +5673,8 @@ var PathScurryWin32 = class extends PathScurryBase {
5596
5673
  /**
5597
5674
  * @internal
5598
5675
  */
5599
- newRoot(fs2) {
5600
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5676
+ newRoot(fs3) {
5677
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5601
5678
  }
5602
5679
  /**
5603
5680
  * Return true if the provided path string is an absolute path
@@ -5625,8 +5702,8 @@ var PathScurryPosix = class extends PathScurryBase {
5625
5702
  /**
5626
5703
  * @internal
5627
5704
  */
5628
- newRoot(fs2) {
5629
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5705
+ newRoot(fs3) {
5706
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5630
5707
  }
5631
5708
  /**
5632
5709
  * Return true if the provided path string is an absolute path
@@ -5644,7 +5721,7 @@ var PathScurryDarwin = class extends PathScurryPosix {
5644
5721
  var Path = process.platform === "win32" ? PathWin32 : PathPosix;
5645
5722
  var PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
5646
5723
 
5647
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/pattern.js
5724
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/pattern.js
5648
5725
  var isPatternList = (pl) => pl.length >= 1;
5649
5726
  var isGlobList = (gl) => gl.length >= 1;
5650
5727
  var Pattern = class _Pattern {
@@ -5809,7 +5886,7 @@ var Pattern = class _Pattern {
5809
5886
  }
5810
5887
  };
5811
5888
 
5812
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/ignore.js
5889
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/ignore.js
5813
5890
  var defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
5814
5891
  var Ignore = class {
5815
5892
  relative;
@@ -5896,7 +5973,7 @@ var Ignore = class {
5896
5973
  }
5897
5974
  };
5898
5975
 
5899
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/processor.js
5976
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/processor.js
5900
5977
  var HasWalkedCache = class _HasWalkedCache {
5901
5978
  store;
5902
5979
  constructor(store = /* @__PURE__ */ new Map()) {
@@ -5926,8 +6003,8 @@ var MatchRecord = class {
5926
6003
  }
5927
6004
  // match, absolute, ifdir
5928
6005
  entries() {
5929
- return [...this.store.entries()].map(([path6, n]) => [
5930
- path6,
6006
+ return [...this.store.entries()].map(([path14, n]) => [
6007
+ path14,
5931
6008
  !!(n & 2),
5932
6009
  !!(n & 1)
5933
6010
  ]);
@@ -6117,7 +6194,7 @@ var Processor = class _Processor {
6117
6194
  }
6118
6195
  };
6119
6196
 
6120
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/walker.js
6197
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/walker.js
6121
6198
  var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
6122
6199
  var GlobUtil = class {
6123
6200
  path;
@@ -6132,9 +6209,9 @@ var GlobUtil = class {
6132
6209
  signal;
6133
6210
  maxDepth;
6134
6211
  includeChildMatches;
6135
- constructor(patterns, path6, opts) {
6212
+ constructor(patterns, path14, opts) {
6136
6213
  this.patterns = patterns;
6137
- this.path = path6;
6214
+ this.path = path14;
6138
6215
  this.opts = opts;
6139
6216
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6140
6217
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6153,11 +6230,11 @@ var GlobUtil = class {
6153
6230
  });
6154
6231
  }
6155
6232
  }
6156
- #ignored(path6) {
6157
- return this.seen.has(path6) || !!this.#ignore?.ignored?.(path6);
6233
+ #ignored(path14) {
6234
+ return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
6158
6235
  }
6159
- #childrenIgnored(path6) {
6160
- return !!this.#ignore?.childrenIgnored?.(path6);
6236
+ #childrenIgnored(path14) {
6237
+ return !!this.#ignore?.childrenIgnored?.(path14);
6161
6238
  }
6162
6239
  // backpressure mechanism
6163
6240
  pause() {
@@ -6372,8 +6449,8 @@ var GlobUtil = class {
6372
6449
  };
6373
6450
  var GlobWalker = class extends GlobUtil {
6374
6451
  matches = /* @__PURE__ */ new Set();
6375
- constructor(patterns, path6, opts) {
6376
- super(patterns, path6, opts);
6452
+ constructor(patterns, path14, opts) {
6453
+ super(patterns, path14, opts);
6377
6454
  }
6378
6455
  matchEmit(e) {
6379
6456
  this.matches.add(e);
@@ -6410,8 +6487,8 @@ var GlobWalker = class extends GlobUtil {
6410
6487
  };
6411
6488
  var GlobStream = class extends GlobUtil {
6412
6489
  results;
6413
- constructor(patterns, path6, opts) {
6414
- super(patterns, path6, opts);
6490
+ constructor(patterns, path14, opts) {
6491
+ super(patterns, path14, opts);
6415
6492
  this.results = new Minipass({
6416
6493
  signal: this.signal,
6417
6494
  objectMode: true
@@ -6444,7 +6521,7 @@ var GlobStream = class extends GlobUtil {
6444
6521
  }
6445
6522
  };
6446
6523
 
6447
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
6524
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/glob.js
6448
6525
  var defaultPlatform3 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
6449
6526
  var Glob = class {
6450
6527
  absolute;
@@ -6644,7 +6721,7 @@ var Glob = class {
6644
6721
  }
6645
6722
  };
6646
6723
 
6647
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/has-magic.js
6724
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/has-magic.js
6648
6725
  var hasMagic = (pattern, options = {}) => {
6649
6726
  if (!Array.isArray(pattern)) {
6650
6727
  pattern = [pattern];
@@ -6656,7 +6733,7 @@ var hasMagic = (pattern, options = {}) => {
6656
6733
  return false;
6657
6734
  };
6658
6735
 
6659
- // ../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/index.js
6736
+ // ../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/dist/esm/index.js
6660
6737
  function globStreamSync(pattern, options = {}) {
6661
6738
  return new Glob(pattern, options).streamSync();
6662
6739
  }
@@ -6704,60 +6781,44 @@ var glob = Object.assign(glob_, {
6704
6781
  });
6705
6782
  glob.glob = glob;
6706
6783
 
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\((.+?), .+?\) {/,
6784
+ // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6785
+ import path5 from "node:path";
6786
+ function inlineEvalManifest(code, config) {
6787
+ console.log("# inlineEvalManifest");
6788
+ const manifestJss = globSync(
6789
+ path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6790
+ ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6791
+ return code.replace(
6792
+ /function evalManifest\((.+?), .+?\) {/,
6721
6793
  `$&
6722
- ${manifestJsons.map(
6723
- (manifestJson) => `
6724
- if ($1.endsWith("${manifestJson}")) {
6725
- return ${readFileSync(`${nextjsAppPaths.standaloneAppDir}/${manifestJson}`, "utf-8")};
6726
- }
6727
- `
6794
+ ${manifestJss.map(
6795
+ (manifestJs) => `
6796
+ if ($1.endsWith("${manifestJs}")) {
6797
+ require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6798
+ return {
6799
+ __RSC_MANIFEST: {
6800
+ "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6801
+ },
6802
+ };
6803
+ }
6804
+ `
6728
6805
  ).join("\n")}
6729
- throw new Error("Unknown loadManifest: " + $1);
6730
- `
6731
- );
6732
- return code;
6733
- }
6734
-
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);
6806
+ throw new Error("Unknown evalManifest: " + $1);
6747
6807
  `
6748
6808
  );
6749
6809
  }
6750
6810
 
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) {
6811
+ // src/cli/build/patches/to-investigate/inline-next-require.ts
6812
+ import { existsSync, readFileSync } from "node:fs";
6813
+ import path6 from "node:path";
6814
+ function inlineNextRequire(code, config) {
6754
6815
  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(
6816
+ const pagesManifestFile = path6.join(config.paths.standaloneAppServer, "pages-manifest.json");
6817
+ const appPathsManifestFile = path6.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6818
+ const pagesManifestFiles = existsSync(pagesManifestFile) ? Object.values(JSON.parse(readFileSync(pagesManifestFile, "utf-8"))).map(
6758
6819
  (file) => ".next/server/" + file
6759
6820
  ) : [];
6760
- const appPathsManifestFiles = existsSync2(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync2(appPathsManifestFile, "utf-8"))).map(
6821
+ const appPathsManifestFiles = existsSync(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync(appPathsManifestFile, "utf-8"))).map(
6761
6822
  (file) => ".next/server/" + file
6762
6823
  ) : [];
6763
6824
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6769,14 +6830,14 @@ function inlineNextRequire(code, nextjsAppPaths) {
6769
6830
  ${htmlPages.map(
6770
6831
  (htmlPage) => `
6771
6832
  if (pagePath.endsWith("${htmlPage}")) {
6772
- return ${JSON.stringify(readFileSync2(`${nextjsAppPaths.standaloneAppDir}/${htmlPage}`, "utf-8"))};
6833
+ return ${JSON.stringify(readFileSync(path6.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6773
6834
  }
6774
6835
  `
6775
6836
  ).join("\n")}
6776
6837
  ${pageModules.map(
6777
6838
  (module) => `
6778
6839
  if (pagePath.endsWith("${module}")) {
6779
- return require("${nextjsAppPaths.standaloneAppDir}/${module}");
6840
+ return require("${path6.join(config.paths.standaloneApp, module)}");
6780
6841
  }
6781
6842
  `
6782
6843
  ).join("\n")}
@@ -6785,75 +6846,264 @@ function inlineNextRequire(code, nextjsAppPaths) {
6785
6846
  );
6786
6847
  }
6787
6848
 
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}/`, ""));
6849
+ // src/cli/build/patches/investigated/patch-cache.ts
6850
+ import path7 from "node:path";
6851
+ function patchCache(code, config) {
6852
+ console.log("# patchCached");
6853
+ const cacheHandler = path7.join(config.paths.internalPackage, "cli", "cache-handler.mjs");
6854
+ const patchedCode = code.replace(
6855
+ "const { cacheHandler } = this.nextConfig;",
6856
+ `const cacheHandler = null;
6857
+ CacheHandler = (await import('${cacheHandler}')).default;
6858
+ CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6859
+ `
6860
+ );
6861
+ if (patchedCode === code) {
6862
+ throw new Error("Cache patch not applied");
6863
+ }
6864
+ return patchedCode;
6865
+ }
6866
+
6867
+ // src/cli/build/patches/to-investigate/patch-find-dir.ts
6868
+ import { existsSync as existsSync2 } from "node:fs";
6869
+ import path8 from "node:path";
6870
+ function patchFindDir(code, config) {
6871
+ console.log("# patchFindDir");
6794
6872
  return code.replace(
6795
- /function evalManifest\((.+?), .+?\) {/,
6873
+ "function findDir(dir, name) {",
6874
+ `function findDir(dir, name) {
6875
+ if (dir.endsWith(".next/server")) {
6876
+ if (name === "app") {
6877
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "app")}`)};
6878
+ }
6879
+ if (name === "pages") {
6880
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "pages")}`)};
6881
+ }
6882
+ }
6883
+ throw new Error("Unknown findDir call: " + dir + " " + name);
6884
+ `
6885
+ );
6886
+ }
6887
+
6888
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
6889
+ import path9 from "node:path";
6890
+ import { readFileSync as readFileSync2 } from "node:fs";
6891
+ function patchReadFile(code, config) {
6892
+ console.log("# patchReadFile");
6893
+ code = code.replace(
6894
+ "getBuildId() {",
6895
+ `getBuildId() {
6896
+ return ${JSON.stringify(readFileSync2(path9.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6897
+ `
6898
+ );
6899
+ const manifestJsons = globSync(path9.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6900
+ (file) => file.replace(config.paths.standaloneApp + "/", "")
6901
+ );
6902
+ code = code.replace(
6903
+ /function loadManifest\((.+?), .+?\) {/,
6796
6904
  `$&
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
- `
6905
+ ${manifestJsons.map(
6906
+ (manifestJson) => `
6907
+ if ($1.endsWith("${manifestJson}")) {
6908
+ return ${readFileSync2(path9.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6909
+ }
6910
+ `
6808
6911
  ).join("\n")}
6809
- throw new Error("Unknown evalManifest: " + $1);
6810
- `
6912
+ throw new Error("Unknown loadManifest: " + $1);
6913
+ `
6811
6914
  );
6915
+ return code;
6812
6916
  }
6813
6917
 
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) {
6918
+ // src/cli/build/patches/investigated/patch-require.ts
6919
+ function patchRequire(code) {
6920
+ console.log("# patchRequire");
6921
+ return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
6922
+ }
6923
+
6924
+ // src/cli/build/patches/to-investigate/wrangler-deps.ts
6925
+ import fs2, { writeFileSync } from "node:fs";
6926
+ import path10 from "node:path";
6927
+ function patchWranglerDeps(config) {
6818
6928
  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"
6929
+ const distPath = getDistPath(config);
6930
+ const pagesRuntimeFile = path10.join(distPath, "compiled", "next-server", "pages.runtime.prod.js");
6931
+ const patchedPagesRuntime = fs2.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6932
+ fs2.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6933
+ const tracerFile = path10.join(distPath, "server", "lib", "trace", "tracer.js");
6934
+ const pacthedTracer = fs2.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6935
+ writeFileSync(tracerFile, pacthedTracer);
6936
+ }
6937
+ function getDistPath(config) {
6938
+ for (const root of [config.paths.standaloneApp, config.paths.standaloneRoot]) {
6939
+ try {
6940
+ const distPath = path10.join(root, "node_modules", "next", "dist");
6941
+ if (fs2.statSync(distPath).isDirectory()) return distPath;
6942
+ } catch {
6943
+ }
6944
+ }
6945
+ throw new Error("Unexpected error: unable to detect the node_modules/next/dist directory");
6946
+ }
6947
+
6948
+ // src/cli/build/build-worker.ts
6949
+ import path12 from "node:path";
6950
+
6951
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
6952
+ import { readFileSync as readFileSync3, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
6953
+
6954
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6955
+ import * as ts from "ts-morph";
6956
+ async function getChunkInstallationIdentifiers(sourceFile) {
6957
+ const installChunkDeclaration = getInstallChunkDeclaration(sourceFile);
6958
+ const installedChunksDeclaration = getInstalledChunksDeclaration(sourceFile, installChunkDeclaration);
6959
+ return {
6960
+ installChunk: installChunkDeclaration.getName(),
6961
+ installedChunks: installedChunksDeclaration.getName()
6962
+ };
6963
+ }
6964
+ function getInstallChunkDeclaration(sourceFile) {
6965
+ const installChunkDeclaration = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration).find((declaration) => {
6966
+ const arrowFunction = declaration.getInitializerIfKind(ts.SyntaxKind.ArrowFunction);
6967
+ if (!arrowFunction) return false;
6968
+ const functionParameters = arrowFunction.getParameters();
6969
+ if (functionParameters.length !== 1) return false;
6970
+ const arrowFunctionBodyBlock = arrowFunction.getFirstChildByKind(ts.SyntaxKind.Block);
6971
+ if (!arrowFunctionBodyBlock) return false;
6972
+ const statementKinds = arrowFunctionBodyBlock.getStatements().map((statement) => statement.getKind());
6973
+ const forInStatements = statementKinds.filter((s) => s === ts.SyntaxKind.ForInStatement);
6974
+ const forStatements = statementKinds.filter((s) => s === ts.SyntaxKind.ForStatement);
6975
+ if (forInStatements.length !== 1 || forStatements.length !== 1) return false;
6976
+ const parameterName = functionParameters[0].getText();
6977
+ const functionParameterAccessedProperties = arrowFunctionBodyBlock.getDescendantsOfKind(ts.SyntaxKind.PropertyAccessExpression).filter(
6978
+ (propertyAccessExpression) => propertyAccessExpression.getExpression().getText() === parameterName
6979
+ ).map((propertyAccessExpression) => propertyAccessExpression.getName());
6980
+ if (functionParameterAccessedProperties.join(", ") !== "modules, ids, runtime") return false;
6981
+ return true;
6982
+ });
6983
+ if (!installChunkDeclaration) {
6984
+ throw new Error("ERROR: unable to find the installChunk function declaration");
6985
+ }
6986
+ return installChunkDeclaration;
6987
+ }
6988
+ function getInstalledChunksDeclaration(sourceFile, installChunkDeclaration) {
6989
+ const allVariableDeclarations = sourceFile.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration);
6990
+ const installChunkDeclarationIdx = allVariableDeclarations.findIndex(
6991
+ (declaration) => declaration === installChunkDeclaration
6828
6992
  );
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"
6993
+ const installedChunksDeclaration = allVariableDeclarations[installChunkDeclarationIdx - 1];
6994
+ if (!installedChunksDeclaration?.getInitializer()?.isKind(ts.SyntaxKind.ObjectLiteralExpression)) {
6995
+ throw new Error("ERROR: unable to find the installedChunks declaration");
6996
+ }
6997
+ return installedChunksDeclaration;
6998
+ }
6999
+
7000
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
7001
+ import * as ts2 from "ts-morph";
7002
+ async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { installedChunks, installChunk }, chunks) {
7003
+ const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.ArrowFunction).find((arrowFunction) => {
7004
+ const binaryExpression = arrowFunction.getFirstAncestorByKind(ts2.SyntaxKind.BinaryExpression);
7005
+ if (!binaryExpression) return false;
7006
+ const binaryExpressionLeft = binaryExpression.getLeft();
7007
+ if (!binaryExpressionLeft.getText().endsWith(".f.require")) return false;
7008
+ const binaryExpressionOperator = binaryExpression.getOperatorToken();
7009
+ if (binaryExpressionOperator.getText() !== "=") return false;
7010
+ const binaryExpressionRight = binaryExpression.getRight();
7011
+ if (binaryExpressionRight !== arrowFunction) return false;
7012
+ const arrowFunctionBody = arrowFunction.getBody();
7013
+ if (!arrowFunctionBody.isKind(ts2.SyntaxKind.Block)) return false;
7014
+ const arrowFunctionBodyText = arrowFunctionBody.getText();
7015
+ const functionUsesChunkInstallationVariables = arrowFunctionBodyText.includes(installChunk) && arrowFunctionBodyText.includes(installedChunks);
7016
+ if (!functionUsesChunkInstallationVariables) return false;
7017
+ const functionParameters = arrowFunction.getParameters();
7018
+ if (functionParameters.length !== 2) return false;
7019
+ const callsInstallChunk = arrowFunctionBody.getDescendantsOfKind(ts2.SyntaxKind.CallExpression).some((callExpression) => callExpression.getExpression().getText() === installChunk);
7020
+ if (!callsInstallChunk) return false;
7021
+ const functionFirstParameterName = functionParameters[0]?.getName();
7022
+ const accessesInstalledChunksUsingItsFirstParameter = arrowFunctionBody.getDescendantsOfKind(ts2.SyntaxKind.ElementAccessExpression).some((elementAccess) => {
7023
+ return elementAccess.getExpression().getText() === installedChunks && elementAccess.getArgumentExpression()?.getText() === functionFirstParameterName;
7024
+ });
7025
+ if (!accessesInstalledChunksUsingItsFirstParameter) return false;
7026
+ return true;
7027
+ });
7028
+ if (!webpackFRequireFunction) {
7029
+ throw new Error("ERROR: unable to find the webpack f require function declaration");
7030
+ }
7031
+ const functionParameterNames = webpackFRequireFunction.getParameters().map((parameter) => parameter.getName());
7032
+ const chunkId = functionParameterNames[0];
7033
+ const functionBody = webpackFRequireFunction.getBody();
7034
+ functionBody.insertStatements(0, [
7035
+ `if (${installedChunks}[${chunkId}]) return;`,
7036
+ ...chunks.map(
7037
+ (chunk) => `
7038
+ if(${chunkId} === ${chunk}) return ${installChunk}(require("./chunks/${chunk}.js"));`
7039
+ )
7040
+ ]);
7041
+ return sourceFile.print();
7042
+ }
7043
+
7044
+ // src/cli/build/utils/ts-parse-file.ts
7045
+ import * as ts3 from "ts-morph";
7046
+ function tsParseFile(fileContent) {
7047
+ const project = new ts3.Project();
7048
+ const sourceFile = project.createSourceFile("file.js", fileContent);
7049
+ return sourceFile;
7050
+ }
7051
+
7052
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
7053
+ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
7054
+ const tsSourceFile = tsParseFile(fileContent);
7055
+ const chunkInstallationIdentifiers = await getChunkInstallationIdentifiers(tsSourceFile);
7056
+ const updatedFileContent = getFileContentWithUpdatedWebpackFRequireCode(
7057
+ tsSourceFile,
7058
+ chunkInstallationIdentifiers,
7059
+ chunks
6840
7060
  );
6841
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6842
- writeFileSync(tracerFile, pacthedTracer);
7061
+ return updatedFileContent;
7062
+ }
7063
+
7064
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7065
+ import path11 from "node:path";
7066
+ async function updateWebpackChunksFile(config) {
7067
+ console.log("# updateWebpackChunksFile");
7068
+ const webpackRuntimeFile = path11.join(config.paths.standaloneAppServer, "webpack-runtime.js");
7069
+ const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
7070
+ const chunks = readdirSync3(path11.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
7071
+ console.log(` - chunk ${chunk}`);
7072
+ return chunk.replace(/\.js$/, "");
7073
+ });
7074
+ const updatedFileContent = await getUpdatedWebpackChunksFileContent(fileContent, chunks);
7075
+ writeFileSync2(webpackRuntimeFile, updatedFileContent);
6843
7076
  }
6844
7077
 
6845
- // src/build/build-worker.ts
6846
- async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
6847
- const templateDir = copyTemplates(templateSrcDir, nextjsAppPaths);
6848
- const workerEntrypoint = `${templateDir}/worker.ts`;
6849
- const workerOutputFile = `${outputDir2}/index.mjs`;
6850
- const nextConfigStr = readFileSync3(nextjsAppPaths.standaloneAppDir + "/server.js", "utf8")?.match(
7078
+ // src/cli/build/build-worker.ts
7079
+ var packageDistDir = path12.join(path12.dirname(fileURLToPath3(import.meta.url)), "..");
7080
+ async function buildWorker(config) {
7081
+ console.log(`\x1B[35m\u2699\uFE0F Copying files...
7082
+ \x1B[0m`);
7083
+ await cp(
7084
+ path12.join(config.paths.dotNext, "static"),
7085
+ path12.join(config.paths.builderOutput, "assets", "_next", "static"),
7086
+ {
7087
+ recursive: true
7088
+ }
7089
+ );
7090
+ const publicDir = path12.join(config.paths.nextApp, "public");
7091
+ if (existsSync3(publicDir)) {
7092
+ await cp(publicDir, path12.join(config.paths.builderOutput, "assets"), {
7093
+ recursive: true
7094
+ });
7095
+ }
7096
+ copyPackageCliFiles(packageDistDir, config);
7097
+ const templateDir = path12.join(config.paths.internalPackage, "cli", "templates");
7098
+ const workerEntrypoint = path12.join(templateDir, "worker.ts");
7099
+ const workerOutputFile = path12.join(config.paths.builderOutput, "index.mjs");
7100
+ const nextConfigStr = readFileSync4(path12.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
6851
7101
  /const nextConfig = ({.+?})\n/
6852
7102
  )?.[1] ?? {};
6853
7103
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
6854
7104
  \x1B[0m`);
6855
- patchWranglerDeps(nextjsAppPaths);
6856
- updateWebpackChunksFile(nextjsAppPaths);
7105
+ patchWranglerDeps(config);
7106
+ updateWebpackChunksFile(config);
6857
7107
  await build({
6858
7108
  entryPoints: [workerEntrypoint],
6859
7109
  bundle: true,
@@ -6866,15 +7116,15 @@ async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
6866
7116
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
6867
7117
  // eval("require")("bufferutil");
6868
7118
  // eval("require")("utf-8-validate");
6869
- "next/dist/compiled/ws": `${templateDir}/shims/empty.ts`,
7119
+ "next/dist/compiled/ws": path12.join(templateDir, "shims", "empty.ts"),
6870
7120
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
6871
7121
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
6872
7122
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
6873
7123
  // QUESTION: Why did I encountered this but mhart didn't?
6874
- "next/dist/compiled/edge-runtime": `${templateDir}/shims/empty.ts`,
7124
+ "next/dist/compiled/edge-runtime": path12.join(templateDir, "shims", "empty.ts"),
6875
7125
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
6876
7126
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
6877
- "@next/env": `${templateDir}/shims/env.ts`
7127
+ "@next/env": path12.join(templateDir, "shims", "env.ts")
6878
7128
  },
6879
7129
  define: {
6880
7130
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -6908,22 +7158,21 @@ async function buildWorker(outputDir2, nextjsAppPaths, templateSrcDir) {
6908
7158
  // Do not crash on cache not supported
6909
7159
  // https://github.com/cloudflare/workerd/pull/2434
6910
7160
  // compatibility flag "cache_option_enabled" -> does not support "force-cache"
6911
- let isPatchedAlready = globalThis.fetch.__nextPatched;
6912
7161
  const curFetch = globalThis.fetch;
6913
7162
  globalThis.fetch = (input, init) => {
6914
- console.log("globalThis.fetch", input);
6915
- if (init) delete init.cache;
7163
+ if (init) {
7164
+ delete init.cache;
7165
+ }
6916
7166
  return curFetch(input, init);
6917
7167
  };
6918
7168
  import { Readable } from 'node:stream';
6919
- globalThis.fetch.__nextPatched = isPatchedAlready;
6920
7169
  fetch = globalThis.fetch;
6921
7170
  const CustomRequest = class extends globalThis.Request {
6922
7171
  constructor(input, init) {
6923
- console.log("CustomRequest", input);
6924
7172
  if (init) {
6925
7173
  delete init.cache;
6926
7174
  if (init.body?.__node_stream__ === true) {
7175
+ // https://github.com/cloudflare/workerd/issues/2746
6927
7176
  init.body = Readable.toWeb(init.body);
6928
7177
  }
6929
7178
  }
@@ -6932,152 +7181,113 @@ const CustomRequest = class extends globalThis.Request {
6932
7181
  };
6933
7182
  globalThis.Request = CustomRequest;
6934
7183
  Request = globalThis.Request;
6935
- `
7184
+ `
6936
7185
  }
6937
7186
  });
6938
- await updateWorkerBundledCode(workerOutputFile, nextjsAppPaths);
6939
- console.log(`\x1B[35m\u2699\uFE0F Copying asset files...
6940
- \x1B[0m`);
6941
- await cp(`${nextjsAppPaths.dotNextDir}/static`, `${outputDir2}/assets/_next/static`, {
6942
- recursive: true
6943
- });
7187
+ await updateWorkerBundledCode(workerOutputFile, config);
6944
7188
  console.log(`\x1B[35mWorker saved in \`${workerOutputFile}\` \u{1F680}
6945
7189
  \x1B[0m`);
6946
7190
  }
6947
- async function updateWorkerBundledCode(workerOutputFile, nextjsAppPaths) {
7191
+ async function updateWorkerBundledCode(workerOutputFile, config) {
6948
7192
  const originalCode = await readFile(workerOutputFile, "utf8");
6949
7193
  let patchedCode = originalCode;
6950
7194
  patchedCode = patchRequire(patchedCode);
6951
- patchedCode = patchReadFile(patchedCode, nextjsAppPaths);
6952
- patchedCode = inlineNextRequire(patchedCode, nextjsAppPaths);
6953
- patchedCode = patchFindDir(patchedCode, nextjsAppPaths);
6954
- patchedCode = inlineEvalManifest(patchedCode, nextjsAppPaths);
7195
+ patchedCode = patchReadFile(patchedCode, config);
7196
+ patchedCode = inlineNextRequire(patchedCode, config);
7197
+ patchedCode = patchFindDir(patchedCode, config);
7198
+ patchedCode = inlineEvalManifest(patchedCode, config);
7199
+ patchedCode = patchCache(patchedCode, config);
6955
7200
  await writeFile(workerOutputFile, patchedCode);
6956
7201
  }
6957
- async function updateWebpackChunksFile(nextjsAppPaths) {
6958
- console.log("# updateWebpackChunksFile");
6959
- const webpackRuntimeFile = `${nextjsAppPaths.standaloneAppServerDir}/webpack-runtime.js`;
6960
- console.log({ webpackRuntimeFile });
6961
- const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6962
- const chunks = readdirSync2(`${nextjsAppPaths.standaloneAppServerDir}/chunks`).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6963
- console.log(` - chunk ${chunk}`);
6964
- return chunk.replace(/\.js$/, "");
6965
- });
6966
- const updatedFileContent = fileContent.replace(
6967
- "__webpack_require__.f.require = (chunkId, promises) => {",
6968
- `__webpack_require__.f.require = (chunkId, promises) => {
6969
- if (installedChunks[chunkId]) return;
6970
- ${chunks.map(
6971
- (chunk) => `
6972
- if (chunkId === ${chunk}) {
6973
- installChunk(require("./chunks/${chunk}.js"));
6974
- return;
6975
- }
6976
- `
6977
- ).join("\n")}
6978
- `
6979
- );
6980
- writeFileSync2(webpackRuntimeFile, updatedFileContent);
6981
- }
6982
7202
  function createFixRequiresESBuildPlugin(templateDir) {
6983
7203
  return {
6984
7204
  name: "replaceRelative",
6985
7205
  setup(build3) {
6986
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
6987
- path: `${templateDir}/shims/empty.ts`
7206
+ build3.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7207
+ path: path12.join(templateDir, "shims", "empty.ts")
6988
7208
  }));
6989
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
6990
- path: `${templateDir}/shims/node-fs.ts`
7209
+ build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7210
+ path: path12.join(templateDir, "shims", "empty.ts")
6991
7211
  }));
6992
7212
  }
6993
7213
  };
6994
7214
  }
6995
7215
 
6996
- // src/nextjs-paths.ts
6997
- import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
6998
- import path4, { relative } from "node:path";
6999
- function getNextjsAppPaths(nextAppDir2) {
7000
- const dotNextDir = getDotNextDirPath(nextAppDir2);
7001
- const appPath = getNextjsApplicationPath(dotNextDir).replace(/\/$/, "");
7002
- const standaloneAppDir = path4.join(dotNextDir, "standalone", appPath);
7216
+ // src/cli/build/index.ts
7217
+ import { cpSync as cpSync2 } from "node:fs";
7218
+ import path13 from "node:path";
7219
+ import { rm } from "node:fs/promises";
7220
+ async function build2(appDir, opts) {
7221
+ if (!opts.skipBuild) {
7222
+ await buildNextjsApp(appDir);
7223
+ }
7224
+ if (!containsDotNextDir(appDir)) {
7225
+ throw new Error(`.next folder not found in ${appDir}`);
7226
+ }
7227
+ const outputDir2 = path13.resolve(opts.outputDir ?? appDir, ".worker-next");
7228
+ await cleanDirectory(outputDir2);
7229
+ cpSync2(path13.join(appDir, ".next"), path13.join(outputDir2, ".next"), { recursive: true });
7230
+ const config = getConfig(appDir, outputDir2);
7231
+ await buildWorker(config);
7232
+ }
7233
+ async function cleanDirectory(path14) {
7234
+ return await rm(path14, { recursive: true, force: true });
7235
+ }
7236
+
7237
+ // src/cli/index.ts
7238
+ import { existsSync as existsSync4 } from "node:fs";
7239
+
7240
+ // src/cli/args.ts
7241
+ import { mkdirSync, statSync as statSync2 } from "node:fs";
7242
+ import { parseArgs } from "node:util";
7243
+ import { resolve } from "node:path";
7244
+ function getArgs() {
7245
+ const {
7246
+ values: { skipBuild: skipBuild2, output }
7247
+ } = parseArgs({
7248
+ options: {
7249
+ skipBuild: {
7250
+ type: "boolean",
7251
+ short: "s",
7252
+ default: false
7253
+ },
7254
+ output: {
7255
+ type: "string",
7256
+ short: "o"
7257
+ }
7258
+ },
7259
+ allowPositionals: false
7260
+ });
7261
+ const outputDir2 = output ? resolve(output) : void 0;
7262
+ if (outputDir2) {
7263
+ assertDirArg(outputDir2, "output", true);
7264
+ }
7003
7265
  return {
7004
- appDir: nextAppDir2,
7005
- dotNextDir,
7006
- standaloneAppDir,
7007
- standaloneAppDotNextDir: path4.join(standaloneAppDir, ".next"),
7008
- standaloneAppServerDir: path4.join(standaloneAppDir, ".next", "server")
7266
+ outputDir: outputDir2,
7267
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7009
7268
  };
7010
7269
  }
7011
- function getDotNextDirPath(nextAppDir2) {
7012
- const dotNextDirPath = `${nextAppDir2}/.next`;
7270
+ function assertDirArg(path14, argName, make) {
7271
+ let dirStats;
7013
7272
  try {
7014
- const dirStats = statSync2(dotNextDirPath);
7015
- if (!dirStats.isDirectory()) throw new Error();
7273
+ dirStats = statSync2(path14);
7016
7274
  } catch {
7017
- throw new Error(`Error: \`.next\` directory not found!`);
7018
- }
7019
- return dotNextDirPath;
7020
- }
7021
- function getNextjsApplicationPath(dotNextDir) {
7022
- const serverPath = findServerParentPath(dotNextDir);
7023
- if (!serverPath) {
7024
- throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7025
- }
7026
- return relative(`${dotNextDir}/standalone`, serverPath);
7027
- function findServerParentPath(path6) {
7028
- try {
7029
- if (statSync2(`${path6}/.next/server`).isDirectory()) {
7030
- return path6;
7031
- }
7032
- } catch {
7033
- }
7034
- const files = readdirSync3(path6);
7035
- for (const file of files) {
7036
- if (statSync2(`${path6}/${file}`).isDirectory()) {
7037
- const dirServerPath = findServerParentPath(`${path6}/${file}`);
7038
- if (dirServerPath) {
7039
- return dirServerPath;
7040
- }
7041
- }
7275
+ if (!make) {
7276
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7042
7277
  }
7278
+ mkdirSync(path14);
7279
+ return;
7043
7280
  }
7044
- }
7045
-
7046
- // src/build/build.ts
7047
- import path5 from "node:path";
7048
- import { fileURLToPath as fileURLToPath3 } from "node:url";
7049
- import { cpSync as cpSync2, rmSync } from "node:fs";
7050
- var SAVE_DIR = ".save.next";
7051
- async function build2(inputNextAppDir, opts) {
7052
- if (!opts.skipBuild) {
7053
- buildNextjsApp(inputNextAppDir);
7054
- rmSync(`${inputNextAppDir}/${SAVE_DIR}`, {
7055
- recursive: true,
7056
- force: true
7057
- });
7058
- cpSync2(`${inputNextAppDir}/.next`, `${inputNextAppDir}/${SAVE_DIR}`, {
7059
- recursive: true
7060
- });
7061
- } else {
7062
- rmSync(`${inputNextAppDir}/.next`, { recursive: true, force: true });
7063
- cpSync2(`${inputNextAppDir}/${SAVE_DIR}`, `${inputNextAppDir}/.next`, {
7064
- recursive: true
7065
- });
7281
+ if (!dirStats.isDirectory()) {
7282
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7066
7283
  }
7067
- const outputDir2 = `${opts.outputDir ?? inputNextAppDir}/.worker-next`;
7068
- await cleanDirectory(outputDir2);
7069
- const nextjsAppPaths = getNextjsAppPaths(inputNextAppDir);
7070
- const templateDir = path5.join(path5.dirname(fileURLToPath3(import.meta.url)), "templates");
7071
- await buildWorker(outputDir2, nextjsAppPaths, templateDir);
7072
- }
7073
- async function cleanDirectory(path6) {
7074
- return await rm(path6, { recursive: true, force: true });
7075
7284
  }
7076
7285
 
7077
- // src/index.ts
7286
+ // src/cli/index.ts
7287
+ import { resolve as resolve2 } from "node:path";
7078
7288
  var nextAppDir = resolve2(".");
7079
7289
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7080
- if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync3(`./next.config.${ext2}`))) {
7290
+ if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {
7081
7291
  throw new Error("Error: Not in a Next.js app project");
7082
7292
  }
7083
7293
  var { skipBuild, outputDir } = getArgs();