UNPKG

@wooksjs/event-http

Version:
1,576 lines 50.9 kB
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
	if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
		key = keys[i];
		if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
			get: ((k) => from[k]).bind(null, key),
			enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
		});
	}
	return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
	value: mod,
	enumerable: true
}) : target, mod));

//#endregion
const __wooksjs_event_core = __toESM(require("@wooksjs/event-core"));
const buffer = __toESM(require("buffer"));
const node_stream = __toESM(require("node:stream"));
const node_util = __toESM(require("node:util"));
const node_zlib = __toESM(require("node:zlib"));
const url = __toESM(require("url"));
const http = __toESM(require("http"));
const wooks = __toESM(require("wooks"));
const stream = __toESM(require("stream"));

//#region packages/event-http/src/event-http.ts
function createHttpContext(data, options) {
	return (0, __wooksjs_event_core.createAsyncEventContext)({
		event: {
			...data,
			type: "HTTP"
		},
		options
	});
}
/**
* Wrapper on useEventContext with HTTP event types
* @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
*/
function useHttpContext() {
	return (0, __wooksjs_event_core.useAsyncEventContext)("HTTP");
}

//#endregion
//#region packages/event-http/src/utils/helpers.ts
function escapeRegex(s) {
	return s.replace(/[$()*+\-./?[\\\]^{|}]/gu, "\\$&");
}
function safeDecode(f, v) {
	try {
		return f(v);
	} catch (error) {
		return v;
	}
}
function safeDecodeURIComponent(uri) {
	if (!uri.includes("%")) return uri;
	return safeDecode(decodeURIComponent, uri);
}

//#endregion
//#region packages/event-http/src/utils/time.ts
function convertTime(time, unit = "ms") {
	if (typeof time === "number") return time / units[unit];
	const rg = /(\d+)(\w+)/gu;
	let t = 0;
	let r;
	while (r = rg.exec(time)) t += Number(r[1]) * (units[r[2]] || 0);
	return t / units[unit];
}
const units = {
	ms: 1,
	s: 1e3,
	m: 1e3 * 60,
	h: 1e3 * 60 * 60,
	d: 1e3 * 60 * 60 * 24,
	w: 1e3 * 60 * 60 * 24 * 7,
	M: 1e3 * 60 * 60 * 24 * 30,
	Y: 1e3 * 60 * 60 * 24 * 365
};

//#endregion
//#region packages/event-http/src/utils/set-cookie.ts
function renderCookie(key, data) {
	let attrs = "";
	for (const [a, v] of Object.entries(data.attrs)) {
		const func = cookieAttrFunc[a];
		if (typeof func === "function") {
			const val = func(v);
			attrs += val ? `; ${val}` : "";
		} else throw new TypeError(`Unknown Set-Cookie attribute ${a}`);
	}
	return `${key}=${encodeURIComponent(data.value)}${attrs}`;
}
const cookieAttrFunc = {
	expires: (v) => `Expires=${typeof v === "string" || typeof v === "number" ? new Date(v).toUTCString() : v.toUTCString()}`,
	maxAge: (v) => `Max-Age=${convertTime(v, "s").toString()}`,
	domain: (v) => `Domain=${v}`,
	path: (v) => `Path=${v}`,
	secure: (v) => v ? "Secure" : "",
	httpOnly: (v) => v ? "HttpOnly" : "",
	sameSite: (v) => v ? `SameSite=${typeof v === "string" ? v : "Strict"}` : ""
};

//#endregion
//#region packages/event-http/src/compressor/body-compressor.ts
const compressors = { identity: {
	compress: (v) => v,
	uncompress: (v) => v,
	stream: {
		compress: (data) => data,
		uncompress: (data) => data
	}
} };
function encodingSupportsStream(encodings) {
	return encodings.every((enc) => compressors[enc]?.stream);
}
async function uncompressBody(encodings, compressed) {
	let buf = compressed;
	for (const enc of encodings.slice().reverse()) {
		const c = compressors[enc];
		if (!c) throw new Error(`Unsupported compression type "${enc}".`);
		buf = await c.uncompress(buf);
	}
	return buf;
}
async function uncompressBodyStream(encodings, src) {
	if (!encodingSupportsStream(encodings)) throw new Error("Some encodings lack a streaming decompressor");
	let out = src;
	for (const enc of Array.from(encodings).reverse()) out = await compressors[enc].stream.uncompress(out);
	return out;
}

//#endregion
//#region packages/event-http/src/compressor/zlib-compressors.ts
const pipeline = node_stream.pipeline;
function iterableToReadable(src) {
	return node_stream.Readable.from(src, { objectMode: false });
}
function pump(src, transform) {
	pipeline(iterableToReadable(src), transform, (err) => {
		if (err) transform.destroy(err);
	});
	return transform;
}
function addStreamCodec(name, createDeflater, createInflater) {
	const c = compressors[name] ?? (compressors[name] = {
		compress: (v) => v,
		uncompress: (v) => v
	});
	c.stream = {
		compress: async (src) => pump(src, createDeflater()),
		uncompress: async (src) => pump(src, createInflater())
	};
}
addStreamCodec("gzip", node_zlib.createGzip, node_zlib.createGunzip);
addStreamCodec("deflate", node_zlib.createDeflate, node_zlib.createInflate);
addStreamCodec("br", node_zlib.createBrotliCompress, node_zlib.createBrotliDecompress);
let zp;
async function zlib() {
	if (!zp) {
		const { gzip, gunzip, deflate, inflate, brotliCompress, brotliDecompress } = await import("node:zlib");
		zp = {
			gzip: (0, node_util.promisify)(gzip),
			gunzip: (0, node_util.promisify)(gunzip),
			deflate: (0, node_util.promisify)(deflate),
			inflate: (0, node_util.promisify)(inflate),
			brotliCompress: (0, node_util.promisify)(brotliCompress),
			brotliDecompress: (0, node_util.promisify)(brotliDecompress)
		};
	}
	return zp;
}
compressors.gzip.compress = async (b) => (await zlib()).gzip(b);
compressors.gzip.uncompress = async (b) => (await zlib()).gunzip(b);
compressors.deflate.compress = async (b) => (await zlib()).deflate(b);
compressors.deflate.uncompress = async (b) => (await zlib()).inflate(b);
compressors.br.compress = async (b) => (await zlib()).brotliCompress(b);
compressors.br.uncompress = async (b) => (await zlib()).brotliDecompress(b);

//#endregion
//#region packages/event-http/src/response/renderer.ts
var BaseHttpResponseRenderer = class {
	render(response) {
		if (typeof response.body === "string" || typeof response.body === "boolean" || typeof response.body === "number") {
			if (!response.getContentType()) response.setContentType("text/plain");
			return response.body.toString();
		}
		if (response.body === void 0) return "";
		if (response.body instanceof Uint8Array) return response.body;
		if (typeof response.body === "object") {
			if (!response.getContentType()) response.setContentType("application/json");
			return JSON.stringify(response.body);
		}
		throw new Error(`Unsupported body format "${typeof response.body}"`);
	}
};

