yinzerflow 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,32 +1,32 @@
1
- var H1=Object.create;var{getPrototypeOf:q1,defineProperty:b$,getOwnPropertyNames:V1}=Object;var O1=Object.prototype.hasOwnProperty;var D$=($,M,W)=>{W=$!=null?H1(q1($)):{};let Y=M||!$||!$.__esModule?b$(W,"default",{value:$,enumerable:!0}):W;for(let Z of V1($))if(!O1.call(Y,Z))b$(Y,Z,{get:()=>$[Z],enumerable:!0});return Y};var B1=($,M)=>()=>(M||$((M={exports:{}}).exports,M),M.exports);var o=B1((K$,w$)=>{(function($,M){typeof K$=="object"&&typeof w$<"u"?w$.exports=M():typeof define=="function"&&define.amd?define(M):($=typeof globalThis<"u"?globalThis:$||self).dayjs=M()})(K$,function(){var $=1000,M=60000,W=3600000,Y="millisecond",Z="second",Q="minute",X="hour",w="day",V="week",A="month",u="quarter",L="year",v="date",T$="Invalid Date",j1=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,U1=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,F1={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(U){var K=["th","st","nd","rd"],J=U%100;return"["+U+(K[(J-20)%10]||K[J]||K[0])+"]"}},X$=function(U,K,J){var j=String(U);return!j||j.length>=K?U:""+Array(K+1-j.length).join(J)+U},G1={s:X$,z:function(U){var K=-U.utcOffset(),J=Math.abs(K),j=Math.floor(J/60),D=J%60;return(K<=0?"+":"-")+X$(j,2,"0")+":"+X$(D,2,"0")},m:function U(K,J){if(K.date()<J.date())return-U(J,K);var j=12*(J.year()-K.year())+(J.month()-K.month()),D=K.clone().add(j,A),F=J-D<0,G=K.clone().add(j+(F?-1:1),A);return+(-(j+(J-D)/(F?D-G:G-D))||0)},a:function(U){return U<0?Math.ceil(U)||0:Math.floor(U)},p:function(U){return{M:A,y:L,w:V,d:w,D:v,h:X,m:Q,s:Z,ms:Y,Q:u}[U]||String(U||"").toLowerCase().replace(/s$/,"")},u:function(U){return U===void 0}},g="en",y={};y[g]=F1;var R$="$isDayjsObject",J$=function(U){return U instanceof n||!(!U||!U[R$])},a=function U(K,J,j){var D;if(!K)return g;if(typeof K=="string"){var F=K.toLowerCase();y[F]&&(D=F),J&&(y[F]=J,D=F);var G=K.split("-");if(!D&&G.length>1)return U(G[0])}else{var B=K.name;y[B]=K,D=B}return!j&&D&&(g=D),D||!j&&g},k=function(U,K){if(J$(U))return U.clone();var J=typeof K=="object"?K:{};return J.date=U,J.args=arguments,new n(J)},O=G1;O.l=a,O.i=J$,O.w=function(U,K){return k(U,{locale:K.$L,utc:K.$u,x:K.$x,$offset:K.$offset})};var n=function(){function U(J){this.$L=a(J.locale,null,!0),this.parse(J),this.$x=this.$x||J.x||{},this[R$]=!0}var K=U.prototype;return K.parse=function(J){this.$d=function(j){var{date:D,utc:F}=j;if(D===null)return new Date(NaN);if(O.u(D))return new Date;if(D instanceof Date)return new Date(D);if(typeof D=="string"&&!/Z$/i.test(D)){var G=D.match(j1);if(G){var B=G[2]-1||0,N=(G[7]||"0").substring(0,3);return F?new Date(Date.UTC(G[1],B,G[3]||1,G[4]||0,G[5]||0,G[6]||0,N)):new Date(G[1],B,G[3]||1,G[4]||0,G[5]||0,G[6]||0,N)}}return new Date(D)}(J),this.init()},K.init=function(){var J=this.$d;this.$y=J.getFullYear(),this.$M=J.getMonth(),this.$D=J.getDate(),this.$W=J.getDay(),this.$H=J.getHours(),this.$m=J.getMinutes(),this.$s=J.getSeconds(),this.$ms=J.getMilliseconds()},K.$utils=function(){return O},K.isValid=function(){return this.$d.toString()!==T$},K.isSame=function(J,j){var D=k(J);return this.startOf(j)<=D&&D<=this.endOf(j)},K.isAfter=function(J,j){return k(J)<this.startOf(j)},K.isBefore=function(J,j){return this.endOf(j)<k(J)},K.$g=function(J,j,D){return O.u(J)?this[j]:this.set(D,J)},K.unix=function(){return Math.floor(this.valueOf()/1000)},K.valueOf=function(){return this.$d.getTime()},K.startOf=function(J,j){var D=this,F=!!O.u(j)||j,G=O.p(J),B=function(h,S){var C=O.w(D.$u?Date.UTC(D.$y,S,h):new Date(D.$y,S,h),D);return F?C:C.endOf(w)},N=function(h,S){return O.w(D.toDate()[h].apply(D.toDate("s"),(F?[0,0,0,0]:[23,59,59,999]).slice(S)),D)},E=this.$W,z=this.$M,T=this.$D,l="set"+(this.$u?"UTC":"");switch(G){case L:return F?B(1,0):B(31,11);case A:return F?B(1,z):B(0,z+1);case V:var m=this.$locale().weekStart||0,p=(E<m?E+7:E)-m;return B(F?T-p:T+(6-p),z);case w:case v:return N(l+"Hours",0);case X:return N(l+"Minutes",1);case Q:return N(l+"Seconds",2);case Z:return N(l+"Milliseconds",3);default:return this.clone()}},K.endOf=function(J){return this.startOf(J,!1)},K.$set=function(J,j){var D,F=O.p(J),G="set"+(this.$u?"UTC":""),B=(D={},D[w]=G+"Date",D[v]=G+"Date",D[A]=G+"Month",D[L]=G+"FullYear",D[X]=G+"Hours",D[Q]=G+"Minutes",D[Z]=G+"Seconds",D[Y]=G+"Milliseconds",D)[F],N=F===w?this.$D+(j-this.$W):j;if(F===A||F===L){var E=this.clone().set(v,1);E.$d[B](N),E.init(),this.$d=E.set(v,Math.min(this.$D,E.daysInMonth())).$d}else B&&this.$d[B](N);return this.init(),this},K.set=function(J,j){return this.clone().$set(J,j)},K.get=function(J){return this[O.p(J)]()},K.add=function(J,j){var D,F=this;J=Number(J);var G=O.p(j),B=function(z){var T=k(F);return O.w(T.date(T.date()+Math.round(z*J)),F)};if(G===A)return this.set(A,this.$M+J);if(G===L)return this.set(L,this.$y+J);if(G===w)return B(1);if(G===V)return B(7);var N=(D={},D[Q]=M,D[X]=W,D[Z]=$,D)[G]||1,E=this.$d.getTime()+J*N;return O.w(E,this)},K.subtract=function(J,j){return this.add(-1*J,j)},K.format=function(J){var j=this,D=this.$locale();if(!this.isValid())return D.invalidDate||T$;var F=J||"YYYY-MM-DDTHH:mm:ssZ",G=O.z(this),B=this.$H,N=this.$m,E=this.$M,z=D.weekdays,T=D.months,l=D.meridiem,m=function(S,C,r,t){return S&&(S[C]||S(j,F))||r[C].slice(0,t)},p=function(S){return O.s(B%12||12,S,"0")},h=l||function(S,C,r){var t=S<12?"AM":"PM";return r?t.toLowerCase():t};return F.replace(U1,function(S,C){return C||function(r){switch(r){case"YY":return String(j.$y).slice(-2);case"YYYY":return O.s(j.$y,4,"0");case"M":return E+1;case"MM":return O.s(E+1,2,"0");case"MMM":return m(D.monthsShort,E,T,3);case"MMMM":return m(T,E);case"D":return j.$D;case"DD":return O.s(j.$D,2,"0");case"d":return String(j.$W);case"dd":return m(D.weekdaysMin,j.$W,z,2);case"ddd":return m(D.weekdaysShort,j.$W,z,3);case"dddd":return z[j.$W];case"H":return String(B);case"HH":return O.s(B,2,"0");case"h":return p(1);case"hh":return p(2);case"a":return h(B,N,!0);case"A":return h(B,N,!1);case"m":return String(N);case"mm":return O.s(N,2,"0");case"s":return String(j.$s);case"ss":return O.s(j.$s,2,"0");case"SSS":return O.s(j.$ms,3,"0");case"Z":return G}return null}(S)||G.replace(":","")})},K.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},K.diff=function(J,j,D){var F,G=this,B=O.p(j),N=k(J),E=(N.utcOffset()-this.utcOffset())*M,z=this-N,T=function(){return O.m(G,N)};switch(B){case L:F=T()/12;break;case A:F=T();break;case u:F=T()/3;break;case V:F=(z-E)/604800000;break;case w:F=(z-E)/86400000;break;case X:F=z/W;break;case Q:F=z/M;break;case Z:F=z/$;break;default:F=z}return D?F:O.a(F)},K.daysInMonth=function(){return this.endOf(A).$D},K.$locale=function(){return y[this.$L]},K.locale=function(J,j){if(!J)return this.$L;var D=this.clone(),F=a(J,j,!0);return F&&(D.$L=F),D},K.clone=function(){return O.w(this.$d,this)},K.toDate=function(){return new Date(this.valueOf())},K.toJSON=function(){return this.isValid()?this.toISOString():null},K.toISOString=function(){return this.$d.toISOString()},K.toString=function(){return this.$d.toUTCString()},U}(),P$=n.prototype;return k.prototype=P$,[["$ms",Y],["$s",Z],["$m",Q],["$H",X],["$W",w],["$M",A],["$y",L],["$D",v]].forEach(function(U){P$[U[1]]=function(K){return this.$g(K,U[0],U[1])}}),k.extend=function(U,K){return U.$i||(U(K,n,k),U.$i=!0),k},k.locale=a,k.isDayjs=J$,k.unix=function(U){return k(1000*U)},k.en=y[g],k.Ls=y,k.p={},k})});import{createServer as T0}from"net";var U$=D$(o(),1);var s={ok:"OK",created:"Created",accepted:"Accepted",noContent:"No Content",movedPermanently:"Moved Permanently",found:"Found",notModified:"Not Modified",badRequest:"Bad Request",unauthorized:"Unauthorized",forbidden:"Forbidden",notFound:"Not Found",methodNotAllowed:"Method Not Allowed",conflict:"Conflict",unsupportedMediaType:"Unsupported Media Type",tooManyRequests:"Too Many Requests",internalServerError:"Internal Server Error"},P={ok:200,created:201,accepted:202,noContent:204,movedPermanently:301,found:302,notModified:304,badRequest:400,unauthorized:401,forbidden:403,notFound:404,methodNotAllowed:405,conflict:409,unsupportedMediaType:415,tooManyRequests:429,internalServerError:500},_={delete:"DELETE",get:"GET",head:"HEAD",post:"POST",put:"PUT",patch:"PATCH",options:"OPTIONS"},R={json:"application/json",html:"text/html",form:"application/x-www-form-urlencoded",multipart:"multipart/form-data",xml:"application/xml",text:"text/plain",csv:"text/csv",yamlApplication:"application/yaml",yamlText:"text/yaml",urlEncodedJson:"application/x-www-form-urlencoded+json"},x={authorization:"Authorization",proxyAuthorization:"Proxy-Authorization",wwwAuthenticate:"WWW-Authenticate",cacheControl:"Cache-Control",etag:"ETag",expires:"Expires",lastModified:"Last-Modified",ifMatch:"If-Match",ifNoneMatch:"If-None-Match",ifModifiedSince:"If-Modified-Since",ifUnmodifiedSince:"If-Unmodified-Since",ifRange:"If-Range",age:"Age",vary:"Vary",contentType:"Content-Type",contentLength:"Content-Length",contentEncoding:"Content-Encoding",contentLanguage:"Content-Language",contentDisposition:"Content-Disposition",contentLocation:"Content-Location",contentRange:"Content-Range",accessControlAllowCredentials:"Access-Control-Allow-Credentials",accessControlAllowHeaders:"Access-Control-Allow-Headers",accessControlAllowMethods:"Access-Control-Allow-Methods",accessControlAllowOrigin:"Access-Control-Allow-Origin",accessControlExposeHeaders:"Access-Control-Expose-Headers",accessControlMaxAge:"Access-Control-Max-Age",accessControlRequestHeaders:"Access-Control-Request-Headers",accessControlRequestMethod:"Access-Control-Request-Method",accept:"Accept",acceptEncoding:"Accept-Encoding",acceptLanguage:"Accept-Language",acceptRanges:"Accept-Ranges",host:"Host",userAgent:"User-Agent",referer:"Referer",origin:"Origin",from:"From",expect:"Expect",location:"Location",server:"Server",date:"Date",allow:"Allow",retryAfter:"Retry-After",range:"Range",contentSecurityPolicy:"Content-Security-Policy",contentSecurityPolicyReportOnly:"Content-Security-Policy-Report-Only",strictTransportSecurity:"Strict-Transport-Security",xContentTypeOptions:"X-Content-Type-Options",xFrameOptions:"X-Frame-Options",xXSSProtection:"X-XSS-Protection",referrerPolicy:"Referrer-Policy",permissionsPolicy:"Permissions-Policy",crossOriginEmbedderPolicy:"Cross-Origin-Embedder-Policy",crossOriginOpenerPolicy:"Cross-Origin-Opener-Policy",crossOriginResourcePolicy:"Cross-Origin-Resource-Policy",cookie:"Cookie",setCookie:"Set-Cookie",connection:"Connection",keepAlive:"Keep-Alive",upgrade:"Upgrade",upgradeInsecureRequests:"Upgrade-Insecure-Requests",transferEncoding:"Transfer-Encoding",te:"TE",trailer:"Trailer",forwarded:"Forwarded",xForwardedFor:"X-Forwarded-For",via:"Via",maxForwards:"Max-Forwards",altSvc:"Alt-Svc",altUsed:"Alt-Used",timingAllowOrigin:"Timing-Allow-Origin",serverTiming:"Server-Timing",refresh:"Refresh",link:"Link",xPoweredBy:"X-Powered-By",xPermittedCrossDomainPolicies:"X-Permitted-Cross-Domain-Policies",reportTo:"Report-To",serviceWorkerAllowed:"Service-Worker-Allowed",sourceMap:"SourceMap",priority:"Priority",secGPC:"Sec-GPC",clearSiteData:"Clear-Site-Data",noVarySearch:"No-Vary-Search"},x$={base64:"base64",binary:"binary",utf8:"utf8"};var e=($,M)=>{if(!M.enabled)return!1;if($.request.method==="OPTIONS"){if(!u$($,M))return $.response.setStatusCode(403),$._response._setBody({error:"CORS: Origin not allowed",origin:$.request.headers.origin}),!0;$.response.setStatusCode(M.optionsSuccessStatus);let Z=C$($,M);if($._response._setHeadersIfNotSet({[x.accessControlAllowOrigin]:Z,[x.accessControlAllowMethods]:M.methods.join(", "),[x.accessControlAllowHeaders]:typeof M.allowedHeaders==="string"?M.allowedHeaders:M.allowedHeaders.join(", "),[x.accessControlAllowCredentials]:M.credentials?"true":"false",[x.accessControlExposeHeaders]:M.exposedHeaders.join(", "),[x.accessControlMaxAge]:M.maxAge.toString()}),M.preflightContinue)return!1;return $._response._setBody(""),!0}if(u$($,M)){let Y=C$($,M);$._response._setHeadersIfNotSet({[x.accessControlAllowOrigin]:Y,[x.accessControlAllowCredentials]:M.credentials?"true":"false"})}return!1},C$=($,M)=>{if(M.origin==="*"){if(M.credentials)throw Error('CORS Security Error: origin: "*" with credentials: true is forbidden by CORS spec and creates security vulnerabilities. Use specific origins instead.');return"*"}let W=$.request.headers.origin;if(W)return W;if(typeof M.origin==="string")return M.origin;if(Array.isArray(M.origin)&&M.origin.length>0){let[Y]=M.origin;return Y??"null"}return"null"},u$=($,M)=>{if(M.origin==="*")return!0;let W=$.request.headers.origin?.toLowerCase()??"";if(typeof M.origin==="function")return Boolean(M.origin(W,$.request));if(typeof M.origin==="string")return W===M.origin.toLowerCase();if(Array.isArray(M.origin))return M.origin.some((Y)=>W===Y.toLowerCase());if(M.origin instanceof RegExp)return M.origin.test(W);return!1};var y$=D$(o(),1);var q={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"};var c={off:"off",error:"error",warn:"warn",info:"info"};var f={off:0,error:1,warn:2,info:3},N1={positive:["n'at!","yinz are good!","that's the way!","right on!","lookin' good!","way to go!","keep it up!"],neutral:["n'at","yinz know","just sayin'","that's how it is","what can ya do","it happens"],negative:["aw jeez","that ain't right","what a jagoff move","that's terrible n'at","somebody messed up","this is bad news","yinz better fix this"]},$$=($)=>{let M=N1[$];return M[Math.floor(Math.random()*M.length)]??""},m$=()=>y$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),j$=($,M,...W)=>{let Y=m$(),Z=q.reset;if(M==="NETWORK")Z=q.gray;if($==="error"){let X=`${q.red}[${M}] ❌ [${Y}] [ERROR]${q.reset}`;console.error(`${X}`,`${Z}`,...W,`${q.reset} - ${$$("negative")}`);return}if($==="warn"){let X=`${q.yellow}[${M}] ⚠️ [${Y}] [WARN]${q.reset}`;console.warn(`${X}`,`${Z}`,...W,`${q.reset} - ${$$("neutral")}`);return}if($==="off")return;let Q=`${q.cyan}[${M}] ✅ [${Y}] [INFO]${q.reset}`;console.info(`${Q}`,`${Z}`,...W,`${q.reset} - ${$$("positive")}`)},_1=($,M,...W)=>{let Y=m$(),Z=`${q.magenta}[${$}] \uD83D\uDCCA [${Y}] [TABLE]${q.reset}`;if(console.log(`${Z} - ${$$("positive")}`),console.table(M),W.length>0)console.log(`${q.gray}Additional context:${q.reset}`,...W)},d=($)=>{let M={logLevel:$?.logLevel??c.info,prefix:$?.prefix??"YINZER",logger:$?.logger??null},W=(w)=>f[w]??f.info;return{info:(...w)=>{if(W(M.logLevel)<f.info)return;if(M.logger){M.logger.info(...w);return}j$("info",M.prefix,...w)},warn:(...w)=>{if(W(M.logLevel)<f.warn)return;if(M.logger){M.logger.warn(...w);return}j$("warn",M.prefix,...w)},error:(...w)=>{if(W(M.logLevel)<f.error)return;if(M.logger){M.logger.error(...w);return}j$("error",M.prefix,...w)},table:(w,...V)=>{if(W(M.logLevel)<f.info)return;if(M.logger){M.logger.info("TABLE:",w,...V);return}_1(M.prefix,w,...V)},levels:f}},H=d();class F${setup;constructor($){this.setup=$}async handle($){try{if(this._handleCors($))return;let M=await this._matchRoute($);if(!M)return;Object.assign($.request.params,M.params);let{handler:W,options:Y}=M,{beforeHooks:Z=[],afterHooks:Q=[]}=Y;if(await this._handleBeforeAllHooks($))return;if(await this._handleBeforeHooks($,Z))return;let X=null;try{X=await W($)}catch(V){throw V}for(let V of Q)await V($);let w=this.setup._hooks._afterAll;for(let V of w){if(!this._shouldRunHook(V.options,$.request.path))continue;await V.handler($)}if($._response._setBody(X),$.request.method==="HEAD")$._response._setBody(null);$._response._parseResponseIntoString();return}catch(M){await this.handleError($,M)}}async handleError($,M){try{let W=this.setup._hooks._onError,Y=await W($,M);$._response._setBody(Y),e($,this.setup._configuration.cors),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:U$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
1
+ var k1=Object.create;var{getPrototypeOf:I1,defineProperty:f$,getOwnPropertyNames:S1}=Object;var L1=Object.prototype.hasOwnProperty;var H$=($,W,Y)=>{Y=$!=null?k1(I1($)):{};let Z=W||!$||!$.__esModule?f$(Y,"default",{value:$,enumerable:!0}):Y;for(let Q of S1($))if(!L1.call(Z,Q))f$(Z,Q,{get:()=>$[Q],enumerable:!0});return Z};var T1=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var Z$=T1((q$,w$)=>{(function($,W){typeof q$=="object"&&typeof w$<"u"?w$.exports=W():typeof define=="function"&&define.amd?define(W):($=typeof globalThis<"u"?globalThis:$||self).dayjs=W()})(q$,function(){var $=1000,W=60000,Y=3600000,Z="millisecond",Q="second",X="minute",M="hour",K="day",V="week",z="month",C="quarter",A="year",w="date",E="Invalid Date",P=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,U$=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,z1={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(F){var j=["th","st","nd","rd"],J=F%100;return"["+F+(j[(J-20)%10]||j[J]||j[0])+"]"}},G$=function(F,j,J){var U=String(F);return!U||U.length>=j?F:""+Array(j+1-U.length).join(J)+F},_1={s:G$,z:function(F){var j=-F.utcOffset(),J=Math.abs(j),U=Math.floor(J/60),D=J%60;return(j<=0?"+":"-")+G$(U,2,"0")+":"+G$(D,2,"0")},m:function F(j,J){if(j.date()<J.date())return-F(J,j);var U=12*(J.year()-j.year())+(J.month()-j.month()),D=j.clone().add(U,z),H=J-D<0,q=j.clone().add(U+(H?-1:1),z);return+(-(U+(J-D)/(H?D-q:q-D))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:z,y:A,w:V,d:K,D:w,h:M,m:X,s:Q,ms:Z,Q:C}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},d="en",m={};m[d]=z1;var m$="$isDayjsObject",F$=function(F){return F instanceof W$||!(!F||!F[m$])},$$=function F(j,J,U){var D;if(!j)return d;if(typeof j=="string"){var H=j.toLowerCase();m[H]&&(D=H),J&&(m[H]=J,D=H);var q=j.split("-");if(!D&&q.length>1)return F(q[0])}else{var N=j.name;m[N]=j,D=N}return!U&&D&&(d=D),D||!U&&d},I=function(F,j){if(F$(F))return F.clone();var J=typeof j=="object"?j:{};return J.date=F,J.args=arguments,new W$(J)},O=_1;O.l=$$,O.i=F$,O.w=function(F,j){return I(F,{locale:j.$L,utc:j.$u,x:j.$x,$offset:j.$offset})};var W$=function(){function F(J){this.$L=$$(J.locale,null,!0),this.parse(J),this.$x=this.$x||J.x||{},this[m$]=!0}var j=F.prototype;return j.parse=function(J){this.$d=function(U){var{date:D,utc:H}=U;if(D===null)return new Date(NaN);if(O.u(D))return new Date;if(D instanceof Date)return new Date(D);if(typeof D=="string"&&!/Z$/i.test(D)){var q=D.match(P);if(q){var N=q[2]-1||0,_=(q[7]||"0").substring(0,3);return H?new Date(Date.UTC(q[1],N,q[3]||1,q[4]||0,q[5]||0,q[6]||0,_)):new Date(q[1],N,q[3]||1,q[4]||0,q[5]||0,q[6]||0,_)}}return new Date(D)}(J),this.init()},j.init=function(){var J=this.$d;this.$y=J.getFullYear(),this.$M=J.getMonth(),this.$D=J.getDate(),this.$W=J.getDay(),this.$H=J.getHours(),this.$m=J.getMinutes(),this.$s=J.getSeconds(),this.$ms=J.getMilliseconds()},j.$utils=function(){return O},j.isValid=function(){return this.$d.toString()!==E},j.isSame=function(J,U){var D=I(J);return this.startOf(U)<=D&&D<=this.endOf(U)},j.isAfter=function(J,U){return I(J)<this.startOf(U)},j.isBefore=function(J,U){return this.endOf(U)<I(J)},j.$g=function(J,U,D){return O.u(J)?this[U]:this.set(D,J)},j.unix=function(){return Math.floor(this.valueOf()/1000)},j.valueOf=function(){return this.$d.getTime()},j.startOf=function(J,U){var D=this,H=!!O.u(U)||U,q=O.p(J),N=function(f,v){var h=O.w(D.$u?Date.UTC(D.$y,v,f):new Date(D.$y,v,f),D);return H?h:h.endOf(K)},_=function(f,v){return O.w(D.toDate()[f].apply(D.toDate("s"),(H?[0,0,0,0]:[23,59,59,999]).slice(v)),D)},S=this.$W,L=this.$M,R=this.$D,s="set"+(this.$u?"UTC":"");switch(q){case A:return H?N(1,0):N(31,11);case z:return H?N(1,L):N(0,L+1);case V:var p=this.$locale().weekStart||0,r=(S<p?S+7:S)-p;return N(H?R-r:R+(6-r),L);case K:case w:return _(s+"Hours",0);case M:return _(s+"Minutes",1);case X:return _(s+"Seconds",2);case Q:return _(s+"Milliseconds",3);default:return this.clone()}},j.endOf=function(J){return this.startOf(J,!1)},j.$set=function(J,U){var D,H=O.p(J),q="set"+(this.$u?"UTC":""),N=(D={},D[K]=q+"Date",D[w]=q+"Date",D[z]=q+"Month",D[A]=q+"FullYear",D[M]=q+"Hours",D[X]=q+"Minutes",D[Q]=q+"Seconds",D[Z]=q+"Milliseconds",D)[H],_=H===K?this.$D+(U-this.$W):U;if(H===z||H===A){var S=this.clone().set(w,1);S.$d[N](_),S.init(),this.$d=S.set(w,Math.min(this.$D,S.daysInMonth())).$d}else N&&this.$d[N](_);return this.init(),this},j.set=function(J,U){return this.clone().$set(J,U)},j.get=function(J){return this[O.p(J)]()},j.add=function(J,U){var D,H=this;J=Number(J);var q=O.p(U),N=function(L){var R=I(H);return O.w(R.date(R.date()+Math.round(L*J)),H)};if(q===z)return this.set(z,this.$M+J);if(q===A)return this.set(A,this.$y+J);if(q===K)return N(1);if(q===V)return N(7);var _=(D={},D[X]=W,D[M]=Y,D[Q]=$,D)[q]||1,S=this.$d.getTime()+J*_;return O.w(S,this)},j.subtract=function(J,U){return this.add(-1*J,U)},j.format=function(J){var U=this,D=this.$locale();if(!this.isValid())return D.invalidDate||E;var H=J||"YYYY-MM-DDTHH:mm:ssZ",q=O.z(this),N=this.$H,_=this.$m,S=this.$M,L=D.weekdays,R=D.months,s=D.meridiem,p=function(v,h,c,Y$){return v&&(v[h]||v(U,H))||c[h].slice(0,Y$)},r=function(v){return O.s(N%12||12,v,"0")},f=s||function(v,h,c){var Y$=v<12?"AM":"PM";return c?Y$.toLowerCase():Y$};return H.replace(U$,function(v,h){return h||function(c){switch(c){case"YY":return String(U.$y).slice(-2);case"YYYY":return O.s(U.$y,4,"0");case"M":return S+1;case"MM":return O.s(S+1,2,"0");case"MMM":return p(D.monthsShort,S,R,3);case"MMMM":return p(R,S);case"D":return U.$D;case"DD":return O.s(U.$D,2,"0");case"d":return String(U.$W);case"dd":return p(D.weekdaysMin,U.$W,L,2);case"ddd":return p(D.weekdaysShort,U.$W,L,3);case"dddd":return L[U.$W];case"H":return String(N);case"HH":return O.s(N,2,"0");case"h":return r(1);case"hh":return r(2);case"a":return f(N,_,!0);case"A":return f(N,_,!1);case"m":return String(_);case"mm":return O.s(_,2,"0");case"s":return String(U.$s);case"ss":return O.s(U.$s,2,"0");case"SSS":return O.s(U.$ms,3,"0");case"Z":return q}return null}(v)||q.replace(":","")})},j.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},j.diff=function(J,U,D){var H,q=this,N=O.p(U),_=I(J),S=(_.utcOffset()-this.utcOffset())*W,L=this-_,R=function(){return O.m(q,_)};switch(N){case A:H=R()/12;break;case z:H=R();break;case C:H=R()/3;break;case V:H=(L-S)/604800000;break;case K:H=(L-S)/86400000;break;case M:H=L/Y;break;case X:H=L/W;break;case Q:H=L/$;break;default:H=L}return D?H:O.a(H)},j.daysInMonth=function(){return this.endOf(z).$D},j.$locale=function(){return m[this.$L]},j.locale=function(J,U){if(!J)return this.$L;var D=this.clone(),H=$$(J,U,!0);return H&&(D.$L=H),D},j.clone=function(){return O.w(this.$d,this)},j.toDate=function(){return new Date(this.valueOf())},j.toJSON=function(){return this.isValid()?this.toISOString():null},j.toISOString=function(){return this.$d.toISOString()},j.toString=function(){return this.$d.toUTCString()},F}(),p$=W$.prototype;return I.prototype=p$,[["$ms",Z],["$s",Q],["$m",X],["$H",M],["$W",K],["$M",z],["$y",A],["$D",w]].forEach(function(F){p$[F[1]]=function(j){return this.$g(j,F[0],F[1])}}),I.extend=function(F,j){return F.$i||(F(j,W$,I),F.$i=!0),I},I.locale=$$,I.isDayjs=F$,I.unix=function(F){return I(1000*F)},I.en=m[d],I.Ls=m,I.p={},I})});import{createServer as i0}from"net";var B$=H$(Z$(),1);var a={ok:"OK",created:"Created",accepted:"Accepted",noContent:"No Content",movedPermanently:"Moved Permanently",found:"Found",notModified:"Not Modified",badRequest:"Bad Request",unauthorized:"Unauthorized",forbidden:"Forbidden",notFound:"Not Found",methodNotAllowed:"Method Not Allowed",conflict:"Conflict",unsupportedMediaType:"Unsupported Media Type",tooManyRequests:"Too Many Requests",internalServerError:"Internal Server Error"},b={ok:200,created:201,accepted:202,noContent:204,movedPermanently:301,found:302,notModified:304,badRequest:400,unauthorized:401,forbidden:403,notFound:404,methodNotAllowed:405,conflict:409,unsupportedMediaType:415,tooManyRequests:429,internalServerError:500},k={delete:"DELETE",get:"GET",head:"HEAD",post:"POST",put:"PUT",patch:"PATCH",options:"OPTIONS"},x={json:"application/json",html:"text/html",form:"application/x-www-form-urlencoded",multipart:"multipart/form-data",xml:"application/xml",text:"text/plain",csv:"text/csv",yamlApplication:"application/yaml",yamlText:"text/yaml",urlEncodedJson:"application/x-www-form-urlencoded+json"},u={authorization:"Authorization",proxyAuthorization:"Proxy-Authorization",wwwAuthenticate:"WWW-Authenticate",cacheControl:"Cache-Control",etag:"ETag",expires:"Expires",lastModified:"Last-Modified",ifMatch:"If-Match",ifNoneMatch:"If-None-Match",ifModifiedSince:"If-Modified-Since",ifUnmodifiedSince:"If-Unmodified-Since",ifRange:"If-Range",age:"Age",vary:"Vary",contentType:"Content-Type",contentLength:"Content-Length",contentEncoding:"Content-Encoding",contentLanguage:"Content-Language",contentDisposition:"Content-Disposition",contentLocation:"Content-Location",contentRange:"Content-Range",accessControlAllowCredentials:"Access-Control-Allow-Credentials",accessControlAllowHeaders:"Access-Control-Allow-Headers",accessControlAllowMethods:"Access-Control-Allow-Methods",accessControlAllowOrigin:"Access-Control-Allow-Origin",accessControlExposeHeaders:"Access-Control-Expose-Headers",accessControlMaxAge:"Access-Control-Max-Age",accessControlRequestHeaders:"Access-Control-Request-Headers",accessControlRequestMethod:"Access-Control-Request-Method",accept:"Accept",acceptEncoding:"Accept-Encoding",acceptLanguage:"Accept-Language",acceptRanges:"Accept-Ranges",host:"Host",userAgent:"User-Agent",referer:"Referer",origin:"Origin",from:"From",expect:"Expect",location:"Location",server:"Server",date:"Date",allow:"Allow",retryAfter:"Retry-After",range:"Range",contentSecurityPolicy:"Content-Security-Policy",contentSecurityPolicyReportOnly:"Content-Security-Policy-Report-Only",strictTransportSecurity:"Strict-Transport-Security",xContentTypeOptions:"X-Content-Type-Options",xFrameOptions:"X-Frame-Options",xXSSProtection:"X-XSS-Protection",referrerPolicy:"Referrer-Policy",permissionsPolicy:"Permissions-Policy",crossOriginEmbedderPolicy:"Cross-Origin-Embedder-Policy",crossOriginOpenerPolicy:"Cross-Origin-Opener-Policy",crossOriginResourcePolicy:"Cross-Origin-Resource-Policy",cookie:"Cookie",setCookie:"Set-Cookie",connection:"Connection",keepAlive:"Keep-Alive",upgrade:"Upgrade",upgradeInsecureRequests:"Upgrade-Insecure-Requests",transferEncoding:"Transfer-Encoding",te:"TE",trailer:"Trailer",forwarded:"Forwarded",xForwardedFor:"X-Forwarded-For",via:"Via",maxForwards:"Max-Forwards",altSvc:"Alt-Svc",altUsed:"Alt-Used",timingAllowOrigin:"Timing-Allow-Origin",serverTiming:"Server-Timing",refresh:"Refresh",link:"Link",xPoweredBy:"X-Powered-By",xPermittedCrossDomainPolicies:"X-Permitted-Cross-Domain-Policies",reportTo:"Report-To",serviceWorkerAllowed:"Service-Worker-Allowed",sourceMap:"SourceMap",priority:"Priority",secGPC:"Sec-GPC",clearSiteData:"Clear-Site-Data",noVarySearch:"No-Vary-Search"},l$={base64:"base64",binary:"binary",utf8:"utf8"};var Q$=($,W)=>{if(!W.enabled)return!1;if($.request.method==="OPTIONS"){if(!s$($,W))return $.response.setStatusCode(403),$._response._setBody({error:"CORS: Origin not allowed",origin:$.request.headers.origin}),!0;$.response.setStatusCode(W.optionsSuccessStatus);let Q=g$($,W);if($._response._setHeadersIfNotSet({[u.accessControlAllowOrigin]:Q,[u.accessControlAllowMethods]:W.methods.join(", "),[u.accessControlAllowHeaders]:typeof W.allowedHeaders==="string"?W.allowedHeaders:W.allowedHeaders.join(", "),[u.accessControlAllowCredentials]:W.credentials?"true":"false",[u.accessControlExposeHeaders]:W.exposedHeaders.join(", "),[u.accessControlMaxAge]:W.maxAge.toString()}),W.preflightContinue)return!1;return $._response._setBody(""),!0}if(s$($,W)){let Z=g$($,W);$._response._setHeadersIfNotSet({[u.accessControlAllowOrigin]:Z,[u.accessControlAllowCredentials]:W.credentials?"true":"false"})}return!1},g$=($,W)=>{if(W.origin==="*"){if(W.credentials)throw Error('CORS Security Error: origin: "*" with credentials: true is forbidden by CORS spec and creates security vulnerabilities. Use specific origins instead.');return"*"}let Y=$.request.headers.origin;if(Y)return Y;if(typeof W.origin==="string")return W.origin;if(Array.isArray(W.origin)&&W.origin.length>0){let[Z]=W.origin;return Z??"null"}return"null"},s$=($,W)=>{if(W.origin==="*")return!0;let Y=$.request.headers.origin?.toLowerCase()??"";if(typeof W.origin==="function")return Boolean(W.origin(Y,$.request));if(typeof W.origin==="string")return Y===W.origin.toLowerCase();if(Array.isArray(W.origin))return W.origin.some((Z)=>Y===Z.toLowerCase());if(W.origin instanceof RegExp)return W.origin.test(Y);return!1};var d$=H$(Z$(),1);var B={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"};var i={off:"off",error:"error",warn:"warn",info:"info"};var l={off:0,error:1,warn:2,info:3},v1={positive:["n'at!","yinz are good!","that's the way!","right on!","lookin' good!","way to go!","keep it up!"],neutral:["n'at","yinz know","just sayin'","that's how it is","what can ya do","it happens"],negative:["aw jeez","that ain't right","what a jagoff move","that's terrible n'at","somebody messed up","this is bad news","yinz better fix this"]},X$=($)=>{let W=v1[$];return W[Math.floor(Math.random()*W.length)]??""},r$=()=>d$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),V$=($,W,...Y)=>{let Z=r$(),Q=B.reset;if(W==="NETWORK")Q=B.gray;if($==="error"){let M=`${B.red}[${W}] ❌ [${Z}] [ERROR]${B.reset}`;console.error(`${M}`,`${Q}`,...Y,`${B.reset} - ${X$("negative")}`);return}if($==="warn"){let M=`${B.yellow}[${W}] ⚠️ [${Z}] [WARN]${B.reset}`;console.warn(`${M}`,`${Q}`,...Y,`${B.reset} - ${X$("neutral")}`);return}if($==="off")return;let X=`${B.cyan}[${W}] ✅ [${Z}] [INFO]${B.reset}`;console.info(`${X}`,`${Q}`,...Y,`${B.reset} - ${X$("positive")}`)},P1=($,W,...Y)=>{let Z=r$(),Q=`${B.magenta}[${$}] \uD83D\uDCCA [${Z}] [TABLE]${B.reset}`;if(console.log(`${Q} - ${X$("positive")}`),console.table(W),Y.length>0)console.log(`${B.gray}Additional context:${B.reset}`,...Y)},n=($)=>{let W={logLevel:$?.logLevel??i.info,prefix:$?.prefix??"YINZER",logger:$?.logger??null},Y=(K)=>l[K]??l.info;return{info:(...K)=>{if(Y(W.logLevel)<l.info)return;if(W.logger){W.logger.info(...K);return}V$("info",W.prefix,...K)},warn:(...K)=>{if(Y(W.logLevel)<l.warn)return;if(W.logger){W.logger.warn(...K);return}V$("warn",W.prefix,...K)},error:(...K)=>{if(Y(W.logLevel)<l.error)return;if(W.logger){W.logger.error(...K);return}V$("error",W.prefix,...K)},table:(K,...V)=>{if(Y(W.logLevel)<l.info)return;if(W.logger){W.logger.info("TABLE:",K,...V);return}P1(W.prefix,K,...V)},levels:l}},G=n();class O${setup;constructor($){this.setup=$}async handle($){try{if(this._handleCors($))return;let W=await this._matchRoute($);if(!W)return;Object.assign($.request.params,W.params);let{handler:Y,options:Z}=W,{beforeHooks:Q=[],afterHooks:X=[]}=Z;if(await this._handleBeforeAllHooks($))return;if(await this._handleBeforeHooks($,Q))return;let M=null;try{M=await Y($)}catch(V){throw V}for(let V of X)await V($);let K=this.setup._hooks._afterAll;for(let V of K){if(!this._shouldRunHook(V.options,$.request.path))continue;await V.handler($)}if($._response._setBody(M),$.request.method==="HEAD")$._response._setBody(null);$._response._parseResponseIntoString();return}catch(W){await this.handleError($,W)}}async handleError($,W){try{let Y=this.setup._hooks._onError,Z=await Y($,W);$._response._setBody(Z),Q$($,this.setup._configuration.cors),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:B$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
2
2
 
3
- `)[1]?.length.toString()??"0"})}catch(W){H.error("Error handler failed, this might be an internal error in the YinzerFlow framework: ",W),$.response.setStatusCode(500),$._response._setBody({success:!1,message:"Internal Server Error"}),e($,this.setup._configuration.cors),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:U$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
3
+ `)[1]?.length.toString()??"0"})}catch(Y){G.error("Error handler failed, this might be an internal error in the YinzerFlow framework: ",Y),$.response.setStatusCode(500),$._response._setBody({success:!1,message:"Internal Server Error"}),Q$($,this.setup._configuration.cors),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:B$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
4
4
 
5
- `)[1]?.length.toString()??"0"})}}_handleCors($){if(e($,this.setup._configuration.cors))return $._response._parseResponseIntoString(),!0;return!1}async _matchRoute($){let M=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!M){let W=await this.setup._hooks._onNotFound($);return $._response._setBody(W),$._response._parseResponseIntoString(),null}return M}async _handleBeforeAllHooks($){let M=this.setup._hooks._beforeAll;for(let W of M){if(!this._shouldRunHook(W.options,$.request.path))continue;let Y=await W.handler($);if(Y!==void 0)return $._response._setBody(Y),$._response._parseResponseIntoString(),!0}return!1}async _handleBeforeHooks($,M){for(let W of M){let Y=await W($);if(Y!==void 0)return $._response._setBody(Y),$._response._parseResponseIntoString(),!0}return!1}_shouldRunHook($,M){if(!$)return!0;let{routesToInclude:W,routesToExclude:Y}=$;if(Y.some((Z)=>this._matchesPattern(M,Z)))return!1;if(W.length===0)return!0;return W.some((Z)=>this._matchesPattern(M,Z))}_matchesPattern($,M){if(M===$)return!0;if(M.endsWith("/*")){let W=M.slice(0,-2);return $.startsWith(W)}return!1}}var h$=["__proto__","constructor","prototype"],f$=($,M)=>{if(!$||!$.trim()||$.trim()==="\x00")return;let W=Buffer.byteLength($,"utf8");if(W>M.maxSize)throw H.warn("[SECURITY] JSON request body too large",{size:W,limit:M.maxSize,sizeMB:Math.round(W/1024/1024)}),Error(`Request body too large: ${W} bytes exceeds limit of ${M.maxSize} bytes`);let Y=null;try{Y=JSON.parse($)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`Invalid JSON syntax: ${Q}`)}try{G$(Y,M,1)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`JSON security validation failed: ${Q}`)}return Y},k1=($,M)=>{if(typeof $==="string"&&$.length>M.maxStringLength)throw Error(`String too long: ${$.length} characters exceeds limit of ${M.maxStringLength}`)},E1=($,M,W)=>{if($.length>M.maxArrayLength)throw Error(`Array too large: ${$.length} elements exceeds limit of ${M.maxArrayLength}`);for(let Y of $)G$(Y,M,W+1)},L1=($,M)=>{if($.length>M.maxKeys)throw Error(`Object has too many keys: ${$.length} exceeds limit of ${M.maxKeys}`);if(!M.allowPrototypeProperties){for(let W of $)if(h$.includes(W))throw H.warn("[SECURITY] Prototype pollution attempt detected",{property:W,dangerousProperties:h$}),Error(`Prototype pollution attempt detected: property '${W}' is not allowed`)}},A1=($,M,W)=>{let Y=Object.keys($);for(let Z of Y){if(Z.length>M.maxStringLength)throw Error(`Object key too long: '${Z.substring(0,50)}...' exceeds limit of ${M.maxStringLength}`);let Q=$[Z];if(typeof Q==="string"&&Q.length>M.maxStringLength)throw Error(`String value too long: property '${Z}' has ${Q.length} characters, exceeds limit of ${M.maxStringLength}`);G$(Q,M,W+1)}},G$=($,M,W)=>{if(W>M.maxDepth)throw H.warn("[SECURITY] JSON nesting too deep - potential stack overflow attack",{currentDepth:W,maxDepth:M.maxDepth}),Error(`JSON nesting too deep: current depth ${W} exceeds maximum depth of ${M.maxDepth}`);if($===null||typeof $!=="object"){k1($,M);return}if(Array.isArray($)){E1($,M,W);return}let Y=Object.keys($);L1(Y,M),A1($,M,W)};var z1=($)=>{let M=$.startsWith(`\r
6
- `)?$.slice(2):$,W=M.indexOf(`\r
5
+ `)[1]?.length.toString()??"0"})}}_handleCors($){if(Q$($,this.setup._configuration.cors))return $._response._parseResponseIntoString(),!0;return!1}async _matchRoute($){let W=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!W){let Y=await this.setup._hooks._onNotFound($);return $._response._setBody(Y),$._response._parseResponseIntoString(),null}return W}async _handleBeforeAllHooks($){let W=this.setup._hooks._beforeAll;for(let Y of W){if(!this._shouldRunHook(Y.options,$.request.path))continue;let Z=await Y.handler($);if(Z!==void 0)return $._response._setBody(Z),$._response._parseResponseIntoString(),!0}return!1}async _handleBeforeHooks($,W){for(let Y of W){let Z=await Y($);if(Z!==void 0)return $._response._setBody(Z),$._response._parseResponseIntoString(),!0}return!1}_shouldRunHook($,W){if(!$)return!0;let{routesToInclude:Y,routesToExclude:Z}=$;if(Z.some((Q)=>this._matchesPattern(W,Q)))return!1;if(Y.length===0)return!0;return Y.some((Q)=>this._matchesPattern(W,Q))}_matchesPattern($,W){if(W===$)return!0;if(W.endsWith("/*")){let Y=W.slice(0,-2);return $.startsWith(Y)}return!1}}var c$=["__proto__","constructor","prototype"],a$=($,W)=>{if(!$||!$.trim()||$.trim()==="\x00")return;let Y=Buffer.byteLength($,"utf8");if(Y>W.maxSize)throw G.warn("[SECURITY] JSON request body too large",{size:Y,limit:W.maxSize,sizeMB:Math.round(Y/1024/1024)}),Error(`Request body too large: ${Y} bytes exceeds limit of ${W.maxSize} bytes`);let Z=null;try{Z=JSON.parse($)}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw Error(`Invalid JSON syntax: ${X}`)}try{N$(Z,W,1)}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw Error(`JSON security validation failed: ${X}`)}return Z},R1=($,W)=>{if(typeof $==="string"&&$.length>W.maxStringLength)throw Error(`String too long: ${$.length} characters exceeds limit of ${W.maxStringLength}`)},b1=($,W,Y)=>{if($.length>W.maxArrayLength)throw Error(`Array too large: ${$.length} elements exceeds limit of ${W.maxArrayLength}`);for(let Z of $)N$(Z,W,Y+1)},x1=($,W)=>{if($.length>W.maxKeys)throw Error(`Object has too many keys: ${$.length} exceeds limit of ${W.maxKeys}`);if(!W.allowPrototypeProperties){for(let Y of $)if(c$.includes(Y))throw G.warn("[SECURITY] Prototype pollution attempt detected",{property:Y,dangerousProperties:c$}),Error(`Prototype pollution attempt detected: property '${Y}' is not allowed`)}},C1=($,W,Y)=>{let Z=Object.keys($);for(let Q of Z){if(Q.length>W.maxStringLength)throw Error(`Object key too long: '${Q.substring(0,50)}...' exceeds limit of ${W.maxStringLength}`);let X=$[Q];if(typeof X==="string"&&X.length>W.maxStringLength)throw Error(`String value too long: property '${Q}' has ${X.length} characters, exceeds limit of ${W.maxStringLength}`);N$(X,W,Y+1)}},N$=($,W,Y)=>{if(Y>W.maxDepth)throw G.warn("[SECURITY] JSON nesting too deep - potential stack overflow attack",{currentDepth:Y,maxDepth:W.maxDepth}),Error(`JSON nesting too deep: current depth ${Y} exceeds maximum depth of ${W.maxDepth}`);if($===null||typeof $!=="object"){R1($,W);return}if(Array.isArray($)){b1($,W,Y);return}let Z=Object.keys($);x1(Z,W),C1($,W,Y)};var y1=($)=>{let W=$.startsWith(`\r
6
+ `)?$.slice(2):$,Y=W.indexOf(`\r
7
7
  \r
8
- `);if(W===-1)return["",""];let Y=M.slice(0,W),Z=M.slice(W+4);return[Y,Z]},I1=($)=>{let M={name:""},W=/name=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($),Y=/filename=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($);if(W)M.name=W[1]??W[2]??"";if(Y){let Z=Y[1]??Y[2];if(Z)M.filename=Z}return M},S1=($)=>{let W=$.split(/\r?\n/).find((Y)=>Y.toLowerCase().startsWith("content-type:"));if(!W)return"application/octet-stream";return W.slice(W.indexOf(":")+1).trim().split(";")[0]?.trim()??"application/octet-stream"},v1=($)=>{return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/x-"].some((W)=>$.toLowerCase().startsWith(W))},T1=($)=>Buffer.isBuffer($)?$.length:Buffer.byteLength($,"utf8"),R1=($,M)=>{if(!M)return;if($.size>M.maxFileSize)throw H.warn("[SECURITY] File upload too large",{filename:$.filename,size:$.size,limit:M.maxFileSize,sizeMB:Math.round($.size/1024/1024)}),Error(`File too large: ${$.filename} is ${$.size} bytes, exceeds limit of ${M.maxFileSize} bytes`);if($.filename&&$.filename.length>M.maxFilenameLength)throw Error(`Filename too long: ${$.filename.length} characters exceeds limit of ${M.maxFilenameLength}`);if($.filename){let W=$.filename.toLowerCase().substring($.filename.lastIndexOf("."));if(M.blockedExtensions.includes(W))throw H.warn("[SECURITY] Blocked file type upload attempt",{filename:$.filename,extension:W,blockedExtensions:M.blockedExtensions}),Error(`File type not allowed: ${W} files are blocked for security reasons`);if(M.allowedExtensions.length>0&&!M.allowedExtensions.includes(W))throw Error(`File type not allowed: ${W} is not in the allowed extensions list`)}},P1=({contentDisposition:$,contentSection:M,headersSection:W,config:Y})=>{let Z=S1(W),Q=M.endsWith(`\r
9
- `)?M.slice(0,-2):M,X=v1(Z)?Buffer.from(Q,"binary"):Q,w={filename:$.filename??"",contentType:Z,size:T1(X),content:X};return R1(w,Y),w},l$=($,M,W)=>{let Y={fields:{},files:[]},Z=$.split(`--${M}`).slice(1),Q=0;for(let X of Z){if(!X||X.trim()===""||X.trim()==="--")continue;let[w,V]=z1(X);if(!w)continue;let u=w.split(/\r?\n/).find((v)=>v.toLowerCase().startsWith("content-disposition:"));if(!u)continue;let L=I1(u);if(!L.name)continue;if(L.filename!==void 0){if(W&&Y.files.length>=W.maxFiles)throw H.warn("[SECURITY] Too many files in upload request",{fileCount:Y.files.length,maxFiles:W.maxFiles}),Error(`Too many files: maximum of ${W.maxFiles} files allowed per request`);let v=P1({contentDisposition:L,contentSection:V,headersSection:w,config:W});if(Q+=v.size,W&&Q>W.maxTotalSize)throw H.warn("[SECURITY] Total upload size too large",{totalSize:Q,limit:W.maxTotalSize,totalSizeMB:Math.round(Q/1024/1024)}),Error(`Total file size too large: ${Q} bytes exceeds limit of ${W.maxTotalSize} bytes`);Y.files.push(v)}if(L.filename===void 0){let v=V.endsWith(`\r
10
- `)?V.slice(0,-2):V;Y.fields[L.name]=v}}return Y};var b1=($,M)=>{if($.length>M.maxFields)throw Error(`Too many form fields: ${$.length} exceeds limit of ${M.maxFields}`)},x1=($,M,W)=>{if($.length>W.maxFieldNameLength)throw Error(`Form field name too long: ${$.length} characters exceeds limit of ${W.maxFieldNameLength}`);if(M&&M.length>W.maxFieldLength)throw Error(`Form field value too long: field '${$}' has ${M.length} characters, exceeds limit of ${W.maxFieldLength}`)},C1=($,M,W)=>{if($.length>W.maxFieldNameLength)throw Error(`Decoded form field name too long: ${$.length} characters exceeds limit of ${W.maxFieldNameLength}`);if(M.length>W.maxFieldLength)throw Error(`Decoded form field value too long: field '${$}' has ${M.length} characters, exceeds limit of ${W.maxFieldLength}`)},u1=($,M,W)=>{let[Y,Z]=$.split("=");if(!Y)return;if(W)x1(Y,Z,W);try{let Q=decodeURIComponent(Y),X=Z?decodeURIComponent(Z):"";if(W)C1(Q,X,W);M[Q]=X}catch(Q){if(Q instanceof Error&&Q.message.includes("exceeds limit"))throw Q;M[Y]=Z??""}},g$=($,M)=>{let W={},Y=$.split("&");if(M)b1(Y,M);for(let Z of Y)u1(Z,W,M);return W};var M$={JPEG:[255,216,255],PNG:[137,80,78,71],GIF87A:[71,73,70,56,55,97],GIF89A:[71,73,70,56,57,97],BMP:[66,77],TIFF_LE:[73,73,42,0],TIFF_BE:[77,77,0,42],WEBP:[82,73,70,70],ICO:[0,0,1,0],MP3_ID3:[73,68,51],MP3_FRAME:[255,251],WAV:[82,73,70,70],FLAC:[102,76,97,67],OGG:[79,103,103,83],MP4_FTYP:[0,0,0,24,102,116,121,112],MP4_FTYP_ALT:[0,0,0,28,102,116,121,112],AVI:[82,73,70,70],WEBM:[26,69,223,163],PDF:[37,80,68,70],ZIP:[80,75,3,4],ZIP_EMPTY:[80,75,5,6],ZIP_SPANNED:[80,75,7,8],RAR:[82,97,114,33,26,7,0],RAR5:[82,97,114,33,26,7,1,0],SEVENZ:[55,122,188,175,39,28],GZIP:[31,139],EXE:[77,90],ELF:[127,69,76,70],OFFICE_OLD:[208,207,17,224,161,177,26,225]},W$=($,M)=>{if($.length<M.length)return!1;return M.every((W,Y)=>$[Y]===W)},y1=($)=>{if(W$($,M$.WEBP)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WEBP";if(W$($,M$.WAV)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WAVE";if(W$($,M$.AVI)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="AVI ";return!1},Y$=($,M)=>{if(!$)return m1(M);let W=$.toLowerCase();if(W.startsWith("image/")||W.startsWith("video/")||W.startsWith("audio/")||W==="application/pdf"||W==="application/octet-stream"||W.startsWith("application/zip")||W.startsWith("application/x-"))return"base64";if(W.startsWith("text/")||W.startsWith("application/json")||W.startsWith("application/xml")||W.startsWith("application/javascript"))return"utf8";return"binary"},m1=($)=>{if(Buffer.isBuffer($))return h1($)?"base64":"utf8";if(typeof $==="object"&&$!==null)return"utf8";if(typeof $==="string")return"utf8";return"utf8"},h1=($)=>{if($.length===0)return!1;let M=Object.values(M$);for(let Z of M)if(W$($,Z))return!0;if(y1($))return!0;let W=$.filter((Z)=>Z===0).length,Y=$.filter((Z)=>Z<32&&Z!==9&&Z!==10&&Z!==13).length;return W/$.length>0.1||Y/$.length>0.3};var f1=($)=>{if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return!1;try{return JSON.parse($),!0}catch{return!1}},l1=($)=>$.includes("=")&&$.includes("&"),g1=($)=>$.includes("boundary="),p1=($)=>typeof $==="object"&&$!==null&&!Buffer.isBuffer($)&&!($ instanceof Uint8Array)&&!($ instanceof ArrayBuffer)&&!($ instanceof Date),r1=($)=>$ instanceof Date,s1=($)=>{if(Buffer.isBuffer($))return $;return Buffer.from($)},c1=($)=>{return Y$(void 0,$)==="base64"?"application/octet-stream":"text/plain"},H$=($)=>{let M=$.trim();if(f1(M))return R.json;if(l1(M))return R.form;if(g1(M))return R.multipart;return"text/plain"},p$=($)=>{if($===null||$===void 0)return"text/plain";if(r1($))return"text/plain";if(p1($))return R.json;if(typeof $==="string")return H$($);if(Buffer.isBuffer($)||$ instanceof Uint8Array||$ instanceof ArrayBuffer){let M=s1($);return c1(M)}return"text/plain"};var d1=($,M,W)=>{let Y=Buffer.byteLength($,"utf8");if(M===R.json){if(Y>W.json.maxSize)throw Error(`JSON body too large: ${Y} bytes exceeds limit of ${W.json.maxSize} bytes`)}else if(M===R.form){if(Y>W.urlEncoded.maxSize)throw Error(`URL-encoded body too large: ${Y} bytes exceeds limit of ${W.urlEncoded.maxSize} bytes`)}else if(M===R.multipart){if(Y>W.fileUploads.maxTotalSize)throw Error(`Multipart body too large: ${Y} bytes exceeds limit of ${W.fileUploads.maxTotalSize} bytes`)}},r$=($,M={})=>{let{headerContentType:W,boundary:Y,config:Z}=M;if(!$||!$.trim())return;let Q=W??H$($);if(Z)d1($,Q,Z);if(Q===R.json){if(!Z)throw Error("Body parser configuration is required for JSON parsing");return f$($,Z.json)}if(Q===R.multipart){if(!Y)throw Error("Invalid multipart form data: missing boundary");return l$($,Y,Z?.fileUploads)}if(Q===R.form)return g$($,Z?.urlEncoded);return $};var q$=($,M)=>{let W=$.indexOf(M);if(W===-1)return[$,""];let Y=$.slice(0,W),Z=$.slice(W+M.length);return[Y,Z]};var s$=($)=>{if(!$||!$.trim())return{method:"GET",path:"/",protocol:"HTTP/1.1",headersRaw:"",rawBody:""};let[M,W]=q$($,`\r
11
- `),[Y,Z,Q]=M.split(" ",3),[X,w]=q$(W,`\r
8
+ `);if(Y===-1)return["",""];let Z=W.slice(0,Y),Q=W.slice(Y+4);return[Z,Q]},u1=($)=>{let W={name:""},Y=/name=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($),Z=/filename=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($);if(Y)W.name=Y[1]??Y[2]??"";if(Z){let Q=Z[1]??Z[2];if(Q)W.filename=Q}return W},h1=($)=>{let Y=$.split(/\r?\n/).find((Z)=>Z.toLowerCase().startsWith("content-type:"));if(!Y)return"application/octet-stream";return Y.slice(Y.indexOf(":")+1).trim().split(";")[0]?.trim()??"application/octet-stream"},m1=($)=>{return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/x-"].some((Y)=>$.toLowerCase().startsWith(Y))},p1=($)=>Buffer.isBuffer($)?$.length:Buffer.byteLength($,"utf8"),f1=($,W)=>{if(!W)return;if($.size>W.maxFileSize)throw G.warn("[SECURITY] File upload too large",{filename:$.filename,size:$.size,limit:W.maxFileSize,sizeMB:Math.round($.size/1024/1024)}),Error(`File too large: ${$.filename} is ${$.size} bytes, exceeds limit of ${W.maxFileSize} bytes`);if($.filename&&$.filename.length>W.maxFilenameLength)throw Error(`Filename too long: ${$.filename.length} characters exceeds limit of ${W.maxFilenameLength}`);if($.filename){let Y=$.filename.toLowerCase().substring($.filename.lastIndexOf("."));if(W.blockedExtensions.includes(Y))throw G.warn("[SECURITY] Blocked file type upload attempt",{filename:$.filename,extension:Y,blockedExtensions:W.blockedExtensions}),Error(`File type not allowed: ${Y} files are blocked for security reasons`);if(W.allowedExtensions.length>0&&!W.allowedExtensions.includes(Y))throw Error(`File type not allowed: ${Y} is not in the allowed extensions list`)}},l1=({contentDisposition:$,contentSection:W,headersSection:Y,config:Z})=>{let Q=h1(Y),X=W.endsWith(`\r
9
+ `)?W.slice(0,-2):W,M=m1(Q)?Buffer.from(X,"binary"):X,K={filename:$.filename??"",contentType:Q,size:p1(M),content:M};return f1(K,Z),K},i$=($,W,Y)=>{let Z={fields:{},files:[]},Q=$.split(`--${W}`).slice(1),X=0;for(let M of Q){if(!M||M.trim()===""||M.trim()==="--")continue;let[K,V]=y1(M);if(!K)continue;let C=K.split(/\r?\n/).find((w)=>w.toLowerCase().startsWith("content-disposition:"));if(!C)continue;let A=u1(C);if(!A.name)continue;if(A.filename!==void 0){if(Y&&Z.files.length>=Y.maxFiles)throw G.warn("[SECURITY] Too many files in upload request",{fileCount:Z.files.length,maxFiles:Y.maxFiles}),Error(`Too many files: maximum of ${Y.maxFiles} files allowed per request`);let w=l1({contentDisposition:A,contentSection:V,headersSection:K,config:Y});if(X+=w.size,Y&&X>Y.maxTotalSize)throw G.warn("[SECURITY] Total upload size too large",{totalSize:X,limit:Y.maxTotalSize,totalSizeMB:Math.round(X/1024/1024)}),Error(`Total file size too large: ${X} bytes exceeds limit of ${Y.maxTotalSize} bytes`);Z.files.push(w)}if(A.filename===void 0){let w=V.endsWith(`\r
10
+ `)?V.slice(0,-2):V;Z.fields[A.name]=w}}return Z};var g1=($,W)=>{if($.length>W.maxFields)throw Error(`Too many form fields: ${$.length} exceeds limit of ${W.maxFields}`)},s1=($,W,Y)=>{if($.length>Y.maxFieldNameLength)throw Error(`Form field name too long: ${$.length} characters exceeds limit of ${Y.maxFieldNameLength}`);if(W&&W.length>Y.maxFieldLength)throw Error(`Form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Y.maxFieldLength}`)},d1=($,W,Y)=>{if($.length>Y.maxFieldNameLength)throw Error(`Decoded form field name too long: ${$.length} characters exceeds limit of ${Y.maxFieldNameLength}`);if(W.length>Y.maxFieldLength)throw Error(`Decoded form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Y.maxFieldLength}`)},r1=($,W,Y)=>{let[Z,Q]=$.split("=");if(!Z)return;if(Y)s1(Z,Q,Y);try{let X=decodeURIComponent(Z),M=Q?decodeURIComponent(Q):"";if(Y)d1(X,M,Y);W[X]=M}catch(X){if(X instanceof Error&&X.message.includes("exceeds limit"))throw X;W[Z]=Q??""}},n$=($,W)=>{let Y={},Z=$.split("&");if(W)g1(Z,W);for(let Q of Z)r1(Q,Y,W);return Y};var M$={JPEG:[255,216,255],PNG:[137,80,78,71],GIF87A:[71,73,70,56,55,97],GIF89A:[71,73,70,56,57,97],BMP:[66,77],TIFF_LE:[73,73,42,0],TIFF_BE:[77,77,0,42],WEBP:[82,73,70,70],ICO:[0,0,1,0],MP3_ID3:[73,68,51],MP3_FRAME:[255,251],WAV:[82,73,70,70],FLAC:[102,76,97,67],OGG:[79,103,103,83],MP4_FTYP:[0,0,0,24,102,116,121,112],MP4_FTYP_ALT:[0,0,0,28,102,116,121,112],AVI:[82,73,70,70],WEBM:[26,69,223,163],PDF:[37,80,68,70],ZIP:[80,75,3,4],ZIP_EMPTY:[80,75,5,6],ZIP_SPANNED:[80,75,7,8],RAR:[82,97,114,33,26,7,0],RAR5:[82,97,114,33,26,7,1,0],SEVENZ:[55,122,188,175,39,28],GZIP:[31,139],EXE:[77,90],ELF:[127,69,76,70],OFFICE_OLD:[208,207,17,224,161,177,26,225]},J$=($,W)=>{if($.length<W.length)return!1;return W.every((Y,Z)=>$[Z]===Y)},c1=($)=>{if(J$($,M$.WEBP)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WEBP";if(J$($,M$.WAV)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WAVE";if(J$($,M$.AVI)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="AVI ";return!1},D$=($,W)=>{if(!$)return a1(W);let Y=$.toLowerCase();if(Y.startsWith("image/")||Y.startsWith("video/")||Y.startsWith("audio/")||Y==="application/pdf"||Y==="application/octet-stream"||Y.startsWith("application/zip")||Y.startsWith("application/x-"))return"base64";if(Y.startsWith("text/")||Y.startsWith("application/json")||Y.startsWith("application/xml")||Y.startsWith("application/javascript"))return"utf8";return"binary"},a1=($)=>{if(Buffer.isBuffer($))return i1($)?"base64":"utf8";if(typeof $==="object"&&$!==null)return"utf8";if(typeof $==="string")return"utf8";return"utf8"},i1=($)=>{if($.length===0)return!1;let W=Object.values(M$);for(let Q of W)if(J$($,Q))return!0;if(c1($))return!0;let Y=$.filter((Q)=>Q===0).length,Z=$.filter((Q)=>Q<32&&Q!==9&&Q!==10&&Q!==13).length;return Y/$.length>0.1||Z/$.length>0.3};var n1=($)=>{if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return!1;try{return JSON.parse($),!0}catch{return!1}},t1=($)=>$.includes("=")&&$.includes("&"),o1=($)=>$.includes("boundary="),e1=($)=>typeof $==="object"&&$!==null&&!Buffer.isBuffer($)&&!($ instanceof Uint8Array)&&!($ instanceof ArrayBuffer)&&!($ instanceof Date),$0=($)=>$ instanceof Date,W0=($)=>{if(Buffer.isBuffer($))return $;return Buffer.from($)},Y0=($)=>{return D$(void 0,$)==="base64"?"application/octet-stream":"text/plain"},E$=($)=>{let W=$.trim();if(n1(W))return x.json;if(t1(W))return x.form;if(o1(W))return x.multipart;return"text/plain"},t$=($)=>{if($===null||$===void 0)return"text/plain";if($0($))return"text/plain";if(e1($))return x.json;if(typeof $==="string")return E$($);if(Buffer.isBuffer($)||$ instanceof Uint8Array||$ instanceof ArrayBuffer){let W=W0($);return Y0(W)}return"text/plain"};var Z0=($,W,Y)=>{let Z=Buffer.byteLength($,"utf8");if(W===x.json){if(Z>Y.json.maxSize)throw Error(`JSON body too large: ${Z} bytes exceeds limit of ${Y.json.maxSize} bytes`)}else if(W===x.form){if(Z>Y.urlEncoded.maxSize)throw Error(`URL-encoded body too large: ${Z} bytes exceeds limit of ${Y.urlEncoded.maxSize} bytes`)}else if(W===x.multipart){if(Z>Y.fileUploads.maxTotalSize)throw Error(`Multipart body too large: ${Z} bytes exceeds limit of ${Y.fileUploads.maxTotalSize} bytes`)}},o$=($,W={})=>{let{headerContentType:Y,boundary:Z,config:Q}=W;if(!$||!$.trim())return;let X=Y??E$($);if(Q)Z0($,X,Q);if(X===x.json){if(!Q)throw Error("Body parser configuration is required for JSON parsing");return a$($,Q.json)}if(X===x.multipart){if(!Z)throw Error("Invalid multipart form data: missing boundary");return i$($,Z,Q?.fileUploads)}if(X===x.form)return n$($,Q?.urlEncoded);return $};var A$=($,W)=>{let Y=$.indexOf(W);if(Y===-1)return[$,""];let Z=$.slice(0,Y),Q=$.slice(Y+W.length);return[Z,Q]};var e$=($)=>{if(!$||!$.trim())return{method:"GET",path:"/",protocol:"HTTP/1.1",headersRaw:"",rawBody:""};let[W,Y]=A$($,`\r
11
+ `),[Z,Q,X]=W.split(" ",3),[M,K]=A$(Y,`\r
12
12
  \r
