blaizejs 0.5.3 → 0.7.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/dist/{chunk-VVEKNV22.js → chunk-CM6LIHRF.js} +3 -3
- package/dist/{chunk-ZBJU7ZOM.js → chunk-FLI2OVQ5.js} +3 -3
- package/dist/{chunk-BOFAGA5B.js → chunk-HQRQVJL6.js} +3 -3
- package/dist/{chunk-NXPSLUP5.js → chunk-J5FJFX2G.js} +3 -3
- package/dist/{chunk-JMYOXYX4.js → chunk-MZG6O7BX.js} +2 -2
- package/dist/{chunk-JMYOXYX4.js.map → chunk-MZG6O7BX.js.map} +1 -1
- package/dist/index.cjs +16 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3014 -1689
- package/dist/index.d.ts +3014 -1689
- package/dist/index.js +17 -15
- package/dist/index.js.map +1 -1
- package/dist/{internal-server-error-MIWZOL6G.js → internal-server-error-RRNSAEYK.js} +3 -3
- package/dist/{payload-too-large-error-INCZ2WM7.js → payload-too-large-error-SQMCGPZ7.js} +3 -3
- package/dist/{unsupported-media-type-error-BVGBPGOM.js → unsupported-media-type-error-6T47SVVY.js} +3 -3
- package/dist/{validation-error-BQK2BTX6.js → validation-error-DRCBJ7IF.js} +3 -3
- package/package.json +2 -2
- /package/dist/{chunk-VVEKNV22.js.map → chunk-CM6LIHRF.js.map} +0 -0
- /package/dist/{chunk-ZBJU7ZOM.js.map → chunk-FLI2OVQ5.js.map} +0 -0
- /package/dist/{chunk-BOFAGA5B.js.map → chunk-HQRQVJL6.js.map} +0 -0
- /package/dist/{chunk-NXPSLUP5.js.map → chunk-J5FJFX2G.js.map} +0 -0
- /package/dist/{internal-server-error-MIWZOL6G.js.map → internal-server-error-RRNSAEYK.js.map} +0 -0
- /package/dist/{payload-too-large-error-INCZ2WM7.js.map → payload-too-large-error-SQMCGPZ7.js.map} +0 -0
- /package/dist/{unsupported-media-type-error-BVGBPGOM.js.map → unsupported-media-type-error-6T47SVVY.js.map} +0 -0
- /package/dist/{validation-error-BQK2BTX6.js.map → validation-error-DRCBJ7IF.js.map} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -1,31 +1,33 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* blaizejs v0.
|
|
3
|
+
* blaizejs v0.7.0
|
|
4
4
|
* A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
|
|
5
5
|
*
|
|
6
6
|
* Copyright (c) 2025 BlaizeJS Contributors
|
|
7
7
|
* @license MIT
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
"use strict";var Jr=Object.create;var he=Object.defineProperty;var Yr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,en=Object.prototype.hasOwnProperty;var J=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var r in t)he(e,r,{get:t[r],enumerable:!0})},xt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kr(t))!en.call(e,o)&&o!==r&&he(e,o,{get:()=>t[o],enumerable:!(n=Yr(t,o))||n.enumerable});return e};var M=(e,t,r)=>(r=e!=null?Jr(Xr(e)):{},xt(t||!e||!e.__esModule?he(r,"default",{value:e,enumerable:!0}):r,e)),tn=e=>xt(he({},"__esModule",{value:!0}),e);var P,Et,w,C=J(()=>{"use strict";P=(y=>(y.VALIDATION_ERROR="VALIDATION_ERROR",y.NOT_FOUND="NOT_FOUND",y.UNAUTHORIZED="UNAUTHORIZED",y.FORBIDDEN="FORBIDDEN",y.SSE_NOT_ACCEPTABLE="SSE_NOT_ACCEPTABLE",y.CONFLICT="CONFLICT",y.RATE_LIMITED="RATE_LIMITED",y.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",y.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",y.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",y.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",y.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",y.NETWORK_ERROR="NETWORK_ERROR",y.TIMEOUT_ERROR="TIMEOUT_ERROR",y.PARSE_ERROR="PARSE_ERROR",y.HTTP_ERROR="HTTP_ERROR",y.SSE_CONNECTION_ERROR="SSE_CONNECTION_ERROR",y.SSE_BUFFER_OVERFLOW="SSE_BUFFER_OVERFLOW",y.SSE_STREAM_CLOSED="SSE_STREAM_CLOSED",y.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",y))(P||{}),Et=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(Et||{}),w=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,r,n,o,i){super(r),this.name=this.constructor.name,this.type=t,this.title=r,this.status=n,this.correlationId=o,this.timestamp=new Date,this.details=i,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}}});function rn(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function bt(e,t){ye={headerName:e||Ge.headerName,generator:t||Ge.generator}}function W(){return ye.headerName}function nn(){return ye.generator()}function m(){let e=Rt.getStore();return e&&e.trim()?e:"unknown"}function Ct(e,t){return Rt.run(e,t)}function Se(e){let t=ye.headerName,r=e[t],n;return Array.isArray(r)?n=r[0]:typeof r=="string"&&(n=r),n&&n.trim()?n:nn()}var Tt,Ge,ye,Rt,b=J(()=>{"use strict";Tt=require("async_hooks"),Ge={headerName:"x-correlation-id",generator:rn},ye={...Ge},Rt=new Tt.AsyncLocalStorage});var Q={};te(Q,{ValidationError:()=>_});var _,k=J(()=>{"use strict";C();b();_=class extends w{constructor(t,r=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??m(),r)}}});var tt={};te(tt,{PayloadTooLargeError:()=>I});var I,ae=J(()=>{"use strict";C();b();I=class extends w{constructor(t,r,n){super("PAYLOAD_TOO_LARGE",t,413,n??m(),r)}}});var rt={};te(rt,{UnsupportedMediaTypeError:()=>L});var L,ce=J(()=>{"use strict";C();b();L=class extends w{constructor(t,r,n){super("UNSUPPORTED_MEDIA_TYPE",t,415,n??m(),r)}}});var tr={};te(tr,{InternalServerError:()=>H});var H,le=J(()=>{"use strict";C();b();H=class extends w{constructor(t,r=void 0,n=void 0){super("INTERNAL_SERVER_ERROR",t,500,n??m(),r)}}});var pi={};te(pi,{Blaize:()=>di,BlaizeError:()=>w,ConflictError:()=>qe,ErrorSeverity:()=>Et,ErrorType:()=>P,ForbiddenError:()=>Y,InternalServerError:()=>H,MiddlewareAPI:()=>Qr,NotFoundError:()=>U,PayloadTooLargeError:()=>I,PluginsAPI:()=>Gr,RateLimitError:()=>je,RequestTimeoutError:()=>Ve,RouterAPI:()=>Wr,ServerAPI:()=>Vr,ServiceNotAvailableError:()=>Qe,UnauthorizedError:()=>Ue,UnprocessableEntityError:()=>We,UnsupportedMediaTypeError:()=>L,VERSION:()=>jr,ValidationError:()=>_,asMiddlewareArray:()=>ai,asPluginArray:()=>ci,buildUrl:()=>Ie,compilePathPattern:()=>K,compose:()=>V,cors:()=>ne,createDeleteRoute:()=>Oe,createGetRoute:()=>Pe,createHeadRoute:()=>Fe,createMatcher:()=>X,createMiddleware:()=>$,createMiddlewareArray:()=>li,createOptionsRoute:()=>ke,createPatchRoute:()=>Ae,createPlugin:()=>ve,createPluginArray:()=>ui,createPostRoute:()=>_e,createPutRoute:()=>Me,createRouteFactory:()=>et,createServer:()=>Le,createServiceMiddleware:()=>xe,createStateMiddleware:()=>we,extractParams:()=>Z,getCorrelationId:()=>m,inferContext:()=>wt,isMiddleware:()=>ii,isPlugin:()=>si,paramsToQuery:()=>ie});module.exports=tn(pi);function vt(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let n=e.execute(t,r);return n instanceof Promise?n:Promise.resolve(n)}catch(n){return Promise.reject(n)}}function V(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let n=new Set,o=async i=>{if(i>=e.length)return Promise.resolve(r());let s=e[i];return vt(s,t,()=>{if(n.has(i))throw new Error("next() called multiple times");return n.add(i),o(i+1)})};return o(0)}}C();b();var Y=class extends w{constructor(t,r=void 0,n=void 0){super("FORBIDDEN",t,403,n??m(),r)}};function $(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:n,debug:o=!1}=e;return{name:t,execute:r,debug:o,...n!==void 0&&{skip:n}}}function we(e){return $({name:"state-middleware",handler:e})}function xe(e){return $({name:"service-middleware",handler:e})}var on={origin:!0,methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],credentials:!1,optionsSuccessStatus:204},sn={origin:!1,methods:["GET","HEAD"],credentials:!1,optionsSuccessStatus:204};function Pt(e){return e===void 0&&(e=process.env.NODE_ENV!=="production"),e?{...on}:{...sn}}function an(e=6e4,t=1e3){let r=new Map,n={ttl:e,maxSize:t},o=(h,x,T)=>`${h}:${x}:${T||"anonymous"}`,i=()=>{if(r.size===0)return;let h=null,x=1/0;for(let[T,u]of r.entries())u.lastAccessed<x&&(x=u.lastAccessed,h=T);h&&r.delete(h)};return{get:(h,x,T)=>{let u=o(h,x,T),f=r.get(u);if(!f)return null;let g=Date.now();return g>f.expiresAt?(r.delete(u),null):(f.lastAccessed=g,f.allowed)},set:(h,x,T,u)=>{let f=o(h,T,u),g=Date.now();if(r.has(f)){r.set(f,{allowed:x,expiresAt:g+n.ttl,lastAccessed:g});return}r.size>=n.maxSize&&i(),r.set(f,{allowed:x,expiresAt:g+n.ttl,lastAccessed:g})},clear:()=>{r.clear()},cleanExpired:()=>{let h=Date.now(),x=0;for(let[T,u]of r.entries())h>u.expiresAt&&(r.delete(T),x++);return x},getStats:()=>({size:r.size,maxSize:n.maxSize,ttl:n.ttl})}}var _t=an();function cn(e){return typeof e=="boolean"||typeof e=="function"?!1:Array.isArray(e)?e.every(t=>typeof t=="string"||t instanceof RegExp):typeof e=="string"||e instanceof RegExp}function ln(e){return typeof e=="string"?`str:${e}`:e instanceof RegExp?`regex:${e.source}:${e.flags}`:Array.isArray(e)?`array:[${e.map(t=>typeof t=="string"?`str:${t}`:t instanceof RegExp?`regex:${t.source}:${t.flags}`:"unknown").join(",")}]`:"unknown"}async function un(e,t){return t==="*"?!0:e===t}async function dn(e,t){return t.test(e)}async function pn(e,t,r,n=100){let o;try{let i=new Promise(a=>{o=setTimeout(()=>{a({timedOut:!0})},n)}),s=await Promise.race([Promise.resolve(t(e,r)).then(a=>({result:a})),i]);return o&&clearTimeout(o),"timedOut"in s?(console.warn(`CORS origin validation function timed out after ${n}ms for origin: ${e}`),!1):s.result}catch(i){return o&&clearTimeout(o),console.error("CORS origin validation function error:",i),!1}}async function Mt(e,t,r){let n=t.map(i=>Ze(e,i,r));return(await Promise.all(n)).some(i=>i===!0)}async function Ze(e,t,r){return typeof t=="string"?un(e,t):t instanceof RegExp?dn(e,t):typeof t=="function"?pn(e,t,r):(console.warn("Unknown CORS origin type:",typeof t),!1)}async function re(e,t,r){if(t===!0)return!0;if(t===!1)return!1;if(cn(t)){let o=r?.state?.user?.id||r?.state?.userId,i=ln(t),s=_t.get(e,i,o);if(s!==null)return s;let a;return Array.isArray(t)?a=await Mt(e,t,r):a=await Ze(e,t,r),_t.set(e,a,i,o),a}else return Array.isArray(t)?Mt(e,t,r):Ze(e,t,r)}k();function fn(e){let t=e.request.header("origin")||e.request.header("Origin"),r=e.request.header("access-control-request-method")||e.request.header("Access-Control-Request-Method"),n=e.request.header("access-control-request-headers")||e.request.header("Access-Control-Request-Headers"),o=n?n.split(",").map(i=>i.trim().toLowerCase()):void 0;return{origin:t,requestedMethod:r,requestedHeaders:o}}function Je(e){return e.toUpperCase()}function mn(e,t){return t?(typeof t=="string"?t.split(",").map(n=>n.trim()):t).map(n=>Je(n)).includes(Je(e)):["GET","HEAD","PUT","PATCH","POST","DELETE"].includes(Je(e))}function gn(e,t){if(!e||e.length===0||t===void 0)return!0;let r=typeof t=="string"?t.split(",").map(n=>n.trim().toLowerCase()):t.map(n=>n.toLowerCase());return e.every(n=>r.includes(n.toLowerCase()))}function hn(e,t,r,n){n&&(t.origin===!0&&!t.credentials?e.response.header("Access-Control-Allow-Origin","*"):(e.response.header("Access-Control-Allow-Origin",r),e.response.header("Vary","Origin"))),t.credentials&&n&&e.response.header("Access-Control-Allow-Credentials","true");let o=t.methods||["GET","HEAD","PUT","PATCH","POST","DELETE"],i=typeof o=="string"?o:o.join(", ");if(e.response.header("Access-Control-Allow-Methods",i),t.allowedHeaders){let s=typeof t.allowedHeaders=="string"?t.allowedHeaders:t.allowedHeaders.join(", ");e.response.header("Access-Control-Allow-Headers",s)}else{let s=e.request.header("access-control-request-headers")||e.request.header("Access-Control-Request-Headers");s&&e.response.header("Access-Control-Allow-Headers",s)}t.maxAge!==void 0&&t.maxAge>=0&&e.response.header("Access-Control-Max-Age",String(t.maxAge))}async function Ot(e,t){let r=fn(e);if(!r.origin||!r.requestedMethod)throw e.response.status(403),new _("Invalid preflight request: missing required headers",{fields:[{field:r.origin?"Access-Control-Request-Method":"Origin",messages:["Required header is missing"]}],errorCount:1,section:"body"});let n=await re(r.origin,t.origin||!1,e);if(!n)throw e.response.status(403),new _("CORS origin not allowed",{fields:[{field:"Origin",messages:[`Origin '${r.origin}' is not allowed`],rejectedValue:r.origin}],errorCount:1,section:"body"});if(!mn(r.requestedMethod,t.methods))throw e.response.status(403),new _("CORS method not allowed",{fields:[{field:"Access-Control-Request-Method",messages:[`Method '${r.requestedMethod}' is not allowed`],rejectedValue:r.requestedMethod,expectedType:typeof t.methods=="string"?t.methods:t.methods?.join(", ")}],errorCount:1,section:"body"});if(!gn(r.requestedHeaders,t.allowedHeaders)){let i=r.requestedHeaders?.filter(s=>{let a=t.allowedHeaders;return a?!(typeof a=="string"?a.split(",").map(l=>l.trim().toLowerCase()):a.map(l=>l.toLowerCase())).includes(s.toLowerCase()):!1});throw e.response.status(403),new _("CORS headers not allowed",{fields:[{field:"Access-Control-Request-Headers",messages:[`Headers not allowed: ${i?.join(", ")}`],rejectedValue:i}],errorCount:1,section:"body"})}hn(e,t,r.origin,n);let o=t.optionsSuccessStatus||204;e.response.status(o),t.preflightContinue||e.response.text("")}function Ye(e){return e.request.method==="OPTIONS"&&!!(e.request.header("access-control-request-method")||e.request.header("Access-Control-Request-Method"))}var R=require("zod"),yn=R.z.enum(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"]),Sn=R.z.union([R.z.array(yn),R.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),At=R.z.union([R.z.array(R.z.string()),R.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),wn=R.z.custom(e=>typeof e=="function"&&e.length<=2,{message:"Origin validator must be a function accepting (origin, ctx?) parameters"}),Ft=R.z.union([R.z.string(),R.z.instanceof(RegExp),wn]),xn=R.z.union([R.z.boolean(),Ft,R.z.array(Ft)]),kt=R.z.object({origin:xn.optional(),methods:Sn,allowedHeaders:At,exposedHeaders:At,credentials:R.z.boolean().optional(),maxAge:R.z.number().int().optional(),preflightContinue:R.z.boolean().optional(),optionsSuccessStatus:R.z.number().int().min(200).max(299).optional()}).strict(),It=R.z.union([R.z.boolean(),kt]).optional();function zt(e){try{return typeof e=="boolean"?e===!1?{origin:!1}:{origin:!0}:kt.parse(e)}catch(t){if(t instanceof R.z.ZodError){let r=vn(t);throw new Error(`Invalid CORS options:
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
"use strict";var dn=Object.create;var Te=Object.defineProperty;var pn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var mn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var ee=(e,t)=>()=>(e&&(t=e(e=0)),t);var se=(e,t)=>{for(var r in t)Te(e,r,{get:t[r],enumerable:!0})},Lt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fn(t))!gn.call(e,o)&&o!==r&&Te(e,o,{get:()=>t[o],enumerable:!(n=pn(t,o))||n.enumerable});return e};var O=(e,t,r)=>(r=e!=null?dn(mn(e)):{},Lt(t||!e||!e.__esModule?Te(r,"default",{value:e,enumerable:!0}):r,e)),hn=e=>Lt(Te({},"__esModule",{value:!0}),e);var M,Dt,v,P=ee(()=>{"use strict";M=(w=>(w.VALIDATION_ERROR="VALIDATION_ERROR",w.NOT_FOUND="NOT_FOUND",w.UNAUTHORIZED="UNAUTHORIZED",w.FORBIDDEN="FORBIDDEN",w.SSE_NOT_ACCEPTABLE="SSE_NOT_ACCEPTABLE",w.CONFLICT="CONFLICT",w.RATE_LIMITED="RATE_LIMITED",w.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",w.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",w.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",w.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",w.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",w.NETWORK_ERROR="NETWORK_ERROR",w.TIMEOUT_ERROR="TIMEOUT_ERROR",w.PARSE_ERROR="PARSE_ERROR",w.HTTP_ERROR="HTTP_ERROR",w.SSE_CONNECTION_ERROR="SSE_CONNECTION_ERROR",w.SSE_BUFFER_OVERFLOW="SSE_BUFFER_OVERFLOW",w.SSE_STREAM_CLOSED="SSE_STREAM_CLOSED",w.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",w))(M||{}),Dt=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(Dt||{}),v=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,r,n,o,i){super(r),this.name=this.constructor.name,this.type=t,this.title=r,this.status=n,this.correlationId=o,this.timestamp=new Date,this.details=i,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}}});function En(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function Nt(e,t){Re={headerName:e||ot.headerName,generator:t||ot.generator}}function J(){return Re.headerName}function Tn(){return Re.generator()}function g(){let e=Bt.getStore();return e&&e.trim()?e:"unknown"}function Ht(e,t){return Bt.run(e,t)}function Ce(e){let t=Re.headerName,r=e[t],n;return Array.isArray(r)?n=r[0]:typeof r=="string"&&(n=r),n&&n.trim()?n:Tn()}var It,ot,Re,Bt,R=ee(()=>{"use strict";It=require("async_hooks"),ot={headerName:"x-correlation-id",generator:En},Re={...ot},Bt=new It.AsyncLocalStorage});var Y={};se(Y,{ValidationError:()=>_});var _,D=ee(()=>{"use strict";P();R();_=class extends v{constructor(t,r=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??g(),r)}}});var pt={};se(pt,{PayloadTooLargeError:()=>I});var I,me=ee(()=>{"use strict";P();R();I=class extends v{constructor(t,r,n){super("PAYLOAD_TOO_LARGE",t,413,n??g(),r)}}});var ft={};se(ft,{UnsupportedMediaTypeError:()=>j});var j,ge=ee(()=>{"use strict";P();R();j=class extends v{constructor(t,r,n){super("UNSUPPORTED_MEDIA_TYPE",t,415,n??g(),r)}}});var gr={};se(gr,{InternalServerError:()=>U});var U,he=ee(()=>{"use strict";P();R();U=class extends v{constructor(t,r=void 0,n=void 0){super("INTERNAL_SERVER_ERROR",t,500,n??g(),r)}}});var Di={};se(Di,{Blaize:()=>Fi,BlaizeError:()=>v,ConflictError:()=>Ye,ConsoleTransport:()=>H,ErrorSeverity:()=>Dt,ErrorType:()=>M,ForbiddenError:()=>re,InternalServerError:()=>U,JSONTransport:()=>G,Logger:()=>te,MiddlewareAPI:()=>cn,NotFoundError:()=>V,NullTransport:()=>ae,PayloadTooLargeError:()=>I,PluginsAPI:()=>ln,RateLimitError:()=>Ke,RequestTimeoutError:()=>Xe,RouterAPI:()=>an,ServerAPI:()=>sn,ServiceNotAvailableError:()=>tt,UnauthorizedError:()=>Je,UnprocessableEntityError:()=>et,UnsupportedMediaTypeError:()=>j,VERSION:()=>on,ValidationError:()=>_,asMiddlewareArray:()=>Li,asPluginArray:()=>Ai,buildUrl:()=>qe,compilePathPattern:()=>ne,compose:()=>Z,configureGlobalLogger:()=>ce,cors:()=>ue,createDeleteRoute:()=>Be,createGetRoute:()=>Fe,createHeadRoute:()=>He,createLogger:()=>F,createMatcher:()=>oe,createMiddleware:()=>A,createMiddlewareArray:()=>zi,createOptionsRoute:()=>$e,createPatchRoute:()=>Ne,createPlugin:()=>_e,createPluginArray:()=>ki,createPostRoute:()=>De,createPutRoute:()=>Ie,createRouteFactory:()=>dt,createServer:()=>Ze,createServiceMiddleware:()=>Me,createStateMiddleware:()=>Pe,extractParams:()=>X,getCorrelationId:()=>g,inferContext:()=>Ot,isMiddleware:()=>_i,isPlugin:()=>Oi,logger:()=>C,paramsToQuery:()=>pe,requestLoggerMiddleware:()=>ct});module.exports=hn(Di);var zt=require("util");function rt(e){return e instanceof Error}function nt(e){return{message:e.message,name:e.name,stack:e.stack}}function be(e){let t={};for(let[r,n]of Object.entries(e))if(rt(n))t[r]=nt(n);else if(Array.isArray(n))t[r]=n.map(o=>rt(o)?nt(o):o);else if(n instanceof Date)t[r]=n;else if(n&&typeof n=="object"){let o={};for(let[i,s]of Object.entries(n))rt(s)?o[i]=nt(s):o[i]=s;t[r]=o}else t[r]=n;return t}function At(){let e=new WeakSet;return(t,r)=>{if(typeof r=="object"&&r!==null){if(e.has(r))return"[Circular]";e.add(r)}return r}}var yn={debug:"\x1B[36m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},Sn="\x1B[0m",wn="\x1B[1m",H=class{write(t,r,n){let o=be(n),a=`${`${yn[t]}${wn}[${t.toUpperCase()}]${Sn}`} ${r}`,l=Object.keys(o).length>0?`
|
|
11
|
+
|
|
12
|
+
${(0,zt.inspect)(o,{colors:!0,depth:3,compact:!1,breakLength:80})}`:"";switch(t){case"error":console.error(a+l);break;case"warn":console.warn(a+l);break;case"debug":case"info":default:console.log(a+l);break}}};var G=class{write(t,r,n){let o=be(n),i={level:t,message:r,...o},s=JSON.stringify(i,At());console.log(s)}async flush(){return Promise.resolve()}};var kt={debug:0,info:1,warn:2,error:3},te=class e{config;inheritedMeta;minLevelPriority;constructor(t,r){this.config=t,this.inheritedMeta=Object.freeze(r?{...r}:{}),this.minLevelPriority=kt[t.level]}debug(t,r){this.log("debug",t,r)}info(t,r){this.log("info",t,r)}warn(t,r){this.log("warn",t,r)}error(t,r){this.log("error",t,r)}child(t){let r={...this.inheritedMeta,...t};return new e(this.config,r)}async flush(){await this.config.transport.flush?.()}log(t,r,n){if(!this.shouldLog(t))return;let o={...this.inheritedMeta,...n||{}},i=o;this.config.includeTimestamp&&(i={timestamp:new Date().toISOString(),...o});let s=this.redact(i);this.config.transport.write(t,r,s)}shouldLog(t){return kt[t]>=this.minLevelPriority}redact(t){if(this.config.redactKeys.length===0)return t;let r=new Set(this.config.redactKeys.map(o=>o.toLowerCase())),n={};for(let[o,i]of Object.entries(t))r.has(o.toLowerCase())?n[o]="[REDACTED]":n[o]=i;return n}};function vn(){return process.env.NODE_ENV!=="production"?new H:new G}function F(e){let t=process.env.NODE_ENV!=="production",r={level:e?.level??(t?"debug":"info"),transport:e?.transport??vn(),redactKeys:e?.redactKeys??[],includeTimestamp:e?.includeTimestamp??!0};return new te(r)}var ae=class{write(t,r,n){}async flush(){return Promise.resolve()}};var C=F({level:process.env.NODE_ENV==="development"?"debug":"info",transport:new H,includeTimestamp:!0,redactKeys:[]}),xn=C;function ce(e){let t=F(e);xn=t,Object.assign(C,t)}function Ft(e,t,r,n){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let o=e.execute(t,r,n);return o instanceof Promise?o:Promise.resolve(o)}catch(o){return Promise.reject(o)}}function Z(e){return e.length===0?async(t,r,n)=>{await Promise.resolve(r())}:async function(t,r,n){let o=new Set,i=async s=>{if(s>=e.length)return Promise.resolve(r());let a=e[s],c=()=>{if(o.has(s))throw new Error("next() called multiple times");return o.add(s),i(s+1)},l=n.child({middleware:a?.name||"anonymous"});return Ft(a,t,c,l)};return i(0)}}P();R();var re=class extends v{constructor(t,r=void 0,n=void 0){super("FORBIDDEN",t,403,n??g(),r)}};function A(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:n,debug:o=!1}=e;return{name:t,execute:r,debug:o,...n!==void 0&&{skip:n}}}function Pe(e){return A({name:"state-middleware",handler:e})}function Me(e){return A({name:"service-middleware",handler:e})}var bn={origin:!0,methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],credentials:!1,optionsSuccessStatus:204},Rn={origin:!1,methods:["GET","HEAD"],credentials:!1,optionsSuccessStatus:204};function $t(e){return e===void 0&&(e=process.env.NODE_ENV!=="production"),e?{...bn}:{...Rn}}function Cn(e=6e4,t=1e3){let r=new Map,n={ttl:e,maxSize:t},o=(y,x,T)=>`${y}:${x}:${T||"anonymous"}`,i=()=>{if(r.size===0)return;let y=null,x=1/0;for(let[T,u]of r.entries())u.lastAccessed<x&&(x=u.lastAccessed,y=T);y&&r.delete(y)};return{get:(y,x,T)=>{let u=o(y,x,T),d=r.get(u);if(!d)return null;let h=Date.now();return h>d.expiresAt?(r.delete(u),null):(d.lastAccessed=h,d.allowed)},set:(y,x,T,u)=>{let d=o(y,T,u),h=Date.now();if(r.has(d)){r.set(d,{allowed:x,expiresAt:h+n.ttl,lastAccessed:h});return}r.size>=n.maxSize&&i(),r.set(d,{allowed:x,expiresAt:h+n.ttl,lastAccessed:h})},clear:()=>{r.clear()},cleanExpired:()=>{let y=Date.now(),x=0;for(let[T,u]of r.entries())y>u.expiresAt&&(r.delete(T),x++);return x},getStats:()=>({size:r.size,maxSize:n.maxSize,ttl:n.ttl})}}var qt=Cn();function Pn(e){return typeof e=="boolean"||typeof e=="function"?!1:Array.isArray(e)?e.every(t=>typeof t=="string"||t instanceof RegExp):typeof e=="string"||e instanceof RegExp}function Mn(e){return typeof e=="string"?`str:${e}`:e instanceof RegExp?`regex:${e.source}:${e.flags}`:Array.isArray(e)?`array:[${e.map(t=>typeof t=="string"?`str:${t}`:t instanceof RegExp?`regex:${t.source}:${t.flags}`:"unknown").join(",")}]`:"unknown"}async function _n(e,t){return t==="*"?!0:e===t}async function On(e,t){return t.test(e)}async function Ln(e,t,r,n=100){let o;try{let i=new Promise(a=>{o=setTimeout(()=>{a({timedOut:!0})},n)}),s=await Promise.race([Promise.resolve(t(e,r)).then(a=>({result:a})),i]);return o&&clearTimeout(o),"timedOut"in s?(console.warn(`CORS origin validation function timed out after ${n}ms for origin: ${e}`),!1):s.result}catch(i){return o&&clearTimeout(o),console.error("CORS origin validation function error:",i),!1}}async function Ut(e,t,r){let n=t.map(i=>it(e,i,r));return(await Promise.all(n)).some(i=>i===!0)}async function it(e,t,r){return typeof t=="string"?_n(e,t):t instanceof RegExp?On(e,t):typeof t=="function"?Ln(e,t,r):(console.warn("Unknown CORS origin type:",typeof t),!1)}async function le(e,t,r){if(t===!0)return!0;if(t===!1)return!1;if(Pn(t)){let o=r?.state?.user?.id||r?.state?.userId,i=Mn(t),s=qt.get(e,i,o);if(s!==null)return s;let a;return Array.isArray(t)?a=await Ut(e,t,r):a=await it(e,t,r),qt.set(e,a,i,o),a}else return Array.isArray(t)?Ut(e,t,r):it(e,t,r)}D();function An(e){let t=e.request.header("origin")||e.request.header("Origin"),r=e.request.header("access-control-request-method")||e.request.header("Access-Control-Request-Method"),n=e.request.header("access-control-request-headers")||e.request.header("Access-Control-Request-Headers"),o=n?n.split(",").map(i=>i.trim().toLowerCase()):void 0;return{origin:t,requestedMethod:r,requestedHeaders:o}}function st(e){return e.toUpperCase()}function zn(e,t){return t?(typeof t=="string"?t.split(",").map(n=>n.trim()):t).map(n=>st(n)).includes(st(e)):["GET","HEAD","PUT","PATCH","POST","DELETE"].includes(st(e))}function kn(e,t){if(!e||e.length===0||t===void 0)return!0;let r=typeof t=="string"?t.split(",").map(n=>n.trim().toLowerCase()):t.map(n=>n.toLowerCase());return e.every(n=>r.includes(n.toLowerCase()))}function Fn(e,t,r,n){n&&(t.origin===!0&&!t.credentials?e.response.header("Access-Control-Allow-Origin","*"):(e.response.header("Access-Control-Allow-Origin",r),e.response.header("Vary","Origin"))),t.credentials&&n&&e.response.header("Access-Control-Allow-Credentials","true");let o=t.methods||["GET","HEAD","PUT","PATCH","POST","DELETE"],i=typeof o=="string"?o:o.join(", ");if(e.response.header("Access-Control-Allow-Methods",i),t.allowedHeaders){let s=typeof t.allowedHeaders=="string"?t.allowedHeaders:t.allowedHeaders.join(", ");e.response.header("Access-Control-Allow-Headers",s)}else{let s=e.request.header("access-control-request-headers")||e.request.header("Access-Control-Request-Headers");s&&e.response.header("Access-Control-Allow-Headers",s)}t.maxAge!==void 0&&t.maxAge>=0&&e.response.header("Access-Control-Max-Age",String(t.maxAge))}async function jt(e,t){let r=An(e);if(!r.origin||!r.requestedMethod)throw e.response.status(403),new _("Invalid preflight request: missing required headers",{fields:[{field:r.origin?"Access-Control-Request-Method":"Origin",messages:["Required header is missing"]}],errorCount:1,section:"body"});let n=await le(r.origin,t.origin||!1,e);if(!n)throw e.response.status(403),new _("CORS origin not allowed",{fields:[{field:"Origin",messages:[`Origin '${r.origin}' is not allowed`],rejectedValue:r.origin}],errorCount:1,section:"body"});if(!zn(r.requestedMethod,t.methods))throw e.response.status(403),new _("CORS method not allowed",{fields:[{field:"Access-Control-Request-Method",messages:[`Method '${r.requestedMethod}' is not allowed`],rejectedValue:r.requestedMethod,expectedType:typeof t.methods=="string"?t.methods:t.methods?.join(", ")}],errorCount:1,section:"body"});if(!kn(r.requestedHeaders,t.allowedHeaders)){let i=r.requestedHeaders?.filter(s=>{let a=t.allowedHeaders;return a?!(typeof a=="string"?a.split(",").map(l=>l.trim().toLowerCase()):a.map(l=>l.toLowerCase())).includes(s.toLowerCase()):!1});throw e.response.status(403),new _("CORS headers not allowed",{fields:[{field:"Access-Control-Request-Headers",messages:[`Headers not allowed: ${i?.join(", ")}`],rejectedValue:i}],errorCount:1,section:"body"})}Fn(e,t,r.origin,n);let o=t.optionsSuccessStatus||204;e.response.status(o),t.preflightContinue||e.response.text("")}function at(e){return e.request.method==="OPTIONS"&&!!(e.request.header("access-control-request-method")||e.request.header("Access-Control-Request-Method"))}var b=require("zod"),Dn=b.z.enum(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"]),In=b.z.union([b.z.array(Dn),b.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),Vt=b.z.union([b.z.array(b.z.string()),b.z.string().transform(e=>e.split(",").map(t=>t.trim()))]).optional(),Bn=b.z.custom(e=>typeof e=="function"&&e.length<=2,{message:"Origin validator must be a function accepting (origin, ctx?) parameters"}),Wt=b.z.union([b.z.string(),b.z.instanceof(RegExp),Bn]),Nn=b.z.union([b.z.boolean(),Wt,b.z.array(Wt)]),Qt=b.z.object({origin:Nn.optional(),methods:In,allowedHeaders:Vt,exposedHeaders:Vt,credentials:b.z.boolean().optional(),maxAge:b.z.number().int().optional(),preflightContinue:b.z.boolean().optional(),optionsSuccessStatus:b.z.number().int().min(200).max(299).optional()}).strict(),Gt=b.z.union([b.z.boolean(),Qt]).optional();function Zt(e){try{return typeof e=="boolean"?e===!1?{origin:!1}:{origin:!0}:Qt.parse(e)}catch(t){if(t instanceof b.z.ZodError){let r=Hn(t);throw new Error(`Invalid CORS options:
|
|
13
|
+
${r}`)}throw new Error(`Invalid CORS options: ${String(t)}`)}}function Hn(e){return e.errors.map(r=>` - ${r.path.join(".")||"root"}: ${r.message}`).join(`
|
|
14
|
+
`)}function $n(e){return Array.isArray(e)}function Jt(e){if(e.credentials===!0&&e.origin!==void 0){if(e.origin===!0||e.origin==="*")throw new Error("CORS security violation: Cannot use wildcard origin (*) with credentials. When credentials are enabled, you must specify explicit origins.");if($n(e.origin)&&e.origin.some(r=>r==="*"))throw new Error("CORS security violation: Cannot include wildcard origin (*) in array when credentials are enabled.")}}function Yt(e,t){return e===!0?{...t,origin:!0}:e===!1?{origin:!1}:e?{...t,...e,methods:e.methods??t.methods,allowedHeaders:e.allowedHeaders??t.allowedHeaders,exposedHeaders:e.exposedHeaders??t.exposedHeaders}:t}function qn(e,t,r,n){if(!(!n||!r)&&(t.origin===!0&&!t.credentials?e.response.header("Access-Control-Allow-Origin","*"):(e.response.header("Access-Control-Allow-Origin",r),e.response.header("Vary","Origin")),t.credentials&&e.response.header("Access-Control-Allow-Credentials","true"),t.exposedHeaders)){let o=typeof t.exposedHeaders=="string"?t.exposedHeaders:t.exposedHeaders.join(", ");e.response.header("Access-Control-Expose-Headers",o)}}function ue(e){let t=process.env.NODE_ENV==="development",r=$t(t),n=Yt(e,r),o=Zt(n);return Jt(o),A({name:"cors",handler:async(i,s)=>{let a=i.request.header("origin")||i.request.header("Origin");if(at(i)){if(await jt(i,o),!o.preflightContinue)return}else{if(!a){await s();return}let c=await le(a,o.origin||!1,i);if(!c)throw i.response.status(403),new re("CORS validation failed",{reason:"origin_not_allowed",origin:a,allowedOrigins:o.origin});qn(i,o,a,c)}await s()},debug:process.env.DEBUG?.includes("cors")})}P();var Un=["accept","content-type","user-agent","x-correlation-id"],jn=["authorization","cookie","x-api-key","proxy-authorization"];function Vn(e,t){let r={},n=new Set(t.map(i=>i.toLowerCase())),o=new Set(jn.map(i=>i.toLowerCase()));for(let[i,s]of Object.entries(e)){let a=i.toLowerCase();n.has(a)&&(o.has(a)?r[i]="[REDACTED]":r[i]=s)}return r}function ct(e){return A({name:"requestLogger",handler:async(t,r,n)=>{let o=Date.now(),i;"socket"in t.request.raw&&(i=t.request.raw.socket?.remoteAddress);let s={timestamp:new Date().toISOString()};if(i&&(s.ip=i),e?.includeHeaders){let c=e.headerWhitelist||Un,l=t.request.headers(),p=Vn(l,c);Object.keys(p).length>0&&(s.headers=p)}if(e?.includeQuery){let c=t.request.query;c&&Object.keys(c).length>0&&(s.query=c)}n.info("Request started",s);let a;try{await r()}catch(c){a=c}finally{let c=Date.now()-o;if(a){let l={duration:c,timestamp:new Date().toISOString()};a instanceof v?l.error={type:a.type,title:a.title,status:a.status,message:a.message,details:a.details,...a.status>=500&&a.stack?{stack:a.stack}:{}}:a instanceof Error?l.error={message:a.message,name:a.name,stack:a.stack}:l.error=String(a),n.error("Request failed",l)}else{let l=t.response.statusCode||200;n.info("Request completed",{statusCode:l,duration:c,timestamp:new Date().toISOString()})}if(a)throw a}}})}function _e(e){if(!e.name||typeof e.name!="string")throw new Error("Plugin name must be a non-empty string");if(!e.version||typeof e.version!="string")throw new Error("Plugin version must be a non-empty string");if(typeof e.setup!="function")throw new Error("Plugin setup must be a function");return function(r){let n={...e.defaultConfig||{},...r||{}},o=F().child({plugin:e.name,version:e.version}),i=e.setup(n,o);if(i===null||typeof i!="object")throw new Error(`Plugin "${e.name}" setup() must return an object with lifecycle hooks`);return{name:e.name,version:e.version,register:i.register||(async()=>{o.debug("Plugin registered (no-op)")}),initialize:i.initialize,onServerStart:i.onServerStart,onServerStop:i.onServerStop,terminate:i.terminate}}}var sr=require("url");var Oe={};function Kt(e){Oe={...Oe,...e}}function Xt(){if(!Oe.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return Oe.routesDir}var er=O(require("path"),1);function Le(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),o=n.endsWith("/")?n:`${n}/`,i=r;r.startsWith(o)?i=r.substring(o.length):r.startsWith(n)?(i=r.substring(n.length),i.startsWith("/")&&(i=i.substring(1))):i=er.relative(n,r).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),a=[],c=s.map(p=>{if(p.startsWith("[")&&p.endsWith("]")){let y=p.slice(1,-1);return a.push(y),`:${y}`}return p}),l=c.length>0?`/${c.join("/")}`:"/";return l.endsWith("/index")&&(l=l.slice(0,-6)||"/"),{filePath:e,routePath:l,params:a}}var nr=require("events");var z=require("zod"),Wn=z.z.enum(["drop-oldest","drop-newest","close"]),Qn=z.z.object({low:z.z.number().int().positive().describe("Resume threshold in messages"),high:z.z.number().int().positive().describe("Trigger threshold in messages")}).refine(e=>e.low<e.high,{message:"Low watermark must be less than high watermark",path:["low"]}),Gn=z.z.object({maxMessages:z.z.number().int().positive().max(1e5).describe("Maximum number of messages in buffer"),maxBytes:z.z.number().int().positive().max(100*1024*1024).optional().describe("Maximum buffer size in bytes"),messageTimeout:z.z.number().int().nonnegative().max(3e5).optional().describe("Message TTL in milliseconds")}),tr=z.z.object({enabled:z.z.boolean().default(!0).describe("Enable backpressure management"),strategy:Wn.default("drop-oldest").describe("Strategy when buffer reaches high watermark"),watermarks:Qn.default({low:100,high:1e3}).describe("Buffer watermark thresholds"),limits:Gn.default({maxMessages:1e4}).describe("Buffer size constraints"),metrics:z.z.object({enabled:z.z.boolean().default(!1),interval:z.z.number().int().positive().default(5e3)}).optional().describe("Metrics collection configuration")}).refine(e=>e.watermarks.high<=e.limits.maxMessages,{message:"High watermark cannot exceed maxMessages limit",path:["watermarks","high"]});var Zn={maxConnections:1e4,maxConnectionsPerClient:100,inactiveTimeout:18e5,cleanupInterval:6e4};function Jn(e){let t={...Zn,...e},r=new Map,n=new Map,o=null,i={},s=f=>{!o&&t.cleanupInterval>0&&(o=setInterval(()=>{f()},t.cleanupInterval),o.unref&&o.unref())},a=()=>{o&&(clearInterval(o),o=null)},c=(f,m)=>{if(!f)return;let w=(n.get(f)||0)+m;w<=0?n.delete(f):n.set(f,w)},l=(f,m,E)=>{if(r.has(f))throw new Error(`Connection with ID ${f} already exists`);if(r.size>=t.maxConnections)throw new Error(`Maximum connection limit reached (${t.maxConnections})`);if(E?.clientIp&&(n.get(E.clientIp)||0)>=t.maxConnectionsPerClient)throw new Error(`Maximum connections per client reached (${t.maxConnectionsPerClient})`);let w=Date.now();r.set(f,{stream:m,connectedAt:w,lastActivity:w,clientIp:E?.clientIp,userAgent:E?.userAgent}),c(E?.clientIp,1),r.size===1&&s(i.cleanup),m.onClose(()=>{p(f)})},p=f=>{let m=r.get(f);m&&(r.delete(f),c(m.clientIp,-1),r.size===0&&a())},y=()=>r.size,x=()=>{let f=Date.now(),m=[];r.forEach((E,w)=>{let N=f-E.lastActivity>t.inactiveTimeout,un=!E.stream||E.stream.state==="closed"||!E.stream.isWritable;if((N||un)&&(m.push(w),E.stream&&typeof E.stream.close=="function"))try{E.stream.close()}catch{}}),m.forEach(E=>p(E))},T=f=>r.get(f)?.stream,u=f=>r.has(f),d=()=>Array.from(r.keys()),h=()=>{a(),r.forEach(f=>{if(f.stream&&typeof f.stream.close=="function")try{f.stream.close()}catch{}}),r.clear(),n.clear()};return i.add=l,i.remove=p,i.count=y,i.cleanup=x,i.get=T,i.has=u,i.getIds=d,i.shutdown=h,i}var lt=null;function Ae(e){return lt||(lt=Jn(e)),lt}P();R();var de=class extends v{constructor(t,r,n=void 0){super("SSE_BUFFER_OVERFLOW",t,503,n??g(),r)}};P();R();var ze=class extends v{constructor(t,r=void 0,n=void 0){super("SSE_STREAM_CLOSED",t,410,n??g(),r)}};R();var Yn={heartbeatInterval:3e4,maxEventSize:1024*1024,autoClose:!0,maxBufferSize:1e3,bufferStrategy:"drop-oldest"};function rr(e,t,r,n){let o=[];r&&o.push(`id: ${r}`),n!==void 0&&o.push(`retry: ${n}`),o.push(`event: ${e}`);let s=(t===null?"null":t===void 0?"undefined":typeof t=="string"?t:JSON.stringify(t)).split(`
|
|
13
15
|
`);for(let a of s)o.push(`data: ${a}`);return o.push(""),o.join(`
|
|
14
16
|
`)+`
|
|
15
|
-
`}function
|
|
17
|
+
`}function Kn(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`${e}-${t}`}function Xn(e,t){let r=t===null?"null":t===void 0?"undefined":typeof t=="string"?t:JSON.stringify(t);return e.length+r.length+50}function eo(e,t,r,n){let o=0;switch(t){case"drop-oldest":{for(;e.length>=n&&e.length>0;)e.shift(),o++;e.push(r);break}case"drop-newest":{e.length>=n?o=1:e.push(r);break}case"close":break;default:for(;e.length>=n&&e.length>0;)e.shift(),o++;e.push(r)}return{buffer:e,dropped:o}}var ut=class{id;_state="connecting";_buffer=[];_closeCallbacks=[];_errorCallbacks=[];_emitter=new nr.EventEmitter;_metrics;_options;_response;_request;_writable=!0;_cleanupExecuted=!1;_eventCounter=0;_lastEventId=null;_heartbeatTimer;_backpressureConfig;_disconnectHandlers=null;constructor(t,r={}){if(this.id=`sse-${Kn()}`,this._options={...Yn,...r},this._response=t.response,this._request=t.request,r.backpressure){let o=tr.safeParse(r.backpressure);o.success&&(this._backpressureConfig=o.data,this._options.maxBufferSize=o.data.limits.maxMessages,this._options.bufferStrategy=o.data.strategy)}let n=t.request.header("last-event-id");n&&(this._eventCounter=parseInt(n)||0,this._lastEventId=n),this._metrics={eventsSent:0,eventsDropped:0,bytesWritten:0,bufferHighWatermark:0,lastEventTime:Date.now()};try{let o=Ae(),i={clientIp:this._request.header("x-forwarded-for")||this._request.header("x-real-ip")||this._request.raw.socket?.remoteAddress,userAgent:this._request.header("user-agent")};o.add(this.id,this,i)}catch(o){throw this._state="closed",this._writable=!1,console.error("[SSE] Failed to register connection:",o),o}this._setupDisconnectHandling(),this._response.status(200).header("Content-Type","text/event-stream").header("Cache-Control","no-cache").header("X-Accel-Buffering","no"),(!this._request.raw.httpVersionMajor||this._request.raw.httpVersionMajor<2)&&this._response.header("Connection","keep-alive"),this._options.heartbeatInterval&&this._options.heartbeatInterval>0&&this._setupHeartbeat(this._options.heartbeatInterval),this._state="connected",this._writeRaw(`: SSE connection established
|
|
16
18
|
|
|
17
|
-
`)}_registerConnection(){try{let t=
|
|
19
|
+
`)}_registerConnection(){try{let t=Ae(),r={clientIp:this._request.header("x-forwarded-for")||this._request.header("x-real-ip")||this._request.raw.socket?.remoteAddress,userAgent:this._request.header("user-agent")};t.add(this.id,this,r)}catch(t){throw this._state="closed",this._writable=!1,t}}_setupHeartbeat(t){this._heartbeatTimer=global.setInterval(()=>{this.isWritable&&Date.now()-this._metrics.lastEventTime>t*.9&&this.ping(`heartbeat ${new Date().toISOString()}`)},t),this._heartbeatTimer.unref&&this._heartbeatTimer.unref()}_setupDisconnectHandling(){let t=this._request.raw,r=this._response.raw,n=()=>{this._options.autoClose&&this._state!=="closed"&&this.close()};this._disconnectHandlers={req:{close:n,error:n},res:{close:n,error:n}},t.on("close",this._disconnectHandlers.req.close),t.on("error",this._disconnectHandlers.req.error),r.on("close",this._disconnectHandlers.res.close),r.on("error",this._disconnectHandlers.res.error)}_writeRaw(t){if(!this._writable||this._state==="closed")return!1;try{let r=this._response.raw,n;if("write"in r&&typeof r.write=="function")n=r.write(t);else throw new Error("Response stream does not support write operation");return n&&(this._metrics.bytesWritten+=Buffer.byteLength(t)),n}catch(r){return this._writable=!1,this._handleError(r),!1}}async _flushBuffer(){for(;this._buffer.length>0&&this._writable;){let t=this._buffer.shift();if(!t)break;let r=rr(t.event,t.data,t.id);this._writeRaw(r)?(this._metrics.eventsSent++,this._metrics.lastEventTime=Date.now()):(this._buffer.unshift(t),await this._waitForDrain())}}_waitForDrain(){return new Promise(t=>{this._response.raw.once("drain",t)})}_handleError(t){this._errorCallbacks.forEach(r=>{try{r(t)}catch(n){console.error("Error in error callback:",n)}}),this._writable&&this.sendError(t)}_executeCleanup(){if(this._cleanupExecuted)return;if(this._cleanupExecuted=!0,this._heartbeatTimer&&(global.clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0),this._disconnectHandlers){let r=this._request.raw,n=this._response.raw;r.removeListener("close",this._disconnectHandlers.req.close),r.removeListener("error",this._disconnectHandlers.req.error),n.removeListener("close",this._disconnectHandlers.res.close),n.removeListener("error",this._disconnectHandlers.res.error),this._disconnectHandlers=null}try{Ae().remove(this.id)}catch(r){console.error("Registry cleanup error:",r)}let t=[...this._closeCallbacks];for(let r of t)try{let n=r();n&&typeof n.then=="function"&&n.catch(o=>{console.error("Error in async close callback:",o)})}catch(n){console.error("Error in close callback:",n)}this._closeCallbacks=[],this._errorCallbacks=[],this._buffer=[],this._emitter.removeAllListeners()}get state(){return this._state}get bufferSize(){return this._buffer.length}get isWritable(){return this._writable&&this._state==="connected"}send(t,r){if(!this.isWritable)throw new ze("Cannot send event to closed stream",{clientId:this.id,closedAt:new Date().toISOString(),closeReason:"server-close",canReconnect:!1});let n=String(++this._eventCounter);this._lastEventId=n;let o=g(),i=Xn(t,r),s=this._options.maxEventSize;if(i>s)throw new de("Event size exceeds maximum allowed",{currentSize:i,maxSize:s,strategy:"close",clientId:this.id,eventsDropped:0,triggeringEvent:t});let a={id:n,event:t,data:r,size:i,timestamp:Date.now(),correlationId:o},c=this._backpressureConfig?this._backpressureConfig.watermarks.high:this._options.maxBufferSize;if(this._buffer.length>=c){if(this._options.bufferStrategy==="close"){let p=this._buffer.length;throw this.close(),new de("Buffer overflow - stream closed",{currentSize:p,maxSize:c,strategy:"close",clientId:this.id})}let l=eo(this._buffer,this._options.bufferStrategy,a,c);this._buffer=l.buffer,this._metrics.eventsDropped+=l.dropped,l.dropped>0&&console.warn(`SSE stream ${this.id}: Dropped ${l.dropped} events due to buffer overflow`)}else this._buffer.push(a);this._metrics.bufferHighWatermark=Math.max(this._metrics.bufferHighWatermark,this._buffer.length),this._emitter.emit("event"),this._flushBuffer().catch(l=>{this._handleError(l)})}sendError(t){if(!this.isWritable)return;let r={message:t.message,name:t.name,correlationId:g(),timestamp:new Date().toISOString(),stack:process.env.NODE_ENV==="development"?t.stack:void 0};try{this.send("error",r)}catch(n){console.error("Failed to send error event:",n)}}close(){if(this._state!=="closed"){this._state="closed",this._writable=!1,this._emitter.emit("close");try{let t=rr("close",{reason:"stream-closed",reconnect:!1}),r=this._response.raw;"write"in r&&typeof r.write=="function"&&r.write(t)}catch{}try{let t=this._response.raw;!t.writableEnded&&typeof t.end=="function"&&t.end()}catch(t){console.error("Error ending response:",t)}this._executeCleanup()}}onClose(t){if(this._state==="closed")try{let r=t();r&&typeof r.then=="function"&&r.catch(n=>{console.error("Error in close callback:",n)})}catch(r){console.error("Error in close callback:",r)}else this._closeCallbacks.push(t)}ping(t){if(!this.isWritable)return;let r=t?`: ${t}
|
|
18
20
|
|
|
19
21
|
`:`: ping
|
|
20
22
|
|
|
21
23
|
`;this._writeRaw(r)}setRetry(t){if(this.isWritable){if(t<0||!Number.isFinite(t))throw new Error("Retry interval must be a positive number");this._writeRaw(`retry: ${Math.floor(t)}
|
|
22
24
|
|
|
23
|
-
`)}}flush(){this.isWritable&&this._flushBuffer().catch(t=>{this._handleError(t)})}getMetrics(){return{...this._metrics}}async*[Symbol.asyncIterator](){for(;this.isWritable;){for(;this._buffer.length>0;){let t=this._buffer.shift();t&&(yield t)}await new Promise(t=>{let r=()=>{(this._buffer.length>0||!this.isWritable)&&(this._emitter.off("event",r),this._emitter.off("close",r),t())};this._emitter.on("event",r),this._emitter.on("close",r)})}}};function
|
|
25
|
+
`)}}flush(){this.isWritable&&this._flushBuffer().catch(t=>{this._handleError(t)})}getMetrics(){return{...this._metrics}}async*[Symbol.asyncIterator](){for(;this.isWritable;){for(;this._buffer.length>0;){let t=this._buffer.shift();t&&(yield t)}await new Promise(t=>{let r=()=>{(this._buffer.length>0||!this.isWritable)&&(this._emitter.off("event",r),this._emitter.off("close",r),t())};this._emitter.on("event",r),this._emitter.on("close",r)})}}};function or(e,t){return new ut(e,t)}P();R();var ke=class extends v{constructor(t,r,n){super("SSE_NOT_ACCEPTABLE",t,406,n||g(),r)}};function to(e){if(!e.handler||typeof e.handler!="function")throw new Error("SSE route handler must be a function");if(e.middleware&&!Array.isArray(e.middleware))throw new Error("Middleware for SSE route must be an array");if(e.schema){let{params:t,query:r,events:n}=e.schema;if(t&&(!t._def||typeof t.parse!="function"))throw new Error("Params schema for SSE must be a valid Zod schema");if(r&&(!r._def||typeof r.parse!="function"))throw new Error("Query schema for SSE must be a valid Zod schema");if(n){if(typeof n=="object"&&!n._def){for(let[o,i]of Object.entries(n))if(!i||typeof i!="object"||!i._def||typeof i.parse!="function")throw new Error(`Event schema for '${o}' must be a valid Zod schema`)}else if(!(n._def&&typeof n.parse=="function"))throw new Error("Events schema for SSE must be a valid Zod schema or event map")}}}function ro(e,t){let r=Object.create(e),n=e.send.bind(e);return r.send=function(o,i){let s=t[o];if(s)try{let a=s.parse(i);n(o,a)}catch(a){e.sendError(new Error(`Event '${o}' validation failed: ${a instanceof Error?a.message:String(a)}`))}else n(o,i)},r}var ir=()=>e=>{to(e);let t=$();return{GET:{handler:async(n,o)=>{let i=n.request.header("accept");if(i&&!i.includes("text/event-stream")&&!i.includes("*/*"))throw new ke("This endpoint requires Server-Sent Events support",{acceptHeader:i,requiredHeader:"text/event-stream",endpoint:n.request.path});if(e.schema)try{e.schema.params&&(o=e.schema.params.parse(o)),e.schema.query&&(n.request.query=e.schema.query.parse(n.request.query))}catch(c){throw console.error("[SSE] Validation error:",c),c}let s=or(n,e.options),a=e.schema?.events&&typeof e.schema.events=="object"&&!e.schema.events._def?ro(s,e.schema.events):s;n.request.raw.on("close",()=>a.close());try{await e.handler(a,n,o)}catch(c){throw console.error("[SSE] Handler error - THIS IS THE REAL ERROR:",c),console.error("[SSE] Stack trace:",c instanceof Error?c.stack:"No stack"),a.isWritable&&a.sendError(c instanceof Error?c:new Error(String(c))),a.close(),c}},schema:e.schema?.params||e.schema?.query?{params:e.schema?.params,query:e.schema?.query}:void 0,middleware:e.middleware,options:e.options},path:t}};function no(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(o,i)=>i;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let n=r.getFileName();if(!n)throw new Error("Unable to determine caller file name");return n.startsWith("file://")?(0,sr.fileURLToPath)(n):n}finally{Error.prepareStackTrace=e}}function $(){let e=no(),t=Xt(),r=Le(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var Fe=()=>e=>{K("GET",e);let t=$();return{GET:e,path:t}},De=()=>e=>{K("POST",e);let t=$();return{POST:e,path:t}},Ie=()=>e=>{K("PUT",e);let t=$();return{PUT:e,path:t}},Be=()=>e=>{K("DELETE",e);let t=$();return{DELETE:e,path:t}},Ne=()=>e=>{K("PATCH",e);let t=$();return{PATCH:e,path:t}},He=()=>e=>{K("HEAD",e);let t=$();return{HEAD:e,path:t}},$e=()=>e=>{K("OPTIONS",e);let t=$();return{OPTIONS:e,path:t}};function K(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&oo(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function oo(e,t){let{params:r,query:n,body:o,response:i}=t;if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}function dt(){return{get:Fe(),post:De(),put:Ie(),delete:Be(),patch:Ne(),head:He(),options:$e(),sse:ir()}}function X(e,t,r){let n=t.exec(e);if(!n)return{};let o={};for(let i=0;i<r.length;i++)o[r[i]]=n[i+1]||"";return o}function ne(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(o,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(o,i)=>(t.push(i),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function pe(e){let t=[];for(let[r,n]of Object.entries(e))if(n!=null){let o=encodeURIComponent(r),i=encodeURIComponent(String(n));t.push(`${o}=${i}`)}return t.length>0?`?${t.join("&")}`:""}function qe(e,t={},r={}){let n={},o={...r},i=[];e.replace(/\/:([^/]+)/g,(c,l)=>(i.push(l),"/"));for(let[c,l]of Object.entries(t))i.includes(c)?n[c]=l:o[c]=l;let s=e;for(let[c,l]of Object.entries(n))s=s.replace(`:${c}`,encodeURIComponent(String(l)));let a=pe(o);return s+a}function oe(){let e=[];return{add(t,r,n){let{pattern:o,paramNames:i}=ne(t),s={path:t,method:r,pattern:o,paramNames:i,routeOptions:n},a=e.findIndex(c=>i.length<c.paramNames.length);a===-1?e.push(s):e.splice(a,0,s)},remove(t){for(let r=e.length-1;r>=0;r--)e[r].path===t&&e.splice(r,1)},clear(){e.length=0},match(t,r){let n=t.split("?")[0];if(!n)return null;for(let i of e){if(i.method!==r)continue;if(i.pattern.exec(n)){let a=X(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:a}}}return e.find(i=>i.method!==r&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(r=>r.pattern.test(t)).map(r=>({path:r.path,method:r.method,params:X(t,r.pattern,r.paramNames)}))}}}var rn=require("async_hooks"),nn=O(require("events"),1);var ht=O(require("fs"),1),Or=O(require("http"),1),Lr=O(require("http2"),1);var q=O(require("fs"),1),Ue=O(require("path"),1),ar=O(require("selfsigned"),1);async function cr(){let e=Ue.join(process.cwd(),".blaizejs","certs"),t=Ue.join(e,"dev.key"),r=Ue.join(e,"dev.cert");if(q.existsSync(t)&&q.existsSync(r))return{keyFile:t,certFile:r};q.existsSync(e)||q.mkdirSync(e,{recursive:!0});let i=ar.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return q.writeFileSync(t,Buffer.from(i.private,"utf-8")),q.writeFileSync(r,Buffer.from(i.cert,"utf-8")),console.log(`
|
|
24
26
|
\u{1F512} Generated self-signed certificates for development at ${e}
|
|
25
|
-
`),{keyFile:t,certFile:r}}var
|
|
26
|
-
`))&&(n=n.subarray(2)),{...e,buffer:n,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function
|
|
27
|
+
`),{keyFile:t,certFile:r}}var k=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},fe=class extends k{constructor(t="Cannot set header after response has been sent"){super(t)}},je=class extends k{constructor(t="Cannot set content type after response has been sent"){super(t)}},Ve=class extends k{constructor(t="Invalide URL"){super(t)}};var lr=require("async_hooks"),io=new lr.AsyncLocalStorage;function ur(e,t){return io.run(e,t)}me();ge();D();R();var hr=O(require("crypto"),1),yr=require("fs"),Sr=require("os"),wr=require("path"),mt=require("stream");var so=/boundary=([^;]+)/i,ao=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,co=/Content-Type:\s*([^\r\n]+)/i,lo=/multipart\/form-data/i;function dr(e){let t=e.match(so);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function pr(e){let t=e.match(ao);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function fr(e){let t=e.match(co);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function mr(e){return lo.test(e)}var uo={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:(0,Sr.tmpdir)(),computeHash:!1};function po(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...uo,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function fo(e,t){let r=Buffer.concat([e.buffer,t]),n={...e,buffer:r};for(;n.buffer.length>0&&!n.isFinished;){let o=await mo(n);if(o===n)break;n=o}return n}async function mo(e){switch(e.stage){case"boundary":return go(e);case"headers":return ho(e);case"content":return yo(e);default:{let{InternalServerError:t}=await Promise.resolve().then(()=>(he(),gr));throw new t("Invalid parser stage",{operation:e.stage})}}}function go(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let r=!0,n=e.buffer.subarray(t+e.boundary.length);return n.length>=2&&n.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:n,hasFoundValidBoundary:r,isFinished:!0,stage:"boundary"}:(n.length>=2&&n.subarray(0,2).equals(Buffer.from(`\r
|
|
28
|
+
`))&&(n=n.subarray(2)),{...e,buffer:n,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function ho(e){let t=e.buffer.indexOf(`\r
|
|
27
29
|
\r
|
|
28
|
-
`);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),n=e.buffer.subarray(t+4),o=Kt(r);if(!o){let{ValidationError:a}=await Promise.resolve().then(()=>(k(),Q));throw new a("Missing or invalid Content-Disposition header")}let i=Xt(r),s=o.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(ae(),tt));throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:o.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await Promise.resolve().then(()=>(ce(),rt));throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:o.filename})}return{...e,buffer:n,stage:"content",currentHeaders:r,currentField:o.name,currentFilename:o.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Gn(e){let t=e.buffer.indexOf(e.boundary),r,n=!1,o=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),o=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),o=e.buffer.subarray(t),n=!0}let i={...e,buffer:o};return r.length>0&&(i=await Zn(i,r)),n&&(i=await Kn(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function Zn(e,t){let r=e.currentContentLength+t.length,n=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>n){let o=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(ae(),tt)),s=e.currentField?{contentType:o?"file":"field",currentSize:r,maxSize:n,field:e.currentField,filename:e.currentFilename}:{contentType:o?"file":"field",currentSize:r,maxSize:n,filename:e.currentFilename};throw new i(`${o?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?Jn(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function Jn(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await no(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:n}=await Promise.resolve().then(()=>(k(),Q));throw new n("Invalid parsing strategy")}}}async function Yn(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:n=>{t=n}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=(0,ir.join)(e.options.tempDir,`upload-${rr.randomUUID()}`),r=(0,nr.createWriteStream)(t),n=async()=>{try{let{unlink:o}=await import("fs/promises");await o(t)}catch(o){console.warn(`Failed to cleanup temp file: ${t}`,o)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,n]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(k(),Q));throw new t("Invalid file processing strategy")}}}async function Kn(e){return e.currentField?e.currentFilename!==void 0?Xn(e):eo(e):ue(e)}async function Xn(e){if(!e.currentField||e.currentFilename===void 0)return ue(e);let t,r,n;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=nt.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await ar(e.currentWriteStream),n=e.currentTempPath,t=nt.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(k(),Q));throw new s("Invalid file finalization strategy")}}let o={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:n},i=sr(e.files,e.currentField,o);return{...ue(e),files:i}}function eo(e){if(!e.currentField)return ue(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=sr(e.fields,e.currentField,t);return{...ue(e),fields:r}}function ue(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function sr(e,t,r){let n=new Map(e),o=n.get(t)||[];return n.set(t,[...o,r]),n}async function to(e){if(!e.hasFoundValidBoundary){let{ValidationError:n}=await Promise.resolve().then(()=>(k(),Q));throw new n("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:n}=await Promise.resolve().then(()=>(k(),Q));throw new n("Empty multipart request")}let t={};for(let[n,o]of e.fields.entries())t[n]=o.length===1?o[0]:o;let r={};for(let[n,o]of e.files.entries())r[n]=o.length===1?o[0]:o;return{fields:t,files:r}}async function ro(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await ar(e.currentWriteStream)}async function no(e,t){return new Promise((r,n)=>{e.write(t,o=>{o?n(o):r()})})}async function ar(e){return new Promise(t=>{e.end(()=>t())})}async function cr(e,t={}){let r=e.headers["content-type"]||"",n=Yt(r);if(!n){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(ce(),rt));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let o=qn(n,t);o.currentFilename!==void 0&&(o=await Yn(o));try{for await(let i of e)o=await jn(o,i);return to(o)}finally{await ro(o)}}var de="Content-Type";function oo(e){let t=e.url||"/",r=e.headers.host||"localhost",o=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(o),s=i.pathname,a={};return i.searchParams.forEach((c,l)=>{a[l]!==void 0?Array.isArray(a[l])?a[l].push(c):a[l]=[a[l],c]:a[l]=c}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${o}`,i),new Ne(`Invalid URL: ${o}`)}}function io(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function so(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function lr(e,t,r){let{path:n,url:o,query:i}=oo(e),s=e.method||"GET",a=io(e),c=so(e),l={},p={...r.initialState||{}},h={...r.initialServices||{}},x={sent:!1},T={request:ao(e,{path:n,url:o,query:i,params:l,method:s,isHttp2:a,protocol:c}),response:{},state:p,services:h};return T.response=lo(t,x,T),r.parseBody&&await xo(e,T,r),T}function ao(e,t){return{raw:e,...t,header:ur(e),headers:co(e),body:void 0}}function ur(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function co(e){let t=ur(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((n,o)=>(n[o]=t(o),n),{}):Object.entries(e.headers).reduce((n,[o,i])=>(n[o]=Array.isArray(i)?i.join(", "):i||void 0,n),{})}function pe(e,t){if(t.correlationId){let r=W(),n=String(t.correlationId);e.setHeader(r,n)}}function lo(e,t,r){return{raw:e,get statusCode(){return e.statusCode||200},get sent(){return t.sent},status:uo(e,t,r),header:po(e,t,r),headers:fo(e,t,r),type:mo(e,t,r),json:go(e,t,r.state),text:ho(e,t,r.state),html:yo(e,t,r.state),redirect:So(e,t,r.state),stream:wo(e,t,r.state)}}function uo(e,t,r){return function(o){if(t.sent)throw new F;return e.statusCode=o,r.response}}function po(e,t,r){return function(o,i){if(t.sent)throw new se;return e.setHeader(o,i),r.response}}function fo(e,t,r){return function(o){if(t.sent)throw new se;for(let[i,s]of Object.entries(o))e.setHeader(i,s);return r.response}}function mo(e,t,r){return function(o){if(t.sent)throw new De;return e.setHeader(de,o),r.response}}function go(e,t,r){return function(o,i){if(t.sent)throw new F;i!==void 0&&(e.statusCode=i),pe(e,r),e.setHeader(de,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function ho(e,t,r){return function(o,i){if(t.sent)throw new F;i!==void 0&&(e.statusCode=i),pe(e,r),e.setHeader(de,"text/plain"),e.end(o),t.sent=!0}}function yo(e,t,r){return function(o,i){if(t.sent)throw new F;i!==void 0&&(e.statusCode=i),pe(e,r),e.setHeader(de,"text/html"),e.end(o),t.sent=!0}}function So(e,t,r){return function(o,i=302){if(t.sent)throw new F;pe(e,r),e.statusCode=i,e.setHeader("Location",o),e.end(),t.sent=!0}}function wo(e,t,r){return function(o,i={}){if(t.sent)throw new F;if(i.status!==void 0&&(e.statusCode=i.status),pe(e,r),i.contentType&&e.setHeader(de,i.contentType),i.headers)for(let[s,a]of Object.entries(i.headers))e.setHeader(s,a);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",s=>{console.error("Stream error:",s),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function xo(e,t,r){if(vo(e.method))return;let n=e.headers["content-type"]||"",o=parseInt(e.headers["content-length"]||"0",10);if(o===0)return;let i=r.bodyLimits;if(n.includes("application/json")){if(o>i.json)throw new I("JSON body exceeds size limit",{currentSize:o,maxSize:i.json,contentType:"application/json"},m());await Eo(e,t)}else if(n.includes("application/x-www-form-urlencoded")){if(o>i.form)throw new I("Form body exceeds size limit",{currentSize:o,maxSize:i.form,contentType:"application/x-www-form-urlencoded"},m());await To(e,t)}else if(n.includes("text/")){if(o>i.text)throw new I("Text body exceeds size limit",{currentSize:o,maxSize:i.text,contentType:n},m());await bo(e,t)}else if(er(n))await Co(e,t,i.multipart);else{if(o>i.raw)throw new I("Request body exceeds size limit",{currentSize:o,maxSize:i.raw,contentType:n||"unknown"},m());return}}function vo(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function Eo(e,t){let r=await ot(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let n=JSON.parse(r);t.request.body=n}catch(n){throw new _("Invalid JSON in request body",{fields:[{field:"body",messages:["Request body contains malformed JSON",n instanceof Error?n.message:"JSON parse failed"]}],errorCount:1,section:"body"},m())}}async function To(e,t){let r=await ot(e);if(r)try{t.request.body=Ro(r)}catch(n){throw new _("Request body contains malformed form data",{fields:[{field:"body",messages:["Invalid URL-encoded form data",n instanceof Error?n.message:"Form parse failed"]}],errorCount:1,section:"body"},m())}}function Ro(e){let t=new URLSearchParams(e),r={};return t.forEach((n,o)=>{r[o]!==void 0?Array.isArray(r[o])?r[o].push(n):r[o]=[r[o],n]:r[o]=n}),r}async function bo(e,t){let r=await ot(e);r&&(t.request.body=r)}async function Co(e,t,r){try{let n=r,o=await cr(e,{strategy:"stream",maxFileSize:n.maxFileSize,maxFiles:n.maxFiles,maxFieldSize:n.maxFieldSize});t.request.multipart=o,t.request.files=o.files,t.request.body=o.fields}catch(n){throw n instanceof I||n instanceof L?n:new L("Failed to parse multipart/form-data",{receivedContentType:e.headers["content-type"],expectedFormat:"multipart/form-data; boundary=..."},m())}}async function ot(e){return new Promise((t,r)=>{let n=[];e.on("data",o=>{n.push(Buffer.isBuffer(o)?o:Buffer.from(o))}),e.on("end",()=>{t(Buffer.concat(n).toString("utf8"))}),e.on("error",o=>{r(o)})})}C();b();var U=class extends w{constructor(t,r=void 0,n=void 0){super("NOT_FOUND",t,404,n??m(),r)}};C();le();b();function Po(e){return e instanceof w}function dr(e){if(Po(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=m(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let n=new H("Internal Server Error",{originalMessage:r},t);return{type:n.type,title:n.title,status:n.status,correlationId:n.correlationId,timestamp:n.timestamp.toISOString(),details:n.details}}function pr(e){let t=W(),r={[t]:e(t)};return Se(r)}function fr(e,t){let r=W();e(r,t)}function mr(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(n,o)=>{try{await o()}catch(i){if(n.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=pr(n.request.header),a=dr(i);a.correlationId=s,fr(n.response.header,s),n.response.status(a.status).json(a)}},debug:t}}b();function gr(e){return async(t,r)=>{let n=Se(t.headers);try{await Ct(n,async()=>{let o=await lr(t,r,{parseBody:!0,initialState:{correlationId:n},bodyLimits:e.bodyLimits}),s=[mr()];"corsOptions"in e&&e.corsOptions!==!1&&s.push(ne(e.corsOptions)),s.push(...e.middleware);let a=V(s);await Jt(o,async()=>{await a(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o),!r.headersSent&&!o.response.sent))throw new U(`Route not found: ${o.request.method} ${o.request.path}`)})})})}catch(o){console.error("Error creating context:",o);let i=W();if(r.headersSent||r.stream?.headersSent){console.error("Headers already sent, cannot send error response");return}"stream"in r&&typeof r.stream?.respond=="function"?(r.stream.respond({":status":500,"content-type":"application/json",[i.toLowerCase()]:n}),r.stream.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n}))):(r.setHeader(i,n),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n})))}}}async function _o(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,n=process.env.NODE_ENV==="development",o=!t||!r;if(o&&n)return await Gt();if(o)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function Mo(e,t){if(!e)return hr.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=it.readFileSync(t.keyFile)),t.certFile&&(r.cert=it.readFileSync(t.certFile))}catch(n){throw new Error(`Failed to read certificate files: ${n instanceof Error?n.message:String(n)}`)}return yr.createSecureServer(r)}function Oo(e,t,r,n){return new Promise((o,i)=>{e.listen(t,r,()=>{let a=`${n?"https":"http"}://${r}:${t}`;console.log(`
|
|
30
|
+
`);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),n=e.buffer.subarray(t+4),o=pr(r);if(!o){let{ValidationError:a}=await Promise.resolve().then(()=>(D(),Y));throw new a("Missing or invalid Content-Disposition header")}let i=fr(r),s=o.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(me(),pt));throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:o.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await Promise.resolve().then(()=>(ge(),ft));throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:o.filename})}return{...e,buffer:n,stage:"content",currentHeaders:r,currentField:o.name,currentFilename:o.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function yo(e){let t=e.buffer.indexOf(e.boundary),r,n=!1,o=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),o=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),o=e.buffer.subarray(t),n=!0}let i={...e,buffer:o};return r.length>0&&(i=await So(i,r)),n&&(i=await xo(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function So(e,t){let r=e.currentContentLength+t.length,n=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>n){let o=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(me(),pt)),s=e.currentField?{contentType:o?"file":"field",currentSize:r,maxSize:n,field:e.currentField,filename:e.currentFilename}:{contentType:o?"file":"field",currentSize:r,maxSize:n,filename:e.currentFilename};throw new i(`${o?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?wo(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function wo(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await Co(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:n}=await Promise.resolve().then(()=>(D(),Y));throw new n("Invalid parsing strategy")}}}async function vo(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:n=>{t=n}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=(0,wr.join)(e.options.tempDir,`upload-${hr.randomUUID()}`),r=(0,yr.createWriteStream)(t),n=async()=>{try{let{unlink:o}=await import("fs/promises");await o(t)}catch(o){console.warn(`Failed to cleanup temp file: ${t}`,o)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,n]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(D(),Y));throw new t("Invalid file processing strategy")}}}async function xo(e){return e.currentField?e.currentFilename!==void 0?Eo(e):To(e):ye(e)}async function Eo(e){if(!e.currentField||e.currentFilename===void 0)return ye(e);let t,r,n;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=mt.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await xr(e.currentWriteStream),n=e.currentTempPath,t=mt.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(D(),Y));throw new s("Invalid file finalization strategy")}}let o={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:n},i=vr(e.files,e.currentField,o);return{...ye(e),files:i}}function To(e){if(!e.currentField)return ye(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=vr(e.fields,e.currentField,t);return{...ye(e),fields:r}}function ye(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function vr(e,t,r){let n=new Map(e),o=n.get(t)||[];return n.set(t,[...o,r]),n}async function bo(e){if(!e.hasFoundValidBoundary){let{ValidationError:n}=await Promise.resolve().then(()=>(D(),Y));throw new n("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:n}=await Promise.resolve().then(()=>(D(),Y));throw new n("Empty multipart request")}let t={};for(let[n,o]of e.fields.entries())t[n]=o.length===1?o[0]:o;let r={};for(let[n,o]of e.files.entries())r[n]=o.length===1?o[0]:o;return{fields:t,files:r}}async function Ro(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await xr(e.currentWriteStream)}async function Co(e,t){return new Promise((r,n)=>{e.write(t,o=>{o?n(o):r()})})}async function xr(e){return new Promise(t=>{e.end(()=>t())})}async function Er(e,t={}){let r=e.headers["content-type"]||"",n=dr(r);if(!n){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(ge(),ft));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let o=po(n,t);o.currentFilename!==void 0&&(o=await vo(o));try{for await(let i of e)o=await fo(o,i);return bo(o)}finally{await Ro(o)}}var Se="Content-Type";function Po(e){let t=e.url||"/",r=e.headers.host||"localhost",o=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(o),s=i.pathname,a={};return i.searchParams.forEach((c,l)=>{a[l]!==void 0?Array.isArray(a[l])?a[l].push(c):a[l]=[a[l],c]:a[l]=c}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${o}`,i),new Ve(`Invalid URL: ${o}`)}}function Mo(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function _o(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function Tr(e,t,r){let{path:n,url:o,query:i}=Po(e),s=e.method||"GET",a=Mo(e),c=_o(e),l={},p={...r.initialState||{}},y={...r.initialServices||{}},x={sent:!1},T={request:Oo(e,{path:n,url:o,query:i,params:l,method:s,isHttp2:a,protocol:c}),response:{},state:p,services:y};return T.response=Ao(t,x,T),r.parseBody&&await qo(e,T,r),T}function Oo(e,t){return{raw:e,...t,header:br(e),headers:Lo(e),body:void 0}}function br(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function Lo(e){let t=br(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((n,o)=>(n[o]=t(o),n),{}):Object.entries(e.headers).reduce((n,[o,i])=>(n[o]=Array.isArray(i)?i.join(", "):i||void 0,n),{})}function we(e,t){if(t.correlationId){let r=J(),n=String(t.correlationId);e.setHeader(r,n)}}function Ao(e,t,r){return{raw:e,get statusCode(){return e.statusCode||200},get sent(){return t.sent},status:zo(e,t,r),header:ko(e,t,r),headers:Fo(e,t,r),type:Do(e,t,r),json:Io(e,t,r.state),text:Bo(e,t,r.state),html:No(e,t,r.state),redirect:Ho(e,t,r.state),stream:$o(e,t,r.state)}}function zo(e,t,r){return function(o){if(t.sent)throw new k;return e.statusCode=o,r.response}}function ko(e,t,r){return function(o,i){if(t.sent)throw new fe;return e.setHeader(o,i),r.response}}function Fo(e,t,r){return function(o){if(t.sent)throw new fe;for(let[i,s]of Object.entries(o))e.setHeader(i,s);return r.response}}function Do(e,t,r){return function(o){if(t.sent)throw new je;return e.setHeader(Se,o),r.response}}function Io(e,t,r){return function(o,i){if(t.sent)throw new k;i!==void 0&&(e.statusCode=i),we(e,r),e.setHeader(Se,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function Bo(e,t,r){return function(o,i){if(t.sent)throw new k;i!==void 0&&(e.statusCode=i),we(e,r),e.setHeader(Se,"text/plain"),e.end(o),t.sent=!0}}function No(e,t,r){return function(o,i){if(t.sent)throw new k;i!==void 0&&(e.statusCode=i),we(e,r),e.setHeader(Se,"text/html"),e.end(o),t.sent=!0}}function Ho(e,t,r){return function(o,i=302){if(t.sent)throw new k;we(e,r),e.statusCode=i,e.setHeader("Location",o),e.end(),t.sent=!0}}function $o(e,t,r){return function(o,i={}){if(t.sent)throw new k;if(i.status!==void 0&&(e.statusCode=i.status),we(e,r),i.contentType&&e.setHeader(Se,i.contentType),i.headers)for(let[s,a]of Object.entries(i.headers))e.setHeader(s,a);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",s=>{console.error("Stream error:",s),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function qo(e,t,r){if(Uo(e.method))return;let n=e.headers["content-type"]||"",o=parseInt(e.headers["content-length"]||"0",10);if(o===0)return;let i=r.bodyLimits;if(n.includes("application/json")){if(o>i.json)throw new I("JSON body exceeds size limit",{currentSize:o,maxSize:i.json,contentType:"application/json"},g());await jo(e,t)}else if(n.includes("application/x-www-form-urlencoded")){if(o>i.form)throw new I("Form body exceeds size limit",{currentSize:o,maxSize:i.form,contentType:"application/x-www-form-urlencoded"},g());await Vo(e,t)}else if(n.includes("text/")){if(o>i.text)throw new I("Text body exceeds size limit",{currentSize:o,maxSize:i.text,contentType:n},g());await Qo(e,t)}else if(mr(n))await Go(e,t,i.multipart);else{if(o>i.raw)throw new I("Request body exceeds size limit",{currentSize:o,maxSize:i.raw,contentType:n||"unknown"},g());return}}function Uo(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function jo(e,t){let r=await gt(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let n=JSON.parse(r);t.request.body=n}catch(n){throw new _("Invalid JSON in request body",{fields:[{field:"body",messages:["Request body contains malformed JSON",n instanceof Error?n.message:"JSON parse failed"]}],errorCount:1,section:"body"},g())}}async function Vo(e,t){let r=await gt(e);if(r)try{t.request.body=Wo(r)}catch(n){throw new _("Request body contains malformed form data",{fields:[{field:"body",messages:["Invalid URL-encoded form data",n instanceof Error?n.message:"Form parse failed"]}],errorCount:1,section:"body"},g())}}function Wo(e){let t=new URLSearchParams(e),r={};return t.forEach((n,o)=>{r[o]!==void 0?Array.isArray(r[o])?r[o].push(n):r[o]=[r[o],n]:r[o]=n}),r}async function Qo(e,t){let r=await gt(e);r&&(t.request.body=r)}async function Go(e,t,r){try{let n=r,o=await Er(e,{strategy:"stream",maxFileSize:n.maxFileSize,maxFiles:n.maxFiles,maxFieldSize:n.maxFieldSize});t.request.multipart=o,t.request.files=o.files,t.request.body=o.fields}catch(n){throw n instanceof I||n instanceof j?n:new j("Failed to parse multipart/form-data",{receivedContentType:e.headers["content-type"],expectedFormat:"multipart/form-data; boundary=..."},g())}}async function gt(e){return new Promise((t,r)=>{let n=[];e.on("data",o=>{n.push(Buffer.isBuffer(o)?o:Buffer.from(o))}),e.on("end",()=>{t(Buffer.concat(n).toString("utf8"))}),e.on("error",o=>{r(o)})})}P();R();var V=class extends v{constructor(t,r=void 0,n=void 0){super("NOT_FOUND",t,404,n??g(),r)}};P();he();R();function Zo(e){return e instanceof v}function Rr(e){if(Zo(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=g(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let n=new U("Internal Server Error",{originalMessage:r},t);return{type:n.type,title:n.title,status:n.status,correlationId:n.correlationId,timestamp:n.timestamp.toISOString(),details:n.details}}function Cr(e){let t=J(),r={[t]:e(t)};return Ce(r)}function Pr(e,t){let r=J();e(r,t)}function Mr(e={}){let{debug:t=!1}=e;return A({name:"ErrorBoundary",debug:t,handler:async(r,n,o)=>{try{await n()}catch(i){if(r.response.sent){t&&o.error("Error occurred after response was sent:",{error:i});return}t&&o.error("Error boundary caught error:",{error:i});let s=Cr(r.request.header),a=Rr(i);a.correlationId=s,Pr(r.response.header,s),r.response.status(a.status).json(a)}}})}R();function _r(e){return async(t,r)=>{let n=Ce(t.headers);try{await Ht(n,async()=>{let o=await Tr(t,r,{parseBody:!0,initialState:{correlationId:n},bodyLimits:e.bodyLimits}),i=e._logger.child({correlationId:n,method:o.request.method,path:o.request.path}),a=[Mr()];"corsOptions"in e&&e.corsOptions!==!1&&a.push(ue(e.corsOptions)),a.push(...e.middleware);let c=Z(a);await ur(o,async()=>{await c(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o,i),!r.headersSent&&!o.response.sent))throw new V(`Route not found: ${o.request.method} ${o.request.path}`)},i)})})}catch(o){e._logger.error("Unhandled request error",{error:o,correlationId:n});let i=J();if(r.headersSent||r.stream?.headersSent){e._logger.error("Headers already sent, cannot send error response");return}"stream"in r&&typeof r.stream?.respond=="function"?(r.stream.respond({":status":500,"content-type":"application/json",[i.toLowerCase()]:n}),r.stream.end(JSON.stringify({error:"Internal Server Error",message:"An unexpected error occurred while processing the request",correlationId:n}))):(r.setHeader(i,n),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"An unexpected error occurred while processing the request",correlationId:n})))}}}async function Jo(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,n=process.env.NODE_ENV==="development",o=!t||!r;if(o&&n)return await cr();if(o)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function Yo(e,t){if(!e)return Or.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=ht.readFileSync(t.keyFile)),t.certFile&&(r.cert=ht.readFileSync(t.certFile))}catch(n){throw new Error(`Failed to read certificate files: ${n instanceof Error?n.message:String(n)}`)}return Lr.createSecureServer(r)}function Ko(e,t,r,n){return new Promise((o,i)=>{e.listen(t,r,()=>{let a=`${n?"https":"http"}://${r}:${t}`;C.info(`
|
|
29
31
|
\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
|
|
30
32
|
|
|
31
33
|
\u26A1 BlaizeJS DEVELOPMENT SERVER HOT AND READY \u26A1
|
|
@@ -37,8 +39,8 @@ ${r}`)}throw new Error(`Invalid CORS options: ${String(t)}`)}}function vn(e){ret
|
|
|
37
39
|
Time to build something amazing! \u{1F680}
|
|
38
40
|
|
|
39
41
|
\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
|
|
40
|
-
`),o()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function Ao(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function Sr(e,t){if(!e.server)try{let r=t.port,n=t.host;await Ao(e);let o=t.http2||{enabled:!0},i=!!o.enabled,s=await _o(o);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=Mo(i,s);e.server=a,e.port=r,e.host=n;let c=gr(e);a.on("request",c),await Oo(a,r,n,i)}catch(r){throw console.error("Failed to start server:",r),r}}var Be=!1;async function wr(e,t={}){let r=e.server,n=e.events;if(Be){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;Be=!0;let o=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),n.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,c)=>setTimeout(()=>c(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,c)=>setTimeout(()=>c(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let i=new Promise((a,c)=>{r.close(l=>{if(l)return c(l);a()})}),s=new Promise((a,c)=>{setTimeout(()=>{c(new Error("Server shutdown timeout"))},o)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,c)=>setTimeout(()=>c(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),n.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),Be=!1}catch(i){throw Be=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),n.emit("error",i),i}}function xr(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},n=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},n=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}}var E=require("zod");var Fo=E.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),ko=E.z.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),Io=E.z.object({enabled:E.z.boolean().optional().default(!0),keyFile:E.z.string().optional(),certFile:E.z.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),zo=E.z.object({headerName:E.z.string().regex(/^[a-z][a-z0-9-]*$/,{message:"Header name must start with a letter and contain only lowercase letters, numbers, and hyphens"}).optional(),generator:E.z.function().args().returns(E.z.string()).optional()}).optional(),Do=E.z.object({maxFileSize:E.z.number().positive().default(50*1024*1024),maxTotalSize:E.z.number().positive().default(100*1024*1024),maxFiles:E.z.number().positive().int().default(10),maxFieldSize:E.z.number().positive().default(1024*1024)}),No=E.z.object({json:E.z.number().positive().default(512*1024),form:E.z.number().positive().default(1024*1024),text:E.z.number().positive().default(5*1024*1024),raw:E.z.number().positive().default(10*1024*1024),multipart:Do}),Bo=E.z.object({port:E.z.number().int().positive().optional().default(3e3),host:E.z.string().optional().default("localhost"),routesDir:E.z.string().optional().default("./routes"),http2:Io.optional().default({enabled:!0}),middleware:E.z.array(Fo).optional().default([]),plugins:E.z.array(ko).optional().default([]),correlation:zo,cors:It,bodyLimits:No});function vr(e){try{return Bo.parse(e)}catch(t){if(t instanceof E.z.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function Er(e={}){let{continueOnError:t=!0,debug:r=!1,onError:n}=e;function o(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function i(s,a,c){let l=`Plugin ${s.name} failed during ${a}: ${c.message}`;if(n?n(s,a,c):console.error(l,c),!t)throw new Error(l)}return{async initializePlugins(s){o("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{o(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(c){i(a,"initialize",c)}o(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){o("Terminating plugins...");let a=[...s.plugins].reverse();for(let c of a)if(c.terminate)try{o(`Terminating plugin: ${c.name}`),await c.terminate(s)}catch(l){i(c,"terminate",l)}o(`Terminated ${a.length} plugins`)},async onServerStart(s,a){o("Notifying plugins of server start...");for(let c of s.plugins)if(c.onServerStart)try{o(`Notifying plugin of server start: ${c.name}`),await c.onServerStart(a)}catch(l){i(c,"onServerStart",l)}},async onServerStop(s,a){o("Notifying plugins of server stop...");let c=[...s.plugins].reverse();for(let l of c)if(l.onServerStop)try{o(`Notifying plugin of server stop: ${l.name}`),await l.onServerStop(a)}catch(p){i(l,"onServerStop",p)}}}}var z=class extends Error{constructor(r,n){super(`Plugin validation error${r?` for "${r}"`:""}: ${n}`);this.pluginName=r;this.name="PluginValidationError"}};var Ho=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),$o=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,Lo=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function st(e,t={}){let{requireVersion:r=!0,validateNameFormat:n=!0,checkReservedNames:o=!0}=t;if(!e||typeof e!="object")throw new z("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new z("","Plugin must have a name (string)");if(n&&!$o.test(i.name))throw new z(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(o&&Ho.has(i.name.toLowerCase()))throw new z(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new z(i.name,"Plugin must have a version (string)");if(!Lo.test(i.version))throw new z(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new z(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(i[a]&&typeof i[a]!="function")throw new z(i.name,`Plugin ${a} must be a function if provided`)}var Rr=M(require("crypto"),1),br=M(require("fs/promises"),1);async function Uo(e){let t=`?t=${Date.now()}`,r=e+t;try{let n=await import(r);return console.log("\u2705 Successfully imported module"),n}catch(n){let o=n instanceof Error?n.message:String(n);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",o),import(e)}}async function Tr(e,t){try{let r=Te(e,t),n=await Uo(e);console.log("\u{1F4E6} Module exports:",Object.keys(n));let o=[];if(n.default&&typeof n.default=="object"){let i={...n.default,path:r.routePath};o.push(i)}return Object.entries(n).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(qo(a)){let c={...a,path:r.routePath};o.push(c)}}),o.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${o.length} route(s)`),o)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function qo(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(n=>e[n]&&typeof e[n]=="object"&&e[n].handler)}var fe=new Map;async function me(e,t,r=!0){let o=(await br.stat(e)).mtime.getTime(),i=fe.get(e);if(r&&i&&i.timestamp===o)return i.routes;let s=await Tr(e,t);if(r){let a=Pr(s);fe.set(e,{routes:s,timestamp:o,hash:a})}return s}function Cr(e,t){let r=fe.get(e);if(!r)return!0;let n=Pr(t);return r.hash!==n}function at(e){e?fe.delete(e):fe.clear()}function Pr(e){let t=e.map(o=>({path:o.path,methods:Object.keys(o).filter(i=>i!=="path").sort().map(i=>{let s=o[i],a=s?.handler?s.handler.toString():null;return{method:i,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return Rr.createHash("md5").update(r).digest("hex")}var Mr=M(require("os"),1);var He=M(require("fs/promises"),1),ee=M(require("path"),1);async function _r(e,t={}){let r=ee.isAbsolute(e)?e:ee.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await He.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let n=[],o=t.ignore||["node_modules",".git"];async function i(s){let a=await He.readdir(s,{withFileTypes:!0});for(let c of a){let l=ee.join(s,c.name);c.isDirectory()&&o.includes(c.name)||(c.isDirectory()?await i(l):jo(c.name)&&n.push(l))}}return await i(r),n}function jo(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function Vo(e,t,r=Math.max(1,Math.floor(Mr.cpus().length/2))){let n=Wo(e,r),o=[];for(let i of n){let a=(await Promise.allSettled(i.map(c=>t(c)))).filter(c=>c.status==="fulfilled").map(c=>c.value);o.push(...a)}return o}async function Or(e){let t=await _r(e);return(await Vo(t,n=>me(n,e))).flat()}function Wo(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var q={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Ar(e,t){let r=Date.now()-t;if(q.fileChanges++,q.totalReloadTime+=r,q.averageReloadTime=q.totalReloadTime/q.fileChanges,r>100&&(q.slowReloads.push({file:e,time:r}),q.slowReloads.length>10&&q.slowReloads.shift()),process.env.NODE_ENV==="development"){let n=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${n} Route reload: ${e} (${r}ms)`)}}function ct(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let n=Date.now();try{let o=await e(...r);return Ar(t,n),o}catch(o){throw Ar(t,n),o}}}var lt=M(require("path"),1),Fr=require("chokidar");function ut(e,t={}){let r=t.debounceMs||16,n=new Map;function o(p,h){return(...x)=>{let T=n.get(h);T&&clearTimeout(T);let u=setTimeout(()=>{p(...x),n.delete(h)},r);n.set(h,u)}}let i=new Map;async function s(p){try{let h=i.get(p),x=await me(p,e,!1);if(!x||x.length===0||h&&!Cr(p,x))return;await me(p,e,!0);let T=lt.normalize(p);h?(i.set(p,x),t.onRouteChanged&&t.onRouteChanged(T,x)):(i.set(p,x),t.onRouteAdded&&t.onRouteAdded(T,x))}catch(h){console.log(`\u26A0\uFE0F Error processing file ${p}:`,h),c(h)}}function a(p){let h=lt.normalize(p),x=i.get(h);x&&x.length>0&&t.onRouteRemoved&&t.onRouteRemoved(h,x),i.delete(h)}function c(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let l=(0,Fr.watch)(e,{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return l.on("add",p=>{o(s,p)(p)}).on("change",p=>{o(s,p)(p)}).on("unlink",p=>{o(a,p)(p)}).on("error",c),{close:()=>(n.forEach(p=>clearTimeout(p)),n.clear(),l.close()),getRoutes:()=>{let p=[];for(let h of i.values())p.push(...h);return p},getRoutesByFile:()=>new Map(i)}}var Nr=require("zod");var kr=require("zod");function dt(e,t){return t instanceof kr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Ir=require("zod");function pt(e,t){return t instanceof Ir.z.ZodObject?t.strict().parse(e):t.parse(e)}var zr=require("zod");function ft(e,t){return t instanceof zr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Dr=require("zod");function mt(e,t){return t instanceof Dr.z.ZodObject?t.strict().parse(e):t.parse(e)}le();k();function gt(e,t=!1){return{name:"RequestValidator",execute:async(n,o)=>{if(e.params&&n.request.params)try{n.request.params=pt(n.request.params,e.params)}catch(i){let s=$e(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new _("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&n.request.query)try{n.request.query=ft(n.request.query,e.query)}catch(i){let s=$e(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new _("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{n.request.body=dt(n.request.body,e.body)}catch(i){let s=$e(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new _("Request validation failed",{fields:s,errorCount:a,section:"body"})}await o()},debug:t}}function Qo(e){return e!==null&&typeof e=="object"&&"type"in e&&"status"in e&&"correlationId"in e&&"timestamp"in e}function ht(e,t=!1){return{name:"ResponseValidator",execute:async(n,o)=>{let i=n.response.json,s=!0;n.response.json=(a,c)=>{if(!s||Qo(a))return i.call(n.response,a,c);try{let l=mt(a,e);return i.call(n.response,l,c)}catch(l){throw s=!1,new H("Response validation failed",{validationError:$e(l),hint:"The handler returned data that does not match the response schema"})}};try{await o()}catch(a){throw s=!1,n.response.json=i,a}finally{n.response.json=i}},debug:t}}function $e(e){if(e instanceof Nr.z.ZodError){let t=new Map;for(let r of e.issues){let n=r.path.length>0?r.path.join("."):"root";t.has(n)||t.set(n,[]),t.get(n).push(r.message)}return Array.from(t.entries()).map(([r,n])=>({field:r,messages:n}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function yt(e,t,r){let n=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&n.unshift(gt(t.schema)),t.schema.response&&n.push(ht(t.schema.response))),await V([...n])(e,async()=>{let i=await t.handler(e,r);!e.response.sent&&i!==void 0&&e.response.json(i)})}function Br(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function j(e,t,r){console.log(`Updating routes from file: ${t}`);let n=e.routesByFile.get(t)||new Set,o=new Set(r.map(l=>l.path)),i=r.filter(l=>!n.has(l.path)),s=Array.from(n).filter(l=>!o.has(l)),c=r.filter(l=>n.has(l.path)).filter(l=>{let p=e.routesByPath.get(l.path);return!p||!Zo(p,l)});return Go(e,t,{added:i,removed:s,changed:c}),{added:i,removed:s,changed:c}}function Hr(e){return Array.from(e.routesByPath.values())}function Go(e,t,r){let{added:n,removed:o,changed:i}=r;o.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...n,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...n.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!o.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Zo(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(o=>o!=="path").sort(),n=Object.keys(t).filter(o=>o!=="path").sort();return r.length!==n.length?!1:r.every(o=>{let i=e[o],s=t[o];return typeof i==typeof s})}function St(e,t){Object.entries(e).forEach(([r,n])=>{r==="path"||!n||t.add(e.path,r,n)})}function ge(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function $r(e,t){ge(e.path,t),St(e,t)}var Jo={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function Lr(e){let t={...Jo,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=Br(),n=X(),o=!1,i=null,s=null,a=new Set([t.routesDir]);function c(u){console.log(`
|
|
41
|
-
\u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${u.added.length} routes`),console.log(` Removing ${u.removed.length} routes`),console.log(` Updating ${u.changed.length} routes`),u.removed.forEach(
|
|
42
|
-
`)}function l(u,
|
|
43
|
-
\u{1F4E5} Handling request: ${
|
|
42
|
+
`),o()}),e.on("error",s=>{C.error("Server error:",{error:s,host:r,port:t}),i(s)})})}async function Xo(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function Ar(e,t){if(!e.server)try{let r=t.port,n=t.host;await Xo(e);let o=t.http2||{enabled:!0},i=!!o.enabled,s=await Jo(o);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=Yo(i,s);e.server=a,e.port=r,e.host=n;let c=_r(e);a.on("request",c),await Ko(a,r,n,i)}catch(r){throw C.error("Failed to start server:",{error:r}),r}}var We=!1;async function zr(e,t={}){let r=e.server,n=e.events;if(We){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;We=!0;let o=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),n.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,c)=>setTimeout(()=>c(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,c)=>setTimeout(()=>c(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let i=new Promise((a,c)=>{r.close(l=>{if(l)return c(l);a()})}),s=new Promise((a,c)=>{setTimeout(()=>{c(new Error("Server shutdown timeout"))},o)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,c)=>setTimeout(()=>c(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),n.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),We=!1}catch(i){throw We=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),n.emit("error",i),i}}function kr(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},n=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},n=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}}var S=require("zod");var ei=S.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),ti=S.z.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),ri=S.z.object({enabled:S.z.boolean().optional().default(!0),keyFile:S.z.string().optional(),certFile:S.z.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),ni=S.z.object({headerName:S.z.string().regex(/^[a-z][a-z0-9-]*$/,{message:"Header name must start with a letter and contain only lowercase letters, numbers, and hyphens"}).optional(),generator:S.z.function().args().returns(S.z.string()).optional()}).optional(),oi=S.z.object({maxFileSize:S.z.number().positive().default(50*1024*1024),maxTotalSize:S.z.number().positive().default(100*1024*1024),maxFiles:S.z.number().positive().int().default(10),maxFieldSize:S.z.number().positive().default(1024*1024)}),ii=S.z.object({json:S.z.number().positive().default(512*1024),form:S.z.number().positive().default(1024*1024),text:S.z.number().positive().default(5*1024*1024),raw:S.z.number().positive().default(10*1024*1024),multipart:oi}),si=S.z.object({includeHeaders:S.z.boolean().optional(),headerWhitelist:S.z.array(S.z.string().min(1)).optional(),includeQuery:S.z.boolean().optional()}).optional(),ai=S.z.object({level:S.z.enum(["debug","info","warn","error"]).optional(),transport:S.z.any().optional(),redactKeys:S.z.array(S.z.string().min(1)).optional(),includeTimestamp:S.z.boolean().optional(),requestLogging:S.z.boolean().optional(),requestLoggerOptions:si}).optional(),ci=S.z.object({port:S.z.number().int().positive().optional().default(3e3),host:S.z.string().optional().default("localhost"),routesDir:S.z.string().optional().default("./routes"),http2:ri.optional().default({enabled:!0}),middleware:S.z.array(ei).optional().default([]),plugins:S.z.array(ti).optional().default([]),correlation:ni,cors:Gt,bodyLimits:ii,logging:ai});function Fr(e){try{return ci.parse(e)}catch(t){if(t instanceof S.z.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function Dr(e={}){let{continueOnError:t=!0,onError:r}=e;function n(o,i,s){let a=`Plugin ${o.name} failed during ${i}: ${s.message}`;if(r?r(o,i,s):C.error(`[PluginLifecycle] ${a}`,{plugin:o.name,phase:i,error:{message:s.message,stack:s.stack,name:s.name}}),!t)throw new Error(a)}return{async initializePlugins(o){C.debug("[PluginLifecycle] Initializing plugins",{count:o.plugins.length});for(let i of o.plugins)if(i.initialize)try{C.debug("[PluginLifecycle] Initializing plugin",{plugin:i.name}),await i.initialize(o)}catch(s){n(i,"initialize",s)}C.info("[PluginLifecycle] Plugins initialized",{count:o.plugins.length,plugins:o.plugins.map(i=>i.name)})},async terminatePlugins(o){C.debug("[PluginLifecycle] Terminating plugins",{count:o.plugins.length});let i=[...o.plugins].reverse();for(let s of i)if(s.terminate)try{C.debug("[PluginLifecycle] Terminating plugin",{plugin:s.name}),await s.terminate(o)}catch(a){n(s,"terminate",a)}C.info("[PluginLifecycle] Plugins terminated",{count:i.length})},async onServerStart(o,i){C.debug("[PluginLifecycle] Notifying plugins of server start");for(let s of o.plugins)if(s.onServerStart)try{C.debug("[PluginLifecycle] Notifying plugin of server start",{plugin:s.name}),await s.onServerStart(i)}catch(a){n(s,"onServerStart",a)}},async onServerStop(o,i){C.debug("[PluginLifecycle] Notifying plugins of server stop...");let s=[...o.plugins].reverse();for(let a of s)if(a.onServerStop)try{C.debug(`[PluginLifecycle] Notifying plugin of server stop: ${a.name}`),await a.onServerStop(i)}catch(c){n(a,"onServerStop",c)}}}}var B=class extends Error{constructor(r,n){super(`Plugin validation error${r?` for "${r}"`:""}: ${n}`);this.pluginName=r;this.name="PluginValidationError"}};var li=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),ui=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,di=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function yt(e,t={}){let{requireVersion:r=!0,validateNameFormat:n=!0,checkReservedNames:o=!0}=t;if(!e||typeof e!="object")throw new B("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new B("","Plugin must have a name (string)");if(n&&!ui.test(i.name))throw new B(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(o&&li.has(i.name.toLowerCase()))throw new B(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new B(i.name,"Plugin must have a version (string)");if(!di.test(i.version))throw new B(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new B(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(i[a]&&typeof i[a]!="function")throw new B(i.name,`Plugin ${a} must be a function if provided`)}var Br=O(require("crypto"),1),Nr=O(require("fs/promises"),1);async function pi(e){let t=`?t=${Date.now()}`,r=e+t;try{let n=await import(r);return console.log("\u2705 Successfully imported module"),n}catch(n){let o=n instanceof Error?n.message:String(n);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",o),import(e)}}async function Ir(e,t){try{let r=Le(e,t),n=await pi(e);console.log("\u{1F4E6} Module exports:",Object.keys(n));let o=[];if(n.default&&typeof n.default=="object"){let i={...n.default,path:r.routePath};o.push(i)}return Object.entries(n).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(fi(a)){let c={...a,path:r.routePath};o.push(c)}}),o.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${o.length} route(s)`),o)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function fi(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(n=>e[n]&&typeof e[n]=="object"&&e[n].handler)}var ve=new Map;async function xe(e,t,r=!0){let o=(await Nr.stat(e)).mtime.getTime(),i=ve.get(e);if(r&&i&&i.timestamp===o)return i.routes;let s=await Ir(e,t);if(r){let a=$r(s);ve.set(e,{routes:s,timestamp:o,hash:a})}return s}function Hr(e,t){let r=ve.get(e);if(!r)return!0;let n=$r(t);return r.hash!==n}function St(e){e?ve.delete(e):ve.clear()}function $r(e){let t=e.map(o=>({path:o.path,methods:Object.keys(o).filter(i=>i!=="path").sort().map(i=>{let s=o[i],a=s?.handler?s.handler.toString():null;return{method:i,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return Br.createHash("md5").update(r).digest("hex")}var Ur=O(require("os"),1);var Qe=O(require("fs/promises"),1),ie=O(require("path"),1);async function qr(e,t={}){let r=ie.isAbsolute(e)?e:ie.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await Qe.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let n=[],o=t.ignore||["node_modules",".git"];async function i(s){let a=await Qe.readdir(s,{withFileTypes:!0});for(let c of a){let l=ie.join(s,c.name);c.isDirectory()&&o.includes(c.name)||(c.isDirectory()?await i(l):mi(c.name)&&n.push(l))}}return await i(r),n}function mi(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function gi(e,t,r=Math.max(1,Math.floor(Ur.cpus().length/2))){let n=hi(e,r),o=[];for(let i of n){let a=(await Promise.allSettled(i.map(c=>t(c)))).filter(c=>c.status==="fulfilled").map(c=>c.value);o.push(...a)}return o}async function jr(e){let t=await qr(e);return(await gi(t,n=>xe(n,e))).flat()}function hi(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var W={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Vr(e,t){let r=Date.now()-t;if(W.fileChanges++,W.totalReloadTime+=r,W.averageReloadTime=W.totalReloadTime/W.fileChanges,r>100&&(W.slowReloads.push({file:e,time:r}),W.slowReloads.length>10&&W.slowReloads.shift()),process.env.NODE_ENV==="development"){let n=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${n} Route reload: ${e} (${r}ms)`)}}function wt(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let n=Date.now();try{let o=await e(...r);return Vr(t,n),o}catch(o){throw Vr(t,n),o}}}var vt=O(require("path"),1),Wr=require("chokidar");function xt(e,t={}){let r=t.debounceMs||16,n=new Map;function o(p,y){return(...x)=>{let T=n.get(y);T&&clearTimeout(T);let u=setTimeout(()=>{p(...x),n.delete(y)},r);n.set(y,u)}}let i=new Map;async function s(p){try{let y=i.get(p),x=await xe(p,e,!1);if(!x||x.length===0||y&&!Hr(p,x))return;await xe(p,e,!0);let T=vt.normalize(p);y?(i.set(p,x),t.onRouteChanged&&t.onRouteChanged(T,x)):(i.set(p,x),t.onRouteAdded&&t.onRouteAdded(T,x))}catch(y){console.log(`\u26A0\uFE0F Error processing file ${p}:`,y),c(y)}}function a(p){let y=vt.normalize(p),x=i.get(y);x&&x.length>0&&t.onRouteRemoved&&t.onRouteRemoved(y,x),i.delete(y)}function c(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let l=(0,Wr.watch)(e,{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return l.on("add",p=>{o(s,p)(p)}).on("change",p=>{o(s,p)(p)}).on("unlink",p=>{o(a,p)(p)}).on("error",c),{close:()=>(n.forEach(p=>clearTimeout(p)),n.clear(),l.close()),getRoutes:()=>{let p=[];for(let y of i.values())p.push(...y);return p},getRoutesByFile:()=>new Map(i)}}var Yr=require("zod");var Qr=require("zod");function Et(e,t){return t instanceof Qr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Gr=require("zod");function Tt(e,t){return t instanceof Gr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Zr=require("zod");function bt(e,t){return t instanceof Zr.z.ZodObject?t.strict().parse(e):t.parse(e)}var Jr=require("zod");function Rt(e,t){return t instanceof Jr.z.ZodObject?t.strict().parse(e):t.parse(e)}he();D();function Ct(e,t=!1){return A({name:"RequestValidator",debug:t,handler:async(r,n,o)=>{if(e.params&&r.request.params)try{r.request.params=Tt(r.request.params,e.params)}catch(i){let s=Ge(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new _("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&r.request.query)try{r.request.query=bt(r.request.query,e.query)}catch(i){let s=Ge(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new _("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{r.request.body=Et(r.request.body,e.body)}catch(i){let s=Ge(i),a=s.reduce((c,l)=>c+l.messages.length,0);throw new _("Request validation failed",{fields:s,errorCount:a,section:"body"})}await n()}})}function yi(e){return e!==null&&typeof e=="object"&&"type"in e&&"status"in e&&"correlationId"in e&&"timestamp"in e}function Pt(e){return A({name:"ResponseValidator",handler:async(t,r)=>{let n=t.response.json,o=!0;t.response.json=(i,s)=>{if(!o||yi(i))return n.call(t.response,i,s);try{let a=Rt(i,e);return n.call(t.response,a,s)}catch(a){throw o=!1,new U("Response validation failed",{validationError:Ge(a),hint:"The handler returned data that does not match the response schema"})}};try{await r()}catch(i){throw o=!1,t.response.json=n,i}finally{t.response.json=n}}})}function Ge(e){if(e instanceof Yr.z.ZodError){let t=new Map;for(let r of e.issues){let n=r.path.length>0?r.path.join("."):"root";t.has(n)||t.set(n,[]),t.get(n).push(r.message)}return Array.from(t.entries()).map(([r,n])=>({field:r,messages:n}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function Mt(e,t,r,n){let o=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&o.unshift(Ct(t.schema)),t.schema.response&&o.push(Pt(t.schema.response))),await Z([...o])(e,async()=>{let s=n.child({route:e.request.path,method:e.request.method}),a=await t.handler(e,r,s);!e.response.sent&&a!==void 0&&e.response.json(a)},n)}function Kr(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function Q(e,t,r){console.log(`Updating routes from file: ${t}`);let n=e.routesByFile.get(t)||new Set,o=new Set(r.map(l=>l.path)),i=r.filter(l=>!n.has(l.path)),s=Array.from(n).filter(l=>!o.has(l)),c=r.filter(l=>n.has(l.path)).filter(l=>{let p=e.routesByPath.get(l.path);return!p||!wi(p,l)});return Si(e,t,{added:i,removed:s,changed:c}),{added:i,removed:s,changed:c}}function Xr(e){return Array.from(e.routesByPath.values())}function Si(e,t,r){let{added:n,removed:o,changed:i}=r;o.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...n,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...n.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!o.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function wi(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(o=>o!=="path").sort(),n=Object.keys(t).filter(o=>o!=="path").sort();return r.length!==n.length?!1:r.every(o=>{let i=e[o],s=t[o];return typeof i==typeof s})}function _t(e,t){Object.entries(e).forEach(([r,n])=>{r==="path"||!n||t.add(e.path,r,n)})}function Ee(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function en(e,t){Ee(e.path,t),_t(e,t)}var vi={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function tn(e){let t={...vi,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=Kr(),n=oe(),o=!1,i=null,s=null,a=new Set([t.routesDir]);function c(u){console.log(`
|
|
43
|
+
\u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${u.added.length} routes`),console.log(` Removing ${u.removed.length} routes`),console.log(` Updating ${u.changed.length} routes`),u.removed.forEach(d=>{console.log(` \u2796 Removing: ${d}`),Ee(d,n)}),u.added.forEach(d=>{let h=Object.keys(d).filter(f=>f!=="path");console.log(` \u2795 Adding: ${d.path} [${h.join(", ")}]`),_t(d,n)}),u.changed.forEach(d=>{let h=Object.keys(d).filter(f=>f!=="path");console.log(` \u{1F504} Updating: ${d.path} [${h.join(", ")}]`),en(d,n)}),console.log(`\u2705 Matcher changes applied
|
|
44
|
+
`)}function l(u,d){try{let h=Q(r,d,u);return c(h),h}catch(h){throw console.error(`\u26A0\uFE0F Route conflicts from ${d}:`,h),h}}async function p(u,d,h){try{let f=await jr(u),m=f.map(w=>h?{...w,path:`${h}${w.path}`}:w),E=l(m,d);console.log(`Loaded ${f.length} routes from ${d}${h?` with prefix ${h}`:""} (${E.added.length} added, ${E.changed.length} changed, ${E.removed.length} removed)`)}catch(f){throw console.error(`\u26A0\uFE0F Failed to load routes from ${d}:`,f),f}}async function y(){return o||i||(i=(async()=>{try{await Promise.all(Array.from(a).map(u=>p(u,u))),t.watchMode&&x(),o=!0}catch(u){throw console.error("\u26A0\uFE0F Failed to initialize router:",u),u}})()),i}function x(){s||(s=new Map);for(let u of a)if(!s.has(u)){let d=xt(u,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(h,f)=>{try{let m=Q(r,h,f);c(m)}catch(m){console.error(`Error adding routes from ${u}:`,m)}},onRouteChanged:wt(async(h,f)=>{try{console.log(`Processing changes for ${h}`);let m=Q(r,h,f);console.log(`Changes detected: ${m.added.length} added, ${m.changed.length} changed, ${m.removed.length} removed`),c(m),console.log(`Route changes applied: ${m.added.length} added, ${m.changed.length} changed, ${m.removed.length} removed`)}catch(m){console.error(`\u26A0\uFE0F Error updating routes from ${u}:`,m)}},u),onRouteRemoved:(h,f)=>{console.log(`File removed: ${h} with ${f.length} routes`);try{f.forEach(m=>{Ee(m.path,n)}),St(h)}catch(m){console.error(`\u26A0\uFE0F Error removing routes from ${h}:`,m)}},onError:h=>{console.error(`\u26A0\uFE0F Route watcher error for ${u}:`,h)}});s.set(u,d)}}function T(u,d){s||(s=new Map);let h=xt(u,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(f,m)=>{try{let E=m.map(N=>d?{...N,path:`${d}${N.path}`}:N),w=Q(r,f,E);c(w)}catch(E){console.error(`\u26A0\uFE0F Error adding routes from ${u}:`,E)}},onRouteChanged:wt(async(f,m)=>{try{let E=m.map(N=>d?{...N,path:`${d}${N.path}`}:N),w=Q(r,f,E);c(w)}catch(E){console.error(`\u26A0\uFE0F Error updating routes from ${u}:`,E)}},u),onRouteRemoved:(f,m)=>{try{m.forEach(E=>{let w=d?`${d}${E.path}`:E.path;Ee(w,n)}),St(f)}catch(E){console.error(`Error removing routes from ${f}:`,E)}},onError:f=>{console.error(`\u26A0\uFE0F Route watcher error for ${u}:`,f)}});return s.set(u,h),h}return y().catch(u=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",u)}),{async handleRequest(u,d){o||(console.log("\u{1F504} Router not initialized, initializing..."),await y());let{method:h,path:f}=u.request;console.log(`
|
|
45
|
+
\u{1F4E5} Handling request: ${h} ${f}`);let m=n.match(f,h);if(!m)throw console.log(`\u274C No match found for: ${h} ${f}`),new V("Not found");if(console.log(`\u2705 Route matched: ${h} ${f}`),console.log(` Params: ${JSON.stringify(m.params)}`),m.methodNotAllowed){u.response.status(405).json({error:"\u274C Method Not Allowed",allowed:m.allowedMethods}),m.allowedMethods&&m.allowedMethods.length>0&&u.response.header("Allow",m.allowedMethods.join(", "));return}u.request.params=m.params,await Mt(u,m.route,m.params,d)},getRoutes(){return Xr(r)},addRoute(u){let d=Q(r,"programmatic",[u]);c(d)},addRoutes(u){let d=Q(r,"programmatic",u);return c(d),d},async addRouteDirectory(u,d={}){if(a.has(u)){console.warn(`Route directory ${u} already registered`);return}a.add(u),o&&(await p(u,u,d.prefix),t.watchMode&&T(u,d.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let u of s.values())await u.close();s.clear()}}}}R();var L={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[],bodyLimits:{json:512*1024,form:1024*1024,text:5*1024*1024,raw:10*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024}}};function xi(e={}){let t={port:e.port??L.port,host:e.host??L.host,routesDir:e.routesDir??L.routesDir,http2:{enabled:e.http2?.enabled??L.http2.enabled,keyFile:e.http2?.keyFile,certFile:e.http2?.certFile},middleware:e.middleware??L.middleware,plugins:e.plugins??L.plugins,correlation:e.correlation,cors:e.cors,bodyLimits:e.bodyLimits?{json:e.bodyLimits.json??L.bodyLimits.json,form:e.bodyLimits.form??L.bodyLimits.form,text:e.bodyLimits.text??L.bodyLimits.text,raw:e.bodyLimits.raw??L.bodyLimits.raw,multipart:{maxFileSize:e.bodyLimits.multipart?.maxFileSize??L.bodyLimits.multipart.maxFileSize,maxTotalSize:e.bodyLimits.multipart?.maxTotalSize??L.bodyLimits.multipart.maxTotalSize,maxFiles:e.bodyLimits.multipart?.maxFiles??L.bodyLimits.multipart.maxFiles,maxFieldSize:e.bodyLimits.multipart?.maxFieldSize??L.bodyLimits.multipart.maxFieldSize}}:L.bodyLimits,logging:e.logging||L.logging};try{let r=Fr(t);return Kt({routesDir:r.routesDir}),r}catch(r){throw r instanceof Error?new Error(`Failed to create server: ${r.message}`):new Error(`Failed to create server: ${String(r)}`)}}function Ei(e){e.correlation&&Nt(e.correlation.headerName,e.correlation.generator)}function Ti(e,t){return async()=>(Ei(t),await bi(e),await e.pluginManager.initializePlugins(e),await Ar(e,t),await e.pluginManager.onServerStart(e,e.server),Ri(e),e)}async function bi(e){for(let t of e.plugins)await t.register(e)}function Ri(e){let t=kr(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function Ci(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await zr(e,r)}}function Pi(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function Mi(e){return async t=>{if(Array.isArray(t))for(let r of t)yt(r),e.plugins.push(r),await r.register(e);else yt(t),e.plugins.push(t),await t.register(e);return e}}function Ze(e={}){let t=xi(e),{port:r,host:n,middleware:o,plugins:i,cors:s,bodyLimits:a}=t,c=F(t.logging||{});ce(t.logging||{});let l=Array.isArray(o)?[...o]:[],p=Array.isArray(i)?[...i]:[],y=new rn.AsyncLocalStorage,x=tn({routesDir:t.routesDir,watchMode:process.env.NODE_ENV==="development"}),T=Dr({continueOnError:!0}),u=new nn.default,d={server:null,port:r,host:n,context:y,events:u,plugins:[...p],middleware:[...l],corsOptions:s,bodyLimits:a,_signalHandlers:{unregister:()=>{}},_logger:c,use:()=>d,register:async()=>d,listen:async()=>d,close:async()=>{},router:x,pluginManager:T};return d.listen=Ti(d,t),d.close=Ci(d),d.use=Pi(d),d.register=Mi(d),d}function Ot(e){return{}}R();function _i(e){return typeof e=="object"&&e!==null&&"name"in e&&"execute"in e&&typeof e.name=="string"&&typeof e.execute=="function"}function Oi(e){return typeof e=="object"&&e!==null&&"name"in e&&"version"in e&&"register"in e&&typeof e.name=="string"&&typeof e.version=="string"&&typeof e.register=="function"}function Li(e){return e}function Ai(e){return e}function zi(...e){return e}function ki(...e){return e}P();D();P();R();var Je=class extends v{constructor(t,r=void 0,n=void 0){super("UNAUTHORIZED",t,401,n??g(),r)}};P();R();var Ye=class extends v{constructor(t,r=void 0,n=void 0){super("CONFLICT",t,409,n??g(),r)}};P();R();var Ke=class extends v{constructor(t,r=void 0,n=void 0){super("RATE_LIMITED",t,429,n??g(),r)}};he();me();P();R();var Xe=class extends v{constructor(t,r,n){super("UPLOAD_TIMEOUT",t,408,n??g(),r)}};P();R();var et=class extends v{constructor(t,r,n){super("UNPROCESSABLE_ENTITY",t,422,n??g(),r)}};ge();P();R();var tt=class extends v{constructor(t,r=void 0,n=void 0){super("SERVICE_UNAVAILABLE",t,503,n??g(),r)}};var on="0.1.0",sn={createServer:Ze,inferContext:Ot},an={createDeleteRoute:Be,createGetRoute:Fe,createHeadRoute:He,createOptionsRoute:$e,createPatchRoute:Ne,createPostRoute:De,createPutRoute:Ie,createRouteFactory:dt,createMatcher:oe,extractParams:X,compilePathPattern:ne,paramsToQuery:pe,buildUrl:qe},cn={createMiddleware:A,createServiceMiddleware:Me,createStateMiddleware:Pe,compose:Z,cors:ue,requestLoggerMiddleware:ct},ln={createPlugin:_e},Fi={createServer:Ze,createMiddleware:A,createServiceMiddleware:Me,createStateMiddleware:Pe,createPlugin:_e,getCorrelationId:g,configureGlobalLogger:ce,createLogger:F,logger:C,Server:sn,Router:an,Middleware:cn,Plugins:ln,VERSION:on};0&&(module.exports={Blaize,BlaizeError,ConflictError,ConsoleTransport,ErrorSeverity,ErrorType,ForbiddenError,InternalServerError,JSONTransport,Logger,MiddlewareAPI,NotFoundError,NullTransport,PayloadTooLargeError,PluginsAPI,RateLimitError,RequestTimeoutError,RouterAPI,ServerAPI,ServiceNotAvailableError,UnauthorizedError,UnprocessableEntityError,UnsupportedMediaTypeError,VERSION,ValidationError,asMiddlewareArray,asPluginArray,buildUrl,compilePathPattern,compose,configureGlobalLogger,cors,createDeleteRoute,createGetRoute,createHeadRoute,createLogger,createMatcher,createMiddleware,createMiddlewareArray,createOptionsRoute,createPatchRoute,createPlugin,createPluginArray,createPostRoute,createPutRoute,createRouteFactory,createServer,createServiceMiddleware,createStateMiddleware,extractParams,getCorrelationId,inferContext,isMiddleware,isPlugin,logger,paramsToQuery,requestLoggerMiddleware});
|
|
44
46
|
//# sourceMappingURL=index.cjs.map
|