yinzerflow 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/docs/configuration/advanced-configuration-options.md +1 -1
- package/docs/configuration/configuration-patterns.md +1 -1
- package/docs/core/logging.md +130 -0
- package/docs/security/security-overview.md +2 -2
- package/docs/start-here.md +2 -2
- package/example/README.md +11 -0
- package/example/app/handlers/example.ts +27 -0
- package/example/app/index.ts +163 -0
- package/example/app/routes/example.ts +18 -0
- package/example/app/routes/group-example.ts +13 -0
- package/example/app/util/customLogger.ts +166 -0
- package/example/docker-compose.yml +28 -0
- package/example/package.json +16 -0
- package/example/tsconfig.json +54 -0
- package/index.d.ts +44 -24
- package/index.js +18 -18
- package/index.js.map +13 -12
- package/package.json +1 -1
- package/docs/security/logging.md +0 -348
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"composite": true,
|
|
4
|
+
"target": "ESNext",
|
|
5
|
+
"useDefineForClassFields": true,
|
|
6
|
+
"module": "NodeNext",
|
|
7
|
+
"lib": ["ESNext"],
|
|
8
|
+
"skipLibCheck": true,
|
|
9
|
+
"types": ["bun-types"],
|
|
10
|
+
|
|
11
|
+
/* Bundler mode */
|
|
12
|
+
"moduleResolution": "NodeNext",
|
|
13
|
+
"moduleDetection": "force",
|
|
14
|
+
"allowImportingTsExtensions": true,
|
|
15
|
+
"resolveJsonModule": true,
|
|
16
|
+
"isolatedModules": true,
|
|
17
|
+
"noEmit": true,
|
|
18
|
+
"jsx": "preserve",
|
|
19
|
+
"alwaysStrict": true,
|
|
20
|
+
"declaration": true,
|
|
21
|
+
"outDir": "lib",
|
|
22
|
+
"declarationDir": "lib",
|
|
23
|
+
"verbatimModuleSyntax": true,
|
|
24
|
+
"baseUrl": ".",
|
|
25
|
+
"paths": {
|
|
26
|
+
"@app/*": ["./app/*"]
|
|
27
|
+
},
|
|
28
|
+
"sourceMap": false,
|
|
29
|
+
"removeComments": true,
|
|
30
|
+
"declarationMap": true,
|
|
31
|
+
|
|
32
|
+
/* Linting */
|
|
33
|
+
"strict": true,
|
|
34
|
+
"noUnusedLocals": true,
|
|
35
|
+
"noUnusedParameters": true,
|
|
36
|
+
"noFallthroughCasesInSwitch": true,
|
|
37
|
+
"allowSyntheticDefaultImports": true,
|
|
38
|
+
"allowJs": false,
|
|
39
|
+
"forceConsistentCasingInFileNames": true,
|
|
40
|
+
"noImplicitAny": true,
|
|
41
|
+
"noImplicitReturns": true,
|
|
42
|
+
"noImplicitThis": true,
|
|
43
|
+
"noImplicitOverride": true,
|
|
44
|
+
"strictFunctionTypes": true,
|
|
45
|
+
"strictNullChecks": true,
|
|
46
|
+
"strictPropertyInitialization": true,
|
|
47
|
+
"allowUnreachableCode": false,
|
|
48
|
+
"allowUnusedLabels": false,
|
|
49
|
+
"exactOptionalPropertyTypes": true,
|
|
50
|
+
"noUncheckedIndexedAccess": true,
|
|
51
|
+
"strictBindCallApply": true
|
|
52
|
+
},
|
|
53
|
+
"include": ["app/**/*"]
|
|
54
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -1559,12 +1559,31 @@ declare const logLevels: {
|
|
|
1559
1559
|
readonly warn: "warn";
|
|
1560
1560
|
readonly info: "info";
|
|
1561
1561
|
};
|
|
1562
|
+
/**
|
|
1563
|
+
* YinzerFlow Logging Levels
|
|
1564
|
+
*
|
|
1565
|
+
* String-based logging levels for intuitive configuration:
|
|
1566
|
+
* - 'off': No logging at all. Mainly used for network logging internally, but feel free to use it for other purposes.
|
|
1567
|
+
* - 'error': Only errors
|
|
1568
|
+
* - 'warn': Warnings and errors (includes security warnings, slow requests)
|
|
1569
|
+
* - 'info': Info, warnings, and errors (standard application logging)
|
|
1570
|
+
*
|
|
1571
|
+
* Network logging is controlled separately via boolean networkLogging config.
|
|
1572
|
+
*/
|
|
1573
|
+
export type LogLevel = CreateEnum<typeof logLevels>;
|
|
1562
1574
|
export interface Logger {
|
|
1563
1575
|
info: (...args: Array<unknown>) => void;
|
|
1564
1576
|
warn: (...args: Array<unknown>) => void;
|
|
1565
1577
|
error: (...args: Array<unknown>) => void;
|
|
1566
|
-
|
|
1567
|
-
|
|
1578
|
+
}
|
|
1579
|
+
export interface LoggerConfig {
|
|
1580
|
+
logLevel?: LogLevel | undefined;
|
|
1581
|
+
prefix?: string | undefined;
|
|
1582
|
+
logger?: {
|
|
1583
|
+
info: (...args: Array<unknown>) => void;
|
|
1584
|
+
warn: (...args: Array<unknown>) => void;
|
|
1585
|
+
error: (...args: Array<unknown>) => void;
|
|
1586
|
+
} | undefined;
|
|
1568
1587
|
}
|
|
1569
1588
|
/**
|
|
1570
1589
|
* Internal CORS Configuration Options
|
|
@@ -1870,19 +1889,16 @@ export interface InternalServerConfiguration {
|
|
|
1870
1889
|
*/
|
|
1871
1890
|
host: string;
|
|
1872
1891
|
/**
|
|
1873
|
-
*
|
|
1874
|
-
*
|
|
1875
|
-
*
|
|
1876
|
-
* -
|
|
1877
|
-
*
|
|
1878
|
-
* @
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
*
|
|
1883
|
-
* If provided, this logger will be used instead of the built-in YinzerFlow logger
|
|
1884
|
-
* Must implement the Logger interface
|
|
1885
|
-
* @default undefined (uses built-in logger)
|
|
1892
|
+
* Custom logger instance
|
|
1893
|
+
*
|
|
1894
|
+
* Use createLogger() to create logger instances with custom configuration
|
|
1895
|
+
* @default undefined (uses built-in logger with default settings)
|
|
1896
|
+
*
|
|
1897
|
+
* @example
|
|
1898
|
+
* ```typescript
|
|
1899
|
+
* const logger = createLogger({ prefix: 'APP', logLevel: 'info' });
|
|
1900
|
+
* new YinzerFlow({ logger });
|
|
1901
|
+
* ```
|
|
1886
1902
|
*/
|
|
1887
1903
|
logger?: Logger;
|
|
1888
1904
|
/**
|
|
@@ -2322,19 +2338,23 @@ export declare class YinzerFlow extends SetupImpl {
|
|
|
2322
2338
|
};
|
|
2323
2339
|
private _setupGracefulShutdown;
|
|
2324
2340
|
}
|
|
2341
|
+
declare const LOG_LEVELS: {
|
|
2342
|
+
readonly off: 0;
|
|
2343
|
+
readonly error: 1;
|
|
2344
|
+
readonly warn: 2;
|
|
2345
|
+
readonly info: 3;
|
|
2346
|
+
};
|
|
2347
|
+
export declare const createLogger: (initialConfig?: LoggerConfig) => {
|
|
2348
|
+
info: (...args: Array<unknown>) => void;
|
|
2349
|
+
warn: (...args: Array<unknown>) => void;
|
|
2350
|
+
error: (...args: Array<unknown>) => void;
|
|
2351
|
+
levels: typeof LOG_LEVELS;
|
|
2352
|
+
};
|
|
2325
2353
|
export declare const log: {
|
|
2326
|
-
setLogLevel: (level: "error" | "info" | "off" | "warn") => void;
|
|
2327
|
-
setCustomLogger: (logger: Logger) => void;
|
|
2328
2354
|
info: (...args: Array<unknown>) => void;
|
|
2329
2355
|
warn: (...args: Array<unknown>) => void;
|
|
2330
2356
|
error: (...args: Array<unknown>) => void;
|
|
2331
|
-
|
|
2332
|
-
levels: {
|
|
2333
|
-
readonly off: 0;
|
|
2334
|
-
readonly error: 1;
|
|
2335
|
-
readonly warn: 2;
|
|
2336
|
-
readonly info: 3;
|
|
2337
|
-
};
|
|
2357
|
+
levels: typeof LOG_LEVELS;
|
|
2338
2358
|
};
|
|
2339
2359
|
|
|
2340
2360
|
export {};
|
package/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
var _0=Object.create;var{getPrototypeOf:w0,defineProperty:f$,getOwnPropertyNames:O0}=Object;var V0=Object.prototype.hasOwnProperty;var w$=($,W,Y)=>{Y=$!=null?_0(w0($)):{};let Z=W||!$||!$.__esModule?f$(Y,"default",{value:$,enumerable:!0}):Y;for(let D of O0($))if(!V0.call(Z,D))f$(Z,D,{get:()=>$[D],enumerable:!0});return Z};var N0=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var Q$=N0((O$,V$)=>{(function($,W){typeof O$=="object"&&typeof V$!="undefined"?V$.exports=W():typeof define=="function"&&define.amd?define(W):($=typeof globalThis!="undefined"?globalThis:$||self).dayjs=W()})(O$,function(){var $=1000,W=60000,Y=3600000,Z="millisecond",D="second",Q="minute",X="hour",G="day",V="week",A="month",q="quarter",z="year",L="date",e="Invalid Date",j$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,$$=/\[([^\]]+)]|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,H$={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(F){var M=["th","st","nd","rd"],J=F%100;return"["+F+(M[(J-20)%10]||M[J]||M[0])+"]"}},r=function(F,M,J){var U=String(F);return!U||U.length>=M?F:""+Array(M+1-U.length).join(J)+F},W$={s:r,z:function(F){var M=-F.utcOffset(),J=Math.abs(M),U=Math.floor(J/60),K=J%60;return(M<=0?"+":"-")+r(U,2,"0")+":"+r(K,2,"0")},m:function F(M,J){if(M.date()<J.date())return-F(J,M);var U=12*(J.year()-M.year())+(J.month()-M.month()),K=M.clone().add(U,A),j=J-K<0,H=M.clone().add(U+(j?-1:1),A);return+(-(U+(J-K)/(j?K-H:H-K))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:A,y:z,w:V,d:G,D:L,h:X,m:Q,s:D,ms:Z,Q:q}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},f="en",l={};l[f]=H$;var h$="$isDayjsObject",_$=function(F){return F instanceof Z$||!(!F||!F[h$])},Y$=function F(M,J,U){var K;if(!M)return f;if(typeof M=="string"){var j=M.toLowerCase();l[j]&&(K=j),J&&(l[j]=J,K=j);var H=M.split("-");if(!K&&H.length>1)return F(H[0])}else{var N=M.name;l[N]=M,K=N}return!U&&K&&(f=K),K||!U&&f},S=function(F,M){if(_$(F))return F.clone();var J=typeof M=="object"?M:{};return J.date=F,J.args=arguments,new Z$(J)},O=W$;O.l=Y$,O.i=_$,O.w=function(F,M){return S(F,{locale:M.$L,utc:M.$u,x:M.$x,$offset:M.$offset})};var Z$=function(){function F(J){this.$L=Y$(J.locale,null,!0),this.parse(J),this.$x=this.$x||J.x||{},this[h$]=!0}var M=F.prototype;return M.parse=function(J){this.$d=function(U){var{date:K,utc:j}=U;if(K===null)return new Date(NaN);if(O.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var H=K.match(j$);if(H){var N=H[2]-1||0,B=(H[7]||"0").substring(0,3);return j?new Date(Date.UTC(H[1],N,H[3]||1,H[4]||0,H[5]||0,H[6]||0,B)):new Date(H[1],N,H[3]||1,H[4]||0,H[5]||0,H[6]||0,B)}}return new Date(K)}(J),this.init()},M.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()},M.$utils=function(){return O},M.isValid=function(){return this.$d.toString()!==e},M.isSame=function(J,U){var K=S(J);return this.startOf(U)<=K&&K<=this.endOf(U)},M.isAfter=function(J,U){return S(J)<this.startOf(U)},M.isBefore=function(J,U){return this.endOf(U)<S(J)},M.$g=function(J,U,K){return O.u(J)?this[U]:this.set(K,J)},M.unix=function(){return Math.floor(this.valueOf()/1000)},M.valueOf=function(){return this.$d.getTime()},M.startOf=function(J,U){var K=this,j=!!O.u(U)||U,H=O.p(J),N=function(g,v){var m=O.w(K.$u?Date.UTC(K.$y,v,g):new Date(K.$y,v,g),K);return j?m:m.endOf(G)},B=function(g,v){return O.w(K.toDate()[g].apply(K.toDate("s"),(j?[0,0,0,0]:[23,59,59,999]).slice(v)),K)},k=this.$W,I=this.$M,T=this.$D,s="set"+(this.$u?"UTC":"");switch(H){case z:return j?N(1,0):N(31,11);case A:return j?N(1,I):N(0,I+1);case V:var p=this.$locale().weekStart||0,n=(k<p?k+7:k)-p;return N(j?T-n:T+(6-n),I);case G:case L:return B(s+"Hours",0);case X:return B(s+"Minutes",1);case Q:return B(s+"Seconds",2);case D:return B(s+"Milliseconds",3);default:return this.clone()}},M.endOf=function(J){return this.startOf(J,!1)},M.$set=function(J,U){var K,j=O.p(J),H="set"+(this.$u?"UTC":""),N=(K={},K[G]=H+"Date",K[L]=H+"Date",K[A]=H+"Month",K[z]=H+"FullYear",K[X]=H+"Hours",K[Q]=H+"Minutes",K[D]=H+"Seconds",K[Z]=H+"Milliseconds",K)[j],B=j===G?this.$D+(U-this.$W):U;if(j===A||j===z){var k=this.clone().set(L,1);k.$d[N](B),k.init(),this.$d=k.set(L,Math.min(this.$D,k.daysInMonth())).$d}else N&&this.$d[N](B);return this.init(),this},M.set=function(J,U){return this.clone().$set(J,U)},M.get=function(J){return this[O.p(J)]()},M.add=function(J,U){var K,j=this;J=Number(J);var H=O.p(U),N=function(I){var T=S(j);return O.w(T.date(T.date()+Math.round(I*J)),j)};if(H===A)return this.set(A,this.$M+J);if(H===z)return this.set(z,this.$y+J);if(H===G)return N(1);if(H===V)return N(7);var B=(K={},K[Q]=W,K[X]=Y,K[D]=$,K)[H]||1,k=this.$d.getTime()+J*B;return O.w(k,this)},M.subtract=function(J,U){return this.add(-1*J,U)},M.format=function(J){var U=this,K=this.$locale();if(!this.isValid())return K.invalidDate||e;var j=J||"YYYY-MM-DDTHH:mm:ssZ",H=O.z(this),N=this.$H,B=this.$m,k=this.$M,I=K.weekdays,T=K.months,s=K.meridiem,p=function(v,m,t,D$){return v&&(v[m]||v(U,j))||t[m].slice(0,D$)},n=function(v){return O.s(N%12||12,v,"0")},g=s||function(v,m,t){var D$=v<12?"AM":"PM";return t?D$.toLowerCase():D$};return j.replace($$,function(v,m){return m||function(t){switch(t){case"YY":return String(U.$y).slice(-2);case"YYYY":return O.s(U.$y,4,"0");case"M":return k+1;case"MM":return O.s(k+1,2,"0");case"MMM":return p(K.monthsShort,k,T,3);case"MMMM":return p(T,k);case"D":return U.$D;case"DD":return O.s(U.$D,2,"0");case"d":return String(U.$W);case"dd":return p(K.weekdaysMin,U.$W,I,2);case"ddd":return p(K.weekdaysShort,U.$W,I,3);case"dddd":return I[U.$W];case"H":return String(N);case"HH":return O.s(N,2,"0");case"h":return n(1);case"hh":return n(2);case"a":return g(N,B,!0);case"A":return g(N,B,!1);case"m":return String(B);case"mm":return O.s(B,2,"0");case"s":return String(U.$s);case"ss":return O.s(U.$s,2,"0");case"SSS":return O.s(U.$ms,3,"0");case"Z":return H}return null}(v)||H.replace(":","")})},M.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},M.diff=function(J,U,K){var j,H=this,N=O.p(U),B=S(J),k=(B.utcOffset()-this.utcOffset())*W,I=this-B,T=function(){return O.m(H,B)};switch(N){case z:j=T()/12;break;case A:j=T();break;case q:j=T()/3;break;case V:j=(I-k)/604800000;break;case G:j=(I-k)/86400000;break;case X:j=I/Y;break;case Q:j=I/W;break;case D:j=I/$;break;default:j=I}return K?j:O.a(j)},M.daysInMonth=function(){return this.endOf(A).$D},M.$locale=function(){return l[this.$L]},M.locale=function(J,U){if(!J)return this.$L;var K=this.clone(),j=Y$(J,U,!0);return j&&(K.$L=j),K},M.clone=function(){return O.w(this.$d,this)},M.toDate=function(){return new Date(this.valueOf())},M.toJSON=function(){return this.isValid()?this.toISOString():null},M.toISOString=function(){return this.$d.toISOString()},M.toString=function(){return this.$d.toUTCString()},F}(),m$=Z$.prototype;return S.prototype=m$,[["$ms",Z],["$s",D],["$m",Q],["$H",X],["$W",G],["$M",A],["$y",z],["$D",L]].forEach(function(F){m$[F[1]]=function(M){return this.$g(M,F[0],F[1])}}),S.extend=function(F,M){return F.$i||(F(M,Z$,S),F.$i=!0),S},S.locale=Y$,S.isDayjs=_$,S.unix=function(F){return S(1000*F)},S.en=l[f],S.Ls=l,S.p={},S})});import{createServer as r1}from"net";var B$=w$(Q$(),1);var X$={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"},u={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},E={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"},y={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"},d={base64:"base64",binary:"binary",utf8:"utf8"};var J$=($,W)=>{if(!W.enabled)return!1;if($.request.method==="OPTIONS"){if(!p$($,W))return $.response.setStatusCode(403),$._response._setBody({error:"CORS: Origin not allowed",origin:$.request.headers.origin}),!0;$.response.setStatusCode(W.optionsSuccessStatus);let D=l$($,W);if($._response._setHeadersIfNotSet({[y.accessControlAllowOrigin]:D,[y.accessControlAllowMethods]:W.methods.join(", "),[y.accessControlAllowHeaders]:typeof W.allowedHeaders==="string"?W.allowedHeaders:W.allowedHeaders.join(", "),[y.accessControlAllowCredentials]:W.credentials?"true":"false",[y.accessControlExposeHeaders]:W.exposedHeaders.join(", "),[y.accessControlMaxAge]:W.maxAge.toString()}),W.preflightContinue)return!1;return $._response._setBody(""),!0}if(p$($,W)){let Z=l$($,W);$._response._setHeadersIfNotSet({[y.accessControlAllowOrigin]:Z,[y.accessControlAllowCredentials]:W.credentials?"true":"false"})}return!1},l$=($,W)=>{if(W.origin==="*"){if(W.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 Y=$.request.headers.origin;if(Y)return Y;if(typeof W.origin==="string")return W.origin;if(Array.isArray(W.origin)&&W.origin.length>0){let[Z]=W.origin;return Z??"null"}return"null"},p$=($,W)=>{if(W.origin==="*")return!0;let Y=$.request.headers.origin?.toLowerCase()??"";if(typeof W.origin==="function")return Boolean(W.origin(Y,$.request));if(typeof W.origin==="string")return Y===W.origin.toLowerCase();if(Array.isArray(W.origin))return W.origin.some((Z)=>Y===Z.toLowerCase());if(W.origin instanceof RegExp)return W.origin.test(Y);return!1};var g$=w$(Q$(),1),h="YINZER",w={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"},q0={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"]},i=!1,P=null,C=()=>g$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),N$=($)=>{let W=q0[$];return W[Math.floor(Math.random()*W.length)]??""},B0=($)=>{if(typeof $==="string")return Buffer.byteLength($,"utf8");if(Buffer.isBuffer($))return $.length;if(typeof $==="object"&&$!==null)try{return Buffer.byteLength(JSON.stringify($),"utf8")}catch{return 0}return 0},E0=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},A0=($)=>{if($<50)return{emoji:"⚡",phrase:Math.random()<0.5?"lightning quick n'at!":"faster than a Stillers touchdown!"};if($<100)return{emoji:"\uD83D\uDD25",phrase:Math.random()<0.5?"that's the way!":"smooth as butter n'at!"};if($<200)return{emoji:"✅",phrase:Math.random()<0.5?"not bad yinz!":"keepin' up just fine!"};if($<500)return{emoji:"⚠️",phrase:Math.random()<0.5?"eh, could be better":"slowin' down a bit there"};if($<1000)return{emoji:"\uD83D\uDC0C",phrase:Math.random()<0.5?"that's draggin' n'at":"c'mon, pick up the pace!"};return{emoji:"\uD83D\uDCA5",phrase:Math.random()<0.5?"what a jagoff response time!":"slower than traffic on the Parkway!"}},z0=($,W,Y)=>{if(!i)return;let Z=C(),D=W??"unknown",Q=Y?` - ${Y}`:"",X="",G="info";if($==="connect")X=`\uD83E\uDD1D [NETWORK] New visitor from ${D} - Welcome to the 'Burgh!`;else if($==="disconnect")X=`\uD83D\uDC4B [NETWORK] ${D} headed out - Thanks for stopping by, yinz come back now!`;else X=`\uD83D\uDCA5 [NETWORK] Connection trouble with ${D}${Q} - That's not good, n'at!`,G="error";if(P)P[G](X);else{let V=G==="error"?w.red:w.gray;console.log(`${V}[${h}] [${Z}] ${X}${w.reset}`)}},S0=($,W,Y)=>{if(!i)return;let{request:Z}=$,D=$._response,Q=(Y-W).toFixed(1),X=Z.ipAddress||"unknown",{method:G,path:V,protocol:A}=Z,q=D._statusCode,z=B0(D._body),L=Z.headers.referer?`"${Z.headers.referer}"`:'"-"',e=Z.headers["user-agent"]?`"${Z.headers["user-agent"]}"`:'"-"',j$=E0(q),$$=`\uD83C\uDFE0 ${X} - - [${C()}] "${G} ${V} ${A}" ${q} ${z}b ${L} ${e} ${Q}ms ${j$}`,H$=parseFloat(Q),{emoji:r,phrase:W$}=A0(H$),f=`${r} [PERF] Response time: ${Q}ms - ${W$}`;if(P)P.info(`[NETWORK] ${$$}`),P.info(`[PERF] ${f}`);else console.log(`${w.gray}[${h}] [${C()}] [NETWORK] ${$$}${w.reset}`),console.log(`${w.magenta}[${h}] ${r} [${C()}] [PERF] Response time: ${Q}ms - ${W$}${w.reset}`)},k0=($,W)=>{if(!i)return;let Y=C(),Z=$&&W?`${W}:${$}`:"unknown",D=N$("positive"),Q=`\uD83D\uDE80 [NETWORK] YinzerFlow server is up and running at ${Z} - Ready to serve yinz all, ${D}!`;if(P)P.info(Q);else console.log(`${w.gray}[${h}] [${Y}] ${Q}${w.reset}`)},I0=($,W)=>{if(!i)return;let Y=C(),Z=$&&W?`${W}:${$}`:"unknown",D=N$("neutral"),Q=`\uD83D\uDED1 [NETWORK] YinzerFlow server at ${Z} is shutting down - See yinz later, ${D}!`;if(P)P.info(Q);else console.log(`${w.gray}[${h}] [${Y}] ${Q}${w.reset}`)},L0=($,W,Y)=>{if(!i)return;let Z=C(),D=$&&W?`${W}:${$}`:"unknown",Q=Y?` - ${Y}`:"",X=N$("negative"),G=`\uD83D\uDCA5 [NETWORK] Server error at ${D}${Q} - Something's not right, ${X}!`;if(P)P.error(G);else console.log(`${w.red}[${h}] [${Z}] ${G}${w.reset}`)},v0=($)=>{i=$},T0=($)=>{P=$},x={setEnabled:v0,setNetworkLogger:T0,connection:z0,request:S0,serverStart:k0,serverStop:I0,serverError:L0};var a={off:0,error:1,warn:2,info:3},R0={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"]},o=a.warn,c=null,P0=($)=>{let W=R0[$];return W[Math.floor(Math.random()*W.length)]??""},x0=(...$)=>{if(o<a.info)return;if(c)c.info(...$);else q$("info",...$)},C0=(...$)=>{if(o<a.warn)return;if(c)c.warn(...$);else q$("warn",...$)},b0=(...$)=>{if(o<a.error)return;if(c)c.error(...$);else q$("error",...$)},u0=($,W,Y)=>{if(o<a.info)return;let Z=C(),D="❓ ",Q="";if(W<50)D="⚡ ",Q=Math.random()<0.5?"lightning quick n'at!":"faster than a Stillers touchdown!";else if(W<100)D="\uD83D\uDD25 ",Q=Math.random()<0.5?"that's the way!":"smooth as butter n'at!";else if(W<200)D="✅ ",Q=Math.random()<0.5?"not bad yinz!":"keepin' up just fine!";else if(W<500)D="⚠️ ",Q=Math.random()<0.5?"eh, could be better":"slowin' down a bit there";else if(W<1000)D="\uD83D\uDC0C ",Q=Math.random()<0.5?"that's draggin' n'at":"c'mon, pick up the pace!";else D="\uD83D\uDCA5 ",Q=Math.random()<0.5?"what a jagoff response time!":"slower than traffic on the Parkway!";let X=`${w.magenta}[${h}] ${D} [${Z}] [PERF]${w.reset}`,G=Y?{...Y,executionTime:`${W}ms`}:{executionTime:`${W}ms`};console.log(`${X} ${$} -`,G,`- ${Q}`)},y0=($)=>{o={off:0,error:1,warn:2,info:3}[$]},h0=($)=>{c=$},q$=($,...W)=>{let Y=C(),Z="✅ ",D=w.cyan,Q="positive",X="info";if($==="error")Z="❌ ",D=w.red,Q="negative",X="error";else if($==="warn")Z="⚠️ ",D=w.yellow,Q="neutral",X="warn";else Z="✅ ",D=w.cyan,Q="positive",X="info";let G=P0(Q),V=`${D}[${h}] ${Z}[${Y}] [${$.toUpperCase()}]${w.reset}`;console[X](`${V}`,...W,`- ${G}`)},_={setLogLevel:y0,setCustomLogger:h0,info:x0,warn:C0,error:b0,perf:u0,levels:a};class E${setup;constructor($){this.setup=$}async handle($){try{if(J$($,this.setup._configuration.cors)){$._response._parseResponseIntoString();return}let Y=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!Y){let q=await this.setup._hooks._onNotFound($);$._response._setBody(q),$._response._parseResponseIntoString();return}$.request.params=Y.params;let{handler:Z,options:D}=Y,{beforeHooks:Q=[],afterHooks:X=[]}=D,G=this.setup._hooks._beforeAll;for(let q of G)await q.handler($);for(let q of Q)await q($);let V=null;try{V=await Z($)}catch(q){throw q}for(let q of X)await q($);let A=this.setup._hooks._afterAll;for(let q of A)await q.handler($);if($._response._setBody(V),$.request.method==="HEAD")$._response._setBody(null);$._response._parseResponseIntoString();return}catch(W){await this.handleError($,W)}}async handleError($,W){try{let Y=this.setup._hooks._onError,Z=await Y($,W);$._response._setBody(Z),J$($,this.setup._configuration.cors),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:B$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
|
|
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(`
|
|
2
2
|
|
|
3
|
-
`)[1]?.length.toString()??"0"})}catch(
|
|
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
|
|
6
|
-
`)?$.slice(2):$,
|
|
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
|
|
6
|
+
`)?$.slice(2):$,W=M.indexOf(`\r
|
|
7
7
|
\r
|
|
8
|
-
`);if(
|
|
9
|
-
`)?
|
|
10
|
-
`)?
|
|
11
|
-
`),[Z,
|
|
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
|
|
12
12
|
\r
|
|
13
|
-
`);if(!
|
|
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,`
|
|
14
14
|
`).split(`
|
|
15
|
-
`);for(let
|
|
16
|
-
`))throw new Error(`Header value contains invalid line break characters: ${$}`);let
|
|
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(`
|
|
17
17
|
`)}
|
|
18
18
|
`:"";this._stringBody=`${$}
|
|
19
|
-
${
|
|
20
|
-
${
|
|
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"?`
|
|
21
21
|
|
|
22
|
-
❌ Incorrect: app.${
|
|
23
|
-
✅ Correct: app.${
|
|
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}
|
|
24
24
|
|
|
25
|
-
Note: Wrap your handler function in ${
|
|
25
|
+
Note: Wrap your handler function in ${O.magenta}square brackets${O.reset} to make it an array.
|
|
26
26
|
|
|
27
27
|
`:`
|
|
28
28
|
|
|
29
29
|
Expected: Array<HandlerCallback>
|
|
30
|
-
Received: ${
|
|
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};
|
|
31
31
|
|
|
32
|
-
//# debugId=
|
|
32
|
+
//# debugId=E1941AE25D0319AE64756E2164756E21
|