rom "./defineProperty.js";
function ownKeys(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function (r) {
      return Object.getOwnPropertyDescriptor(e, r).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread2(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
      definePro

criptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
      Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
    });
  }
  return e;
}
export { _objectSpread2 as default };

perty(e, r, t[r]);
    }) : Object.getOwnPropertyDes


unctionName = require("./setFunctionName.js");
var toPropertyKey = require("./toPropertyKey.js");
function applyDecs2311(e, t, n, r, o, i) {
  var a,
    c,
    u,
    s,
    f,
    l,
    p,
    d = Symbol.metadata || Symbol["for"]("Symbol.metadata"),
    m = Object.defineProperty,
    h = Object.create,
    y = [h(null), h(null)],
    v = t.length;
  function g(t, n, r) {
    return function (o, i) {
      n && (i = o, o = e);
      for (var a = 0; a < t.length; a++) i = t[a].apply(o, r ? [i] : []);

ction applyDec(e, t, n, r, o, i, u, s, f, l, p) {
    function d(e) {
      if (!p(e)) throw new TypeError("Attempted to access private element on non-instance");
    }
    var h = [].concat(t[0]),
      v = t[3],
      w = !u,
      D = 1 === o,
      S =

 return r ? i : o;
    };
  }
  function b(e, t, n, r) {
    if ("function" != typeof e && (r || void 0 !== e)) throw new TypeError(t + " must " + (n || "be") + " a function" + (r ? "" : " or undefined"));
    return e;
  }
  fun


tedIterableToArray = require("./unsupportedIterableToArray.js");
function _createForOfIteratorHelper(r, e) {
  var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (!t) {
    if (Array.isArray(r) || (t = unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
      t && (r = t);
      var _n = 0,
        F = function F() {};
      return {
        s: F,
        n: function n() {
          return _n >= r.length ? {
            done: !0
          } : {

 order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var o,
    a = !0,
    u = !1;
  return {
    s: function s() {
      t = t.call(r);
    },
    n: function n() {
      var r = t.next();
      return a = r.done, r;

     done: !1,
            value: r[_n++]
          };
        },
        e: function e(r) {
          throw r;
        },
        f: F
      };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn


nsupportedIterableToArray = require("./unsupportedIterableToArray.js");
function _createForOfIteratorHelperLoose(r, e) {
  var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (t) return (t = t.call(r)).next.bind(t);
  if (Array.isArray(r) || (t = unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
    t && (r = t);
    var o = 0;
    return function () {
      return o >= r.length ? {
        done: !0
      } : {
        done: !1,
        value: r[o++]

ttempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports

      };
    };
  }
  throw new TypeError("Invalid a


f SuppressedError ? dispose_SuppressedError = SuppressedError : (dispose_SuppressedError = function dispose_SuppressedError(r, e) {
    this.suppressed = e, this.error = r, this.stack = Error().stack;
  }, dispose_SuppressedError.prototype = Object.create(Error.prototype, {
    constructor: {
      value: dispose_SuppressedError,
      writable: !0,
      configurable: !0
    }
  })), new dispose_SuppressedError(r, e);
}
function _dispose(r, e, s) {
  function next() {
    for (; r.length > 0;) try {

 (o.a) return Promise.resolve(p).then(next, err);
    } catch (r) {
      return err(r);
    }
    if (s) throw e;
  }
  function err(r) {
    return e = s ? new dispose_SuppressedError(e, r) : r, s = !0, next();
  }
  return next();
}
module.exports = _di

var o = r.pop(),
        p = o.d.call(o.v);
      if


ar _typeof = require("./typeof.js")["default"];
function _getRequireWildcardCache(e) {
  if ("function" != typeof WeakMap) return null;
  var r = new WeakMap(),
    t = new WeakMap();
  return (_getRequireWildcardCache = function _getRequireWildcardCache(e) {
    return e ? t : r;
  })(e);
}
function _interopRequireWildcard(e, r) {
  if (!r && e && e.__esModule) return e;
  if (null === e || "object" != _typeof(e) && "function" != typeof e) return {
    "default": e
  };
  var t = _getRequireWildcardCache(r

 i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
    i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u];
  }
  return n["default"] = e, t && t.set(e, n), n;
}
module.exports = _interopRequireWildcard, module.exports.__esModule = tru

);
  if (t && t.has(e)) return t.get(e);
  var n = {
      __proto__: null
    },
    a = Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
    var


ELEMENT_TYPE;
function _createRawReactElement(e, r, E, l) {
  REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103);
  var o = e && e.defaultProps,
    n = arguments.length - 3;
  if (r || 0 === n || (r = {
    children: void 0
  }), 1 === n) r.children = l;else if (n > 1) {
    for (var t = Array(n), f = 0; f < n; f++) t[f] = arguments[f + 3];
    r.children = t;
  }
  if (r && o) for (var i in o) void 0 === r[i] && (r[i] = o[i]

 = o || {});
  return {
    $$typeof: REACT_ELEMENT_TYPE,
    type: e,
    key: void 0 === E ? null : "" + E,
    ref: null,
    props: r,
    _owner: null
  };
}
module.exports = _createRawReactElement, module.exports.__esModule = true, module.exports["de


default"] = module.exports;
  var t,
    e = {},
    r = Object.prototype,
    n = r.hasOwnProperty,
    o = Object.defineProperty || function (t, e, r) {
      t[e] = r.value;
    },
    i = "function" == typeof Symbol ? Symbol : {},
    a = i.iterator || "@@iterator",
    c = i.asyncIterator || "@@asyncIterator",
    u = i.toStringTag || "@@toStringTag";
  function define(t, e, r) {
    return Object.defineProperty(t, e, {
      value: r,
      enumerable: !0,
      configurable: !0,
      writable: !0

,
      a = Object.create(i.prototype),
      c = new Context(n || []);
    return o(a, "_invoke", {
      value: makeInvokeMethod(t, r, c)
    }), a;
  }
  function tryCatch(t, e, r) {
    try {
      return {
        type: "normal",
        arg: t.call(e

  }), t[e];
  }
  try {
    define({}, "");
  } catch (t) {
    define = function define(t, e, r) {
      return t[e] = r;
    };
  }
  function wrap(t, e, r, n) {
    var i = e && e.prototype instanceof Generator ? e : Generator


re("./OverloadYield.js");
function _wrapAsyncGenerator(e) {
  return function () {
    return new AsyncGenerator(e.apply(this, arguments));
  };
}
function AsyncGenerator(e) {
  var r, t;
  function resume(r, t) {
    try {
      var n = e[r](t),
        o = n.value,
        u = o instanceof OverloadYield;
      Promise.resolve(u ? o.v : o).then(function (t) {
        if (u) {
          var i = "return" === r ? "return" : "next";
          if (!o.k || t.done) return resume(i, t);
          t = e[i](t).value

e "return":
        r.resolve({
          value: n,
          done: !0
        });
        break;
      case "throw":
        r.reject(n);
        break;
      default:
        r.resolve({
          value: n,
          done: !1
        });
    }
    (r = r

;
        }
        settle(n.done ? "return" : "normal", t);
      }, function (e) {
        resume("throw", e);
      });
    } catch (e) {
      settle("throw", e);
    }
  }
  function settle(e, n) {
    switch (e) {
      cas


var r = "function" == typeof SuppressedError ? SuppressedError : function (r, e) {
      var n = Error();
      return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
    },
    e = {},
    n = [];
  function using(r, e) {
    if (null != e) {
      if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
      if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
      if (void 0 === o && (o = e[Symb

(r) {
          return Promise.reject(r);
        }
      }), n.push({
        v: e,
        d: o,
        a: r
      });
    } else r && n.push({
      d: e,
      a: r
    });
    return e;
  }
  return {
    e: e,
    u: using.bind(null, !1),
    a: usi

ol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
      if ("function" != typeof o) throw new TypeError("Object is not disposable.");
      t && (o = function o() {
        try {
          t.call(e);
        } catch


typeof.js")["default"];
var setPrototypeOf = require("./setPrototypeOf.js");
var inherits = require("./inherits.js");
function _wrapRegExp() {
  module.exports = _wrapRegExp = function _wrapRegExp(e, r) {
    return new BabelRegExp(e, void 0, r);
  }, module.exports.__esModule = true, module.exports["default"] = module.exports;
  var e = RegExp.prototype,
    r = new WeakMap();
  function BabelRegExp(e, t, p) {
    var o = RegExp(e, t);
    return r.set(o, p || r.get(e)), setPrototypeOf(o, BabelRegExp.proto

&& i + 1 < o.length;) i++;
        r[t] = e[o[i]];
      }
      return r;
    }, Object.create(null));
  }
  return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (r) {
    var t = e.exec.call(this, r);
    if (t) {
      t.groups =

type);
  }
  function buildGroups(e, t) {
    var p = r.get(t);
    return Object.keys(p).reduce(function (r, t) {
      var o = p[t];
      if ("number" == typeof o) r[t] = e[o];else {
        for (var i = 0; void 0 === e[o[i]]


hod(e, t) {
    return function (r) {
      !function (e, t) {
        if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
      }(t), assertCallable(r, "An initializer"), e.push(r);
    };
  }
  function memberDec(e, t, r, n, a, i, o, s) {
    var c;
    switch (a) {
      case 1:
        c = "accessor";
        break;
      case 2:
        c = "method";
        break;
      case 3:
        c = "getter";
        break;
      case 4:
        c = "setter";
        break;

== a && (f.addInitializer = createAddInitializerMethod(n, p)), 0 === a ? o ? (l = r.get, u = r.set) : (l = function l() {
      return this[t];
    }, u = function u(e) {
      this[t] = e;
    }) : 2 === a ? l = function l() {
      return r.value;
    }

     default:
        c = "field";
    }
    var l,
      u,
      f = {
        kind: c,
        name: o ? "#" + t : toPropertyKey(t),
        "static": i,
        "private": o
      },
      p = {
        v: !1
      };
    0 !


yncIterator(r) {
  var n,
    t,
    o,
    e = 2;
  for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
    if (t && null != (n = r[t])) return n.call(r);
    if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
    t = "@@asyncIterator", o = "@@iterator";
  }
  throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(r) {
  function AsyncFromSyncIteratorContinuation(r) {
    if (Object(r) !== r) return Promise.reje

ion AsyncFromSyncIterator(r) {
    this.s = r, this.n = r.next;
  }, AsyncFromSyncIterator.prototype = {
    s: null,
    n: null,
    next: function next() {
      return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
    },
    "retu

ct(new TypeError(r + " is not an object."));
    var n = r.done;
    return Promise.resolve(r.value).then(function (r) {
      return {
        value: r,
        done: n
      };
    });
  }
  return AsyncFromSyncIterator = funct


) {
  if ("function" != typeof WeakMap) return null;
  var r = new WeakMap(),
    t = new WeakMap();
  return (_getRequireWildcardCache = function _getRequireWildcardCache(e) {
    return e ? t : r;
  })(e);
}
function _interopRequireWildcard(e, r) {
  if (!r && e && e.__esModule) return e;
  if (null === e || "object" != _typeof(e) && "function" != typeof e) return {
    "default": e
  };
  var t = _getRequireWildcardCache(r);
  if (t && t.has(e)) return t.get(e);
  var n = {
      __proto__: null
    },

yDescriptor;
  for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
    var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
    i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u];
  }
  return n["default"] = e, t

a = Object.defineProperty && Object.getOwnPropert


unctionName = require("./setFunctionName.js");
var toPropertyKey = require("./toPropertyKey.js");
function applyDecs2305(e, t, r, n, o, a) {
  function i(e, t, r) {
    return function (n, o) {
      return r && r(n), e[t].call(n, o);
    };
  }
  function c(e, t) {
    for (var r = 0; r < e.length; r++) e[r].call(t);
    return t;
  }
  function s(e, t, r, n) {
    if ("function" != typeof e && (n || void 0 !== e)) throw new TypeError(t + " must " + (r || "be") + " a function" + (n ? "" : " or undefined"))

    g = t[3],
      b = !u;
    if (!b) {
      r || Array.isArray(v) || (v = [v]);
      var w = {},
        S = [],
        A = 3 === o ? "get" : 4 === o || d ? "set" : "value";
      f ? (p || d ? w = {
        get: setFunctionName(function () {

;
    return e;
  }
  function applyDec(e, t, r, n, o, a, c, u, l, f, p, d, h) {
    function m(e) {
      if (!h(e)) throw new TypeError("Attempted to access private element on non-instance");
    }
    var y,
      v = t[0],


lassElements(s.F, a.elements), o.runClassFinishers(s.F, a.finishers);
}
function _getDecoratorsApi() {
  _getDecoratorsApi = function _getDecoratorsApi() {
    return e;
  };
  var e = {
    elementsDefinitionOrder: [["method"], ["field"]],
    initializeInstanceElements: function initializeInstanceElements(e, r) {
      ["method", "field"].forEach(function (t) {
        r.forEach(function (r) {
          r.kind === t && "own" === r.placement && this.defineClassElement(e, r);
        }, this);
      }, this

 if (r.kind === i && ("static" === o || "prototype" === o)) {
            var n = "static" === o ? e : t;
            this.defineClassElement(n, r);
          }
        }, this);
      }, this);
    },
    defineClassElement: function defineClassElement(e,

);
    },
    initializeClassElements: function initializeClassElements(e, r) {
      var t = e.prototype;
      ["method", "field"].forEach(function (i) {
        r.forEach(function (r) {
          var o = r.placement;


 _importDeferProxy(e) {
  var t = null,
    constValue = function constValue(e) {
      return function () {
        return e;
      };
    },
    proxy = function proxy(r) {
      return function (n, o, f) {
        return null === t && (t = e()), r(t, o, f);
      };
    };
  return new Proxy({}, {
    defineProperty: constValue(!1),
    deleteProperty: constValue(!1),
    get: proxy(Reflect.get),
    getOwnPropertyDescriptor: proxy(Reflect.getOwnPropertyDescriptor),
    getPrototypeOf: constValue(null),

lect.has),
    ownKeys: proxy(Reflect.ownKeys),
    preventExtensions: constValue(!0),
    set: constValue(!1),
    setPrototypeOf: constValue(!1)
  });
}
module.exports = _importDeferProxy, module.exports.__esModule = true, module.exports["default"] = mod

    isExtensible: constValue(!1),
    has: proxy(Ref


 = require("./superPropBase.js");
var defineProperty = require("./defineProperty.js");
function set(e, r, t, o) {
  return set = "undefined" != typeof Reflect && Reflect.set ? Reflect.set : function (e, r, t, o) {
    var f,
      i = superPropBase(e, r);
    if (i) {
      if ((f = Object.getOwnPropertyDescriptor(i, r)).set) return f.set.call(o, t), !0;
      if (!f.writable) return !1;
    }
    if (f = Object.getOwnPropertyDescriptor(o, r)) {
      if (!f.writable) return !1;
      f.value = t, Object.de

r, t);
    return !0;
  }, set(e, r, t, o);
}
function _set(e, r, t, o, f) {
  if (!set(e, r, t, o || e) && f) throw new TypeError("failed to set property");
  return t;
}
module.exports = _set, module.exports.__esModule = true, module.exports["default"] =

fineProperty(o, r, f);
    } else defineProperty(o,


{
    getMetadata: function getMetadata(o) {
      old_assertNotFinished(r, "getMetadata"), old_assertMetadataKey(o);
      var i = e[o];
      if (void 0 !== i) if (1 === t) {
        var n = i["public"];
        if (void 0 !== n) return n[a];
      } else if (2 === t) {
        var l = i["private"];
        if (void 0 !== l) return l.get(a);
      } else if (Object.hasOwnProperty.call(i, "constructor")) return i.constructor;
    },
    setMetadata: function setMetadata(o, i) {
      old_assertNotFinished(

t) {
        var s = n.priv;
        void 0 === s && (s = n["private"] = new Map()), s.set(a, i);
      } else n.constructor = i;
    }
  };
}
function old_convertMetadataMapToFinal(e, t) {
  var a = e[Symbol.metadata || Symbol["for"]("Symbol.metadata")],

r, "setMetadata"), old_assertMetadataKey(o);
      var n = e[o];
      if (void 0 === n && (n = e[o] = {}), 1 === t) {
        var l = n["public"];
        void 0 === l && (l = n["public"] = {}), l[a] = i;
      } else if (2 ===


d to call addInitializer after decoration was finished");
      }(t), assertCallable(r, "An initializer"), e.push(r);
    };
  }
  function memberDec(e, t, r, a, n, i, s, o) {
    var c;
    switch (n) {
      case 1:
        c = "accessor";
        break;
      case 2:
        c = "method";
        break;
      case 3:
        c = "getter";
        break;
      case 4:
        c = "setter";
        break;
      default:
        c = "field";
    }
    var l,
      u,
      f = {
        kind: c,
        nam

l() {
      return this[t];
    }, u = function u(e) {
      this[t] = e;
    }) : 2 === n ? l = function l() {
      return r.value;
    } : (1 !== n && 3 !== n || (l = function l() {
      return r.get.call(this);
    }), 1 !== n && 4 !== n || (u = funct

e: s ? "#" + t : t,
        "static": i,
        "private": s
      },
      p = {
        v: !1
      };
    0 !== n && (f.addInitializer = createAddInitializerMethod(a, p)), 0 === n ? s ? (l = r.get, u = r.set) : (l = function


Object.defineProperty || function (t, e, r) {
      t[e] = r.value;
    },
    i = "function" == typeof Symbol ? Symbol : {},
    a = i.iterator || "@@iterator",
    c = i.asyncIterator || "@@asyncIterator",
    u = i.toStringTag || "@@toStringTag";
  function define(t, e, r) {
    return Object.defineProperty(t, e, {
      value: r,
      enumerable: !0,
      configurable: !0,
      writable: !0
    }), t[e];
  }
  try {
    define({}, "");
  } catch (t) {
    define = function define(t, e, r) {
      ret

lue: makeInvokeMethod(t, r, c)
    }), a;
  }
  function tryCatch(t, e, r) {
    try {
      return {
        type: "normal",
        arg: t.call(e, r)
      };
    } catch (t) {
      return {
        type: "throw",
        arg: t
      };
    }
  }
  e.w

urn t[e] = r;
    };
  }
  function wrap(t, e, r, n) {
    var i = e && e.prototype instanceof Generator ? e : Generator,
      a = Object.create(i.prototype),
      c = new Context(n || []);
    return o(a, "_invoke", {
      va


loadYield = require("./OverloadYield.js");
function _asyncGeneratorDelegate(t) {
  var e = {},
    n = !1;
  function pump(e, r) {
    return n = !0, r = new Promise(function (n) {
      n(t[e](r));
    }), {
      done: !1,
      value: new OverloadYield(r, 1)
    };
  }
  return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () {
    return this;
  }, e.next = function (t) {
    return n ? (n = !1, t) : pump("next", t);
  }, "function" == typeof t["throw"] && (e["throw"] = f

 pump("throw", t);
  }), "function" == typeof t["return"] && (e["return"] = function (t) {
    return n ? (n = !1, t) : pump("return", t);
  }), e;
}
module.exports = _asyncGeneratorDelegate, module.exports.__esModule = true, module.exports["default"] = mo

unction (t) {
    if (n) throw n = !1, t;
    return


k,
}
/**
 * Parse the bundler arguments and potentially sets the `TURBOPACK` environment variable.
 *
 * NOTE: rspack is configured via next config which is chaotic so it is possible for this to be overridden later.
 *
 * @param options The options to parse.
 * @returns The bundler that was configured
 */
export function parseBundlerArgs(options: {
  turbo?: boolean
  turbopack?: boolean
  webpack?: boolean
}): Bundler {
  const bundlerFlags = new Map<Bundler, string[]>()
  const setBundlerFlag = (bundler:

t one.
  if (options.turbopack) {
    setBundlerFlag(Bundler.Turbopack, '--turbopack')
  }
  if (options.turbo) {
    setBundlerFlag(Bundler.Turbopack, '--turbo')
  } else if (process.env.TURBOPACK) {
    // We don't really want to support this but it is t

Bundler, flag: string) => {
    bundlerFlags.set(bundler, (bundlerFlags.get(bundler) ?? []).concat(flag))
  }
  // What turbo flag was set? We allow multiple to be set, which is silly but not ambiguous, just pick the most relevan


e CoalescedInvoke<T> = {
  isOrigin: boolean
  value: T
}

export type UnwrapPromise<T> = T extends Promise<infer U> ? U : T

const globalInvokeCache = new Map<string, Promise<CoalescedInvoke<unknown>>>()

export function withCoalescedInvoke<F extends (...args: any) => any>(
  func: F
): (
  key: string,
  args: Parameters<F>
) => Promise<CoalescedInvoke<UnwrapPromise<ReturnType<F>>>> {
  return async function (key: string, args: Parameters<F>) {
    const entry = globalInvokeCache.get(key)
    if (entry) {

onst future = __wrapper()
      .then((res) => {
        globalInvokeCache.delete(key)
        return { isOrigin: true, value: res as UnwrapPromise<ReturnType<F>> }
      })
      .catch((err) => {
        globalInvokeCache.delete(key)
        return Promi

      return entry.then((res) => ({
        isOrigin: false,
        value: res.value as UnwrapPromise<ReturnType<F>>,
      }))
    }

    async function __wrapper() {
      return await func.apply(undefined, args)
    }

    c


-to-regexp'
import { BloomFilter } from '../shared/lib/bloom-filter'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import type { Redirect } from './load-custom-routes'
import { tryToParsePath } from './try-to-parse-path'
import {
  extractInterceptionRouteInformation,
  isInterceptionRouteAppPath,
} from '../shared/lib/router/utils/interception-routes'

export function createClientRouterFilter(
  paths: stri

 = new Set<string>()

  for (let path of paths) {
    if (isDynamicRoute(path)) {
      if (isInterceptionRouteAppPath(path)) {
        path = extractInterceptionRouteInformation(path).interceptedRoute
      }

      let subPath = ''
      const pathParts

ng[],
  redirects: Redirect[],
  allowedErrorRate?: number
): {
  staticFilter: ReturnType<BloomFilter['export']>
  dynamicFilter: ReturnType<BloomFilter['export']>
} {
  const staticPaths = new Set<string>()
  const dynamicPaths


* A `Promise.withResolvers` implementation that exposes the `resolve` and
 * `reject` functions on a `Promise`.
 *
 * @see https://tc39.es/proposal-promise-with-resolvers/
 */
export class DetachedPromise<T = any> {
  public readonly resolve: (value: T | PromiseLike<T>) => void
  public readonly reject: (reason: any) => void
  public readonly promise: Promise<T>

  constructor() {
    let resolve: (value: T | PromiseLike<T>) => void
    let reject: (reason: any) => void

    // Create the promise and assign

 to the object.
    this.promise = new Promise<T>((res, rej) => {
      resolve = res
      reject = rej
    })

    // We know that resolvers is defined because the Promise constructor runs
    // synchronously.
    this.resolve = resolve!
    this.reject


CODE_DELIMITER = '@'

/**
 * Augments the digest field of errors thrown in React Server Components (RSC) with an error code.
 * Since RSC errors can only be serialized through the digest field, this provides a way to include
 * an additional error code that can be extracted client-side via `extractNextErrorCode`.
 *
 * The error code is appended to the digest string with a semicolon separator, allowing it to be
 * parsed out later while preserving the original digest value.
 */
export const createDigestWith

RROR_CODE_DELIMITER}${thrownValue.__NEXT_ERROR_CODE}`
  }
  return originalDigest
}

export const extractNextErrorCode = (error: unknown): string | undefined => {
  if (
    typeof error === 'object' &&
    error !== null &&
    '__NEXT_ERROR_CODE' in erro

ErrorCode = (
  thrownValue: unknown,
  originalDigest: string
): string => {
  if (
    typeof thrownValue === 'object' &&
    thrownValue !== null &&
    '__NEXT_ERROR_CODE' in thrownValue
  ) {
    return `${originalDigest}${E


s'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { findConfig } from './find-config'

// Jest does not support `import('file://something')` (file: imports) yet.
describe('findConfig()', () => {
  const exampleConfig = {
    basePath: '/docs',
  }
  const configCode = {
    mjs: `
      const config = ${JSON.stringify(exampleConfig)}

      export default config;
    `,
    cjs: `
      const config = ${JSON.stringify(exampleConfig)}

      module.exports = config;
    `,
  }
  typ

 (const pkgConfigType of testPatterns.pkgConfigTypes) {
    for (const ext of testPatterns.exts) {
      it(`should load config properly from *.config.* file (type: "${pkgConfigType}", config: awsome.config.${ext})`, async () => {
        // Create fixture

e TestPatterns = {
    pkgConfigTypes: ('module' | 'commonjs')[]
    exts: ('js' | 'mjs' | 'cjs')[]
  }
  const testPatterns: TestPatterns = {
    pkgConfigTypes: ['module', 'commonjs'],
    exts: ['js', 'mjs', 'cjs'],
  }

  for


ort { readFile } from 'fs/promises'
import JSON5 from 'next/dist/compiled/json5'
import { pathToFileURL } from 'url'

type RecursivePartial<T> = {
  [P in keyof T]?: RecursivePartial<T[P]>
}

export function findConfigPath(
  dir: string,
  key: string
): Promise<string | undefined> {
  // If we didn't find the configuration in `package.json`, we should look for
  // known filenames.
  return findUp(
    [
      `.${key}rc.json`,
      `${key}.config.json`,
      `.${key}rc.js`,
      `${key}.config.js`,

on. We should maybe
// force all the types to be `unknown` as well.
export async function findConfig<T>(
  directory: string,
  key: string,
  _returnFile?: boolean
): Promise<RecursivePartial<T> | null> {
  // `package.json` configuration always wins. Let

    `${key}.config.mjs`,
      `${key}.config.cjs`,
    ],
    {
      cwd: dir,
    }
  )
}

// We'll allow configuration to be typed, but we force everything provided to
// become optional. We do not perform any schema validati


nction _iterableToArrayLimit(r, l) {
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (null != t) {
    var e,
      n,
      i,
      u,
      a = [],
      f = !0,
      o = !1;
    try {
      if (i = (t = t.call(r)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = !1;
      } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
    } catch (r) {
      o = !0, n = r;
    } finally {
      try {

null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.ex


.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function (r) {
      return Object.getOwnPropertyDescriptor(e, r).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread2(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
      defineProperty(e, r, t[r]);
    }) : Object.getOwnPropertyDescriptors ? Objec

rs(t)) : ownKeys(Object(t)).forEach(function (r) {
      Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
    });
  }
  return e;
}
module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exp


ements(s.F, a.elements), o.runClassFinishers(s.F, a.finishers);
}
function _getDecoratorsApi() {
  _getDecoratorsApi = function _getDecoratorsApi() {
    return e;
  };
  var e = {
    elementsDefinitionOrder: [["method"], ["field"]],
    initializeInstanceElements: function initializeInstanceElements(e, r) {
      ["method", "field"].forEach(function (t) {
        r.forEach(function (r) {
          r.kind === t && "own" === r.placement && this.defineClassElement(e, r);
        }, this);
      }, this);

.kind === i && ("static" === o || "prototype" === o)) {
            var n = "static" === o ? e : t;
            this.defineClassElement(n, r);
          }
        }, this);
      }, this);
    },
    defineClassElement: function defineClassElement(e, r) {

 },
    initializeClassElements: function initializeClassElements(e, r) {
      var t = e.prototype;
      ["method", "field"].forEach(function (i) {
        r.forEach(function (r) {
          var o = r.placement;
          if (r


rom 'next/dist/compiled/path-to-regexp'
import type {
  ManifestHeaderRoute,
  ManifestRedirectRoute,
  ManifestRewriteRoute,
} from '../build'
import {
  normalizeRouteRegex,
  type Header,
  type Redirect,
  type Rewrite,
  type RouteType,
} from './load-custom-routes'
import { getRedirectStatus, modifyRouteRegex } from './redirect-status'

export function buildCustomRoute(
  type: 'header',
  route: Header
): ManifestHeaderRoute
export function buildCustomRoute(
  type: 'rewrite',
  route: Rewrite
): Man

ite | Header,
  restrictedRedirectPaths?: string[]
): ManifestHeaderRoute | ManifestRewriteRoute | ManifestRedirectRoute {
  const compiled = pathToRegexp(route.source, [], {
    strict: true,
    sensitive: false,
    delimiter: '/', // default is `/#?`,

ifestRewriteRoute
export function buildCustomRoute(
  type: 'redirect',
  route: Redirect,
  restrictedRedirectPaths: string[]
): ManifestRedirectRoute
export function buildCustomRoute(
  type: RouteType,
  route: Redirect | Rewr


HEADER = 'application/json; charset=utf-8'
export const NEXT_QUERY_PARAM_PREFIX = 'nxtP'
export const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'

export const MATCHED_PATH_HEADER = 'x-matched-path'
export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'
export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
  'x-prerender-revalidate-if-generated'

export const RSC_SEGMENTS_DIR_SUFFIX = '.segments'
export const RSC_SEGMENT_SUFFIX = '.segment.rsc'
export const RSC_SUFFIX = '.rsc'
export const ACT

EXT_CACHE_TAGS_HEADER = 'x-next-cache-tags'
export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'
export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER =
  'x-next-revalidate-tag-token'

export const NEXT_RESUME_HEADER = 'next-resume'
e

ION_SUFFIX = '.action'
export const NEXT_DATA_SUFFIX = '.json'
export const NEXT_META_SUFFIX = '.meta'
export const NEXT_BODY_SUFFIX = '.body'

export const NEXT_NAV_DEPLOYMENT_ID_HEADER = 'x-nextjs-deployment-id'

export const N


 minimum number of operations required to convert string a to string b.
function minDistance(a: string, b: string, threshold: number): number {
  const m = a.length
  const n = b.length

  if (m < n) {
    return minDistance(b, a, threshold)
  }

  if (n === 0) {
    return m
  }

  let previousRow = Array.from({ length: n + 1 }, (_, i) => i)

  for (let i = 0; i < m; i++) {
    const s1 = a[i]
    let currentRow = [i + 1]
    for (let j = 0; j < n; j++) {
      const s2 = b[j]
      const insertions = prev

  }
  return previousRow[previousRow.length - 1]
}

export function detectTypo(input: string, options: string[], threshold = 2) {
  const potentialTypos = options
    .map((o) => ({
      option: o,
      distance: minDistance(o, input, threshold),
    }))

iousRow[j + 1] + 1
      const deletions = currentRow[j] + 1
      const substitutions = previousRow[j] + Number(s1 !== s2)
      currentRow.push(Math.min(insertions, deletions, substitutions))
    }
    previousRow = currentRow


tPrototypeOf = require("./getPrototypeOf.js");
var setPrototypeOf = require("./setPrototypeOf.js");
var isNativeFunction = require("./isNativeFunction.js");
var construct = require("./construct.js");
function _wrapNativeSuper(t) {
  var r = "function" == typeof Map ? new Map() : void 0;
  return module.exports = _wrapNativeSuper = function _wrapNativeSuper(t) {
    if (null === t || !isNativeFunction(t)) return t;
    if ("function" != typeof t) throw new TypeError("Super expression must either be null or a

ototype = Object.create(t.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: !1,
        writable: !0,
        configurable: !0
      }
    }), setPrototypeOf(Wrapper, t);
  }, module.exports.__esModule = true, module.exports["de

 function");
    if (void 0 !== r) {
      if (r.has(t)) return r.get(t);
      r.set(t, Wrapper);
    }
    function Wrapper() {
      return construct(t, arguments, getPrototypeOf(this).constructor);
    }
    return Wrapper.pr


om "./setFunctionName.js";
import toPropertyKey from "./toPropertyKey.js";
function applyDecs2305(e, t, r, n, o, a) {
  function i(e, t, r) {
    return function (n, o) {
      return r && r(n), e[t].call(n, o);
    };
  }
  function c(e, t) {
    for (var r = 0; r < e.length; r++) e[r].call(t);
    return t;
  }
  function s(e, t, r, n) {
    if ("function" != typeof e && (n || void 0 !== e)) throw new TypeError(t + " must " + (r || "be") + " a function" + (n ? "" : " or undefined"));
    return e;
  }
  f

 !u;
    if (!b) {
      r || Array.isArray(v) || (v = [v]);
      var w = {},
        S = [],
        A = 3 === o ? "get" : 4 === o || d ? "set" : "value";
      f ? (p || d ? w = {
        get: setFunctionName(function () {
          return g(this);

unction applyDec(e, t, r, n, o, a, c, u, l, f, p, d, h) {
    function m(e) {
      if (!h(e)) throw new TypeError("Attempted to access private element on non-instance");
    }
    var y,
      v = t[0],
      g = t[3],
      b =


om 'next/dist/compiled/tar'
const { WritableStream } =
  require('node:stream/web') as typeof import('node:stream/web')
import { getRegistry } from './helpers/get-registry'
import { getCacheDirectory } from './helpers/get-cache-directory'

const MAX_VERSIONS_TO_CACHE = 8

async function extractBinary(
  outputDirectory: string,
  pkgName: string,
  tarFileName: string
) {
  const cacheDirectory = getCacheDirectory(
    'next-swc',
    process.env['NEXT_SWC_PATH']
  )

  const extractFromTar = () =>
    x({

eDirectory}`)
    await fs.promises.mkdir(cacheDirectory, { recursive: true })
    const tempFile = path.join(
      cacheDirectory,
      `${tarFileName}.temp-${Date.now()}`
    )

    const registry = getRegistry()

    const downloadUrl = `${registry}${

      file: path.join(cacheDirectory, tarFileName),
      cwd: outputDirectory,
      strip: 1,
    })

  if (!fs.existsSync(path.join(cacheDirectory, tarFileName))) {
    Log.info(`Downloading swc package ${pkgName}... to ${cach


ort { DetachedPromise } from './detached-promise'

type CacheKeyFn<K, C extends string | number | null> = (
  key: K
) => PromiseLike<C> | C

type BatcherOptions<K, C extends string | number | null> = {
  cacheKeyFn?: CacheKeyFn<K, C>
  schedulerFn?: SchedulerFn<void>
}

type WorkFnContext<V, K> = {
  resolve: (value: V | PromiseLike<V>) => void
  key: K
}

type WorkFn<V, K> = (context: WorkFnContext<V, K>) => Promise<V>

/**
 * A wrapper for a function that will only allow one call to the function to
 * ex

* A function that will be called to schedule the wrapped function to be
     * executed. This defaults to a function that will execute the function
     * immediately.
     */
    private readonly schedulerFn: SchedulerFn<void> = (fn) => fn()
  ) {}

  /**

ecute at a time.
 */
export class Batcher<K, V, C extends string | number | null> {
  private readonly pending = new Map<C, Promise<V>>()

  protected constructor(
    private readonly cacheKeyFn?: CacheKeyFn<K, C>,
    /**


 {
  extractInfoFromServerReferenceId,
  type ServerReferenceInfo,
} from '../shared/lib/server-reference-info'

// Only contains the properties we're interested in.
export interface ServerReference {
  $$typeof: Symbol
  $$id: string
}

export type ServerFunction = ServerReference &
  ((...args: unknown[]) => Promise<unknown>)

export function isServerReference<T>(
  value: T & Partial<ServerReference>
): value is T & ServerFunction {
  return value.$$typeof === Symbol.for('react.server.reference')
}

expo

 return type === 'use-cache'
}

export function getUseCacheFunctionInfo<T>(
  value: T & Partial<ServerReference>
): ServerReferenceInfo | null {
  if (!isServerReference(value)) {
    return null
  }

  const info = extractInfoFromServerReferenceId(value.

rt function isUseCacheFunction<T>(
  value: T & Partial<ServerReference>
): value is T & ServerFunction {
  if (!isServerReference(value)) {
    return false
  }

  const { type } = extractInfoFromServerReferenceId(value.$$id)


from '../shared/lib/is-plain-object'

// We allow some additional attached properties for Next.js errors
export interface NextError extends Error {
  type?: string
  page?: string
  code?: string | number
  cancelled?: boolean
  digest?: string
}

/**
 * This is a safe stringify function that handles circular references.
 * We're using a simpler version here to avoid introducing
 * the dependency `safe-stable-stringify` into production bundle.
 *
 * This helper is used both in development and production.
 *

value !== null) {
      if (seen.has(value)) {
        return '[Circular]'
      }
      seen.add(value)
    }
    return value
  })
}

/**
 * Checks whether the given value is a NextError.
 * This can be used to print a more detailed error message with pr

/
function safeStringifyLite(obj: any) {
  const seen = new WeakSet()

  return JSON.stringify(obj, (_key, value) => {
    // If value is an object and already seen, replace with "[Circular]"
    if (typeof value === 'object' &&


at rejects certain
 * patterns commonly used in Next.js interception routes. This module provides
 * normalization functions to make Next.js route patterns compatible with the
 * updated library while preserving all functionality.
 */

/**
 * Internal separator used to normalize adjacent parameter patterns.
 * This unique marker is inserted between adjacent parameters and stripped out
 * during parameter extraction to avoid conflicts with real URL content.
 */
export const PARAM_SEPARATOR = '_NEXTSEP_'

/**

ion route markers followed immediately by parameters
  // Pattern: /(.):param, /(..):param, /(...):param, /(.)(.):param etc.
  // These patterns cause "Must have text between two parameters" errors
  if (/\/\(\.{1,3}\):[^/\s]+/.test(route)) {
    return tr

 * Detects if a route pattern needs normalization for path-to-regexp compatibility.
 */
export function hasAdjacentParameterIssues(route: string): boolean {
  if (typeof route !== 'string') return false

  // Check for intercept


seLike<T>
export type SchedulerFn<T = void> = (cb: ScheduledFn<T>) => void

/**
 * Schedules a function to be called on the next tick after the other promises
 * have been resolved.
 *
 * @param cb the function to schedule
 */
export const scheduleOnNextTick = (cb: ScheduledFn<void>) => {
  // We use Promise.resolve().then() here so that the operation is scheduled at
  // the end of the promise job queue, we then add it to the next process tick
  // to ensure it's evaluated afterwards.
  //
  // This was in

UNTIME === 'edge') {
      setTimeout(cb, 0)
    } else {
      process.nextTick(cb)
    }
  })
}

/**
 * Schedules a function to be called using `setImmediate` or `setTimeout` if
 * `setImmediate` is not available (like in the Edge runtime).
 *
 * @param

spired by the implementation of the DataLoader interface: https://github.com/graphql/dataloader/blob/d336bd15282664e0be4b4a657cb796f09bafbc6b/src/index.js#L213-L255
  //
  Promise.resolve().then(() => {
    if (process.env.NEXT_R


time,
} from '../server/config-shared'

function errorIfEnvConflicted(
  config: NextConfigComplete | NextConfigRuntime,
  key: string
) {
  const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
  const hasNextRuntimeKey = key === 'NEXT_RUNTIME'

  if (isPrivateKey || hasNextRuntimeKey) {
    throw new Error(
      `The key "${key}" under "env" in ${config.configFileName || 'config'} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
    )
  }
}

/**
 * Collects all environment variab

_')) {
      const value = process.env[key]
      if (value != null) {
        defineEnv.push([`process.env.${key}`, value])
      }
    }
  }
  defineEnv.sort((a, b) => a[0].localeCompare(b[0]))
  return Object.fromEntries(defineEnv)
}

/**
 * Collects th

les that are using the `NEXT_PUBLIC_` prefix.
 */
export function getNextPublicEnvironmentVariables() {
  const defineEnv: [string, string | undefined][] = []
  for (const key in process.env) {
    if (key.startsWith('NEXT_PUBLIC


-to-regexp'
import { parse, tokensToRegexp } from 'next/dist/compiled/path-to-regexp'
import isError from './is-error'
import { normalizeTokensForRegexp } from './route-pattern-normalizer'

interface ParseResult {
  error?: any
  parsedPath: string
  regexStr?: string
  route: string
  tokens?: Token[]
}

/**
 * If there is an error show our error link but still show original error or
 * a formatted one if we can
 */
function reportError({ route, parsedPath }: ParseResult, err: any) {
  let errMatches
  if

te-source\n` +
        `Reason: ${err.message}\n\n` +
        `  ${parsedPath}\n` +
        `  ${new Array(position).fill(' ').join('')}^\n`
    )
  } else {
    console.error(
      `\nError parsing ${route} https://nextjs.org/docs/messages/invalid-route-

(isError(err) && (errMatches = err.message.match(/at (\d{0,})/))) {
    const position = parseInt(errMatches[1], 10)
    console.error(
      `\nError parsing \`${route}\` ` +
        `https://nextjs.org/docs/messages/invalid-rou


 Left to be implemented (priority)
  // 'experimental.clientRouterFilter',
  // 'experimental.optimizePackageImports',
  // 'compiler.emotion',
  // 'compiler.reactRemoveProperties',
  // 'compiler.relay',
  // 'compiler.removeConsole',
  // 'compiler.styledComponents',
  'experimental.fetchCacheKeyPrefix',

  // Left to be implemented
  // 'excludeDefaultMomentLocales',
  // 'experimental.optimizeServerReact',
  'experimental.clientRouterFilterAllowedRate',
  // 'experimental.serverMinification',
  // 'exp

needed for Turbopack)
  'experimental.craCompat',
  'experimental.disablePostcssPresetEnv',
  'experimental.esmExternals',
  // This is used to force swc-loader to run regardless of finding Babel.
  'experimental.forceSwcTransforms',
  'experimental.fullyS

erimental.serverSourceMaps',

  'experimental.allowedRevalidateHeaderKeys',
  'experimental.extensionAlias',
  'experimental.fallbackNodePolyfills',

  'experimental.swcTraceProfiling',

  // Left to be implemented (Might not be


{ UrlWithParsedQuery } from 'url'
import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'

const DUMMY_ORIGIN = 'http://n'

export function isFullStringUrl(url: string) {
  return /https?:\/\//.test(url)
}

export function parseUrl(url: string): URL | undefined {
  let parsed: URL | undefined = undefined
  try {
    parsed = new URL(url, DUMMY_ORIGIN)
  } catch {}
  return parsed
}

export function parseReqUrl(url: string): UrlWithParsedQuery | undefined {
  const parsedUrl: URL | und

ry[key] = values.length > 1 ? values : values[0]
  }

  const legacyUrl: UrlWithParsedQuery = {
    query,
    hash: parsedUrl.hash,
    search: parsedUrl.search,
    path: parsedUrl.pathname,
    pathname: parsedUrl.pathname,
    href: `${parsedUrl.pathna

efined = parseUrl(url)

  if (!parsedUrl) {
    return
  }

  const query: Record<string, string | string[]> = {}

  for (const key of parsedUrl.searchParams.keys()) {
    const values = parsedUrl.searchParams.getAll(key)
    que


red } from './picocolors'

import path from 'path'
import { hasNecessaryDependencies } from './has-necessary-dependencies'
import type { NecessaryDependencies } from './has-necessary-dependencies'
import { fileExists, FileType } from './file-exists'
import * as Log from '../build/output/log'
import { getPkgManager } from './helpers/get-pkg-manager'

async function missingDependencyError(dir: string) {
  const packageManager = getPkgManager(dir)

  throw new Error(
    bold(
      red(
        "It looks like

(
          (packageManager === 'yarn'
            ? 'yarn add --dev'
            : packageManager === 'pnpm'
              ? 'pnpm install --save-dev'
              : 'npm install --save-dev') + ' @builder.io/partytown'
        )
      )}` +
      '\n\n'

 you're trying to use Partytown with next/script but do not have the required package(s) installed."
      )
    ) +
      '\n\n' +
      bold(`Please install Partytown by running:`) +
      '\n\n' +
      `\t${bold(
        cyan


import { bold } from './picocolors'
import { APP_DIR_ALIAS } from './constants'
import type { PageExtensions } from '../build/page-extensions-type'

const globOrig =
  require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')
const glob = (cwd: string, pattern: string): Promise<string[]> => {
  return new Promise((resolve, reject) => {
    globOrig(pattern, { cwd }, (err, files) => {
      if (err) {
        return reject(err)
      }
      resolve(files)
    })
  })
}

function getRoo

eturn (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
`
  }

  return `export const metadata = {
  title: 'Next.js',
  description: 'Generated by Next.js',
}

export default function RootLayout({ children }) {
  return (
    <html la

tLayout(isTs: boolean) {
  if (isTs) {
    return `export const metadata = {
  title: 'Next.js',
  description: 'Generated by Next.js',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  r


 } from 'fs'
import { promises, constants } from 'fs'
import { Sema } from 'next/dist/compiled/async-sema'
import isError from './is-error'

const COPYFILE_EXCL = constants.COPYFILE_EXCL

export async function recursiveCopy(
  source: string,
  dest: string,
  {
    concurrency = 32,
    overwrite = false,
    filter = () => true,
  }: {
    concurrency?: number
    overwrite?: boolean
    filter?(filePath: string): boolean
  } = {}
): Promise<void> {
  const cwdPath = process.cwd()
  const from = path.reso

t = item.replace(from, to)

    await sema.acquire()

    if (!lstats) {
      // after lock on first run
      lstats = await promises.lstat(from)
    }

    // readdir & lstat do not follow symbolic links
    // if part is a symbolic link, follow it with

lve(cwdPath, source)
  const to = path.resolve(cwdPath, dest)

  const sema = new Sema(concurrency)

  // deep copy the file/directory
  async function _copy(item: string, lstats?: Stats | Dirent): Promise<void> {
    const targe


s from 'node:fs'
import { join } from 'node:path'
import isError from './is-error'
import { wait } from './wait'

// We use an exponential backoff. See the unit test for example values.
//
// - Node's `fs` module uses a linear backoff, starting with 100ms.
// - Rust tries 64 times with only a `thread::yield_now` in between.
//
// We want something more aggressive, as `recursiveDelete` is in the critical
// path of `next dev` and `next build` startup.
const INITIAL_RETRY_MS = 8
const MAX_RETRY_MS = 64
const

Dir = false,
  attempt = 0
): Promise<void> | void {
  try {
    if (isDir) {
      fs.rmdirSync(p)
    } else {
      fs.unlinkSync(p)
    }
  } catch (e) {
    const code = isError(e) && e.code
    if (
      (code === 'EBUSY' ||
        code === 'ENOTEM

MAX_RETRIES = 6

/**
 * Used in unit test.
 * @ignore
 */
export function calcBackoffMs(attempt: number): number {
  return Math.min(INITIAL_RETRY_MS * Math.pow(2, attempt), MAX_RETRY_MS)
}

function unlinkPath(
  p: string,
  is


 This module imports the client instrumentation hook from the project root.
 *
 * The `private-next-instrumentation-client` module is automatically aliased to
 * the `instrumentation-client.ts` file in the project root by webpack or turbopack.
 */
if (process.env.NODE_ENV === 'development') {
  const measureName = 'Client Instrumentation Hook'
  const startTime = performance.now()
  // eslint-disable-next-line @next/internal/typechecked-require -- Not a module.
  module.exports = require('private-next-instr

on
  // could potentially cause frame drops during development.
  const THRESHOLD = 16
  if (duration > THRESHOLD) {
    console.log(
      `[${measureName}] Slow execution detected: ${duration.toFixed(0)}ms (Note: Code download overhead is not included in

umentation-client')
  const endTime = performance.now()
  const duration = endTime - startTime

  // Using 16ms threshold as it represents one frame (1000ms/60fps)
  // This helps identify if the instrumentation hook initializati


ttps://github.com/sindresorhus/resolve-from
import path from 'path'
import isError from './is-error'
import { realpathSync } from './realpath'

const Module = require('module') as typeof import('module')

export const resolveFrom = (
  fromDirectory: string,
  moduleId: string,
  silent?: boolean
) => {
  if (typeof fromDirectory !== 'string') {
    throw new TypeError(
      `Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``
    )
  }

  if (typeof moduleId !== 'string') {

ror.code === 'ENOENT') {
      fromDirectory = path.resolve(fromDirectory)
    } else if (silent) {
      return
    } else {
      throw error
    }
  }

  const fromFile = path.join(fromDirectory, 'noop.js')

  const resolveFileName = () =>
    // @ts-ex

 throw new TypeError(
      `Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``
    )
  }

  try {
    fromDirectory = realpathSync(fromDirectory)
  } catch (error: unknown) {
    if (isError(error) && er


a given page can have.
 */
export const enum FallbackMode {
  /**
   * A BLOCKING_STATIC_RENDER fallback will block the request until the page is
   * generated. No fallback page will be rendered, and users will have to wait
   * to render the page.
   */
  BLOCKING_STATIC_RENDER = 'BLOCKING_STATIC_RENDER',

  /**
   * When set to PRERENDER, a fallback page will be sent to users in place of
   * forcing them to wait for the page to be generated. This allows the user to
   * see a rendered page earlier.
   *

StaticPaths` function.
 */
export type GetStaticPathsFallback = boolean | 'blocking'

/**
 * Parses the fallback field from the prerender manifest.
 *
 * @param fallbackField The fallback field from the prerender manifest.
 * @returns The fallback mode.
 *

/
  PRERENDER = 'PRERENDER',

  /**
   * When set to NOT_FOUND, pages that are not already prerendered will result
   * in a not found response.
   */
  NOT_FOUND = 'NOT_FOUND',
}

/**
 * The fallback value returned from the `get


next/dist/compiled/find-up'
import * as Log from '../build/output/log'

function findWorkRoot(cwd: string) {
  // Find-up evaluates the list of files at each level.
  // For pnpm-workspace.yaml we first want to look up before searching for lockfiles as those can be included in the application directory by accident.
  const pnpmWorkspaceFile = findUp.sync(
    'pnpm-workspace.yaml',

    {
      cwd,
    }
  )

  if (pnpmWorkspaceFile) {
    return pnpmWorkspaceFile
  }

  return findUp.sync(
    [
      'pn

g
} {
  const lockFile = findWorkRoot(cwd)
  if (!lockFile)
    return {
      lockFiles: [],
      rootDir: cwd,
    }

  const lockFiles = [lockFile]
  while (true) {
    const lastLockFile = lockFiles[lockFiles.length - 1]
    const currentDir = dirname

pm-lock.yaml',
      'package-lock.json',
      'yarn.lock',
      'bun.lock',
      'bun.lockb',
    ],
    {
      cwd,
    }
  )
}

export function findRootDirAndLockFiles(cwd: string): {
  lockFiles: string[]
  rootDir: strin


from 'path'
import { pathToFileURL, fileURLToPath } from 'url'

/**
 * Converts a cache handler path to a filesystem path.
 * ESM's import.meta.resolve() returns file:// URLs which break when concatenated
 * with .next/ or used with path.join/path.relative.
 * @param filePath - Absolute path, relative path, or file:// URL (e.g. from import.meta.resolve)
 * @returns A filesystem path suitable for path operations
 */
export function resolveCacheHandlerPathToFilesystem(filePath: string): string {
  if (filePat

eginning of the path as a protocol (`C:`).
 * Therefore, it is important to always construct a complete path.
 * @param dir File directory
 * @param filePath Absolute or relative path, or file:// URL (e.g. from import.meta.resolve)
 */
export const formatD

h.startsWith('file://')) {
    return fileURLToPath(filePath)
  }
  return filePath
}

/**
 * The path for a dynamic route must be URLs with a valid scheme.
 *
 * When an absolute Windows path is passed to it, it interprets the b


 { formatServerError } from './format-server-error'

describe('formatServerError', () => {
  it('should not append message several times', () => {
    const err = new Error(
      'Class extends value undefined is not a constructor or null'
    )

    // Before
    expect(err.message).toMatchInlineSnapshot(
      `"Class extends value undefined is not a constructor or null"`
    )

    // After
    formatServerError(err)
    expect(err.message).toMatchInlineSnapshot(`
      "Class extends value undefined is

ponent-in-server-component"
    `)

    // After second
    formatServerError(err)
    expect(err.message).toMatchInlineSnapshot(`
      "Class extends value undefined is not a constructor or null

      This might be caused by a React Class Component bein

 not a constructor or null

      This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-com


/ From root
      expect(headerRegex.test('/groups')).toBe(true) // From /groups
      expect(headerRegex.test('/groups/123')).toBe(true) // From /groups/123 (THE BUG FIX!)
      expect(headerRegex.test('/groups/123/settings')).toBe(true) // From any nested route
      expect(headerRegex.test('/other/route/deep')).toBe(true) // From any other route
    })

    it('should generate rewrite for nested route intercepting sibling', () => {
      const rewrites = generateInterceptionRoutesRewrites([
        '/int

ntercepting-routes/feed/photos/:nxtPid')

      // Destination should be the intercepting route with the same named parameter
      expect(rewrite.destination).toBe(
        '/intercepting-routes/feed/(.)photos/:nxtPid'
      )

      // Verify the regex i

ercepting-routes/feed/(.)photos/[id]',
      ])

      expect(rewrites).toHaveLength(1)
      const rewrite = rewrites[0]

      // Source should be the intercepted route with named parameter
      expect(rewrite.source).toBe('/i


: string[] {
  const interfaces = os.networkInterfaces()
  const hosts: string[] = []

  Object.keys(interfaces).forEach((key) => {
    interfaces[key]
      ?.filter((networkInterface) => {
        switch (networkInterface.family) {
          case 'IPv6':
            return (
              family === 'IPv6' &&
              networkInterface.scopeid === 0 &&
              networkInterface.address !== '::1'
            )
          case 'IPv4':
            return family === 'IPv4' && networkInterface.address

n false
        }
      })
      .forEach((networkInterface) => {
        if (networkInterface.address) {
          hosts.push(networkInterface.address)
        }
      })
  })

  return hosts
}

export function getNetworkHost(family: 'IPv4' | 'IPv6'): str


 from 'fs'
import findUp from 'next/dist/compiled/find-up'
import JSON5 from 'next/dist/compiled/json5'
import * as path from 'path'

type PackageJsonDependencies = {
  dependencies: Record<string, string>
  devDependencies: Record<string, string>
}

let cachedDeps: Promise<PackageJsonDependencies>

export function getDependencies({
  cwd,
}: {
  cwd: string
}): Promise<PackageJsonDependencies> {
  if (cachedDeps) {
    return cachedDeps
  }

  return (cachedDeps = (async () => {
    const configurationPath

    const packageJson: any = JSON5.parse(content)

    const { dependencies = {}, devDependencies = {} } = packageJson || {}
    return { dependencies, devDependencies }
  })())
}

export async function getPackageVersion({
  cwd,
  name,
}: {
  cwd: strin

: string | undefined = await findUp('package.json', {
      cwd,
    })
    if (!configurationPath) {
      return { dependencies: {}, devDependencies: {} }
    }

    const content = await fs.readFile(configurationPath, 'utf-8')


t { resolveFrom } from './resolve-from'
import { dirname, join, relative } from 'path'

export interface MissingDependency {
  file: string
  /**
   * The package's package.json (e.g. require(`${pkg}/package.json`)) MUST resolve.
   * If `exportsRestrict` is false, `${file}` MUST also resolve.
   */
  pkg: string
  /**
   * If true, the pkg's package.json needs to be resolvable.
   * If true, will resolve `file` relative to the real path of the package.json.
   *
   * For example, `{ file: '@types/react/ind

s')`.
   *
   * If false, will resolve `file` relative to the baseDir.
   * ForFor example, `{ file: '@types/react/index.d.ts', pkg: '@types/react', exportsRestrict: true }`
   * will try to resolve `@types/react/index.d.ts` directly.
   */
  exportsRestri

ex.d.ts', pkg: '@types/react', exportsRestrict: true }`
   * will try to resolve '@types/react/package.json' first and then assume `@types/react/index.d.ts`
   * resolves to `path.join(dirname(resolvedPackageJsonPath), 'index.d.t


pe { MissingDependency } from './has-necessary-dependencies'
import { getPkgManager } from './helpers/get-pkg-manager'
import { install } from './helpers/install'
import { getOnline } from './helpers/get-online'

export type Dependencies = {
  resolved: Map<string, string>
}

export async function installDependencies(
  baseDir: string,
  deps: any,
  dev: boolean = false
) {
  const packageManager = getPkgManager(baseDir)
  const isOnline = await getOnline()

  if (deps.length) {
    console.log()
    cons

ndencies' : 'dependencies'
      } (${packageManager}):`
    )
    for (const dep of deps) {
      console.log(`- ${cyan(dep.pkg)}`)
    }
    console.log()

    await install(
      path.resolve(baseDir),
      deps.map((dep: MissingDependency) => dep.pkg

ole.log(
      `Installing ${
        dev ? 'devDepe


= await loadCustomRoutes({})
      expect(customRoutes.rewrites.beforeFiles).toEqual([])
      expect(customRoutes.rewrites.afterFiles).toEqual([])
      expect(customRoutes.rewrites.fallback).toEqual([])
    })

    it('array rewrites should be added to afterFiles', async () => {
      const customRoutes = await loadCustomRoutes({
        async rewrites() {
          return [
            {
              source: '/a',
              destination: '/b',
            },
          ]
        },
      })
      expe

back).toEqual([])
    })

    it('rewrites should be preserved correctly', async () => {
      const customRoutes = await loadCustomRoutes({
        async rewrites() {
          return {
            beforeFiles: [
              {
                source: '/

ct(customRoutes.rewrites.beforeFiles).toEqual([])
      expect(customRoutes.rewrites.afterFiles).toEqual([
        {
          destination: '/b',
          source: '/a',
        },
      ])
      expect(customRoutes.rewrites.fall


m 'node:crypto'
import { getCacheDirectory } from './helpers/get-cache-directory'
import * as Log from '../build/output/log'
import { execSync } from 'node:child_process'
const { WritableStream } =
  require('node:stream/web') as typeof import('node:stream/web')

const MKCERT_VERSION = 'v1.4.4'

export interface SelfSignedCertificate {
  key: string
  cert: string
  rootCA?: string
}

function getBinaryName() {
  const platform = process.platform
  const arch = process.arch === 'x64' ? 'amd64' : process.arc

rt-${MKCERT_VERSION}-linux-${arch}`
  }

  throw new Error(`Unsupported platform: ${platform}`)
}

async function downloadBinary() {
  try {
    const binaryName = getBinaryName()
    const cacheDirectory = getCacheDirectory('mkcert')
    const binaryPath

h

  if (platform === 'win32') {
    return `mkcert-${MKCERT_VERSION}-windows-${arch}.exe`
  }
  if (platform === 'darwin') {
    return `mkcert-${MKCERT_VERSION}-darwin-${arch}`
  }
  if (platform === 'linux') {
    return `mkce


dUp from 'next/dist/compiled/find-up'
// @ts-ignore no-json types
import { optionalDependencies as nextOptionalDeps } from 'next/package.json'
import type { UnwrapPromise } from './coalesced-function'
import { isCI } from '../server/ci-info'
import { getRegistry } from './helpers/get-registry'

let registry: string | undefined

async function fetchPkgInfo(pkg: string) {
  if (!registry) registry = getRegistry()
  const res = await fetch(`${registry}${pkg}`)

  if (!res.ok) {
    throw new Error(
      `Fail

ionData.cpu,
    engines: versionData.engines,
    tarball: versionData.dist.tarball,
    integrity: versionData.dist.integrity,
  }
}

/**
 * Attempts to patch npm package-lock.json when it
 * fails to include optionalDependencies for other platforms
 * t

ed to fetch registry info for ${pkg}, got status ${res.status}`
    )
  }
  const data = await res.json()
  const versionData = data.versions[process.env.__NEXT_VERSION as string]

  return {
    os: versionData.os,
    cpu: vers


sorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this perm

ILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

ission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTAB


'../client/components/redirect-status-code'

export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])

export function getRedirectStatus(route: {
  statusCode?: number
  permanent?: boolean
}): number {
  return (
    route.statusCode ||
    (route.permanent
      ? RedirectStatusCode.PermanentRedirect
      : RedirectStatusCode.TemporaryRedirect)
  )
}

// for redirects we restrict matching /_next and for all routes
// we add an optional trailing slash at the end for easier
// configuring betwe

outeRegex(regex: string, restrictedPaths?: string[]) {
  if (restrictedPaths) {
    regex = regex.replace(
      /\^/,
      `^(?!${restrictedPaths
        .map((path) => path.replace(/\//g, '\\/'))
        .join('|')})`
    )
  }
  regex = regex.replace(/

en trailingSlash: true/false
export function modifyR


mport fs from 'fs'
import path from 'path'

export function findDir(dir: string, name: 'pages' | 'app'): string | null {
  // prioritize ./${name} over ./src/${name}
  let curDir = path.join(dir, name)
  if (fs.existsSync(curDir)) return curDir

  curDir = path.join(dir, 'src', name)
  if (fs.existsSync(curDir)) return curDir

  return null
}

export function findPagesDir(dir: string): {
  pagesDir: string | undefined
  appDir: string | undefined
} {
  const pagesDir = findDir(dir, 'pages') || undefined
  c

gesDir && appDir) {
    const pagesParent = path.dirname(pagesDir)
    const appParent = path.dirname(appDir)
    if (pagesParent !== appParent) {
      throw new Error(
        '> `pages` and `app` directories should be under the same folder'
      )

onst appDir = findDir(dir, 'app') || undefined

  if (appDir == null && pagesDir == null) {
    throw new Error(
      "> Couldn't find any `pages` or `app` directory. Please create one under the project root"
    )
  }

  if (pa


ferredValue',
  'useEffect',
  'useEffectEvent',
  'useImperativeHandle',
  'useInsertionEffect',
  'useLayoutEffect',
  'useReducer',
  'useRef',
  'useState',
  'useSyncExternalStore',
  'useTransition',
  'experimental_useOptimistic',
  'useOptimistic',
]

function setMessage(error: Error, message: string): void {
  error.message = message
  if (error.stack) {
    const lines = error.stack.split('\n')
    lines[0] = message
    error.stack = lines.join('\n')
  }
}

/**
 * Input:
 * Error: Something went

essage(error: Error): string {
  const stack = error.stack
  if (!stack) return ''
  return stack.replace(/^[^\n]*\n/, '')
}

export function formatServerError(error: Error): void {
  if (typeof error?.message !== 'string') return

  if (
    error.message

wrong
    at funcName (/path/to/file.js:10:5)
    at anotherFunc (/path/to/file.js:15:10)

 * Output:
    at funcName (/path/to/file.js:10:5)
    at anotherFunc (/path/to/file.js:15:10)
 */
export function getStackWithoutErrorM


from 'path'
import { warn } from '../build/output/log'
import { detectTypo } from './detect-typo'
import { realpathSync } from './realpath'
import { printAndExit } from '../server/lib/utils'

export function getProjectDir(dir?: string, exitOnEnoent = true) {
  const resolvedDir = path.resolve(dir || '.')
  try {
    const realDir = realpathSync(resolvedDir)

    if (
      resolvedDir !== realDir &&
      resolvedDir.toLowerCase() === realDir.toLowerCase()
    ) {
      warn(
        `Invalid casing detecte

ENT' && exitOnEnoent) {
      if (typeof dir === 'string') {
        const detectedTypo = detectTypo(dir, [
          'build',
          'dev',
          'info',
          'lint',
          'start',
          'telemetry',
          'experimental-test',

d for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing`
      )
    }

    return realDir
  } catch (err: any) {
    if (err.code === 'ENO


*/
  internal?: boolean

  /**
   * @internal - used internally for routing
   */
  regex?: string
}

export type Header = {
  source: string
  basePath?: false
  locale?: false
  headers: Array<{ key: string; value: string }>
  has?: RouteHas[]
  missing?: RouteHas[]

  /**
   * @internal - used internally for routing
   */
  internal?: boolean
}

// internal type used for validation (not user facing)
export type Redirect = {
  source: string
  destination: string
  basePath?: false
  locale?: false
  has?

umber
      permanent?: never
    }
)

export type Middleware = {
  source: string
  locale?: false
  has?: RouteHas[]
  missing?: RouteHas[]
}

const allowedHasTypes = new Set(['header', 'cookie', 'query', 'host'])
const namedGroupsRegex = /\(\?<([a-zA-Z]

: RouteHas[]
  missing?: RouteHas[]
  priority?: boolean

  /**
   * @internal - used internally for routing
   */
  internal?: boolean
} & (
  | {
      statusCode?: never
      permanent: boolean
    }
  | {
      statusCode: n


o_station'
  | 'profile'
  | 'website'
  | 'video.tv_show'
  | 'video.other'
  | 'video.movie'
  | 'video.episode'

export type OpenGraph =
  | OpenGraphWebsite
  | OpenGraphArticle
  | OpenGraphBook
  | OpenGraphProfile
  | OpenGraphMusicSong
  | OpenGraphMusicAlbum
  | OpenGraphMusicPlaylist
  | OpenGraphRadioStation
  | OpenGraphVideoMovie
  | OpenGraphVideoEpisode
  | OpenGraphVideoTVShow
  | OpenGraphVideoOther
  | OpenGraphMetadata

// update this type to reflect actual locales
type Locale = string

t

 string | Array<string> | undefined
  faxNumbers?: string | Array<string> | undefined
  siteName?: string | undefined
  locale?: Locale | undefined
  alternateLocale?: Locale | Array<Locale> | undefined
  images?: OGImage | Array<OGImage> | undefined
  aud

ype OpenGraphMetadata = {
  determiner?: 'a' | 'an' | 'the' | 'auto' | '' | undefined
  title?: string | TemplateString | undefined
  description?: string | undefined
  emails?: string | Array<string> | undefined
  phoneNumbers?:


adata, ResolvedMetadataWithURLs } from './metadata-interface'

export type FieldResolver<
  Key extends keyof Data & keyof ResolvedData,
  Data = Metadata,
  ResolvedData = ResolvedMetadataWithURLs,
> = (T: Data[Key]) => ResolvedData[Key]

export type FieldResolverExtraArgs<
  Key extends keyof Data & keyof ResolvedData,
  ExtraArgs extends unknown[] = any[],
  Data = Metadata,
  ResolvedData = ResolvedMetadataWithURLs,
> = (T: Data[Key], ...args: ExtraArgs) => ResolvedData[Key]

export type AsyncFieldResol

vedData,
  ExtraArgs extends unknown[] = any[],
  Data = Metadata,
  ResolvedData = ResolvedMetadataWithURLs,
> = (T: Data[Key], ...args: ExtraArgs) => Promise<ResolvedData[Key]>

export type MetadataContext = {
  trailingSlash: boolean
  isStaticMetadataR


const glob = promisify(globOriginal)

interface ResolvedBuildPaths {
  appPaths: string[]
  pagePaths: string[]
}

/**
 * Escapes Next.js dynamic route bracket expressions so glob treats them as
 * literal directory names rather than character classes.
 *
 * e.g., "app/blog/[slug]/** /page.tsx" → "app/blog/\[slug\]/** /page.tsx"
 */
function escapeBrackets(pattern: string): string {
  // Match Next.js dynamic route patterns: [name], [...name], [[...name]]
  return pattern.replace(/\[\[?\.\.\.[^\]]+\]?\]|\[

 negation patterns prefixed with "!" to exclude paths.
 * e.g., "app/**,!app/[lang]/page.js" includes all App Router paths except
 * app/[lang]/page.js
 */
export async function resolveBuildPaths(
  patterns: string[],
  projectDir: string
): Promise<Resol

[^\]]+\]/g, (match) =>
    match.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
  )
}

/**
 * Resolves glob patterns and explicit paths to actual file paths.
 * Categorizes them into App Router and Pages Router paths.
 *
 * Supports


'../client/components/app-router-headers'
import {
  extractInterceptionRouteInformation,
  isInterceptionRouteAppPath,
} from '../shared/lib/router/utils/interception-routes'
import type { Rewrite } from './load-custom-routes'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'

export function generateInterceptionRoutesRewrites(
  appPaths: string[],
  basePath = ''
): Rewrite[] {
  const rewrites: Rewrite[] = []

  for (const appPath of appPaths) {
    if (isInterceptionRouteAppPa

      const header = getNamedRouteRegex(interceptingRoute, {
        prefixRouteKeys: true,
        reference: destination.reference,
      })

      const source = getNamedRouteRegex(basePath + interceptedRoute, {
        prefixRouteKeys: true,

th(appPath)) {
      const { interceptingRoute, interceptedRoute } =
        extractInterceptionRouteInformation(appPath)

      const destination = getNamedRouteRegex(basePath + appPath, {
        prefixRouteKeys: true,
      })


lainIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/

export class SerializableError extends Error {
  constructor(page: string, method: string, path: string, message: string) {
    super(
      path
        ? `Error serializing \`${path}\` returned from \`${method}\` in "${page}".\nReason: ${message}`
        : `Error serializing props returned from \`${method}\` in "${page}".\nReason: ${message}`
    )
  }
}

export function isSerializableProps(
  page: string,
  method: string,
  input: any
): true {
  if (!isP

    )}\`).`
    )
  }

  function visit(visited: Map<any, string>, value: any, path: string) {
    if (visited.has(value)) {
      throw new SerializableError(
        page,
        method,
        path,
        `Circular references cannot be expressed in

lainObject(input)) {
    throw new SerializableError(
      page,
      method,
      '',
      `Props must be returned as a plain object from ${method}: \`{ props: { ... } }\` (received: \`${getObjectClassLabel(
        input


saryDependencies,
} from './has-necessary-dependencies'
import semver from 'next/dist/compiled/semver'
import { CompileError } from './compile-error'
import * as log from '../build/output/log'

import { getTypeScriptIntent } from './typescript/getTypeScriptIntent'
import type { TypeCheckResult } from './typescript/runTypeCheck'
import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations'
import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults'
import { install

issingDependency = {
  file: 'typescript/lib/typescript.js',
  pkg: 'typescript',
  exportsRestrict: true,
}

const requiredPackages: MissingDependency[] = [
  typescriptPackage,
  {
    file: '@types/react/index.d.ts',
    pkg: '@types/react',
    exports

Dependencies } from './install-dependencies'
import { isCI } from '../server/ci-info'
import { missingDepsError } from './typescript/missingDependencyError'
import { resolveFrom } from './resolve-from'

const typescriptPackage: M


t/dist/compiled/jest-worker', () => {
  const WorkerMock = jest.fn().mockImplementation((_path, options) => {
    latestForkEnv = options?.forkOptions?.env
    return {
      _workerPool: { _workers: [] },
      getStdout: () => new PassThrough(),
      getStderr: () => new PassThrough(),
      end: jest.fn().mockResolvedValue(undefined),
      close: jest.fn(),
    }
  })

  return { Worker: WorkerMock }
})

const noopOptions = {
  debuggerPortOffset: -1,
  isolatedMemory: false,
  exposedMethods: [] as st

criptor(target, property)
  restoreDescriptors.push(() => {
    if (descriptor) {
      Object.defineProperty(target, property, descriptor)
    } else {
      delete (target as any)[property]
    }
  })
  Object.defineProperty(target, property, {
    confi

ring[],
}

const restoreDescriptors: Array<() => void> = []

const overrideBooleanDescriptor = (
  target: NodeJS.WriteStream,
  property: 'isTTY',
  value: boolean | undefined
) => {
  const descriptor = Object.getOwnPropertyDes


t path from 'path'
import fs from 'fs'

// get platform specific cache directory adapted from playwright's handling
// https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141
export function getCacheDirectory(fileDirectory: string, envPath?: string) {
  let result

  if (envPath) {
    result = envPath
  } else {
    let systemCacheDirectory
    if (process.platform === 'linux') {
      systemCacheDirectory =
        process.e

 systemCacheDirectory =
        process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')
    } else {
      /// Attempt to use generic tmp location for un-handled platform
      if (!systemCacheDirectory) {
        for (const dir of [

nv.XDG_CACHE_HOME || path.join(os.homedir(), '.cache')
    } else if (process.platform === 'darwin') {
      systemCacheDirectory = path.join(os.homedir(), 'Library', 'Caches')
    } else if (process.platform === 'win32') {


cSync } from 'child_process'
import { getPkgManager } from './get-pkg-manager'
import { getFormattedNodeOptionsWithoutInspect } from '../../server/lib/utils'

/**
 * Returns the package registry using the user's package manager.
 * The URL will have a trailing slash.
 * @default https://registry.npmjs.org/
 */
export function getRegistry(baseDir: string = process.cwd()) {
  const pkgManager = getPkgManager(baseDir)
  // Since `npm config` command fails in npm workspace to prevent workspace config conflicts,

21#issuecomment-1499044345
  // x-ref: https://github.com/npm/statusboard/issues/371#issue-920669998
  const resolvedFlags = pkgManager === 'npm' ? '--no-workspaces' : ''
  let registry = `https://registry.npmjs.org/`

  try {
    const output = execSync(

  // add `--no-workspaces` flag to run under the context of the root project only.
  // Safe for non-workspace projects as it's equivalent to default `--workspaces=false`.
  // x-ref: https://github.com/vercel/next.js/issues/471


cSync } from 'child_process'

function gitExec(args: string, cwd: string): string {
  return execSync(`git ${args}`, {
    cwd,
    timeout: 2000,
    stdio: ['ignore', 'pipe', 'ignore'],
  })
    .toString()
    .trim()
}

/**
 * Returns the current git branch name for the given working directory, or
 * undefined if it cannot be determined (not a git repo, detached HEAD,
 * git not installed, etc.). Prefers VERCEL_GIT_COMMIT_REF when set.
 */
export function getGitBranch(cwd: string): string | undefined {

non-zero in detached HEAD state
    // (caught below and treated as unknown).
    return gitExec('symbolic-ref --short HEAD', cwd)
  } catch {
    return undefined
  }
}

/**
 * Returns the current git commit SHA for the given working directory, or
 * unde

  if (process.env.VERCEL_GIT_COMMIT_REF) {
    return process.env.VERCEL_GIT_COMMIT_REF
  }
  try {
    // symbolic-ref --short HEAD: returns the branch name for regular branches,
    // works on repos with no commits, and exits


 from 'next/dist/compiled/cross-spawn'
import type { PackageManager } from './get-pkg-manager'

interface InstallArgs {
  /**
   * Indicate whether to install packages using npm, pnpm, or yarn.
   */
  packageManager: PackageManager
  /**
   * Indicate whether there is an active internet connection.
   */
  isOnline: boolean
  /**
   * Indicate whether the given dependencies are devDependencies.
   */
  devDependencies?: boolean
}

/**
 * Spawn a package manager installation with either npm, pnpm, or yarn.

t args: string[] = []

  if (dependencies.length > 0) {
    if (packageManager === 'yarn') {
      args = ['add', '--exact']
      if (devDependencies) args.push('--dev')
    } else if (packageManager === 'pnpm') {
      args = ['add', '--save-exact']

 *
 * @returns A Promise that resolves once the installation is finished.
 */
export function install(
  root: string,
  dependencies: string[],
  { packageManager, isOnline, devDependencies }: InstallArgs
): Promise<void> {
  le


ormalizeMetadataRoute,
} from './get-metadata-route'

describe('fillStaticMetadataSegment', () => {
  it('should preserve a statically known root favicon path', () => {
    expect(fillStaticMetadataSegment('/', 'favicon.ico')).toBe('/favicon.ico')
  })

  it('should replace dynamic segments with placeholder segments', () => {
    expect(fillStaticMetadataSegment('/blog/[slug]', 'favicon.ico')).toBe(
      '/blog/-/favicon.ico'
    )
    expect(fillStaticMetadataSegment('/blog/[...slug]', 'icon.png')).toBe(

e = normalizeMetadataRoute(
      '/(post)/@feed/blog/twitter-image'
    )
    const suffix = normalizedRoute.match(/twitter-image(-[0-9a-z]{6})\/route$/)

    expect(suffix).not.toBeNull()
    expect(staticPath).toBe(`/blog/twitter-image${suffix?.[1]}.png

      '/blog/-/icon.png'
    )
  })

  it('should preserve grouped metadata suffixes', () => {
    const staticPath = fillStaticMetadataSegment(
      '/(post)/@feed/blog',
      'twitter-image.png'
    )
    const normalizedRout


om '../../shared/lib/router/utils/route-regex'
import { PARAMETER_PATTERN } from '../../shared/lib/router/utils/get-dynamic-param'
import { djb2Hash } from '../../shared/lib/hash'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { isDynamicRoute } from '../../shared/lib/router/utils'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { isMetadataRouteFile } from './is-metadata-route'
import {
  isGroupSegment,
  isParallelRouteSegment,
}

ge.tsx -> /opengraph-image-[0-9a-z]{6}
 *
 * Sitemap is an exception, it should not have a suffix.
 * Each sitemap contains all the urls of sub routes, we don't have the case of duplicates `/(group)/sitemap.[ext]` and `/sitemap.[ext]` since they should be

from '../../shared/lib/segment'

/*
 * If there's special convention like (...) or @ in the page path,
 * Give it a unique hash suffix to avoid conflicts
 *
 * e.g.
 * /opengraph-image -> /opengraph-image
 * /(post)/opengraph-ima


n this way we can let the metadata tags always render successfully,
// and the error will be caught by the error boundary and trigger fallbacks.
export function createMetadataComponents({
  tree,
  pathname,
  parsedQuery,
  metadataContext,
  interpolatedParams,
  errorType,
  serveStreamingMetadata,
  isRuntimePrefetchable,
}: {
  tree: LoaderTree
  pathname: string
  parsedQuery: SearchParams
  metadataContext: MetadataContext
  interpolatedParams: Params
  errorType?: MetadataErrorType | 'redirect'
  se

data(
    parsedQuery,
    isRuntimePrefetchable
  )
  const pathnameForMetadata = createServerPathnameForMetadata(pathname)

  async function Viewport() {
    // Gate metadata to the correct render stage. If the page is not
    // runtime-prefetchable, de

rveStreamingMetadata: boolean
  isRuntimePrefetchable: boolean
}): {
  Viewport: React.ComponentType
  Metadata: React.ComponentType
  MetadataOutlet: React.ComponentType
} {
  const searchParams = createServerSearchParamsForMeta


pp-dir-module'
import {
  resolveAlternates,
  resolveAppleWebApp,
  resolveAppLinks,
  resolveRobots,
  resolveThemeColor,
  resolveVerification,
  resolveItunes,
  resolveFacebook,
  resolvePagination,
} from './resolvers/resolve-basics'
import { resolveIcons } from './resolvers/resolve-icons'
import { getTracer } from '../../server/lib/trace/tracer'
import { ResolveMetadataSpan } from '../../server/lib/trace/constants'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import * as Log from '../.

lient-and-server-references'
import type {
  UseCacheLayoutProps,
  UseCachePageProps,
} from '../../server/use-cache/use-cache-wrapper'
import { createLazyResult } from '../../server/lib/lazy-result'

type StaticIcons = Pick<ResolvedIcons, 'icon' | 'apple

./build/output/log'
import { createServerParamsForMetadata } from '../../server/request/params'
import type { MetadataBaseURL } from './resolvers/resolve-url'
import {
  getUseCacheFunctionInfo,
  isUseCacheFunction,
} from '../c


 member exists.
// ref: https://developers.facebook.com/docs/applinks/metadata-reference

export type AppLinks = {
  ios?: AppLinksApple | Array<AppLinksApple> | undefined
  iphone?: AppLinksApple | Array<AppLinksApple> | undefined
  ipad?: AppLinksApple | Array<AppLinksApple> | undefined
  android?: AppLinksAndroid | Array<AppLinksAndroid> | undefined
  windows_phone?: AppLinksWindows | Array<AppLinksWindows> | undefined
  windows?: AppLinksWindows | Array<AppLinksWindows> | undefined
  windows_universal?:

ipad?: Array<AppLinksApple> | undefined
  android?: Array<AppLinksAndroid> | undefined
  windows_phone?: Array<AppLinksWindows> | undefined
  windows?: Array<AppLinksWindows> | undefined
  windows_universal?: Array<AppLinksWindows> | undefined
  web?: Arra

 AppLinksWindows | Array<AppLinksWindows> | undefined
  web?: AppLinksWeb | Array<AppLinksWeb> | undefined
}
export type ResolvedAppLinks = {
  ios?: Array<AppLinksApple> | undefined
  iphone?: Array<AppLinksApple> | undefined


g'
  | 'navigate-existing'
  | 'navigate-new'

type File = {
  name: string
  accept: string | string[]
}

type Icon = {
  src: string
  type?: string | undefined
  sizes?: string | undefined
  purpose?: 'any' | 'maskable' | 'monochrome' | undefined
}

export type Manifest = {
  background_color?: string | undefined
  categories?: string[] | undefined
  description?: string | undefined
  dir?: 'ltr' | 'rtl' | 'auto' | undefined
  display?: 'fullscreen' | 'standalone' | 'minimal-ui' | 'browser' | undefined

       accept: {
          [mimeType: string]: string[]
        }
      }[]
    | undefined
  icons?: Icon[] | undefined
  id?: string | undefined
  lang?: string | undefined
  launch_handler?:
    | {
        client_mode: ClientModeEnum | ClientModeEnum[]

 display_override?:
    | (
        | 'fullscreen'
        | 'standalone'
        | 'minimal-ui'
        | 'browser'
        | 'window-controls-overlay'
      )[]
    | undefined
  file_handlers?:
    | {
        action: string


port type { CacheFs } from '../shared/lib/utils'

/**
 * A task to be written.
 */
type Task = [
  /**
   * The directory to create.
   */
  directory: string,

  /**
   * The promise to create the directory.
   */
  mkdir: Promise<unknown>,

  /**
   * The promises to write the files that are dependent on the directory being
   * created.
   */
  writeFile: Promise<unknown>[],
]
/**
 * MultiFileWriter is a utility for writing multiple files in parallel that
 * guarantees that all files will be written afte

/**
     * The file system methods to use.
     */
    private readonly fs: Pick<CacheFs, 'mkdir' | 'writeFile'>
  ) {}

  /**
   * Finds or creates a task for a directory.
   *
   * @param directory - The directory to find or create a task for.
   * @retu

r their containing directory
 * is created, and that the directory will only be created once.
 */
export class MultiFileWriter {
  /**
   * The tasks to be written.
   */
  private readonly tasks: Task[] = []

  constructor(


eadDirOptions = {
  /**
   * Filter to ignore files with absolute pathnames, false to ignore.
   */
  pathnameFilter?: Filter

  /**
   * Filter to ignore files and directories with absolute pathnames, false to
   * ignore.
   */
  ignoreFilter?: Filter

  /**
   * Filter to ignore files and directories with the pathname part, false to
   * ignore.
   */
  ignorePartFilter?: Filter

  /**
   * Whether to sort the results, true by default.
   */
  sortPathnames?: boolean

  /**
   * Whether to return relativ

e behavior of the recursive read
 * @returns the list of pathnames
 */
export async function recursiveReadDir(
  rootDirectory: string,
  options: RecursiveReadDirOptions = {}
): Promise<string[]> {
  // Grab our options.
  const {
    pathnameFilter,

e pathnames, true by default.
   */
  relativePathnames?: boolean
}

/**
 * Recursively reads a directory and returns the list of pathnames.
 *
 * @param rootDirectory the directory to read
 * @param options options to control th


l'
import globOriginal from 'next/dist/compiled/glob'
import { Sema } from 'next/dist/compiled/async-sema'
import type { NextConfigComplete } from '../server/config-shared'
import { getNextConfigEnv, getStaticEnv } from './static-env'

const glob = promisify(globOriginal)

export async function inlineStaticEnv({
  distDir,
  config,
}: {
  distDir: string
  config: NextConfigComplete
}) {
  const nextConfigEnv = getNextConfigEnv(config)
  const staticEnv = getStaticEnv(config, config.deploymentId)

  const

ap}', {
    cwd: clientDir,
  })
  const manifestChunks = await glob('*.{js,json,js.map}', {
    cwd: distDir,
  })

  const inlineSema = new Sema(8)
  const nextConfigEnvKeys = Object.keys(nextConfigEnv).map((item) =>
    item.split('process.env.').pop()

serverDir = path.join(distDir, 'server')
  const serverChunks = await glob('**/*.{js,json,js.map}', {
    cwd: serverDir,
  })
  const clientDir = path.join(distDir, 'static')
  const clientChunks = await glob('**/*.{js,json,js.m


t type { LRUCache } from '../server/lib/lru-cache'

export function withPromiseCache<K, V>(
  cache: LRUCache<Promise<V>>,
  fn: (value: K) => Promise<V>
): (value: K) => Promise<V>
export function withPromiseCache<T extends any[], K, V>(
  cache: LRUCache<Promise<V>>,
  fn: (...values: T) => Promise<V>,
  getKey: (...values: T) => K
): (...values: T) => Promise<V>
export function withPromiseCache<T extends any[], K, V>(
  cache: LRUCache<Promise<V>>,
  fn: (...values: T) => Promise<V>,
  getKey?: (...value

(...values: T) => Promise<V> {
  return (...values: T) => {
    const key = getKey ? getKey(...values) : values[0]
    let p = cache.get(key)
    if (!p) {
      p = fn(...values)
      p.catch(() => cache.remove(key))
      cache.set(key, p)
    }
    ret


 RESTARTED = Symbol('restarted')

const cleanupWorkers = (worker: JestWorker) => {
  for (const curWorker of ((worker as any)._workerPool?._workers || []) as {
    _child?: ChildProcess
  }[]) {
    curWorker._child?.kill('SIGINT')
  }
}

export function getNextBuildDebuggerPortOffset(_: {
  kind: 'export-page'
}): number {
  // 0: export worker
  return 0
}

export class Worker {
  private _worker: JestWorker | undefined

  private _onActivity: (() => void) | undefined
  private _onActivityAbort: (() => vo

ocessEnv> | undefined
          })
        | undefined
      /**
       * `-1` if not inspectable
       */
      debuggerPortOffset: number
      enableSourceMaps?: boolean
      /**
       * True if `--max-old-space-size` should not be forwarded to the w

id) | undefined

  constructor(
    workerPath: string,
    options: Omit<FarmOptions, 'forkOptions'> & {
      forkOptions?:
        | (Omit<NonNullable<FarmOptions['forkOptions']>, 'env'> & {
            env?: Partial<NodeJS.Pr


{
  ResolvedMetadata,
  ResolvedViewport,
} from './types/metadata-interface'

export function createDefaultViewport(): ResolvedViewport {
  return {
    // name=viewport
    width: 'device-width',
    initialScale: 1,
    // visual metadata
    themeColor: null,
    colorScheme: null,
  }
}

export function createDefaultMetadata(): ResolvedMetadata {
  return {
    // Deprecated ones
    viewport: null,
    themeColor: null,
    colorScheme: null,

    metadataBase: null,
    // Other values are all null

lternates: {
      canonical: null,
      languages: null,
      media: null,
      types: null,
    },
    icons: null,
    openGraph: null,
    twitter: null,
    verification: {},
    appleWebApp: null,
    formatDetection: null,
    itunes: null,
    f

   title: null,
    description: null,
    applicationName: null,
    authors: null,
    generator: null,
    keywords: null,
    referrer: null,
    creator: null,
    publisher: null,
    robots: null,
    manifest: null,
    a


ex(
    ...args: Parameters<typeof getExtensionRegexString>
  ) {
    return new RegExp(`^${getExtensionRegexString(...args)}$`)
  }

  describe('with dynamic extensions', () => {
    it('should return the correct regex', () => {
      const regex = createExtensionMatchRegex(['png', 'jpg'], ['tsx', 'ts'])
      expect(regex.test('.png')).toBe(true)
      expect(regex.test('.jpg')).toBe(true)
      expect(regex.test('.webp')).toBe(false)

      expect(regex.test('.tsx')).toBe(true)
      expect(regex.test('.

egex.test('.png')).toBe(true)
      expect(regex.test('.jpg')).toBe(true)
      expect(regex.test('.webp')).toBe(false)

      expect(regex.test('.ts')).toBe(false)
      expect(regex.test('.tsx')).toBe(false)
      expect(regex.test('.js')).toBe(false)

ts')).toBe(true)
      expect(regex.test('.js')).toBe(false)
    })

    it('should not handle js extensions with empty dynamic extensions', () => {
      const regex = createExtensionMatchRegex(['png', 'jpg'], [])
      expect(r


reen'?: never | undefined

  /**
   * Obsolete since iOS 7.
   * @see https://web.dev/apple-touch-icon/
   * @deprecated Use icons.apple instead
   */
  'apple-touch-icon-precomposed'?: never | undefined
}

export type TemplateString =
  | DefaultTemplateString
  | AbsoluteTemplateString
  | AbsoluteString
export type DefaultTemplateString = {
  default: string
  template: string
}
export type AbsoluteTemplateString = {
  absolute: string
  template: string | null
}
export type AbsoluteString = {
  absolute

hould
// use '"unsafe-URL" as ReferrerEnum'
export type ReferrerEnum =
  | 'no-referrer'
  | 'origin'
  | 'no-referrer-when-downgrade'
  | 'origin-when-cross-origin'
  | 'same-origin'
  | 'strict-origin'
  | 'strict-origin-when-cross-origin'

export type C

: string
}

export type Author = {
  // renders as <link rel="author"...
  url?: string | URL | undefined
  // renders as <meta name="author"...
  name?: string | undefined
}

// does not include "unsafe-URL". to use this users s


n to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.

// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEV

lexeyraspopov/picocolors/blob/b6261487e7b81aaab2440e397a356732cad9e342/picocolors.js#L1

const { env, stdout } = globalThis?.process ?? {}

const enabled =
  env &&
  !env.NO_COLOR &&
  (env.FORCE_COLOR || (stdout?.isTTY && !env.CI && env.TERM !== 'dumb'))

ER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// https://github.com/a


import fs from 'fs'
import path from 'path'
import { execSync } from 'child_process'

export type PackageManager = 'npm' | 'pnpm' | 'yarn'

export function getPkgManager(baseDir: string): PackageManager {
  try {
    for (const { lockFile, packageManager } of [
      { lockFile: 'yarn.lock', packageManager: 'yarn' },
      { lockFile: 'pnpm-lock.yaml', packageManager: 'pnpm' },
      { lockFile: 'package-lock.json', packageManager: 'npm' },
    ]) {
      if (fs.existsSync(path.join(baseDir, lockFile))) {

startsWith('pnpm')) {
        return 'pnpm'
      }
    }
    try {
      execSync('yarn --version', { stdio: 'ignore' })
      return 'yarn'
    } catch {
      execSync('pnpm --version', { stdio: 'ignore' })
      return 'pnpm'
    }
  } catch {
    retu

       return packageManager as PackageManager
      }
    }
    const userAgent = process.env.npm_config_user_agent
    if (userAgent) {
      if (userAgent.startsWith('yarn')) {
        return 'yarn'
      } else if (userAgent.


outer/utils/app-paths'
import { isAppRouteRoute } from '../is-app-route-route'

export const STATIC_METADATA_IMAGES = {
  icon: {
    filename: 'icon',
    extensions: ['ico', 'jpg', 'jpeg', 'png', 'svg'],
  },
  apple: {
    filename: 'apple-icon',
    extensions: ['jpg', 'jpeg', 'png'],
  },
  favicon: {
    filename: 'favicon',
    extensions: ['ico'],
  },
  openGraph: {
    filename: 'opengraph-image',
    extensions: ['jpg', 'jpeg', 'png', 'gif'],
  },
  twitter: {
    filename: 'twitter-image',
    e

t const DEFAULT_METADATA_ROUTE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx']

// Match the file extension with the dynamic multi-routes extensions
// e.g. ([xml, js], null) -> can match `/sitemap.xml/route`, `sitemap.js/route`
// e.g. ([png], [ts]) -> can match

xtensions: ['jpg', 'jpeg', 'png', 'gif'],
  },
} as const

// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc.
// TODO-METADATA: support more metadata routes with more extensions
expor


inks,
  ResolvedFacebook,
  ResolvedPinterest,
  ViewportLayout,
} from './extra-types'
import type {
  DeprecatedMetadataFields,
  AbsoluteTemplateString,
  Author,
  ColorSchemeEnum,
  Icon,
  Icons,
  IconURL,
  ReferrerEnum,
  ResolvedIcons,
  ResolvedVerification,
  Robots,
  ResolvedRobots,
  TemplateString,
  Verification,
  ThemeColorDescriptor,
  Videos,
} from './metadata-types'
import type { Manifest as ManifestFile } from './manifest-types'
import type { OpenGraph, ResolvedOpenGraph } from './op

metadata fields available in Next.js including title, description,
 * icons, openGraph, twitter, and more. Fields such as `metadataBase` help in composing absolute URLs
 * from relative ones. The `title` field supports both simple strings and a template ob

engraph-types'
import type { ResolvedTwitterMetadata, Twitter } from './twitter-types'

/**
 * Metadata interface to describe all the metadata fields that can be set in a document.
 *
 * @remarks
 * This interface covers all the


led/commander'
import { bold } from '../lib/picocolors'

// Copy-pasted from Commander's Help class -> formatHelp().
// TL;DR, we're overriding the built-in help to add a few niceties.
// Link: https://github.com/tj/commander.js/blob/master/lib/help.js
const formatCliHelpOutput = (cmd: Command, helper: Help) => {
  const termWidth = helper.padWidth(cmd, helper)
  const helpWidth = helper.helpWidth || 80
  const itemIndentWidth = 2
  const itemSeparatorWidth = 2 // between term and description

  function fo

aratorWidth
      )}${description}`

      return helper.wrap(
        fullText,
        helpWidth - itemIndentWidth,
        termWidth + itemSeparatorWidth
      )
    }

    return term
  }

  function formatList(textArray: string[]) {
    return textArr

rmatItem(term: string, description: string) {
    let value = term

    if (description) {
      if (term === 'directory') {
        value = `[${term}]`
      }

      const fullText = `${value.padEnd(
        termWidth + itemSep


ports: Viewport[]) {
  // skip the first two arguments (metadata and static metadata)
  return originAccumulateViewport(viewportExports.map((item) => item))
}

function mapUrlsToStrings(obj: any) {
  if (typeof obj === 'object') {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] instanceof URL) {
          // If the property is a URL instance, convert it to a string
          obj[key] = obj[key].href
        } else if (typeof obj[key] === 'object') {
          // Recurs

nc metadata', async () => {
      const generateMetadata = () => Promise.resolve({ description: 'child' })
      const metadataItems: MetadataItems = [
        [{ description: 'parent' }, null],
        [
          Object.assign(generateMetadata, { $$origi

ively process nested objects
          obj[key] = mapUrlsToStrings(obj[key])
        }
      }
    }
  }
  return obj
}

describe('accumulateMetadata', () => {
  describe('typing', () => {
    it('should support both sync and asy


atwg.org/#port-blocking */
export const KNOWN_RESERVED_PORTS = {
  1: 'tcpmux',
  7: 'echo',
  9: 'discard',
  11: 'systat',
  13: 'daytime',
  15: 'netstat',
  17: 'qotd',
  19: 'chargen',
  20: 'ftp-data',
  21: 'ftp',
  22: 'ssh',
  23: 'telnet',
  25: 'smtp',
  37: 'time',
  42: 'name',
  43: 'nicname',
  53: 'domain',
  69: 'tftp',
  77: 'rje',
  79: 'finger',
  87: 'link',
  95: 'supdup',
  101: 'hostname',
  102: 'iso-tsap',
  103: 'gppitnp',
  104: 'acr-nema',
  109: 'pop2',
  110: 'pop3',
  111: 's