| Server IP : 159.203.156.69 / Your IP : 216.73.217.172 Web Server : nginx/1.24.0 System : Linux main-ubuntu 6.8.0-71-generic #71-Ubuntu SMP PREEMPT_DYNAMIC Tue Jul 22 16:52:38 UTC 2025 x86_64 User : root ( 0) PHP Version : 8.3.6 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/tanviranik.com/node_modules/vinext/dist/shims/ |
Upload File : |
import { stripBasePath } from "../utils/base-path.js";
import { getRequestExecutionContext } from "./request-context.js";
import { MIDDLEWARE_NEXT_HEADER, MIDDLEWARE_REWRITE_HEADER, MIDDLEWARE_SET_COOKIE_HEADER } from "../server/headers.js";
import { encodeMiddlewareRequestHeaders } from "../server/middleware-request-headers.js";
import { serializeSetCookie, validateCookieName } from "./internal/cookie-serialize.js";
import { parseCookieHeader } from "./internal/parse-cookie-header.js";
import { assertSafeNavigationUrl } from "./url-safety.js";
//#region src/shims/server.ts
/**
* next/server shim
*
* Provides NextRequest, NextResponse, and related types that work with
* standard Web APIs (Request/Response). This means they work on Node,
* Cloudflare Workers, Deno, and any WinterCG-compatible runtime.
*
* This is a pragmatic subset — we implement the most commonly used APIs
* rather than bug-for-bug parity with Next.js internals.
*/
const _USE_CACHE_ALS_KEY = Symbol.for("vinext.cacheRuntime.contextAls");
const _UNSTABLE_CACHE_ALS_KEY = Symbol.for("vinext.unstableCache.als");
const _g = globalThis;
/**
* Record an invalid dynamic usage error on the request context so it survives
* user try/catch and can be forwarded to the dev overlay on client-side navigations.
*/
function _recordInvalidDynamicUsageError(error) {
try {
const ctx = _g[Symbol.for("vinext.unifiedRequestContext.als")]?.getStore();
if (ctx) ctx.invalidDynamicUsageError = error;
} catch {}
}
function _throwIfInsideCacheScope(apiName) {
if (_g[_USE_CACHE_ALS_KEY]?.getStore() != null) {
const error = /* @__PURE__ */ new Error(`\`${apiName}\` cannot be called inside "use cache". If you need this data inside a cached function, call \`${apiName}\` outside and pass the required data as an argument.`);
_recordInvalidDynamicUsageError(error);
throw error;
}
if (_g[_UNSTABLE_CACHE_ALS_KEY]?.getStore() === true) {
const error = /* @__PURE__ */ new Error(`\`${apiName}\` cannot be called inside a function cached with \`unstable_cache()\`. If you need this data inside a cached function, call \`${apiName}\` outside and pass the required data as an argument.`);
_recordInvalidDynamicUsageError(error);
throw error;
}
}
var NextRequest = class extends Request {
_nextUrl;
_url;
_cookies;
constructor(input, init) {
const { nextConfig: _nextConfig, ...requestInit } = init ?? {};
if (input instanceof Request) {
const requestInput = requestInit.body === void 0 && input.body && !input.bodyUsed ? input.clone() : input;
super(requestInput, requestInit);
} else super(input, requestInit);
const url = typeof input === "string" ? new URL(input, "http://localhost") : input instanceof URL ? input : new URL(input.url, "http://localhost");
const urlConfig = _nextConfig ? {
basePath: _nextConfig.basePath,
nextConfig: { i18n: _nextConfig.i18n }
} : void 0;
this._nextUrl = new NextURL(url, void 0, urlConfig);
this._url = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? url.toString() : this._nextUrl.toString();
this._cookies = new RequestCookies(this.headers);
}
get nextUrl() {
return this._nextUrl;
}
get url() {
return this._url;
}
get cookies() {
return this._cookies;
}
/**
* Client IP address. Prefers Cloudflare's trusted CF-Connecting-IP header
* over the spoofable X-Forwarded-For. Returns undefined if unavailable.
*/
get ip() {
return this.headers.get("cf-connecting-ip") ?? this.headers.get("x-real-ip") ?? this.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? void 0;
}
/**
* Geolocation data. Platform-dependent (e.g., Cloudflare, Vercel).
* Returns undefined if not available.
*/
get geo() {
const country = this.headers.get("cf-ipcountry") ?? this.headers.get("x-vercel-ip-country") ?? void 0;
if (!country) return void 0;
return {
country,
city: this.headers.get("cf-ipcity") ?? this.headers.get("x-vercel-ip-city") ?? void 0,
region: this.headers.get("cf-region") ?? this.headers.get("x-vercel-ip-country-region") ?? void 0,
latitude: this.headers.get("cf-iplatitude") ?? this.headers.get("x-vercel-ip-latitude") ?? void 0,
longitude: this.headers.get("cf-iplongitude") ?? this.headers.get("x-vercel-ip-longitude") ?? void 0
};
}
/**
* The build ID of the Next.js application.
* Delegates to `nextUrl.buildId` to match Next.js API surface.
* Can be used in middleware to detect deployment skew between client and server.
*/
get buildId() {
return this._nextUrl.buildId;
}
};
/** Valid HTTP redirect status codes, matching Next.js's REDIRECTS set. */
const REDIRECT_STATUSES = new Set([
301,
302,
303,
307,
308
]);
function validateURL(url) {
assertSafeNavigationUrl(String(url));
try {
return String(new URL(String(url)));
} catch (error) {
throw new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, { cause: error });
}
}
var NextResponse = class NextResponse extends Response {
_cookies;
constructor(body, init) {
super(body, init);
this._cookies = new MiddlewareResponseCookies(this.headers);
}
get cookies() {
return this._cookies;
}
/**
* Create a JSON response.
*/
static json(body, init) {
const headers = new Headers(init?.headers);
if (!headers.has("content-type")) headers.set("content-type", "application/json");
return new NextResponse(JSON.stringify(body), {
...init,
headers
});
}
/**
* Create a redirect response.
*/
static redirect(url, init) {
const status = typeof init === "number" ? init : init?.status ?? 307;
if (!REDIRECT_STATUSES.has(status)) throw new RangeError(`Failed to execute "redirect" on "response": Invalid status code`);
const headers = new Headers(typeof init === "object" ? init?.headers : void 0);
headers.set("Location", validateURL(url));
return new NextResponse(null, {
status,
headers
});
}
/**
* Create a rewrite response (middleware pattern).
* Sets the x-middleware-rewrite header.
*/
static rewrite(destination, init) {
const headers = new Headers(init?.headers);
headers.set(MIDDLEWARE_REWRITE_HEADER, validateURL(destination));
if (init?.request?.headers) encodeMiddlewareRequestHeaders(headers, init.request.headers);
return new NextResponse(null, {
...init,
headers
});
}
/**
* Continue to the next handler (middleware pattern).
* Sets the x-middleware-next header.
*/
static next(init) {
const headers = new Headers(init?.headers);
headers.set(MIDDLEWARE_NEXT_HEADER, "1");
if (init?.request?.headers) encodeMiddlewareRequestHeaders(headers, init.request.headers);
return new NextResponse(null, {
...init,
headers
});
}
};
var NextURL = class NextURL {
/** Internal URL stores the pathname WITHOUT basePath or locale prefix. */
_url;
_basePath;
_locale;
_defaultLocale;
_locales;
constructor(input, base, config) {
this._url = new URL(input.toString(), base);
this._basePath = config?.basePath ?? "";
this._stripBasePath();
const i18n = config?.nextConfig?.i18n;
if (i18n) {
this._locales = [...i18n.locales];
this._defaultLocale = i18n.defaultLocale;
this._analyzeLocale(this._locales);
}
}
/** Strip basePath prefix from the internal pathname. */
_stripBasePath() {
if (!this._basePath) return;
this._url.pathname = stripBasePath(this._url.pathname, this._basePath);
}
/** Extract locale from pathname, stripping it from the internal URL. */
_analyzeLocale(locales) {
const segments = this._url.pathname.split("/");
const candidate = segments[1]?.toLowerCase();
const match = locales.find((l) => l.toLowerCase() === candidate);
if (match) {
this._locale = match;
this._url.pathname = "/" + segments.slice(2).join("/");
} else this._locale = this._defaultLocale;
}
/**
* Reconstruct the full pathname with basePath + locale prefix.
* Mirrors Next.js's internal formatPathname().
*/
_formatPathname() {
let prefix = this._basePath;
if (this._locale && this._locale !== this._defaultLocale) prefix += "/" + this._locale;
if (!prefix) return this._url.pathname;
const inner = this._url.pathname;
return inner === "/" ? prefix : prefix + inner;
}
get href() {
const formatted = this._formatPathname();
if (formatted === this._url.pathname) return this._url.href;
const { href, pathname, search, hash } = this._url;
const baseEnd = href.length - pathname.length - search.length - hash.length;
return href.slice(0, baseEnd) + formatted + search + hash;
}
set href(value) {
this._url.href = value;
this._stripBasePath();
if (this._locales) this._analyzeLocale(this._locales);
}
get origin() {
return this._url.origin;
}
get protocol() {
return this._url.protocol;
}
set protocol(value) {
this._url.protocol = value;
}
get username() {
return this._url.username;
}
set username(value) {
this._url.username = value;
}
get password() {
return this._url.password;
}
set password(value) {
this._url.password = value;
}
get host() {
return this._url.host;
}
set host(value) {
this._url.host = value;
}
get hostname() {
return this._url.hostname;
}
set hostname(value) {
this._url.hostname = value;
}
get port() {
return this._url.port;
}
set port(value) {
this._url.port = value;
}
/** Returns the pathname WITHOUT basePath or locale prefix. */
get pathname() {
return this._url.pathname;
}
set pathname(value) {
this._url.pathname = value;
}
get search() {
return this._url.search;
}
set search(value) {
this._url.search = value;
}
get searchParams() {
return this._url.searchParams;
}
get hash() {
return this._url.hash;
}
set hash(value) {
this._url.hash = value;
}
get basePath() {
return this._basePath;
}
set basePath(value) {
this._basePath = value === "" ? "" : value.startsWith("/") ? value : "/" + value;
}
get locale() {
return this._locale ?? "";
}
set locale(value) {
if (this._locales) {
if (!value) {
this._locale = this._defaultLocale;
return;
}
if (!this._locales.includes(value)) throw new TypeError(`The locale "${value}" is not in the configured locales: ${this._locales.join(", ")}`);
}
this._locale = this._locales ? value : this._locale;
}
get defaultLocale() {
return this._defaultLocale;
}
get locales() {
return this._locales ? [...this._locales] : void 0;
}
clone() {
const config = {
basePath: this._basePath,
nextConfig: this._locales ? { i18n: {
locales: [...this._locales],
defaultLocale: this._defaultLocale
} } : void 0
};
return new NextURL(this.href, void 0, config);
}
toString() {
return this.href;
}
/**
* The build ID of the Next.js application.
* Set from `generateBuildId` in next.config.js, or a random UUID if not configured.
* Can be used in middleware to detect deployment skew between client and server.
* Matches the Next.js API: `request.nextUrl.buildId`.
*/
get buildId() {
return process.env.__VINEXT_BUILD_ID ?? void 0;
}
};
var RequestCookies = class {
_headers;
_parsed;
constructor(headers) {
this._headers = headers;
this._parsed = parseCookieHeader(headers.get("cookie") ?? "");
}
get(name) {
const value = this._parsed.get(name);
return value !== void 0 ? {
name,
value
} : void 0;
}
getAll(nameOrOptions) {
const name = typeof nameOrOptions === "string" ? nameOrOptions : nameOrOptions?.name;
return [...this._parsed.entries()].filter(([cookieName]) => name === void 0 || cookieName === name).map(([cookieName, value]) => ({
name: cookieName,
value
}));
}
has(name) {
return this._parsed.has(name);
}
set(nameOrOptions, value) {
let cookieName;
let cookieValue;
if (typeof nameOrOptions === "string") {
cookieName = nameOrOptions;
cookieValue = value ?? "";
} else {
cookieName = nameOrOptions.name;
cookieValue = nameOrOptions.value;
}
validateCookieName(cookieName);
this._parsed.set(cookieName, cookieValue);
this._syncHeader();
return this;
}
delete(names) {
if (Array.isArray(names)) {
const results = names.map((name) => {
validateCookieName(name);
return this._parsed.delete(name);
});
this._syncHeader();
return results;
}
validateCookieName(names);
const result = this._parsed.delete(names);
this._syncHeader();
return result;
}
clear() {
this._parsed.clear();
this._syncHeader();
return this;
}
get size() {
return this._parsed.size;
}
toString() {
return this._serialize();
}
_serialize() {
return [...this._parsed.entries()].map(([n, v]) => `${n}=${encodeURIComponent(v)}`).join("; ");
}
_syncHeader() {
if (this._parsed.size === 0) this._headers.delete("cookie");
else this._headers.set("cookie", this._serialize());
}
[Symbol.iterator]() {
return this.getAll().map((c) => [c.name, c])[Symbol.iterator]();
}
};
var ReadonlyRequestCookiesError = class ReadonlyRequestCookiesError extends Error {
constructor() {
super("Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options");
}
static callable() {
throw new ReadonlyRequestCookiesError();
}
};
const REQUEST_HEADERS_MUTATING_METHODS = new Set([
"set",
"delete",
"append"
]);
var ReadonlyRequestHeadersError = class ReadonlyRequestHeadersError extends Error {
constructor() {
super("Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers");
}
static callable() {
throw new ReadonlyRequestHeadersError();
}
};
function sealRequestHeaders(headers) {
return new Proxy(headers, { get(target, prop) {
if (typeof prop === "string" && REQUEST_HEADERS_MUTATING_METHODS.has(prop)) return ReadonlyRequestHeadersError.callable;
const value = Reflect.get(target, prop, target);
return typeof value === "function" ? value.bind(target) : value;
} });
}
function sealRequestCookies(cookies) {
return new Proxy(cookies, { get(target, prop) {
if (prop === "set" || prop === "delete" || prop === "clear") return ReadonlyRequestCookiesError.callable;
const value = Reflect.get(target, prop, target);
return typeof value === "function" ? value.bind(target) : value;
} });
}
var ResponseCookies = class {
_headers;
/** Internal map keyed by cookie name — single source of truth. */
_parsed = /* @__PURE__ */ new Map();
constructor(headers) {
this._headers = headers;
for (const header of headers.getSetCookie()) {
const eq = header.indexOf("=");
if (eq === -1) continue;
const cookieName = header.slice(0, eq);
const semi = header.indexOf(";", eq);
const raw = header.slice(eq + 1, semi === -1 ? void 0 : semi);
let value;
try {
value = decodeURIComponent(raw);
} catch {
value = raw;
}
this._parsed.set(cookieName, {
serialized: header,
entry: {
name: cookieName,
value
}
});
}
}
set(...args) {
const [name, value, opts] = parseCookieSetArgs(args);
validateCookieName(name);
const serialized = serializeSetCookie(name, value, opts);
this._parsed.set(name, {
serialized,
entry: {
name,
value
}
});
this._syncHeaders();
return this;
}
get(...args) {
const key = typeof args[0] === "string" ? args[0] : args[0].name;
return this._parsed.get(key)?.entry;
}
has(name) {
return this._parsed.has(name);
}
getAll(...args) {
const all = [...this._parsed.values()].map((v) => v.entry);
if (args.length === 0) return all;
const key = typeof args[0] === "string" ? args[0] : args[0].name;
return all.filter((c) => c.name === key);
}
delete(...args) {
const [name, opts] = typeof args[0] === "string" ? [args[0], void 0] : [args[0].name, args[0]];
return this.set({
name,
value: "",
expires: /* @__PURE__ */ new Date(0),
path: opts?.path,
domain: opts?.domain,
httpOnly: opts?.httpOnly,
secure: opts?.secure,
sameSite: opts?.sameSite
});
}
[Symbol.iterator]() {
return [...this._parsed.values()].map((v) => [v.entry.name, v.entry])[Symbol.iterator]();
}
/** Delete all Set-Cookie headers and re-append from the internal map. */
_syncHeaders() {
this._headers.delete("Set-Cookie");
for (const { serialized } of this._parsed.values()) this._headers.append("Set-Cookie", serialized);
}
};
var MiddlewareResponseCookies = class extends ResponseCookies {
_responseHeaders;
constructor(headers) {
super(headers);
this._responseHeaders = headers;
}
set(...args) {
super.set(...args);
this._syncMiddlewareCookieHeader();
return this;
}
delete(...args) {
super.delete(...args);
this._syncMiddlewareCookieHeader();
return this;
}
_syncMiddlewareCookieHeader() {
const cookies = this._responseHeaders.getSetCookie();
if (cookies.length === 0) {
this._responseHeaders.delete(MIDDLEWARE_SET_COOKIE_HEADER);
return;
}
this._responseHeaders.set(MIDDLEWARE_SET_COOKIE_HEADER, cookies.join(","));
}
};
/**
* Parse the overloaded arguments for ResponseCookies.set():
* - (name, value, options?) — positional form
* - ({ name, value, ...options }) — object form
*/
function parseCookieSetArgs(args) {
if (typeof args[0] === "string") return [
args[0],
args[1],
args[2]
];
const { name, value, ...opts } = args[0];
return [
name,
value,
opts
];
}
/**
* Minimal NextFetchEvent — extends FetchEvent where available,
* otherwise provides the waitUntil pattern standalone.
*/
var NextFetchEvent = class {
sourcePage;
_waitUntilPromises = [];
constructor(params) {
this.sourcePage = params.page;
}
waitUntil(promise) {
this._waitUntilPromises.push(promise);
}
get waitUntilPromises() {
return this._waitUntilPromises;
}
/** Drain all waitUntil promises. Returns a single promise that settles when all are done. */
drainWaitUntil() {
return Promise.allSettled(this._waitUntilPromises);
}
};
/**
* Parse user agent string. Minimal implementation — for full UA parsing,
* apps should use a dedicated library like `ua-parser-js`.
*/
function userAgentFromString(ua) {
const input = ua ?? "";
return {
isBot: /bot|crawler|spider|crawling/i.test(input),
ua: input,
browser: {},
device: {},
engine: {},
os: {},
cpu: {}
};
}
function userAgent({ headers }) {
return userAgentFromString(headers.get("user-agent") ?? void 0);
}
/**
* after() — schedule work after the response is sent.
*
* Uses the platform's `waitUntil` (via the per-request ExecutionContext) when
* available so the task survives past the response on Cloudflare Workers.
* Falls back to a fire-and-forget microtask on runtimes without an execution
* context (e.g. Node.js dev server).
*
* Throws when called inside a cached scope — request-specific
* side-effects must not leak into cached results.
*/
function after(task) {
_throwIfInsideCacheScope("after()");
const guarded = (typeof task === "function" ? Promise.resolve().then(task) : task).catch((err) => {
console.error("[vinext] after() task failed:", err);
});
getRequestExecutionContext()?.waitUntil(guarded);
}
/**
* connection() — signals that the response requires a live connection
* (not a static/cached response). Opts the page out of ISR caching
* and sets Cache-Control: no-store on the response.
*/
async function connection() {
const { markDynamicUsage, throwIfInsideCacheScope } = await import("./headers.js");
throwIfInsideCacheScope("connection()");
markDynamicUsage();
}
/**
* URLPattern re-export — used in middleware for route matching.
* Available natively in Node 20+, Cloudflare Workers, Deno.
* Falls back to urlpattern-polyfill if the global is not available.
*/
const URLPattern = globalThis.URLPattern ?? (() => {
throw new Error("URLPattern is not available in this runtime. Install the `urlpattern-polyfill` package or upgrade to Node 20+.");
});
//#endregion
export { NextFetchEvent, NextRequest, NextResponse, NextURL, RequestCookies, ResponseCookies, URLPattern, after, connection, sealRequestCookies, sealRequestHeaders, userAgent, userAgentFromString };
//# sourceMappingURL=server.js.map