//#endregion
//#region packages/event-http/src/utils/status-codes.ts
const httpStatusCodes = {
	100: "Continue",
	101: "Switching protocols",
	102: "Processing",
	103: "Early Hints",
	200: "OK",
	201: "Created",
	202: "Accepted",
	203: "Non-Authoritative Information",
	204: "No Content",
	205: "Reset Content",
	206: "Partial Content",
	207: "Multi-Status",
	208: "Already Reported",
	226: "IM Used",
	300: "Multiple Choices",
	301: "Moved Permanently",
	302: "Found (Previously \"Moved Temporarily\")",
	303: "See Other",
	304: "Not Modified",
	305: "Use Proxy",
	306: "Switch Proxy",
	307: "Temporary Redirect",
	308: "Permanent Redirect",
	400: "Bad Request",
	401: "Unauthorized",
	402: "Payment Required",
	403: "Forbidden",
	404: "Not Found",
	405: "Method Not Allowed",
	406: "Not Acceptable",
	407: "Proxy Authentication Required",
	408: "Request Timeout",
	409: "Conflict",
	410: "Gone",
	411: "Length Required",
	412: "Precondition Failed",
	413: "Payload Too Large",
	414: "URI Too Long",
	415: "Unsupported Media Type",
	416: "Range Not Satisfiable",
	417: "Expectation Failed",
	418: "I'm a Teapot",
	421: "Misdirected Request",
	422: "Unprocessable Entity",
	423: "Locked",
	424: "Failed Dependency",
	425: "Too Early",
	426: "Upgrade Required",
	428: "Precondition Required",
	429: "Too Many Requests",
	431: "Request Header Fields Too Large",
	451: "Unavailable For Legal Reasons",
	500: "Internal Server Error",
	501: "Not Implemented",
	502: "Bad Gateway",
	503: "Service Unavailable",
	504: "Gateway Timeout",
	505: "HTTP Version Not Supported",
	506: "Variant Also Negotiates",
	507: "Insufficient Storage",
	508: "Loop Detected",
	510: "Not Extended",
	511: "Network Authentication Required"
};
let EHttpStatusCode = /* @__PURE__ */ function(EHttpStatusCode$1) {
	EHttpStatusCode$1[EHttpStatusCode$1["Continue"] = 100] = "Continue";
	EHttpStatusCode$1[EHttpStatusCode$1["SwitchingProtocols"] = 101] = "SwitchingProtocols";
	EHttpStatusCode$1[EHttpStatusCode$1["Processing"] = 102] = "Processing";
	EHttpStatusCode$1[EHttpStatusCode$1["EarlyHints"] = 103] = "EarlyHints";
	EHttpStatusCode$1[EHttpStatusCode$1["OK"] = 200] = "OK";
	EHttpStatusCode$1[EHttpStatusCode$1["Created"] = 201] = "Created";
	EHttpStatusCode$1[EHttpStatusCode$1["Accepted"] = 202] = "Accepted";
	EHttpStatusCode$1[EHttpStatusCode$1["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
	EHttpStatusCode$1[EHttpStatusCode$1["NoContent"] = 204] = "NoContent";
	EHttpStatusCode$1[EHttpStatusCode$1["ResetContent"] = 205] = "ResetContent";
	EHttpStatusCode$1[EHttpStatusCode$1["PartialContent"] = 206] = "PartialContent";
	EHttpStatusCode$1[EHttpStatusCode$1["MultiStatus"] = 207] = "MultiStatus";
	EHttpStatusCode$1[EHttpStatusCode$1["AlreadyReported"] = 208] = "AlreadyReported";
	EHttpStatusCode$1[EHttpStatusCode$1["IMUsed"] = 226] = "IMUsed";
	EHttpStatusCode$1[EHttpStatusCode$1["MultipleChoices"] = 300] = "MultipleChoices";
	EHttpStatusCode$1[EHttpStatusCode$1["MovedPermanently"] = 301] = "MovedPermanently";
	EHttpStatusCode$1[EHttpStatusCode$1["Found"] = 302] = "Found";
	EHttpStatusCode$1[EHttpStatusCode$1["SeeOther"] = 303] = "SeeOther";
	EHttpStatusCode$1[EHttpStatusCode$1["NotModified"] = 304] = "NotModified";
	EHttpStatusCode$1[EHttpStatusCode$1["UseProxy"] = 305] = "UseProxy";
	EHttpStatusCode$1[EHttpStatusCode$1["SwitchProxy"] = 306] = "SwitchProxy";
	EHttpStatusCode$1[EHttpStatusCode$1["TemporaryRedirect"] = 307] = "TemporaryRedirect";
	EHttpStatusCode$1[EHttpStatusCode$1["PermanentRedirect"] = 308] = "PermanentRedirect";
	EHttpStatusCode$1[EHttpStatusCode$1["BadRequest"] = 400] = "BadRequest";
	EHttpStatusCode$1[EHttpStatusCode$1["Unauthorized"] = 401] = "Unauthorized";
	EHttpStatusCode$1[EHttpStatusCode$1["PaymentRequired"] = 402] = "PaymentRequired";
	EHttpStatusCode$1[EHttpStatusCode$1["Forbidden"] = 403] = "Forbidden";
	EHttpStatusCode$1[EHttpStatusCode$1["NotFound"] = 404] = "NotFound";
	EHttpStatusCode$1[EHttpStatusCode$1["MethodNotAllowed"] = 405] = "MethodNotAllowed";
	EHttpStatusCode$1[EHttpStatusCode$1["NotAcceptable"] = 406] = "NotAcceptable";
	EHttpStatusCode$1[EHttpStatusCode$1["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
	EHttpStatusCode$1[EHttpStatusCode$1["RequestTimeout"] = 408] = "RequestTimeout";
	EHttpStatusCode$1[EHttpStatusCode$1["Conflict"] = 409] = "Conflict";
	EHttpStatusCode$1[EHttpStatusCode$1["Gone"] = 410] = "Gone";
	EHttpStatusCode$1[EHttpStatusCode$1["LengthRequired"] = 411] = "LengthRequired";
	EHttpStatusCode$1[EHttpStatusCode$1["PreconditionFailed"] = 412] = "PreconditionFailed";
	EHttpStatusCode$1[EHttpStatusCode$1["PayloadTooLarge"] = 413] = "PayloadTooLarge";
	EHttpStatusCode$1[EHttpStatusCode$1["URITooLong"] = 414] = "URITooLong";
	EHttpStatusCode$1[EHttpStatusCode$1["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
	EHttpStatusCode$1[EHttpStatusCode$1["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
	EHttpStatusCode$1[EHttpStatusCode$1["ExpectationFailed"] = 417] = "ExpectationFailed";
	EHttpStatusCode$1[EHttpStatusCode$1["ImATeapot"] = 418] = "ImATeapot";
	EHttpStatusCode$1[EHttpStatusCode$1["MisdirectedRequest"] = 421] = "MisdirectedRequest";
	EHttpStatusCode$1[EHttpStatusCode$1["UnprocessableEntity"] = 422] = "UnprocessableEntity";
	EHttpStatusCode$1[EHttpStatusCode$1["Locked"] = 423] = "Locked";
	EHttpStatusCode$1[EHttpStatusCode$1["FailedDependency"] = 424] = "FailedDependency";
	EHttpStatusCode$1[EHttpStatusCode$1["TooEarly"] = 425] = "TooEarly";
	EHttpStatusCode$1[EHttpStatusCode$1["UpgradeRequired"] = 426] = "UpgradeRequired";
	EHttpStatusCode$1[EHttpStatusCode$1["PreconditionRequired"] = 428] = "PreconditionRequired";
	EHttpStatusCode$1[EHttpStatusCode$1["TooManyRequests"] = 429] = "TooManyRequests";
	EHttpStatusCode$1[EHttpStatusCode$1["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
	EHttpStatusCode$1[EHttpStatusCode$1["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
	EHttpStatusCode$1[EHttpStatusCode$1["InternalServerError"] = 500] = "InternalServerError";
	EHttpStatusCode$1[EHttpStatusCode$1["NotImplemented"] = 501] = "NotImplemented";
	EHttpStatusCode$1[EHttpStatusCode$1["BadGateway"] = 502] = "BadGateway";
	EHttpStatusCode$1[EHttpStatusCode$1["ServiceUnavailable"] = 503] = "ServiceUnavailable";
	EHttpStatusCode$1[EHttpStatusCode$1["GatewayTimeout"] = 504] = "GatewayTimeout";
	EHttpStatusCode$1[EHttpStatusCode$1["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
	EHttpStatusCode$1[EHttpStatusCode$1["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
	EHttpStatusCode$1[EHttpStatusCode$1["InsufficientStorage"] = 507] = "InsufficientStorage";
	EHttpStatusCode$1[EHttpStatusCode$1["LoopDetected"] = 508] = "LoopDetected";
	EHttpStatusCode$1[EHttpStatusCode$1["NotExtended"] = 510] = "NotExtended";
	EHttpStatusCode$1[EHttpStatusCode$1["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
	return EHttpStatusCode$1;
}({});

//#endregion
//#region packages/event-http/src/errors/403.tl.svg
function _403_tl_default(ctx) {
	return `<svg height="64" viewBox="0 4 100 96" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#888888" stroke-width="2">
  <path d="M50 90.625C64.4042 87.1875 83.5751 69.8667 83.5751 48.6937V24.0854L50 9.375L16.425 24.0833V48.6937C16.425 69.8667 35.5959 87.1875 50 90.625Z" fill="#ff000050">
    <animate attributeName="fill" dur="2s" repeatCount="indefinite"
             values="#ff000000;#ff000050;#ff000000" />
  </path>

  <path d="M61.5395 46.0812H38.4604C37.1061 46.0812 36.0083 47.1791 36.0083 48.5333V65.075C36.0083 66.4292 37.1061 67.5271 38.4604 67.5271H61.5395C62.8938 67.5271 63.9916 66.4292 63.9916 65.075V48.5333C63.9916 47.1791 62.8938 46.0812 61.5395 46.0812Z" />

  <path d="M41.7834 46.0834V39.6813C41.7834 37.5021 42.6491 35.4121 44.1901 33.8712C45.731 32.3303 47.8209 31.4646 50.0001 31.4646C52.1793 31.4646 54.2693 32.3303 55.8102 33.8712C57.3511 35.4121 58.2168 37.5021 58.2168 39.6813V46.0813" />
</svg>
`;
}

//#endregion
//#region packages/event-http/src/errors/404.tl.svg
function _404_tl_default(ctx) {
	return `<svg height="64" viewBox="0 20 100 64" fill="none" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <path id="sheet" d="M86.5 36.5V47.5H97.5V92.5H52.5V36.5H86.5ZM63 68.5H87V67.5H63V68.5ZM63 63.5H87V62.5H63V63.5ZM63 58.5H87V57.5H63V58.5ZM96.793 46.5H87.5V37.207L96.793 46.5Z" fill="#88888833" stroke="#888888aa"/>
  </defs>

  <g id="queue" transform="translate(-5 -10)">
    <use href="#sheet" opacity="0">
      <animateTransform attributeName="transform" type="translate"
                        dur="3s" repeatCount="indefinite"
                        keyTimes="0;0.1;0.32;0.42;1"
                        values="30 0; -20 0; -20 0; -70 0; -70 0" />
      <animate attributeName="opacity"
               dur="3s" repeatCount="indefinite"
                        keyTimes="0;0.1;0.32;0.42;1"
               values="0;1;1;0;0" />
    </use>

    <use href="#sheet" opacity="0">
      <animateTransform attributeName="transform" type="translate"
                        dur="3s" begin="1s" repeatCount="indefinite"
                        keyTimes="0;0.1;0.32;0.42;1"
                        values="30 0; -20 0; -20 0; -70 0; -70 0" />
      <animate attributeName="opacity"
               dur="3s" begin="1s" repeatCount="indefinite"
                        keyTimes="0;0.1;0.32;0.42;1"
               values="0;1;1;0;0" />
    </use>

    <use href="#sheet" opacity="0">
      <animateTransform attributeName="transform" type="translate"
                        dur="3s" begin="2s" repeatCount="indefinite"
                        keyTimes="0;0.1;0.32;0.42;1"
                        values="30 0; -20 0; -20 0; -70 0; -70 0" />
      <animate attributeName="opacity"
               dur="3s" begin="2s" repeatCount="indefinite"
                        keyTimes="0;0.1;0.32;0.42;1"
               values="0;1;1;0;0" />
    </use>
  </g>

  <g>
    <path d="M49.5 32.5C58.3366 32.5 65.5 39.6634 65.5 48.5C65.5 54.4781 62.222 59.6923 57.3584 62.4404C55.0386 63.7512 52.3591 64.5 49.5 64.5C40.6634 64.5 33.5 57.3366 33.5 48.5C33.5 39.6634 40.6634 32.5 49.5 32.5Z" fill="#ffffff50" stroke="#888888" stroke-width="3"/>

    <path d="M62.7101 74.5691C63.117 75.2907 64.0318 75.5459 64.7534 75.139C65.4751 74.7321 65.7302 73.8173 65.3233 73.0957L62.7101 74.5691ZM58.05 63.25L56.7434 63.9867L62.7101 74.5691L64.0167 73.8324L65.3233 73.0957L59.3567 62.5133L58.05 63.25Z" fill="#888888"/>
  </g>
</svg>

`;
}

//#endregion
//#region packages/event-http/src/errors/500.tl.svg
function _500_tl_default(ctx) {
	return `<svg  height="64" viewBox="0 0 120 100" xmlns="http://www.w3.org/2000/svg">

  <g id="server">

<g fill="#88888888" stroke="#88888888" stroke-width="2" >
<path d="M18 90C13.5817 90 10 86.4182 10 82V38C10 33.5817 13.5817 30 18 30H50.5L58 43L52.5 53L56 68.5L49.0098 89.97L61.2141 71.4358L58.363 54.315L64.7769 43.5511L58.2763 30.2943L104.243 32.0434C108.658 32.2114 112.101 35.9267 111.933 40.3418L110.26 84.31C110.092 88.725 106.377 92.168 101.962 92L49 90H18Z" />
</g>
    <circle cx="30" cy="60" r="6" fill="red">
      <animate attributeName="fill" dur="0.8s"
               values="red;#2d0000;red" repeatCount="indefinite"/>
    </circle>

  </g>

  <g fill="lightgray" opacity="0.75">
    <circle cx="50" cy="35" r="6">
      <animate attributeName="cy" from="35" to="15" dur="2s"
               repeatCount="indefinite"/>
      <animate attributeName="opacity" values="0.75;0" dur="2s"
               repeatCount="indefinite"/>
    </circle>
    <circle cx="60" cy="40" r="4">
      <animate attributeName="cy" from="40" to="20" dur="2s"
               begin="0.4s" repeatCount="indefinite"/>
      <animate attributeName="opacity" values="0.75;0" dur="2s"
               begin="0.4s" repeatCount="indefinite"/>
    </circle>
  </g>

</svg>
`;
}

//#endregion
//#region packages/event-http/src/errors/error.tl.html
function error_tl_default(ctx) {
	const { statusCode, statusMessage, icon, message, details, link, image, version } = ctx;
	return `<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>${statusCode} ${statusMessage}</title>
    <style>
      body {
        font-family: -apple-system, BlinkMacMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
          Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        display: flex;
        justify-content: center;
        align-items: flex-start;
        min-height: 100vh;
        margin: 0;
        padding: 0 20px;
        box-sizing: border-box;
        transition:
          background-color 0.3s ease,
          color 0.3s ease;
      }

      .error-container {
        padding: 48px;
        padding-bottom: 12px !important;
        background-color: #ffffff;
        border-radius: 0 0 12px 12px;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
        text-align: center;
        max-width: 650px;
        width: 100%;
        transition:
          background-color 0.3s ease,
          border-color 0.3s ease,
          box-shadow 0.3s ease;
      }

      .status-code {
        font-size: 5rem;
        font-weight: 900;
        margin-bottom: 5px;
        line-height: 1;
        transition: color 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
        position: relative;
        margin-right: 24px;
      }

      .status-text {
        font-size: 2.25rem;
        font-weight: 700;
        margin-bottom: 25px;
        transition: color 0.3s ease;
      }

      .error-message {
        font-size: 1.25rem;
        margin-bottom: 40px;
        line-height: 1.7;
        transition: color 0.3s ease;
      }

      .json-details-container {
        padding: 20px;
        border-radius: 8px;
        text-align: left;
        overflow-x: auto;
        font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
        font-size: 0.9rem;
        border: 1px solid;
        transition:
          background-color 0.3s ease,
          color 0.3s ease,
          border-color 0.3s ease;
      }

      .json-details-container pre {
        margin: 0;
        white-space: pre-wrap;
        word-break: break-all;
      }

      .json-details-container code {
        display: block;
      }

      body {
        background-color: #f8fafc;
        color: #1f2937;
      }
      .error-container {
        background-color: #ffffff;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
      }
      .status-code {
        color: #dc2626;
      }
      .status-text {
        color: #1f2937;
      }
      .error-message {
        color: #4b5563;
      }
      .json-details-container {
        background-color: #f0f4f8;
        color: #374151;
        border-color: #d1d5db;
      }
      .json-details-container p {
        color: #6b7280;
      }

      @media (prefers-color-scheme: dark) {
        body {
          background-color: #2d3748;
          color: #e2e8f0;
        }
        .error-container {
          background-color: #1a202c;
          box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
        }
        .status-code {
          color: #f56565;
        }
        .status-text {
          color: #cbd5e1;
        }
        .error-message {
          color: #a0aec0;
        }
        .json-details-container {
          background-color: #2d3748;
          color: #e2e8f0;
          border-color: #4a5568;
        }
        .json-details-container p {
          color: #a0aec0;
        }
      }

      .footer {
        display: flex;
        gap: 0.25rem;
        font-size: 0.6em;
        justify-content: flex-end;
        align-items: center;
        margin-top: 12px;
        opacity: 0.5;
        transition: 0.25s ease-in-out;
      }

      .footer img {
        filter: grayscale(0.5);
        transition: 0.25s ease-in-out;
      }

      .footer:hover {
        opacity: 1;
      }
      .footer:hover img {
        filter: grayscale(0);
      }

      @media (max-width: 768px) {
        body {
          padding: 15px;
        }
        .error-container {
          padding: 32px;
        }
        .status-code {
          font-size: 4rem;
        }
        .status-text {
          font-size: 1.8rem;
        }
        .error-message {
          font-size: 1.1rem;
          margin-bottom: 30px;
        }
        .json-details-container {
          font-size: 0.85rem;
        }
      }

      @media (max-width: 480px) {
        body {
          padding: 10px;
        }
        .error-container {
          padding: 24px;
          border-radius: 8px;
        }
        .status-code {
          font-size: 3rem;
        }
        .status-text {
          font-size: 1.5rem;
          margin-bottom: 20px;
        }
        .error-message {
          font-size: 1rem;
          margin-bottom: 25px;
        }
        .json-details-container {
          padding: 15px;
          font-size: 0.8rem;
        }
      }
    </style>
  </head>
  <body>
    <div class="error-container">
      <div id="statusCode" class="status-code">${icon} ${statusCode}</div>

      <div id="statusText" class="status-text">${statusMessage}</div>

      <p id="errorMessage" class="error-message">${message}</p>

      <!-- prettier-ignore -->
      <div class="json-details-container"style="display: ${details ? "block" : "none"};">
        <p class="text-sm">Technical Details:</p>
        <pre><code id="jsonDetails">${details}</code></pre>
      </div>
      <div class="footer">
        Powered by
        <a href="${link}" target="_blank">
          <img height="20" alt="%{poweredBy}" src="${image}" />
        </a>
        v${version}
      </div>
    </div>
  </body>
</html>
`;
}

//#endregion
//#region packages/event-http/src/errors/error-renderer.ts
let framework = {
	version: "0.6.1",
	poweredBy: `wooksjs`,
	link: `https://wooks.moost.org/`,
	image: `https://wooks.moost.org/wooks-full-logo.png`
};
var HttpErrorRenderer = class extends BaseHttpResponseRenderer {
	constructor(opts) {
		super();
		this.opts = opts;
	}
	icons = {
		401: typeof _403_tl_default === "function" ? _403_tl_default({}) : "",
		403: typeof _403_tl_default === "function" ? _403_tl_default({}) : "",
		404: typeof _404_tl_default === "function" ? _404_tl_default({}) : "",
		500: typeof _500_tl_default === "function" ? _500_tl_default({}) : ""
	};
	static registerFramework(opts) {
		framework = opts;
	}
	renderHtml(response) {
		const data = response.body || {};
		response.setContentType("text/html");
		const hasDetails = Object.keys(data).length > 3;
		const icon = data.statusCode >= 500 ? this.icons[500] : this.icons[data.statusCode] || "";
		return typeof error_tl_default === "function" ? error_tl_default({
			icon,
			statusCode: data.statusCode,
			statusMessage: httpStatusCodes[data.statusCode],
			message: data.message,
			details: hasDetails ? JSON.stringify(data, null, "  ") : "",
			version: (this.opts || framework).version,
			poweredBy: (this.opts || framework).poweredBy,
			link: (this.opts || framework).link,
			image: (this.opts || framework).image
		}) : JSON.stringify(data, null, "  ");
	}
	renderText(response) {
		const data = response.body || {};
		response.setContentType("text/plain");
		const keys = Object.keys(data).filter((key) => ![
			"statusCode",
			"error",
			"message"
		].includes(key));
		return `${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}\n\n${keys.length > 0 ? `${JSON.stringify({
			...data,
			statusCode: void 0,
			message: void 0,
			error: void 0
		}, null, "  ")}` : ""}`;
	}
	renderJson(response) {
		const data = response.body || {};
		response.setContentType("application/json");
		const keys = Object.keys(data).filter((key) => ![
			"statusCode",
			"error",
			"message"
		].includes(key));
		return `{"statusCode":${escapeQuotes(data.statusCode)},"error":"${escapeQuotes(data.error)}","message":"${escapeQuotes(data.message)}"${keys.length > 0 ? `,${keys.map((k) => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`).join(",")}` : ""}}`;
	}
	render(response) {
		const { acceptsJson, acceptsText, acceptsHtml } = useAccept();
		response.status = response.body?.statusCode || 500;
		if (acceptsJson()) return this.renderJson(response);
		else if (acceptsHtml()) return this.renderHtml(response);
		else if (acceptsText()) return this.renderText(response);
		else return this.renderJson(response);
	}
};
function escapeQuotes(s) {
	return (typeof s === "number" ? s : s || "").toString().replace(/"/gu, "\\\"");
}

//#endregion
//#region packages/event-http/src/errors/http-error.ts
var HttpError = class extends Error {
	name = "HttpError";
	constructor(code = 500, _body = "") {
		super(typeof _body === "string" ? _body : _body.message);
		this.code = code;
		this._body = _body;
	}
	get body() {
		return typeof this._body === "string" ? {
			statusCode: this.code,
			message: this.message,
			error: httpStatusCodes[this.code]
		} : {
			...this._body,
			statusCode: this.code,
			message: this.message,
			error: httpStatusCodes[this.code]
		};
	}
	renderer;
	attachRenderer(renderer) {
		this.renderer = renderer;
	}
	getRenderer() {
		return this.renderer;
	}
};

//#endregion
//#region packages/event-http/src/composables/request.ts
const xForwardedFor = "x-forwarded-for";
const DEFAULT_LIMITS = {
	maxCompressed: 1 * 1024 * 1024,
	maxInflated: 10 * 1024 * 1024,
	maxRatio: 100,
	readTimeoutMs: 1e4
};
function useRequest() {
	const { store } = useHttpContext();
	const { init, get, set } = store("request");
	const event = store("event");
	const req = event.get("req");
	const contentEncoding = req.headers["content-encoding"];
	const contentEncodings = () => init("contentEncodings", () => (contentEncoding || "").split(",").map((p) => p.trim()).filter((p) => !!p));
	const isCompressed = () => init("isCompressed", () => {
		const parts = contentEncodings();
		for (const p of parts) if ([
			"deflate",
			"gzip",
			"br"
		].includes(p)) return true;
		return false;
	});
	const getMaxCompressed = () => get("maxCompressed") ?? DEFAULT_LIMITS.maxCompressed;
	const setMaxCompressed = (limit) => set("maxCompressed", limit);
	const getReadTimeoutMs = () => get("readTimeoutMs") ?? DEFAULT_LIMITS.readTimeoutMs;
	const setReadTimeoutMs = (limit) => set("readTimeoutMs", limit);
	const getMaxInflated = () => get("maxInflated") ?? DEFAULT_LIMITS.maxInflated;
	const setMaxInflated = (limit) => set("maxInflated", limit);
	const rawBody = () => init("rawBody", async () => {
		const encs = contentEncodings();
		const isZip = isCompressed();
		const streamable = isZip && encodingSupportsStream(encs);
		const maxCompressed = getMaxCompressed();
		const maxInflated = getMaxInflated();
		const timeoutMs = getReadTimeoutMs();
		const cl = Number(req.headers["content-length"] ?? 0);
		const upfrontLimit = isZip ? maxCompressed : maxInflated;
		if (cl && cl > upfrontLimit) throw new HttpError(413, "Payload Too Large");
		for (const enc of encs) if (!compressors[enc]) throw new HttpError(415, `Unsupported Content-Encoding "${enc}"`);
		let timer = null;
		function resetTimer() {
			if (timeoutMs === 0) return;
			clearTimer();
			timer = setTimeout(() => {
				clearTimer();
				req.destroy();
			}, timeoutMs);
		}
		function clearTimer() {
			if (timer) {
				clearTimeout(timer);
				timer = null;
			}
		}
		let rawBytes = 0;
		async function* limitedCompressed() {
			resetTimer();
			try {
				for await (const chunk of req) {
					rawBytes += chunk.length;
					if (rawBytes > upfrontLimit) {
						req.destroy();
						throw new HttpError(413, "Payload Too Large");
					}
					resetTimer();
					yield chunk;
				}
			} finally {
				clearTimer();
			}
		}
		let stream$1 = limitedCompressed();
		if (streamable) stream$1 = await uncompressBodyStream(encs, stream$1);
		const chunks = [];
		let inflatedBytes = 0;
		try {
			for await (const chunk of stream$1) {
				inflatedBytes += chunk.length;
				if (inflatedBytes > maxInflated) throw new HttpError(413, "Inflated body too large");
				chunks.push(chunk);
			}
		} catch (error) {
			if (error instanceof HttpError) throw error;
			throw new HttpError(408, "Request body timeout");
		}
		let body = buffer.Buffer.concat(chunks);
		if (!streamable && isZip) {
			body = await uncompressBody(encs, body);
			inflatedBytes = body.byteLength;
			if (inflatedBytes > maxInflated) throw new HttpError(413, "Inflated body too large");
		}
		return body;
	});
	const reqId = (0, __wooksjs_event_core.useEventId)().getId;
	const forwardedIp = () => init("forwardedIp", () => {
		if (typeof req.headers[xForwardedFor] === "string" && req.headers[xForwardedFor]) return req.headers[xForwardedFor].split(",").shift()?.trim();
		else return "";
	});
	const remoteIp = () => init("remoteIp", () => req.socket.remoteAddress || req.connection.remoteAddress || "");
	function getIp(options) {
		if (options?.trustProxy) return forwardedIp() || getIp();
		else return remoteIp();
	}
	const getIpList = () => init("ipList", () => ({
		remoteIp: req.socket.remoteAddress || req.connection.remoteAddress || "",
		forwarded: (req.headers[xForwardedFor] || "").split(",").map((s) => s.trim())
	}));
	return {
		rawRequest: req,
		url: req.url,
		method: req.method,
		headers: req.headers,
		rawBody,
		reqId,
		getIp,
		getIpList,
		isCompressed,
		getMaxCompressed,
		setMaxCompressed,
		getReadTimeoutMs,
		setReadTimeoutMs,
		getMaxInflated,
		setMaxInflated
	};
}

//#endregion
//#region packages/event-http/src/composables/headers.ts
function useHeaders() {
	return useRequest().headers;
}
function useSetHeaders() {
	const { store } = useHttpContext();
	const setHeaderStore = store("setHeader");
	function setHeader(name, value) {
		setHeaderStore.set(name, value.toString());
	}
	function setContentType(value) {
		setHeader("content-type", value);
	}
	function enableCors(origin = "*") {
		setHeader("access-control-allow-origin", origin);
	}
	return {
		setHeader,
		getHeader: setHeaderStore.get,
		removeHeader: setHeaderStore.del,
		setContentType,
		headers: () => setHeaderStore.value || {},
		enableCors
	};
}
function useSetHeader(name) {
	const { store } = useHttpContext();
	const { hook } = store("setHeader");
	return hook(name);
}

//#endregion
//#region packages/event-http/src/composables/cookies.ts
function useCookies() {
	const { store } = useHttpContext();
	const { cookie } = useHeaders();
	const { init } = store("cookies");
	const getCookie = (name) => init(name, () => {
		if (cookie) {
			const result = new RegExp(`(?:^|; )${escapeRegex(name)}=(.*?)(?:;?$|; )`, "i").exec(cookie);
			return result?.[1] ? safeDecodeURIComponent(result[1]) : null;
		} else return null;
	});
	return {
		rawCookies: cookie,
		getCookie
	};
}
function useSetCookies() {
	const { store } = useHttpContext();
	const cookiesStore = store("setCookies");
	function setCookie(name, value, attrs) {
		cookiesStore.set(name, {
			value,
			attrs: attrs || {}
		});
	}
	function cookies() {
		return cookiesStore.entries().filter((a) => !!a[1]).map(([key, value]) => renderCookie(key, value));
	}
	return {
		setCookie,
		getCookie: cookiesStore.get,
		removeCookie: cookiesStore.del,
		clearCookies: cookiesStore.clear,
		cookies
	};
}
function useSetCookie(name) {
	const { setCookie, getCookie } = useSetCookies();
	const valueHook = (0, __wooksjs_event_core.attachHook)({
		name,
		type: "cookie"
	}, {
		get: () => getCookie(name)?.value,
		set: (value) => {
			setCookie(name, value, getCookie(name)?.attrs);
		}
	});
	return (0, __wooksjs_event_core.attachHook)(valueHook, {
		get: () => getCookie(name)?.attrs,
		set: (attrs) => {
			setCookie(name, getCookie(name)?.value || "", attrs);
		}
	}, "attrs");
}

//#endregion
//#region packages/event-http/src/composables/header-accept.ts
function useAccept() {
	const { store } = useHttpContext();
	const { accept } = useHeaders();
	const accepts = (mime) => {
		const { set, get, has } = store("accept");
		if (!has(mime)) return set(mime, !!(accept && (accept === "*/*" || accept.includes(mime))));
		return get(mime);
	};
	return {
		accept,
		accepts,
		acceptsJson: () => accepts("application/json"),
		acceptsXml: () => accepts("application/xml"),
		acceptsText: () => accepts("text/plain"),
		acceptsHtml: () => accepts("text/html")
	};
}

//#endregion
//#region packages/event-http/src/composables/header-authorization.ts
function useAuthorization() {
	const { store } = useHttpContext();
	const { authorization } = useHeaders();
	const { init } = store("authorization");
	const authType = () => init("type", () => {
		if (authorization) {
			const space = authorization.indexOf(" ");
			return authorization.slice(0, space);
		}
		return null;
	});
	const authRawCredentials = () => init("credentials", () => {
		if (authorization) {
			const space = authorization.indexOf(" ");
			return authorization.slice(space + 1);
		}
		return null;
	});
	return {
		authorization,
		authType,
		authRawCredentials,
		isBasic: () => authType()?.toLocaleLowerCase() === "basic",
		isBearer: () => authType()?.toLocaleLowerCase() === "bearer",
		basicCredentials: () => init("basicCredentials", () => {
			if (authorization) {
				const type = authType();
				if (type?.toLocaleLowerCase() === "basic") {
					const creds = buffer.Buffer.from(authRawCredentials() || "", "base64").toString("ascii");
					const [username, password] = creds.split(":");
					return {
						username,
						password
					};
				}
			}
			return null;
		})
	};
}

//#endregion
//#region packages/event-http/src/utils/cache-control.ts
function renderCacheControl(data) {
	let attrs = "";
	for (const [a, v] of Object.entries(data)) {
		if (v === void 0) continue;
		const func = cacheControlFunc[a];
		if (typeof func === "function") {
			const val = func(v);
			if (val) attrs += attrs ? `, ${val}` : val;
		} else throw new TypeError(`Unknown Cache-Control attribute ${a}`);
	}
	return attrs;
}
const cacheControlFunc = {
	mustRevalidate: (v) => v ? "must-revalidate" : "",
	noCache: (v) => v ? typeof v === "string" ? `no-cache="${v}"` : "no-cache" : "",
	noStore: (v) => v ? "no-store" : "",
	noTransform: (v) => v ? "no-transform" : "",
	public: (v) => v ? "public" : "",
	private: (v) => v ? typeof v === "string" ? `private="${v}"` : "private" : "",
	proxyRevalidate: (v) => v ? "proxy-revalidate" : "",
	maxAge: (v) => `max-age=${convertTime(v, "s").toString()}`,
	sMaxage: (v) => `s-maxage=${convertTime(v, "s").toString()}`
};

//#endregion
//#region packages/event-http/src/composables/header-set-cache-control.ts
const renderAge = (v) => convertTime(v, "s").toString();
const renderExpires = (v) => typeof v === "string" || typeof v === "number" ? new Date(v).toUTCString() : v.toUTCString();
const renderPragmaNoCache = (v) => v ? "no-cache" : "";
function useSetCacheControl() {
	const { setHeader } = useSetHeaders();
	const setAge = (value) => {
		setHeader("age", renderAge(value));
	};
	const setExpires = (value) => {
		setHeader("expires", renderExpires(value));
	};
	const setPragmaNoCache = (value = true) => {
		setHeader("pragma", renderPragmaNoCache(value));
	};
	const setCacheControl = (data) => {
		setHeader("cache-control", renderCacheControl(data));
	};
	return {
		setExpires,
		setAge,
		setPragmaNoCache,
		setCacheControl
	};
}

//#endregion
//#region packages/event-http/src/composables/response.ts
function useResponse() {
	const { store } = useHttpContext();
	const event = store("event");
	const res = event.get("res");
	const responded = store("response").hook("responded");
	const statusCode = store("status").hook("code");
	function status(code) {
		return statusCode.value = code ? code : statusCode.value;
	}
	const rawResponse = (options) => {
		if (!options || !options.passthrough) responded.value = true;
		return res;
	};
	return {
		rawResponse,
		hasResponded: () => responded.value || !res.writable || res.writableEnded,
		status: (0, __wooksjs_event_core.attachHook)(status, {
			get: () => statusCode.value,
			set: (code) => statusCode.value = code
		})
	};
}
function useStatus() {
	const { store } = useHttpContext();
	return store("status").hook("code");
}

//#endregion
//#region packages/event-http/src/utils/url-search-params.ts
var WooksURLSearchParams = class extends url.URLSearchParams {
	toJson() {
		const json = Object.create(null);
		for (const [key, value] of this.entries()) if (isArrayParam(key)) {
			const a = json[key] = json[key] || [];
			a.push(value);
		} else {
			if (key === "__proto__") throw new HttpError(400, `Illegal key name "${key}"`);
			if (key in json) throw new HttpError(400, `Duplicate key "${key}"`);
			json[key] = value;
		}
		return json;
	}
};
function isArrayParam(name) {
	return name.endsWith("[]");
}

//#endregion
//#region packages/event-http/src/composables/search-params.ts
function useSearchParams() {
	const { store } = useHttpContext();
	const url$1 = useRequest().url || "";
	const { init } = store("searchParams");
	const rawSearchParams = () => init("raw", () => {
		const i = url$1.indexOf("?");
		return i >= 0 ? url$1.slice(i) : "";
	});
	const urlSearchParams = () => init("urlSearchParams", () => new WooksURLSearchParams(rawSearchParams()));
	return {
		rawSearchParams,
		urlSearchParams,
		jsonSearchParams: () => urlSearchParams().toJson()
	};
}

//#endregion
//#region packages/event-http/src/response/core.ts
const defaultStatus = {
	GET: EHttpStatusCode.OK,
	POST: EHttpStatusCode.Created,
	PUT: EHttpStatusCode.Created,
	PATCH: EHttpStatusCode.Accepted,
	DELETE: EHttpStatusCode.Accepted
};
const baseRenderer = new BaseHttpResponseRenderer();
var BaseHttpResponse = class {
	constructor(renderer = baseRenderer) {
		this.renderer = renderer;
	}
	_status = 0;
	_body;
	_headers = {};
	get status() {
		return this._status;
	}
	set status(value) {
		this._status = value;
	}
	get body() {
		return this._body;
	}
	set body(value) {
		this._body = value;
	}
	setStatus(value) {
		this.status = value;
		return this;
	}
	setBody(value) {
		this.body = value;
		return this;
	}
	getContentType() {
		return this._headers["content-type"];
	}
	setContentType(value) {
		this._headers["content-type"] = value;
		return this;
	}
	enableCors(origin = "*") {
		this._headers["Access-Control-Allow-Origin"] = origin;
		return this;
	}
	setCookie(name, value, attrs) {
		const cookies = this._headers["set-cookie"] = this._headers["set-cookie"] || [];
		cookies.push(renderCookie(name, {
			value,
			attrs: attrs || {}
		}));
		return this;
	}
	setCacheControl(data) {
		this.setHeader("cache-control", renderCacheControl(data));
	}
	setCookieRaw(rawValue) {
		const cookies = this._headers["set-cookie"] = this._headers["set-cookie"] || [];
		cookies.push(rawValue);
		return this;
	}
	header(name, value) {
		this._headers[name] = value;
		return this;
	}
	setHeader(name, value) {
		return this.header(name, value);
	}
	getHeader(name) {
		return this._headers[name];
	}
	mergeHeaders() {
		const { headers } = useSetHeaders();
		const { cookies, removeCookie } = useSetCookies();
		const newCookies = this._headers["set-cookie"] || [];
		for (const cookie of newCookies) removeCookie(cookie.slice(0, cookie.indexOf("=")));
		this._headers = {
			...headers(),
			...this._headers
		};
		const setCookie = [...newCookies, ...cookies()];
		if (setCookie.length > 0) this._headers["set-cookie"] = setCookie;
		return this;
	}
	mergeStatus(renderedBody) {
		this.status = this.status || useResponse().status();
		if (!this.status) {
			const { method } = useRequest();
			this.status = renderedBody ? defaultStatus[method] || EHttpStatusCode.OK : EHttpStatusCode.NoContent;
		}
		return this;
	}
	mergeFetchStatus(fetchStatus) {
		this.status = this.status || useResponse().status() || fetchStatus;
	}
	panic(text, logger) {
		const error = new Error(text);
		logger.error(error);
		throw error;
	}
	async respond() {
		const { rawResponse, hasResponded } = useResponse();
		const { method, rawRequest } = useRequest();
		const logger = (0, __wooksjs_event_core.useEventLogger)("http-response") || console;
		if (hasResponded()) this.panic("The response was already sent.", logger);
		this.mergeHeaders();
		const res = rawResponse();
		if (this.body instanceof stream.Readable) {
			const stream$1 = this.body;
			this.mergeStatus("ok");
			res.writeHead(this.status, { ...this._headers });
			rawRequest.once("close", () => {
				stream$1.destroy();
			});
			if (method === "HEAD") {
				stream$1.destroy();
				res.end();
			} else return new Promise((resolve, reject) => {
				stream$1.on("error", (e) => {
					stream$1.destroy();
					res.end();
					reject(e);
				});
				stream$1.on("close", () => {
					stream$1.destroy();
					resolve(void 0);
				});
				stream$1.pipe(res);
			});
		} else if (globalThis.Response && this.body instanceof Response) {
			this.mergeFetchStatus(this.body.status);
			if (method === "HEAD") res.end();
			else {
				const additionalHeaders = {};
				if (this.body.headers.get("content-length")) additionalHeaders["content-length"] = this.body.headers.get("content-length");
				if (this.body.headers.get("content-type")) additionalHeaders["content-type"] = this.body.headers.get("content-type");
				res.writeHead(this.status, {
					...additionalHeaders,
					...this._headers
				});
				await respondWithFetch(this.body.body, res);
			}
		} else {
			const renderedBody = this.renderer.render(this);
			this.mergeStatus(renderedBody);
			res.writeHead(this.status, {
				"content-length": Buffer.byteLength(renderedBody),
				...this._headers
			}).end(method === "HEAD" ? "" : renderedBody);
		}
	}
};
async function respondWithFetch(fetchBody, res) {
	if (fetchBody) try {
		for await (const chunk of fetchBody) res.write(chunk);
	} catch (error) {}
	res.end();
}

//#endregion
//#region packages/event-http/src/response/factory.ts
function createWooksResponder(renderer = new BaseHttpResponseRenderer(), errorRenderer = new HttpErrorRenderer()) {
	function createResponse(data) {
		const { hasResponded } = useResponse();
		if (hasResponded()) return null;
		if (data instanceof Error) {
			const r = new BaseHttpResponse(errorRenderer);
			let httpError;
			if (data instanceof HttpError) httpError = data;
			else httpError = new HttpError(500, data.message);
			r.setBody(httpError.body);
			return r;
		} else if (data instanceof BaseHttpResponse) return data;
		else return new BaseHttpResponse(renderer).setBody(data);
	}
	return {
		createResponse,
		respond: (data) => createResponse(data)?.respond()
	};
}

//#endregion
//#region packages/event-http/src/http-adapter.ts
var WooksHttp = class extends wooks.WooksAdapterBase {
	logger;
	constructor(opts, wooks$1) {
		super(wooks$1, opts?.logger, opts?.router);
		this.opts = opts;
		this.logger = opts?.logger || this.getLogger(`[wooks-http]`);
	}
	all(path, handler) {
		return this.on("*", path, handler);
	}
	get(path, handler) {
		return this.on("GET", path, handler);
	}
	post(path, handler) {
		return this.on("POST", path, handler);
	}
	put(path, handler) {
		return this.on("PUT", path, handler);
	}
	patch(path, handler) {
		return this.on("PATCH", path, handler);
	}
	delete(path, handler) {
		return this.on("DELETE", path, handler);
	}
	head(path, handler) {
		return this.on("HEAD", path, handler);
	}
	options(path, handler) {
		return this.on("OPTIONS", path, handler);
	}
	server;
	async listen(port, hostname, backlog, listeningListener) {
		const server = this.server = http.default.createServer(this.getServerCb());
		return new Promise((resolve, reject) => {
			server.once("listening", resolve);
			server.once("error", reject);
			let args = [
				port,
				hostname,
				backlog,
				listeningListener
			];
			const ui = args.indexOf(void 0);
			if (ui >= 0) args = args.slice(0, ui);
			server.listen(...args);
		});
	}
	/**
	* Stops the server if it was attached or passed via argument
	* @param server
	*/
	close(server) {
		const srv = server || this.server;
		return new Promise((resolve, reject) => {
			srv?.close((err) => {
				if (err) {
					reject(err);
					return;
				}
				resolve(srv);
			});
		});
	}
	/**
	* Returns http(s) server that was attached to Wooks
	*
	* See attachServer method docs
	* @returns Server
	*/
	getServer() {
		return this.server;
	}
	/**
	* Attaches http(s) server instance
	* to Wooks.
	*
	* Use it only if you want to `close` method to stop the server.
	* @param server Server
	*/
	attachServer(server) {
		this.server = server;
	}
	responder = createWooksResponder();
	respond(data) {
		this.responder.respond(data)?.catch((e) => {
			this.logger.error("Uncaught response exception", e);
		});
	}
	/**
	* Returns server callback function
	* that can be passed to any node server:
	* ```js
	* import { createHttpApp } from '@wooksjs/event-http'
	* import http from 'http'
	*
	* const app = createHttpApp()
	* const server = http.createServer(app.getServerCb())
	* server.listen(3000)
	* ```
	*/
	getServerCb() {
		return (req, res) => {
			const runInContext = createHttpContext({
				req,
				res
			}, this.mergeEventOptions(this.opts?.eventOptions));
			runInContext(async () => {
				const { handlers } = this.wooks.lookup(req.method, req.url);
				if (handlers || this.opts?.onNotFound) try {
					return await this.processHandlers(handlers || [this.opts?.onNotFound]);
				} catch (error) {
					this.logger.error("Internal error, please report", error);
					this.respond(error);
					return error;
				}
				else {
					this.logger.debug(`404 Not found (${req.method})${req.url}`);
					const error = new HttpError(404);
					this.respond(error);
					return error;
				}
			});
		};
	}
	async processHandlers(handlers) {
		const { store } = useHttpContext();
		for (const [i, handler] of handlers.entries()) {
			const isLastHandler = handlers.length === i + 1;
			try {
				const promise = handler();
				const result = await promise;
				this.respond(result);
				return result;
			} catch (error) {
				if (error instanceof HttpError) {} else this.logger.error(`Uncaught route handler exception: ${store("event").get("req")?.url || ""}`, error);
				if (isLastHandler) {
					this.respond(error);
					return error;
				}
			}
		}
	}
};
/**
* Factory for WooksHttp App
* @param opts TWooksHttpOptions
* @param wooks Wooks | WooksAdapterBase
* @returns WooksHttp
*/
function createHttpApp(opts, wooks$1) {
	return new WooksHttp(opts, wooks$1);
}

//#endregion
exports.BaseHttpResponse = BaseHttpResponse;
exports.BaseHttpResponseRenderer = BaseHttpResponseRenderer;
exports.DEFAULT_LIMITS = DEFAULT_LIMITS;
exports.EHttpStatusCode = EHttpStatusCode;
exports.HttpError = HttpError;
exports.HttpErrorRenderer = HttpErrorRenderer;
exports.WooksHttp = WooksHttp;
exports.WooksURLSearchParams = WooksURLSearchParams;
exports.createHttpApp = createHttpApp;
exports.createHttpContext = createHttpContext;
exports.createWooksResponder = createWooksResponder;
exports.httpStatusCodes = httpStatusCodes;
exports.renderCacheControl = renderCacheControl;
exports.useAccept = useAccept;
exports.useAuthorization = useAuthorization;
exports.useCookies = useCookies;
Object.defineProperty(exports, 'useEventLogger', {
  enumerable: true,
  get: function () {
    return __wooksjs_event_core.useEventLogger;
  }
});
exports.useHeaders = useHeaders;
exports.useHttpContext = useHttpContext;
exports.useRequest = useRequest;
exports.useResponse = useResponse;
Object.defineProperty(exports, 'useRouteParams', {
  enumerable: true,
  get: function () {
    return __wooksjs_event_core.useRouteParams;
  }
});
exports.useSearchParams = useSearchParams;
exports.useSetCacheControl = useSetCacheControl;
exports.useSetCookie = useSetCookie;
exports.useSetCookies = useSetCookies;
exports.useSetHeader = useSetHeader;
exports.useSetHeaders = useSetHeaders;
exports.useStatus = useStatus;