@stacksjs/bun-router 0.1.0 → 0.1.1
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-03m2j6h7.js +2 -0
- package/dist/chunk-08cw7ejr.js +3 -0
- package/dist/chunk-0e4g0fyv.js +62 -0
- package/dist/chunk-0mmn02yw.js +2 -0
- package/dist/chunk-126c9qm3.js +2 -0
- package/dist/chunk-12p13817.js +2 -0
- package/dist/chunk-14v65c37.js +4 -0
- package/dist/{chunk-s3dn1kwx.js → chunk-1b6a7t3v.js} +2 -2
- package/dist/chunk-1wenkmk0.js +2 -0
- package/dist/chunk-2152npfd.js +2 -0
- package/dist/chunk-26w23krx.js +2 -0
- package/dist/chunk-2g8m379z.js +10 -0
- package/dist/{chunk-5mxby3fd.js → chunk-2rr178et.js} +2 -2
- package/dist/chunk-2w8f3swz.js +29 -0
- package/dist/chunk-3y4gaz7v.js +82 -0
- package/dist/chunk-4r1x4afz.js +12 -0
- package/dist/chunk-4wyw66zk.js +2 -0
- package/dist/chunk-4z5sf8ag.js +2 -0
- package/dist/{chunk-krkchy8v.js → chunk-58tfvayh.js} +3 -3
- package/dist/{chunk-ex5fkjah.js → chunk-5dp83qcx.js} +43 -43
- package/dist/chunk-5f0d9j9a.js +2 -0
- package/dist/{chunk-zhx0hxdd.js → chunk-5z52b0fc.js} +7 -7
- package/dist/{chunk-kc659vhx.js → chunk-5zrnk2kq.js} +3 -3
- package/dist/chunk-6dmqtdnq.js +2 -0
- package/dist/{chunk-5s1pr62n.js → chunk-6e91956t.js} +2 -2
- package/dist/{chunk-jrf5a2ap.js → chunk-6rv8w5jk.js} +1 -1
- package/dist/{chunk-5n0ckcmc.js → chunk-6x1feysm.js} +2 -2
- package/dist/chunk-7y72hm1x.js +2 -0
- package/dist/{chunk-zetqzgf3.js → chunk-8hbhfh6b.js} +6 -6
- package/dist/{chunk-5ncn73tp.js → chunk-8kfzygg5.js} +2 -2
- package/dist/chunk-8wydx2we.js +2 -0
- package/dist/chunk-8zjnjvv7.js +2 -0
- package/dist/chunk-988h4bzr.js +2 -0
- package/dist/chunk-9b6a58ac.js +2 -0
- package/dist/chunk-a8fcaywb.js +2 -0
- package/dist/chunk-bfjwn7yg.js +2 -0
- package/dist/chunk-bp2522mm.js +2 -0
- package/dist/chunk-bswe62q4.js +48 -0
- package/dist/chunk-c3v796c8.js +943 -0
- package/dist/chunk-ccqmwdry.js +2 -0
- package/dist/chunk-ck0crwnx.js +2 -0
- package/dist/chunk-cqgkxcb4.js +2 -0
- package/dist/chunk-dntnakjy.js +2 -0
- package/dist/{chunk-67wgad4f.js → chunk-ettdpnrw.js} +2 -2
- package/dist/{chunk-csfrpsp7.js → chunk-ezqwq17j.js} +10 -10
- package/dist/chunk-ezx3qsez.js +2 -0
- package/dist/{chunk-73k79n7q.js → chunk-f72nnjy4.js} +360 -360
- package/dist/chunk-fna5n0ey.js +246 -0
- package/dist/chunk-fqhckdt8.js +2 -0
- package/dist/chunk-fr6hbx25.js +2 -0
- package/dist/{chunk-vr10sbbh.js → chunk-g9cwng6w.js} +1 -1
- package/dist/chunk-gd3za5x0.js +2 -0
- package/dist/chunk-gf28608k.js +2 -0
- package/dist/chunk-h1dj6v8q.js +3 -0
- package/dist/chunk-hjxe7k2g.js +2 -0
- package/dist/chunk-hrkgznbn.js +2 -0
- package/dist/chunk-j6h5v0br.js +2 -0
- package/dist/{chunk-0gjq8ttx.js → chunk-mgb01qdv.js} +2 -2
- package/dist/chunk-n24c9whp.js +2 -0
- package/dist/{chunk-kxp888dn.js → chunk-n2j24b0h.js} +244 -244
- package/dist/{chunk-vv3gb1m5.js → chunk-nhmtg01n.js} +2 -2
- package/dist/chunk-p0qhpnqh.js +70 -0
- package/dist/chunk-p0w1x8y2.js +3 -0
- package/dist/{chunk-9ght4n4r.js → chunk-p3dk1w2w.js} +11 -11
- package/dist/{chunk-6sjvhy5f.js → chunk-q4e9pxs7.js} +2 -2
- package/dist/chunk-q5dv1kyy.js +2 -0
- package/dist/chunk-qnqgf9tq.js +2 -0
- package/dist/chunk-qvwy1808.js +898 -0
- package/dist/{chunk-5s0pnsd6.js → chunk-r18f77vc.js} +4 -4
- package/dist/chunk-r63za1mr.js +2 -0
- package/dist/{chunk-6s1kbajm.js → chunk-rft8gw92.js} +1 -1
- package/dist/chunk-ryvmyskt.js +4211 -0
- package/dist/chunk-sa6mx308.js +2 -0
- package/dist/chunk-va0pc7hx.js +2 -0
- package/dist/chunk-vcp8dnjq.js +412 -0
- package/dist/chunk-vg1erq1q.js +2 -0
- package/dist/{chunk-hmgedrmr.js → chunk-w0jv49ch.js} +3 -3
- package/dist/{chunk-0t5vz87j.js → chunk-wm805tte.js} +19 -19
- package/dist/chunk-xj9h6mc9.js +2 -0
- package/dist/chunk-ytvzwrq3.js +51 -0
- package/dist/{chunk-w4r464v5.js → chunk-zde7ebc4.js} +2 -2
- package/dist/chunk-zmqsv2xy.js +2 -0
- package/dist/cli.js +57 -66
- package/dist/container/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +29 -29
- package/dist/typed/client.d.ts +89 -0
- package/dist/typed/contract.d.ts +34 -0
- package/dist/typed/endpoint.d.ts +90 -0
- package/dist/typed/index.d.ts +14 -0
- package/dist/typed/router.d.ts +141 -0
- package/package.json +1 -1
- package/dist/chunk-30rkn2ym.js +0 -2
- package/dist/chunk-38cmrard.js +0 -2
- package/dist/chunk-3qna6dwd.js +0 -2
- package/dist/chunk-4d5fmta0.js +0 -2
- package/dist/chunk-4x3b4b4q.js +0 -2
- package/dist/chunk-6xed4va1.js +0 -2
- package/dist/chunk-748n6ydj.js +0 -2
- package/dist/chunk-7rsf8tes.js +0 -898
- package/dist/chunk-8aspmtf1.js +0 -2
- package/dist/chunk-8yfdg595.js +0 -2
- package/dist/chunk-90eze7av.js +0 -3
- package/dist/chunk-9dvwyej7.js +0 -2
- package/dist/chunk-a2w45krb.js +0 -2
- package/dist/chunk-a547f2ab.js +0 -48
- package/dist/chunk-bqdycvtc.js +0 -2
- package/dist/chunk-cd03rk3x.js +0 -2
- package/dist/chunk-ct0m17q5.js +0 -2
- package/dist/chunk-dhbvvr5h.js +0 -2
- package/dist/chunk-dhptcsya.js +0 -943
- package/dist/chunk-dq93zag9.js +0 -2
- package/dist/chunk-edrtesh7.js +0 -2
- package/dist/chunk-ejcws37w.js +0 -2
- package/dist/chunk-ex890p45.js +0 -51
- package/dist/chunk-f69cpnhw.js +0 -2
- package/dist/chunk-fjf53b44.js +0 -2
- package/dist/chunk-fjzye4qj.js +0 -2
- package/dist/chunk-gfd23b6t.js +0 -2
- package/dist/chunk-habv0vef.js +0 -12
- package/dist/chunk-hz6fc788.js +0 -2
- package/dist/chunk-jff6j9y3.js +0 -10
- package/dist/chunk-jmeb7n8k.js +0 -70
- package/dist/chunk-jy2jhcpy.js +0 -246
- package/dist/chunk-m249t3je.js +0 -3
- package/dist/chunk-m9yabnjx.js +0 -2
- package/dist/chunk-mekrq9wd.js +0 -2
- package/dist/chunk-mmxv535f.js +0 -82
- package/dist/chunk-mypn7jss.js +0 -2
- package/dist/chunk-n18x1k3c.js +0 -2
- package/dist/chunk-nkddjzsa.js +0 -2
- package/dist/chunk-pjmhqmr9.js +0 -2
- package/dist/chunk-qyrnsaq1.js +0 -2
- package/dist/chunk-r19ff2qm.js +0 -62
- package/dist/chunk-r338fssq.js +0 -2
- package/dist/chunk-s36z58x2.js +0 -29
- package/dist/chunk-s79dd325.js +0 -471
- package/dist/chunk-ta38j9em.js +0 -2
- package/dist/chunk-tpfgntwj.js +0 -4211
- package/dist/chunk-vw8rwv6e.js +0 -2
- package/dist/chunk-wcrqs5z9.js +0 -2
- package/dist/chunk-x6d1rmwa.js +0 -2
- package/dist/chunk-x7ft15zz.js +0 -2
- package/dist/chunk-x8trwn7j.js +0 -3
- package/dist/chunk-xhepdj1f.js +0 -2
- package/dist/chunk-xv2em0q4.js +0 -4
- package/dist/chunk-ypw6g0te.js +0 -2
- package/dist/chunk-z8szsm21.js +0 -2
- package/dist/chunk-zfbh14qe.js +0 -2
- /package/dist/{chunk-a3wahyg7.js → chunk-nf3kv7kv.js} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$p as C7,Aq as r7,Bq as e7,Cq as YX,Dq as ZX,Eq as $X,Fq as XX,Gq as JX,Hq as QX,Ip as _7,Iq as _X,Jp as j7,Jq as jX,Kp as G7,Kq as GX,Lp as W7,Lq as WX,Mp as K7,Mq as KX,Np as z7,Nq as zX,Op as L7,Oq as LX,Pp as U7,Pq as UX,Qp as V7,Qq as VX,Rp as A7,Rq as AX,Sp as D7,Tp as E7,Up as I7,Vp as O7,Wp as H7,Xp as F7,Yp as B7,Zp as N7,_p as S7,aq as M7,bq as T7,cq as P7,dq as b7,eq as x7,fq as R7,gq as w7,hq as k7,iq as v7,jq as q7,kq as f7,lq as y7,mq as g7,nq as h7,oq as c7,pq as p7,qq as m7,rq as u7,sq as d7,tq as l7,uq as i7,vq as n7,wq as s7,xq as o7,yq as a7,zq as t7}from"./chunk-s79dd325.js";import{$q as Q9,Br as m$,Gr as u$,Sq as lY,Tq as $Y,Uq as e8,Vq as Y9,Wq as Z9,Xq as $9,Yq as EY,Zq as X9,_q as J9,ar as _9,br as OY,cr as IY,dr as j9,er as G9,fr as W9,gr as v,hr as K9,ir as z9,jr as L9,kr as U9,lr as V9,mr as A9,nr as D9,or as E9,pr as I9,ur as f$,vr as y$,wr as g$,xr as h$,yr as c$,zr as p$}from"./chunk-mmxv535f.js";import{Yu as r8,Zu as pY}from"./chunk-a3wahyg7.js";import{timingSafeEqual as c8}from"crypto";function hY(Y){return btoa(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function DY(Y){Y=Y.replace(/-/g,"+").replace(/_/g,"/");while(Y.length%4)Y+="=";return atob(Y)}class LZ{secret;constructor(Y){this.secret=Y}sign(Y,Z={}){let $={alg:Z.algorithm||"HS256",typ:"JWT",...Z.header},X=Math.floor(Date.now()/1000),J={...Y,iat:X};if(Z.expiresIn){let W=typeof Z.expiresIn==="string"?this.parseTimespan(Z.expiresIn):Z.expiresIn;J.exp=X+W}if(Z.notBefore){let W=typeof Z.notBefore==="string"?this.parseTimespan(Z.notBefore):Z.notBefore;J.nbf=X+W}if(Z.issuer)J.iss=Z.issuer;if(Z.subject)J.sub=Z.subject;if(Z.audience)J.aud=Z.audience;if(Z.jwtid)J.jti=Z.jwtid;let Q=hY(JSON.stringify($)),_=hY(JSON.stringify(J)),j=`${Q}.${_}`,G=this.createSignature(j,this.secret,$.alg);return`${j}.${G}`}verify(Y,Z={}){try{let $=Y.split(".");if($.length!==3)throw Error("Token structure invalid");let[X,J,Q]=$,_=JSON.parse(DY(X)),j=JSON.parse(DY(J));if(Z.algorithms&&!Z.algorithms.includes(_.alg))throw Error(`Algorithm ${_.alg} not allowed`);let G=`${X}.${J}`,W=this.createSignature(G,this.secret,_.alg),K=Buffer.from(Q),z=Buffer.from(W);if(K.length!==z.length||!c8(K,z))throw Error("Invalid signature");let L=Math.floor(Date.now()/1000);if(j.exp&&!Z.ignoreExpiration&&L>=j.exp)throw Error("Token expired");if(j.nbf&&L<j.nbf)throw Error("Token not active yet");if(j.iat&&j.iat>L)throw Error("Token used before issued");if(Z.issuer&&j.iss!==Z.issuer)throw Error("Invalid issuer");if(Z.audience&&j.aud!==Z.audience)throw Error("Invalid audience");if(Z.subject&&j.sub!==Z.subject)throw Error("Invalid subject");return j}catch{return null}}decode(Y){try{let Z=Y.split(".");if(Z.length!==3)return null;let[$,X]=Z;return{header:JSON.parse(DY($)),payload:JSON.parse(DY(X))}}catch{return null}}createSignature(Y,Z,$){return hY(JSON.stringify({data:Y,secret:Z.slice(0,5),alg:$}))}parseTimespan(Y){let Z=Y.match(/^(\d+)\s*([smhd])$/i);if(!Z)return Number.parseInt(Y,10)||0;let $=Number.parseInt(Z[1],10);switch(Z[2].toLowerCase()){case"s":return $;case"m":return $*60;case"h":return $*60*60;case"d":return $*24*60*60;default:return $}}}class UZ{keys;options;constructor(Y={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...Y}}generateKey(Y,Z=[],$){let X=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(X,{owner:Y,scopes:Z,expiresAt:$?new Date(Date.now()+$*1000):void 0}),X}validateKey(Y,Z=[]){let $=this.keys.get(Y);if(!$)return!1;if($.expiresAt&&$.expiresAt<new Date)return!1;if(Z.length>0)return Z.every((X)=>$.scopes.includes(X));return!0}getKeyInfo(Y){return this.keys.get(Y)||null}revokeKey(Y){return this.keys.delete(Y)}extractFromRequest(Y){let{source:Z,keyName:$}=this.options;switch(Z){case"header":return Y.headers.get($||"X-API-Key")||null;case"query":return new URL(Y.url).searchParams.get($||"api_key")||null;case"cookie":if(Y.cookies){let X=$||"api_key";if(typeof Y.cookies.get==="function")return Y.cookies.get(X)||null;return Y.cookies[X]||null}return null;default:return null}}randomString(Y){let $="";for(let X=0;X<Y;X++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return $}}class VZ{config;constructor(Y){this.config=Y}getAuthorizationUrl(Y={}){let Z=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...Y});if(this.config.scope)Z.set("scope",this.config.scope);if(this.config.state)Z.set("state",this.config.state);return`${this.config.authorizeUrl}?${Z.toString()}`}async exchangeCodeForToken(Y){let Z=new URLSearchParams({grant_type:"authorization_code",code:Y,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),$=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z.toString()});if(!$.ok)throw Error(`OAuth token exchange failed: ${$.status} ${$.statusText}`);return await $.json()}async refreshToken(Y){let Z=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y,client_id:this.config.clientId,client_secret:this.config.clientSecret}),$=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z.toString()});if(!$.ok)throw Error(`OAuth token refresh failed: ${$.status} ${$.statusText}`);return await $.json()}}var p8={JWT:LZ,ApiKeyManager:UZ,OAuth2Helper:VZ},m8=p8;var OZ={};r8(OZ,{withCircuitBreaker:()=>n8,globalCircuitBreakerRegistry:()=>cY,findSimilarRoutes:()=>D9,detectRouteConflicts:()=>E9,createGracefulDegradationMiddleware:()=>a8,createErrorReporting:()=>s8,createCircuitBreakerMiddleware:()=>d8,createCircuitBreaker:()=>i8,createAdvancedErrorHandler:()=>IZ,circuitBreaker:()=>u8,ValidationException:()=>$Y,TimeoutException:()=>EY,ServiceUnavailableException:()=>Q9,ServiceHealthMonitor:()=>dY,SentryReporter:()=>mY,RouterException:()=>lY,RouterErrorFactory:()=>I9,RouteNotFoundException:()=>U9,RouteConflictException:()=>K9,RateLimitException:()=>X9,NotFoundException:()=>Z9,ModelBindingException:()=>A9,MiddlewareConfigurationException:()=>L9,MethodNotAllowedException:()=>$9,InternalServerException:()=>J9,HandlerResolutionException:()=>V9,GracefulDegradationManager:()=>ZY,FileSystemException:()=>W9,ExternalServiceException:()=>OY,ErrorReportingPresets:()=>o8,ErrorReportingManager:()=>YY,ErrorFactory:()=>v,DegradationStrategies:()=>t8,DatabaseException:()=>_9,CustomReporter:()=>DZ,ConfigurationException:()=>G9,CircularDependencyException:()=>z9,CircuitBreakerRegistry:()=>n,CircuitBreakerPresets:()=>l8,CircuitBreakerOpenException:()=>IY,CircuitBreakerHttpClient:()=>AZ,CircuitBreaker:()=>HY,BusinessLogicException:()=>j9,BugsnagReporter:()=>uY,AuthorizationException:()=>Y9,AuthenticationException:()=>e8});class HY{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(Y){let Z={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...Z,...Y},this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},setInterval(()=>this.cleanupOldRequests(),this.config.monitoringPeriod/4).unref?.()}async execute(Y){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let J=new IY(this.config.name,this.nextAttemptTime,Y.context);if(Y.fallback)try{return await Y.fallback()}catch(Q){console.error(Q)}throw J}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let J=new IY(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),Y.context);if(Y.fallback)try{return await Y.fallback()}catch(Q){throw console.error(Q),J}throw J}let Z=Date.now(),$,X=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let J=Y.timeout||this.config.timeout,Q=new Promise((_,j)=>{setTimeout(()=>{j(new EY(`Circuit breaker timeout for ${this.config.name}`,J,Y.context))},J)});return $=await Promise.race([Y.execute(),Q]),this.onSuccess(Date.now()-Z),$}catch(J){if(X=J,this.onFailure(X,Date.now()-Z),Y.fallback)try{return await Y.fallback()}catch(Q){throw console.error(Q),X}else throw X}}getState(){return this.state}getMetrics(){return{...this.metrics,state:this.state,nextAttemptTime:this.nextAttemptTime}}forceOpen(){this.transitionToOpen()}forceClosed(){this.transitionToClosed()}reset(){this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},this.recentRequests=[]}onSuccess(Y){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(Y),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:Y}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(Y,Z){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,Y instanceof EY)this.metrics.timeouts++;if(this.updateAverageResponseTime(Z),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:Z}),this.shouldTrip(Y)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(Y,this.config.name)}shouldTrip(Y){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(Y))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let Z=this.getRecentRequests();if(Z.length>=this.config.minimumRequests){if(Z.filter((J)=>!J.success).length/Z.length*100>=this.config.errorThresholdPercentage)return!0}return!1}transitionToClosed(){if(this.state="CLOSED",this.nextAttemptTime=void 0,this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToOpen(){if(this.state="OPEN",this.nextAttemptTime=new Date(Date.now()+this.config.recoveryTimeout),this.halfOpenCallCount=0,this.metrics.state=this.state,this.metrics.nextAttemptTime=this.nextAttemptTime,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToHalfOpen(){if(this.state="HALF_OPEN",this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}updateAverageResponseTime(Y){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=Y;else this.metrics.averageResponseTime=0.1*Y+0.9*this.metrics.averageResponseTime}getRecentRequests(){let Y=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((Z)=>Z.timestamp>Y)}cleanupOldRequests(){let Y=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((Z)=>Z.timestamp>Y)}}class n{breakers=new Map;configs=new Map;register(Y){let Z=new HY(Y);return this.breakers.set(Y.name,Z),this.configs.set(Y.name,Y),Z}get(Y){return this.breakers.get(Y)}async execute(Y,Z){let $=this.breakers.get(Y);if(!$)throw Error(`Circuit breaker '${Y}' not found`);return $.execute(Z)}getAllMetrics(){let Y={};for(let[Z,$]of this.breakers)Y[Z]=$.getMetrics();return Y}getBreakersByState(Y){let Z=[];for(let[$,X]of this.breakers)if(X.getState()===Y)Z.push($);return Z}forceAllClosed(){for(let Y of this.breakers.values())Y.forceClosed()}resetAll(){for(let Y of this.breakers.values())Y.reset()}remove(Y){return this.configs.delete(Y),this.breakers.delete(Y)}getNames(){return Array.from(this.breakers.keys())}}function u8(Y){let Z=new HY(Y);return function($,X,J){let Q=J.value;return J.value=async function(..._){return Z.execute({execute:()=>Q.apply(this,_),context:{method:X,timestamp:new Date}})},J}}class AZ{registry;constructor(Y){this.registry=Y||new n}async fetch(Y,Z={}){let{circuitBreaker:$,fallback:X,context:J,...Q}=Z,_;if(typeof $==="string")_=$;else if($){if(_=$.name,!this.registry.get(_))this.registry.register($)}else if(_=`http-${new URL(Y).hostname}`,!this.registry.get(_))this.registry.register({name:_,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(_,{execute:async()=>{let j=await fetch(Y,Q);if(j.status>=500)throw new OY(`HTTP ${j.status}: ${j.statusText}`,_,Y,j.status,void 0,J);return j},fallback:X,context:J})}getRegistry(){return this.registry}}function d8(Y){return async(Z,$)=>{let X=Z.context?.serviceName;if(!X)return $();let J=Y.get(X);if(!J)return $();return J.execute({execute:$,context:{requestId:Z.requestId,route:Z.route,method:Z.method,url:Z.url}})}}var l8={critical:(Y)=>({name:Y,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(Y)=>({name:Y,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(Y)=>({name:Y,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(Y)=>({name:Y,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(Z)=>{return!(Z.message.includes("validation")||Z.message.includes("constraint"))}}),externalApi:(Y)=>({name:Y,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(Z)=>{if(Z instanceof OY)return Z.statusCode>=500;return!0}})},cY=new n;function i8(Y){return cY.register(Y)}async function n8(Y,Z){return cY.execute(Y,Z)}class mY{config;sentry;constructor(Y){this.config=Y,this.initializeSentry()}async initializeSentry(){try{let Y=await import("@sentry/node");Y.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(Z,$)=>{let X=$.originalException;if(X&&this.config.beforeSend)return this.config.beforeSend(X,X.context)?Z:null;return Z},ignoreErrors:this.config.filters?.ignoreErrors,denyUrls:this.config.filters?.ignoreUrls,allowUrls:this.config.filters?.allowUrls,initialScope:{tags:this.config.tags,extra:this.config.extra,user:this.config.user},maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||100,tracesSampleRate:this.config.performance?.tracesSampleRate||0.1}),this.sentry=Y}catch(Y){console.warn("Failed to initialize Sentry:",Y)}}async report(Y,Z){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(Y))return null;let $={...Y.context,...Z};return this.sentry.withScope((X)=>{if($.requestId)X.setTag("requestId",$.requestId);if($.userId)X.setUser({id:$.userId});if($.traceId)X.setTag("traceId",$.traceId);if($.route)X.setTag("route",$.route);if($.method)X.setTag("method",$.method);X.setTag("errorCode",Y.code),X.setTag("severity",Y.severity),X.setTag("category",Y.category),X.setLevel(this.mapSeverityToLevel(Y.severity)),X.setExtra("statusCode",Y.statusCode),X.setExtra("retryable",Y.retryable),X.setExtra("timestamp",Y.timestamp),X.setExtra("context",$);let J=this.generateFingerprint(Y);if(J.length>0)X.setFingerprint(J);return this.sentry.captureException(Y)})}catch($){return console.error("Failed to report error to Sentry:",$),null}}addBreadcrumb(Y,Z="default",$="info",X){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:Y,category:Z,level:$,data:X,timestamp:Date.now()/1000})}setUser(Y){if(!this.sentry)return;this.sentry.setUser(Y)}setTag(Y,Z){if(!this.sentry)return;this.sentry.setTag(Y,Z)}setExtra(Y,Z){if(!this.sentry)return;this.sentry.setExtra(Y,Z)}setContext(Y,Z){if(!this.sentry)return;this.sentry.setContext(Y,Z)}async close(Y=2000){if(!this.sentry)return!0;return this.sentry.close(Y)}shouldIgnoreError(Y){let Z=this.config.filters;if(!Z)return!1;if(Z.ignoreCodes?.includes(Y.code))return!0;if(Z.ignoreErrors?.some(($)=>{if(typeof $==="string")return Y.message.includes($);return $.test(Y.message)}))return!0;return!1}mapSeverityToLevel(Y){switch(Y){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(Y){let Z=[];if(Z.push(Y.code),Z.push(Y.category),Y.context.route)Z.push(Y.context.route);return Z}}class uY{config;bugsnag;constructor(Y){this.config=Y,this.initializeBugsnag()}async initializeBugsnag(){try{let Y=await import("@bugsnag/js");Y.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(Z)=>{let $=Z.originalError;if($&&this.config.beforeSend)return this.config.beforeSend($,$.context)!==null;return!this.shouldIgnoreError($)}}),this.bugsnag=Y}catch(Y){console.warn("Failed to initialize Bugsnag:",Y)}}async report(Y,Z){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(Y))return null;let $={...Y.context,...Z};return this.bugsnag.notify(Y,(X)=>{if(X.severity=this.mapSeverityToBugsnag(Y.severity),X.context=$.route||$.url,$.userId)X.setUser($.userId,void 0,void 0);X.addMetadata("error",{code:Y.code,category:Y.category,statusCode:Y.statusCode,retryable:Y.retryable,timestamp:Y.timestamp}),X.addMetadata("request",{requestId:$.requestId,method:$.method,url:$.url,userAgent:$.userAgent,ip:$.ip}),X.groupingHash=this.generateGroupingHash(Y)}),"reported"}catch($){return console.error("Failed to report error to Bugsnag:",$),null}}addBreadcrumb(Y,Z="manual",$="info",X){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(Y,X,Z)}setUser(Y){if(!this.bugsnag)return;this.bugsnag.setUser(Y.id,Y.email,Y.username)}setTag(Y,Z){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[Y]:Z})}setExtra(Y,Z){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[Y]:Z})}setContext(Y,Z){if(!this.bugsnag)return;this.bugsnag.addMetadata(Y,Z)}async close(){return!0}shouldIgnoreError(Y){let Z=this.config.filters;if(!Z)return!1;if(Z.ignoreCodes?.includes(Y.code))return!0;if(Z.ignoreErrors?.some(($)=>{if(typeof $==="string")return Y.message.includes($);return $.test(Y.message)}))return!0;return!1}mapSeverityToBugsnag(Y){switch(Y){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(Y){return`${Y.code}-${Y.category}-${Y.context.route||"unknown"}`}}class DZ{config;reportHandler;constructor(Y,Z){this.config=Y,this.reportHandler=Z}async report(Y,Z){if(!this.config.enabled)return null;try{let $={...Y.context,...Z};if(this.config.beforeSend){if(!this.config.beforeSend(Y,$))return null}let X={error:Y,context:$,level:this.mapSeverityToLevel(Y.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(X)}catch($){return console.error("Failed to report error with custom handler:",$),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(Y){switch(Y){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class YY{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(Y){this.initializeReporters(Y)}initializeReporters(Y){for(let Z of Y){if(!Z.enabled)continue;switch(Z.service){case"sentry":this.reporters.push(new mY(Z));break;case"bugsnag":this.reporters.push(new uY(Z));break;case"custom":break}}}addReporter(Y){this.reporters.push(Y)}async report(Y,Z){let $=[];this.addBreadcrumb(`Error occurred: ${Y.message}`,"error",{code:Y.code,severity:Y.severity});let X=this.reporters.map(async(J)=>{try{let Q=await J.report(Y,Z);if(Q)$.push(Q)}catch(Q){console.error("Reporter failed:",Q)}});return await Promise.allSettled(X),$}addBreadcrumb(Y,Z="default",$){if(this.breadcrumbs.push({message:Y,timestamp:new Date,data:{category:Z,...$}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((X)=>{X.addBreadcrumb(Y,Z,"info",$)})}setUser(Y){this.reporters.forEach((Z)=>Z.setUser(Y))}setTag(Y,Z){this.reporters.forEach(($)=>$.setTag(Y,Z))}setExtra(Y,Z){this.reporters.forEach(($)=>$.setExtra(Y,Z))}setContext(Y,Z){this.reporters.forEach(($)=>$.setContext(Y,Z))}async close(Y=5000){let Z=this.reporters.map((X)=>X.close(Y));return(await Promise.allSettled(Z)).every((X)=>X.status==="fulfilled"&&X.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function s8(Y){return new YY(Y)}var o8={sentry:(Y,Z="production")=>({enabled:!0,service:"sentry",dsn:Y,environment:Z,sampleRate:1,breadcrumbs:{enabled:!0,maxBreadcrumbs:100},performance:{enabled:!0,tracesSampleRate:0.1},filters:{ignoreErrors:["Non-Error promise rejection captured","ResizeObserver loop limit exceeded"],ignoreCodes:["VALIDATION_ERROR"]}}),bugsnag:(Y,Z="production")=>({enabled:!0,service:"bugsnag",apiKey:Y,environment:Z,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class dY{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(Y){this.config=Y,this.initializeHealthChecks()}initializeHealthChecks(){for(let[Y,Z]of Object.entries(this.config.healthChecks)){if(!Z.enabled)continue;this.healthStatus.set(Y,{name:Y,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let $=setInterval(()=>this.performHealthCheck(Y,Z),Z.interval);$.unref?.(),this.healthCheckIntervals.set(Y,$)}}async performHealthCheck(Y,Z){let $=Date.now(),X=!1;try{let Q=new AbortController,_=setTimeout(()=>Q.abort(),Z.timeout),j=await fetch(Z.endpoint,{signal:Q.signal,headers:Z.headers,method:"GET"});if(clearTimeout(_),X=Z.expectedStatus.includes(j.status),X&&Z.expectedBody){let G=await j.text();if(typeof Z.expectedBody==="string")X=G.includes(Z.expectedBody);else X=Z.expectedBody.test(G)}}catch(Q){console.error(Q),X=!1}let J=Date.now()-$;if(this.updateHealthStatus(Y,X,J),X&&Z.onHealthy)Z.onHealthy();else if(!X&&Z.onUnhealthy)Z.onUnhealthy(Error(`Health check failed for ${Y}`))}updateHealthStatus(Y,Z,$){let X=this.healthStatus.get(Y);if(!X)return;let J={...X,lastCheck:new Date,responseTime:$,consecutiveFailures:Z?0:X.consecutiveFailures+1};if(J.consecutiveFailures===0)J.status="healthy";else if(J.consecutiveFailures<3)J.status="degraded";else J.status="unhealthy";let Q=Z?1:0;J.availability=X.availability*0.9+Q*10,this.healthStatus.set(Y,J)}getServiceHealth(Y){return this.healthStatus.get(Y)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(Y){return this.healthStatus.get(Y)?.status==="healthy"}isServiceDegraded(Y){return this.healthStatus.get(Y)?.status==="degraded"}stop(){for(let Y of this.healthCheckIntervals.values())clearInterval(Y);this.healthCheckIntervals.clear()}}class ZY{config;healthMonitor;cache=new Map;metrics=new Map;constructor(Y){this.config=Y,this.healthMonitor=new dY(Y)}async handleFailure(Y,Z,$,X){if(!this.config.enabled)throw Z;let J=this.config.fallbackStrategies[Y];if(!J)throw Z;let Q={request:$,serviceName:Y,error:Z,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(J,Q,X)}async executeFallbackStrategy(Y,Z,$){if(Z.attemptCount<=Y.retries)try{if(Z.attemptCount>1){let Q=this.calculateBackoffDelay(Y.backoff,Z.attemptCount);await this.sleep(Q)}let X=new Promise((Q,_)=>{setTimeout(()=>_(Error("Timeout")),Y.timeout)}),J=await Promise.race([$(),X]);return this.updateMetrics(Z.serviceName,!0,Date.now()-Z.startTime.getTime()),J}catch(X){if(console.error(X),Z.attemptCount++,Z.attemptCount<=Y.retries)return this.executeFallbackStrategy(Y,Z,$)}switch(this.updateMetrics(Z.serviceName,!1,Date.now()-Z.startTime.getTime()),Y.type){case"cache":return this.handleCacheFallback(Y,Z);case"static":return this.handleStaticFallback(Y,Z);case"simplified":return this.handleSimplifiedFallback(Y,Z);case"redirect":return this.handleRedirectFallback(Y,Z);case"custom":return this.handleCustomFallback(Y,Z);default:throw Z.error}}async handleCacheFallback(Y,Z){if(!Y.cacheConfig)throw Z.error;let $=this.generateCacheKey(Y.cacheConfig.key,Z),X=this.cache.get($);if(X&&(X.expires>new Date||Y.cacheConfig.staleWhileRevalidate)){let J=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(Z.serviceName)?.status||"unknown"});if(Y.cacheConfig.staleWhileRevalidate&&X.expires<=new Date)J.set("X-Cache","STALE");return new Response(JSON.stringify(X.data),{status:200,headers:J})}throw Z.error}async handleStaticFallback(Y,Z){if(!Y.staticResponse)throw Z.error;let $=new Headers(Y.staticResponse.headers||{});return $.set("X-Degraded","true"),$.set("X-Fallback-Type","static"),$.set("X-Service-Status",this.healthMonitor.getServiceHealth(Z.serviceName)?.status||"unknown"),new Response(typeof Y.staticResponse.body==="string"?Y.staticResponse.body:JSON.stringify(Y.staticResponse.body),{status:Y.staticResponse.status,headers:$})}async handleSimplifiedFallback(Y,Z){let $={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:Z.request.requestId};return new Response(JSON.stringify($),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(Z.serviceName)?.status||"unknown"}})}async handleRedirectFallback(Y,Z){if(!Y.redirectConfig)throw Z.error;return new Response(null,{status:Y.redirectConfig.permanent?301:302,headers:{Location:Y.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(Y,Z){if(!Y.fallbackHandler)throw Z.error;try{let $=await Y.fallbackHandler(Z.error,Z.error.context);return $.headers.set("X-Degraded","true"),$.headers.set("X-Fallback-Type","custom"),$.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(Z.serviceName)?.status||"unknown"),$}catch($){throw console.error($),Z.error}}cacheResponse(Y,Z,$,X){let J=this.config.fallbackStrategies[Y];if(J?.type==="cache"&&J.cacheConfig){let Q=this.generateCacheKey(Z,{serviceName:Y});this.cache.set(Q,{data:$,expires:new Date(Date.now()+X*1000)})}}getServiceMetrics(Y){let Z=this.metrics.get(Y);if(!Z||Z.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:Z.errors/Z.requests*100,avgResponseTime:Z.totalTime/Z.requests,totalRequests:Z.requests}}getSystemHealth(){let Y=this.healthMonitor.getAllServiceHealth(),Z=Y.filter((J)=>J.status==="unhealthy").length,$=Y.filter((J)=>J.status==="degraded").length,X="healthy";if(Z>0)X=Z>Y.length/2?"unhealthy":"degraded";else if($>0)X="degraded";return{status:X,services:Y}}calculateBackoffDelay(Y,Z){if(Y.type==="fixed")return Y.delay;let $=Y.delay*2**(Z-1);return Math.min($,Y.maxDelay||30000)}generateCacheKey(Y,Z){return Y.replace("{service}",Z.serviceName).replace("{url}",Z.request.url).replace("{method}",Z.request.method).replace("{userId}",String(Z.request.user?.id||"anonymous"))}updateMetrics(Y,Z,$){let X=this.metrics.get(Y)||{requests:0,errors:0,totalTime:0};if(X.requests++,X.totalTime+=$,!Z)X.errors++;this.metrics.set(Y,X)}sleep(Y){return new Promise((Z)=>setTimeout(Z,Y))}stop(){this.healthMonitor.stop()}}function a8(Y){let Z=new ZY(Y);return async($,X)=>{try{let J=await X(),Q=$.context?.serviceName;if(Q&&J.ok){let _=Y.fallbackStrategies[Q];if(_?.type==="cache"&&_.cacheConfig)try{let j=await J.clone().json();Z.cacheResponse(Q,_.cacheConfig.key,j,_.cacheConfig.ttl)}catch{}}return J}catch(J){let Q=$.context?.serviceName;if(Q&&J instanceof Error){let _=J;try{return await Z.handleFailure(Q,_,$,X)}catch(j){throw console.error(j),J}}throw J}}}var t8={cacheFirst:(Y=3600,Z=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:Y,staleWhileRevalidate:Z}}),staticFallback:(Y,Z=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:Z,body:Y,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(Y)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:Y,permanent:!1}})};class EZ{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(Y={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...Y},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new YY(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new ZY(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new n;for(let Y of this.config.circuitBreakers)this.circuitBreakerRegistry.register(Y)}}middleware(){return async(Y,Z)=>{try{let $={requestId:Y.requestId,userId:Y.user?.id,traceId:Y.traceId,spanId:Y.spanId,route:Y.params?.route||Y.url,method:Y.method,url:Y.url,userAgent:Y.userAgent?.()||void 0,ip:Y.ip?.()||void 0,timestamp:new Date};if(Y.context={...Y.context,errorContext:$},this.circuitBreakerRegistry&&Y.context?.serviceName){let X=this.circuitBreakerRegistry.get(Y.context.serviceName);if(X)return await X.execute({execute:Z,context:$})}return await Z()}catch($){return this.handleError($,Y)}}}async handleError(Y,Z){let $=this.normalizeError(Y,Z);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${Z.method} ${Z.url}`,"error",{code:$.code,severity:$.severity,statusCode:$.statusCode});if(this.config.logErrors)this.logError($,Z);if(this.gracefulDegradation&&Z.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(Z.context.serviceName,$,Z,async()=>{throw $})}catch{}if(this.errorReporting)try{await this.errorReporting.report($,$.context)}catch(J){console.error("Failed to report error:",J)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler($,Z)}catch(J){console.error("Global error handler failed:",J)}let X=this.config.customErrorPages?.[$.statusCode];if(X)try{if(typeof X==="string")return new Response(X,{status:$.statusCode,headers:{"Content-Type":"text/html"}});else return await X($,Z)}catch(J){console.error("Custom error page failed:",J)}return this.createErrorResponse($,Z)}normalizeError(Y,Z){let $={requestId:Z.requestId,userId:Z.user?.id,traceId:Z.traceId,spanId:Z.spanId,route:Z.params?.route||Z.url,method:Z.method,url:Z.url,userAgent:Z.userAgent?.()||void 0,ip:Z.ip?.()||void 0,timestamp:new Date,metadata:Z.context};if(Y instanceof lY)return Y;if(Y instanceof Error){if(Y.name==="ValidationError")return v.validation(Y.message,{},$);if(Y.name==="UnauthorizedError"||Y.message.includes("unauthorized"))return v.authentication(Y.message,$);if(Y.name==="ForbiddenError"||Y.message.includes("forbidden"))return v.authorization(Y.message,[],$);if(Y.name==="NotFoundError"||Y.message.includes("not found"))return v.notFound(void 0,void 0,$);if(Y.name==="TimeoutError"||Y.message.includes("timeout"))return v.timeout(30000,Y.message,$);return v.internalServer(Y.message,Y,$)}if(typeof Y==="string")return v.internalServer(Y,void 0,$);return v.internalServer("An unknown error occurred",void 0,$)}createErrorResponse(Y,Z){let $=this.config.development,X=this.config.includeStackTrace||$,J=this.config.sanitizeErrors&&!$,Q=Y.message;if(J&&Y.statusCode>=500)Q="An internal server error occurred";let _={error:{code:Y.code,message:Q,statusCode:Y.statusCode,timestamp:Y.timestamp.toISOString(),requestId:Y.context.requestId,traceId:Y.context.traceId}};if($)_.error.category=Y.category,_.error.severity=Y.severity,_.error.retryable=Y.retryable,_.error.context=Y.context;if(X){if(_.error.stack=Y.stack,Y.cause)_.error.cause={name:Y.cause.name,message:Y.cause.message,stack:Y.cause.stack}}if("fields"in Y)_.error.fields=Y.fields;if("allowedMethods"in Y)_.error.allowedMethods=Y.allowedMethods;if("retryAfter"in Y)_.error.retryAfter=Y.retryAfter;let j=new Headers({"Content-Type":"application/json","X-Error-Code":Y.code,"X-Request-ID":Y.context.requestId||"","X-Trace-ID":Y.context.traceId||""});if("allowedMethods"in Y)j.set("Allow",Y.allowedMethods.join(", "));if("retryAfter"in Y)j.set("Retry-After",Y.retryAfter.toString());if("limit"in Y)j.set("X-RateLimit-Limit",Y.limit.toString()),j.set("X-RateLimit-Remaining",Y.remaining.toString());return new Response(JSON.stringify(_),{status:Y.statusCode,headers:j})}logError(Y,Z){let $={error:Y.toJSON(),request:{method:Z.method,url:Z.url,headers:Object.fromEntries(Z.headers.entries()),userAgent:Z.userAgent?.()||void 0,ip:Z.ip?.()||void 0,requestId:Z.requestId,traceId:Z.traceId}};switch(Y.severity){case"critical":console.error("[CRITICAL ERROR]",$);break;case"high":console.error("[ERROR]",$);break;case"medium":console.warn("[WARNING]",$);break;case"low":console.warn("[INFO]",$);break;default:console.error("[ERROR]",$)}}getStats(){return{errorReporting:this.errorReporting?{breadcrumbs:this.errorReporting.getBreadcrumbs().length}:void 0,gracefulDegradation:this.gracefulDegradation?this.gracefulDegradation.getSystemHealth():void 0,circuitBreakers:this.circuitBreakerRegistry?this.circuitBreakerRegistry.getAllMetrics():void 0}}async cleanup(){if(this.errorReporting)await this.errorReporting.close();if(this.gracefulDegradation)this.gracefulDegradation.stop()}}function IZ(Y={}){let Z=new EZ(Y);return{middleware:Z.middleware(),getStats:()=>Z.getStats(),cleanup:()=>Z.cleanup()}}import{AsyncLocalStorage as O9}from"async_hooks";var iY=new O9,FY=!1,p=null;function H9(){FY=!0}function BY(Y,Z){if(!FY){p=Y;let $=Z();if($ instanceof Promise)return $.finally(()=>{p=null});return p=null,$}return iY.run({current:Y},Z)}function NY(Y){let Z=iY.getStore();if(Z){Z.current=Y;return}if(p!==null)p=Y}function HZ(){if(!FY)return FY=!0,p??void 0;return iY.getStore()?.current??p??void 0}function F9(){let Y=HZ();if(!Y)throw Error("request() called outside a request scope. It can only be invoked from within a route handler or middleware.");return Y}var B9={enabled:!0,level:6,threshold:1024};function FZ(Y){if(!Y)return!1;let Z=Y.split(";")[0]?.trim().toLowerCase()??"";if(Z==="text/event-stream")return!1;if(Z.startsWith("text/"))return!0;return["application/json","application/ld+json","application/manifest+json","application/javascript","application/x-javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/graphql","application/x-ndjson","image/svg+xml"].includes(Z)}function N9(Y){if(!Y)return null;let Z=new Map;for(let X of Y.split(",")){let[J="",...Q]=X.trim().split(";"),_=Q.map((j)=>/^\s*q=([\d.]+)\s*$/i.exec(j)).find(Boolean);Z.set(J.trim().toLowerCase(),_?Number(_[1]):1)}let $=(X)=>(Z.get(X)??Z.get("*")??0)>0;if($("gzip"))return"gzip";if($("deflate"))return"deflate";return null}function S9(Y,Z,$){if(!Z)return!1;if(Y.status===204||Y.status===304||Y.status===206)return!1;if(Y.headers.has("content-encoding"))return!1;if(!FZ(Y.headers.get("content-type")))return!1;if(!Y.body)return!1;let X=Number(Y.headers.get("content-length")??Number.NaN);return Number.isFinite(X)?X>=$:!0}async function BZ(Y,Z,$={}){let X={...B9,...$};if(!X.enabled)return Y;let J=N9(Z.headers.get("accept-encoding"));if(!S9(Y,J,X.threshold)){if(FZ(Y.headers.get("content-type"))&&!Y.headers.has("content-encoding"))nY(Y.headers,"Accept-Encoding");return Y}let Q=Number(Y.headers.get("content-length")??Number.NaN),_=Number.isFinite(Q)?{stream:Y.body,size:Q,ended:!1}:await C9(Y.body,X.threshold);if(_.ended&&_.size<X.threshold){let W=new Headers(Y.headers);return nY(W,"Accept-Encoding"),new Response(_.stream,{status:Y.status,statusText:Y.statusText,headers:W})}let j=new Headers(Y.headers);j.set("Content-Encoding",J),nY(j,"Accept-Encoding"),j.delete("Content-Length");let G=_.stream.pipeThrough(new CompressionStream(J==="gzip"?"gzip":"deflate"));return new Response(G,{status:Y.status,statusText:Y.statusText,headers:j})}async function C9(Y,Z){let $=Y.getReader(),X=[],J=0,Q=!1;while(J<Z){let{value:j,done:G}=await $.read();if(G){Q=!0;break}if(j)X.push(j),J+=j.byteLength}return{stream:new ReadableStream({start(j){for(let G of X)j.enqueue(G);if(Q)j.close()},async pull(j){if(Q)return;let{value:G,done:W}=await $.read();if(W){Q=!0,j.close();return}if(G)j.enqueue(G)},cancel(j){return $.cancel(j)}}),size:J,ended:Q}}function nY(Y,Z){let $=Y.get("vary");if(!$){Y.set("Vary",Z);return}let X=$.split(",").map((J)=>J.trim().toLowerCase());if(X.includes("*")||X.includes(Z.toLowerCase()))return;Y.set("Vary",`${$}, ${Z}`)}var E={json:(Y,Z={})=>{let $=typeof Z==="number"?{status:Z}:Z,{status:X=200,headers:J={},pretty:Q=!1}=$,_=Q?JSON.stringify(Y,null,2):JSON.stringify(Y);return new Response(_,{status:X,headers:{"Content-Type":"application/json",...J}})},noContent:(Y={})=>{return new Response(null,{status:204,headers:Y})},download:async(Y,Z,$={})=>{let X=Bun.file(Y);if(!await X.exists())return new Response("File not found",{status:404});let Q=Z||Y.split("/").pop()||"download",_=X.type||"application/octet-stream";return new Response(X,{status:200,headers:{"Content-Type":_,"Content-Disposition":`attachment; filename="${Q}"`,"Content-Length":String(X.size),...$}})},file:async(Y,Z={})=>{let $=Bun.file(Y);if(!await $.exists())return new Response("File not found",{status:404});let J=$.type||"application/octet-stream";return new Response($,{status:200,headers:{"Content-Type":J,"Content-Length":String($.size),...Z}})},streamDownload:(Y,Z,$={})=>{let{contentType:X="application/octet-stream",headers:J={}}=$,Q=new ReadableStream({async start(_){try{for await(let j of Y())if(typeof j==="string")_.enqueue(new TextEncoder().encode(j));else _.enqueue(j);_.close()}catch(j){_.error(j)}}});return new Response(Q,{status:200,headers:{"Content-Type":X,"Content-Disposition":`attachment; filename="${Z}"`,"Transfer-Encoding":"chunked",...J}})},redirect:(Y,Z=302)=>{return new Response(null,{status:Z,headers:{Location:Y}})},redirectPermanent:(Y)=>{return E.redirect(Y,301)},redirectTemporary:(Y)=>{return E.redirect(Y,302)},back:(Y,Z="/")=>{let $=Y.headers.get("referer")||Z;return E.redirect($)},view:(Y,Z=200,$={})=>{return new Response(Y,{status:Z,headers:{"Content-Type":"text/html; charset=utf-8",...$}})},text:(Y,Z=200,$={})=>{return new Response(Y,{status:Z,headers:{"Content-Type":"text/plain; charset=utf-8",...$}})},xml:(Y,Z=200,$={})=>{return new Response(Y,{status:Z,headers:{"Content-Type":"application/xml; charset=utf-8",...$}})},success:(Y,Z,$=200)=>{let X={success:!0};if(Y!==void 0)X.data=Y;if(Z!==void 0)X.message=Z;return E.json(X,{status:$})},error:(Y,Z=400,$)=>{let X={success:!1,message:Y};if($!==void 0)X.errors=$;return E.json(X,{status:Z})},paginate:(Y,Z)=>{let{page:$,perPage:X,total:J,path:Q}=Z,_=Math.ceil(J/X),j=($-1)*X+1,G=Math.min($*X,J);return E.json({data:Y,meta:{current_page:$,per_page:X,total:J,last_page:_,from:j,to:G,path:Q,first_page_url:`${Q}?page=1`,last_page_url:`${Q}?page=${_}`,next_page_url:$<_?`${Q}?page=${$+1}`:null,prev_page_url:$>1?`${Q}?page=${$-1}`:null}})},created:(Y,Z)=>{let $={};if(Z)$.Location=Z;let X={success:!0};if(Y!==void 0)X.data=Y;return E.json(X,{status:201,headers:$})},accepted:(Y)=>{let Z={success:!0};if(Y!==void 0)Z.data=Y;return E.json(Z,{status:202})},notFound:(Y="Resource not found")=>{return E.error(Y,404)},unauthorized:(Y="Unauthorized")=>{return E.error(Y,401)},forbidden:(Y="Forbidden")=>{return E.error(Y,403)},badRequest:(Y="Bad request",Z)=>{return E.error(Y,400,Z)},validationError:(Y,Z="Validation failed")=>{return E.error(Z,422,Y)},unprocessableEntity:(Y="Unprocessable entity",Z)=>{return E.error(Y,422,Z)},serverError:(Y="Internal server error")=>{return E.error(Y,500)},tooManyRequests:(Y="Too many requests",Z)=>{let $={};if(Z)$["Retry-After"]=String(Z);return new Response(JSON.stringify({message:Y}),{status:429,headers:{"Content-Type":"application/json",...$}})}};class NZ{_status=200;_headers={};_cookies=[];_deleteCookies=[];status(Y){return this._status=Y,this}header(Y,Z){return this._headers[Y]=Z,this}withHeaders(Y){return this._headers={...this._headers,...Y},this}cookie(Y,Z,$={}){return this._cookies.push({name:Y,value:Z,options:$}),this}withoutCookie(Y,Z={}){return this._deleteCookies.push({name:Y,options:Z}),this}json(Y){let Z=E.json(Y,{status:this._status,headers:this._headers});return this.applyCookies(Z)}text(Y){let Z=E.text(Y,this._status,this._headers);return this.applyCookies(Z)}html(Y){let Z=E.view(Y,this._status,this._headers);return this.applyCookies(Z)}noContent(){let Y=E.noContent(this._headers);return this.applyCookies(Y)}applyCookies(Y){let Z=new Headers(Y.headers);for(let{name:$,value:X,options:J}of this._cookies){let Q=this.serializeCookie($,X,J);Z.append("Set-Cookie",Q)}for(let{name:$,options:X}of this._deleteCookies){let J=this.serializeCookie($,"",{...X,maxAge:0,expires:new Date(0)});Z.append("Set-Cookie",J)}return new Response(Y.body,{status:Y.status,headers:Z})}serializeCookie(Y,Z,$){let X=`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`;if($.maxAge!==void 0)X+=`; Max-Age=${$.maxAge}`;if($.expires)X+=`; Expires=${$.expires.toUTCString()}`;if($.httpOnly)X+="; HttpOnly";if($.secure)X+="; Secure";if($.path)X+=`; Path=${$.path}`;if($.domain)X+=`; Domain=${$.domain}`;if($.sameSite)X+=`; SameSite=${$.sameSite.charAt(0).toUpperCase()+$.sameSite.slice(1)}`;return X}}function K6(){return new NZ}import M9 from"process";class sY{compiledPipelines=new Map;dependencyRegistry=new Map;singletonInstances=new Map;stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0};registerDependency(Y){this.dependencyRegistry.set(Y.name,Y)}compileMiddleware(Y,Z,$=[]){let X=[];for(let J=0;J<Z.length;J++){let Q=Z[J],_=Q.name||`middleware_${J}`;X.push({handler:Q,name:_,skipConditions:$.filter((j)=>j.name.includes(_)||j.name==="global"),dependencies:this.extractDependencies(Q),canShortCircuit:this.canShortCircuit(Q),priority:J})}this.compiledPipelines.set(Y,X)}async execute(Y,Z,$){let X=performance.now();this.stats.totalExecutions++;let J=this.compiledPipelines.get(Y);if(!J)return this.stats.cacheMisses++,await $();this.stats.cacheHits++;let Q={request:Z,dependencies:new Map,metadata:{}};await this.resolveDependencies(Q,J);let _=0,j=async()=>{if(_>=J.length)return await $();let K=J[_++];if(await this.shouldSkip(K,Q))return this.stats.skippedMiddleware++,await j();let z=await K.handler(Z,j);if(z instanceof Response&&K.canShortCircuit)return this.stats.shortCircuits++,z;return z},G=await j(),W=performance.now()-X;return this.updateAverageExecutionTime(W),G||new Response("Internal Server Error",{status:500})}async shouldSkip(Y,Z){for(let $ of Y.skipConditions)if(await $.condition(Z))return!0;return!1}async resolveDependencies(Y,Z){let $=new Set;for(let X of Z)for(let J of X.dependencies)$.add(J);for(let X of $){let J=this.dependencyRegistry.get(X);if(!J)continue;if(this.stats.dependencyResolutions++,J.singleton&&this.singletonInstances.has(X))Y.dependencies.set(X,this.singletonInstances.get(X));else{let Q=await J.factory(Y);if(Y.dependencies.set(X,Q),J.singleton)this.singletonInstances.set(X,Q)}}}extractDependencies(Y){let Z=Y.toString(),$=[];if(Z.includes("database")||Z.includes("db"))$.push("database");if(Z.includes("logger")||Z.includes("log"))$.push("logger");if(Z.includes("cache"))$.push("cache");if(Z.includes("httpClient")||Z.includes("http"))$.push("httpClient");return $}canShortCircuit(Y){let Z=Y.toString();return Z.includes("return")&&Z.includes("Response")}updateAverageExecutionTime(Y){let Z=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(Z+Y)/this.stats.totalExecutions}getStats(){return{...this.stats}}clear(){this.compiledPipelines.clear(),this.singletonInstances.clear(),this.stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0}}}var T9={skipForMethods:(Y)=>({name:`skip_for_methods_${Y.join("_")}`,condition:(Z)=>Y.includes(Z.request.method)}),skipForPaths:(Y)=>({name:`skip_for_paths_${Y.join("_").replace(/\//g,"_")}`,condition:(Z)=>{let $=new URL(Z.request.url);return Y.some((X)=>$.pathname.startsWith(X))}}),skipForHeaders:(Y)=>({name:`skip_for_headers_${Object.keys(Y).join("_")}`,condition:(Z)=>{return Object.entries(Y).some(([$,X])=>Z.request.headers.get($)===X)}}),skipForRoles:(Y)=>({name:`skip_for_roles_${Y.join("_")}`,condition:(Z)=>{let $=Z.request.user?.roles||[];return!Y.some((X)=>$.includes(X))}}),skipForEnvironment:(Y)=>({name:`skip_for_env_${Y.join("_")}`,condition:()=>{let Z=M9.env.NODE_ENV||"development";return Y.includes(Z)}})},P9={database:(Y)=>({name:"database",factory:async()=>{return{query:async(Z)=>({rows:[]}),close:async()=>{},connectionString:Y||"mock://database"}},singleton:!0}),logger:(Y="info")=>({name:"logger",factory:()=>({info:(Z)=>console.log(`[INFO] ${Z}`),error:(Z)=>console.error(`[ERROR] ${Z}`),warn:(Z)=>console.warn(`[WARN] ${Z}`),debug:(Z)=>console.debug(`[DEBUG] ${Z}`),level:Y}),singleton:!0}),cache:(Y=1000)=>({name:"cache",factory:()=>{let Z=new Map;return{get:($)=>Z.get($),set:($,X)=>{if(Z.size>=Y){let J=Z.keys().next().value;Z.delete(J)}Z.set($,X)},delete:($)=>Z.delete($),clear:()=>Z.clear(),size:()=>Z.size}},singleton:!0}),httpClient:(Y)=>({name:"httpClient",factory:()=>({get:async(Z)=>fetch(Y?`${Y}${Z}`:Z),post:async(Z,$)=>fetch(Y?`${Y}${Z}`:Z,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),put:async(Z,$)=>fetch(Y?`${Y}${Z}`:Z,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),delete:async(Z)=>fetch(Y?`${Y}${Z}`:Z,{method:"DELETE"})}),singleton:!0})},b9={auth:(Y={})=>{return async(Z,$)=>{let X=new URL(Z.url);if(Y.skipPaths?.some((Q)=>X.pathname.startsWith(Q)))return await $();if(!Z.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return Z.user={id:"123",roles:["user"]},await $()}catch{return new Response("Invalid token",{status:401})}}},rateLimit:(Y)=>{let Z=new Map;return async($,X)=>{let J=$.headers.get("x-forwarded-for")||"unknown",Q=Date.now(),_=Q-Y.windowMs;if(!Z.has(J))Z.set(J,[]);let G=Z.get(J).filter((W)=>W>_);if(G.length>=Y.maxRequests)return new Response("Too Many Requests",{status:429});return G.push(Q),Z.set(J,G),await X()}},cors:(Y={})=>{return async(Z,$)=>{let X=await $();if(X){let J=new Headers(X.headers);return J.set("Access-Control-Allow-Origin",Y.origin||"*"),J.set("Access-Control-Allow-Methods",Y.methods?.join(", ")||"GET, POST, PUT, DELETE"),J.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(X.body,{status:X.status,statusText:X.statusText,headers:J})}return X}},logging:(Y={})=>{return async(Z,$)=>{let X=performance.now(),J=new URL(Z.url);console.log(`[${new Date().toISOString()}] ${Z.method} ${J.pathname}`);let Q=await $(),_=performance.now()-X;if(Q)console.log(`[${new Date().toISOString()}] ${Z.method} ${J.pathname} - ${Q.status} (${_.toFixed(2)}ms)`);return Q}}},x9=new sY;import{existsSync as CZ,readdirSync as R9,statSync as w9}from"fs";import{basename as MZ,extname as SZ,join as k9,resolve as TZ}from"path";var v9=[".ts",".js"],q9=["routes","src/routes"],f9=["web","index"];function y9(){let Y=process.cwd();for(let Z of q9){let $=TZ(Y,Z);if(CZ($)&&w9($).isDirectory())return $}return null}function PZ(Y,Z){let $=[];if(!CZ(Y))return $;let X=R9(Y,{withFileTypes:!0});for(let J of X){if(J.name.startsWith(".")||J.name.startsWith("_"))continue;let Q=k9(Y,J.name);if(J.isDirectory())$.push(...PZ(Q,Z));else if(v9.includes(SZ(J.name))){let _=Y===Z?"":Y.slice(Z.length),j=MZ(J.name,SZ(J.name)),G=f9.includes(j)?_||"":`${_}/${j}`;$.push({filePath:Q,prefix:G})}}return $}async function g9(Y,Z,$,X){try{let J=await import(Z),Q=0,_=Y.routes?.length||0;if(typeof J.default==="function"){let j=h9(Y,$);await J.default(j),Q=(Y.routes?.length||0)-_}else if(Array.isArray(J.routes))for(let j of J.routes){let G=(j.method||"GET").toLowerCase(),W=`${$}${j.path}`;if(typeof Y[G]==="function")await Y[G](W,j.handler),Q++}if(X&&Q>0)console.log(` ${$||"/"} \u2192 ${MZ(Z)} (${Q} routes)`);return Q}catch(J){return console.error(`[bun-router] Failed to load route file ${Z}:`,J),0}}function h9(Y,Z){if(!Z)return Y;let $=["get","post","put","patch","delete","options","any"];return new Proxy(Y,{get(X,J){if($.includes(J))return async(Q,..._)=>{return X[J](`${Z}${Q}`,..._)};if(J==="group")return async(Q,_)=>{let j=Q.prefix?`${Z}${Q.prefix}`:Z;return X.group({...Q,prefix:j},_)};return X[J]}})}function bZ(Y){Object.defineProperties(Y.prototype,{_routesDir:{value:null,writable:!0,configurable:!0},_apiRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initApiRoutes:{async value(){if(this._apiRoutesInitialized)return;let Z=this._routesDir||y9();if(!Z){this._apiRoutesInitialized=!0;return}let $=this.config?.verbose||!1,X=PZ(Z,Z);if(X.length===0){this._apiRoutesInitialized=!0;return}if($)console.log(`[bun-router] Auto-discovering API routes from ${Z}:`);let J=0;for(let{filePath:Q,prefix:_}of X)J+=await g9(this,Q,_,$);if(J>0&&$)console.log(`[bun-router] Registered ${J} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(Z){return this._routesDir=TZ(Z),this},writable:!0,configurable:!0}})}import{join as XY,relative as oY,resolve as q,dirname as p9}from"path";import{readdirSync as xZ,statSync as m9,existsSync as CY}from"fs";var E6={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function c9(Y){let{preserve:Z=[],exclude:$=[],routes:X=[]}=Y;if(!Z.length)return"";return`<script data-query-preservation>
|
|
2
|
+
import{$o as Fc,Ap as ll,Bp as dl,Cp as pl,Dp as hl,Ep as gl,Fp as ml,Gp as fl,Hp as yl,Ip as Rl,Jp as wl,Kp as bl,Lp as Tl,Mp as xl,Np as vl,Op as Cl,Pp as Pl,Qo as Ec,Qp as El,Ro as Mc,Rp as Ml,So as Sc,Sp as Sl,To as kc,Tp as kl,Uo as Hc,Up as Hl,Vo as Ac,Vp as Al,Wo as qc,Wp as ql,Xo as Oc,Xp as Ol,Yo as $c,Yp as $l,Zo as Bc,Zp as Bl,_o as Dc,ap as Uc,bp as Nc,cp as Ic,dp as _c,ep as jc,fp as Lc,gp as zc,hp as Gc,ip as Wc,jp as Vc,kp as Jc,lp as Kc,mp as Xc,np as Qc,op as Zc,pp as Yc,qp as el,rp as tl,sp as rl,tp as nl,up as sl,vp as il,wp as ol,xp as al,yp as ul,zp as cl}from"./chunk-vcp8dnjq.js";import"./chunk-p0qhpnqh.js";import{$q as ln,Br as Ys,Gr as ei,Sq as We,Tq as ne,Uq as nn,Vq as sn,Wq as on,Xq as an,Yq as Re,Zq as un,_q as cn,ar as dn,br as be,cr as we,dr as pn,er as hn,fr as gn,gr as B,hr as mn,ir as fn,jr as yn,kr as Rn,lr as wn,mr as bn,nr as Tn,or as xn,pr as vn,ur as Vs,vr as Js,wr as Ks,xr as Xs,yr as Qs,zr as Zs}from"./chunk-3y4gaz7v.js";import{Yu as rn,Zu as je}from"./chunk-nf3kv7kv.js";import{timingSafeEqual as zr}from"crypto";function Ie(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ye(e){e=e.replace(/-/g,"+").replace(/_/g,"/");while(e.length%4)e+="=";return atob(e)}class gt{secret;constructor(e){this.secret=e}sign(e,t={}){let r={alg:t.algorithm||"HS256",typ:"JWT",...t.header},n=Math.floor(Date.now()/1000),s={...e,iat:n};if(t.expiresIn){let c=typeof t.expiresIn==="string"?this.parseTimespan(t.expiresIn):t.expiresIn;s.exp=n+c}if(t.notBefore){let c=typeof t.notBefore==="string"?this.parseTimespan(t.notBefore):t.notBefore;s.nbf=n+c}if(t.issuer)s.iss=t.issuer;if(t.subject)s.sub=t.subject;if(t.audience)s.aud=t.audience;if(t.jwtid)s.jti=t.jwtid;let i=Ie(JSON.stringify(r)),o=Ie(JSON.stringify(s)),a=`${i}.${o}`,u=this.createSignature(a,this.secret,r.alg);return`${a}.${u}`}verify(e,t={}){try{let r=e.split(".");if(r.length!==3)throw Error("Token structure invalid");let[n,s,i]=r,o=JSON.parse(ye(n)),a=JSON.parse(ye(s));if(t.algorithms&&!t.algorithms.includes(o.alg))throw Error(`Algorithm ${o.alg} not allowed`);let u=`${n}.${s}`,c=this.createSignature(u,this.secret,o.alg),l=Buffer.from(i),d=Buffer.from(c);if(l.length!==d.length||!zr(l,d))throw Error("Invalid signature");let p=Math.floor(Date.now()/1000);if(a.exp&&!t.ignoreExpiration&&p>=a.exp)throw Error("Token expired");if(a.nbf&&p<a.nbf)throw Error("Token not active yet");if(a.iat&&a.iat>p)throw Error("Token used before issued");if(t.issuer&&a.iss!==t.issuer)throw Error("Invalid issuer");if(t.audience&&a.aud!==t.audience)throw Error("Invalid audience");if(t.subject&&a.sub!==t.subject)throw Error("Invalid subject");return a}catch{return null}}decode(e){try{let t=e.split(".");if(t.length!==3)return null;let[r,n]=t;return{header:JSON.parse(ye(r)),payload:JSON.parse(ye(n))}}catch{return null}}createSignature(e,t,r){return Ie(JSON.stringify({data:e,secret:t.slice(0,5),alg:r}))}parseTimespan(e){let t=e.match(/^(\d+)\s*([smhd])$/i);if(!t)return Number.parseInt(e,10)||0;let r=Number.parseInt(t[1],10);switch(t[2].toLowerCase()){case"s":return r;case"m":return r*60;case"h":return r*60*60;case"d":return r*24*60*60;default:return r}}}class mt{keys;options;constructor(e={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...e}}generateKey(e,t=[],r){let n=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(n,{owner:e,scopes:t,expiresAt:r?new Date(Date.now()+r*1000):void 0}),n}validateKey(e,t=[]){let r=this.keys.get(e);if(!r)return!1;if(r.expiresAt&&r.expiresAt<new Date)return!1;if(t.length>0)return t.every((n)=>r.scopes.includes(n));return!0}getKeyInfo(e){return this.keys.get(e)||null}revokeKey(e){return this.keys.delete(e)}extractFromRequest(e){let{source:t,keyName:r}=this.options;switch(t){case"header":return e.headers.get(r||"X-API-Key")||null;case"query":return new URL(e.url).searchParams.get(r||"api_key")||null;case"cookie":if(e.cookies){let n=r||"api_key";if(typeof e.cookies.get==="function")return e.cookies.get(n)||null;return e.cookies[n]||null}return null;default:return null}}randomString(e){let r="";for(let n=0;n<e;n++)r+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return r}}class ft{config;constructor(e){this.config=e}getAuthorizationUrl(e={}){let t=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...e});if(this.config.scope)t.set("scope",this.config.scope);if(this.config.state)t.set("state",this.config.state);return`${this.config.authorizeUrl}?${t.toString()}`}async exchangeCodeForToken(e){let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),r=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!r.ok)throw Error(`OAuth token exchange failed: ${r.status} ${r.statusText}`);return await r.json()}async refreshToken(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId,client_secret:this.config.clientSecret}),r=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!r.ok)throw Error(`OAuth token refresh failed: ${r.status} ${r.statusText}`);return await r.json()}}var Gr={JWT:gt,ApiKeyManager:mt,OAuth2Helper:ft},Wr=Gr;var Tt={};rn(Tt,{AuthenticationException:()=>nn,AuthorizationException:()=>sn,BugsnagReporter:()=>ze,BusinessLogicException:()=>pn,CircuitBreaker:()=>Te,CircuitBreakerHttpClient:()=>yt,CircuitBreakerOpenException:()=>we,CircuitBreakerPresets:()=>Kr,CircuitBreakerRegistry:()=>J,CircularDependencyException:()=>fn,ConfigurationException:()=>hn,CustomReporter:()=>Rt,DatabaseException:()=>dn,DegradationStrategies:()=>tn,ErrorFactory:()=>B,ErrorReportingManager:()=>te,ErrorReportingPresets:()=>Yr,ExternalServiceException:()=>be,FileSystemException:()=>gn,GracefulDegradationManager:()=>re,HandlerResolutionException:()=>wn,InternalServerException:()=>cn,MethodNotAllowedException:()=>an,MiddlewareConfigurationException:()=>yn,ModelBindingException:()=>bn,NotFoundException:()=>on,RateLimitException:()=>un,RouteConflictException:()=>mn,RouteNotFoundException:()=>Rn,RouterErrorFactory:()=>vn,RouterException:()=>We,SentryReporter:()=>Le,ServiceHealthMonitor:()=>Ge,ServiceUnavailableException:()=>ln,TimeoutException:()=>Re,ValidationException:()=>ne,circuitBreaker:()=>Vr,createAdvancedErrorHandler:()=>bt,createCircuitBreaker:()=>Xr,createCircuitBreakerMiddleware:()=>Jr,createErrorReporting:()=>Zr,createGracefulDegradationMiddleware:()=>en,detectRouteConflicts:()=>xn,findSimilarRoutes:()=>Tn,globalCircuitBreakerRegistry:()=>_e,withCircuitBreaker:()=>Qr});class Te{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(e){let t={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...t,...e},this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},setInterval(()=>this.cleanupOldRequests(),this.config.monitoringPeriod/4).unref?.()}async execute(e){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let s=new we(this.config.name,this.nextAttemptTime,e.context);if(e.fallback)try{return await e.fallback()}catch(i){console.error(i)}throw s}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let s=new we(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),e.context);if(e.fallback)try{return await e.fallback()}catch(i){throw console.error(i),s}throw s}let t=Date.now(),r,n=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let s=e.timeout||this.config.timeout,i=new Promise((o,a)=>{setTimeout(()=>{a(new Re(`Circuit breaker timeout for ${this.config.name}`,s,e.context))},s)});return r=await Promise.race([e.execute(),i]),this.onSuccess(Date.now()-t),r}catch(s){if(n=s,this.onFailure(n,Date.now()-t),e.fallback)try{return await e.fallback()}catch(i){throw console.error(i),n}else throw n}}getState(){return this.state}getMetrics(){return{...this.metrics,state:this.state,nextAttemptTime:this.nextAttemptTime}}forceOpen(){this.transitionToOpen()}forceClosed(){this.transitionToClosed()}reset(){this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},this.recentRequests=[]}onSuccess(e){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(e),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:e}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(e,t){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,e instanceof Re)this.metrics.timeouts++;if(this.updateAverageResponseTime(t),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:t}),this.shouldTrip(e)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(e,this.config.name)}shouldTrip(e){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(e))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let t=this.getRecentRequests();if(t.length>=this.config.minimumRequests){if(t.filter((s)=>!s.success).length/t.length*100>=this.config.errorThresholdPercentage)return!0}return!1}transitionToClosed(){if(this.state="CLOSED",this.nextAttemptTime=void 0,this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToOpen(){if(this.state="OPEN",this.nextAttemptTime=new Date(Date.now()+this.config.recoveryTimeout),this.halfOpenCallCount=0,this.metrics.state=this.state,this.metrics.nextAttemptTime=this.nextAttemptTime,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToHalfOpen(){if(this.state="HALF_OPEN",this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}updateAverageResponseTime(e){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=e;else this.metrics.averageResponseTime=0.1*e+0.9*this.metrics.averageResponseTime}getRecentRequests(){let e=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((t)=>t.timestamp>e)}cleanupOldRequests(){let e=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((t)=>t.timestamp>e)}}class J{breakers=new Map;configs=new Map;register(e){let t=new Te(e);return this.breakers.set(e.name,t),this.configs.set(e.name,e),t}get(e){return this.breakers.get(e)}async execute(e,t){let r=this.breakers.get(e);if(!r)throw Error(`Circuit breaker '${e}' not found`);return r.execute(t)}getAllMetrics(){let e={};for(let[t,r]of this.breakers)e[t]=r.getMetrics();return e}getBreakersByState(e){let t=[];for(let[r,n]of this.breakers)if(n.getState()===e)t.push(r);return t}forceAllClosed(){for(let e of this.breakers.values())e.forceClosed()}resetAll(){for(let e of this.breakers.values())e.reset()}remove(e){return this.configs.delete(e),this.breakers.delete(e)}getNames(){return Array.from(this.breakers.keys())}}function Vr(e){let t=new Te(e);return function(r,n,s){let i=s.value;return s.value=async function(...o){return t.execute({execute:()=>i.apply(this,o),context:{method:n,timestamp:new Date}})},s}}class yt{registry;constructor(e){this.registry=e||new J}async fetch(e,t={}){let{circuitBreaker:r,fallback:n,context:s,...i}=t,o;if(typeof r==="string")o=r;else if(r){if(o=r.name,!this.registry.get(o))this.registry.register(r)}else if(o=`http-${new URL(e).hostname}`,!this.registry.get(o))this.registry.register({name:o,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(o,{execute:async()=>{let a=await fetch(e,i);if(a.status>=500)throw new be(`HTTP ${a.status}: ${a.statusText}`,o,e,a.status,void 0,s);return a},fallback:n,context:s})}getRegistry(){return this.registry}}function Jr(e){return async(t,r)=>{let n=t.context?.serviceName;if(!n)return r();let s=e.get(n);if(!s)return r();return s.execute({execute:r,context:{requestId:t.requestId,route:t.route,method:t.method,url:t.url}})}}var Kr={critical:(e)=>({name:e,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(e)=>({name:e,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(e)=>({name:e,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(e)=>({name:e,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(t)=>!(t.message.includes("validation")||t.message.includes("constraint"))}),externalApi:(e)=>({name:e,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(t)=>{if(t instanceof be)return t.statusCode>=500;return!0}})},_e=new J;function Xr(e){return _e.register(e)}async function Qr(e,t){return _e.execute(e,t)}class Le{config;sentry;constructor(e){this.config=e,this.initializeSentry()}async initializeSentry(){try{let e=await import("@sentry/node");e.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(t,r)=>{let n=r.originalException;if(n&&this.config.beforeSend)return this.config.beforeSend(n,n.context)?t:null;return t},ignoreErrors:this.config.filters?.ignoreErrors,denyUrls:this.config.filters?.ignoreUrls,allowUrls:this.config.filters?.allowUrls,initialScope:{tags:this.config.tags,extra:this.config.extra,user:this.config.user},maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||100,tracesSampleRate:this.config.performance?.tracesSampleRate||0.1}),this.sentry=e}catch(e){console.warn("Failed to initialize Sentry:",e)}}async report(e,t){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(e))return null;let r={...e.context,...t};return this.sentry.withScope((n)=>{if(r.requestId)n.setTag("requestId",r.requestId);if(r.userId)n.setUser({id:r.userId});if(r.traceId)n.setTag("traceId",r.traceId);if(r.route)n.setTag("route",r.route);if(r.method)n.setTag("method",r.method);n.setTag("errorCode",e.code),n.setTag("severity",e.severity),n.setTag("category",e.category),n.setLevel(this.mapSeverityToLevel(e.severity)),n.setExtra("statusCode",e.statusCode),n.setExtra("retryable",e.retryable),n.setExtra("timestamp",e.timestamp),n.setExtra("context",r);let s=this.generateFingerprint(e);if(s.length>0)n.setFingerprint(s);return this.sentry.captureException(e)})}catch(r){return console.error("Failed to report error to Sentry:",r),null}}addBreadcrumb(e,t="default",r="info",n){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:e,category:t,level:r,data:n,timestamp:Date.now()/1000})}setUser(e){if(!this.sentry)return;this.sentry.setUser(e)}setTag(e,t){if(!this.sentry)return;this.sentry.setTag(e,t)}setExtra(e,t){if(!this.sentry)return;this.sentry.setExtra(e,t)}setContext(e,t){if(!this.sentry)return;this.sentry.setContext(e,t)}async close(e=2000){if(!this.sentry)return!0;return this.sentry.close(e)}shouldIgnoreError(e){let t=this.config.filters;if(!t)return!1;if(t.ignoreCodes?.includes(e.code))return!0;if(t.ignoreErrors?.some((r)=>{if(typeof r==="string")return e.message.includes(r);return r.test(e.message)}))return!0;return!1}mapSeverityToLevel(e){switch(e){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(e){let t=[];if(t.push(e.code),t.push(e.category),e.context.route)t.push(e.context.route);return t}}class ze{config;bugsnag;constructor(e){this.config=e,this.initializeBugsnag()}async initializeBugsnag(){try{let e=await import("@bugsnag/js");e.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(t)=>{let r=t.originalError;if(r&&this.config.beforeSend)return this.config.beforeSend(r,r.context)!==null;return!this.shouldIgnoreError(r)}}),this.bugsnag=e}catch(e){console.warn("Failed to initialize Bugsnag:",e)}}async report(e,t){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(e))return null;let r={...e.context,...t};return this.bugsnag.notify(e,(n)=>{if(n.severity=this.mapSeverityToBugsnag(e.severity),n.context=r.route||r.url,r.userId)n.setUser(r.userId,void 0,void 0);n.addMetadata("error",{code:e.code,category:e.category,statusCode:e.statusCode,retryable:e.retryable,timestamp:e.timestamp}),n.addMetadata("request",{requestId:r.requestId,method:r.method,url:r.url,userAgent:r.userAgent,ip:r.ip}),n.groupingHash=this.generateGroupingHash(e)}),"reported"}catch(r){return console.error("Failed to report error to Bugsnag:",r),null}}addBreadcrumb(e,t="manual",r="info",n){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(e,n,t)}setUser(e){if(!this.bugsnag)return;this.bugsnag.setUser(e.id,e.email,e.username)}setTag(e,t){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[e]:t})}setExtra(e,t){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[e]:t})}setContext(e,t){if(!this.bugsnag)return;this.bugsnag.addMetadata(e,t)}async close(){return!0}shouldIgnoreError(e){let t=this.config.filters;if(!t)return!1;if(t.ignoreCodes?.includes(e.code))return!0;if(t.ignoreErrors?.some((r)=>{if(typeof r==="string")return e.message.includes(r);return r.test(e.message)}))return!0;return!1}mapSeverityToBugsnag(e){switch(e){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(e){return`${e.code}-${e.category}-${e.context.route||"unknown"}`}}class Rt{config;reportHandler;constructor(e,t){this.config=e,this.reportHandler=t}async report(e,t){if(!this.config.enabled)return null;try{let r={...e.context,...t};if(this.config.beforeSend){if(!this.config.beforeSend(e,r))return null}let n={error:e,context:r,level:this.mapSeverityToLevel(e.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(n)}catch(r){return console.error("Failed to report error with custom handler:",r),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(e){switch(e){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class te{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(e){this.initializeReporters(e)}initializeReporters(e){for(let t of e){if(!t.enabled)continue;switch(t.service){case"sentry":this.reporters.push(new Le(t));break;case"bugsnag":this.reporters.push(new ze(t));break;case"custom":break}}}addReporter(e){this.reporters.push(e)}async report(e,t){let r=[];this.addBreadcrumb(`Error occurred: ${e.message}`,"error",{code:e.code,severity:e.severity});let n=this.reporters.map(async(s)=>{try{let i=await s.report(e,t);if(i)r.push(i)}catch(i){console.error("Reporter failed:",i)}});return await Promise.allSettled(n),r}addBreadcrumb(e,t="default",r){if(this.breadcrumbs.push({message:e,timestamp:new Date,data:{category:t,...r}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((n)=>{n.addBreadcrumb(e,t,"info",r)})}setUser(e){this.reporters.forEach((t)=>t.setUser(e))}setTag(e,t){this.reporters.forEach((r)=>r.setTag(e,t))}setExtra(e,t){this.reporters.forEach((r)=>r.setExtra(e,t))}setContext(e,t){this.reporters.forEach((r)=>r.setContext(e,t))}async close(e=5000){let t=this.reporters.map((n)=>n.close(e));return(await Promise.allSettled(t)).every((n)=>n.status==="fulfilled"&&n.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function Zr(e){return new te(e)}var Yr={sentry:(e,t="production")=>({enabled:!0,service:"sentry",dsn:e,environment:t,sampleRate:1,breadcrumbs:{enabled:!0,maxBreadcrumbs:100},performance:{enabled:!0,tracesSampleRate:0.1},filters:{ignoreErrors:["Non-Error promise rejection captured","ResizeObserver loop limit exceeded"],ignoreCodes:["VALIDATION_ERROR"]}}),bugsnag:(e,t="production")=>({enabled:!0,service:"bugsnag",apiKey:e,environment:t,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class Ge{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(e){this.config=e,this.initializeHealthChecks()}initializeHealthChecks(){for(let[e,t]of Object.entries(this.config.healthChecks)){if(!t.enabled)continue;this.healthStatus.set(e,{name:e,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let r=setInterval(()=>this.performHealthCheck(e,t),t.interval);r.unref?.(),this.healthCheckIntervals.set(e,r)}}async performHealthCheck(e,t){let r=Date.now(),n=!1;try{let i=new AbortController,o=setTimeout(()=>i.abort(),t.timeout),a=await fetch(t.endpoint,{signal:i.signal,headers:t.headers,method:"GET"});if(clearTimeout(o),n=t.expectedStatus.includes(a.status),n&&t.expectedBody){let u=await a.text();if(typeof t.expectedBody==="string")n=u.includes(t.expectedBody);else n=t.expectedBody.test(u)}}catch(i){console.error(i),n=!1}let s=Date.now()-r;if(this.updateHealthStatus(e,n,s),n&&t.onHealthy)t.onHealthy();else if(!n&&t.onUnhealthy)t.onUnhealthy(Error(`Health check failed for ${e}`))}updateHealthStatus(e,t,r){let n=this.healthStatus.get(e);if(!n)return;let s={...n,lastCheck:new Date,responseTime:r,consecutiveFailures:t?0:n.consecutiveFailures+1};if(s.consecutiveFailures===0)s.status="healthy";else if(s.consecutiveFailures<3)s.status="degraded";else s.status="unhealthy";let i=t?1:0;s.availability=n.availability*0.9+i*10,this.healthStatus.set(e,s)}getServiceHealth(e){return this.healthStatus.get(e)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(e){return this.healthStatus.get(e)?.status==="healthy"}isServiceDegraded(e){return this.healthStatus.get(e)?.status==="degraded"}stop(){for(let e of this.healthCheckIntervals.values())clearInterval(e);this.healthCheckIntervals.clear()}}class re{config;healthMonitor;cache=new Map;metrics=new Map;constructor(e){this.config=e,this.healthMonitor=new Ge(e)}async handleFailure(e,t,r,n){if(!this.config.enabled)throw t;let s=this.config.fallbackStrategies[e];if(!s)throw t;let i={request:r,serviceName:e,error:t,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(s,i,n)}async executeFallbackStrategy(e,t,r){if(t.attemptCount<=e.retries)try{if(t.attemptCount>1){let i=this.calculateBackoffDelay(e.backoff,t.attemptCount);await this.sleep(i)}let n=new Promise((i,o)=>{setTimeout(()=>o(Error("Timeout")),e.timeout)}),s=await Promise.race([r(),n]);return this.updateMetrics(t.serviceName,!0,Date.now()-t.startTime.getTime()),s}catch(n){if(console.error(n),t.attemptCount++,t.attemptCount<=e.retries)return this.executeFallbackStrategy(e,t,r)}switch(this.updateMetrics(t.serviceName,!1,Date.now()-t.startTime.getTime()),e.type){case"cache":return this.handleCacheFallback(e,t);case"static":return this.handleStaticFallback(e,t);case"simplified":return this.handleSimplifiedFallback(e,t);case"redirect":return this.handleRedirectFallback(e,t);case"custom":return this.handleCustomFallback(e,t);default:throw t.error}}async handleCacheFallback(e,t){if(!e.cacheConfig)throw t.error;let r=this.generateCacheKey(e.cacheConfig.key,t),n=this.cache.get(r);if(n&&(n.expires>new Date||e.cacheConfig.staleWhileRevalidate)){let s=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"});if(e.cacheConfig.staleWhileRevalidate&&n.expires<=new Date)s.set("X-Cache","STALE");return new Response(JSON.stringify(n.data),{status:200,headers:s})}throw t.error}async handleStaticFallback(e,t){if(!e.staticResponse)throw t.error;let r=new Headers(e.staticResponse.headers||{});return r.set("X-Degraded","true"),r.set("X-Fallback-Type","static"),r.set("X-Service-Status",this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"),new Response(typeof e.staticResponse.body==="string"?e.staticResponse.body:JSON.stringify(e.staticResponse.body),{status:e.staticResponse.status,headers:r})}async handleSimplifiedFallback(e,t){let r={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:t.request.requestId};return new Response(JSON.stringify(r),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"}})}async handleRedirectFallback(e,t){if(!e.redirectConfig)throw t.error;return new Response(null,{status:e.redirectConfig.permanent?301:302,headers:{Location:e.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(e,t){if(!e.fallbackHandler)throw t.error;try{let r=await e.fallbackHandler(t.error,t.error.context);return r.headers.set("X-Degraded","true"),r.headers.set("X-Fallback-Type","custom"),r.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"),r}catch(r){throw console.error(r),t.error}}cacheResponse(e,t,r,n){let s=this.config.fallbackStrategies[e];if(s?.type==="cache"&&s.cacheConfig){let i=this.generateCacheKey(t,{serviceName:e});this.cache.set(i,{data:r,expires:new Date(Date.now()+n*1000)})}}getServiceMetrics(e){let t=this.metrics.get(e);if(!t||t.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:t.errors/t.requests*100,avgResponseTime:t.totalTime/t.requests,totalRequests:t.requests}}getSystemHealth(){let e=this.healthMonitor.getAllServiceHealth(),t=e.filter((s)=>s.status==="unhealthy").length,r=e.filter((s)=>s.status==="degraded").length,n="healthy";if(t>0)n=t>e.length/2?"unhealthy":"degraded";else if(r>0)n="degraded";return{status:n,services:e}}calculateBackoffDelay(e,t){if(e.type==="fixed")return e.delay;let r=e.delay*2**(t-1);return Math.min(r,e.maxDelay||30000)}generateCacheKey(e,t){return e.replace("{service}",t.serviceName).replace("{url}",t.request.url).replace("{method}",t.request.method).replace("{userId}",String(t.request.user?.id||"anonymous"))}updateMetrics(e,t,r){let n=this.metrics.get(e)||{requests:0,errors:0,totalTime:0};if(n.requests++,n.totalTime+=r,!t)n.errors++;this.metrics.set(e,n)}sleep(e){return new Promise((t)=>setTimeout(t,e))}stop(){this.healthMonitor.stop()}}function en(e){let t=new re(e);return async(r,n)=>{try{let s=await n(),i=r.context?.serviceName;if(i&&s.ok){let o=e.fallbackStrategies[i];if(o?.type==="cache"&&o.cacheConfig)try{let a=await s.clone().json();t.cacheResponse(i,o.cacheConfig.key,a,o.cacheConfig.ttl)}catch{}}return s}catch(s){let i=r.context?.serviceName;if(i&&s instanceof Error){let o=s;try{return await t.handleFailure(i,o,r,n)}catch(a){throw console.error(a),s}}throw s}}}var tn={cacheFirst:(e=3600,t=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:e,staleWhileRevalidate:t}}),staticFallback:(e,t=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:t,body:e,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(e)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:e,permanent:!1}})};class wt{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(e={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...e},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new te(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new re(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new J;for(let e of this.config.circuitBreakers)this.circuitBreakerRegistry.register(e)}}middleware(){return async(e,t)=>{try{let r={requestId:e.requestId,userId:e.user?.id,traceId:e.traceId,spanId:e.spanId,route:e.params?.route||e.url,method:e.method,url:e.url,userAgent:e.userAgent?.()||void 0,ip:e.ip?.()||void 0,timestamp:new Date};if(e.context={...e.context,errorContext:r},this.circuitBreakerRegistry&&e.context?.serviceName){let n=this.circuitBreakerRegistry.get(e.context.serviceName);if(n)return await n.execute({execute:t,context:r})}return await t()}catch(r){return this.handleError(r,e)}}}async handleError(e,t){let r=this.normalizeError(e,t);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${t.method} ${t.url}`,"error",{code:r.code,severity:r.severity,statusCode:r.statusCode});if(this.config.logErrors)this.logError(r,t);if(this.gracefulDegradation&&t.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(t.context.serviceName,r,t,async()=>{throw r})}catch{}if(this.errorReporting)try{await this.errorReporting.report(r,r.context)}catch(s){console.error("Failed to report error:",s)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler(r,t)}catch(s){console.error("Global error handler failed:",s)}let n=this.config.customErrorPages?.[r.statusCode];if(n)try{if(typeof n==="string")return new Response(n,{status:r.statusCode,headers:{"Content-Type":"text/html"}});else return await n(r,t)}catch(s){console.error("Custom error page failed:",s)}return this.createErrorResponse(r,t)}normalizeError(e,t){let r={requestId:t.requestId,userId:t.user?.id,traceId:t.traceId,spanId:t.spanId,route:t.params?.route||t.url,method:t.method,url:t.url,userAgent:t.userAgent?.()||void 0,ip:t.ip?.()||void 0,timestamp:new Date,metadata:t.context};if(e instanceof We)return e;if(e instanceof Error){if(e.name==="ValidationError")return B.validation(e.message,{},r);if(e.name==="UnauthorizedError"||e.message.includes("unauthorized"))return B.authentication(e.message,r);if(e.name==="ForbiddenError"||e.message.includes("forbidden"))return B.authorization(e.message,[],r);if(e.name==="NotFoundError"||e.message.includes("not found"))return B.notFound(void 0,void 0,r);if(e.name==="TimeoutError"||e.message.includes("timeout"))return B.timeout(30000,e.message,r);return B.internalServer(e.message,e,r)}if(typeof e==="string")return B.internalServer(e,void 0,r);return B.internalServer("An unknown error occurred",void 0,r)}createErrorResponse(e,t){let r=this.config.development,n=this.config.includeStackTrace||r,s=this.config.sanitizeErrors&&!r,i=e.message;if(s&&e.statusCode>=500)i="An internal server error occurred";let o={error:{code:e.code,message:i,statusCode:e.statusCode,timestamp:e.timestamp.toISOString(),requestId:e.context.requestId,traceId:e.context.traceId}};if(r)o.error.category=e.category,o.error.severity=e.severity,o.error.retryable=e.retryable,o.error.context=e.context;if(n){if(o.error.stack=e.stack,e.cause)o.error.cause={name:e.cause.name,message:e.cause.message,stack:e.cause.stack}}if("fields"in e)o.error.fields=e.fields;if("allowedMethods"in e)o.error.allowedMethods=e.allowedMethods;if("retryAfter"in e)o.error.retryAfter=e.retryAfter;let a=new Headers({"Content-Type":"application/json","X-Error-Code":e.code,"X-Request-ID":e.context.requestId||"","X-Trace-ID":e.context.traceId||""});if("allowedMethods"in e)a.set("Allow",e.allowedMethods.join(", "));if("retryAfter"in e)a.set("Retry-After",e.retryAfter.toString());if("limit"in e)a.set("X-RateLimit-Limit",e.limit.toString()),a.set("X-RateLimit-Remaining",e.remaining.toString());return new Response(JSON.stringify(o),{status:e.statusCode,headers:a})}logError(e,t){let r={error:e.toJSON(),request:{method:t.method,url:t.url,headers:Object.fromEntries(t.headers.entries()),userAgent:t.userAgent?.()||void 0,ip:t.ip?.()||void 0,requestId:t.requestId,traceId:t.traceId}};switch(e.severity){case"critical":console.error("[CRITICAL ERROR]",r);break;case"high":console.error("[ERROR]",r);break;case"medium":console.warn("[WARNING]",r);break;case"low":console.warn("[INFO]",r);break;default:console.error("[ERROR]",r)}}getStats(){return{errorReporting:this.errorReporting?{breadcrumbs:this.errorReporting.getBreadcrumbs().length}:void 0,gracefulDegradation:this.gracefulDegradation?this.gracefulDegradation.getSystemHealth():void 0,circuitBreakers:this.circuitBreakerRegistry?this.circuitBreakerRegistry.getAllMetrics():void 0}}async cleanup(){if(this.errorReporting)await this.errorReporting.close();if(this.gracefulDegradation)this.gracefulDegradation.stop()}}function bt(e={}){let t=new wt(e);return{middleware:t.middleware(),getStats:()=>t.getStats(),cleanup:()=>t.cleanup()}}import{AsyncLocalStorage as Cn}from"async_hooks";var Ve=new Cn,xe=!1,j=null;function Pn(){xe=!0}function ve(e,t){if(!xe){j=e;let r=t();if(r instanceof Promise)return r.finally(()=>{j=null});return j=null,r}return Ve.run({current:e},t)}function Ce(e){let t=Ve.getStore();if(t){t.current=e;return}if(j!==null)j=e}function xt(){if(!xe)return xe=!0,j??void 0;return Ve.getStore()?.current??j??void 0}function En(){let e=xt();if(!e)throw Error("request() called outside a request scope. It can only be invoked from within a route handler or middleware.");return e}var Mn={enabled:!0,level:6,threshold:1024};function vt(e){if(!e)return!1;let t=e.split(";")[0]?.trim().toLowerCase()??"";if(t==="text/event-stream")return!1;if(t.startsWith("text/"))return!0;return["application/json","application/ld+json","application/manifest+json","application/javascript","application/x-javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/graphql","application/x-ndjson","image/svg+xml"].includes(t)}function Sn(e){if(!e)return null;let t=new Map;for(let n of e.split(",")){let[s="",...i]=n.trim().split(";"),o=i.map((a)=>/^\s*q=([\d.]+)\s*$/i.exec(a)).find(Boolean);t.set(s.trim().toLowerCase(),o?Number(o[1]):1)}let r=(n)=>(t.get(n)??t.get("*")??0)>0;if(r("gzip"))return"gzip";if(r("deflate"))return"deflate";return null}function kn(e,t,r){if(!t)return!1;if(e.status===204||e.status===304||e.status===206)return!1;if(e.headers.has("content-encoding"))return!1;if(!vt(e.headers.get("content-type")))return!1;if(!e.body)return!1;let n=Number(e.headers.get("content-length")??Number.NaN);return Number.isFinite(n)?n>=r:!0}async function Ct(e,t,r={}){let n={...Mn,...r};if(!n.enabled)return e;let s=Sn(t.headers.get("accept-encoding"));if(!kn(e,s,n.threshold)){if(vt(e.headers.get("content-type"))&&!e.headers.has("content-encoding"))Je(e.headers,"Accept-Encoding");return e}let i=Number(e.headers.get("content-length")??Number.NaN),o=Number.isFinite(i)?{stream:e.body,size:i,ended:!1}:await Hn(e.body,n.threshold);if(o.ended&&o.size<n.threshold){let c=new Headers(e.headers);return Je(c,"Accept-Encoding"),new Response(o.stream,{status:e.status,statusText:e.statusText,headers:c})}let a=new Headers(e.headers);a.set("Content-Encoding",s),Je(a,"Accept-Encoding"),a.delete("Content-Length");let u=o.stream.pipeThrough(new CompressionStream(s==="gzip"?"gzip":"deflate"));return new Response(u,{status:e.status,statusText:e.statusText,headers:a})}async function Hn(e,t){let r=e.getReader(),n=[],s=0,i=!1;while(s<t){let{value:a,done:u}=await r.read();if(u){i=!0;break}if(a)n.push(a),s+=a.byteLength}return{stream:new ReadableStream({start(a){for(let u of n)a.enqueue(u);if(i)a.close()},async pull(a){if(i)return;let{value:u,done:c}=await r.read();if(c){i=!0,a.close();return}if(u)a.enqueue(u)},cancel(a){return r.cancel(a)}}),size:s,ended:i}}function Je(e,t){let r=e.get("vary");if(!r){e.set("Vary",t);return}let n=r.split(",").map((s)=>s.trim().toLowerCase());if(n.includes("*")||n.includes(t.toLowerCase()))return;e.set("Vary",`${r}, ${t}`)}var y={json:(e,t={})=>{let r=typeof t==="number"?{status:t}:t,{status:n=200,headers:s={},pretty:i=!1}=r,o=i?JSON.stringify(e,null,2):JSON.stringify(e);return new Response(o,{status:n,headers:{"Content-Type":"application/json",...s}})},noContent:(e={})=>new Response(null,{status:204,headers:e}),download:async(e,t,r={})=>{let n=Bun.file(e);if(!await n.exists())return new Response("File not found",{status:404});let i=t||e.split("/").pop()||"download",o=n.type||"application/octet-stream";return new Response(n,{status:200,headers:{"Content-Type":o,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":String(n.size),...r}})},file:async(e,t={})=>{let r=Bun.file(e);if(!await r.exists())return new Response("File not found",{status:404});let s=r.type||"application/octet-stream";return new Response(r,{status:200,headers:{"Content-Type":s,"Content-Length":String(r.size),...t}})},streamDownload:(e,t,r={})=>{let{contentType:n="application/octet-stream",headers:s={}}=r,i=new ReadableStream({async start(o){try{for await(let a of e())if(typeof a==="string")o.enqueue(new TextEncoder().encode(a));else o.enqueue(a);o.close()}catch(a){o.error(a)}}});return new Response(i,{status:200,headers:{"Content-Type":n,"Content-Disposition":`attachment; filename="${t}"`,"Transfer-Encoding":"chunked",...s}})},redirect:(e,t=302)=>new Response(null,{status:t,headers:{Location:e}}),redirectPermanent:(e)=>y.redirect(e,301),redirectTemporary:(e)=>y.redirect(e,302),back:(e,t="/")=>{let r=e.headers.get("referer")||t;return y.redirect(r)},view:(e,t=200,r={})=>new Response(e,{status:t,headers:{"Content-Type":"text/html; charset=utf-8",...r}}),text:(e,t=200,r={})=>new Response(e,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8",...r}}),xml:(e,t=200,r={})=>new Response(e,{status:t,headers:{"Content-Type":"application/xml; charset=utf-8",...r}}),success:(e,t,r=200)=>{let n={success:!0};if(e!==void 0)n.data=e;if(t!==void 0)n.message=t;return y.json(n,{status:r})},error:(e,t=400,r)=>{let n={success:!1,message:e};if(r!==void 0)n.errors=r;return y.json(n,{status:t})},paginate:(e,t)=>{let{page:r,perPage:n,total:s,path:i}=t,o=Math.ceil(s/n),a=(r-1)*n+1,u=Math.min(r*n,s);return y.json({data:e,meta:{current_page:r,per_page:n,total:s,last_page:o,from:a,to:u,path:i,first_page_url:`${i}?page=1`,last_page_url:`${i}?page=${o}`,next_page_url:r<o?`${i}?page=${r+1}`:null,prev_page_url:r>1?`${i}?page=${r-1}`:null}})},created:(e,t)=>{let r={};if(t)r.Location=t;let n={success:!0};if(e!==void 0)n.data=e;return y.json(n,{status:201,headers:r})},accepted:(e)=>{let t={success:!0};if(e!==void 0)t.data=e;return y.json(t,{status:202})},notFound:(e="Resource not found")=>y.error(e,404),unauthorized:(e="Unauthorized")=>y.error(e,401),forbidden:(e="Forbidden")=>y.error(e,403),badRequest:(e="Bad request",t)=>y.error(e,400,t),validationError:(e,t="Validation failed")=>y.error(t,422,e),unprocessableEntity:(e="Unprocessable entity",t)=>y.error(e,422,t),serverError:(e="Internal server error")=>y.error(e,500),tooManyRequests:(e="Too many requests",t)=>{let r={};if(t)r["Retry-After"]=String(t);return new Response(JSON.stringify({message:e}),{status:429,headers:{"Content-Type":"application/json",...r}})}};class Pt{_status=200;_headers={};_cookies=[];_deleteCookies=[];status(e){return this._status=e,this}header(e,t){return this._headers[e]=t,this}withHeaders(e){return this._headers={...this._headers,...e},this}cookie(e,t,r={}){return this._cookies.push({name:e,value:t,options:r}),this}withoutCookie(e,t={}){return this._deleteCookies.push({name:e,options:t}),this}json(e){let t=y.json(e,{status:this._status,headers:this._headers});return this.applyCookies(t)}text(e){let t=y.text(e,this._status,this._headers);return this.applyCookies(t)}html(e){let t=y.view(e,this._status,this._headers);return this.applyCookies(t)}noContent(){let e=y.noContent(this._headers);return this.applyCookies(e)}applyCookies(e){let t=new Headers(e.headers);for(let{name:r,value:n,options:s}of this._cookies){let i=this.serializeCookie(r,n,s);t.append("Set-Cookie",i)}for(let{name:r,options:n}of this._deleteCookies){let s=this.serializeCookie(r,"",{...n,maxAge:0,expires:new Date(0)});t.append("Set-Cookie",s)}return new Response(e.body,{status:e.status,headers:t})}serializeCookie(e,t,r){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(r.maxAge!==void 0)n+=`; Max-Age=${r.maxAge}`;if(r.expires)n+=`; Expires=${r.expires.toUTCString()}`;if(r.httpOnly)n+="; HttpOnly";if(r.secure)n+="; Secure";if(r.path)n+=`; Path=${r.path}`;if(r.domain)n+=`; Domain=${r.domain}`;if(r.sameSite)n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`;return n}}function Ti(){return new Pt}import An from"process";class Ke{compiledPipelines=new Map;dependencyRegistry=new Map;singletonInstances=new Map;stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0};registerDependency(e){this.dependencyRegistry.set(e.name,e)}compileMiddleware(e,t,r=[]){let n=[];for(let s=0;s<t.length;s++){let i=t[s],o=i.name||`middleware_${s}`;n.push({handler:i,name:o,skipConditions:r.filter((a)=>a.name.includes(o)||a.name==="global"),dependencies:this.extractDependencies(i),canShortCircuit:this.canShortCircuit(i),priority:s})}this.compiledPipelines.set(e,n)}async execute(e,t,r){let n=performance.now();this.stats.totalExecutions++;let s=this.compiledPipelines.get(e);if(!s)return this.stats.cacheMisses++,await r();this.stats.cacheHits++;let i={request:t,dependencies:new Map,metadata:{}};await this.resolveDependencies(i,s);let o=0,a=async()=>{if(o>=s.length)return await r();let l=s[o++];if(await this.shouldSkip(l,i))return this.stats.skippedMiddleware++,await a();let d=await l.handler(t,a);if(d instanceof Response&&l.canShortCircuit)return this.stats.shortCircuits++,d;return d},u=await a(),c=performance.now()-n;return this.updateAverageExecutionTime(c),u||new Response("Internal Server Error",{status:500})}async shouldSkip(e,t){for(let r of e.skipConditions)if(await r.condition(t))return!0;return!1}async resolveDependencies(e,t){let r=new Set;for(let n of t)for(let s of n.dependencies)r.add(s);for(let n of r){let s=this.dependencyRegistry.get(n);if(!s)continue;if(this.stats.dependencyResolutions++,s.singleton&&this.singletonInstances.has(n))e.dependencies.set(n,this.singletonInstances.get(n));else{let i=await s.factory(e);if(e.dependencies.set(n,i),s.singleton)this.singletonInstances.set(n,i)}}}extractDependencies(e){let t=e.toString(),r=[];if(t.includes("database")||t.includes("db"))r.push("database");if(t.includes("logger")||t.includes("log"))r.push("logger");if(t.includes("cache"))r.push("cache");if(t.includes("httpClient")||t.includes("http"))r.push("httpClient");return r}canShortCircuit(e){let t=e.toString();return t.includes("return")&&t.includes("Response")}updateAverageExecutionTime(e){let t=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(t+e)/this.stats.totalExecutions}getStats(){return{...this.stats}}clear(){this.compiledPipelines.clear(),this.singletonInstances.clear(),this.stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0}}}var qn={skipForMethods:(e)=>({name:`skip_for_methods_${e.join("_")}`,condition:(t)=>e.includes(t.request.method)}),skipForPaths:(e)=>({name:`skip_for_paths_${e.join("_").replace(/\//g,"_")}`,condition:(t)=>{let r=new URL(t.request.url);return e.some((n)=>r.pathname.startsWith(n))}}),skipForHeaders:(e)=>({name:`skip_for_headers_${Object.keys(e).join("_")}`,condition:(t)=>Object.entries(e).some(([r,n])=>t.request.headers.get(r)===n)}),skipForRoles:(e)=>({name:`skip_for_roles_${e.join("_")}`,condition:(t)=>{let r=t.request.user?.roles||[];return!e.some((n)=>r.includes(n))}}),skipForEnvironment:(e)=>({name:`skip_for_env_${e.join("_")}`,condition:()=>{let t=An.env.NODE_ENV||"development";return e.includes(t)}})},On={database:(e)=>({name:"database",factory:async()=>({query:async(t)=>({rows:[]}),close:async()=>{},connectionString:e||"mock://database"}),singleton:!0}),logger:(e="info")=>({name:"logger",factory:()=>({info:(t)=>console.log(`[INFO] ${t}`),error:(t)=>console.error(`[ERROR] ${t}`),warn:(t)=>console.warn(`[WARN] ${t}`),debug:(t)=>console.debug(`[DEBUG] ${t}`),level:e}),singleton:!0}),cache:(e=1000)=>({name:"cache",factory:()=>{let t=new Map;return{get:(r)=>t.get(r),set:(r,n)=>{if(t.size>=e){let s=t.keys().next().value;t.delete(s)}t.set(r,n)},delete:(r)=>t.delete(r),clear:()=>t.clear(),size:()=>t.size}},singleton:!0}),httpClient:(e)=>({name:"httpClient",factory:()=>({get:async(t)=>fetch(e?`${e}${t}`:t),post:async(t,r)=>fetch(e?`${e}${t}`:t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),put:async(t,r)=>fetch(e?`${e}${t}`:t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),delete:async(t)=>fetch(e?`${e}${t}`:t,{method:"DELETE"})}),singleton:!0})},$n={auth:(e={})=>async(t,r)=>{let n=new URL(t.url);if(e.skipPaths?.some((i)=>n.pathname.startsWith(i)))return await r();if(!t.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return t.user={id:"123",roles:["user"]},await r()}catch{return new Response("Invalid token",{status:401})}},rateLimit:(e)=>{let t=new Map;return async(r,n)=>{let s=r.headers.get("x-forwarded-for")||"unknown",i=Date.now(),o=i-e.windowMs;if(!t.has(s))t.set(s,[]);let u=t.get(s).filter((c)=>c>o);if(u.length>=e.maxRequests)return new Response("Too Many Requests",{status:429});return u.push(i),t.set(s,u),await n()}},cors:(e={})=>async(t,r)=>{let n=await r();if(n){let s=new Headers(n.headers);return s.set("Access-Control-Allow-Origin",e.origin||"*"),s.set("Access-Control-Allow-Methods",e.methods?.join(", ")||"GET, POST, PUT, DELETE"),s.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(n.body,{status:n.status,statusText:n.statusText,headers:s})}return n},logging:(e={})=>async(t,r)=>{let n=performance.now(),s=new URL(t.url);console.log(`[${new Date().toISOString()}] ${t.method} ${s.pathname}`);let i=await r(),o=performance.now()-n;if(i)console.log(`[${new Date().toISOString()}] ${t.method} ${s.pathname} - ${i.status} (${o.toFixed(2)}ms)`);return i}},Bn=new Ke;import{existsSync as Mt,readdirSync as Dn,statSync as Fn}from"fs";import{basename as St,extname as Et,join as Un,resolve as kt}from"path";var Nn=[".ts",".js"],In=["routes","src/routes"],_n=["web","index"];function jn(){let e=process.cwd();for(let t of In){let r=kt(e,t);if(Mt(r)&&Fn(r).isDirectory())return r}return null}function Ht(e,t){let r=[];if(!Mt(e))return r;let n=Dn(e,{withFileTypes:!0});for(let s of n){if(s.name.startsWith(".")||s.name.startsWith("_"))continue;let i=Un(e,s.name);if(s.isDirectory())r.push(...Ht(i,t));else if(Nn.includes(Et(s.name))){let o=e===t?"":e.slice(t.length),a=St(s.name,Et(s.name)),u=_n.includes(a)?o||"":`${o}/${a}`;r.push({filePath:i,prefix:u})}}return r}async function Ln(e,t,r,n){try{let s=await import(t),i=0,o=e.routes?.length||0;if(typeof s.default==="function"){let a=zn(e,r);await s.default(a),i=(e.routes?.length||0)-o}else if(Array.isArray(s.routes))for(let a of s.routes){let u=(a.method||"GET").toLowerCase(),c=`${r}${a.path}`;if(typeof e[u]==="function")await e[u](c,a.handler),i++}if(n&&i>0)console.log(` ${r||"/"} \u2192 ${St(t)} (${i} routes)`);return i}catch(s){return console.error(`[bun-router] Failed to load route file ${t}:`,s),0}}function zn(e,t){if(!t)return e;let r=["get","post","put","patch","delete","options","any"];return new Proxy(e,{get(n,s){if(r.includes(s))return async(i,...o)=>n[s](`${t}${i}`,...o);if(s==="group")return async(i,o)=>{let a=i.prefix?`${t}${i.prefix}`:t;return n.group({...i,prefix:a},o)};return n[s]}})}function At(e){Object.defineProperties(e.prototype,{_routesDir:{value:null,writable:!0,configurable:!0},_apiRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initApiRoutes:{async value(){if(this._apiRoutesInitialized)return;let t=this._routesDir||jn();if(!t){this._apiRoutesInitialized=!0;return}let r=this.config?.verbose||!1,n=Ht(t,t);if(n.length===0){this._apiRoutesInitialized=!0;return}if(r)console.log(`[bun-router] Auto-discovering API routes from ${t}:`);let s=0;for(let{filePath:i,prefix:o}of n)s+=await Ln(this,i,o,r);if(s>0&&r)console.log(`[bun-router] Registered ${s} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(t){return this._routesDir=kt(t),this},writable:!0,configurable:!0}})}import{join as se,relative as Xe,resolve as D,dirname as Wn}from"path";import{readdirSync as qt,statSync as Vn,existsSync as Ee}from"fs";var Si={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function Gn(e){let{preserve:t=[],exclude:r=[],routes:n=[]}=e;if(!t.length)return"";return`<script data-query-preservation>
|
|
3
3
|
(function(){
|
|
4
|
-
var preserve = ${JSON.stringify(
|
|
5
|
-
var exclude = ${JSON.stringify(
|
|
6
|
-
var routes = ${JSON.stringify(
|
|
4
|
+
var preserve = ${JSON.stringify(t)};
|
|
5
|
+
var exclude = ${JSON.stringify(r)};
|
|
6
|
+
var routes = ${JSON.stringify(n)};
|
|
7
7
|
|
|
8
8
|
function shouldPreserve(href) {
|
|
9
9
|
// Only preserve for same-origin links
|
|
@@ -76,30 +76,30 @@ catch (e) { return false; }
|
|
|
76
76
|
}
|
|
77
77
|
};
|
|
78
78
|
})();
|
|
79
|
-
</script>`}function
|
|
80
|
-
</head>`);if(
|
|
81
|
-
</body>`);return
|
|
82
|
-
- ${
|
|
83
|
-
- ${
|
|
84
|
-
Using: ${
|
|
85
|
-
`,contentType:
|
|
86
|
-
`));for await(let
|
|
87
|
-
`))}
|
|
88
|
-
`))return`"${
|
|
89
|
-
`;if(
|
|
90
|
-
`;if(
|
|
91
|
-
`;let
|
|
79
|
+
</script>`}function Pe(e,t){if(!t.enabled||!t.preserve?.length)return e;let r=Gn(t);if(!r)return e;if(e.includes("</head>"))return e.replace("</head>",`${r}
|
|
80
|
+
</head>`);if(e.includes("</body>"))return e.replace("</body>",`${r}
|
|
81
|
+
</body>`);return e+r}function ki(e,t,r,n){let s=typeof t==="string"?new URL(t):t,i=new URL(e,s.origin);if(r.preserve){for(let o of r.preserve)if(s.searchParams.has(o)&&!r.exclude?.includes(o)){if(!i.searchParams.has(o))i.searchParams.set(o,s.searchParams.get(o))}}if(n)for(let[o,a]of Object.entries(n))i.searchParams.set(o,a);return i.pathname+i.search}var Jn=["src/views","views","resources/views","app/views"],Kn=["_","components","layouts","partials","scripts","styles"],Xn=[".stx",".html"];function Qn(e=process.cwd()){for(let t of Jn){let r=D(e,t);if(Ee(r)&&Vn(r).isDirectory())return r}return null}function Ot(e,t,r){if(!Ee(e))return!1;try{let n=qt(e,{withFileTypes:!0});for(let s of n){if(r.some((i)=>s.name.startsWith(i)||s.name===i))continue;if(s.isFile()&&t.some((i)=>s.name.endsWith(i)))return!0;if(s.isDirectory()){let i=se(e,s.name);if(Ot(i,t,r))return!0}}}catch{}return!1}function Zn(e,t,r){let n=Xe(t,e);for(let i of r)if(n.endsWith(i)){n=n.slice(0,-i.length);break}if(n=n.replace(/\\/g,"/"),n==="index"||n.endsWith("/index"))n=n.replace(/\/?index$/,"");let s=[];if(n=n.replace(/\[\.\.\.([^\]]+)\]/g,(i,o)=>(s.push(o),`{${o}}*`)),n=n.replace(/\[([^\]]+)\]/g,(i,o)=>(s.push(o),`{${o}}`)),!n.startsWith("/"))n=`/${n}`;if(n==="/")return{routePath:"/",params:s};return{routePath:n,params:s}}function $t(e,t,r,n){let s=[];if(!Ee(e))return s;let i=qt(e,{withFileTypes:!0});for(let a of i){let u=se(e,a.name);if(n.some((c)=>a.name.startsWith(c)||a.name===c))continue;if(a.isDirectory())s.push(...$t(u,t,r,n));else if(a.isFile()){if(r.some((l)=>a.name.endsWith(l))){let{routePath:l,params:d}=Zn(u,t,r);s.push({filePath:u,routePath:l,params:d,isIndex:a.name.startsWith("index."),isDynamic:d.length>0})}}}s.sort((a,u)=>{if(a.isDynamic!==u.isDynamic)return a.isDynamic?1:-1;let c=a.routePath.split("/").length,l=u.routePath.split("/").length;if(c!==l)return l-c;return a.routePath.localeCompare(u.routePath)});let o=new Map;for(let a of s){let u=o.get(a.routePath);if(u)console.warn(`[bun-router] Warning: Duplicate route "${a.routePath}" found:
|
|
82
|
+
- ${u.filePath}
|
|
83
|
+
- ${a.filePath}
|
|
84
|
+
Using: ${u.filePath}`);else o.set(a.routePath,a)}return Array.from(o.values())}function Yn(e,t){let r=Xe(t,e),n=[D(process.cwd(),"dist/views",r.replace(/\.stx$/,".html")),D(process.cwd(),"views",r.replace(/\.stx$/,".html")),D("/var/task/views",r.replace(/\.stx$/,".html"))];for(let s of n)if(Ee(s))return s;return null}function es(e){let t={};for(let r of String(e??"").split(";")){let n=r.indexOf("=");if(n<0)continue;try{t[r.slice(0,n).trim()]=decodeURIComponent(r.slice(n+1).trim())}catch{}}return t}async function ts(e,t,r,n,s){let o=await import("./chunk-n2j24b0h.js");if(!o.processDirectives||!o.extractVariables)throw Error("STX library not properly loaded. Install with: bun add @stacksjs/stx");let a=await Bun.file(e).text(),u=a.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),c=u?u[1]:"",l=u?a.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):a;l=l.replace(/<script\s+client\s*>/gi,"<script>");let d={status:200,headers:{}},p=r.headers??{},g=String(p.cookie??p.Cookie??""),h=String(r.url??""),m=h.includes("?")?h.slice(h.indexOf("?")):"",R={url:h,path:String(r.path??""),search:m,host:String(p.host??""),cookieHeader:g,cookies:es(g),ip:"",locale:null,params:r.params??{},method:String(r.method??"GET"),request:s},T={__filename:e,__dirname:Wn(e),props:r,...r,__stxServeContext:R,setResponseStatus:(E)=>{if(Number.isInteger(E)&&E>=100&&E<=599)d.status=E},notFound:(E=404)=>{d.status=Number.isInteger(E)&&E>=400&&E<=599?E:404},setResponseHeader:(E,Lr)=>{if(E)d.headers[String(E)]=String(Lr)},definePageMeta:()=>{}};if(c)await o.extractVariables(c,T,e);let V=n?.componentsDir?D(n.componentsDir):se(t,"components"),me=n?.layoutsDir?D(n.layoutsDir):se(t,"layouts"),Nr=n?.partialsDir?D(n.partialsDir):se(t,"partials"),Ir={...o.defaultConfig,componentsDir:V,layoutsDir:me,partialsDir:Nr},_r=await o.processDirectives(l,T,e,Ir,new Set),fe=Number(T.__stxResponseStatus),jr=T.__stxResponseHeaders;return{html:_r,status:Number.isInteger(fe)&&fe>=100&&fe<=599?fe:d.status,headers:{...d.headers,...jr??{}}}}function rs(e,t,r,n){return async(s)=>{let i=new URL(s.url),o={params:s.params||{},query:Object.fromEntries(i.searchParams),url:s.url,path:i.pathname,method:s.method,headers:Object.fromEntries(s.headers.entries())};function a(u){if(n?.enabled!==!1&&n?.preserve?.length)return Pe(u,n);return u}try{let u=Yn(e,t);if(u){let l=await Bun.file(u).text();return l=a(l),new Response(l,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}if(e.endsWith(".stx")){let l=await ts(e,t,o,r,s),d=a(l.html);return new Response(d,{status:l.status,headers:{"Content-Type":"text/html; charset=utf-8",...l.headers}})}let c=await Bun.file(e).text();return c=a(c),new Response(c,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}catch(u){return console.error(`[bun-router] Error rendering ${e}:`,u),new Response("Internal Server Error",{status:500})}}}function Bt(e){Object.defineProperties(e.prototype,{_viewsDir:{value:null,writable:!0,configurable:!0},_fileRoutingConfig:{value:null,writable:!0,configurable:!0},_fileBasedRoutes:{value:[],writable:!0,configurable:!0},_fileRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initFileRoutes:{async value(){if(this._fileRoutesInitialized)return;if(!Object.prototype.hasOwnProperty.call(this,"_fileBasedRoutes"))this._fileBasedRoutes=[];let t=this._viewsDir||Qn();if(!t){this._fileRoutesInitialized=!0;return}let r=this._fileRoutingConfig||{};if(r.enabled===!1){this._fileRoutesInitialized=!0;return}let n=r.extensions||Xn,s=r.exclude||Kn;if(!Ot(t,n,s)){this._fileRoutesInitialized=!0;return}let i=$t(t,t,n,s);if(this.config.verbose){console.log(`[bun-router] Auto-discovered ${i.length} file-based routes from ${t}:`);for(let a of i)console.log(` ${a.routePath} -> ${Xe(t,a.filePath)}`)}this._viewsDir=t;let o=new Set;for(let a of this.routes)if(a.method==="GET")o.add(a.path);for(let a of i){if(o.has(a.routePath))continue;let u=rs(a.filePath,t,r,this.config.queryPreservation);this.get(a.routePath,u,"web"),this._fileBasedRoutes.push(a),o.add(a.routePath)}this._fileRoutesInitialized=!0},writable:!0,configurable:!0},views:{value(t){if(typeof t==="string")this._viewsDir=D(t),this._fileRoutingConfig={};else{if(t.viewsPath)this._viewsDir=D(t.viewsPath);this._fileRoutingConfig=t}return this},writable:!0,configurable:!0},disableFileRouting:{value(){return this._fileRoutingConfig={enabled:!1},this},writable:!0,configurable:!0},getFileRoutes:{value(){return this._fileBasedRoutes||[]},writable:!0,configurable:!0},fileRoutes:{async value(t,r){if(t)this._viewsDir=D(t);if(r)this._fileRoutingConfig={...this._fileRoutingConfig,...r};return this._fileRoutesInitialized=!1,await this._initFileRoutes(),this},writable:!0,configurable:!0},loadFileRoutes:{async value(t={}){return this.fileRoutes(t.viewsPath,t)},writable:!0,configurable:!0}})}class Me{stream;headers;status;constructor(e,t={}){if(this.stream=e,this.status=t.status||200,this.headers=new Headers(t.headers),t.contentType)this.headers.set("Content-Type",t.contentType)}toResponse(){return new Response(this.stream,{status:this.status,headers:this.headers})}addHeader(e,t){return this.headers.set(e,t),this}setContentType(e){return this.headers.set("Content-Type",e),this}setStatus(e){return this.status=e,this}}class S{static direct(e,t={}){let{format:r="json",delimiter:n=`
|
|
85
|
+
`,contentType:s,headers:i={},status:o=200,enableCompression:a=!1}=t,u=new ReadableStream({async start(l){try{let d=new TextEncoder,p=!0;for await(let g of Array.isArray(e)?e:e){if(!p&&n)l.enqueue(d.encode(n));let h=S.formatData(g,r);l.enqueue(d.encode(h)),p=!1}l.close()}catch(d){l.error(d)}}}),c=new Headers(i);if(s)c.set("Content-Type",s);else c.set("Content-Type",S.getContentTypeForFormat(r));return new Me(u,{headers:c,status:o})}static buffered(e,t={}){let{format:r="json",bufferSize:n=1024,flushInterval:s=100,contentType:i,headers:o={},status:a=200}=t,u=new ReadableStream({async start(l){try{let d=new TextEncoder,p=[],g=0,h=()=>{if(p.length>0){let R=p.join("");l.enqueue(d.encode(R)),p=[],g=0}},m=setInterval(h,s);try{for await(let R of Array.isArray(e)?e:e){let T=S.formatData(R,r);if(p.push(T),g+=T.length,g>=n)h()}h()}finally{clearInterval(m)}l.close()}catch(d){l.error(d)}}}),c=new Headers(o);if(i)c.set("Content-Type",i);else c.set("Content-Type",S.getContentTypeForFormat(r));return new Me(u,{headers:c,status:a})}static json(e,t={}){return S.direct(e,{...t,format:"json",contentType:t.contentType||"application/json"})}static text(e,t={}){return S.direct(e,{...t,format:"text",contentType:t.contentType||"text/plain"})}static csv(e,t={}){let{csvHeaders:r,...n}=t,s=new ReadableStream({async start(i){try{let o=new TextEncoder,a=!0;if(r&&r.length>0)i.enqueue(o.encode(`${r.join(",")}
|
|
86
|
+
`));for await(let u of Array.isArray(e)?e:e){let c=S.objectToCsvRow(u,r);i.enqueue(o.encode(`${c}
|
|
87
|
+
`))}i.close()}catch(o){i.error(o)}}});return new Me(s,{headers:n.headers,status:n.status,contentType:n.contentType||"text/csv"})}static formatData(e,t){switch(t){case"json":return JSON.stringify(e);case"text":return String(e);case"csv":return typeof e==="object"?S.objectToCsvRow(e):String(e);case"ndjson":return JSON.stringify(e);default:return JSON.stringify(e)}}static objectToCsvRow(e,t){return(t||Object.keys(e)).map((n)=>{let s=e[n],i=s===null||s===void 0?"":String(s);if(i.includes(",")||i.includes('"')||i.includes(`
|
|
88
|
+
`))return`"${i.replace(/"/g,'""')}"`;return i}).join(",")}static getContentTypeForFormat(e){switch(e){case"json":case"ndjson":return"application/json";case"text":return"text/plain";case"csv":return"text/csv";default:return"application/json"}}}class K{static async streamFile(e,t,r={}){let{contentType:n,enableRanges:s=!0,chunkSize:i=65536}=r;try{let o=Bun.file(e),a=o.size,u=s?t.headers.get("range"):null;if(u&&s)return K.handleRangeRequest(o,u,n);let c=new Headers({"Content-Length":a.toString(),"Accept-Ranges":s?"bytes":"none"});if(n)c.set("Content-Type",n);return new Response(o.stream(),{status:200,headers:c})}catch(o){return console.error("Error streaming file:",o),new Response("File not found",{status:404})}}static async handleRangeRequest(e,t,r){let n=K.parseRangeHeader(t,e.size);if(!n||n.length===0)return new Response("Invalid range",{status:416});let[s,i]=n[0],o=i-s+1,a=new Headers({"Content-Range":`bytes ${s}-${i}/${e.size}`,"Content-Length":o.toString(),"Accept-Ranges":"bytes"});if(r)a.set("Content-Type",r);let u=e.slice(s,i+1);return new Response(u.stream(),{status:206,headers:a})}static parseRangeHeader(e,t){let r=e.match(/^bytes=(.+)$/);if(!r)return null;let n=[],s=r[1].split(",");for(let i of s){let[o,a]=i.trim().split("-"),u,c;if(o==="")u=Math.max(0,t-Number.parseInt(a,10)),c=t-1;else if(a==="")u=Number.parseInt(o,10),c=t-1;else u=Number.parseInt(o,10),c=Number.parseInt(a,10);if(u<0||c>=t||u>c)return null;n.push([u,c])}return n}}function Se(e,t){try{e.close()}catch{}}function Dt(e){Object.defineProperties(e.prototype,{streamFile:{value(t,r,n){return K.streamFile(t,r,n)},writable:!0,configurable:!0},streamFileWithRanges:{async value(t,r){return K.streamFile(t,r,{enableRanges:!0})},writable:!0,configurable:!0},health:{value(){let r=this.config.apiPrefix?`${this.config.apiPrefix}/health`:"/health";return this.get(r,()=>new Response("OK",{headers:{"Content-Type":"text/plain"}})),this},writable:!0,configurable:!0},streamResponse:{value(t,r){let n=new Headers;if(r?.headers)for(let[s,i]of Object.entries(r.headers))n.set(s,i);return new Response(t(),{status:r?.status||200,headers:n})},writable:!0,configurable:!0},transformStream:{value(t,r){return(n)=>{if(!n.body)throw Error("Request body is required for stream transformation");let s=new TransformStream({async transform(o,a){try{let u=await t(o);if(typeof u==="string")a.enqueue(new TextEncoder().encode(u));else a.enqueue(u)}catch(u){a.error(u)}}}),i=new Headers;if(r?.headers)for(let[o,a]of Object.entries(r.headers))i.set(o,a);return new Response(n.body.pipeThrough(s),{status:r?.status||200,headers:i})}},writable:!0,configurable:!0},stream:{value(t,r=200,n={}){let s=new Headers(n),i=new ReadableStream({async start(o){let a=new TextEncoder;try{for await(let u of t())if(typeof u==="string")o.enqueue(a.encode(u));else o.enqueue(u);o.close()}catch(u){Se(o,u)}}});return new Response(i,{status:r,headers:s})},writable:!0,configurable:!0},streamJson:{value(t,r=200,n={}){let s=new Headers({"Content-Type":"application/json",...n}),i=new ReadableStream({async start(o){let a=new TextEncoder;try{o.enqueue(a.encode("{"));let u=Object.keys(t);for(let c=0;c<u.length;c++){let l=u[c],d=t[l];o.enqueue(a.encode(`"${l}":[`));let p=!0;for await(let g of d){if(!p)o.enqueue(a.encode(","));o.enqueue(a.encode(JSON.stringify(g))),p=!1}if(o.enqueue(a.encode("]")),c<u.length-1)o.enqueue(a.encode(","))}o.enqueue(a.encode("}")),o.close()}catch(u){Se(o,u)}}});return new Response(i,{status:r,headers:s})},writable:!0,configurable:!0},eventStream:{value(t,r={}){let n=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Cache-Control",...r}),s=new ReadableStream({async start(i){let o=new TextEncoder;try{for await(let a of t()){let u="";if(a.id)u+=`id: ${a.id}
|
|
89
|
+
`;if(a.event)u+=`event: ${a.event}
|
|
90
|
+
`;if(a.retry)u+=`retry: ${a.retry}
|
|
91
|
+
`;let c=typeof a.data==="string"?a.data:JSON.stringify(a.data);u+=`data: ${c}
|
|
92
92
|
|
|
93
|
-
`,Q.enqueue(_.encode(G))}Q.close()}catch(j){TY(Q,j)}}});return new Response(J,{status:200,headers:X})},writable:!0,configurable:!0},streamDownload:{value(Z,$,X={}){let J=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${$}"`,...X}),Q=new ReadableStream({async start(_){let j=new TextEncoder;try{for await(let G of Z())if(typeof G==="string")_.enqueue(j.encode(G));else _.enqueue(G);_.close()}catch(G){TY(_,G)}}});return new Response(Q,{status:200,headers:J})},writable:!0,configurable:!0},streamAsyncIterator:{value(Z,$={}){return P.direct(Z,$).toResponse()},writable:!0,configurable:!0}})}class PY extends Error{modelName;value;field;constructor(Y,Z,$="id"){super(`${Y} not found with ${$}: ${Z}`);this.modelName=Y;this.value=Z;this.field=$;this.name="ModelNotFoundError"}}class fZ{bindings=new Map;model(Y,Z){this.bindings.set(Y,Z)}bind(Y,Z){this.bindings.set(Y,Z)}getBinding(Y){return this.bindings.get(Y)}hasBinding(Y){return this.bindings.has(Y)}}var r9=new fZ;async function qZ(Y,Z,$,X,J={}){if(X)return await $.resolveRouteBinding(Z,X);let Q=$.getRouteKeyName();if(Q!=="id")return await $.resolveRouteBinding(Z,Q);return await $.find(Z)}function yZ(Y,Z){return async($,X)=>{let J={};try{for(let Q of Y){let _=$.params?.[Q.name];if(!_)continue;let j=r9.getBinding(Q.name);if(j){let K=null;if(typeof j==="function")K=await j(_);else K=await qZ(Q.name,_,j,Q.key,J);if(!K)throw new PY(Q.name,_,Q.key||"id");J[Q.name]=K;continue}let G=Z[Q.name];if(!G)continue;let W=await qZ(Q.name,_,G,Q.key,J);if(!W)throw new PY(Q.name,_,Q.key||"id");J[Q.name]=W}return $.models=J,await X()}catch(Q){if(Q instanceof PY)return new Response(`${Q.modelName} not found`,{status:404});throw Q}}}class gZ{key;entry;prev;next;constructor(Y,Z,$=null,X=null){this.key=Y;this.entry=Z;this.prev=$;this.next=X}}class JY{options;cache=new Map;head=null;tail=null;stats={hits:0,misses:0,evictions:0};constructor(Y){this.options=Y;if(Y.maxSize<=0)throw Error("maxSize must be greater than 0")}get(Y){let Z=this.cache.get(Y);if(!Z){this.stats.misses++;return}let $=Date.now(),X=Z.entry;if(this.isExpired(X,$)){if(!this.options.allowStale){this.delete(Y),this.stats.misses++;return}}if(X.lastAccessed=$,X.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(Z);return X.value}set(Y,Z,$){let X=Date.now(),J=this.cache.get(Y);if(J){J.entry.value=Z,J.entry.timestamp=X,J.entry.lastAccessed=X,J.entry.ttl=$??this.options.ttl,this.moveToFront(J);return}let Q={value:Z,timestamp:X,accessCount:0,lastAccessed:X,ttl:$??this.options.ttl},_=new gZ(Y,Q);if(this.cache.set(Y,_),this.addToFront(_),this.cache.size>this.options.maxSize)this.evictLRU()}delete(Y){let Z=this.cache.get(Y);if(!Z)return!1;if(this.cache.delete(Y),this.removeNode(Z),this.options.onEvict)this.options.onEvict(Y,Z.entry.value);return!0}has(Y){let Z=this.cache.get(Y);if(!Z)return!1;let $=Date.now();if(this.isExpired(Z.entry,$)){if(!this.options.allowStale)return this.delete(Y),!1}return!0}clear(){if(this.options.onEvict)for(let[Y,Z]of this.cache)this.options.onEvict(Y,Z.entry.value);this.cache.clear(),this.head=null,this.tail=null,this.stats.evictions+=this.cache.size}keys(){let Y=[],Z=this.head;while(Z)Y.push(Z.key),Z=Z.next;return Y}values(){let Y=[],Z=this.head;while(Z)Y.push(Z.entry.value),Z=Z.next;return Y}getStats(){let Y=this.estimateMemoryUsage(),Z=this.stats.hits+this.stats.misses;return{size:this.cache.size,maxSize:this.options.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,hitRate:Z>0?this.stats.hits/Z:0,memoryUsage:Y}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}prune(){let Y=Date.now(),Z=[];for(let[$,X]of this.cache)if(this.isExpired(X.entry,Y))Z.push($);for(let $ of Z)this.delete($);return Z.length}getFrequentlyUsed(Y=10){let Z=[];for(let[$,X]of this.cache)Z.push({key:$,value:X.entry.value,accessCount:X.entry.accessCount});return Z.sort(($,X)=>X.accessCount-$.accessCount).slice(0,Y)}resize(Y){if(Y<=0)throw Error("maxSize must be greater than 0");this.options.maxSize=Y;while(this.cache.size>Y)this.evictLRU()}isExpired(Y,Z){if(!Y.ttl)return!1;return Z-Y.timestamp>Y.ttl}moveToFront(Y){if(Y===this.head)return;this.removeNode(Y),this.addToFront(Y)}addToFront(Y){if(Y.prev=null,Y.next=this.head,this.head)this.head.prev=Y;if(this.head=Y,!this.tail)this.tail=Y}removeNode(Y){if(Y.prev)Y.prev.next=Y.next;else this.head=Y.next;if(Y.next)Y.next.prev=Y.prev;else this.tail=Y.prev}evictLRU(){if(!this.tail)return;let Y=this.tail.key,Z=this.tail.entry.value;if(this.cache.delete(Y),this.removeNode(this.tail),this.stats.evictions++,this.options.onEvict)this.options.onEvict(Y,Z)}estimateMemoryUsage(){let Y=0;for(let[Z,$]of this.cache)Y+=Z.length*2,Y+=this.estimateValueSize($.entry.value),Y+=64;return Y+=this.cache.size*48,Y}estimateValueSize(Y){if(Y===null||Y===void 0)return 0;if(typeof Y==="string")return Y.length*2;if(typeof Y==="number")return 8;if(typeof Y==="boolean")return 1;if(Y instanceof ArrayBuffer)return Y.byteLength;if(Y instanceof Uint8Array)return Y.length;try{return JSON.stringify(Y).length*2}catch{return 100}}}class hZ{static generateKey(Y,Z){let $=new URL(Y.url),X=Y.method,J=$.pathname,Q=[X,J],_=new URLSearchParams($.search),j=Z.excludeQuery||[],G=[];for(let[W,K]of _.entries())if(!j.includes(W))G.push(`${W}=${K}`);if(G.length>0)Q.push(G.sort().join("&"));if(Z.varyBy){let W=[];for(let K of Z.varyBy){let z=Y.headers.get(K);if(z)W.push(`${K}:${z}`)}if(W.length>0)Q.push(W.join("|"))}return Q.join("::")}}class cZ{cache;tagIndex=new Map;keyTags=new Map;constructor(Y=1000){this.cache=new JY({maxSize:Y})}async get(Y){let Z=this.cache.get(Y);if(!Z)return null;if(Z.ttl&&Date.now()-Z.timestamp>Z.ttl)return this.delete(Y),null;return Z}async set(Y,Z){this.cache.set(Y,Z),this.keyTags.set(Y,new Set(Z.tags));for(let $ of Z.tags){if(!this.tagIndex.has($))this.tagIndex.set($,new Set);this.tagIndex.get($).add(Y)}}delete(Y){let Z=this.keyTags.get(Y);if(Z){for(let $ of Z){let X=this.tagIndex.get($);if(X){if(X.delete(Y),X.size===0)this.tagIndex.delete($)}}this.keyTags.delete(Y)}return this.cache.delete(Y)}invalidateByTags(Y){let Z=new Set;for(let $ of Y){let X=this.tagIndex.get($);if(X)for(let J of X)Z.add(J)}for(let $ of Z)this.delete($);return Z.size}clear(){this.cache.clear(),this.tagIndex.clear(),this.keyTags.clear()}getStats(){return{...this.cache.getStats(),totalTags:this.tagIndex.size,totalKeyTagMappings:this.keyTags.size}}}var o=new cZ;function pZ(Y){return async(Z,$)=>{if(Y.condition&&!Y.condition(Z))return await $();if(Z.method!=="GET"&&Z.method!=="HEAD")return await $();let X=hZ.generateKey(Z,Y),J=await o.get(X);if(J){let _=new Headers(J.headers);if(_.set("X-Cache","HIT"),_.set("X-Cache-Key",X),J.etag){if(_.set("ETag",J.etag),Z.headers.get("If-None-Match")===J.etag)return new Response(null,{status:304,headers:_})}return new Response(J.body,{status:J.status,headers:_})}let Q=await $();if(Q.status>=200&&Q.status<300)try{let _=Q.clone(),j=await _.arrayBuffer(),G=await e9(j),W={};_.headers.forEach((L,V)=>{W[V]=L});let K={response:_,headers:W,status:Q.status,body:new Uint8Array(j),timestamp:Date.now(),ttl:Y.ttl,tags:Y.tags||[],etag:G};await o.set(X,K);let z=new Headers(Q.headers);return z.set("X-Cache","MISS"),z.set("X-Cache-Key",X),z.set("ETag",G),new Response(Q.body,{status:Q.status,headers:z})}catch(_){return console.error("Error caching response:",_),Q}return Q}}async function e9(Y){let Z=await crypto.subtle.digest("SHA-256",Y);return`"${Array.from(new Uint8Array(Z)).map((J)=>J.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var mZ={short:(Y=[])=>({ttl:300000,maxSize:500,tags:Y}),medium:(Y=[])=>({ttl:3600000,maxSize:1000,tags:Y}),long:(Y=[])=>({ttl:86400000,maxSize:2000,tags:Y}),api:(Y=[])=>({ttl:900000,maxSize:1000,tags:Y,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(Y=[])=>({ttl:604800000,maxSize:5000,tags:Y,varyBy:["Accept-Encoding"]}),user:(Y=[])=>({ttl:1800000,maxSize:2000,tags:Y,varyBy:["Authorization"],condition:(Z)=>!!Z.headers.get("Authorization")})},R6={byTags:(Y)=>{return o.invalidateByTags(Y)},forUser:(Y)=>{return o.invalidateByTags([`user:${Y}`])},forModel:(Y,Z)=>{let $=Z?[`${Y}:${Z}`,Y]:[Y];return o.invalidateByTags($)},all:()=>{o.clear()}};class bY{cache;config;constructor(Y,Z=1e4){this.config=Y,this.cache=new JY({maxSize:Z,ttl:Y.windowMs*2})}async checkLimit(Y){if(this.config.skipIf&&this.config.skipIf(Y))return{allowed:!0,info:{totalHits:0,resetTime:new Date(Date.now()+this.config.windowMs),remaining:this.config.maxAttempts,limit:this.config.maxAttempts,windowMs:this.config.windowMs}};let Z=this.generateKey(Y),$=Date.now(),X=this.cache.get(Z);if(!X||$>=X.resetTime)X={count:1,resetTime:$+this.config.windowMs,firstHit:$};else X.count++;this.cache.set(Z,X);let J={totalHits:X.count,resetTime:new Date(X.resetTime),remaining:Math.max(0,this.config.maxAttempts-X.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:X.count<=this.config.maxAttempts,info:J}}generateKey(Y){if(this.config.keyGenerator)return this.config.keyGenerator(Y);let Z=this.getClientIP(Y),$=Y.user?.id;if($)return`user:${$}`;return`ip:${Z}`}getClientIP(Y){let Z=Y.headers.get("x-forwarded-for");if(Z)return Z.split(",")[0].trim();let $=Y.headers.get("x-real-ip");if($)return $;let X=Y.headers.get("cf-connecting-ip");if(X)return X;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class uZ{limiters=new Map;register(Y,Z){let $=new bY(Z);return this.limiters.set(Y,$),$}get(Y){return this.limiters.get(Y)}getOrCreate(Y,Z){let $=this.limiters.get(Y);if($)return $;return this.register(Y,Z)}}var dZ=new uZ;function a(Y,Z){let $=Z?dZ.getOrCreate(Z,Y):new bY(Y);return async(X,J)=>{let{allowed:Q,info:_}=await $.checkLimit(X);if(!Q){if(Y.onLimitReached)return Y.onLimitReached(X,_);let G=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((_.resetTime.getTime()-Date.now())/1000).toString()});if(Y.headers!==!1)G.set("X-RateLimit-Limit",_.limit.toString()),G.set("X-RateLimit-Remaining",_.remaining.toString()),G.set("X-RateLimit-Reset",Math.ceil(_.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((_.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((_.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:G})}let j=await J();if(j&&Y.headers!==!1&&j.status<400){let G=new Headers(j.headers);return G.set("X-RateLimit-Limit",_.limit.toString()),G.set("X-RateLimit-Remaining",_.remaining.toString()),G.set("X-RateLimit-Reset",Math.ceil(_.resetTime.getTime()/1000).toString()),new Response(j.body,{status:j.status,statusText:j.statusText,headers:G})}return j}}function t(Y){let Z=Y.split(","),$=Number.parseInt(Z[0],10);if(Number.isNaN($)||$<=0)throw Error(`Invalid throttle max attempts: ${Z[0]}`);let X;if(Z.length===1)X=60000;else{let J=Z[1];X=Y$(J)}return{maxAttempts:$,windowMs:X}}function Y$(Y){let Z=/^(\d+)([smh]|sec|min|hour)?$/,$=Y.match(Z);if(!$)throw Error(`Invalid time format: ${Y}`);let X=Number.parseInt($[1],10),J=$[2]||"m";if(Number.isNaN(X)||X<=0)throw Error(`Invalid time value: ${$[1]}`);switch(J){case"s":case"sec":return X*1000;case"m":case"min":return X*60*1000;case"h":case"hour":return X*60*60*1000;default:return X*60*1000}}var Z$={api:(Y=60,Z=1)=>({maxAttempts:Y,windowMs:Z*60*1000,headers:!0}),auth:()=>({maxAttempts:5,windowMs:900000,keyGenerator:(Y)=>{let Z=Y.headers.get("x-forwarded-for")?.split(",")[0]||"unknown",$=Y.jsonBody?.email||Y.formBody?.email||Y.query?.email||"unknown";return`auth:${Z}:${$}`},onLimitReached:(Y,Z)=>new Response(JSON.stringify({error:"Too many authentication attempts",message:"Please try again later",retryAfter:Math.ceil((Z.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:{"Content-Type":"application/json","Retry-After":Math.ceil((Z.resetTime.getTime()-Date.now())/1000).toString()}})}),upload:()=>({maxAttempts:10,windowMs:3600000,keyGenerator:(Y)=>{let Z=Y.user?.id;if(Z)return`upload:user:${Z}`;return`upload:ip:${Y.headers.get("x-forwarded-for")?.split(",")[0]||"unknown"}`}}),search:()=>({maxAttempts:100,windowMs:600000,skipIf:(Y)=>{return Y.user?.plan==="premium"}}),perUser:(Y,Z)=>({maxAttempts:Y,windowMs:Z*60*1000,keyGenerator:($)=>{let X=$.user?.id;if(!X)throw Error("User authentication required for per-user rate limiting");return`user:${X}`},skipIf:($)=>!$.user?.id}),perIP:(Y,Z)=>({maxAttempts:Y,windowMs:Z*60*1000,keyGenerator:($)=>{return`ip:${$.headers.get("x-forwarded-for")?.split(",")[0]||$.headers.get("x-real-ip")||$.headers.get("cf-connecting-ip")||"unknown"}`}}),global:(Y,Z)=>({maxAttempts:Y,windowMs:Z*60*1000,keyGenerator:()=>"global"})},v6={fromString:(Y,Z)=>{let $=t(Y);return a($,Z)},getInfo:async(Y,Z)=>{let $=new bY(Z),{info:X}=await $.checkLimit(Y);return X},reset:(Y,Z)=>{let $=dZ.get(Y);if($)return $.cache.delete(Z);return!1}};class b{static parseDomainPattern(Y){let Z=[],$=Y.match(/\{([^}]+)\}/g)||[];for(let Q of $){let _=Q.slice(1,-1);Z.push(_)}let X=Y.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");X=`^${X}$`;let J=new RegExp(X,"i");return{pattern:Y,parameters:Z,regex:J}}static matchDomain(Y,Z){let $=Y.match(Z.regex);if(!$)return null;let X={};for(let J=0;J<Z.parameters.length;J++){let Q=Z.parameters[J],_=$[J+1];X[Q]=_}return X}static extractSubdomainInfo(Y){let Z=Y.split(".");if(Z.length<=2)return{domain:Y,parameters:{},rootDomain:Y};let $=Z[0],X=Z.slice(1).join(".");return{domain:Y,parameters:{subdomain:$},subdomain:$,rootDomain:X}}}class QY{pattern;config;routes=[];constructor(Y,Z){this.pattern=Y;this.config=Z}addRoute(Y,Z,$,X=[],J){let Q=[...this.config.middleware||[],...X],_=this.config.prefix?`${this.config.prefix}${Z}`:Z;this.routes.push({method:Y.toUpperCase(),path:_,handler:$,middleware:Q,name:J||(this.config.name?`${this.config.name}.${Y.toLowerCase()}${Z}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(Y){return b.matchDomain(Y,this.pattern)}}class aY{domainGroups=[];wildcardGroup;domain(Y){let Z=b.parseDomainPattern(Y);return new lZ(this,Z)}addDomainGroup(Y){if(Y.pattern.pattern.includes("*")&&Y.pattern.parameters.length===0)this.wildcardGroup=Y;else this.domainGroups.push(Y)}findDomainGroup(Y){for(let Z of this.domainGroups){let $=Z.matchesDomain(Y);if($!==null)return{group:Z,parameters:$}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:b.extractSubdomainInfo(Y).parameters};return null}getAllRoutes(){let Y=[];for(let Z of this.domainGroups){let $=Z.getRoutes();for(let X of $)Y.push({domainPattern:Z.pattern.pattern,domainParameters:{},...X})}if(this.wildcardGroup){let Z=this.wildcardGroup.getRoutes();for(let $ of Z)Y.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...$})}return Y}}class lZ{router;pattern;group;constructor(Y,Z){this.router=Y;this.pattern=Z;this.group=new QY(Z,{domain:Z.pattern})}middleware(Y){return this.group.config.middleware=Y,this}prefix(Y){return this.group.config.prefix=Y,this}name(Y){return this.group.config.name=Y,this}routes(Y){let Z=new iZ(this.group);Y(Z),this.router.addDomainGroup(this.group)}get(Y,Z,$){this.group.addRoute("GET",Y,Z,$),this.router.addDomainGroup(this.group)}post(Y,Z,$){this.group.addRoute("POST",Y,Z,$),this.router.addDomainGroup(this.group)}put(Y,Z,$){this.group.addRoute("PUT",Y,Z,$),this.router.addDomainGroup(this.group)}delete(Y,Z,$){this.group.addRoute("DELETE",Y,Z,$),this.router.addDomainGroup(this.group)}patch(Y,Z,$){this.group.addRoute("PATCH",Y,Z,$),this.router.addDomainGroup(this.group)}}class iZ{group;constructor(Y){this.group=Y}get(Y,Z,$,X){this.group.addRoute("GET",Y,Z,$,X)}post(Y,Z,$,X){this.group.addRoute("POST",Y,Z,$,X)}put(Y,Z,$,X){this.group.addRoute("PUT",Y,Z,$,X)}delete(Y,Z,$,X){this.group.addRoute("DELETE",Y,Z,$,X)}patch(Y,Z,$,X){this.group.addRoute("PATCH",Y,Z,$,X)}options(Y,Z,$,X){this.group.addRoute("OPTIONS",Y,Z,$,X)}head(Y,Z,$,X){this.group.addRoute("HEAD",Y,Z,$,X)}any(Y,Z,$,X){let J=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let Q of J)this.group.addRoute(Q,Y,Z,$,X)}}function f6(Y){return async(Z,$)=>{let J=new URL(Z.url).hostname,Q=Y.findDomainGroup(J);if(Q){let _=Z;_.domainParams=Q.parameters,Object.assign(Z.params||{},Q.parameters);let j=b.extractSubdomainInfo(J);_.subdomainInfo=j}return await $()}}var y6={getSubdomain:(Y)=>{let Z=new URL(Y.url);return b.extractSubdomainInfo(Z.hostname).subdomain||null},getDomainParams:(Y)=>{return Y.domainParams||{}},matchesDomain:(Y,Z)=>{let $=new URL(Y.url),X=b.parseDomainPattern(Z);return b.matchDomain($.hostname,X)!==null},getSubdomainInfo:(Y)=>{return Y.subdomainInfo||null}},g6={single:(Y,Z)=>`${Y}.${Z}`,wildcard:(Y,Z="subdomain")=>`{${Z}}.${Y}`,multiLevel:(Y,...Z)=>{return`${Z.map((X)=>`{${X}}`).join(".")}.${Y}`},apiVersion:(Y)=>`{version}.api.${Y}`,tenant:(Y)=>`{tenant}.app.${Y}`,environment:(Y)=>`{env}.${Y}`};import $$ from"process";var r=new Map;function g(Y,Z){r.set(Y,Z)}function tY(Y){return r.get(Y)}function X$(){return new Map(r)}function J$(){r.clear()}function Q$(Y,Z={},$={}){let X=r.get(Y);if(!X){let G=[...r.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${Y}' is not defined. Known routes: ${G}`)}let J=new Set,Q=X;for(let[G,W]of Object.entries(Z)){let K=`{${G}}`,z=`{${G}?}`,L=encodeURIComponent(String(W));if(Q.includes(K))Q=Q.replaceAll(K,L),J.add(G);else if(Q.includes(z))Q=Q.replaceAll(z,L),J.add(G)}if(Q.includes("?}")){if(Q=Q.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),Q.length>1&&Q.endsWith("/"))Q=Q.slice(0,-1)}let _=Q.match(/\{([^}?]+)\}/g);if(_&&_.length>0)throw Error(`Missing required params for route '${Y}': ${_.join(", ")}`);let j=Object.entries(Z).filter(([G])=>!J.has(G));if(j.length>0){let G=new URLSearchParams;for(let[W,K]of j)G.set(W,String(K));Q+=`?${G.toString()}`}if($.absolute){let G=($.base??$$.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${G.startsWith("http")?G:`https://${G}`}${Q.startsWith("/")?Q:`/${Q}`}`}return Q}import{join as nZ}from"path";function _Y(Y){let Z=Y.replace(/\/+/g,"/");if(!Z.startsWith("/"))Z=`/${Z}`;if(Z.length>1&&Z.endsWith("/"))Z=Z.slice(0,-1);return Z}function u6(Y){return Y.replace(/\//g,"_").toLowerCase()}function _$(Y){if(typeof Y!=="function"&&typeof Y!=="object")return!1;if(typeof Y==="function"&&Y.prototype){if(typeof Y.prototype.handle==="function")return!0}if(typeof Y==="object"&&Y!==null&&"handle"in Y&&typeof Y.handle==="function")return!0;return!1}function d6(Y){return typeof Y==="function"&&!_$(Y)}function xY(Y){let Z=Y.match(/\{([^}]+)\}/g);return Z?Z.map(($)=>$.slice(1,-1).replace("?","")):[]}function l6(Y){let Z=Y.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${Z}$`)}var j$=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,G$=/\{[^}]+\?\}/,sZ=new Map,oZ=new Map;function W$(Y){let Z=sZ.get(Y);if(Z)return Z;let $=Y.endsWith("/*"),X=_Y(Y),J=0,Q=X.split("/").filter(Boolean).map((j)=>{let G=G$.test(j);if(G)J++;let W=j.match(j$);return{isParam:!!W,paramName:W?W[1].replace("?",""):"",isOptional:G,literal:j}}),_={isWildcard:$,wildcardBase:$?Y.slice(0,-2):"",segments:Q,optionalCount:J};return sZ.set(Y,_),_}function K$(Y){let Z=oZ.get(Y);if(Z!==void 0)return Z;let $;try{$=new RegExp(`^${Y}$`)}catch{$=null}return oZ.set(Y,$),$}function x(Y,Z,$,X){let J=W$(Y);if(J.isWildcard&&Z.startsWith(J.wildcardBase))return!0;let Q=J.segments,_=_Y(Z).split("/").filter(Boolean);if(_.length<Q.length-J.optionalCount||_.length>Q.length)return!1;for(let j=0;j<Q.length;j++){let G=Q[j],W=_[j];if(W===void 0){if(G.isOptional)continue;return!1}if(G.isParam){if($[G.paramName]=W,X&&X[G.paramName]){let K=K$(X[G.paramName]);if(K){if(!K.test(W))return!1}else console.warn(`Invalid constraint regex for parameter ${G.paramName}: ${X[G.paramName]}`)}}else if(G.literal!==W)return!1}return!0}function f(...Y){return _Y(Y.join("/"))}function i6(Y){if(!Y.startsWith("/"))return!1;let Z=[];for(let $ of Y)if($==="{")Z.push($);else if($==="}"){if(Z.length===0||Z.pop()!=="{")return!1}return Z.length===0}async function aZ(Y){try{return await Bun.file(Y).exists()}catch{return!1}}async function rY(Y,Z,$){if($.some((X)=>Y.endsWith(X))){let X=_Y(nZ(Z,Y));if(await aZ(X))return X;return null}for(let X of $){let J=_Y(nZ(Z,`${Y}${X}`));if(await aZ(J))return J}return null}function tZ(Y,Z){let $=Y.replace(/\{\{([^}]+)\}\}/g,(X,J)=>{let Q=J.trim(),_=eY(Z,Q);return _!==void 0?String(_):X});return $=z$($,Z),$=L$($,Z),$}function z$(Y,Z){return Y.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,($,X,J,Q="")=>{let _=X.trim();return eY(Z,_)?J:Q})}function L$(Y,Z){return Y.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,($,X,J)=>{let Q=eY(Z,X.trim());if(!Array.isArray(Q))return"";return Q.map((_)=>{return J.replace(/\{\{@index\}\}/g,String(Q.indexOf(_))).replace(/\{\{this\}\}/g,String(_)).replace(/\{\{this\.([^}]+)\}\}/g,(j,G)=>{let W=_[G.trim()];return W!==void 0?String(W):""})}).join("")})}function eY(Y,Z){return Z.split(".").reduce(($,X)=>{if($&&typeof $==="object"&&X in $)return $[X];return},Y)}class D{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(Y,Z,$){this.method=Y;this.path=Z;this.handler=$}addMiddleware(Y){if(Array.isArray(Y))this.middleware.push(...Y);else this.middleware.push(Y);return this}cached(Y=[],Z){return this.cacheConfig={...mZ.api(Y),...Z},this}throttle(Y,Z){if(typeof Y==="string"){let $=t(Y);this.throttleConfig={maxAttempts:$.maxAttempts??60,windowMs:$.windowMs,keyGenerator:(X)=>X.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=Y;return this}name(Y){return this.routeName=Y,this}model(Y,Z){return this.modelBindings[Y]=Z,this}build(){let Y=[];if(Object.keys(this.modelBindings).length>0){let Z=Object.keys(this.modelBindings).map((X)=>({name:X})),$=yZ(Z,this.modelBindings);Y.push($)}if(this.throttleConfig){let Z=a(this.throttleConfig);Y.push(Z)}if(this.cacheConfig){let Z=pZ(this.cacheConfig);Y.push(Z)}return Y.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:Y,name:this.routeName}}}class rZ{router;condition;constructor(Y,Z){this.router=Y;this.condition=Z}middleware(Y){let[Z,$]=Y.split(":"),X=this.router.resolveNamedMiddleware(Z);if(!X)throw Error(`Unknown middleware: ${Z}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[X($)]}),this}}class eZ{router;middleware;constructor(Y,Z){this.router=Y;this.middleware=Z}get(Y,Z){return new D("GET",Y,Z).addMiddleware(this.middleware)}post(Y,Z){return new D("POST",Y,Z).addMiddleware(this.middleware)}put(Y,Z){return new D("PUT",Y,Z).addMiddleware(this.middleware)}delete(Y,Z){return new D("DELETE",Y,Z).addMiddleware(this.middleware)}patch(Y,Z){return new D("PATCH",Y,Z).addMiddleware(this.middleware)}}class Y8{router;groupMiddleware;constructor(Y,Z){this.router=Y;this.groupMiddleware=Z}get(Y,Z){return new D("GET",Y,Z).addMiddleware(this.groupMiddleware)}post(Y,Z){return new D("POST",Y,Z).addMiddleware(this.groupMiddleware)}put(Y,Z){return new D("PUT",Y,Z).addMiddleware(this.groupMiddleware)}delete(Y,Z){return new D("DELETE",Y,Z).addMiddleware(this.groupMiddleware)}patch(Y,Z){return new D("PATCH",Y,Z).addMiddleware(this.groupMiddleware)}}class jY{routes=[];globalMiddleware=[];subdomainRouter=new aY;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(Y)=>{let Z=Y?t(Y):{maxAttempts:60,windowMs:60000},$=a({maxAttempts:Z.maxAttempts,windowMs:Z.windowMs,keyGenerator:(J)=>J.headers.get("x-forwarded-for")||"anonymous"});return async(J,Q)=>{return await $(J,async()=>{return await Q()??new Response(null)})}}),this.namedMiddleware.set("auth",()=>{return async(Y,Z)=>{if(!Y.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return Y.user={id:"123",roles:["user"]},await Z()}}),this.namedMiddleware.set("cors",()=>{return async(Y,Z)=>{let $=await Z();if($){let X=new Headers($.headers);return X.set("Access-Control-Allow-Origin","*"),X.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),X.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response($.body,{status:$.status,statusText:$.statusText,headers:X})}return $}})}middlewareGroup(Y,Z){let $=[];for(let X of Z){let[J,Q]=X.split(":"),_=this.namedMiddleware.get(J);if(_)$.push(_(Q))}return this.middlewareGroups.set(Y,$),this}middlewareGroupRoutes(Y){let Z=this.middlewareGroups.get(Y)||[];return new Y8(this,Z)}when(Y){return new rZ(this,Y)}resolveNamedMiddleware(Y){return this.namedMiddleware.get(Y)}addConditionalMiddleware(Y){this.conditionalMiddleware.push(Y)}middleware(Y){let[Z,$]=Y.split(":"),X=this.namedMiddleware.get(Z);if(!X)throw Error(`Unknown middleware: ${Z}`);let J=X($);return new eZ(this,[J])}use(Y){return this.globalMiddleware.push(Y),this}get(Y,Z){return new D("GET",Y,Z)}post(Y,Z){return new D("POST",Y,Z)}put(Y,Z){return new D("PUT",Y,Z)}delete(Y,Z){return new D("DELETE",Y,Z)}patch(Y,Z){return new D("PATCH",Y,Z)}register(Y){let Z=Y.build();if(this.routes.push(Z),Z.name)g(Z.name,Z.path);return this}cached(Y=[],Z){return{get:($,X)=>this.get($,X).cached(Y,Z),post:($,X)=>this.post($,X).cached(Y,Z),put:($,X)=>this.put($,X).cached(Y,Z),delete:($,X)=>this.delete($,X).cached(Y,Z),patch:($,X)=>this.patch($,X).cached(Y,Z)}}throttled(Y){return{get:(Z,$)=>this.get(Z,$).throttle(Y),post:(Z,$)=>this.post(Z,$).throttle(Y),put:(Z,$)=>this.put(Z,$).throttle(Y),delete:(Z,$)=>this.delete(Z,$).throttle(Y),patch:(Z,$)=>this.patch(Z,$).throttle(Y)}}group(Y,Z){let $=new jY;Z($);for(let X of $.routes){let J={...X,path:Y.prefix?`${Y.prefix}${X.path}`:X.path,middleware:[...Y.middleware||[],...X.middleware],name:Y.name&&X.name?`${Y.name}.${X.name}`:X.name};if(Y.domain){let Q=b.parseDomainPattern(Y.domain),_=new QY(Q,{domain:Y.domain});_.addRoute(J.method,J.path,J.handler,J.middleware,J.name),this.subdomainRouter.addDomainGroup(_)}else if(this.routes.push(J),J.name)g(J.name,J.path)}return this}domain(Y){return{routes:(Z)=>{let $=new jY;Z($);let X=b.parseDomainPattern(Y),J=new QY(X,{domain:Y});for(let Q of $.routes)J.addRoute(Q.method,Q.path,Q.handler,Q.middleware,Q.name);return this.subdomainRouter.addDomainGroup(J),this}}}resource(Y,Z,$={}){let X=["index","create","store","show","edit","update","destroy"],J=$.only||X.filter((_)=>!$.except?.includes(_)),Q=[{action:"index",method:"GET",path:`/${Y}`,handler:Z.index},{action:"create",method:"GET",path:`/${Y}/create`,handler:Z.create},{action:"store",method:"POST",path:`/${Y}`,handler:Z.store},{action:"show",method:"GET",path:`/${Y}/{${Y.slice(0,-1)}}`,handler:Z.show},{action:"edit",method:"GET",path:`/${Y}/{${Y.slice(0,-1)}}/edit`,handler:Z.edit},{action:"update",method:"PUT",path:`/${Y}/{${Y.slice(0,-1)}}`,handler:Z.update},{action:"destroy",method:"DELETE",path:`/${Y}/{${Y.slice(0,-1)}}`,handler:Z.destroy}];for(let _ of Q)if(J.includes(_.action)&&_.handler){let j=new D(_.method,_.path,_.handler).name(`${Y}.${_.action}`);if($.model&&["show","edit","update","destroy"].includes(_.action))j.model(Y.slice(0,-1),$.model);this.register(j)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(Y){let Z=new URL(Y.url),$=Z.hostname,X=this.subdomainRouter.findDomainGroup($);if(X){let J=Y;J.domainParams=X.parameters;for(let Q of X.group.getRoutes()){let _=this.matchRouteParams(Q,Y.method,Z.pathname);if(_)return await this.executeRoute(Q,J,_)}}for(let J of this.routes){let Q=this.matchRouteParams(J,Y.method,Z.pathname);if(Q)return await this.executeRoute(J,Y,Q)}return null}matchRouteParams(Y,Z,$){if(Y.method!==Z)return null;let X={};return x(Y.path,$,X)?X:null}async executeRoute(Y,Z,$){Z.params=$;let X=[...this.globalMiddleware];for(let _ of this.conditionalMiddleware)if(await _.condition(Z))X.push(..._.middleware);X.push(...Y.middleware);let J=0,Q=async()=>{if(J<X.length){let _=X[J++];return await _(Z,Q)??new Response(null)}return await Y.handler(Z)};return await Q()}}var U$={api:(Y,Z,$={})=>{let X=$.method||"GET",J=new D(X,Y,Z);if($.cache)J.cached($.cache);if($.throttle)J.throttle($.throttle);return J},protected:(Y,Z,$={})=>{let X=$.method||"GET",J=new D(X,Y,Z);return J.addMiddleware(async(Q,_)=>{if(!Q.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await _()}),J},upload:(Y,Z,$={})=>{let X=new D("POST",Y,Z);return X.addMiddleware(async(J,Q)=>{return await Q()}),X}},V$={route:(Y,Z={},$={})=>{let X=tY(Y)??`/${Y}`;for(let[Q,_]of Object.entries(Z)){let j=encodeURIComponent(_);X=X.replace(`{${Q}}`,j),X=X.replace(`{${Q}?}`,j)}if(X.includes("?}")){if(X=X.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),X.length>1&&X.endsWith("/"))X=X.slice(0,-1)}let J=new URLSearchParams($).toString();if(J)X+=`?${J}`;return X},redirect:(Y,Z=302)=>{return new Response(null,{status:Z,headers:{Location:Y}})},json:(Y,Z=200)=>{return new Response(JSON.stringify(Y),{status:Z,headers:{"Content-Type":"application/json"}})}},A$=new jY;function Z8(Y){Object.defineProperties(Y.prototype,{group:{value(Z,$){let X=this.currentGroup,J={...X};if(Z.prefix&&X?.prefix)J.prefix=f(X.prefix,Z.prefix);else if(Z.prefix)J.prefix=Z.prefix;if(Z.middleware)J.middleware=[...X?.middleware||[],...Z.middleware];this.currentGroup=J;let Q=$();if(Q instanceof Promise)return Q.then(()=>{return this.currentGroup=X,this},(_)=>{throw this.currentGroup=X,_});return this.currentGroup=X,this},writable:!0,configurable:!0},name:{value(Z,$){let X=this.currentGroup||{},J={...X};this.currentGroup=J;let Q=this.routes.length;$();for(let _=Q;_<this.routes.length;_++){let j=this.routes[_];if(j.name)j.name=`${Z}.${j.name}`}return this.currentGroup=X,this},writable:!0,configurable:!0},controller:{value(Z,$){let X=this.currentGroup||{},J={...X,controller:Z};return this.currentGroup=J,$(),this.currentGroup=X,this},writable:!0,configurable:!0},domain:{value(Z,$){let X=this.currentDomain;return this.currentDomain=Z,$(),this.currentDomain=X,this},writable:!0,configurable:!0},prefix:{value(Z,$){return this.group({prefix:Z},$)},writable:!0,configurable:!0},resource:{value(Z,$,X="api"){let J=Z.endsWith("s")?Z:`${Z}s`,Q=Z.endsWith("s")?Z.slice(0,-1):Z,_=[{name:"index",method:"GET",path:`/${J}`,action:"index"},{name:"create",method:"GET",path:`/${J}/create`,action:"create"},{name:"store",method:"POST",path:`/${J}`,action:"store"},{name:"show",method:"GET",path:`/${J}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${J}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${J}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${J}/{id}`,action:"destroy"}];return this.name(Q,()=>{for(let j of _){let G;if(typeof $==="string")G=`${$}${j.action.charAt(0).toUpperCase()+j.action.slice(1)}Action`;else if($[j.action])G=$[j.action];else continue;switch(j.method){case"GET":this.get(j.path,G,X,j.name);break;case"POST":this.post(j.path,G,X,j.name);break;case"PUT":this.put(j.path,G,X,j.name);break;case"DELETE":this.delete(j.path,G,X,j.name);break}}}),this},writable:!0,configurable:!0}})}function $8(Y){Object.defineProperties(Y.prototype,{addRoute:{value(Z,$,X,J,Q,_){let j=$,G=[],W=J||"web";if(this.currentGroup){if(this.currentGroup.prefix)j=f(this.currentGroup.prefix,$);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)G=[...this.currentGroup.middleware]}if(_&&_.length>0)for(let U of _){let A=this.resolveMiddleware(U);if(A)G.push(A)}if(W==="api"&&this.config.apiPrefix)j=f(this.config.apiPrefix,j);else if(W==="web"&&this.config.webPrefix)j=f(this.config.webPrefix,j);let K;if(this.currentDomain)K=this.currentDomain;let z={method:Z.toUpperCase(),path:j,handler:X,domain:K,params:{},middleware:G},L=xY(j),V={};if(L.forEach((U)=>{let A=U.replace("?","");if(this.patterns.has(A))V[A]=this.patterns.get(A)}),Object.keys(V).length>0)z.constraints=V;if(z.pattern={exec:(U)=>{let A={},I=z.constraints&&!Array.isArray(z.constraints)?z.constraints:void 0;if(!x(j,U.pathname,A,I))return null;return{pathname:{groups:A}}}},X instanceof Response)this.staticResponses.set(j,X);if(K){if(!this.domains[K])this.domains[K]=[];this.domains[K].push(z)}else this.routes.push(z);if(!j.includes("{")&&!j.includes("*")){if(!this.staticRoutes.has(Z.toUpperCase()))this.staticRoutes.set(Z.toUpperCase(),new Map);let U=this.staticRoutes.get(Z.toUpperCase());if(!U.has(j))U.set(j,z)}if(Q)z.name=Q,this.namedRoutes.set(Q,z),g(Q,z.path);if(this.addRouteToCompiler&&!K)this.addRouteToCompiler(z);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(Z,$,X,J,Q){return this.addRoute("GET",Z,$,X,J,Q)},writable:!0,configurable:!0},post:{value(Z,$,X,J,Q){return this.addRoute("POST",Z,$,X,J,Q)},writable:!0,configurable:!0},put:{value(Z,$,X,J,Q){return this.addRoute("PUT",Z,$,X,J,Q)},writable:!0,configurable:!0},patch:{value(Z,$,X,J,Q){return this.addRoute("PATCH",Z,$,X,J,Q)},writable:!0,configurable:!0},delete:{value(Z,$,X,J,Q){return this.addRoute("DELETE",Z,$,X,J,Q)},writable:!0,configurable:!0},options:{value(Z,$,X,J,Q){return this.addRoute("OPTIONS",Z,$,X,J,Q)},writable:!0,configurable:!0},head:{value(Z,$,X,J,Q){return this.addRoute("HEAD",Z,$,X,J,Q)},writable:!0,configurable:!0},match:{value(Z,$,X,J,Q,_){for(let j of Z)this.addRoute(j,$,X,J,Q,_);return this},writable:!0,configurable:!0},any:{value(Z,$,X,J,Q){let _=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(_,Z,$,X,J,Q)},writable:!0,configurable:!0},fallback:{value(Z){return this.fallbackHandler=Z,this},writable:!0,configurable:!0},route:{value(Z,$={}){let X=this.namedRoutes.get(Z);if(!X)throw Error(`Route with name "${Z}" not found`);let J=X.path;for(let[Q,_]of Object.entries($))J=J.replace(`{${Q}}`,encodeURIComponent(_)),J=J.replace(`{${Q}?}`,encodeURIComponent(_));if(J.includes("{")){if(J=J.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),J.length>1&&J.endsWith("/"))J=J.slice(0,-1)}return J},writable:!0,configurable:!0},onError:{value(Z){return this.errorHandler=Z,this},writable:!0,configurable:!0}})}function X8(Y){Object.defineProperties(Y.prototype,{redirect:{value(Z,$=302){let X=new Headers;return X.set("Location",Z),new Response(null,{status:$,headers:X})},writable:!0,configurable:!0},permanentRedirect:{value(Z){return this.redirect(Z,301)},writable:!0,configurable:!0},redirectRoute:{value(Z,$,X=302){return this.get(Z,(J)=>{return this.redirect($,X)}),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(Z,$){return this.redirectRoute(Z,$,301)},writable:!0,configurable:!0}})}function T(Y){if(Y instanceof Response)return Y;if(Y===null||Y===void 0)return new Response(null,{status:204});if(typeof Y==="string")return new Response(Y,{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(typeof Y==="number"||typeof Y==="boolean")return new Response(String(Y),{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(Y instanceof ArrayBuffer||Y instanceof Uint8Array)return new Response(Y,{headers:{"Content-Type":"application/octet-stream"}});if(Y instanceof ReadableStream)return new Response(Y);if(typeof Y==="object")return new Response(JSON.stringify(Y),{headers:{"Content-Type":"application/json; charset=utf-8"}});return new Response(String(Y),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function D$(Y,Z){let $=Z.actionsPath||"actions",X=Z.controllersPath||"controllers",J=Y.replace(/\.(ts|js)$/,""),Q=[];if(J.includes("@")){let[j,G]=J.split("@");Q.push(`${X}/${j}`,`${X}/${j}.ts`,`${X}/${j}.js`,`./${X}/${j}`,`../${X}/${j}`)}else if(J.startsWith("Actions/")||J.startsWith("actions/"))Q.push(J,`./${J}`,`../${J}`);else if(J.startsWith("./")||J.startsWith("../"))Q.push(J);else Q.push(`${$}/${J}`,`./${$}/${J}`,`../${$}/${J}`,J,`./${J}`,`../${J}`);let _=null;for(let j of Q)try{return await import(j)}catch(G){_=G}throw Error(`Failed to import handler "${Y}".
|
|
94
|
-
Tried paths: ${
|
|
95
|
-
Last error: ${
|
|
96
|
-
Tried paths: ${
|
|
97
|
-
Last error: ${K?.message||"Unknown error"}`);let z=W.default||W;if(typeof z==="function"){let L=new z,V=L[j];if(typeof V!=="function")throw TypeError(`Method "${j}" not found on controller "${_}"`);let U=await V.call(L,Z);return T(U)}throw Error(`Controller "${_}" is not a valid class`)}let J=await D$(Y,$),Q=J.default||J;if(typeof Q==="function"){if(Q.prototype&&typeof Q.prototype.handle==="function"){let G=await new Q().handle(Z);return T(G)}let _=await Q(Z);return T(_)}if(Q&&typeof Q==="object"&&"handle"in Q){let _=Q;if(typeof _.handle==="function"){let j=await _.handle(Z);return T(j)}}throw Error(`Handler "${Y}" does not export a valid handler function or class`)}function I$(Y){return(Z,$)=>GY(Z,$,Y)}function Q8(Y,Z){if(Y instanceof Response)return async()=>Y.clone();if(J8(Y))return async($)=>T(await Y($));if(typeof Y==="function"&&Y.prototype&&typeof Y.prototype.handle==="function"){let $=Y;return async(X)=>T(await new $().handle(X))}return($)=>GY(Y,$,Z)}function _8(Y){Object.defineProperties(Y.prototype,{use:{value(...Z){for(let $ of Z){let X=this.resolveMiddleware($);if(X)this.globalMiddleware.push(X)}return this._mwEpoch=(this._mwEpoch||0)+1,this},writable:!0,configurable:!0},resolveMiddleware:{value(Z){if(typeof Z==="function")return Z;if(typeof Z==="object"&&Z!==null&&"handle"in Z&&typeof Z.handle==="function")return($,X)=>{return Z.handle($,X)};if(typeof Z==="string"){let[$,X]=Z.split(":"),J=this.namedMiddleware?.get($);if(J)return J(X);let Q=null,_=Z;return async(j,G)=>{if(!Q)try{let W=await import(`../middleware/${_}.ts`);if(W.default&&typeof W.default==="function")Q=W.default;else if(W.default&&typeof W.default.handle==="function")Q=(K,z)=>W.default.handle(K,z)}catch(W){console.error(`Failed to load middleware "${_}":`,W)}if(Q)return Q(j,G);return G()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value(Z){if(Z.length===0)return async(X)=>null;let $=async(X)=>null;for(let X=Z.length-1;X>=0;X--){let J=Z[X],Q=$;$=async(_)=>{return J(_,async()=>{return await Q(_)||new Response(null,{status:200})})}}return $},writable:!0,configurable:!0},runMiddleware:{async value(Z,$){if($.length===0)return null;try{return await this.buildMiddlewareChain($)(Z)}catch(X){if(this.errorHandler)return this.errorHandler(X);throw X}},writable:!0,configurable:!0},middleware:{value(...Z){for(let $ of Z)if(typeof $==="string"){let[X]=$.split(":");if(!this.namedMiddleware.has(X))throw Error(`Unknown middleware: ${X}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...Z)}else{let $=this.routes[this.routes.length-1];if($)this.applyMiddlewareToRoute($,Z)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(Z,$){for(let X of $){let J=this.resolveMiddleware(X);if(J)Z.middleware.push(J)}},writable:!0,configurable:!0},resolveHandler:{async value(Z,$){return GY(Z,$,this.config)},writable:!0,configurable:!0},wrapResponse:{value:T,writable:!0,configurable:!0},onError:{value(Z){return this.errorHandler=Z,this},writable:!0,configurable:!0}})}class j8{models=new Map;cache=new Map;register(Y,Z){this.models.set(Y,Z)}get(Y){return this.models.get(Y)}has(Y){return this.models.has(Y)}async resolve(Y,Z,$){let X=this.models.get(Y);if(!X)return{model:null,error:`Model binding '${Y}' not found`,status:500};try{if(X.cache?.enabled){let _=this.getCachedModel(Y,Z,X);if(_)return{model:_}}let J=await X.resolver(Z,$);if(J===null||J===void 0)return{model:null,error:`${Y} not found`,status:404};if(X.validator){let _=await X.validator(J,Z,$);if(!_.valid)return{model:null,error:_.error||"Model validation failed",status:_.status||422}}let Q=J;if(X.transformer)Q=await X.transformer(J,Z,$);if(X.cache?.enabled)this.cacheModel(Y,Z,Q,X);return{model:Q}}catch(J){return{model:null,error:J instanceof Error?J.message:"Model resolution failed",status:500}}}createErrorResponse(Y,Z,$){let X=this.models.get(Y),J=Z.status||404,Q=Z.error||"Model not found";if(X?.errorHandling){if(J===404&&X.errorHandling.notFound)return X.errorHandling.notFound($);if(J===422&&X.errorHandling.validation)return X.errorHandling.validation(null,Q);if(X.errorHandling.transform)return X.errorHandling.transform(Q)}return new Response(JSON.stringify({error:Q,status:J,message:`Failed to resolve ${Y}`}),{status:J,headers:{"Content-Type":"application/json"}})}clearCache(Y,Z){if(Z){let $=this.models.get(Y);if($?.cache){let X=this.generateCacheKey(Y,Z,$);this.cache.delete(X)}}else{let $=[];for(let X of this.cache.keys())if(X.startsWith(`${Y}:`))$.push(X);for(let X of $)this.cache.delete(X)}}clearAllCache(){this.cache.clear()}getCacheStats(){let Y=Date.now(),Z=0,$=0;for(let X of this.cache.values())if(Y-X.timestamp>X.ttl)$++;else Z++;return{totalEntries:this.cache.size,validEntries:Z,expiredEntries:$,models:this.models.size}}cleanupCache(){let Y=Date.now(),Z=[];for(let[$,X]of this.cache.entries())if(Y-X.timestamp>X.ttl)Z.push($);for(let $ of Z)this.cache.delete($);return Z.length}getCachedModel(Y,Z,$){if(!$.cache?.enabled)return null;let X=this.generateCacheKey(Y,Z,$),J=this.cache.get(X);if(!J)return null;if(Date.now()-J.timestamp>J.ttl)return this.cache.delete(X),null;return J.model}cacheModel(Y,Z,$,X){if(!X.cache?.enabled)return;let J=this.generateCacheKey(Y,Z,X);this.cache.set(J,{model:$,timestamp:Date.now(),ttl:X.cache.ttl})}generateCacheKey(Y,Z,$){if($.cache?.key)return`${Y}:${$.cache.key(Z)}`;let X=Object.entries(Z).sort(([J],[Q])=>J.localeCompare(Q)).map(([J,Q])=>`${J}=${Q}`).join("&");return`${Y}:${X}`}}var G8=new j8;function W8(Y){Object.defineProperties(Y.prototype,{modelRegistry:{value:G8,writable:!0,configurable:!0},model:{value(Z,$,X){if(typeof $==="string")this.modelRegistry.register(Z,{resolver:async(J)=>{return console.warn(`Model class ${$} not implemented`),{id:J[Z],modelClass:$}},errorHandling:X?{notFound:(J)=>X(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(Z,{resolver:async(J)=>{let Q=J[Z];if(!Q)return null;return $(Q)},errorHandling:X?{notFound:(J)=>X(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(Z,$)=>{if(!Z.params)return await $()||new Response("Not Found",{status:404});for(let[J,Q]of Object.entries(Z.params))if(this.modelRegistry.has(J))try{let _=await this.modelRegistry.resolve(J,Z.params,Z);if(_.model===null){if(_.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:_.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(_.status===404)return this.modelRegistry.createErrorResponse(J,_,Z.params)}else Z[J]=_.model}catch(_){return new Response(JSON.stringify({error:"Internal Server Error",message:_ instanceof Error?_.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await $()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(Z){return async($,X)=>{try{return await X()||Z($)}catch(J){return console.error(J),Z($)}}},writable:!0,configurable:!0},scopedBindings:{value(Z){return async($,X)=>{if(!$.params)return await X()||new Response("Not Found",{status:404});for(let[Q,_]of Object.entries(Z))if($.params[Q]&&$.params[_]);return await X()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},clearModelCache:{value(Z){if(Z)this.modelRegistry.clearCache(Z);else this.modelRegistry.clearAllCache();return this},writable:!0,configurable:!0},getModelStats:{value(){return this.modelRegistry.getCacheStats()},writable:!0,configurable:!0}})}class h{children=new Map;paramChild=null;wildcardChild=null;routes=new Map;paramName=null;pattern=null;isEndpoint=!1;addRoute(Y,Z){this.routes.set(Y,Z),this.isEndpoint=!0}getRoute(Y){return this.routes.get(Y)}getAllRoutes(){return Array.from(this.routes.values())}}class YZ{root=new h;compiledRoutes=new Map;methodTries=new Map;constructor(){let Y=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","TRACE","CONNECT"];for(let Z of Y)this.methodTries.set(Z,new h)}compileRoute(Y){let Z=`${Y.method}:${Y.path}`;if(Y.constraints&&!Array.isArray(Y.constraints)){let G=Y.constraints,K=Object.keys(G).sort().map((z)=>`${z}:${G[z]}`).join("|");Z=`${Y.method}:${Y.path}#${K}`}if(this.compiledRoutes.has(Z))return this.compiledRoutes.get(Z);let $=this.parsePathSegments(Y.path),X=$.filter((G)=>G.type==="parameter").map((G)=>G.paramName);if(Y.constraints&&!Array.isArray(Y.constraints)){let G=Y.constraints;for(let W of $)if(W.type==="parameter"&&W.paramName&&G[W.paramName])W.pattern=new RegExp(`^${G[W.paramName]}$`)}let J=this.calculateRoutePriority($),Q=$.filter((G)=>G.type==="static").length,_=$.filter((G)=>G.type!=="static").length,j={route:Y,segments:$,paramNames:X,priority:J,staticScore:Q,dynamicScore:_};return this.compiledRoutes.set(Z,j),j}parsePathSegments(Y){let Z=[],$=Y.split("/").filter((X)=>X.length>0);for(let X of $)if(X==="*")Z.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(X))Z.push({type:"wildcard",value:X,paramName:X.slice(1,X.indexOf("}"))});else if(X.startsWith("{")&&X.endsWith("}")){let J=X.slice(1,-1),[Q,_]=J.split(":");Z.push({type:"parameter",value:X,paramName:Q.replace("?",""),pattern:_?new RegExp(`^${_}$`):void 0,optional:J.endsWith("?")})}else if(X.includes("{")){let J=X.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(_,j,G)=>{return G?`(${G})`:"([^/]+)"}),Q=Array.from(X.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((_)=>_[1].replace("?",""));Z.push({type:"parameter",value:X,paramName:Q[0],pattern:new RegExp(`^${J}$`)})}else Z.push({type:"static",value:X});return Z}calculateRoutePriority(Y){let Z=0;for(let $=0;$<Y.length;$++){let X=Y[$],J=Y.length-$;switch(X.type){case"static":Z+=J*1000;break;case"parameter":if(X.pattern)Z+=J*100;else Z+=J*10;break;case"wildcard":Z+=J*1;break}}return Z}addRoute(Y){let Z=this.compileRoute(Y);this.insertRoute(this.root,Z,0);let $=this.methodTries.get(Y.method);if($)this.insertRoute($,Z,0)}insertRoute(Y,Z,$){if($>=Z.segments.length){Y.addRoute(Z.route.method,Z);return}let X=Z.segments[$];switch(X.type){case"static":if(!Y.children.has(X.value))Y.children.set(X.value,new h);this.insertRoute(Y.children.get(X.value),Z,$+1);break;case"parameter":if(!Y.paramChild)Y.paramChild=new h,Y.paramChild.paramName=X.paramName,Y.paramChild.pattern=X.pattern||null;this.insertRoute(Y.paramChild,Z,$+1);break;case"wildcard":if(!Y.wildcardChild)Y.wildcardChild=new h,Y.wildcardChild.paramName=X.paramName??null;this.insertRoute(Y.wildcardChild,Z,$+1);break}}match(Y,Z){let $=Y.split("/").filter((J)=>J.length>0),X=this.methodTries.get(Z);if(X){let J=this.matchSegments(X,$,0,{},Z);if(J)return J}return this.matchSegments(this.root,$,0,{},Z)}matchSegments(Y,Z,$,X,J){if($>=Z.length){let G=Y.getRoute(J);if(G)return{route:G.route,params:X,score:G.priority};return null}let Q=Z[$],_=Y.children.get(Q);if(_){let G=this.matchSegments(_,Z,$+1,X,J);if(G)return G}let j=Y.paramChild;if(j&&j.paramName&&(!j.pattern||j.pattern.test(Q))){let G=X[j.paramName];X[j.paramName]=Q;let W=this.matchSegments(j,Z,$+1,X,J);if(W)return W;if(G===void 0)delete X[j.paramName];else X[j.paramName]=G}if(Y.wildcardChild){let G=Y.wildcardChild.getRoute(J);if(G)return X[Y.wildcardChild.paramName??"wildcard"]=Z.slice($).join("/"),{route:G.route,params:X,score:G.priority}}return null}getAllRoutes(){return Array.from(this.compiledRoutes.values())}removeRoute(Y){let Z=`${Y.method}:${Y.path}`;if(Y.constraints&&!Array.isArray(Y.constraints)){let $=Y.constraints,J=Object.keys($).sort().map((Q)=>`${Q}:${$[Q]}`).join("|");Z=`${Y.method}:${Y.path}#${J}`}this.compiledRoutes.delete(Z)}clear(){this.root=new h,this.compiledRoutes.clear();for(let[Y]of this.methodTries)this.methodTries.set(Y,new h)}getStats(){let Y={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let Z of this.compiledRoutes.values()){let $=Z.route.method;Y.methodDistribution[$]=(Y.methodDistribution[$]||0)+1}return Y}countNodes(Y){let Z=1;for(let $ of Y.children.values())Z+=this.countNodes($);if(Y.paramChild)Z+=this.countNodes(Y.paramChild);if(Y.wildcardChild)Z+=this.countNodes(Y.wildcardChild);return Z}}class RY{trie;matchCache=new Map;routeKeys=new Set;stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}};options;constructor(Y={}){this.options={enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0,enableProfiling:!1,...Y},this.trie=new YZ}addRoute(Y){if(this.options.precompilePatterns)this.precompileRoutePattern(Y);let Z=`${Y.method}:${Y.path}`;if(this.routeKeys.has(Z))return!1;if(this.routeKeys.add(Z),this.trie.addRoute(Y),this.options.enableCaching)this.matchCache.clear();let $=Y.method;return this.stats.methodDistribution[$]=(this.stats.methodDistribution[$]||0)+1,!0}patternCache=new Map;extractParamNames(Y){let Z=[],$=/\{([^}:]+)(?::[^}]+)?\}/g,X;while(X=$.exec(Y))Z.push(X[1].replace("?",""));return Z}precompileRoutePattern(Y){if(!Y.pattern&&Y.path.includes("{")){let Z=Y.path;if(Y.constraints&&!Array.isArray(Y.constraints)){let J=Y.constraints,_=Object.keys(J).sort().map((j)=>`${j}:${J[j]}`).join("|");Z=`${Y.path}#${_}`}if(this.patternCache.has(Z)){Y.pattern=this.patternCache.get(Z);return}let $=this.convertToURLPattern(Y.path,Y.constraints&&!Array.isArray(Y.constraints)?Y.constraints:void 0),X={exec:(J)=>{let Q=J.pathname,_=$.exec(Q);if(!_)return null;return{pathname:{groups:_.groups||{}}}}};this.patternCache.set(Z,X),Y.pattern=X}}convertToURLPattern(Y,Z){let $=Y,X=null,J=$.match(/\{([^{}/]+)\}\*$/);if(J)X=J[1],$=$.slice(0,J.index);else if($.endsWith("*"))X="wildcard",$=$.slice(0,-1);let Q=[],j=$.replace(/\{([^}]+)\}/g,(W,K)=>{return Q.push(K),`\x00${Q.length-1}\x00`}).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(j=j.replace(/\/?\u0000(\d+)\u0000/g,(W,K)=>{let z=Q[Number(K)],L=z.endsWith("?"),V=L?z.slice(0,-1):z,U=V.indexOf(":"),A=U===-1?V:V.slice(0,U),I=U===-1?void 0:V.slice(U+1),F=Z?.[A]??I??"[^/]+",i=`(?<${A}>${F})`,VY=W.startsWith("/")?"/":"";return L?`(?:${VY}${i})?`:`${VY}${i}`}),X!==null)j+=`(?<${X}>${Z?.[X]??".+"})`;let G=new RegExp(`^${j}$`);return{exec:(W)=>{let K=W.match(G);if(!K)return null;return{groups:K.groups||{}}}}}match(Y,Z){let $=this.options.enableProfiling?performance.now():0;if(this.stats.totalMatches++,this.options.enableCaching){let Q=`${Z}:${Y}`,_=this.matchCache.get(Q);if(_!==void 0||this.matchCache.has(Q)){if(this.stats.cacheHits++,$)this.updateMatchTime($);return _?{route:_.route,params:{..._.params}}:null}this.stats.cacheMisses++}let X=this.trie.match(Y,Z),J=null;if(X)J={route:X.route,params:X.params};if(this.options.enableCaching){let Q=`${Z}:${Y}`;this.addToCache(Q,J)}if($)this.updateMatchTime($);return J?{route:J.route,params:{...J.params}}:null}addToCache(Y,Z){if(this.matchCache.size>=this.options.cacheSize&&!this.matchCache.has(Y)){let $=this.matchCache.keys().next().value;if($!==void 0)this.matchCache.delete($)}this.matchCache.set(Y,Z)}updateMatchTime(Y){let Z=performance.now()-Y;this.stats.averageMatchTime=(this.stats.averageMatchTime*(this.stats.totalMatches-1)+Z)/this.stats.totalMatches}getCompiledRoutes(){let Y=this.trie.getAllRoutes();if(this.options.enablePriorityOptimization)return Y.sort((Z,$)=>$.priority-Z.priority);return Y}getRoutesByMethod(){let Y=new Map;for(let Z of this.trie.getAllRoutes()){let $=Z.route.method;if(!Y.has($))Y.set($,[]);Y.get($).push(Z)}if(this.options.enablePriorityOptimization)for(let[Z,$]of Y)$.sort((X,J)=>J.priority-X.priority),Y.set(Z,$);return Y}warmCache(Y,Z={}){if(!this.options.enableCaching&&!Z.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let $=this.options.enableCaching;if(Z.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(Z.precompile)for(let{path:K,method:z}of Y){let L=`${z}:${K}`;this.matchCache.delete(L)}let X=this.matchCache.size,J=this.stats.cacheHits,Q=this.stats.totalMatches;for(let{path:K,method:z}of Y)if(this.match(K,z),Z.precompile)this.match(K,z);let _=this.matchCache.size-X,j=this.stats.cacheHits-J,G=this.stats.totalMatches-Q,W=G>0?j/G:0;if(Z.force&&!$)this.options.enableCaching=$;return{warmedPaths:_,cacheSize:this.matchCache.size,hitRate:W}}clear(){this.trie.clear(),this.matchCache.clear(),this.routeKeys.clear(),this.stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}}}getStats(){let Y=this.trie.getStats();return{...this.stats,trieDepth:Y.averageDepth,methodDistribution:Y.methodDistribution}}getCacheStats(){let Y=this.stats.totalMatches>0?this.stats.cacheHits/this.stats.totalMatches:0;return{size:this.matchCache.size,maxSize:this.options.cacheSize,hitRate:Y,enabled:this.options.enableCaching}}optimizeRouteOrder(Y){if(!this.options.enablePriorityOptimization)return;this.matchCache.clear()}getRouteConflicts(){let Y=[],Z=this.trie.getAllRoutes(),$=new Map;for(let X of Z){let J=X.route.method;if(!$.has(J))$.set(J,[]);$.get(J).push(X)}for(let[X,J]of $)for(let Q=0;Q<J.length;Q++)for(let _=Q+1;_<J.length;_++){let j=J[Q],G=J[_];if(this.routesConflict(j,G)){let W=this.getConflictSeverity(j,G),K=this.getConflictType(j,G);Y.push({routes:[j,G],conflictType:K,severity:W})}}return Y}routesConflict(Y,Z){if(Y.route.path===Z.route.path)return!0;if(Y.route.method!==Z.route.method)return!1;return this.patternsOverlap(Y.segments,Z.segments)}patternsOverlap(Y,Z){let $=Y.some((_)=>_.optional||_.type==="wildcard"),X=Z.some((_)=>_.optional||_.type==="wildcard");if(Y.length!==Z.length&&!$&&!X)return!1;let J=Math.max(Y.length,Z.length),Q=!0;for(let _=0;_<J;_++){let j=_<Y.length?Y[_]:null,G=_<Z.length?Z[_]:null;if(!j&&G&&!G.optional)return!1;if(!G&&j&&!j.optional)return!1;if(!j||!G)continue;if(j.type==="static"&&G.type==="static"){if(j.value!==G.value)return!1}else if(j.type==="parameter"&&G.type==="parameter"){if(j.pattern&&G.pattern){if(j.pattern.toString()===G.pattern.toString())Q=!0}if(j.paramName===G.paramName)Q=!0}else if(j.type==="static"&&G.type==="parameter"||j.type==="parameter"&&G.type==="static"){let W=j.type==="static"?j:G,K=j.type==="parameter"?j:G;if(K.pattern){if(!K.pattern.test(W.value))return!1}}else if(j.type==="wildcard"||G.type==="wildcard")return!0}return Q}getConflictSeverity(Y,Z){if(Y.route.path===Z.route.path)return"high";if(Y.staticScore===Z.staticScore)return"medium";return"low"}getConflictType(Y,Z){if(Y.route.path===Z.route.path)return"duplicate";if(this.hasAmbiguousParameters(Y,Z))return"ambiguous";if(Math.abs(Y.priority-Z.priority)<10)return"ambiguous";return"overlap"}hasAmbiguousParameters(Y,Z){if(Math.abs(Y.segments.length-Z.segments.length)>1)return!1;let $=Y.segments.filter((J)=>J.type==="parameter").length,X=Z.segments.filter((J)=>J.type==="parameter").length;if($>0&&X>0){let J=Math.min(Y.segments.length,Z.segments.length),Q=0;for(let _=0;_<J;_++)if(Y.segments[_].type==="parameter"&&Z.segments[_].type==="parameter"){Q++;let j=!!Y.segments[_].pattern,G=!!Z.segments[_].pattern;if(j!==G)return!0}return Q>0&&Q>=Math.min($,X)/2}return!1}}function K8(Y){Object.defineProperties(Y.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new RY({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0})},writable:!0,configurable:!0},addRouteToCompiler:{value(Z){this.initializeRouteCompiler(),this.routeCompiler.addRoute(Z)},writable:!0,configurable:!0},matchRoute:{value(Z,$,X){if(this.initializeRouteCompiler(),X&&this.domains[X]){let J=this.fallbackMatchRoute(Z,$,X);if(J)return J}else{let J=this.routeCompiler.match(Z,$);if(J&&(!X||!J.route.domain||J.route.domain===X))return J;let Q=this.fallbackMatchRoute(Z,$,X);if(Q)return Q}if($==="HEAD")return this.matchRoute(Z,"GET",X);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(Z,$,X){let J=new URL(Z,"http://localhost"),Q=`${X||""}:${$}:${J.pathname}`;if(this.routeCache.has(Q))return this.routeCache.get(Q);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has($)){let W=this.staticRoutes.get($).get(J.pathname);if(W&&(!X||!W.domain||W.domain===X)){let K={route:W,params:{}};return this.routeCache.set(Q,K),K}}let j=(X&&this.domains[X]?this.domains[X]:this.routes).filter((W)=>W.method===$);for(let W of j)if(W.path===J.pathname){let K={route:W,params:{}};return this.routeCache.set(Q,K),K}for(let W of j)if(W.pattern){let K=W.pattern.exec(J);if(K){let z={route:W,params:K.pathname.groups};return this.routeCache.set(Q,z),z}}let G=X&&this.domains[X]?[this.domains[X],this.routes]:[this.routes];for(let W of G)for(let K of W){if(K.method!==$||!K.path.endsWith("*"))continue;let z=K.path.slice(0,-1);if(J.pathname.startsWith(z)){let L={route:K,params:{wildcard:J.pathname.slice(z.length)}};return this.routeCache.set(Q,L),L}}this.routeCache.set(Q,void 0);return},writable:!0,configurable:!0},getRouteStats:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getStats()},writable:!0,configurable:!0},getCacheStats:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getCacheStats()},writable:!0,configurable:!0},warmRouteCache:{value(Z){this.initializeRouteCompiler(),this.routeCompiler.warmCache(Z)},writable:!0,configurable:!0},getRoutesByMethod:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getRoutesByMethod()},writable:!0,configurable:!0},getRouteConflicts:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getRouteConflicts()},writable:!0,configurable:!0},clearRouteCache:{value(){if(this.routeCompiler)this.routeCompiler.clear();this.routeCache.clear()},writable:!0,configurable:!0},rebuildRouteCompiler:{value(){this.routeCompiler=new RY({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0});for(let Z of this.routes)this.routeCompiler.addRoute(Z);for(let Z of Object.values(this.domains))for(let $ of Z)this.routeCompiler.addRoute($)},writable:!0,configurable:!0},optimizeRoutes:{value(Z={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(Z)},writable:!0,configurable:!0}})}function z8(Y){Object.defineProperties(Y.prototype,{buildBunServeRoutes:{value(){let Z={},$=new Map;for(let X of this.routes){if(!$.has(X.path))$.set(X.path,[]);$.get(X.path).push(X)}for(let[X,J]of $.entries())if(J.length===1){let Q=J[0];if(typeof Q.handler==="function"&&Q.handler.toString().includes("new Response")&&!Q.handler.toString().includes("await")&&Q.middleware.length===0)try{let _=this.enhanceRequest(new Request("https://example.com"),{}),j=Q.handler(_);if(j instanceof Response){Z[X]=j;continue}}catch{}Z[X]=async(_)=>{let j=new URL(_.url),G={},W=Q.constraints&&!Array.isArray(Q.constraints)?Q.constraints:void 0;x(X,j.pathname,G,W);let K=this.enhanceRequest(_,G),z=async(U,A)=>await this.resolveHandler(Q.handler,U),L=[...this.globalMiddleware,...Q.middleware,z],V=await this.runMiddleware(K,L);return this.applyModifiedCookies(V??new Response("No response from middleware chain",{status:500}),K)}}else{let Q={};for(let _ of J){let j=_.method;Q[j]=async(G)=>{let W=new URL(G.url),K={},z=_.constraints&&!Array.isArray(_.constraints)?_.constraints:void 0;x(X,W.pathname,K,z);let L=this.enhanceRequest(G,K),V=async(I,F)=>await this.resolveHandler(_.handler,I),U=[...this.globalMiddleware,..._.middleware,V],A=await this.runMiddleware(L,U);return this.applyModifiedCookies(A??new Response("No response from middleware chain",{status:500}),L)}}Z[X]=Q}return Z},writable:!0,configurable:!0},loadRoutes:{async value(){if(!this.config.routesPath)return;try{if(this.config.apiRoutesPath)try{let Z=await import(this.config.apiRoutesPath);if(Z.default&&Array.isArray(Z.default))for(let $ of Z.default)this.registerRoute($,"api")}catch(Z){if(this.config.verbose)console.warn(`Failed to load API routes: ${Z}`)}if(this.config.webRoutesPath)try{let Z=await import(this.config.webRoutesPath);if(Z.default&&Array.isArray(Z.default))for(let $ of Z.default)this.registerRoute($,"web")}catch(Z){if(this.config.verbose)console.warn(`Failed to load Web routes: ${Z}`)}}catch(Z){console.error("Error loading routes:",Z)}},writable:!0,configurable:!0},registerRoute:{value(Z,$){let{path:X,method:J,handler:Q,middleware:_=[],name:j}=Z;switch(J){case"GET":this.get(X,Q,$,j,_);break;case"POST":this.post(X,Q,$,j,_);break;case"PUT":this.put(X,Q,$,j,_);break;case"DELETE":this.delete(X,Q,$,j,_);break;case"PATCH":this.patch(X,Q,$,j,_);break;case"OPTIONS":this.options(X,Q,$,j,_);break;default:console.warn(`Unsupported HTTP method: ${J}`)}},writable:!0,configurable:!0}})}function L8(Y){Object.defineProperties(Y.prototype,{matchRoute:{value(Z,$,X){let J=new URL(Z,"http://localhost"),Q=`${X||""}:${$}:${J.pathname}`;if(this.routeCache.has(Q))return this.routeCache.get(Q);if(this.staticRoutes.has($)){let W=this.staticRoutes.get($).get(J.pathname);if(W&&(!X||!W.domain||W.domain===X)){let K={route:W,params:{}};return this.routeCache.set(Q,K),K}}let _=X&&this.domains[X]?this.domains[X]:this.routes,j=_.filter((W)=>W.method===$);for(let W of j)if(W.path===J.pathname){let K={route:W,params:{}};return this.routeCache.set(Q,K),K}for(let W of j)if(W.pattern){let K=W.pattern.exec(J);if(K){let z={route:W,params:K.pathname.groups};return this.routeCache.set(Q,z),z}}if(X&&this.domains[X]){let W=this.domains[X].filter((K)=>K.method===$&&K.path.endsWith("*"));for(let K of W){let z=K.path.slice(0,-1);if(J.pathname.startsWith(z)){let L={route:K,params:{wildcard:J.pathname.slice(z.length)}};return this.routeCache.set(Q,L),L}}}let G=this.routes.filter((W)=>W.method===$&&W.path.endsWith("*")&&(!X||!W.domain));for(let W of G){let K=W.path.slice(0,-1);if(J.pathname.startsWith(K)){let z={route:W,params:{wildcard:J.pathname.slice(K.length)}};return this.routeCache.set(Q,z),z}}if($==="HEAD")return this.matchRoute(Z,"GET",X);if($==="OPTIONS"){let W=_.find((K)=>K.method==="OPTIONS"&&K.path==="*");if(W){let K={route:W,params:{}};return this.routeCache.set(Q,K),K}for(let K of["GET","POST","PUT","PATCH","DELETE"]){let z=this.matchRoute(Z,K,X);if(z){let L={route:{...z.route,method:"OPTIONS",handler:(V)=>new Response(null,{status:204})},params:z.params};return this.routeCache.set(Q,L),L}}}return},writable:!0,configurable:!0},matchDomain:{value(Z,$){if(Z===$)return!0;if(Z.startsWith("*.")){let X=Z.substring(2);return $===X||$.endsWith(`.${X}`)}if(Z.includes("{")){let X;if(!this.domainPatternCache.has(Z)){let J=Z.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");X=new RegExp(`^${J}$`),this.domainPatternCache.set(Z,X)}else X=this.domainPatternCache.get(Z);return X.test($)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(Z,$){let X={};if(!Z.includes("{"))return X;let J=Z.match(/\{([^}]+)\}/g)?.map((j)=>j.substring(1,j.length-1))||[],Q=Z.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),_=$.match(new RegExp(`^${Q}$`));if(_&&_.length>1)for(let j=0;j<J.length;j++)X[J[j]]=_[j+1];return X},writable:!0,configurable:!0},pattern:{value(Z,$){return this.patterns.set(Z,$),this},writable:!0,configurable:!0},where:{value(Z){let $=this.routes[this.routes.length-1];if($){$.constraints={...$.constraints||{},...Z};let X=$.path,J=$.constraints&&!Array.isArray($.constraints)?$.constraints:void 0;if($.pattern={exec:(Q)=>{let _={};if(!x(X,Q.pathname,_,J))return null;return{pathname:{groups:_}}}},this.routeCache.clear(),this.routeCompiler){let Q=[...this.routes];this.routeCompiler.clear();for(let _ of Q)this.routeCompiler.addRoute(_)}}return this},writable:!0,configurable:!0},withoutNativeDispatch:{value(){let Z=this.routes[this.routes.length-1];if(Z)Z.nativeDispatch=!1;return this},writable:!0,configurable:!0},whereNumber:{value(Z){return this.where({[Z]:"\\d+"})},writable:!0,configurable:!0},whereAlpha:{value(Z){return this.where({[Z]:"[A-Za-z]+"})},writable:!0,configurable:!0},whereAlphaNumeric:{value(Z){return this.where({[Z]:"[A-Za-z0-9]+"})},writable:!0,configurable:!0},whereUuid:{value(Z){return this.where({[Z]:"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"})},writable:!0,configurable:!0},whereIn:{value(Z,$){return this.where({[Z]:$.join("|")})},writable:!0,configurable:!0}})}class O{routes=[];currentGroup=null;globalMiddleware=[];namedRoutes=new Map;fallbackHandler=null;patterns=new Map;currentDomain=null;domains={};serverInstance=null;wsConfig=null;errorHandler=null;templateCache=new Map;routeCache=new Map;staticRoutes=new Map;staticResponses=new Map;precompiledPatterns=new Map;domainPatternCache=new Map;routeCompiler=null;middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];_middlewarePipeline;_mwEpoch=0;_allowedMethodsCache=new Map;config={verbose:!1,routesPath:"routes",apiRoutesPath:"routes/api.ts",webRoutesPath:"routes/web.ts",apiPrefix:"/api",webPrefix:"",actionsPath:"actions",controllersPath:"controllers",defaultMiddleware:{api:[],web:[]}};constructor(Y={}){this.routes=[],this.config={...this.config,...Y},this.initializeDefaultMiddleware()}initializeDefaultMiddleware(){this.namedMiddleware.set("auth",()=>async(Y,Z)=>{if(!Y.headers.get("authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return await Z()}),this.namedMiddleware.set("throttle",(Y)=>{let Z=Y?t(Y):{maxAttempts:60,windowMs:60000};return a({maxAttempts:Z.maxAttempts||60,windowMs:Z.windowMs,keyGenerator:($)=>$.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(Y,Z)=>{let $=await Z();if($)$.headers.set("Access-Control-Allow-Origin","*"),$.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),$.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return $})}middlewareGroup(Y,Z){let $=[];for(let X of Z){let[J,Q]=X.split(":"),_=this.namedMiddleware.get(J);if(_)$.push(_(Q))}return this.middlewareGroups.set(Y,$),this}middlewareGroupRoutes(Y){let Z=this.middlewareGroups.get(Y)||[];return new A8(this,Z)}when(Y){return new U8(this,Y)}middleware(Y){let[Z,$]=Y.split(":"),X=this.namedMiddleware.get(Z);if(!X)throw Error(`Unknown middleware: ${Z}`);let J=X($);return new V8(this,[J])}getServer(){return this.serverInstance}extend(Y){for(let[Z,$]of Object.entries(Y))if(typeof $==="function")this[Z]=$.bind(this);return this}async register(Y,Z){let $=async()=>{await import(Y)};if(Z?.prefix||Z?.middleware&&Z.middleware.length>0)await this.group({prefix:Z.prefix,middleware:Z.middleware},$);else await $();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(Y,Z,$,X,J,Q){let _=Z,j=[],G=X||"web";if(this.currentGroup){if(this.currentGroup.prefix)_=f(this.currentGroup.prefix,Z);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)j=[...this.currentGroup.middleware]}if(Q&&Q.length>0)for(let V of Q){let U=this.resolveMiddleware(V);if(U)j.push(U)}if(G==="api"&&this.config.apiPrefix)_=f(this.config.apiPrefix,_);else if(G==="web"&&this.config.webPrefix)_=f(this.config.webPrefix,_);let W;if(this.currentDomain)W=this.currentDomain;let K={method:Y.toUpperCase(),path:_,handler:$,domain:W,params:{},middleware:j},z=xY(_),L={};if(z.forEach((V)=>{let U=V.replace("?","");if(this.patterns.has(U))L[U]=this.patterns.get(U)}),Object.keys(L).length>0)K.constraints=L;if(K.pattern={exec:(V)=>{let U={},A=K.constraints&&!Array.isArray(K.constraints)?K.constraints:void 0;if(!x(_,V.pathname,U,A))return null;return{pathname:{groups:U}}}},W){if(!this.domains[W])this.domains[W]=[];this.domains[W].push(K)}else this.routes.push(K);if(!_.includes("{")&&!_.includes("*")){if(!this.staticRoutes.has(Y.toUpperCase()))this.staticRoutes.set(Y.toUpperCase(),new Map);this.staticRoutes.get(Y.toUpperCase()).set(_,K)}if(J)K.name=J,this.namedRoutes.set(J,K),g(J,K.path);return this.routeCache.clear(),this}resolveMiddleware(Y){if(typeof Y==="function")return Y;let[Z,$]=Y.split(":"),X=this.namedMiddleware.get(Z);if(X)return X($);return null}get(Y,Z,$,X,J){return this.registerRoute("GET",Y,Z,$,X,J)}post(Y,Z,$,X,J){return this.registerRoute("POST",Y,Z,$,X,J)}put(Y,Z,$,X,J){return this.registerRoute("PUT",Y,Z,$,X,J)}patch(Y,Z,$,X,J){return this.registerRoute("PATCH",Y,Z,$,X,J)}delete(Y,Z,$,X,J){return this.registerRoute("DELETE",Y,Z,$,X,J)}options(Y,Z,$,X,J){return this.registerRoute("OPTIONS",Y,Z,$,X,J)}match(Y,Z,$,X,J,Q){for(let _ of Y)this.registerRoute(_,Z,$,X,J,Q);return this}any(Y,Z,$,X,J){let Q=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(Q,Y,Z,$,X,J)}fallback(Y){return this.fallbackHandler=Y,this}route(Y,Z={}){let $=this.namedRoutes.get(Y);if(!$)throw Error(`Route with name "${Y}" not found`);let X=$.path;for(let[J,Q]of Object.entries(Z))X=X.replace(`{${J}}`,encodeURIComponent(Q)),X=X.replace(`{${J}?}`,encodeURIComponent(Q));return X}onError(Y){return this.errorHandler=Y,this}redirect(Y,Z=302){let $=new Headers;return $.set("Location",Y),new Response(null,{status:Z,headers:$})}permanentRedirect(Y){return this.redirect(Y,301)}redirectRoute(Y,Z,$=302){return this.get(Y,(X)=>{return this.redirect(Z,$)}),this}async serve(Y){this.invalidateCache();let Z={...Y,fetch:this.handleRequest.bind(this),websocket:this.wsConfig};if(this.serverInstance=Bun.serve(Z),this.config.verbose){let $=this.serverInstance.port,X=this.serverInstance.hostname;console.log(`
|
|
98
|
-
\uD83D\uDE80 Server running at http://${
|
|
99
|
-
`)}return this.serverInstance}async handleRequest(Y){try{let Z=new URL(Y.url);if(this.config.verbose)console.log(`${Y.method} ${Z.pathname}`);if(Y.method==="OPTIONS"){let _=Z.hostname||Y.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(Z.pathname,"OPTIONS",_))return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}})}let $=Z.hostname||Y.headers.get("host")?.split(":")[0]||"localhost",X=this.matchRoute(Z.pathname,Y.method,$),J=this.enhanceRequest(Y,X?.params||{});if(X){J.route=X.route;let _=[...this.globalMiddleware];if(X.route.middleware&&X.route.middleware.length>0)_.push(...X.route.middleware);let j=async(W,K)=>{return await this.resolveHandler(X.route.handler,W)};_.push(j);let G=await this.runMiddleware(J,_);if(G)return this.applyModifiedCookies(G,J);return new Response("No response from middleware chain",{status:500})}let Q=this.getAllowedMethods(Z.pathname,$);if(Q.length>0){let _=async(j,G)=>{return new Response(JSON.stringify({error:"Method Not Allowed",path:Z.pathname,method:Y.method,allowed:Q}),{status:405,headers:{"Content-Type":"application/json",Allow:Q.join(", ")}})};if(this.globalMiddleware.length>0){let j=[...this.globalMiddleware,_],G=await this.runMiddleware(J,j);if(G)return this.applyModifiedCookies(G,J)}return _(J,async()=>new Response(null))}if(this.globalMiddleware.length>0){let _=async(W,K)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,J);return new Response(JSON.stringify({error:"Not Found",path:Z.pathname,method:Y.method}),{status:404,headers:{"Content-Type":"application/json"}})},j=[...this.globalMiddleware,_],G=await this.runMiddleware(J,j);if(G)return this.applyModifiedCookies(G,J)}if(this.fallbackHandler){let _=await this.resolveHandler(this.fallbackHandler,J);return this.applyModifiedCookies(_,J)}return new Response(JSON.stringify({error:"Not Found",path:Z.pathname,method:Y.method}),{status:404,headers:{"Content-Type":"application/json"}})}catch(Z){if(console.error("Error handling request:",Z),this.globalMiddleware.length>0){let $=this.enhanceRequest(Y,{}),X=async(Q,_)=>{if(this.errorHandler)return this.errorHandler(Z);return new Response(JSON.stringify({error:"Internal Server Error",message:Z instanceof Error?Z.message:String(Z)}),{status:500,headers:{"Content-Type":"application/json"}})},J=[...this.globalMiddleware,X];try{let Q=await this.runMiddleware($,J);if(Q)return Q}catch{}}if(this.errorHandler)return this.errorHandler(Z);return new Response(JSON.stringify({error:"Internal Server Error",message:Z instanceof Error?Z.message:String(Z)}),{status:500,headers:{"Content-Type":"application/json"}})}}getAllowedMethods(Y,Z){let $=new URL(Y,"http://localhost"),X=`${Z||""}:${$.pathname}`,J=this._allowedMethodsCache.get(X);if(J)return J;let Q=new Set;for(let[G,W]of this.staticRoutes){let K=W.get($.pathname);if(K&&(!Z||!K.domain||K.domain===Z))Q.add(G)}let _=Z&&this.domains[Z]?this.domains[Z]:this.routes;for(let G of _){if(Q.has(G.method))continue;if(G.path===$.pathname){Q.add(G.method);continue}if(G.pattern&&G.pattern.exec($)){Q.add(G.method);continue}if(G.path.endsWith("*")&&$.pathname.startsWith(G.path.slice(0,-1)))Q.add(G.method)}if(Q.has("GET"))Q.add("HEAD");let j=Array.from(Q);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(X,j),j}matchRoute(Y,Z,$){let X=new URL(Y,"http://localhost"),J=`${$||""}:${Z}:${X.pathname}`;if(this.routeCache.has(J))return this.routeCache.get(J);if(this.staticRoutes.has(Z)){let G=this.staticRoutes.get(Z).get(X.pathname);if(G&&(!$||!G.domain||G.domain===$)){let W={route:G,params:{}};return this.routeCache.set(J,W),W}}let _=($&&this.domains[$]?this.domains[$]:this.routes).filter((G)=>G.method===Z);for(let G of _)if(G.path===X.pathname){let W={route:G,params:{}};return this.routeCache.set(J,W),W}for(let G of _)if(G.pattern){let W=G.pattern.exec(X);if(W){let K={route:G,params:W.pathname.groups};return this.routeCache.set(J,K),K}}if($&&this.domains[$]){let G=this.domains[$].filter((W)=>W.method===Z&&W.path.endsWith("*"));for(let W of G){let K=W.path.slice(0,-1);if(X.pathname.startsWith(K)){let z={route:W,params:{wildcard:X.pathname.slice(K.length)}};return this.routeCache.set(J,z),z}}}let j=this.routes.filter((G)=>G.method===Z&&G.path.endsWith("*")&&(!$||!G.domain));for(let G of j){let W=G.path.slice(0,-1);if(X.pathname.startsWith(W)){let K={route:G,params:{wildcard:X.pathname.slice(W.length)}};return this.routeCache.set(J,K),K}}if(Z==="HEAD")return this.matchRoute(Y,"GET",$);return}enhanceRequest(Y,Z={}){let $=null,X=()=>{if($===null)$={},(Y.headers.get("cookie")||"").split(";").forEach((W)=>{let K=W.trim().split("=");if(K.length>=2){let z=K[0].trim(),L=K.slice(1).join("=").trim();$[z]=decodeURIComponent(L)}});return $},J=new URL(Y.url),Q={};J.searchParams.forEach((G,W)=>{Q[W]=G});let _={get url(){return Y.url},get method(){return Y.method},get headers(){return Y.headers},get body(){return Y.body},get bodyUsed(){return Y.bodyUsed},get cache(){return Y.cache},get credentials(){return Y.credentials},get destination(){return Y.destination},get integrity(){return Y.integrity},get keepalive(){return Y.keepalive},get mode(){return Y.mode},get redirect(){return Y.redirect},get referrer(){return Y.referrer},get referrerPolicy(){return Y.referrerPolicy},get signal(){return Y.signal},arrayBuffer:()=>Y.arrayBuffer(),blob:()=>Y.blob(),clone:()=>Y.clone(),formData:()=>Y.formData(),json:()=>Y.json(),text:()=>Y.text(),params:Z,query:Q,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},j=()=>{let G={};for(let[W,K]of Object.entries(Q))G[W]=K;if(_.jsonBody&&typeof _.jsonBody==="object")for(let[W,K]of Object.entries(_.jsonBody))G[W]=K;if(_.formBody&&typeof _.formBody==="object")for(let[W,K]of Object.entries(_.formBody))G[W]=K;for(let[W,K]of Object.entries(Z))G[W]=K;return G};return _.cookies={get:(G)=>X()[G],set:(G,W,K={})=>{_._cookiesToSet.push({name:G,value:W,options:K})},delete:(G,W={})=>{_._cookiesToDelete.push({name:G,options:W})},getAll:()=>({...X()})},_.get=(G,W)=>{let z=j()[G];return z!==void 0?z:W},_.input=(G,W)=>{let z=j()[G];return z!==void 0?z:W},_.all=()=>j(),_.only=(G)=>{let W=j(),K={};for(let z of G)if(z in W)K[z]=W[z];return K},_.except=(G)=>{let K={...j()};for(let z of G)delete K[z];return K},_.has=(G)=>{let W=j();if(Array.isArray(G))return G.every((K)=>(K in W)&&W[K]!==void 0);return G in W&&W[G]!==void 0},_.hasAny=(G)=>{let W=j();return G.some((K)=>(K in W)&&W[K]!==void 0)},_.filled=(G)=>{let W=j(),K=(z)=>{let L=W[z];return L!==void 0&&L!==null&&L!==""&&!(Array.isArray(L)&&L.length===0)};if(Array.isArray(G))return G.every(K);return K(G)},_.missing=(G)=>{let W=j();if(Array.isArray(G))return G.every((K)=>!(K in W)||W[K]===void 0);return!(G in W)||W[G]===void 0},_.string=(G,W="")=>{let z=j()[G];return z!==void 0&&z!==null?String(z):W},_.integer=(G,W=0)=>{let z=j()[G],L=Number.parseInt(String(z),10);return Number.isNaN(L)?W:L},_.float=(G,W=0)=>{let z=j()[G],L=Number.parseFloat(String(z));return Number.isNaN(L)?W:L},_.boolean=(G,W=!1)=>{let z=j()[G];if(z===void 0||z===null)return W;if(typeof z==="boolean")return z;if(z==="true"||z==="1"||z===1)return!0;if(z==="false"||z==="0"||z===0)return!1;return W},_.array=(G)=>{let K=j()[G];if(Array.isArray(K))return K;return K!==void 0&&K!==null?[K]:[]},_.bearerToken=()=>{let G=Y.headers.get("authorization")||Y.headers.get("Authorization")||"";if(G.startsWith("Bearer "))return G.substring(7);return null},_.header=(G)=>{return Y.headers.get(G)||Y.headers.get(G.toLowerCase())||null},_.cookie=(G,W)=>{let K=X()[G];return K!==void 0?K:W??null},_.getParam=(G,W)=>{let K=Z?.[G];return K!==void 0?K:W},_.getParamAsInt=(G)=>{let W=Z?.[G];if(W===void 0||W.trim()==="")return null;let K=Number(W);return Number.isSafeInteger(K)?K:null},_.params=Z||{},_}applyModifiedCookies(Y,Z){let $=new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:Y.headers});if(Z._cookiesToSet&&Z._cookiesToSet.length>0)for(let{name:X,value:J,options:Q}of Z._cookiesToSet){let _=this.serializeCookie(X,J,Q);$.headers.append("Set-Cookie",_)}if(Z._cookiesToDelete&&Z._cookiesToDelete.length>0)for(let{name:X,options:J}of Z._cookiesToDelete){let Q={...J,expires:new Date(0),maxAge:0},_=this.serializeCookie(X,"",Q);$.headers.append("Set-Cookie",_)}return $}serializeCookie(Y,Z,$={}){let X=`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`;if($.maxAge!==void 0)X+=`; Max-Age=${$.maxAge}`;if($.expires&&$.expires instanceof Date)X+=`; Expires=${$.expires.toUTCString()}`;if($.path)X+=`; Path=${$.path}`;else X+="; Path=/";if($.domain)X+=`; Domain=${$.domain}`;if($.secure)X+="; Secure";if($.httpOnly)X+="; HttpOnly";if($.sameSite){let J=$.sameSite.toLowerCase();X+=`; SameSite=${J.charAt(0).toUpperCase()+J.slice(1)}`}return X}buildMiddlewareChain(Y){if(Y.length===0)return async($)=>null;let Z=async($)=>null;for(let $=Y.length-1;$>=0;$--){let X=Y[$],J=Z;Z=async(Q)=>{return X(Q,async()=>{return await J(Q)||new Response(null,{status:200})})}}return Z}async runMiddleware(Y,Z){if(Z.length===0)return null;try{return await this.buildMiddlewareChain(Z)(Y)}catch($){if(this.errorHandler)return this.errorHandler($);throw $}}async resolveHandler(Y,Z){if(typeof Y==="function"&&!Y.prototype?.handle)return await Y(Z);if(typeof Y==="function"&&Y.prototype?.handle)return await new Y().handle(Z);if(Y&&typeof Y.handle==="function")return await Y.handle(Z);throw Error(`Invalid action handler: ${typeof Y}`)}use(...Y){for(let Z of Y){let $=this.resolveMiddleware(Z);if($)this.globalMiddleware.push($)}return this}group(Y,Z){let $=this.currentGroup;if(this.currentGroup={prefix:Y.prefix||"",middleware:[]},Y.middleware){for(let J of Y.middleware)if(typeof J==="function")this.currentGroup.middleware.push(J)}let X=Z();if(X instanceof Promise)return X.then(()=>{return this.currentGroup=$,this},(J)=>{throw this.currentGroup=$,J});return this.currentGroup=$,this}addRoute(Y){if(this.routes.push(Y),Y.name)this.namedRoutes.set(Y.name,Y),g(Y.name,Y.path);return this}registerMiddlewareDependency(Y){if(this._middlewarePipeline)this._middlewarePipeline.registerDependency(Y);return this}registerMiddlewareSkipConditions(Y,Z){return this}getMiddlewareStats(){if(this._middlewarePipeline)return this._middlewarePipeline.getStats();return{}}getMiddlewareCacheInfo(){return{size:0,routes:[],hitRate:0}}clearMiddlewareCache(){if(this._middlewarePipeline)this._middlewarePipeline.clear();return this}async executeMiddleware(Y,Z,$){if(Y.length===0)return $();let X=0,J=async()=>{if(X>=Y.length)return $();let Q=Y[X++];return await Q(Z,J)||new Response("No response from middleware",{status:500})};return J()}}class U8{router;condition;constructor(Y,Z){this.router=Y;this.condition=Z}middleware(Y){let[Z,$]=Y.split(":"),X=this.router.namedMiddleware.get(Z);if(!X)throw Error(`Unknown middleware: ${Z}`);let J=X($);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[J]}),this}}class V8{router;middleware;constructor(Y,Z){this.router=Y;this.middleware=Z}get(Y,Z){return this}post(Y,Z){return this}put(Y,Z){return this}delete(Y,Z){return this}}class A8{router;middleware;constructor(Y,Z){this.router=Y;this.middleware=Z}get(Y,Z){return this}post(Y,Z){return this}put(Y,Z){return this}delete(Y,Z){return this}}var ZZ=null;function O$(){if(ZZ===null)ZZ=new O;return ZZ}function H$(Y,Z={}){if(typeof Y.bearerToken==="function")return Y;return O$().enhanceRequest(Y,Z)}var F$=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,B$=/bot|crawler|spider|crawling/i,wY=new Map;function zY(Y){let Z=Y;if(!Z._parsedURL)Z._parsedURL=new URL(Y.url);return Z._parsedURL}function m(Y){let Z=Y;if(!Z._parsedCookies){let $={},X=Y.headers.get("cookie");if(X)for(let J of X.split(";")){let Q=J.indexOf("=");if(Q===-1)continue;let _=J.slice(0,Q).trim();if(!_)continue;let j=J.slice(Q+1).trim();try{$[_]=decodeURIComponent(j)}catch{$[_]=j}}Z._parsedCookies=$}return Z._parsedCookies}class I8{macros=new Map;epoch=0;register(Y,Z,$=!1){this.macros.set(Y,{name:Y,handler:Z,accessor:$}),this.epoch++}get(Y){return this.macros.get(Y)}has(Y){return this.macros.has(Y)}all(){return Array.from(this.macros.values())}remove(Y){let Z=this.macros.delete(Y);if(Z)this.epoch++;return Z}clear(){this.macros.clear(),this.epoch++}getEpoch(){return this.epoch}}var WY=new I8,D8=Symbol("bunRouterMacroProto"),$Z=Symbol("bunRouterMacroBase"),kY=new WeakMap,E8=-1;class B{static macro(Y,Z){WY.register(Y,Z)}static macroAccessor(Y,Z){WY.register(Y,Z,!0)}static applyMacros(Y){let Z=WY.getEpoch();if(Z!==E8)kY=new WeakMap,E8=Z;let $=Object.getPrototypeOf(Y)??Object.prototype;if($[D8]){if(kY.get($[$Z])===$)return Y;$=$[$Z]}let X=kY.get($);if(!X){X=Object.create($);for(let J of WY.all())if(J.accessor)Object.defineProperty(X,J.name,{get:J.handler,set(Q){Object.defineProperty(this,J.name,{value:Q,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else X[J.name]=J.handler;Object.defineProperty(X,D8,{value:!0}),Object.defineProperty(X,$Z,{value:$}),kY.set($,X)}return Object.setPrototypeOf(Y,X),Y}static hasMacro(Y){return WY.has(Y)}}var KY={wantsJson(){let Y=this.headers.get("accept")||"";return Y.includes("application/json")||Y.includes("json")},wantsHtml(){let Y=this.headers.get("accept")||"";return Y.includes("text/html")||Y.includes("html")},wantsXml(){let Y=this.headers.get("accept")||"";return Y.includes("application/xml")||Y.includes("xml")},expectsJson(){return this.wantsJson()||this.isAjax()||this.isPjax()},isAjax(){return this.headers.get("x-requested-with")==="XMLHttpRequest"},isPjax(){return this.headers.get("x-pjax")==="true"},isMobile(){return F$.test(this.headers.get("user-agent")||"")},isBot(){return B$.test(this.headers.get("user-agent")||"")},isSecure(){return this.url.startsWith("https://")||this.headers.get("x-forwarded-proto")==="https"||this.headers.get("x-forwarded-ssl")==="on"},ip(){return this.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||this.headers.get("x-real-ip")||this.headers.get("cf-connecting-ip")||this.headers.get("x-client-ip")||"unknown"},ips(){let Y=this.headers.get("x-forwarded-for");if(Y)return Y.split(",").map((Z)=>Z.trim());return[KY.ip.call(this)]},userAgent(){return this.headers.get("user-agent")||""},referer(){return this.headers.get("referer")||this.headers.get("referrer")||null},bearerToken(){let Y=this.headers.get("authorization");if(Y&&Y.startsWith("Bearer "))return Y.substring(7);return null},async rawBody(){if(typeof this._rawBody==="string")return this._rawBody;try{let Y=await this.clone().text();return this._rawBody=Y,Y}catch{return""}},basicAuth(){let Y=this.headers.get("authorization");if(Y&&Y.startsWith("Basic "))try{let Z=atob(Y.substring(6)),[$,X]=Z.split(":");return{username:$,password:X}}catch{return null}return null},hasHeader(Y){return this.headers.has(Y.toLowerCase())},header(Y,Z){return this.headers.get(Y.toLowerCase())||Z||null},allHeaders(){let Y={};return this.headers.forEach((Z,$)=>{Y[$]=Z}),Y},input(Y,Z){if(this.validated&&Y in this.validated)return this.validated[Y];if(this.query&&Y in this.query)return this.query[Y];if(this.params&&Y in this.params)return this.params[Y];if(this.jsonBody&&typeof this.jsonBody==="object"&&Y in this.jsonBody)return this.jsonBody[Y];if(this.formBody&&typeof this.formBody==="object"&&Y in this.formBody)return this.formBody[Y];return Z},all(){return{...this.params,...this.query,...typeof this.jsonBody==="object"&&this.jsonBody!==null?this.jsonBody:{},...typeof this.formBody==="object"&&this.formBody!==null?this.formBody:{},...typeof this.validated==="object"&&this.validated!==null?this.validated:{}}},only(Y){let Z=this.all(),$={};return Y.forEach((X)=>{if(X in Z)$[X]=Z[X]}),$},except(Y){let Z=this.all(),$={};return Object.keys(Z).forEach((X)=>{if(!Y.includes(X))$[X]=Z[X]}),$},has(Y){let Z=this.all();return Y in Z&&Z[Y]!==void 0&&Z[Y]!==null&&Z[Y]!==""},hasAny(Y){return Y.some((Z)=>this.has(Z))},missing(Y){return!this.has(Y)},filled(Y){let Z=this.input(Y);if(Z===null||Z===void 0)return!1;if(typeof Z==="string")return Z.trim().length>0;if(Array.isArray(Z))return Z.length>0;if(typeof Z==="object")return Object.keys(Z).length>0;return!0},getQuery(Y,Z){if(!Y)return this.query||{};return this.query?.[Y]||Z},param(Y,Z){return this.params?.[Y]||Z},cookie(Y,Z){let $=m(this)[Y];return $!==void 0?$:Z||null},cookies(){return{...m(this)}},file(Y){return this.files?.find((Z)=>Z.fieldName===Y)},hasFile(Y){return!!this.files?.find((Z)=>Z.fieldName===Y)},path(){return zY(this).pathname},fullUrl(){return this.url},root(){let Y=zY(this);return`${Y.protocol}//${Y.host}`},is(Y){let Z=this.path(),$=wY.get(Y);if(!$){let X=Y.replace(/\*/g,".*").replace(/\?/g,".");if($=new RegExp(`^${X}$`),wY.size>=1000)wY.clear();wY.set(Y,$)}return $.test(Z)},route(){return this.routeName||null},fingerprint(){let Y=zY(this),Z={method:this.method,path:Y.pathname,query:Y.search,ip:KY.ip.call(this)};return btoa(JSON.stringify(Z))},signature(Y){let Z=`${this.method}${this.url}${KY.ip.call(this)}${Y}`,$=0;for(let X=0;X<Z.length;X++){let J=Z.charCodeAt(X);$=($<<5)-$+J,$=$&$}return Math.abs($).toString(36)},merge(Y){if(!this.validated)this.validated={};Object.assign(this.validated,Y)},replace(Y){this.validated={...Y}},age(){let Y=this.startTime||Date.now();return Date.now()-Y},isFromTrustedProxy(Y=[]){let Z=KY.ip.call(this);return Y.includes(Z)},contentLength(){let Y=this.headers.get("content-length");return Y?Number.parseInt(Y,10):0},contentType(){return this.headers.get("content-type")},isContentType(Y){let Z=this.contentType();return Z?Z.includes(Y):!1}};function N$(){Object.entries(KY).forEach(([Y,Z])=>{B.macro(Y,Z)})}N$();if(!B.hasMacro("getParam"))B.macro("getParam",function(Y,Z){let $=this.params?.[Y];return $!==void 0?$:Z});if(!B.hasMacro("getParamAsInt"))B.macro("getParamAsInt",function(Y){let Z=this.params?.[Y];if(Z===void 0||Z.trim()==="")return null;let $=Number(Z);return Number.isSafeInteger($)?$:null});if(!B.hasMacro("get"))B.macro("get",function(Y,Z){let $=zY(this).searchParams.get(Y);return $!==null&&$!==void 0?$:Z});B.macroAccessor("cookies",function(){let Y=this,Z=()=>({...m(Y)});for(let[$,X]of Object.entries(m(Y)))Object.defineProperty(Z,$,{value:X,writable:!0,enumerable:!0,configurable:!0});return Z.get=($)=>m(Y)[$],Z.set=($,X,J={})=>{if(!Y._cookiesToSet)Y._cookiesToSet=[];Y._cookiesToSet.push({name:$,value:X,options:J})},Z.delete=($,X={})=>{if(!Y._cookiesToDelete)Y._cookiesToDelete=[];Y._cookiesToDelete.push({name:$,options:X})},Z.getAll=()=>({...m(Y)}),Object.defineProperty(Y,"cookies",{value:Z,writable:!0,configurable:!0,enumerable:!0}),Z});function O8(Y){Object.defineProperties(Y.prototype,{serve:{async value(Z={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let $={idleTimeout:255,...Z,fetch:this.handleRequest.bind(this)},X={};if(this.staticResponses&&this.staticResponses.size>0)for(let[J,Q]of this.staticResponses)X[J]=Q;if(Z.static)Object.assign(X,Z.static);if(Object.keys(X).length>0)$.static=X;if(Z.development!==void 0)$.development=Z.development;if(this._nativeRoutesEnabled=Z.nativeRoutes===!0,this._nativeRoutesEnabled){let J=this._buildNativeRoutes();if(J)$.routes=J}if(this.wsConfig)$.websocket=this.wsConfig;if(this.serverInstance=Bun.serve($),this.config.verbose){let J=this.serverInstance.port,Q=this.serverInstance.hostname;console.log(`
|
|
100
|
-
\uD83D\uDE80 Server running at http://${
|
|
101
|
-
`)}return this.serverInstance},writable:!0,configurable:!0},reload:{async value(){if(!this.serverInstance)throw Error("Server not started, cannot reload");this.invalidateCache();let Z=this.serverInstance.port,$=this.serverInstance.hostname;this.serverInstance.stop();let X={port:Z,hostname:$,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0};if(this._nativeRoutesEnabled){let J=this._buildNativeRoutes();if(J)X.routes=J}if(this.serverInstance=Bun.serve(X),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${$}:${Z}`)},writable:!0,configurable:!0},handleRequest:{async value(Z){let $=this,X=await BY(Z,()=>$.handleRequestImpl(Z));return await BZ(X,Z,$.config?.compression??{})},writable:!0,configurable:!0},_dispatchMatchedRoute:{async value(Z,$,X){let J=this.enhanceRequest($,X);NY(J),J.route=Z;let Q=Z,_=this._mwEpoch||0,j=Q.middleware?Q.middleware.length:0,G=Q._compiledChain;if(!G||Q._chainEpoch!==_||Q._chainMwLen!==j){let K=Q8(Q.handler,this.config);if(j===0&&this.globalMiddleware.length===0)G=K;else{let z=j>0?[...this.globalMiddleware,...Q.middleware]:[...this.globalMiddleware];z.push((L,V)=>K(L)),G=this.buildMiddlewareChain(z)}Q._compiledChain=G,Q._chainEpoch=_,Q._chainMwLen=j}let W;try{W=await G(J)}catch(K){if(this.errorHandler)W=await this.errorHandler(K);else throw K}if(W)return this.applyModifiedCookies(W,J);return new Response("No response from middleware chain",{status:500})},writable:!0,configurable:!0},_buildNativeRoutes:{value(){let Z=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),$=(j)=>{if(j==="*")return"/*";let G=j.split("/"),W=[];for(let K=0;K<G.length;K++){let z=G[K];if(z===""){W.push(z);continue}if(z==="*")return K===G.length-1?[...W,"*"].join("/"):null;let L=z.match(/^\{([A-Z_$][\w$]*)\}$/i);if(L){W.push(`:${L[1]}`);continue}if(z.includes("{")||z.includes(":")||z.includes("*"))return null;W.push(z)}return W.join("/")},X=this,J=(j,G)=>{return(W)=>{return BY(W,async()=>{try{let K=W.params??{};if(G){let z=new URL(W.url).pathname,L=j.path==="*"?"/":j.path.slice(0,-1);K={...K,wildcard:z.slice(L.length)}}return await X._dispatchMatchedRoute(j,W,K)}catch(K){if(console.error("Error handling request:",K),X.errorHandler)return X.errorHandler(K);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:K instanceof Error?K.message:String(K)}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"}})}})}},Q={},_=new Map;for(let j of this.routes){if(!Z.has(j.method))continue;if(j.nativeDispatch===!1)continue;if(j.constraints&&Object.keys(j.constraints).length>0)continue;if(j.handler instanceof Response)continue;let G=$(j.path);if(!G)continue;let W=G.replace(/:[^/]+/g,":p"),K=_.get(W);if(K&&K!==G)continue;_.set(W,G);let z=Q[G]??={};if(z[j.method])continue;z[j.method]=J(j,j.path.endsWith("*"))}for(let j of Object.values(Q))if(j.GET&&!j.HEAD)j.HEAD=j.GET;return Object.keys(Q).length>0?Q:null},writable:!0,configurable:!0},handleRequestImpl:{async value(Z){try{let $=new URL(Z.url);Z._parsedURL=$;let X=$.hostname||Z.headers.get("host")?.split(":")[0]||"localhost",J=this.matchRoute($.pathname,Z.method,X);if(Z.method==="OPTIONS"&&!J){let W=Z.headers.get("origin"),K={"Access-Control-Allow-Origin":W||"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin","Access-Control-Max-Age":"86400"};if(W)K["Access-Control-Allow-Credentials"]="true",K.Vary="Origin";return new Response(null,{status:204,headers:K})}if(J)return await this._dispatchMatchedRoute(J.route,Z,J.params);let Q=this.enhanceRequest(Z,{});NY(Q);let _=this.getAllowedMethods($.pathname,X),j={"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"};if(_.length>0){let W=async(K,z)=>{return new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:$.pathname,method:Z.method,allowed:_}),{status:405,headers:{...j,Allow:_.join(", ")}})};if(this.globalMiddleware.length>0){let K=[...this.globalMiddleware,W],z=await this.runMiddleware(Q,K);if(z)return this.applyModifiedCookies(z,Q)}return await W(Q,async()=>null)}if(this.fallbackHandler){let W=await this.resolveHandler(this.fallbackHandler,Q);return this.applyModifiedCookies(W,Q)}let G=async(W,K)=>{return new Response(JSON.stringify({success:!1,message:"Not Found",path:$.pathname,method:Z.method}),{status:404,headers:j})};if(this.globalMiddleware.length>0){let W=[...this.globalMiddleware,G],K=await this.runMiddleware(Q,W);if(K)return this.applyModifiedCookies(K,Q)}return await G(Q,async()=>null)}catch($){if(console.error("Error handling request:",$),this.errorHandler)return this.errorHandler($);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:$ instanceof Error?$.message:String($)}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"}})}},writable:!0,configurable:!0},enhanceRequest:{value(Z,$={}){let X=Z;if("params"in Z)Object.defineProperty(X,"params",{value:$,writable:!0,configurable:!0,enumerable:!0});else X.params=$;return B.applyMacros(X),X},writable:!0,configurable:!0},applyModifiedCookies:{value(Z,$){let X=$._cookiesToSet&&$._cookiesToSet.length>0,J=$._cookiesToDelete&&$._cookiesToDelete.length>0;if(!X&&!J)return Z;let Q=new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:Z.headers});if($._cookiesToSet&&$._cookiesToSet.length>0)for(let{name:_,value:j,options:G}of $._cookiesToSet){let W=this.serializeCookie(_,j,G);Q.headers.append("Set-Cookie",W)}if($._cookiesToDelete&&$._cookiesToDelete.length>0)for(let{name:_,options:j}of $._cookiesToDelete){let G={...j,expires:new Date(0),maxAge:0},W=this.serializeCookie(_,"",G);Q.headers.append("Set-Cookie",W)}return Q},writable:!0,configurable:!0},serializeCookie:{value(Z,$,X={}){let J=`${encodeURIComponent(Z)}=${encodeURIComponent($)}`;if(X.maxAge!==void 0)J+=`; Max-Age=${X.maxAge}`;if(X.expires&&X.expires instanceof Date)J+=`; Expires=${X.expires.toUTCString()}`;if(X.path)J+=`; Path=${X.path}`;else J+="; Path=/";if(X.domain)J+=`; Domain=${X.domain}`;if(X.secure)J+="; Secure";if(X.httpOnly)J+="; HttpOnly";if(X.sameSite){let Q=X.sameSite.toLowerCase();J+=`; SameSite=${Q.charAt(0).toUpperCase()+Q.slice(1)}`}return J},writable:!0,configurable:!0}})}import{join as S$}from"path";function H8(Y){Object.defineProperties(Y.prototype,{renderView:{async value(Z,$={},X={}){let J=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},Q=`${Z}:${X.layout||""}`;if(J.cache&&this.templateCache.has(Q))return this.processTemplate(this.templateCache.get(Q),$,J);let _=await rY(Z,J.viewsPath,J.extensions);if(!_)throw Error(`View '${Z}' not found`);let j=await Bun.file(_).text(),G=X.layout||J.defaultLayout;if(G){let W=await rY(S$("layouts",G),J.viewsPath,J.extensions);if(!W)throw Error(`Layout '${G}' not found`);j=(await Bun.file(W).text()).replace(/\{\{\s*content\s*\}\}/g,j)}if(J.cache)this.templateCache.set(Q,j);return this.processTemplate(j,$,J)},writable:!0,configurable:!0},processTemplate:{async value(Z,$,X){if((X?.engine||"auto")==="custom"&&X?.customRenderer)return X.customRenderer(Z,$,{});let Q=tZ(Z,$);if(X?.minify?.enabled)try{let _=X.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};Q=Q.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(_){console.error("Error minifying HTML:",_)}return Q},writable:!0,configurable:!0},view:{value(Z,$,X={},J={},Q="web",_){let j,G={},W={},K="web",z;if(typeof $==="string"){if(j=$,typeof X==="object"&&!Array.isArray(X))if("layout"in X||"status"in X||"headers"in X)W=X;else G=X;if(typeof J==="object")W={...W,...J};else if(typeof J==="string")K=J;if(typeof Q==="string")if(Q==="web"||Q==="api")K=Q;else z=Q;if(_)z=_}else{if(G=$,typeof X==="string")j=X;else throw TypeError("View name must be a string");if(typeof J==="object")W=J;else if(typeof J==="string")if(J==="web"||J==="api")K=J;else j=J,K="web"}let L=async(V)=>{let U=await this.renderView(j,G,{layout:W.layout}),A=this.config?.queryPreservation;if(A?.enabled!==!1&&A?.preserve?.length)U=SY(U,A);let I=new Headers;if(I.set("Content-Type","text/html; charset=utf-8"),W.headers)for(let[F,i]of Object.entries(W.headers))I.set(F,i);return new Response(U,{status:W.status||200,headers:I})};return this.get(Z,L,K,z),this},writable:!0,configurable:!0}})}function F8(Y){Object.defineProperties(Y.prototype,{websocket:{value(Z){return this.wsConfig=Z,this},writable:!0,configurable:!0},publish:{value(Z,$,X=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(Z,$,X)},writable:!0,configurable:!0},subscriberCount:{value(Z){if(!this.serverInstance)throw Error("Server not started, cannot get subscriber count");return this.serverInstance.subscriberCount(Z)},writable:!0,configurable:!0},upgrade:{value(Z,$){if(!this.serverInstance)throw Error("Server not started, cannot upgrade to WebSocket");if(!this.wsConfig)throw Error("WebSocket configuration not set, use router.websocket() to configure");return this.serverInstance.upgrade(Z,$)},writable:!0,configurable:!0},timeout:{value(Z,$){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(Z,$)},writable:!0,configurable:!0},requestIP:{value(Z){if(!this.serverInstance)throw Error("Server not started, cannot get request IP");return this.serverInstance.requestIP(Z)},writable:!0,configurable:!0}})}import C$ from"process";class B8{macros=new Map;register(Y,Z){this.macros.set(Y,{name:Y,handler:Z})}get(Y){return this.macros.get(Y)}has(Y){return this.macros.has(Y)}all(){return Array.from(this.macros.values())}remove(Y){return this.macros.delete(Y)}clear(){this.macros.clear()}}var XZ=new B8;class LY extends Response{static macro(Y,Z){XZ.register(Y,Z),Response[Y]=Z}static callMacro(Y,...Z){let $=XZ.get(Y);if(!$)throw Error(`Response macro "${Y}" not found`);return $.handler(...Z)}static hasMacro(Y){return XZ.has(Y)}}function vY(Y,Z){if(typeof Y==="number")return{status:Y,mergedHeaders:Z};if(Y&&typeof Y==="object"){let $=typeof Y.status==="number"?Y.status:200,X=Z;if(Y.headers)if(X={},Y.headers instanceof Headers)Y.headers.forEach((J,Q)=>{X[Q]=J});else if(Array.isArray(Y.headers))for(let[J,Q]of Y.headers)X[J]=Q;else Object.assign(X,Y.headers);return{status:$,mergedHeaders:X}}return{status:200,mergedHeaders:Z}}var R={success:(Y,Z,$=200)=>{let X={};if(Y!==void 0)X.data=Y;if(Z!==void 0)X.message=Z;return new Response(JSON.stringify(X),{status:$,headers:{"Content-Type":"application/json"}})},error:(Y,Z,$=400)=>{let X={error:Y};if(Z!==void 0)X.errors=Z;return new Response(JSON.stringify(X),{status:$,headers:{"Content-Type":"application/json"}})},validationError:(Y,Z="Validation failed")=>{return R.error(Z,Y,422)},notFound:(Y="Resource not found")=>{return R.error(Y,void 0,404)},unauthorized:(Y="Unauthorized")=>{return R.error(Y,void 0,401)},forbidden:(Y="Forbidden")=>{return R.error(Y,void 0,403)},serverError:(Y="Internal server error")=>{return R.error(Y,void 0,500)},created:(Y,Z="Resource created successfully")=>{return R.success(Y,Z,201)},updated:(Y,Z="Resource updated successfully")=>{return R.success(Y,Z,200)},deleted:(Y="Resource deleted successfully")=>{return R.success(null,Y,200)},noContent:()=>{return new Response(null,{status:204})},accepted:(Y,Z="Request accepted")=>{return R.success(Y,Z,202)},paginated:(Y,Z,$)=>{let X=Math.ceil(Z.total/Z.per_page),J=(Z.current_page-1)*Z.per_page+1,Q=Math.min(J+Z.per_page-1,Z.total),_={data:Y,message:$,meta:{current_page:Z.current_page,per_page:Z.per_page,total:Z.total,last_page:X,from:J,to:Q,path:Z.path,first_page_url:`${Z.path}?page=1`,last_page_url:`${Z.path}?page=${X}`,next_page_url:Z.current_page<X?`${Z.path}?page=${Z.current_page+1}`:void 0,prev_page_url:Z.current_page>1?`${Z.path}?page=${Z.current_page-1}`:void 0}};return new Response(JSON.stringify(_),{status:200,headers:{"Content-Type":"application/json"}})},json:(Y,Z=200,$={})=>{let{status:X,mergedHeaders:J}=vY(Z,$);return new Response(JSON.stringify(Y),{status:X,headers:{"Content-Type":"application/json",...J}})},html:(Y,Z=200,$={})=>{let{status:X,mergedHeaders:J}=vY(Z,$);return new Response(Y,{status:X,headers:{"Content-Type":"text/html",...J}})},text:(Y,Z=200,$={})=>{let{status:X,mergedHeaders:J}=vY(Z,$);return new Response(Y,{status:X,headers:{"Content-Type":"text/plain",...J}})},xml:(Y,Z=200,$={})=>{let{status:X,mergedHeaders:J}=vY(Z,$);return new Response(Y,{status:X,headers:{"Content-Type":"application/xml",...J}})},redirect:(Y,Z=302)=>{return new Response(null,{status:Z,headers:{Location:Y}})},permanentRedirect:(Y)=>{return R.redirect(Y,301)},download:(Y,Z,$="application/octet-stream")=>{return new Response(Y,{status:200,headers:{"Content-Type":$,"Content-Disposition":`attachment; filename="${Z}"`}})},stream:(Y,Z="application/octet-stream",$={})=>{return new Response(Y,{status:200,headers:{"Content-Type":Z,...$}})},cache:(Y,Z=3600,$=!0,X)=>{let Q={"Content-Type":"application/json","Cache-Control":$?`public, max-age=${Z}`:`private, max-age=${Z}`};if(X)Q.ETag=X;return new Response(JSON.stringify(Y),{status:200,headers:Q})},cors:(Y,Z="*",$="GET,POST,PUT,DELETE,OPTIONS",X="Content-Type,Authorization")=>{return new Response(JSON.stringify(Y),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":Z,"Access-Control-Allow-Methods":$,"Access-Control-Allow-Headers":X}})},sse:(Y,Z,$)=>{let X="";if($)X+=`id: ${$}
|
|
102
|
-
`;if(
|
|
103
|
-
`;return
|
|
93
|
+
`,i.enqueue(o.encode(u))}i.close()}catch(a){Se(i,a)}}});return new Response(s,{status:200,headers:n})},writable:!0,configurable:!0},streamDownload:{value(t,r,n={}){let s=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${r}"`,...n}),i=new ReadableStream({async start(o){let a=new TextEncoder;try{for await(let u of t())if(typeof u==="string")o.enqueue(a.encode(u));else o.enqueue(u);o.close()}catch(u){Se(o,u)}}});return new Response(i,{status:200,headers:s})},writable:!0,configurable:!0},streamAsyncIterator:{value(t,r={}){return S.direct(t,r).toResponse()},writable:!0,configurable:!0}})}class ke extends Error{modelName;value;field;constructor(e,t,r="id"){super(`${e} not found with ${r}: ${t}`);this.modelName=e;this.value=t;this.field=r;this.name="ModelNotFoundError"}}class Ut{bindings=new Map;model(e,t){this.bindings.set(e,t)}bind(e,t){this.bindings.set(e,t)}getBinding(e){return this.bindings.get(e)}hasBinding(e){return this.bindings.has(e)}}var ns=new Ut;async function Ft(e,t,r,n,s={}){if(n)return await r.resolveRouteBinding(t,n);let i=r.getRouteKeyName();if(i!=="id")return await r.resolveRouteBinding(t,i);return await r.find(t)}function Nt(e,t){return async(r,n)=>{let s={};try{for(let i of e){let o=r.params?.[i.name];if(!o)continue;let a=ns.getBinding(i.name);if(a){let l=null;if(typeof a==="function")l=await a(o);else l=await Ft(i.name,o,a,i.key,s);if(!l)throw new ke(i.name,o,i.key||"id");s[i.name]=l;continue}let u=t[i.name];if(!u)continue;let c=await Ft(i.name,o,u,i.key,s);if(!c)throw new ke(i.name,o,i.key||"id");s[i.name]=c}return r.models=s,await n()}catch(i){if(i instanceof ke)return new Response(`${i.modelName} not found`,{status:404});throw i}}}class It{key;entry;prev;next;constructor(e,t,r=null,n=null){this.key=e;this.entry=t;this.prev=r;this.next=n}}class ie{options;cache=new Map;head=null;tail=null;stats={hits:0,misses:0,evictions:0};constructor(e){this.options=e;if(e.maxSize<=0)throw Error("maxSize must be greater than 0")}get(e){let t=this.cache.get(e);if(!t){this.stats.misses++;return}let r=Date.now(),n=t.entry;if(this.isExpired(n,r)){if(!this.options.allowStale){this.delete(e),this.stats.misses++;return}}if(n.lastAccessed=r,n.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(t);return n.value}set(e,t,r){let n=Date.now(),s=this.cache.get(e);if(s){s.entry.value=t,s.entry.timestamp=n,s.entry.lastAccessed=n,s.entry.ttl=r??this.options.ttl,this.moveToFront(s);return}let i={value:t,timestamp:n,accessCount:0,lastAccessed:n,ttl:r??this.options.ttl},o=new It(e,i);if(this.cache.set(e,o),this.addToFront(o),this.cache.size>this.options.maxSize)this.evictLRU()}delete(e){let t=this.cache.get(e);if(!t)return!1;if(this.cache.delete(e),this.removeNode(t),this.options.onEvict)this.options.onEvict(e,t.entry.value);return!0}has(e){let t=this.cache.get(e);if(!t)return!1;let r=Date.now();if(this.isExpired(t.entry,r)){if(!this.options.allowStale)return this.delete(e),!1}return!0}clear(){if(this.options.onEvict)for(let[e,t]of this.cache)this.options.onEvict(e,t.entry.value);this.cache.clear(),this.head=null,this.tail=null,this.stats.evictions+=this.cache.size}keys(){let e=[],t=this.head;while(t)e.push(t.key),t=t.next;return e}values(){let e=[],t=this.head;while(t)e.push(t.entry.value),t=t.next;return e}getStats(){let e=this.estimateMemoryUsage(),t=this.stats.hits+this.stats.misses;return{size:this.cache.size,maxSize:this.options.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,hitRate:t>0?this.stats.hits/t:0,memoryUsage:e}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}prune(){let e=Date.now(),t=[];for(let[r,n]of this.cache)if(this.isExpired(n.entry,e))t.push(r);for(let r of t)this.delete(r);return t.length}getFrequentlyUsed(e=10){let t=[];for(let[r,n]of this.cache)t.push({key:r,value:n.entry.value,accessCount:n.entry.accessCount});return t.sort((r,n)=>n.accessCount-r.accessCount).slice(0,e)}resize(e){if(e<=0)throw Error("maxSize must be greater than 0");this.options.maxSize=e;while(this.cache.size>e)this.evictLRU()}isExpired(e,t){if(!e.ttl)return!1;return t-e.timestamp>e.ttl}moveToFront(e){if(e===this.head)return;this.removeNode(e),this.addToFront(e)}addToFront(e){if(e.prev=null,e.next=this.head,this.head)this.head.prev=e;if(this.head=e,!this.tail)this.tail=e}removeNode(e){if(e.prev)e.prev.next=e.next;else this.head=e.next;if(e.next)e.next.prev=e.prev;else this.tail=e.prev}evictLRU(){if(!this.tail)return;let e=this.tail.key,t=this.tail.entry.value;if(this.cache.delete(e),this.removeNode(this.tail),this.stats.evictions++,this.options.onEvict)this.options.onEvict(e,t)}estimateMemoryUsage(){let e=0;for(let[t,r]of this.cache)e+=t.length*2,e+=this.estimateValueSize(r.entry.value),e+=64;return e+=this.cache.size*48,e}estimateValueSize(e){if(e===null||e===void 0)return 0;if(typeof e==="string")return e.length*2;if(typeof e==="number")return 8;if(typeof e==="boolean")return 1;if(e instanceof ArrayBuffer)return e.byteLength;if(e instanceof Uint8Array)return e.length;try{return JSON.stringify(e).length*2}catch{return 100}}}class _t{static generateKey(e,t){let r=new URL(e.url),n=e.method,s=r.pathname,i=[n,s],o=new URLSearchParams(r.search),a=t.excludeQuery||[],u=[];for(let[c,l]of o.entries())if(!a.includes(c))u.push(`${c}=${l}`);if(u.length>0)i.push(u.sort().join("&"));if(t.varyBy){let c=[];for(let l of t.varyBy){let d=e.headers.get(l);if(d)c.push(`${l}:${d}`)}if(c.length>0)i.push(c.join("|"))}return i.join("::")}}class jt{cache;tagIndex=new Map;keyTags=new Map;constructor(e=1000){this.cache=new ie({maxSize:e})}async get(e){let t=this.cache.get(e);if(!t)return null;if(t.ttl&&Date.now()-t.timestamp>t.ttl)return this.delete(e),null;return t}async set(e,t){this.cache.set(e,t),this.keyTags.set(e,new Set(t.tags));for(let r of t.tags){if(!this.tagIndex.has(r))this.tagIndex.set(r,new Set);this.tagIndex.get(r).add(e)}}delete(e){let t=this.keyTags.get(e);if(t){for(let r of t){let n=this.tagIndex.get(r);if(n){if(n.delete(e),n.size===0)this.tagIndex.delete(r)}}this.keyTags.delete(e)}return this.cache.delete(e)}invalidateByTags(e){let t=new Set;for(let r of e){let n=this.tagIndex.get(r);if(n)for(let s of n)t.add(s)}for(let r of t)this.delete(r);return t.size}clear(){this.cache.clear(),this.tagIndex.clear(),this.keyTags.clear()}getStats(){return{...this.cache.getStats(),totalTags:this.tagIndex.size,totalKeyTagMappings:this.keyTags.size}}}var X=new jt;function Lt(e){return async(t,r)=>{if(e.condition&&!e.condition(t))return await r();if(t.method!=="GET"&&t.method!=="HEAD")return await r();let n=_t.generateKey(t,e),s=await X.get(n);if(s){let o=new Headers(s.headers);if(o.set("X-Cache","HIT"),o.set("X-Cache-Key",n),s.etag){if(o.set("ETag",s.etag),t.headers.get("If-None-Match")===s.etag)return new Response(null,{status:304,headers:o})}return new Response(s.body,{status:s.status,headers:o})}let i=await r();if(i.status>=200&&i.status<300)try{let o=i.clone(),a=await o.arrayBuffer(),u=await ss(a),c={};o.headers.forEach((p,g)=>{c[g]=p});let l={response:o,headers:c,status:i.status,body:new Uint8Array(a),timestamp:Date.now(),ttl:e.ttl,tags:e.tags||[],etag:u};await X.set(n,l);let d=new Headers(i.headers);return d.set("X-Cache","MISS"),d.set("X-Cache-Key",n),d.set("ETag",u),new Response(i.body,{status:i.status,headers:d})}catch(o){return console.error("Error caching response:",o),i}return i}}async function ss(e){let t=await crypto.subtle.digest("SHA-256",e);return`"${Array.from(new Uint8Array(t)).map((s)=>s.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var zt={short:(e=[])=>({ttl:300000,maxSize:500,tags:e}),medium:(e=[])=>({ttl:3600000,maxSize:1000,tags:e}),long:(e=[])=>({ttl:86400000,maxSize:2000,tags:e}),api:(e=[])=>({ttl:900000,maxSize:1000,tags:e,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(e=[])=>({ttl:604800000,maxSize:5000,tags:e,varyBy:["Accept-Encoding"]}),user:(e=[])=>({ttl:1800000,maxSize:2000,tags:e,varyBy:["Authorization"],condition:(t)=>!!t.headers.get("Authorization")})},ji={byTags:(e)=>X.invalidateByTags(e),forUser:(e)=>X.invalidateByTags([`user:${e}`]),forModel:(e,t)=>{let r=t?[`${e}:${t}`,e]:[e];return X.invalidateByTags(r)},all:()=>{X.clear()}};class He{cache;config;constructor(e,t=1e4){this.config=e,this.cache=new ie({maxSize:t,ttl:e.windowMs*2})}async checkLimit(e){if(this.config.skipIf&&this.config.skipIf(e))return{allowed:!0,info:{totalHits:0,resetTime:new Date(Date.now()+this.config.windowMs),remaining:this.config.maxAttempts,limit:this.config.maxAttempts,windowMs:this.config.windowMs}};let t=this.generateKey(e),r=Date.now(),n=this.cache.get(t);if(!n||r>=n.resetTime)n={count:1,resetTime:r+this.config.windowMs,firstHit:r};else n.count++;this.cache.set(t,n);let s={totalHits:n.count,resetTime:new Date(n.resetTime),remaining:Math.max(0,this.config.maxAttempts-n.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:n.count<=this.config.maxAttempts,info:s}}generateKey(e){if(this.config.keyGenerator)return this.config.keyGenerator(e);let t=this.getClientIP(e),r=e.user?.id;if(r)return`user:${r}`;return`ip:${t}`}getClientIP(e){let t=e.headers.get("x-forwarded-for");if(t)return t.split(",")[0].trim();let r=e.headers.get("x-real-ip");if(r)return r;let n=e.headers.get("cf-connecting-ip");if(n)return n;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class Gt{limiters=new Map;register(e,t){let r=new He(t);return this.limiters.set(e,r),r}get(e){return this.limiters.get(e)}getOrCreate(e,t){let r=this.limiters.get(e);if(r)return r;return this.register(e,t)}}var Wt=new Gt;function Q(e,t){let r=t?Wt.getOrCreate(t,e):new He(e);return async(n,s)=>{let{allowed:i,info:o}=await r.checkLimit(n);if(!i){if(e.onLimitReached)return e.onLimitReached(n,o);let u=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((o.resetTime.getTime()-Date.now())/1000).toString()});if(e.headers!==!1)u.set("X-RateLimit-Limit",o.limit.toString()),u.set("X-RateLimit-Remaining",o.remaining.toString()),u.set("X-RateLimit-Reset",Math.ceil(o.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((o.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((o.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:u})}let a=await s();if(a&&e.headers!==!1&&a.status<400){let u=new Headers(a.headers);return u.set("X-RateLimit-Limit",o.limit.toString()),u.set("X-RateLimit-Remaining",o.remaining.toString()),u.set("X-RateLimit-Reset",Math.ceil(o.resetTime.getTime()/1000).toString()),new Response(a.body,{status:a.status,statusText:a.statusText,headers:u})}return a}}function Z(e){let t=e.split(","),r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<=0)throw Error(`Invalid throttle max attempts: ${t[0]}`);let n;if(t.length===1)n=60000;else{let s=t[1];n=is(s)}return{maxAttempts:r,windowMs:n}}function is(e){let t=/^(\d+)([smh]|sec|min|hour)?$/,r=e.match(t);if(!r)throw Error(`Invalid time format: ${e}`);let n=Number.parseInt(r[1],10),s=r[2]||"m";if(Number.isNaN(n)||n<=0)throw Error(`Invalid time value: ${r[1]}`);switch(s){case"s":case"sec":return n*1000;case"m":case"min":return n*60*1000;case"h":case"hour":return n*60*60*1000;default:return n*60*1000}}var os={api:(e=60,t=1)=>({maxAttempts:e,windowMs:t*60*1000,headers:!0}),auth:()=>({maxAttempts:5,windowMs:900000,keyGenerator:(e)=>{let t=e.headers.get("x-forwarded-for")?.split(",")[0]||"unknown",r=e.jsonBody?.email||e.formBody?.email||e.query?.email||"unknown";return`auth:${t}:${r}`},onLimitReached:(e,t)=>new Response(JSON.stringify({error:"Too many authentication attempts",message:"Please try again later",retryAfter:Math.ceil((t.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:{"Content-Type":"application/json","Retry-After":Math.ceil((t.resetTime.getTime()-Date.now())/1000).toString()}})}),upload:()=>({maxAttempts:10,windowMs:3600000,keyGenerator:(e)=>{let t=e.user?.id;if(t)return`upload:user:${t}`;return`upload:ip:${e.headers.get("x-forwarded-for")?.split(",")[0]||"unknown"}`}}),search:()=>({maxAttempts:100,windowMs:600000,skipIf:(e)=>e.user?.plan==="premium"}),perUser:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:(r)=>{let n=r.user?.id;if(!n)throw Error("User authentication required for per-user rate limiting");return`user:${n}`},skipIf:(r)=>!r.user?.id}),perIP:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:(r)=>`ip:${r.headers.get("x-forwarded-for")?.split(",")[0]||r.headers.get("x-real-ip")||r.headers.get("cf-connecting-ip")||"unknown"}`}),global:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:()=>"global"})},Gi={fromString:(e,t)=>{let r=Z(e);return Q(r,t)},getInfo:async(e,t)=>{let r=new He(t),{info:n}=await r.checkLimit(e);return n},reset:(e,t)=>{let r=Wt.get(e);if(r)return r.cache.delete(t);return!1}};class k{static parseDomainPattern(e){let t=[],r=e.match(/\{([^}]+)\}/g)||[];for(let i of r){let o=i.slice(1,-1);t.push(o)}let n=e.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");n=`^${n}$`;let s=new RegExp(n,"i");return{pattern:e,parameters:t,regex:s}}static matchDomain(e,t){let r=e.match(t.regex);if(!r)return null;let n={};for(let s=0;s<t.parameters.length;s++){let i=t.parameters[s],o=r[s+1];n[i]=o}return n}static extractSubdomainInfo(e){let t=e.split(".");if(t.length<=2)return{domain:e,parameters:{},rootDomain:e};let r=t[0],n=t.slice(1).join(".");return{domain:e,parameters:{subdomain:r},subdomain:r,rootDomain:n}}}class oe{pattern;config;routes=[];constructor(e,t){this.pattern=e;this.config=t}addRoute(e,t,r,n=[],s){let i=[...this.config.middleware||[],...n],o=this.config.prefix?`${this.config.prefix}${t}`:t;this.routes.push({method:e.toUpperCase(),path:o,handler:r,middleware:i,name:s||(this.config.name?`${this.config.name}.${e.toLowerCase()}${t}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(e){return k.matchDomain(e,this.pattern)}}class Qe{domainGroups=[];wildcardGroup;domain(e){let t=k.parseDomainPattern(e);return new Vt(this,t)}addDomainGroup(e){if(e.pattern.pattern.includes("*")&&e.pattern.parameters.length===0)this.wildcardGroup=e;else this.domainGroups.push(e)}findDomainGroup(e){for(let t of this.domainGroups){let r=t.matchesDomain(e);if(r!==null)return{group:t,parameters:r}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:k.extractSubdomainInfo(e).parameters};return null}getAllRoutes(){let e=[];for(let t of this.domainGroups){let r=t.getRoutes();for(let n of r)e.push({domainPattern:t.pattern.pattern,domainParameters:{},...n})}if(this.wildcardGroup){let t=this.wildcardGroup.getRoutes();for(let r of t)e.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...r})}return e}}class Vt{router;pattern;group;constructor(e,t){this.router=e;this.pattern=t;this.group=new oe(t,{domain:t.pattern})}middleware(e){return this.group.config.middleware=e,this}prefix(e){return this.group.config.prefix=e,this}name(e){return this.group.config.name=e,this}routes(e){let t=new Jt(this.group);e(t),this.router.addDomainGroup(this.group)}get(e,t,r){this.group.addRoute("GET",e,t,r),this.router.addDomainGroup(this.group)}post(e,t,r){this.group.addRoute("POST",e,t,r),this.router.addDomainGroup(this.group)}put(e,t,r){this.group.addRoute("PUT",e,t,r),this.router.addDomainGroup(this.group)}delete(e,t,r){this.group.addRoute("DELETE",e,t,r),this.router.addDomainGroup(this.group)}patch(e,t,r){this.group.addRoute("PATCH",e,t,r),this.router.addDomainGroup(this.group)}}class Jt{group;constructor(e){this.group=e}get(e,t,r,n){this.group.addRoute("GET",e,t,r,n)}post(e,t,r,n){this.group.addRoute("POST",e,t,r,n)}put(e,t,r,n){this.group.addRoute("PUT",e,t,r,n)}delete(e,t,r,n){this.group.addRoute("DELETE",e,t,r,n)}patch(e,t,r,n){this.group.addRoute("PATCH",e,t,r,n)}options(e,t,r,n){this.group.addRoute("OPTIONS",e,t,r,n)}head(e,t,r,n){this.group.addRoute("HEAD",e,t,r,n)}any(e,t,r,n){let s=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let i of s)this.group.addRoute(i,e,t,r,n)}}function Vi(e){return async(t,r)=>{let s=new URL(t.url).hostname,i=e.findDomainGroup(s);if(i){let o=t;o.domainParams=i.parameters,Object.assign(t.params||{},i.parameters);let a=k.extractSubdomainInfo(s);o.subdomainInfo=a}return await r()}}var Ji={getSubdomain:(e)=>{let t=new URL(e.url);return k.extractSubdomainInfo(t.hostname).subdomain||null},getDomainParams:(e)=>e.domainParams||{},matchesDomain:(e,t)=>{let r=new URL(e.url),n=k.parseDomainPattern(t);return k.matchDomain(r.hostname,n)!==null},getSubdomainInfo:(e)=>e.subdomainInfo||null},Ki={single:(e,t)=>`${e}.${t}`,wildcard:(e,t="subdomain")=>`{${t}}.${e}`,multiLevel:(e,...t)=>`${t.map((n)=>`{${n}}`).join(".")}.${e}`,apiVersion:(e)=>`{version}.api.${e}`,tenant:(e)=>`{tenant}.app.${e}`,environment:(e)=>`{env}.${e}`};import as from"process";var Y=new Map;function N(e,t){Y.set(e,t)}function Ze(e){return Y.get(e)}function us(){return new Map(Y)}function cs(){Y.clear()}function ls(e,t={},r={}){let n=Y.get(e);if(!n){let u=[...Y.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${e}' is not defined. Known routes: ${u}`)}let s=new Set,i=n;for(let[u,c]of Object.entries(t)){let l=`{${u}}`,d=`{${u}?}`,p=encodeURIComponent(String(c));if(i.includes(l))i=i.replaceAll(l,p),s.add(u);else if(i.includes(d))i=i.replaceAll(d,p),s.add(u)}if(i.includes("?}")){if(i=i.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),i.length>1&&i.endsWith("/"))i=i.slice(0,-1)}let o=i.match(/\{([^}?]+)\}/g);if(o&&o.length>0)throw Error(`Missing required params for route '${e}': ${o.join(", ")}`);let a=Object.entries(t).filter(([u])=>!s.has(u));if(a.length>0){let u=new URLSearchParams;for(let[c,l]of a)u.set(c,String(l));i+=`?${u.toString()}`}if(r.absolute){let u=(r.base??as.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${u.startsWith("http")?u:`https://${u}`}${i.startsWith("/")?i:`/${i}`}`}return i}import{join as Kt}from"path";function ae(e){let t=e.replace(/\/+/g,"/");if(!t.startsWith("/"))t=`/${t}`;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return t}function eo(e){return e.replace(/\//g,"_").toLowerCase()}function ds(e){if(typeof e!=="function"&&typeof e!=="object")return!1;if(typeof e==="function"&&e.prototype){if(typeof e.prototype.handle==="function")return!0}if(typeof e==="object"&&e!==null&&"handle"in e&&typeof e.handle==="function")return!0;return!1}function to(e){return typeof e==="function"&&!ds(e)}function Ae(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map((r)=>r.slice(1,-1).replace("?","")):[]}function ro(e){let t=e.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${t}$`)}var ps=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,hs=/\{[^}]+\?\}/,Xt=new Map,Qt=new Map;function gs(e){let t=Xt.get(e);if(t)return t;let r=e.endsWith("/*"),n=ae(e),s=0,i=n.split("/").filter(Boolean).map((a)=>{let u=hs.test(a);if(u)s++;let c=a.match(ps);return{isParam:!!c,paramName:c?c[1].replace("?",""):"",isOptional:u,literal:a}}),o={isWildcard:r,wildcardBase:r?e.slice(0,-2):"",segments:i,optionalCount:s};return Xt.set(e,o),o}function ms(e){let t=Qt.get(e);if(t!==void 0)return t;let r;try{r=new RegExp(`^${e}$`)}catch{r=null}return Qt.set(e,r),r}function H(e,t,r,n){let s=gs(e);if(s.isWildcard&&t.startsWith(s.wildcardBase))return!0;let i=s.segments,o=ae(t).split("/").filter(Boolean);if(o.length<i.length-s.optionalCount||o.length>i.length)return!1;for(let a=0;a<i.length;a++){let u=i[a],c=o[a];if(c===void 0){if(u.isOptional)continue;return!1}if(u.isParam){if(r[u.paramName]=c,n&&n[u.paramName]){let l=ms(n[u.paramName]);if(l){if(!l.test(c))return!1}else console.warn(`Invalid constraint regex for parameter ${u.paramName}: ${n[u.paramName]}`)}}else if(u.literal!==c)return!1}return!0}function F(...e){return ae(e.join("/"))}function no(e){if(!e.startsWith("/"))return!1;let t=[];for(let r of e)if(r==="{")t.push(r);else if(r==="}"){if(t.length===0||t.pop()!=="{")return!1}return t.length===0}async function Zt(e){try{return await Bun.file(e).exists()}catch{return!1}}async function Ye(e,t,r){if(r.some((n)=>e.endsWith(n))){let n=ae(Kt(t,e));if(await Zt(n))return n;return null}for(let n of r){let s=ae(Kt(t,`${e}${n}`));if(await Zt(s))return s}return null}function Yt(e,t){let r=e.replace(/\{\{([^}]+)\}\}/g,(n,s)=>{let i=s.trim(),o=et(t,i);return o!==void 0?String(o):n});return r=fs(r,t),r=ys(r,t),r}function fs(e,t){return e.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(r,n,s,i="")=>{let o=n.trim();return et(t,o)?s:i})}function ys(e,t){return e.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(r,n,s)=>{let i=et(t,n.trim());if(!Array.isArray(i))return"";return i.map((o)=>s.replace(/\{\{@index\}\}/g,String(i.indexOf(o))).replace(/\{\{this\}\}/g,String(o)).replace(/\{\{this\.([^}]+)\}\}/g,(a,u)=>{let c=o[u.trim()];return c!==void 0?String(c):""})).join("")})}function et(e,t){return t.split(".").reduce((r,n)=>{if(r&&typeof r==="object"&&n in r)return r[n];return},e)}class f{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(e,t,r){this.method=e;this.path=t;this.handler=r}addMiddleware(e){if(Array.isArray(e))this.middleware.push(...e);else this.middleware.push(e);return this}cached(e=[],t){return this.cacheConfig={...zt.api(e),...t},this}throttle(e,t){if(typeof e==="string"){let r=Z(e);this.throttleConfig={maxAttempts:r.maxAttempts??60,windowMs:r.windowMs,keyGenerator:(n)=>n.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=e;return this}name(e){return this.routeName=e,this}model(e,t){return this.modelBindings[e]=t,this}build(){let e=[];if(Object.keys(this.modelBindings).length>0){let t=Object.keys(this.modelBindings).map((n)=>({name:n})),r=Nt(t,this.modelBindings);e.push(r)}if(this.throttleConfig){let t=Q(this.throttleConfig);e.push(t)}if(this.cacheConfig){let t=Lt(this.cacheConfig);e.push(t)}return e.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:e,name:this.routeName}}}class er{router;condition;constructor(e,t){this.router=e;this.condition=t}middleware(e){let[t,r]=e.split(":"),n=this.router.resolveNamedMiddleware(t);if(!n)throw Error(`Unknown middleware: ${t}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[n(r)]}),this}}class tr{router;middleware;constructor(e,t){this.router=e;this.middleware=t}get(e,t){return new f("GET",e,t).addMiddleware(this.middleware)}post(e,t){return new f("POST",e,t).addMiddleware(this.middleware)}put(e,t){return new f("PUT",e,t).addMiddleware(this.middleware)}delete(e,t){return new f("DELETE",e,t).addMiddleware(this.middleware)}patch(e,t){return new f("PATCH",e,t).addMiddleware(this.middleware)}}class rr{router;groupMiddleware;constructor(e,t){this.router=e;this.groupMiddleware=t}get(e,t){return new f("GET",e,t).addMiddleware(this.groupMiddleware)}post(e,t){return new f("POST",e,t).addMiddleware(this.groupMiddleware)}put(e,t){return new f("PUT",e,t).addMiddleware(this.groupMiddleware)}delete(e,t){return new f("DELETE",e,t).addMiddleware(this.groupMiddleware)}patch(e,t){return new f("PATCH",e,t).addMiddleware(this.groupMiddleware)}}class ue{routes=[];globalMiddleware=[];subdomainRouter=new Qe;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(e)=>{let t=e?Z(e):{maxAttempts:60,windowMs:60000},r=Q({maxAttempts:t.maxAttempts,windowMs:t.windowMs,keyGenerator:(s)=>s.headers.get("x-forwarded-for")||"anonymous"});return async(s,i)=>await r(s,async()=>await i()??new Response(null))}),this.namedMiddleware.set("auth",()=>async(e,t)=>{if(!e.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return e.user={id:"123",roles:["user"]},await t()}),this.namedMiddleware.set("cors",()=>async(e,t)=>{let r=await t();if(r){let n=new Headers(r.headers);return n.set("Access-Control-Allow-Origin","*"),n.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),n.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(r.body,{status:r.status,statusText:r.statusText,headers:n})}return r})}middlewareGroup(e,t){let r=[];for(let n of t){let[s,i]=n.split(":"),o=this.namedMiddleware.get(s);if(o)r.push(o(i))}return this.middlewareGroups.set(e,r),this}middlewareGroupRoutes(e){let t=this.middlewareGroups.get(e)||[];return new rr(this,t)}when(e){return new er(this,e)}resolveNamedMiddleware(e){return this.namedMiddleware.get(e)}addConditionalMiddleware(e){this.conditionalMiddleware.push(e)}middleware(e){let[t,r]=e.split(":"),n=this.namedMiddleware.get(t);if(!n)throw Error(`Unknown middleware: ${t}`);let s=n(r);return new tr(this,[s])}use(e){return this.globalMiddleware.push(e),this}get(e,t){return new f("GET",e,t)}post(e,t){return new f("POST",e,t)}put(e,t){return new f("PUT",e,t)}delete(e,t){return new f("DELETE",e,t)}patch(e,t){return new f("PATCH",e,t)}register(e){let t=e.build();if(this.routes.push(t),t.name)N(t.name,t.path);return this}cached(e=[],t){return{get:(r,n)=>this.get(r,n).cached(e,t),post:(r,n)=>this.post(r,n).cached(e,t),put:(r,n)=>this.put(r,n).cached(e,t),delete:(r,n)=>this.delete(r,n).cached(e,t),patch:(r,n)=>this.patch(r,n).cached(e,t)}}throttled(e){return{get:(t,r)=>this.get(t,r).throttle(e),post:(t,r)=>this.post(t,r).throttle(e),put:(t,r)=>this.put(t,r).throttle(e),delete:(t,r)=>this.delete(t,r).throttle(e),patch:(t,r)=>this.patch(t,r).throttle(e)}}group(e,t){let r=new ue;t(r);for(let n of r.routes){let s={...n,path:e.prefix?`${e.prefix}${n.path}`:n.path,middleware:[...e.middleware||[],...n.middleware],name:e.name&&n.name?`${e.name}.${n.name}`:n.name};if(e.domain){let i=k.parseDomainPattern(e.domain),o=new oe(i,{domain:e.domain});o.addRoute(s.method,s.path,s.handler,s.middleware,s.name),this.subdomainRouter.addDomainGroup(o)}else if(this.routes.push(s),s.name)N(s.name,s.path)}return this}domain(e){return{routes:(t)=>{let r=new ue;t(r);let n=k.parseDomainPattern(e),s=new oe(n,{domain:e});for(let i of r.routes)s.addRoute(i.method,i.path,i.handler,i.middleware,i.name);return this.subdomainRouter.addDomainGroup(s),this}}}resource(e,t,r={}){let n=["index","create","store","show","edit","update","destroy"],s=r.only||n.filter((o)=>!r.except?.includes(o)),i=[{action:"index",method:"GET",path:`/${e}`,handler:t.index},{action:"create",method:"GET",path:`/${e}/create`,handler:t.create},{action:"store",method:"POST",path:`/${e}`,handler:t.store},{action:"show",method:"GET",path:`/${e}/{${e.slice(0,-1)}}`,handler:t.show},{action:"edit",method:"GET",path:`/${e}/{${e.slice(0,-1)}}/edit`,handler:t.edit},{action:"update",method:"PUT",path:`/${e}/{${e.slice(0,-1)}}`,handler:t.update},{action:"destroy",method:"DELETE",path:`/${e}/{${e.slice(0,-1)}}`,handler:t.destroy}];for(let o of i)if(s.includes(o.action)&&o.handler){let a=new f(o.method,o.path,o.handler).name(`${e}.${o.action}`);if(r.model&&["show","edit","update","destroy"].includes(o.action))a.model(e.slice(0,-1),r.model);this.register(a)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(e){let t=new URL(e.url),r=t.hostname,n=this.subdomainRouter.findDomainGroup(r);if(n){let s=e;s.domainParams=n.parameters;for(let i of n.group.getRoutes()){let o=this.matchRouteParams(i,e.method,t.pathname);if(o)return await this.executeRoute(i,s,o)}}for(let s of this.routes){let i=this.matchRouteParams(s,e.method,t.pathname);if(i)return await this.executeRoute(s,e,i)}return null}matchRouteParams(e,t,r){if(e.method!==t)return null;let n={};return H(e.path,r,n)?n:null}async executeRoute(e,t,r){t.params=r;let n=[...this.globalMiddleware];for(let o of this.conditionalMiddleware)if(await o.condition(t))n.push(...o.middleware);n.push(...e.middleware);let s=0,i=async()=>{if(s<n.length){let o=n[s++];return await o(t,i)??new Response(null)}return await e.handler(t)};return await i()}}var Rs={api:(e,t,r={})=>{let n=r.method||"GET",s=new f(n,e,t);if(r.cache)s.cached(r.cache);if(r.throttle)s.throttle(r.throttle);return s},protected:(e,t,r={})=>{let n=r.method||"GET",s=new f(n,e,t);return s.addMiddleware(async(i,o)=>{if(!i.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await o()}),s},upload:(e,t,r={})=>{let n=new f("POST",e,t);return n.addMiddleware(async(s,i)=>await i()),n}},ws={route:(e,t={},r={})=>{let n=Ze(e)??`/${e}`;for(let[i,o]of Object.entries(t)){let a=encodeURIComponent(o);n=n.replace(`{${i}}`,a),n=n.replace(`{${i}?}`,a)}if(n.includes("?}")){if(n=n.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),n.length>1&&n.endsWith("/"))n=n.slice(0,-1)}let s=new URLSearchParams(r).toString();if(s)n+=`?${s}`;return n},redirect:(e,t=302)=>new Response(null,{status:t,headers:{Location:e}}),json:(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})},bs=new ue;function nr(e){Object.defineProperties(e.prototype,{group:{value(t,r){let n=this.currentGroup,s={...n};if(t.prefix&&n?.prefix)s.prefix=F(n.prefix,t.prefix);else if(t.prefix)s.prefix=t.prefix;if(t.middleware)s.middleware=[...n?.middleware||[],...t.middleware];this.currentGroup=s;let i=r();if(i instanceof Promise)return i.then(()=>(this.currentGroup=n,this),(o)=>{throw this.currentGroup=n,o});return this.currentGroup=n,this},writable:!0,configurable:!0},name:{value(t,r){let n=this.currentGroup||{},s={...n};this.currentGroup=s;let i=this.routes.length;r();for(let o=i;o<this.routes.length;o++){let a=this.routes[o];if(a.name)a.name=`${t}.${a.name}`}return this.currentGroup=n,this},writable:!0,configurable:!0},controller:{value(t,r){let n=this.currentGroup||{},s={...n,controller:t};return this.currentGroup=s,r(),this.currentGroup=n,this},writable:!0,configurable:!0},domain:{value(t,r){let n=this.currentDomain;return this.currentDomain=t,r(),this.currentDomain=n,this},writable:!0,configurable:!0},prefix:{value(t,r){return this.group({prefix:t},r)},writable:!0,configurable:!0},resource:{value(t,r,n="api"){let s=t.endsWith("s")?t:`${t}s`,i=t.endsWith("s")?t.slice(0,-1):t,o=[{name:"index",method:"GET",path:`/${s}`,action:"index"},{name:"create",method:"GET",path:`/${s}/create`,action:"create"},{name:"store",method:"POST",path:`/${s}`,action:"store"},{name:"show",method:"GET",path:`/${s}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${s}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${s}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${s}/{id}`,action:"destroy"}];return this.name(i,()=>{for(let a of o){let u;if(typeof r==="string")u=`${r}${a.action.charAt(0).toUpperCase()+a.action.slice(1)}Action`;else if(r[a.action])u=r[a.action];else continue;switch(a.method){case"GET":this.get(a.path,u,n,a.name);break;case"POST":this.post(a.path,u,n,a.name);break;case"PUT":this.put(a.path,u,n,a.name);break;case"DELETE":this.delete(a.path,u,n,a.name);break}}}),this},writable:!0,configurable:!0}})}function sr(e){Object.defineProperties(e.prototype,{addRoute:{value(t,r,n,s,i,o){let a=r,u=[],c=s||"web";if(this.currentGroup){if(this.currentGroup.prefix)a=F(this.currentGroup.prefix,r);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)u=[...this.currentGroup.middleware]}if(o&&o.length>0)for(let h of o){let m=this.resolveMiddleware(h);if(m)u.push(m)}if(c==="api"&&this.config.apiPrefix)a=F(this.config.apiPrefix,a);else if(c==="web"&&this.config.webPrefix)a=F(this.config.webPrefix,a);let l;if(this.currentDomain)l=this.currentDomain;let d={method:t.toUpperCase(),path:a,handler:n,domain:l,params:{},middleware:u},p=Ae(a),g={};if(p.forEach((h)=>{let m=h.replace("?","");if(this.patterns.has(m))g[m]=this.patterns.get(m)}),Object.keys(g).length>0)d.constraints=g;if(d.pattern={exec:(h)=>{let m={},R=d.constraints&&!Array.isArray(d.constraints)?d.constraints:void 0;if(!H(a,h.pathname,m,R))return null;return{pathname:{groups:m}}}},n instanceof Response)this.staticResponses.set(a,n);if(l){if(!this.domains[l])this.domains[l]=[];this.domains[l].push(d)}else this.routes.push(d);if(!a.includes("{")&&!a.includes("*")){if(!this.staticRoutes.has(t.toUpperCase()))this.staticRoutes.set(t.toUpperCase(),new Map);let h=this.staticRoutes.get(t.toUpperCase());if(!h.has(a))h.set(a,d)}if(i)d.name=i,this.namedRoutes.set(i,d),N(i,d.path);if(this.addRouteToCompiler&&!l)this.addRouteToCompiler(d);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(t,r,n,s,i){return this.addRoute("GET",t,r,n,s,i)},writable:!0,configurable:!0},post:{value(t,r,n,s,i){return this.addRoute("POST",t,r,n,s,i)},writable:!0,configurable:!0},put:{value(t,r,n,s,i){return this.addRoute("PUT",t,r,n,s,i)},writable:!0,configurable:!0},patch:{value(t,r,n,s,i){return this.addRoute("PATCH",t,r,n,s,i)},writable:!0,configurable:!0},delete:{value(t,r,n,s,i){return this.addRoute("DELETE",t,r,n,s,i)},writable:!0,configurable:!0},options:{value(t,r,n,s,i){return this.addRoute("OPTIONS",t,r,n,s,i)},writable:!0,configurable:!0},head:{value(t,r,n,s,i){return this.addRoute("HEAD",t,r,n,s,i)},writable:!0,configurable:!0},match:{value(t,r,n,s,i,o){for(let a of t)this.addRoute(a,r,n,s,i,o);return this},writable:!0,configurable:!0},any:{value(t,r,n,s,i){let o=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(o,t,r,n,s,i)},writable:!0,configurable:!0},fallback:{value(t){return this.fallbackHandler=t,this},writable:!0,configurable:!0},route:{value(t,r={}){let n=this.namedRoutes.get(t);if(!n)throw Error(`Route with name "${t}" not found`);let s=n.path;for(let[i,o]of Object.entries(r))s=s.replace(`{${i}}`,encodeURIComponent(o)),s=s.replace(`{${i}?}`,encodeURIComponent(o));if(s.includes("{")){if(s=s.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),s.length>1&&s.endsWith("/"))s=s.slice(0,-1)}return s},writable:!0,configurable:!0},onError:{value(t){return this.errorHandler=t,this},writable:!0,configurable:!0}})}function ir(e){Object.defineProperties(e.prototype,{redirect:{value(t,r=302){let n=new Headers;return n.set("Location",t),new Response(null,{status:r,headers:n})},writable:!0,configurable:!0},permanentRedirect:{value(t){return this.redirect(t,301)},writable:!0,configurable:!0},redirectRoute:{value(t,r,n=302){return this.get(t,(s)=>this.redirect(r,n)),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(t,r){return this.redirectRoute(t,r,301)},writable:!0,configurable:!0}})}function M(e){if(e instanceof Response)return e;if(e===null||e===void 0)return new Response(null,{status:204});if(typeof e==="string")return new Response(e,{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(typeof e==="number"||typeof e==="boolean")return new Response(String(e),{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(e instanceof ArrayBuffer||e instanceof Uint8Array)return new Response(e,{headers:{"Content-Type":"application/octet-stream"}});if(e instanceof ReadableStream)return new Response(e);if(typeof e==="object")return new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json; charset=utf-8"}});return new Response(String(e),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function Ts(e,t){let r=t.actionsPath||"actions",n=t.controllersPath||"controllers",s=e.replace(/\.(ts|js)$/,""),i=[];if(s.includes("@")){let[a,u]=s.split("@");i.push(`${n}/${a}`,`${n}/${a}.ts`,`${n}/${a}.js`,`./${n}/${a}`,`../${n}/${a}`)}else if(s.startsWith("Actions/")||s.startsWith("actions/"))i.push(s,`./${s}`,`../${s}`);else if(s.startsWith("./")||s.startsWith("../"))i.push(s);else i.push(`${r}/${s}`,`./${r}/${s}`,`../${r}/${s}`,s,`./${s}`,`../${s}`);let o=null;for(let a of i)try{return await import(a)}catch(u){o=u}throw Error(`Failed to import handler "${e}".
|
|
94
|
+
Tried paths: ${i.join(", ")}
|
|
95
|
+
Last error: ${o?.message||"Unknown error"}`)}function or(e){return typeof e==="function"&&!e.prototype?.handle}async function ce(e,t,r){if(e instanceof Response)return e.clone();if(or(e)){let n=await e(t);return M(n)}if(typeof e==="string")return xs(e,t,r);if(typeof e==="function"&&e.prototype&&typeof e.prototype.handle==="function"){let i=await new e().handle(t);return M(i)}if(e&&typeof e==="object"&&"handle"in e){let n=e;if(typeof n.handle==="function"){let s=await n.handle(t);return M(s)}}throw Error(`Invalid handler type: ${typeof e}`)}async function xs(e,t,r){let n=r.controllersPath||"controllers";if(e.includes("@")){let[o,a]=e.split("@"),u=[`${n}/${o}`,`./${n}/${o}`,`../${n}/${o}`,o,`./${o}`,`../${o}`],c=null,l=null;for(let p of u)try{c=await import(p);break}catch(g){l=g}if(!c)throw Error(`Failed to import controller "${o}".
|
|
96
|
+
Tried paths: ${u.join(", ")}
|
|
97
|
+
Last error: ${l?.message||"Unknown error"}`);let d=c.default||c;if(typeof d==="function"){let p=new d,g=p[a];if(typeof g!=="function")throw TypeError(`Method "${a}" not found on controller "${o}"`);let h=await g.call(p,t);return M(h)}throw Error(`Controller "${o}" is not a valid class`)}let s=await Ts(e,r),i=s.default||s;if(typeof i==="function"){if(i.prototype&&typeof i.prototype.handle==="function"){let u=await new i().handle(t);return M(u)}let o=await i(t);return M(o)}if(i&&typeof i==="object"&&"handle"in i){let o=i;if(typeof o.handle==="function"){let a=await o.handle(t);return M(a)}}throw Error(`Handler "${e}" does not export a valid handler function or class`)}function vs(e){return(t,r)=>ce(t,r,e)}function ar(e,t){if(e instanceof Response)return async()=>e.clone();if(or(e))return async(r)=>M(await e(r));if(typeof e==="function"&&e.prototype&&typeof e.prototype.handle==="function"){let r=e;return async(n)=>M(await new r().handle(n))}return(r)=>ce(e,r,t)}function ur(e){Object.defineProperties(e.prototype,{use:{value(...t){for(let r of t){let n=this.resolveMiddleware(r);if(n)this.globalMiddleware.push(n)}return this._mwEpoch=(this._mwEpoch||0)+1,this},writable:!0,configurable:!0},resolveMiddleware:{value(t){if(typeof t==="function")return t;if(typeof t==="object"&&t!==null&&"handle"in t&&typeof t.handle==="function")return(r,n)=>t.handle(r,n);if(typeof t==="string"){let[r,n]=t.split(":"),s=this.namedMiddleware?.get(r);if(s)return s(n);let i=null,o=t;return async(a,u)=>{if(!i)try{let c=await import(`../middleware/${o}.ts`);if(c.default&&typeof c.default==="function")i=c.default;else if(c.default&&typeof c.default.handle==="function")i=(l,d)=>c.default.handle(l,d)}catch(c){console.error(`Failed to load middleware "${o}":`,c)}if(i)return i(a,u);return u()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value(t){if(t.length===0)return async(n)=>null;let r=async(n)=>null;for(let n=t.length-1;n>=0;n--){let s=t[n],i=r;r=async(o)=>s(o,async()=>await i(o)||new Response(null,{status:200}))}return r},writable:!0,configurable:!0},runMiddleware:{async value(t,r){if(r.length===0)return null;try{return await this.buildMiddlewareChain(r)(t)}catch(n){if(this.errorHandler)return this.errorHandler(n);throw n}},writable:!0,configurable:!0},middleware:{value(...t){for(let r of t)if(typeof r==="string"){let[n]=r.split(":");if(!this.namedMiddleware.has(n))throw Error(`Unknown middleware: ${n}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...t)}else{let r=this.routes[this.routes.length-1];if(r)this.applyMiddlewareToRoute(r,t)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(t,r){for(let n of r){let s=this.resolveMiddleware(n);if(s)t.middleware.push(s)}},writable:!0,configurable:!0},resolveHandler:{async value(t,r){return ce(t,r,this.config)},writable:!0,configurable:!0},wrapResponse:{value:M,writable:!0,configurable:!0},onError:{value(t){return this.errorHandler=t,this},writable:!0,configurable:!0}})}class cr{models=new Map;cache=new Map;register(e,t){this.models.set(e,t)}get(e){return this.models.get(e)}has(e){return this.models.has(e)}async resolve(e,t,r){let n=this.models.get(e);if(!n)return{model:null,error:`Model binding '${e}' not found`,status:500};try{if(n.cache?.enabled){let o=this.getCachedModel(e,t,n);if(o)return{model:o}}let s=await n.resolver(t,r);if(s===null||s===void 0)return{model:null,error:`${e} not found`,status:404};if(n.validator){let o=await n.validator(s,t,r);if(!o.valid)return{model:null,error:o.error||"Model validation failed",status:o.status||422}}let i=s;if(n.transformer)i=await n.transformer(s,t,r);if(n.cache?.enabled)this.cacheModel(e,t,i,n);return{model:i}}catch(s){return{model:null,error:s instanceof Error?s.message:"Model resolution failed",status:500}}}createErrorResponse(e,t,r){let n=this.models.get(e),s=t.status||404,i=t.error||"Model not found";if(n?.errorHandling){if(s===404&&n.errorHandling.notFound)return n.errorHandling.notFound(r);if(s===422&&n.errorHandling.validation)return n.errorHandling.validation(null,i);if(n.errorHandling.transform)return n.errorHandling.transform(i)}return new Response(JSON.stringify({error:i,status:s,message:`Failed to resolve ${e}`}),{status:s,headers:{"Content-Type":"application/json"}})}clearCache(e,t){if(t){let r=this.models.get(e);if(r?.cache){let n=this.generateCacheKey(e,t,r);this.cache.delete(n)}}else{let r=[];for(let n of this.cache.keys())if(n.startsWith(`${e}:`))r.push(n);for(let n of r)this.cache.delete(n)}}clearAllCache(){this.cache.clear()}getCacheStats(){let e=Date.now(),t=0,r=0;for(let n of this.cache.values())if(e-n.timestamp>n.ttl)r++;else t++;return{totalEntries:this.cache.size,validEntries:t,expiredEntries:r,models:this.models.size}}cleanupCache(){let e=Date.now(),t=[];for(let[r,n]of this.cache.entries())if(e-n.timestamp>n.ttl)t.push(r);for(let r of t)this.cache.delete(r);return t.length}getCachedModel(e,t,r){if(!r.cache?.enabled)return null;let n=this.generateCacheKey(e,t,r),s=this.cache.get(n);if(!s)return null;if(Date.now()-s.timestamp>s.ttl)return this.cache.delete(n),null;return s.model}cacheModel(e,t,r,n){if(!n.cache?.enabled)return;let s=this.generateCacheKey(e,t,n);this.cache.set(s,{model:r,timestamp:Date.now(),ttl:n.cache.ttl})}generateCacheKey(e,t,r){if(r.cache?.key)return`${e}:${r.cache.key(t)}`;let n=Object.entries(t).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${i}`).join("&");return`${e}:${n}`}}var lr=new cr;function dr(e){Object.defineProperties(e.prototype,{modelRegistry:{value:lr,writable:!0,configurable:!0},model:{value(t,r,n){if(typeof r==="string")this.modelRegistry.register(t,{resolver:async(s)=>(console.warn(`Model class ${r} not implemented`),{id:s[t],modelClass:r}),errorHandling:n?{notFound:(s)=>n(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(t,{resolver:async(s)=>{let i=s[t];if(!i)return null;return r(i)},errorHandling:n?{notFound:(s)=>n(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(t,r)=>{if(!t.params)return await r()||new Response("Not Found",{status:404});for(let[s,i]of Object.entries(t.params))if(this.modelRegistry.has(s))try{let o=await this.modelRegistry.resolve(s,t.params,t);if(o.model===null){if(o.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:o.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(o.status===404)return this.modelRegistry.createErrorResponse(s,o,t.params)}else t[s]=o.model}catch(o){return new Response(JSON.stringify({error:"Internal Server Error",message:o instanceof Error?o.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await r()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(t){return async(r,n)=>{try{return await n()||t(r)}catch(s){return console.error(s),t(r)}}},writable:!0,configurable:!0},scopedBindings:{value(t){return async(r,n)=>{if(!r.params)return await n()||new Response("Not Found",{status:404});for(let[i,o]of Object.entries(t))if(r.params[i]&&r.params[o]);return await n()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},clearModelCache:{value(t){if(t)this.modelRegistry.clearCache(t);else this.modelRegistry.clearAllCache();return this},writable:!0,configurable:!0},getModelStats:{value(){return this.modelRegistry.getCacheStats()},writable:!0,configurable:!0}})}class I{children=new Map;paramChild=null;wildcardChild=null;routes=new Map;paramName=null;pattern=null;isEndpoint=!1;addRoute(e,t){this.routes.set(e,t),this.isEndpoint=!0}getRoute(e){return this.routes.get(e)}getAllRoutes(){return Array.from(this.routes.values())}}class tt{root=new I;compiledRoutes=new Map;methodTries=new Map;constructor(){let e=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","TRACE","CONNECT"];for(let t of e)this.methodTries.set(t,new I)}compileRoute(e){let t=`${e.method}:${e.path}`;if(e.constraints&&!Array.isArray(e.constraints)){let u=e.constraints,l=Object.keys(u).sort().map((d)=>`${d}:${u[d]}`).join("|");t=`${e.method}:${e.path}#${l}`}if(this.compiledRoutes.has(t))return this.compiledRoutes.get(t);let r=this.parsePathSegments(e.path),n=r.filter((u)=>u.type==="parameter").map((u)=>u.paramName);if(e.constraints&&!Array.isArray(e.constraints)){let u=e.constraints;for(let c of r)if(c.type==="parameter"&&c.paramName&&u[c.paramName])c.pattern=new RegExp(`^${u[c.paramName]}$`)}let s=this.calculateRoutePriority(r),i=r.filter((u)=>u.type==="static").length,o=r.filter((u)=>u.type!=="static").length,a={route:e,segments:r,paramNames:n,priority:s,staticScore:i,dynamicScore:o};return this.compiledRoutes.set(t,a),a}parsePathSegments(e){let t=[],r=e.split("/").filter((n)=>n.length>0);for(let n of r)if(n==="*")t.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(n))t.push({type:"wildcard",value:n,paramName:n.slice(1,n.indexOf("}"))});else if(n.startsWith("{")&&n.endsWith("}")){let s=n.slice(1,-1),[i,o]=s.split(":");t.push({type:"parameter",value:n,paramName:i.replace("?",""),pattern:o?new RegExp(`^${o}$`):void 0,optional:s.endsWith("?")})}else if(n.includes("{")){let s=n.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(o,a,u)=>u?`(${u})`:"([^/]+)"),i=Array.from(n.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((o)=>o[1].replace("?",""));t.push({type:"parameter",value:n,paramName:i[0],pattern:new RegExp(`^${s}$`)})}else t.push({type:"static",value:n});return t}calculateRoutePriority(e){let t=0;for(let r=0;r<e.length;r++){let n=e[r],s=e.length-r;switch(n.type){case"static":t+=s*1000;break;case"parameter":if(n.pattern)t+=s*100;else t+=s*10;break;case"wildcard":t+=s*1;break}}return t}addRoute(e){let t=this.compileRoute(e);this.insertRoute(this.root,t,0);let r=this.methodTries.get(e.method);if(r)this.insertRoute(r,t,0)}insertRoute(e,t,r){if(r>=t.segments.length){e.addRoute(t.route.method,t);return}let n=t.segments[r];switch(n.type){case"static":if(!e.children.has(n.value))e.children.set(n.value,new I);this.insertRoute(e.children.get(n.value),t,r+1);break;case"parameter":if(!e.paramChild)e.paramChild=new I,e.paramChild.paramName=n.paramName,e.paramChild.pattern=n.pattern||null;this.insertRoute(e.paramChild,t,r+1);break;case"wildcard":if(!e.wildcardChild)e.wildcardChild=new I,e.wildcardChild.paramName=n.paramName??null;this.insertRoute(e.wildcardChild,t,r+1);break}}match(e,t){let r=e.split("/").filter((s)=>s.length>0),n=this.methodTries.get(t);if(n){let s=this.matchSegments(n,r,0,{},t);if(s)return s}return this.matchSegments(this.root,r,0,{},t)}matchSegments(e,t,r,n,s){if(r>=t.length){let u=e.getRoute(s);if(u)return{route:u.route,params:n,score:u.priority};return null}let i=t[r],o=e.children.get(i);if(o){let u=this.matchSegments(o,t,r+1,n,s);if(u)return u}let a=e.paramChild;if(a&&a.paramName&&(!a.pattern||a.pattern.test(i))){let u=n[a.paramName];n[a.paramName]=i;let c=this.matchSegments(a,t,r+1,n,s);if(c)return c;if(u===void 0)delete n[a.paramName];else n[a.paramName]=u}if(e.wildcardChild){let u=e.wildcardChild.getRoute(s);if(u)return n[e.wildcardChild.paramName??"wildcard"]=t.slice(r).join("/"),{route:u.route,params:n,score:u.priority}}return null}getAllRoutes(){return Array.from(this.compiledRoutes.values())}removeRoute(e){let t=`${e.method}:${e.path}`;if(e.constraints&&!Array.isArray(e.constraints)){let r=e.constraints,s=Object.keys(r).sort().map((i)=>`${i}:${r[i]}`).join("|");t=`${e.method}:${e.path}#${s}`}this.compiledRoutes.delete(t)}clear(){this.root=new I,this.compiledRoutes.clear();for(let[e]of this.methodTries)this.methodTries.set(e,new I)}getStats(){let e={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let t of this.compiledRoutes.values()){let r=t.route.method;e.methodDistribution[r]=(e.methodDistribution[r]||0)+1}return e}countNodes(e){let t=1;for(let r of e.children.values())t+=this.countNodes(r);if(e.paramChild)t+=this.countNodes(e.paramChild);if(e.wildcardChild)t+=this.countNodes(e.wildcardChild);return t}}class qe{trie;matchCache=new Map;routeKeys=new Set;stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}};options;constructor(e={}){this.options={enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0,enableProfiling:!1,...e},this.trie=new tt}addRoute(e){if(this.options.precompilePatterns)this.precompileRoutePattern(e);let t=`${e.method}:${e.path}`;if(this.routeKeys.has(t))return!1;if(this.routeKeys.add(t),this.trie.addRoute(e),this.options.enableCaching)this.matchCache.clear();let r=e.method;return this.stats.methodDistribution[r]=(this.stats.methodDistribution[r]||0)+1,!0}patternCache=new Map;extractParamNames(e){let t=[],r=/\{([^}:]+)(?::[^}]+)?\}/g,n;while(n=r.exec(e))t.push(n[1].replace("?",""));return t}precompileRoutePattern(e){if(!e.pattern&&e.path.includes("{")){let t=e.path;if(e.constraints&&!Array.isArray(e.constraints)){let s=e.constraints,o=Object.keys(s).sort().map((a)=>`${a}:${s[a]}`).join("|");t=`${e.path}#${o}`}if(this.patternCache.has(t)){e.pattern=this.patternCache.get(t);return}let r=this.convertToURLPattern(e.path,e.constraints&&!Array.isArray(e.constraints)?e.constraints:void 0),n={exec:(s)=>{let i=s.pathname,o=r.exec(i);if(!o)return null;return{pathname:{groups:o.groups||{}}}}};this.patternCache.set(t,n),e.pattern=n}}convertToURLPattern(e,t){let r=e,n=null,s=r.match(/\{([^{}/]+)\}\*$/);if(s)n=s[1],r=r.slice(0,s.index);else if(r.endsWith("*"))n="wildcard",r=r.slice(0,-1);let i=[],a=r.replace(/\{([^}]+)\}/g,(c,l)=>(i.push(l),`\x00${i.length-1}\x00`)).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(a=a.replace(/\/?\u0000(\d+)\u0000/g,(c,l)=>{let d=i[Number(l)],p=d.endsWith("?"),g=p?d.slice(0,-1):d,h=g.indexOf(":"),m=h===-1?g:g.slice(0,h),R=h===-1?void 0:g.slice(h+1),T=t?.[m]??R??"[^/]+",V=`(?<${m}>${T})`,me=c.startsWith("/")?"/":"";return p?`(?:${me}${V})?`:`${me}${V}`}),n!==null)a+=`(?<${n}>${t?.[n]??".+"})`;let u=new RegExp(`^${a}$`);return{exec:(c)=>{let l=c.match(u);if(!l)return null;return{groups:l.groups||{}}}}}match(e,t){let r=this.options.enableProfiling?performance.now():0;if(this.stats.totalMatches++,this.options.enableCaching){let i=`${t}:${e}`,o=this.matchCache.get(i);if(o!==void 0||this.matchCache.has(i)){if(this.stats.cacheHits++,r)this.updateMatchTime(r);return o?{route:o.route,params:{...o.params}}:null}this.stats.cacheMisses++}let n=this.trie.match(e,t),s=null;if(n)s={route:n.route,params:n.params};if(this.options.enableCaching){let i=`${t}:${e}`;this.addToCache(i,s)}if(r)this.updateMatchTime(r);return s?{route:s.route,params:{...s.params}}:null}addToCache(e,t){if(this.matchCache.size>=this.options.cacheSize&&!this.matchCache.has(e)){let r=this.matchCache.keys().next().value;if(r!==void 0)this.matchCache.delete(r)}this.matchCache.set(e,t)}updateMatchTime(e){let t=performance.now()-e;this.stats.averageMatchTime=(this.stats.averageMatchTime*(this.stats.totalMatches-1)+t)/this.stats.totalMatches}getCompiledRoutes(){let e=this.trie.getAllRoutes();if(this.options.enablePriorityOptimization)return e.sort((t,r)=>r.priority-t.priority);return e}getRoutesByMethod(){let e=new Map;for(let t of this.trie.getAllRoutes()){let r=t.route.method;if(!e.has(r))e.set(r,[]);e.get(r).push(t)}if(this.options.enablePriorityOptimization)for(let[t,r]of e)r.sort((n,s)=>s.priority-n.priority),e.set(t,r);return e}warmCache(e,t={}){if(!this.options.enableCaching&&!t.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let r=this.options.enableCaching;if(t.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(t.precompile)for(let{path:l,method:d}of e){let p=`${d}:${l}`;this.matchCache.delete(p)}let n=this.matchCache.size,s=this.stats.cacheHits,i=this.stats.totalMatches;for(let{path:l,method:d}of e)if(this.match(l,d),t.precompile)this.match(l,d);let o=this.matchCache.size-n,a=this.stats.cacheHits-s,u=this.stats.totalMatches-i,c=u>0?a/u:0;if(t.force&&!r)this.options.enableCaching=r;return{warmedPaths:o,cacheSize:this.matchCache.size,hitRate:c}}clear(){this.trie.clear(),this.matchCache.clear(),this.routeKeys.clear(),this.stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}}}getStats(){let e=this.trie.getStats();return{...this.stats,trieDepth:e.averageDepth,methodDistribution:e.methodDistribution}}getCacheStats(){let e=this.stats.totalMatches>0?this.stats.cacheHits/this.stats.totalMatches:0;return{size:this.matchCache.size,maxSize:this.options.cacheSize,hitRate:e,enabled:this.options.enableCaching}}optimizeRouteOrder(e){if(!this.options.enablePriorityOptimization)return;this.matchCache.clear()}getRouteConflicts(){let e=[],t=this.trie.getAllRoutes(),r=new Map;for(let n of t){let s=n.route.method;if(!r.has(s))r.set(s,[]);r.get(s).push(n)}for(let[n,s]of r)for(let i=0;i<s.length;i++)for(let o=i+1;o<s.length;o++){let a=s[i],u=s[o];if(this.routesConflict(a,u)){let c=this.getConflictSeverity(a,u),l=this.getConflictType(a,u);e.push({routes:[a,u],conflictType:l,severity:c})}}return e}routesConflict(e,t){if(e.route.path===t.route.path)return!0;if(e.route.method!==t.route.method)return!1;return this.patternsOverlap(e.segments,t.segments)}patternsOverlap(e,t){let r=e.some((o)=>o.optional||o.type==="wildcard"),n=t.some((o)=>o.optional||o.type==="wildcard");if(e.length!==t.length&&!r&&!n)return!1;let s=Math.max(e.length,t.length),i=!0;for(let o=0;o<s;o++){let a=o<e.length?e[o]:null,u=o<t.length?t[o]:null;if(!a&&u&&!u.optional)return!1;if(!u&&a&&!a.optional)return!1;if(!a||!u)continue;if(a.type==="static"&&u.type==="static"){if(a.value!==u.value)return!1}else if(a.type==="parameter"&&u.type==="parameter"){if(a.pattern&&u.pattern){if(a.pattern.toString()===u.pattern.toString())i=!0}if(a.paramName===u.paramName)i=!0}else if(a.type==="static"&&u.type==="parameter"||a.type==="parameter"&&u.type==="static"){let c=a.type==="static"?a:u,l=a.type==="parameter"?a:u;if(l.pattern){if(!l.pattern.test(c.value))return!1}}else if(a.type==="wildcard"||u.type==="wildcard")return!0}return i}getConflictSeverity(e,t){if(e.route.path===t.route.path)return"high";if(e.staticScore===t.staticScore)return"medium";return"low"}getConflictType(e,t){if(e.route.path===t.route.path)return"duplicate";if(this.hasAmbiguousParameters(e,t))return"ambiguous";if(Math.abs(e.priority-t.priority)<10)return"ambiguous";return"overlap"}hasAmbiguousParameters(e,t){if(Math.abs(e.segments.length-t.segments.length)>1)return!1;let r=e.segments.filter((s)=>s.type==="parameter").length,n=t.segments.filter((s)=>s.type==="parameter").length;if(r>0&&n>0){let s=Math.min(e.segments.length,t.segments.length),i=0;for(let o=0;o<s;o++)if(e.segments[o].type==="parameter"&&t.segments[o].type==="parameter"){i++;let a=!!e.segments[o].pattern,u=!!t.segments[o].pattern;if(a!==u)return!0}return i>0&&i>=Math.min(r,n)/2}return!1}}function pr(e){Object.defineProperties(e.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new qe({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0})},writable:!0,configurable:!0},addRouteToCompiler:{value(t){this.initializeRouteCompiler(),this.routeCompiler.addRoute(t)},writable:!0,configurable:!0},matchRoute:{value(t,r,n){if(this.initializeRouteCompiler(),n&&this.domains[n]){let s=this.fallbackMatchRoute(t,r,n);if(s)return s}else{let s=this.routeCompiler.match(t,r);if(s&&(!n||!s.route.domain||s.route.domain===n))return s;let i=this.fallbackMatchRoute(t,r,n);if(i)return i}if(r==="HEAD")return this.matchRoute(t,"GET",n);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(t,r,n){let s=new URL(t,"http://localhost"),i=`${n||""}:${r}:${s.pathname}`;if(this.routeCache.has(i))return this.routeCache.get(i);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has(r)){let c=this.staticRoutes.get(r).get(s.pathname);if(c&&(!n||!c.domain||c.domain===n)){let l={route:c,params:{}};return this.routeCache.set(i,l),l}}let a=(n&&this.domains[n]?this.domains[n]:this.routes).filter((c)=>c.method===r);for(let c of a)if(c.path===s.pathname){let l={route:c,params:{}};return this.routeCache.set(i,l),l}for(let c of a)if(c.pattern){let l=c.pattern.exec(s);if(l){let d={route:c,params:l.pathname.groups};return this.routeCache.set(i,d),d}}let u=n&&this.domains[n]?[this.domains[n],this.routes]:[this.routes];for(let c of u)for(let l of c){if(l.method!==r||!l.path.endsWith("*"))continue;let d=l.path.slice(0,-1);if(s.pathname.startsWith(d)){let p={route:l,params:{wildcard:s.pathname.slice(d.length)}};return this.routeCache.set(i,p),p}}this.routeCache.set(i,void 0);return},writable:!0,configurable:!0},getRouteStats:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getStats()},writable:!0,configurable:!0},getCacheStats:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getCacheStats()},writable:!0,configurable:!0},warmRouteCache:{value(t){this.initializeRouteCompiler(),this.routeCompiler.warmCache(t)},writable:!0,configurable:!0},getRoutesByMethod:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getRoutesByMethod()},writable:!0,configurable:!0},getRouteConflicts:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getRouteConflicts()},writable:!0,configurable:!0},clearRouteCache:{value(){if(this.routeCompiler)this.routeCompiler.clear();this.routeCache.clear()},writable:!0,configurable:!0},rebuildRouteCompiler:{value(){this.routeCompiler=new qe({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0});for(let t of this.routes)this.routeCompiler.addRoute(t);for(let t of Object.values(this.domains))for(let r of t)this.routeCompiler.addRoute(r)},writable:!0,configurable:!0},optimizeRoutes:{value(t={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(t)},writable:!0,configurable:!0}})}function hr(e){Object.defineProperties(e.prototype,{buildBunServeRoutes:{value(){let t={},r=new Map;for(let n of this.routes){if(!r.has(n.path))r.set(n.path,[]);r.get(n.path).push(n)}for(let[n,s]of r.entries())if(s.length===1){let i=s[0];if(typeof i.handler==="function"&&i.handler.toString().includes("new Response")&&!i.handler.toString().includes("await")&&i.middleware.length===0)try{let o=this.enhanceRequest(new Request("https://example.com"),{}),a=i.handler(o);if(a instanceof Response){t[n]=a;continue}}catch{}t[n]=async(o)=>{let a=new URL(o.url),u={},c=i.constraints&&!Array.isArray(i.constraints)?i.constraints:void 0;H(n,a.pathname,u,c);let l=this.enhanceRequest(o,u),d=async(h,m)=>await this.resolveHandler(i.handler,h),p=[...this.globalMiddleware,...i.middleware,d],g=await this.runMiddleware(l,p);return this.applyModifiedCookies(g??new Response("No response from middleware chain",{status:500}),l)}}else{let i={};for(let o of s){let a=o.method;i[a]=async(u)=>{let c=new URL(u.url),l={},d=o.constraints&&!Array.isArray(o.constraints)?o.constraints:void 0;H(n,c.pathname,l,d);let p=this.enhanceRequest(u,l),g=async(R,T)=>await this.resolveHandler(o.handler,R),h=[...this.globalMiddleware,...o.middleware,g],m=await this.runMiddleware(p,h);return this.applyModifiedCookies(m??new Response("No response from middleware chain",{status:500}),p)}}t[n]=i}return t},writable:!0,configurable:!0},loadRoutes:{async value(){if(!this.config.routesPath)return;try{if(this.config.apiRoutesPath)try{let t=await import(this.config.apiRoutesPath);if(t.default&&Array.isArray(t.default))for(let r of t.default)this.registerRoute(r,"api")}catch(t){if(this.config.verbose)console.warn(`Failed to load API routes: ${t}`)}if(this.config.webRoutesPath)try{let t=await import(this.config.webRoutesPath);if(t.default&&Array.isArray(t.default))for(let r of t.default)this.registerRoute(r,"web")}catch(t){if(this.config.verbose)console.warn(`Failed to load Web routes: ${t}`)}}catch(t){console.error("Error loading routes:",t)}},writable:!0,configurable:!0},registerRoute:{value(t,r){let{path:n,method:s,handler:i,middleware:o=[],name:a}=t;switch(s){case"GET":this.get(n,i,r,a,o);break;case"POST":this.post(n,i,r,a,o);break;case"PUT":this.put(n,i,r,a,o);break;case"DELETE":this.delete(n,i,r,a,o);break;case"PATCH":this.patch(n,i,r,a,o);break;case"OPTIONS":this.options(n,i,r,a,o);break;default:console.warn(`Unsupported HTTP method: ${s}`)}},writable:!0,configurable:!0}})}function gr(e){Object.defineProperties(e.prototype,{matchRoute:{value(t,r,n){let s=new URL(t,"http://localhost"),i=`${n||""}:${r}:${s.pathname}`;if(this.routeCache.has(i))return this.routeCache.get(i);if(this.staticRoutes.has(r)){let c=this.staticRoutes.get(r).get(s.pathname);if(c&&(!n||!c.domain||c.domain===n)){let l={route:c,params:{}};return this.routeCache.set(i,l),l}}let o=n&&this.domains[n]?this.domains[n]:this.routes,a=o.filter((c)=>c.method===r);for(let c of a)if(c.path===s.pathname){let l={route:c,params:{}};return this.routeCache.set(i,l),l}for(let c of a)if(c.pattern){let l=c.pattern.exec(s);if(l){let d={route:c,params:l.pathname.groups};return this.routeCache.set(i,d),d}}if(n&&this.domains[n]){let c=this.domains[n].filter((l)=>l.method===r&&l.path.endsWith("*"));for(let l of c){let d=l.path.slice(0,-1);if(s.pathname.startsWith(d)){let p={route:l,params:{wildcard:s.pathname.slice(d.length)}};return this.routeCache.set(i,p),p}}}let u=this.routes.filter((c)=>c.method===r&&c.path.endsWith("*")&&(!n||!c.domain));for(let c of u){let l=c.path.slice(0,-1);if(s.pathname.startsWith(l)){let d={route:c,params:{wildcard:s.pathname.slice(l.length)}};return this.routeCache.set(i,d),d}}if(r==="HEAD")return this.matchRoute(t,"GET",n);if(r==="OPTIONS"){let c=o.find((l)=>l.method==="OPTIONS"&&l.path==="*");if(c){let l={route:c,params:{}};return this.routeCache.set(i,l),l}for(let l of["GET","POST","PUT","PATCH","DELETE"]){let d=this.matchRoute(t,l,n);if(d){let p={route:{...d.route,method:"OPTIONS",handler:(g)=>new Response(null,{status:204})},params:d.params};return this.routeCache.set(i,p),p}}}return},writable:!0,configurable:!0},matchDomain:{value(t,r){if(t===r)return!0;if(t.startsWith("*.")){let n=t.substring(2);return r===n||r.endsWith(`.${n}`)}if(t.includes("{")){let n;if(!this.domainPatternCache.has(t)){let s=t.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");n=new RegExp(`^${s}$`),this.domainPatternCache.set(t,n)}else n=this.domainPatternCache.get(t);return n.test(r)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(t,r){let n={};if(!t.includes("{"))return n;let s=t.match(/\{([^}]+)\}/g)?.map((a)=>a.substring(1,a.length-1))||[],i=t.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),o=r.match(new RegExp(`^${i}$`));if(o&&o.length>1)for(let a=0;a<s.length;a++)n[s[a]]=o[a+1];return n},writable:!0,configurable:!0},pattern:{value(t,r){return this.patterns.set(t,r),this},writable:!0,configurable:!0},where:{value(t){let r=this.routes[this.routes.length-1];if(r){r.constraints={...r.constraints||{},...t};let n=r.path,s=r.constraints&&!Array.isArray(r.constraints)?r.constraints:void 0;if(r.pattern={exec:(i)=>{let o={};if(!H(n,i.pathname,o,s))return null;return{pathname:{groups:o}}}},this.routeCache.clear(),this.routeCompiler){let i=[...this.routes];this.routeCompiler.clear();for(let o of i)this.routeCompiler.addRoute(o)}}return this},writable:!0,configurable:!0},withoutNativeDispatch:{value(){let t=this.routes[this.routes.length-1];if(t)t.nativeDispatch=!1;return this},writable:!0,configurable:!0},whereNumber:{value(t){return this.where({[t]:"\\d+"})},writable:!0,configurable:!0},whereAlpha:{value(t){return this.where({[t]:"[A-Za-z]+"})},writable:!0,configurable:!0},whereAlphaNumeric:{value(t){return this.where({[t]:"[A-Za-z0-9]+"})},writable:!0,configurable:!0},whereUuid:{value(t){return this.where({[t]:"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"})},writable:!0,configurable:!0},whereIn:{value(t,r){return this.where({[t]:r.join("|")})},writable:!0,configurable:!0}})}class w{routes=[];currentGroup=null;globalMiddleware=[];namedRoutes=new Map;fallbackHandler=null;patterns=new Map;currentDomain=null;domains={};serverInstance=null;wsConfig=null;errorHandler=null;templateCache=new Map;routeCache=new Map;staticRoutes=new Map;staticResponses=new Map;precompiledPatterns=new Map;domainPatternCache=new Map;routeCompiler=null;middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];_middlewarePipeline;_mwEpoch=0;_allowedMethodsCache=new Map;config={verbose:!1,routesPath:"routes",apiRoutesPath:"routes/api.ts",webRoutesPath:"routes/web.ts",apiPrefix:"/api",webPrefix:"",actionsPath:"actions",controllersPath:"controllers",defaultMiddleware:{api:[],web:[]}};constructor(e={}){this.routes=[],this.config={...this.config,...e},this.initializeDefaultMiddleware()}initializeDefaultMiddleware(){this.namedMiddleware.set("auth",()=>async(e,t)=>{if(!e.headers.get("authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return await t()}),this.namedMiddleware.set("throttle",(e)=>{let t=e?Z(e):{maxAttempts:60,windowMs:60000};return Q({maxAttempts:t.maxAttempts||60,windowMs:t.windowMs,keyGenerator:(r)=>r.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(e,t)=>{let r=await t();if(r)r.headers.set("Access-Control-Allow-Origin","*"),r.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),r.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return r})}middlewareGroup(e,t){let r=[];for(let n of t){let[s,i]=n.split(":"),o=this.namedMiddleware.get(s);if(o)r.push(o(i))}return this.middlewareGroups.set(e,r),this}middlewareGroupRoutes(e){let t=this.middlewareGroups.get(e)||[];return new yr(this,t)}when(e){return new mr(this,e)}middleware(e){let[t,r]=e.split(":"),n=this.namedMiddleware.get(t);if(!n)throw Error(`Unknown middleware: ${t}`);let s=n(r);return new fr(this,[s])}getServer(){return this.serverInstance}extend(e){for(let[t,r]of Object.entries(e))if(typeof r==="function")this[t]=r.bind(this);return this}async register(e,t){let r=async()=>{await import(e)};if(t?.prefix||t?.middleware&&t.middleware.length>0)await this.group({prefix:t.prefix,middleware:t.middleware},r);else await r();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(e,t,r,n,s,i){let o=t,a=[],u=n||"web";if(this.currentGroup){if(this.currentGroup.prefix)o=F(this.currentGroup.prefix,t);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)a=[...this.currentGroup.middleware]}if(i&&i.length>0)for(let g of i){let h=this.resolveMiddleware(g);if(h)a.push(h)}if(u==="api"&&this.config.apiPrefix)o=F(this.config.apiPrefix,o);else if(u==="web"&&this.config.webPrefix)o=F(this.config.webPrefix,o);let c;if(this.currentDomain)c=this.currentDomain;let l={method:e.toUpperCase(),path:o,handler:r,domain:c,params:{},middleware:a},d=Ae(o),p={};if(d.forEach((g)=>{let h=g.replace("?","");if(this.patterns.has(h))p[h]=this.patterns.get(h)}),Object.keys(p).length>0)l.constraints=p;if(l.pattern={exec:(g)=>{let h={},m=l.constraints&&!Array.isArray(l.constraints)?l.constraints:void 0;if(!H(o,g.pathname,h,m))return null;return{pathname:{groups:h}}}},c){if(!this.domains[c])this.domains[c]=[];this.domains[c].push(l)}else this.routes.push(l);if(!o.includes("{")&&!o.includes("*")){if(!this.staticRoutes.has(e.toUpperCase()))this.staticRoutes.set(e.toUpperCase(),new Map);this.staticRoutes.get(e.toUpperCase()).set(o,l)}if(s)l.name=s,this.namedRoutes.set(s,l),N(s,l.path);return this.routeCache.clear(),this}resolveMiddleware(e){if(typeof e==="function")return e;let[t,r]=e.split(":"),n=this.namedMiddleware.get(t);if(n)return n(r);return null}get(e,t,r,n,s){return this.registerRoute("GET",e,t,r,n,s)}post(e,t,r,n,s){return this.registerRoute("POST",e,t,r,n,s)}put(e,t,r,n,s){return this.registerRoute("PUT",e,t,r,n,s)}patch(e,t,r,n,s){return this.registerRoute("PATCH",e,t,r,n,s)}delete(e,t,r,n,s){return this.registerRoute("DELETE",e,t,r,n,s)}options(e,t,r,n,s){return this.registerRoute("OPTIONS",e,t,r,n,s)}match(e,t,r,n,s,i){for(let o of e)this.registerRoute(o,t,r,n,s,i);return this}any(e,t,r,n,s){let i=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(i,e,t,r,n,s)}fallback(e){return this.fallbackHandler=e,this}route(e,t={}){let r=this.namedRoutes.get(e);if(!r)throw Error(`Route with name "${e}" not found`);let n=r.path;for(let[s,i]of Object.entries(t))n=n.replace(`{${s}}`,encodeURIComponent(i)),n=n.replace(`{${s}?}`,encodeURIComponent(i));return n}onError(e){return this.errorHandler=e,this}redirect(e,t=302){let r=new Headers;return r.set("Location",e),new Response(null,{status:t,headers:r})}permanentRedirect(e){return this.redirect(e,301)}redirectRoute(e,t,r=302){return this.get(e,(n)=>this.redirect(t,r)),this}async serve(e){this.invalidateCache();let t={...e,fetch:this.handleRequest.bind(this),websocket:this.wsConfig};if(this.serverInstance=Bun.serve(t),this.config.verbose){let r=this.serverInstance.port,n=this.serverInstance.hostname;console.log(`
|
|
98
|
+
\uD83D\uDE80 Server running at http://${n}:${r}
|
|
99
|
+
`)}return this.serverInstance}async handleRequest(e){try{let t=new URL(e.url);if(this.config.verbose)console.log(`${e.method} ${t.pathname}`);if(e.method==="OPTIONS"){let o=t.hostname||e.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(t.pathname,"OPTIONS",o))return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}})}let r=t.hostname||e.headers.get("host")?.split(":")[0]||"localhost",n=this.matchRoute(t.pathname,e.method,r),s=this.enhanceRequest(e,n?.params||{});if(n){s.route=n.route;let o=[...this.globalMiddleware];if(n.route.middleware&&n.route.middleware.length>0)o.push(...n.route.middleware);let a=async(c,l)=>await this.resolveHandler(n.route.handler,c);o.push(a);let u=await this.runMiddleware(s,o);if(u)return this.applyModifiedCookies(u,s);return new Response("No response from middleware chain",{status:500})}let i=this.getAllowedMethods(t.pathname,r);if(i.length>0){let o=async(a,u)=>new Response(JSON.stringify({error:"Method Not Allowed",path:t.pathname,method:e.method,allowed:i}),{status:405,headers:{"Content-Type":"application/json",Allow:i.join(", ")}});if(this.globalMiddleware.length>0){let a=[...this.globalMiddleware,o],u=await this.runMiddleware(s,a);if(u)return this.applyModifiedCookies(u,s)}return o(s,async()=>new Response(null))}if(this.globalMiddleware.length>0){let o=async(c,l)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,s);return new Response(JSON.stringify({error:"Not Found",path:t.pathname,method:e.method}),{status:404,headers:{"Content-Type":"application/json"}})},a=[...this.globalMiddleware,o],u=await this.runMiddleware(s,a);if(u)return this.applyModifiedCookies(u,s)}if(this.fallbackHandler){let o=await this.resolveHandler(this.fallbackHandler,s);return this.applyModifiedCookies(o,s)}return new Response(JSON.stringify({error:"Not Found",path:t.pathname,method:e.method}),{status:404,headers:{"Content-Type":"application/json"}})}catch(t){if(console.error("Error handling request:",t),this.globalMiddleware.length>0){let r=this.enhanceRequest(e,{}),n=async(i,o)=>{if(this.errorHandler)return this.errorHandler(t);return new Response(JSON.stringify({error:"Internal Server Error",message:t instanceof Error?t.message:String(t)}),{status:500,headers:{"Content-Type":"application/json"}})},s=[...this.globalMiddleware,n];try{let i=await this.runMiddleware(r,s);if(i)return i}catch{}}if(this.errorHandler)return this.errorHandler(t);return new Response(JSON.stringify({error:"Internal Server Error",message:t instanceof Error?t.message:String(t)}),{status:500,headers:{"Content-Type":"application/json"}})}}getAllowedMethods(e,t){let r=new URL(e,"http://localhost"),n=`${t||""}:${r.pathname}`,s=this._allowedMethodsCache.get(n);if(s)return s;let i=new Set;for(let[u,c]of this.staticRoutes){let l=c.get(r.pathname);if(l&&(!t||!l.domain||l.domain===t))i.add(u)}let o=t&&this.domains[t]?this.domains[t]:this.routes;for(let u of o){if(i.has(u.method))continue;if(u.path===r.pathname){i.add(u.method);continue}if(u.pattern&&u.pattern.exec(r)){i.add(u.method);continue}if(u.path.endsWith("*")&&r.pathname.startsWith(u.path.slice(0,-1)))i.add(u.method)}if(i.has("GET"))i.add("HEAD");let a=Array.from(i);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(n,a),a}matchRoute(e,t,r){let n=new URL(e,"http://localhost"),s=`${r||""}:${t}:${n.pathname}`;if(this.routeCache.has(s))return this.routeCache.get(s);if(this.staticRoutes.has(t)){let u=this.staticRoutes.get(t).get(n.pathname);if(u&&(!r||!u.domain||u.domain===r)){let c={route:u,params:{}};return this.routeCache.set(s,c),c}}let o=(r&&this.domains[r]?this.domains[r]:this.routes).filter((u)=>u.method===t);for(let u of o)if(u.path===n.pathname){let c={route:u,params:{}};return this.routeCache.set(s,c),c}for(let u of o)if(u.pattern){let c=u.pattern.exec(n);if(c){let l={route:u,params:c.pathname.groups};return this.routeCache.set(s,l),l}}if(r&&this.domains[r]){let u=this.domains[r].filter((c)=>c.method===t&&c.path.endsWith("*"));for(let c of u){let l=c.path.slice(0,-1);if(n.pathname.startsWith(l)){let d={route:c,params:{wildcard:n.pathname.slice(l.length)}};return this.routeCache.set(s,d),d}}}let a=this.routes.filter((u)=>u.method===t&&u.path.endsWith("*")&&(!r||!u.domain));for(let u of a){let c=u.path.slice(0,-1);if(n.pathname.startsWith(c)){let l={route:u,params:{wildcard:n.pathname.slice(c.length)}};return this.routeCache.set(s,l),l}}if(t==="HEAD")return this.matchRoute(e,"GET",r);return}enhanceRequest(e,t={}){let r=null,n=()=>{if(r===null)r={},(e.headers.get("cookie")||"").split(";").forEach((c)=>{let l=c.trim().split("=");if(l.length>=2){let d=l[0].trim(),p=l.slice(1).join("=").trim();r[d]=decodeURIComponent(p)}});return r},s=new URL(e.url),i={};s.searchParams.forEach((u,c)=>{i[c]=u});let o={get url(){return e.url},get method(){return e.method},get headers(){return e.headers},get body(){return e.body},get bodyUsed(){return e.bodyUsed},get cache(){return e.cache},get credentials(){return e.credentials},get destination(){return e.destination},get integrity(){return e.integrity},get keepalive(){return e.keepalive},get mode(){return e.mode},get redirect(){return e.redirect},get referrer(){return e.referrer},get referrerPolicy(){return e.referrerPolicy},get signal(){return e.signal},arrayBuffer:()=>e.arrayBuffer(),blob:()=>e.blob(),clone:()=>e.clone(),formData:()=>e.formData(),json:()=>e.json(),text:()=>e.text(),params:t,query:i,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},a=()=>{let u={};for(let[c,l]of Object.entries(i))u[c]=l;if(o.jsonBody&&typeof o.jsonBody==="object")for(let[c,l]of Object.entries(o.jsonBody))u[c]=l;if(o.formBody&&typeof o.formBody==="object")for(let[c,l]of Object.entries(o.formBody))u[c]=l;for(let[c,l]of Object.entries(t))u[c]=l;return u};return o.cookies={get:(u)=>n()[u],set:(u,c,l={})=>{o._cookiesToSet.push({name:u,value:c,options:l})},delete:(u,c={})=>{o._cookiesToDelete.push({name:u,options:c})},getAll:()=>({...n()})},o.get=(u,c)=>{let d=a()[u];return d!==void 0?d:c},o.input=(u,c)=>{let d=a()[u];return d!==void 0?d:c},o.all=()=>a(),o.only=(u)=>{let c=a(),l={};for(let d of u)if(d in c)l[d]=c[d];return l},o.except=(u)=>{let l={...a()};for(let d of u)delete l[d];return l},o.has=(u)=>{let c=a();if(Array.isArray(u))return u.every((l)=>(l in c)&&c[l]!==void 0);return u in c&&c[u]!==void 0},o.hasAny=(u)=>{let c=a();return u.some((l)=>(l in c)&&c[l]!==void 0)},o.filled=(u)=>{let c=a(),l=(d)=>{let p=c[d];return p!==void 0&&p!==null&&p!==""&&!(Array.isArray(p)&&p.length===0)};if(Array.isArray(u))return u.every(l);return l(u)},o.missing=(u)=>{let c=a();if(Array.isArray(u))return u.every((l)=>!(l in c)||c[l]===void 0);return!(u in c)||c[u]===void 0},o.string=(u,c="")=>{let d=a()[u];return d!==void 0&&d!==null?String(d):c},o.integer=(u,c=0)=>{let d=a()[u],p=Number.parseInt(String(d),10);return Number.isNaN(p)?c:p},o.float=(u,c=0)=>{let d=a()[u],p=Number.parseFloat(String(d));return Number.isNaN(p)?c:p},o.boolean=(u,c=!1)=>{let d=a()[u];if(d===void 0||d===null)return c;if(typeof d==="boolean")return d;if(d==="true"||d==="1"||d===1)return!0;if(d==="false"||d==="0"||d===0)return!1;return c},o.array=(u)=>{let l=a()[u];if(Array.isArray(l))return l;return l!==void 0&&l!==null?[l]:[]},o.bearerToken=()=>{let u=e.headers.get("authorization")||e.headers.get("Authorization")||"";if(u.startsWith("Bearer "))return u.substring(7);return null},o.header=(u)=>e.headers.get(u)||e.headers.get(u.toLowerCase())||null,o.cookie=(u,c)=>{let l=n()[u];return l!==void 0?l:c??null},o.getParam=(u,c)=>{let l=t?.[u];return l!==void 0?l:c},o.getParamAsInt=(u)=>{let c=t?.[u];if(c===void 0||c.trim()==="")return null;let l=Number(c);return Number.isSafeInteger(l)?l:null},o.params=t||{},o}applyModifiedCookies(e,t){let r=new Response(e.body,{status:e.status,statusText:e.statusText,headers:e.headers});if(t._cookiesToSet&&t._cookiesToSet.length>0)for(let{name:n,value:s,options:i}of t._cookiesToSet){let o=this.serializeCookie(n,s,i);r.headers.append("Set-Cookie",o)}if(t._cookiesToDelete&&t._cookiesToDelete.length>0)for(let{name:n,options:s}of t._cookiesToDelete){let i={...s,expires:new Date(0),maxAge:0},o=this.serializeCookie(n,"",i);r.headers.append("Set-Cookie",o)}return r}serializeCookie(e,t,r={}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(r.maxAge!==void 0)n+=`; Max-Age=${r.maxAge}`;if(r.expires&&r.expires instanceof Date)n+=`; Expires=${r.expires.toUTCString()}`;if(r.path)n+=`; Path=${r.path}`;else n+="; Path=/";if(r.domain)n+=`; Domain=${r.domain}`;if(r.secure)n+="; Secure";if(r.httpOnly)n+="; HttpOnly";if(r.sameSite){let s=r.sameSite.toLowerCase();n+=`; SameSite=${s.charAt(0).toUpperCase()+s.slice(1)}`}return n}buildMiddlewareChain(e){if(e.length===0)return async(r)=>null;let t=async(r)=>null;for(let r=e.length-1;r>=0;r--){let n=e[r],s=t;t=async(i)=>n(i,async()=>await s(i)||new Response(null,{status:200}))}return t}async runMiddleware(e,t){if(t.length===0)return null;try{return await this.buildMiddlewareChain(t)(e)}catch(r){if(this.errorHandler)return this.errorHandler(r);throw r}}async resolveHandler(e,t){if(typeof e==="function"&&!e.prototype?.handle)return await e(t);if(typeof e==="function"&&e.prototype?.handle)return await new e().handle(t);if(e&&typeof e.handle==="function")return await e.handle(t);throw Error(`Invalid action handler: ${typeof e}`)}use(...e){for(let t of e){let r=this.resolveMiddleware(t);if(r)this.globalMiddleware.push(r)}return this}group(e,t){let r=this.currentGroup;if(this.currentGroup={prefix:e.prefix||"",middleware:[]},e.middleware){for(let s of e.middleware)if(typeof s==="function")this.currentGroup.middleware.push(s)}let n=t();if(n instanceof Promise)return n.then(()=>(this.currentGroup=r,this),(s)=>{throw this.currentGroup=r,s});return this.currentGroup=r,this}addRoute(e){if(this.routes.push(e),e.name)this.namedRoutes.set(e.name,e),N(e.name,e.path);return this}registerMiddlewareDependency(e){if(this._middlewarePipeline)this._middlewarePipeline.registerDependency(e);return this}registerMiddlewareSkipConditions(e,t){return this}getMiddlewareStats(){if(this._middlewarePipeline)return this._middlewarePipeline.getStats();return{}}getMiddlewareCacheInfo(){return{size:0,routes:[],hitRate:0}}clearMiddlewareCache(){if(this._middlewarePipeline)this._middlewarePipeline.clear();return this}async executeMiddleware(e,t,r){if(e.length===0)return r();let n=0,s=async()=>{if(n>=e.length)return r();let i=e[n++];return await i(t,s)||new Response("No response from middleware",{status:500})};return s()}}class mr{router;condition;constructor(e,t){this.router=e;this.condition=t}middleware(e){let[t,r]=e.split(":"),n=this.router.namedMiddleware.get(t);if(!n)throw Error(`Unknown middleware: ${t}`);let s=n(r);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[s]}),this}}class fr{router;middleware;constructor(e,t){this.router=e;this.middleware=t}get(e,t){return this}post(e,t){return this}put(e,t){return this}delete(e,t){return this}}class yr{router;middleware;constructor(e,t){this.router=e;this.middleware=t}get(e,t){return this}post(e,t){return this}put(e,t){return this}delete(e,t){return this}}var rt=null;function Cs(){if(rt===null)rt=new w;return rt}function Ps(e,t={}){if(typeof e.bearerToken==="function")return e;return Cs().enhanceRequest(e,t)}var Es=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,Ms=/bot|crawler|spider|crawling/i,Oe=new Map;function pe(e){let t=e;if(!t._parsedURL)t._parsedURL=new URL(e.url);return t._parsedURL}function L(e){let t=e;if(!t._parsedCookies){let r={},n=e.headers.get("cookie");if(n)for(let s of n.split(";")){let i=s.indexOf("=");if(i===-1)continue;let o=s.slice(0,i).trim();if(!o)continue;let a=s.slice(i+1).trim();try{r[o]=decodeURIComponent(a)}catch{r[o]=a}}t._parsedCookies=r}return t._parsedCookies}class br{macros=new Map;epoch=0;register(e,t,r=!1){this.macros.set(e,{name:e,handler:t,accessor:r}),this.epoch++}get(e){return this.macros.get(e)}has(e){return this.macros.has(e)}all(){return Array.from(this.macros.values())}remove(e){let t=this.macros.delete(e);if(t)this.epoch++;return t}clear(){this.macros.clear(),this.epoch++}getEpoch(){return this.epoch}}var le=new br,Rr=Symbol("bunRouterMacroProto"),nt=Symbol("bunRouterMacroBase"),$e=new WeakMap,wr=-1;class x{static macro(e,t){le.register(e,t)}static macroAccessor(e,t){le.register(e,t,!0)}static applyMacros(e){let t=le.getEpoch();if(t!==wr)$e=new WeakMap,wr=t;let r=Object.getPrototypeOf(e)??Object.prototype;if(r[Rr]){if($e.get(r[nt])===r)return e;r=r[nt]}let n=$e.get(r);if(!n){n=Object.create(r);for(let s of le.all())if(s.accessor)Object.defineProperty(n,s.name,{get:s.handler,set(i){Object.defineProperty(this,s.name,{value:i,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else n[s.name]=s.handler;Object.defineProperty(n,Rr,{value:!0}),Object.defineProperty(n,nt,{value:r}),$e.set(r,n)}return Object.setPrototypeOf(e,n),e}static hasMacro(e){return le.has(e)}}var de={wantsJson(){let e=this.headers.get("accept")||"";return e.includes("application/json")||e.includes("json")},wantsHtml(){let e=this.headers.get("accept")||"";return e.includes("text/html")||e.includes("html")},wantsXml(){let e=this.headers.get("accept")||"";return e.includes("application/xml")||e.includes("xml")},expectsJson(){return this.wantsJson()||this.isAjax()||this.isPjax()},isAjax(){return this.headers.get("x-requested-with")==="XMLHttpRequest"},isPjax(){return this.headers.get("x-pjax")==="true"},isMobile(){return Es.test(this.headers.get("user-agent")||"")},isBot(){return Ms.test(this.headers.get("user-agent")||"")},isSecure(){return this.url.startsWith("https://")||this.headers.get("x-forwarded-proto")==="https"||this.headers.get("x-forwarded-ssl")==="on"},ip(){return this.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||this.headers.get("x-real-ip")||this.headers.get("cf-connecting-ip")||this.headers.get("x-client-ip")||"unknown"},ips(){let e=this.headers.get("x-forwarded-for");if(e)return e.split(",").map((t)=>t.trim());return[de.ip.call(this)]},userAgent(){return this.headers.get("user-agent")||""},referer(){return this.headers.get("referer")||this.headers.get("referrer")||null},bearerToken(){let e=this.headers.get("authorization");if(e&&e.startsWith("Bearer "))return e.substring(7);return null},async rawBody(){if(typeof this._rawBody==="string")return this._rawBody;try{let e=await this.clone().text();return this._rawBody=e,e}catch{return""}},basicAuth(){let e=this.headers.get("authorization");if(e&&e.startsWith("Basic "))try{let t=atob(e.substring(6)),[r,n]=t.split(":");return{username:r,password:n}}catch{return null}return null},hasHeader(e){return this.headers.has(e.toLowerCase())},header(e,t){return this.headers.get(e.toLowerCase())||t||null},allHeaders(){let e={};return this.headers.forEach((t,r)=>{e[r]=t}),e},input(e,t){if(this.validated&&e in this.validated)return this.validated[e];if(this.query&&e in this.query)return this.query[e];if(this.params&&e in this.params)return this.params[e];if(this.jsonBody&&typeof this.jsonBody==="object"&&e in this.jsonBody)return this.jsonBody[e];if(this.formBody&&typeof this.formBody==="object"&&e in this.formBody)return this.formBody[e];return t},all(){return{...this.params,...this.query,...typeof this.jsonBody==="object"&&this.jsonBody!==null?this.jsonBody:{},...typeof this.formBody==="object"&&this.formBody!==null?this.formBody:{},...typeof this.validated==="object"&&this.validated!==null?this.validated:{}}},only(e){let t=this.all(),r={};return e.forEach((n)=>{if(n in t)r[n]=t[n]}),r},except(e){let t=this.all(),r={};return Object.keys(t).forEach((n)=>{if(!e.includes(n))r[n]=t[n]}),r},has(e){let t=this.all();return e in t&&t[e]!==void 0&&t[e]!==null&&t[e]!==""},hasAny(e){return e.some((t)=>this.has(t))},missing(e){return!this.has(e)},filled(e){let t=this.input(e);if(t===null||t===void 0)return!1;if(typeof t==="string")return t.trim().length>0;if(Array.isArray(t))return t.length>0;if(typeof t==="object")return Object.keys(t).length>0;return!0},getQuery(e,t){if(!e)return this.query||{};return this.query?.[e]||t},param(e,t){return this.params?.[e]||t},cookie(e,t){let r=L(this)[e];return r!==void 0?r:t||null},cookies(){return{...L(this)}},file(e){return this.files?.find((t)=>t.fieldName===e)},hasFile(e){return!!this.files?.find((t)=>t.fieldName===e)},path(){return pe(this).pathname},fullUrl(){return this.url},root(){let e=pe(this);return`${e.protocol}//${e.host}`},is(e){let t=this.path(),r=Oe.get(e);if(!r){let n=e.replace(/\*/g,".*").replace(/\?/g,".");if(r=new RegExp(`^${n}$`),Oe.size>=1000)Oe.clear();Oe.set(e,r)}return r.test(t)},route(){return this.routeName||null},fingerprint(){let e=pe(this),t={method:this.method,path:e.pathname,query:e.search,ip:de.ip.call(this)};return btoa(JSON.stringify(t))},signature(e){let t=`${this.method}${this.url}${de.ip.call(this)}${e}`,r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return Math.abs(r).toString(36)},merge(e){if(!this.validated)this.validated={};Object.assign(this.validated,e)},replace(e){this.validated={...e}},age(){let e=this.startTime||Date.now();return Date.now()-e},isFromTrustedProxy(e=[]){let t=de.ip.call(this);return e.includes(t)},contentLength(){let e=this.headers.get("content-length");return e?Number.parseInt(e,10):0},contentType(){return this.headers.get("content-type")},isContentType(e){let t=this.contentType();return t?t.includes(e):!1}};function Ss(){Object.entries(de).forEach(([e,t])=>{x.macro(e,t)})}Ss();if(!x.hasMacro("getParam"))x.macro("getParam",function(e,t){let r=this.params?.[e];return r!==void 0?r:t});if(!x.hasMacro("getParamAsInt"))x.macro("getParamAsInt",function(e){let t=this.params?.[e];if(t===void 0||t.trim()==="")return null;let r=Number(t);return Number.isSafeInteger(r)?r:null});if(!x.hasMacro("get"))x.macro("get",function(e,t){let r=pe(this).searchParams.get(e);return r!==null&&r!==void 0?r:t});x.macroAccessor("cookies",function(){let e=this,t=()=>({...L(e)});for(let[r,n]of Object.entries(L(e)))Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0});return t.get=(r)=>L(e)[r],t.set=(r,n,s={})=>{if(!e._cookiesToSet)e._cookiesToSet=[];e._cookiesToSet.push({name:r,value:n,options:s})},t.delete=(r,n={})=>{if(!e._cookiesToDelete)e._cookiesToDelete=[];e._cookiesToDelete.push({name:r,options:n})},t.getAll=()=>({...L(e)}),Object.defineProperty(e,"cookies",{value:t,writable:!0,configurable:!0,enumerable:!0}),t});function Tr(e){Object.defineProperties(e.prototype,{serve:{async value(t={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let r={idleTimeout:255,...t,fetch:this.handleRequest.bind(this)},n={};if(this.staticResponses&&this.staticResponses.size>0)for(let[s,i]of this.staticResponses)n[s]=i;if(t.static)Object.assign(n,t.static);if(Object.keys(n).length>0)r.static=n;if(t.development!==void 0)r.development=t.development;if(this._nativeRoutesEnabled=t.nativeRoutes===!0,this._nativeRoutesEnabled){let s=this._buildNativeRoutes();if(s)r.routes=s}if(this.wsConfig)r.websocket=this.wsConfig;if(this.serverInstance=Bun.serve(r),this.config.verbose){let s=this.serverInstance.port,i=this.serverInstance.hostname;console.log(`
|
|
100
|
+
\uD83D\uDE80 Server running at http://${i}:${s}
|
|
101
|
+
`)}return this.serverInstance},writable:!0,configurable:!0},reload:{async value(){if(!this.serverInstance)throw Error("Server not started, cannot reload");this.invalidateCache();let t=this.serverInstance.port,r=this.serverInstance.hostname;this.serverInstance.stop();let n={port:t,hostname:r,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0};if(this._nativeRoutesEnabled){let s=this._buildNativeRoutes();if(s)n.routes=s}if(this.serverInstance=Bun.serve(n),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${r}:${t}`)},writable:!0,configurable:!0},handleRequest:{async value(t){let r=this,n=await ve(t,()=>r.handleRequestImpl(t));return await Ct(n,t,r.config?.compression??{})},writable:!0,configurable:!0},_dispatchMatchedRoute:{async value(t,r,n){let s=this.enhanceRequest(r,n);Ce(s),s.route=t;let i=t,o=this._mwEpoch||0,a=i.middleware?i.middleware.length:0,u=i._compiledChain;if(!u||i._chainEpoch!==o||i._chainMwLen!==a){let l=ar(i.handler,this.config);if(a===0&&this.globalMiddleware.length===0)u=l;else{let d=a>0?[...this.globalMiddleware,...i.middleware]:[...this.globalMiddleware];d.push((p,g)=>l(p)),u=this.buildMiddlewareChain(d)}i._compiledChain=u,i._chainEpoch=o,i._chainMwLen=a}let c;try{c=await u(s)}catch(l){if(this.errorHandler)c=await this.errorHandler(l);else throw l}if(c)return this.applyModifiedCookies(c,s);return new Response("No response from middleware chain",{status:500})},writable:!0,configurable:!0},_buildNativeRoutes:{value(){let t=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),r=(a)=>{if(a==="*")return"/*";let u=a.split("/"),c=[];for(let l=0;l<u.length;l++){let d=u[l];if(d===""){c.push(d);continue}if(d==="*")return l===u.length-1?[...c,"*"].join("/"):null;let p=d.match(/^\{([A-Z_$][\w$]*)\}$/i);if(p){c.push(`:${p[1]}`);continue}if(d.includes("{")||d.includes(":")||d.includes("*"))return null;c.push(d)}return c.join("/")},n=this,s=(a,u)=>(c)=>ve(c,async()=>{try{let l=c.params??{};if(u){let d=new URL(c.url).pathname,p=a.path==="*"?"/":a.path.slice(0,-1);l={...l,wildcard:d.slice(p.length)}}return await n._dispatchMatchedRoute(a,c,l)}catch(l){if(console.error("Error handling request:",l),n.errorHandler)return n.errorHandler(l);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:l instanceof Error?l.message:String(l)}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"}})}}),i={},o=new Map;for(let a of this.routes){if(!t.has(a.method))continue;if(a.nativeDispatch===!1)continue;if(a.constraints&&Object.keys(a.constraints).length>0)continue;if(a.handler instanceof Response)continue;let u=r(a.path);if(!u)continue;let c=u.replace(/:[^/]+/g,":p"),l=o.get(c);if(l&&l!==u)continue;o.set(c,u);let d=i[u]??={};if(d[a.method])continue;d[a.method]=s(a,a.path.endsWith("*"))}for(let a of Object.values(i))if(a.GET&&!a.HEAD)a.HEAD=a.GET;return Object.keys(i).length>0?i:null},writable:!0,configurable:!0},handleRequestImpl:{async value(t){try{let r=new URL(t.url);t._parsedURL=r;let n=r.hostname||t.headers.get("host")?.split(":")[0]||"localhost",s=this.matchRoute(r.pathname,t.method,n);if(t.method==="OPTIONS"&&!s){let c=t.headers.get("origin"),l={"Access-Control-Allow-Origin":c||"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin","Access-Control-Max-Age":"86400"};if(c)l["Access-Control-Allow-Credentials"]="true",l.Vary="Origin";return new Response(null,{status:204,headers:l})}if(s)return await this._dispatchMatchedRoute(s.route,t,s.params);let i=this.enhanceRequest(t,{});Ce(i);let o=this.getAllowedMethods(r.pathname,n),a={"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"};if(o.length>0){let c=async(l,d)=>new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:r.pathname,method:t.method,allowed:o}),{status:405,headers:{...a,Allow:o.join(", ")}});if(this.globalMiddleware.length>0){let l=[...this.globalMiddleware,c],d=await this.runMiddleware(i,l);if(d)return this.applyModifiedCookies(d,i)}return await c(i,async()=>null)}if(this.fallbackHandler){let c=await this.resolveHandler(this.fallbackHandler,i);return this.applyModifiedCookies(c,i)}let u=async(c,l)=>new Response(JSON.stringify({success:!1,message:"Not Found",path:r.pathname,method:t.method}),{status:404,headers:a});if(this.globalMiddleware.length>0){let c=[...this.globalMiddleware,u],l=await this.runMiddleware(i,c);if(l)return this.applyModifiedCookies(l,i)}return await u(i,async()=>null)}catch(r){if(console.error("Error handling request:",r),this.errorHandler)return this.errorHandler(r);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:r instanceof Error?r.message:String(r)}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"}})}},writable:!0,configurable:!0},enhanceRequest:{value(t,r={}){let n=t;if("params"in t)Object.defineProperty(n,"params",{value:r,writable:!0,configurable:!0,enumerable:!0});else n.params=r;return x.applyMacros(n),n},writable:!0,configurable:!0},applyModifiedCookies:{value(t,r){let n=r._cookiesToSet&&r._cookiesToSet.length>0,s=r._cookiesToDelete&&r._cookiesToDelete.length>0;if(!n&&!s)return t;let i=new Response(t.body,{status:t.status,statusText:t.statusText,headers:t.headers});if(r._cookiesToSet&&r._cookiesToSet.length>0)for(let{name:o,value:a,options:u}of r._cookiesToSet){let c=this.serializeCookie(o,a,u);i.headers.append("Set-Cookie",c)}if(r._cookiesToDelete&&r._cookiesToDelete.length>0)for(let{name:o,options:a}of r._cookiesToDelete){let u={...a,expires:new Date(0),maxAge:0},c=this.serializeCookie(o,"",u);i.headers.append("Set-Cookie",c)}return i},writable:!0,configurable:!0},serializeCookie:{value(t,r,n={}){let s=`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(n.maxAge!==void 0)s+=`; Max-Age=${n.maxAge}`;if(n.expires&&n.expires instanceof Date)s+=`; Expires=${n.expires.toUTCString()}`;if(n.path)s+=`; Path=${n.path}`;else s+="; Path=/";if(n.domain)s+=`; Domain=${n.domain}`;if(n.secure)s+="; Secure";if(n.httpOnly)s+="; HttpOnly";if(n.sameSite){let i=n.sameSite.toLowerCase();s+=`; SameSite=${i.charAt(0).toUpperCase()+i.slice(1)}`}return s},writable:!0,configurable:!0}})}import{join as ks}from"path";function xr(e){Object.defineProperties(e.prototype,{renderView:{async value(t,r={},n={}){let s=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},i=`${t}:${n.layout||""}`;if(s.cache&&this.templateCache.has(i))return this.processTemplate(this.templateCache.get(i),r,s);let o=await Ye(t,s.viewsPath,s.extensions);if(!o)throw Error(`View '${t}' not found`);let a=await Bun.file(o).text(),u=n.layout||s.defaultLayout;if(u){let c=await Ye(ks("layouts",u),s.viewsPath,s.extensions);if(!c)throw Error(`Layout '${u}' not found`);a=(await Bun.file(c).text()).replace(/\{\{\s*content\s*\}\}/g,a)}if(s.cache)this.templateCache.set(i,a);return this.processTemplate(a,r,s)},writable:!0,configurable:!0},processTemplate:{async value(t,r,n){if((n?.engine||"auto")==="custom"&&n?.customRenderer)return n.customRenderer(t,r,{});let i=Yt(t,r);if(n?.minify?.enabled)try{let o=n.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};i=i.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(o){console.error("Error minifying HTML:",o)}return i},writable:!0,configurable:!0},view:{value(t,r,n={},s={},i="web",o){let a,u={},c={},l="web",d;if(typeof r==="string"){if(a=r,typeof n==="object"&&!Array.isArray(n))if("layout"in n||"status"in n||"headers"in n)c=n;else u=n;if(typeof s==="object")c={...c,...s};else if(typeof s==="string")l=s;if(typeof i==="string")if(i==="web"||i==="api")l=i;else d=i;if(o)d=o}else{if(u=r,typeof n==="string")a=n;else throw TypeError("View name must be a string");if(typeof s==="object")c=s;else if(typeof s==="string")if(s==="web"||s==="api")l=s;else a=s,l="web"}let p=async(g)=>{let h=await this.renderView(a,u,{layout:c.layout}),m=this.config?.queryPreservation;if(m?.enabled!==!1&&m?.preserve?.length)h=Pe(h,m);let R=new Headers;if(R.set("Content-Type","text/html; charset=utf-8"),c.headers)for(let[T,V]of Object.entries(c.headers))R.set(T,V);return new Response(h,{status:c.status||200,headers:R})};return this.get(t,p,l,d),this},writable:!0,configurable:!0}})}function vr(e){Object.defineProperties(e.prototype,{websocket:{value(t){return this.wsConfig=t,this},writable:!0,configurable:!0},publish:{value(t,r,n=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(t,r,n)},writable:!0,configurable:!0},subscriberCount:{value(t){if(!this.serverInstance)throw Error("Server not started, cannot get subscriber count");return this.serverInstance.subscriberCount(t)},writable:!0,configurable:!0},upgrade:{value(t,r){if(!this.serverInstance)throw Error("Server not started, cannot upgrade to WebSocket");if(!this.wsConfig)throw Error("WebSocket configuration not set, use router.websocket() to configure");return this.serverInstance.upgrade(t,r)},writable:!0,configurable:!0},timeout:{value(t,r){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(t,r)},writable:!0,configurable:!0},requestIP:{value(t){if(!this.serverInstance)throw Error("Server not started, cannot get request IP");return this.serverInstance.requestIP(t)},writable:!0,configurable:!0}})}import Hs from"process";class Cr{macros=new Map;register(e,t){this.macros.set(e,{name:e,handler:t})}get(e){return this.macros.get(e)}has(e){return this.macros.has(e)}all(){return Array.from(this.macros.values())}remove(e){return this.macros.delete(e)}clear(){this.macros.clear()}}var st=new Cr;class he extends Response{static macro(e,t){st.register(e,t),Response[e]=t}static callMacro(e,...t){let r=st.get(e);if(!r)throw Error(`Response macro "${e}" not found`);return r.handler(...t)}static hasMacro(e){return st.has(e)}}function Be(e,t){if(typeof e==="number")return{status:e,mergedHeaders:t};if(e&&typeof e==="object"){let r=typeof e.status==="number"?e.status:200,n=t;if(e.headers)if(n={},e.headers instanceof Headers)e.headers.forEach((s,i)=>{n[i]=s});else if(Array.isArray(e.headers))for(let[s,i]of e.headers)n[s]=i;else Object.assign(n,e.headers);return{status:r,mergedHeaders:n}}return{status:200,mergedHeaders:t}}var A={success:(e,t,r=200)=>{let n={};if(e!==void 0)n.data=e;if(t!==void 0)n.message=t;return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})},error:(e,t,r=400)=>{let n={error:e};if(t!==void 0)n.errors=t;return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})},validationError:(e,t="Validation failed")=>A.error(t,e,422),notFound:(e="Resource not found")=>A.error(e,void 0,404),unauthorized:(e="Unauthorized")=>A.error(e,void 0,401),forbidden:(e="Forbidden")=>A.error(e,void 0,403),serverError:(e="Internal server error")=>A.error(e,void 0,500),created:(e,t="Resource created successfully")=>A.success(e,t,201),updated:(e,t="Resource updated successfully")=>A.success(e,t,200),deleted:(e="Resource deleted successfully")=>A.success(null,e,200),noContent:()=>new Response(null,{status:204}),accepted:(e,t="Request accepted")=>A.success(e,t,202),paginated:(e,t,r)=>{let n=Math.ceil(t.total/t.per_page),s=(t.current_page-1)*t.per_page+1,i=Math.min(s+t.per_page-1,t.total),o={data:e,message:r,meta:{current_page:t.current_page,per_page:t.per_page,total:t.total,last_page:n,from:s,to:i,path:t.path,first_page_url:`${t.path}?page=1`,last_page_url:`${t.path}?page=${n}`,next_page_url:t.current_page<n?`${t.path}?page=${t.current_page+1}`:void 0,prev_page_url:t.current_page>1?`${t.path}?page=${t.current_page-1}`:void 0}};return new Response(JSON.stringify(o),{status:200,headers:{"Content-Type":"application/json"}})},json:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Be(t,r);return new Response(JSON.stringify(e),{status:n,headers:{"Content-Type":"application/json",...s}})},html:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Be(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/html",...s}})},text:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Be(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/plain",...s}})},xml:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Be(t,r);return new Response(e,{status:n,headers:{"Content-Type":"application/xml",...s}})},redirect:(e,t=302)=>new Response(null,{status:t,headers:{Location:e}}),permanentRedirect:(e)=>A.redirect(e,301),download:(e,t,r="application/octet-stream")=>new Response(e,{status:200,headers:{"Content-Type":r,"Content-Disposition":`attachment; filename="${t}"`}}),stream:(e,t="application/octet-stream",r={})=>new Response(e,{status:200,headers:{"Content-Type":t,...r}}),cache:(e,t=3600,r=!0,n)=>{let i={"Content-Type":"application/json","Cache-Control":r?`public, max-age=${t}`:`private, max-age=${t}`};if(n)i.ETag=n;return new Response(JSON.stringify(e),{status:200,headers:i})},cors:(e,t="*",r="GET,POST,PUT,DELETE,OPTIONS",n="Content-Type,Authorization")=>new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":t,"Access-Control-Allow-Methods":r,"Access-Control-Allow-Headers":n}}),sse:(e,t,r)=>{let n="";if(r)n+=`id: ${r}
|
|
102
|
+
`;if(t)n+=`event: ${t}
|
|
103
|
+
`;return n+=`data: ${e}
|
|
104
104
|
|
|
105
|
-
`,new Response(X,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(Y="healthy",Z={})=>{let $=Y==="healthy"?200:Y==="degraded"?200:503,X={status:Y,timestamp:new Date().toISOString(),checks:Z,uptime:C$.uptime?.()||0};return new Response(JSON.stringify(X),{status:$,headers:{"Content-Type":"application/json"}})}};function M$(){Object.entries(R).forEach(([Y,Z])=>{LY.macro(Y,Z)})}M$();var T$=/^[A-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?(?:\.[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?)*\.[A-Z]{2,}$/i,P$={required:{name:"required",validate:(Y)=>{if(Y===null||Y===void 0)return!1;if(typeof Y==="string")return Y.trim().length>0;if(Array.isArray(Y))return Y.length>0;if(typeof Y==="object")return Object.keys(Y).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(Y)=>typeof Y==="string",message:"The :field field must be a string."},number:{name:"number",validate:(Y)=>typeof Y==="number"&&!Number.isNaN(Y),message:"The :field field must be a number."},integer:{name:"integer",validate:(Y)=>Number.isInteger(Number(Y)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(Y)=>typeof Y==="boolean"||Y==="true"||Y==="false"||Y==="1"||Y==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(Y)=>typeof Y==="string"&&T$.test(Y),message:"The :field field must be a valid email address."},url:{name:"url",validate:(Y)=>{try{let Z=new URL(Y);return Boolean(Z)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(Y,Z)=>{let $=Number(Z[0]);if(typeof Y==="string")return Y.length>=$;if(typeof Y==="number")return Y>=$;if(Array.isArray(Y))return Y.length>=$;return!1},message:(Y,Z)=>`The ${Y} field must be at least ${Z[0]} characters.`},max:{name:"max",validate:(Y,Z)=>{let $=Number(Z[0]);if(typeof Y==="string")return Y.length<=$;if(typeof Y==="number")return Y<=$;if(Array.isArray(Y))return Y.length<=$;return!1},message:(Y,Z)=>`The ${Y} field must not exceed ${Z[0]} characters.`},between:{name:"between",validate:(Y,Z)=>{let $=Number(Z[0]),X=Number(Z[1]);if(typeof Y==="string")return Y.length>=$&&Y.length<=X;if(typeof Y==="number")return Y>=$&&Y<=X;if(Array.isArray(Y))return Y.length>=$&&Y.length<=X;return!1},message:(Y,Z)=>`The ${Y} field must be between ${Z[0]} and ${Z[1]}.`},in:{name:"in",validate:(Y,Z)=>Z.includes(String(Y)),message:(Y,Z)=>`The ${Y} field must be one of: ${Z.join(", ")}.`},notIn:{name:"not_in",validate:(Y,Z)=>!Z.includes(String(Y)),message:(Y,Z)=>`The ${Y} field must not be one of: ${Z.join(", ")}.`},regex:{name:"regex",validate:(Y,Z)=>{let $=new RegExp(Z[0]);return typeof Y==="string"&&$.test(Y)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(Y)=>typeof Y==="string"&&/^[a-z]+$/i.test(Y),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(Y)=>typeof Y==="string"&&/^[a-z0-9]+$/i.test(Y),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(Y)=>typeof Y==="string"&&/^[\w-]+$/.test(Y),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(Y)=>{let Z=new Date(Y);return!Number.isNaN(Z.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(Y,Z)=>{let $=new Date(Y),X=new Date(Z[0]);return!Number.isNaN($.getTime())&&!Number.isNaN(X.getTime())&&$>X},message:(Y,Z)=>`The ${Y} field must be after ${Z[0]}.`},dateBefore:{name:"before",validate:(Y,Z)=>{let $=new Date(Y),X=new Date(Z[0]);return!Number.isNaN($.getTime())&&!Number.isNaN(X.getTime())&&$<X},message:(Y,Z)=>`The ${Y} field must be before ${Z[0]}.`},confirmed:{name:"confirmed",validate:(Y,Z,$,X)=>{let J=Z[0]||`${$}_confirmation`;return Y===X[J]},message:"The :field confirmation does not match."},same:{name:"same",validate:(Y,Z,$,X)=>{return Y===X[Z[0]]},message:(Y,Z)=>`The ${Y} field must match ${Z[0]}.`},different:{name:"different",validate:(Y,Z,$,X)=>{return Y!==X[Z[0]]},message:(Y,Z)=>`The ${Y} field must be different from ${Z[0]}.`},json:{name:"json",validate:(Y)=>{try{return JSON.parse(Y),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(Y)=>{return typeof Y==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(Y)},message:"The :field field must be a valid UUID."},array:{name:"array",validate:(Y)=>Array.isArray(Y),message:"The :field field must be an array."},object:{name:"object",validate:(Y)=>typeof Y==="object"&&Y!==null&&!Array.isArray(Y),message:"The :field field must be an object."}},h4={unique:{name:"unique",validate:async(Y,Z)=>{return console.warn('Database validation rule "unique" requires external implementation'),!0},message:"The :field field must be unique."},exists:{name:"exists",validate:async(Y,Z)=>{return console.warn('Database validation rule "exists" requires external implementation'),!0},message:"The selected :field is invalid."}};class qY{rules={};config;constructor(Y={}){this.config={stopOnFirstFailure:!1,bail:!1,...Y},this.registerRules(P$)}registerRule(Y){this.rules[Y.name]=Y}registerRules(Y){Object.values(Y).forEach((Z)=>this.registerRule(Z))}parseRuleString(Y){return Y.split("|").map((Z)=>{let[$,...X]=Z.split(":"),J=X.length>0?X.join(":").split(","):[];return{name:$.trim(),parameters:J}})}async validate(Y,Z){let $={};for(let[X,J]of Object.entries(Z)){let Q=[],_=this.getNestedValue(Y,X),j=typeof J==="string"?this.parseRuleString(J):J.map((G)=>({name:G.name,parameters:[]}));for(let{name:G,parameters:W}of j){let K=this.rules[G];if(!K){console.warn(`Validation rule "${G}" not found`);continue}try{if(!await K.validate(_,W,X,Y)){let L=this.formatErrorMessage(K,X,W);if(Q.push(L),this.config.stopOnFirstFailure||this.config.bail)break}}catch(z){console.error(`Error validating rule "${G}" for field "${X}":`,z),Q.push(`Validation error for ${X}`)}}if(Q.length>0)$[X]=Q}return $}async validateOrFail(Y,Z){let $=await this.validate(Y,Z);if(Object.keys($).length>0)throw new $Y("Validation failed",$)}getNestedValue(Y,Z){return Z.split(".").reduce(($,X)=>{return $&&$[X]!==void 0?$[X]:void 0},Y)}formatErrorMessage(Y,Z,$){let X=this.config.customMessages?.[`${Z}.${Y.name}`]||this.config.customMessages?.[Y.name];if(X)return this.replacePlaceholders(X,Z,$);let J=typeof Y.message==="function"?Y.message(Z,$):Y.message;return this.replacePlaceholders(J,Z,$)}replacePlaceholders(Y,Z,$){let X=this.config.customAttributes?.[Z]||Z.replace(/_/g," ");return Y.replace(/:field/g,X).replace(/:attribute/g,X).replace(/:value/g,$[0]||"").replace(/:other/g,$[1]||"")}}var c4=new qY;function fY(Y,Z){let $=new qY(Z);return async(X,J)=>{try{let Q={...X.query,...X.params,...X.jsonBody||{},...X.formBody||{}};return await $.validateOrFail(Q,Y),X.validated=Q,await J()}catch(Q){if(Q instanceof $Y)throw Q;throw new $Y("Validation error occurred")}}}class JZ{rules=[];required(){return this.rules.push("required"),this}string(){return this.rules.push("string"),this}number(){return this.rules.push("number"),this}integer(){return this.rules.push("integer"),this}boolean(){return this.rules.push("boolean"),this}email(){return this.rules.push("email"),this}url(){return this.rules.push("url"),this}min(Y){return this.rules.push(`min:${Y}`),this}max(Y){return this.rules.push(`max:${Y}`),this}between(Y,Z){return this.rules.push(`between:${Y},${Z}`),this}in(...Y){return this.rules.push(`in:${Y.join(",")}`),this}notIn(...Y){return this.rules.push(`not_in:${Y.join(",")}`),this}regex(Y){return this.rules.push(`regex:${Y}`),this}alpha(){return this.rules.push("alpha"),this}alphaNum(){return this.rules.push("alpha_num"),this}alphaDash(){return this.rules.push("alpha_dash"),this}date(){return this.rules.push("date"),this}after(Y){return this.rules.push(`after:${Y}`),this}before(Y){return this.rules.push(`before:${Y}`),this}confirmed(Y){return this.rules.push(Y?`confirmed:${Y}`:"confirmed"),this}same(Y){return this.rules.push(`same:${Y}`),this}different(Y){return this.rules.push(`different:${Y}`),this}json(){return this.rules.push("json"),this}uuid(){return this.rules.push("uuid"),this}array(){return this.rules.push("array"),this}object(){return this.rules.push("object"),this}unique(Y,Z){return this.rules.push(Z?`unique:${Y},${Z}`:`unique:${Y}`),this}exists(Y,Z){return this.rules.push(Z?`exists:${Y},${Z}`:`exists:${Y}`),this}custom(Y,...Z){return this.rules.push(Z.length>0?`${Y}:${Z.join(",")}`:Y),this}build(){return this.rules.join("|")}}function p4(){return new JZ}var m4={rules(Y){let Z={};for(let[$,X]of Object.entries(Y))Z[$]=X instanceof JZ?X.build():X;return Z},async validateValue(Y,Z,$="value"){return(await new qY().validate({[$]:Y},{[$]:Z}))[$]||[]},async passes(Y,Z){return(await this.validateValue(Y,Z)).length===0},async fails(Y,Z){return!await this.passes(Y,Z)}};class S{method;path;handler;validationRules;validatorConfig;constructor(Y,Z,$){this.method=Y;this.path=Z;this.handler=$}validate(Y,Z){return this.validationRules=Y,this.validatorConfig=Z,this}build(){let Y=[];if(this.validationRules)Y.push(fY(this.validationRules,this.validatorConfig));return Y.push(async(Z,$)=>{return B.applyMacros(Z),await $()||new Response("Not Found",{status:404})}),{method:this.method,path:this.path,handler:this.handler,middleware:Y.length>0?Y:void 0}}}class S8{routes=[];get(Y,Z){return new S("GET",Y,Z)}post(Y,Z){return new S("POST",Y,Z)}put(Y,Z){return new S("PUT",Y,Z)}patch(Y,Z){return new S("PATCH",Y,Z)}delete(Y,Z){return new S("DELETE",Y,Z)}register(Y){let Z=Y.build();this.routes.push(Z)}getRoutes(){return this.routes}}function QZ(){return async(Y,Z)=>{return B.applyMacros(Y),Y.startTime=Date.now(),await Z()}}class C8{rules={};config={};field(Y,Z){return this.rules[Y]=Z,this}fields(Y){return Object.assign(this.rules,Y),this}configure(Y){return Object.assign(this.config,Y),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(Y){return this.config.customMessages=Y,this}attributes(Y){return this.config.customAttributes=Y,this}build(){return fY(this.rules,this.config)}}function n4(){return new C8}var s4={validated:(Y,Z,$,X,J)=>{return new S(Y,Z,$).validate(X,J)},apiRoute:(Y,Z,$,X)=>{let J=new S(Y,Z,async(Q)=>{if(!Q.expectsJson())return LY.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return await $(Q)});if(X)J.validate(X);return J},resourceRoute:(Y,Z,$)=>{let X=[];if(Z.index)X.push(new S("GET",Y,Z.index));if(Z.show)X.push(new S("GET",`${Y}/{id}`,Z.show));if(Z.store){let J=new S("POST",Y,Z.store);if($?.store)J.validate($.store);X.push(J)}if(Z.update){let J=new S("PUT",`${Y}/{id}`,Z.update);if($?.update)J.validate($.update);X.push(J)}if(Z.destroy)X.push(new S("DELETE",`${Y}/{id}`,Z.destroy));return X}};function o4(){return new S8}var N8={compose:(...Y)=>{return async(Z,$)=>{let X=0,J=async()=>{if(X>=Y.length)return await $();let Q=Y[X++];return await Q(Z,J)};return await J()}},when:(Y,Z)=>{return async($,X)=>{if(Y($))return await Z($,X);return await X()}},unless:(Y,Z)=>{return N8.when(($)=>!Y($),Z)},group:(Y)=>{return N8.compose(...Y)}},a4={api:()=>[QZ(),async(Y,Z)=>{try{let $=await Z(),X=new Headers($.headers);return X.set("X-API-Version","1.0"),X.set("X-Response-Time",new Date().toISOString()),new Response($.body,{status:$.status,statusText:$.statusText,headers:X})}catch($){return console.error($),LY.callMacro("error","Internal server error",void 0,500)}}],web:()=>[QZ(),async(Y,Z)=>{return Y.session={},await Z()}],validation:(Y,Z)=>[QZ(),fY(Y,Z)]};$8(O);X8(O);L8(O);K8(O);_8(O);H8(O);F8(O);vZ(O);Z8(O);O8(O);z8(O);W8(O);kZ(O);bZ(O);class _Z{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(Y,Z){return this.groups.set(Y,[...Z]),this}extend(Y,Z){let $=this.groups.get(Y)||[];return this.groups.set(Y,[...$,...Z]),this}prepend(Y,Z){let $=this.groups.get(Y)||[];return this.groups.set(Y,[...Z,...$]),this}get(Y){return this.groups.get(Y)||[]}has(Y){return this.groups.has(Y)}remove(Y){return this.groups.delete(Y),this}resolve(Y){if(typeof Y==="function")return[Y];if(this.groups.has(Y))return this.get(Y);return[Y]}resolveAll(Y){let Z=[];for(let $ of Y)Z.push(...this.resolve($));return Z}pushGlobal(...Y){return this.globalMiddleware.push(...Y),this}prependGlobal(...Y){return this.globalMiddleware.unshift(...Y),this}removeGlobal(Y){return this.globalMiddleware=this.globalMiddleware.filter((Z)=>typeof Z==="string"?Z!==Y:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(Y,Z){return this.middlewarePriority.set(Y,Z),this}sortByPriority(Y){return[...Y].sort((Z,$)=>{let X=typeof Z==="string"?Z.split(":")[0]:"",J=typeof $==="string"?$.split(":")[0]:"",Q=this.middlewarePriority.get(X)??100,_=this.middlewarePriority.get(J)??100;return Q-_})}filter(Y,Z){if(Z.only&&Z.only.length>0)return Y.filter(($)=>{if(typeof $==="string"){let X=$.split(":")[0];return Z.only.includes(X)}return!1});if(Z.except&&Z.except.length>0)return Y.filter(($)=>{if(typeof $==="string"){let X=$.split(":")[0];return!Z.except.includes(X)}return!0});return Y}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var C=new _Z;C.define("web",["session","csrf","cors"]);C.define("api",["throttle:60,1","cors"]);C.setPriority("session",10);C.setPriority("cors",20);C.setPriority("csrf",30);C.setPriority("auth",40);C.setPriority("throttle",50);C.setPriority("role",60);C.setPriority("permission",60);C.setPriority("can",70);C.setPriority("abilities",70);C.setPriority("verified",80);import{mock as jZ}from"bun:test";function M8(Y){let Z={...Y};return{get:($)=>Z[$],set:($,X,J)=>{Z[$]=X},delete:($,X)=>{delete Z[$]},getAll:()=>({...Z})}}class w{request;url;constructor(Y,Z,$={}){if(this.url=new URL(Z,"http://localhost:3000"),$.query)Object.entries($.query).forEach(([X,J])=>{if(Array.isArray(J))J.forEach((Q)=>this.url.searchParams.append(X,Q));else this.url.searchParams.set(X,J)});this.request={method:Y,url:this.url.toString(),headers:new Headers($.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:$.body&&typeof $.body==="object"?$.body:void 0,files:$.files?this.convertTestFiles($.files):void 0,session:$.session,user:$.user,context:$.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:M8($.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody($.body)}parseQuery(Y){let Z={};for(let[$,X]of Y.entries())if(Z[$])if(Array.isArray(Z[$]))Z[$].push(X);else Z[$]=[Z[$],X];else Z[$]=X;return Z}convertTestFiles(Y){return Y.map((Z)=>({fieldName:Z.fieldName,originalName:Z.filename,filename:`test-${Date.now()}-${Z.filename}`,path:`/tmp/test-uploads/${Z.filename}`,size:Z.content instanceof ArrayBuffer?Z.content.byteLength:new TextEncoder().encode(Z.content.toString()).length,mimetype:Z.mimetype||"application/octet-stream",buffer:Z.content instanceof ArrayBuffer?Z.content:new TextEncoder().encode(Z.content.toString()).buffer}))}handleBody(Y){if(!Y)return;let Z=this.request.headers?.get("content-type")||"";if(Z.includes("application/json")||typeof Y==="object"){if(this.request.jsonBody=Y,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(Z.includes("application/x-www-form-urlencoded"))this.request.formBody=Y}params(Y){return this.request.params={...this.request.params,...Y},this}headers(Y){return Object.entries(Y).forEach(([Z,$])=>{this.request.headers?.set(Z,$)}),this}auth(Y,Z="Bearer"){return this.request.headers?.set("Authorization",`${Z} ${Y}`),this}user(Y){return this.request.user=Y,this}session(Y){return this.request.session=Y,this}cookies(Y){let Z=this.request.cookies?.getAll()||{};return this.request.cookies=M8({...Z,...Y}),this}context(Y){return this.request.context={...this.request.context,...Y},this}json(Y){return this.request.jsonBody=Y,this.request.headers?.set("content-type","application/json"),this}form(Y){return this.request.formBody=Y,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(Y){return this.request.files=this.convertTestFiles(Y),this.request.headers?.set("content-type","multipart/form-data"),this}ip(Y){return this.request.ip=Y,this}userAgent(Y){return this.request.userAgent=()=>Y,this.request.headers?.set("User-Agent",Y),this}csrf(Y){return this.request.csrfToken=Y,this.request.headers?.set("X-CSRF-Token",Y),this}build(){let Y={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)Y.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let X=new FormData;Object.entries(this.request.formBody).forEach(([J,Q])=>{X.append(J,Q)}),Y.body=X}let Z=new Request(this.url.toString(),Y);return Object.assign(Z,{params:this.request.params||{},query:this.request.query||{},jsonBody:this.request.jsonBody,formBody:this.request.formBody,files:this.request.files,session:this.request.session,user:this.request.user,context:this.request.context||{},requestId:this.request.requestId,ip:this.request.ip,userAgent:this.request.userAgent,cookies:this.request.cookies||{},startTime:this.request.startTime,traceId:this.request.traceId,spanId:this.request.spanId})}}var N0={get:(Y,Z)=>new w("GET",Y,Z),post:(Y,Z)=>new w("POST",Y,Z),put:(Y,Z)=>new w("PUT",Y,Z),patch:(Y,Z)=>new w("PATCH",Y,Z),delete:(Y,Z)=>new w("DELETE",Y,Z),options:(Y,Z)=>new w("OPTIONS",Y,Z),head:(Y,Z)=>new w("HEAD",Y,Z)};function H(Y="GET",Z="/",$={}){return new w(Y,Z,$).build()}function b$(Y){let Z={...Y};return{get:($)=>Z[$],set:($,X,J)=>{Z[$]=X},delete:($,X)=>{delete Z[$]},getAll:()=>({...Z})}}class UY{request;constructor(Y){this.request=Y||H()}as(Y){return this.request.user=Y,this}withJWT(Y,Z="Bearer"){let $=new Headers(this.request.headers);return $.set("Authorization",`${Z} ${Y}`),this.request={...this.request,headers:$},this}withSession(Y){return this.request.session=Y,this}withApiKey(Y,Z="X-API-Key"){let $=new Headers(this.request.headers);return $.set(Z,Y),this.request={...this.request,headers:$},this}withBasicAuth(Y,Z){let $=btoa(`${Y}:${Z}`),X=new Headers(this.request.headers);return X.set("Authorization",`Basic ${$}`),this.request={...this.request,headers:X},this}withAuthCookies(Y){let Z=this.request.cookies?.getAll()||{};return this.request.cookies=b$({...Z,...Y}),this}unauthenticated(){if(this.request.user=void 0,this.request.session=void 0,this.request.headers)this.request.headers.delete("Authorization");return this}getRequest(){return this.request}}class GZ{options;constructor(Y={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...Y}}generateToken(Y={}){let Z={alg:this.options.algorithm,typ:"JWT",...this.options.headers},$=Math.floor(Date.now()/1000),X=$+this.parseExpiresIn(this.options.expiresIn||"1h"),J={iat:$,exp:X,...this.options.payload,...Y},Q=btoa(JSON.stringify(Z)).replace(/=/g,""),_=btoa(JSON.stringify(J)).replace(/=/g,""),j=btoa(`${Q}.${_}.${this.options.secret}`).replace(/=/g,"");return`${Q}.${_}.${j}`}generateExpiredToken(Y={}){let Z={alg:this.options.algorithm,typ:"JWT"},$=Math.floor(Date.now()/1000),X={iat:$-7200,exp:$-3600,...Y},J=btoa(JSON.stringify(Z)).replace(/=/g,""),Q=btoa(JSON.stringify(X)).replace(/=/g,""),_=btoa(`${J}.${Q}.${this.options.secret}`).replace(/=/g,"");return`${J}.${Q}.${_}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(Y){let[Z,$,X]=Y.split(".");return{header:JSON.parse(atob(Z)),payload:JSON.parse(atob($)),signature:X}}parseExpiresIn(Y){let Z=Y.match(/^(\d+)([smhd])$/);if(!Z)return 3600;let $=Number.parseInt(Z[1]);switch(Z[2]){case"s":return $;case"m":return $*60;case"h":return $*3600;case"d":return $*86400;default:return 3600}}}class WZ{options;constructor(Y={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...Y}}createSession(Y={}){let Z={...this.options.data,...Y},$=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:Z,cookie:$}}generateSessionCookie(Y="session"){let Z=[];if(this.options.maxAge)Z.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)Z.push("Secure");if(this.options.httpOnly)Z.push("HttpOnly");let $=Z.length>0?`; ${Z.join("; ")}`:"";return`${Y}=${this.options.sessionId}${$}`}createExpiredSession(){let Y={...this.options,maxAge:-1};return new WZ(Y).createSession()}}var T0={user:(Y={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...Y}),adminUser:(Y={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...Y}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(Y)=>jZ(async(Z,$)=>{if(Y)return Z.user=Y,await $();return new Response("Unauthorized",{status:401})}),roleMiddleware:(Y)=>jZ(async(Z,$)=>{if(!Z.user)return new Response("Unauthorized",{status:401});let X=Z.user.roles||[];if(!Y.some((Q)=>X.includes(Q)))return new Response("Forbidden",{status:403});return await $()}),permissionMiddleware:(Y)=>jZ(async(Z,$)=>{if(!Z.user)return new Response("Unauthorized",{status:401});let X=Z.user.permissions||[];if(!Y.every((Q)=>X.includes(Q)))return new Response("Forbidden",{status:403});return await $()})},P0={authenticatedRequest:(Y,Z)=>{return new UY(Z).as(Y).getRequest()},jwtRequest:(Y={},Z)=>{let X=new GZ().generateToken(Y);return new UY(Z).withJWT(X).getRequest()},sessionRequest:(Y={},Z)=>{return new UY(Z).withSession(Y).getRequest()},verifyJWTStructure:(Y)=>{let Z=Y.split(".");return Z.length===3&&Z.every(($)=>$.length>0)},extractJWTPayload:(Y)=>{try{let[,Z]=Y.split(".");return JSON.parse(atob(Z))}catch{return null}}};function b0(Y){return new UY(Y)}function x0(Y){return new GZ(Y)}function R0(Y){return new WZ(Y)}import{mock as u}from"bun:test";class c{request;files;constructor(Y){this.request=Y||H(),this.files=[]}addFile(Y){let Z={fieldName:Y.fieldName,originalName:Y.filename,filename:`test-${Date.now()}-${Y.filename}`,path:`/tmp/test-uploads/${Y.filename}`,size:Y.content instanceof ArrayBuffer?Y.content.byteLength:new TextEncoder().encode(Y.content.toString()).length,mimetype:Y.mimetype||this.detectMimeType(Y.filename),buffer:Y.content instanceof ArrayBuffer?Y.content:new TextEncoder().encode(Y.content.toString()).buffer};return this.files.push(Z),this.request.files=[...this.request.files||[],Z],this}addFiles(Y){return Y.forEach((Z)=>this.addFile(Z)),this}addImage(Y,Z="test.jpg",$=1024){let X=new ArrayBuffer($);return this.addFile({fieldName:Y,filename:Z,content:X,mimetype:"image/jpeg"})}addDocument(Y,Z="test.pdf",$="Test PDF content"){return this.addFile({fieldName:Y,filename:Z,content:$,mimetype:"application/pdf"})}addTextFile(Y,Z="test.txt",$="Test content"){return this.addFile({fieldName:Y,filename:Z,content:$,mimetype:"text/plain"})}addLargeFile(Y,Z=10){let $=Z*1024*1024,X=new ArrayBuffer($);return this.addFile({fieldName:Y,filename:`large-file-${Z}mb.bin`,content:X,mimetype:"application/octet-stream"})}addInvalidFile(Y,Z="malicious.exe"){return this.addFile({fieldName:Y,filename:Z,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(Y){return this.request.formBody={...this.request.formBody,...Y},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(Y){let Z=Y.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json",xml:"application/xml",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}[Z||""]||"application/octet-stream"}}class KZ{static testFileSize(Y,Z){return Y.size<=Z}static testFileType(Y,Z){return Z.includes(Y.mimetype)}static testFileExtension(Y,Z){let $=Y.originalName.split(".").pop()?.toLowerCase();return $?Z.includes($):!1}static testFilename(Y){let Z=Y.originalName;if(Z.includes("..")||Z.includes("/")||Z.includes("\\"))return!1;if(Z.includes("\x00"))return!1;let $=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],X=Z.split(".")[0].toUpperCase();if($.includes(X))return!1;return!0}static testImageFile(Y){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(Y.mimetype)}static testDocumentFile(Y){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(Y.mimetype)}}var q0={validationMiddleware:(Y={})=>{return u(async($,X)=>{let J=$.files||[],{maxSize:Q=5242880,allowedTypes:_=[],maxFiles:j=10}=Y;if(J.length>j)return new Response(`Too many files. Maximum ${j} allowed.`,{status:400});for(let G of J){if(G.size>Q)return new Response(`File ${G.originalName} is too large. Maximum size: ${Q} bytes.`,{status:400});if(_.length>0&&!_.includes(G.mimetype))return new Response(`File type ${G.mimetype} not allowed.`,{status:400});if(!KZ.testFilename(G))return new Response(`Invalid filename: ${G.originalName}`,{status:400})}return await X()})},imageUploadMiddleware:(Y={})=>{return u(async($,X)=>{let J=$.files||[],{maxSize:Q=2097152}=Y;for(let _ of J){if(!KZ.testImageFile(_))return new Response(`File ${_.originalName} is not a valid image.`,{status:400});if(_.size>Q)return new Response(`Image ${_.originalName} is too large.`,{status:400})}return await X()})},storageService:{store:u(async(Y,Z)=>{return Z||`/uploads/${Date.now()}-${Y.filename}`}),delete:u(async(Y)=>{}),exists:u(async(Y)=>{return!Y.includes("not-found")}),getUrl:u((Y)=>{return`https://example.com/storage${Y}`})},virusScanner:{scan:u(async(Y)=>{if(Y.originalName.endsWith(".exe")||Y.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},f0={singleFileUpload:()=>{return new c().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"})},multipleFileUpload:()=>{return new c().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"})},fileSizeExceeded:()=>{return new c().addLargeFile("file",50)},invalidFileType:()=>{return new c().addInvalidFile("file","virus.exe")},emptyFileUpload:()=>{return new c().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"})},maliciousFilename:()=>{return new c().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})}},y0={hasFiles:(Y,Z)=>{let $=Y.files||[];if(Z!==void 0&&$.length!==Z)throw Error(`Expected ${Z} files, but got ${$.length}`);if($.length===0)throw Error("Expected request to have files")},hasFileWithField:(Y,Z)=>{if(!(Y.files||[]).some((J)=>J.fieldName===Z))throw Error(`Expected file with field name '${Z}'`)},fileMatches:(Y,Z)=>{Object.entries(Z).forEach(([$,X])=>{if(Y[$]!==X)throw Error(`Expected file.${$} to be '${X}', got '${Y[$]}'`)})},fileSizeWithinLimit:(Y,Z)=>{if(Y.size>Z)throw Error(`File size ${Y.size} exceeds limit of ${Z}`)},fileTypeAllowed:(Y,Z)=>{if(!Z.includes(Y.mimetype))throw Error(`File type '${Y.mimetype}' is not allowed. Allowed types: ${Z.join(", ")}`)}};function g0(Y){return new c(Y)}var h0={image:(Y="image",Z="test.jpg")=>({fieldName:Y,filename:Z,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(Y="document",Z="test.pdf")=>({fieldName:Y,filename:Z,content:"PDF content",mimetype:"application/pdf"}),text:(Y="file",Z="test.txt",$="Test content")=>({fieldName:Y,filename:Z,content:$,mimetype:"text/plain"}),large:(Y="file",Z=10)=>({fieldName:Y,filename:`large-${Z}mb.bin`,content:new ArrayBuffer(Z*1024*1024),mimetype:"application/octet-stream"}),malicious:(Y="file")=>({fieldName:Y,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as N,spyOn as x$}from"bun:test";class T8{middleware;context;constructor(Y){this.middleware=Y,this.context=this.createContext()}createContext(){let Y=H(),Z=N(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:Y,next:Z}}withRequest(Y){return this.context.request=Y,this}withNext(Y){return this.context.next=N(Y),this}withError(Y){return this.context.error=Y,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(Y){throw this.context.error=Y,Y}}expectNextCalled(Y=1){if(this.context.next.mock.calls.length!==Y)throw Error(`Expected next to be called ${Y} times, but was called ${this.context.next.mock.calls.length} times`);return this}expectNextNotCalled(){if(this.context.next.mock.calls.length>0)throw Error(`Expected next not to be called, but was called ${this.context.next.mock.calls.length} times`);return this}expectError(Y){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(Y&&this.context.error.message!==Y)throw Error(`Expected error message "${Y}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function u0(Y){return new T8(Y)}var d0={passthrough:()=>N(async(Y,Z)=>await Z()),response:(Y=200,Z)=>N(async()=>new Response(Z?JSON.stringify(Z):null,{status:Y})),error:(Y="Middleware error")=>N(async()=>{throw Error(Y)}),modifyRequest:(Y)=>N(async(Z,$)=>{return Y(Z),await $()}),addContext:(Y,Z)=>N(async($,X)=>{return $.context=$.context||{},$.context[Y]=Z,await X()}),auth:(Y)=>N(async(Z,$)=>{if(Y)return Z.user=Y,await $();else return new Response("Unauthorized",{status:401})}),rateLimit:(Y=!1)=>N(async(Z,$)=>{if(Y)return new Response("Too Many Requests",{status:429});return await $()}),cors:(Y="*")=>N(async(Z,$)=>{let X=await $();if(X)X.headers.set("Access-Control-Allow-Origin",Y);return X})};class P8{middlewares;request;finalHandler;constructor(Y){this.middlewares=Y,this.request=H(),this.finalHandler=N(async()=>new Response("Final handler",{status:200}))}withRequest(Y){return this.request=Y,this}withFinalHandler(Y){return this.finalHandler=N(Y),this}async execute(){let Y=0,Z=async()=>{if(Y<this.middlewares.length){let $=this.middlewares[Y++];return await $(this.request,Z)}else return await this.finalHandler()};return await Z()}getExecutionOrder(){return this.middlewares.map((Y,Z)=>Z)}}function l0(Y){return new P8(Y)}function i0(Y){return x$(Y,"call")}function n0(){let Y=N(async(Z,$)=>{return await $()});return{middleware:Y,spy:Y}}async function s0(Y,Z=1000){let $=[],X=H(),J=N(async()=>new Response("OK"));for(let W=0;W<Z;W++){let K=performance.now();await Y(X,J);let z=performance.now();$.push(z-K)}let Q=$.reduce((W,K)=>W+K,0),_=Q/Z,j=Math.min(...$),G=Math.max(...$);return{averageTime:_,minTime:j,maxTime:G,totalTime:Q}}import{mock as y}from"bun:test";class R${id;attributes;constructor(Y={}){this.id=Y.id,this.attributes=Y}static modelName="GenericMockModel";static async find(Y){return null}static async findOrFail(Y){throw Error("Not implemented")}static async where(Y){return[]}static async create(Y){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class w${id;email;name;constructor(Y={id:1}){this.id=Y.id,this.email=Y.email||"test@example.com",this.name=Y.name||"Test User"}static async find(Y){return null}static async findOrFail(Y){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class k${id;title;content;userId;constructor(Y={id:1}){this.id=Y.id,this.title=Y.title||"Test Post",this.content=Y.content||"Test content",this.userId=Y.userId||1}static async find(Y){return null}static async findOrFail(Y){throw Error("Not implemented")}async belongsTo(Y){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class b8{request;options;constructor(Y={}){this.options=Y,this.request=H()}withRequest(Y){return this.request=Y,this}withParams(Y){return this.request.params={...this.request.params,...Y},this}withModel(Y){return this.options.modelClass=Y,this}withRouteKey(Y){return this.options.routeKey=Y,this}withConstraints(Y){return this.options.constraints=Y,this}withResolver(Y){return this.options.customResolver=Y,this}async testResolution(Y){if(this.options.customResolver)return await this.options.customResolver(Y);if(this.options.modelClass)return new this.options.modelClass({id:Y});return{id:Y}}async testNotFound(Y){try{throw await this.testResolution(Y),Error("Expected model not found error")}catch(Z){if(Z instanceof Error&&Z.message!=="Model not found")throw Z}}getRequest(){return this.request}}var r0={createModel:(Y,Z={})=>{return class ${id;attributes;constructor(X={}){this.id=X.id,this.attributes={...Z,...X}}static modelName=Y;static async find(X){if(X==="not-found")return null;return new $({id:X,...Z})}static async findOrFail(X){let J=await this.find(X);if(!J)throw Error("Model not found");return J}static async where(X){return[new $({id:1,...Z,...X})]}static async create(X){return new $({id:Date.now(),...X})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}},User:class Y{id;email;name;constructor(Z={id:1}){this.id=Z.id,this.email=Z.email||"test@example.com",this.name=Z.name||"Test User"}static async find(Z){if(Z==="not-found")return null;return new Y({id:Number.parseInt(Z)})}static async findOrFail(Z){let $=await this.find(Z);if(!$)throw Error("User not found");return $}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class Y{id;title;content;userId;constructor(Z={id:1}){this.id=Z.id,this.title=Z.title||"Test Post",this.content=Z.content||"Test content",this.userId=Z.userId||1}static async find(Z){if(Z==="not-found")return null;return new Y({id:Number.parseInt(Z)})}static async findOrFail(Z){let $=await this.find(Z);if(!$)throw Error("Post not found");return $}async belongsTo(Z){return this.userId===Z}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},e0={belongsTo:(Y="userId")=>{return y(async($,X)=>{if(!X.user)return!1;return $[Y]===X.user.id})},belongsToUser:()=>{return y(async(Z,$)=>{if(!$.user)return!1;return Z.userId===$.user.id})},published:()=>{return y(async(Z)=>{return Z.published===!0||Z.status==="published"})},visible:()=>{return y(async(Z)=>{return Z.visible!==!1&&Z.hidden!==!0})},custom:(Y)=>{return y(Y)},combine:(...Y)=>{return y(async($,X)=>{for(let J of Y)if(!await J($,X))return!1;return!0})}};class x8{resolvers=new Map;register(Y,Z){return this.resolvers.set(Y,y(Z)),this}registerModel(Y,Z){let $=y(async(X)=>{if(Z.find){let J=await Z.find(X);if(!J)throw Error(`${Z.name||"Model"} not found`);return J}return new Z({id:X})});return this.resolvers.set(Y,$),this}async resolve(Y,Z){let $=this.resolvers.get(Y);if(!$)throw Error(`No resolver registered for key: ${Y}`);return await $(Z)}async testAll(Y="1"){let Z={};for(let[$,X]of this.resolvers)try{Z[$]=await X(Y)}catch(J){Z[$]={error:J instanceof Error?J.message:"Unknown error"}}return Z}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var Y1={testRoute:async(Y,Z,$)=>{let X=H("GET",Y);X.params=Z;for(let[J,Q]of Object.entries($))X.context=X.context||{},X.context[J]=Q;return X},createHandler:(Y)=>{return y(async($)=>{let X=$.context||{};for(let J of Y)if(!X[J])return new Response(`Model ${J} not found`,{status:404});return new Response(JSON.stringify({params:$.params,models:Object.fromEntries(Y.map((J)=>[J,X[J]]))}),{headers:{"Content-Type":"application/json"}})})},testBindingMiddleware:(Y)=>{return y(async($,X)=>{$.context=$.context||{};for(let[J,Q]of Object.entries(Y)){let _=$.params[J];if(_)try{if(typeof Q==="function")$.context[J]=await Q(_);else $.context[J]=Q}catch(j){return console.error(`Error resolving model ${J}:`,j),new Response(`${J} not found`,{status:404})}}return await X()})}};function Z1(Y){return new b8(Y)}function $1(){return new x8}var v$=async(Y,Z)=>Y.userId===Z.id,X1={testUserScoped:async(Y,Z,$=v$)=>{return await $(Y,Z)},testRoleAccess:async(Y,Z,$)=>{if(!Z.roles)return!1;return $.some((X)=>Z.roles.includes(X))},testPermissionAccess:async(Y,Z,$)=>{if(!Z.permissions)return!1;return $.every((X)=>Z.permissions.includes(X))}};import{mock as q$}from"bun:test";import d from"process";class w8{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(Y){return this.metrics.push(Y),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((Z,$)=>Z+$.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let Y=this.metrics.map(($)=>$.memoryUsage.heapUsed),Z=this.metrics.map(($)=>$.memoryUsage.rss);return{averageHeapUsed:Y.reduce(($,X)=>$+X,0)/Y.length,maxHeapUsed:Math.max(...Y),averageRSS:Z.reduce(($,X)=>$+X,0)/Z.length,maxRSS:Math.max(...Z)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class e{client;config;constructor(Y,Z){this.client=Y,this.config=Z}async run(Y,Z="GET",$={}){let X={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},J=[],Q=new Map,_=Date.now(),j=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),G=[];for(let z=0;z<j;z++){let L=this.makeRequest(Y,Z,$).then((V)=>{J.push(V),X.successfulRequests++}).catch((V)=>{let U=V instanceof Error?V.message:"Unknown error";Q.set(U,(Q.get(U)||0)+1),X.failedRequests++});if(G.push(L),this.config.requestsPerSecond){let V=1000/this.config.requestsPerSecond;await new Promise((U)=>setTimeout(U,V))}if(G.length>=this.config.concurrency)await Promise.race(G),G.filter((U)=>U.then(()=>!0).catch(()=>!0)).forEach((U)=>{let A=G.indexOf(U);if(A>-1)G.splice(A,1)})}await Promise.allSettled(G);let K=(Date.now()-_)/1000;return X.totalRequests=j,X.averageResponseTime=J.length>0?J.reduce((z,L)=>z+L,0)/J.length:0,X.requestsPerSecond=j/K,X.errors=Array.from(Q.entries()).map(([z,L])=>({error:z,count:L})),X}async makeRequest(Y,Z,$){let X=performance.now();try{return await this.client.request(Z,Y,$),performance.now()-X}catch(J){let Q=performance.now();throw J}}}var G1={routeHandler:async(Y,Z=1000)=>{let $=[],X=H();for(let W=0;W<Z;W++){let K=performance.now();await Y(X);let z=performance.now();$.push(z-K)}let J=$.reduce((W,K)=>W+K,0),Q=J/Z,_=Math.min(...$),j=Math.max(...$),G=Z/J*1000;return{averageTime:Q,minTime:_,maxTime:j,totalTime:J,throughput:G}},middleware:async(Y,Z=1000)=>{let $=[],X=H(),J=q$(async()=>new Response("OK"));for(let W=0;W<Z;W++){let K=performance.now();await Y(X,J);let z=performance.now();$.push(z-K)}let Q=$.reduce((W,K)=>W+K,0),_=Q/Z,j=Math.min(...$),G=Math.max(...$);return{averageTime:_,minTime:j,maxTime:G,totalTime:Q}},jsonSerialization:async(Y,Z=1e4)=>{let $=[];for(let G=0;G<Z;G++){let W=performance.now(),K=JSON.stringify(Y),z=performance.now();$.push(z-W)}let X=$.reduce((G,W)=>G+W,0),J=X/Z,Q=Math.min(...$),_=Math.max(...$),j=JSON.stringify(Y).length;return{averageTime:J,minTime:Q,maxTime:_,totalTime:X,dataSize:j}},routeMatching:async(Y,Z,$=1000)=>{let X=[],J=0;for(let K=0;K<$;K++){let z=Z[K%Z.length],L=performance.now();if(Y.find((A)=>{let I=A.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${I}$`).test(z)}))J++;let U=performance.now();X.push(U-L)}let Q=X.reduce((K,z)=>K+z,0),_=Q/$,j=Math.min(...X),G=Math.max(...X),W=J/$;return{averageTime:_,minTime:j,maxTime:G,totalTime:Q,matchRate:W}}},W1={measureMemoryUsage:async(Y,Z=100)=>{let $=[],X=[];if(globalThis.gc)globalThis.gc();let J=d.memoryUsage().heapUsed;for(let W=0;W<Z;W++){let K=await Y();$.push(K);let z=d.memoryUsage();if(X.push(z.heapUsed),W%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let Q=d.memoryUsage().heapUsed,_=X.reduce((W,K)=>W+K,0)/X.length,j=Math.max(...X),G=Q-J>1048576;return{averageHeapUsed:_,maxHeapUsed:j,memoryLeakDetected:G,results:$}},testRouteHandlerMemoryLeaks:async(Y,Z=1000)=>{if(globalThis.gc)globalThis.gc();let $=d.memoryUsage().heapUsed;for(let _=0;_<Z;_++){let j=H();if(await Y(j),_%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let X=d.memoryUsage().heapUsed,J=X-$;return{memoryLeakDetected:J>5242880,initialMemory:$,finalMemory:X,memoryGrowth:J}}},K1={rampUpTest:async(Y,Z,$)=>{let X=[],J=10,Q=$.testDuration/10,_=($.endConcurrency-$.startConcurrency)/10;for(let j=0;j<10;j++){let G=Math.round($.startConcurrency+_*j),K=await new e(Y,{duration:Q,concurrency:G,requestsPerSecond:G*2}).run(Z);X.push({concurrency:G,requestsPerSecond:K.requestsPerSecond,averageResponseTime:K.averageResponseTime,errorRate:K.failedRequests/K.totalRequests})}return X},spikeTest:async(Y,Z,$)=>{let J=await new e(Y,{duration:30000,concurrency:$.normalLoad}).run(Z),_=await new e(Y,{duration:$.spikeDuration,concurrency:$.spikeLoad}).run(Z),G=await new e(Y,{duration:30000,concurrency:$.normalLoad}).run(Z);return{normalPhase:J,spikePhase:_,recoveryPhase:G}}},z1={responseTimeWithin:(Y,Z)=>{if(Y>Z)throw Error(`Response time ${Y}ms exceeds maximum ${Z}ms`)},throughputAtLeast:(Y,Z)=>{if(Y<Z)throw Error(`Throughput ${Y} RPS is below minimum ${Z} RPS`)},errorRateBelow:(Y,Z)=>{if(Y>Z)throw Error(`Error rate ${(Y*100).toFixed(2)}% exceeds maximum ${(Z*100).toFixed(2)}%`)},memoryUsageWithin:(Y,Z)=>{if(Y>Z)throw Error(`Memory usage ${(Y/1024/1024).toFixed(2)}MB exceeds maximum ${(Z/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(Y,Z=5242880)=>{if(Y>Z)throw Error(`Potential memory leak detected: ${(Y/1024/1024).toFixed(2)}MB growth`)}};function L1(){return new w8}function U1(Y,Z){return new e(Y,Z)}var R8={getCurrentMemoryUsage:()=>{let Y=d.memoryUsage();return{heapUsed:Y.heapUsed,heapTotal:Y.heapTotal,external:Y.external,rss:Y.rss}},getCPUUsage:()=>{let Y=d.cpuUsage();return{user:Y.user,system:Y.system}},createMetricSnapshot:(Y)=>({responseTime:Y,memoryUsage:R8.getCurrentMemoryUsage(),cpuUsage:R8.getCPUUsage()}),formatResults:(Y)=>{return JSON.stringify(Y,null,2)}};class zZ{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(Y,Z){this.originalResponse=Y,this.status=Y.status,this.statusText=Y.statusText,this.headers=this.parseHeaders(Y.headers),this.cookies=this.parseCookies(Y.headers.get("set-cookie")),this.redirected=Y.redirected,this.url=Y.url,this.ok=Y.ok,this.type=Y.type,this.body=Z,this.text=typeof Z==="string"?Z:JSON.stringify(Z);try{this.json=typeof Z==="string"?JSON.parse(Z):Z}catch{this.json=null}}parseHeaders(Y){let Z={};return Y.forEach(($,X)=>{Z[X.toLowerCase()]=$}),Z}parseCookies(Y){if(!Y)return{};let Z={};return Y.split(",").forEach(($)=>{let[X]=$.trim().split(";"),[J,Q]=X.split("=");if(J&&Q)Z[J.trim()]=Q.trim()}),Z}expectStatus(Y){if(this.status!==Y)throw Error(`Expected status ${Y}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(Y,Z){let $=this.headers[Y.toLowerCase()];if($===void 0)throw Error(`Expected header '${Y}' to be present`);if(Z!==void 0&&$!==Z)throw Error(`Expected header '${Y}' to be '${Z}', got '${$}'`);return this}expectBody(Y){if(typeof Y==="string"){if(this.text!==Y)throw Error(`Expected body '${Y}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(Y))throw Error(`Expected body ${JSON.stringify(Y)}, got ${JSON.stringify(this.json)}`);return this}expectJson(Y){if(JSON.stringify(this.json)!==JSON.stringify(Y))throw Error(`Expected JSON ${JSON.stringify(Y)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(Y){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(Y).forEach(([Z,$])=>{let X=this.json[Z];if(typeof $==="object"&&$!==null&&typeof X==="object"&&X!==null){let J=JSON.stringify($),Q=JSON.stringify(X);if(J!==Q)throw Error(`Expected JSON property '${Z}' to be ${J}, got ${Q}`)}else if(X!==$)throw Error(`Expected JSON property '${Z}' to be '${$}', got '${X}'`)}),this}expectCookie(Y,Z){let $=this.cookies[Y];if($===void 0)throw Error(`Expected cookie '${Y}' to be present`);if(Z!==void 0&&$!==Z)throw Error(`Expected cookie '${Y}' to be '${Z}', got '${$}'`);return this}expectRedirect(Y){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(Y){let Z=this.headers.location;if(Z!==Y)throw Error(`Expected redirect to '${Y}', got '${Z}'`)}return this}expectValidationError(Y,Z){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(Y){let $=this.json?.errors||this.json?.message;if(!$||!$[Y])throw Error(`Expected validation error for field '${Y}'`);if(Z){if(!(Array.isArray($[Y])?$[Y]:[$[Y]]).includes(Z))throw Error(`Expected validation error message '${Z}' for field '${Y}'`)}}return this}expectContentType(Y){let Z=this.headers["content-type"];if(!Z||!Z.includes(Y))throw Error(`Expected content type '${Y}', got '${Z}'`);return this}expectBodyContains(Y){if(!this.text.includes(Y))throw Error(`Expected body to contain '${Y}'`);return this}expectBodyMatches(Y){if(!Y.test(this.text))throw Error(`Expected body to match pattern ${Y}`);return this}expectJsonStructure(Y){return this.validateStructure(this.json,Y,"root"),this}validateStructure(Y,Z,$){if(Z&&typeof Z==="object"&&Z.$$typeof)return;if(Array.isArray(Z)){if(!Array.isArray(Y))throw TypeError(`Expected ${$} to be an array`);if(Z.length>0&&Y.length>0)this.validateStructure(Y[0],Z[0],`${$}[0]`)}else if(typeof Z==="object"&&Z!==null){if(typeof Y!=="object"||Y===null)throw Error(`Expected ${$} to be an object`);Object.keys(Z).forEach((X)=>{if(!(X in Y))throw Error(`Expected ${$} to have property '${X}'`);this.validateStructure(Y[X],Z[X],`${$}.${X}`)})}}getOriginalResponse(){return this.originalResponse}toJSON(){return{status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,json:this.json,cookies:this.cookies,redirected:this.redirected,url:this.url,ok:this.ok,type:this.type}}}async function k8(Y){let Z=await Y.text();return new zZ(Y,Z)}function A1(Y=200,Z,$){let X=new Headers($);if(Z&&typeof Z==="object"&&!X.has("content-type"))X.set("content-type","application/json");let J=new Response(Z?typeof Z==="string"?Z:JSON.stringify(Z):null,{status:Y,headers:X});return new zZ(J,Z)}class gY{router;config;defaultHeaders;constructor(Y,Z={}){this.router=Y,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:($)=>$>=200&&$<300,...Z},this.defaultHeaders=Z.defaultHeaders||{}}async get(Y,Z={}){return this.request("GET",Y,Z)}async post(Y,Z={}){return this.request("POST",Y,Z)}async put(Y,Z={}){return this.request("PUT",Y,Z)}async patch(Y,Z={}){return this.request("PATCH",Y,Z)}async delete(Y,Z={}){return this.request("DELETE",Y,Z)}async options(Y,Z={}){return this.request("OPTIONS",Y,Z)}async head(Y,Z={}){return this.request("HEAD",Y,Z)}async request(Y,Z,$={}){let X={...this.defaultHeaders,...$.headers},J={...$,headers:X},Q=new w(Y,Z,J).build();try{let _=await this.handleRequest(Q);return await k8(_)}catch(_){throw Error(`Test request failed: ${_ instanceof Error?_.message:"Unknown error"}`)}}async handleRequest(Y){let Z=new URL(Y.url),$=this.findMatchingRoute(Y.method,Z.pathname);if(!$)return new Response("Not Found",{status:404});let{route:X,params:J}=$;Y.params={...Y.params,...J};try{return await this.executeMiddlewareChain(Y,X)||new Response("No response",{status:500})}catch(Q){return new Response(JSON.stringify({error:Q instanceof Error?Q.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(Y,Z){for(let $ of this.router.routes){if($.method.toLowerCase()!==Y.toLowerCase())continue;let X=this.matchPath($.path,Z);if(X!==null)return{route:$,params:X}}return null}matchPath(Y,Z){let $=Y.split("/"),X=Z.split("/");if($.length!==X.length)return null;let J={};for(let Q=0;Q<$.length;Q++){let _=$[Q],j=X[Q];if(_.startsWith(":")){let G=_.slice(1);J[G]=j}else if(_!==j)return null}return J}async executeMiddlewareChain(Y,Z){let $=[...this.router.globalMiddleware,...Z.middleware],X=0,J=async()=>{if(X<$.length){let _=$[X++];return await _(Y,J)}else return await this.executeHandler(Z.handler,Y)};return await J()||new Response("No response",{status:500})}async executeHandler(Y,Z){if(typeof Y==="function")return await Y(Z);else if(typeof Y==="string")throw TypeError(`String handlers not supported in test environment: ${Y}`);else if(typeof Y==="object"&&Y.handle)return await new Y().handle(Z);throw Error("Invalid handler type")}setDefaultHeaders(Y){return this.defaultHeaders={...this.defaultHeaders,...Y},this}auth(Y,Z="Bearer"){return this.defaultHeaders.Authorization=`${Z} ${Y}`,this}userAgent(Y){return this.defaultHeaders["User-Agent"]=Y,this}withConfig(Y){return new gY(this.router,{...this.config,...Y})}withHeaders(Y){return new gY(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...Y}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function yY(Y,Z){return new gY(Y,Z)}var O1={for:(Y,Z)=>yY(Y,Z),withConfig:(Y)=>(Z)=>yY(Z,Y),withAuth:(Y,Z="Bearer")=>($)=>yY($).auth(Y,Z),withHeaders:(Y)=>(Z)=>yY(Z).withHeaders(Y)};import{mock as l}from"bun:test";class k{messages=[];isConnected=!1;readyState=0;eventHandlers=new Map;constructor(){this.setupEventHandlers()}setupEventHandlers(){this.eventHandlers.set("open",[]),this.eventHandlers.set("message",[]),this.eventHandlers.set("close",[]),this.eventHandlers.set("error",[])}connect(){return this.isConnected=!0,this.readyState=1,this.emit("open",{type:"open"}),this}disconnect(Y=1000,Z="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:Y,reason:Z}),this}send(Y){if(!this.isConnected)throw Error("WebSocket is not connected");let Z={type:typeof Y==="string"?"text":"binary",data:Y,timestamp:Date.now()};return this.messages.push(Z),this}receive(Y){if(!this.isConnected)throw Error("WebSocket is not connected");let Z={type:typeof Y==="string"?"text":"binary",data:Y,timestamp:Date.now()};return this.emit("message",{type:"message",data:Y}),this}ping(Y){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:Y}),this}pong(Y){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:Y}),this}on(Y,Z){if(!this.eventHandlers.has(Y))this.eventHandlers.set(Y,[]);return this.eventHandlers.get(Y).push(Z),this}off(Y,Z){let $=this.eventHandlers.get(Y);if($){let X=$.indexOf(Z);if(X>-1)$.splice(X,1)}return this}emit(Y,Z){(this.eventHandlers.get(Y)||[]).forEach((X)=>X(Z))}getSentMessages(){return[...this.messages]}getMessagesByType(Y){return this.messages.filter((Z)=>Z.type===Y)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(Y)=>this.send(Y),close:(Y,Z)=>this.disconnect(Y,Z),ping:(Y)=>this.ping(Y),pong:(Y)=>this.pong(Y),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class v8{tester;_data;constructor(Y={}){this.tester=new k,this._data=Y}send(Y){this.tester.send(Y)}close(Y,Z){this.tester.disconnect(Y,Z)}ping(Y){this.tester.ping(Y)}pong(Y){this.tester.pong(Y)}publish(Y,Z){this.tester.send(Z)}subscribe(Y){}unsubscribe(Y){}isSubscribed(Y){return!0}cork(Y){Y()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(Y){this._data=Y}getTester(){return this.tester}}var B1={onOpen:()=>l(async(Y)=>{}),onMessage:(Y)=>l(async(Z,$)=>{if(Y)Z.send(Y)}),onClose:()=>l(async(Y,Z,$)=>{}),onError:()=>l(async(Y,Z)=>{}),echo:()=>l(async(Y,Z)=>{Y.send(Z)}),broadcast:(Y)=>l(async(Z,$)=>{Y.forEach((X)=>{if(X!==Z&&X.readyState===1)X.send($)})}),chatRoom:(Y)=>l(async(Z,$)=>{Z.publish(Y,$)})},N1={basicConnection:()=>{return new k().connect().send("Hello WebSocket").receive("Hello Client")},connectionFailure:()=>{let Y=new k;return Y.on("error",()=>{}),Y},messageBroadcast:(Y=3)=>{let Z=Array.from({length:Y},()=>new k().connect());return Z[0].send("Broadcast message"),Z.slice(1).forEach(($)=>$.receive("Broadcast message")),Z},pingPong:()=>{return new k().connect().ping().pong()},connectionTimeout:()=>{let Y=new k;return setTimeout(()=>{Y.disconnect(1006,"Connection timeout")},100),Y}},S1={isConnected:(Y)=>{if(!Y.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(Y)=>{if(Y.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(Y,Z)=>{if(!Y.getSentMessages().some((J)=>{if(typeof Z==="string"&&typeof J.data==="string")return J.data===Z;return J.data===Z}))throw Error("Expected message not found in sent messages")},messageCount:(Y,Z)=>{let $=Y.getSentMessages();if($.length!==Z)throw Error(`Expected ${Z} messages, but got ${$.length}`)},messageType:(Y,Z,$)=>{let X=Y.getSentMessages();if(Z>=X.length)throw Error(`Message at index ${Z} does not exist`);if(X[Z].type!==$)throw Error(`Expected message type '${$}', got '${X[Z].type}'`)},readyState:(Y,Z)=>{let $=Y.getState();if($.readyState!==Z)throw Error(`Expected ready state ${Z}, got ${$.readyState}`)}},C1={testThroughput:async(Y=1000,Z=1024)=>{let $=new k().connect(),X="x".repeat(Z),J=performance.now();for(let W=0;W<Y;W++)$.send(X);let _=performance.now()-J,j=Y/_*1000,G=_/Y;return{messagesPerSecond:j,totalTime:_,averageLatency:G}},testConcurrentConnections:async(Y=100)=>{let Z={successfulConnections:0,failedConnections:0,averageConnectionTime:0},$=[],X=Array.from({length:Y},async()=>{let J=performance.now();try{new k().connect();let _=performance.now();$.push(_-J),Z.successfulConnections++}catch(Q){console.error("WebSocket connection failed:",Q),Z.failedConnections++}});return await Promise.all(X),Z.averageConnectionTime=$.length>0?$.reduce((J,Q)=>J+Q,0)/$.length:0,Z}};function M1(){return new k}function T1(Y){return new v8(Y)}var P1={createClients:(Y)=>{return Array.from({length:Y},()=>new k().connect())},withLatency:(Y,Z)=>{let $=Y.send.bind(Y);return Y.send=(X)=>{return setTimeout(()=>$(X),Z),Y},Y},withPacketLoss:(Y,Z)=>{let $=Y.send.bind(Y);return Y.send=(X)=>{if(Math.random()>Z)$(X);return Y},Y},*messageGenerator(Y,Z="Message"){for(let $=1;$<=Y;$++)yield`${Z} ${$}`}};export{P1 as wsTestUtils,N1 as wsTestScenarios,C1 as wsPerformance,B1 as wsHandlerMocks,S1 as wsAssertions,T as wrapResponse,P7 as verifySignature,i6 as validatePath,n4 as validate,Q$ as url,u6 as toActionPath,N0 as testRequest,l0 as testMiddlewareChain,u0 as testMiddleware,h0 as testFiles,O1 as testClient,K1 as stressTests,i0 as spyOnMiddleware,d7 as singleFileUpload,T7 as signRequest,S9 as shouldCompress,NY as setCurrentRequest,h$ as setContainer,LX as session,GX as securitySuite,_X as security,X1 as scopedBindingHelpers,BY as runWithRequest,p4 as rule,A$ as router,Y1 as routeModelHelpers,o as routeCacheManager,K6 as responseBuilder,E as response,rY as resolveViewPath,GY as resolveHandler,JX as requestTracer,M7 as requestSigning,zX as requestId,F9 as request,g as registerNamedRoute,dZ as rateLimitRegistry,F7 as rateLimit,tZ as processHtmlTemplate,R8 as performanceUtils,$X as performanceMonitor,YX as performanceDashboard,z1 as performanceAssertions,r7 as performanceAlerting,C9 as peekBody,t as parseThrottleString,D7 as oauth2Auth,_Y as normalizePath,N9 as negotiateEncoding,l7 as multipleFileUpload,r0 as modelMocks,d0 as mockMiddleware,C as middlewareGroups,AX as middleware,W1 as memoryTests,x as matchPath,V7 as jwtAuth,KX as jsonBody,f as joinPaths,d6 as isRouteHandler,FZ as isCompressible,_$ as isActionClass,a7 as inputValidation,SY as injectQueryPreservationScript,i7 as imageUpload,c4 as globalValidator,x9 as globalMiddlewarePipeline,X$ as getNamedRoutes,tY as getNamedRoutePath,HZ as getCurrentRequest,g$ as getContainer,j7 as getConfig,q7 as generateSessionId,c9 as generateQueryPreservationScript,f0 as fileUploadScenarios,q0 as fileUploadMocks,y0 as fileUploadAssertions,u7 as fileUpload,aZ as fileExists,xY as extractParamNames,K7 as extractBearerToken,W7 as extractBasicAuth,z7 as extractApiKey,H9 as enableRequestContext,n7 as documentUpload,E6 as defaultQueryPreservationConfig,_7 as defaultConfig,c7 as ddosProtection,UX as csrf,M1 as createWebSocketTester,fY as createValidationMiddleware,k8 as createTestResponse,yY as createTestClient,f6 as createSubdomainMiddleware,R0 as createSessionTester,k7 as createSessionStore,pZ as createRouteCacheMiddleware,a as createRateLimitMiddleware,L1 as createPerformanceTester,l6 as createPathRegex,$1 as createModelResolverTester,Z1 as createModelBindingTester,T1 as createMockServerWebSocket,A1 as createMockResponse,H as createMockRequest,n0 as createMiddlewareSpy,U1 as createLoadTester,x0 as createJWTTester,I$ as createHandlerResolver,o4 as createFluentRouter,g0 as createFileUploadTester,QZ as createEnhancementMiddleware,c$ as createContainer,b0 as createAuthTester,WX as cors,g7 as contentSecurityPolicy,e0 as constraintHelpers,G7 as config,BZ as compressResponse,J$ as clearNamedRoutes,I6 as buildUrlWithPreservedParams,G1 as benchmarkTests,s0 as benchmarkMiddleware,U7 as bearerAuth,L7 as basicAuth,T0 as authMocks,P0 as authHelpers,VX as auth,H$ as applyRequestEnhancements,nY as appendVary,A7 as apiKeyAuth,k as WebSocketTester,qY as Validator,JZ as ValidationRuleBuilder,C8 as ValidationMiddlewareBuilder,m4 as ValidationHelpers,S8 as ValidationFluentRouter,Z$ as ThrottleFactory,zZ as TestResponseWrapper,w as TestRequestBuilder,gY as TestClient,y6 as SubdomainUtils,aY as SubdomainRouter,g6 as SubdomainPatterns,T9 as SkipConditions,N7 as SignatureError,WZ as SessionTester,v7 as SessionManager,f7 as Session,jX as SecuritySuite,QX as Security,V$ as RouterUtils,O as Router,s4 as RouteHelpers,iZ as RouteGroupBuilder,U$ as RouteFactory,cZ as RouteCacheManager,hZ as RouteCacheKeyGenerator,mZ as RouteCacheFactory,S as RouteBuilder,NZ as ResponseBuilder,XX as RequestTracer,C7 as RequestSigning,B7 as RequestId,R7 as RedisSessionStore,bY as RateLimiter,v6 as RateLimitUtils,uZ as RateLimitRegistry,H7 as RateLimit,w8 as PerformanceTester,ZX as PerformanceMonitor,e7 as PerformanceDashboard,t7 as PerformanceAlerting,VZ as OAuth2Helper,x8 as ModelResolverTester,b8 as ModelBindingTester,w$ as MockUserClass,v8 as MockServerWebSocket,k$ as MockPostClass,T8 as MiddlewareTester,sY as MiddlewarePipeline,N8 as MiddlewareHelpers,_Z as MiddlewareGroupRegistry,b9 as MiddlewareFactory,P8 as MiddlewareChainTester,b7 as MemorySessionStore,e as LoadTester,O7 as JsonBody,GZ as JWTTester,LZ as JWT,o7 as InputValidation,S7 as InMemoryNonceStore,s7 as Helmet,R$ as GenericMockModel,jY as FluentRouter,D as FluentRouteBuilder,KZ as FileValidationTester,c as FileUploadTester,m7 as FileUpload,x7 as FileSessionStore,p7 as FileSecurity,OZ as Errors,p$ as EnvironmentManager,a4 as EnhancementPresets,b as DomainMatcher,lZ as DomainGroupBuilder,QY as DomainGroup,P9 as Dependencies,u$ as DefaultServiceProviderManager,w7 as DatabaseSessionStore,h4 as DatabaseRules,B9 as DEFAULT_COMPRESSION,h7 as DDoSProtection,I7 as Csrf,E7 as Cors,m$ as ContextualContainer,y7 as ContentSecurityPolicy,f$ as Container,R6 as CacheInvalidation,P$ as BuiltInRules,y$ as BindingBuilder,UY as AuthTester,m8 as Auth,UZ as ApiKeyManager};
|
|
105
|
+
`,new Response(n,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(e="healthy",t={})=>{let r=e==="healthy"?200:e==="degraded"?200:503,n={status:e,timestamp:new Date().toISOString(),checks:t,uptime:Hs.uptime?.()||0};return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})}};function As(){Object.entries(A).forEach(([e,t])=>{he.macro(e,t)})}As();var qs=/^[A-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?(?:\.[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?)*\.[A-Z]{2,}$/i,Os={required:{name:"required",validate:(e)=>{if(e===null||e===void 0)return!1;if(typeof e==="string")return e.trim().length>0;if(Array.isArray(e))return e.length>0;if(typeof e==="object")return Object.keys(e).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(e)=>typeof e==="string",message:"The :field field must be a string."},number:{name:"number",validate:(e)=>typeof e==="number"&&!Number.isNaN(e),message:"The :field field must be a number."},integer:{name:"integer",validate:(e)=>Number.isInteger(Number(e)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(e)=>typeof e==="boolean"||e==="true"||e==="false"||e==="1"||e==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(e)=>typeof e==="string"&&qs.test(e),message:"The :field field must be a valid email address."},url:{name:"url",validate:(e)=>{try{let t=new URL(e);return Boolean(t)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(e,t)=>{let r=Number(t[0]);if(typeof e==="string")return e.length>=r;if(typeof e==="number")return e>=r;if(Array.isArray(e))return e.length>=r;return!1},message:(e,t)=>`The ${e} field must be at least ${t[0]} characters.`},max:{name:"max",validate:(e,t)=>{let r=Number(t[0]);if(typeof e==="string")return e.length<=r;if(typeof e==="number")return e<=r;if(Array.isArray(e))return e.length<=r;return!1},message:(e,t)=>`The ${e} field must not exceed ${t[0]} characters.`},between:{name:"between",validate:(e,t)=>{let r=Number(t[0]),n=Number(t[1]);if(typeof e==="string")return e.length>=r&&e.length<=n;if(typeof e==="number")return e>=r&&e<=n;if(Array.isArray(e))return e.length>=r&&e.length<=n;return!1},message:(e,t)=>`The ${e} field must be between ${t[0]} and ${t[1]}.`},in:{name:"in",validate:(e,t)=>t.includes(String(e)),message:(e,t)=>`The ${e} field must be one of: ${t.join(", ")}.`},notIn:{name:"not_in",validate:(e,t)=>!t.includes(String(e)),message:(e,t)=>`The ${e} field must not be one of: ${t.join(", ")}.`},regex:{name:"regex",validate:(e,t)=>{let r=new RegExp(t[0]);return typeof e==="string"&&r.test(e)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(e)=>typeof e==="string"&&/^[a-z]+$/i.test(e),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(e)=>typeof e==="string"&&/^[a-z0-9]+$/i.test(e),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(e)=>typeof e==="string"&&/^[\w-]+$/.test(e),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(e)=>{let t=new Date(e);return!Number.isNaN(t.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(e,t)=>{let r=new Date(e),n=new Date(t[0]);return!Number.isNaN(r.getTime())&&!Number.isNaN(n.getTime())&&r>n},message:(e,t)=>`The ${e} field must be after ${t[0]}.`},dateBefore:{name:"before",validate:(e,t)=>{let r=new Date(e),n=new Date(t[0]);return!Number.isNaN(r.getTime())&&!Number.isNaN(n.getTime())&&r<n},message:(e,t)=>`The ${e} field must be before ${t[0]}.`},confirmed:{name:"confirmed",validate:(e,t,r,n)=>{let s=t[0]||`${r}_confirmation`;return e===n[s]},message:"The :field confirmation does not match."},same:{name:"same",validate:(e,t,r,n)=>e===n[t[0]],message:(e,t)=>`The ${e} field must match ${t[0]}.`},different:{name:"different",validate:(e,t,r,n)=>e!==n[t[0]],message:(e,t)=>`The ${e} field must be different from ${t[0]}.`},json:{name:"json",validate:(e)=>{try{return JSON.parse(e),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(e)=>typeof e==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e),message:"The :field field must be a valid UUID."},array:{name:"array",validate:(e)=>Array.isArray(e),message:"The :field field must be an array."},object:{name:"object",validate:(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),message:"The :field field must be an object."}},Qo={unique:{name:"unique",validate:async(e,t)=>(console.warn('Database validation rule "unique" requires external implementation'),!0),message:"The :field field must be unique."},exists:{name:"exists",validate:async(e,t)=>(console.warn('Database validation rule "exists" requires external implementation'),!0),message:"The selected :field is invalid."}};class De{rules={};config;constructor(e={}){this.config={stopOnFirstFailure:!1,bail:!1,...e},this.registerRules(Os)}registerRule(e){this.rules[e.name]=e}registerRules(e){Object.values(e).forEach((t)=>this.registerRule(t))}parseRuleString(e){return e.split("|").map((t)=>{let[r,...n]=t.split(":"),s=n.length>0?n.join(":").split(","):[];return{name:r.trim(),parameters:s}})}async validate(e,t){let r={};for(let[n,s]of Object.entries(t)){let i=[],o=this.getNestedValue(e,n),a=typeof s==="string"?this.parseRuleString(s):s.map((u)=>({name:u.name,parameters:[]}));for(let{name:u,parameters:c}of a){let l=this.rules[u];if(!l){console.warn(`Validation rule "${u}" not found`);continue}try{if(!await l.validate(o,c,n,e)){let p=this.formatErrorMessage(l,n,c);if(i.push(p),this.config.stopOnFirstFailure||this.config.bail)break}}catch(d){console.error(`Error validating rule "${u}" for field "${n}":`,d),i.push(`Validation error for ${n}`)}}if(i.length>0)r[n]=i}return r}async validateOrFail(e,t){let r=await this.validate(e,t);if(Object.keys(r).length>0)throw new ne("Validation failed",r)}getNestedValue(e,t){return t.split(".").reduce((r,n)=>r&&r[n]!==void 0?r[n]:void 0,e)}formatErrorMessage(e,t,r){let n=this.config.customMessages?.[`${t}.${e.name}`]||this.config.customMessages?.[e.name];if(n)return this.replacePlaceholders(n,t,r);let s=typeof e.message==="function"?e.message(t,r):e.message;return this.replacePlaceholders(s,t,r)}replacePlaceholders(e,t,r){let n=this.config.customAttributes?.[t]||t.replace(/_/g," ");return e.replace(/:field/g,n).replace(/:attribute/g,n).replace(/:value/g,r[0]||"").replace(/:other/g,r[1]||"")}}var Zo=new De;function Fe(e,t){let r=new De(t);return async(n,s)=>{try{let i={...n.query,...n.params,...n.jsonBody||{},...n.formBody||{}};return await r.validateOrFail(i,e),n.validated=i,await s()}catch(i){if(i instanceof ne)throw i;throw new ne("Validation error occurred")}}}class it{rules=[];required(){return this.rules.push("required"),this}string(){return this.rules.push("string"),this}number(){return this.rules.push("number"),this}integer(){return this.rules.push("integer"),this}boolean(){return this.rules.push("boolean"),this}email(){return this.rules.push("email"),this}url(){return this.rules.push("url"),this}min(e){return this.rules.push(`min:${e}`),this}max(e){return this.rules.push(`max:${e}`),this}between(e,t){return this.rules.push(`between:${e},${t}`),this}in(...e){return this.rules.push(`in:${e.join(",")}`),this}notIn(...e){return this.rules.push(`not_in:${e.join(",")}`),this}regex(e){return this.rules.push(`regex:${e}`),this}alpha(){return this.rules.push("alpha"),this}alphaNum(){return this.rules.push("alpha_num"),this}alphaDash(){return this.rules.push("alpha_dash"),this}date(){return this.rules.push("date"),this}after(e){return this.rules.push(`after:${e}`),this}before(e){return this.rules.push(`before:${e}`),this}confirmed(e){return this.rules.push(e?`confirmed:${e}`:"confirmed"),this}same(e){return this.rules.push(`same:${e}`),this}different(e){return this.rules.push(`different:${e}`),this}json(){return this.rules.push("json"),this}uuid(){return this.rules.push("uuid"),this}array(){return this.rules.push("array"),this}object(){return this.rules.push("object"),this}unique(e,t){return this.rules.push(t?`unique:${e},${t}`:`unique:${e}`),this}exists(e,t){return this.rules.push(t?`exists:${e},${t}`:`exists:${e}`),this}custom(e,...t){return this.rules.push(t.length>0?`${e}:${t.join(",")}`:e),this}build(){return this.rules.join("|")}}function Yo(){return new it}var ea={rules(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n instanceof it?n.build():n;return t},async validateValue(e,t,r="value"){return(await new De().validate({[r]:e},{[r]:t}))[r]||[]},async passes(e,t){return(await this.validateValue(e,t)).length===0},async fails(e,t){return!await this.passes(e,t)}};class C{method;path;handler;validationRules;validatorConfig;constructor(e,t,r){this.method=e;this.path=t;this.handler=r}validate(e,t){return this.validationRules=e,this.validatorConfig=t,this}build(){let e=[];if(this.validationRules)e.push(Fe(this.validationRules,this.validatorConfig));return e.push(async(t,r)=>(x.applyMacros(t),await r()||new Response("Not Found",{status:404}))),{method:this.method,path:this.path,handler:this.handler,middleware:e.length>0?e:void 0}}}class Er{routes=[];get(e,t){return new C("GET",e,t)}post(e,t){return new C("POST",e,t)}put(e,t){return new C("PUT",e,t)}patch(e,t){return new C("PATCH",e,t)}delete(e,t){return new C("DELETE",e,t)}register(e){let t=e.build();this.routes.push(t)}getRoutes(){return this.routes}}function ot(){return async(e,t)=>(x.applyMacros(e),e.startTime=Date.now(),await t())}class Mr{rules={};config={};field(e,t){return this.rules[e]=t,this}fields(e){return Object.assign(this.rules,e),this}configure(e){return Object.assign(this.config,e),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(e){return this.config.customMessages=e,this}attributes(e){return this.config.customAttributes=e,this}build(){return Fe(this.rules,this.config)}}function ia(){return new Mr}var oa={validated:(e,t,r,n,s)=>new C(e,t,r).validate(n,s),apiRoute:(e,t,r,n)=>{let s=new C(e,t,async(i)=>{if(!i.expectsJson())return he.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return await r(i)});if(n)s.validate(n);return s},resourceRoute:(e,t,r)=>{let n=[];if(t.index)n.push(new C("GET",e,t.index));if(t.show)n.push(new C("GET",`${e}/{id}`,t.show));if(t.store){let s=new C("POST",e,t.store);if(r?.store)s.validate(r.store);n.push(s)}if(t.update){let s=new C("PUT",`${e}/{id}`,t.update);if(r?.update)s.validate(r.update);n.push(s)}if(t.destroy)n.push(new C("DELETE",`${e}/{id}`,t.destroy));return n}};function aa(){return new Er}var Pr={compose:(...e)=>async(t,r)=>{let n=0,s=async()=>{if(n>=e.length)return await r();let i=e[n++];return await i(t,s)};return await s()},when:(e,t)=>async(r,n)=>{if(e(r))return await t(r,n);return await n()},unless:(e,t)=>Pr.when((r)=>!e(r),t),group:(e)=>Pr.compose(...e)},ua={api:()=>[ot(),async(e,t)=>{try{let r=await t(),n=new Headers(r.headers);return n.set("X-API-Version","1.0"),n.set("X-Response-Time",new Date().toISOString()),new Response(r.body,{status:r.status,statusText:r.statusText,headers:n})}catch(r){return console.error(r),he.callMacro("error","Internal server error",void 0,500)}}],web:()=>[ot(),async(e,t)=>(e.session={},await t())],validation:(e,t)=>[ot(),Fe(e,t)]};sr(w);ir(w);gr(w);pr(w);ur(w);xr(w);vr(w);Dt(w);nr(w);Tr(w);hr(w);dr(w);Bt(w);At(w);class at{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(e,t){return this.groups.set(e,[...t]),this}extend(e,t){let r=this.groups.get(e)||[];return this.groups.set(e,[...r,...t]),this}prepend(e,t){let r=this.groups.get(e)||[];return this.groups.set(e,[...t,...r]),this}get(e){return this.groups.get(e)||[]}has(e){return this.groups.has(e)}remove(e){return this.groups.delete(e),this}resolve(e){if(typeof e==="function")return[e];if(this.groups.has(e))return this.get(e);return[e]}resolveAll(e){let t=[];for(let r of e)t.push(...this.resolve(r));return t}pushGlobal(...e){return this.globalMiddleware.push(...e),this}prependGlobal(...e){return this.globalMiddleware.unshift(...e),this}removeGlobal(e){return this.globalMiddleware=this.globalMiddleware.filter((t)=>typeof t==="string"?t!==e:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(e,t){return this.middlewarePriority.set(e,t),this}sortByPriority(e){return[...e].sort((t,r)=>{let n=typeof t==="string"?t.split(":")[0]:"",s=typeof r==="string"?r.split(":")[0]:"",i=this.middlewarePriority.get(n)??100,o=this.middlewarePriority.get(s)??100;return i-o})}filter(e,t){if(t.only&&t.only.length>0)return e.filter((r)=>{if(typeof r==="string"){let n=r.split(":")[0];return t.only.includes(n)}return!1});if(t.except&&t.except.length>0)return e.filter((r)=>{if(typeof r==="string"){let n=r.split(":")[0];return!t.except.includes(n)}return!0});return e}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var P=new at;P.define("web",["session","csrf","cors"]);P.define("api",["throttle:60,1","cors"]);P.setPriority("session",10);P.setPriority("cors",20);P.setPriority("csrf",30);P.setPriority("auth",40);P.setPriority("throttle",50);P.setPriority("role",60);P.setPriority("permission",60);P.setPriority("can",70);P.setPriority("abilities",70);P.setPriority("verified",80);import{mock as ut}from"bun:test";function Sr(e){let t={...e};return{get:(r)=>t[r],set:(r,n,s)=>{t[r]=n},delete:(r,n)=>{delete t[r]},getAll:()=>({...t})}}class q{request;url;constructor(e,t,r={}){if(this.url=new URL(t,"http://localhost:3000"),r.query)Object.entries(r.query).forEach(([n,s])=>{if(Array.isArray(s))s.forEach((i)=>this.url.searchParams.append(n,i));else this.url.searchParams.set(n,s)});this.request={method:e,url:this.url.toString(),headers:new Headers(r.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:r.body&&typeof r.body==="object"?r.body:void 0,files:r.files?this.convertTestFiles(r.files):void 0,session:r.session,user:r.user,context:r.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:Sr(r.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody(r.body)}parseQuery(e){let t={};for(let[r,n]of e.entries())if(t[r])if(Array.isArray(t[r]))t[r].push(n);else t[r]=[t[r],n];else t[r]=n;return t}convertTestFiles(e){return e.map((t)=>({fieldName:t.fieldName,originalName:t.filename,filename:`test-${Date.now()}-${t.filename}`,path:`/tmp/test-uploads/${t.filename}`,size:t.content instanceof ArrayBuffer?t.content.byteLength:new TextEncoder().encode(t.content.toString()).length,mimetype:t.mimetype||"application/octet-stream",buffer:t.content instanceof ArrayBuffer?t.content:new TextEncoder().encode(t.content.toString()).buffer}))}handleBody(e){if(!e)return;let t=this.request.headers?.get("content-type")||"";if(t.includes("application/json")||typeof e==="object"){if(this.request.jsonBody=e,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(t.includes("application/x-www-form-urlencoded"))this.request.formBody=e}params(e){return this.request.params={...this.request.params,...e},this}headers(e){return Object.entries(e).forEach(([t,r])=>{this.request.headers?.set(t,r)}),this}auth(e,t="Bearer"){return this.request.headers?.set("Authorization",`${t} ${e}`),this}user(e){return this.request.user=e,this}session(e){return this.request.session=e,this}cookies(e){let t=this.request.cookies?.getAll()||{};return this.request.cookies=Sr({...t,...e}),this}context(e){return this.request.context={...this.request.context,...e},this}json(e){return this.request.jsonBody=e,this.request.headers?.set("content-type","application/json"),this}form(e){return this.request.formBody=e,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(e){return this.request.files=this.convertTestFiles(e),this.request.headers?.set("content-type","multipart/form-data"),this}ip(e){return this.request.ip=e,this}userAgent(e){return this.request.userAgent=()=>e,this.request.headers?.set("User-Agent",e),this}csrf(e){return this.request.csrfToken=e,this.request.headers?.set("X-CSRF-Token",e),this}build(){let e={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)e.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let n=new FormData;Object.entries(this.request.formBody).forEach(([s,i])=>{n.append(s,i)}),e.body=n}let t=new Request(this.url.toString(),e);return Object.assign(t,{params:this.request.params||{},query:this.request.query||{},jsonBody:this.request.jsonBody,formBody:this.request.formBody,files:this.request.files,session:this.request.session,user:this.request.user,context:this.request.context||{},requestId:this.request.requestId,ip:this.request.ip,userAgent:this.request.userAgent,cookies:this.request.cookies||{},startTime:this.request.startTime,traceId:this.request.traceId,spanId:this.request.spanId})}}var Ba={get:(e,t)=>new q("GET",e,t),post:(e,t)=>new q("POST",e,t),put:(e,t)=>new q("PUT",e,t),patch:(e,t)=>new q("PATCH",e,t),delete:(e,t)=>new q("DELETE",e,t),options:(e,t)=>new q("OPTIONS",e,t),head:(e,t)=>new q("HEAD",e,t)};function b(e="GET",t="/",r={}){return new q(e,t,r).build()}function $s(e){let t={...e};return{get:(r)=>t[r],set:(r,n,s)=>{t[r]=n},delete:(r,n)=>{delete t[r]},getAll:()=>({...t})}}class ge{request;constructor(e){this.request=e||b()}as(e){return this.request.user=e,this}withJWT(e,t="Bearer"){let r=new Headers(this.request.headers);return r.set("Authorization",`${t} ${e}`),this.request={...this.request,headers:r},this}withSession(e){return this.request.session=e,this}withApiKey(e,t="X-API-Key"){let r=new Headers(this.request.headers);return r.set(t,e),this.request={...this.request,headers:r},this}withBasicAuth(e,t){let r=btoa(`${e}:${t}`),n=new Headers(this.request.headers);return n.set("Authorization",`Basic ${r}`),this.request={...this.request,headers:n},this}withAuthCookies(e){let t=this.request.cookies?.getAll()||{};return this.request.cookies=$s({...t,...e}),this}unauthenticated(){if(this.request.user=void 0,this.request.session=void 0,this.request.headers)this.request.headers.delete("Authorization");return this}getRequest(){return this.request}}class ct{options;constructor(e={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...e}}generateToken(e={}){let t={alg:this.options.algorithm,typ:"JWT",...this.options.headers},r=Math.floor(Date.now()/1000),n=r+this.parseExpiresIn(this.options.expiresIn||"1h"),s={iat:r,exp:n,...this.options.payload,...e},i=btoa(JSON.stringify(t)).replace(/=/g,""),o=btoa(JSON.stringify(s)).replace(/=/g,""),a=btoa(`${i}.${o}.${this.options.secret}`).replace(/=/g,"");return`${i}.${o}.${a}`}generateExpiredToken(e={}){let t={alg:this.options.algorithm,typ:"JWT"},r=Math.floor(Date.now()/1000),n={iat:r-7200,exp:r-3600,...e},s=btoa(JSON.stringify(t)).replace(/=/g,""),i=btoa(JSON.stringify(n)).replace(/=/g,""),o=btoa(`${s}.${i}.${this.options.secret}`).replace(/=/g,"");return`${s}.${i}.${o}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(e){let[t,r,n]=e.split(".");return{header:JSON.parse(atob(t)),payload:JSON.parse(atob(r)),signature:n}}parseExpiresIn(e){let t=e.match(/^(\d+)([smhd])$/);if(!t)return 3600;let r=Number.parseInt(t[1]);switch(t[2]){case"s":return r;case"m":return r*60;case"h":return r*3600;case"d":return r*86400;default:return 3600}}}class lt{options;constructor(e={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...e}}createSession(e={}){let t={...this.options.data,...e},r=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:t,cookie:r}}generateSessionCookie(e="session"){let t=[];if(this.options.maxAge)t.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)t.push("Secure");if(this.options.httpOnly)t.push("HttpOnly");let r=t.length>0?`; ${t.join("; ")}`:"";return`${e}=${this.options.sessionId}${r}`}createExpiredSession(){let e={...this.options,maxAge:-1};return new lt(e).createSession()}}var Na={user:(e={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...e}),adminUser:(e={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...e}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(e)=>ut(async(t,r)=>{if(e)return t.user=e,await r();return new Response("Unauthorized",{status:401})}),roleMiddleware:(e)=>ut(async(t,r)=>{if(!t.user)return new Response("Unauthorized",{status:401});let n=t.user.roles||[];if(!e.some((i)=>n.includes(i)))return new Response("Forbidden",{status:403});return await r()}),permissionMiddleware:(e)=>ut(async(t,r)=>{if(!t.user)return new Response("Unauthorized",{status:401});let n=t.user.permissions||[];if(!e.every((i)=>n.includes(i)))return new Response("Forbidden",{status:403});return await r()})},Ia={authenticatedRequest:(e,t)=>new ge(t).as(e).getRequest(),jwtRequest:(e={},t)=>{let n=new ct().generateToken(e);return new ge(t).withJWT(n).getRequest()},sessionRequest:(e={},t)=>new ge(t).withSession(e).getRequest(),verifyJWTStructure:(e)=>{let t=e.split(".");return t.length===3&&t.every((r)=>r.length>0)},extractJWTPayload:(e)=>{try{let[,t]=e.split(".");return JSON.parse(atob(t))}catch{return null}}};function _a(e){return new ge(e)}function ja(e){return new ct(e)}function La(e){return new lt(e)}import{mock as z}from"bun:test";class _{request;files;constructor(e){this.request=e||b(),this.files=[]}addFile(e){let t={fieldName:e.fieldName,originalName:e.filename,filename:`test-${Date.now()}-${e.filename}`,path:`/tmp/test-uploads/${e.filename}`,size:e.content instanceof ArrayBuffer?e.content.byteLength:new TextEncoder().encode(e.content.toString()).length,mimetype:e.mimetype||this.detectMimeType(e.filename),buffer:e.content instanceof ArrayBuffer?e.content:new TextEncoder().encode(e.content.toString()).buffer};return this.files.push(t),this.request.files=[...this.request.files||[],t],this}addFiles(e){return e.forEach((t)=>this.addFile(t)),this}addImage(e,t="test.jpg",r=1024){let n=new ArrayBuffer(r);return this.addFile({fieldName:e,filename:t,content:n,mimetype:"image/jpeg"})}addDocument(e,t="test.pdf",r="Test PDF content"){return this.addFile({fieldName:e,filename:t,content:r,mimetype:"application/pdf"})}addTextFile(e,t="test.txt",r="Test content"){return this.addFile({fieldName:e,filename:t,content:r,mimetype:"text/plain"})}addLargeFile(e,t=10){let r=t*1024*1024,n=new ArrayBuffer(r);return this.addFile({fieldName:e,filename:`large-file-${t}mb.bin`,content:n,mimetype:"application/octet-stream"})}addInvalidFile(e,t="malicious.exe"){return this.addFile({fieldName:e,filename:t,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(e){return this.request.formBody={...this.request.formBody,...e},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json",xml:"application/xml",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}[t||""]||"application/octet-stream"}}class dt{static testFileSize(e,t){return e.size<=t}static testFileType(e,t){return t.includes(e.mimetype)}static testFileExtension(e,t){let r=e.originalName.split(".").pop()?.toLowerCase();return r?t.includes(r):!1}static testFilename(e){let t=e.originalName;if(t.includes("..")||t.includes("/")||t.includes("\\"))return!1;if(t.includes("\x00"))return!1;let r=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],n=t.split(".")[0].toUpperCase();if(r.includes(n))return!1;return!0}static testImageFile(e){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(e.mimetype)}static testDocumentFile(e){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(e.mimetype)}}var Va={validationMiddleware:(e={})=>z(async(r,n)=>{let s=r.files||[],{maxSize:i=5242880,allowedTypes:o=[],maxFiles:a=10}=e;if(s.length>a)return new Response(`Too many files. Maximum ${a} allowed.`,{status:400});for(let u of s){if(u.size>i)return new Response(`File ${u.originalName} is too large. Maximum size: ${i} bytes.`,{status:400});if(o.length>0&&!o.includes(u.mimetype))return new Response(`File type ${u.mimetype} not allowed.`,{status:400});if(!dt.testFilename(u))return new Response(`Invalid filename: ${u.originalName}`,{status:400})}return await n()}),imageUploadMiddleware:(e={})=>z(async(r,n)=>{let s=r.files||[],{maxSize:i=2097152}=e;for(let o of s){if(!dt.testImageFile(o))return new Response(`File ${o.originalName} is not a valid image.`,{status:400});if(o.size>i)return new Response(`Image ${o.originalName} is too large.`,{status:400})}return await n()}),storageService:{store:z(async(e,t)=>t||`/uploads/${Date.now()}-${e.filename}`),delete:z(async(e)=>{}),exists:z(async(e)=>!e.includes("not-found")),getUrl:z((e)=>`https://example.com/storage${e}`)},virusScanner:{scan:z(async(e)=>{if(e.originalName.endsWith(".exe")||e.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},Ja={singleFileUpload:()=>new _().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"}),multipleFileUpload:()=>new _().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"}),fileSizeExceeded:()=>new _().addLargeFile("file",50),invalidFileType:()=>new _().addInvalidFile("file","virus.exe"),emptyFileUpload:()=>new _().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"}),maliciousFilename:()=>new _().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})},Ka={hasFiles:(e,t)=>{let r=e.files||[];if(t!==void 0&&r.length!==t)throw Error(`Expected ${t} files, but got ${r.length}`);if(r.length===0)throw Error("Expected request to have files")},hasFileWithField:(e,t)=>{if(!(e.files||[]).some((s)=>s.fieldName===t))throw Error(`Expected file with field name '${t}'`)},fileMatches:(e,t)=>{Object.entries(t).forEach(([r,n])=>{if(e[r]!==n)throw Error(`Expected file.${r} to be '${n}', got '${e[r]}'`)})},fileSizeWithinLimit:(e,t)=>{if(e.size>t)throw Error(`File size ${e.size} exceeds limit of ${t}`)},fileTypeAllowed:(e,t)=>{if(!t.includes(e.mimetype))throw Error(`File type '${e.mimetype}' is not allowed. Allowed types: ${t.join(", ")}`)}};function Xa(e){return new _(e)}var Qa={image:(e="image",t="test.jpg")=>({fieldName:e,filename:t,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(e="document",t="test.pdf")=>({fieldName:e,filename:t,content:"PDF content",mimetype:"application/pdf"}),text:(e="file",t="test.txt",r="Test content")=>({fieldName:e,filename:t,content:r,mimetype:"text/plain"}),large:(e="file",t=10)=>({fieldName:e,filename:`large-${t}mb.bin`,content:new ArrayBuffer(t*1024*1024),mimetype:"application/octet-stream"}),malicious:(e="file")=>({fieldName:e,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as v,spyOn as Bs}from"bun:test";class kr{middleware;context;constructor(e){this.middleware=e,this.context=this.createContext()}createContext(){let e=b(),t=v(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:e,next:t}}withRequest(e){return this.context.request=e,this}withNext(e){return this.context.next=v(e),this}withError(e){return this.context.error=e,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(e){throw this.context.error=e,e}}expectNextCalled(e=1){if(this.context.next.mock.calls.length!==e)throw Error(`Expected next to be called ${e} times, but was called ${this.context.next.mock.calls.length} times`);return this}expectNextNotCalled(){if(this.context.next.mock.calls.length>0)throw Error(`Expected next not to be called, but was called ${this.context.next.mock.calls.length} times`);return this}expectError(e){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(e&&this.context.error.message!==e)throw Error(`Expected error message "${e}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function tu(e){return new kr(e)}var ru={passthrough:()=>v(async(e,t)=>await t()),response:(e=200,t)=>v(async()=>new Response(t?JSON.stringify(t):null,{status:e})),error:(e="Middleware error")=>v(async()=>{throw Error(e)}),modifyRequest:(e)=>v(async(t,r)=>(e(t),await r())),addContext:(e,t)=>v(async(r,n)=>(r.context=r.context||{},r.context[e]=t,await n())),auth:(e)=>v(async(t,r)=>{if(e)return t.user=e,await r();else return new Response("Unauthorized",{status:401})}),rateLimit:(e=!1)=>v(async(t,r)=>{if(e)return new Response("Too Many Requests",{status:429});return await r()}),cors:(e="*")=>v(async(t,r)=>{let n=await r();if(n)n.headers.set("Access-Control-Allow-Origin",e);return n})};class Hr{middlewares;request;finalHandler;constructor(e){this.middlewares=e,this.request=b(),this.finalHandler=v(async()=>new Response("Final handler",{status:200}))}withRequest(e){return this.request=e,this}withFinalHandler(e){return this.finalHandler=v(e),this}async execute(){let e=0,t=async()=>{if(e<this.middlewares.length){let r=this.middlewares[e++];return await r(this.request,t)}else return await this.finalHandler()};return await t()}getExecutionOrder(){return this.middlewares.map((e,t)=>t)}}function nu(e){return new Hr(e)}function su(e){return Bs(e,"call")}function iu(){let e=v(async(t,r)=>await r());return{middleware:e,spy:e}}async function ou(e,t=1000){let r=[],n=b(),s=v(async()=>new Response("OK"));for(let c=0;c<t;c++){let l=performance.now();await e(n,s);let d=performance.now();r.push(d-l)}let i=r.reduce((c,l)=>c+l,0),o=i/t,a=Math.min(...r),u=Math.max(...r);return{averageTime:o,minTime:a,maxTime:u,totalTime:i}}import{mock as U}from"bun:test";class Ds{id;attributes;constructor(e={}){this.id=e.id,this.attributes=e}static modelName="GenericMockModel";static async find(e){return null}static async findOrFail(e){throw Error("Not implemented")}static async where(e){return[]}static async create(e){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class Fs{id;email;name;constructor(e={id:1}){this.id=e.id,this.email=e.email||"test@example.com",this.name=e.name||"Test User"}static async find(e){return null}static async findOrFail(e){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class Us{id;title;content;userId;constructor(e={id:1}){this.id=e.id,this.title=e.title||"Test Post",this.content=e.content||"Test content",this.userId=e.userId||1}static async find(e){return null}static async findOrFail(e){throw Error("Not implemented")}async belongsTo(e){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class Ar{request;options;constructor(e={}){this.options=e,this.request=b()}withRequest(e){return this.request=e,this}withParams(e){return this.request.params={...this.request.params,...e},this}withModel(e){return this.options.modelClass=e,this}withRouteKey(e){return this.options.routeKey=e,this}withConstraints(e){return this.options.constraints=e,this}withResolver(e){return this.options.customResolver=e,this}async testResolution(e){if(this.options.customResolver)return await this.options.customResolver(e);if(this.options.modelClass)return new this.options.modelClass({id:e});return{id:e}}async testNotFound(e){try{throw await this.testResolution(e),Error("Expected model not found error")}catch(t){if(t instanceof Error&&t.message!=="Model not found")throw t}}getRequest(){return this.request}}var lu={createModel:(e,t={})=>class r{id;attributes;constructor(n={}){this.id=n.id,this.attributes={...t,...n}}static modelName=e;static async find(n){if(n==="not-found")return null;return new r({id:n,...t})}static async findOrFail(n){let s=await this.find(n);if(!s)throw Error("Model not found");return s}static async where(n){return[new r({id:1,...t,...n})]}static async create(n){return new r({id:Date.now(),...n})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}},User:class e{id;email;name;constructor(t={id:1}){this.id=t.id,this.email=t.email||"test@example.com",this.name=t.name||"Test User"}static async find(t){if(t==="not-found")return null;return new e({id:Number.parseInt(t)})}static async findOrFail(t){let r=await this.find(t);if(!r)throw Error("User not found");return r}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class e{id;title;content;userId;constructor(t={id:1}){this.id=t.id,this.title=t.title||"Test Post",this.content=t.content||"Test content",this.userId=t.userId||1}static async find(t){if(t==="not-found")return null;return new e({id:Number.parseInt(t)})}static async findOrFail(t){let r=await this.find(t);if(!r)throw Error("Post not found");return r}async belongsTo(t){return this.userId===t}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},du={belongsTo:(e="userId")=>U(async(r,n)=>{if(!n.user)return!1;return r[e]===n.user.id}),belongsToUser:()=>U(async(t,r)=>{if(!r.user)return!1;return t.userId===r.user.id}),published:()=>U(async(t)=>t.published===!0||t.status==="published"),visible:()=>U(async(t)=>t.visible!==!1&&t.hidden!==!0),custom:(e)=>U(e),combine:(...e)=>U(async(r,n)=>{for(let s of e)if(!await s(r,n))return!1;return!0})};class qr{resolvers=new Map;register(e,t){return this.resolvers.set(e,U(t)),this}registerModel(e,t){let r=U(async(n)=>{if(t.find){let s=await t.find(n);if(!s)throw Error(`${t.name||"Model"} not found`);return s}return new t({id:n})});return this.resolvers.set(e,r),this}async resolve(e,t){let r=this.resolvers.get(e);if(!r)throw Error(`No resolver registered for key: ${e}`);return await r(t)}async testAll(e="1"){let t={};for(let[r,n]of this.resolvers)try{t[r]=await n(e)}catch(s){t[r]={error:s instanceof Error?s.message:"Unknown error"}}return t}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var pu={testRoute:async(e,t,r)=>{let n=b("GET",e);n.params=t;for(let[s,i]of Object.entries(r))n.context=n.context||{},n.context[s]=i;return n},createHandler:(e)=>U(async(r)=>{let n=r.context||{};for(let s of e)if(!n[s])return new Response(`Model ${s} not found`,{status:404});return new Response(JSON.stringify({params:r.params,models:Object.fromEntries(e.map((s)=>[s,n[s]]))}),{headers:{"Content-Type":"application/json"}})}),testBindingMiddleware:(e)=>U(async(r,n)=>{r.context=r.context||{};for(let[s,i]of Object.entries(e)){let o=r.params[s];if(o)try{if(typeof i==="function")r.context[s]=await i(o);else r.context[s]=i}catch(a){return console.error(`Error resolving model ${s}:`,a),new Response(`${s} not found`,{status:404})}}return await n()})};function hu(e){return new Ar(e)}function gu(){return new qr}var Ns=async(e,t)=>e.userId===t.id,mu={testUserScoped:async(e,t,r=Ns)=>await r(e,t),testRoleAccess:async(e,t,r)=>{if(!t.roles)return!1;return r.some((n)=>t.roles.includes(n))},testPermissionAccess:async(e,t,r)=>{if(!t.permissions)return!1;return r.every((n)=>t.permissions.includes(n))}};import{mock as Is}from"bun:test";import G from"process";class $r{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(e){return this.metrics.push(e),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((t,r)=>t+r.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let e=this.metrics.map((r)=>r.memoryUsage.heapUsed),t=this.metrics.map((r)=>r.memoryUsage.rss);return{averageHeapUsed:e.reduce((r,n)=>r+n,0)/e.length,maxHeapUsed:Math.max(...e),averageRSS:t.reduce((r,n)=>r+n,0)/t.length,maxRSS:Math.max(...t)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class ee{client;config;constructor(e,t){this.client=e,this.config=t}async run(e,t="GET",r={}){let n={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},s=[],i=new Map,o=Date.now(),a=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),u=[];for(let d=0;d<a;d++){let p=this.makeRequest(e,t,r).then((g)=>{s.push(g),n.successfulRequests++}).catch((g)=>{let h=g instanceof Error?g.message:"Unknown error";i.set(h,(i.get(h)||0)+1),n.failedRequests++});if(u.push(p),this.config.requestsPerSecond){let g=1000/this.config.requestsPerSecond;await new Promise((h)=>setTimeout(h,g))}if(u.length>=this.config.concurrency)await Promise.race(u),u.filter((h)=>h.then(()=>!0).catch(()=>!0)).forEach((h)=>{let m=u.indexOf(h);if(m>-1)u.splice(m,1)})}await Promise.allSettled(u);let l=(Date.now()-o)/1000;return n.totalRequests=a,n.averageResponseTime=s.length>0?s.reduce((d,p)=>d+p,0)/s.length:0,n.requestsPerSecond=a/l,n.errors=Array.from(i.entries()).map(([d,p])=>({error:d,count:p})),n}async makeRequest(e,t,r){let n=performance.now();try{return await this.client.request(t,e,r),performance.now()-n}catch(s){let i=performance.now();throw s}}}var bu={routeHandler:async(e,t=1000)=>{let r=[],n=b();for(let c=0;c<t;c++){let l=performance.now();await e(n);let d=performance.now();r.push(d-l)}let s=r.reduce((c,l)=>c+l,0),i=s/t,o=Math.min(...r),a=Math.max(...r),u=t/s*1000;return{averageTime:i,minTime:o,maxTime:a,totalTime:s,throughput:u}},middleware:async(e,t=1000)=>{let r=[],n=b(),s=Is(async()=>new Response("OK"));for(let c=0;c<t;c++){let l=performance.now();await e(n,s);let d=performance.now();r.push(d-l)}let i=r.reduce((c,l)=>c+l,0),o=i/t,a=Math.min(...r),u=Math.max(...r);return{averageTime:o,minTime:a,maxTime:u,totalTime:i}},jsonSerialization:async(e,t=1e4)=>{let r=[];for(let u=0;u<t;u++){let c=performance.now(),l=JSON.stringify(e),d=performance.now();r.push(d-c)}let n=r.reduce((u,c)=>u+c,0),s=n/t,i=Math.min(...r),o=Math.max(...r),a=JSON.stringify(e).length;return{averageTime:s,minTime:i,maxTime:o,totalTime:n,dataSize:a}},routeMatching:async(e,t,r=1000)=>{let n=[],s=0;for(let l=0;l<r;l++){let d=t[l%t.length],p=performance.now();if(e.find((m)=>{let R=m.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${R}$`).test(d)}))s++;let h=performance.now();n.push(h-p)}let i=n.reduce((l,d)=>l+d,0),o=i/r,a=Math.min(...n),u=Math.max(...n),c=s/r;return{averageTime:o,minTime:a,maxTime:u,totalTime:i,matchRate:c}}},Tu={measureMemoryUsage:async(e,t=100)=>{let r=[],n=[];if(globalThis.gc)globalThis.gc();let s=G.memoryUsage().heapUsed;for(let c=0;c<t;c++){let l=await e();r.push(l);let d=G.memoryUsage();if(n.push(d.heapUsed),c%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let i=G.memoryUsage().heapUsed,o=n.reduce((c,l)=>c+l,0)/n.length,a=Math.max(...n),u=i-s>1048576;return{averageHeapUsed:o,maxHeapUsed:a,memoryLeakDetected:u,results:r}},testRouteHandlerMemoryLeaks:async(e,t=1000)=>{if(globalThis.gc)globalThis.gc();let r=G.memoryUsage().heapUsed;for(let o=0;o<t;o++){let a=b();if(await e(a),o%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let n=G.memoryUsage().heapUsed,s=n-r;return{memoryLeakDetected:s>5242880,initialMemory:r,finalMemory:n,memoryGrowth:s}}},xu={rampUpTest:async(e,t,r)=>{let n=[],s=10,i=r.testDuration/10,o=(r.endConcurrency-r.startConcurrency)/10;for(let a=0;a<10;a++){let u=Math.round(r.startConcurrency+o*a),l=await new ee(e,{duration:i,concurrency:u,requestsPerSecond:u*2}).run(t);n.push({concurrency:u,requestsPerSecond:l.requestsPerSecond,averageResponseTime:l.averageResponseTime,errorRate:l.failedRequests/l.totalRequests})}return n},spikeTest:async(e,t,r)=>{let s=await new ee(e,{duration:30000,concurrency:r.normalLoad}).run(t),o=await new ee(e,{duration:r.spikeDuration,concurrency:r.spikeLoad}).run(t),u=await new ee(e,{duration:30000,concurrency:r.normalLoad}).run(t);return{normalPhase:s,spikePhase:o,recoveryPhase:u}}},vu={responseTimeWithin:(e,t)=>{if(e>t)throw Error(`Response time ${e}ms exceeds maximum ${t}ms`)},throughputAtLeast:(e,t)=>{if(e<t)throw Error(`Throughput ${e} RPS is below minimum ${t} RPS`)},errorRateBelow:(e,t)=>{if(e>t)throw Error(`Error rate ${(e*100).toFixed(2)}% exceeds maximum ${(t*100).toFixed(2)}%`)},memoryUsageWithin:(e,t)=>{if(e>t)throw Error(`Memory usage ${(e/1024/1024).toFixed(2)}MB exceeds maximum ${(t/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(e,t=5242880)=>{if(e>t)throw Error(`Potential memory leak detected: ${(e/1024/1024).toFixed(2)}MB growth`)}};function Cu(){return new $r}function Pu(e,t){return new ee(e,t)}var Or={getCurrentMemoryUsage:()=>{let e=G.memoryUsage();return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,rss:e.rss}},getCPUUsage:()=>{let e=G.cpuUsage();return{user:e.user,system:e.system}},createMetricSnapshot:(e)=>({responseTime:e,memoryUsage:Or.getCurrentMemoryUsage(),cpuUsage:Or.getCPUUsage()}),formatResults:(e)=>JSON.stringify(e,null,2)};class pt{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(e,t){this.originalResponse=e,this.status=e.status,this.statusText=e.statusText,this.headers=this.parseHeaders(e.headers),this.cookies=this.parseCookies(e.headers.get("set-cookie")),this.redirected=e.redirected,this.url=e.url,this.ok=e.ok,this.type=e.type,this.body=t,this.text=typeof t==="string"?t:JSON.stringify(t);try{this.json=typeof t==="string"?JSON.parse(t):t}catch{this.json=null}}parseHeaders(e){let t={};return e.forEach((r,n)=>{t[n.toLowerCase()]=r}),t}parseCookies(e){if(!e)return{};let t={};return e.split(",").forEach((r)=>{let[n]=r.trim().split(";"),[s,i]=n.split("=");if(s&&i)t[s.trim()]=i.trim()}),t}expectStatus(e){if(this.status!==e)throw Error(`Expected status ${e}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(e,t){let r=this.headers[e.toLowerCase()];if(r===void 0)throw Error(`Expected header '${e}' to be present`);if(t!==void 0&&r!==t)throw Error(`Expected header '${e}' to be '${t}', got '${r}'`);return this}expectBody(e){if(typeof e==="string"){if(this.text!==e)throw Error(`Expected body '${e}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(e))throw Error(`Expected body ${JSON.stringify(e)}, got ${JSON.stringify(this.json)}`);return this}expectJson(e){if(JSON.stringify(this.json)!==JSON.stringify(e))throw Error(`Expected JSON ${JSON.stringify(e)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(e){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(e).forEach(([t,r])=>{let n=this.json[t];if(typeof r==="object"&&r!==null&&typeof n==="object"&&n!==null){let s=JSON.stringify(r),i=JSON.stringify(n);if(s!==i)throw Error(`Expected JSON property '${t}' to be ${s}, got ${i}`)}else if(n!==r)throw Error(`Expected JSON property '${t}' to be '${r}', got '${n}'`)}),this}expectCookie(e,t){let r=this.cookies[e];if(r===void 0)throw Error(`Expected cookie '${e}' to be present`);if(t!==void 0&&r!==t)throw Error(`Expected cookie '${e}' to be '${t}', got '${r}'`);return this}expectRedirect(e){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(e){let t=this.headers.location;if(t!==e)throw Error(`Expected redirect to '${e}', got '${t}'`)}return this}expectValidationError(e,t){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(e){let r=this.json?.errors||this.json?.message;if(!r||!r[e])throw Error(`Expected validation error for field '${e}'`);if(t){if(!(Array.isArray(r[e])?r[e]:[r[e]]).includes(t))throw Error(`Expected validation error message '${t}' for field '${e}'`)}}return this}expectContentType(e){let t=this.headers["content-type"];if(!t||!t.includes(e))throw Error(`Expected content type '${e}', got '${t}'`);return this}expectBodyContains(e){if(!this.text.includes(e))throw Error(`Expected body to contain '${e}'`);return this}expectBodyMatches(e){if(!e.test(this.text))throw Error(`Expected body to match pattern ${e}`);return this}expectJsonStructure(e){return this.validateStructure(this.json,e,"root"),this}validateStructure(e,t,r){if(t&&typeof t==="object"&&t.$$typeof)return;if(Array.isArray(t)){if(!Array.isArray(e))throw TypeError(`Expected ${r} to be an array`);if(t.length>0&&e.length>0)this.validateStructure(e[0],t[0],`${r}[0]`)}else if(typeof t==="object"&&t!==null){if(typeof e!=="object"||e===null)throw Error(`Expected ${r} to be an object`);Object.keys(t).forEach((n)=>{if(!(n in e))throw Error(`Expected ${r} to have property '${n}'`);this.validateStructure(e[n],t[n],`${r}.${n}`)})}}getOriginalResponse(){return this.originalResponse}toJSON(){return{status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,json:this.json,cookies:this.cookies,redirected:this.redirected,url:this.url,ok:this.ok,type:this.type}}}async function Br(e){let t=await e.text();return new pt(e,t)}function Mu(e=200,t,r){let n=new Headers(r);if(t&&typeof t==="object"&&!n.has("content-type"))n.set("content-type","application/json");let s=new Response(t?typeof t==="string"?t:JSON.stringify(t):null,{status:e,headers:n});return new pt(s,t)}class Ne{router;config;defaultHeaders;constructor(e,t={}){this.router=e,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:(r)=>r>=200&&r<300,...t},this.defaultHeaders=t.defaultHeaders||{}}async get(e,t={}){return this.request("GET",e,t)}async post(e,t={}){return this.request("POST",e,t)}async put(e,t={}){return this.request("PUT",e,t)}async patch(e,t={}){return this.request("PATCH",e,t)}async delete(e,t={}){return this.request("DELETE",e,t)}async options(e,t={}){return this.request("OPTIONS",e,t)}async head(e,t={}){return this.request("HEAD",e,t)}async request(e,t,r={}){let n={...this.defaultHeaders,...r.headers},s={...r,headers:n},i=new q(e,t,s).build();try{let o=await this.handleRequest(i);return await Br(o)}catch(o){throw Error(`Test request failed: ${o instanceof Error?o.message:"Unknown error"}`)}}async handleRequest(e){let t=new URL(e.url),r=this.findMatchingRoute(e.method,t.pathname);if(!r)return new Response("Not Found",{status:404});let{route:n,params:s}=r;e.params={...e.params,...s};try{return await this.executeMiddlewareChain(e,n)||new Response("No response",{status:500})}catch(i){return new Response(JSON.stringify({error:i instanceof Error?i.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(e,t){for(let r of this.router.routes){if(r.method.toLowerCase()!==e.toLowerCase())continue;let n=this.matchPath(r.path,t);if(n!==null)return{route:r,params:n}}return null}matchPath(e,t){let r=e.split("/"),n=t.split("/");if(r.length!==n.length)return null;let s={};for(let i=0;i<r.length;i++){let o=r[i],a=n[i];if(o.startsWith(":")){let u=o.slice(1);s[u]=a}else if(o!==a)return null}return s}async executeMiddlewareChain(e,t){let r=[...this.router.globalMiddleware,...t.middleware],n=0,s=async()=>{if(n<r.length){let o=r[n++];return await o(e,s)}else return await this.executeHandler(t.handler,e)};return await s()||new Response("No response",{status:500})}async executeHandler(e,t){if(typeof e==="function")return await e(t);else if(typeof e==="string")throw TypeError(`String handlers not supported in test environment: ${e}`);else if(typeof e==="object"&&e.handle)return await new e().handle(t);throw Error("Invalid handler type")}setDefaultHeaders(e){return this.defaultHeaders={...this.defaultHeaders,...e},this}auth(e,t="Bearer"){return this.defaultHeaders.Authorization=`${t} ${e}`,this}userAgent(e){return this.defaultHeaders["User-Agent"]=e,this}withConfig(e){return new Ne(this.router,{...this.config,...e})}withHeaders(e){return new Ne(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...e}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function Ue(e,t){return new Ne(e,t)}var Au={for:(e,t)=>Ue(e,t),withConfig:(e)=>(t)=>Ue(t,e),withAuth:(e,t="Bearer")=>(r)=>Ue(r).auth(e,t),withHeaders:(e)=>(t)=>Ue(t).withHeaders(e)};import{mock as W}from"bun:test";class O{messages=[];isConnected=!1;readyState=0;eventHandlers=new Map;constructor(){this.setupEventHandlers()}setupEventHandlers(){this.eventHandlers.set("open",[]),this.eventHandlers.set("message",[]),this.eventHandlers.set("close",[]),this.eventHandlers.set("error",[])}connect(){return this.isConnected=!0,this.readyState=1,this.emit("open",{type:"open"}),this}disconnect(e=1000,t="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:e,reason:t}),this}send(e){if(!this.isConnected)throw Error("WebSocket is not connected");let t={type:typeof e==="string"?"text":"binary",data:e,timestamp:Date.now()};return this.messages.push(t),this}receive(e){if(!this.isConnected)throw Error("WebSocket is not connected");let t={type:typeof e==="string"?"text":"binary",data:e,timestamp:Date.now()};return this.emit("message",{type:"message",data:e}),this}ping(e){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:e}),this}pong(e){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:e}),this}on(e,t){if(!this.eventHandlers.has(e))this.eventHandlers.set(e,[]);return this.eventHandlers.get(e).push(t),this}off(e,t){let r=this.eventHandlers.get(e);if(r){let n=r.indexOf(t);if(n>-1)r.splice(n,1)}return this}emit(e,t){(this.eventHandlers.get(e)||[]).forEach((n)=>n(t))}getSentMessages(){return[...this.messages]}getMessagesByType(e){return this.messages.filter((t)=>t.type===e)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(e)=>this.send(e),close:(e,t)=>this.disconnect(e,t),ping:(e)=>this.ping(e),pong:(e)=>this.pong(e),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class Dr{tester;_data;constructor(e={}){this.tester=new O,this._data=e}send(e){this.tester.send(e)}close(e,t){this.tester.disconnect(e,t)}ping(e){this.tester.ping(e)}pong(e){this.tester.pong(e)}publish(e,t){this.tester.send(t)}subscribe(e){}unsubscribe(e){}isSubscribed(e){return!0}cork(e){e()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(e){this._data=e}getTester(){return this.tester}}var $u={onOpen:()=>W(async(e)=>{}),onMessage:(e)=>W(async(t,r)=>{if(e)t.send(e)}),onClose:()=>W(async(e,t,r)=>{}),onError:()=>W(async(e,t)=>{}),echo:()=>W(async(e,t)=>{e.send(t)}),broadcast:(e)=>W(async(t,r)=>{e.forEach((n)=>{if(n!==t&&n.readyState===1)n.send(r)})}),chatRoom:(e)=>W(async(t,r)=>{t.publish(e,r)})},Bu={basicConnection:()=>new O().connect().send("Hello WebSocket").receive("Hello Client"),connectionFailure:()=>{let e=new O;return e.on("error",()=>{}),e},messageBroadcast:(e=3)=>{let t=Array.from({length:e},()=>new O().connect());return t[0].send("Broadcast message"),t.slice(1).forEach((r)=>r.receive("Broadcast message")),t},pingPong:()=>new O().connect().ping().pong(),connectionTimeout:()=>{let e=new O;return setTimeout(()=>{e.disconnect(1006,"Connection timeout")},100),e}},Du={isConnected:(e)=>{if(!e.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(e)=>{if(e.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(e,t)=>{if(!e.getSentMessages().some((s)=>{if(typeof t==="string"&&typeof s.data==="string")return s.data===t;return s.data===t}))throw Error("Expected message not found in sent messages")},messageCount:(e,t)=>{let r=e.getSentMessages();if(r.length!==t)throw Error(`Expected ${t} messages, but got ${r.length}`)},messageType:(e,t,r)=>{let n=e.getSentMessages();if(t>=n.length)throw Error(`Message at index ${t} does not exist`);if(n[t].type!==r)throw Error(`Expected message type '${r}', got '${n[t].type}'`)},readyState:(e,t)=>{let r=e.getState();if(r.readyState!==t)throw Error(`Expected ready state ${t}, got ${r.readyState}`)}},Fu={testThroughput:async(e=1000,t=1024)=>{let r=new O().connect(),n="x".repeat(t),s=performance.now();for(let c=0;c<e;c++)r.send(n);let o=performance.now()-s,a=e/o*1000,u=o/e;return{messagesPerSecond:a,totalTime:o,averageLatency:u}},testConcurrentConnections:async(e=100)=>{let t={successfulConnections:0,failedConnections:0,averageConnectionTime:0},r=[],n=Array.from({length:e},async()=>{let s=performance.now();try{new O().connect();let o=performance.now();r.push(o-s),t.successfulConnections++}catch(i){console.error("WebSocket connection failed:",i),t.failedConnections++}});return await Promise.all(n),t.averageConnectionTime=r.length>0?r.reduce((s,i)=>s+i,0)/r.length:0,t}};function Uu(){return new O}function Nu(e){return new Dr(e)}var Iu={createClients:(e)=>Array.from({length:e},()=>new O().connect()),withLatency:(e,t)=>{let r=e.send.bind(e);return e.send=(n)=>(setTimeout(()=>r(n),t),e),e},withPacketLoss:(e,t)=>{let r=e.send.bind(e);return e.send=(n)=>{if(Math.random()>t)r(n);return e},e},*messageGenerator(e,t="Message"){for(let r=1;r<=e;r++)yield`${t} ${r}`}};class ht extends Error{status;response;body;constructor(e,t){let r=typeof t?.message==="string"?t.message:e.statusText||"Request failed";super(`${e.status} ${r}`);this.name="TypedClientError",this.status=e.status,this.response=e,this.body=t}}function Fr(e,t){if(!t)return e;let r=e;for(let[n,s]of Object.entries(t)){let i=encodeURIComponent(s);r=r.split(`{${n}}`).join(i),r=r.replace(new RegExp(`:${n}(?![A-Z0-9_])`,"gi"),i)}return r}function Ur(e,t){if(!t)return e;let r=new URLSearchParams;for(let[s,i]of Object.entries(t))if(i!==void 0&&i!==null)r.append(s,String(i));let n=r.toString();if(!n)return e;return e.includes("?")?`${e}&${n}`:`${e}?${n}`}async function _s(e){if(e.status===204||e.headers.get("content-length")==="0")return;if((e.headers.get("content-type")??"").includes("json"))try{return await e.json()}catch{return}return await e.text()}function js(e){let t=e.baseUrl.replace(/\/+$/,""),r=e.fetch??globalThis.fetch;async function n(){if(typeof e.headers==="function")return await e.headers();return e.headers??{}}async function s(i,o,a,u,c){let l=Ur(`${t}${Fr(o,c?.params)}`,c?.query),d={accept:"application/json",...await n(),...c?.headers};if(u&&d["content-type"]===void 0&&d["Content-Type"]===void 0)d["content-type"]="application/json";let p=await r(l,{method:i,headers:d,...u?{body:JSON.stringify(a)}:{},...e.credentials?{credentials:e.credentials}:{},...c?.signal?{signal:c.signal}:{}}),g=await _s(p);if(!p.ok){let h=new ht(p,g);if(e.onError)return e.onError(h);throw h}return g}return{get:(i,o)=>s("GET",i,void 0,!1,o),post:(i,o,a)=>s("POST",i,o,!0,a),put:(i,o,a)=>s("PUT",i,o,!0,a),patch:(i,o,a)=>s("PATCH",i,o,!0,a),delete:(i,o)=>s("DELETE",i,void 0,!1,o),async raw(i,o,a){let{params:u,query:c,...l}=a??{},d=Ur(`${t}${Fr(o,u)}`,c);return await r(d,{method:i,...l,headers:{...await n(),...l.headers},...e.credentials?{credentials:e.credentials}:{}})}}}function Ls(e){return e}var zs=["get","post","put","patch","delete"];function Gs(e,t,r,n){if(!n)return;let s=e,i=(o)=>{let a=s?.[o];if(typeof a!=="function")throw TypeError(`[typed-router] ${t.toUpperCase()} ${r}: this router's route does not support .${String(o)}(), so the \`${String(o)}\` option cannot be applied. Register the route directly instead of dropping it.`);return a};if(n.middleware)i("middleware").call(s,n.middleware);if(n.name)i("name").call(s,n.name);if(n.skipCsrf)i("skipCsrf").call(s);if(n.requireCsrf)i("requireCsrf").call(s);if(n.rateLimit)i("rateLimit").call(s,n.rateLimit.max,n.rateLimit.window??"minute")}function Ws(e){let t={};for(let r of zs)t[r]=(n,s,i)=>(Gs(e[r](n,s),r,n,i),t);return t}export{mt as ApiKeyManager,Wr as Auth,ge as AuthTester,Js as BindingBuilder,Os as BuiltInRules,ji as CacheInvalidation,Vs as Container,nl as ContentSecurityPolicy,Ys as ContextualContainer,Fc as Cors,Uc as Csrf,il as DDoSProtection,Mn as DEFAULT_COMPRESSION,Qo as DatabaseRules,Zc as DatabaseSessionStore,ei as DefaultServiceProviderManager,On as Dependencies,oe as DomainGroup,Vt as DomainGroupBuilder,k as DomainMatcher,ua as EnhancementPresets,Zs as EnvironmentManager,Tt as Errors,al as FileSecurity,Xc as FileSessionStore,ul as FileUpload,_ as FileUploadTester,dt as FileValidationTester,f as FluentRouteBuilder,ue as FluentRouter,Ds as GenericMockModel,gl as Helmet,zc as InMemoryNonceStore,ml as InputValidation,gt as JWT,ct as JWTTester,Nc as JsonBody,ee as LoadTester,Kc as MemorySessionStore,Hr as MiddlewareChainTester,$n as MiddlewareFactory,at as MiddlewareGroupRegistry,Pr as MiddlewareHelpers,Ke as MiddlewarePipeline,kr as MiddlewareTester,Us as MockPostClass,Dr as MockServerWebSocket,Fs as MockUserClass,Ar as ModelBindingTester,qr as ModelResolverTester,ft as OAuth2Helper,yl as PerformanceAlerting,wl as PerformanceDashboard,Tl as PerformanceMonitor,$r as PerformanceTester,Ic as RateLimit,Gt as RateLimitRegistry,Gi as RateLimitUtils,He as RateLimiter,Qc as RedisSessionStore,jc as RequestId,Gc as RequestSigning,vl as RequestTracer,Pt as ResponseBuilder,C as RouteBuilder,zt as RouteCacheFactory,_t as RouteCacheKeyGenerator,jt as RouteCacheManager,Rs as RouteFactory,Jt as RouteGroupBuilder,oa as RouteHelpers,w as Router,ws as RouterUtils,Pl as Security,Ml as SecuritySuite,rl as Session,el as SessionManager,lt as SessionTester,Lc as SignatureError,qn as SkipConditions,Ki as SubdomainPatterns,Qe as SubdomainRouter,Ji as SubdomainUtils,Ne as TestClient,q as TestRequestBuilder,pt as TestResponseWrapper,os as ThrottleFactory,ht as TypedClientError,Er as ValidationFluentRouter,ea as ValidationHelpers,Mr as ValidationMiddlewareBuilder,it as ValidationRuleBuilder,De as Validator,O as WebSocketTester,Bc as apiKeyAuth,Je as appendVary,Ps as applyRequestEnhancements,$l as auth,Ia as authHelpers,Na as authMocks,qc as basicAuth,Oc as bearerAuth,ou as benchmarkMiddleware,bu as benchmarkTests,ki as buildUrlWithPreservedParams,cs as clearNamedRoutes,Ct as compressResponse,Sc as config,du as constraintHelpers,sl as contentSecurityPolicy,kl as cors,_a as createAuthTester,Qs as createContainer,ot as createEnhancementMiddleware,Xa as createFileUploadTester,aa as createFluentRouter,vs as createHandlerResolver,ja as createJWTTester,Pu as createLoadTester,iu as createMiddlewareSpy,b as createMockRequest,Mu as createMockResponse,Nu as createMockServerWebSocket,hu as createModelBindingTester,gu as createModelResolverTester,ro as createPathRegex,Cu as createPerformanceTester,Q as createRateLimitMiddleware,Lt as createRouteCacheMiddleware,Yc as createSessionStore,La as createSessionTester,Vi as createSubdomainMiddleware,Ue as createTestClient,Br as createTestResponse,js as createTypedClient,Ws as createTypedRouter,Fe as createValidationMiddleware,Uu as createWebSocketTester,Ol as csrf,ol as ddosProtection,Ec as defaultConfig,Si as defaultQueryPreservationConfig,Ls as defineEndpoint,hl as documentUpload,Pn as enableRequestContext,Ac as extractApiKey,kc as extractBasicAuth,Hc as extractBearerToken,Ae as extractParamNames,Zt as fileExists,cl as fileUpload,Ka as fileUploadAssertions,Va as fileUploadMocks,Ja as fileUploadScenarios,Gn as generateQueryPreservationScript,tl as generateSessionId,Mc as getConfig,Ks as getContainer,xt as getCurrentRequest,Ze as getNamedRoutePath,us as getNamedRoutes,Bn as globalMiddlewarePipeline,Zo as globalValidator,pl as imageUpload,Pe as injectQueryPreservationScript,fl as inputValidation,ds as isActionClass,vt as isCompressible,to as isRouteHandler,F as joinPaths,Hl as jsonBody,$c as jwtAuth,H as matchPath,Tu as memoryTests,Bl as middleware,P as middlewareGroups,ru as mockMiddleware,lu as modelMocks,dl as multipleFileUpload,Sn as negotiateEncoding,ae as normalizePath,Dc as oauth2Auth,Z as parseThrottleString,Hn as peekBody,Rl as performanceAlerting,vu as performanceAssertions,bl as performanceDashboard,xl as performanceMonitor,Or as performanceUtils,Yt as processHtmlTemplate,_c as rateLimit,Wt as rateLimitRegistry,N as registerNamedRoute,En as request,Al as requestId,Wc as requestSigning,Cl as requestTracer,ce as resolveHandler,Ye as resolveViewPath,y as response,Ti as responseBuilder,X as routeCacheManager,pu as routeModelHelpers,bs as router,Yo as rule,ve as runWithRequest,mu as scopedBindingHelpers,El as security,Sl as securitySuite,ql as session,Xs as setContainer,Ce as setCurrentRequest,kn as shouldCompress,Vc as signRequest,ll as singleFileUpload,su as spyOnMiddleware,xu as stressTests,Au as testClient,Qa as testFiles,tu as testMiddleware,nu as testMiddlewareChain,Ba as testRequest,eo as toActionPath,ls as url,ia as validate,no as validatePath,Jc as verifySignature,M as wrapResponse,Du as wsAssertions,$u as wsHandlerMocks,Fu as wsPerformance,Bu as wsTestScenarios,Iu as wsTestUtils};
|