import { t as apiError } from "./error-CkAseSqZ.mjs";
import { z } from "zod";

//#region src/api/parse.ts
/** Maximum allowed JSON request body size (10 MB). */
const MAX_BODY_SIZE = 10 * 1024 * 1024;
/**
* Parse and validate a JSON request body against a Zod schema.
*
* Returns the validated data on success, or a 400 Response on failure.
* Replaces all `(await request.json()) as T` casts.
*/
async function parseBody(request, schema) {
	const contentLength = request.headers.get("Content-Length");
	if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) return apiError("PAYLOAD_TOO_LARGE", "Request body too large", 413);
	let raw;
	try {
		raw = await request.json();
	} catch {
		return apiError("INVALID_JSON", "Request body must be valid JSON", 400);
	}
	return validate(schema, raw);
}
/**
* Parse and validate an optional JSON request body.
*
* Returns `defaultValue` if the body is empty, or the validated data if present.
* For endpoints where the body is optional (e.g., preview-url, confirm).
*/
async function parseOptionalBody(request, schema, defaultValue) {
	const contentLength = request.headers.get("Content-Length");
	if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) return apiError("PAYLOAD_TOO_LARGE", "Request body too large", 413);
	let text;
	try {
		text = await request.text();
	} catch {
		return defaultValue;
	}
	if (!text.trim()) return defaultValue;
	let raw;
	try {
		raw = JSON.parse(text);
	} catch {
		return apiError("INVALID_JSON", "Request body must be valid JSON", 400);
	}
	return validate(schema, raw);
}
/**
* Parse and validate URL search params against a Zod schema.
*
* Converts searchParams to a plain object before validation.
* Zod coercion handles string -> number/boolean conversion.
* Replaces manual `url.searchParams.get()` + `parseInt()` patterns.
*/
function parseQuery(url, schema) {
	const raw = {};
	for (const [key, value] of url.searchParams) raw[key] = value;
	return validate(schema, raw);
}
/**
* Validate raw data against a schema. Returns data or error Response.
*/
function validate(schema, data) {
	const result = schema.safeParse(data);
	if (result.success) return result.data;
	const issues = result.error.issues.map((issue) => ({
		path: issue.path.join("."),
		message: issue.message
	}));
	return Response.json({ error: {
		code: "VALIDATION_ERROR",
		message: "Invalid request data",
		details: { issues }
	} }, {
		status: 400,
		headers: { "Cache-Control": "private, no-store" }
	});
}
/**
* Type guard to check if a ParseResult is an error Response.
* Usage: `if (isParseError(result)) return result;`
*/
function isParseError(result) {
	return result instanceof Response;
}

//#endregion
export { parseQuery as i, parseBody as n, parseOptionalBody as r, isParseError as t };
//# sourceMappingURL=parse-GmjecGct.mjs.map