13
- `);if(!Y||!Object.values(_).includes(Y))return{method:"GET",path:Z??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:w};return{method:Y,path:Z??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:w}};var c$=($)=>{if(!$)return{};if(!$.includes("?"))return{};let[,M]=$.split("?");if(!M)return{};let W={},Y=M.split("&");for(let Z of Y){let[Q,X]=Z.split("=");if(Q)try{let w=decodeURIComponent(Q),V=X?decodeURIComponent(X):"";W[w]=V}catch{W[Q]=X??""}}return W};var i1=[/^(?<classA>10)\./,/^(?<classB>172)\.(?<classBRange>1[6-9]|2[0-9]|3[0-1])\./,/^(?<classC>192)\.(?<classCRange>168)\./,/^(?<linkLocal>169)\.(?<linkLocalRange>254)\./,/^(?<loopback>127)\./,/^(?<ipv6Loopback>::1)$/,/^(?<ipv6LinkLocal>fe80):/i,/^(?<ipv6UniqueLocalFC>fc00):/i,/^(?<ipv6UniqueLocalFD>fd00):/i],d$=($)=>{if(!$||typeof $!=="string")return!1;let M=$.replace(/^\[|\]$/g,"");if(/^(?<octet>(?<highByte>25[0-5]|(?<midByte>2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/.test(M)){let Z=M.split(".");return Z.length===4&&Z.every((Q)=>{let X=parseInt(Q,10);return X>=0&&X<=255})}if(M.includes("::")&&(M.match(/::/g)??[]).length>1)return!1;return/^(?<ipv6Address>(?<fullAddress>(?<hexQuad>[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})|(?<compressedAddress>(?<leadingPart>[0-9a-fA-F]{1,4}:){1,7}:)|(?<mixedCompression>(?<frontPart>[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4})|(?<doubleColonOnly>::)|(?<linkLocal>fe80:(?<linkSuffix>:[0-9a-fA-F]{0,4}){0,4}(?<zoneId>%[0-9a-zA-Z]+)?)|(?<ipv4MappedFull>::ffff:(?<mappedIpv4>(?<mappedOctet>[0-9]{1,3}\.){3}[0-9]{1,3}))|(?<generalPattern>(?<segmentGroup>[0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}))$/.test(M)},i$=($)=>{if(!$)return!1;let M=$.replace(/^\[|\]$/g,"");return i1.some((W)=>W.test(M))},a$=($,M)=>{if(!$||!M.length)return!1;if(M.includes("*"))return!0;return M.includes($)},a1=($,M)=>{if(!M.detectSpoofing||$.length<=1)return!1;if($.length>M.maxChainLength)return!0;if(new Set($).size!==$.length)return!0;let Y=$.filter(d$).length;if(Y>0&&Y<$.length)return!0;return!1},n1=($,M)=>{if($.length<=1)return!0;let W=$[$.length-1];return Boolean(W&&a$(W,M.trustedProxies))},t1=($,M)=>{if(M==="x-forwarded-for")return $[0];return $[$.length-1]},o1=($)=>{let{clientIp:M,headerName:W,ipChain:Y,config:Z}=$,Q=i$(M),X=W==="x-forwarded-for"?a$(Y[Y.length-1]??"",Z.trustedProxies):!0;return{ip:M,isValid:!0,isPrivate:Q,source:W,trusted:X}},e1=()=>({ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}),$0=($,M)=>{for(let W of M.headerPreference){let Y=$[W];if(!Y)continue;let Z=Y.split(",").map((w)=>w.trim()).filter(Boolean);if(Z.length===0)continue;if(a1(Z,M))continue;if(W==="x-forwarded-for"&&!n1(Z,M))continue;let Q=t1(Z,W);if(!Q||!d$(Q))continue;if(i$(Q)&&!M.allowPrivateIps)continue;return o1({clientIp:Q,headerName:W,ipChain:Z,config:M})}return e1()},M0=($,M,W={})=>{let Z={...$._configuration.ipSecurity,...W},Q=$0(M,Z);if(Q.isValid)return Q;return{ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}},n$=($,M)=>{return M0($,M).ip};var t$=($)=>{if(!$)return;return/boundary\s*=\s*(?<temp1>[^;,\s]*)/i.exec($)?.[1]};var o$=($)=>{if(!$)return{};W0($);let M=Y0($),W=Z0(M);return Q0(W)},W0=($)=>{if($.split(/\r\n|\r|\n/).length>100)throw Error("Too many headers: maximum 100 allowed")},Y0=($)=>{let M={},Y=$.replace(/\r\n|\r|\n/g,`
13
+ `);if(!Z||!Object.values(k).includes(Z))return{method:"GET",path:Q??"/",protocol:X??"HTTP/1.1",headersRaw:M,rawBody:K};return{method:Z,path:Q??"/",protocol:X??"HTTP/1.1",headersRaw:M,rawBody:K}};var $1=($)=>{if(!$)return{};if(!$.includes("?"))return{};let[,W]=$.split("?");if(!W)return{};let Y={},Z=W.split("&");for(let Q of Z){let[X,M]=Q.split("=");if(X)try{let K=decodeURIComponent(X),V=M?decodeURIComponent(M):"";Y[K]=V}catch{Y[X]=M??""}}return Y};var Q0=[/^(?<classA>10)\./,/^(?<classB>172)\.(?<classBRange>1[6-9]|2[0-9]|3[0-1])\./,/^(?<classC>192)\.(?<classCRange>168)\./,/^(?<linkLocal>169)\.(?<linkLocalRange>254)\./,/^(?<loopback>127)\./,/^(?<ipv6Loopback>::1)$/,/^(?<ipv6LinkLocal>fe80):/i,/^(?<ipv6UniqueLocalFC>fc00):/i,/^(?<ipv6UniqueLocalFD>fd00):/i],W1=($)=>{if(!$||typeof $!=="string")return!1;let W=$.replace(/^\[|\]$/g,"");if(/^(?<octet>(?<highByte>25[0-5]|(?<midByte>2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/.test(W)){let Q=W.split(".");return Q.length===4&&Q.every((X)=>{let M=parseInt(X,10);return M>=0&&M<=255})}if(W.includes("::")&&(W.match(/::/g)??[]).length>1)return!1;return/^(?<ipv6Address>(?<fullAddress>(?<hexQuad>[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})|(?<compressedAddress>(?<leadingPart>[0-9a-fA-F]{1,4}:){1,7}:)|(?<mixedCompression>(?<frontPart>[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4})|(?<doubleColonOnly>::)|(?<linkLocal>fe80:(?<linkSuffix>:[0-9a-fA-F]{0,4}){0,4}(?<zoneId>%[0-9a-zA-Z]+)?)|(?<ipv4MappedFull>::ffff:(?<mappedIpv4>(?<mappedOctet>[0-9]{1,3}\.){3}[0-9]{1,3}))|(?<generalPattern>(?<segmentGroup>[0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}))$/.test(W)},Y1=($)=>{if(!$)return!1;let W=$.replace(/^\[|\]$/g,"");return Q0.some((Y)=>Y.test(W))},Z1=($,W)=>{if(!$||!W.length)return!1;if(W.includes("*"))return!0;return W.includes($)},X0=($,W)=>{if(!W.detectSpoofing||$.length<=1)return!1;if($.length>W.maxChainLength)return!0;if(new Set($).size!==$.length)return!0;let Z=$.filter(W1).length;if(Z>0&&Z<$.length)return!0;return!1},M0=($,W)=>{if($.length<=1)return!0;let Y=$[$.length-1];return Boolean(Y&&Z1(Y,W.trustedProxies))},J0=($,W)=>{if(W==="x-forwarded-for")return $[0];return $[$.length-1]},D0=($)=>{let{clientIp:W,headerName:Y,ipChain:Z,config:Q}=$,X=Y1(W),M=Y==="x-forwarded-for"?Z1(Z[Z.length-1]??"",Q.trustedProxies):!0;return{ip:W,isValid:!0,isPrivate:X,source:Y,trusted:M}},K0=()=>({ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}),j0=($,W)=>{for(let Y of W.headerPreference){let Z=$[Y];if(!Z)continue;let Q=Z.split(",").map((K)=>K.trim()).filter(Boolean);if(Q.length===0)continue;if(X0(Q,W))continue;if(Y==="x-forwarded-for"&&!M0(Q,W))continue;let X=J0(Q,Y);if(!X||!W1(X))continue;if(Y1(X)&&!W.allowPrivateIps)continue;return D0({clientIp:X,headerName:Y,ipChain:Q,config:W})}return K0()},U0=($,W,Y={})=>{let Q={...$._configuration.ipSecurity,...Y},X=j0(W,Q);if(X.isValid)return X;return{ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}},Q1=($,W)=>{return U0($,W).ip};var X1=($)=>{if(!$)return;return/boundary\s*=\s*(?<temp1>[^;,\s]*)/i.exec($)?.[1]};var M1=($)=>{if(!$)return{};G0($);let W=F0($),Y=H0(W);return q0(Y)},G0=($)=>{if($.split(/\r\n|\r|\n/).length>100)throw Error("Too many headers: maximum 100 allowed")},F0=($)=>{let W={},Z=$.replace(/\r\n|\r|\n/g,`
14
14
  `).split(`
