yinzerflow 0.4.0 → 0.4.2

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.d.ts CHANGED
@@ -1939,10 +1939,16 @@ export interface InternalServerConfiguration {
1939
1939
  autoGracefulShutdown: boolean;
1940
1940
  }
1941
1941
  export type HttpMethodHandlers = Record<Lowercase<keyof typeof httpMethod>, InternalSetupMethod>;
1942
- export type RouteGroupMethod = (prefix: string, callback: (group: InternalGroupApp) => void, options?: InternalRouteRegistryOptions) => InternalGroupApp;
1942
+ export type RouteGroupMethod = (prefix: string, callback: (group: RouteGroup) => void, options?: InternalRouteRegistryOptions) => RouteGroup;
1943
1943
  export interface InternalGroupApp extends HttpMethodHandlers {
1944
1944
  readonly group: RouteGroupMethod;
1945
1945
  }
1946
+ /**
1947
+ * Route group instance that provides HTTP method handlers and nested group support.
1948
+ *
1949
+ * @see {@link InternalGroupApp} for internal implementation details
1950
+ */
1951
+ export type RouteGroup = InternalGroupApp;
1946
1952
  /**
1947
1953
  * Main setup interface for configuring YinzerFlow routes, hooks, and middleware.
1948
1954
  *
@@ -2316,7 +2322,7 @@ declare class SetupImpl implements InternalSetupImpl {
2316
2322
  patch(path: string, handler: HandlerCallback<any>, options?: InternalRouteRegistryOptions): void;
2317
2323
  delete(path: string, handler: HandlerCallback<any>, options?: InternalRouteRegistryOptions): void;
2318
2324
  options(path: string, handler: HandlerCallback<any>, options?: InternalRouteRegistryOptions): void;
2319
- group(prefix: string, callback: (group: InternalGroupApp) => void, options?: InternalRouteRegistryOptions): InternalGroupApp;
2325
+ group(prefix: string, callback: (group: RouteGroup) => void, options?: InternalRouteRegistryOptions): RouteGroup;
2320
2326
  beforeAll(handlers: Array<HandlerCallback<any>>, options?: InternalGlobalHookOptions): void;
2321
2327
  afterAll(handlers: Array<HandlerCallback<any>>, options?: InternalGlobalHookOptions): void;
2322
2328
  onError(handler: HandlerCallback<any>): void;
package/index.js CHANGED
@@ -1,32 +1,32 @@
1
- var F1=Object.create;var{getPrototypeOf:H1,defineProperty:x$,getOwnPropertyNames:q1}=Object;var V1=Object.prototype.hasOwnProperty;var J$=($,M,W)=>{W=$!=null?F1(H1($)):{};let Y=M||!$||!$.__esModule?x$(W,"default",{value:$,enumerable:!0}):W;for(let Z of q1($))if(!V1.call(Y,Z))x$(Y,Z,{get:()=>$[Z],enumerable:!0});return Y};var O1=($,M)=>()=>(M||$((M={exports:{}}).exports,M),M.exports);var n=O1((D$,K$)=>{(function($,M){typeof D$=="object"&&typeof K$!="undefined"?K$.exports=M():typeof define=="function"&&define.amd?define(M):($=typeof globalThis!="undefined"?globalThis:$||self).dayjs=M()})(D$,function(){var $=1000,M=60000,W=3600000,Y="millisecond",Z="second",Q="minute",X="hour",j="day",_="week",E="month",k="quarter",z="year",v="date",v$="Invalid Date",w1=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,j1=/\[([^\]]+)]|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,U1={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])+"]"}},Q$=function(U,K,J){var w=String(U);return!w||w.length>=K?U:""+Array(K+1-w.length).join(J)+U},G1={s:Q$,z:function(U){var K=-U.utcOffset(),J=Math.abs(K),w=Math.floor(J/60),D=J%60;return(K<=0?"+":"-")+Q$(w,2,"0")+":"+Q$(D,2,"0")},m:function U(K,J){if(K.date()<J.date())return-U(J,K);var w=12*(J.year()-K.year())+(J.month()-K.month()),D=K.clone().add(w,E),G=J-D<0,F=K.clone().add(w+(G?-1:1),E);return+(-(w+(J-D)/(G?D-F:F-D))||0)},a:function(U){return U<0?Math.ceil(U)||0:Math.floor(U)},p:function(U){return{M:E,y:z,w:_,d:j,D:v,h:X,m:Q,s:Z,ms:Y,Q:k}[U]||String(U||"").toLowerCase().replace(/s$/,"")},u:function(U){return U===void 0}},g="en",y={};y[g]=U1;var P$="$isDayjsObject",X$=function(U){return U instanceof i||!(!U||!U[P$])},d=function U(K,J,w){var D;if(!K)return g;if(typeof K=="string"){var G=K.toLowerCase();y[G]&&(D=G),J&&(y[G]=J,D=G);var F=K.split("-");if(!D&&F.length>1)return U(F[0])}else{var V=K.name;y[V]=K,D=V}return!w&&D&&(g=D),D||!w&&g},A=function(U,K){if(X$(U))return U.clone();var J=typeof K=="object"?K:{};return J.date=U,J.args=arguments,new i(J)},q=G1;q.l=d,q.i=X$,q.w=function(U,K){return A(U,{locale:K.$L,utc:K.$u,x:K.$x,$offset:K.$offset})};var i=function(){function U(J){this.$L=d(J.locale,null,!0),this.parse(J),this.$x=this.$x||J.x||{},this[P$]=!0}var K=U.prototype;return K.parse=function(J){this.$d=function(w){var{date:D,utc:G}=w;if(D===null)return new Date(NaN);if(q.u(D))return new Date;if(D instanceof Date)return new Date(D);if(typeof D=="string"&&!/Z$/i.test(D)){var F=D.match(w1);if(F){var V=F[2]-1||0,N=(F[7]||"0").substring(0,3);return G?new Date(Date.UTC(F[1],V,F[3]||1,F[4]||0,F[5]||0,F[6]||0,N)):new Date(F[1],V,F[3]||1,F[4]||0,F[5]||0,F[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 q},K.isValid=function(){return this.$d.toString()!==v$},K.isSame=function(J,w){var D=A(J);return this.startOf(w)<=D&&D<=this.endOf(w)},K.isAfter=function(J,w){return A(J)<this.startOf(w)},K.isBefore=function(J,w){return this.endOf(w)<A(J)},K.$g=function(J,w,D){return q.u(J)?this[w]:this.set(D,J)},K.unix=function(){return Math.floor(this.valueOf()/1000)},K.valueOf=function(){return this.$d.getTime()},K.startOf=function(J,w){var D=this,G=!!q.u(w)||w,F=q.p(J),V=function(h,T){var u=q.w(D.$u?Date.UTC(D.$y,T,h):new Date(D.$y,T,h),D);return G?u:u.endOf(j)},N=function(h,T){return q.w(D.toDate()[h].apply(D.toDate("s"),(G?[0,0,0,0]:[23,59,59,999]).slice(T)),D)},L=this.$W,I=this.$M,P=this.$D,f="set"+(this.$u?"UTC":"");switch(F){case z:return G?V(1,0):V(31,11);case E:return G?V(1,I):V(0,I+1);case _:var m=this.$locale().weekStart||0,p=(L<m?L+7:L)-m;return V(G?P-p:P+(6-p),I);case j:case v:return N(f+"Hours",0);case X:return N(f+"Minutes",1);case Q:return N(f+"Seconds",2);case Z:return N(f+"Milliseconds",3);default:return this.clone()}},K.endOf=function(J){return this.startOf(J,!1)},K.$set=function(J,w){var D,G=q.p(J),F="set"+(this.$u?"UTC":""),V=(D={},D[j]=F+"Date",D[v]=F+"Date",D[E]=F+"Month",D[z]=F+"FullYear",D[X]=F+"Hours",D[Q]=F+"Minutes",D[Z]=F+"Seconds",D[Y]=F+"Milliseconds",D)[G],N=G===j?this.$D+(w-this.$W):w;if(G===E||G===z){var L=this.clone().set(v,1);L.$d[V](N),L.init(),this.$d=L.set(v,Math.min(this.$D,L.daysInMonth())).$d}else V&&this.$d[V](N);return this.init(),this},K.set=function(J,w){return this.clone().$set(J,w)},K.get=function(J){return this[q.p(J)]()},K.add=function(J,w){var D,G=this;J=Number(J);var F=q.p(w),V=function(I){var P=A(G);return q.w(P.date(P.date()+Math.round(I*J)),G)};if(F===E)return this.set(E,this.$M+J);if(F===z)return this.set(z,this.$y+J);if(F===j)return V(1);if(F===_)return V(7);var N=(D={},D[Q]=M,D[X]=W,D[Z]=$,D)[F]||1,L=this.$d.getTime()+J*N;return q.w(L,this)},K.subtract=function(J,w){return this.add(-1*J,w)},K.format=function(J){var w=this,D=this.$locale();if(!this.isValid())return D.invalidDate||v$;var G=J||"YYYY-MM-DDTHH:mm:ssZ",F=q.z(this),V=this.$H,N=this.$m,L=this.$M,I=D.weekdays,P=D.months,f=D.meridiem,m=function(T,u,r,a){return T&&(T[u]||T(w,G))||r[u].slice(0,a)},p=function(T){return q.s(V%12||12,T,"0")},h=f||function(T,u,r){var a=T<12?"AM":"PM";return r?a.toLowerCase():a};return G.replace(j1,function(T,u){return u||function(r){switch(r){case"YY":return String(w.$y).slice(-2);case"YYYY":return q.s(w.$y,4,"0");case"M":return L+1;case"MM":return q.s(L+1,2,"0");case"MMM":return m(D.monthsShort,L,P,3);case"MMMM":return m(P,L);case"D":return w.$D;case"DD":return q.s(w.$D,2,"0");case"d":return String(w.$W);case"dd":return m(D.weekdaysMin,w.$W,I,2);case"ddd":return m(D.weekdaysShort,w.$W,I,3);case"dddd":return I[w.$W];case"H":return String(V);case"HH":return q.s(V,2,"0");case"h":return p(1);case"hh":return p(2);case"a":return h(V,N,!0);case"A":return h(V,N,!1);case"m":return String(N);case"mm":return q.s(N,2,"0");case"s":return String(w.$s);case"ss":return q.s(w.$s,2,"0");case"SSS":return q.s(w.$ms,3,"0");case"Z":return F}return null}(T)||F.replace(":","")})},K.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},K.diff=function(J,w,D){var G,F=this,V=q.p(w),N=A(J),L=(N.utcOffset()-this.utcOffset())*M,I=this-N,P=function(){return q.m(F,N)};switch(V){case z:G=P()/12;break;case E:G=P();break;case k:G=P()/3;break;case _:G=(I-L)/604800000;break;case j:G=(I-L)/86400000;break;case X:G=I/W;break;case Q:G=I/M;break;case Z:G=I/$;break;default:G=I}return D?G:q.a(G)},K.daysInMonth=function(){return this.endOf(E).$D},K.$locale=function(){return y[this.$L]},K.locale=function(J,w){if(!J)return this.$L;var D=this.clone(),G=d(J,w,!0);return G&&(D.$L=G),D},K.clone=function(){return q.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}(),R$=i.prototype;return A.prototype=R$,[["$ms",Y],["$s",Z],["$m",Q],["$H",X],["$W",j],["$M",E],["$y",z],["$D",v]].forEach(function(U){R$[U[1]]=function(K){return this.$g(K,U[0],U[1])}}),A.extend=function(U,K){return U.$i||(U(K,i,A),U.$i=!0),A},A.locale=d,A.isDayjs=X$,A.unix=function(U){return A(1000*U)},A.en=y[g],A.Ls=y,A.p={},A})});import{createServer as T0}from"net";var U$=J$(n(),1);var t={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},B={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"},C={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"},b$={base64:"base64",binary:"binary",utf8:"utf8"};var o=($,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({[C.accessControlAllowOrigin]:Z,[C.accessControlAllowMethods]:M.methods.join(", "),[C.accessControlAllowHeaders]:typeof M.allowedHeaders==="string"?M.allowedHeaders:M.allowedHeaders.join(", "),[C.accessControlAllowCredentials]:M.credentials?"true":"false",[C.accessControlExposeHeaders]:M.exposedHeaders.join(", "),[C.accessControlMaxAge]:M.maxAge.toString()}),M.preflightContinue)return!1;return $._response._setBody(""),!0}if(u$($,M)){let Y=C$($,M);$._response._setHeadersIfNotSet({[C.accessControlAllowOrigin]:Y,[C.accessControlAllowCredentials]:M.credentials?"true":"false"})}return!1},C$=($,M)=>{if(M.origin==="*"){if(M.credentials)throw new 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$=J$(n(),1);var O={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"};var e={off:"off",error:"error",warn:"warn",info:"info"};var l={off:0,error:1,warn:2,info:3},_1={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"]},w$=($)=>{let M=_1[$];return M[Math.floor(Math.random()*M.length)]??""},N1=()=>y$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),j$=($,M,...W)=>{let Y=N1(),Z=O.reset;if(M==="NETWORK")Z=O.gray;if($==="error"){let X=`${O.red}[${M}] ❌ [${Y}] [ERROR]${O.reset}`;console.error(`${X}`,`${Z}`,...W,`${O.reset} - ${w$("negative")}`);return}if($==="warn"){let X=`${O.yellow}[${M}] ⚠️ [${Y}] [WARN]${O.reset}`;console.warn(`${X}`,`${Z}`,...W,`${O.reset} - ${w$("neutral")}`);return}if($==="off")return;let Q=`${O.cyan}[${M}] ✅ [${Y}] [INFO]${O.reset}`;console.info(`${Q}`,`${Z}`,...W,`${O.reset} - ${w$("positive")}`)},s=($)=>{let M={logLevel:$?.logLevel??e.info,prefix:$?.prefix??"YINZER",logger:$?.logger??null},W=(X)=>l[X]??l.info;return{info:(...X)=>{if(W(M.logLevel)<l.info)return;if(M.logger){M.logger.info(...X);return}j$("info",M.prefix,...X)},warn:(...X)=>{if(W(M.logLevel)<l.warn)return;if(M.logger){M.logger.warn(...X);return}j$("warn",M.prefix,...X)},error:(...X)=>{if(W(M.logLevel)<l.error)return;if(M.logger){M.logger.error(...X);return}j$("error",M.prefix,...X)},levels:l}},H=s();class G${setup;constructor($){this.setup=$}async handle($){try{if(o($,this.setup._configuration.cors)){$._response._parseResponseIntoString();return}let W=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!W){let k=await this.setup._hooks._onNotFound($);$._response._setBody(k),$._response._parseResponseIntoString();return}$.request.params=W.params;let{handler:Y,options:Z}=W,{beforeHooks:Q=[],afterHooks:X=[]}=Z,j=this.setup._hooks._beforeAll;for(let k of j)await k.handler($);for(let k of Q)await k($);let _=null;try{_=await Y($)}catch(k){throw k}for(let k of X)await k($);let E=this.setup._hooks._afterAll;for(let k of E)await k.handler($);if($._response._setBody(_),$.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),o($,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 F1=Object.create;var{getPrototypeOf:H1,defineProperty:b$,getOwnPropertyNames:V1}=Object;var q1=Object.prototype.hasOwnProperty;var J$=($,M,W)=>{W=$!=null?F1(H1($)):{};let Y=M||!$||!$.__esModule?b$(W,"default",{value:$,enumerable:!0}):W;for(let Z of V1($))if(!q1.call(Y,Z))b$(Y,Z,{get:()=>$[Z],enumerable:!0});return Y};var O1=($,M)=>()=>(M||$((M={exports:{}}).exports,M),M.exports);var n=O1((D$,K$)=>{(function($,M){typeof D$=="object"&&typeof K$!="undefined"?K$.exports=M():typeof define=="function"&&define.amd?define(M):($=typeof globalThis!="undefined"?globalThis:$||self).dayjs=M()})(D$,function(){var $=1000,M=60000,W=3600000,Y="millisecond",Z="second",Q="minute",X="hour",j="day",q="week",L="month",u="quarter",A="year",v="date",T$="Invalid Date",w1=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,j1=/\[([^\]]+)]|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,U1={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])+"]"}},Q$=function(U,K,J){var w=String(U);return!w||w.length>=K?U:""+Array(K+1-w.length).join(J)+U},G1={s:Q$,z:function(U){var K=-U.utcOffset(),J=Math.abs(K),w=Math.floor(J/60),D=J%60;return(K<=0?"+":"-")+Q$(w,2,"0")+":"+Q$(D,2,"0")},m:function U(K,J){if(K.date()<J.date())return-U(J,K);var w=12*(J.year()-K.year())+(J.month()-K.month()),D=K.clone().add(w,L),G=J-D<0,F=K.clone().add(w+(G?-1:1),L);return+(-(w+(J-D)/(G?D-F:F-D))||0)},a:function(U){return U<0?Math.ceil(U)||0:Math.floor(U)},p:function(U){return{M:L,y:A,w:q,d:j,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]=U1;var P$="$isDayjsObject",X$=function(U){return U instanceof i||!(!U||!U[P$])},d=function U(K,J,w){var D;if(!K)return g;if(typeof K=="string"){var G=K.toLowerCase();y[G]&&(D=G),J&&(y[G]=J,D=G);var F=K.split("-");if(!D&&F.length>1)return U(F[0])}else{var O=K.name;y[O]=K,D=O}return!w&&D&&(g=D),D||!w&&g},k=function(U,K){if(X$(U))return U.clone();var J=typeof K=="object"?K:{};return J.date=U,J.args=arguments,new i(J)},V=G1;V.l=d,V.i=X$,V.w=function(U,K){return k(U,{locale:K.$L,utc:K.$u,x:K.$x,$offset:K.$offset})};var i=function(){function U(J){this.$L=d(J.locale,null,!0),this.parse(J),this.$x=this.$x||J.x||{},this[P$]=!0}var K=U.prototype;return K.parse=function(J){this.$d=function(w){var{date:D,utc:G}=w;if(D===null)return new Date(NaN);if(V.u(D))return new Date;if(D instanceof Date)return new Date(D);if(typeof D=="string"&&!/Z$/i.test(D)){var F=D.match(w1);if(F){var O=F[2]-1||0,B=(F[7]||"0").substring(0,3);return G?new Date(Date.UTC(F[1],O,F[3]||1,F[4]||0,F[5]||0,F[6]||0,B)):new Date(F[1],O,F[3]||1,F[4]||0,F[5]||0,F[6]||0,B)}}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 V},K.isValid=function(){return this.$d.toString()!==T$},K.isSame=function(J,w){var D=k(J);return this.startOf(w)<=D&&D<=this.endOf(w)},K.isAfter=function(J,w){return k(J)<this.startOf(w)},K.isBefore=function(J,w){return this.endOf(w)<k(J)},K.$g=function(J,w,D){return V.u(J)?this[w]:this.set(D,J)},K.unix=function(){return Math.floor(this.valueOf()/1000)},K.valueOf=function(){return this.$d.getTime()},K.startOf=function(J,w){var D=this,G=!!V.u(w)||w,F=V.p(J),O=function(h,S){var C=V.w(D.$u?Date.UTC(D.$y,S,h):new Date(D.$y,S,h),D);return G?C:C.endOf(j)},B=function(h,S){return V.w(D.toDate()[h].apply(D.toDate("s"),(G?[0,0,0,0]:[23,59,59,999]).slice(S)),D)},E=this.$W,z=this.$M,T=this.$D,f="set"+(this.$u?"UTC":"");switch(F){case A:return G?O(1,0):O(31,11);case L:return G?O(1,z):O(0,z+1);case q:var m=this.$locale().weekStart||0,p=(E<m?E+7:E)-m;return O(G?T-p:T+(6-p),z);case j:case v:return B(f+"Hours",0);case X:return B(f+"Minutes",1);case Q:return B(f+"Seconds",2);case Z:return B(f+"Milliseconds",3);default:return this.clone()}},K.endOf=function(J){return this.startOf(J,!1)},K.$set=function(J,w){var D,G=V.p(J),F="set"+(this.$u?"UTC":""),O=(D={},D[j]=F+"Date",D[v]=F+"Date",D[L]=F+"Month",D[A]=F+"FullYear",D[X]=F+"Hours",D[Q]=F+"Minutes",D[Z]=F+"Seconds",D[Y]=F+"Milliseconds",D)[G],B=G===j?this.$D+(w-this.$W):w;if(G===L||G===A){var E=this.clone().set(v,1);E.$d[O](B),E.init(),this.$d=E.set(v,Math.min(this.$D,E.daysInMonth())).$d}else O&&this.$d[O](B);return this.init(),this},K.set=function(J,w){return this.clone().$set(J,w)},K.get=function(J){return this[V.p(J)]()},K.add=function(J,w){var D,G=this;J=Number(J);var F=V.p(w),O=function(z){var T=k(G);return V.w(T.date(T.date()+Math.round(z*J)),G)};if(F===L)return this.set(L,this.$M+J);if(F===A)return this.set(A,this.$y+J);if(F===j)return O(1);if(F===q)return O(7);var B=(D={},D[Q]=M,D[X]=W,D[Z]=$,D)[F]||1,E=this.$d.getTime()+J*B;return V.w(E,this)},K.subtract=function(J,w){return this.add(-1*J,w)},K.format=function(J){var w=this,D=this.$locale();if(!this.isValid())return D.invalidDate||T$;var G=J||"YYYY-MM-DDTHH:mm:ssZ",F=V.z(this),O=this.$H,B=this.$m,E=this.$M,z=D.weekdays,T=D.months,f=D.meridiem,m=function(S,C,s,a){return S&&(S[C]||S(w,G))||s[C].slice(0,a)},p=function(S){return V.s(O%12||12,S,"0")},h=f||function(S,C,s){var a=S<12?"AM":"PM";return s?a.toLowerCase():a};return G.replace(j1,function(S,C){return C||function(s){switch(s){case"YY":return String(w.$y).slice(-2);case"YYYY":return V.s(w.$y,4,"0");case"M":return E+1;case"MM":return V.s(E+1,2,"0");case"MMM":return m(D.monthsShort,E,T,3);case"MMMM":return m(T,E);case"D":return w.$D;case"DD":return V.s(w.$D,2,"0");case"d":return String(w.$W);case"dd":return m(D.weekdaysMin,w.$W,z,2);case"ddd":return m(D.weekdaysShort,w.$W,z,3);case"dddd":return z[w.$W];case"H":return String(O);case"HH":return V.s(O,2,"0");case"h":return p(1);case"hh":return p(2);case"a":return h(O,B,!0);case"A":return h(O,B,!1);case"m":return String(B);case"mm":return V.s(B,2,"0");case"s":return String(w.$s);case"ss":return V.s(w.$s,2,"0");case"SSS":return V.s(w.$ms,3,"0");case"Z":return F}return null}(S)||F.replace(":","")})},K.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},K.diff=function(J,w,D){var G,F=this,O=V.p(w),B=k(J),E=(B.utcOffset()-this.utcOffset())*M,z=this-B,T=function(){return V.m(F,B)};switch(O){case A:G=T()/12;break;case L:G=T();break;case u:G=T()/3;break;case q:G=(z-E)/604800000;break;case j:G=(z-E)/86400000;break;case X:G=z/W;break;case Q:G=z/M;break;case Z:G=z/$;break;default:G=z}return D?G:V.a(G)},K.daysInMonth=function(){return this.endOf(L).$D},K.$locale=function(){return y[this.$L]},K.locale=function(J,w){if(!J)return this.$L;var D=this.clone(),G=d(J,w,!0);return G&&(D.$L=G),D},K.clone=function(){return V.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}(),R$=i.prototype;return k.prototype=R$,[["$ms",Y],["$s",Z],["$m",Q],["$H",X],["$W",j],["$M",L],["$y",A],["$D",v]].forEach(function(U){R$[U[1]]=function(K){return this.$g(K,U[0],U[1])}}),k.extend=function(U,K){return U.$i||(U(K,i,k),U.$i=!0),k},k.locale=d,k.isDayjs=X$,k.unix=function(U){return k(1000*U)},k.en=y[g],k.Ls=y,k.p={},k})});import{createServer as v0}from"net";var U$=J$(n(),1);var t={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},N={delete:"DELETE",get:"GET",head:"HEAD",post:"POST",put:"PUT",patch:"PATCH",options:"OPTIONS"},P={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 o=($,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 new 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$=J$(n(),1);var _={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"};var e={off:"off",error:"error",warn:"warn",info:"info"};var l={off:0,error:1,warn:2,info:3},_1={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"]},w$=($)=>{let M=_1[$];return M[Math.floor(Math.random()*M.length)]??""},B1=()=>y$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),j$=($,M,...W)=>{let Y=B1(),Z=_.reset;if(M==="NETWORK")Z=_.gray;if($==="error"){let X=`${_.red}[${M}] ❌ [${Y}] [ERROR]${_.reset}`;console.error(`${X}`,`${Z}`,...W,`${_.reset} - ${w$("negative")}`);return}if($==="warn"){let X=`${_.yellow}[${M}] ⚠️ [${Y}] [WARN]${_.reset}`;console.warn(`${X}`,`${Z}`,...W,`${_.reset} - ${w$("neutral")}`);return}if($==="off")return;let Q=`${_.cyan}[${M}] ✅ [${Y}] [INFO]${_.reset}`;console.info(`${Q}`,`${Z}`,...W,`${_.reset} - ${w$("positive")}`)},r=($)=>{let M={logLevel:$?.logLevel??e.info,prefix:$?.prefix??"YINZER",logger:$?.logger??null},W=(X)=>l[X]??l.info;return{info:(...X)=>{if(W(M.logLevel)<l.info)return;if(M.logger){M.logger.info(...X);return}j$("info",M.prefix,...X)},warn:(...X)=>{if(W(M.logLevel)<l.warn)return;if(M.logger){M.logger.warn(...X);return}j$("warn",M.prefix,...X)},error:(...X)=>{if(W(M.logLevel)<l.error)return;if(M.logger){M.logger.error(...X);return}j$("error",M.prefix,...X)},levels:l}},H=r();class G${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(q){throw q}for(let q of Q)await q($);let j=this.setup._hooks._afterAll;for(let q of j){if(!this._shouldRunHook(q.options,$.request.path))continue;await q.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),o($,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(`
2
2
 
3
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"}),o($,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(`
4
4
 
5
- `)[1]?.length.toString()??"0"})}}}var m$=["__proto__","constructor","prototype"],h$=($,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)}),new 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 new Error(`Invalid JSON syntax: ${Q}`)}try{F$(Y,M,1)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new Error(`JSON security validation failed: ${Q}`)}return Y},B1=($,M)=>{if(typeof $==="string"&&$.length>M.maxStringLength)throw new Error(`String too long: ${$.length} characters exceeds limit of ${M.maxStringLength}`)},k1=($,M,W)=>{if($.length>M.maxArrayLength)throw new Error(`Array too large: ${$.length} elements exceeds limit of ${M.maxArrayLength}`);for(let Y of $)F$(Y,M,W+1)},E1=($,M)=>{if($.length>M.maxKeys)throw new Error(`Object has too many keys: ${$.length} exceeds limit of ${M.maxKeys}`);if(!M.allowPrototypeProperties){for(let W of $)if(m$.includes(W))throw H.warn("[SECURITY] Prototype pollution attempt detected",{property:W,dangerousProperties:m$}),new 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 new 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 new Error(`String value too long: property '${Z}' has ${Q.length} characters, exceeds limit of ${M.maxStringLength}`);F$(Q,M,W+1)}},F$=($,M,W)=>{if(W>M.maxDepth)throw H.warn("[SECURITY] JSON nesting too deep - potential stack overflow attack",{currentDepth:W,maxDepth:M.maxDepth}),new Error(`JSON nesting too deep: current depth ${W} exceeds maximum depth of ${M.maxDepth}`);if($===null||typeof $!=="object"){B1($,M);return}if(Array.isArray($)){k1($,M,W);return}let Y=Object.keys($);E1(Y,M),A1($,M,W)};var L1=($)=>{let M=$.startsWith(`\r
5
+ `)[1]?.length.toString()??"0"})}}_handleCors($){if(o($,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 m$=["__proto__","constructor","prototype"],h$=($,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)}),new 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 new Error(`Invalid JSON syntax: ${Q}`)}try{F$(Y,M,1)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new Error(`JSON security validation failed: ${Q}`)}return Y},N1=($,M)=>{if(typeof $==="string"&&$.length>M.maxStringLength)throw new Error(`String too long: ${$.length} characters exceeds limit of ${M.maxStringLength}`)},k1=($,M,W)=>{if($.length>M.maxArrayLength)throw new Error(`Array too large: ${$.length} elements exceeds limit of ${M.maxArrayLength}`);for(let Y of $)F$(Y,M,W+1)},E1=($,M)=>{if($.length>M.maxKeys)throw new Error(`Object has too many keys: ${$.length} exceeds limit of ${M.maxKeys}`);if(!M.allowPrototypeProperties){for(let W of $)if(m$.includes(W))throw H.warn("[SECURITY] Prototype pollution attempt detected",{property:W,dangerousProperties:m$}),new 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 new 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 new Error(`String value too long: property '${Z}' has ${Q.length} characters, exceeds limit of ${M.maxStringLength}`);F$(Q,M,W+1)}},F$=($,M,W)=>{if(W>M.maxDepth)throw H.warn("[SECURITY] JSON nesting too deep - potential stack overflow attack",{currentDepth:W,maxDepth:M.maxDepth}),new Error(`JSON nesting too deep: current depth ${W} exceeds maximum depth of ${M.maxDepth}`);if($===null||typeof $!=="object"){N1($,M);return}if(Array.isArray($)){k1($,M,W);return}let Y=Object.keys($);E1(Y,M),A1($,M,W)};var L1=($)=>{let M=$.startsWith(`\r
6
6
  `)?$.slice(2):$,W=M.indexOf(`\r
7
7
  \r
8
- `);if(W===-1)return["",""];let Y=M.slice(0,W),Z=M.slice(W+4);return[Y,Z]},z1=($)=>{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},I1=($)=>{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"},S1=($)=>{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"),v1=($,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)}),new Error(`File too large: ${$.filename} is ${$.size} bytes, exceeds limit of ${M.maxFileSize} bytes`);if($.filename&&$.filename.length>M.maxFilenameLength)throw new 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}),new Error(`File type not allowed: ${W} files are blocked for security reasons`);if(M.allowedExtensions.length>0&&!M.allowedExtensions.includes(W))throw new Error(`File type not allowed: ${W} is not in the allowed extensions list`)}},P1=({contentDisposition:$,contentSection:M,headersSection:W,config:Y})=>{let Z=I1(W),Q=M.endsWith(`\r
9
- `)?M.slice(0,-2):M,X=S1(Z)?Buffer.from(Q,"binary"):Q,j={filename:$.filename??"",contentType:Z,size:T1(X),content:X};return v1(j,Y),j},f$=($,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[j,_]=L1(X);if(!j)continue;let k=j.split(/\r?\n/).find((v)=>v.toLowerCase().startsWith("content-disposition:"));if(!k)continue;let z=z1(k);if(!z.name)continue;if(z.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}),new Error(`Too many files: maximum of ${W.maxFiles} files allowed per request`);let v=P1({contentDisposition:z,contentSection:_,headersSection:j,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)}),new Error(`Total file size too large: ${Q} bytes exceeds limit of ${W.maxTotalSize} bytes`);Y.files.push(v)}if(z.filename===void 0){let v=_.endsWith(`\r
10
- `)?_.slice(0,-2):_;Y.fields[z.name]=v}}return Y};var R1=($,M)=>{if($.length>M.maxFields)throw new Error(`Too many form fields: ${$.length} exceeds limit of ${M.maxFields}`)},x1=($,M,W)=>{if($.length>W.maxFieldNameLength)throw new Error(`Form field name too long: ${$.length} characters exceeds limit of ${W.maxFieldNameLength}`);if(M&&M.length>W.maxFieldLength)throw new Error(`Form field value too long: field '${$}' has ${M.length} characters, exceeds limit of ${W.maxFieldLength}`)},b1=($,M,W)=>{if($.length>W.maxFieldNameLength)throw new Error(`Decoded form field name too long: ${$.length} characters exceeds limit of ${W.maxFieldNameLength}`);if(M.length>W.maxFieldLength)throw new Error(`Decoded form field value too long: field '${$}' has ${M.length} characters, exceeds limit of ${W.maxFieldLength}`)},C1=($,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)b1(Q,X,W);M[Q]=X}catch(Q){if(Q instanceof Error&&Q.message.includes("exceeds limit"))throw Q;M[Y]=Z??""}},l$=($,M)=>{let W={},Y=$.split("&");if(M)R1(Y,M);for(let Z of Y)C1(Z,W,M);return W};var $$={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]},M$=($,M)=>{if($.length<M.length)return!1;return M.every((W,Y)=>$[Y]===W)},u1=($)=>{if(M$($,$$.WEBP)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WEBP";if(M$($,$$.WAV)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WAVE";if(M$($,$$.AVI)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="AVI ";return!1},W$=($,M)=>{if(!$)return y1(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"},y1=($)=>{if(Buffer.isBuffer($))return m1($)?"base64":"utf8";if(typeof $==="object"&&$!==null)return"utf8";if(typeof $==="string")return"utf8";return"utf8"},m1=($)=>{if($.length===0)return!1;let M=Object.values($$);for(let Z of M)if(M$($,Z))return!0;if(u1($))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 h1=($)=>{if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return!1;try{return JSON.parse($),!0}catch{return!1}},f1=($)=>$.includes("=")&&$.includes("&"),l1=($)=>$.includes("boundary="),g1=($)=>typeof $==="object"&&$!==null&&!Buffer.isBuffer($)&&!($ instanceof Uint8Array)&&!($ instanceof ArrayBuffer)&&!($ instanceof Date),p1=($)=>$ instanceof Date,r1=($)=>{if(Buffer.isBuffer($))return $;return Buffer.from($)},s1=($)=>{return W$(void 0,$)==="base64"?"application/octet-stream":"text/plain"},H$=($)=>{let M=$.trim();if(h1(M))return R.json;if(f1(M))return R.form;if(l1(M))return R.multipart;return"text/plain"},g$=($)=>{if($===null||$===void 0)return"text/plain";if(p1($))return"text/plain";if(g1($))return R.json;if(typeof $==="string")return H$($);if(Buffer.isBuffer($)||$ instanceof Uint8Array||$ instanceof ArrayBuffer){let M=r1($);return s1(M)}return"text/plain"};var c1=($,M,W)=>{let Y=Buffer.byteLength($,"utf8");if(M===R.json){if(Y>W.json.maxSize)throw new 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 new 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 new Error(`Multipart body too large: ${Y} bytes exceeds limit of ${W.fileUploads.maxTotalSize} bytes`)}},p$=($,M={})=>{let{headerContentType:W,boundary:Y,config:Z}=M;if(!$||!$.trim())return;let Q=W??H$($);if(Z)c1($,Q,Z);if(Q===R.json){if(!Z)throw new Error("Body parser configuration is required for JSON parsing");return h$($,Z.json)}if(Q===R.multipart){if(!Y)throw new Error("Invalid multipart form data: missing boundary");return f$($,Y,Z?.fileUploads)}if(Q===R.form)return l$($,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 r$=($)=>{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,j]=q$(W,`\r
8
+ `);if(W===-1)return["",""];let Y=M.slice(0,W),Z=M.slice(W+4);return[Y,Z]},z1=($)=>{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},I1=($)=>{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"},S1=($)=>{return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/x-"].some((W)=>$.toLowerCase().startsWith(W))},v1=($)=>Buffer.isBuffer($)?$.length:Buffer.byteLength($,"utf8"),T1=($,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)}),new Error(`File too large: ${$.filename} is ${$.size} bytes, exceeds limit of ${M.maxFileSize} bytes`);if($.filename&&$.filename.length>M.maxFilenameLength)throw new 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}),new Error(`File type not allowed: ${W} files are blocked for security reasons`);if(M.allowedExtensions.length>0&&!M.allowedExtensions.includes(W))throw new Error(`File type not allowed: ${W} is not in the allowed extensions list`)}},P1=({contentDisposition:$,contentSection:M,headersSection:W,config:Y})=>{let Z=I1(W),Q=M.endsWith(`\r
9
+ `)?M.slice(0,-2):M,X=S1(Z)?Buffer.from(Q,"binary"):Q,j={filename:$.filename??"",contentType:Z,size:v1(X),content:X};return T1(j,Y),j},f$=($,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[j,q]=L1(X);if(!j)continue;let u=j.split(/\r?\n/).find((v)=>v.toLowerCase().startsWith("content-disposition:"));if(!u)continue;let A=z1(u);if(!A.name)continue;if(A.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}),new Error(`Too many files: maximum of ${W.maxFiles} files allowed per request`);let v=P1({contentDisposition:A,contentSection:q,headersSection:j,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)}),new Error(`Total file size too large: ${Q} bytes exceeds limit of ${W.maxTotalSize} bytes`);Y.files.push(v)}if(A.filename===void 0){let v=q.endsWith(`\r
10
+ `)?q.slice(0,-2):q;Y.fields[A.name]=v}}return Y};var R1=($,M)=>{if($.length>M.maxFields)throw new Error(`Too many form fields: ${$.length} exceeds limit of ${M.maxFields}`)},b1=($,M,W)=>{if($.length>W.maxFieldNameLength)throw new Error(`Form field name too long: ${$.length} characters exceeds limit of ${W.maxFieldNameLength}`);if(M&&M.length>W.maxFieldLength)throw new Error(`Form field value too long: field '${$}' has ${M.length} characters, exceeds limit of ${W.maxFieldLength}`)},x1=($,M,W)=>{if($.length>W.maxFieldNameLength)throw new Error(`Decoded form field name too long: ${$.length} characters exceeds limit of ${W.maxFieldNameLength}`);if(M.length>W.maxFieldLength)throw new Error(`Decoded form field value too long: field '${$}' has ${M.length} characters, exceeds limit of ${W.maxFieldLength}`)},C1=($,M,W)=>{let[Y,Z]=$.split("=");if(!Y)return;if(W)b1(Y,Z,W);try{let Q=decodeURIComponent(Y),X=Z?decodeURIComponent(Z):"";if(W)x1(Q,X,W);M[Q]=X}catch(Q){if(Q instanceof Error&&Q.message.includes("exceeds limit"))throw Q;M[Y]=Z??""}},l$=($,M)=>{let W={},Y=$.split("&");if(M)R1(Y,M);for(let Z of Y)C1(Z,W,M);return W};var $$={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]},M$=($,M)=>{if($.length<M.length)return!1;return M.every((W,Y)=>$[Y]===W)},u1=($)=>{if(M$($,$$.WEBP)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WEBP";if(M$($,$$.WAV)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WAVE";if(M$($,$$.AVI)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="AVI ";return!1},W$=($,M)=>{if(!$)return y1(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"},y1=($)=>{if(Buffer.isBuffer($))return m1($)?"base64":"utf8";if(typeof $==="object"&&$!==null)return"utf8";if(typeof $==="string")return"utf8";return"utf8"},m1=($)=>{if($.length===0)return!1;let M=Object.values($$);for(let Z of M)if(M$($,Z))return!0;if(u1($))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 h1=($)=>{if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return!1;try{return JSON.parse($),!0}catch{return!1}},f1=($)=>$.includes("=")&&$.includes("&"),l1=($)=>$.includes("boundary="),g1=($)=>typeof $==="object"&&$!==null&&!Buffer.isBuffer($)&&!($ instanceof Uint8Array)&&!($ instanceof ArrayBuffer)&&!($ instanceof Date),p1=($)=>$ instanceof Date,s1=($)=>{if(Buffer.isBuffer($))return $;return Buffer.from($)},r1=($)=>{return W$(void 0,$)==="base64"?"application/octet-stream":"text/plain"},H$=($)=>{let M=$.trim();if(h1(M))return P.json;if(f1(M))return P.form;if(l1(M))return P.multipart;return"text/plain"},g$=($)=>{if($===null||$===void 0)return"text/plain";if(p1($))return"text/plain";if(g1($))return P.json;if(typeof $==="string")return H$($);if(Buffer.isBuffer($)||$ instanceof Uint8Array||$ instanceof ArrayBuffer){let M=s1($);return r1(M)}return"text/plain"};var c1=($,M,W)=>{let Y=Buffer.byteLength($,"utf8");if(M===P.json){if(Y>W.json.maxSize)throw new Error(`JSON body too large: ${Y} bytes exceeds limit of ${W.json.maxSize} bytes`)}else if(M===P.form){if(Y>W.urlEncoded.maxSize)throw new Error(`URL-encoded body too large: ${Y} bytes exceeds limit of ${W.urlEncoded.maxSize} bytes`)}else if(M===P.multipart){if(Y>W.fileUploads.maxTotalSize)throw new Error(`Multipart body too large: ${Y} bytes exceeds limit of ${W.fileUploads.maxTotalSize} bytes`)}},p$=($,M={})=>{let{headerContentType:W,boundary:Y,config:Z}=M;if(!$||!$.trim())return;let Q=W??H$($);if(Z)c1($,Q,Z);if(Q===P.json){if(!Z)throw new Error("Body parser configuration is required for JSON parsing");return h$($,Z.json)}if(Q===P.multipart){if(!Y)throw new Error("Invalid multipart form data: missing boundary");return f$($,Y,Z?.fileUploads)}if(Q===P.form)return l$($,Z?.urlEncoded);return $};var V$=($,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]=V$($,`\r
11
+ `),[Y,Z,Q]=M.split(" ",3),[X,j]=V$(W,`\r
12
12
  \r
13
- `);if(!Y||!Object.values(B).includes(Y))return{method:"GET",path:Z??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:j};return{method:Y,path:Z??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:j}};var s$=($)=>{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 j=decodeURIComponent(Q),_=X?decodeURIComponent(X):"";W[j]=_}catch{W[Q]=X??""}}return W};var d1=[/^(?<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],c$=($)=>{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)},d$=($)=>{if(!$)return!1;let M=$.replace(/^\[|\]$/g,"");return d1.some((W)=>W.test(M))},i$=($,M)=>{if(!$||!M.length)return!1;if(M.includes("*"))return!0;return M.includes($)},i1=($,M)=>{if(!M.detectSpoofing||$.length<=1)return!1;if($.length>M.maxChainLength)return!0;if(new Set($).size!==$.length)return!0;let Y=$.filter(c$).length;if(Y>0&&Y<$.length)return!0;return!1},a1=($,M)=>{if($.length<=1)return!0;let W=$[$.length-1];return Boolean(W&&i$(W,M.trustedProxies))},n1=($,M)=>{if(M==="x-forwarded-for")return $[0];return $[$.length-1]},t1=($)=>{let{clientIp:M,headerName:W,ipChain:Y,config:Z}=$,Q=d$(M),X=W==="x-forwarded-for"?i$(Y[Y.length-1]??"",Z.trustedProxies):!0;return{ip:M,isValid:!0,isPrivate:Q,source:W,trusted:X}},o1=()=>({ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}),e1=($,M)=>{for(let W of M.headerPreference){let Y=$[W];if(!Y)continue;let Z=Y.split(",").map((j)=>j.trim()).filter(Boolean);if(Z.length===0)continue;if(i1(Z,M))continue;if(W==="x-forwarded-for"&&!a1(Z,M))continue;let Q=n1(Z,W);if(!Q||!c$(Q))continue;if(d$(Q)&&!M.allowPrivateIps)continue;return t1({clientIp:Q,headerName:W,ipChain:Z,config:M})}return o1()},$0=($,M,W={})=>{let Z={...$._configuration.ipSecurity,...W},Q=e1(M,Z);if(Q.isValid)return Q;return{ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}},a$=($,M)=>{return $0($,M).ip};var n$=($)=>{if(!$)return;return/boundary\s*=\s*(?<temp1>[^;,\s]*)/i.exec($)?.[1]};var t$=($)=>{if(!$)return{};M0($);let M=W0($),W=Y0(M);return Z0(W)},M0=($)=>{if($.split(/\r\n|\r|\n/).length>100)throw new Error("Too many headers: maximum 100 allowed")},W0=($)=>{let M={},Y=$.replace(/\r\n|\r|\n/g,`
13
+ `);if(!Y||!Object.values(N).includes(Y))return{method:"GET",path:Z??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:j};return{method:Y,path:Z??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:j}};var r$=($)=>{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 j=decodeURIComponent(Q),q=X?decodeURIComponent(X):"";W[j]=q}catch{W[Q]=X??""}}return W};var d1=[/^(?<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],c$=($)=>{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)},d$=($)=>{if(!$)return!1;let M=$.replace(/^\[|\]$/g,"");return d1.some((W)=>W.test(M))},i$=($,M)=>{if(!$||!M.length)return!1;if(M.includes("*"))return!0;return M.includes($)},i1=($,M)=>{if(!M.detectSpoofing||$.length<=1)return!1;if($.length>M.maxChainLength)return!0;if(new Set($).size!==$.length)return!0;let Y=$.filter(c$).length;if(Y>0&&Y<$.length)return!0;return!1},a1=($,M)=>{if($.length<=1)return!0;let W=$[$.length-1];return Boolean(W&&i$(W,M.trustedProxies))},n1=($,M)=>{if(M==="x-forwarded-for")return $[0];return $[$.length-1]},t1=($)=>{let{clientIp:M,headerName:W,ipChain:Y,config:Z}=$,Q=d$(M),X=W==="x-forwarded-for"?i$(Y[Y.length-1]??"",Z.trustedProxies):!0;return{ip:M,isValid:!0,isPrivate:Q,source:W,trusted:X}},o1=()=>({ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}),e1=($,M)=>{for(let W of M.headerPreference){let Y=$[W];if(!Y)continue;let Z=Y.split(",").map((j)=>j.trim()).filter(Boolean);if(Z.length===0)continue;if(i1(Z,M))continue;if(W==="x-forwarded-for"&&!a1(Z,M))continue;let Q=n1(Z,W);if(!Q||!c$(Q))continue;if(d$(Q)&&!M.allowPrivateIps)continue;return t1({clientIp:Q,headerName:W,ipChain:Z,config:M})}return o1()},$0=($,M,W={})=>{let Z={...$._configuration.ipSecurity,...W},Q=e1(M,Z);if(Q.isValid)return Q;return{ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}},a$=($,M)=>{return $0($,M).ip};var n$=($)=>{if(!$)return;return/boundary\s*=\s*(?<temp1>[^;,\s]*)/i.exec($)?.[1]};var t$=($)=>{if(!$)return{};M0($);let M=W0($),W=Y0(M);return Z0(W)},M0=($)=>{if($.split(/\r\n|\r|\n/).length>100)throw new Error("Too many headers: maximum 100 allowed")},W0=($)=>{let M={},Y=$.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(),j=Z.slice(Q+1).trim();if(!X)continue;if(!Q0(X))throw new Error(`Invalid header name: ${X}`);if(X.length>200)throw new Error("Header name too long: maximum 200 characters allowed");if(j.length>8192)throw new Error("Header value too long: maximum 8192 characters allowed");M[X.toLowerCase()]=j}return M},Y0=($)=>{let M={};for(let[W,Y]of Object.entries($))M[W]=X0(Y);return M},Z0=($)=>$,Q0=($)=>{return/^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/.test($)},X0=($)=>{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:j,query:_,params:E,rawBody:k}=this._parseRequestIntoObject();this.method=Y,this.path=Z,this.protocol=Q,this.headers=X,this.body=j,this.query=_??{},this.params=E??{},this.rawBody=k;let z=a$(this._setup,X);if(z)this.ipAddress=z}_parseRequestIntoObject(){let $=this._rawRequest.toString(),{method:M,path:W,protocol:Y,headersRaw:Z,rawBody:Q}=r$($),X=t$(Z),j=X["content-type"],_=j?.split(";")[0]?.trim().toLowerCase(),E=n$(j);return{method:M,path:W,protocol:Y,headers:X,body:p$(Q,{headerContentType:_,boundary:E,config:this._setup._configuration.bodyParser}),query:s$(W),params:{},rawBody:Q}}}var M1=J$(n(),1);var o$=($,M)=>{let W=M?.encoding??"utf8";if($===null||$===void 0)return"";if(Buffer.isBuffer($))return O$($,W);if($ instanceof Uint8Array)return J0($,W);if($ instanceof ArrayBuffer)return D0($,W);if(typeof $==="string")return $;if(typeof $==="object")return K0($);return String($)},O$=($,M)=>{if(M==="base64")return $.toString("base64");if(M==="binary")return $.toString("binary");return $.toString("utf8")},J0=($,M)=>{let W=Buffer.from($);return O$(W,M)},D0=($,M)=>{let W=Buffer.from($);return O$(W,M)},K0=($)=>{try{return JSON.stringify($)}catch(M){return String($)}};var e$=new Map;for(let[$,M]of Object.entries(b)){let Y=t[$];e$.set(M,Y)}var $1=($)=>{let M=e$.get($);if(!M)throw new Error(`Unknown status code: ${$}`);return M};var w0=($,M)=>{if(typeof M!=="string")throw new Error(`Header value must be a string, got ${typeof M}`);if(M.includes("\r")||M.includes(`
16
- `))throw new 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 new Error(`Header value contains suspicious injection pattern: ${$}`)},j0=($)=>{for(let[M,W]of Object.entries($))w0(M,W)},_$=($)=>{let M={};for(let[W,Y]of Object.entries($))if(Y!==void 0)M[W]=Y;return j0(M),M};var c=($)=>{if(U0($))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},U0=($)=>typeof Buffer!=="undefined"&&Buffer.isBuffer($),G0=($)=>typeof $==="object"&&$!==null;class N${_request;_statusCode=b.ok;_status=t.ok;_headers={};_body="";_stringBody="";_encoding=b$.utf8;constructor($){this._request=$,this._setSecurityHeaders()}_parseResponseIntoString(){let $=`${this._request.protocol} ${this._statusCode} ${this._status}`,M=Object.entries(this._headers).map(([X,j])=>`${X}: ${j}`),W=W$(this._headers["content-type"],this._body),Y=o$(this._body,{encoding:W});this._encoding=W;let Z=M.length>0?`${M.join(`
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(),j=Z.slice(Q+1).trim();if(!X)continue;if(!Q0(X))throw new Error(`Invalid header name: ${X}`);if(X.length>200)throw new Error("Header name too long: maximum 200 characters allowed");if(j.length>8192)throw new Error("Header value too long: maximum 8192 characters allowed");M[X.toLowerCase()]=j}return M},Y0=($)=>{let M={};for(let[W,Y]of Object.entries($))M[W]=X0(Y);return M},Z0=($)=>$,Q0=($)=>{return/^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/.test($)},X0=($)=>{return $.replace(/[\x00-\x08\x0A-\x1F\x7F]/g,"")};class q${_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:j,query:q,params:L,rawBody:u}=this._parseRequestIntoObject();this.method=Y,this.path=Z,this.protocol=Q,this.headers=X,this.body=j,this.query=q??{},this.params=L??{},this.rawBody=u;let A=a$(this._setup,X);if(A)this.ipAddress=A}_parseRequestIntoObject(){let $=this._rawRequest.toString(),{method:M,path:W,protocol:Y,headersRaw:Z,rawBody:Q}=s$($),X=t$(Z),j=X["content-type"],q=j?.split(";")[0]?.trim().toLowerCase(),L=n$(j);return{method:M,path:W,protocol:Y,headers:X,body:p$(Q,{headerContentType:q,boundary:L,config:this._setup._configuration.bodyParser}),query:r$(W),params:{},rawBody:Q}}}var M1=J$(n(),1);var o$=($,M)=>{let W=M?.encoding??"utf8";if($===null||$===void 0)return"";if(Buffer.isBuffer($))return O$($,W);if($ instanceof Uint8Array)return J0($,W);if($ instanceof ArrayBuffer)return D0($,W);if(typeof $==="string")return $;if(typeof $==="object")return K0($);return String($)},O$=($,M)=>{if(M==="base64")return $.toString("base64");if(M==="binary")return $.toString("binary");return $.toString("utf8")},J0=($,M)=>{let W=Buffer.from($);return O$(W,M)},D0=($,M)=>{let W=Buffer.from($);return O$(W,M)},K0=($)=>{try{return JSON.stringify($)}catch(M){return String($)}};var e$=new Map;for(let[$,M]of Object.entries(b)){let Y=t[$];e$.set(M,Y)}var $1=($)=>{let M=e$.get($);if(!M)throw new Error(`Unknown status code: ${$}`);return M};var w0=($,M)=>{if(typeof M!=="string")throw new Error(`Header value must be a string, got ${typeof M}`);if(M.includes("\r")||M.includes(`
16
+ `))throw new 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 new Error(`Header value contains suspicious injection pattern: ${$}`)},j0=($)=>{for(let[M,W]of Object.entries($))w0(M,W)},_$=($)=>{let M={};for(let[W,Y]of Object.entries($))if(Y!==void 0)M[W]=Y;return j0(M),M};var c=($)=>{if(U0($))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},U0=($)=>typeof Buffer!=="undefined"&&Buffer.isBuffer($),G0=($)=>typeof $==="object"&&$!==null;class B${_request;_statusCode=b.ok;_status=t.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,j])=>`${X}: ${j}`),W=W$(this._headers["content-type"],this._body),Y=o$(this._body,{encoding:W});this._encoding=W;let Z=M.length>0?`${M.join(`
17
17
  `)}
18
18
  `:"";this._stringBody=`${$}
19
19
  ${Z}
20
- ${Y}`;let Q=c(this._stringBody);this._setHeadersIfNotSet({Date:M1.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=_$(M);Object.assign(this._headers,W)}_setBody($){if(this._body=$,!this._headers["content-type"]){let M=g$($);this._setHeadersIfNotSet({"Content-Type":M})}}setStatusCode($){this._statusCode=$,this._status=$1($)}addHeaders($){let M=_$($);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 B${_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 F0={enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:b.noContent},Y$={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}},W1={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},H0={port:5000,host:"0.0.0.0",networkLogs:!1,cors:{enabled:!1},bodyParser:Y$,ipSecurity:W1,connectionOptions:{socketTimeout:30000,gracefulShutdownTimeout:30000,keepAliveTimeout:65000,headersTimeout:66000},autoGracefulShutdown:!0},q0=($)=>{if($.maxSize<1)throw new Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw new Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw new Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw new Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw new Error("bodyParser.json.maxArrayLength must be at least 1")},V0=($)=>{if($.maxFileSize<1)throw new Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw new Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw new Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw new Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},O0=($)=>{if($.maxSize<1)throw new Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw new Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw new Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw new Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},_0=($)=>{if(!Array.isArray($.trustedProxies))throw new Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw new Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw new Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw new Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw new Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},N0=($)=>{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.`)},B0=($)=>{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.")},k0=($)=>{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.")},E0=($,M)=>{if(M?.cors?.enabled)$.cors={...F0,...M.cors,enabled:!0}},A0=($,M)=>{if(M?.bodyParser)$.bodyParser={json:{...Y$.json,...M.bodyParser.json},fileUploads:{...Y$.fileUploads,...M.bodyParser.fileUploads},urlEncoded:{...Y$.urlEncoded,...M.bodyParser.urlEncoded}},I0($.bodyParser)},L0=($,M)=>{if(M?.ipSecurity)$.ipSecurity={...W1,...M.ipSecurity},_0($.ipSecurity),k0($.ipSecurity)},z0=($,M)=>{if(M?.port!==void 0){let W=Number(M.port);if(isNaN(W)||W<1||W>65535)throw new Error("Invalid port number");$.port=W}},I0=($)=>{q0($.json),V0($.fileUploads),O0($.urlEncoded),N0($.json),B0($.fileUploads)},Y1=($)=>{let M={...H0};return Object.assign(M,$),E0(M,$),A0(M,$),L0(M,$),z0(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(b.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(b.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 new Error(`YinzerFlow: ${M}() expects an array of handler functions, but received ${W}.${W==="function"?`
20
+ ${Y}`;let Q=c(this._stringBody);this._setHeadersIfNotSet({Date:M1.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=_$(M);Object.assign(this._headers,W)}_setBody($){if(this._body=$,!this._headers["content-type"]){let M=g$($);this._setHeadersIfNotSet({"Content-Type":M})}}setStatusCode($){this._statusCode=$,this._status=$1($)}addHeaders($){let M=_$($);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 N${_request;_response;request;response;state={};constructor($,M,W){this._request=new q$($,M,W),this._response=new B$(this._request),this.request=this._request,this.response=this._response}}var F0={enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:b.noContent},Y$={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}},W1={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},H0={port:5000,host:"0.0.0.0",networkLogs:!1,cors:{enabled:!1},bodyParser:Y$,ipSecurity:W1,connectionOptions:{socketTimeout:30000,gracefulShutdownTimeout:30000,keepAliveTimeout:65000,headersTimeout:66000},autoGracefulShutdown:!0},V0=($)=>{if($.maxSize<1)throw new Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw new Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw new Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw new Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw new Error("bodyParser.json.maxArrayLength must be at least 1")},q0=($)=>{if($.maxFileSize<1)throw new Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw new Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw new Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw new Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},O0=($)=>{if($.maxSize<1)throw new Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw new Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw new Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw new Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},_0=($)=>{if(!Array.isArray($.trustedProxies))throw new Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw new Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw new Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw new Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw new Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},B0=($)=>{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.`)},N0=($)=>{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.")},k0=($)=>{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.")},E0=($,M)=>{if(M?.cors?.enabled)$.cors={...F0,...M.cors,enabled:!0}},A0=($,M)=>{if(M?.bodyParser)$.bodyParser={json:{...Y$.json,...M.bodyParser.json},fileUploads:{...Y$.fileUploads,...M.bodyParser.fileUploads},urlEncoded:{...Y$.urlEncoded,...M.bodyParser.urlEncoded}},I0($.bodyParser)},L0=($,M)=>{if(M?.ipSecurity)$.ipSecurity={...W1,...M.ipSecurity},_0($.ipSecurity),k0($.ipSecurity)},z0=($,M)=>{if(M?.port!==void 0){let W=Number(M.port);if(isNaN(W)||W<1||W>65535)throw new Error("Invalid port number");$.port=W}},I0=($)=>{V0($.json),q0($.fileUploads),O0($.urlEncoded),B0($.json),N0($.fileUploads)},Y1=($)=>{let M={...H0};return Object.assign(M,$),E0(M,$),A0(M,$),L0(M,$),z0(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(b.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(b.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 new Error(`YinzerFlow: ${M}() expects an array of handler functions, but received ${W}.${W==="function"?`
21
21
 
22
- ❌ Incorrect: app.${M}${O.red}(${O.reset}(ctx) => { ... }${O.red})${O.reset}
23
- ✅ Correct: app.${M}${O.green}([${O.reset}(ctx) => { ... }${O.green}])${O.reset}
22
+ ❌ Incorrect: app.${M}${_.red}(${_.reset}(ctx) => { ... }${_.red})${_.reset}
23
+ ✅ Correct: app.${M}${_.green}([${_.reset}(ctx) => { ... }${_.green}])${_.reset}
24
24
 
25
- Note: Wrap your handler function in ${O.magenta}square brackets${O.reset} to make it an array.
25
+ Note: Wrap your handler function in ${_.magenta}square brackets${_.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 new Error(`YinzerFlow: ${M}() array contains non-function at index ${W}. Expected: function, received: ${typeof Y}`)}}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var Z1=($)=>{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=S0(M),M.length>1&&M.endsWith("/"))M=M.slice(0,-1);return M},S0=($)=>{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("/")||"/"},A$=($)=>$.replace(/:\w+/g,":param");var Q1=($)=>{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 new Error(`Route ${$} has duplicate parameter names: ${Z.join(", ")}. Parameter names must be unique within a route for clarity and to prevent conflicts.`)}};class L${_exactRoutes=new Map;_parameterizedRoutes=new Map;_register({method:$,path:M,handler:W,options:Y}){let Z=E$(M),Q=Z.includes(":");if(Q)Q1(Z);if(this._hasExactRoutePattern($,Z))throw new 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=A$(M),Y=this._parameterizedRoutes.get($);if(Y)return Y.some((Z)=>A$(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=Z1(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 j=Z[X+1],_=Y.paramNames[X];if(j!==void 0&&_!==void 0)Q[_]=j}return{...Y,params:Q}}}return}}var x=($)=>({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 Z${_setup;_prefix;_options;constructor($,M,W){this._setup=$,this._prefix=M,this._options=x(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:{}}),$===B.get)this._setup._routeRegistry._register({method:B.head,handler:W,path:Z,options:Q,params:{}})}}get=this._createRouteHandler(B.get);head=this._createRouteHandler(B.head);post=this._createRouteHandler(B.post);put=this._createRouteHandler(B.put);delete=this._createRouteHandler(B.delete);patch=this._createRouteHandler(B.patch);options=this._createRouteHandler(B.options);group($,M,W){let Y=I$(this._prefix,$),Z=z$(this._options,W),Q=new Z$(this._setup,Y,Z);return M(Q),Q}}class S${_configuration;_routeRegistry=new L$;_hooks=new k$;constructor($){this._configuration=Y1($)}get($,M,W){let Y=x(W);this._routeRegistry._register({method:B.get,handler:M,path:$,options:Y,params:{}}),this._routeRegistry._register({method:B.head,handler:M,path:$,options:Y,params:{}})}head($,M,W){this._routeRegistry._register({method:B.head,handler:M,path:$,options:x(W),params:{}})}post($,M,W){this._routeRegistry._register({method:B.post,handler:M,path:$,options:x(W),params:{}})}put($,M,W){this._routeRegistry._register({method:B.put,handler:M,path:$,options:x(W),params:{}})}patch($,M,W){this._routeRegistry._register({method:B.patch,handler:M,path:$,options:x(W),params:{}})}delete($,M,W){this._routeRegistry._register({method:B.delete,handler:M,path:$,options:x(W),params:{}})}options($,M,W){this._routeRegistry._register({method:B.options,handler:M,path:$,options:x(W),params:{}})}group($,M,W){let Y=new Z$(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 X1={prefix:"NETWORK",logLevel:"off",logger:void 0},S={log:s(X1),enable:($)=>{S.log=s({...X1,logLevel:e.info,logger:$})}},J1=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},T$=[{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!"}],D1=($)=>{let M=T$.find((W)=>$<W.maxTime)??T$[T$.length-1];if(!M)throw new Error("No threshold found for performance details");S.log.warn(`${O.magenta} ${M.emoji} Response time: ${$}ms - ${M.phrase}${O.reset}`)};class K1 extends S${_isListening=!1;_server;constructor($){super($);if(this._configuration.logger)Object.assign(H,this._configuration.logger);if(this._configuration.networkLogs)S.enable(this._configuration.networkLogger);if(this._configuration.autoGracefulShutdown)this._setupGracefulShutdown()}_setupServer($,M,W){if(!this._server)return;this._server.on("error",(Y)=>{S.log.error(`YinzerFlow server error at ${this._configuration.host}:${this._configuration.port} - ${Y.message}`),M(Y)}),this._server.on("listening",()=>{this._isListening=!0,S.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();S.log.info("Incoming request",`${Y} ${c($)}bytes`);let Q=new B$($,this,Y);await W.handle(Q),M.write(Q._response._stringBody),M.end();let j=Date.now()-Z;S.log.info(`${J1(Q._response._statusCode)} ${Y} "${Q.request.method} ${Q.request.path} ${Q.request.protocol}" ${Q._response._statusCode} ${c(Q._response._body)}bytes "${Q.request.headers.referer??"-"}" "${Q.request.headers["user-agent"]??"-"}" ${j}ms`),D1(j)}_handleConnection($,M){let W=$.remoteAddress??"unknown",Y=Date.now(),Z=!1,Q=null;S.log.info(`New visitor from ${W}`),$.on("data",(X)=>{if(!Z){Z=!0,Q=Date.now();let j=Q-Y;if(j>100)S.log.warn(`Delayed data from ${W} (${j}ms connection delay)`)}this._processRequest({data:X,socket:$,requestHandler:M,clientAddress:W}).catch((j)=>{let _=j instanceof Error?j.message:"Unknown error";S.log.error(`Visitor from ${W} experienced an error during request processing: ${_}`,j),$.destroy()})}),$.on("error",(X)=>{S.log.error(`Visitor from ${W} experienced an error during socket connection: ${X.message}`,X)}),$.on("close",()=>{let X=Date.now()-Y;if(Z){S.log.info(`Visitor from ${W} headed out (${X}ms total)`);return}if(X<10)S.log.info(`${W} quick connectivity check (${X}ms) - health probe`);else S.log.warn(`${W} disconnected without sending data (${X}ms) - potential probe`)})}async listen(){if(this._isListening)throw new Error("Server is already listening");return new Promise(($,M)=>{let W=new G$(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,S.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{H as log,s as createLogger,K1 as YinzerFlow};
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 new Error(`YinzerFlow: ${M}() array contains non-function at index ${W}. Expected: function, received: ${typeof Y}`)}}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var Z1=($)=>{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=S0(M),M.length>1&&M.endsWith("/"))M=M.slice(0,-1);return M},S0=($)=>{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("/")||"/"},A$=($)=>$.replace(/:\w+/g,":param");var Q1=($)=>{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 new Error(`Route ${$} has duplicate parameter names: ${Z.join(", ")}. Parameter names must be unique within a route for clarity and to prevent conflicts.`)}};class L${_exactRoutes=new Map;_parameterizedRoutes=new Map;_register({method:$,path:M,handler:W,options:Y}){let Z=E$(M),Q=Z.includes(":");if(Q)Q1(Z);if(this._hasExactRoutePattern($,Z))throw new 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=A$(M),Y=this._parameterizedRoutes.get($);if(Y)return Y.some((Z)=>A$(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=Z1(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 j=Z[X+1],q=Y.paramNames[X];if(j!==void 0&&q!==void 0)Q[q]=j}return{...Y,params:Q}}}return}}var R=($)=>({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 Z${_setup;_prefix;_options;constructor($,M,W){this._setup=$,this._prefix=M,this._options=R(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:{}}),$===N.get)this._setup._routeRegistry._register({method:N.head,handler:W,path:Z,options:Q,params:{}})}}get=this._createRouteHandler(N.get);head=this._createRouteHandler(N.head);post=this._createRouteHandler(N.post);put=this._createRouteHandler(N.put);delete=this._createRouteHandler(N.delete);patch=this._createRouteHandler(N.patch);options=this._createRouteHandler(N.options);group($,M,W){let Y=I$(this._prefix,$),Z=z$(this._options,W),Q=new Z$(this._setup,Y,Z);return M(Q),Q}}class S${_configuration;_routeRegistry=new L$;_hooks=new k$;constructor($){this._configuration=Y1($)}get($,M,W){let Y=R(W);this._routeRegistry._register({method:N.get,handler:M,path:$,options:Y,params:{}}),this._routeRegistry._register({method:N.head,handler:M,path:$,options:Y,params:{}})}head($,M,W){this._routeRegistry._register({method:N.head,handler:M,path:$,options:R(W),params:{}})}post($,M,W){this._routeRegistry._register({method:N.post,handler:M,path:$,options:R(W),params:{}})}put($,M,W){this._routeRegistry._register({method:N.put,handler:M,path:$,options:R(W),params:{}})}patch($,M,W){this._routeRegistry._register({method:N.patch,handler:M,path:$,options:R(W),params:{}})}delete($,M,W){this._routeRegistry._register({method:N.delete,handler:M,path:$,options:R(W),params:{}})}options($,M,W){this._routeRegistry._register({method:N.options,handler:M,path:$,options:R(W),params:{}})}group($,M,W){let Y=new Z$(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 X1={prefix:"NETWORK",logLevel:"off",logger:void 0},I={log:r(X1),enable:($)=>{I.log=r({...X1,logLevel:e.info,logger:$})}},J1=($)=>{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!"}],D1=($)=>{let M=v$.find((W)=>$<W.maxTime)??v$[v$.length-1];if(!M)throw new Error("No threshold found for performance details");I.log.warn(`${_.magenta} ${M.emoji} Response time: ${$}ms - ${M.phrase}${_.reset}`)};class K1 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} ${c($)}bytes`);let Q=new N$($,this,Y);await W.handle(Q),M.write(Q._response._stringBody),M.end();let j=Date.now()-Z;I.log.info(`${J1(Q._response._statusCode)} ${Y} "${Q.request.method} ${Q.request.path} ${Q.request.protocol}" ${Q._response._statusCode} ${c(Q._response._body)}bytes "${Q.request.headers.referer??"-"}" "${Q.request.headers["user-agent"]??"-"}" ${j}ms`),D1(j)}_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 j=Q-Y;if(j>100)I.log.warn(`Delayed data from ${W} (${j}ms connection delay)`)}this._processRequest({data:X,socket:$,requestHandler:M,clientAddress:W}).catch((j)=>{let q=j instanceof Error?j.message:"Unknown error";I.log.error(`Visitor from ${W} experienced an error during request processing: ${q}`,j),$.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 new Error("Server is already listening");return new Promise(($,M)=>{let W=new G$(this);this._server=v0(),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{H as log,r as createLogger,K1 as YinzerFlow};
31
31
 
32
- //# debugId=E1941AE25D0319AE64756E2164756E21
32
+ //# debugId=5BAF1FCD834DE93664756E2164756E21