15
- `);for(let Z of Y){if(!Z.trim())continue;let Q=Z.indexOf(":");if(Q===-1)continue;let X=Z.slice(0,Q).trim(),w=Z.slice(Q+1).trim();if(!X)continue;if(!X0(X))throw Error(`Invalid header name: ${X}`);if(X.length>200)throw Error("Header name too long: maximum 200 characters allowed");if(w.length>8192)throw Error("Header value too long: maximum 8192 characters allowed");M[X.toLowerCase()]=w}return M},Z0=($)=>{let M={};for(let[W,Y]of Object.entries($))M[W]=J0(Y);return M},Q0=($)=>$,X0=($)=>{return/^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/.test($)},J0=($)=>{return $.replace(/[\x00-\x08\x0A-\x1F\x7F]/g,"")};class V${_rawRequest;_setup;method;path;protocol;headers;body;query;params;ipAddress;rawBody;constructor($,M,W){this._rawRequest=$,this._setup=M,this.ipAddress=W??"";let{method:Y,path:Z,protocol:Q,headers:X,body:w,query:V,params:A,rawBody:u}=this._parseRequestIntoObject();this.method=Y,this.path=Z,this.protocol=Q,this.headers=X,this.body=w,this.query=V??{},this.params=A??{},this.rawBody=u;let L=n$(this._setup,X);if(L)this.ipAddress=L}_parseRequestIntoObject(){let $=this._rawRequest.toString(),{method:M,path:W,protocol:Y,headersRaw:Z,rawBody:Q}=s$($),X=o$(Z),w=X["content-type"],V=w?.split(";")[0]?.trim().toLowerCase(),A=t$(w);return{method:M,path:W,protocol:Y,headers:X,body:r$(Q,{headerContentType:V,boundary:A,config:this._setup._configuration.bodyParser}),query:c$(W),params:{},rawBody:Q}}}var W1=D$(o(),1);var e$=($,M)=>{let W=M?.encoding??"utf8";if($===null||$===void 0)return"";if(Buffer.isBuffer($))return O$($,W);if($ instanceof Uint8Array)return D0($,W);if($ instanceof ArrayBuffer)return K0($,W);if(typeof $==="string")return $;if(typeof $==="object")return w0($);return String($)},O$=($,M)=>{if(M==="base64")return $.toString("base64");if(M==="binary")return $.toString("binary");return $.toString("utf8")},D0=($,M)=>{let W=Buffer.from($);return O$(W,M)},K0=($,M)=>{let W=Buffer.from($);return O$(W,M)},w0=($)=>{try{return JSON.stringify($)}catch(M){return String($)}};var $1=new Map;for(let[$,M]of Object.entries(P)){let Y=s[$];$1.set(M,Y)}var M1=($)=>{let M=$1.get($);if(!M)throw Error(`Unknown status code: ${$}`);return M};var j0=($,M)=>{if(typeof M!=="string")throw Error(`Header value must be a string, got ${typeof M}`);if(M.includes("\r")||M.includes(`
16
- `))throw Error(`Header value contains invalid line break characters: ${$}`);let W=[/[\r\n](?:set-cookie|location|authorization|www-authenticate):/i,/\r\n\r\n|\n\n/,/[\r\n]http\/\d\.\d\s+\d+/i];for(let Y of W)if(Y.test(M))throw Error(`Header value contains suspicious injection pattern: ${$}`)},U0=($)=>{for(let[M,W]of Object.entries($))j0(M,W)},B$=($)=>{let M={};for(let[W,Y]of Object.entries($))if(Y!==void 0)M[W]=Y;return U0(M),M};var i=($)=>{if(F0($))return $.length;if(typeof $==="string")return Buffer.byteLength($,"utf8");if(G0($))try{let M=JSON.stringify($);return Buffer.byteLength(M,"utf8")}catch{return 0}return 0},F0=($)=>typeof Buffer<"u"&&Buffer.isBuffer($),G0=($)=>typeof $==="object"&&$!==null;class N${_request;_statusCode=P.ok;_status=s.ok;_headers={};_body="";_stringBody="";_encoding=x$.utf8;constructor($){this._request=$,this._setSecurityHeaders()}_parseResponseIntoString(){let $=`${this._request.protocol} ${this._statusCode} ${this._status}`,M=Object.entries(this._headers).map(([X,w])=>`${X}: ${w}`),W=Y$(this._headers["content-type"],this._body),Y=e$(this._body,{encoding:W});this._encoding=W;let Z=M.length>0?`${M.join(`
15
+ `);for(let Q of Z){if(!Q.trim())continue;let X=Q.indexOf(":");if(X===-1)continue;let M=Q.slice(0,X).trim(),K=Q.slice(X+1).trim();if(!M)continue;if(!w0(M))throw Error(`Invalid header name: ${M}`);if(M.length>200)throw Error("Header name too long: maximum 200 characters allowed");if(K.length>8192)throw Error("Header value too long: maximum 8192 characters allowed");W[M.toLowerCase()]=K}return W},H0=($)=>{let W={};for(let[Y,Z]of Object.entries($))W[Y]=V0(Z);return W},q0=($)=>$,w0=($)=>{return/^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/.test($)},V0=($)=>{return $.replace(/[\x00-\x08\x0A-\x1F\x7F]/g,"")};class z${_rawRequest;_setup;method;path;protocol;headers;body;query;params;ipAddress;rawBody;constructor($,W,Y){this._rawRequest=$,this._setup=W,this.ipAddress=Y??"";let{method:Z,path:Q,protocol:X,headers:M,body:K,query:V,params:z,rawBody:C}=this._parseRequestIntoObject();this.method=Z,this.path=Q,this.protocol=X,this.headers=M,this.body=K,this.query=V??{},this.params=z??{},this.rawBody=C;let A=Q1(this._setup,M);if(A)this.ipAddress=A}_parseRequestIntoObject(){let $=this._rawRequest.toString(),{method:W,path:Y,protocol:Z,headersRaw:Q,rawBody:X}=e$($),M=M1(Q),K=M["content-type"],V=K?.split(";")[0]?.trim().toLowerCase(),z=X1(K);return{method:W,path:Y,protocol:Z,headers:M,body:o$(X,{headerContentType:V,boundary:z,config:this._setup._configuration.bodyParser}),query:$1(Y),params:{},rawBody:X}}}var j1=H$(Z$(),1);var J1=($,W)=>{let Y=W?.encoding??"utf8";if($===null||$===void 0)return"";if(Buffer.isBuffer($))return _$($,Y);if($ instanceof Uint8Array)return B0($,Y);if($ instanceof ArrayBuffer)return O0($,Y);if(typeof $==="string")return $;if(typeof $==="object")return N0($);return String($)},_$=($,W)=>{if(W==="base64")return $.toString("base64");if(W==="binary")return $.toString("binary");return $.toString("utf8")},B0=($,W)=>{let Y=Buffer.from($);return _$(Y,W)},O0=($,W)=>{let Y=Buffer.from($);return _$(Y,W)},N0=($)=>{try{return JSON.stringify($)}catch(W){return String($)}};var D1=new Map;for(let[$,W]of Object.entries(b)){let Z=a[$];D1.set(W,Z)}var K1=($)=>{let W=D1.get($);if(!W)throw Error(`Unknown status code: ${$}`);return W};var E0=($,W)=>{if(typeof W!=="string")throw Error(`Header value must be a string, got ${typeof W}`);if(W.includes("\r")||W.includes(`
16
+ `))throw Error(`Header value contains invalid line break characters: ${$}`);let Y=[/[\r\n](?:set-cookie|location|authorization|www-authenticate):/i,/\r\n\r\n|\n\n/,/[\r\n]http\/\d\.\d\s+\d+/i];for(let Z of Y)if(Z.test(W))throw Error(`Header value contains suspicious injection pattern: ${$}`)},A0=($)=>{for(let[W,Y]of Object.entries($))E0(W,Y)},k$=($)=>{let W={};for(let[Y,Z]of Object.entries($))if(Z!==void 0)W[Y]=Z;return A0(W),W};var t=($)=>{if(z0($))return $.length;if(typeof $==="string")return Buffer.byteLength($,"utf8");if(_0($))try{let W=JSON.stringify($);return Buffer.byteLength(W,"utf8")}catch{return 0}return 0},z0=($)=>typeof Buffer<"u"&&Buffer.isBuffer($),_0=($)=>typeof $==="object"&&$!==null;class I${_request;_statusCode=b.ok;_status=a.ok;_headers={};_body="";_stringBody="";_encoding=l$.utf8;constructor($){this._request=$,this._setSecurityHeaders()}_parseResponseIntoString(){let $=`${this._request.protocol} ${this._statusCode} ${this._status}`,W=Object.entries(this._headers).map(([M,K])=>`${M}: ${K}`),Y=D$(this._headers["content-type"],this._body),Z=J1(this._body,{encoding:Y});this._encoding=Y;let Q=W.length>0?`${W.join(`
17
17
  `)}
18
18
  `:"";this._stringBody=`${$}
19
- ${Z}
20
- ${Y}`;let Q=i(this._stringBody);this._setHeadersIfNotSet({Date:W1.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":String(Q)})}_setHeadersIfNotSet($){let M={};for(let[Y,Z]of Object.entries($))if(Z!==void 0&&!(Y in this._headers))M[Y]=Z;let W=B$(M);Object.assign(this._headers,W)}_setBody($){if(this._body=$,!this._headers["content-type"]){let M=p$($);this._setHeadersIfNotSet({"Content-Type":M})}}setStatusCode($){this._statusCode=$,this._status=M1($)}addHeaders($){let M=B$($);this._headers={...this._headers,...M}}removeHeaders($){for(let M of $)delete this._headers[M]}_setSecurityHeaders(){this._setHeadersIfNotSet({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"1; mode=block","Referrer-Policy":"strict-origin-when-cross-origin"})}}class _${_request;_response;request;response;state={};constructor($,M,W){this._request=new V$($,M,W),this._response=new N$(this._request),this.request=this._request,this.response=this._response}}var H0={enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:P.noContent},Z$={json:{maxSize:262144,maxDepth:10,allowPrototypeProperties:!1,maxKeys:1000,maxStringLength:1048576,maxArrayLength:1e4},fileUploads:{maxFileSize:10485760,maxTotalSize:52428800,maxFiles:10,allowedExtensions:[],blockedExtensions:[".exe",".bat",".cmd",".scr",".pif",".com"],maxFilenameLength:255},urlEncoded:{maxSize:1048576,maxFields:1000,maxFieldNameLength:100,maxFieldLength:1048576}},Y1={trustedProxies:["127.0.0.1","::1"],allowPrivateIps:!0,headerPreference:["x-forwarded-for","x-real-ip","cf-connecting-ip","x-client-ip","true-client-ip"],maxChainLength:10,detectSpoofing:!0},q0={port:5000,host:"0.0.0.0",networkLogs:!1,cors:{enabled:!1},bodyParser:Z$,ipSecurity:Y1,connectionOptions:{socketTimeout:30000,gracefulShutdownTimeout:30000,keepAliveTimeout:65000,headersTimeout:66000},autoGracefulShutdown:!0},V0=($)=>{if($.maxSize<1)throw Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw Error("bodyParser.json.maxArrayLength must be at least 1")},O0=($)=>{if($.maxFileSize<1)throw Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},B0=($)=>{if($.maxSize<1)throw Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},N0=($)=>{if(!Array.isArray($.trustedProxies))throw Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},_0=($)=>{if($.allowPrototypeProperties)H.warn("[SECURITY WARNING] bodyParser.json.allowPrototypeProperties is enabled. This allows prototype pollution attacks. Only enable this if you absolutely need it and have other protections in place.");if($.maxSize>10485760)H.warn(`[SECURITY WARNING] bodyParser.json.maxSize is set to ${$.maxSize} bytes (${Math.round($.maxSize/1024/1024)}MB). Large JSON payloads can cause memory exhaustion and DoS attacks. Consider if this size is necessary.`);if($.maxDepth>50)H.warn(`[SECURITY WARNING] bodyParser.json.maxDepth is set to ${$.maxDepth}. Very deep JSON nesting can cause stack overflow attacks. Consider if this depth is necessary.`)},k0=($)=>{if($.maxFileSize>104857600)H.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxFileSize is set to ${$.maxFileSize} bytes (${Math.round($.maxFileSize/1024/1024)}MB). Large file uploads can consume significant server resources.`);if($.maxTotalSize>1073741824)H.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxTotalSize is set to ${$.maxTotalSize} bytes (${Math.round($.maxTotalSize/1024/1024/1024)}GB). Very large total upload sizes can cause memory and disk space exhaustion.`);let M=[".exe",".bat",".cmd",".scr",".pif",".com",".vbs",".jar",".app"],W=$.allowedExtensions.filter((Y)=>M.includes(Y.toLowerCase()));if(W.length>0)H.warn(`[SECURITY WARNING] bodyParser.fileUploads.allowedExtensions includes dangerous file types: ${W.join(", ")}. This could allow execution of malicious files. Only allow these if absolutely necessary.`);if($.blockedExtensions.length===0&&$.allowedExtensions.length===0)H.warn("[SECURITY WARNING] File uploads have no extension restrictions (no blockedExtensions and no allowedExtensions). Consider adding blockedExtensions or allowedExtensions to improve security.")},E0=($)=>{if($.trustedProxies.length===0)H.warn("[SECURITY WARNING] ipSecurity.trustedProxies is empty. No proxy headers will be trusted, which may prevent proper client IP detection.");if($.maxChainLength>20)H.warn(`[SECURITY WARNING] ipSecurity.maxChainLength is set to ${$.maxChainLength}. Very long proxy chains can consume significant resources and may indicate amplification attacks.`);if(!$.detectSpoofing)H.warn("[SECURITY WARNING] ipSecurity.detectSpoofing is disabled. This reduces protection against IP spoofing attacks. Only disable if you have other protective measures.")},L0=($,M)=>{if(M?.cors?.enabled)$.cors={...H0,...M.cors,enabled:!0}},A0=($,M)=>{if(M?.bodyParser)$.bodyParser={json:{...Z$.json,...M.bodyParser.json},fileUploads:{...Z$.fileUploads,...M.bodyParser.fileUploads},urlEncoded:{...Z$.urlEncoded,...M.bodyParser.urlEncoded}},S0($.bodyParser)},z0=($,M)=>{if(M?.ipSecurity)$.ipSecurity={...Y1,...M.ipSecurity},N0($.ipSecurity),E0($.ipSecurity)},I0=($,M)=>{if(M?.port!==void 0){let W=Number(M.port);if(isNaN(W)||W<1||W>65535)throw Error("Invalid port number");$.port=W}},S0=($)=>{V0($.json),O0($.fileUploads),B0($.urlEncoded),_0($.json),k0($.fileUploads)},Z1=($)=>{let M={...q0};return Object.assign(M,$),L0(M,$),A0(M,$),z0(M,$),I0(M,$),M};class k${_beforeAll;_afterAll;_onError;_onNotFound;constructor(){this._beforeAll=new Set,this._afterAll=new Set,this._onError=($,M)=>{return H.error("Error while handeling your request: ",M),$.response.setStatusCode(P.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(P.notFound),{success:!1,message:"404 Not Found"}}}_addBeforeHooks($,M){this._validateHandlersArray($,"beforeAll");for(let W of $)this._beforeAll.add({handler:W,options:M??{routesToExclude:[],routesToInclude:[]}})}_addAfterHooks($,M){this._validateHandlersArray($,"afterAll");for(let W of $)this._afterAll.add({handler:W,options:M??{routesToExclude:[],routesToInclude:[]}})}_validateHandlersArray($,M){if(!Array.isArray($)){let W=typeof $;throw Error(`YinzerFlow: ${M}() expects an array of handler functions, but received ${W}.${W==="function"?`
19
+ ${Q}
20
+ ${Z}`;let X=t(this._stringBody);this._setHeadersIfNotSet({Date:j1.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":String(X)})}_setHeadersIfNotSet($){let W={};for(let[Z,Q]of Object.entries($))if(Q!==void 0&&!(Z in this._headers))W[Z]=Q;let Y=k$(W);Object.assign(this._headers,Y)}_setBody($){if(this._body=$,!this._headers["content-type"]){let W=t$($);this._setHeadersIfNotSet({"Content-Type":W})}}setStatusCode($){this._statusCode=$,this._status=K1($)}addHeaders($){let W=k$($);this._headers={...this._headers,...W}}removeHeaders($){for(let W of $)delete this._headers[W]}_setSecurityHeaders(){this._setHeadersIfNotSet({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"1; mode=block","Referrer-Policy":"strict-origin-when-cross-origin"})}}class S${_request;_response;request;response;state={};constructor($,W,Y){this._request=new z$($,W,Y),this._response=new I$(this._request),this.request=this._request,this.response=this._response}}var k0={enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:b.noContent},K$={json:{maxSize:262144,maxDepth:10,allowPrototypeProperties:!1,maxKeys:1000,maxStringLength:1048576,maxArrayLength:1e4},fileUploads:{maxFileSize:10485760,maxTotalSize:52428800,maxFiles:10,allowedExtensions:[],blockedExtensions:[".exe",".bat",".cmd",".scr",".pif",".com"],maxFilenameLength:255},urlEncoded:{maxSize:1048576,maxFields:1000,maxFieldNameLength:100,maxFieldLength:1048576}},U1={trustedProxies:["127.0.0.1","::1"],allowPrivateIps:!0,headerPreference:["x-forwarded-for","x-real-ip","cf-connecting-ip","x-client-ip","true-client-ip"],maxChainLength:10,detectSpoofing:!0},I0={port:5000,host:"0.0.0.0",networkLogs:!1,gracefulShutdownTimeout:"15m",cors:{enabled:!1},bodyParser:K$,ipSecurity:U1},S0=($)=>{if($.maxSize<1)throw Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw Error("bodyParser.json.maxArrayLength must be at least 1")},L0=($)=>{if($.maxFileSize<1)throw Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},T0=($)=>{if($.maxSize<1)throw Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},v0=($)=>{if(!Array.isArray($.trustedProxies))throw Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},P0=($)=>{if($.allowPrototypeProperties)G.warn("[SECURITY WARNING] bodyParser.json.allowPrototypeProperties is enabled. This allows prototype pollution attacks. Only enable this if you absolutely need it and have other protections in place.");if($.maxSize>10485760)G.warn(`[SECURITY WARNING] bodyParser.json.maxSize is set to ${$.maxSize} bytes (${Math.round($.maxSize/1024/1024)}MB). Large JSON payloads can cause memory exhaustion and DoS attacks. Consider if this size is necessary.`);if($.maxDepth>50)G.warn(`[SECURITY WARNING] bodyParser.json.maxDepth is set to ${$.maxDepth}. Very deep JSON nesting can cause stack overflow attacks. Consider if this depth is necessary.`)},R0=($)=>{if($.maxFileSize>104857600)G.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxFileSize is set to ${$.maxFileSize} bytes (${Math.round($.maxFileSize/1024/1024)}MB). Large file uploads can consume significant server resources.`);if($.maxTotalSize>1073741824)G.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxTotalSize is set to ${$.maxTotalSize} bytes (${Math.round($.maxTotalSize/1024/1024/1024)}GB). Very large total upload sizes can cause memory and disk space exhaustion.`);let W=[".exe",".bat",".cmd",".scr",".pif",".com",".vbs",".jar",".app"],Y=$.allowedExtensions.filter((Z)=>W.includes(Z.toLowerCase()));if(Y.length>0)G.warn(`[SECURITY WARNING] bodyParser.fileUploads.allowedExtensions includes dangerous file types: ${Y.join(", ")}. This could allow execution of malicious files. Only allow these if absolutely necessary.`);if($.blockedExtensions.length===0&&$.allowedExtensions.length===0)G.warn("[SECURITY WARNING] File uploads have no extension restrictions (no blockedExtensions and no allowedExtensions). Consider adding blockedExtensions or allowedExtensions to improve security.")},b0=($)=>{if($.trustedProxies.length===0)G.warn("[SECURITY WARNING] ipSecurity.trustedProxies is empty. No proxy headers will be trusted, which may prevent proper client IP detection.");if($.maxChainLength>20)G.warn(`[SECURITY WARNING] ipSecurity.maxChainLength is set to ${$.maxChainLength}. Very long proxy chains can consume significant resources and may indicate amplification attacks.`);if(!$.detectSpoofing)G.warn("[SECURITY WARNING] ipSecurity.detectSpoofing is disabled. This reduces protection against IP spoofing attacks. Only disable if you have other protective measures.")},x0=($,W)=>{if(W?.cors?.enabled)$.cors={...k0,...W.cors,enabled:!0}},C0=($,W)=>{if(W?.bodyParser)$.bodyParser={json:{...K$.json,...W.bodyParser.json},fileUploads:{...K$.fileUploads,...W.bodyParser.fileUploads},urlEncoded:{...K$.urlEncoded,...W.bodyParser.urlEncoded}},h0($.bodyParser)},y0=($,W)=>{if(W?.ipSecurity)$.ipSecurity={...U1,...W.ipSecurity},v0($.ipSecurity),b0($.ipSecurity)},u0=($,W)=>{if(W?.port!==void 0){let Y=Number(W.port);if(isNaN(Y)||Y<1||Y>65535)throw Error("Invalid port number");$.port=Y}},h0=($)=>{S0($.json),L0($.fileUploads),T0($.urlEncoded),P0($.json),R0($.fileUploads)},G1=($)=>{let W={...I0};return Object.assign(W,$),x0(W,$),C0(W,$),y0(W,$),u0(W,$),W};class L${_beforeAll;_afterAll;_onError;_onNotFound;constructor(){this._beforeAll=new Set,this._afterAll=new Set,this._onError=($,W)=>{return G.error("Error while handeling your request: ",W),$.response.setStatusCode(b.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(b.notFound),{success:!1,message:"404 Not Found"}}}_addBeforeHooks($,W){this._validateHandlersArray($,"beforeAll");for(let Y of $)this._beforeAll.add({handler:Y,options:W??{routesToExclude:[],routesToInclude:[]}})}_addAfterHooks($,W){this._validateHandlersArray($,"afterAll");for(let Y of $)this._afterAll.add({handler:Y,options:W??{routesToExclude:[],routesToInclude:[]}})}_validateHandlersArray($,W){if(!Array.isArray($)){let Y=typeof $;throw Error(`YinzerFlow: ${W}() expects an array of handler functions, but received ${Y}.${Y==="function"?`
21
21
 
22
- ❌ Incorrect: app.${M}${q.red}(${q.reset}(ctx) => { ... }${q.red})${q.reset}
23
- ✅ Correct: app.${M}${q.green}([${q.reset}(ctx) => { ... }${q.green}])${q.reset}
22
+ ❌ Incorrect: app.${W}${B.red}(${B.reset}(ctx) => { ... }${B.red})${B.reset}
23
+ ✅ Correct: app.${W}${B.green}([${B.reset}(ctx) => { ... }${B.green}])${B.reset}
24
24
 
25
- Note: Wrap your handler function in ${q.magenta}square brackets${q.reset} to make it an array.
25
+ Note: Wrap your handler function in ${B.magenta}square brackets${B.reset} to make it an array.
26
26
 
27
27
  `:`
28
28
 
29
29
  Expected: Array<HandlerCallback>
30
- Received: ${W}`}`)}if($.length===0){H.warn(`${M}() called with empty array. No hooks will be registered.`);return}for(let W=0;W<$.length;W++){let Y=$[W];if(typeof Y!=="function")throw Error(`YinzerFlow: ${M}() array contains non-function at index ${W}. Expected: function, received: ${typeof Y}`)}}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var Q1=($)=>{let M=[],W=$.path.replace(/:\w+/g,(Y)=>{let Z=Y.slice(1);return M.push(Z),"([^/]+)"}).replace(/\//g,"\\/");return{...$,pattern:new RegExp(`^${W}$`),paramNames:M,isParameterized:!0}};var E$=($)=>{let[M]=$.split("?");if(!M)return"";if([M]=M.split("#"),!M)return"";try{M=decodeURIComponent(M)}catch(W){H.warn("Failed to decode URL path",{path:M})}if(M=M.startsWith("/")?M:`/${M}`,M=M.replace(/\/\/+/g,"/"),M=v0(M),M.length>1&&M.endsWith("/"))M=M.slice(0,-1);return M},v0=($)=>{let M=$.split("/"),W=[];for(let Z of M){if(Z==="."||Z===""){if(Z===""&&W.length===0)W.push(Z);continue}if(Z===".."){if(W.length>1)W.pop()}else W.push(Z)}return W.join("/")||"/"},L$=($)=>$.replace(/:\w+/g,":param");var X1=($)=>{let M=$.match(/:\w+/g);if(!M)return;let W=M.map((Z)=>Z.slice(1)),Y=new Set(W);if(W.length!==Y.size){let Z=W.filter((Q,X)=>W.indexOf(Q)!==X);throw Error(`Route ${$} has duplicate parameter names: ${Z.join(", ")}. Parameter names must be unique within a route for clarity and to prevent conflicts.`)}};class A${_exactRoutes=new Map;_parameterizedRoutes=new Map;_register({method:$,path:M,handler:W,options:Y}){let Z=E$(M),Q=Z.includes(":");if(Q)X1(Z);if(this._hasExactRoutePattern($,Z))throw Error(`Route ${Z} already exists for method ${$}`);let X={method:$,path:Z,handler:W,options:Y,params:{}};if(Q)this._storeParameterizedRoute($,X);else this._storeExactRoute($,Z,X)}_findRoute($,M){let W=E$(M),Y=this._exactRoutes.get($)?.get(W);if(Y)return Y;let Z=this._findParameterizedRoute($,W);if(Z)return Z;return}_hasExactRoutePattern($,M){if(this._exactRoutes.get($)?.has(M))return!0;if(M.includes(":")){let W=L$(M),Y=this._parameterizedRoutes.get($);if(Y)return Y.some((Z)=>L$(Z.path)===W)}else{let W=this._parameterizedRoutes.get($);if(W)return W.some((Y)=>Y.path===M)}return!1}_storeExactRoute($,M,W){if(!this._exactRoutes.has($))this._exactRoutes.set($,new Map);this._exactRoutes.get($)?.set(M,W)}_storeParameterizedRoute($,M){if(!this._parameterizedRoutes.has($))this._parameterizedRoutes.set($,[]);let W=Q1(M);this._parameterizedRoutes.get($)?.push(W)}_findParameterizedRoute($,M){let W=this._parameterizedRoutes.get($);if(!W)return;for(let Y of W){let Z=M.match(Y.pattern);if(Z){let Q={};for(let X=0;X<Y.paramNames.length;X++){let w=Z[X+1],V=Y.paramNames[X];if(w!==void 0&&V!==void 0)Q[V]=w}return{...Y,params:Q}}}return}}var b=($)=>({beforeHooks:$?.beforeHooks??[],afterHooks:$?.afterHooks??[]}),z$=($,M)=>({beforeHooks:[...$.beforeHooks??[],...M?.beforeHooks??[]],afterHooks:[...M?.afterHooks??[],...$.afterHooks??[]]}),I$=($,M)=>{let W=$.endsWith("/")?$.slice(0,-1):$,Y=M.startsWith("/")?M:`/${M}`;return`${W}${Y}`};class Q${_setup;_prefix;_options;constructor($,M,W){this._setup=$,this._prefix=M,this._options=b(W)}_createRouteHandler($){return(M,W,Y)=>{let Z=I$(this._prefix,M),Q=z$(this._options,Y);if(this._setup._routeRegistry._register({method:$,handler:W,path:Z,options:Q,params:{}}),$===_.get)this._setup._routeRegistry._register({method:_.head,handler:W,path:Z,options:Q,params:{}})}}get=this._createRouteHandler(_.get);head=this._createRouteHandler(_.head);post=this._createRouteHandler(_.post);put=this._createRouteHandler(_.put);delete=this._createRouteHandler(_.delete);patch=this._createRouteHandler(_.patch);options=this._createRouteHandler(_.options);group($,M,W){let Y=I$(this._prefix,$),Z=z$(this._options,W),Q=new Q$(this._setup,Y,Z);return M(Q),Q}}class S${_configuration;_routeRegistry=new A$;_hooks=new k$;constructor($){this._configuration=Z1($)}get($,M,W){let Y=b(W);this._routeRegistry._register({method:_.get,handler:M,path:$,options:Y,params:{}}),this._routeRegistry._register({method:_.head,handler:M,path:$,options:Y,params:{}})}head($,M,W){this._routeRegistry._register({method:_.head,handler:M,path:$,options:b(W),params:{}})}post($,M,W){this._routeRegistry._register({method:_.post,handler:M,path:$,options:b(W),params:{}})}put($,M,W){this._routeRegistry._register({method:_.put,handler:M,path:$,options:b(W),params:{}})}patch($,M,W){this._routeRegistry._register({method:_.patch,handler:M,path:$,options:b(W),params:{}})}delete($,M,W){this._routeRegistry._register({method:_.delete,handler:M,path:$,options:b(W),params:{}})}options($,M,W){this._routeRegistry._register({method:_.options,handler:M,path:$,options:b(W),params:{}})}group($,M,W){let Y=new Q$(this,$,W);return M(Y),Y}beforeAll($,M){this._hooks._addBeforeHooks($,M)}afterAll($,M){this._hooks._addAfterHooks($,M)}onError($){this._hooks._addOnError($)}onNotFound($){this._hooks._addOnNotFound($)}}var J1={prefix:"NETWORK",logLevel:"off",logger:void 0},I={log:d(J1),enable:($)=>{I.log=d({...J1,logLevel:c.info,logger:$})}},D1=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},v$=[{maxTime:50,emoji:"⚡",phrase:"faster than a Stillers touchdown!"},{maxTime:100,emoji:"\uD83D\uDD25",phrase:"smooth as butter n'at!"},{maxTime:200,emoji:"✅",phrase:"not bad yinz!"},{maxTime:500,emoji:"⚠️",phrase:"slowin' down a bit there"},{maxTime:1000,emoji:"\uD83D\uDC0C",phrase:"that's draggin' n'at"},{maxTime:1/0,emoji:"\uD83D\uDCA5",phrase:"what a jagoff response time!"}],K1=($)=>{let M=v$.find((W)=>$<W.maxTime)??v$[v$.length-1];if(!M)throw Error("No threshold found for performance details");I.log.warn(`${q.magenta} ${M.emoji} Response time: ${$}ms - ${M.phrase}${q.reset}`)};class w1 extends S${_isListening=!1;_server;constructor($){super($);if(this._configuration.logger)Object.assign(H,this._configuration.logger);if(this._configuration.networkLogs)I.enable(this._configuration.networkLogger);if(this._configuration.autoGracefulShutdown)this._setupGracefulShutdown()}_setupServer($,M,W){if(!this._server)return;this._server.on("error",(Y)=>{I.log.error(`YinzerFlow server error at ${this._configuration.host}:${this._configuration.port} - ${Y.message}`),M(Y)}),this._server.on("listening",()=>{this._isListening=!0,I.log.info(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is up and running`),$()}),this._server.on("connection",(Y)=>{this._handleConnection(Y,W)})}async _processRequest({data:$,socket:M,requestHandler:W,clientAddress:Y}){let Z=Date.now();I.log.info("Incoming request",`${Y} ${i($)}bytes`);let Q=new _$($,this,Y);await W.handle(Q),M.write(Q._response._stringBody),M.end();let w=Date.now()-Z;I.log.info(`${D1(Q._response._statusCode)} ${Y} "${Q.request.method} ${Q.request.path} ${Q.request.protocol}" ${Q._response._statusCode} ${i(Q._response._body)}bytes "${Q.request.headers.referer??"-"}" "${Q.request.headers["user-agent"]??"-"}" ${w}ms`),K1(w)}_handleConnection($,M){let W=$.remoteAddress??"unknown",Y=Date.now(),Z=!1,Q=null;I.log.info(`New visitor from ${W}`),$.on("data",(X)=>{if(!Z){Z=!0,Q=Date.now();let w=Q-Y;if(w>100)I.log.warn(`Delayed data from ${W} (${w}ms connection delay)`)}this._processRequest({data:X,socket:$,requestHandler:M,clientAddress:W}).catch((w)=>{let V=w instanceof Error?w.message:"Unknown error";I.log.error(`Visitor from ${W} experienced an error during request processing: ${V}`,w),$.destroy()})}),$.on("error",(X)=>{I.log.error(`Visitor from ${W} experienced an error during socket connection: ${X.message}`,X)}),$.on("close",()=>{let X=Date.now()-Y;if(Z){I.log.info(`Visitor from ${W} headed out (${X}ms total)`);return}if(X<10)I.log.info(`${W} quick connectivity check (${X}ms) - health probe`);else I.log.warn(`${W} disconnected without sending data (${X}ms) - potential probe`)})}async listen(){if(this._isListening)throw Error("Server is already listening");return new Promise(($,M)=>{let W=new F$(this);this._server=T0(),this._setupServer($,M,W),this._server.listen(this._configuration.port,this._configuration.host)})}async close(){if(!this._isListening||!this._server)return;return new Promise(($)=>{if(!this._server){this._isListening=!1,$();return}this._server.close(()=>{this._isListening=!1,I.log.warn(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is shutting down - See yinz later`),$()})})}status(){return{isListening:this._isListening,port:this._configuration.port,host:this._configuration.host}}_setupGracefulShutdown(){if(process.listenerCount("SIGTERM")===0&&process.listenerCount("SIGINT")===0){let $=(M)=>{H.info(`\uD83D\uDED1 Received ${M}, shutting down gracefully...`),this.close().then(()=>{H.info("✅ Server shut down gracefully"),process.exit(0)}).catch((W)=>{H.error("❌ Error during graceful shutdown:",W),process.exit(1)})};process.on("SIGTERM",()=>$("SIGTERM")),process.on("SIGINT",()=>$("SIGINT"))}}}export{c as logLevels,H as log,P as httpStatusCode,s as httpStatus,d as createLogger,q as colors,w1 as YinzerFlow};
30
+ Received: ${Y}`}`)}if($.length===0){G.warn(`${W}() called with empty array. No hooks will be registered.`);return}for(let Y=0;Y<$.length;Y++){let Z=$[Y];if(typeof Z!=="function")throw Error(`YinzerFlow: ${W}() array contains non-function at index ${Y}. Expected: function, received: ${typeof Z}`)}}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var F1=($)=>{let W=[],Y=$.path.replace(/:\w+/g,(Z)=>{let Q=Z.slice(1);return W.push(Q),"([^/]+)"}).replace(/\//g,"\\/");return{...$,pattern:new RegExp(`^${Y}$`),paramNames:W,isParameterized:!0}};var T$=($)=>{let[W]=$.split("?");if(!W)return"";if([W]=W.split("#"),!W)return"";try{W=decodeURIComponent(W)}catch(Y){G.warn("Failed to decode URL path",{path:W})}if(W=W.startsWith("/")?W:`/${W}`,W=W.replace(/\/\/+/g,"/"),W=m0(W),W.length>1&&W.endsWith("/"))W=W.slice(0,-1);return W},m0=($)=>{let W=$.split("/"),Y=[];for(let Q of W){if(Q==="."||Q===""){if(Q===""&&Y.length===0)Y.push(Q);continue}if(Q===".."){if(Y.length>1)Y.pop()}else Y.push(Q)}return Y.join("/")||"/"},v$=($)=>$.replace(/:\w+/g,":param");var H1=($)=>{let W=$.match(/:\w+/g);if(!W)return;let Y=W.map((Q)=>Q.slice(1)),Z=new Set(Y);if(Y.length!==Z.size){let Q=Y.filter((X,M)=>Y.indexOf(X)!==M);throw Error(`Route ${$} has duplicate parameter names: ${Q.join(", ")}. Parameter names must be unique within a route for clarity and to prevent conflicts.`)}};class P${_exactRoutes=new Map;_parameterizedRoutes=new Map;_register({method:$,path:W,handler:Y,options:Z}){let Q=T$(W),X=Q.includes(":");if(X)H1(Q);if(this._hasExactRoutePattern($,Q))throw Error(`Route ${Q} already exists for method ${$}`);let M={method:$,path:Q,handler:Y,options:Z,params:{}};if(X)this._storeParameterizedRoute($,M);else this._storeExactRoute($,Q,M)}_findRoute($,W){let Y=T$(W),Z=this._exactRoutes.get($)?.get(Y);if(Z)return Z;let Q=this._findParameterizedRoute($,Y);if(Q)return Q;return}_hasExactRoutePattern($,W){if(this._exactRoutes.get($)?.has(W))return!0;if(W.includes(":")){let Y=v$(W),Z=this._parameterizedRoutes.get($);if(Z)return Z.some((Q)=>v$(Q.path)===Y)}else{let Y=this._parameterizedRoutes.get($);if(Y)return Y.some((Z)=>Z.path===W)}return!1}_storeExactRoute($,W,Y){if(!this._exactRoutes.has($))this._exactRoutes.set($,new Map);this._exactRoutes.get($)?.set(W,Y)}_storeParameterizedRoute($,W){if(!this._parameterizedRoutes.has($))this._parameterizedRoutes.set($,[]);let Y=F1(W);this._parameterizedRoutes.get($)?.push(Y)}_findParameterizedRoute($,W){let Y=this._parameterizedRoutes.get($);if(!Y)return;for(let Z of Y){let Q=W.match(Z.pattern);if(Q){let X={};for(let M=0;M<Z.paramNames.length;M++){let K=Q[M+1],V=Z.paramNames[M];if(K!==void 0&&V!==void 0)X[V]=K}return{...Z,params:X}}}return}}var y=($)=>({beforeHooks:$?.beforeHooks??[],afterHooks:$?.afterHooks??[]}),R$=($,W)=>({beforeHooks:[...$.beforeHooks??[],...W?.beforeHooks??[]],afterHooks:[...W?.afterHooks??[],...$.afterHooks??[]]}),b$=($,W)=>{let Y=$.endsWith("/")?$.slice(0,-1):$,Z=W.startsWith("/")?W:`/${W}`;return`${Y}${Z}`};class j${_setup;_prefix;_options;constructor($,W,Y){this._setup=$,this._prefix=W,this._options=y(Y)}_createRouteHandler($){return(W,Y,Z)=>{let Q=b$(this._prefix,W),X=R$(this._options,Z);if(this._setup._routeRegistry._register({method:$,handler:Y,path:Q,options:X,params:{}}),$===k.get)this._setup._routeRegistry._register({method:k.head,handler:Y,path:Q,options:X,params:{}})}}get=this._createRouteHandler(k.get);head=this._createRouteHandler(k.head);post=this._createRouteHandler(k.post);put=this._createRouteHandler(k.put);delete=this._createRouteHandler(k.delete);patch=this._createRouteHandler(k.patch);options=this._createRouteHandler(k.options);group($,W,Y){let Z=b$(this._prefix,$),Q=R$(this._options,Y),X=new j$(this._setup,Z,Q);return W(X),X}}class x${_configuration;_routeRegistry=new P$;_hooks=new L$;constructor($){this._configuration=G1($)}get($,W,Y){let Z=y(Y);this._routeRegistry._register({method:k.get,handler:W,path:$,options:Z,params:{}}),this._routeRegistry._register({method:k.head,handler:W,path:$,options:Z,params:{}})}head($,W,Y){this._routeRegistry._register({method:k.head,handler:W,path:$,options:y(Y),params:{}})}post($,W,Y){this._routeRegistry._register({method:k.post,handler:W,path:$,options:y(Y),params:{}})}put($,W,Y){this._routeRegistry._register({method:k.put,handler:W,path:$,options:y(Y),params:{}})}patch($,W,Y){this._routeRegistry._register({method:k.patch,handler:W,path:$,options:y(Y),params:{}})}delete($,W,Y){this._routeRegistry._register({method:k.delete,handler:W,path:$,options:y(Y),params:{}})}options($,W,Y){this._routeRegistry._register({method:k.options,handler:W,path:$,options:y(Y),params:{}})}group($,W,Y){let Z=new j$(this,$,Y);return W(Z),Z}beforeAll($,W){this._hooks._addBeforeHooks($,W)}afterAll($,W){this._hooks._addAfterHooks($,W)}onError($){this._hooks._addOnError($)}onNotFound($){this._hooks._addOnNotFound($)}}var q1={prefix:"NETWORK",logLevel:"off",logger:void 0},T={log:n(q1),enable:($)=>{T.log=n({...q1,logLevel:i.info,logger:$})}},w1=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},C$=[{maxTime:50,emoji:"⚡",phrase:"faster than a Stillers touchdown!"},{maxTime:100,emoji:"\uD83D\uDD25",phrase:"smooth as butter n'at!"},{maxTime:200,emoji:"✅",phrase:"not bad yinz!"},{maxTime:500,emoji:"⚠️",phrase:"slowin' down a bit there"},{maxTime:1000,emoji:"\uD83D\uDC0C",phrase:"that's draggin' n'at"},{maxTime:1/0,emoji:"\uD83D\uDCA5",phrase:"what a jagoff response time!"}],V1=($)=>{let W=C$.find((Y)=>$<Y.maxTime)??C$[C$.length-1];if(!W)throw Error("No threshold found for performance details");T.log.warn(`${B.magenta} ${W.emoji} Response time: ${$}ms - ${W.phrase}${B.reset}`)};var B1=()=>{let $=new Map;return{get:async(W)=>Promise.resolve($.get(W)),set:async(W,Y)=>{return $.set(W,Y),Promise.resolve()},delete:async(W)=>{return $.delete(W),Promise.resolve()},destroy:async()=>{return $.clear(),Promise.resolve()}}};var O1=async($)=>{let{store:W}=$;if(W.type!=="redis")throw Error(`Expected Redis store configuration but got: ${JSON.stringify(W)}`);let{client:Y,keyPrefix:Z="rate_limit:",maxRetries:Q=3,retryDelay:X=1000}=W,M=!1;await(async()=>{for(let w=1;w<=Q;w++)try{await Y.ping(),M=!0,G.info(`[RedisStore] Successfully connected to Redis (attempt ${w})`);return}catch(E){if(G.warn(`[RedisStore] Redis connection attempt ${w}/${Q} failed:`,E),w<Q)G.info(`[RedisStore] Retrying connection in ${X}ms...`),await new Promise((P)=>{setTimeout(P,X)});else G.error("[RedisStore] All Redis connection attempts failed. Store will operate in degraded mode."),M=!1}})();let V=(w)=>`${Z}${w}`,z=(w)=>{try{return JSON.stringify(w)}catch(E){throw G.error("[RedisStore] Failed to serialize value:",E),Error("Failed to serialize rate limit data")}},C=(w)=>{try{return JSON.parse(w)}catch(E){throw G.error("[RedisStore] Failed to deserialize value:",E),Error("Failed to deserialize rate limit data")}},A=(w,E)=>{if(M)G.warn(`[RedisStore] Redis ${w} failed (connection was healthy):`,E);else G.error(`[RedisStore] Redis ${w} failed (connection unhealthy):`,E)};return{get:async(w)=>{try{let E=V(w),P=await Y.get(E);if(P===null)return;return C(P)}catch(E){A("GET",E);return}},set:async(w,E)=>{try{let P=V(w),U$=z(E);await Y.setEx(P,Math.floor($.window/1000),U$)}catch(P){A("SET",P)}},delete:async(w)=>{try{let E=V(w);await Y.del(E)}catch(E){A("DELETE",E)}},destroy:async()=>{try{let w=`${Z}*`,E=await Y.keys(w);if(E.length>0)await Promise.all(E.map(async(P)=>Y.del(P))),G.info(`[RedisStore] Destroyed ${E.length} rate limit keys`)}catch(w){A("DESTROY",w)}}}};var p0=()=>({memory:()=>B1(),redis:async($)=>O1($)}),N1=async($)=>{let Y=p0()[$.store.type];if(!Y)throw Error(`Unsupported store type: ${$.store.type}`);return Y($)};class y${_config;_store=null;constructor($){this._config=$}async _getStore(){return this._store??=await N1(this._config),this._store}async check($){let W=await this._getStore(),Y=this._config.keyGenerator($),Z=Date.now(),Q=await W.get(Y)??{currentWindowCount:0,previousWindowCount:0,windowStart:Z},X=Z-Q.windowStart;if(X>=this._config.window){if(Math.floor(X/this._config.window)===1)Q.previousWindowCount=Q.currentWindowCount,Q.currentWindowCount=0;else Q.previousWindowCount=0,Q.currentWindowCount=0;Q.windowStart=Z}let M=X/this._config.window,K=Q.previousWindowCount*(1-M),V=Q.currentWindowCount+K,z=V<this._config.max;if(z)Q.currentWindowCount++;await W.set(Y,Q);let C=Math.max(0,Math.floor(this._config.max-V-(z?1:0))),A=Q.windowStart+this._config.window;return{allowed:z,remaining:C,resetTime:A,totalHits:Math.ceil(V+(z?1:0)),limit:this._config.max}}async destroy(){await(await this._getStore()).destroy()}}var f0=($)=>Math.ceil(($-Date.now())/1000),l0=($)=>new y$($);class o{_config;_strategy;constructor($){this._config=$,this._strategy=l0($)}async check($){return this._strategy.check($)}async destroy(){await this._strategy.destroy()}get config(){return this._config}}var u$=($,W)=>{if($.response.addHeaders({"RateLimit-Limit":String(W.limit),"RateLimit-Remaining":String(W.remaining),"RateLimit-Reset":String(Math.ceil(W.resetTime/1000))}),!W.allowed){let Y=f0(W.resetTime);$.response.addHeaders({"Retry-After":String(Y)})}};var h$={slidingWindowCounter:"sliding-window-counter"},g0={memory:"memory",redis:"redis"};var g=($)=>{if(typeof $==="number")return $;if(typeof $!=="string")throw Error("Invalid time format. Expected format: 1s, 1m, 1h, 1d");if($.length<2)throw Error("Invalid time format. Expected format: 1s, 1m, 1h, 1d");let W=$.slice(-1),Y=$.slice(0,-1);if(!["s","m","h","d"].includes(W))throw Error(`Invalid time unit: "${W}". Expected: s (seconds), m (minutes), h (hours), or d (days)`);let Z=Number(Y);if(isNaN(Z)||Z<=0)throw Error(`Invalid time value: "${Y}". Must be a positive number`);switch(W){case"s":return Z*1000;case"m":return Z*60*1000;case"h":return Z*60*60*1000;case"d":return Z*24*60*60*1000;default:throw Error(`Unsupported time unit: "${W}"`)}};class e{algorithm;store;window;max;standardHeaders;skipSuccessfulRequests;skipFailedRequests;keyGenerator;handler;constructor($){this._validateConfig($),this.algorithm=$?.algorithm??h$.slidingWindowCounter,this.store=$?.store??{type:"memory"},this.window=g($?.window??"15m"),this.max=$?.max??100,this.standardHeaders=$?.standardHeaders??!0,this.skipSuccessfulRequests=$?.skipSuccessfulRequests??!1,this.skipFailedRequests=$?.skipFailedRequests??!1,this.keyGenerator=$?.keyGenerator??c0,this.handler=$?.handler??r0}_validateConfig($){if(!$)return;s0($),d0($)}get config(){return{algorithm:this.algorithm,window:this.window,max:this.max,standardHeaders:this.standardHeaders,skipSuccessfulRequests:this.skipSuccessfulRequests,skipFailedRequests:this.skipFailedRequests,keyGenerator:this.keyGenerator,handler:this.handler}}}var s0=($)=>{if($.max!==void 0){if(typeof $.max!=="number"||isNaN($.max))throw Error("rateLimit.max must be a number");if($.max<1)throw Error("rateLimit.max must be at least 1 request per window");if(!Number.isInteger($.max))throw Error("rateLimit.max must be an integer (no decimals)")}if($.window!==void 0)if(typeof $.window==="string"){if(!/^(?<value>\d+)(?<unit>s|m|h|d)$/.test($.window))throw Error(`rateLimit.window must be a valid time string (e.g., '30s', '15m', '2h', '1d') or milliseconds as a number. Received: "${$.window}"`);let Y=g($.window);if(Y<1000)throw Error(`rateLimit.window must be at least 1000ms (1 second). Received: ${$.window} (${Y}ms). Very short time windows can cause performance issues and inaccurate rate limiting.`)}else if(typeof $.window==="number"){if(isNaN($.window))throw Error("rateLimit.window must be a valid number when using milliseconds");if($.window<1000)throw Error(`rateLimit.window must be at least 1000ms (1 second). Received: ${$.window}ms. Very short time windows can cause performance issues and inaccurate rate limiting.`);if(!Number.isInteger($.window))throw Error("rateLimit.window must be an integer when using milliseconds (no decimals)")}else throw Error('rateLimit.window must be a time string (e.g., "15m") or milliseconds as a number')},d0=($)=>{if($.enabled===!1)G.warn("[SECURITY WARNING] Rate limiting is disabled. This removes DoS protection from your API. Only disable for development or if you have external rate limiting (e.g., API gateway, CDN).");if($.max!==void 0&&$.max>1e4)G.warn(`[SECURITY WARNING] rateLimit.max is set to ${$.max} requests. Very high rate limits may not provide adequate DoS protection. Consider if this limit is necessary for your use case.`);if($.window!==void 0){let W=typeof $.window==="string"?g($.window):$.window,Y=3600000;if(W>3600000){let Z=Math.round(W/3600000);G.warn(`[SECURITY WARNING] rateLimit.window is set to ${typeof $.window==="string"?$.window:`${W}ms`} (${Z}h). Very long time windows may allow burst attacks before limits are enforced. Consider shorter windows for better protection.`)}}if($.window!==void 0){let W=typeof $.window==="string"?g($.window):$.window;if(W<1e4&&$.max!==void 0&&$.max>100)G.warn(`[PERFORMANCE WARNING] rateLimit.window is set to ${typeof $.window==="string"?$.window:`${W}ms`} with max ${$.max} requests. Very short time windows with high request counts can cause performance overhead. Consider increasing the window or decreasing max.`)}},r0=($)=>{return $.response.setStatusCode(b.tooManyRequests),{success:!1,message:"Yinz are sending too many requests. Slow down, jagoff!"}},c0=($)=>$.request.ipAddress;var a0=($)=>async(W)=>{let Y=new e($),Z=new o(Y),Q=await Z.check(W);if(Z.config.standardHeaders)u$(W,Q);if(!Q.allowed)return Z.config.handler(W);return},E1=($)=>async(W)=>{let Y=await $.check(W);if($.config.standardHeaders)u$(W,Y);if(!Y.allowed)return $.config.handler(W);return};class A1 extends x${_isListening=!1;_server;_globalRateLimiter;constructor($){super($);if(this._configuration.logger)Object.assign(G,this._configuration.logger);if(this._configuration.networkLogs)T.enable(this._configuration.networkLogger);let W=new e($?.rateLimit);if($?.rateLimit?.enabled){this._globalRateLimiter=new o(W);let Y=E1(this._globalRateLimiter);this.beforeAll([Y])}if(this._configuration.gracefulShutdownTimeout){let Y=g(this._configuration.gracefulShutdownTimeout);if(Y>0)this._setupGracefulShutdown(Y)}}_setupServer($,W,Y){if(!this._server)return;this._server.on("error",(Z)=>{T.log.error(`YinzerFlow server error at ${this._configuration.host}:${this._configuration.port} - ${Z.message}`),W(Z)}),this._server.on("listening",()=>{this._isListening=!0,T.log.info(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is up and running`),$()}),this._server.on("connection",(Z)=>{this._handleConnection(Z,Y)})}async _processRequest({data:$,socket:W,requestHandler:Y,clientAddress:Z}){let Q=Date.now();T.log.info("Incoming request",`${Z} ${t($)}bytes`);let X=new S$($,this,Z);await Y.handle(X),W.write(X._response._stringBody),W.end();let K=Date.now()-Q;T.log.info(`${w1(X._response._statusCode)} ${Z} "${X.request.method} ${X.request.path} ${X.request.protocol}" ${X._response._statusCode} ${t(X._response._body)}bytes "${X.request.headers.referer??"-"}" "${X.request.headers["user-agent"]??"-"}" ${K}ms`),V1(K)}_handleConnection($,W){let Y=$.remoteAddress??"unknown",Z=Date.now(),Q=!1,X=null;T.log.info(`New visitor from ${Y}`),$.on("data",(M)=>{if(!Q){Q=!0,X=Date.now();let K=X-Z;if(K>100)T.log.warn(`Delayed data from ${Y} (${K}ms connection delay)`)}this._processRequest({data:M,socket:$,requestHandler:W,clientAddress:Y}).catch((K)=>{let V=K instanceof Error?K.message:"Unknown error";T.log.error(`Visitor from ${Y} experienced an error during request processing: ${V}`,K),$.destroy()})}),$.on("error",(M)=>{T.log.error(`Visitor from ${Y} experienced an error during socket connection: ${M.message}`,M)}),$.on("close",()=>{let M=Date.now()-Z;if(Q){T.log.info(`Visitor from ${Y} headed out (${M}ms total)`);return}if(M<10)T.log.info(`${Y} quick connectivity check (${M}ms) - health probe`);else T.log.warn(`${Y} disconnected without sending data (${M}ms) - potential probe`)})}async listen(){if(this._isListening)throw Error("Server is already listening");return new Promise(($,W)=>{let Y=new O$(this);this._server=i0(),this._setupServer($,W,Y),this._server.listen(this._configuration.port,this._configuration.host)})}async close(){if(!this._isListening||!this._server)return;if(this._globalRateLimiter)await this._globalRateLimiter.destroy(),this._globalRateLimiter=void 0;return new Promise(($)=>{if(!this._server){this._isListening=!1,$();return}this._server.close(()=>{this._isListening=!1,T.log.warn(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is shutting down - See yinz later`),$()})})}status(){return{isListening:this._isListening,port:this._configuration.port,host:this._configuration.host}}_setupGracefulShutdown($){if($<=0)return;if(process.listenerCount("SIGTERM")===0&&process.listenerCount("SIGINT")===0){let W=(Y)=>{G.info(`\uD83D\uDED1 Received ${Y}, shutting down gracefully in ${this._configuration.gracefulShutdownTimeout}...`),setTimeout(()=>{this.close().then(()=>{G.info("✅ Server shut down gracefully"),process.exit(0)}).catch((Z)=>{G.error("❌ Error during graceful shutdown:",Z),process.exit(1)})},$)};process.on("SIGTERM",()=>W("SIGTERM")),process.on("SIGINT",()=>W("SIGINT"))}}}export{g0 as rateLimitStoreType,a0 as rateLimitHook,h$ as rateLimitAlgorithm,i as logLevels,G as log,b as httpStatusCode,a as httpStatus,n as createLogger,B as colors,A1 as YinzerFlow};
31
31
 
32
- //# debugId=E2AA94F639968B3064756E2164756E21
32
+ //# debugId=ECB1D9C83B6BA94964756E2164756E21