@stacksjs/bun-router 0.1.11 → 0.1.14

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/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{he,ft,e,me,V,ge,Ne,qe,He,Be,je,p,r,h,k,W,m,n,fe,g,Ue,Le,_e,l,A,O,I,yt,G,F,f,y,ze,w,Ve,C,a,We,Ge,Ke,Je,Xe,S,b,Ye,D,Qe,N,Ze,q,et,H,tt,R,rt,B,nt,wt,bt,Rt,vt,xt,Tt,K}from"./chunk-trm3jyqk.js";import{t,u,J,X,Y,Q,v,Z,ee,te,re,x,T,ne,se,ie,s,E,d,oe,j,ae,ce,st,it,ot,o,L,ye,we,be,_,le,ue}from"./chunk-7g1et0fb.js";var Os=Object.defineProperty;var $s=(i)=>i;function Bs(i,c){this[i]=$s.bind(null,c)}var Ds=(i,c)=>{for(var P in c)Os(i,P,{get:c[P],enumerable:!0,configurable:!0,set:Bs.bind(c,P)})};import{timingSafeEqual as Ns}from"crypto";function kr(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ar(i){i=i.replace(/-/g,"+").replace(/_/g,"/");while(i.length%4)i+="=";return atob(i)}class rn{secret;constructor(i){this.secret=i}sign(i,c={}){let P={alg:c.algorithm||"HS256",typ:"JWT",...c.header},M=Math.floor(Date.now()/1000),U={...i,iat:M};if(c.expiresIn){let Te=typeof c.expiresIn==="string"?this.parseTimespan(c.expiresIn):c.expiresIn;U.exp=M+Te}if(c.notBefore){let Te=typeof c.notBefore==="string"?this.parseTimespan(c.notBefore):c.notBefore;U.nbf=M+Te}if(c.issuer)U.iss=c.issuer;if(c.subject)U.sub=c.subject;if(c.audience)U.aud=c.audience;if(c.jwtid)U.jti=c.jwtid;let z=kr(JSON.stringify(P)),de=kr(JSON.stringify(U)),pe=`${z}.${de}`,Re=this.createSignature(pe,this.secret,P.alg);return`${pe}.${Re}`}verify(i,c={}){try{let P=i.split(".");if(P.length!==3)throw Error("Token structure invalid");let[M,U,z]=P,de=JSON.parse(ar(M)),pe=JSON.parse(ar(U));if(c.algorithms&&!c.algorithms.includes(de.alg))throw Error(`Algorithm ${de.alg} not allowed`);let Re=`${M}.${U}`,Te=this.createSignature(Re,this.secret,de.alg),xe=Buffer.from(z),ve=Buffer.from(Te);if(xe.length!==ve.length||!Ns(xe,ve))throw Error("Invalid signature");let Ce=Math.floor(Date.now()/1000);if(pe.exp&&!c.ignoreExpiration&&Ce>=pe.exp)throw Error("Token expired");if(pe.nbf&&Ce<pe.nbf)throw Error("Token not active yet");if(pe.iat&&pe.iat>Ce)throw Error("Token used before issued");if(c.issuer&&pe.iss!==c.issuer)throw Error("Invalid issuer");if(c.audience&&pe.aud!==c.audience)throw Error("Invalid audience");if(c.subject&&pe.sub!==c.subject)throw Error("Invalid subject");return pe}catch{return null}}decode(i){try{let c=i.split(".");if(c.length!==3)return null;let[P,M]=c;return{header:JSON.parse(ar(P)),payload:JSON.parse(ar(M))}}catch{return null}}createSignature(i,c,P){return kr(JSON.stringify({data:i,secret:c.slice(0,5),alg:P}))}parseTimespan(i){let c=i.match(/^(\d+)\s*([smhd])$/i);if(!c)return Number.parseInt(i,10)||0;let P=Number.parseInt(c[1],10);switch(c[2].toLowerCase()){case"s":return P;case"m":return P*60;case"h":return P*60*60;case"d":return P*24*60*60;default:return P}}}class nn{keys;options;constructor(i={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...i}}generateKey(i,c=[],P){let M=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(M,{owner:i,scopes:c,expiresAt:P?new Date(Date.now()+P*1000):void 0}),M}validateKey(i,c=[]){let P=this.keys.get(i);if(!P)return!1;if(P.expiresAt&&P.expiresAt<new Date)return!1;if(c.length>0)return c.every((M)=>P.scopes.includes(M));return!0}getKeyInfo(i){return this.keys.get(i)||null}revokeKey(i){return this.keys.delete(i)}extractFromRequest(i){let{source:c,keyName:P}=this.options;switch(c){case"header":return i.headers.get(P||"X-API-Key")||null;case"query":return new URL(i.url).searchParams.get(P||"api_key")||null;case"cookie":if(i.cookies){let M=P||"api_key";if(typeof i.cookies.get==="function")return i.cookies.get(M)||null;return i.cookies[M]||null}return null;default:return null}}randomString(i){let P="";for(let M=0;M<i;M++)P+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return P}}class sn{config;constructor(i){this.config=i}getAuthorizationUrl(i={}){let c=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...i});if(this.config.scope)c.set("scope",this.config.scope);if(this.config.state)c.set("state",this.config.state);return`${this.config.authorizeUrl}?${c.toString()}`}async exchangeCodeForToken(i){let c=new URLSearchParams({grant_type:"authorization_code",code:i,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),P=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString()});if(!P.ok)throw Error(`OAuth token exchange failed: ${P.status} ${P.statusText}`);return await P.json()}async refreshToken(i){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:i,client_id:this.config.clientId,client_secret:this.config.clientSecret}),P=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString()});if(!P.ok)throw Error(`OAuth token refresh failed: ${P.status} ${P.statusText}`);return await P.json()}}var Fs={JWT:rn,ApiKeyManager:nn,OAuth2Helper:sn},Us=Fs;var ln={};Ds(ln,{AuthenticationException:()=>J,AuthorizationException:()=>X,BugsnagReporter:()=>qr,BusinessLogicException:()=>ne,CircuitBreaker:()=>ur,CircuitBreakerHttpClient:()=>on,CircuitBreakerOpenException:()=>T,CircuitBreakerPresets:()=>js,CircuitBreakerRegistry:()=>Nt,CircularDependencyException:()=>d,ConfigurationException:()=>se,CustomReporter:()=>an,DatabaseException:()=>re,DegradationStrategies:()=>Js,ErrorFactory:()=>s,ErrorReportingManager:()=>Vt,ErrorReportingPresets:()=>Ws,ExternalServiceException:()=>x,FileSystemException:()=>ie,GracefulDegradationManager:()=>Jt,HandlerResolutionException:()=>ae,InternalServerException:()=>ee,MethodNotAllowedException:()=>Q,MiddlewareConfigurationException:()=>oe,ModelBindingException:()=>ce,NotFoundException:()=>Y,RateLimitException:()=>Z,RouteConflictException:()=>E,RouteNotFoundException:()=>j,RouterErrorFactory:()=>ot,RouterException:()=>t,SentryReporter:()=>Ar,ServiceHealthMonitor:()=>Or,ServiceUnavailableException:()=>te,TimeoutException:()=>v,ValidationException:()=>u,circuitBreaker:()=>Is,createAdvancedErrorHandler:()=>cn,createCircuitBreaker:()=>Ls,createCircuitBreakerMiddleware:()=>_s,createErrorReporting:()=>Gs,createGracefulDegradationMiddleware:()=>Vs,detectRouteConflicts:()=>it,findSimilarRoutes:()=>st,globalCircuitBreakerRegistry:()=>Hr,withCircuitBreaker:()=>zs});class ur{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(i){let c={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...c,...i},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(i){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let U=new T(this.config.name,this.nextAttemptTime,i.context);if(i.fallback)try{return await i.fallback()}catch(z){console.error(z)}throw U}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let U=new T(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),i.context);if(i.fallback)try{return await i.fallback()}catch(z){throw console.error(z),U}throw U}let c=Date.now(),P,M=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let U=i.timeout||this.config.timeout,z=new Promise((de,pe)=>{setTimeout(()=>{pe(new v(`Circuit breaker timeout for ${this.config.name}`,U,i.context))},U)});return P=await Promise.race([i.execute(),z]),this.onSuccess(Date.now()-c),P}catch(U){if(M=U,this.onFailure(M,Date.now()-c),i.fallback)try{return await i.fallback()}catch(z){throw console.error(z),M}else throw M}}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(i){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(i),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:i}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(i,c){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,i instanceof v)this.metrics.timeouts++;if(this.updateAverageResponseTime(c),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:c}),this.shouldTrip(i)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(i,this.config.name)}shouldTrip(i){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(i))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let c=this.getRecentRequests();if(c.length>=this.config.minimumRequests){if(c.filter((U)=>!U.success).length/c.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(i){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=i;else this.metrics.averageResponseTime=0.1*i+0.9*this.metrics.averageResponseTime}getRecentRequests(){let i=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((c)=>c.timestamp>i)}cleanupOldRequests(){let i=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((c)=>c.timestamp>i)}}class Nt{breakers=new Map;configs=new Map;register(i){let c=new ur(i);return this.breakers.set(i.name,c),this.configs.set(i.name,i),c}get(i){return this.breakers.get(i)}async execute(i,c){let P=this.breakers.get(i);if(!P)throw Error(`Circuit breaker '${i}' not found`);return P.execute(c)}getAllMetrics(){let i={};for(let[c,P]of this.breakers)i[c]=P.getMetrics();return i}getBreakersByState(i){let c=[];for(let[P,M]of this.breakers)if(M.getState()===i)c.push(P);return c}forceAllClosed(){for(let i of this.breakers.values())i.forceClosed()}resetAll(){for(let i of this.breakers.values())i.reset()}remove(i){return this.configs.delete(i),this.breakers.delete(i)}getNames(){return Array.from(this.breakers.keys())}}function Is(i){let c=new ur(i);return function(P,M,U){let z=U.value;return U.value=async function(...de){return c.execute({execute:()=>z.apply(this,de),context:{method:M,timestamp:new Date}})},U}}class on{registry;constructor(i){this.registry=i||new Nt}async fetch(i,c={}){let{circuitBreaker:P,fallback:M,context:U,...z}=c,de;if(typeof P==="string")de=P;else if(P){if(de=P.name,!this.registry.get(de))this.registry.register(P)}else if(de=`http-${new URL(i).hostname}`,!this.registry.get(de))this.registry.register({name:de,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(de,{execute:async()=>{let pe=await fetch(i,z);if(pe.status>=500)throw new x(`HTTP ${pe.status}: ${pe.statusText}`,de,i,pe.status,void 0,U);return pe},fallback:M,context:U})}getRegistry(){return this.registry}}function _s(i){return async(c,P)=>{let M=c.context?.serviceName;if(!M)return P();let U=i.get(M);if(!U)return P();return U.execute({execute:P,context:{requestId:c.requestId,route:c.route,method:c.method,url:c.url}})}}var js={critical:(i)=>({name:i,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(i)=>({name:i,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(i)=>({name:i,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(i)=>({name:i,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(c)=>!(c.message.includes("validation")||c.message.includes("constraint"))}),externalApi:(i)=>({name:i,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(c)=>{if(c instanceof x)return c.statusCode>=500;return!0}})},Hr=new Nt;function Ls(i){return Hr.register(i)}async function zs(i,c){return Hr.execute(i,c)}class Ar{config;sentry;constructor(i){this.config=i,this.initializeSentry()}async initializeSentry(){try{let i=await import("@sentry/node");i.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(c,P)=>{let M=P.originalException;if(M&&this.config.beforeSend)return this.config.beforeSend(M,M.context)?c:null;return c},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=i}catch(i){console.warn("Failed to initialize Sentry:",i)}}async report(i,c){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(i))return null;let P={...i.context,...c};return this.sentry.withScope((M)=>{if(P.requestId)M.setTag("requestId",P.requestId);if(P.userId)M.setUser({id:P.userId});if(P.traceId)M.setTag("traceId",P.traceId);if(P.route)M.setTag("route",P.route);if(P.method)M.setTag("method",P.method);M.setTag("errorCode",i.code),M.setTag("severity",i.severity),M.setTag("category",i.category),M.setLevel(this.mapSeverityToLevel(i.severity)),M.setExtra("statusCode",i.statusCode),M.setExtra("retryable",i.retryable),M.setExtra("timestamp",i.timestamp),M.setExtra("context",P);let U=this.generateFingerprint(i);if(U.length>0)M.setFingerprint(U);return this.sentry.captureException(i)})}catch(P){return console.error("Failed to report error to Sentry:",P),null}}addBreadcrumb(i,c="default",P="info",M){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:i,category:c,level:P,data:M,timestamp:Date.now()/1000})}setUser(i){if(!this.sentry)return;this.sentry.setUser(i)}setTag(i,c){if(!this.sentry)return;this.sentry.setTag(i,c)}setExtra(i,c){if(!this.sentry)return;this.sentry.setExtra(i,c)}setContext(i,c){if(!this.sentry)return;this.sentry.setContext(i,c)}async close(i=2000){if(!this.sentry)return!0;return this.sentry.close(i)}shouldIgnoreError(i){let c=this.config.filters;if(!c)return!1;if(c.ignoreCodes?.includes(i.code))return!0;if(c.ignoreErrors?.some((P)=>{if(typeof P==="string")return i.message.includes(P);return P.test(i.message)}))return!0;return!1}mapSeverityToLevel(i){switch(i){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(i){let c=[];if(c.push(i.code),c.push(i.category),i.context.route)c.push(i.context.route);return c}}class qr{config;bugsnag;constructor(i){this.config=i,this.initializeBugsnag()}async initializeBugsnag(){try{let i=await import("@bugsnag/js");i.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(c)=>{let P=c.originalError;if(P&&this.config.beforeSend)return this.config.beforeSend(P,P.context)!==null;return!this.shouldIgnoreError(P)}}),this.bugsnag=i}catch(i){console.warn("Failed to initialize Bugsnag:",i)}}async report(i,c){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(i))return null;let P={...i.context,...c};return this.bugsnag.notify(i,(M)=>{if(M.severity=this.mapSeverityToBugsnag(i.severity),M.context=P.route||P.url,P.userId)M.setUser(P.userId,void 0,void 0);M.addMetadata("error",{code:i.code,category:i.category,statusCode:i.statusCode,retryable:i.retryable,timestamp:i.timestamp}),M.addMetadata("request",{requestId:P.requestId,method:P.method,url:P.url,userAgent:P.userAgent,ip:P.ip}),M.groupingHash=this.generateGroupingHash(i)}),"reported"}catch(P){return console.error("Failed to report error to Bugsnag:",P),null}}addBreadcrumb(i,c="manual",P="info",M){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(i,M,c)}setUser(i){if(!this.bugsnag)return;this.bugsnag.setUser(i.id,i.email,i.username)}setTag(i,c){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[i]:c})}setExtra(i,c){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[i]:c})}setContext(i,c){if(!this.bugsnag)return;this.bugsnag.addMetadata(i,c)}async close(){return!0}shouldIgnoreError(i){let c=this.config.filters;if(!c)return!1;if(c.ignoreCodes?.includes(i.code))return!0;if(c.ignoreErrors?.some((P)=>{if(typeof P==="string")return i.message.includes(P);return P.test(i.message)}))return!0;return!1}mapSeverityToBugsnag(i){switch(i){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(i){return`${i.code}-${i.category}-${i.context.route||"unknown"}`}}class an{config;reportHandler;constructor(i,c){this.config=i,this.reportHandler=c}async report(i,c){if(!this.config.enabled)return null;try{let P={...i.context,...c};if(this.config.beforeSend){if(!this.config.beforeSend(i,P))return null}let M={error:i,context:P,level:this.mapSeverityToLevel(i.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(M)}catch(P){return console.error("Failed to report error with custom handler:",P),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(i){switch(i){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class Vt{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(i){this.initializeReporters(i)}initializeReporters(i){for(let c of i){if(!c.enabled)continue;switch(c.service){case"sentry":this.reporters.push(new Ar(c));break;case"bugsnag":this.reporters.push(new qr(c));break;case"custom":break}}}addReporter(i){this.reporters.push(i)}async report(i,c){let P=[];this.addBreadcrumb(`Error occurred: ${i.message}`,"error",{code:i.code,severity:i.severity});let M=this.reporters.map(async(U)=>{try{let z=await U.report(i,c);if(z)P.push(z)}catch(z){console.error("Reporter failed:",z)}});return await Promise.allSettled(M),P}addBreadcrumb(i,c="default",P){if(this.breadcrumbs.push({message:i,timestamp:new Date,data:{category:c,...P}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((M)=>{M.addBreadcrumb(i,c,"info",P)})}setUser(i){this.reporters.forEach((c)=>c.setUser(i))}setTag(i,c){this.reporters.forEach((P)=>P.setTag(i,c))}setExtra(i,c){this.reporters.forEach((P)=>P.setExtra(i,c))}setContext(i,c){this.reporters.forEach((P)=>P.setContext(i,c))}async close(i=5000){let c=this.reporters.map((M)=>M.close(i));return(await Promise.allSettled(c)).every((M)=>M.status==="fulfilled"&&M.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function Gs(i){return new Vt(i)}var Ws={sentry:(i,c="production")=>({enabled:!0,service:"sentry",dsn:i,environment:c,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:(i,c="production")=>({enabled:!0,service:"bugsnag",apiKey:i,environment:c,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class Or{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(i){this.config=i,this.initializeHealthChecks()}initializeHealthChecks(){for(let[i,c]of Object.entries(this.config.healthChecks)){if(!c.enabled)continue;this.healthStatus.set(i,{name:i,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let P=setInterval(()=>this.performHealthCheck(i,c),c.interval);P.unref?.(),this.healthCheckIntervals.set(i,P)}}async performHealthCheck(i,c){let P=Date.now(),M=!1;try{let z=new AbortController,de=setTimeout(()=>z.abort(),c.timeout),pe=await fetch(c.endpoint,{signal:z.signal,headers:c.headers,method:"GET"});if(clearTimeout(de),M=c.expectedStatus.includes(pe.status),M&&c.expectedBody){let Re=await pe.text();if(typeof c.expectedBody==="string")M=Re.includes(c.expectedBody);else M=c.expectedBody.test(Re)}}catch(z){console.error(z),M=!1}let U=Date.now()-P;if(this.updateHealthStatus(i,M,U),M&&c.onHealthy)c.onHealthy();else if(!M&&c.onUnhealthy)c.onUnhealthy(Error(`Health check failed for ${i}`))}updateHealthStatus(i,c,P){let M=this.healthStatus.get(i);if(!M)return;let U={...M,lastCheck:new Date,responseTime:P,consecutiveFailures:c?0:M.consecutiveFailures+1};if(U.consecutiveFailures===0)U.status="healthy";else if(U.consecutiveFailures<3)U.status="degraded";else U.status="unhealthy";let z=c?1:0;U.availability=M.availability*0.9+z*10,this.healthStatus.set(i,U)}getServiceHealth(i){return this.healthStatus.get(i)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(i){return this.healthStatus.get(i)?.status==="healthy"}isServiceDegraded(i){return this.healthStatus.get(i)?.status==="degraded"}stop(){for(let i of this.healthCheckIntervals.values())clearInterval(i);this.healthCheckIntervals.clear()}}class Jt{config;healthMonitor;cache=new Map;metrics=new Map;constructor(i){this.config=i,this.healthMonitor=new Or(i)}async handleFailure(i,c,P,M){if(!this.config.enabled)throw c;let U=this.config.fallbackStrategies[i];if(!U)throw c;let z={request:P,serviceName:i,error:c,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(U,z,M)}async executeFallbackStrategy(i,c,P){if(c.attemptCount<=i.retries)try{if(c.attemptCount>1){let z=this.calculateBackoffDelay(i.backoff,c.attemptCount);await this.sleep(z)}let M=new Promise((z,de)=>{setTimeout(()=>de(Error("Timeout")),i.timeout)}),U=await Promise.race([P(),M]);return this.updateMetrics(c.serviceName,!0,Date.now()-c.startTime.getTime()),U}catch(M){if(console.error(M),c.attemptCount++,c.attemptCount<=i.retries)return this.executeFallbackStrategy(i,c,P)}switch(this.updateMetrics(c.serviceName,!1,Date.now()-c.startTime.getTime()),i.type){case"cache":return this.handleCacheFallback(i,c);case"static":return this.handleStaticFallback(i,c);case"simplified":return this.handleSimplifiedFallback(i,c);case"redirect":return this.handleRedirectFallback(i,c);case"custom":return this.handleCustomFallback(i,c);default:throw c.error}}async handleCacheFallback(i,c){if(!i.cacheConfig)throw c.error;let P=this.generateCacheKey(i.cacheConfig.key,c),M=this.cache.get(P);if(M&&(M.expires>new Date||i.cacheConfig.staleWhileRevalidate)){let U=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"});if(i.cacheConfig.staleWhileRevalidate&&M.expires<=new Date)U.set("X-Cache","STALE");return new Response(JSON.stringify(M.data),{status:200,headers:U})}throw c.error}async handleStaticFallback(i,c){if(!i.staticResponse)throw c.error;let P=new Headers(i.staticResponse.headers||{});return P.set("X-Degraded","true"),P.set("X-Fallback-Type","static"),P.set("X-Service-Status",this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"),new Response(typeof i.staticResponse.body==="string"?i.staticResponse.body:JSON.stringify(i.staticResponse.body),{status:i.staticResponse.status,headers:P})}async handleSimplifiedFallback(i,c){let P={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:c.request.requestId};return new Response(JSON.stringify(P),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"}})}async handleRedirectFallback(i,c){if(!i.redirectConfig)throw c.error;return new Response(null,{status:i.redirectConfig.permanent?301:302,headers:{Location:i.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(i,c){if(!i.fallbackHandler)throw c.error;try{let P=await i.fallbackHandler(c.error,c.error.context);return P.headers.set("X-Degraded","true"),P.headers.set("X-Fallback-Type","custom"),P.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"),P}catch(P){throw console.error(P),c.error}}cacheResponse(i,c,P,M){let U=this.config.fallbackStrategies[i];if(U?.type==="cache"&&U.cacheConfig){let z=this.generateCacheKey(c,{serviceName:i});this.cache.set(z,{data:P,expires:new Date(Date.now()+M*1000)})}}getServiceMetrics(i){let c=this.metrics.get(i);if(!c||c.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:c.errors/c.requests*100,avgResponseTime:c.totalTime/c.requests,totalRequests:c.requests}}getSystemHealth(){let i=this.healthMonitor.getAllServiceHealth(),c=i.filter((U)=>U.status==="unhealthy").length,P=i.filter((U)=>U.status==="degraded").length,M="healthy";if(c>0)M=c>i.length/2?"unhealthy":"degraded";else if(P>0)M="degraded";return{status:M,services:i}}calculateBackoffDelay(i,c){if(i.type==="fixed")return i.delay;let P=i.delay*2**(c-1);return Math.min(P,i.maxDelay||30000)}generateCacheKey(i,c){return i.replace("{service}",c.serviceName).replace("{url}",c.request.url).replace("{method}",c.request.method).replace("{userId}",String(c.request.user?.id||"anonymous"))}updateMetrics(i,c,P){let M=this.metrics.get(i)||{requests:0,errors:0,totalTime:0};if(M.requests++,M.totalTime+=P,!c)M.errors++;this.metrics.set(i,M)}sleep(i){return new Promise((c)=>setTimeout(c,i))}stop(){this.healthMonitor.stop()}}function Vs(i){let c=new Jt(i);return async(P,M)=>{try{let U=await M(),z=P.context?.serviceName;if(z&&U.ok){let de=i.fallbackStrategies[z];if(de?.type==="cache"&&de.cacheConfig)try{let pe=await U.clone().json();c.cacheResponse(z,de.cacheConfig.key,pe,de.cacheConfig.ttl)}catch{}}return U}catch(U){let z=P.context?.serviceName;if(z&&U instanceof Error){let de=U;try{return await c.handleFailure(z,de,P,M)}catch(pe){throw console.error(pe),U}}throw U}}}var Js={cacheFirst:(i=3600,c=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:i,staleWhileRevalidate:c}}),staticFallback:(i,c=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:c,body:i,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(i)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:i,permanent:!1}})};class un{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(i={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...i},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new Vt(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new Jt(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new Nt;for(let i of this.config.circuitBreakers)this.circuitBreakerRegistry.register(i)}}middleware(){return async(i,c)=>{try{let P={requestId:i.requestId,userId:i.user?.id,traceId:i.traceId,spanId:i.spanId,route:i.params?.route||i.url,method:i.method,url:i.url,userAgent:i.userAgent?.()||void 0,ip:i.ip?.()||void 0,timestamp:new Date};if(i.context={...i.context,errorContext:P},this.circuitBreakerRegistry&&i.context?.serviceName){let M=this.circuitBreakerRegistry.get(i.context.serviceName);if(M)return await M.execute({execute:c,context:P})}return await c()}catch(P){return this.handleError(P,i)}}}async handleError(i,c){let P=this.normalizeError(i,c);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${c.method} ${c.url}`,"error",{code:P.code,severity:P.severity,statusCode:P.statusCode});if(this.config.logErrors)this.logError(P,c);if(this.gracefulDegradation&&c.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(c.context.serviceName,P,c,async()=>{throw P})}catch{}if(this.errorReporting)try{await this.errorReporting.report(P,P.context)}catch(U){console.error("Failed to report error:",U)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler(P,c)}catch(U){console.error("Global error handler failed:",U)}let M=this.config.customErrorPages?.[P.statusCode];if(M)try{if(typeof M==="string")return new Response(M,{status:P.statusCode,headers:{"Content-Type":"text/html"}});else return await M(P,c)}catch(U){console.error("Custom error page failed:",U)}return this.createErrorResponse(P,c)}normalizeError(i,c){let P={requestId:c.requestId,userId:c.user?.id,traceId:c.traceId,spanId:c.spanId,route:c.params?.route||c.url,method:c.method,url:c.url,userAgent:c.userAgent?.()||void 0,ip:c.ip?.()||void 0,timestamp:new Date,metadata:c.context};if(i instanceof t)return i;if(i instanceof Error){if(i.name==="ValidationError")return s.validation(i.message,{},P);if(i.name==="UnauthorizedError"||i.message.includes("unauthorized"))return s.authentication(i.message,P);if(i.name==="ForbiddenError"||i.message.includes("forbidden"))return s.authorization(i.message,[],P);if(i.name==="NotFoundError"||i.message.includes("not found"))return s.notFound(void 0,void 0,P);if(i.name==="TimeoutError"||i.message.includes("timeout"))return s.timeout(30000,i.message,P);return s.internalServer(i.message,i,P)}if(typeof i==="string")return s.internalServer(i,void 0,P);return s.internalServer("An unknown error occurred",void 0,P)}createErrorResponse(i,c){let P=this.config.development,M=this.config.includeStackTrace||P,U=this.config.sanitizeErrors&&!P,z=i.message;if(U&&i.statusCode>=500)z="An internal server error occurred";let de={error:{code:i.code,message:z,statusCode:i.statusCode,timestamp:i.timestamp.toISOString(),requestId:i.context.requestId,traceId:i.context.traceId}};if(P)de.error.category=i.category,de.error.severity=i.severity,de.error.retryable=i.retryable,de.error.context=i.context;if(M){if(de.error.stack=i.stack,i.cause)de.error.cause={name:i.cause.name,message:i.cause.message,stack:i.cause.stack}}if("fields"in i)de.error.fields=i.fields;if("allowedMethods"in i)de.error.allowedMethods=i.allowedMethods;if("retryAfter"in i)de.error.retryAfter=i.retryAfter;let pe=new Headers({"Content-Type":"application/json","X-Error-Code":i.code,"X-Request-ID":i.context.requestId||"","X-Trace-ID":i.context.traceId||""});if("allowedMethods"in i)pe.set("Allow",i.allowedMethods.join(", "));if("retryAfter"in i)pe.set("Retry-After",i.retryAfter.toString());if("limit"in i)pe.set("X-RateLimit-Limit",i.limit.toString()),pe.set("X-RateLimit-Remaining",i.remaining.toString());return new Response(JSON.stringify(de),{status:i.statusCode,headers:pe})}logError(i,c){let P={error:i.toJSON(),request:{method:c.method,url:c.url,headers:Object.fromEntries(c.headers.entries()),userAgent:c.userAgent?.()||void 0,ip:c.ip?.()||void 0,requestId:c.requestId,traceId:c.traceId}};switch(i.severity){case"critical":console.error("[CRITICAL ERROR]",P);break;case"high":console.error("[ERROR]",P);break;case"medium":console.warn("[WARNING]",P);break;case"low":console.warn("[INFO]",P);break;default:console.error("[ERROR]",P)}}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 cn(i={}){let c=new un(i);return{middleware:c.middleware(),getStats:()=>c.getStats(),cleanup:()=>c.cleanup()}}function Ft(i){if(!i.includes("%"))return i;try{return decodeURIComponent(i)}catch{return i}}function cr(i){let{read:c,write:P,remove:M}=i,U=()=>({...c()});for(let[z,de]of Object.entries(c()))Object.defineProperty(U,z,{value:de,writable:!0,enumerable:!0,configurable:!0});return U.get=(z)=>c()[z],U.set=(z,de,pe={})=>P?.(z,de,pe),U.delete=(z,de={})=>M?.(z,de),U.getAll=()=>({...c()}),U}function Ut(i={}){let c={...i};return cr({read:()=>c,write:(P,M)=>{c[P]=M},remove:(P)=>{delete c[P]}})}import{AsyncLocalStorage as Ks}from"async_hooks";var $r=new Ks,lr=!1,At=null;function Xs(){lr=!0}function dr(i,c){if(!lr){At=i;let P=c();if(P instanceof Promise)return P.finally(()=>{At=null});return At=null,P}return $r.run({current:i},c)}function pr(i){let c=$r.getStore();if(c){c.current=i;return}if(At!==null)At=i}function dn(){if(!lr)return lr=!0,At??void 0;return $r.getStore()?.current??At??void 0}function Qs(){let i=dn();if(!i)throw Error("request() called outside a request scope. It can only be invoked from within a route handler or middleware.");return i}var pn={enabled:!0,level:6,threshold:1024};function hn(i){if(!i)return!1;let c=i.split(";")[0]?.trim().toLowerCase()??"";if(c==="text/event-stream")return!1;if(c.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(c)}function Zs(i){if(!i)return null;let c=new Map;for(let M of i.split(",")){let[U="",...z]=M.trim().split(";"),de=z.map((pe)=>/^\s*q=([\d.]+)\s*$/i.exec(pe)).find(Boolean);c.set(U.trim().toLowerCase(),de?Number(de[1]):1)}let P=(M)=>(c.get(M)??c.get("*")??0)>0;if(P("gzip"))return"gzip";if(P("deflate"))return"deflate";return null}function Ys(i,c,P){if(!c)return!1;if(i.status===204||i.status===304||i.status===206)return!1;if(i.headers.has("content-encoding"))return!1;if(!hn(i.headers.get("content-type")))return!1;let M=Number(i.headers.get("content-length")??Number.NaN);if(Number.isFinite(M)&&!(M>=P))return!1;return Boolean(i.body)}function Br(i,c,P={}){if(!(P.enabled??pn.enabled))return i;let U=P.threshold??pn.threshold,z=c.headers.get("accept-encoding"),de=z?Number(i.headers.get("content-length")??Number.NaN):Number.NaN,pe=Number.isFinite(de)&&!(de>=U)?null:Zs(z);if(!Ys(i,pe,U)){if(hn(i.headers.get("content-type"))&&!i.headers.has("content-encoding"))Dr(i.headers,"Accept-Encoding");return i}let Re=Number(i.headers.get("content-length")??Number.NaN);if(!Number.isFinite(Re))return ei(i,pe,U);return gn(i,i.body,pe)}async function Io(i,c,P={}){return Br(i,c,P)}async function ei(i,c,P){let M=await ti(i.body,P);if(M.ended&&M.size<P){let U=new Headers(i.headers);return Dr(U,"Accept-Encoding"),new Response(M.stream,{status:i.status,statusText:i.statusText,headers:U})}return gn(i,M.stream,c)}function gn(i,c,P){let M=new Headers(i.headers);M.set("Content-Encoding",P),Dr(M,"Accept-Encoding"),M.delete("Content-Length");let U=c.pipeThrough(new CompressionStream(P==="gzip"?"gzip":"deflate"));return new Response(U,{status:i.status,statusText:i.statusText,headers:M})}async function ti(i,c){let P=i.getReader(),M=[],U=0,z=!1;while(U<c){let{value:pe,done:Re}=await P.read();if(Re){z=!0;break}if(pe)M.push(pe),U+=pe.byteLength}return{stream:new ReadableStream({start(pe){for(let Re of M)pe.enqueue(Re);if(z)pe.close()},async pull(pe){if(z)return;let{value:Re,done:Te}=await P.read();if(Te){z=!0,pe.close();return}if(Re)pe.enqueue(Re)},cancel(pe){return P.cancel(pe)}}),size:U,ended:z}}function Dr(i,c){let P=i.get("vary");if(!P){i.set("Vary",c);return}let M=P.split(",").map((U)=>U.trim().toLowerCase());if(M.includes("*")||M.includes(c.toLowerCase()))return;i.set("Vary",`${P}, ${c}`)}var ke={json:(i,c={})=>{let P=typeof c==="number"?{status:c}:c,{status:M=200,headers:U={},pretty:z=!1}=P,de=z?JSON.stringify(i,null,2):JSON.stringify(i);return new Response(de,{status:M,headers:{"Content-Type":"application/json",...U}})},noContent:(i={})=>new Response(null,{status:204,headers:i}),download:async(i,c,P={})=>{let M=Bun.file(i);if(!await M.exists())return new Response("File not found",{status:404});let z=c||i.split("/").pop()||"download",de=M.type||"application/octet-stream";return new Response(M,{status:200,headers:{"Content-Type":de,"Content-Disposition":`attachment; filename="${z}"`,"Content-Length":String(M.size),...P}})},file:async(i,c={})=>{let P=Bun.file(i);if(!await P.exists())return new Response("File not found",{status:404});let U=P.type||"application/octet-stream";return new Response(P,{status:200,headers:{"Content-Type":U,"Content-Length":String(P.size),...c}})},streamDownload:(i,c,P={})=>{let{contentType:M="application/octet-stream",headers:U={}}=P,z=new ReadableStream({async start(de){try{for await(let pe of i())if(typeof pe==="string")de.enqueue(new TextEncoder().encode(pe));else de.enqueue(pe);de.close()}catch(pe){de.error(pe)}}});return new Response(z,{status:200,headers:{"Content-Type":M,"Content-Disposition":`attachment; filename="${c}"`,"Transfer-Encoding":"chunked",...U}})},redirect:(i,c=302)=>new Response(null,{status:c,headers:{Location:i}}),redirectPermanent:(i)=>ke.redirect(i,301),redirectTemporary:(i)=>ke.redirect(i,302),back:(i,c="/")=>{let P=i.headers.get("referer")||c;return ke.redirect(P)},view:(i,c=200,P={})=>new Response(i,{status:c,headers:{"Content-Type":"text/html; charset=utf-8",...P}}),text:(i,c=200,P={})=>new Response(i,{status:c,headers:{"Content-Type":"text/plain; charset=utf-8",...P}}),xml:(i,c=200,P={})=>new Response(i,{status:c,headers:{"Content-Type":"application/xml; charset=utf-8",...P}}),success:(i,c,P=200)=>{let M={success:!0};if(i!==void 0)M.data=i;if(c!==void 0)M.message=c;return ke.json(M,{status:P})},error:(i,c=400,P)=>{let M={success:!1,message:i};if(P!==void 0)M.errors=P;return ke.json(M,{status:c})},paginate:(i,c)=>{let{page:P,perPage:M,total:U,path:z}=c,de=Math.ceil(U/M),pe=(P-1)*M+1,Re=Math.min(P*M,U);return ke.json({data:i,meta:{current_page:P,per_page:M,total:U,last_page:de,from:pe,to:Re,path:z,first_page_url:`${z}?page=1`,last_page_url:`${z}?page=${de}`,next_page_url:P<de?`${z}?page=${P+1}`:null,prev_page_url:P>1?`${z}?page=${P-1}`:null}})},created:(i,c)=>{let P={};if(c)P.Location=c;let M={success:!0};if(i!==void 0)M.data=i;return ke.json(M,{status:201,headers:P})},accepted:(i)=>{let c={success:!0};if(i!==void 0)c.data=i;return ke.json(c,{status:202})},notFound:(i="Resource not found")=>ke.error(i,404),unauthorized:(i="Unauthorized")=>ke.error(i,401),forbidden:(i="Forbidden")=>ke.error(i,403),badRequest:(i="Bad request",c)=>ke.error(i,400,c),validationError:(i,c="Validation failed")=>ke.error(c,422,i),unprocessableEntity:(i="Unprocessable entity",c)=>ke.error(i,422,c),serverError:(i="Internal server error")=>ke.error(i,500),tooManyRequests:(i="Too many requests",c)=>{let P={};if(c)P["Retry-After"]=String(c);return new Response(JSON.stringify({message:i}),{status:429,headers:{"Content-Type":"application/json",...P}})}};class mn{_status=200;_headers={};_cookies=[];_deleteCookies=[];status(i){return this._status=i,this}header(i,c){return this._headers[i]=c,this}withHeaders(i){return this._headers={...this._headers,...i},this}cookie(i,c,P={}){return this._cookies.push({name:i,value:c,options:P}),this}withoutCookie(i,c={}){return this._deleteCookies.push({name:i,options:c}),this}json(i){let c=ke.json(i,{status:this._status,headers:this._headers});return this.applyCookies(c)}text(i){let c=ke.text(i,this._status,this._headers);return this.applyCookies(c)}html(i){let c=ke.view(i,this._status,this._headers);return this.applyCookies(c)}noContent(){let i=ke.noContent(this._headers);return this.applyCookies(i)}applyCookies(i){let c=new Headers(i.headers);for(let{name:P,value:M,options:U}of this._cookies){let z=this.serializeCookie(P,M,U);c.append("Set-Cookie",z)}for(let{name:P,options:M}of this._deleteCookies){let U=this.serializeCookie(P,"",{...M,maxAge:0,expires:new Date(0)});c.append("Set-Cookie",U)}return new Response(i.body,{status:i.status,headers:c})}serializeCookie(i,c,P){let M=`${encodeURIComponent(i)}=${encodeURIComponent(c)}`;if(P.maxAge!==void 0)M+=`; Max-Age=${P.maxAge}`;if(P.expires)M+=`; Expires=${P.expires.toUTCString()}`;if(P.httpOnly)M+="; HttpOnly";if(P.secure)M+="; Secure";if(P.path)M+=`; Path=${P.path}`;if(P.domain)M+=`; Domain=${P.domain}`;if(P.sameSite)M+=`; SameSite=${P.sameSite.charAt(0).toUpperCase()+P.sameSite.slice(1)}`;return M}}function jo(){return new mn}import ri from"process";class Nr{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(i){this.dependencyRegistry.set(i.name,i)}compileMiddleware(i,c,P=[]){let M=[];for(let U=0;U<c.length;U++){let z=c[U],de=z.name||`middleware_${U}`;M.push({handler:z,name:de,skipConditions:P.filter((pe)=>pe.name.includes(de)||pe.name==="global"),dependencies:this.extractDependencies(z),canShortCircuit:this.canShortCircuit(z),priority:U})}this.compiledPipelines.set(i,M)}async execute(i,c,P){let M=performance.now();this.stats.totalExecutions++;let U=this.compiledPipelines.get(i);if(!U)return this.stats.cacheMisses++,await P();this.stats.cacheHits++;let z={request:c,dependencies:new Map,metadata:{}};await this.resolveDependencies(z,U);let de=0,pe=async()=>{if(de>=U.length)return await P();let xe=U[de++];if(await this.shouldSkip(xe,z))return this.stats.skippedMiddleware++,await pe();let ve=await xe.handler(c,pe);if(ve instanceof Response&&xe.canShortCircuit)return this.stats.shortCircuits++,ve;return ve},Re=await pe(),Te=performance.now()-M;return this.updateAverageExecutionTime(Te),Re||new Response("Internal Server Error",{status:500})}async shouldSkip(i,c){for(let P of i.skipConditions)if(await P.condition(c))return!0;return!1}async resolveDependencies(i,c){let P=new Set;for(let M of c)for(let U of M.dependencies)P.add(U);for(let M of P){let U=this.dependencyRegistry.get(M);if(!U)continue;if(this.stats.dependencyResolutions++,U.singleton&&this.singletonInstances.has(M))i.dependencies.set(M,this.singletonInstances.get(M));else{let z=await U.factory(i);if(i.dependencies.set(M,z),U.singleton)this.singletonInstances.set(M,z)}}}extractDependencies(i){let c=i.toString(),P=[];if(c.includes("database")||c.includes("db"))P.push("database");if(c.includes("logger")||c.includes("log"))P.push("logger");if(c.includes("cache"))P.push("cache");if(c.includes("httpClient")||c.includes("http"))P.push("httpClient");return P}canShortCircuit(i){let c=i.toString();return c.includes("return")&&c.includes("Response")}updateAverageExecutionTime(i){let c=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(c+i)/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 ni={skipForMethods:(i)=>({name:`skip_for_methods_${i.join("_")}`,condition:(c)=>i.includes(c.request.method)}),skipForPaths:(i)=>({name:`skip_for_paths_${i.join("_").replace(/\//g,"_")}`,condition:(c)=>{let P=new URL(c.request.url);return i.some((M)=>P.pathname.startsWith(M))}}),skipForHeaders:(i)=>({name:`skip_for_headers_${Object.keys(i).join("_")}`,condition:(c)=>Object.entries(i).some(([P,M])=>c.request.headers.get(P)===M)}),skipForRoles:(i)=>({name:`skip_for_roles_${i.join("_")}`,condition:(c)=>{let P=c.request.user?.roles||[];return!i.some((M)=>P.includes(M))}}),skipForEnvironment:(i)=>({name:`skip_for_env_${i.join("_")}`,condition:()=>{let c=ri.env.NODE_ENV||"development";return i.includes(c)}})},si={database:(i)=>({name:"database",factory:async()=>({query:async(c)=>({rows:[]}),close:async()=>{},connectionString:i||"mock://database"}),singleton:!0}),logger:(i="info")=>({name:"logger",factory:()=>({info:(c)=>console.log(`[INFO] ${c}`),error:(c)=>console.error(`[ERROR] ${c}`),warn:(c)=>console.warn(`[WARN] ${c}`),debug:(c)=>console.debug(`[DEBUG] ${c}`),level:i}),singleton:!0}),cache:(i=1000)=>({name:"cache",factory:()=>{let c=new Map;return{get:(P)=>c.get(P),set:(P,M)=>{if(c.size>=i){let U=c.keys().next().value;c.delete(U)}c.set(P,M)},delete:(P)=>c.delete(P),clear:()=>c.clear(),size:()=>c.size}},singleton:!0}),httpClient:(i)=>({name:"httpClient",factory:()=>({get:async(c)=>fetch(i?`${i}${c}`:c),post:async(c,P)=>fetch(i?`${i}${c}`:c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}),put:async(c,P)=>fetch(i?`${i}${c}`:c,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}),delete:async(c)=>fetch(i?`${i}${c}`:c,{method:"DELETE"})}),singleton:!0})},ii={auth:(i={})=>async(c,P)=>{let M=new URL(c.url);if(i.skipPaths?.some((z)=>M.pathname.startsWith(z)))return await P();if(!c.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return c.user={id:"123",roles:["user"]},await P()}catch{return new Response("Invalid token",{status:401})}},rateLimit:(i)=>{let c=new Map;return async(P,M)=>{let U=P.headers.get("x-forwarded-for")||"unknown",z=Date.now(),de=z-i.windowMs;if(!c.has(U))c.set(U,[]);let Re=c.get(U).filter((Te)=>Te>de);if(Re.length>=i.maxRequests)return new Response("Too Many Requests",{status:429});return Re.push(z),c.set(U,Re),await M()}},cors:(i={})=>async(c,P)=>{let M=await P();if(M){let U=new Headers(M.headers);return U.set("Access-Control-Allow-Origin",i.origin||"*"),U.set("Access-Control-Allow-Methods",i.methods?.join(", ")||"GET, POST, PUT, DELETE"),U.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(M.body,{status:M.status,statusText:M.statusText,headers:U})}return M},logging:(i={})=>async(c,P)=>{let M=performance.now(),U=new URL(c.url);console.log(`[${new Date().toISOString()}] ${c.method} ${U.pathname}`);let z=await P(),de=performance.now()-M;if(z)console.log(`[${new Date().toISOString()}] ${c.method} ${U.pathname} - ${z.status} (${de.toFixed(2)}ms)`);return z}},oi=new Nr;import{existsSync as Rn,readdirSync as ai,statSync as ui}from"fs";import{basename as yn,extname as fn,join as ci,resolve as wn}from"path";var li=[".ts",".js"],di=["routes","src/routes"],pi=["web","index"];function hi(){let i=process.cwd();for(let c of di){let P=wn(i,c);if(Rn(P)&&ui(P).isDirectory())return P}return null}function bn(i,c){let P=[];if(!Rn(i))return P;let M=ai(i,{withFileTypes:!0});for(let U of M){if(U.name.startsWith(".")||U.name.startsWith("_"))continue;let z=ci(i,U.name);if(U.isDirectory())P.push(...bn(z,c));else if(li.includes(fn(U.name))){let de=i===c?"":i.slice(c.length),pe=yn(U.name,fn(U.name)),Re=pi.includes(pe)?de||"":`${de}/${pe}`;P.push({filePath:z,prefix:Re})}}return P}async function gi(i,c,P,M){try{let U=await import(c),z=0,de=i.routes?.length||0;if(typeof U.default==="function"){let pe=mi(i,P);await U.default(pe),z=(i.routes?.length||0)-de}else if(Array.isArray(U.routes))for(let pe of U.routes){let Re=(pe.method||"GET").toLowerCase(),Te=`${P}${pe.path}`;if(typeof i[Re]==="function")await i[Re](Te,pe.handler),z++}if(M&&z>0)console.log(` ${P||"/"} \u2192 ${yn(c)} (${z} routes)`);return z}catch(U){return console.error(`[bun-router] Failed to load route file ${c}:`,U),0}}function mi(i,c){if(!c)return i;let P=["get","post","put","patch","delete","options","any"];return new Proxy(i,{get(M,U){if(P.includes(U))return async(z,...de)=>M[U](`${c}${z}`,...de);if(U==="group")return async(z,de)=>{let pe=z.prefix?`${c}${z.prefix}`:c;return M.group({...z,prefix:pe},de)};return M[U]}})}function Tn(i){Object.defineProperties(i.prototype,{_routesDir:{value:null,writable:!0,configurable:!0},_apiRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initApiRoutes:{async value(){if(this._apiRoutesInitialized)return;let c=this._routesDir||hi();if(!c){this._apiRoutesInitialized=!0;return}let P=this.config?.verbose||!1,M=bn(c,c);if(M.length===0){this._apiRoutesInitialized=!0;return}if(P)console.log(`[bun-router] Auto-discovering API routes from ${c}:`);let U=0;for(let{filePath:z,prefix:de}of M)U+=await gi(this,z,de,P);if(U>0&&P)console.log(`[bun-router] Registered ${U} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(c){return this._routesDir=wn(c),this},writable:!0,configurable:!0}})}import{join as Kt,relative as Fr,resolve as Pt,dirname as Ri}from"path";import{readdirSync as xn,statSync as yi,existsSync as gr}from"fs";var Ko={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function fi(i){let{preserve:c=[],exclude:P=[],routes:M=[]}=i;if(!c.length)return"";return`<script data-query-preservation>
2
+ import{qe,s,me,wt,e,ge,W,fe,He,Be,je,Ue,Le,h,r,m,A,G,g,n,ye,f,_e,ze,Ve,u,O,I,F,bt,K,D,y,w,We,b,Ge,S,c,Ke,Je,Xe,Ye,Qe,E,R,Ze,N,et,q,tt,H,rt,B,nt,v,st,j,it,Rt,vt,xt,Tt,Ct,St,J}from"./chunk-7s1kcj7w.js";import{t,d,X,Y,Q,Z,x,ee,te,re,ne,T,C,se,ie,oe,i,P,p,ae,U,ce,le,ot,at,ct,a,_,we,be,Re,z,ue,de}from"./chunk-sccx6r6k.js";function Or(o){return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function pr(o){o=o.replace(/-/g,"+").replace(/_/g,"/");while(o.length%4)o+="=";return atob(o)}class an{secret;constructor(o){this.secret=o}sign(o,l={}){let M={alg:l.algorithm||"HS256",typ:"JWT",...l.header},k=Math.floor(Date.now()/1000),L={...o,iat:k};if(l.expiresIn){let xe=typeof l.expiresIn==="string"?this.parseTimespan(l.expiresIn):l.expiresIn;L.exp=k+xe}if(l.notBefore){let xe=typeof l.notBefore==="string"?this.parseTimespan(l.notBefore):l.notBefore;L.nbf=k+xe}if(l.issuer)L.iss=l.issuer;if(l.subject)L.sub=l.subject;if(l.audience)L.aud=l.audience;if(l.jwtid)L.jti=l.jwtid;let V=Or(JSON.stringify(M)),pe=Or(JSON.stringify(L)),he=`${V}.${pe}`,Te=this.createSignature(he,this.secret,M.alg);return`${he}.${Te}`}verify(o,l={}){try{let M=o.split(".");if(M.length!==3)throw Error("Token structure invalid");let[k,L,V]=M,pe=JSON.parse(pr(k)),he=JSON.parse(pr(L));if(l.algorithms&&!l.algorithms.includes(pe.alg))throw Error(`Algorithm ${pe.alg} not allowed`);let Te=`${k}.${L}`,xe=this.createSignature(Te,this.secret,pe.alg),ve=Buffer.from(V),Pe=Buffer.from(xe);if(ve.length!==Pe.length||!s().timingSafeEqual(ve,Pe))throw Error("Invalid signature");let Ce=Math.floor(Date.now()/1000);if(he.exp&&!l.ignoreExpiration&&Ce>=he.exp)throw Error("Token expired");if(he.nbf&&Ce<he.nbf)throw Error("Token not active yet");if(he.iat&&he.iat>Ce)throw Error("Token used before issued");if(l.issuer&&he.iss!==l.issuer)throw Error("Invalid issuer");if(l.audience&&he.aud!==l.audience)throw Error("Invalid audience");if(l.subject&&he.sub!==l.subject)throw Error("Invalid subject");return he}catch{return null}}decode(o){try{let l=o.split(".");if(l.length!==3)return null;let[M,k]=l;return{header:JSON.parse(pr(M)),payload:JSON.parse(pr(k))}}catch{return null}}createSignature(o,l,M){return Or(JSON.stringify({data:o,secret:l.slice(0,5),alg:M}))}parseTimespan(o){let l=o.match(/^(\d+)\s*([smhd])$/i);if(!l)return Number.parseInt(o,10)||0;let M=Number.parseInt(l[1],10);switch(l[2].toLowerCase()){case"s":return M;case"m":return M*60;case"h":return M*60*60;case"d":return M*24*60*60;default:return M}}}class un{keys;options;constructor(o={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...o}}generateKey(o,l=[],M){let k=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(k,{owner:o,scopes:l,expiresAt:M?new Date(Date.now()+M*1000):void 0}),k}validateKey(o,l=[]){let M=this.keys.get(o);if(!M)return!1;if(M.expiresAt&&M.expiresAt<new Date)return!1;if(l.length>0)return l.every((k)=>M.scopes.includes(k));return!0}getKeyInfo(o){return this.keys.get(o)||null}revokeKey(o){return this.keys.delete(o)}extractFromRequest(o){let{source:l,keyName:M}=this.options;switch(l){case"header":return o.headers.get(M||"X-API-Key")||null;case"query":return new URL(o.url).searchParams.get(M||"api_key")||null;case"cookie":if(o.cookies){let k=M||"api_key";if(typeof o.cookies.get==="function")return o.cookies.get(k)||null;return o.cookies[k]||null}return null;default:return null}}randomString(o){let M="";for(let k=0;k<o;k++)M+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return M}}class cn{config;constructor(o){this.config=o}getAuthorizationUrl(o={}){let l=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...o});if(this.config.scope)l.set("scope",this.config.scope);if(this.config.state)l.set("state",this.config.state);return`${this.config.authorizeUrl}?${l.toString()}`}async exchangeCodeForToken(o){let l=new URLSearchParams({grant_type:"authorization_code",code:o,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),M=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!M.ok)throw Error(`OAuth token exchange failed: ${M.status} ${M.statusText}`);return await M.json()}async refreshToken(o){let l=new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:this.config.clientId,client_secret:this.config.clientSecret}),M=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!M.ok)throw Error(`OAuth token refresh failed: ${M.status} ${M.statusText}`);return await M.json()}}var Us={JWT:an,ApiKeyManager:un,OAuth2Helper:cn},Is=Us;var gn={};qe(gn,{AuthenticationException:()=>X,AuthorizationException:()=>Y,BugsnagReporter:()=>Dr,BusinessLogicException:()=>se,CircuitBreaker:()=>hr,CircuitBreakerHttpClient:()=>ln,CircuitBreakerOpenException:()=>C,CircuitBreakerPresets:()=>Ls,CircuitBreakerRegistry:()=>It,CircularDependencyException:()=>p,ConfigurationException:()=>ie,CustomReporter:()=>dn,DatabaseException:()=>ne,DegradationStrategies:()=>Ks,ErrorFactory:()=>i,ErrorReportingManager:()=>Xt,ErrorReportingPresets:()=>Vs,ExternalServiceException:()=>T,FileSystemException:()=>oe,GracefulDegradationManager:()=>Qt,HandlerResolutionException:()=>ce,InternalServerException:()=>te,MethodNotAllowedException:()=>Z,MiddlewareConfigurationException:()=>ae,ModelBindingException:()=>le,NotFoundException:()=>Q,RateLimitException:()=>ee,RouteConflictException:()=>P,RouteNotFoundException:()=>U,RouterErrorFactory:()=>ct,RouterException:()=>t,SentryReporter:()=>Br,ServiceHealthMonitor:()=>Nr,ServiceUnavailableException:()=>re,TimeoutException:()=>x,ValidationException:()=>d,circuitBreaker:()=>_s,createAdvancedErrorHandler:()=>hn,createCircuitBreaker:()=>zs,createCircuitBreakerMiddleware:()=>js,createErrorReporting:()=>Ws,createGracefulDegradationMiddleware:()=>Js,detectRouteConflicts:()=>at,findSimilarRoutes:()=>ot,globalCircuitBreakerRegistry:()=>$r,withCircuitBreaker:()=>Gs});class hr{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(o){let l={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...l,...o},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(o){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let L=new C(this.config.name,this.nextAttemptTime,o.context);if(o.fallback)try{return await o.fallback()}catch(V){console.error(V)}throw L}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let L=new C(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),o.context);if(o.fallback)try{return await o.fallback()}catch(V){throw console.error(V),L}throw L}let l=Date.now(),M,k=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let L=o.timeout||this.config.timeout,V=new Promise((pe,he)=>{setTimeout(()=>{he(new x(`Circuit breaker timeout for ${this.config.name}`,L,o.context))},L)});return M=await Promise.race([o.execute(),V]),this.onSuccess(Date.now()-l),M}catch(L){if(k=L,this.onFailure(k,Date.now()-l),o.fallback)try{return await o.fallback()}catch(V){throw console.error(V),k}else throw k}}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(o){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(o),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:o}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(o,l){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,o instanceof x)this.metrics.timeouts++;if(this.updateAverageResponseTime(l),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:l}),this.shouldTrip(o)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(o,this.config.name)}shouldTrip(o){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(o))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let l=this.getRecentRequests();if(l.length>=this.config.minimumRequests){if(l.filter((L)=>!L.success).length/l.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(o){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=o;else this.metrics.averageResponseTime=0.1*o+0.9*this.metrics.averageResponseTime}getRecentRequests(){let o=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((l)=>l.timestamp>o)}cleanupOldRequests(){let o=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((l)=>l.timestamp>o)}}class It{breakers=new Map;configs=new Map;register(o){let l=new hr(o);return this.breakers.set(o.name,l),this.configs.set(o.name,o),l}get(o){return this.breakers.get(o)}async execute(o,l){let M=this.breakers.get(o);if(!M)throw Error(`Circuit breaker '${o}' not found`);return M.execute(l)}getAllMetrics(){let o={};for(let[l,M]of this.breakers)o[l]=M.getMetrics();return o}getBreakersByState(o){let l=[];for(let[M,k]of this.breakers)if(k.getState()===o)l.push(M);return l}forceAllClosed(){for(let o of this.breakers.values())o.forceClosed()}resetAll(){for(let o of this.breakers.values())o.reset()}remove(o){return this.configs.delete(o),this.breakers.delete(o)}getNames(){return Array.from(this.breakers.keys())}}function _s(o){let l=new hr(o);return function(M,k,L){let V=L.value;return L.value=async function(...pe){return l.execute({execute:()=>V.apply(this,pe),context:{method:k,timestamp:new Date}})},L}}class ln{registry;constructor(o){this.registry=o||new It}async fetch(o,l={}){let{circuitBreaker:M,fallback:k,context:L,...V}=l,pe;if(typeof M==="string")pe=M;else if(M){if(pe=M.name,!this.registry.get(pe))this.registry.register(M)}else if(pe=`http-${new URL(o).hostname}`,!this.registry.get(pe))this.registry.register({name:pe,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(pe,{execute:async()=>{let he=await fetch(o,V);if(he.status>=500)throw new T(`HTTP ${he.status}: ${he.statusText}`,pe,o,he.status,void 0,L);return he},fallback:k,context:L})}getRegistry(){return this.registry}}function js(o){return async(l,M)=>{let k=l.context?.serviceName;if(!k)return M();let L=o.get(k);if(!L)return M();return L.execute({execute:M,context:{requestId:l.requestId,route:l.route,method:l.method,url:l.url}})}}var Ls={critical:(o)=>({name:o,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(o)=>({name:o,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(o)=>({name:o,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(o)=>({name:o,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(l)=>!(l.message.includes("validation")||l.message.includes("constraint"))}),externalApi:(o)=>({name:o,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(l)=>{if(l instanceof T)return l.statusCode>=500;return!0}})},$r=new It;function zs(o){return $r.register(o)}async function Gs(o,l){return $r.execute(o,l)}class Br{config;sentry;constructor(o){this.config=o,this.initializeSentry()}async initializeSentry(){try{let o=await import("@sentry/node");o.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(l,M)=>{let k=M.originalException;if(k&&this.config.beforeSend)return this.config.beforeSend(k,k.context)?l:null;return l},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=o}catch(o){console.warn("Failed to initialize Sentry:",o)}}async report(o,l){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(o))return null;let M={...o.context,...l};return this.sentry.withScope((k)=>{if(M.requestId)k.setTag("requestId",M.requestId);if(M.userId)k.setUser({id:M.userId});if(M.traceId)k.setTag("traceId",M.traceId);if(M.route)k.setTag("route",M.route);if(M.method)k.setTag("method",M.method);k.setTag("errorCode",o.code),k.setTag("severity",o.severity),k.setTag("category",o.category),k.setLevel(this.mapSeverityToLevel(o.severity)),k.setExtra("statusCode",o.statusCode),k.setExtra("retryable",o.retryable),k.setExtra("timestamp",o.timestamp),k.setExtra("context",M);let L=this.generateFingerprint(o);if(L.length>0)k.setFingerprint(L);return this.sentry.captureException(o)})}catch(M){return console.error("Failed to report error to Sentry:",M),null}}addBreadcrumb(o,l="default",M="info",k){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:o,category:l,level:M,data:k,timestamp:Date.now()/1000})}setUser(o){if(!this.sentry)return;this.sentry.setUser(o)}setTag(o,l){if(!this.sentry)return;this.sentry.setTag(o,l)}setExtra(o,l){if(!this.sentry)return;this.sentry.setExtra(o,l)}setContext(o,l){if(!this.sentry)return;this.sentry.setContext(o,l)}async close(o=2000){if(!this.sentry)return!0;return this.sentry.close(o)}shouldIgnoreError(o){let l=this.config.filters;if(!l)return!1;if(l.ignoreCodes?.includes(o.code))return!0;if(l.ignoreErrors?.some((M)=>{if(typeof M==="string")return o.message.includes(M);return M.test(o.message)}))return!0;return!1}mapSeverityToLevel(o){switch(o){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(o){let l=[];if(l.push(o.code),l.push(o.category),o.context.route)l.push(o.context.route);return l}}class Dr{config;bugsnag;constructor(o){this.config=o,this.initializeBugsnag()}async initializeBugsnag(){try{let o=await import("@bugsnag/js");o.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(l)=>{let M=l.originalError;if(M&&this.config.beforeSend)return this.config.beforeSend(M,M.context)!==null;return!this.shouldIgnoreError(M)}}),this.bugsnag=o}catch(o){console.warn("Failed to initialize Bugsnag:",o)}}async report(o,l){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(o))return null;let M={...o.context,...l};return this.bugsnag.notify(o,(k)=>{if(k.severity=this.mapSeverityToBugsnag(o.severity),k.context=M.route||M.url,M.userId)k.setUser(M.userId,void 0,void 0);k.addMetadata("error",{code:o.code,category:o.category,statusCode:o.statusCode,retryable:o.retryable,timestamp:o.timestamp}),k.addMetadata("request",{requestId:M.requestId,method:M.method,url:M.url,userAgent:M.userAgent,ip:M.ip}),k.groupingHash=this.generateGroupingHash(o)}),"reported"}catch(M){return console.error("Failed to report error to Bugsnag:",M),null}}addBreadcrumb(o,l="manual",M="info",k){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(o,k,l)}setUser(o){if(!this.bugsnag)return;this.bugsnag.setUser(o.id,o.email,o.username)}setTag(o,l){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[o]:l})}setExtra(o,l){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[o]:l})}setContext(o,l){if(!this.bugsnag)return;this.bugsnag.addMetadata(o,l)}async close(){return!0}shouldIgnoreError(o){let l=this.config.filters;if(!l)return!1;if(l.ignoreCodes?.includes(o.code))return!0;if(l.ignoreErrors?.some((M)=>{if(typeof M==="string")return o.message.includes(M);return M.test(o.message)}))return!0;return!1}mapSeverityToBugsnag(o){switch(o){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(o){return`${o.code}-${o.category}-${o.context.route||"unknown"}`}}class dn{config;reportHandler;constructor(o,l){this.config=o,this.reportHandler=l}async report(o,l){if(!this.config.enabled)return null;try{let M={...o.context,...l};if(this.config.beforeSend){if(!this.config.beforeSend(o,M))return null}let k={error:o,context:M,level:this.mapSeverityToLevel(o.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(k)}catch(M){return console.error("Failed to report error with custom handler:",M),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(o){switch(o){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class Xt{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(o){this.initializeReporters(o)}initializeReporters(o){for(let l of o){if(!l.enabled)continue;switch(l.service){case"sentry":this.reporters.push(new Br(l));break;case"bugsnag":this.reporters.push(new Dr(l));break;case"custom":break}}}addReporter(o){this.reporters.push(o)}async report(o,l){let M=[];this.addBreadcrumb(`Error occurred: ${o.message}`,"error",{code:o.code,severity:o.severity});let k=this.reporters.map(async(L)=>{try{let V=await L.report(o,l);if(V)M.push(V)}catch(V){console.error("Reporter failed:",V)}});return await Promise.allSettled(k),M}addBreadcrumb(o,l="default",M){if(this.breadcrumbs.push({message:o,timestamp:new Date,data:{category:l,...M}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((k)=>{k.addBreadcrumb(o,l,"info",M)})}setUser(o){this.reporters.forEach((l)=>l.setUser(o))}setTag(o,l){this.reporters.forEach((M)=>M.setTag(o,l))}setExtra(o,l){this.reporters.forEach((M)=>M.setExtra(o,l))}setContext(o,l){this.reporters.forEach((M)=>M.setContext(o,l))}async close(o=5000){let l=this.reporters.map((k)=>k.close(o));return(await Promise.allSettled(l)).every((k)=>k.status==="fulfilled"&&k.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function Ws(o){return new Xt(o)}var Vs={sentry:(o,l="production")=>({enabled:!0,service:"sentry",dsn:o,environment:l,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:(o,l="production")=>({enabled:!0,service:"bugsnag",apiKey:o,environment:l,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class Nr{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(o){this.config=o,this.initializeHealthChecks()}initializeHealthChecks(){for(let[o,l]of Object.entries(this.config.healthChecks)){if(!l.enabled)continue;this.healthStatus.set(o,{name:o,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let M=setInterval(()=>this.performHealthCheck(o,l),l.interval);M.unref?.(),this.healthCheckIntervals.set(o,M)}}async performHealthCheck(o,l){let M=Date.now(),k=!1;try{let V=new AbortController,pe=setTimeout(()=>V.abort(),l.timeout),he=await fetch(l.endpoint,{signal:V.signal,headers:l.headers,method:"GET"});if(clearTimeout(pe),k=l.expectedStatus.includes(he.status),k&&l.expectedBody){let Te=await he.text();if(typeof l.expectedBody==="string")k=Te.includes(l.expectedBody);else k=l.expectedBody.test(Te)}}catch(V){console.error(V),k=!1}let L=Date.now()-M;if(this.updateHealthStatus(o,k,L),k&&l.onHealthy)l.onHealthy();else if(!k&&l.onUnhealthy)l.onUnhealthy(Error(`Health check failed for ${o}`))}updateHealthStatus(o,l,M){let k=this.healthStatus.get(o);if(!k)return;let L={...k,lastCheck:new Date,responseTime:M,consecutiveFailures:l?0:k.consecutiveFailures+1};if(L.consecutiveFailures===0)L.status="healthy";else if(L.consecutiveFailures<3)L.status="degraded";else L.status="unhealthy";let V=l?1:0;L.availability=k.availability*0.9+V*10,this.healthStatus.set(o,L)}getServiceHealth(o){return this.healthStatus.get(o)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(o){return this.healthStatus.get(o)?.status==="healthy"}isServiceDegraded(o){return this.healthStatus.get(o)?.status==="degraded"}stop(){for(let o of this.healthCheckIntervals.values())clearInterval(o);this.healthCheckIntervals.clear()}}class Qt{config;healthMonitor;cache=new Map;metrics=new Map;constructor(o){this.config=o,this.healthMonitor=new Nr(o)}async handleFailure(o,l,M,k){if(!this.config.enabled)throw l;let L=this.config.fallbackStrategies[o];if(!L)throw l;let V={request:M,serviceName:o,error:l,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(L,V,k)}async executeFallbackStrategy(o,l,M){if(l.attemptCount<=o.retries)try{if(l.attemptCount>1){let V=this.calculateBackoffDelay(o.backoff,l.attemptCount);await this.sleep(V)}let k=new Promise((V,pe)=>{setTimeout(()=>pe(Error("Timeout")),o.timeout)}),L=await Promise.race([M(),k]);return this.updateMetrics(l.serviceName,!0,Date.now()-l.startTime.getTime()),L}catch(k){if(console.error(k),l.attemptCount++,l.attemptCount<=o.retries)return this.executeFallbackStrategy(o,l,M)}switch(this.updateMetrics(l.serviceName,!1,Date.now()-l.startTime.getTime()),o.type){case"cache":return this.handleCacheFallback(o,l);case"static":return this.handleStaticFallback(o,l);case"simplified":return this.handleSimplifiedFallback(o,l);case"redirect":return this.handleRedirectFallback(o,l);case"custom":return this.handleCustomFallback(o,l);default:throw l.error}}async handleCacheFallback(o,l){if(!o.cacheConfig)throw l.error;let M=this.generateCacheKey(o.cacheConfig.key,l),k=this.cache.get(M);if(k&&(k.expires>new Date||o.cacheConfig.staleWhileRevalidate)){let L=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"});if(o.cacheConfig.staleWhileRevalidate&&k.expires<=new Date)L.set("X-Cache","STALE");return new Response(JSON.stringify(k.data),{status:200,headers:L})}throw l.error}async handleStaticFallback(o,l){if(!o.staticResponse)throw l.error;let M=new Headers(o.staticResponse.headers||{});return M.set("X-Degraded","true"),M.set("X-Fallback-Type","static"),M.set("X-Service-Status",this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"),new Response(typeof o.staticResponse.body==="string"?o.staticResponse.body:JSON.stringify(o.staticResponse.body),{status:o.staticResponse.status,headers:M})}async handleSimplifiedFallback(o,l){let M={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:l.request.requestId};return new Response(JSON.stringify(M),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"}})}async handleRedirectFallback(o,l){if(!o.redirectConfig)throw l.error;return new Response(null,{status:o.redirectConfig.permanent?301:302,headers:{Location:o.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(o,l){if(!o.fallbackHandler)throw l.error;try{let M=await o.fallbackHandler(l.error,l.error.context);return M.headers.set("X-Degraded","true"),M.headers.set("X-Fallback-Type","custom"),M.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"),M}catch(M){throw console.error(M),l.error}}cacheResponse(o,l,M,k){let L=this.config.fallbackStrategies[o];if(L?.type==="cache"&&L.cacheConfig){let V=this.generateCacheKey(l,{serviceName:o});this.cache.set(V,{data:M,expires:new Date(Date.now()+k*1000)})}}getServiceMetrics(o){let l=this.metrics.get(o);if(!l||l.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:l.errors/l.requests*100,avgResponseTime:l.totalTime/l.requests,totalRequests:l.requests}}getSystemHealth(){let o=this.healthMonitor.getAllServiceHealth(),l=o.filter((L)=>L.status==="unhealthy").length,M=o.filter((L)=>L.status==="degraded").length,k="healthy";if(l>0)k=l>o.length/2?"unhealthy":"degraded";else if(M>0)k="degraded";return{status:k,services:o}}calculateBackoffDelay(o,l){if(o.type==="fixed")return o.delay;let M=o.delay*2**(l-1);return Math.min(M,o.maxDelay||30000)}generateCacheKey(o,l){return o.replace("{service}",l.serviceName).replace("{url}",l.request.url).replace("{method}",l.request.method).replace("{userId}",String(l.request.user?.id||"anonymous"))}updateMetrics(o,l,M){let k=this.metrics.get(o)||{requests:0,errors:0,totalTime:0};if(k.requests++,k.totalTime+=M,!l)k.errors++;this.metrics.set(o,k)}sleep(o){return new Promise((l)=>setTimeout(l,o))}stop(){this.healthMonitor.stop()}}function Js(o){let l=new Qt(o);return async(M,k)=>{try{let L=await k(),V=M.context?.serviceName;if(V&&L.ok){let pe=o.fallbackStrategies[V];if(pe?.type==="cache"&&pe.cacheConfig)try{let he=await L.clone().json();l.cacheResponse(V,pe.cacheConfig.key,he,pe.cacheConfig.ttl)}catch{}}return L}catch(L){let V=M.context?.serviceName;if(V&&L instanceof Error){let pe=L;try{return await l.handleFailure(V,pe,M,k)}catch(he){throw console.error(he),L}}throw L}}}var Ks={cacheFirst:(o=3600,l=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:o,staleWhileRevalidate:l}}),staticFallback:(o,l=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:l,body:o,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(o)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:o,permanent:!1}})};class pn{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(o={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...o},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new Xt(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new Qt(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new It;for(let o of this.config.circuitBreakers)this.circuitBreakerRegistry.register(o)}}middleware(){return async(o,l)=>{try{let M={requestId:o.requestId,userId:o.user?.id,traceId:o.traceId,spanId:o.spanId,route:o.params?.route||o.url,method:o.method,url:o.url,userAgent:o.userAgent?.()||void 0,ip:o.ip?.()||void 0,timestamp:new Date};if(o.context={...o.context,errorContext:M},this.circuitBreakerRegistry&&o.context?.serviceName){let k=this.circuitBreakerRegistry.get(o.context.serviceName);if(k)return await k.execute({execute:l,context:M})}return await l()}catch(M){return this.handleError(M,o)}}}async handleError(o,l){let M=this.normalizeError(o,l);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${l.method} ${l.url}`,"error",{code:M.code,severity:M.severity,statusCode:M.statusCode});if(this.config.logErrors)this.logError(M,l);if(this.gracefulDegradation&&l.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(l.context.serviceName,M,l,async()=>{throw M})}catch{}if(this.errorReporting)try{await this.errorReporting.report(M,M.context)}catch(L){console.error("Failed to report error:",L)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler(M,l)}catch(L){console.error("Global error handler failed:",L)}let k=this.config.customErrorPages?.[M.statusCode];if(k)try{if(typeof k==="string")return new Response(k,{status:M.statusCode,headers:{"Content-Type":"text/html"}});else return await k(M,l)}catch(L){console.error("Custom error page failed:",L)}return this.createErrorResponse(M,l)}normalizeError(o,l){let M={requestId:l.requestId,userId:l.user?.id,traceId:l.traceId,spanId:l.spanId,route:l.params?.route||l.url,method:l.method,url:l.url,userAgent:l.userAgent?.()||void 0,ip:l.ip?.()||void 0,timestamp:new Date,metadata:l.context};if(o instanceof t)return o;if(o instanceof Error){if(o.name==="ValidationError")return i.validation(o.message,{},M);if(o.name==="UnauthorizedError"||o.message.includes("unauthorized"))return i.authentication(o.message,M);if(o.name==="ForbiddenError"||o.message.includes("forbidden"))return i.authorization(o.message,[],M);if(o.name==="NotFoundError"||o.message.includes("not found"))return i.notFound(void 0,void 0,M);if(o.name==="TimeoutError"||o.message.includes("timeout"))return i.timeout(30000,o.message,M);return i.internalServer(o.message,o,M)}if(typeof o==="string")return i.internalServer(o,void 0,M);return i.internalServer("An unknown error occurred",void 0,M)}createErrorResponse(o,l){let M=this.config.development,k=this.config.includeStackTrace||M,L=this.config.sanitizeErrors&&!M,V=o.message;if(L&&o.statusCode>=500)V="An internal server error occurred";let pe={error:{code:o.code,message:V,statusCode:o.statusCode,timestamp:o.timestamp.toISOString(),requestId:o.context.requestId,traceId:o.context.traceId}};if(M)pe.error.category=o.category,pe.error.severity=o.severity,pe.error.retryable=o.retryable,pe.error.context=o.context;if(k){if(pe.error.stack=o.stack,o.cause)pe.error.cause={name:o.cause.name,message:o.cause.message,stack:o.cause.stack}}if("fields"in o)pe.error.fields=o.fields;if("allowedMethods"in o)pe.error.allowedMethods=o.allowedMethods;if("retryAfter"in o)pe.error.retryAfter=o.retryAfter;let he=new Headers({"Content-Type":"application/json","X-Error-Code":o.code,"X-Request-ID":o.context.requestId||"","X-Trace-ID":o.context.traceId||""});if("allowedMethods"in o)he.set("Allow",o.allowedMethods.join(", "));if("retryAfter"in o)he.set("Retry-After",o.retryAfter.toString());if("limit"in o)he.set("X-RateLimit-Limit",o.limit.toString()),he.set("X-RateLimit-Remaining",o.remaining.toString());return new Response(JSON.stringify(pe),{status:o.statusCode,headers:he})}logError(o,l){let M={error:o.toJSON(),request:{method:l.method,url:l.url,headers:Object.fromEntries(l.headers.entries()),userAgent:l.userAgent?.()||void 0,ip:l.ip?.()||void 0,requestId:l.requestId,traceId:l.traceId}};switch(o.severity){case"critical":console.error("[CRITICAL ERROR]",M);break;case"high":console.error("[ERROR]",M);break;case"medium":console.warn("[WARNING]",M);break;case"low":console.warn("[INFO]",M);break;default:console.error("[ERROR]",M)}}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 hn(o={}){let l=new pn(o);return{middleware:l.middleware(),getStats:()=>l.getStats(),cleanup:()=>l.cleanup()}}function _t(o){if(!o.includes("%"))return o;try{return decodeURIComponent(o)}catch{return o}}function gr(o){let{read:l,write:M,remove:k}=o,L=()=>({...l()});for(let[V,pe]of Object.entries(l()))Object.defineProperty(L,V,{value:pe,writable:!0,enumerable:!0,configurable:!0});return L.get=(V)=>l()[V],L.set=(V,pe,he={})=>M?.(V,pe,he),L.delete=(V,pe={})=>k?.(V,pe),L.getAll=()=>({...l()}),L}function jt(o={}){let l={...o};return gr({read:()=>l,write:(M,k)=>{l[M]=k},remove:(M)=>{delete l[M]}})}import{AsyncLocalStorage as Xs}from"async_hooks";var mr=new Xs,Zt=!1,ht=null;function Qs(){Zt=!0}function Fr(o,l){if(!Zt){ht=o;let M;try{M=l()}catch(k){throw ht=null,k}if(M instanceof Promise)return M.finally(()=>{ht=null});return ht=null,M}return mr.run({current:o},l)}function Ur(o,l,M,k){if(!Zt){ht=o;let L;try{L=l(M,k)}catch(V){throw ht=null,V}if(L instanceof Promise)return L.finally(()=>{ht=null});return ht=null,L}return mr.run({current:o},l,M,k)}function fr(o){let l=mr.getStore();if(l){l.current=o;return}if(ht!==null)ht=o}function mn(){if(!Zt)return Zt=!0,ht??void 0;return mr.getStore()?.current??ht??void 0}function Zs(){let o=mn();if(!o)throw Error("request() called outside a request scope. It can only be invoked from within a route handler or middleware.");return o}var fn={enabled:!0,level:6,threshold:1024};function Rn(o){if(!o)return!1;if(o==="application/json")return!0;if(o.startsWith("text/")){if(!o.startsWith("text/event-stream"))return!0;if(o.length===17)return!1;let M=o.charCodeAt(17);return M>32&&M!==59}let l=o.split(";")[0]?.trim().toLowerCase()??"";if(l==="text/event-stream")return!1;if(l.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(l)}function _o(o){return yn(o).encoding}function yn(o){if(!o)return{encoding:null,identityAllowed:!0};let l,M,k,L;for(let pe of o.split(",")){let he=pe.indexOf(";"),Te=(he<0?pe:pe.slice(0,he)).trim().toLowerCase();if(Te!=="gzip"&&Te!=="deflate"&&Te!=="identity"&&Te!=="*")continue;let xe=1;if(he>=0){let ve=/^;[\t ]*q=(0(?:\.\d{0,3})?|1(?:\.0{0,3})?)[\t ]*$/i.exec(pe.slice(he));xe=ve?Number(ve[1]):0}if(Te==="gzip")l=xe;else if(Te==="deflate")M=xe;else if(Te==="identity")k=xe;else L=xe}l??=L??0,M??=L??0;let V=k!==void 0?k>0:L!==0;if(k!==void 0&&k>Math.max(l,M))return{encoding:null,identityAllowed:V};if(l>0&&l>=M)return{encoding:"gzip",identityAllowed:V};if(M>0)return{encoding:"deflate",identityAllowed:V};return{encoding:null,identityAllowed:V}}function jo(o,l,M){if(!l)return!1;if(o.status===204||o.status===304||o.status===206)return!1;if(o.headers.has("content-encoding"))return!1;if(!Rn(o.headers.get("content-type")))return!1;let k=Number(o.headers.get("content-length")??Number.NaN);if(Number.isFinite(k)&&!(k>=M))return!1;return Boolean(o.body)}function $t(o,l,M={}){if(!(M.enabled??fn.enabled))return o;let L=o.headers;if(L.has("content-encoding"))return o;let V=M.threshold??fn.threshold,pe=l.headers.get("accept-encoding"),he=pe?Number(L.get("content-length")??Number.NaN):Number.NaN,Te=Number.isFinite(he)&&!(he>=V);if(!pe||Te&&(!pe.includes(";")||!/identity|\*/i.test(pe)))return Yt(L,"Accept-Encoding"),o;let{encoding:xe,identityAllowed:ve}=yn(pe),Pe=Rn(L.get("content-type"))&&o.status!==206;if(!ve&&o.status!==204&&o.status!==304&&o.body){if(!xe||!Pe)return Ys(o);return Ir(o,o.body,xe)}if(!xe||Te||!Pe||o.status===204||o.status===304||!o.body){if(o.status!==204)Yt(L,"Accept-Encoding");return o}if(!Number.isFinite(he))return ei(o,xe,V);return Ir(o,o.body,xe)}function Ys(o){o.body?.cancel().catch(()=>{});let l=new Headers(o.headers);for(let M of["content-type","content-length","content-encoding","content-range","content-disposition","etag","last-modified","content-md5","digest","content-digest","repr-digest","expires"])l.delete(M);return l.set("Cache-Control","no-store"),Yt(l,"Accept-Encoding"),new Response(null,{status:406,headers:l})}async function Lo(o,l,M={}){return $t(o,l,M)}async function ei(o,l,M){let k=await ti(o.body,M);if(k.ended&&k.size<M){let L=new Headers(o.headers);return Yt(L,"Accept-Encoding"),new Response(k.stream,{status:o.status,statusText:o.statusText,headers:L})}return Ir(o,k.stream,l)}function Ir(o,l,M){let k=new Headers(o.headers);k.set("Content-Encoding",M),Yt(k,"Accept-Encoding"),k.delete("Content-Length");let L=l.pipeThrough(new CompressionStream(M==="gzip"?"gzip":"deflate"));return new Response(L,{status:o.status,statusText:o.statusText,headers:k})}async function ti(o,l){let M=o.getReader(),k=[],L=0,V=!1;while(L<l){let{value:he,done:Te}=await M.read();if(Te){V=!0;break}if(he)k.push(he),L+=he.byteLength}return{stream:new ReadableStream({start(he){for(let Te of k)he.enqueue(Te);if(V)he.close()},async pull(he){if(V)return;let{value:Te,done:xe}=await M.read();if(xe){V=!0,he.close();return}if(Te)he.enqueue(Te)},cancel(he){return M.cancel(he)}}),size:L,ended:V}}function Yt(o,l){let M=o.get("vary");if(!M){o.set("Vary",l);return}let k=M.split(",").map((L)=>L.trim().toLowerCase());if(k.includes("*")||k.includes(l.toLowerCase()))return;o.set("Vary",`${M}, ${l}`)}var Ae={json:(o,l={})=>{let M=typeof l==="number"?{status:l}:l,{status:k=200,headers:L={},pretty:V=!1}=M,pe=V?JSON.stringify(o,null,2):JSON.stringify(o);return new Response(pe,{status:k,headers:{"Content-Type":"application/json",...L}})},noContent:(o={})=>new Response(null,{status:204,headers:o}),download:async(o,l,M={})=>{let k=Bun.file(o);if(!await k.exists())return new Response("File not found",{status:404});let V=l||o.split("/").pop()||"download",pe=k.type||"application/octet-stream";return new Response(k,{status:200,headers:{"Content-Type":pe,"Content-Disposition":`attachment; filename="${V}"`,"Content-Length":String(k.size),...M}})},file:async(o,l={})=>{let M=Bun.file(o);if(!await M.exists())return new Response("File not found",{status:404});let L=M.type||"application/octet-stream";return new Response(M,{status:200,headers:{"Content-Type":L,"Content-Length":String(M.size),...l}})},streamDownload:(o,l,M={})=>{let{contentType:k="application/octet-stream",headers:L={}}=M,V=new ReadableStream({async start(pe){try{for await(let he of o())if(typeof he==="string")pe.enqueue(new TextEncoder().encode(he));else pe.enqueue(he);pe.close()}catch(he){pe.error(he)}}});return new Response(V,{status:200,headers:{"Content-Type":k,"Content-Disposition":`attachment; filename="${l}"`,"Transfer-Encoding":"chunked",...L}})},redirect:(o,l=302)=>new Response(null,{status:l,headers:{Location:o}}),redirectPermanent:(o)=>Ae.redirect(o,301),redirectTemporary:(o)=>Ae.redirect(o,302),back:(o,l="/")=>{let M=o.headers.get("referer")||l;return Ae.redirect(M)},view:(o,l=200,M={})=>new Response(o,{status:l,headers:{"Content-Type":"text/html; charset=utf-8",...M}}),text:(o,l=200,M={})=>new Response(o,{status:l,headers:{"Content-Type":"text/plain; charset=utf-8",...M}}),xml:(o,l=200,M={})=>new Response(o,{status:l,headers:{"Content-Type":"application/xml; charset=utf-8",...M}}),success:(o,l,M=200)=>{let k={success:!0};if(o!==void 0)k.data=o;if(l!==void 0)k.message=l;return Ae.json(k,{status:M})},error:(o,l=400,M)=>{let k={success:!1,message:o};if(M!==void 0)k.errors=M;return Ae.json(k,{status:l})},paginate:(o,l)=>{let{page:M,perPage:k,total:L,path:V}=l,pe=Math.ceil(L/k),he=(M-1)*k+1,Te=Math.min(M*k,L);return Ae.json({data:o,meta:{current_page:M,per_page:k,total:L,last_page:pe,from:he,to:Te,path:V,first_page_url:`${V}?page=1`,last_page_url:`${V}?page=${pe}`,next_page_url:M<pe?`${V}?page=${M+1}`:null,prev_page_url:M>1?`${V}?page=${M-1}`:null}})},created:(o,l)=>{let M={};if(l)M.Location=l;let k={success:!0};if(o!==void 0)k.data=o;return Ae.json(k,{status:201,headers:M})},accepted:(o)=>{let l={success:!0};if(o!==void 0)l.data=o;return Ae.json(l,{status:202})},notFound:(o="Resource not found")=>Ae.error(o,404),unauthorized:(o="Unauthorized")=>Ae.error(o,401),forbidden:(o="Forbidden")=>Ae.error(o,403),badRequest:(o="Bad request",l)=>Ae.error(o,400,l),validationError:(o,l="Validation failed")=>Ae.error(l,422,o),unprocessableEntity:(o="Unprocessable entity",l)=>Ae.error(o,422,l),serverError:(o="Internal server error")=>Ae.error(o,500),tooManyRequests:(o="Too many requests",l)=>{let M={};if(l)M["Retry-After"]=String(l);return new Response(JSON.stringify({message:o}),{status:429,headers:{"Content-Type":"application/json",...M}})}};class wn{_status=200;_headers={};_cookies=[];_deleteCookies=[];status(o){return this._status=o,this}header(o,l){return this._headers[o]=l,this}withHeaders(o){return this._headers={...this._headers,...o},this}cookie(o,l,M={}){return this._cookies.push({name:o,value:l,options:M}),this}withoutCookie(o,l={}){return this._deleteCookies.push({name:o,options:l}),this}json(o){let l=Ae.json(o,{status:this._status,headers:this._headers});return this.applyCookies(l)}text(o){let l=Ae.text(o,this._status,this._headers);return this.applyCookies(l)}html(o){let l=Ae.view(o,this._status,this._headers);return this.applyCookies(l)}noContent(){let o=Ae.noContent(this._headers);return this.applyCookies(o)}applyCookies(o){let l=new Headers(o.headers);for(let{name:M,value:k,options:L}of this._cookies){let V=this.serializeCookie(M,k,L);l.append("Set-Cookie",V)}for(let{name:M,options:k}of this._deleteCookies){let L=this.serializeCookie(M,"",{...k,maxAge:0,expires:new Date(0)});l.append("Set-Cookie",L)}return new Response(o.body,{status:o.status,headers:l})}serializeCookie(o,l,M){let k=`${encodeURIComponent(o)}=${encodeURIComponent(l)}`;if(M.maxAge!==void 0)k+=`; Max-Age=${M.maxAge}`;if(M.expires)k+=`; Expires=${M.expires.toUTCString()}`;if(M.httpOnly)k+="; HttpOnly";if(M.secure)k+="; Secure";if(M.path)k+=`; Path=${M.path}`;if(M.domain)k+=`; Domain=${M.domain}`;if(M.sameSite)k+=`; SameSite=${M.sameSite.charAt(0).toUpperCase()+M.sameSite.slice(1)}`;return k}}function Go(){return new wn}import ri from"process";class _r{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(o){this.dependencyRegistry.set(o.name,o)}compileMiddleware(o,l,M=[]){let k=[];for(let L=0;L<l.length;L++){let V=l[L],pe=V.name||`middleware_${L}`;k.push({handler:V,name:pe,skipConditions:M.filter((he)=>he.name.includes(pe)||he.name==="global"),dependencies:this.extractDependencies(V),canShortCircuit:this.canShortCircuit(V),priority:L})}this.compiledPipelines.set(o,k)}async execute(o,l,M){let k=performance.now();this.stats.totalExecutions++;let L=this.compiledPipelines.get(o);if(!L)return this.stats.cacheMisses++,await M();this.stats.cacheHits++;let V={request:l,dependencies:new Map,metadata:{}};await this.resolveDependencies(V,L);let pe=0,he=async()=>{if(pe>=L.length)return await M();let ve=L[pe++];if(await this.shouldSkip(ve,V))return this.stats.skippedMiddleware++,await he();let Pe=await ve.handler(l,he);if(Pe instanceof Response&&ve.canShortCircuit)return this.stats.shortCircuits++,Pe;return Pe},Te=await he(),xe=performance.now()-k;return this.updateAverageExecutionTime(xe),Te||new Response("Internal Server Error",{status:500})}async shouldSkip(o,l){for(let M of o.skipConditions)if(await M.condition(l))return!0;return!1}async resolveDependencies(o,l){let M=new Set;for(let k of l)for(let L of k.dependencies)M.add(L);for(let k of M){let L=this.dependencyRegistry.get(k);if(!L)continue;if(this.stats.dependencyResolutions++,L.singleton&&this.singletonInstances.has(k))o.dependencies.set(k,this.singletonInstances.get(k));else{let V=await L.factory(o);if(o.dependencies.set(k,V),L.singleton)this.singletonInstances.set(k,V)}}}extractDependencies(o){let l=o.toString(),M=[];if(l.includes("database")||l.includes("db"))M.push("database");if(l.includes("logger")||l.includes("log"))M.push("logger");if(l.includes("cache"))M.push("cache");if(l.includes("httpClient")||l.includes("http"))M.push("httpClient");return M}canShortCircuit(o){let l=o.toString();return l.includes("return")&&l.includes("Response")}updateAverageExecutionTime(o){let l=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(l+o)/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 ni={skipForMethods:(o)=>({name:`skip_for_methods_${o.join("_")}`,condition:(l)=>o.includes(l.request.method)}),skipForPaths:(o)=>({name:`skip_for_paths_${o.join("_").replace(/\//g,"_")}`,condition:(l)=>{let M=new URL(l.request.url);return o.some((k)=>M.pathname.startsWith(k))}}),skipForHeaders:(o)=>({name:`skip_for_headers_${Object.keys(o).join("_")}`,condition:(l)=>Object.entries(o).some(([M,k])=>l.request.headers.get(M)===k)}),skipForRoles:(o)=>({name:`skip_for_roles_${o.join("_")}`,condition:(l)=>{let M=l.request.user?.roles||[];return!o.some((k)=>M.includes(k))}}),skipForEnvironment:(o)=>({name:`skip_for_env_${o.join("_")}`,condition:()=>{let l=ri.env.NODE_ENV||"development";return o.includes(l)}})},si={database:(o)=>({name:"database",factory:async()=>({query:async(l)=>({rows:[]}),close:async()=>{},connectionString:o||"mock://database"}),singleton:!0}),logger:(o="info")=>({name:"logger",factory:()=>({info:(l)=>console.log(`[INFO] ${l}`),error:(l)=>console.error(`[ERROR] ${l}`),warn:(l)=>console.warn(`[WARN] ${l}`),debug:(l)=>console.debug(`[DEBUG] ${l}`),level:o}),singleton:!0}),cache:(o=1000)=>({name:"cache",factory:()=>{let l=new Map;return{get:(M)=>l.get(M),set:(M,k)=>{if(l.size>=o){let L=l.keys().next().value;l.delete(L)}l.set(M,k)},delete:(M)=>l.delete(M),clear:()=>l.clear(),size:()=>l.size}},singleton:!0}),httpClient:(o)=>({name:"httpClient",factory:()=>({get:async(l)=>fetch(o?`${o}${l}`:l),post:async(l,M)=>fetch(o?`${o}${l}`:l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}),put:async(l,M)=>fetch(o?`${o}${l}`:l,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}),delete:async(l)=>fetch(o?`${o}${l}`:l,{method:"DELETE"})}),singleton:!0})},ii={auth:(o={})=>async(l,M)=>{let k=new URL(l.url);if(o.skipPaths?.some((V)=>k.pathname.startsWith(V)))return await M();if(!l.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return l.user={id:"123",roles:["user"]},await M()}catch{return new Response("Invalid token",{status:401})}},rateLimit:(o)=>{let l=new Map;return async(M,k)=>{let L=M.headers.get("x-forwarded-for")||"unknown",V=Date.now(),pe=V-o.windowMs;if(!l.has(L))l.set(L,[]);let Te=l.get(L).filter((xe)=>xe>pe);if(Te.length>=o.maxRequests)return new Response("Too Many Requests",{status:429});return Te.push(V),l.set(L,Te),await k()}},cors:(o={})=>async(l,M)=>{let k=await M();if(k){let L=new Headers(k.headers);return L.set("Access-Control-Allow-Origin",o.origin||"*"),L.set("Access-Control-Allow-Methods",o.methods?.join(", ")||"GET, POST, PUT, DELETE"),L.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(k.body,{status:k.status,statusText:k.statusText,headers:L})}return k},logging:(o={})=>async(l,M)=>{let k=performance.now(),L=new URL(l.url);console.log(`[${new Date().toISOString()}] ${l.method} ${L.pathname}`);let V=await M(),pe=performance.now()-k;if(V)console.log(`[${new Date().toISOString()}] ${l.method} ${L.pathname} - ${V.status} (${pe.toFixed(2)}ms)`);return V}},oi=new _r;import{existsSync as Tn,readdirSync as ai,statSync as ui}from"fs";import{basename as xn,extname as bn,join as ci,resolve as vn}from"path";var li=[".ts",".js"],di=["routes","src/routes"],pi=["web","index"];function hi(){let o=process.cwd();for(let l of di){let M=vn(o,l);if(Tn(M)&&ui(M).isDirectory())return M}return null}function Pn(o,l){let M=[];if(!Tn(o))return M;let k=ai(o,{withFileTypes:!0});for(let L of k){if(L.name.startsWith(".")||L.name.startsWith("_"))continue;let V=ci(o,L.name);if(L.isDirectory())M.push(...Pn(V,l));else if(li.includes(bn(L.name))){let pe=o===l?"":o.slice(l.length),he=xn(L.name,bn(L.name)),Te=pi.includes(he)?pe||"":`${pe}/${he}`;M.push({filePath:V,prefix:Te})}}return M}async function gi(o,l,M,k){try{let L=await import(l),V=0,pe=o.routes?.length||0;if(typeof L.default==="function"){let he=mi(o,M);await L.default(he),V=(o.routes?.length||0)-pe}else if(Array.isArray(L.routes))for(let he of L.routes){let Te=(he.method||"GET").toLowerCase(),xe=`${M}${he.path}`;if(typeof o[Te]==="function")await o[Te](xe,he.handler),V++}if(k&&V>0)console.log(` ${M||"/"} \u2192 ${xn(l)} (${V} routes)`);return V}catch(L){return console.error(`[bun-router] Failed to load route file ${l}:`,L),0}}function mi(o,l){if(!l)return o;let M=["get","post","put","patch","delete","options","any"];return new Proxy(o,{get(k,L){if(M.includes(L))return async(V,...pe)=>k[L](`${l}${V}`,...pe);if(L==="group")return async(V,pe)=>{let he=V.prefix?`${l}${V.prefix}`:l;return k.group({...V,prefix:he},pe)};return k[L]}})}function Cn(o){Object.defineProperties(o.prototype,{_routesDir:{value:null,writable:!0,configurable:!0},_apiRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initApiRoutes:{async value(){if(this._apiRoutesInitialized)return;let l=this._routesDir||hi();if(!l){this._apiRoutesInitialized=!0;return}let M=this.config?.verbose||!1,k=Pn(l,l);if(k.length===0){this._apiRoutesInitialized=!0;return}if(M)console.log(`[bun-router] Auto-discovering API routes from ${l}:`);let L=0;for(let{filePath:V,prefix:pe}of k)L+=await gi(this,V,pe,M);if(L>0&&M)console.log(`[bun-router] Registered ${L} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(l){return this._routesDir=vn(l),this},writable:!0,configurable:!0}})}import{join as er,relative as jr,resolve as Et,dirname as Ri}from"path";import{readdirSync as Mn,statSync as yi,existsSync as yr}from"fs";var Zo={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function fi(o){let{preserve:l=[],exclude:M=[],routes:k=[]}=o;if(!l.length)return"";return`<script data-query-preservation>
3
3
  (function(){
4
- var preserve = ${JSON.stringify(c)};
5
- var exclude = ${JSON.stringify(P)};
6
- var routes = ${JSON.stringify(M)};
4
+ var preserve = ${JSON.stringify(l)};
5
+ var exclude = ${JSON.stringify(M)};
6
+ var routes = ${JSON.stringify(k)};
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 hr(i,c){if(!c.enabled||!c.preserve?.length)return i;let P=fi(c);if(!P)return i;if(i.includes("</head>"))return i.replace("</head>",`${P}
80
- </head>`);if(i.includes("</body>"))return i.replace("</body>",`${P}
81
- </body>`);return i+P}function Xo(i,c,P,M){let U=typeof c==="string"?new URL(c):c,z=new URL(i,U.origin);if(P.preserve){for(let de of P.preserve)if(U.searchParams.has(de)&&!P.exclude?.includes(de)){if(!z.searchParams.has(de))z.searchParams.set(de,U.searchParams.get(de))}}if(M)for(let[de,pe]of Object.entries(M))z.searchParams.set(de,pe);return z.pathname+z.search}var wi=["src/views","views","resources/views","app/views"],bi=["_","components","layouts","partials","scripts","styles"],Ti=[".stx",".html"];function xi(i=process.cwd()){for(let c of wi){let P=Pt(i,c);if(gr(P)&&yi(P).isDirectory())return P}return null}function vn(i,c,P){if(!gr(i))return!1;try{let M=xn(i,{withFileTypes:!0});for(let U of M){if(P.some((z)=>U.name.startsWith(z)||U.name===z))continue;if(U.isFile()&&c.some((z)=>U.name.endsWith(z)))return!0;if(U.isDirectory()){let z=Kt(i,U.name);if(vn(z,c,P))return!0}}}catch{}return!1}function vi(i,c,P){let M=Fr(c,i);for(let z of P)if(M.endsWith(z)){M=M.slice(0,-z.length);break}if(M=M.replace(/\\/g,"/"),M==="index"||M.endsWith("/index"))M=M.replace(/\/?index$/,"");let U=[];if(M=M.replace(/\[\.\.\.([^\]]+)\]/g,(z,de)=>(U.push(de),`{${de}}*`)),M=M.replace(/\[([^\]]+)\]/g,(z,de)=>(U.push(de),`{${de}}`)),!M.startsWith("/"))M=`/${M}`;if(M==="/")return{routePath:"/",params:U};return{routePath:M,params:U}}function Cn(i,c,P,M){let U=[];if(!gr(i))return U;let z=xn(i,{withFileTypes:!0});for(let pe of z){let Re=Kt(i,pe.name);if(M.some((Te)=>pe.name.startsWith(Te)||pe.name===Te))continue;if(pe.isDirectory())U.push(...Cn(Re,c,P,M));else if(pe.isFile()){if(P.some((xe)=>pe.name.endsWith(xe))){let{routePath:xe,params:ve}=vi(Re,c,P);U.push({filePath:Re,routePath:xe,params:ve,isIndex:pe.name.startsWith("index."),isDynamic:ve.length>0})}}}U.sort((pe,Re)=>{if(pe.isDynamic!==Re.isDynamic)return pe.isDynamic?1:-1;let Te=pe.routePath.split("/").length,xe=Re.routePath.split("/").length;if(Te!==xe)return xe-Te;return pe.routePath.localeCompare(Re.routePath)});let de=new Map;for(let pe of U){let Re=de.get(pe.routePath);if(Re)console.warn(`[bun-router] Warning: Duplicate route "${pe.routePath}" found:
82
- - ${Re.filePath}
83
- - ${pe.filePath}
84
- Using: ${Re.filePath}`);else de.set(pe.routePath,pe)}return Array.from(de.values())}function Ci(i,c){let P=Fr(c,i),M=[Pt(process.cwd(),"dist/views",P.replace(/\.stx$/,".html")),Pt(process.cwd(),"views",P.replace(/\.stx$/,".html")),Pt("/var/task/views",P.replace(/\.stx$/,".html"))];for(let U of M)if(gr(U))return U;return null}function Pi(i){let c={};for(let P of String(i??"").split(";")){let M=P.indexOf("=");if(M<0)continue;try{c[P.slice(0,M).trim()]=decodeURIComponent(P.slice(M+1).trim())}catch{}}return c}async function Mi(i,c,P,M,U){let de=await import("@stacksjs/stx");if(!de.processDirectives||!de.extractVariables)throw Error("STX library not properly loaded. Install with: bun add @stacksjs/stx");let pe=await Bun.file(i).text(),Re=pe.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),Te=Re?Re[1]:"",xe=Re?pe.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):pe;xe=xe.replace(/<script\s+client\s*>/gi,"<script>");let ve={status:200,headers:{}},Ce=P.headers??{},Me=String(Ce.cookie??Ce.Cookie??""),Pe=String(P.url??""),Ee=Pe.includes("?")?Pe.slice(Pe.indexOf("?")):"",Ae={url:Pe,path:String(P.path??""),search:Ee,host:String(Ce.host??""),cookieHeader:Me,cookies:Pi(Me),ip:"",locale:null,params:P.params??{},method:String(P.method??"GET"),request:U},Fe={__filename:i,__dirname:Ri(i),props:P,...P,__stxServeContext:Ae,setResponseStatus:(ct)=>{if(Number.isInteger(ct)&&ct>=100&&ct<=599)ve.status=ct},notFound:(ct=404)=>{ve.status=Number.isInteger(ct)&&ct>=400&&ct<=599?ct:404},setResponseHeader:(ct,qs)=>{if(ct)ve.headers[String(ct)]=String(qs)},definePageMeta:()=>{}};if(Te)await de.extractVariables(Te,Fe,i);let Dt=M?.componentsDir?Pt(M.componentsDir):Kt(c,"components"),ir=M?.layoutsDir?Pt(M.layoutsDir):Kt(c,"layouts"),Ss=M?.partialsDir?Pt(M.partialsDir):Kt(c,"partials"),ks={...de.defaultConfig,componentsDir:Dt,layoutsDir:ir,partialsDir:Ss},Hs=await de.processDirectives(xe,Fe,i,ks,new Set),or=Number(Fe.__stxResponseStatus),As=Fe.__stxResponseHeaders;return{html:Hs,status:Number.isInteger(or)&&or>=100&&or<=599?or:ve.status,headers:{...ve.headers,...As??{}}}}function Ei(i,c,P,M){return async(U)=>{let z=new URL(U.url),de={params:U.params||{},query:Object.fromEntries(z.searchParams),url:U.url,path:z.pathname,method:U.method,headers:Object.fromEntries(U.headers.entries())};function pe(Re){if(M?.enabled!==!1&&M?.preserve?.length)return hr(Re,M);return Re}try{let Re=Ci(i,c);if(Re){let xe=await Bun.file(Re).text();return xe=pe(xe),new Response(xe,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}if(i.endsWith(".stx")){let xe=await Mi(i,c,de,P,U),ve=pe(xe.html);return new Response(ve,{status:xe.status,headers:{"Content-Type":"text/html; charset=utf-8",...xe.headers}})}let Te=await Bun.file(i).text();return Te=pe(Te),new Response(Te,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}catch(Re){return console.error(`[bun-router] Error rendering ${i}:`,Re),new Response("Internal Server Error",{status:500})}}}function Pn(i){Object.defineProperties(i.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 c=this._viewsDir||xi();if(!c){this._fileRoutesInitialized=!0;return}let P=this._fileRoutingConfig||{};if(P.enabled===!1){this._fileRoutesInitialized=!0;return}let M=P.extensions||Ti,U=P.exclude||bi;if(!vn(c,M,U)){this._fileRoutesInitialized=!0;return}let z=Cn(c,c,M,U);if(this.config.verbose){console.log(`[bun-router] Auto-discovered ${z.length} file-based routes from ${c}:`);for(let pe of z)console.log(` ${pe.routePath} -> ${Fr(c,pe.filePath)}`)}this._viewsDir=c;let de=new Set;for(let pe of this.routes)if(pe.method==="GET")de.add(pe.path);for(let pe of z){if(de.has(pe.routePath))continue;let Re=Ei(pe.filePath,c,P,this.config.queryPreservation);this.get(pe.routePath,Re,"web"),this._fileBasedRoutes.push(pe),de.add(pe.routePath)}this._fileRoutesInitialized=!0},writable:!0,configurable:!0},views:{value(c){if(typeof c==="string")this._viewsDir=Pt(c),this._fileRoutingConfig={};else{if(c.viewsPath)this._viewsDir=Pt(c.viewsPath);this._fileRoutingConfig=c}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(c,P){if(c)this._viewsDir=Pt(c);if(P)this._fileRoutingConfig={...this._fileRoutingConfig,...P};return this._fileRoutesInitialized=!1,await this._initFileRoutes(),this},writable:!0,configurable:!0},loadFileRoutes:{async value(c={}){return this.fileRoutes(c.viewsPath,c)},writable:!0,configurable:!0}})}class mr{stream;headers;status;constructor(i,c={}){if(this.stream=i,this.status=c.status||200,this.headers=new Headers(c.headers),c.contentType)this.headers.set("Content-Type",c.contentType)}toResponse(){return new Response(this.stream,{status:this.status,headers:this.headers})}addHeader(i,c){return this.headers.set(i,c),this}setContentType(i){return this.headers.set("Content-Type",i),this}setStatus(i){return this.status=i,this}}class dt{static direct(i,c={}){let{format:P="json",delimiter:M=`
85
- `,contentType:U,headers:z={},status:de=200,enableCompression:pe=!1}=c,Re=new ReadableStream({async start(xe){try{let ve=new TextEncoder,Ce=!0;for await(let Me of Array.isArray(i)?i:i){if(!Ce&&M)xe.enqueue(ve.encode(M));let Pe=dt.formatData(Me,P);xe.enqueue(ve.encode(Pe)),Ce=!1}xe.close()}catch(ve){xe.error(ve)}}}),Te=new Headers(z);if(U)Te.set("Content-Type",U);else Te.set("Content-Type",dt.getContentTypeForFormat(P));return new mr(Re,{headers:Te,status:de})}static buffered(i,c={}){let{format:P="json",bufferSize:M=1024,flushInterval:U=100,contentType:z,headers:de={},status:pe=200}=c,Re=new ReadableStream({async start(xe){try{let ve=new TextEncoder,Ce=[],Me=0,Pe=()=>{if(Ce.length>0){let Ae=Ce.join("");xe.enqueue(ve.encode(Ae)),Ce=[],Me=0}},Ee=setInterval(Pe,U);try{for await(let Ae of Array.isArray(i)?i:i){let Fe=dt.formatData(Ae,P);if(Ce.push(Fe),Me+=Fe.length,Me>=M)Pe()}Pe()}finally{clearInterval(Ee)}xe.close()}catch(ve){xe.error(ve)}}}),Te=new Headers(de);if(z)Te.set("Content-Type",z);else Te.set("Content-Type",dt.getContentTypeForFormat(P));return new mr(Re,{headers:Te,status:pe})}static json(i,c={}){return dt.direct(i,{...c,format:"json",contentType:c.contentType||"application/json"})}static text(i,c={}){return dt.direct(i,{...c,format:"text",contentType:c.contentType||"text/plain"})}static csv(i,c={}){let{csvHeaders:P,...M}=c,U=new ReadableStream({async start(z){try{let de=new TextEncoder,pe=!0;if(P&&P.length>0)z.enqueue(de.encode(`${P.join(",")}
86
- `));for await(let Re of Array.isArray(i)?i:i){let Te=dt.objectToCsvRow(Re,P);z.enqueue(de.encode(`${Te}
87
- `))}z.close()}catch(de){z.error(de)}}});return new mr(U,{headers:M.headers,status:M.status,contentType:M.contentType||"text/csv"})}static formatData(i,c){switch(c){case"json":return JSON.stringify(i);case"text":return String(i);case"csv":return typeof i==="object"?dt.objectToCsvRow(i):String(i);case"ndjson":return JSON.stringify(i);default:return JSON.stringify(i)}}static objectToCsvRow(i,c){return(c||Object.keys(i)).map((M)=>{let U=i[M],z=U===null||U===void 0?"":String(U);if(z.includes(",")||z.includes('"')||z.includes(`
88
- `))return`"${z.replace(/"/g,'""')}"`;return z}).join(",")}static getContentTypeForFormat(i){switch(i){case"json":case"ndjson":return"application/json";case"text":return"text/plain";case"csv":return"text/csv";default:return"application/json"}}}class It{static async streamFile(i,c,P={}){let{contentType:M,enableRanges:U=!0,chunkSize:z=65536}=P;try{let de=Bun.file(i),pe=de.size,Re=U?c.headers.get("range"):null;if(Re&&U)return It.handleRangeRequest(de,Re,M);let Te=new Headers({"Content-Length":pe.toString(),"Accept-Ranges":U?"bytes":"none"});if(M)Te.set("Content-Type",M);return new Response(de.stream(),{status:200,headers:Te})}catch(de){return console.error("Error streaming file:",de),new Response("File not found",{status:404})}}static async handleRangeRequest(i,c,P){let M=It.parseRangeHeader(c,i.size);if(!M||M.length===0)return new Response("Invalid range",{status:416});let[U,z]=M[0],de=z-U+1,pe=new Headers({"Content-Range":`bytes ${U}-${z}/${i.size}`,"Content-Length":de.toString(),"Accept-Ranges":"bytes"});if(P)pe.set("Content-Type",P);let Re=i.slice(U,z+1);return new Response(Re.stream(),{status:206,headers:pe})}static parseRangeHeader(i,c){let P=i.match(/^bytes=(.+)$/);if(!P)return null;let M=[],U=P[1].split(",");for(let z of U){let[de,pe]=z.trim().split("-"),Re,Te;if(de==="")Re=Math.max(0,c-Number.parseInt(pe,10)),Te=c-1;else if(pe==="")Re=Number.parseInt(de,10),Te=c-1;else Re=Number.parseInt(de,10),Te=Number.parseInt(pe,10);if(Re<0||Te>=c||Re>Te)return null;M.push([Re,Te])}return M}}function fr(i,c){try{i.close()}catch{}}function Mn(i){Object.defineProperties(i.prototype,{streamFile:{value(c,P,M){return It.streamFile(c,P,M)},writable:!0,configurable:!0},streamFileWithRanges:{async value(c,P){return It.streamFile(c,P,{enableRanges:!0})},writable:!0,configurable:!0},health:{value(){let P=this.config.apiPrefix?`${this.config.apiPrefix}/health`:"/health";return this.get(P,()=>new Response("OK",{headers:{"Content-Type":"text/plain"}})),this},writable:!0,configurable:!0},streamResponse:{value(c,P){let M=new Headers;if(P?.headers)for(let[U,z]of Object.entries(P.headers))M.set(U,z);return new Response(c(),{status:P?.status||200,headers:M})},writable:!0,configurable:!0},transformStream:{value(c,P){return(M)=>{if(!M.body)throw Error("Request body is required for stream transformation");let U=new TransformStream({async transform(de,pe){try{let Re=await c(de);if(typeof Re==="string")pe.enqueue(new TextEncoder().encode(Re));else pe.enqueue(Re)}catch(Re){pe.error(Re)}}}),z=new Headers;if(P?.headers)for(let[de,pe]of Object.entries(P.headers))z.set(de,pe);return new Response(M.body.pipeThrough(U),{status:P?.status||200,headers:z})}},writable:!0,configurable:!0},stream:{value(c,P=200,M={}){let U=new Headers(M),z=new ReadableStream({async start(de){let pe=new TextEncoder;try{for await(let Re of c())if(typeof Re==="string")de.enqueue(pe.encode(Re));else de.enqueue(Re);de.close()}catch(Re){fr(de,Re)}}});return new Response(z,{status:P,headers:U})},writable:!0,configurable:!0},streamJson:{value(c,P=200,M={}){let U=new Headers({"Content-Type":"application/json",...M}),z=new ReadableStream({async start(de){let pe=new TextEncoder;try{de.enqueue(pe.encode("{"));let Re=Object.keys(c);for(let Te=0;Te<Re.length;Te++){let xe=Re[Te],ve=c[xe];de.enqueue(pe.encode(`"${xe}":[`));let Ce=!0;for await(let Me of ve){if(!Ce)de.enqueue(pe.encode(","));de.enqueue(pe.encode(JSON.stringify(Me))),Ce=!1}if(de.enqueue(pe.encode("]")),Te<Re.length-1)de.enqueue(pe.encode(","))}de.enqueue(pe.encode("}")),de.close()}catch(Re){fr(de,Re)}}});return new Response(z,{status:P,headers:U})},writable:!0,configurable:!0},eventStream:{value(c,P={}){let M=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Cache-Control",...P}),U=new ReadableStream({async start(z){let de=new TextEncoder;try{for await(let pe of c()){let Re="";if(pe.id)Re+=`id: ${pe.id}
89
- `;if(pe.event)Re+=`event: ${pe.event}
90
- `;if(pe.retry)Re+=`retry: ${pe.retry}
91
- `;let Te=typeof pe.data==="string"?pe.data:JSON.stringify(pe.data);Re+=`data: ${Te}
79
+ </script>`}function Rr(o,l){if(!l.enabled||!l.preserve?.length)return o;let M=fi(l);if(!M)return o;if(o.includes("</head>"))return o.replace("</head>",`${M}
80
+ </head>`);if(o.includes("</body>"))return o.replace("</body>",`${M}
81
+ </body>`);return o+M}function Yo(o,l,M,k){let L=typeof l==="string"?new URL(l):l,V=new URL(o,L.origin);if(M.preserve){for(let pe of M.preserve)if(L.searchParams.has(pe)&&!M.exclude?.includes(pe)){if(!V.searchParams.has(pe))V.searchParams.set(pe,L.searchParams.get(pe))}}if(k)for(let[pe,he]of Object.entries(k))V.searchParams.set(pe,he);return V.pathname+V.search}var wi=["src/views","views","resources/views","app/views"],bi=["_","components","layouts","partials","scripts","styles"],Ti=[".stx",".html"];function xi(o=process.cwd()){for(let l of wi){let M=Et(o,l);if(yr(M)&&yi(M).isDirectory())return M}return null}function En(o,l,M){if(!yr(o))return!1;try{let k=Mn(o,{withFileTypes:!0});for(let L of k){if(M.some((V)=>L.name.startsWith(V)||L.name===V))continue;if(L.isFile()&&l.some((V)=>L.name.endsWith(V)))return!0;if(L.isDirectory()){let V=er(o,L.name);if(En(V,l,M))return!0}}}catch{}return!1}function vi(o,l,M){let k=jr(l,o);for(let V of M)if(k.endsWith(V)){k=k.slice(0,-V.length);break}if(k=k.replace(/\\/g,"/"),k==="index"||k.endsWith("/index"))k=k.replace(/\/?index$/,"");let L=[];if(k=k.replace(/\[\.\.\.([^\]]+)\]/g,(V,pe)=>(L.push(pe),`{${pe}}*`)),k=k.replace(/\[([^\]]+)\]/g,(V,pe)=>(L.push(pe),`{${pe}}`)),!k.startsWith("/"))k=`/${k}`;if(k==="/")return{routePath:"/",params:L};return{routePath:k,params:L}}function Sn(o,l,M,k){let L=[];if(!yr(o))return L;let V=Mn(o,{withFileTypes:!0});for(let he of V){let Te=er(o,he.name);if(k.some((xe)=>he.name.startsWith(xe)||he.name===xe))continue;if(he.isDirectory())L.push(...Sn(Te,l,M,k));else if(he.isFile()){if(M.some((ve)=>he.name.endsWith(ve))){let{routePath:ve,params:Pe}=vi(Te,l,M);L.push({filePath:Te,routePath:ve,params:Pe,isIndex:he.name.startsWith("index."),isDynamic:Pe.length>0})}}}L.sort((he,Te)=>{if(he.isDynamic!==Te.isDynamic)return he.isDynamic?1:-1;let xe=he.routePath.split("/").length,ve=Te.routePath.split("/").length;if(xe!==ve)return ve-xe;return he.routePath.localeCompare(Te.routePath)});let pe=new Map;for(let he of L){let Te=pe.get(he.routePath);if(Te)console.warn(`[bun-router] Warning: Duplicate route "${he.routePath}" found:
82
+ - ${Te.filePath}
83
+ - ${he.filePath}
84
+ Using: ${Te.filePath}`);else pe.set(he.routePath,he)}return Array.from(pe.values())}function Pi(o,l){let M=jr(l,o),k=[Et(process.cwd(),"dist/views",M.replace(/\.stx$/,".html")),Et(process.cwd(),"views",M.replace(/\.stx$/,".html")),Et("/var/task/views",M.replace(/\.stx$/,".html"))];for(let L of k)if(yr(L))return L;return null}function Ci(o){let l={};for(let M of String(o??"").split(";")){let k=M.indexOf("=");if(k<0)continue;try{l[M.slice(0,k).trim()]=decodeURIComponent(M.slice(k+1).trim())}catch{}}return l}async function Mi(o,l,M,k,L){let pe=await import("@stacksjs/stx");if(!pe.processDirectives||!pe.extractVariables)throw Error("STX library not properly loaded. Install with: bun add @stacksjs/stx");let he=await Bun.file(o).text(),Te=he.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),xe=Te?Te[1]:"",ve=Te?he.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):he;ve=ve.replace(/<script\s+client\s*>/gi,"<script>");let Pe={status:200,headers:{}},Ce=M.headers??{},Ee=String(Ce.cookie??Ce.Cookie??""),Me=String(M.url??""),Se=Me.includes("?")?Me.slice(Me.indexOf("?")):"",Oe={url:Me,path:String(M.path??""),search:Se,host:String(Ce.host??""),cookieHeader:Ee,cookies:Ci(Ee),ip:"",locale:null,params:M.params??{},method:String(M.method??"GET"),request:L},Fe={__filename:o,__dirname:Ri(o),props:M,...M,__stxServeContext:Oe,setResponseStatus:(pt)=>{if(Number.isInteger(pt)&&pt>=100&&pt<=599)Pe.status=pt},notFound:(pt=404)=>{Pe.status=Number.isInteger(pt)&&pt>=400&&pt<=599?pt:404},setResponseHeader:(pt,Fs)=>{if(pt)Pe.headers[String(pt)]=String(Fs)},definePageMeta:()=>{}};if(xe)await pe.extractVariables(xe,Fe,o);let Ut=k?.componentsDir?Et(k.componentsDir):er(l,"components"),lr=k?.layoutsDir?Et(k.layoutsDir):er(l,"layouts"),$s=k?.partialsDir?Et(k.partialsDir):er(l,"partials"),Bs={...pe.defaultConfig,componentsDir:Ut,layoutsDir:lr,partialsDir:$s},Ds=await pe.processDirectives(ve,Fe,o,Bs,new Set),dr=Number(Fe.__stxResponseStatus),Ns=Fe.__stxResponseHeaders;return{html:Ds,status:Number.isInteger(dr)&&dr>=100&&dr<=599?dr:Pe.status,headers:{...Pe.headers,...Ns??{}}}}function Ei(o,l,M,k){return async(L)=>{let V=new URL(L.url),pe={params:L.params||{},query:Object.fromEntries(V.searchParams),url:L.url,path:V.pathname,method:L.method,headers:Object.fromEntries(L.headers.entries())};function he(Te){if(k?.enabled!==!1&&k?.preserve?.length)return Rr(Te,k);return Te}try{let Te=Pi(o,l);if(Te){let ve=await Bun.file(Te).text();return ve=he(ve),new Response(ve,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}if(o.endsWith(".stx")){let ve=await Mi(o,l,pe,M,L),Pe=he(ve.html);return new Response(Pe,{status:ve.status,headers:{"Content-Type":"text/html; charset=utf-8",...ve.headers}})}let xe=await Bun.file(o).text();return xe=he(xe),new Response(xe,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}catch(Te){return console.error(`[bun-router] Error rendering ${o}:`,Te),new Response("Internal Server Error",{status:500})}}}function kn(o){Object.defineProperties(o.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 l=this._viewsDir||xi();if(!l){this._fileRoutesInitialized=!0;return}let M=this._fileRoutingConfig||{};if(M.enabled===!1){this._fileRoutesInitialized=!0;return}let k=M.extensions||Ti,L=M.exclude||bi;if(!En(l,k,L)){this._fileRoutesInitialized=!0;return}let V=Sn(l,l,k,L);if(this.config.verbose){console.log(`[bun-router] Auto-discovered ${V.length} file-based routes from ${l}:`);for(let he of V)console.log(` ${he.routePath} -> ${jr(l,he.filePath)}`)}this._viewsDir=l;let pe=new Set;for(let he of this.routes)if(he.method==="GET")pe.add(he.path);for(let he of V){if(pe.has(he.routePath))continue;let Te=Ei(he.filePath,l,M,this.config.queryPreservation);this.get(he.routePath,Te,"web"),this._fileBasedRoutes.push(he),pe.add(he.routePath)}this._fileRoutesInitialized=!0},writable:!0,configurable:!0},views:{value(l){if(typeof l==="string")this._viewsDir=Et(l),this._fileRoutingConfig={};else{if(l.viewsPath)this._viewsDir=Et(l.viewsPath);this._fileRoutingConfig=l}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(l,M){if(l)this._viewsDir=Et(l);if(M)this._fileRoutingConfig={...this._fileRoutingConfig,...M};return this._fileRoutesInitialized=!1,await this._initFileRoutes(),this},writable:!0,configurable:!0},loadFileRoutes:{async value(l={}){return this.fileRoutes(l.viewsPath,l)},writable:!0,configurable:!0}})}class wr{stream;headers;status;constructor(o,l={}){if(this.stream=o,this.status=l.status||200,this.headers=new Headers(l.headers),l.contentType)this.headers.set("Content-Type",l.contentType)}toResponse(){return new Response(this.stream,{status:this.status,headers:this.headers})}addHeader(o,l){return this.headers.set(o,l),this}setContentType(o){return this.headers.set("Content-Type",o),this}setStatus(o){return this.status=o,this}}class gt{static direct(o,l={}){let{format:M="json",delimiter:k=`
85
+ `,contentType:L,headers:V={},status:pe=200,enableCompression:he=!1}=l,Te=new ReadableStream({async start(ve){try{let Pe=new TextEncoder,Ce=!0;for await(let Ee of Array.isArray(o)?o:o){if(!Ce&&k)ve.enqueue(Pe.encode(k));let Me=gt.formatData(Ee,M);ve.enqueue(Pe.encode(Me)),Ce=!1}ve.close()}catch(Pe){ve.error(Pe)}}}),xe=new Headers(V);if(L)xe.set("Content-Type",L);else xe.set("Content-Type",gt.getContentTypeForFormat(M));return new wr(Te,{headers:xe,status:pe})}static buffered(o,l={}){let{format:M="json",bufferSize:k=1024,flushInterval:L=100,contentType:V,headers:pe={},status:he=200}=l,Te=new ReadableStream({async start(ve){try{let Pe=new TextEncoder,Ce=[],Ee=0,Me=()=>{if(Ce.length>0){let Oe=Ce.join("");ve.enqueue(Pe.encode(Oe)),Ce=[],Ee=0}},Se=setInterval(Me,L);try{for await(let Oe of Array.isArray(o)?o:o){let Fe=gt.formatData(Oe,M);if(Ce.push(Fe),Ee+=Fe.length,Ee>=k)Me()}Me()}finally{clearInterval(Se)}ve.close()}catch(Pe){ve.error(Pe)}}}),xe=new Headers(pe);if(V)xe.set("Content-Type",V);else xe.set("Content-Type",gt.getContentTypeForFormat(M));return new wr(Te,{headers:xe,status:he})}static json(o,l={}){return gt.direct(o,{...l,format:"json",contentType:l.contentType||"application/json"})}static text(o,l={}){return gt.direct(o,{...l,format:"text",contentType:l.contentType||"text/plain"})}static csv(o,l={}){let{csvHeaders:M,...k}=l,L=new ReadableStream({async start(V){try{let pe=new TextEncoder,he=!0;if(M&&M.length>0)V.enqueue(pe.encode(`${M.join(",")}
86
+ `));for await(let Te of Array.isArray(o)?o:o){let xe=gt.objectToCsvRow(Te,M);V.enqueue(pe.encode(`${xe}
87
+ `))}V.close()}catch(pe){V.error(pe)}}});return new wr(L,{headers:k.headers,status:k.status,contentType:k.contentType||"text/csv"})}static formatData(o,l){switch(l){case"json":return JSON.stringify(o);case"text":return String(o);case"csv":return typeof o==="object"?gt.objectToCsvRow(o):String(o);case"ndjson":return JSON.stringify(o);default:return JSON.stringify(o)}}static objectToCsvRow(o,l){return(l||Object.keys(o)).map((k)=>{let L=o[k],V=L===null||L===void 0?"":String(L);if(V.includes(",")||V.includes('"')||V.includes(`
88
+ `))return`"${V.replace(/"/g,'""')}"`;return V}).join(",")}static getContentTypeForFormat(o){switch(o){case"json":case"ndjson":return"application/json";case"text":return"text/plain";case"csv":return"text/csv";default:return"application/json"}}}class Lt{static async streamFile(o,l,M={}){let{contentType:k,enableRanges:L=!0,chunkSize:V=65536}=M;try{let pe=Bun.file(o),he=pe.size,Te=L?l.headers.get("range"):null;if(Te&&L)return Lt.handleRangeRequest(pe,Te,k);let xe=new Headers({"Content-Length":he.toString(),"Accept-Ranges":L?"bytes":"none"});if(k)xe.set("Content-Type",k);return new Response(pe.stream(),{status:200,headers:xe})}catch(pe){return console.error("Error streaming file:",pe),new Response("File not found",{status:404})}}static async handleRangeRequest(o,l,M){let k=Lt.parseRangeHeader(l,o.size);if(!k||k.length===0)return new Response("Invalid range",{status:416});let[L,V]=k[0],pe=V-L+1,he=new Headers({"Content-Range":`bytes ${L}-${V}/${o.size}`,"Content-Length":pe.toString(),"Accept-Ranges":"bytes"});if(M)he.set("Content-Type",M);let Te=o.slice(L,V+1);return new Response(Te.stream(),{status:206,headers:he})}static parseRangeHeader(o,l){let M=o.match(/^bytes=(.+)$/);if(!M)return null;let k=[],L=M[1].split(",");for(let V of L){let[pe,he]=V.trim().split("-"),Te,xe;if(pe==="")Te=Math.max(0,l-Number.parseInt(he,10)),xe=l-1;else if(he==="")Te=Number.parseInt(pe,10),xe=l-1;else Te=Number.parseInt(pe,10),xe=Number.parseInt(he,10);if(Te<0||xe>=l||Te>xe)return null;k.push([Te,xe])}return k}}function br(o,l){try{o.close()}catch{}}function Hn(o){Object.defineProperties(o.prototype,{streamFile:{value(l,M,k){return Lt.streamFile(l,M,k)},writable:!0,configurable:!0},streamFileWithRanges:{async value(l,M){return Lt.streamFile(l,M,{enableRanges:!0})},writable:!0,configurable:!0},health:{value(){let M=this.config.apiPrefix?`${this.config.apiPrefix}/health`:"/health";return this.get(M,()=>new Response("OK",{headers:{"Content-Type":"text/plain"}})),this},writable:!0,configurable:!0},streamResponse:{value(l,M){let k=new Headers;if(M?.headers)for(let[L,V]of Object.entries(M.headers))k.set(L,V);return new Response(l(),{status:M?.status||200,headers:k})},writable:!0,configurable:!0},transformStream:{value(l,M){return(k)=>{if(!k.body)throw Error("Request body is required for stream transformation");let L=new TransformStream({async transform(pe,he){try{let Te=await l(pe);if(typeof Te==="string")he.enqueue(new TextEncoder().encode(Te));else he.enqueue(Te)}catch(Te){he.error(Te)}}}),V=new Headers;if(M?.headers)for(let[pe,he]of Object.entries(M.headers))V.set(pe,he);return new Response(k.body.pipeThrough(L),{status:M?.status||200,headers:V})}},writable:!0,configurable:!0},stream:{value(l,M=200,k={}){let L=new Headers(k),V=new ReadableStream({async start(pe){let he=new TextEncoder;try{for await(let Te of l())if(typeof Te==="string")pe.enqueue(he.encode(Te));else pe.enqueue(Te);pe.close()}catch(Te){br(pe,Te)}}});return new Response(V,{status:M,headers:L})},writable:!0,configurable:!0},streamJson:{value(l,M=200,k={}){let L=new Headers({"Content-Type":"application/json",...k}),V=new ReadableStream({async start(pe){let he=new TextEncoder;try{pe.enqueue(he.encode("{"));let Te=Object.keys(l);for(let xe=0;xe<Te.length;xe++){let ve=Te[xe],Pe=l[ve];pe.enqueue(he.encode(`"${ve}":[`));let Ce=!0;for await(let Ee of Pe){if(!Ce)pe.enqueue(he.encode(","));pe.enqueue(he.encode(JSON.stringify(Ee))),Ce=!1}if(pe.enqueue(he.encode("]")),xe<Te.length-1)pe.enqueue(he.encode(","))}pe.enqueue(he.encode("}")),pe.close()}catch(Te){br(pe,Te)}}});return new Response(V,{status:M,headers:L})},writable:!0,configurable:!0},eventStream:{value(l,M={}){let k=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Cache-Control",...M}),L=new ReadableStream({async start(V){let pe=new TextEncoder;try{for await(let he of l()){let Te="";if(he.id)Te+=`id: ${he.id}
89
+ `;if(he.event)Te+=`event: ${he.event}
90
+ `;if(he.retry)Te+=`retry: ${he.retry}
91
+ `;let xe=typeof he.data==="string"?he.data:JSON.stringify(he.data);Te+=`data: ${xe}
92
92
 
93
- `,z.enqueue(de.encode(Re))}z.close()}catch(pe){fr(z,pe)}}});return new Response(U,{status:200,headers:M})},writable:!0,configurable:!0},streamDownload:{value(c,P,M={}){let U=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${P}"`,...M}),z=new ReadableStream({async start(de){let pe=new TextEncoder;try{for await(let Re of c())if(typeof Re==="string")de.enqueue(pe.encode(Re));else de.enqueue(Re);de.close()}catch(Re){fr(de,Re)}}});return new Response(z,{status:200,headers:U})},writable:!0,configurable:!0},streamAsyncIterator:{value(c,P={}){return dt.direct(c,P).toResponse()},writable:!0,configurable:!0}})}class Rr extends Error{modelName;value;field;constructor(i,c,P="id"){super(`${i} not found with ${P}: ${c}`);this.modelName=i;this.value=c;this.field=P;this.name="ModelNotFoundError"}}class Sn{bindings=new Map;model(i,c){this.bindings.set(i,c)}bind(i,c){this.bindings.set(i,c)}getBinding(i){return this.bindings.get(i)}hasBinding(i){return this.bindings.has(i)}}var Si=new Sn;async function En(i,c,P,M,U={}){if(M)return await P.resolveRouteBinding(c,M);let z=P.getRouteKeyName();if(z!=="id")return await P.resolveRouteBinding(c,z);return await P.find(c)}function kn(i,c){return async(P,M)=>{let U={};try{for(let z of i){let de=P.params?.[z.name];if(!de)continue;let pe=Si.getBinding(z.name);if(pe){let xe=null;if(typeof pe==="function")xe=await pe(de);else xe=await En(z.name,de,pe,z.key,U);if(!xe)throw new Rr(z.name,de,z.key||"id");U[z.name]=xe;continue}let Re=c[z.name];if(!Re)continue;let Te=await En(z.name,de,Re,z.key,U);if(!Te)throw new Rr(z.name,de,z.key||"id");U[z.name]=Te}return P.models=U,await M()}catch(z){if(z instanceof Rr)return new Response(`${z.modelName} not found`,{status:404});throw z}}}class Hn{key;entry;prev;next;constructor(i,c,P=null,M=null){this.key=i;this.entry=c;this.prev=P;this.next=M}}class Xt{options;cache=new Map;head=null;tail=null;stats={hits:0,misses:0,evictions:0};constructor(i){this.options=i;if(i.maxSize<=0)throw Error("maxSize must be greater than 0")}get(i){let c=this.cache.get(i);if(!c){this.stats.misses++;return}let P=Date.now(),M=c.entry;if(this.isExpired(M,P)){if(!this.options.allowStale){this.delete(i),this.stats.misses++;return}}if(M.lastAccessed=P,M.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(c);return M.value}set(i,c,P){let M=Date.now(),U=this.cache.get(i);if(U){U.entry.value=c,U.entry.timestamp=M,U.entry.lastAccessed=M,U.entry.ttl=P??this.options.ttl,this.moveToFront(U);return}let z={value:c,timestamp:M,accessCount:0,lastAccessed:M,ttl:P??this.options.ttl},de=new Hn(i,z);if(this.cache.set(i,de),this.addToFront(de),this.cache.size>this.options.maxSize)this.evictLRU()}delete(i){let c=this.cache.get(i);if(!c)return!1;if(this.cache.delete(i),this.removeNode(c),this.options.onEvict)this.options.onEvict(i,c.entry.value);return!0}has(i){let c=this.cache.get(i);if(!c)return!1;let P=Date.now();if(this.isExpired(c.entry,P)){if(!this.options.allowStale)return this.delete(i),!1}return!0}clear(){if(this.options.onEvict)for(let[i,c]of this.cache)this.options.onEvict(i,c.entry.value);this.cache.clear(),this.head=null,this.tail=null,this.stats.evictions+=this.cache.size}keys(){let i=[],c=this.head;while(c)i.push(c.key),c=c.next;return i}values(){let i=[],c=this.head;while(c)i.push(c.entry.value),c=c.next;return i}getStats(){let i=this.estimateMemoryUsage(),c=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:c>0?this.stats.hits/c:0,memoryUsage:i}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}prune(){let i=Date.now(),c=[];for(let[P,M]of this.cache)if(this.isExpired(M.entry,i))c.push(P);for(let P of c)this.delete(P);return c.length}getFrequentlyUsed(i=10){let c=[];for(let[P,M]of this.cache)c.push({key:P,value:M.entry.value,accessCount:M.entry.accessCount});return c.sort((P,M)=>M.accessCount-P.accessCount).slice(0,i)}resize(i){if(i<=0)throw Error("maxSize must be greater than 0");this.options.maxSize=i;while(this.cache.size>i)this.evictLRU()}isExpired(i,c){if(!i.ttl)return!1;return c-i.timestamp>i.ttl}moveToFront(i){if(i===this.head)return;this.removeNode(i),this.addToFront(i)}addToFront(i){if(i.prev=null,i.next=this.head,this.head)this.head.prev=i;if(this.head=i,!this.tail)this.tail=i}removeNode(i){if(i.prev)i.prev.next=i.next;else this.head=i.next;if(i.next)i.next.prev=i.prev;else this.tail=i.prev}evictLRU(){if(!this.tail)return;let i=this.tail.key,c=this.tail.entry.value;if(this.cache.delete(i),this.removeNode(this.tail),this.stats.evictions++,this.options.onEvict)this.options.onEvict(i,c)}estimateMemoryUsage(){let i=0;for(let[c,P]of this.cache)i+=c.length*2,i+=this.estimateValueSize(P.entry.value),i+=64;return i+=this.cache.size*48,i}estimateValueSize(i){if(i===null||i===void 0)return 0;if(typeof i==="string")return i.length*2;if(typeof i==="number")return 8;if(typeof i==="boolean")return 1;if(i instanceof ArrayBuffer)return i.byteLength;if(i instanceof Uint8Array)return i.length;try{return JSON.stringify(i).length*2}catch{return 100}}}class An{static generateKey(i,c){let P=new URL(i.url),M=i.method,U=P.pathname,z=[M,U],de=new URLSearchParams(P.search),pe=c.excludeQuery||[],Re=[];for(let[Te,xe]of de.entries())if(!pe.includes(Te))Re.push(`${Te}=${xe}`);if(Re.length>0)z.push(Re.sort().join("&"));if(c.varyBy){let Te=[];for(let xe of c.varyBy){let ve=i.headers.get(xe);if(ve)Te.push(`${xe}:${ve}`)}if(Te.length>0)z.push(Te.join("|"))}return z.join("::")}}class qn{cache;tagIndex=new Map;keyTags=new Map;constructor(i=1000){this.cache=new Xt({maxSize:i})}async get(i){let c=this.cache.get(i);if(!c)return null;if(c.ttl&&Date.now()-c.timestamp>c.ttl)return this.delete(i),null;return c}async set(i,c){this.cache.set(i,c),this.keyTags.set(i,new Set(c.tags));for(let P of c.tags){if(!this.tagIndex.has(P))this.tagIndex.set(P,new Set);this.tagIndex.get(P).add(i)}}delete(i){let c=this.keyTags.get(i);if(c){for(let P of c){let M=this.tagIndex.get(P);if(M){if(M.delete(i),M.size===0)this.tagIndex.delete(P)}}this.keyTags.delete(i)}return this.cache.delete(i)}invalidateByTags(i){let c=new Set;for(let P of i){let M=this.tagIndex.get(P);if(M)for(let U of M)c.add(U)}for(let P of c)this.delete(P);return c.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 _t=new qn;function On(i){return async(c,P)=>{if(i.condition&&!i.condition(c))return await P();if(c.method!=="GET"&&c.method!=="HEAD")return await P();let M=An.generateKey(c,i),U=await _t.get(M);if(U){let de=new Headers(U.headers);if(de.set("X-Cache","HIT"),de.set("X-Cache-Key",M),U.etag){if(de.set("ETag",U.etag),c.headers.get("If-None-Match")===U.etag)return new Response(null,{status:304,headers:de})}return new Response(U.body,{status:U.status,headers:de})}let z=await P();if(z.status>=200&&z.status<300)try{let de=z.clone(),pe=await de.arrayBuffer(),Re=await ki(pe),Te={};de.headers.forEach((Ce,Me)=>{Te[Me]=Ce});let xe={response:de,headers:Te,status:z.status,body:new Uint8Array(pe),timestamp:Date.now(),ttl:i.ttl,tags:i.tags||[],etag:Re};await _t.set(M,xe);let ve=new Headers(z.headers);return ve.set("X-Cache","MISS"),ve.set("X-Cache-Key",M),ve.set("ETag",Re),new Response(z.body,{status:z.status,headers:ve})}catch(de){return console.error("Error caching response:",de),z}return z}}async function ki(i){let c=await crypto.subtle.digest("SHA-256",i);return`"${Array.from(new Uint8Array(c)).map((U)=>U.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var $n={short:(i=[])=>({ttl:300000,maxSize:500,tags:i}),medium:(i=[])=>({ttl:3600000,maxSize:1000,tags:i}),long:(i=[])=>({ttl:86400000,maxSize:2000,tags:i}),api:(i=[])=>({ttl:900000,maxSize:1000,tags:i,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(i=[])=>({ttl:604800000,maxSize:5000,tags:i,varyBy:["Accept-Encoding"]}),user:(i=[])=>({ttl:1800000,maxSize:2000,tags:i,varyBy:["Authorization"],condition:(c)=>!!c.headers.get("Authorization")})},ca={byTags:(i)=>_t.invalidateByTags(i),forUser:(i)=>_t.invalidateByTags([`user:${i}`]),forModel:(i,c)=>{let P=c?[`${i}:${c}`,i]:[i];return _t.invalidateByTags(P)},all:()=>{_t.clear()}};class yr{cache;config;constructor(i,c=1e4){this.config=i,this.cache=new Xt({maxSize:c,ttl:i.windowMs*2})}async checkLimit(i){if(this.config.skipIf&&this.config.skipIf(i))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 c=this.generateKey(i),P=Date.now(),M=this.cache.get(c);if(!M||P>=M.resetTime)M={count:1,resetTime:P+this.config.windowMs,firstHit:P};else M.count++;this.cache.set(c,M);let U={totalHits:M.count,resetTime:new Date(M.resetTime),remaining:Math.max(0,this.config.maxAttempts-M.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:M.count<=this.config.maxAttempts,info:U}}generateKey(i){if(this.config.keyGenerator)return this.config.keyGenerator(i);let c=this.getClientIP(i),P=i.user?.id;if(P)return`user:${P}`;return`ip:${c}`}getClientIP(i){let c=i.headers.get("x-forwarded-for");if(c)return c.split(",")[0].trim();let P=i.headers.get("x-real-ip");if(P)return P;let M=i.headers.get("cf-connecting-ip");if(M)return M;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class Bn{limiters=new Map;register(i,c){let P=new yr(c);return this.limiters.set(i,P),P}get(i){return this.limiters.get(i)}getOrCreate(i,c){let P=this.limiters.get(i);if(P)return P;return this.register(i,c)}}var Dn=new Bn;function jt(i,c){let P=c?Dn.getOrCreate(c,i):new yr(i);return async(M,U)=>{let{allowed:z,info:de}=await P.checkLimit(M);if(!z){if(i.onLimitReached)return i.onLimitReached(M,de);let Re=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((de.resetTime.getTime()-Date.now())/1000).toString()});if(i.headers!==!1)Re.set("X-RateLimit-Limit",de.limit.toString()),Re.set("X-RateLimit-Remaining",de.remaining.toString()),Re.set("X-RateLimit-Reset",Math.ceil(de.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((de.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((de.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:Re})}let pe=await U();if(pe&&i.headers!==!1&&pe.status<400){let Re=new Headers(pe.headers);return Re.set("X-RateLimit-Limit",de.limit.toString()),Re.set("X-RateLimit-Remaining",de.remaining.toString()),Re.set("X-RateLimit-Reset",Math.ceil(de.resetTime.getTime()/1000).toString()),new Response(pe.body,{status:pe.status,statusText:pe.statusText,headers:Re})}return pe}}function Lt(i){let c=i.split(","),P=Number.parseInt(c[0],10);if(Number.isNaN(P)||P<=0)throw Error(`Invalid throttle max attempts: ${c[0]}`);let M;if(c.length===1)M=60000;else{let U=c[1];M=Hi(U)}return{maxAttempts:P,windowMs:M}}function Hi(i){let c=/^(\d+)([smh]|sec|min|hour)?$/,P=i.match(c);if(!P)throw Error(`Invalid time format: ${i}`);let M=Number.parseInt(P[1],10),U=P[2]||"m";if(Number.isNaN(M)||M<=0)throw Error(`Invalid time value: ${P[1]}`);switch(U){case"s":case"sec":return M*1000;case"m":case"min":return M*60*1000;case"h":case"hour":return M*60*60*1000;default:return M*60*1000}}var Ai={api:(i=60,c=1)=>({maxAttempts:i,windowMs:c*60*1000,headers:!0}),auth:()=>({maxAttempts:5,windowMs:900000,keyGenerator:(i)=>{let c=i.headers.get("x-forwarded-for")?.split(",")[0]||"unknown",P=i.jsonBody?.email||i.formBody?.email||i.query?.email||"unknown";return`auth:${c}:${P}`},onLimitReached:(i,c)=>new Response(JSON.stringify({error:"Too many authentication attempts",message:"Please try again later",retryAfter:Math.ceil((c.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:{"Content-Type":"application/json","Retry-After":Math.ceil((c.resetTime.getTime()-Date.now())/1000).toString()}})}),upload:()=>({maxAttempts:10,windowMs:3600000,keyGenerator:(i)=>{let c=i.user?.id;if(c)return`upload:user:${c}`;return`upload:ip:${i.headers.get("x-forwarded-for")?.split(",")[0]||"unknown"}`}}),search:()=>({maxAttempts:100,windowMs:600000,skipIf:(i)=>i.user?.plan==="premium"}),perUser:(i,c)=>({maxAttempts:i,windowMs:c*60*1000,keyGenerator:(P)=>{let M=P.user?.id;if(!M)throw Error("User authentication required for per-user rate limiting");return`user:${M}`},skipIf:(P)=>!P.user?.id}),perIP:(i,c)=>({maxAttempts:i,windowMs:c*60*1000,keyGenerator:(P)=>`ip:${P.headers.get("x-forwarded-for")?.split(",")[0]||P.headers.get("x-real-ip")||P.headers.get("cf-connecting-ip")||"unknown"}`}),global:(i,c)=>({maxAttempts:i,windowMs:c*60*1000,keyGenerator:()=>"global"})},pa={fromString:(i,c)=>{let P=Lt(i);return jt(P,c)},getInfo:async(i,c)=>{let P=new yr(c),{info:M}=await P.checkLimit(i);return M},reset:(i,c)=>{let P=Dn.get(i);if(P)return P.cache.delete(c);return!1}};class pt{static parseDomainPattern(i){let c=[],P=i.match(/\{([^}]+)\}/g)||[];for(let z of P){let de=z.slice(1,-1);c.push(de)}let M=i.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");M=`^${M}$`;let U=new RegExp(M,"i");return{pattern:i,parameters:c,regex:U}}static matchDomain(i,c){let P=i.match(c.regex);if(!P)return null;let M={};for(let U=0;U<c.parameters.length;U++){let z=c.parameters[U],de=P[U+1];M[z]=de}return M}static extractSubdomainInfo(i){let c=i.split(".");if(c.length<=2)return{domain:i,parameters:{},rootDomain:i};let P=c[0],M=c.slice(1).join(".");return{domain:i,parameters:{subdomain:P},subdomain:P,rootDomain:M}}}class Qt{pattern;config;routes=[];constructor(i,c){this.pattern=i;this.config=c}addRoute(i,c,P,M=[],U){let z=[...this.config.middleware||[],...M],de=this.config.prefix?`${this.config.prefix}${c}`:c;this.routes.push({method:i.toUpperCase(),path:de,handler:P,middleware:z,name:U||(this.config.name?`${this.config.name}.${i.toLowerCase()}${c}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(i){return pt.matchDomain(i,this.pattern)}}class Ur{domainGroups=[];wildcardGroup;domain(i){let c=pt.parseDomainPattern(i);return new Nn(this,c)}addDomainGroup(i){if(i.pattern.pattern.includes("*")&&i.pattern.parameters.length===0)this.wildcardGroup=i;else this.domainGroups.push(i)}findDomainGroup(i){for(let c of this.domainGroups){let P=c.matchesDomain(i);if(P!==null)return{group:c,parameters:P}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:pt.extractSubdomainInfo(i).parameters};return null}getAllRoutes(){let i=[];for(let c of this.domainGroups){let P=c.getRoutes();for(let M of P)i.push({domainPattern:c.pattern.pattern,domainParameters:{},...M})}if(this.wildcardGroup){let c=this.wildcardGroup.getRoutes();for(let P of c)i.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...P})}return i}}class Nn{router;pattern;group;constructor(i,c){this.router=i;this.pattern=c;this.group=new Qt(c,{domain:c.pattern})}middleware(i){return this.group.config.middleware=i,this}prefix(i){return this.group.config.prefix=i,this}name(i){return this.group.config.name=i,this}routes(i){let c=new Fn(this.group);i(c),this.router.addDomainGroup(this.group)}get(i,c,P){this.group.addRoute("GET",i,c,P),this.router.addDomainGroup(this.group)}post(i,c,P){this.group.addRoute("POST",i,c,P),this.router.addDomainGroup(this.group)}put(i,c,P){this.group.addRoute("PUT",i,c,P),this.router.addDomainGroup(this.group)}delete(i,c,P){this.group.addRoute("DELETE",i,c,P),this.router.addDomainGroup(this.group)}patch(i,c,P){this.group.addRoute("PATCH",i,c,P),this.router.addDomainGroup(this.group)}}class Fn{group;constructor(i){this.group=i}get(i,c,P,M){this.group.addRoute("GET",i,c,P,M)}post(i,c,P,M){this.group.addRoute("POST",i,c,P,M)}put(i,c,P,M){this.group.addRoute("PUT",i,c,P,M)}delete(i,c,P,M){this.group.addRoute("DELETE",i,c,P,M)}patch(i,c,P,M){this.group.addRoute("PATCH",i,c,P,M)}options(i,c,P,M){this.group.addRoute("OPTIONS",i,c,P,M)}head(i,c,P,M){this.group.addRoute("HEAD",i,c,P,M)}any(i,c,P,M){let U=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let z of U)this.group.addRoute(z,i,c,P,M)}}function ga(i){return async(c,P)=>{let U=new URL(c.url).hostname,z=i.findDomainGroup(U);if(z){let de=c;de.domainParams=z.parameters,Object.assign(c.params||{},z.parameters);let pe=pt.extractSubdomainInfo(U);de.subdomainInfo=pe}return await P()}}var ma={getSubdomain:(i)=>{let c=new URL(i.url);return pt.extractSubdomainInfo(c.hostname).subdomain||null},getDomainParams:(i)=>i.domainParams||{},matchesDomain:(i,c)=>{let P=new URL(i.url),M=pt.parseDomainPattern(c);return pt.matchDomain(P.hostname,M)!==null},getSubdomainInfo:(i)=>i.subdomainInfo||null},fa={single:(i,c)=>`${i}.${c}`,wildcard:(i,c="subdomain")=>`{${c}}.${i}`,multiLevel:(i,...c)=>`${c.map((M)=>`{${M}}`).join(".")}.${i}`,apiVersion:(i)=>`{version}.api.${i}`,tenant:(i)=>`{tenant}.app.${i}`,environment:(i)=>`{env}.${i}`};import qi from"process";var zt=new Map;function St(i,c){zt.set(i,c)}function Ir(i){return zt.get(i)}function Oi(){return new Map(zt)}function $i(){zt.clear()}function Bi(i,c={},P={}){let M=zt.get(i);if(!M){let Re=[...zt.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${i}' is not defined. Known routes: ${Re}`)}let U=new Set,z=M;for(let[Re,Te]of Object.entries(c)){let xe=`{${Re}}`,ve=`{${Re}?}`,Ce=encodeURIComponent(String(Te));if(z.includes(xe))z=z.replaceAll(xe,Ce),U.add(Re);else if(z.includes(ve))z=z.replaceAll(ve,Ce),U.add(Re)}if(z.includes("?}")){if(z=z.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),z.length>1&&z.endsWith("/"))z=z.slice(0,-1)}let de=z.match(/\{([^}?]+)\}/g);if(de&&de.length>0)throw Error(`Missing required params for route '${i}': ${de.join(", ")}`);let pe=Object.entries(c).filter(([Re])=>!U.has(Re));if(pe.length>0){let Re=new URLSearchParams;for(let[Te,xe]of pe)Re.set(Te,String(xe));z+=`?${Re.toString()}`}if(P.absolute){let Re=(P.base??qi.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${Re.startsWith("http")?Re:`https://${Re}`}${z.startsWith("/")?z:`/${z}`}`}return z}import{join as Un}from"path";function Zt(i){let c=i.replace(/\/+/g,"/");if(!c.startsWith("/"))c=`/${c}`;if(c.length>1&&c.endsWith("/"))c=c.slice(0,-1);return c}function xa(i){return i.replace(/\//g,"_").toLowerCase()}function Di(i){if(typeof i!=="function"&&typeof i!=="object")return!1;if(typeof i==="function"&&i.prototype){if(typeof i.prototype.handle==="function")return!0}if(typeof i==="object"&&i!==null&&"handle"in i&&typeof i.handle==="function")return!0;return!1}function va(i){return typeof i==="function"&&!Di(i)}function wr(i){let c=i.match(/\{([^}]+)\}/g);return c?c.map((P)=>P.slice(1,-1).replace("?","")):[]}function Ca(i){let c=i.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${c}$`)}var Ni=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,Fi=/\{[^}]+\?\}/,In=new Map,_n=new Map;function Ui(i){let c=In.get(i);if(c)return c;let P=i.endsWith("/*"),M=Zt(i),U=0,z=M.split("/").filter(Boolean).map((pe)=>{let Re=Fi.test(pe);if(Re)U++;let Te=pe.match(Ni);return{isParam:!!Te,paramName:Te?Te[1].replace("?",""):"",isOptional:Re,literal:pe}}),de={isWildcard:P,wildcardBase:P?i.slice(0,-2):"",segments:z,optionalCount:U};return In.set(i,de),de}function Ii(i){let c=_n.get(i);if(c!==void 0)return c;let P;try{P=new RegExp(`^${i}$`)}catch{P=null}return _n.set(i,P),P}function ht(i,c,P,M){let U=Ui(i);if(U.isWildcard&&c.startsWith(U.wildcardBase))return!0;let z=U.segments,de=Zt(c).split("/").filter(Boolean);if(de.length<z.length-U.optionalCount||de.length>z.length)return!1;for(let pe=0;pe<z.length;pe++){let Re=z[pe],Te=de[pe];if(Te===void 0){if(Re.isOptional)continue;return!1}if(Re.isParam){let xe=Ft(Te);if(P[Re.paramName]=xe,M&&M[Re.paramName]){let ve=Ii(M[Re.paramName]);if(ve){if(!ve.test(xe))return!1}else console.warn(`Invalid constraint regex for parameter ${Re.paramName}: ${M[Re.paramName]}`)}}else if(Re.literal!==Te)return!1}return!0}function Mt(...i){return Zt(i.join("/"))}function Pa(i){if(!i.startsWith("/"))return!1;let c=[];for(let P of i)if(P==="{")c.push(P);else if(P==="}"){if(c.length===0||c.pop()!=="{")return!1}return c.length===0}async function jn(i){try{return await Bun.file(i).exists()}catch{return!1}}async function _r(i,c,P){if(P.some((M)=>i.endsWith(M))){let M=Zt(Un(c,i));if(await jn(M))return M;return null}for(let M of P){let U=Zt(Un(c,`${i}${M}`));if(await jn(U))return U}return null}function Ln(i,c){let P=i.replace(/\{\{([^}]+)\}\}/g,(M,U)=>{let z=U.trim(),de=jr(c,z);return de!==void 0?String(de):M});return P=_i(P,c),P=ji(P,c),P}function _i(i,c){return i.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(P,M,U,z="")=>{let de=M.trim();return jr(c,de)?U:z})}function ji(i,c){return i.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(P,M,U)=>{let z=jr(c,M.trim());if(!Array.isArray(z))return"";return z.map((de)=>U.replace(/\{\{@index\}\}/g,String(z.indexOf(de))).replace(/\{\{this\}\}/g,String(de)).replace(/\{\{this\.([^}]+)\}\}/g,(pe,Re)=>{let Te=de[Re.trim()];return Te!==void 0?String(Te):""})).join("")})}function jr(i,c){return c.split(".").reduce((P,M)=>{if(P&&typeof P==="object"&&M in P)return P[M];return},i)}class Se{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(i,c,P){this.method=i;this.path=c;this.handler=P}addMiddleware(i){if(Array.isArray(i))this.middleware.push(...i);else this.middleware.push(i);return this}cached(i=[],c){return this.cacheConfig={...$n.api(i),...c},this}throttle(i,c){if(typeof i==="string"){let P=Lt(i);this.throttleConfig={maxAttempts:P.maxAttempts??60,windowMs:P.windowMs,keyGenerator:(M)=>M.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=i;return this}name(i){return this.routeName=i,this}model(i,c){return this.modelBindings[i]=c,this}build(){let i=[];if(Object.keys(this.modelBindings).length>0){let c=Object.keys(this.modelBindings).map((M)=>({name:M})),P=kn(c,this.modelBindings);i.push(P)}if(this.throttleConfig){let c=jt(this.throttleConfig);i.push(c)}if(this.cacheConfig){let c=On(this.cacheConfig);i.push(c)}return i.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:i,name:this.routeName}}}class zn{router;condition;constructor(i,c){this.router=i;this.condition=c}middleware(i){let[c,P]=i.split(":"),M=this.router.resolveNamedMiddleware(c);if(!M)throw Error(`Unknown middleware: ${c}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[M(P)]}),this}}class Gn{router;middleware;constructor(i,c){this.router=i;this.middleware=c}get(i,c){return new Se("GET",i,c).addMiddleware(this.middleware)}post(i,c){return new Se("POST",i,c).addMiddleware(this.middleware)}put(i,c){return new Se("PUT",i,c).addMiddleware(this.middleware)}delete(i,c){return new Se("DELETE",i,c).addMiddleware(this.middleware)}patch(i,c){return new Se("PATCH",i,c).addMiddleware(this.middleware)}}class Wn{router;groupMiddleware;constructor(i,c){this.router=i;this.groupMiddleware=c}get(i,c){return new Se("GET",i,c).addMiddleware(this.groupMiddleware)}post(i,c){return new Se("POST",i,c).addMiddleware(this.groupMiddleware)}put(i,c){return new Se("PUT",i,c).addMiddleware(this.groupMiddleware)}delete(i,c){return new Se("DELETE",i,c).addMiddleware(this.groupMiddleware)}patch(i,c){return new Se("PATCH",i,c).addMiddleware(this.groupMiddleware)}}class Yt{routes=[];globalMiddleware=[];subdomainRouter=new Ur;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(i)=>{let c=i?Lt(i):{maxAttempts:60,windowMs:60000},P=jt({maxAttempts:c.maxAttempts,windowMs:c.windowMs,keyGenerator:(U)=>U.headers.get("x-forwarded-for")||"anonymous"});return async(U,z)=>await P(U,async()=>await z()??new Response(null))}),this.namedMiddleware.set("auth",()=>async(i,c)=>{if(!i.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return i.user={id:"123",roles:["user"]},await c()}),this.namedMiddleware.set("cors",()=>async(i,c)=>{let P=await c();if(P){let M=new Headers(P.headers);return M.set("Access-Control-Allow-Origin","*"),M.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),M.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(P.body,{status:P.status,statusText:P.statusText,headers:M})}return P})}middlewareGroup(i,c){let P=[];for(let M of c){let[U,z]=M.split(":"),de=this.namedMiddleware.get(U);if(de)P.push(de(z))}return this.middlewareGroups.set(i,P),this}middlewareGroupRoutes(i){let c=this.middlewareGroups.get(i)||[];return new Wn(this,c)}when(i){return new zn(this,i)}resolveNamedMiddleware(i){return this.namedMiddleware.get(i)}addConditionalMiddleware(i){this.conditionalMiddleware.push(i)}middleware(i){let[c,P]=i.split(":"),M=this.namedMiddleware.get(c);if(!M)throw Error(`Unknown middleware: ${c}`);let U=M(P);return new Gn(this,[U])}use(i){return this.globalMiddleware.push(i),this}get(i,c){return new Se("GET",i,c)}post(i,c){return new Se("POST",i,c)}put(i,c){return new Se("PUT",i,c)}delete(i,c){return new Se("DELETE",i,c)}patch(i,c){return new Se("PATCH",i,c)}register(i){let c=i.build();if(this.routes.push(c),c.name)St(c.name,c.path);return this}cached(i=[],c){return{get:(P,M)=>this.get(P,M).cached(i,c),post:(P,M)=>this.post(P,M).cached(i,c),put:(P,M)=>this.put(P,M).cached(i,c),delete:(P,M)=>this.delete(P,M).cached(i,c),patch:(P,M)=>this.patch(P,M).cached(i,c)}}throttled(i){return{get:(c,P)=>this.get(c,P).throttle(i),post:(c,P)=>this.post(c,P).throttle(i),put:(c,P)=>this.put(c,P).throttle(i),delete:(c,P)=>this.delete(c,P).throttle(i),patch:(c,P)=>this.patch(c,P).throttle(i)}}group(i,c){let P=new Yt;c(P);for(let M of P.routes){let U={...M,path:i.prefix?`${i.prefix}${M.path}`:M.path,middleware:[...i.middleware||[],...M.middleware],name:i.name&&M.name?`${i.name}.${M.name}`:M.name};if(i.domain){let z=pt.parseDomainPattern(i.domain),de=new Qt(z,{domain:i.domain});de.addRoute(U.method,U.path,U.handler,U.middleware,U.name),this.subdomainRouter.addDomainGroup(de)}else if(this.routes.push(U),U.name)St(U.name,U.path)}return this}domain(i){return{routes:(c)=>{let P=new Yt;c(P);let M=pt.parseDomainPattern(i),U=new Qt(M,{domain:i});for(let z of P.routes)U.addRoute(z.method,z.path,z.handler,z.middleware,z.name);return this.subdomainRouter.addDomainGroup(U),this}}}resource(i,c,P={}){let M=["index","create","store","show","edit","update","destroy"],U=P.only||M.filter((de)=>!P.except?.includes(de)),z=[{action:"index",method:"GET",path:`/${i}`,handler:c.index},{action:"create",method:"GET",path:`/${i}/create`,handler:c.create},{action:"store",method:"POST",path:`/${i}`,handler:c.store},{action:"show",method:"GET",path:`/${i}/{${i.slice(0,-1)}}`,handler:c.show},{action:"edit",method:"GET",path:`/${i}/{${i.slice(0,-1)}}/edit`,handler:c.edit},{action:"update",method:"PUT",path:`/${i}/{${i.slice(0,-1)}}`,handler:c.update},{action:"destroy",method:"DELETE",path:`/${i}/{${i.slice(0,-1)}}`,handler:c.destroy}];for(let de of z)if(U.includes(de.action)&&de.handler){let pe=new Se(de.method,de.path,de.handler).name(`${i}.${de.action}`);if(P.model&&["show","edit","update","destroy"].includes(de.action))pe.model(i.slice(0,-1),P.model);this.register(pe)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(i){let c=new URL(i.url),P=c.hostname,M=this.subdomainRouter.findDomainGroup(P);if(M){let U=i;U.domainParams=M.parameters;for(let z of M.group.getRoutes()){let de=this.matchRouteParams(z,i.method,c.pathname);if(de)return await this.executeRoute(z,U,de)}}for(let U of this.routes){let z=this.matchRouteParams(U,i.method,c.pathname);if(z)return await this.executeRoute(U,i,z)}return null}matchRouteParams(i,c,P){if(i.method!==c)return null;let M={};return ht(i.path,P,M)?M:null}async executeRoute(i,c,P){c.params=P;let M=[...this.globalMiddleware];for(let de of this.conditionalMiddleware)if(await de.condition(c))M.push(...de.middleware);M.push(...i.middleware);let U=0,z=async()=>{if(U<M.length){let de=M[U++];return await de(c,z)??new Response(null)}return await i.handler(c)};return await z()}}var Li={api:(i,c,P={})=>{let M=P.method||"GET",U=new Se(M,i,c);if(P.cache)U.cached(P.cache);if(P.throttle)U.throttle(P.throttle);return U},protected:(i,c,P={})=>{let M=P.method||"GET",U=new Se(M,i,c);return U.addMiddleware(async(z,de)=>{if(!z.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await de()}),U},upload:(i,c,P={})=>{let M=new Se("POST",i,c);return M.addMiddleware(async(U,z)=>await z()),M}},zi={route:(i,c={},P={})=>{let M=Ir(i)??`/${i}`;for(let[z,de]of Object.entries(c)){let pe=encodeURIComponent(de);M=M.replace(`{${z}}`,pe),M=M.replace(`{${z}?}`,pe)}if(M.includes("?}")){if(M=M.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),M.length>1&&M.endsWith("/"))M=M.slice(0,-1)}let U=new URLSearchParams(P).toString();if(U)M+=`?${U}`;return M},redirect:(i,c=302)=>new Response(null,{status:c,headers:{Location:i}}),json:(i,c=200)=>new Response(JSON.stringify(i),{status:c,headers:{"Content-Type":"application/json"}})},Gi=new Yt;function Vn(i){Object.defineProperties(i.prototype,{group:{value(c,P){let M=this.currentGroup,U={...M};if(c.prefix&&M?.prefix)U.prefix=Mt(M.prefix,c.prefix);else if(c.prefix)U.prefix=c.prefix;if(c.middleware)U.middleware=[...M?.middleware||[],...c.middleware];this.currentGroup=U;let z=P();if(z instanceof Promise)return z.then(()=>(this.currentGroup=M,this),(de)=>{throw this.currentGroup=M,de});return this.currentGroup=M,this},writable:!0,configurable:!0},name:{value(c,P){let M=this.currentGroup||{},U={...M};this.currentGroup=U;let z=this.routes.length;P();for(let de=z;de<this.routes.length;de++){let pe=this.routes[de];if(pe.name)pe.name=`${c}.${pe.name}`}return this.currentGroup=M,this},writable:!0,configurable:!0},controller:{value(c,P){let M=this.currentGroup||{},U={...M,controller:c};return this.currentGroup=U,P(),this.currentGroup=M,this},writable:!0,configurable:!0},domain:{value(c,P){let M=this.currentDomain;return this.currentDomain=c,P(),this.currentDomain=M,this},writable:!0,configurable:!0},prefix:{value(c,P){return this.group({prefix:c},P)},writable:!0,configurable:!0},resource:{value(c,P,M="api"){let U=c.endsWith("s")?c:`${c}s`,z=c.endsWith("s")?c.slice(0,-1):c,de=[{name:"index",method:"GET",path:`/${U}`,action:"index"},{name:"create",method:"GET",path:`/${U}/create`,action:"create"},{name:"store",method:"POST",path:`/${U}`,action:"store"},{name:"show",method:"GET",path:`/${U}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${U}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${U}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${U}/{id}`,action:"destroy"}];return this.name(z,()=>{for(let pe of de){let Re;if(typeof P==="string")Re=`${P}${pe.action.charAt(0).toUpperCase()+pe.action.slice(1)}Action`;else if(P[pe.action])Re=P[pe.action];else continue;switch(pe.method){case"GET":this.get(pe.path,Re,M,pe.name);break;case"POST":this.post(pe.path,Re,M,pe.name);break;case"PUT":this.put(pe.path,Re,M,pe.name);break;case"DELETE":this.delete(pe.path,Re,M,pe.name);break}}}),this},writable:!0,configurable:!0}})}function Jn(i){Object.defineProperties(i.prototype,{addRoute:{value(c,P,M,U,z,de){let pe=P,Re=[],Te=U||"web";if(this.currentGroup){if(this.currentGroup.prefix)pe=Mt(this.currentGroup.prefix,P);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)Re=[...this.currentGroup.middleware]}if(de&&de.length>0)for(let Pe of de){let Ee=this.resolveMiddleware(Pe);if(Ee)Re.push(Ee)}if(Te==="api"&&this.config.apiPrefix)pe=Mt(this.config.apiPrefix,pe);else if(Te==="web"&&this.config.webPrefix)pe=Mt(this.config.webPrefix,pe);let xe;if(this.currentDomain)xe=this.currentDomain;let ve={method:c.toUpperCase(),path:pe,handler:M,domain:xe,params:{},middleware:Re},Ce=wr(pe),Me={};if(Ce.forEach((Pe)=>{let Ee=Pe.replace("?","");if(this.patterns.has(Ee))Me[Ee]=this.patterns.get(Ee)}),Object.keys(Me).length>0)ve.constraints=Me;if(ve.pattern={exec:(Pe)=>{let Ee={},Ae=ve.constraints&&!Array.isArray(ve.constraints)?ve.constraints:void 0;if(!ht(pe,Pe.pathname,Ee,Ae))return null;return{pathname:{groups:Ee}}}},M instanceof Response)this.staticResponses.set(pe,M);if(xe){if(!this.domains[xe])this.domains[xe]=[];this.domains[xe].push(ve)}else this.routes.push(ve);if(!pe.includes("{")&&!pe.includes("*")){if(!this.staticRoutes.has(c.toUpperCase()))this.staticRoutes.set(c.toUpperCase(),new Map);let Pe=this.staticRoutes.get(c.toUpperCase());if(!Pe.has(pe))Pe.set(pe,ve)}if(z)ve.name=z,this.namedRoutes.set(z,ve),St(z,ve.path);if(this.addRouteToCompiler&&!xe)this.addRouteToCompiler(ve);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(c,P,M,U,z){return this.addRoute("GET",c,P,M,U,z)},writable:!0,configurable:!0},post:{value(c,P,M,U,z){return this.addRoute("POST",c,P,M,U,z)},writable:!0,configurable:!0},put:{value(c,P,M,U,z){return this.addRoute("PUT",c,P,M,U,z)},writable:!0,configurable:!0},patch:{value(c,P,M,U,z){return this.addRoute("PATCH",c,P,M,U,z)},writable:!0,configurable:!0},delete:{value(c,P,M,U,z){return this.addRoute("DELETE",c,P,M,U,z)},writable:!0,configurable:!0},options:{value(c,P,M,U,z){return this.addRoute("OPTIONS",c,P,M,U,z)},writable:!0,configurable:!0},head:{value(c,P,M,U,z){return this.addRoute("HEAD",c,P,M,U,z)},writable:!0,configurable:!0},match:{value(c,P,M,U,z,de){for(let pe of c)this.addRoute(pe,P,M,U,z,de);return this},writable:!0,configurable:!0},any:{value(c,P,M,U,z){let de=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(de,c,P,M,U,z)},writable:!0,configurable:!0},fallback:{value(c){return this.fallbackHandler=c,this},writable:!0,configurable:!0},route:{value(c,P={}){let M=this.namedRoutes.get(c);if(!M)throw Error(`Route with name "${c}" not found`);let U=M.path;for(let[z,de]of Object.entries(P))U=U.replace(`{${z}}`,encodeURIComponent(de)),U=U.replace(`{${z}?}`,encodeURIComponent(de));if(U.includes("{")){if(U=U.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),U.length>1&&U.endsWith("/"))U=U.slice(0,-1)}return U},writable:!0,configurable:!0},onError:{value(c){return this.errorHandler=c,this},writable:!0,configurable:!0}})}function Kn(i){Object.defineProperties(i.prototype,{redirect:{value(c,P=302){let M=new Headers;return M.set("Location",c),new Response(null,{status:P,headers:M})},writable:!0,configurable:!0},permanentRedirect:{value(c){return this.redirect(c,301)},writable:!0,configurable:!0},redirectRoute:{value(c,P,M=302){return this.get(c,(U)=>this.redirect(P,M)),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(c,P){return this.redirectRoute(c,P,301)},writable:!0,configurable:!0}})}function lt(i){if(i instanceof Response)return i;if(i===null||i===void 0)return new Response(null,{status:204});if(typeof i==="string")return new Response(i,{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(typeof i==="number"||typeof i==="boolean")return new Response(String(i),{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(i instanceof ArrayBuffer||i instanceof Uint8Array)return new Response(i,{headers:{"Content-Type":"application/octet-stream"}});if(i instanceof ReadableStream)return new Response(i);if(typeof i==="object")return new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json; charset=utf-8"}});return new Response(String(i),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function Wi(i,c){let P=c.actionsPath||"actions",M=c.controllersPath||"controllers",U=i.replace(/\.(ts|js)$/,""),z=[];if(U.includes("@")){let[pe,Re]=U.split("@");z.push(`${M}/${pe}`,`${M}/${pe}.ts`,`${M}/${pe}.js`,`./${M}/${pe}`,`../${M}/${pe}`)}else if(U.startsWith("Actions/")||U.startsWith("actions/"))z.push(U,`./${U}`,`../${U}`);else if(U.startsWith("./")||U.startsWith("../"))z.push(U);else z.push(`${P}/${U}`,`./${P}/${U}`,`../${P}/${U}`,U,`./${U}`,`../${U}`);let de=null;for(let pe of z)try{return await import(pe)}catch(Re){de=Re}throw Error(`Failed to import handler "${i}".
94
- Tried paths: ${z.join(", ")}
95
- Last error: ${de?.message||"Unknown error"}`)}function Xn(i){return typeof i==="function"&&!i.prototype?.handle}async function er(i,c,P){if(i instanceof Response)return i.clone();if(Xn(i)){let M=await i(c);return lt(M)}if(typeof i==="string")return Vi(i,c,P);if(typeof i==="function"&&i.prototype&&typeof i.prototype.handle==="function"){let z=await new i().handle(c);return lt(z)}if(i&&typeof i==="object"&&"handle"in i){let M=i;if(typeof M.handle==="function"){let U=await M.handle(c);return lt(U)}}throw Error(`Invalid handler type: ${typeof i}`)}async function Vi(i,c,P){let M=P.controllersPath||"controllers";if(i.includes("@")){let[de,pe]=i.split("@"),Re=[`${M}/${de}`,`./${M}/${de}`,`../${M}/${de}`,de,`./${de}`,`../${de}`],Te=null,xe=null;for(let Ce of Re)try{Te=await import(Ce);break}catch(Me){xe=Me}if(!Te)throw Error(`Failed to import controller "${de}".
96
- Tried paths: ${Re.join(", ")}
97
- Last error: ${xe?.message||"Unknown error"}`);let ve=Te.default||Te;if(typeof ve==="function"){let Ce=new ve,Me=Ce[pe];if(typeof Me!=="function")throw TypeError(`Method "${pe}" not found on controller "${de}"`);let Pe=await Me.call(Ce,c);return lt(Pe)}throw Error(`Controller "${de}" is not a valid class`)}let U=await Wi(i,P),z=U.default||U;if(typeof z==="function"){if(z.prototype&&typeof z.prototype.handle==="function"){let Re=await new z().handle(c);return lt(Re)}let de=await z(c);return lt(de)}if(z&&typeof z==="object"&&"handle"in z){let de=z;if(typeof de.handle==="function"){let pe=await de.handle(c);return lt(pe)}}throw Error(`Handler "${i}" does not export a valid handler function or class`)}function Ji(i){return(c,P)=>er(c,P,i)}function Qn(i,c){if(i instanceof Response)return async()=>i.clone();if(Xn(i))return async(P)=>lt(await i(P));if(typeof i==="function"&&i.prototype&&typeof i.prototype.handle==="function"){let P=i;return async(M)=>lt(await new P().handle(M))}return(P)=>er(i,P,c)}function Zn(i){Object.defineProperties(i.prototype,{use:{value(...c){for(let P of c){let M=this.resolveMiddleware(P);if(M)this.globalMiddleware.push(M)}return this._mwEpoch=(this._mwEpoch||0)+1,this},writable:!0,configurable:!0},resolveMiddleware:{value(c){if(typeof c==="function")return c;if(typeof c==="object"&&c!==null&&"handle"in c&&typeof c.handle==="function")return(P,M)=>c.handle(P,M);if(typeof c==="string"){let[P,M]=c.split(":"),U=this.namedMiddleware?.get(P);if(U)return U(M);let z=null,de=c;return async(pe,Re)=>{if(!z)try{let Te=await import(`../middleware/${de}.ts`);if(Te.default&&typeof Te.default==="function")z=Te.default;else if(Te.default&&typeof Te.default.handle==="function")z=(xe,ve)=>Te.default.handle(xe,ve)}catch(Te){console.error(`Failed to load middleware "${de}":`,Te)}if(z)return z(pe,Re);return Re()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value(c){if(c.length===0)return async(M)=>null;let P=async(M)=>null;for(let M=c.length-1;M>=0;M--){let U=c[M],z=P;P=async(de)=>U(de,async()=>await z(de)||new Response(null,{status:200}))}return P},writable:!0,configurable:!0},runMiddleware:{async value(c,P){if(P.length===0)return null;try{return await this.buildMiddlewareChain(P)(c)}catch(M){if(this.errorHandler)return this.errorHandler(M);throw M}},writable:!0,configurable:!0},middleware:{value(...c){for(let P of c)if(typeof P==="string"){let[M]=P.split(":");if(!this.namedMiddleware.has(M))throw Error(`Unknown middleware: ${M}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...c)}else{let P=this.routes[this.routes.length-1];if(P)this.applyMiddlewareToRoute(P,c)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(c,P){for(let M of P){let U=this.resolveMiddleware(M);if(U)c.middleware.push(U)}},writable:!0,configurable:!0},resolveHandler:{async value(c,P){return er(c,P,this.config)},writable:!0,configurable:!0},wrapResponse:{value:lt,writable:!0,configurable:!0},onError:{value(c){return this.errorHandler=c,this},writable:!0,configurable:!0}})}class Yn{models=new Map;cache=new Map;register(i,c){this.models.set(i,c)}get(i){return this.models.get(i)}has(i){return this.models.has(i)}async resolve(i,c,P){let M=this.models.get(i);if(!M)return{model:null,error:`Model binding '${i}' not found`,status:500};try{if(M.cache?.enabled){let de=this.getCachedModel(i,c,M);if(de)return{model:de}}let U=await M.resolver(c,P);if(U===null||U===void 0)return{model:null,error:`${i} not found`,status:404};if(M.validator){let de=await M.validator(U,c,P);if(!de.valid)return{model:null,error:de.error||"Model validation failed",status:de.status||422}}let z=U;if(M.transformer)z=await M.transformer(U,c,P);if(M.cache?.enabled)this.cacheModel(i,c,z,M);return{model:z}}catch(U){return{model:null,error:U instanceof Error?U.message:"Model resolution failed",status:500}}}createErrorResponse(i,c,P){let M=this.models.get(i),U=c.status||404,z=c.error||"Model not found";if(M?.errorHandling){if(U===404&&M.errorHandling.notFound)return M.errorHandling.notFound(P);if(U===422&&M.errorHandling.validation)return M.errorHandling.validation(null,z);if(M.errorHandling.transform)return M.errorHandling.transform(z)}return new Response(JSON.stringify({error:z,status:U,message:`Failed to resolve ${i}`}),{status:U,headers:{"Content-Type":"application/json"}})}clearCache(i,c){if(c){let P=this.models.get(i);if(P?.cache){let M=this.generateCacheKey(i,c,P);this.cache.delete(M)}}else{let P=[];for(let M of this.cache.keys())if(M.startsWith(`${i}:`))P.push(M);for(let M of P)this.cache.delete(M)}}clearAllCache(){this.cache.clear()}getCacheStats(){let i=Date.now(),c=0,P=0;for(let M of this.cache.values())if(i-M.timestamp>M.ttl)P++;else c++;return{totalEntries:this.cache.size,validEntries:c,expiredEntries:P,models:this.models.size}}cleanupCache(){let i=Date.now(),c=[];for(let[P,M]of this.cache.entries())if(i-M.timestamp>M.ttl)c.push(P);for(let P of c)this.cache.delete(P);return c.length}getCachedModel(i,c,P){if(!P.cache?.enabled)return null;let M=this.generateCacheKey(i,c,P),U=this.cache.get(M);if(!U)return null;if(Date.now()-U.timestamp>U.ttl)return this.cache.delete(M),null;return U.model}cacheModel(i,c,P,M){if(!M.cache?.enabled)return;let U=this.generateCacheKey(i,c,M);this.cache.set(U,{model:P,timestamp:Date.now(),ttl:M.cache.ttl})}generateCacheKey(i,c,P){if(P.cache?.key)return`${i}:${P.cache.key(c)}`;let M=Object.entries(c).sort(([U],[z])=>U.localeCompare(z)).map(([U,z])=>`${U}=${z}`).join("&");return`${i}:${M}`}}var es=new Yn;function ts(i){Object.defineProperties(i.prototype,{modelRegistry:{value:es,writable:!0,configurable:!0},model:{value(c,P,M){if(typeof P==="string")this.modelRegistry.register(c,{resolver:async(U)=>(console.warn(`Model class ${P} not implemented`),{id:U[c],modelClass:P}),errorHandling:M?{notFound:(U)=>M(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(c,{resolver:async(U)=>{let z=U[c];if(!z)return null;return P(z)},errorHandling:M?{notFound:(U)=>M(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(c,P)=>{if(!c.params)return await P()||new Response("Not Found",{status:404});for(let[U,z]of Object.entries(c.params))if(this.modelRegistry.has(U))try{let de=await this.modelRegistry.resolve(U,c.params,c);if(de.model===null){if(de.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:de.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(de.status===404)return this.modelRegistry.createErrorResponse(U,de,c.params)}else c[U]=de.model}catch(de){return new Response(JSON.stringify({error:"Internal Server Error",message:de instanceof Error?de.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await P()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(c){return async(P,M)=>{try{return await M()||c(P)}catch(U){return console.error(U),c(P)}}},writable:!0,configurable:!0},scopedBindings:{value(c){return async(P,M)=>{if(!P.params)return await M()||new Response("Not Found",{status:404});for(let[z,de]of Object.entries(c))if(P.params[z]&&P.params[de]);return await M()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},clearModelCache:{value(c){if(c)this.modelRegistry.clearCache(c);else this.modelRegistry.clearAllCache();return this},writable:!0,configurable:!0},getModelStats:{value(){return this.modelRegistry.getCacheStats()},writable:!0,configurable:!0}})}class kt{children=new Map;paramChild=null;wildcardChild=null;routes=new Map;paramName=null;pattern=null;isEndpoint=!1;addRoute(i,c){this.routes.set(i,c),this.isEndpoint=!0}getRoute(i){return this.routes.get(i)}getAllRoutes(){return Array.from(this.routes.values())}}class Lr{root=new kt;compiledRoutes=new Map;methodTries=new Map;constructor(){let i=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","TRACE","CONNECT"];for(let c of i)this.methodTries.set(c,new kt)}compileRoute(i){let c=`${i.method}:${i.path}`;if(i.constraints&&!Array.isArray(i.constraints)){let Re=i.constraints,xe=Object.keys(Re).sort().map((ve)=>`${ve}:${Re[ve]}`).join("|");c=`${i.method}:${i.path}#${xe}`}if(this.compiledRoutes.has(c))return this.compiledRoutes.get(c);let P=this.parsePathSegments(i.path),M=P.filter((Re)=>Re.type==="parameter").map((Re)=>Re.paramName);if(i.constraints&&!Array.isArray(i.constraints)){let Re=i.constraints;for(let Te of P)if(Te.type==="parameter"&&Te.paramName&&Re[Te.paramName])Te.pattern=new RegExp(`^${Re[Te.paramName]}$`)}let U=this.calculateRoutePriority(P),z=P.filter((Re)=>Re.type==="static").length,de=P.filter((Re)=>Re.type!=="static").length,pe={route:i,segments:P,paramNames:M,priority:U,staticScore:z,dynamicScore:de};return this.compiledRoutes.set(c,pe),pe}parsePathSegments(i){let c=[],P=i.split("/").filter((M)=>M.length>0);for(let M of P)if(M==="*")c.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(M))c.push({type:"wildcard",value:M,paramName:M.slice(1,M.indexOf("}"))});else if(M.startsWith("{")&&M.endsWith("}")){let U=M.slice(1,-1),[z,de]=U.split(":");c.push({type:"parameter",value:M,paramName:z.replace("?",""),pattern:de?new RegExp(`^${de}$`):void 0,optional:U.endsWith("?")})}else if(M.includes("{")){let U=M.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(de,pe,Re)=>Re?`(${Re})`:"([^/]+)"),z=Array.from(M.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((de)=>de[1].replace("?",""));c.push({type:"parameter",value:M,paramName:z[0],pattern:new RegExp(`^${U}$`)})}else c.push({type:"static",value:M});return c}calculateRoutePriority(i){let c=0;for(let P=0;P<i.length;P++){let M=i[P],U=i.length-P;switch(M.type){case"static":c+=U*1000;break;case"parameter":if(M.pattern)c+=U*100;else c+=U*10;break;case"wildcard":c+=U*1;break}}return c}addRoute(i){let c=this.compileRoute(i);this.insertRoute(this.root,c,0);let P=this.methodTries.get(i.method);if(P)this.insertRoute(P,c,0)}insertRoute(i,c,P){if(P>=c.segments.length){i.addRoute(c.route.method,c);return}let M=c.segments[P];switch(M.type){case"static":if(!i.children.has(M.value))i.children.set(M.value,new kt);this.insertRoute(i.children.get(M.value),c,P+1);break;case"parameter":if(!i.paramChild)i.paramChild=new kt,i.paramChild.paramName=M.paramName,i.paramChild.pattern=M.pattern||null;this.insertRoute(i.paramChild,c,P+1);break;case"wildcard":if(!i.wildcardChild)i.wildcardChild=new kt,i.wildcardChild.paramName=M.paramName??null;this.insertRoute(i.wildcardChild,c,P+1);break}}match(i,c){let P=i.split("/").filter((U)=>U.length>0),M=this.methodTries.get(c);if(M){let U=this.matchSegments(M,P,0,{},c);if(U)return U}return this.matchSegments(this.root,P,0,{},c)}matchSegments(i,c,P,M,U){if(P>=c.length){let Te=i.getRoute(U);if(Te)return{route:Te.route,params:M,score:Te.priority};return null}let z=c[P],de=i.children.get(z);if(de){let Te=this.matchSegments(de,c,P+1,M,U);if(Te)return Te}let pe=i.paramChild,Re=pe?.paramName?Ft(z):z;if(pe&&pe.paramName&&(!pe.pattern||pe.pattern.test(Re))){let Te=M[pe.paramName];M[pe.paramName]=Re;let xe=this.matchSegments(pe,c,P+1,M,U);if(xe)return xe;if(Te===void 0)delete M[pe.paramName];else M[pe.paramName]=Te}if(i.wildcardChild){let Te=i.wildcardChild.getRoute(U);if(Te)return M[i.wildcardChild.paramName??"wildcard"]=c.slice(P).map(Ft).join("/"),{route:Te.route,params:M,score:Te.priority}}return null}getAllRoutes(){return Array.from(this.compiledRoutes.values())}removeRoute(i){let c=`${i.method}:${i.path}`;if(i.constraints&&!Array.isArray(i.constraints)){let P=i.constraints,U=Object.keys(P).sort().map((z)=>`${z}:${P[z]}`).join("|");c=`${i.method}:${i.path}#${U}`}this.compiledRoutes.delete(c)}clear(){this.root=new kt,this.compiledRoutes.clear();for(let[i]of this.methodTries)this.methodTries.set(i,new kt)}getStats(){let i={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let c of this.compiledRoutes.values()){let P=c.route.method;i.methodDistribution[P]=(i.methodDistribution[P]||0)+1}return i}countNodes(i){let c=1;for(let P of i.children.values())c+=this.countNodes(P);if(i.paramChild)c+=this.countNodes(i.paramChild);if(i.wildcardChild)c+=this.countNodes(i.wildcardChild);return c}}class br{trie;matchCache=new Map;routeKeys=new Set;stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}};options;constructor(i={}){this.options={enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0,enableProfiling:!1,...i},this.trie=new Lr}addRoute(i){if(this.options.precompilePatterns)this.precompileRoutePattern(i);let c=`${i.method}:${i.path}`;if(this.routeKeys.has(c))return!1;if(this.routeKeys.add(c),this.trie.addRoute(i),this.options.enableCaching)this.matchCache.clear();let P=i.method;return this.stats.methodDistribution[P]=(this.stats.methodDistribution[P]||0)+1,!0}patternCache=new Map;extractParamNames(i){let c=[],P=/\{([^}:]+)(?::[^}]+)?\}/g,M;while(M=P.exec(i))c.push(M[1].replace("?",""));return c}precompileRoutePattern(i){if(!i.pattern&&i.path.includes("{")){let c=i.path;if(i.constraints&&!Array.isArray(i.constraints)){let U=i.constraints,de=Object.keys(U).sort().map((pe)=>`${pe}:${U[pe]}`).join("|");c=`${i.path}#${de}`}if(this.patternCache.has(c)){i.pattern=this.patternCache.get(c);return}let P=this.convertToURLPattern(i.path,i.constraints&&!Array.isArray(i.constraints)?i.constraints:void 0),M={exec:(U)=>{let z=U.pathname,de=P.exec(z);if(!de)return null;return{pathname:{groups:de.groups||{}}}}};this.patternCache.set(c,M),i.pattern=M}}convertToURLPattern(i,c){let P=i,M=null,U=P.match(/\{([^{}/]+)\}\*$/);if(U)M=U[1],P=P.slice(0,U.index);else if(P.endsWith("*"))M="wildcard",P=P.slice(0,-1);let z=[],pe=P.replace(/\{([^}]+)\}/g,(Te,xe)=>(z.push(xe),`\x00${z.length-1}\x00`)).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(pe=pe.replace(/\/?\u0000(\d+)\u0000/g,(Te,xe)=>{let ve=z[Number(xe)],Ce=ve.endsWith("?"),Me=Ce?ve.slice(0,-1):ve,Pe=Me.indexOf(":"),Ee=Pe===-1?Me:Me.slice(0,Pe),Ae=Pe===-1?void 0:Me.slice(Pe+1),Fe=c?.[Ee]??Ae??"[^/]+",Dt=`(?<${Ee}>${Fe})`,ir=Te.startsWith("/")?"/":"";return Ce?`(?:${ir}${Dt})?`:`${ir}${Dt}`}),M!==null)pe+=`(?<${M}>${c?.[M]??".+"})`;let Re=new RegExp(`^${pe}$`);return{exec:(Te)=>{let xe=Te.match(Re);if(!xe)return null;return{groups:xe.groups||{}}}}}match(i,c){let P=this.options.enableProfiling?performance.now():0;if(this.stats.totalMatches++,this.options.enableCaching){let z=`${c}:${i}`,de=this.matchCache.get(z);if(de!==void 0||this.matchCache.has(z)){if(this.stats.cacheHits++,P)this.updateMatchTime(P);return de?{route:de.route,params:{...de.params}}:null}this.stats.cacheMisses++}let M=this.trie.match(i,c),U=null;if(M)U={route:M.route,params:M.params};if(this.options.enableCaching){let z=`${c}:${i}`;this.addToCache(z,U)}if(P)this.updateMatchTime(P);return U?{route:U.route,params:{...U.params}}:null}addToCache(i,c){if(this.matchCache.size>=this.options.cacheSize&&!this.matchCache.has(i)){let P=this.matchCache.keys().next().value;if(P!==void 0)this.matchCache.delete(P)}this.matchCache.set(i,c)}updateMatchTime(i){let c=performance.now()-i;this.stats.averageMatchTime=(this.stats.averageMatchTime*(this.stats.totalMatches-1)+c)/this.stats.totalMatches}getCompiledRoutes(){let i=this.trie.getAllRoutes();if(this.options.enablePriorityOptimization)return i.sort((c,P)=>P.priority-c.priority);return i}getRoutesByMethod(){let i=new Map;for(let c of this.trie.getAllRoutes()){let P=c.route.method;if(!i.has(P))i.set(P,[]);i.get(P).push(c)}if(this.options.enablePriorityOptimization)for(let[c,P]of i)P.sort((M,U)=>U.priority-M.priority),i.set(c,P);return i}warmCache(i,c={}){if(!this.options.enableCaching&&!c.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let P=this.options.enableCaching;if(c.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(c.precompile)for(let{path:xe,method:ve}of i){let Ce=`${ve}:${xe}`;this.matchCache.delete(Ce)}let M=this.matchCache.size,U=this.stats.cacheHits,z=this.stats.totalMatches;for(let{path:xe,method:ve}of i)if(this.match(xe,ve),c.precompile)this.match(xe,ve);let de=this.matchCache.size-M,pe=this.stats.cacheHits-U,Re=this.stats.totalMatches-z,Te=Re>0?pe/Re:0;if(c.force&&!P)this.options.enableCaching=P;return{warmedPaths:de,cacheSize:this.matchCache.size,hitRate:Te}}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 i=this.trie.getStats();return{...this.stats,trieDepth:i.averageDepth,methodDistribution:i.methodDistribution}}getCacheStats(){let i=this.stats.totalMatches>0?this.stats.cacheHits/this.stats.totalMatches:0;return{size:this.matchCache.size,maxSize:this.options.cacheSize,hitRate:i,enabled:this.options.enableCaching}}optimizeRouteOrder(i){if(!this.options.enablePriorityOptimization)return;this.matchCache.clear()}getRouteConflicts(){let i=[],c=this.trie.getAllRoutes(),P=new Map;for(let M of c){let U=M.route.method;if(!P.has(U))P.set(U,[]);P.get(U).push(M)}for(let[M,U]of P)for(let z=0;z<U.length;z++)for(let de=z+1;de<U.length;de++){let pe=U[z],Re=U[de];if(this.routesConflict(pe,Re)){let Te=this.getConflictSeverity(pe,Re),xe=this.getConflictType(pe,Re);i.push({routes:[pe,Re],conflictType:xe,severity:Te})}}return i}routesConflict(i,c){if(i.route.path===c.route.path)return!0;if(i.route.method!==c.route.method)return!1;return this.patternsOverlap(i.segments,c.segments)}patternsOverlap(i,c){let P=i.some((de)=>de.optional||de.type==="wildcard"),M=c.some((de)=>de.optional||de.type==="wildcard");if(i.length!==c.length&&!P&&!M)return!1;let U=Math.max(i.length,c.length),z=!0;for(let de=0;de<U;de++){let pe=de<i.length?i[de]:null,Re=de<c.length?c[de]:null;if(!pe&&Re&&!Re.optional)return!1;if(!Re&&pe&&!pe.optional)return!1;if(!pe||!Re)continue;if(pe.type==="static"&&Re.type==="static"){if(pe.value!==Re.value)return!1}else if(pe.type==="parameter"&&Re.type==="parameter"){if(pe.pattern&&Re.pattern){if(pe.pattern.toString()===Re.pattern.toString())z=!0}if(pe.paramName===Re.paramName)z=!0}else if(pe.type==="static"&&Re.type==="parameter"||pe.type==="parameter"&&Re.type==="static"){let Te=pe.type==="static"?pe:Re,xe=pe.type==="parameter"?pe:Re;if(xe.pattern){if(!xe.pattern.test(Te.value))return!1}}else if(pe.type==="wildcard"||Re.type==="wildcard")return!0}return z}getConflictSeverity(i,c){if(i.route.path===c.route.path)return"high";if(i.staticScore===c.staticScore)return"medium";return"low"}getConflictType(i,c){if(i.route.path===c.route.path)return"duplicate";if(this.hasAmbiguousParameters(i,c))return"ambiguous";if(Math.abs(i.priority-c.priority)<10)return"ambiguous";return"overlap"}hasAmbiguousParameters(i,c){if(Math.abs(i.segments.length-c.segments.length)>1)return!1;let P=i.segments.filter((U)=>U.type==="parameter").length,M=c.segments.filter((U)=>U.type==="parameter").length;if(P>0&&M>0){let U=Math.min(i.segments.length,c.segments.length),z=0;for(let de=0;de<U;de++)if(i.segments[de].type==="parameter"&&c.segments[de].type==="parameter"){z++;let pe=!!i.segments[de].pattern,Re=!!c.segments[de].pattern;if(pe!==Re)return!0}return z>0&&z>=Math.min(P,M)/2}return!1}}function rs(i){Object.defineProperties(i.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new br({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0})},writable:!0,configurable:!0},addRouteToCompiler:{value(c){this.initializeRouteCompiler(),this.routeCompiler.addRoute(c)},writable:!0,configurable:!0},matchRoute:{value(c,P,M){if(this.initializeRouteCompiler(),M&&this.domains[M]){let U=this.fallbackMatchRoute(c,P,M);if(U)return U}else{let U=this.routeCompiler.match(c,P);if(U&&(!M||!U.route.domain||U.route.domain===M))return U;let z=this.fallbackMatchRoute(c,P,M);if(z)return z}if(P==="HEAD")return this.matchRoute(c,"GET",M);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(c,P,M){let U=new URL(c,"http://localhost"),z=`${M||""}:${P}:${U.pathname}`;if(this.routeCache.has(z))return this.routeCache.get(z);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has(P)){let Te=this.staticRoutes.get(P).get(U.pathname);if(Te&&(!M||!Te.domain||Te.domain===M)){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}}let pe=(M&&this.domains[M]?this.domains[M]:this.routes).filter((Te)=>Te.method===P);for(let Te of pe)if(Te.path===U.pathname){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}for(let Te of pe)if(Te.pattern){let xe=Te.pattern.exec(U);if(xe){let ve={route:Te,params:xe.pathname.groups};return this.routeCache.set(z,ve),ve}}let Re=M&&this.domains[M]?[this.domains[M],this.routes]:[this.routes];for(let Te of Re)for(let xe of Te){if(xe.method!==P||!xe.path.endsWith("*"))continue;let ve=xe.path.slice(0,-1);if(U.pathname.startsWith(ve)){let Ce={route:xe,params:{wildcard:U.pathname.slice(ve.length)}};return this.routeCache.set(z,Ce),Ce}}this.routeCache.set(z,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(c){this.initializeRouteCompiler(),this.routeCompiler.warmCache(c)},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 br({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0});for(let c of this.routes)this.routeCompiler.addRoute(c);for(let c of Object.values(this.domains))for(let P of c)this.routeCompiler.addRoute(P)},writable:!0,configurable:!0},optimizeRoutes:{value(c={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(c)},writable:!0,configurable:!0}})}function ns(i){Object.defineProperties(i.prototype,{buildBunServeRoutes:{value(){let c={},P=new Map;for(let M of this.routes){if(!P.has(M.path))P.set(M.path,[]);P.get(M.path).push(M)}for(let[M,U]of P.entries())if(U.length===1){let z=U[0];if(typeof z.handler==="function"&&z.handler.toString().includes("new Response")&&!z.handler.toString().includes("await")&&z.middleware.length===0)try{let de=this.enhanceRequest(new Request("https://example.com"),{}),pe=z.handler(de);if(pe instanceof Response){c[M]=pe;continue}}catch{}c[M]=async(de)=>{let pe=new URL(de.url),Re={},Te=z.constraints&&!Array.isArray(z.constraints)?z.constraints:void 0;ht(M,pe.pathname,Re,Te);let xe=this.enhanceRequest(de,Re),ve=async(Pe,Ee)=>await this.resolveHandler(z.handler,Pe),Ce=[...this.globalMiddleware,...z.middleware,ve],Me=await this.runMiddleware(xe,Ce);return this.applyModifiedCookies(Me??new Response("No response from middleware chain",{status:500}),xe)}}else{let z={};for(let de of U){let pe=de.method;z[pe]=async(Re)=>{let Te=new URL(Re.url),xe={},ve=de.constraints&&!Array.isArray(de.constraints)?de.constraints:void 0;ht(M,Te.pathname,xe,ve);let Ce=this.enhanceRequest(Re,xe),Me=async(Ae,Fe)=>await this.resolveHandler(de.handler,Ae),Pe=[...this.globalMiddleware,...de.middleware,Me],Ee=await this.runMiddleware(Ce,Pe);return this.applyModifiedCookies(Ee??new Response("No response from middleware chain",{status:500}),Ce)}}c[M]=z}return c},writable:!0,configurable:!0},loadRoutes:{async value(){if(!this.config.routesPath)return;try{if(this.config.apiRoutesPath)try{let c=await import(this.config.apiRoutesPath);if(c.default&&Array.isArray(c.default))for(let P of c.default)this.registerRoute(P,"api")}catch(c){if(this.config.verbose)console.warn(`Failed to load API routes: ${c}`)}if(this.config.webRoutesPath)try{let c=await import(this.config.webRoutesPath);if(c.default&&Array.isArray(c.default))for(let P of c.default)this.registerRoute(P,"web")}catch(c){if(this.config.verbose)console.warn(`Failed to load Web routes: ${c}`)}}catch(c){console.error("Error loading routes:",c)}},writable:!0,configurable:!0},registerRoute:{value(c,P){let{path:M,method:U,handler:z,middleware:de=[],name:pe}=c;switch(U){case"GET":this.get(M,z,P,pe,de);break;case"POST":this.post(M,z,P,pe,de);break;case"PUT":this.put(M,z,P,pe,de);break;case"DELETE":this.delete(M,z,P,pe,de);break;case"PATCH":this.patch(M,z,P,pe,de);break;case"OPTIONS":this.options(M,z,P,pe,de);break;default:console.warn(`Unsupported HTTP method: ${U}`)}},writable:!0,configurable:!0}})}function ss(i){Object.defineProperties(i.prototype,{matchRoute:{value(c,P,M){let U=new URL(c,"http://localhost"),z=`${M||""}:${P}:${U.pathname}`;if(this.routeCache.has(z))return this.routeCache.get(z);if(this.staticRoutes.has(P)){let Te=this.staticRoutes.get(P).get(U.pathname);if(Te&&(!M||!Te.domain||Te.domain===M)){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}}let de=M&&this.domains[M]?this.domains[M]:this.routes,pe=de.filter((Te)=>Te.method===P);for(let Te of pe)if(Te.path===U.pathname){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}for(let Te of pe)if(Te.pattern){let xe=Te.pattern.exec(U);if(xe){let ve={route:Te,params:xe.pathname.groups};return this.routeCache.set(z,ve),ve}}if(M&&this.domains[M]){let Te=this.domains[M].filter((xe)=>xe.method===P&&xe.path.endsWith("*"));for(let xe of Te){let ve=xe.path.slice(0,-1);if(U.pathname.startsWith(ve)){let Ce={route:xe,params:{wildcard:U.pathname.slice(ve.length)}};return this.routeCache.set(z,Ce),Ce}}}let Re=this.routes.filter((Te)=>Te.method===P&&Te.path.endsWith("*")&&(!M||!Te.domain));for(let Te of Re){let xe=Te.path.slice(0,-1);if(U.pathname.startsWith(xe)){let ve={route:Te,params:{wildcard:U.pathname.slice(xe.length)}};return this.routeCache.set(z,ve),ve}}if(P==="HEAD")return this.matchRoute(c,"GET",M);if(P==="OPTIONS"){let Te=de.find((xe)=>xe.method==="OPTIONS"&&xe.path==="*");if(Te){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}for(let xe of["GET","POST","PUT","PATCH","DELETE"]){let ve=this.matchRoute(c,xe,M);if(ve){let Ce={route:{...ve.route,method:"OPTIONS",handler:(Me)=>new Response(null,{status:204})},params:ve.params};return this.routeCache.set(z,Ce),Ce}}}return},writable:!0,configurable:!0},matchDomain:{value(c,P){if(c===P)return!0;if(c.startsWith("*.")){let M=c.substring(2);return P===M||P.endsWith(`.${M}`)}if(c.includes("{")){let M;if(!this.domainPatternCache.has(c)){let U=c.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");M=new RegExp(`^${U}$`),this.domainPatternCache.set(c,M)}else M=this.domainPatternCache.get(c);return M.test(P)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(c,P){let M={};if(!c.includes("{"))return M;let U=c.match(/\{([^}]+)\}/g)?.map((pe)=>pe.substring(1,pe.length-1))||[],z=c.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),de=P.match(new RegExp(`^${z}$`));if(de&&de.length>1)for(let pe=0;pe<U.length;pe++)M[U[pe]]=de[pe+1];return M},writable:!0,configurable:!0},pattern:{value(c,P){return this.patterns.set(c,P),this},writable:!0,configurable:!0},where:{value(c){let P=this.routes[this.routes.length-1];if(P){P.constraints={...P.constraints||{},...c};let M=P.path,U=P.constraints&&!Array.isArray(P.constraints)?P.constraints:void 0;if(P.pattern={exec:(z)=>{let de={};if(!ht(M,z.pathname,de,U))return null;return{pathname:{groups:de}}}},this.routeCache.clear(),this.routeCompiler){let z=[...this.routes];this.routeCompiler.clear();for(let de of z)this.routeCompiler.addRoute(de)}}return this},writable:!0,configurable:!0},withoutNativeDispatch:{value(){let c=this.routes[this.routes.length-1];if(c)c.nativeDispatch=!1;return this},writable:!0,configurable:!0},whereNumber:{value(c){return this.where({[c]:"\\d+"})},writable:!0,configurable:!0},whereAlpha:{value(c){return this.where({[c]:"[A-Za-z]+"})},writable:!0,configurable:!0},whereAlphaNumeric:{value(c){return this.where({[c]:"[A-Za-z0-9]+"})},writable:!0,configurable:!0},whereUuid:{value(c){return this.where({[c]:"[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(c,P){return this.where({[c]:P.join("|")})},writable:!0,configurable:!0}})}var Ki=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,Xi=/bot|crawler|spider|crawling/i,Tr=new Map;function Gt(i){let c=i;if(!c._parsedURL)c._parsedURL=new URL(i.url);return c._parsedURL}function qt(i){let c=i;if(!c._parsedCookies){let P={},M=i.headers.get("cookie");if(M)for(let U of M.split(";")){let z=U.indexOf("=");if(z===-1)continue;let de=U.slice(0,z).trim();if(!de)continue;let pe=U.slice(z+1).trim();try{P[de]=decodeURIComponent(pe)}catch{P[de]=pe}}c._parsedCookies=P}return c._parsedCookies}class as{macros=new Map;epoch=0;register(i,c,P=!1){this.macros.set(i,{name:i,handler:c,accessor:P}),this.epoch++}get(i){return this.macros.get(i)}has(i){return this.macros.has(i)}all(){return Array.from(this.macros.values())}remove(i){let c=this.macros.delete(i);if(c)this.epoch++;return c}clear(){this.macros.clear(),this.epoch++}getEpoch(){return this.epoch}}var tr=new as,is=Symbol("bunRouterMacroProto"),zr=Symbol("bunRouterMacroBase"),xr=new WeakMap,os=-1;class $e{static macro(i,c){tr.register(i,c)}static macroAccessor(i,c){tr.register(i,c,!0)}static applyMacros(i){let c=tr.getEpoch();if(c!==os)xr=new WeakMap,os=c;let P=Object.getPrototypeOf(i)??Object.prototype;if(P[is]){if(xr.get(P[zr])===P)return i;P=P[zr]}let M=xr.get(P);if(!M){M=Object.create(P);for(let U of tr.all())if(U.accessor)Object.defineProperty(M,U.name,{get:U.handler,set(z){Object.defineProperty(this,U.name,{value:z,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else M[U.name]=U.handler;Object.defineProperty(M,is,{value:!0}),Object.defineProperty(M,zr,{value:P}),xr.set(P,M)}return Object.setPrototypeOf(i,M),i}static hasMacro(i){return tr.has(i)}}var rr={wantsJson(){let i=this.headers.get("accept")||"";return i.includes("application/json")||i.includes("json")},wantsHtml(){let i=this.headers.get("accept")||"";return i.includes("text/html")||i.includes("html")},wantsXml(){let i=this.headers.get("accept")||"";return i.includes("application/xml")||i.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 Ki.test(this.headers.get("user-agent")||"")},isBot(){return Xi.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 i=this.headers.get("x-forwarded-for");if(i)return i.split(",").map((c)=>c.trim());return[rr.ip.call(this)]},userAgent(){return this.headers.get("user-agent")||""},referer(){return this.headers.get("referer")||this.headers.get("referrer")||null},bearerToken(){let i=this.headers.get("authorization");if(i&&i.startsWith("Bearer "))return i.substring(7);return null},async rawBody(){if(typeof this._rawBody==="string")return this._rawBody;try{let i=await this.clone().text();return this._rawBody=i,i}catch{return""}},basicAuth(){let i=this.headers.get("authorization");if(i&&i.startsWith("Basic "))try{let c=atob(i.substring(6)),[P,M]=c.split(":");return{username:P,password:M}}catch{return null}return null},hasHeader(i){return this.headers.has(i.toLowerCase())},header(i,c){return this.headers.get(i.toLowerCase())||c||null},allHeaders(){let i={};return this.headers.forEach((c,P)=>{i[P]=c}),i},input(i,c){if(this.validated&&i in this.validated)return this.validated[i];if(this.query&&i in this.query)return this.query[i];if(this.params&&i in this.params)return this.params[i];if(this.jsonBody&&typeof this.jsonBody==="object"&&i in this.jsonBody)return this.jsonBody[i];if(this.formBody&&typeof this.formBody==="object"&&i in this.formBody)return this.formBody[i];return c},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(i){let c=this.all(),P={};return i.forEach((M)=>{if(M in c)P[M]=c[M]}),P},except(i){let c=this.all(),P={};return Object.keys(c).forEach((M)=>{if(!i.includes(M))P[M]=c[M]}),P},has(i){let c=this.all();return i in c&&c[i]!==void 0&&c[i]!==null&&c[i]!==""},hasAny(i){return i.some((c)=>this.has(c))},missing(i){return!this.has(i)},filled(i){let c=this.input(i);if(c===null||c===void 0)return!1;if(typeof c==="string")return c.trim().length>0;if(Array.isArray(c))return c.length>0;if(typeof c==="object")return Object.keys(c).length>0;return!0},getQuery(i,c){if(!i)return this.query||{};return this.query?.[i]||c},param(i,c){return this.params?.[i]||c},cookie(i,c){let P=qt(this)[i];return P!==void 0?P:c||null},cookies(){return{...qt(this)}},file(i){return this.files?.find((c)=>c.fieldName===i)},hasFile(i){return!!this.files?.find((c)=>c.fieldName===i)},path(){return Gt(this).pathname},fullUrl(){return this.url},root(){let i=Gt(this);return`${i.protocol}//${i.host}`},is(i){let c=this.path(),P=Tr.get(i);if(!P){let M=i.replace(/\*/g,".*").replace(/\?/g,".");if(P=new RegExp(`^${M}$`),Tr.size>=1000)Tr.clear();Tr.set(i,P)}return P.test(c)},route(){return this.routeName||null},fingerprint(){let i=Gt(this),c={method:this.method,path:i.pathname,query:i.search,ip:rr.ip.call(this)};return btoa(JSON.stringify(c))},signature(i){let c=`${this.method}${this.url}${rr.ip.call(this)}${i}`,P=0;for(let M=0;M<c.length;M++){let U=c.charCodeAt(M);P=(P<<5)-P+U,P=P&P}return Math.abs(P).toString(36)},merge(i){if(!this.validated)this.validated={};Object.assign(this.validated,i)},replace(i){this.validated={...i}},age(){let i=this.startTime||Date.now();return Date.now()-i},isFromTrustedProxy(i=[]){let c=rr.ip.call(this);return i.includes(c)},contentLength(){let i=this.headers.get("content-length");return i?Number.parseInt(i,10):0},contentType(){return this.headers.get("content-type")},isContentType(i){let c=this.contentType();return c?c.includes(i):!1}};function Qi(){Object.entries(rr).forEach(([i,c])=>{$e.macro(i,c)})}Qi();function vr(i){let c=i;if(!c._parsedQuery){let P={};for(let[M,U]of Gt(i).searchParams){let z=P[M];if(z===void 0)P[M]=U;else if(Array.isArray(z))z.push(U);else P[M]=[z,U]}c._parsedQuery=P}return c._parsedQuery}class Oe{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(i={}){this.routes=[],this.config={...this.config,...i},this.initializeDefaultMiddleware()}initializeDefaultMiddleware(){this.namedMiddleware.set("auth",()=>async(i,c)=>{if(!i.headers.get("authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return await c()}),this.namedMiddleware.set("throttle",(i)=>{let c=i?Lt(i):{maxAttempts:60,windowMs:60000};return jt({maxAttempts:c.maxAttempts||60,windowMs:c.windowMs,keyGenerator:(P)=>P.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(i,c)=>{let P=await c();if(P)P.headers.set("Access-Control-Allow-Origin","*"),P.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),P.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return P})}middlewareGroup(i,c){let P=[];for(let M of c){let[U,z]=M.split(":"),de=this.namedMiddleware.get(U);if(de)P.push(de(z))}return this.middlewareGroups.set(i,P),this}middlewareGroupRoutes(i){let c=this.middlewareGroups.get(i)||[];return new ls(this,c)}when(i){return new us(this,i)}middleware(i){let[c,P]=i.split(":"),M=this.namedMiddleware.get(c);if(!M)throw Error(`Unknown middleware: ${c}`);let U=M(P);return new cs(this,[U])}getServer(){return this.serverInstance}extend(i){for(let[c,P]of Object.entries(i))if(typeof P==="function")this[c]=P.bind(this);return this}async register(i,c){let P=async()=>{await import(i)};if(c?.prefix||c?.middleware&&c.middleware.length>0)await this.group({prefix:c.prefix,middleware:c.middleware},P);else await P();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(i,c,P,M,U,z){let de=c,pe=[],Re=M||"web";if(this.currentGroup){if(this.currentGroup.prefix)de=Mt(this.currentGroup.prefix,c);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)pe=[...this.currentGroup.middleware]}if(z&&z.length>0)for(let Me of z){let Pe=this.resolveMiddleware(Me);if(Pe)pe.push(Pe)}if(Re==="api"&&this.config.apiPrefix)de=Mt(this.config.apiPrefix,de);else if(Re==="web"&&this.config.webPrefix)de=Mt(this.config.webPrefix,de);let Te;if(this.currentDomain)Te=this.currentDomain;let xe={method:i.toUpperCase(),path:de,handler:P,domain:Te,params:{},middleware:pe},ve=wr(de),Ce={};if(ve.forEach((Me)=>{let Pe=Me.replace("?","");if(this.patterns.has(Pe))Ce[Pe]=this.patterns.get(Pe)}),Object.keys(Ce).length>0)xe.constraints=Ce;if(xe.pattern={exec:(Me)=>{let Pe={},Ee=xe.constraints&&!Array.isArray(xe.constraints)?xe.constraints:void 0;if(!ht(de,Me.pathname,Pe,Ee))return null;return{pathname:{groups:Pe}}}},Te){if(!this.domains[Te])this.domains[Te]=[];this.domains[Te].push(xe)}else this.routes.push(xe);if(!de.includes("{")&&!de.includes("*")){if(!this.staticRoutes.has(i.toUpperCase()))this.staticRoutes.set(i.toUpperCase(),new Map);this.staticRoutes.get(i.toUpperCase()).set(de,xe)}if(U)xe.name=U,this.namedRoutes.set(U,xe),St(U,xe.path);return this.routeCache.clear(),this}resolveMiddleware(i){if(typeof i==="function")return i;let[c,P]=i.split(":"),M=this.namedMiddleware.get(c);if(M)return M(P);return null}get(i,c,P,M,U){return this.registerRoute("GET",i,c,P,M,U)}post(i,c,P,M,U){return this.registerRoute("POST",i,c,P,M,U)}put(i,c,P,M,U){return this.registerRoute("PUT",i,c,P,M,U)}patch(i,c,P,M,U){return this.registerRoute("PATCH",i,c,P,M,U)}delete(i,c,P,M,U){return this.registerRoute("DELETE",i,c,P,M,U)}options(i,c,P,M,U){return this.registerRoute("OPTIONS",i,c,P,M,U)}match(i,c,P,M,U,z){for(let de of i)this.registerRoute(de,c,P,M,U,z);return this}any(i,c,P,M,U){for(let z of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.registerRoute(z,i,c,P,M,U);return this}fallback(i){return this.fallbackHandler=i,this}route(i,c={}){let P=this.namedRoutes.get(i);if(!P)throw Error(`Route with name "${i}" not found`);let M=P.path;for(let[U,z]of Object.entries(c))M=M.replace(`{${U}}`,encodeURIComponent(z)),M=M.replace(`{${U}?}`,encodeURIComponent(z));return M}onError(i){return this.errorHandler=i,this}redirect(i,c=302){let P=new Headers;return P.set("Location",i),new Response(null,{status:c,headers:P})}permanentRedirect(i){return this.redirect(i,301)}redirectRoute(i,c,P=302){return this.get(i,(M)=>this.redirect(c,P)),this}async serve(i){this.invalidateCache();let c={...i,fetch:this.handleRequest.bind(this),websocket:this.wsConfig};if(this.serverInstance=Bun.serve(c),this.config.verbose){let P=this.serverInstance.port,M=this.serverInstance.hostname;console.log(`
98
- \uD83D\uDE80 Server running at http://${M}:${P}
99
- `)}return this.serverInstance}async handleRequest(i){try{let c=new URL(i.url);if(this.config.verbose)console.log(`${i.method} ${c.pathname}`);if(i.method==="OPTIONS"){let de=c.hostname||i.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(c.pathname,"OPTIONS",de))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 P=c.hostname||i.headers.get("host")?.split(":")[0]||"localhost",M=this.matchRoute(c.pathname,i.method,P),U=this.enhanceRequest(i,M?.params||{});if(M){U.route=M.route;let de=[...this.globalMiddleware];if(M.route.middleware&&M.route.middleware.length>0)de.push(...M.route.middleware);let pe=async(Te,xe)=>await this.resolveHandler(M.route.handler,Te);de.push(pe);let Re=await this.runMiddleware(U,de);if(Re)return this.applyModifiedCookies(Re,U);return new Response("No response from middleware chain",{status:500})}let z=this.getAllowedMethods(c.pathname,P);if(z.length>0){let de=async(pe,Re)=>new Response(JSON.stringify({error:"Method Not Allowed",path:c.pathname,method:i.method,allowed:z}),{status:405,headers:{"Content-Type":"application/json",Allow:z.join(", ")}});if(this.globalMiddleware.length>0){let pe=[...this.globalMiddleware,de],Re=await this.runMiddleware(U,pe);if(Re)return this.applyModifiedCookies(Re,U)}return de(U,async()=>new Response(null))}if(this.globalMiddleware.length>0){let de=async(Te,xe)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,U);return new Response(JSON.stringify({error:"Not Found",path:c.pathname,method:i.method}),{status:404,headers:{"Content-Type":"application/json"}})},pe=[...this.globalMiddleware,de],Re=await this.runMiddleware(U,pe);if(Re)return this.applyModifiedCookies(Re,U)}if(this.fallbackHandler){let de=await this.resolveHandler(this.fallbackHandler,U);return this.applyModifiedCookies(de,U)}return new Response(JSON.stringify({error:"Not Found",path:c.pathname,method:i.method}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){if(console.error("Error handling request:",c),this.globalMiddleware.length>0){let P=this.enhanceRequest(i,{}),M=async(z,de)=>{if(this.errorHandler)return this.errorHandler(c);return new Response(JSON.stringify({error:"Internal Server Error",message:c instanceof Error?c.message:String(c)}),{status:500,headers:{"Content-Type":"application/json"}})},U=[...this.globalMiddleware,M];try{let z=await this.runMiddleware(P,U);if(z)return z}catch{}}if(this.errorHandler)return this.errorHandler(c);return new Response(JSON.stringify({error:"Internal Server Error",message:c instanceof Error?c.message:String(c)}),{status:500,headers:{"Content-Type":"application/json"}})}}getAllowedMethods(i,c){let P=new URL(i,"http://localhost"),M=`${c||""}:${P.pathname}`,U=this._allowedMethodsCache.get(M);if(U)return U;let z=new Set;for(let[Re,Te]of this.staticRoutes){let xe=Te.get(P.pathname);if(xe&&(!c||!xe.domain||xe.domain===c))z.add(Re)}let de=c&&this.domains[c]?this.domains[c]:this.routes;for(let Re of de){if(z.has(Re.method))continue;if(Re.path===P.pathname){z.add(Re.method);continue}if(Re.pattern&&Re.pattern.exec(P)){z.add(Re.method);continue}if(Re.path.endsWith("*")&&P.pathname.startsWith(Re.path.slice(0,-1)))z.add(Re.method)}if(z.has("GET"))z.add("HEAD");let pe=Array.from(z);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(M,pe),pe}matchRoute(i,c,P){let M=new URL(i,"http://localhost"),U=`${P||""}:${c}:${M.pathname}`;if(this.routeCache.has(U))return this.routeCache.get(U);if(this.staticRoutes.has(c)){let Re=this.staticRoutes.get(c).get(M.pathname);if(Re&&(!P||!Re.domain||Re.domain===P)){let Te={route:Re,params:{}};return this.routeCache.set(U,Te),Te}}let de=(P&&this.domains[P]?this.domains[P]:this.routes).filter((Re)=>Re.method===c);for(let Re of de)if(Re.path===M.pathname){let Te={route:Re,params:{}};return this.routeCache.set(U,Te),Te}for(let Re of de)if(Re.pattern){let Te=Re.pattern.exec(M);if(Te){let xe={route:Re,params:Te.pathname.groups};return this.routeCache.set(U,xe),xe}}if(P&&this.domains[P]){let Re=this.domains[P].filter((Te)=>Te.method===c&&Te.path.endsWith("*"));for(let Te of Re){let xe=Te.path.slice(0,-1);if(M.pathname.startsWith(xe)){let ve={route:Te,params:{wildcard:M.pathname.slice(xe.length)}};return this.routeCache.set(U,ve),ve}}}let pe=this.routes.filter((Re)=>Re.method===c&&Re.path.endsWith("*")&&(!P||!Re.domain));for(let Re of pe){let Te=Re.path.slice(0,-1);if(M.pathname.startsWith(Te)){let xe={route:Re,params:{wildcard:M.pathname.slice(Te.length)}};return this.routeCache.set(U,xe),xe}}if(c==="HEAD")return this.matchRoute(i,"GET",P);return}enhanceRequest(i,c={}){let P=null,M=()=>{if(P===null)P={},(i.headers.get("cookie")||"").split(";").forEach((Re)=>{let Te=Re.trim().split("=");if(Te.length>=2){let xe=Te[0].trim(),ve=Te.slice(1).join("=").trim();P[xe]=decodeURIComponent(ve)}});return P},U=vr(i),z={get url(){return i.url},get method(){return i.method},get headers(){return i.headers},get body(){return i.body},get bodyUsed(){return i.bodyUsed},get cache(){return i.cache},get credentials(){return i.credentials},get destination(){return i.destination},get integrity(){return i.integrity},get keepalive(){return i.keepalive},get mode(){return i.mode},get redirect(){return i.redirect},get referrer(){return i.referrer},get referrerPolicy(){return i.referrerPolicy},get signal(){return i.signal},arrayBuffer:()=>i.arrayBuffer(),blob:()=>i.blob(),clone:()=>i.clone(),formData:()=>i.formData(),json:()=>i.json(),text:()=>i.text(),params:c,query:U,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},de=()=>{let pe={};for(let[Re,Te]of Object.entries(U))pe[Re]=Te;if(z.jsonBody&&typeof z.jsonBody==="object")for(let[Re,Te]of Object.entries(z.jsonBody))pe[Re]=Te;if(z.formBody&&typeof z.formBody==="object")for(let[Re,Te]of Object.entries(z.formBody))pe[Re]=Te;for(let[Re,Te]of Object.entries(c))pe[Re]=Te;return pe};return z.cookies=cr({read:M,write:(pe,Re,Te)=>{z._cookiesToSet.push({name:pe,value:Re,options:Te})},remove:(pe,Re)=>{z._cookiesToDelete.push({name:pe,options:Re})}}),z.get=(pe,Re)=>{let xe=de()[pe];return xe!==void 0?xe:Re},z.input=(pe,Re)=>{let xe=de()[pe];return xe!==void 0?xe:Re},z.all=()=>de(),z.only=(pe)=>{let Re=de(),Te={};for(let xe of pe)if(xe in Re)Te[xe]=Re[xe];return Te},z.except=(pe)=>{let Te={...de()};for(let xe of pe)delete Te[xe];return Te},z.has=(pe)=>{let Re=de();if(Array.isArray(pe))return pe.every((Te)=>(Te in Re)&&Re[Te]!==void 0);return pe in Re&&Re[pe]!==void 0},z.hasAny=(pe)=>{let Re=de();return pe.some((Te)=>(Te in Re)&&Re[Te]!==void 0)},z.filled=(pe)=>{let Re=de(),Te=(xe)=>{let ve=Re[xe];return ve!==void 0&&ve!==null&&ve!==""&&!(Array.isArray(ve)&&ve.length===0)};if(Array.isArray(pe))return pe.every(Te);return Te(pe)},z.missing=(pe)=>{let Re=de();if(Array.isArray(pe))return pe.every((Te)=>!(Te in Re)||Re[Te]===void 0);return!(pe in Re)||Re[pe]===void 0},z.string=(pe,Re="")=>{let xe=de()[pe];return xe!==void 0&&xe!==null?String(xe):Re},z.integer=(pe,Re=0)=>{let xe=de()[pe],ve=Number.parseInt(String(xe),10);return Number.isNaN(ve)?Re:ve},z.float=(pe,Re=0)=>{let xe=de()[pe],ve=Number.parseFloat(String(xe));return Number.isNaN(ve)?Re:ve},z.boolean=(pe,Re=!1)=>{let xe=de()[pe];if(xe===void 0||xe===null)return Re;if(typeof xe==="boolean")return xe;if(xe==="true"||xe==="1"||xe===1)return!0;if(xe==="false"||xe==="0"||xe===0)return!1;return Re},z.array=(pe)=>{let Te=de()[pe];if(Array.isArray(Te))return Te;return Te!==void 0&&Te!==null?[Te]:[]},z.bearerToken=()=>{let pe=i.headers.get("authorization")||i.headers.get("Authorization")||"";if(pe.startsWith("Bearer "))return pe.substring(7);return null},z.header=(pe)=>i.headers.get(pe)||i.headers.get(pe.toLowerCase())||null,z.cookie=(pe,Re)=>{let Te=M()[pe];return Te!==void 0?Te:Re??null},z.getParam=(pe,Re)=>{let Te=c?.[pe];return Te!==void 0?Te:Re},z.getParamAsInt=(pe)=>{let Re=c?.[pe];if(Re===void 0||Re.trim()==="")return null;let Te=Number(Re);return Number.isSafeInteger(Te)?Te:null},z.params=c||{},z}applyModifiedCookies(i,c){let P=new Response(i.body,{status:i.status,statusText:i.statusText,headers:i.headers});if(c._cookiesToSet&&c._cookiesToSet.length>0)for(let{name:M,value:U,options:z}of c._cookiesToSet){let de=this.serializeCookie(M,U,z);P.headers.append("Set-Cookie",de)}if(c._cookiesToDelete&&c._cookiesToDelete.length>0)for(let{name:M,options:U}of c._cookiesToDelete){let z={...U,expires:new Date(0),maxAge:0},de=this.serializeCookie(M,"",z);P.headers.append("Set-Cookie",de)}return P}serializeCookie(i,c,P={}){let M=`${encodeURIComponent(i)}=${encodeURIComponent(c)}`;if(P.maxAge!==void 0)M+=`; Max-Age=${P.maxAge}`;if(P.expires&&P.expires instanceof Date)M+=`; Expires=${P.expires.toUTCString()}`;if(P.path)M+=`; Path=${P.path}`;else M+="; Path=/";if(P.domain)M+=`; Domain=${P.domain}`;if(P.secure)M+="; Secure";if(P.httpOnly)M+="; HttpOnly";if(P.sameSite){let U=P.sameSite.toLowerCase();M+=`; SameSite=${U.charAt(0).toUpperCase()+U.slice(1)}`}return M}buildMiddlewareChain(i){if(i.length===0)return async(P)=>null;let c=async(P)=>null;for(let P=i.length-1;P>=0;P--){let M=i[P],U=c;c=async(z)=>M(z,async()=>await U(z)||new Response(null,{status:200}))}return c}async runMiddleware(i,c){if(c.length===0)return null;try{return await this.buildMiddlewareChain(c)(i)}catch(P){if(this.errorHandler)return this.errorHandler(P);throw P}}async resolveHandler(i,c){if(typeof i==="function"&&!i.prototype?.handle)return await i(c);if(typeof i==="function"&&i.prototype?.handle)return await new i().handle(c);if(i&&typeof i.handle==="function")return await i.handle(c);throw Error(`Invalid action handler: ${typeof i}`)}use(...i){for(let c of i){let P=this.resolveMiddleware(c);if(P)this.globalMiddleware.push(P)}return this}group(i,c){let P=this.currentGroup;if(this.currentGroup={prefix:i.prefix||"",middleware:[]},i.middleware){for(let U of i.middleware)if(typeof U==="function")this.currentGroup.middleware.push(U)}let M=c();if(M instanceof Promise)return M.then(()=>(this.currentGroup=P,this),(U)=>{throw this.currentGroup=P,U});return this.currentGroup=P,this}addRoute(i){if(this.routes.push(i),i.name)this.namedRoutes.set(i.name,i),St(i.name,i.path);return this}registerMiddlewareDependency(i){if(this._middlewarePipeline)this._middlewarePipeline.registerDependency(i);return this}registerMiddlewareSkipConditions(i,c){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(i,c,P){if(i.length===0)return P();let M=0,U=async()=>{if(M>=i.length)return P();let z=i[M++];return await z(c,U)||new Response("No response from middleware",{status:500})};return U()}}class us{router;condition;constructor(i,c){this.router=i;this.condition=c}middleware(i){let[c,P]=i.split(":"),M=this.router.namedMiddleware.get(c);if(!M)throw Error(`Unknown middleware: ${c}`);let U=M(P);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[U]}),this}}class cs{router;middleware;constructor(i,c){this.router=i;this.middleware=c}get(i,c){return this}post(i,c){return this}put(i,c){return this}delete(i,c){return this}}class ls{router;middleware;constructor(i,c){this.router=i;this.middleware=c}get(i,c){return this}post(i,c){return this}put(i,c){return this}delete(i,c){return this}}var Gr=null;function Zi(){if(Gr===null)Gr=new Oe;return Gr}function Yi(i,c={}){if(typeof i.bearerToken==="function")return i;return Zi().enhanceRequest(i,c)}if(!$e.hasMacro("getParam"))$e.macro("getParam",function(i,c){let P=this.params?.[i];return P!==void 0?P:c});if(!$e.hasMacro("getParamAsInt"))$e.macro("getParamAsInt",function(i){let c=this.params?.[i];if(c===void 0||c.trim()==="")return null;let P=Number(c);return Number.isSafeInteger(P)?P:null});if(!$e.hasMacro("get"))$e.macro("get",function(i,c){let P=Gt(this).searchParams.get(i);return P!==null&&P!==void 0?P:c});$e.macroAccessor("query",function(){return vr(this)});$e.macroAccessor("cookies",function(){let i=this,c=()=>({...qt(i)});for(let[P,M]of Object.entries(qt(i)))Object.defineProperty(c,P,{value:M,writable:!0,enumerable:!0,configurable:!0});return c.get=(P)=>qt(i)[P],c.set=(P,M,U={})=>{if(!i._cookiesToSet)i._cookiesToSet=[];i._cookiesToSet.push({name:P,value:M,options:U})},c.delete=(P,M={})=>{if(!i._cookiesToDelete)i._cookiesToDelete=[];i._cookiesToDelete.push({name:P,options:M})},c.getAll=()=>({...qt(i)}),Object.defineProperty(i,"cookies",{value:c,writable:!0,configurable:!0,enumerable:!0}),c});function ds(i){Object.defineProperties(i.prototype,{serve:{async value(c={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let P={idleTimeout:255,...c,fetch:this.handleRequest.bind(this)},M={};if(this.staticResponses&&this.staticResponses.size>0)for(let[U,z]of this.staticResponses)M[U]=z;if(c.static)Object.assign(M,c.static);if(Object.keys(M).length>0)P.static=M;if(c.development!==void 0)P.development=c.development;if(this._nativeRoutesEnabled=c.nativeRoutes===!0,this._nativeRoutesEnabled){let U=this._buildNativeRoutes();if(U)P.routes=U}if(this.wsConfig)P.websocket=this.wsConfig;if(this.serverInstance=Bun.serve(P),this.config.verbose){let U=this.serverInstance.port,z=this.serverInstance.hostname;console.log(`
100
- \uD83D\uDE80 Server running at http://${z}:${U}
101
- `)}return this.serverInstance},writable:!0,configurable:!0},reload:{async value(){if(!this.serverInstance)throw Error("Server not started, cannot reload");this.invalidateCache();let c=this.serverInstance.port,P=this.serverInstance.hostname;this.serverInstance.stop();let M={port:c,hostname:P,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0};if(this._nativeRoutesEnabled){let U=this._buildNativeRoutes();if(U)M.routes=U}if(this.serverInstance=Bun.serve(M),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${P}:${c}`)},writable:!0,configurable:!0},handleRequest:{async value(c){let P=this,M=await dr(c,()=>P.handleRequestImpl(c));return Br(M,c,P.config?.compression)},writable:!0,configurable:!0},_dispatchMatchedRoute:{async value(c,P,M){let U=this.enhanceRequest(P,M);pr(U),U.route=c;let z=c,de=this._mwEpoch||0,pe=z.middleware?z.middleware.length:0,Re=z._compiledChain;if(!Re||z._chainEpoch!==de||z._chainMwLen!==pe){let xe=Qn(z.handler,this.config);if(pe===0&&this.globalMiddleware.length===0)Re=xe;else{let ve=pe>0?[...this.globalMiddleware,...z.middleware]:[...this.globalMiddleware];ve.push((Ce,Me)=>xe(Ce)),Re=this.buildMiddlewareChain(ve)}z._compiledChain=Re,z._chainEpoch=de,z._chainMwLen=pe}let Te;try{Te=await Re(U)}catch(xe){if(this.errorHandler)Te=await this.errorHandler(xe);else throw xe}if(Te)return this.applyModifiedCookies(Te,U);return new Response("No response from middleware chain",{status:500})},writable:!0,configurable:!0},_buildNativeRoutes:{value(){let c=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),P=(pe)=>{if(pe==="*")return"/*";let Re=pe.split("/"),Te=[];for(let xe=0;xe<Re.length;xe++){let ve=Re[xe];if(ve===""){Te.push(ve);continue}if(ve==="*")return xe===Re.length-1?[...Te,"*"].join("/"):null;let Ce=ve.match(/^\{([A-Z_$][\w$]*)\}$/i);if(Ce){Te.push(`:${Ce[1]}`);continue}if(ve.includes("{")||ve.includes(":")||ve.includes("*"))return null;Te.push(ve)}return Te.join("/")},M=this,U=(pe,Re)=>(Te)=>dr(Te,async()=>{try{let xe=Te.params??{};if(Re){let ve=new URL(Te.url).pathname,Ce=pe.path==="*"?"/":pe.path.slice(0,-1);xe={...xe,wildcard:ve.slice(Ce.length)}}return await M._dispatchMatchedRoute(pe,Te,xe)}catch(xe){if(console.error("Error handling request:",xe),M.errorHandler)return M.errorHandler(xe);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:xe instanceof Error?xe.message:String(xe)}),{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"}})}}),z={},de=new Map;for(let pe of this.routes){if(!c.has(pe.method))continue;if(pe.nativeDispatch===!1)continue;if(pe.constraints&&Object.keys(pe.constraints).length>0)continue;if(pe.handler instanceof Response)continue;let Re=P(pe.path);if(!Re)continue;let Te=Re.replace(/:[^/]+/g,":p"),xe=de.get(Te);if(xe&&xe!==Re)continue;de.set(Te,Re);let ve=z[Re]??={};if(ve[pe.method])continue;ve[pe.method]=U(pe,pe.path.endsWith("*"))}for(let pe of Object.values(z))if(pe.GET&&!pe.HEAD)pe.HEAD=pe.GET;return Object.keys(z).length>0?z:null},writable:!0,configurable:!0},handleRequestImpl:{async value(c){try{let P=new URL(c.url);c._parsedURL=P;let M=P.hostname||c.headers.get("host")?.split(":")[0]||"localhost",U=this.matchRoute(P.pathname,c.method,M);if(c.method==="OPTIONS"&&!U){let Te=c.headers.get("origin"),xe={"Access-Control-Allow-Origin":Te||"*","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(Te)xe["Access-Control-Allow-Credentials"]="true",xe.Vary="Origin";return new Response(null,{status:204,headers:xe})}if(U)return await this._dispatchMatchedRoute(U.route,c,U.params);let z=this.enhanceRequest(c,{});pr(z);let de=this.getAllowedMethods(P.pathname,M),pe={"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(de.length>0){let Te=async(xe,ve)=>new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:P.pathname,method:c.method,allowed:de}),{status:405,headers:{...pe,Allow:de.join(", ")}});if(this.globalMiddleware.length>0){let xe=[...this.globalMiddleware,Te],ve=await this.runMiddleware(z,xe);if(ve)return this.applyModifiedCookies(ve,z)}return await Te(z,async()=>null)}if(this.fallbackHandler){let Te=await this.resolveHandler(this.fallbackHandler,z);return this.applyModifiedCookies(Te,z)}let Re=async(Te,xe)=>new Response(JSON.stringify({success:!1,message:"Not Found",path:P.pathname,method:c.method}),{status:404,headers:pe});if(this.globalMiddleware.length>0){let Te=[...this.globalMiddleware,Re],xe=await this.runMiddleware(z,Te);if(xe)return this.applyModifiedCookies(xe,z)}return await Re(z,async()=>null)}catch(P){if(console.error("Error handling request:",P),this.errorHandler)return this.errorHandler(P);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:P instanceof Error?P.message:String(P)}),{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(c,P={}){let M=c;if("params"in c)Object.defineProperty(M,"params",{value:P,writable:!0,configurable:!0,enumerable:!0});else M.params=P;return $e.applyMacros(M),M},writable:!0,configurable:!0},applyModifiedCookies:{value(c,P){let M=P._cookiesToSet&&P._cookiesToSet.length>0,U=P._cookiesToDelete&&P._cookiesToDelete.length>0;if(!M&&!U)return c;let z=new Response(c.body,{status:c.status,statusText:c.statusText,headers:c.headers});if(P._cookiesToSet&&P._cookiesToSet.length>0)for(let{name:de,value:pe,options:Re}of P._cookiesToSet){let Te=this.serializeCookie(de,pe,Re);z.headers.append("Set-Cookie",Te)}if(P._cookiesToDelete&&P._cookiesToDelete.length>0)for(let{name:de,options:pe}of P._cookiesToDelete){let Re={...pe,expires:new Date(0),maxAge:0},Te=this.serializeCookie(de,"",Re);z.headers.append("Set-Cookie",Te)}return z},writable:!0,configurable:!0},serializeCookie:{value(c,P,M={}){let U=`${encodeURIComponent(c)}=${encodeURIComponent(P)}`;if(M.maxAge!==void 0)U+=`; Max-Age=${M.maxAge}`;if(M.expires&&M.expires instanceof Date)U+=`; Expires=${M.expires.toUTCString()}`;if(M.path)U+=`; Path=${M.path}`;else U+="; Path=/";if(M.domain)U+=`; Domain=${M.domain}`;if(M.secure)U+="; Secure";if(M.httpOnly)U+="; HttpOnly";if(M.sameSite){let z=M.sameSite.toLowerCase();U+=`; SameSite=${z.charAt(0).toUpperCase()+z.slice(1)}`}return U},writable:!0,configurable:!0}})}import{join as eo}from"path";function ps(i){Object.defineProperties(i.prototype,{renderView:{async value(c,P={},M={}){let U=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},z=`${c}:${M.layout||""}`;if(U.cache&&this.templateCache.has(z))return this.processTemplate(this.templateCache.get(z),P,U);let de=await _r(c,U.viewsPath,U.extensions);if(!de)throw Error(`View '${c}' not found`);let pe=await Bun.file(de).text(),Re=M.layout||U.defaultLayout;if(Re){let Te=await _r(eo("layouts",Re),U.viewsPath,U.extensions);if(!Te)throw Error(`Layout '${Re}' not found`);pe=(await Bun.file(Te).text()).replace(/\{\{\s*content\s*\}\}/g,pe)}if(U.cache)this.templateCache.set(z,pe);return this.processTemplate(pe,P,U)},writable:!0,configurable:!0},processTemplate:{async value(c,P,M){if((M?.engine||"auto")==="custom"&&M?.customRenderer)return M.customRenderer(c,P,{});let z=Ln(c,P);if(M?.minify?.enabled)try{let de=M.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};z=z.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(de){console.error("Error minifying HTML:",de)}return z},writable:!0,configurable:!0},view:{value(c,P,M={},U={},z="web",de){let pe,Re={},Te={},xe="web",ve;if(typeof P==="string"){if(pe=P,typeof M==="object"&&!Array.isArray(M))if("layout"in M||"status"in M||"headers"in M)Te=M;else Re=M;if(typeof U==="object")Te={...Te,...U};else if(typeof U==="string")xe=U;if(typeof z==="string")if(z==="web"||z==="api")xe=z;else ve=z;if(de)ve=de}else{if(Re=P,typeof M==="string")pe=M;else throw TypeError("View name must be a string");if(typeof U==="object")Te=U;else if(typeof U==="string")if(U==="web"||U==="api")xe=U;else pe=U,xe="web"}let Ce=async(Me)=>{let Pe=await this.renderView(pe,Re,{layout:Te.layout}),Ee=this.config?.queryPreservation;if(Ee?.enabled!==!1&&Ee?.preserve?.length)Pe=hr(Pe,Ee);let Ae=new Headers;if(Ae.set("Content-Type","text/html; charset=utf-8"),Te.headers)for(let[Fe,Dt]of Object.entries(Te.headers))Ae.set(Fe,Dt);return new Response(Pe,{status:Te.status||200,headers:Ae})};return this.get(c,Ce,xe,ve),this},writable:!0,configurable:!0}})}function hs(i){Object.defineProperties(i.prototype,{websocket:{value(c){return this.wsConfig=c,this},writable:!0,configurable:!0},publish:{value(c,P,M=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(c,P,M)},writable:!0,configurable:!0},subscriberCount:{value(c){if(!this.serverInstance)throw Error("Server not started, cannot get subscriber count");return this.serverInstance.subscriberCount(c)},writable:!0,configurable:!0},upgrade:{value(c,P){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(c,P)},writable:!0,configurable:!0},timeout:{value(c,P){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(c,P)},writable:!0,configurable:!0},requestIP:{value(c){if(!this.serverInstance)throw Error("Server not started, cannot get request IP");return this.serverInstance.requestIP(c)},writable:!0,configurable:!0}})}import to from"process";class gs{macros=new Map;register(i,c){this.macros.set(i,{name:i,handler:c})}get(i){return this.macros.get(i)}has(i){return this.macros.has(i)}all(){return Array.from(this.macros.values())}remove(i){return this.macros.delete(i)}clear(){this.macros.clear()}}var Wr=new gs;class nr extends Response{static macro(i,c){Wr.register(i,c),Response[i]=c}static callMacro(i,...c){let P=Wr.get(i);if(!P)throw Error(`Response macro "${i}" not found`);return P.handler(...c)}static hasMacro(i){return Wr.has(i)}}function Cr(i,c){if(typeof i==="number")return{status:i,mergedHeaders:c};if(i&&typeof i==="object"){let P=typeof i.status==="number"?i.status:200,M=c;if(i.headers)if(M={},i.headers instanceof Headers)i.headers.forEach((U,z)=>{M[z]=U});else if(Array.isArray(i.headers))for(let[U,z]of i.headers)M[U]=z;else Object.assign(M,i.headers);return{status:P,mergedHeaders:M}}return{status:200,mergedHeaders:c}}var gt={success:(i,c,P=200)=>{let M={};if(i!==void 0)M.data=i;if(c!==void 0)M.message=c;return new Response(JSON.stringify(M),{status:P,headers:{"Content-Type":"application/json"}})},error:(i,c,P=400)=>{let M={error:i};if(c!==void 0)M.errors=c;return new Response(JSON.stringify(M),{status:P,headers:{"Content-Type":"application/json"}})},validationError:(i,c="Validation failed")=>gt.error(c,i,422),notFound:(i="Resource not found")=>gt.error(i,void 0,404),unauthorized:(i="Unauthorized")=>gt.error(i,void 0,401),forbidden:(i="Forbidden")=>gt.error(i,void 0,403),serverError:(i="Internal server error")=>gt.error(i,void 0,500),created:(i,c="Resource created successfully")=>gt.success(i,c,201),updated:(i,c="Resource updated successfully")=>gt.success(i,c,200),deleted:(i="Resource deleted successfully")=>gt.success(null,i,200),noContent:()=>new Response(null,{status:204}),accepted:(i,c="Request accepted")=>gt.success(i,c,202),paginated:(i,c,P)=>{let M=Math.ceil(c.total/c.per_page),U=(c.current_page-1)*c.per_page+1,z=Math.min(U+c.per_page-1,c.total),de={data:i,message:P,meta:{current_page:c.current_page,per_page:c.per_page,total:c.total,last_page:M,from:U,to:z,path:c.path,first_page_url:`${c.path}?page=1`,last_page_url:`${c.path}?page=${M}`,next_page_url:c.current_page<M?`${c.path}?page=${c.current_page+1}`:void 0,prev_page_url:c.current_page>1?`${c.path}?page=${c.current_page-1}`:void 0}};return new Response(JSON.stringify(de),{status:200,headers:{"Content-Type":"application/json"}})},json:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(JSON.stringify(i),{status:M,headers:{"Content-Type":"application/json",...U}})},html:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(i,{status:M,headers:{"Content-Type":"text/html",...U}})},text:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(i,{status:M,headers:{"Content-Type":"text/plain",...U}})},xml:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(i,{status:M,headers:{"Content-Type":"application/xml",...U}})},redirect:(i,c=302)=>new Response(null,{status:c,headers:{Location:i}}),permanentRedirect:(i)=>gt.redirect(i,301),download:(i,c,P="application/octet-stream")=>new Response(i,{status:200,headers:{"Content-Type":P,"Content-Disposition":`attachment; filename="${c}"`}}),stream:(i,c="application/octet-stream",P={})=>new Response(i,{status:200,headers:{"Content-Type":c,...P}}),cache:(i,c=3600,P=!0,M)=>{let z={"Content-Type":"application/json","Cache-Control":P?`public, max-age=${c}`:`private, max-age=${c}`};if(M)z.ETag=M;return new Response(JSON.stringify(i),{status:200,headers:z})},cors:(i,c="*",P="GET,POST,PUT,DELETE,OPTIONS",M="Content-Type,Authorization")=>new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":c,"Access-Control-Allow-Methods":P,"Access-Control-Allow-Headers":M}}),sse:(i,c,P)=>{let M="";if(P)M+=`id: ${P}
102
- `;if(c)M+=`event: ${c}
103
- `;return M+=`data: ${i}
93
+ `,V.enqueue(pe.encode(Te))}V.close()}catch(he){br(V,he)}}});return new Response(L,{status:200,headers:k})},writable:!0,configurable:!0},streamDownload:{value(l,M,k={}){let L=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${M}"`,...k}),V=new ReadableStream({async start(pe){let he=new TextEncoder;try{for await(let Te of l())if(typeof Te==="string")pe.enqueue(he.encode(Te));else pe.enqueue(Te);pe.close()}catch(Te){br(pe,Te)}}});return new Response(V,{status:200,headers:L})},writable:!0,configurable:!0},streamAsyncIterator:{value(l,M={}){return gt.direct(l,M).toResponse()},writable:!0,configurable:!0}})}class Tr extends Error{modelName;value;field;constructor(o,l,M="id"){super(`${o} not found with ${M}: ${l}`);this.modelName=o;this.value=l;this.field=M;this.name="ModelNotFoundError"}}class qn{bindings=new Map;model(o,l){this.bindings.set(o,l)}bind(o,l){this.bindings.set(o,l)}getBinding(o){return this.bindings.get(o)}hasBinding(o){return this.bindings.has(o)}}var Si=new qn;async function An(o,l,M,k,L={}){if(k)return await M.resolveRouteBinding(l,k);let V=M.getRouteKeyName();if(V!=="id")return await M.resolveRouteBinding(l,V);return await M.find(l)}function On(o,l){return async(M,k)=>{let L={};try{for(let V of o){let pe=M.params?.[V.name];if(!pe)continue;let he=Si.getBinding(V.name);if(he){let ve=null;if(typeof he==="function")ve=await he(pe);else ve=await An(V.name,pe,he,V.key,L);if(!ve)throw new Tr(V.name,pe,V.key||"id");L[V.name]=ve;continue}let Te=l[V.name];if(!Te)continue;let xe=await An(V.name,pe,Te,V.key,L);if(!xe)throw new Tr(V.name,pe,V.key||"id");L[V.name]=xe}return M.models=L,await k()}catch(V){if(V instanceof Tr)return new Response(`${V.modelName} not found`,{status:404});throw V}}}class $n{key;entry;prev;next;constructor(o,l,M=null,k=null){this.key=o;this.entry=l;this.prev=M;this.next=k}}class tr{options;cache=new Map;head=null;tail=null;stats={hits:0,misses:0,evictions:0};constructor(o){this.options=o;if(o.maxSize<=0)throw Error("maxSize must be greater than 0")}get(o){let l=this.cache.get(o);if(!l){this.stats.misses++;return}let M=Date.now(),k=l.entry;if(this.isExpired(k,M)){if(!this.options.allowStale){this.delete(o),this.stats.misses++;return}}if(k.lastAccessed=M,k.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(l);return k.value}set(o,l,M){let k=Date.now(),L=this.cache.get(o);if(L){L.entry.value=l,L.entry.timestamp=k,L.entry.lastAccessed=k,L.entry.ttl=M??this.options.ttl,this.moveToFront(L);return}let V={value:l,timestamp:k,accessCount:0,lastAccessed:k,ttl:M??this.options.ttl},pe=new $n(o,V);if(this.cache.set(o,pe),this.addToFront(pe),this.cache.size>this.options.maxSize)this.evictLRU()}delete(o){let l=this.cache.get(o);if(!l)return!1;if(this.cache.delete(o),this.removeNode(l),this.options.onEvict)this.options.onEvict(o,l.entry.value);return!0}has(o){let l=this.cache.get(o);if(!l)return!1;let M=Date.now();if(this.isExpired(l.entry,M)){if(!this.options.allowStale)return this.delete(o),!1}return!0}clear(){if(this.options.onEvict)for(let[o,l]of this.cache)this.options.onEvict(o,l.entry.value);this.cache.clear(),this.head=null,this.tail=null,this.stats.evictions+=this.cache.size}keys(){let o=[],l=this.head;while(l)o.push(l.key),l=l.next;return o}values(){let o=[],l=this.head;while(l)o.push(l.entry.value),l=l.next;return o}getStats(){let o=this.estimateMemoryUsage(),l=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:l>0?this.stats.hits/l:0,memoryUsage:o}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}prune(){let o=Date.now(),l=[];for(let[M,k]of this.cache)if(this.isExpired(k.entry,o))l.push(M);for(let M of l)this.delete(M);return l.length}getFrequentlyUsed(o=10){let l=[];for(let[M,k]of this.cache)l.push({key:M,value:k.entry.value,accessCount:k.entry.accessCount});return l.sort((M,k)=>k.accessCount-M.accessCount).slice(0,o)}resize(o){if(o<=0)throw Error("maxSize must be greater than 0");this.options.maxSize=o;while(this.cache.size>o)this.evictLRU()}isExpired(o,l){if(!o.ttl)return!1;return l-o.timestamp>o.ttl}moveToFront(o){if(o===this.head)return;this.removeNode(o),this.addToFront(o)}addToFront(o){if(o.prev=null,o.next=this.head,this.head)this.head.prev=o;if(this.head=o,!this.tail)this.tail=o}removeNode(o){if(o.prev)o.prev.next=o.next;else this.head=o.next;if(o.next)o.next.prev=o.prev;else this.tail=o.prev}evictLRU(){if(!this.tail)return;let o=this.tail.key,l=this.tail.entry.value;if(this.cache.delete(o),this.removeNode(this.tail),this.stats.evictions++,this.options.onEvict)this.options.onEvict(o,l)}estimateMemoryUsage(){let o=0;for(let[l,M]of this.cache)o+=l.length*2,o+=this.estimateValueSize(M.entry.value),o+=64;return o+=this.cache.size*48,o}estimateValueSize(o){if(o===null||o===void 0)return 0;if(typeof o==="string")return o.length*2;if(typeof o==="number")return 8;if(typeof o==="boolean")return 1;if(o instanceof ArrayBuffer)return o.byteLength;if(o instanceof Uint8Array)return o.length;try{return JSON.stringify(o).length*2}catch{return 100}}}class Bn{static generateKey(o,l){let M=new URL(o.url),k=o.method,L=M.pathname,V=[k,L],pe=new URLSearchParams(M.search),he=l.excludeQuery||[],Te=[];for(let[xe,ve]of pe.entries())if(!he.includes(xe))Te.push(`${xe}=${ve}`);if(Te.length>0)V.push(Te.sort().join("&"));if(l.varyBy){let xe=[];for(let ve of l.varyBy){let Pe=o.headers.get(ve);if(Pe)xe.push(`${ve}:${Pe}`)}if(xe.length>0)V.push(xe.join("|"))}return V.join("::")}}class Dn{cache;tagIndex=new Map;keyTags=new Map;constructor(o=1000){this.cache=new tr({maxSize:o})}async get(o){let l=this.cache.get(o);if(!l)return null;if(l.ttl&&Date.now()-l.timestamp>l.ttl)return this.delete(o),null;return l}async set(o,l){this.cache.set(o,l),this.keyTags.set(o,new Set(l.tags));for(let M of l.tags){if(!this.tagIndex.has(M))this.tagIndex.set(M,new Set);this.tagIndex.get(M).add(o)}}delete(o){let l=this.keyTags.get(o);if(l){for(let M of l){let k=this.tagIndex.get(M);if(k){if(k.delete(o),k.size===0)this.tagIndex.delete(M)}}this.keyTags.delete(o)}return this.cache.delete(o)}invalidateByTags(o){let l=new Set;for(let M of o){let k=this.tagIndex.get(M);if(k)for(let L of k)l.add(L)}for(let M of l)this.delete(M);return l.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 zt=new Dn;function Nn(o){return async(l,M)=>{if(o.condition&&!o.condition(l))return await M();if(l.method!=="GET"&&l.method!=="HEAD")return await M();let k=Bn.generateKey(l,o),L=await zt.get(k);if(L){let pe=new Headers(L.headers);if(pe.set("X-Cache","HIT"),pe.set("X-Cache-Key",k),L.etag){if(pe.set("ETag",L.etag),l.headers.get("If-None-Match")===L.etag)return new Response(null,{status:304,headers:pe})}return new Response(L.body,{status:L.status,headers:pe})}let V=await M();if(V.status>=200&&V.status<300)try{let pe=V.clone(),he=await pe.arrayBuffer(),Te=await ki(he),xe={};pe.headers.forEach((Ce,Ee)=>{xe[Ee]=Ce});let ve={response:pe,headers:xe,status:V.status,body:new Uint8Array(he),timestamp:Date.now(),ttl:o.ttl,tags:o.tags||[],etag:Te};await zt.set(k,ve);let Pe=new Headers(V.headers);return Pe.set("X-Cache","MISS"),Pe.set("X-Cache-Key",k),Pe.set("ETag",Te),new Response(V.body,{status:V.status,headers:Pe})}catch(pe){return console.error("Error caching response:",pe),V}return V}}async function ki(o){let l=await crypto.subtle.digest("SHA-256",o);return`"${Array.from(new Uint8Array(l)).map((L)=>L.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var Fn={short:(o=[])=>({ttl:300000,maxSize:500,tags:o}),medium:(o=[])=>({ttl:3600000,maxSize:1000,tags:o}),long:(o=[])=>({ttl:86400000,maxSize:2000,tags:o}),api:(o=[])=>({ttl:900000,maxSize:1000,tags:o,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(o=[])=>({ttl:604800000,maxSize:5000,tags:o,varyBy:["Accept-Encoding"]}),user:(o=[])=>({ttl:1800000,maxSize:2000,tags:o,varyBy:["Authorization"],condition:(l)=>!!l.headers.get("Authorization")})},pa={byTags:(o)=>zt.invalidateByTags(o),forUser:(o)=>zt.invalidateByTags([`user:${o}`]),forModel:(o,l)=>{let M=l?[`${o}:${l}`,o]:[o];return zt.invalidateByTags(M)},all:()=>{zt.clear()}};class xr{cache;config;constructor(o,l=1e4){this.config=o,this.cache=new tr({maxSize:l,ttl:o.windowMs*2})}async checkLimit(o){if(this.config.skipIf&&this.config.skipIf(o))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 l=this.generateKey(o),M=Date.now(),k=this.cache.get(l);if(!k||M>=k.resetTime)k={count:1,resetTime:M+this.config.windowMs,firstHit:M};else k.count++;this.cache.set(l,k);let L={totalHits:k.count,resetTime:new Date(k.resetTime),remaining:Math.max(0,this.config.maxAttempts-k.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:k.count<=this.config.maxAttempts,info:L}}generateKey(o){if(this.config.keyGenerator)return this.config.keyGenerator(o);let l=this.getClientIP(o),M=o.user?.id;if(M)return`user:${M}`;return`ip:${l}`}getClientIP(o){let l=o.headers.get("x-forwarded-for");if(l)return l.split(",")[0].trim();let M=o.headers.get("x-real-ip");if(M)return M;let k=o.headers.get("cf-connecting-ip");if(k)return k;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class Un{limiters=new Map;register(o,l){let M=new xr(l);return this.limiters.set(o,M),M}get(o){return this.limiters.get(o)}getOrCreate(o,l){let M=this.limiters.get(o);if(M)return M;return this.register(o,l)}}var In=new Un;function Gt(o,l){let M=l?In.getOrCreate(l,o):new xr(o);return async(k,L)=>{let{allowed:V,info:pe}=await M.checkLimit(k);if(!V){if(o.onLimitReached)return o.onLimitReached(k,pe);let Te=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((pe.resetTime.getTime()-Date.now())/1000).toString()});if(o.headers!==!1)Te.set("X-RateLimit-Limit",pe.limit.toString()),Te.set("X-RateLimit-Remaining",pe.remaining.toString()),Te.set("X-RateLimit-Reset",Math.ceil(pe.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((pe.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((pe.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:Te})}let he=await L();if(he&&o.headers!==!1&&he.status<400){let Te=new Headers(he.headers);return Te.set("X-RateLimit-Limit",pe.limit.toString()),Te.set("X-RateLimit-Remaining",pe.remaining.toString()),Te.set("X-RateLimit-Reset",Math.ceil(pe.resetTime.getTime()/1000).toString()),new Response(he.body,{status:he.status,statusText:he.statusText,headers:Te})}return he}}function Wt(o){let l=o.split(","),M=Number.parseInt(l[0],10);if(Number.isNaN(M)||M<=0)throw Error(`Invalid throttle max attempts: ${l[0]}`);let k;if(l.length===1)k=60000;else{let L=l[1];k=Hi(L)}return{maxAttempts:M,windowMs:k}}function Hi(o){let l=/^(\d+)([smh]|sec|min|hour)?$/,M=o.match(l);if(!M)throw Error(`Invalid time format: ${o}`);let k=Number.parseInt(M[1],10),L=M[2]||"m";if(Number.isNaN(k)||k<=0)throw Error(`Invalid time value: ${M[1]}`);switch(L){case"s":case"sec":return k*1000;case"m":case"min":return k*60*1000;case"h":case"hour":return k*60*60*1000;default:return k*60*1000}}var Ai={api:(o=60,l=1)=>({maxAttempts:o,windowMs:l*60*1000,headers:!0}),auth:()=>({maxAttempts:5,windowMs:900000,keyGenerator:(o)=>{let l=o.headers.get("x-forwarded-for")?.split(",")[0]||"unknown",M=o.jsonBody?.email||o.formBody?.email||o.query?.email||"unknown";return`auth:${l}:${M}`},onLimitReached:(o,l)=>new Response(JSON.stringify({error:"Too many authentication attempts",message:"Please try again later",retryAfter:Math.ceil((l.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:{"Content-Type":"application/json","Retry-After":Math.ceil((l.resetTime.getTime()-Date.now())/1000).toString()}})}),upload:()=>({maxAttempts:10,windowMs:3600000,keyGenerator:(o)=>{let l=o.user?.id;if(l)return`upload:user:${l}`;return`upload:ip:${o.headers.get("x-forwarded-for")?.split(",")[0]||"unknown"}`}}),search:()=>({maxAttempts:100,windowMs:600000,skipIf:(o)=>o.user?.plan==="premium"}),perUser:(o,l)=>({maxAttempts:o,windowMs:l*60*1000,keyGenerator:(M)=>{let k=M.user?.id;if(!k)throw Error("User authentication required for per-user rate limiting");return`user:${k}`},skipIf:(M)=>!M.user?.id}),perIP:(o,l)=>({maxAttempts:o,windowMs:l*60*1000,keyGenerator:(M)=>`ip:${M.headers.get("x-forwarded-for")?.split(",")[0]||M.headers.get("x-real-ip")||M.headers.get("cf-connecting-ip")||"unknown"}`}),global:(o,l)=>({maxAttempts:o,windowMs:l*60*1000,keyGenerator:()=>"global"})},ma={fromString:(o,l)=>{let M=Wt(o);return Gt(M,l)},getInfo:async(o,l)=>{let M=new xr(l),{info:k}=await M.checkLimit(o);return k},reset:(o,l)=>{let M=In.get(o);if(M)return M.cache.delete(l);return!1}};class mt{static parseDomainPattern(o){let l=[],M=o.match(/\{([^}]+)\}/g)||[];for(let V of M){let pe=V.slice(1,-1);l.push(pe)}let k=o.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");k=`^${k}$`;let L=new RegExp(k,"i");return{pattern:o,parameters:l,regex:L}}static matchDomain(o,l){let M=o.match(l.regex);if(!M)return null;let k={};for(let L=0;L<l.parameters.length;L++){let V=l.parameters[L],pe=M[L+1];k[V]=pe}return k}static extractSubdomainInfo(o){let l=o.split(".");if(l.length<=2)return{domain:o,parameters:{},rootDomain:o};let M=l[0],k=l.slice(1).join(".");return{domain:o,parameters:{subdomain:M},subdomain:M,rootDomain:k}}}class rr{pattern;config;routes=[];constructor(o,l){this.pattern=o;this.config=l}addRoute(o,l,M,k=[],L){let V=[...this.config.middleware||[],...k],pe=this.config.prefix?`${this.config.prefix}${l}`:l;this.routes.push({method:o.toUpperCase(),path:pe,handler:M,middleware:V,name:L||(this.config.name?`${this.config.name}.${o.toLowerCase()}${l}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(o){return mt.matchDomain(o,this.pattern)}}class Lr{domainGroups=[];wildcardGroup;domain(o){let l=mt.parseDomainPattern(o);return new _n(this,l)}addDomainGroup(o){if(o.pattern.pattern.includes("*")&&o.pattern.parameters.length===0)this.wildcardGroup=o;else this.domainGroups.push(o)}findDomainGroup(o){for(let l of this.domainGroups){let M=l.matchesDomain(o);if(M!==null)return{group:l,parameters:M}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:mt.extractSubdomainInfo(o).parameters};return null}getAllRoutes(){let o=[];for(let l of this.domainGroups){let M=l.getRoutes();for(let k of M)o.push({domainPattern:l.pattern.pattern,domainParameters:{},...k})}if(this.wildcardGroup){let l=this.wildcardGroup.getRoutes();for(let M of l)o.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...M})}return o}}class _n{router;pattern;group;constructor(o,l){this.router=o;this.pattern=l;this.group=new rr(l,{domain:l.pattern})}middleware(o){return this.group.config.middleware=o,this}prefix(o){return this.group.config.prefix=o,this}name(o){return this.group.config.name=o,this}routes(o){let l=new jn(this.group);o(l),this.router.addDomainGroup(this.group)}get(o,l,M){this.group.addRoute("GET",o,l,M),this.router.addDomainGroup(this.group)}post(o,l,M){this.group.addRoute("POST",o,l,M),this.router.addDomainGroup(this.group)}put(o,l,M){this.group.addRoute("PUT",o,l,M),this.router.addDomainGroup(this.group)}delete(o,l,M){this.group.addRoute("DELETE",o,l,M),this.router.addDomainGroup(this.group)}patch(o,l,M){this.group.addRoute("PATCH",o,l,M),this.router.addDomainGroup(this.group)}}class jn{group;constructor(o){this.group=o}get(o,l,M,k){this.group.addRoute("GET",o,l,M,k)}post(o,l,M,k){this.group.addRoute("POST",o,l,M,k)}put(o,l,M,k){this.group.addRoute("PUT",o,l,M,k)}delete(o,l,M,k){this.group.addRoute("DELETE",o,l,M,k)}patch(o,l,M,k){this.group.addRoute("PATCH",o,l,M,k)}options(o,l,M,k){this.group.addRoute("OPTIONS",o,l,M,k)}head(o,l,M,k){this.group.addRoute("HEAD",o,l,M,k)}any(o,l,M,k){let L=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let V of L)this.group.addRoute(V,o,l,M,k)}}function Ra(o){return async(l,M)=>{let L=new URL(l.url).hostname,V=o.findDomainGroup(L);if(V){let pe=l;pe.domainParams=V.parameters,Object.assign(l.params||{},V.parameters);let he=mt.extractSubdomainInfo(L);pe.subdomainInfo=he}return await M()}}var ya={getSubdomain:(o)=>{let l=new URL(o.url);return mt.extractSubdomainInfo(l.hostname).subdomain||null},getDomainParams:(o)=>o.domainParams||{},matchesDomain:(o,l)=>{let M=new URL(o.url),k=mt.parseDomainPattern(l);return mt.matchDomain(M.hostname,k)!==null},getSubdomainInfo:(o)=>o.subdomainInfo||null},wa={single:(o,l)=>`${o}.${l}`,wildcard:(o,l="subdomain")=>`{${l}}.${o}`,multiLevel:(o,...l)=>`${l.map((k)=>`{${k}}`).join(".")}.${o}`,apiVersion:(o)=>`{version}.api.${o}`,tenant:(o)=>`{tenant}.app.${o}`,environment:(o)=>`{env}.${o}`};import qi from"process";var Vt=new Map;function At(o,l){Vt.set(o,l)}function zr(o){return Vt.get(o)}function Oi(){return new Map(Vt)}function $i(){Vt.clear()}function Bi(o,l={},M={}){let k=Vt.get(o);if(!k){let Te=[...Vt.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${o}' is not defined. Known routes: ${Te}`)}let L=new Set,V=k;for(let[Te,xe]of Object.entries(l)){let ve=`{${Te}}`,Pe=`{${Te}?}`,Ce=encodeURIComponent(String(xe));if(V.includes(ve))V=V.replaceAll(ve,Ce),L.add(Te);else if(V.includes(Pe))V=V.replaceAll(Pe,Ce),L.add(Te)}if(V.includes("?}")){if(V=V.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),V.length>1&&V.endsWith("/"))V=V.slice(0,-1)}let pe=V.match(/\{([^}?]+)\}/g);if(pe&&pe.length>0)throw Error(`Missing required params for route '${o}': ${pe.join(", ")}`);let he=Object.entries(l).filter(([Te])=>!L.has(Te));if(he.length>0){let Te=new URLSearchParams;for(let[xe,ve]of he)Te.set(xe,String(ve));V+=`?${Te.toString()}`}if(M.absolute){let Te=(M.base??qi.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${Te.startsWith("http")?Te:`https://${Te}`}${V.startsWith("/")?V:`/${V}`}`}return V}import{join as Ln}from"path";function nr(o){let l=o.replace(/\/+/g,"/");if(!l.startsWith("/"))l=`/${l}`;if(l.length>1&&l.endsWith("/"))l=l.slice(0,-1);return l}function Ca(o){return o.replace(/\//g,"_").toLowerCase()}function Di(o){if(typeof o!=="function"&&typeof o!=="object")return!1;if(typeof o==="function"&&o.prototype){if(typeof o.prototype.handle==="function")return!0}if(typeof o==="object"&&o!==null&&"handle"in o&&typeof o.handle==="function")return!0;return!1}function Ma(o){return typeof o==="function"&&!Di(o)}function vr(o){let l=o.match(/\{([^}]+)\}/g);return l?l.map((M)=>M.slice(1,-1).replace("?","")):[]}function Ea(o){let l=o.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${l}$`)}var Ni=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,Fi=/\{[^}]+\?\}/,zn=new Map,Gn=new Map;function Ui(o){let l=zn.get(o);if(l)return l;let M=o.endsWith("/*"),k=nr(o),L=0,V=k.split("/").filter(Boolean).map((he)=>{let Te=Fi.test(he);if(Te)L++;let xe=he.match(Ni);return{isParam:!!xe,paramName:xe?xe[1].replace("?",""):"",isOptional:Te,literal:he}}),pe={isWildcard:M,wildcardBase:M?o.slice(0,-2):"",segments:V,optionalCount:L};return zn.set(o,pe),pe}function Ii(o){let l=Gn.get(o);if(l!==void 0)return l;let M;try{M=new RegExp(`^${o}$`)}catch{M=null}return Gn.set(o,M),M}function ft(o,l,M,k){let L=Ui(o);if(L.isWildcard&&l.startsWith(L.wildcardBase))return!0;let V=L.segments,pe=nr(l).split("/").filter(Boolean);if(pe.length<V.length-L.optionalCount||pe.length>V.length)return!1;for(let he=0;he<V.length;he++){let Te=V[he],xe=pe[he];if(xe===void 0){if(Te.isOptional)continue;return!1}if(Te.isParam){let ve=_t(xe);if(M[Te.paramName]=ve,k&&k[Te.paramName]){let Pe=Ii(k[Te.paramName]);if(Pe){if(!Pe.test(ve))return!1}else console.warn(`Invalid constraint regex for parameter ${Te.paramName}: ${k[Te.paramName]}`)}}else if(Te.literal!==xe)return!1}return!0}function kt(...o){return nr(o.join("/"))}function Sa(o){if(!o.startsWith("/"))return!1;let l=[];for(let M of o)if(M==="{")l.push(M);else if(M==="}"){if(l.length===0||l.pop()!=="{")return!1}return l.length===0}async function Wn(o){try{return await Bun.file(o).exists()}catch{return!1}}async function Gr(o,l,M){if(M.some((k)=>o.endsWith(k))){let k=nr(Ln(l,o));if(await Wn(k))return k;return null}for(let k of M){let L=nr(Ln(l,`${o}${k}`));if(await Wn(L))return L}return null}function Vn(o,l){let M=o.replace(/\{\{([^}]+)\}\}/g,(k,L)=>{let V=L.trim(),pe=Wr(l,V);return pe!==void 0?String(pe):k});return M=_i(M,l),M=ji(M,l),M}function _i(o,l){return o.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(M,k,L,V="")=>{let pe=k.trim();return Wr(l,pe)?L:V})}function ji(o,l){return o.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(M,k,L)=>{let V=Wr(l,k.trim());if(!Array.isArray(V))return"";return V.map((pe)=>L.replace(/\{\{@index\}\}/g,String(V.indexOf(pe))).replace(/\{\{this\}\}/g,String(pe)).replace(/\{\{this\.([^}]+)\}\}/g,(he,Te)=>{let xe=pe[Te.trim()];return xe!==void 0?String(xe):""})).join("")})}function Wr(o,l){return l.split(".").reduce((M,k)=>{if(M&&typeof M==="object"&&k in M)return M[k];return},o)}class ke{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(o,l,M){this.method=o;this.path=l;this.handler=M}addMiddleware(o){if(Array.isArray(o))this.middleware.push(...o);else this.middleware.push(o);return this}cached(o=[],l){return this.cacheConfig={...Fn.api(o),...l},this}throttle(o,l){if(typeof o==="string"){let M=Wt(o);this.throttleConfig={maxAttempts:M.maxAttempts??60,windowMs:M.windowMs,keyGenerator:(k)=>k.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=o;return this}name(o){return this.routeName=o,this}model(o,l){return this.modelBindings[o]=l,this}build(){let o=[];if(Object.keys(this.modelBindings).length>0){let l=Object.keys(this.modelBindings).map((k)=>({name:k})),M=On(l,this.modelBindings);o.push(M)}if(this.throttleConfig){let l=Gt(this.throttleConfig);o.push(l)}if(this.cacheConfig){let l=Nn(this.cacheConfig);o.push(l)}return o.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:o,name:this.routeName}}}class Jn{router;condition;constructor(o,l){this.router=o;this.condition=l}middleware(o){let[l,M]=o.split(":"),k=this.router.resolveNamedMiddleware(l);if(!k)throw Error(`Unknown middleware: ${l}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[k(M)]}),this}}class Kn{router;middleware;constructor(o,l){this.router=o;this.middleware=l}get(o,l){return new ke("GET",o,l).addMiddleware(this.middleware)}post(o,l){return new ke("POST",o,l).addMiddleware(this.middleware)}put(o,l){return new ke("PUT",o,l).addMiddleware(this.middleware)}delete(o,l){return new ke("DELETE",o,l).addMiddleware(this.middleware)}patch(o,l){return new ke("PATCH",o,l).addMiddleware(this.middleware)}}class Xn{router;groupMiddleware;constructor(o,l){this.router=o;this.groupMiddleware=l}get(o,l){return new ke("GET",o,l).addMiddleware(this.groupMiddleware)}post(o,l){return new ke("POST",o,l).addMiddleware(this.groupMiddleware)}put(o,l){return new ke("PUT",o,l).addMiddleware(this.groupMiddleware)}delete(o,l){return new ke("DELETE",o,l).addMiddleware(this.groupMiddleware)}patch(o,l){return new ke("PATCH",o,l).addMiddleware(this.groupMiddleware)}}class sr{routes=[];globalMiddleware=[];subdomainRouter=new Lr;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(o)=>{let l=o?Wt(o):{maxAttempts:60,windowMs:60000},M=Gt({maxAttempts:l.maxAttempts,windowMs:l.windowMs,keyGenerator:(L)=>L.headers.get("x-forwarded-for")||"anonymous"});return async(L,V)=>await M(L,async()=>await V()??new Response(null))}),this.namedMiddleware.set("auth",()=>async(o,l)=>{if(!o.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return o.user={id:"123",roles:["user"]},await l()}),this.namedMiddleware.set("cors",()=>async(o,l)=>{let M=await l();if(M){let k=new Headers(M.headers);return k.set("Access-Control-Allow-Origin","*"),k.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),k.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(M.body,{status:M.status,statusText:M.statusText,headers:k})}return M})}middlewareGroup(o,l){let M=[];for(let k of l){let[L,V]=k.split(":"),pe=this.namedMiddleware.get(L);if(pe)M.push(pe(V))}return this.middlewareGroups.set(o,M),this}middlewareGroupRoutes(o){let l=this.middlewareGroups.get(o)||[];return new Xn(this,l)}when(o){return new Jn(this,o)}resolveNamedMiddleware(o){return this.namedMiddleware.get(o)}addConditionalMiddleware(o){this.conditionalMiddleware.push(o)}middleware(o){let[l,M]=o.split(":"),k=this.namedMiddleware.get(l);if(!k)throw Error(`Unknown middleware: ${l}`);let L=k(M);return new Kn(this,[L])}use(o){return this.globalMiddleware.push(o),this}get(o,l){return new ke("GET",o,l)}post(o,l){return new ke("POST",o,l)}put(o,l){return new ke("PUT",o,l)}delete(o,l){return new ke("DELETE",o,l)}patch(o,l){return new ke("PATCH",o,l)}register(o){let l=o.build();if(this.routes.push(l),l.name)At(l.name,l.path);return this}cached(o=[],l){return{get:(M,k)=>this.get(M,k).cached(o,l),post:(M,k)=>this.post(M,k).cached(o,l),put:(M,k)=>this.put(M,k).cached(o,l),delete:(M,k)=>this.delete(M,k).cached(o,l),patch:(M,k)=>this.patch(M,k).cached(o,l)}}throttled(o){return{get:(l,M)=>this.get(l,M).throttle(o),post:(l,M)=>this.post(l,M).throttle(o),put:(l,M)=>this.put(l,M).throttle(o),delete:(l,M)=>this.delete(l,M).throttle(o),patch:(l,M)=>this.patch(l,M).throttle(o)}}group(o,l){let M=new sr;l(M);for(let k of M.routes){let L={...k,path:o.prefix?`${o.prefix}${k.path}`:k.path,middleware:[...o.middleware||[],...k.middleware],name:o.name&&k.name?`${o.name}.${k.name}`:k.name};if(o.domain){let V=mt.parseDomainPattern(o.domain),pe=new rr(V,{domain:o.domain});pe.addRoute(L.method,L.path,L.handler,L.middleware,L.name),this.subdomainRouter.addDomainGroup(pe)}else if(this.routes.push(L),L.name)At(L.name,L.path)}return this}domain(o){return{routes:(l)=>{let M=new sr;l(M);let k=mt.parseDomainPattern(o),L=new rr(k,{domain:o});for(let V of M.routes)L.addRoute(V.method,V.path,V.handler,V.middleware,V.name);return this.subdomainRouter.addDomainGroup(L),this}}}resource(o,l,M={}){let k=["index","create","store","show","edit","update","destroy"],L=M.only||k.filter((pe)=>!M.except?.includes(pe)),V=[{action:"index",method:"GET",path:`/${o}`,handler:l.index},{action:"create",method:"GET",path:`/${o}/create`,handler:l.create},{action:"store",method:"POST",path:`/${o}`,handler:l.store},{action:"show",method:"GET",path:`/${o}/{${o.slice(0,-1)}}`,handler:l.show},{action:"edit",method:"GET",path:`/${o}/{${o.slice(0,-1)}}/edit`,handler:l.edit},{action:"update",method:"PUT",path:`/${o}/{${o.slice(0,-1)}}`,handler:l.update},{action:"destroy",method:"DELETE",path:`/${o}/{${o.slice(0,-1)}}`,handler:l.destroy}];for(let pe of V)if(L.includes(pe.action)&&pe.handler){let he=new ke(pe.method,pe.path,pe.handler).name(`${o}.${pe.action}`);if(M.model&&["show","edit","update","destroy"].includes(pe.action))he.model(o.slice(0,-1),M.model);this.register(he)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(o){let l=new URL(o.url),M=l.hostname,k=this.subdomainRouter.findDomainGroup(M);if(k){let L=o;L.domainParams=k.parameters;for(let V of k.group.getRoutes()){let pe=this.matchRouteParams(V,o.method,l.pathname);if(pe)return await this.executeRoute(V,L,pe)}}for(let L of this.routes){let V=this.matchRouteParams(L,o.method,l.pathname);if(V)return await this.executeRoute(L,o,V)}return null}matchRouteParams(o,l,M){if(o.method!==l)return null;let k={};return ft(o.path,M,k)?k:null}async executeRoute(o,l,M){l.params=M;let k=[...this.globalMiddleware];for(let pe of this.conditionalMiddleware)if(await pe.condition(l))k.push(...pe.middleware);k.push(...o.middleware);let L=0,V=async()=>{if(L<k.length){let pe=k[L++];return await pe(l,V)??new Response(null)}return await o.handler(l)};return await V()}}var Li={api:(o,l,M={})=>{let k=M.method||"GET",L=new ke(k,o,l);if(M.cache)L.cached(M.cache);if(M.throttle)L.throttle(M.throttle);return L},protected:(o,l,M={})=>{let k=M.method||"GET",L=new ke(k,o,l);return L.addMiddleware(async(V,pe)=>{if(!V.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await pe()}),L},upload:(o,l,M={})=>{let k=new ke("POST",o,l);return k.addMiddleware(async(L,V)=>await V()),k}},zi={route:(o,l={},M={})=>{let k=zr(o)??`/${o}`;for(let[V,pe]of Object.entries(l)){let he=encodeURIComponent(pe);k=k.replace(`{${V}}`,he),k=k.replace(`{${V}?}`,he)}if(k.includes("?}")){if(k=k.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),k.length>1&&k.endsWith("/"))k=k.slice(0,-1)}let L=new URLSearchParams(M).toString();if(L)k+=`?${L}`;return k},redirect:(o,l=302)=>new Response(null,{status:l,headers:{Location:o}}),json:(o,l=200)=>new Response(JSON.stringify(o),{status:l,headers:{"Content-Type":"application/json"}})},Gi=new sr;function Qn(o){Object.defineProperties(o.prototype,{group:{value(l,M){let k=this.currentGroup,L={...k};if(l.prefix&&k?.prefix)L.prefix=kt(k.prefix,l.prefix);else if(l.prefix)L.prefix=l.prefix;if(l.middleware)L.middleware=[...k?.middleware||[],...l.middleware];this.currentGroup=L;let V=M();if(V instanceof Promise)return V.then(()=>(this.currentGroup=k,this),(pe)=>{throw this.currentGroup=k,pe});return this.currentGroup=k,this},writable:!0,configurable:!0},name:{value(l,M){let k=this.currentGroup||{},L={...k};this.currentGroup=L;let V=this.routes.length;M();for(let pe=V;pe<this.routes.length;pe++){let he=this.routes[pe];if(he.name)he.name=`${l}.${he.name}`}return this.currentGroup=k,this},writable:!0,configurable:!0},controller:{value(l,M){let k=this.currentGroup||{},L={...k,controller:l};return this.currentGroup=L,M(),this.currentGroup=k,this},writable:!0,configurable:!0},domain:{value(l,M){let k=this.currentDomain;return this.currentDomain=l,M(),this.currentDomain=k,this},writable:!0,configurable:!0},prefix:{value(l,M){return this.group({prefix:l},M)},writable:!0,configurable:!0},resource:{value(l,M,k="api"){let L=l.endsWith("s")?l:`${l}s`,V=l.endsWith("s")?l.slice(0,-1):l,pe=[{name:"index",method:"GET",path:`/${L}`,action:"index"},{name:"create",method:"GET",path:`/${L}/create`,action:"create"},{name:"store",method:"POST",path:`/${L}`,action:"store"},{name:"show",method:"GET",path:`/${L}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${L}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${L}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${L}/{id}`,action:"destroy"}];return this.name(V,()=>{for(let he of pe){let Te;if(typeof M==="string")Te=`${M}${he.action.charAt(0).toUpperCase()+he.action.slice(1)}Action`;else if(M[he.action])Te=M[he.action];else continue;switch(he.method){case"GET":this.get(he.path,Te,k,he.name);break;case"POST":this.post(he.path,Te,k,he.name);break;case"PUT":this.put(he.path,Te,k,he.name);break;case"DELETE":this.delete(he.path,Te,k,he.name);break}}}),this},writable:!0,configurable:!0}})}function Zn(o){Object.defineProperties(o.prototype,{addRoute:{value(l,M,k,L,V,pe){let he=M,Te=[],xe=L||"web";if(this.currentGroup){if(this.currentGroup.prefix)he=kt(this.currentGroup.prefix,M);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)Te=[...this.currentGroup.middleware]}if(pe&&pe.length>0)for(let Me of pe){let Se=this.resolveMiddleware(Me);if(Se)Te.push(Se)}if(xe==="api"&&this.config.apiPrefix)he=kt(this.config.apiPrefix,he);else if(xe==="web"&&this.config.webPrefix)he=kt(this.config.webPrefix,he);let ve;if(this.currentDomain)ve=this.currentDomain;let Pe={method:l.toUpperCase(),path:he,handler:k,domain:ve,params:{},middleware:Te},Ce=vr(he),Ee={};if(Ce.forEach((Me)=>{let Se=Me.replace("?","");if(this.patterns.has(Se))Ee[Se]=this.patterns.get(Se)}),Object.keys(Ee).length>0)Pe.constraints=Ee;if(Pe.pattern={exec:(Me)=>{let Se={},Oe=Pe.constraints&&!Array.isArray(Pe.constraints)?Pe.constraints:void 0;if(!ft(he,Me.pathname,Se,Oe))return null;return{pathname:{groups:Se}}}},k instanceof Response)this.staticResponses.set(he,k);if(ve){if(this._hasDomainRoutes=!0,!this.domains[ve])this.domains[ve]=[];this.domains[ve].push(Pe)}else this.routes.push(Pe);if(!he.includes("{")&&!he.includes("*")){if(!this.staticRoutes.has(l.toUpperCase()))this.staticRoutes.set(l.toUpperCase(),new Map);let Me=this.staticRoutes.get(l.toUpperCase());if(!Me.has(he))Me.set(he,Pe)}if(V)Pe.name=V,this.namedRoutes.set(V,Pe),At(V,Pe.path);if(this.addRouteToCompiler&&!ve)this.addRouteToCompiler(Pe);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(l,M,k,L,V){return this.addRoute("GET",l,M,k,L,V)},writable:!0,configurable:!0},post:{value(l,M,k,L,V){return this.addRoute("POST",l,M,k,L,V)},writable:!0,configurable:!0},put:{value(l,M,k,L,V){return this.addRoute("PUT",l,M,k,L,V)},writable:!0,configurable:!0},patch:{value(l,M,k,L,V){return this.addRoute("PATCH",l,M,k,L,V)},writable:!0,configurable:!0},delete:{value(l,M,k,L,V){return this.addRoute("DELETE",l,M,k,L,V)},writable:!0,configurable:!0},options:{value(l,M,k,L,V){return this.addRoute("OPTIONS",l,M,k,L,V)},writable:!0,configurable:!0},head:{value(l,M,k,L,V){return this.addRoute("HEAD",l,M,k,L,V)},writable:!0,configurable:!0},match:{value(l,M,k,L,V,pe){for(let he of l)this.addRoute(he,M,k,L,V,pe);return this},writable:!0,configurable:!0},any:{value(l,M,k,L,V){let pe=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(pe,l,M,k,L,V)},writable:!0,configurable:!0},fallback:{value(l){return this.fallbackHandler=l,this},writable:!0,configurable:!0},route:{value(l,M={}){let k=this.namedRoutes.get(l);if(!k)throw Error(`Route with name "${l}" not found`);let L=k.path;for(let[V,pe]of Object.entries(M))L=L.replace(`{${V}}`,encodeURIComponent(pe)),L=L.replace(`{${V}?}`,encodeURIComponent(pe));if(L.includes("{")){if(L=L.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),L.length>1&&L.endsWith("/"))L=L.slice(0,-1)}return L},writable:!0,configurable:!0},onError:{value(l){return this.errorHandler=l,this},writable:!0,configurable:!0}})}function Yn(o){Object.defineProperties(o.prototype,{redirect:{value(l,M=302){let k=new Headers;return k.set("Location",l),new Response(null,{status:M,headers:k})},writable:!0,configurable:!0},permanentRedirect:{value(l){return this.redirect(l,301)},writable:!0,configurable:!0},redirectRoute:{value(l,M,k=302){return this.get(l,(L)=>this.redirect(M,k)),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(l,M){return this.redirectRoute(l,M,301)},writable:!0,configurable:!0}})}function Ie(o){if(o instanceof Response)return o;if(o===null||o===void 0)return new Response(null,{status:204});if(typeof o==="string")return new Response(o,{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(typeof o==="number"||typeof o==="boolean")return new Response(String(o),{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(o instanceof ArrayBuffer||o instanceof Uint8Array)return new Response(o,{headers:{"Content-Type":"application/octet-stream"}});if(o instanceof ReadableStream)return new Response(o);if(typeof o==="object")return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json; charset=utf-8"}});return new Response(String(o),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function Wi(o,l){let M=l.actionsPath||"actions",k=l.controllersPath||"controllers",L=o.replace(/\.(ts|js)$/,""),V=[];if(L.includes("@")){let[he,Te]=L.split("@");V.push(`${k}/${he}`,`${k}/${he}.ts`,`${k}/${he}.js`,`./${k}/${he}`,`../${k}/${he}`)}else if(L.startsWith("Actions/")||L.startsWith("actions/"))V.push(L,`./${L}`,`../${L}`);else if(L.startsWith("./")||L.startsWith("../"))V.push(L);else V.push(`${M}/${L}`,`./${M}/${L}`,`../${M}/${L}`,L,`./${L}`,`../${L}`);let pe=null;for(let he of V)try{return await import(he)}catch(Te){pe=Te}throw Error(`Failed to import handler "${o}".
94
+ Tried paths: ${V.join(", ")}
95
+ Last error: ${pe?.message||"Unknown error"}`)}function es(o){return typeof o==="function"&&!o.prototype?.handle}async function ir(o,l,M){if(o instanceof Response)return o.clone();if(es(o)){let k=await o(l);return Ie(k)}if(typeof o==="string")return Vi(o,l,M);if(typeof o==="function"&&o.prototype&&typeof o.prototype.handle==="function"){let V=await new o().handle(l);return Ie(V)}if(o&&typeof o==="object"&&"handle"in o){let k=o;if(typeof k.handle==="function"){let L=await k.handle(l);return Ie(L)}}throw Error(`Invalid handler type: ${typeof o}`)}async function Vi(o,l,M){let k=M.controllersPath||"controllers";if(o.includes("@")){let[pe,he]=o.split("@"),Te=[`${k}/${pe}`,`./${k}/${pe}`,`../${k}/${pe}`,pe,`./${pe}`,`../${pe}`],xe=null,ve=null;for(let Ce of Te)try{xe=await import(Ce);break}catch(Ee){ve=Ee}if(!xe)throw Error(`Failed to import controller "${pe}".
96
+ Tried paths: ${Te.join(", ")}
97
+ Last error: ${ve?.message||"Unknown error"}`);let Pe=xe.default||xe;if(typeof Pe==="function"){let Ce=new Pe,Ee=Ce[he];if(typeof Ee!=="function")throw TypeError(`Method "${he}" not found on controller "${pe}"`);let Me=await Ee.call(Ce,l);return Ie(Me)}throw Error(`Controller "${pe}" is not a valid class`)}let L=await Wi(o,M),V=L.default||L;if(typeof V==="function"){if(V.prototype&&typeof V.prototype.handle==="function"){let Te=await new V().handle(l);return Ie(Te)}let pe=await V(l);return Ie(pe)}if(V&&typeof V==="object"&&"handle"in V){let pe=V;if(typeof pe.handle==="function"){let he=await pe.handle(l);return Ie(he)}}throw Error(`Handler "${o}" does not export a valid handler function or class`)}function Ji(o){return(l,M)=>ir(l,M,o)}function ts(o,l){if(o instanceof Response)return()=>o.clone();if(es(o))return(M)=>{let k=o(M);if(k instanceof Response)return k;return k instanceof Promise?k.then(Ie):Ie(k)};if(typeof o==="function"&&o.prototype&&typeof o.prototype.handle==="function"){let M=o;return(k)=>{let L=new M().handle(k);if(L instanceof Response)return L;return L instanceof Promise?L.then(Ie):Ie(L)}}return(M)=>ir(o,M,l)}function rs(o){Object.defineProperties(o.prototype,{use:{value(...l){for(let M of l){let k=this.resolveMiddleware(M);if(k)this.globalMiddleware.push(k)}return this._mwEpoch=(this._mwEpoch||0)+1,this},writable:!0,configurable:!0},resolveMiddleware:{value(l){if(typeof l==="function")return l;if(typeof l==="object"&&l!==null&&"handle"in l&&typeof l.handle==="function")return(M,k)=>l.handle(M,k);if(typeof l==="string"){let[M,k]=l.split(":"),L=this.namedMiddleware?.get(M);if(L)return L(k);let V=null,pe=l;return async(he,Te)=>{if(!V)try{let xe=await import(`../middleware/${pe}.ts`);if(xe.default&&typeof xe.default==="function")V=xe.default;else if(xe.default&&typeof xe.default.handle==="function")V=(ve,Pe)=>xe.default.handle(ve,Pe)}catch(xe){console.error(`Failed to load middleware "${pe}":`,xe)}if(V)return V(he,Te);return Te()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value(l){if(l.length===0)return async(k)=>null;let M=async(k)=>null;for(let k=l.length-1;k>=0;k--){let L=l[k],V=M;M=async(pe)=>L(pe,async()=>await V(pe)||new Response(null,{status:200}))}return M},writable:!0,configurable:!0},runMiddleware:{async value(l,M){if(M.length===0)return null;try{return await this.buildMiddlewareChain(M)(l)}catch(k){if(this.errorHandler)return this.errorHandler(k);throw k}},writable:!0,configurable:!0},middleware:{value(...l){for(let M of l)if(typeof M==="string"){let[k]=M.split(":");if(!this.namedMiddleware.has(k))throw Error(`Unknown middleware: ${k}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...l)}else{let M=this.routes[this.routes.length-1];if(M)this.applyMiddlewareToRoute(M,l)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(l,M){for(let k of M){let L=this.resolveMiddleware(k);if(L)l.middleware.push(L)}},writable:!0,configurable:!0},resolveHandler:{async value(l,M){return ir(l,M,this.config)},writable:!0,configurable:!0},wrapResponse:{value:Ie,writable:!0,configurable:!0},onError:{value(l){return this.errorHandler=l,this},writable:!0,configurable:!0}})}class ns{models=new Map;cache=new Map;register(o,l){this.models.set(o,l)}get(o){return this.models.get(o)}has(o){return this.models.has(o)}async resolve(o,l,M){let k=this.models.get(o);if(!k)return{model:null,error:`Model binding '${o}' not found`,status:500};try{if(k.cache?.enabled){let pe=this.getCachedModel(o,l,k);if(pe)return{model:pe}}let L=await k.resolver(l,M);if(L===null||L===void 0)return{model:null,error:`${o} not found`,status:404};if(k.validator){let pe=await k.validator(L,l,M);if(!pe.valid)return{model:null,error:pe.error||"Model validation failed",status:pe.status||422}}let V=L;if(k.transformer)V=await k.transformer(L,l,M);if(k.cache?.enabled)this.cacheModel(o,l,V,k);return{model:V}}catch(L){return{model:null,error:L instanceof Error?L.message:"Model resolution failed",status:500}}}createErrorResponse(o,l,M){let k=this.models.get(o),L=l.status||404,V=l.error||"Model not found";if(k?.errorHandling){if(L===404&&k.errorHandling.notFound)return k.errorHandling.notFound(M);if(L===422&&k.errorHandling.validation)return k.errorHandling.validation(null,V);if(k.errorHandling.transform)return k.errorHandling.transform(V)}return new Response(JSON.stringify({error:V,status:L,message:`Failed to resolve ${o}`}),{status:L,headers:{"Content-Type":"application/json"}})}clearCache(o,l){if(l){let M=this.models.get(o);if(M?.cache){let k=this.generateCacheKey(o,l,M);this.cache.delete(k)}}else{let M=[];for(let k of this.cache.keys())if(k.startsWith(`${o}:`))M.push(k);for(let k of M)this.cache.delete(k)}}clearAllCache(){this.cache.clear()}getCacheStats(){let o=Date.now(),l=0,M=0;for(let k of this.cache.values())if(o-k.timestamp>k.ttl)M++;else l++;return{totalEntries:this.cache.size,validEntries:l,expiredEntries:M,models:this.models.size}}cleanupCache(){let o=Date.now(),l=[];for(let[M,k]of this.cache.entries())if(o-k.timestamp>k.ttl)l.push(M);for(let M of l)this.cache.delete(M);return l.length}getCachedModel(o,l,M){if(!M.cache?.enabled)return null;let k=this.generateCacheKey(o,l,M),L=this.cache.get(k);if(!L)return null;if(Date.now()-L.timestamp>L.ttl)return this.cache.delete(k),null;return L.model}cacheModel(o,l,M,k){if(!k.cache?.enabled)return;let L=this.generateCacheKey(o,l,k);this.cache.set(L,{model:M,timestamp:Date.now(),ttl:k.cache.ttl})}generateCacheKey(o,l,M){if(M.cache?.key)return`${o}:${M.cache.key(l)}`;let k=Object.entries(l).sort(([L],[V])=>L.localeCompare(V)).map(([L,V])=>`${L}=${V}`).join("&");return`${o}:${k}`}}var ss=new ns;function is(o){Object.defineProperties(o.prototype,{modelRegistry:{value:ss,writable:!0,configurable:!0},model:{value(l,M,k){if(typeof M==="string")this.modelRegistry.register(l,{resolver:async(L)=>(console.warn(`Model class ${M} not implemented`),{id:L[l],modelClass:M}),errorHandling:k?{notFound:(L)=>k(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(l,{resolver:async(L)=>{let V=L[l];if(!V)return null;return M(V)},errorHandling:k?{notFound:(L)=>k(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(l,M)=>{if(!l.params)return await M()||new Response("Not Found",{status:404});for(let[L,V]of Object.entries(l.params))if(this.modelRegistry.has(L))try{let pe=await this.modelRegistry.resolve(L,l.params,l);if(pe.model===null){if(pe.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:pe.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(pe.status===404)return this.modelRegistry.createErrorResponse(L,pe,l.params)}else l[L]=pe.model}catch(pe){return new Response(JSON.stringify({error:"Internal Server Error",message:pe instanceof Error?pe.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await M()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(l){return async(M,k)=>{try{return await k()||l(M)}catch(L){return console.error(L),l(M)}}},writable:!0,configurable:!0},scopedBindings:{value(l){return async(M,k)=>{if(!M.params)return await k()||new Response("Not Found",{status:404});for(let[V,pe]of Object.entries(l))if(M.params[V]&&M.params[pe]);return await k()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},clearModelCache:{value(l){if(l)this.modelRegistry.clearCache(l);else this.modelRegistry.clearAllCache();return this},writable:!0,configurable:!0},getModelStats:{value(){return this.modelRegistry.getCacheStats()},writable:!0,configurable:!0}})}class qt{children=new Map;paramChild=null;wildcardChild=null;routes=new Map;paramName=null;pattern=null;isEndpoint=!1;addRoute(o,l){this.routes.set(o,l),this.isEndpoint=!0}getRoute(o){return this.routes.get(o)}getAllRoutes(){return Array.from(this.routes.values())}}class Vr{root=new qt;compiledRoutes=new Map;methodTries=new Map;constructor(){let o=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","TRACE","CONNECT"];for(let l of o)this.methodTries.set(l,new qt)}compileRoute(o){let l=`${o.method}:${o.path}`;if(o.constraints&&!Array.isArray(o.constraints)){let Te=o.constraints,ve=Object.keys(Te).sort().map((Pe)=>`${Pe}:${Te[Pe]}`).join("|");l=`${o.method}:${o.path}#${ve}`}if(this.compiledRoutes.has(l))return this.compiledRoutes.get(l);let M=this.parsePathSegments(o.path),k=M.filter((Te)=>Te.type==="parameter").map((Te)=>Te.paramName);if(o.constraints&&!Array.isArray(o.constraints)){let Te=o.constraints;for(let xe of M)if(xe.type==="parameter"&&xe.paramName&&Te[xe.paramName])xe.pattern=new RegExp(`^${Te[xe.paramName]}$`)}let L=this.calculateRoutePriority(M),V=M.filter((Te)=>Te.type==="static").length,pe=M.filter((Te)=>Te.type!=="static").length,he={route:o,segments:M,paramNames:k,priority:L,staticScore:V,dynamicScore:pe};return this.compiledRoutes.set(l,he),he}parsePathSegments(o){let l=[],M=o.split("/").filter((k)=>k.length>0);for(let k of M)if(k==="*")l.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(k))l.push({type:"wildcard",value:k,paramName:k.slice(1,k.indexOf("}"))});else if(k.startsWith("{")&&k.endsWith("}")){let L=k.slice(1,-1),[V,pe]=L.split(":");l.push({type:"parameter",value:k,paramName:V.replace("?",""),pattern:pe?new RegExp(`^${pe}$`):void 0,optional:L.endsWith("?")})}else if(k.includes("{")){let L=k.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(pe,he,Te)=>Te?`(${Te})`:"([^/]+)"),V=Array.from(k.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((pe)=>pe[1].replace("?",""));l.push({type:"parameter",value:k,paramName:V[0],pattern:new RegExp(`^${L}$`)})}else l.push({type:"static",value:k});return l}calculateRoutePriority(o){let l=0;for(let M=0;M<o.length;M++){let k=o[M],L=o.length-M;switch(k.type){case"static":l+=L*1000;break;case"parameter":if(k.pattern)l+=L*100;else l+=L*10;break;case"wildcard":l+=L*1;break}}return l}addRoute(o){let l=this.compileRoute(o);this.insertRoute(this.root,l,0);let M=this.methodTries.get(o.method);if(M)this.insertRoute(M,l,0)}insertRoute(o,l,M){if(M>=l.segments.length){o.addRoute(l.route.method,l);return}let k=l.segments[M];switch(k.type){case"static":if(!o.children.has(k.value))o.children.set(k.value,new qt);this.insertRoute(o.children.get(k.value),l,M+1);break;case"parameter":if(!o.paramChild)o.paramChild=new qt,o.paramChild.paramName=k.paramName,o.paramChild.pattern=k.pattern||null;this.insertRoute(o.paramChild,l,M+1);break;case"wildcard":if(!o.wildcardChild)o.wildcardChild=new qt,o.wildcardChild.paramName=k.paramName??null;this.insertRoute(o.wildcardChild,l,M+1);break}}match(o,l){let M=o.split("/").filter((L)=>L.length>0),k=this.methodTries.get(l);if(k){let L=this.matchSegments(k,M,0,{},l);if(L)return L}return this.matchSegments(this.root,M,0,{},l)}matchSegments(o,l,M,k,L){if(M>=l.length){let xe=o.getRoute(L);if(xe)return{route:xe.route,params:k,score:xe.priority};return null}let V=l[M],pe=o.children.get(V);if(pe){let xe=this.matchSegments(pe,l,M+1,k,L);if(xe)return xe}let he=o.paramChild,Te=he?.paramName?_t(V):V;if(he&&he.paramName&&(!he.pattern||he.pattern.test(Te))){let xe=k[he.paramName];k[he.paramName]=Te;let ve=this.matchSegments(he,l,M+1,k,L);if(ve)return ve;if(xe===void 0)delete k[he.paramName];else k[he.paramName]=xe}if(o.wildcardChild){let xe=o.wildcardChild.getRoute(L);if(xe)return k[o.wildcardChild.paramName??"wildcard"]=l.slice(M).map(_t).join("/"),{route:xe.route,params:k,score:xe.priority}}return null}getAllRoutes(){return Array.from(this.compiledRoutes.values())}removeRoute(o){let l=`${o.method}:${o.path}`;if(o.constraints&&!Array.isArray(o.constraints)){let M=o.constraints,L=Object.keys(M).sort().map((V)=>`${V}:${M[V]}`).join("|");l=`${o.method}:${o.path}#${L}`}this.compiledRoutes.delete(l)}clear(){this.root=new qt,this.compiledRoutes.clear();for(let[o]of this.methodTries)this.methodTries.set(o,new qt)}getStats(){let o={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let l of this.compiledRoutes.values()){let M=l.route.method;o.methodDistribution[M]=(o.methodDistribution[M]||0)+1}return o}countNodes(o){let l=1;for(let M of o.children.values())l+=this.countNodes(M);if(o.paramChild)l+=this.countNodes(o.paramChild);if(o.wildcardChild)l+=this.countNodes(o.wildcardChild);return l}}class Pr{trie;matchCache=new Map;routeKeys=new Set;stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}};options;constructor(o={}){this.options={enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0,enableProfiling:!1,...o},this.trie=new Vr}addRoute(o){if(this.options.precompilePatterns)this.precompileRoutePattern(o);let l=`${o.method}:${o.path}`;if(this.routeKeys.has(l))return!1;if(this.routeKeys.add(l),this.trie.addRoute(o),this.options.enableCaching)this.matchCache.clear();let M=o.method;return this.stats.methodDistribution[M]=(this.stats.methodDistribution[M]||0)+1,!0}patternCache=new Map;extractParamNames(o){let l=[],M=/\{([^}:]+)(?::[^}]+)?\}/g,k;while(k=M.exec(o))l.push(k[1].replace("?",""));return l}precompileRoutePattern(o){if(!o.pattern&&o.path.includes("{")){let l=o.path;if(o.constraints&&!Array.isArray(o.constraints)){let L=o.constraints,pe=Object.keys(L).sort().map((he)=>`${he}:${L[he]}`).join("|");l=`${o.path}#${pe}`}if(this.patternCache.has(l)){o.pattern=this.patternCache.get(l);return}let M=this.convertToURLPattern(o.path,o.constraints&&!Array.isArray(o.constraints)?o.constraints:void 0),k={exec:(L)=>{let V=L.pathname,pe=M.exec(V);if(!pe)return null;return{pathname:{groups:pe.groups||{}}}}};this.patternCache.set(l,k),o.pattern=k}}convertToURLPattern(o,l){let M=o,k=null,L=M.match(/\{([^{}/]+)\}\*$/);if(L)k=L[1],M=M.slice(0,L.index);else if(M.endsWith("*"))k="wildcard",M=M.slice(0,-1);let V=[],he=M.replace(/\{([^}]+)\}/g,(xe,ve)=>(V.push(ve),`\x00${V.length-1}\x00`)).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(he=he.replace(/\/?\u0000(\d+)\u0000/g,(xe,ve)=>{let Pe=V[Number(ve)],Ce=Pe.endsWith("?"),Ee=Ce?Pe.slice(0,-1):Pe,Me=Ee.indexOf(":"),Se=Me===-1?Ee:Ee.slice(0,Me),Oe=Me===-1?void 0:Ee.slice(Me+1),Fe=l?.[Se]??Oe??"[^/]+",Ut=`(?<${Se}>${Fe})`,lr=xe.startsWith("/")?"/":"";return Ce?`(?:${lr}${Ut})?`:`${lr}${Ut}`}),k!==null)he+=`(?<${k}>${l?.[k]??".+"})`;let Te=new RegExp(`^${he}$`);return{exec:(xe)=>{let ve=xe.match(Te);if(!ve)return null;return{groups:ve.groups||{}}}}}match(o,l){let M=this.options.enableProfiling?performance.now():0;this.stats.totalMatches++;let k;if(this.options.enableCaching){k=`${l}:${o}`;let pe=this.matchCache.get(k);if(pe!==void 0){if(this.stats.cacheHits++,M)this.updateMatchTime(M);return pe?{route:pe.route,params:{...pe.params}}:null}this.stats.cacheMisses++}let L=this.trie.match(o,l),V=null;if(L)V={route:L.route,params:L.params};if(k!==void 0)this.addToCache(k,V);if(M)this.updateMatchTime(M);return V?{route:V.route,params:{...V.params}}:null}addToCache(o,l){if(this.matchCache.size>=this.options.cacheSize){let M=this.matchCache.keys().next().value;if(M!==void 0)this.matchCache.delete(M)}this.matchCache.set(o,l)}updateMatchTime(o){let l=performance.now()-o;this.stats.averageMatchTime=(this.stats.averageMatchTime*(this.stats.totalMatches-1)+l)/this.stats.totalMatches}getCompiledRoutes(){let o=this.trie.getAllRoutes();if(this.options.enablePriorityOptimization)return o.sort((l,M)=>M.priority-l.priority);return o}getRoutesByMethod(){let o=new Map;for(let l of this.trie.getAllRoutes()){let M=l.route.method;if(!o.has(M))o.set(M,[]);o.get(M).push(l)}if(this.options.enablePriorityOptimization)for(let[l,M]of o)M.sort((k,L)=>L.priority-k.priority),o.set(l,M);return o}warmCache(o,l={}){if(!this.options.enableCaching&&!l.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let M=this.options.enableCaching;if(l.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(l.precompile)for(let{path:ve,method:Pe}of o){let Ce=`${Pe}:${ve}`;this.matchCache.delete(Ce)}let k=this.matchCache.size,L=this.stats.cacheHits,V=this.stats.totalMatches;for(let{path:ve,method:Pe}of o)if(this.match(ve,Pe),l.precompile)this.match(ve,Pe);let pe=this.matchCache.size-k,he=this.stats.cacheHits-L,Te=this.stats.totalMatches-V,xe=Te>0?he/Te:0;if(l.force&&!M)this.options.enableCaching=M;return{warmedPaths:pe,cacheSize:this.matchCache.size,hitRate:xe}}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 o=this.trie.getStats();return{...this.stats,trieDepth:o.averageDepth,methodDistribution:o.methodDistribution}}getCacheStats(){let o=this.stats.totalMatches>0?this.stats.cacheHits/this.stats.totalMatches:0;return{size:this.matchCache.size,maxSize:this.options.cacheSize,hitRate:o,enabled:this.options.enableCaching}}optimizeRouteOrder(o){if(!this.options.enablePriorityOptimization)return;this.matchCache.clear()}getRouteConflicts(){let o=[],l=this.trie.getAllRoutes(),M=new Map;for(let k of l){let L=k.route.method;if(!M.has(L))M.set(L,[]);M.get(L).push(k)}for(let[k,L]of M)for(let V=0;V<L.length;V++)for(let pe=V+1;pe<L.length;pe++){let he=L[V],Te=L[pe];if(this.routesConflict(he,Te)){let xe=this.getConflictSeverity(he,Te),ve=this.getConflictType(he,Te);o.push({routes:[he,Te],conflictType:ve,severity:xe})}}return o}routesConflict(o,l){if(o.route.path===l.route.path)return!0;if(o.route.method!==l.route.method)return!1;return this.patternsOverlap(o.segments,l.segments)}patternsOverlap(o,l){let M=o.some((pe)=>pe.optional||pe.type==="wildcard"),k=l.some((pe)=>pe.optional||pe.type==="wildcard");if(o.length!==l.length&&!M&&!k)return!1;let L=Math.max(o.length,l.length),V=!0;for(let pe=0;pe<L;pe++){let he=pe<o.length?o[pe]:null,Te=pe<l.length?l[pe]:null;if(!he&&Te&&!Te.optional)return!1;if(!Te&&he&&!he.optional)return!1;if(!he||!Te)continue;if(he.type==="static"&&Te.type==="static"){if(he.value!==Te.value)return!1}else if(he.type==="parameter"&&Te.type==="parameter"){if(he.pattern&&Te.pattern){if(he.pattern.toString()===Te.pattern.toString())V=!0}if(he.paramName===Te.paramName)V=!0}else if(he.type==="static"&&Te.type==="parameter"||he.type==="parameter"&&Te.type==="static"){let xe=he.type==="static"?he:Te,ve=he.type==="parameter"?he:Te;if(ve.pattern){if(!ve.pattern.test(xe.value))return!1}}else if(he.type==="wildcard"||Te.type==="wildcard")return!0}return V}getConflictSeverity(o,l){if(o.route.path===l.route.path)return"high";if(o.staticScore===l.staticScore)return"medium";return"low"}getConflictType(o,l){if(o.route.path===l.route.path)return"duplicate";if(this.hasAmbiguousParameters(o,l))return"ambiguous";if(Math.abs(o.priority-l.priority)<10)return"ambiguous";return"overlap"}hasAmbiguousParameters(o,l){if(Math.abs(o.segments.length-l.segments.length)>1)return!1;let M=o.segments.filter((L)=>L.type==="parameter").length,k=l.segments.filter((L)=>L.type==="parameter").length;if(M>0&&k>0){let L=Math.min(o.segments.length,l.segments.length),V=0;for(let pe=0;pe<L;pe++)if(o.segments[pe].type==="parameter"&&l.segments[pe].type==="parameter"){V++;let he=!!o.segments[pe].pattern,Te=!!l.segments[pe].pattern;if(he!==Te)return!0}return V>0&&V>=Math.min(M,k)/2}return!1}}function os(o){Object.defineProperties(o.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new Pr({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0})},writable:!0,configurable:!0},addRouteToCompiler:{value(l){this.initializeRouteCompiler(),this.routeCompiler.addRoute(l)},writable:!0,configurable:!0},matchRoute:{value(l,M,k,L=!1){if(this.initializeRouteCompiler(),k&&this.domains[k]){let V=this.fallbackMatchRoute(l,M,k,L);if(V)return V}else{let V=this.routeCompiler.match(l,M);if(V&&(!k||!V.route.domain||V.route.domain===k))return V;let pe=this.fallbackMatchRoute(l,M,k,L);if(pe)return pe}if(M==="HEAD")return this.matchRoute(l,"GET",k,L);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(l,M,k,L=!1){let V,pe=l;if(!L)V=new URL(l,"http://localhost"),pe=V.pathname;let he=`${k||""}:${M}:${pe}`;if(this.routeCache.has(he))return this.routeCache.get(he);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has(M)){let Pe=this.staticRoutes.get(M).get(pe);if(Pe&&(!k||!Pe.domain||Pe.domain===k)){let Ce={route:Pe,params:{}};return this.routeCache.set(he,Ce),Ce}}let xe=(k&&this.domains[k]?this.domains[k]:this.routes).filter((Pe)=>Pe.method===M);for(let Pe of xe)if(Pe.path===pe){let Ce={route:Pe,params:{}};return this.routeCache.set(he,Ce),Ce}for(let Pe of xe)if(Pe.pattern){let Ce=Pe.pattern.exec(V??=new URL(pe,"http://localhost"));if(Ce){let Ee={route:Pe,params:Ce.pathname.groups};return this.routeCache.set(he,Ee),Ee}}let ve=k&&this.domains[k]?[this.domains[k],this.routes]:[this.routes];for(let Pe of ve)for(let Ce of Pe){if(Ce.method!==M||!Ce.path.endsWith("*"))continue;let Ee=Ce.path.slice(0,-1);if(pe.startsWith(Ee)){let Me={route:Ce,params:{wildcard:pe.slice(Ee.length)}};return this.routeCache.set(he,Me),Me}}this.routeCache.set(he,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(l){this.initializeRouteCompiler(),this.routeCompiler.warmCache(l)},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 Pr({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0});for(let l of this.routes)this.routeCompiler.addRoute(l);for(let l of Object.values(this.domains))for(let M of l)this.routeCompiler.addRoute(M)},writable:!0,configurable:!0},optimizeRoutes:{value(l={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(l)},writable:!0,configurable:!0}})}function as(o){Object.defineProperties(o.prototype,{buildBunServeRoutes:{value(){let l={},M=new Map;for(let k of this.routes){if(!M.has(k.path))M.set(k.path,[]);M.get(k.path).push(k)}for(let[k,L]of M.entries())if(L.length===1){let V=L[0];if(typeof V.handler==="function"&&V.handler.toString().includes("new Response")&&!V.handler.toString().includes("await")&&V.middleware.length===0)try{let pe=this.enhanceRequest(new Request("https://example.com"),{}),he=V.handler(pe);if(he instanceof Response){l[k]=he;continue}}catch{}l[k]=async(pe)=>{let he=new URL(pe.url),Te={},xe=V.constraints&&!Array.isArray(V.constraints)?V.constraints:void 0;ft(k,he.pathname,Te,xe);let ve=this.enhanceRequest(pe,Te),Pe=async(Me,Se)=>await this.resolveHandler(V.handler,Me),Ce=[...this.globalMiddleware,...V.middleware,Pe],Ee=await this.runMiddleware(ve,Ce);return this.applyModifiedCookies(Ee??new Response("No response from middleware chain",{status:500}),ve)}}else{let V={};for(let pe of L){let he=pe.method;V[he]=async(Te)=>{let xe=new URL(Te.url),ve={},Pe=pe.constraints&&!Array.isArray(pe.constraints)?pe.constraints:void 0;ft(k,xe.pathname,ve,Pe);let Ce=this.enhanceRequest(Te,ve),Ee=async(Oe,Fe)=>await this.resolveHandler(pe.handler,Oe),Me=[...this.globalMiddleware,...pe.middleware,Ee],Se=await this.runMiddleware(Ce,Me);return this.applyModifiedCookies(Se??new Response("No response from middleware chain",{status:500}),Ce)}}l[k]=V}return l},writable:!0,configurable:!0},loadRoutes:{async value(){if(!this.config.routesPath)return;try{if(this.config.apiRoutesPath)try{let l=await import(this.config.apiRoutesPath);if(l.default&&Array.isArray(l.default))for(let M of l.default)this.registerRoute(M,"api")}catch(l){if(this.config.verbose)console.warn(`Failed to load API routes: ${l}`)}if(this.config.webRoutesPath)try{let l=await import(this.config.webRoutesPath);if(l.default&&Array.isArray(l.default))for(let M of l.default)this.registerRoute(M,"web")}catch(l){if(this.config.verbose)console.warn(`Failed to load Web routes: ${l}`)}}catch(l){console.error("Error loading routes:",l)}},writable:!0,configurable:!0},registerRoute:{value(l,M){let{path:k,method:L,handler:V,middleware:pe=[],name:he}=l;switch(L){case"GET":this.get(k,V,M,he,pe);break;case"POST":this.post(k,V,M,he,pe);break;case"PUT":this.put(k,V,M,he,pe);break;case"DELETE":this.delete(k,V,M,he,pe);break;case"PATCH":this.patch(k,V,M,he,pe);break;case"OPTIONS":this.options(k,V,M,he,pe);break;default:console.warn(`Unsupported HTTP method: ${L}`)}},writable:!0,configurable:!0}})}function us(o){Object.defineProperties(o.prototype,{matchRoute:{value(l,M,k){let L=new URL(l,"http://localhost"),V=`${k||""}:${M}:${L.pathname}`;if(this.routeCache.has(V))return this.routeCache.get(V);if(this.staticRoutes.has(M)){let xe=this.staticRoutes.get(M).get(L.pathname);if(xe&&(!k||!xe.domain||xe.domain===k)){let ve={route:xe,params:{}};return this.routeCache.set(V,ve),ve}}let pe=k&&this.domains[k]?this.domains[k]:this.routes,he=pe.filter((xe)=>xe.method===M);for(let xe of he)if(xe.path===L.pathname){let ve={route:xe,params:{}};return this.routeCache.set(V,ve),ve}for(let xe of he)if(xe.pattern){let ve=xe.pattern.exec(L);if(ve){let Pe={route:xe,params:ve.pathname.groups};return this.routeCache.set(V,Pe),Pe}}if(k&&this.domains[k]){let xe=this.domains[k].filter((ve)=>ve.method===M&&ve.path.endsWith("*"));for(let ve of xe){let Pe=ve.path.slice(0,-1);if(L.pathname.startsWith(Pe)){let Ce={route:ve,params:{wildcard:L.pathname.slice(Pe.length)}};return this.routeCache.set(V,Ce),Ce}}}let Te=this.routes.filter((xe)=>xe.method===M&&xe.path.endsWith("*")&&(!k||!xe.domain));for(let xe of Te){let ve=xe.path.slice(0,-1);if(L.pathname.startsWith(ve)){let Pe={route:xe,params:{wildcard:L.pathname.slice(ve.length)}};return this.routeCache.set(V,Pe),Pe}}if(M==="HEAD")return this.matchRoute(l,"GET",k);if(M==="OPTIONS"){let xe=pe.find((ve)=>ve.method==="OPTIONS"&&ve.path==="*");if(xe){let ve={route:xe,params:{}};return this.routeCache.set(V,ve),ve}for(let ve of["GET","POST","PUT","PATCH","DELETE"]){let Pe=this.matchRoute(l,ve,k);if(Pe){let Ce={route:{...Pe.route,method:"OPTIONS",handler:(Ee)=>new Response(null,{status:204})},params:Pe.params};return this.routeCache.set(V,Ce),Ce}}}return},writable:!0,configurable:!0},matchDomain:{value(l,M){if(l===M)return!0;if(l.startsWith("*.")){let k=l.substring(2);return M===k||M.endsWith(`.${k}`)}if(l.includes("{")){let k;if(!this.domainPatternCache.has(l)){let L=l.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");k=new RegExp(`^${L}$`),this.domainPatternCache.set(l,k)}else k=this.domainPatternCache.get(l);return k.test(M)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(l,M){let k={};if(!l.includes("{"))return k;let L=l.match(/\{([^}]+)\}/g)?.map((he)=>he.substring(1,he.length-1))||[],V=l.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),pe=M.match(new RegExp(`^${V}$`));if(pe&&pe.length>1)for(let he=0;he<L.length;he++)k[L[he]]=pe[he+1];return k},writable:!0,configurable:!0},pattern:{value(l,M){return this.patterns.set(l,M),this},writable:!0,configurable:!0},where:{value(l){let M=this.routes[this.routes.length-1];if(M){M.constraints={...M.constraints||{},...l};let k=M.path,L=M.constraints&&!Array.isArray(M.constraints)?M.constraints:void 0;if(M.pattern={exec:(V)=>{let pe={};if(!ft(k,V.pathname,pe,L))return null;return{pathname:{groups:pe}}}},this.routeCache.clear(),this.routeCompiler){let V=[...this.routes];this.routeCompiler.clear();for(let pe of V)this.routeCompiler.addRoute(pe)}}return this},writable:!0,configurable:!0},withoutNativeDispatch:{value(){let l=this.routes[this.routes.length-1];if(l)l.nativeDispatch=!1;return this},writable:!0,configurable:!0},whereNumber:{value(l){return this.where({[l]:"\\d+"})},writable:!0,configurable:!0},whereAlpha:{value(l){return this.where({[l]:"[A-Za-z]+"})},writable:!0,configurable:!0},whereAlphaNumeric:{value(l){return this.where({[l]:"[A-Za-z0-9]+"})},writable:!0,configurable:!0},whereUuid:{value(l){return this.where({[l]:"[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(l,M){return this.where({[l]:M.join("|")})},writable:!0,configurable:!0}})}var Ki=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,Xi=/bot|crawler|spider|crawling/i,Cr=new Map;function Jt(o){let l=o;if(!l._parsedURL)l._parsedURL=new URL(o.url);return l._parsedURL}function Bt(o){let l=o;if(!l._parsedCookies){let M={},k=o.headers.get("cookie");if(k)for(let L of k.split(";")){let V=L.indexOf("=");if(V===-1)continue;let pe=L.slice(0,V).trim();if(!pe)continue;let he=L.slice(V+1).trim();try{M[pe]=decodeURIComponent(he)}catch{M[pe]=he}}l._parsedCookies=M}return l._parsedCookies}class ds{macros=new Map;epoch=0;register(o,l,M=!1){this.macros.set(o,{name:o,handler:l,accessor:M}),this.epoch++}get(o){return this.macros.get(o)}has(o){return this.macros.has(o)}all(){return Array.from(this.macros.values())}remove(o){let l=this.macros.delete(o);if(l)this.epoch++;return l}clear(){this.macros.clear(),this.epoch++}getEpoch(){return this.epoch}}var or=new ds,cs=Symbol("bunRouterMacroProto"),Jr=Symbol("bunRouterMacroBase"),Mr=new WeakMap,ls=-1;class De{static macro(o,l){or.register(o,l)}static macroAccessor(o,l){or.register(o,l,!0)}static applyMacros(o){let l=or.getEpoch();if(l!==ls)Mr=new WeakMap,ls=l;let M=Object.getPrototypeOf(o)??Object.prototype;if(M[cs]){if(Mr.get(M[Jr])===M)return o;M=M[Jr]}let k=Mr.get(M);if(!k){k=Object.create(M);for(let L of or.all())if(L.accessor)Object.defineProperty(k,L.name,{get:L.handler,set(V){Object.defineProperty(this,L.name,{value:V,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else k[L.name]=L.handler;Object.defineProperty(k,cs,{value:!0}),Object.defineProperty(k,Jr,{value:M}),Mr.set(M,k)}return Object.setPrototypeOf(o,k),o}static hasMacro(o){return or.has(o)}}var ar={wantsJson(){let o=this.headers.get("accept")||"";return o.includes("application/json")||o.includes("json")},wantsHtml(){let o=this.headers.get("accept")||"";return o.includes("text/html")||o.includes("html")},wantsXml(){let o=this.headers.get("accept")||"";return o.includes("application/xml")||o.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 Ki.test(this.headers.get("user-agent")||"")},isBot(){return Xi.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 o=this.headers.get("x-forwarded-for");if(o)return o.split(",").map((l)=>l.trim());return[ar.ip.call(this)]},userAgent(){return this.headers.get("user-agent")||""},referer(){return this.headers.get("referer")||this.headers.get("referrer")||null},bearerToken(){let o=this.headers.get("authorization");if(o&&o.startsWith("Bearer "))return o.substring(7);return null},async rawBody(){if(typeof this._rawBody==="string")return this._rawBody;try{let o=await this.clone().text();return this._rawBody=o,o}catch{return""}},basicAuth(){let o=this.headers.get("authorization");if(o&&o.startsWith("Basic "))try{let l=atob(o.substring(6)),[M,k]=l.split(":");return{username:M,password:k}}catch{return null}return null},hasHeader(o){return this.headers.has(o.toLowerCase())},header(o,l){return this.headers.get(o.toLowerCase())||l||null},allHeaders(){let o={};return this.headers.forEach((l,M)=>{o[M]=l}),o},input(o,l){if(this.validated&&o in this.validated)return this.validated[o];if(this.query&&o in this.query)return this.query[o];if(this.params&&o in this.params)return this.params[o];if(this.jsonBody&&typeof this.jsonBody==="object"&&o in this.jsonBody)return this.jsonBody[o];if(this.formBody&&typeof this.formBody==="object"&&o in this.formBody)return this.formBody[o];return l},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(o){let l=this.all(),M={};return o.forEach((k)=>{if(k in l)M[k]=l[k]}),M},except(o){let l=this.all(),M={};return Object.keys(l).forEach((k)=>{if(!o.includes(k))M[k]=l[k]}),M},has(o){let l=this.all();return o in l&&l[o]!==void 0&&l[o]!==null&&l[o]!==""},hasAny(o){return o.some((l)=>this.has(l))},missing(o){return!this.has(o)},filled(o){let l=this.input(o);if(l===null||l===void 0)return!1;if(typeof l==="string")return l.trim().length>0;if(Array.isArray(l))return l.length>0;if(typeof l==="object")return Object.keys(l).length>0;return!0},getQuery(o,l){if(!o)return this.query||{};return this.query?.[o]||l},param(o,l){return this.params?.[o]||l},cookie(o,l){let M=Bt(this)[o];return M!==void 0?M:l||null},cookies(){return{...Bt(this)}},file(o){return this.files?.find((l)=>l.fieldName===o)},hasFile(o){return!!this.files?.find((l)=>l.fieldName===o)},path(){return Jt(this).pathname},fullUrl(){return this.url},root(){let o=Jt(this);return`${o.protocol}//${o.host}`},is(o){let l=this.path(),M=Cr.get(o);if(!M){let k=o.replace(/\*/g,".*").replace(/\?/g,".");if(M=new RegExp(`^${k}$`),Cr.size>=1000)Cr.clear();Cr.set(o,M)}return M.test(l)},route(){return this.routeName||null},fingerprint(){let o=Jt(this),l={method:this.method,path:o.pathname,query:o.search,ip:ar.ip.call(this)};return btoa(JSON.stringify(l))},signature(o){let l=`${this.method}${this.url}${ar.ip.call(this)}${o}`,M=0;for(let k=0;k<l.length;k++){let L=l.charCodeAt(k);M=(M<<5)-M+L,M=M&M}return Math.abs(M).toString(36)},merge(o){if(!this.validated)this.validated={};Object.assign(this.validated,o)},replace(o){this.validated={...o}},age(){let o=this.startTime||Date.now();return Date.now()-o},isFromTrustedProxy(o=[]){let l=ar.ip.call(this);return o.includes(l)},contentLength(){let o=this.headers.get("content-length");return o?Number.parseInt(o,10):0},contentType(){return this.headers.get("content-type")},isContentType(o){let l=this.contentType();return l?l.includes(o):!1}};function Qi(){Object.entries(ar).forEach(([o,l])=>{De.macro(o,l)})}Qi();function Er(o){let l=o;if(!l._parsedQuery){let M={};if(l._parsedURL||o.url.includes("?"))for(let[k,L]of Jt(o).searchParams){let V=M[k];if(V===void 0)M[k]=L;else if(Array.isArray(V))V.push(L);else M[k]=[V,L]}l._parsedQuery=M}return l._parsedQuery}class $e{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;_hasDomainRoutes=!1;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(o={}){this.routes=[],this.config={...this.config,...o},this.initializeDefaultMiddleware()}initializeDefaultMiddleware(){this.namedMiddleware.set("auth",()=>async(o,l)=>{if(!o.headers.get("authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return await l()}),this.namedMiddleware.set("throttle",(o)=>{let l=o?Wt(o):{maxAttempts:60,windowMs:60000};return Gt({maxAttempts:l.maxAttempts||60,windowMs:l.windowMs,keyGenerator:(M)=>M.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(o,l)=>{let M=await l();if(M)M.headers.set("Access-Control-Allow-Origin","*"),M.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),M.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return M})}middlewareGroup(o,l){let M=[];for(let k of l){let[L,V]=k.split(":"),pe=this.namedMiddleware.get(L);if(pe)M.push(pe(V))}return this.middlewareGroups.set(o,M),this}middlewareGroupRoutes(o){let l=this.middlewareGroups.get(o)||[];return new gs(this,l)}when(o){return new ps(this,o)}middleware(o){let[l,M]=o.split(":"),k=this.namedMiddleware.get(l);if(!k)throw Error(`Unknown middleware: ${l}`);let L=k(M);return new hs(this,[L])}getServer(){return this.serverInstance}extend(o){for(let[l,M]of Object.entries(o))if(typeof M==="function")this[l]=M.bind(this);return this}async register(o,l){let M=async()=>{await import(o)};if(l?.prefix||l?.middleware&&l.middleware.length>0)await this.group({prefix:l.prefix,middleware:l.middleware},M);else await M();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(o,l,M,k,L,V){let pe=l,he=[],Te=k||"web";if(this.currentGroup){if(this.currentGroup.prefix)pe=kt(this.currentGroup.prefix,l);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)he=[...this.currentGroup.middleware]}if(V&&V.length>0)for(let Ee of V){let Me=this.resolveMiddleware(Ee);if(Me)he.push(Me)}if(Te==="api"&&this.config.apiPrefix)pe=kt(this.config.apiPrefix,pe);else if(Te==="web"&&this.config.webPrefix)pe=kt(this.config.webPrefix,pe);let xe;if(this.currentDomain)xe=this.currentDomain;let ve={method:o.toUpperCase(),path:pe,handler:M,domain:xe,params:{},middleware:he},Pe=vr(pe),Ce={};if(Pe.forEach((Ee)=>{let Me=Ee.replace("?","");if(this.patterns.has(Me))Ce[Me]=this.patterns.get(Me)}),Object.keys(Ce).length>0)ve.constraints=Ce;if(ve.pattern={exec:(Ee)=>{let Me={},Se=ve.constraints&&!Array.isArray(ve.constraints)?ve.constraints:void 0;if(!ft(pe,Ee.pathname,Me,Se))return null;return{pathname:{groups:Me}}}},xe){if(!this.domains[xe])this.domains[xe]=[];this.domains[xe].push(ve)}else this.routes.push(ve);if(!pe.includes("{")&&!pe.includes("*")){if(!this.staticRoutes.has(o.toUpperCase()))this.staticRoutes.set(o.toUpperCase(),new Map);this.staticRoutes.get(o.toUpperCase()).set(pe,ve)}if(L)ve.name=L,this.namedRoutes.set(L,ve),At(L,ve.path);return this.routeCache.clear(),this}resolveMiddleware(o){if(typeof o==="function")return o;let[l,M]=o.split(":"),k=this.namedMiddleware.get(l);if(k)return k(M);return null}get(o,l,M,k,L){return this.registerRoute("GET",o,l,M,k,L)}post(o,l,M,k,L){return this.registerRoute("POST",o,l,M,k,L)}put(o,l,M,k,L){return this.registerRoute("PUT",o,l,M,k,L)}patch(o,l,M,k,L){return this.registerRoute("PATCH",o,l,M,k,L)}delete(o,l,M,k,L){return this.registerRoute("DELETE",o,l,M,k,L)}options(o,l,M,k,L){return this.registerRoute("OPTIONS",o,l,M,k,L)}match(o,l,M,k,L,V){for(let pe of o)this.registerRoute(pe,l,M,k,L,V);return this}any(o,l,M,k,L){for(let V of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.registerRoute(V,o,l,M,k,L);return this}fallback(o){return this.fallbackHandler=o,this}route(o,l={}){let M=this.namedRoutes.get(o);if(!M)throw Error(`Route with name "${o}" not found`);let k=M.path;for(let[L,V]of Object.entries(l))k=k.replace(`{${L}}`,encodeURIComponent(V)),k=k.replace(`{${L}?}`,encodeURIComponent(V));return k}onError(o){return this.errorHandler=o,this}redirect(o,l=302){let M=new Headers;return M.set("Location",o),new Response(null,{status:l,headers:M})}permanentRedirect(o){return this.redirect(o,301)}redirectRoute(o,l,M=302){return this.get(o,(k)=>this.redirect(l,M)),this}async serve(o){this.invalidateCache();let l={...o,fetch:this.handleRequest.bind(this),websocket:this.wsConfig};if(this.serverInstance=Bun.serve(l),this.config.verbose){let M=this.serverInstance.port,k=this.serverInstance.hostname;console.log(`
98
+ \uD83D\uDE80 Server running at http://${k}:${M}
99
+ `)}return this.serverInstance}async handleRequest(o){try{let l=new URL(o.url);if(this.config.verbose)console.log(`${o.method} ${l.pathname}`);if(o.method==="OPTIONS"){let pe=l.hostname||o.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(l.pathname,"OPTIONS",pe))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 M=l.hostname||o.headers.get("host")?.split(":")[0]||"localhost",k=this.matchRoute(l.pathname,o.method,M),L=this.enhanceRequest(o,k?.params||{});if(k){L.route=k.route;let pe=[...this.globalMiddleware];if(k.route.middleware&&k.route.middleware.length>0)pe.push(...k.route.middleware);let he=async(xe,ve)=>await this.resolveHandler(k.route.handler,xe);pe.push(he);let Te=await this.runMiddleware(L,pe);if(Te)return this.applyModifiedCookies(Te,L);return new Response("No response from middleware chain",{status:500})}let V=this.getAllowedMethods(l.pathname,M);if(V.length>0){let pe=async(he,Te)=>new Response(JSON.stringify({error:"Method Not Allowed",path:l.pathname,method:o.method,allowed:V}),{status:405,headers:{"Content-Type":"application/json",Allow:V.join(", ")}});if(this.globalMiddleware.length>0){let he=[...this.globalMiddleware,pe],Te=await this.runMiddleware(L,he);if(Te)return this.applyModifiedCookies(Te,L)}return pe(L,async()=>new Response(null))}if(this.globalMiddleware.length>0){let pe=async(xe,ve)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,L);return new Response(JSON.stringify({error:"Not Found",path:l.pathname,method:o.method}),{status:404,headers:{"Content-Type":"application/json"}})},he=[...this.globalMiddleware,pe],Te=await this.runMiddleware(L,he);if(Te)return this.applyModifiedCookies(Te,L)}if(this.fallbackHandler){let pe=await this.resolveHandler(this.fallbackHandler,L);return this.applyModifiedCookies(pe,L)}return new Response(JSON.stringify({error:"Not Found",path:l.pathname,method:o.method}),{status:404,headers:{"Content-Type":"application/json"}})}catch(l){if(console.error("Error handling request:",l),this.globalMiddleware.length>0){let M=this.enhanceRequest(o,{}),k=async(V,pe)=>{if(this.errorHandler)return this.errorHandler(l);return new Response(JSON.stringify({error:"Internal Server Error",message:l instanceof Error?l.message:String(l)}),{status:500,headers:{"Content-Type":"application/json"}})},L=[...this.globalMiddleware,k];try{let V=await this.runMiddleware(M,L);if(V)return V}catch{}}if(this.errorHandler)return this.errorHandler(l);return new Response(JSON.stringify({error:"Internal Server Error",message:l instanceof Error?l.message:String(l)}),{status:500,headers:{"Content-Type":"application/json"}})}}getAllowedMethods(o,l,M=!1){let k,L=o;if(!M)k=new URL(o,"http://localhost"),L=k.pathname;let V=`${l||""}:${L}`,pe=this._allowedMethodsCache.get(V);if(pe)return pe;let he=new Set;for(let[ve,Pe]of this.staticRoutes){let Ce=Pe.get(L);if(Ce&&(!l||!Ce.domain||Ce.domain===l))he.add(ve)}let Te=l&&this.domains[l]?this.domains[l]:this.routes;for(let ve of Te){if(he.has(ve.method))continue;if(ve.path===L){he.add(ve.method);continue}if(ve.pattern&&ve.pattern.exec(k??=new URL(L,"http://localhost"))){he.add(ve.method);continue}if(ve.path.endsWith("*")&&L.startsWith(ve.path.slice(0,-1)))he.add(ve.method)}if(he.has("GET"))he.add("HEAD");let xe=Array.from(he);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(V,xe),xe}matchRoute(o,l,M){let k=new URL(o,"http://localhost"),L=`${M||""}:${l}:${k.pathname}`;if(this.routeCache.has(L))return this.routeCache.get(L);if(this.staticRoutes.has(l)){let Te=this.staticRoutes.get(l).get(k.pathname);if(Te&&(!M||!Te.domain||Te.domain===M)){let xe={route:Te,params:{}};return this.routeCache.set(L,xe),xe}}let pe=(M&&this.domains[M]?this.domains[M]:this.routes).filter((Te)=>Te.method===l);for(let Te of pe)if(Te.path===k.pathname){let xe={route:Te,params:{}};return this.routeCache.set(L,xe),xe}for(let Te of pe)if(Te.pattern){let xe=Te.pattern.exec(k);if(xe){let ve={route:Te,params:xe.pathname.groups};return this.routeCache.set(L,ve),ve}}if(M&&this.domains[M]){let Te=this.domains[M].filter((xe)=>xe.method===l&&xe.path.endsWith("*"));for(let xe of Te){let ve=xe.path.slice(0,-1);if(k.pathname.startsWith(ve)){let Pe={route:xe,params:{wildcard:k.pathname.slice(ve.length)}};return this.routeCache.set(L,Pe),Pe}}}let he=this.routes.filter((Te)=>Te.method===l&&Te.path.endsWith("*")&&(!M||!Te.domain));for(let Te of he){let xe=Te.path.slice(0,-1);if(k.pathname.startsWith(xe)){let ve={route:Te,params:{wildcard:k.pathname.slice(xe.length)}};return this.routeCache.set(L,ve),ve}}if(l==="HEAD")return this.matchRoute(o,"GET",M);return}enhanceRequest(o,l={}){let M=null,k=()=>{if(M===null)M={},(o.headers.get("cookie")||"").split(";").forEach((Te)=>{let xe=Te.trim().split("=");if(xe.length>=2){let ve=xe[0].trim(),Pe=xe.slice(1).join("=").trim();M[ve]=decodeURIComponent(Pe)}});return M},L=Er(o),V={get url(){return o.url},get method(){return o.method},get headers(){return o.headers},get body(){return o.body},get bodyUsed(){return o.bodyUsed},get cache(){return o.cache},get credentials(){return o.credentials},get destination(){return o.destination},get integrity(){return o.integrity},get keepalive(){return o.keepalive},get mode(){return o.mode},get redirect(){return o.redirect},get referrer(){return o.referrer},get referrerPolicy(){return o.referrerPolicy},get signal(){return o.signal},arrayBuffer:()=>o.arrayBuffer(),blob:()=>o.blob(),clone:()=>o.clone(),formData:()=>o.formData(),json:()=>o.json(),text:()=>o.text(),params:l,query:L,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},pe=()=>{let he={};for(let[Te,xe]of Object.entries(L))he[Te]=xe;if(V.jsonBody&&typeof V.jsonBody==="object")for(let[Te,xe]of Object.entries(V.jsonBody))he[Te]=xe;if(V.formBody&&typeof V.formBody==="object")for(let[Te,xe]of Object.entries(V.formBody))he[Te]=xe;for(let[Te,xe]of Object.entries(l))he[Te]=xe;return he};return V.cookies=gr({read:k,write:(he,Te,xe)=>{V._cookiesToSet.push({name:he,value:Te,options:xe})},remove:(he,Te)=>{V._cookiesToDelete.push({name:he,options:Te})}}),V.get=(he,Te)=>{let ve=pe()[he];return ve!==void 0?ve:Te},V.input=(he,Te)=>{let ve=pe()[he];return ve!==void 0?ve:Te},V.all=()=>pe(),V.only=(he)=>{let Te=pe(),xe={};for(let ve of he)if(ve in Te)xe[ve]=Te[ve];return xe},V.except=(he)=>{let xe={...pe()};for(let ve of he)delete xe[ve];return xe},V.has=(he)=>{let Te=pe();if(Array.isArray(he))return he.every((xe)=>(xe in Te)&&Te[xe]!==void 0);return he in Te&&Te[he]!==void 0},V.hasAny=(he)=>{let Te=pe();return he.some((xe)=>(xe in Te)&&Te[xe]!==void 0)},V.filled=(he)=>{let Te=pe(),xe=(ve)=>{let Pe=Te[ve];return Pe!==void 0&&Pe!==null&&Pe!==""&&!(Array.isArray(Pe)&&Pe.length===0)};if(Array.isArray(he))return he.every(xe);return xe(he)},V.missing=(he)=>{let Te=pe();if(Array.isArray(he))return he.every((xe)=>!(xe in Te)||Te[xe]===void 0);return!(he in Te)||Te[he]===void 0},V.string=(he,Te="")=>{let ve=pe()[he];return ve!==void 0&&ve!==null?String(ve):Te},V.integer=(he,Te=0)=>{let ve=pe()[he],Pe=Number.parseInt(String(ve),10);return Number.isNaN(Pe)?Te:Pe},V.float=(he,Te=0)=>{let ve=pe()[he],Pe=Number.parseFloat(String(ve));return Number.isNaN(Pe)?Te:Pe},V.boolean=(he,Te=!1)=>{let ve=pe()[he];if(ve===void 0||ve===null)return Te;if(typeof ve==="boolean")return ve;if(ve==="true"||ve==="1"||ve===1)return!0;if(ve==="false"||ve==="0"||ve===0)return!1;return Te},V.array=(he)=>{let xe=pe()[he];if(Array.isArray(xe))return xe;return xe!==void 0&&xe!==null?[xe]:[]},V.bearerToken=()=>{let he=o.headers.get("authorization")||o.headers.get("Authorization")||"";if(he.startsWith("Bearer "))return he.substring(7);return null},V.header=(he)=>o.headers.get(he)||o.headers.get(he.toLowerCase())||null,V.cookie=(he,Te)=>{let xe=k()[he];return xe!==void 0?xe:Te??null},V.getParam=(he,Te)=>{let xe=l?.[he];return xe!==void 0?xe:Te},V.getParamAsInt=(he)=>{let Te=l?.[he];if(Te===void 0||Te.trim()==="")return null;let xe=Number(Te);return Number.isSafeInteger(xe)?xe:null},V.params=l||{},V}applyModifiedCookies(o,l){let M=new Response(o.body,{status:o.status,statusText:o.statusText,headers:o.headers});if(l._cookiesToSet&&l._cookiesToSet.length>0)for(let{name:k,value:L,options:V}of l._cookiesToSet){let pe=this.serializeCookie(k,L,V);M.headers.append("Set-Cookie",pe)}if(l._cookiesToDelete&&l._cookiesToDelete.length>0)for(let{name:k,options:L}of l._cookiesToDelete){let V={...L,expires:new Date(0),maxAge:0},pe=this.serializeCookie(k,"",V);M.headers.append("Set-Cookie",pe)}return M}serializeCookie(o,l,M={}){let k=`${encodeURIComponent(o)}=${encodeURIComponent(l)}`;if(M.maxAge!==void 0)k+=`; Max-Age=${M.maxAge}`;if(M.expires&&M.expires instanceof Date)k+=`; Expires=${M.expires.toUTCString()}`;if(M.path)k+=`; Path=${M.path}`;else k+="; Path=/";if(M.domain)k+=`; Domain=${M.domain}`;if(M.secure)k+="; Secure";if(M.httpOnly)k+="; HttpOnly";if(M.sameSite){let L=M.sameSite.toLowerCase();k+=`; SameSite=${L.charAt(0).toUpperCase()+L.slice(1)}`}return k}buildMiddlewareChain(o){if(o.length===0)return async(M)=>null;let l=async(M)=>null;for(let M=o.length-1;M>=0;M--){let k=o[M],L=l;l=async(V)=>k(V,async()=>await L(V)||new Response(null,{status:200}))}return l}async runMiddleware(o,l){if(l.length===0)return null;try{return await this.buildMiddlewareChain(l)(o)}catch(M){if(this.errorHandler)return this.errorHandler(M);throw M}}async resolveHandler(o,l){if(typeof o==="function"&&!o.prototype?.handle)return await o(l);if(typeof o==="function"&&o.prototype?.handle)return await new o().handle(l);if(o&&typeof o.handle==="function")return await o.handle(l);throw Error(`Invalid action handler: ${typeof o}`)}use(...o){for(let l of o){let M=this.resolveMiddleware(l);if(M)this.globalMiddleware.push(M)}return this}group(o,l){let M=this.currentGroup;if(this.currentGroup={prefix:o.prefix||"",middleware:[]},o.middleware){for(let L of o.middleware)if(typeof L==="function")this.currentGroup.middleware.push(L)}let k=l();if(k instanceof Promise)return k.then(()=>(this.currentGroup=M,this),(L)=>{throw this.currentGroup=M,L});return this.currentGroup=M,this}addRoute(o){if(this.routes.push(o),o.name)this.namedRoutes.set(o.name,o),At(o.name,o.path);return this}registerMiddlewareDependency(o){if(this._middlewarePipeline)this._middlewarePipeline.registerDependency(o);return this}registerMiddlewareSkipConditions(o,l){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(o,l,M){if(o.length===0)return M();let k=0,L=async()=>{if(k>=o.length)return M();let V=o[k++];return await V(l,L)||new Response("No response from middleware",{status:500})};return L()}}class ps{router;condition;constructor(o,l){this.router=o;this.condition=l}middleware(o){let[l,M]=o.split(":"),k=this.router.namedMiddleware.get(l);if(!k)throw Error(`Unknown middleware: ${l}`);let L=k(M);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[L]}),this}}class hs{router;middleware;constructor(o,l){this.router=o;this.middleware=l}get(o,l){return this}post(o,l){return this}put(o,l){return this}delete(o,l){return this}}class gs{router;middleware;constructor(o,l){this.router=o;this.middleware=l}get(o,l){return this}post(o,l){return this}put(o,l){return this}delete(o,l){return this}}var Kr=null;function Zi(){if(Kr===null)Kr=new $e;return Kr}function Yi(o,l={}){if(typeof o.bearerToken==="function")return o;return Zi().enhanceRequest(o,l)}function eo(o){let l;if(o.startsWith("http://"))l=7;else if(o.startsWith("https://"))l=8;else{let V=o.indexOf("://");l=V===-1?0:V+3}let M=o.indexOf("/",l);if(M===-1)return"/";let k=o.indexOf("?",M);if(k!==-1)return o.slice(M,k);let L=o.indexOf("#",M);return L===-1?o.slice(M):o.slice(M,L)}async function ms(o,l,M){let k;try{k=await l}catch(L){if(!o.errorHandler)throw L;k=await o.errorHandler(L)}return k?o.applyModifiedCookies(k,M):new Response("No response from middleware chain",{status:500})}function fs(o,l,M){console.error("Error handling request:",M);let k=o.errorHandler?o.errorHandler(M):new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:M instanceof Error?M.message:String(M)}),{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"}});return k instanceof Promise?k.then((L)=>$t(L,l,o.config.compression)):$t(k,l,o.config.compression)}function to(o,l){let{router:M,route:k,isWildcard:L}=o,V=l.params??{};if(L){let he=new URL(l.url).pathname,Te=k.path==="*"?"/":k.path.slice(0,-1);V={...V,wildcard:he.slice(Te.length)}}let pe;try{pe=M._dispatchMatchedRoute(k,l,V)}catch(he){return fs(M,l,he)}return pe instanceof Promise?pe.then((he)=>$t(he,l,M.config.compression),(he)=>fs(M,l,he)):$t(pe,l,M.config.compression)}if(!De.hasMacro("getParam"))De.macro("getParam",function(o,l){let M=this.params?.[o];return M!==void 0?M:l});if(!De.hasMacro("getParamAsInt"))De.macro("getParamAsInt",function(o){let l=this.params?.[o];if(l===void 0||l.trim()==="")return null;let M=Number(l);return Number.isSafeInteger(M)?M:null});if(!De.hasMacro("get"))De.macro("get",function(o,l){let M=Jt(this).searchParams.get(o);return M!==null&&M!==void 0?M:l});De.macroAccessor("query",function(){return Er(this)});De.macroAccessor("cookies",function(){let o=this,l=()=>({...Bt(o)});for(let[M,k]of Object.entries(Bt(o)))Object.defineProperty(l,M,{value:k,writable:!0,enumerable:!0,configurable:!0});return l.get=(M)=>Bt(o)[M],l.set=(M,k,L={})=>{if(!o._cookiesToSet)o._cookiesToSet=[];o._cookiesToSet.push({name:M,value:k,options:L})},l.delete=(M,k={})=>{if(!o._cookiesToDelete)o._cookiesToDelete=[];o._cookiesToDelete.push({name:M,options:k})},l.getAll=()=>({...Bt(o)}),Object.defineProperty(o,"cookies",{value:l,writable:!0,configurable:!0,enumerable:!0}),l});function Rs(o){Object.defineProperties(o.prototype,{serve:{async value(l={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let M={idleTimeout:255,...l,fetch:this.handleRequest.bind(this)},k={};if(this.staticResponses&&this.staticResponses.size>0)for(let[L,V]of this.staticResponses)k[L]=V;if(l.static)Object.assign(k,l.static);if(Object.keys(k).length>0)M.static=k;if(l.development!==void 0)M.development=l.development;if(this._nativeRoutesEnabled=l.nativeRoutes===!0,this._nativeRoutesEnabled){let L=this._buildNativeRoutes();if(L)M.routes=L}if(this.wsConfig)M.websocket=this.wsConfig;if(this.serverInstance=Bun.serve(M),this.config.verbose){let L=this.serverInstance.port,V=this.serverInstance.hostname;console.log(`
100
+ \uD83D\uDE80 Server running at http://${V}:${L}
101
+ `)}return this.serverInstance},writable:!0,configurable:!0},reload:{async value(){if(!this.serverInstance)throw Error("Server not started, cannot reload");this.invalidateCache();let l=this.serverInstance.port,M=this.serverInstance.hostname;this.serverInstance.stop();let k={port:l,hostname:M,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0};if(this._nativeRoutesEnabled){let L=this._buildNativeRoutes();if(L)k.routes=L}if(this.serverInstance=Bun.serve(k),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${M}:${l}`)},writable:!0,configurable:!0},handleRequest:{async value(l){let M=this,k=await Fr(l,()=>M.handleRequestImpl(l));return $t(k,l,M.config?.compression)},writable:!0,configurable:!0},_dispatchMatchedRoute:{value(l,M,k){let L=this.enhanceRequest(M,k);fr(L),L.route=l;let V=l,pe=this._mwEpoch||0,he=V.middleware?V.middleware.length:0,Te=this.globalMiddleware.length,xe=V._compiledChain;if(!xe||V._chainEpoch!==pe||V._chainMwLen!==he){let ve=ts(V.handler,this.config);if(he===0&&Te===0)xe=ve;else{let Pe=he>0?[...this.globalMiddleware,...V.middleware]:[...this.globalMiddleware];Pe.push((Ce,Ee)=>ve(Ce)),xe=this.buildMiddlewareChain(Pe)}V._compiledChain=xe,V._chainEpoch=pe,V._chainMwLen=he}try{let ve=xe(L);if(he!==0||Te!==0)return ms(this,ve,L);if(ve instanceof Promise)return ms(this,ve,L);return ve?this.applyModifiedCookies(ve,L):new Response("No response from middleware chain",{status:500})}catch(ve){if(!this.errorHandler)throw ve;let Pe=this.errorHandler(ve);return Pe instanceof Promise?Pe.then((Ce)=>this.applyModifiedCookies(Ce,L)):this.applyModifiedCookies(Pe,L)}},writable:!0,configurable:!0},_buildNativeRoutes:{value(){let l=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),M=(he)=>{if(he==="*")return"/*";let Te=he.split("/"),xe=[];for(let ve=0;ve<Te.length;ve++){let Pe=Te[ve];if(Pe===""){xe.push(Pe);continue}if(Pe==="*")return ve===Te.length-1?[...xe,"*"].join("/"):null;let Ce=Pe.match(/^\{([A-Z_$][\w$]*)\}$/i);if(Ce){xe.push(`:${Ce[1]}`);continue}if(Pe.includes("{")||Pe.includes(":")||Pe.includes("*"))return null;xe.push(Pe)}return xe.join("/")},k=this,L=(he,Te)=>{let xe={router:k,route:he,isWildcard:Te};return(ve)=>Ur(ve,to,xe,ve)},V={},pe=new Map;for(let he of this.routes){if(!l.has(he.method))continue;if(he.nativeDispatch===!1)continue;if(he.constraints&&Object.keys(he.constraints).length>0)continue;if(he.handler instanceof Response)continue;let Te=M(he.path);if(!Te)continue;let xe=Te.replace(/:[^/]+/g,":p"),ve=pe.get(xe);if(ve&&ve!==Te)continue;pe.set(xe,Te);let Pe=V[Te]??={};if(Pe[he.method])continue;Pe[he.method]=L(he,he.path.endsWith("*"))}for(let he of Object.values(V))if(he.GET&&!he.HEAD)he.HEAD=he.GET;return Object.keys(V).length>0?V:null},writable:!0,configurable:!0},handleRequestImpl:{async value(l){try{let M,k="localhost";if(this._hasDomainRoutes){let xe=new URL(l.url);l._parsedURL=xe,M=xe.pathname,k=xe.hostname||l.headers.get("host")?.split(":")[0]||"localhost"}else M=eo(l.url);let L=this.matchRoute(M,l.method,k,!0);if(l.method==="OPTIONS"&&!L){let xe=l.headers.get("origin"),ve={"Access-Control-Allow-Origin":xe||"*","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(xe)ve["Access-Control-Allow-Credentials"]="true",ve.Vary="Origin";return new Response(null,{status:204,headers:ve})}if(L){let xe=this._dispatchMatchedRoute(L.route,l,L.params);return xe instanceof Promise?await xe:xe}let V=this.enhanceRequest(l,{});fr(V);let pe=this.getAllowedMethods(M,k,!0),he={"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(pe.length>0){let xe=(ve,Pe)=>new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:M,method:l.method,allowed:pe}),{status:405,headers:{...he,Allow:pe.join(", ")}});if(this.globalMiddleware.length>0){let ve=[...this.globalMiddleware,xe],Pe=await this.runMiddleware(V,ve);if(Pe)return this.applyModifiedCookies(Pe,V)}return xe(V,async()=>null)}if(this.fallbackHandler){let xe=await this.resolveHandler(this.fallbackHandler,V);return this.applyModifiedCookies(xe,V)}let Te=(xe,ve)=>new Response(JSON.stringify({success:!1,message:"Not Found",path:M,method:l.method}),{status:404,headers:he});if(this.globalMiddleware.length>0){let xe=[...this.globalMiddleware,Te],ve=await this.runMiddleware(V,xe);if(ve)return this.applyModifiedCookies(ve,V)}return Te(V,async()=>null)}catch(M){if(console.error("Error handling request:",M),this.errorHandler)return this.errorHandler(M);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:M instanceof Error?M.message:String(M)}),{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(l,M={}){let k=l;if("params"in l)Object.defineProperty(k,"params",{value:M,writable:!0,configurable:!0,enumerable:!0});else k.params=M;return De.applyMacros(k),k},writable:!0,configurable:!0},applyModifiedCookies:{value(l,M){let k=M._cookiesToSet&&M._cookiesToSet.length>0,L=M._cookiesToDelete&&M._cookiesToDelete.length>0;if(!k&&!L)return l;let V=new Response(l.body,{status:l.status,statusText:l.statusText,headers:l.headers});if(M._cookiesToSet&&M._cookiesToSet.length>0)for(let{name:pe,value:he,options:Te}of M._cookiesToSet){let xe=this.serializeCookie(pe,he,Te);V.headers.append("Set-Cookie",xe)}if(M._cookiesToDelete&&M._cookiesToDelete.length>0)for(let{name:pe,options:he}of M._cookiesToDelete){let Te={...he,expires:new Date(0),maxAge:0},xe=this.serializeCookie(pe,"",Te);V.headers.append("Set-Cookie",xe)}return V},writable:!0,configurable:!0},serializeCookie:{value(l,M,k={}){let L=`${encodeURIComponent(l)}=${encodeURIComponent(M)}`;if(k.maxAge!==void 0)L+=`; Max-Age=${k.maxAge}`;if(k.expires&&k.expires instanceof Date)L+=`; Expires=${k.expires.toUTCString()}`;if(k.path)L+=`; Path=${k.path}`;else L+="; Path=/";if(k.domain)L+=`; Domain=${k.domain}`;if(k.secure)L+="; Secure";if(k.httpOnly)L+="; HttpOnly";if(k.sameSite){let V=k.sameSite.toLowerCase();L+=`; SameSite=${V.charAt(0).toUpperCase()+V.slice(1)}`}return L},writable:!0,configurable:!0}})}import{join as ro}from"path";function ys(o){Object.defineProperties(o.prototype,{renderView:{async value(l,M={},k={}){let L=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},V=`${l}:${k.layout||""}`;if(L.cache&&this.templateCache.has(V))return this.processTemplate(this.templateCache.get(V),M,L);let pe=await Gr(l,L.viewsPath,L.extensions);if(!pe)throw Error(`View '${l}' not found`);let he=await Bun.file(pe).text(),Te=k.layout||L.defaultLayout;if(Te){let xe=await Gr(ro("layouts",Te),L.viewsPath,L.extensions);if(!xe)throw Error(`Layout '${Te}' not found`);he=(await Bun.file(xe).text()).replace(/\{\{\s*content\s*\}\}/g,he)}if(L.cache)this.templateCache.set(V,he);return this.processTemplate(he,M,L)},writable:!0,configurable:!0},processTemplate:{async value(l,M,k){if((k?.engine||"auto")==="custom"&&k?.customRenderer)return k.customRenderer(l,M,{});let V=Vn(l,M);if(k?.minify?.enabled)try{let pe=k.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};V=V.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(pe){console.error("Error minifying HTML:",pe)}return V},writable:!0,configurable:!0},view:{value(l,M,k={},L={},V="web",pe){let he,Te={},xe={},ve="web",Pe;if(typeof M==="string"){if(he=M,typeof k==="object"&&!Array.isArray(k))if("layout"in k||"status"in k||"headers"in k)xe=k;else Te=k;if(typeof L==="object")xe={...xe,...L};else if(typeof L==="string")ve=L;if(typeof V==="string")if(V==="web"||V==="api")ve=V;else Pe=V;if(pe)Pe=pe}else{if(Te=M,typeof k==="string")he=k;else throw TypeError("View name must be a string");if(typeof L==="object")xe=L;else if(typeof L==="string")if(L==="web"||L==="api")ve=L;else he=L,ve="web"}let Ce=async(Ee)=>{let Me=await this.renderView(he,Te,{layout:xe.layout}),Se=this.config?.queryPreservation;if(Se?.enabled!==!1&&Se?.preserve?.length)Me=Rr(Me,Se);let Oe=new Headers;if(Oe.set("Content-Type","text/html; charset=utf-8"),xe.headers)for(let[Fe,Ut]of Object.entries(xe.headers))Oe.set(Fe,Ut);return new Response(Me,{status:xe.status||200,headers:Oe})};return this.get(l,Ce,ve,Pe),this},writable:!0,configurable:!0}})}function ws(o){Object.defineProperties(o.prototype,{websocket:{value(l){return this.wsConfig=l,this},writable:!0,configurable:!0},publish:{value(l,M,k=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(l,M,k)},writable:!0,configurable:!0},subscriberCount:{value(l){if(!this.serverInstance)throw Error("Server not started, cannot get subscriber count");return this.serverInstance.subscriberCount(l)},writable:!0,configurable:!0},upgrade:{value(l,M){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(l,M)},writable:!0,configurable:!0},timeout:{value(l,M){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(l,M)},writable:!0,configurable:!0},requestIP:{value(l){if(!this.serverInstance)throw Error("Server not started, cannot get request IP");return this.serverInstance.requestIP(l)},writable:!0,configurable:!0}})}import no from"process";class bs{macros=new Map;register(o,l){this.macros.set(o,{name:o,handler:l})}get(o){return this.macros.get(o)}has(o){return this.macros.has(o)}all(){return Array.from(this.macros.values())}remove(o){return this.macros.delete(o)}clear(){this.macros.clear()}}var Xr=new bs;class ur extends Response{static macro(o,l){Xr.register(o,l),Response[o]=l}static callMacro(o,...l){let M=Xr.get(o);if(!M)throw Error(`Response macro "${o}" not found`);return M.handler(...l)}static hasMacro(o){return Xr.has(o)}}function Sr(o,l){if(typeof o==="number")return{status:o,mergedHeaders:l};if(o&&typeof o==="object"){let M=typeof o.status==="number"?o.status:200,k=l;if(o.headers)if(k={},o.headers instanceof Headers)o.headers.forEach((L,V)=>{k[V]=L});else if(Array.isArray(o.headers))for(let[L,V]of o.headers)k[L]=V;else Object.assign(k,o.headers);return{status:M,mergedHeaders:k}}return{status:200,mergedHeaders:l}}var yt={success:(o,l,M=200)=>{let k={};if(o!==void 0)k.data=o;if(l!==void 0)k.message=l;return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})},error:(o,l,M=400)=>{let k={error:o};if(l!==void 0)k.errors=l;return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})},validationError:(o,l="Validation failed")=>yt.error(l,o,422),notFound:(o="Resource not found")=>yt.error(o,void 0,404),unauthorized:(o="Unauthorized")=>yt.error(o,void 0,401),forbidden:(o="Forbidden")=>yt.error(o,void 0,403),serverError:(o="Internal server error")=>yt.error(o,void 0,500),created:(o,l="Resource created successfully")=>yt.success(o,l,201),updated:(o,l="Resource updated successfully")=>yt.success(o,l,200),deleted:(o="Resource deleted successfully")=>yt.success(null,o,200),noContent:()=>new Response(null,{status:204}),accepted:(o,l="Request accepted")=>yt.success(o,l,202),paginated:(o,l,M)=>{let k=Math.ceil(l.total/l.per_page),L=(l.current_page-1)*l.per_page+1,V=Math.min(L+l.per_page-1,l.total),pe={data:o,message:M,meta:{current_page:l.current_page,per_page:l.per_page,total:l.total,last_page:k,from:L,to:V,path:l.path,first_page_url:`${l.path}?page=1`,last_page_url:`${l.path}?page=${k}`,next_page_url:l.current_page<k?`${l.path}?page=${l.current_page+1}`:void 0,prev_page_url:l.current_page>1?`${l.path}?page=${l.current_page-1}`:void 0}};return new Response(JSON.stringify(pe),{status:200,headers:{"Content-Type":"application/json"}})},json:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Sr(l,M);return new Response(JSON.stringify(o),{status:k,headers:{"Content-Type":"application/json",...L}})},html:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Sr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/html",...L}})},text:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Sr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/plain",...L}})},xml:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Sr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"application/xml",...L}})},redirect:(o,l=302)=>new Response(null,{status:l,headers:{Location:o}}),permanentRedirect:(o)=>yt.redirect(o,301),download:(o,l,M="application/octet-stream")=>new Response(o,{status:200,headers:{"Content-Type":M,"Content-Disposition":`attachment; filename="${l}"`}}),stream:(o,l="application/octet-stream",M={})=>new Response(o,{status:200,headers:{"Content-Type":l,...M}}),cache:(o,l=3600,M=!0,k)=>{let V={"Content-Type":"application/json","Cache-Control":M?`public, max-age=${l}`:`private, max-age=${l}`};if(k)V.ETag=k;return new Response(JSON.stringify(o),{status:200,headers:V})},cors:(o,l="*",M="GET,POST,PUT,DELETE,OPTIONS",k="Content-Type,Authorization")=>new Response(JSON.stringify(o),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":l,"Access-Control-Allow-Methods":M,"Access-Control-Allow-Headers":k}}),sse:(o,l,M)=>{let k="";if(M)k+=`id: ${M}
102
+ `;if(l)k+=`event: ${l}
103
+ `;return k+=`data: ${o}
104
104
 
105
- `,new Response(M,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(i="healthy",c={})=>{let P=i==="healthy"?200:i==="degraded"?200:503,M={status:i,timestamp:new Date().toISOString(),checks:c,uptime:to.uptime?.()||0};return new Response(JSON.stringify(M),{status:P,headers:{"Content-Type":"application/json"}})}};function ro(){Object.entries(gt).forEach(([i,c])=>{nr.macro(i,c)})}ro();var no=/^[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,so={required:{name:"required",validate:(i)=>{if(i===null||i===void 0)return!1;if(typeof i==="string")return i.trim().length>0;if(Array.isArray(i))return i.length>0;if(typeof i==="object")return Object.keys(i).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(i)=>typeof i==="string",message:"The :field field must be a string."},number:{name:"number",validate:(i)=>typeof i==="number"&&!Number.isNaN(i),message:"The :field field must be a number."},integer:{name:"integer",validate:(i)=>Number.isInteger(Number(i)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(i)=>typeof i==="boolean"||i==="true"||i==="false"||i==="1"||i==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(i)=>typeof i==="string"&&no.test(i),message:"The :field field must be a valid email address."},url:{name:"url",validate:(i)=>{try{let c=new URL(i);return Boolean(c)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(i,c)=>{let P=Number(c[0]);if(typeof i==="string")return i.length>=P;if(typeof i==="number")return i>=P;if(Array.isArray(i))return i.length>=P;return!1},message:(i,c)=>`The ${i} field must be at least ${c[0]} characters.`},max:{name:"max",validate:(i,c)=>{let P=Number(c[0]);if(typeof i==="string")return i.length<=P;if(typeof i==="number")return i<=P;if(Array.isArray(i))return i.length<=P;return!1},message:(i,c)=>`The ${i} field must not exceed ${c[0]} characters.`},between:{name:"between",validate:(i,c)=>{let P=Number(c[0]),M=Number(c[1]);if(typeof i==="string")return i.length>=P&&i.length<=M;if(typeof i==="number")return i>=P&&i<=M;if(Array.isArray(i))return i.length>=P&&i.length<=M;return!1},message:(i,c)=>`The ${i} field must be between ${c[0]} and ${c[1]}.`},in:{name:"in",validate:(i,c)=>c.includes(String(i)),message:(i,c)=>`The ${i} field must be one of: ${c.join(", ")}.`},notIn:{name:"not_in",validate:(i,c)=>!c.includes(String(i)),message:(i,c)=>`The ${i} field must not be one of: ${c.join(", ")}.`},regex:{name:"regex",validate:(i,c)=>{let P=new RegExp(c[0]);return typeof i==="string"&&P.test(i)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(i)=>typeof i==="string"&&/^[a-z]+$/i.test(i),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(i)=>typeof i==="string"&&/^[a-z0-9]+$/i.test(i),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(i)=>typeof i==="string"&&/^[\w-]+$/.test(i),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(i)=>{let c=new Date(i);return!Number.isNaN(c.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(i,c)=>{let P=new Date(i),M=new Date(c[0]);return!Number.isNaN(P.getTime())&&!Number.isNaN(M.getTime())&&P>M},message:(i,c)=>`The ${i} field must be after ${c[0]}.`},dateBefore:{name:"before",validate:(i,c)=>{let P=new Date(i),M=new Date(c[0]);return!Number.isNaN(P.getTime())&&!Number.isNaN(M.getTime())&&P<M},message:(i,c)=>`The ${i} field must be before ${c[0]}.`},confirmed:{name:"confirmed",validate:(i,c,P,M)=>{let U=c[0]||`${P}_confirmation`;return i===M[U]},message:"The :field confirmation does not match."},same:{name:"same",validate:(i,c,P,M)=>i===M[c[0]],message:(i,c)=>`The ${i} field must match ${c[0]}.`},different:{name:"different",validate:(i,c,P,M)=>i!==M[c[0]],message:(i,c)=>`The ${i} field must be different from ${c[0]}.`},json:{name:"json",validate:(i)=>{try{return JSON.parse(i),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(i)=>typeof i==="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(i),message:"The :field field must be a valid UUID."},array:{name:"array",validate:(i)=>Array.isArray(i),message:"The :field field must be an array."},object:{name:"object",validate:(i)=>typeof i==="object"&&i!==null&&!Array.isArray(i),message:"The :field field must be an object."}},Tu={unique:{name:"unique",validate:async(i,c)=>(console.warn('Database validation rule "unique" requires external implementation'),!0),message:"The :field field must be unique."},exists:{name:"exists",validate:async(i,c)=>(console.warn('Database validation rule "exists" requires external implementation'),!0),message:"The selected :field is invalid."}};class Pr{rules={};config;constructor(i={}){this.config={stopOnFirstFailure:!1,bail:!1,...i},this.registerRules(so)}registerRule(i){this.rules[i.name]=i}registerRules(i){Object.values(i).forEach((c)=>this.registerRule(c))}parseRuleString(i){return i.split("|").map((c)=>{let[P,...M]=c.split(":"),U=M.length>0?M.join(":").split(","):[];return{name:P.trim(),parameters:U}})}async validate(i,c){let P={};for(let[M,U]of Object.entries(c)){let z=[],de=this.getNestedValue(i,M),pe=typeof U==="string"?this.parseRuleString(U):U.map((Re)=>({name:Re.name,parameters:[]}));for(let{name:Re,parameters:Te}of pe){let xe=this.rules[Re];if(!xe){console.warn(`Validation rule "${Re}" not found`);continue}try{if(!await xe.validate(de,Te,M,i)){let Ce=this.formatErrorMessage(xe,M,Te);if(z.push(Ce),this.config.stopOnFirstFailure||this.config.bail)break}}catch(ve){console.error(`Error validating rule "${Re}" for field "${M}":`,ve),z.push(`Validation error for ${M}`)}}if(z.length>0)P[M]=z}return P}async validateOrFail(i,c){let P=await this.validate(i,c);if(Object.keys(P).length>0)throw new u("Validation failed",P)}getNestedValue(i,c){return c.split(".").reduce((P,M)=>P&&P[M]!==void 0?P[M]:void 0,i)}formatErrorMessage(i,c,P){let M=this.config.customMessages?.[`${c}.${i.name}`]||this.config.customMessages?.[i.name];if(M)return this.replacePlaceholders(M,c,P);let U=typeof i.message==="function"?i.message(c,P):i.message;return this.replacePlaceholders(U,c,P)}replacePlaceholders(i,c,P){let M=this.config.customAttributes?.[c]||c.replace(/_/g," ");return i.replace(/:field/g,M).replace(/:attribute/g,M).replace(/:value/g,P[0]||"").replace(/:other/g,P[1]||"")}}var xu=new Pr;function Mr(i,c){let P=new Pr(c);return async(M,U)=>{try{let z={...M.query,...M.params,...M.jsonBody||{},...M.formBody||{}};return await P.validateOrFail(z,i),M.validated=z,await U()}catch(z){if(z instanceof u)throw z;throw new u("Validation error occurred")}}}class Vr{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(i){return this.rules.push(`min:${i}`),this}max(i){return this.rules.push(`max:${i}`),this}between(i,c){return this.rules.push(`between:${i},${c}`),this}in(...i){return this.rules.push(`in:${i.join(",")}`),this}notIn(...i){return this.rules.push(`not_in:${i.join(",")}`),this}regex(i){return this.rules.push(`regex:${i}`),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(i){return this.rules.push(`after:${i}`),this}before(i){return this.rules.push(`before:${i}`),this}confirmed(i){return this.rules.push(i?`confirmed:${i}`:"confirmed"),this}same(i){return this.rules.push(`same:${i}`),this}different(i){return this.rules.push(`different:${i}`),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(i,c){return this.rules.push(c?`unique:${i},${c}`:`unique:${i}`),this}exists(i,c){return this.rules.push(c?`exists:${i},${c}`:`exists:${i}`),this}custom(i,...c){return this.rules.push(c.length>0?`${i}:${c.join(",")}`:i),this}build(){return this.rules.join("|")}}function vu(){return new Vr}var Cu={rules(i){let c={};for(let[P,M]of Object.entries(i))c[P]=M instanceof Vr?M.build():M;return c},async validateValue(i,c,P="value"){return(await new Pr().validate({[P]:i},{[P]:c}))[P]||[]},async passes(i,c){return(await this.validateValue(i,c)).length===0},async fails(i,c){return!await this.passes(i,c)}};class at{method;path;handler;validationRules;validatorConfig;constructor(i,c,P){this.method=i;this.path=c;this.handler=P}validate(i,c){return this.validationRules=i,this.validatorConfig=c,this}build(){let i=[];if(this.validationRules)i.push(Mr(this.validationRules,this.validatorConfig));return i.push(async(c,P)=>($e.applyMacros(c),await P()||new Response("Not Found",{status:404}))),{method:this.method,path:this.path,handler:this.handler,middleware:i.length>0?i:void 0}}}class fs{routes=[];get(i,c){return new at("GET",i,c)}post(i,c){return new at("POST",i,c)}put(i,c){return new at("PUT",i,c)}patch(i,c){return new at("PATCH",i,c)}delete(i,c){return new at("DELETE",i,c)}register(i){let c=i.build();this.routes.push(c)}getRoutes(){return this.routes}}function Jr(){return async(i,c)=>($e.applyMacros(i),i.startTime=Date.now(),await c())}class Rs{rules={};config={};field(i,c){return this.rules[i]=c,this}fields(i){return Object.assign(this.rules,i),this}configure(i){return Object.assign(this.config,i),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(i){return this.config.customMessages=i,this}attributes(i){return this.config.customAttributes=i,this}build(){return Mr(this.rules,this.config)}}function ku(){return new Rs}var Hu={validated:(i,c,P,M,U)=>new at(i,c,P).validate(M,U),apiRoute:(i,c,P,M)=>{let U=new at(i,c,async(z)=>{if(!z.expectsJson())return nr.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return await P(z)});if(M)U.validate(M);return U},resourceRoute:(i,c,P)=>{let M=[];if(c.index)M.push(new at("GET",i,c.index));if(c.show)M.push(new at("GET",`${i}/{id}`,c.show));if(c.store){let U=new at("POST",i,c.store);if(P?.store)U.validate(P.store);M.push(U)}if(c.update){let U=new at("PUT",`${i}/{id}`,c.update);if(P?.update)U.validate(P.update);M.push(U)}if(c.destroy)M.push(new at("DELETE",`${i}/{id}`,c.destroy));return M}};function Au(){return new fs}var ms={compose:(...i)=>async(c,P)=>{let M=0,U=async()=>{if(M>=i.length)return await P();let z=i[M++];return await z(c,U)};return await U()},when:(i,c)=>async(P,M)=>{if(i(P))return await c(P,M);return await M()},unless:(i,c)=>ms.when((P)=>!i(P),c),group:(i)=>ms.compose(...i)},qu={api:()=>[Jr(),async(i,c)=>{try{let P=await c(),M=new Headers(P.headers);return M.set("X-API-Version","1.0"),M.set("X-Response-Time",new Date().toISOString()),new Response(P.body,{status:P.status,statusText:P.statusText,headers:M})}catch(P){return console.error(P),nr.callMacro("error","Internal server error",void 0,500)}}],web:()=>[Jr(),async(i,c)=>(i.session={},await c())],validation:(i,c)=>[Jr(),Mr(i,c)]};Jn(Oe);Kn(Oe);ss(Oe);rs(Oe);Zn(Oe);ps(Oe);hs(Oe);Mn(Oe);Vn(Oe);ds(Oe);ns(Oe);ts(Oe);Pn(Oe);Tn(Oe);class Kr{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(i,c){return this.groups.set(i,[...c]),this}extend(i,c){let P=this.groups.get(i)||[];return this.groups.set(i,[...P,...c]),this}prepend(i,c){let P=this.groups.get(i)||[];return this.groups.set(i,[...c,...P]),this}get(i){return this.groups.get(i)||[]}has(i){return this.groups.has(i)}remove(i){return this.groups.delete(i),this}resolve(i){if(typeof i==="function")return[i];if(this.groups.has(i))return this.get(i);return[i]}resolveAll(i){let c=[];for(let P of i)c.push(...this.resolve(P));return c}pushGlobal(...i){return this.globalMiddleware.push(...i),this}prependGlobal(...i){return this.globalMiddleware.unshift(...i),this}removeGlobal(i){return this.globalMiddleware=this.globalMiddleware.filter((c)=>typeof c==="string"?c!==i:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(i,c){return this.middlewarePriority.set(i,c),this}sortByPriority(i){return[...i].sort((c,P)=>{let M=typeof c==="string"?c.split(":")[0]:"",U=typeof P==="string"?P.split(":")[0]:"",z=this.middlewarePriority.get(M)??100,de=this.middlewarePriority.get(U)??100;return z-de})}filter(i,c){if(c.only&&c.only.length>0)return i.filter((P)=>{if(typeof P==="string"){let M=P.split(":")[0];return c.only.includes(M)}return!1});if(c.except&&c.except.length>0)return i.filter((P)=>{if(typeof P==="string"){let M=P.split(":")[0];return!c.except.includes(M)}return!0});return i}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var ut=new Kr;ut.define("web",["session","csrf","cors"]);ut.define("api",["throttle:60,1","cors"]);ut.setPriority("session",10);ut.setPriority("cors",20);ut.setPriority("csrf",30);ut.setPriority("auth",40);ut.setPriority("throttle",50);ut.setPriority("role",60);ut.setPriority("permission",60);ut.setPriority("can",70);ut.setPriority("abilities",70);ut.setPriority("verified",80);import{mock as Xr}from"bun:test";class mt{request;url;constructor(i,c,P={}){if(this.url=new URL(c,"http://localhost:3000"),P.query)Object.entries(P.query).forEach(([M,U])=>{if(Array.isArray(U))U.forEach((z)=>this.url.searchParams.append(M,z));else this.url.searchParams.set(M,U)});this.request={method:i,url:this.url.toString(),headers:new Headers(P.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:P.body&&typeof P.body==="object"?P.body:void 0,files:P.files?this.convertTestFiles(P.files):void 0,session:P.session,user:P.user,context:P.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:()=>"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:Ut(P.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody(P.body)}parseQuery(i){let c={};for(let[P,M]of i.entries())if(c[P])if(Array.isArray(c[P]))c[P].push(M);else c[P]=[c[P],M];else c[P]=M;return c}convertTestFiles(i){return i.map((c)=>({fieldName:c.fieldName,originalName:c.filename,filename:`test-${Date.now()}-${c.filename}`,path:`/tmp/test-uploads/${c.filename}`,size:c.content instanceof ArrayBuffer?c.content.byteLength:new TextEncoder().encode(c.content.toString()).length,mimetype:c.mimetype||"application/octet-stream",buffer:c.content instanceof ArrayBuffer?c.content:new TextEncoder().encode(c.content.toString()).buffer}))}handleBody(i){if(!i)return;let c=this.request.headers?.get("content-type")||"";if(c.includes("application/json")||typeof i==="object"){if(this.request.jsonBody=i,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(c.includes("application/x-www-form-urlencoded"))this.request.formBody=i}params(i){return this.request.params={...this.request.params,...i},this}headers(i){return Object.entries(i).forEach(([c,P])=>{this.request.headers?.set(c,P)}),this}auth(i,c="Bearer"){return this.request.headers?.set("Authorization",`${c} ${i}`),this}user(i){return this.request.user=i,this}session(i){return this.request.session=i,this}cookies(i){let c=this.request.cookies?.getAll()||{};return this.request.cookies=Ut({...c,...i}),this}context(i){return this.request.context={...this.request.context,...i},this}json(i){return this.request.jsonBody=i,this.request.headers?.set("content-type","application/json"),this}form(i){return this.request.formBody=i,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(i){return this.request.files=this.convertTestFiles(i),this.request.headers?.set("content-type","multipart/form-data"),this}ip(i){return this.request.ip=()=>i,this}userAgent(i){return this.request.userAgent=()=>i,this.request.headers?.set("User-Agent",i),this}csrf(i){return this.request.csrfToken=i,this.request.headers?.set("X-CSRF-Token",i),this}build(){let i={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)i.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let M=new FormData;Object.entries(this.request.formBody).forEach(([U,z])=>{M.append(U,z)}),i.body=M}let c=new Request(this.url.toString(),i);return Object.assign(c,{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 oc={get:(i,c)=>new mt("GET",i,c),post:(i,c)=>new mt("POST",i,c),put:(i,c)=>new mt("PUT",i,c),patch:(i,c)=>new mt("PATCH",i,c),delete:(i,c)=>new mt("DELETE",i,c),options:(i,c)=>new mt("OPTIONS",i,c),head:(i,c)=>new mt("HEAD",i,c)};function De(i="GET",c="/",P={}){return new mt(i,c,P).build()}class sr{request;constructor(i){this.request=i||De()}as(i){return this.request.user=i,this}withJWT(i,c="Bearer"){let P=new Headers(this.request.headers);return P.set("Authorization",`${c} ${i}`),this.request={...this.request,headers:P},this}withSession(i){return this.request.session=i,this}withApiKey(i,c="X-API-Key"){let P=new Headers(this.request.headers);return P.set(c,i),this.request={...this.request,headers:P},this}withBasicAuth(i,c){let P=btoa(`${i}:${c}`),M=new Headers(this.request.headers);return M.set("Authorization",`Basic ${P}`),this.request={...this.request,headers:M},this}withAuthCookies(i){let c=this.request.cookies?.getAll()||{};return this.request.cookies=Ut({...c,...i}),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 Qr{options;constructor(i={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...i}}generateToken(i={}){let c={alg:this.options.algorithm,typ:"JWT",...this.options.headers},P=Math.floor(Date.now()/1000),M=P+this.parseExpiresIn(this.options.expiresIn||"1h"),U={iat:P,exp:M,...this.options.payload,...i},z=btoa(JSON.stringify(c)).replace(/=/g,""),de=btoa(JSON.stringify(U)).replace(/=/g,""),pe=btoa(`${z}.${de}.${this.options.secret}`).replace(/=/g,"");return`${z}.${de}.${pe}`}generateExpiredToken(i={}){let c={alg:this.options.algorithm,typ:"JWT"},P=Math.floor(Date.now()/1000),M={iat:P-7200,exp:P-3600,...i},U=btoa(JSON.stringify(c)).replace(/=/g,""),z=btoa(JSON.stringify(M)).replace(/=/g,""),de=btoa(`${U}.${z}.${this.options.secret}`).replace(/=/g,"");return`${U}.${z}.${de}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(i){let[c,P,M]=i.split(".");return{header:JSON.parse(atob(c)),payload:JSON.parse(atob(P)),signature:M}}parseExpiresIn(i){let c=i.match(/^(\d+)([smhd])$/);if(!c)return 3600;let P=Number.parseInt(c[1]);switch(c[2]){case"s":return P;case"m":return P*60;case"h":return P*3600;case"d":return P*86400;default:return 3600}}}class Zr{options;constructor(i={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...i}}createSession(i={}){let c={...this.options.data,...i},P=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:c,cookie:P}}generateSessionCookie(i="session"){let c=[];if(this.options.maxAge)c.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)c.push("Secure");if(this.options.httpOnly)c.push("HttpOnly");let P=c.length>0?`; ${c.join("; ")}`:"";return`${i}=${this.options.sessionId}${P}`}createExpiredSession(){let i={...this.options,maxAge:-1};return new Zr(i).createSession()}}var dc={user:(i={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...i}),adminUser:(i={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...i}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(i)=>Xr(async(c,P)=>{if(i)return c.user=i,await P();return new Response("Unauthorized",{status:401})}),roleMiddleware:(i)=>Xr(async(c,P)=>{if(!c.user)return new Response("Unauthorized",{status:401});let M=c.user.roles||[];if(!i.some((z)=>M.includes(z)))return new Response("Forbidden",{status:403});return await P()}),permissionMiddleware:(i)=>Xr(async(c,P)=>{if(!c.user)return new Response("Unauthorized",{status:401});let M=c.user.permissions||[];if(!i.every((z)=>M.includes(z)))return new Response("Forbidden",{status:403});return await P()})},pc={authenticatedRequest:(i,c)=>new sr(c).as(i).getRequest(),jwtRequest:(i={},c)=>{let M=new Qr().generateToken(i);return new sr(c).withJWT(M).getRequest()},sessionRequest:(i={},c)=>new sr(c).withSession(i).getRequest(),verifyJWTStructure:(i)=>{let c=i.split(".");return c.length===3&&c.every((P)=>P.length>0)},extractJWTPayload:(i)=>{try{let[,c]=i.split(".");return JSON.parse(atob(c))}catch{return null}}};function hc(i){return new sr(i)}function gc(i){return new Qr(i)}function mc(i){return new Zr(i)}import{mock as Ot}from"bun:test";class Ht{request;files;constructor(i){this.request=i||De(),this.files=[]}addFile(i){let c={fieldName:i.fieldName,originalName:i.filename,filename:`test-${Date.now()}-${i.filename}`,path:`/tmp/test-uploads/${i.filename}`,size:i.content instanceof ArrayBuffer?i.content.byteLength:new TextEncoder().encode(i.content.toString()).length,mimetype:i.mimetype||this.detectMimeType(i.filename),buffer:i.content instanceof ArrayBuffer?i.content:new TextEncoder().encode(i.content.toString()).buffer};return this.files.push(c),this.request.files=[...this.request.files||[],c],this}addFiles(i){return i.forEach((c)=>this.addFile(c)),this}addImage(i,c="test.jpg",P=1024){let M=new ArrayBuffer(P);return this.addFile({fieldName:i,filename:c,content:M,mimetype:"image/jpeg"})}addDocument(i,c="test.pdf",P="Test PDF content"){return this.addFile({fieldName:i,filename:c,content:P,mimetype:"application/pdf"})}addTextFile(i,c="test.txt",P="Test content"){return this.addFile({fieldName:i,filename:c,content:P,mimetype:"text/plain"})}addLargeFile(i,c=10){let P=c*1024*1024,M=new ArrayBuffer(P);return this.addFile({fieldName:i,filename:`large-file-${c}mb.bin`,content:M,mimetype:"application/octet-stream"})}addInvalidFile(i,c="malicious.exe"){return this.addFile({fieldName:i,filename:c,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(i){return this.request.formBody={...this.request.formBody,...i},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(i){let c=i.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"}[c||""]||"application/octet-stream"}}class Yr{static testFileSize(i,c){return i.size<=c}static testFileType(i,c){return c.includes(i.mimetype)}static testFileExtension(i,c){let P=i.originalName.split(".").pop()?.toLowerCase();return P?c.includes(P):!1}static testFilename(i){let c=i.originalName;if(c.includes("..")||c.includes("/")||c.includes("\\"))return!1;if(c.includes("\x00"))return!1;let P=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],M=c.split(".")[0].toUpperCase();if(P.includes(M))return!1;return!0}static testImageFile(i){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(i.mimetype)}static testDocumentFile(i){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(i.mimetype)}}var wc={validationMiddleware:(i={})=>Ot(async(P,M)=>{let U=P.files||[],{maxSize:z=5242880,allowedTypes:de=[],maxFiles:pe=10}=i;if(U.length>pe)return new Response(`Too many files. Maximum ${pe} allowed.`,{status:400});for(let Re of U){if(Re.size>z)return new Response(`File ${Re.originalName} is too large. Maximum size: ${z} bytes.`,{status:400});if(de.length>0&&!de.includes(Re.mimetype))return new Response(`File type ${Re.mimetype} not allowed.`,{status:400});if(!Yr.testFilename(Re))return new Response(`Invalid filename: ${Re.originalName}`,{status:400})}return await M()}),imageUploadMiddleware:(i={})=>Ot(async(P,M)=>{let U=P.files||[],{maxSize:z=2097152}=i;for(let de of U){if(!Yr.testImageFile(de))return new Response(`File ${de.originalName} is not a valid image.`,{status:400});if(de.size>z)return new Response(`Image ${de.originalName} is too large.`,{status:400})}return await M()}),storageService:{store:Ot(async(i,c)=>c||`/uploads/${Date.now()}-${i.filename}`),delete:Ot(async(i)=>{}),exists:Ot(async(i)=>!i.includes("not-found")),getUrl:Ot((i)=>`https://example.com/storage${i}`)},virusScanner:{scan:Ot(async(i)=>{if(i.originalName.endsWith(".exe")||i.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},bc={singleFileUpload:()=>new Ht().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"}),multipleFileUpload:()=>new Ht().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"}),fileSizeExceeded:()=>new Ht().addLargeFile("file",50),invalidFileType:()=>new Ht().addInvalidFile("file","virus.exe"),emptyFileUpload:()=>new Ht().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"}),maliciousFilename:()=>new Ht().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})},Tc={hasFiles:(i,c)=>{let P=i.files||[];if(c!==void 0&&P.length!==c)throw Error(`Expected ${c} files, but got ${P.length}`);if(P.length===0)throw Error("Expected request to have files")},hasFileWithField:(i,c)=>{if(!(i.files||[]).some((U)=>U.fieldName===c))throw Error(`Expected file with field name '${c}'`)},fileMatches:(i,c)=>{Object.entries(c).forEach(([P,M])=>{if(i[P]!==M)throw Error(`Expected file.${P} to be '${M}', got '${i[P]}'`)})},fileSizeWithinLimit:(i,c)=>{if(i.size>c)throw Error(`File size ${i.size} exceeds limit of ${c}`)},fileTypeAllowed:(i,c)=>{if(!c.includes(i.mimetype))throw Error(`File type '${i.mimetype}' is not allowed. Allowed types: ${c.join(", ")}`)}};function xc(i){return new Ht(i)}var vc={image:(i="image",c="test.jpg")=>({fieldName:i,filename:c,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(i="document",c="test.pdf")=>({fieldName:i,filename:c,content:"PDF content",mimetype:"application/pdf"}),text:(i="file",c="test.txt",P="Test content")=>({fieldName:i,filename:c,content:P,mimetype:"text/plain"}),large:(i="file",c=10)=>({fieldName:i,filename:`large-${c}mb.bin`,content:new ArrayBuffer(c*1024*1024),mimetype:"application/octet-stream"}),malicious:(i="file")=>({fieldName:i,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as Ie,spyOn as io}from"bun:test";class ys{middleware;context;constructor(i){this.middleware=i,this.context=this.createContext()}createContext(){let i=De(),c=Ie(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:i,next:c}}withRequest(i){return this.context.request=i,this}withNext(i){return this.context.next=Ie(i),this}withError(i){return this.context.error=i,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(i){throw this.context.error=i,i}}expectNextCalled(i=1){if(this.context.next.mock.calls.length!==i)throw Error(`Expected next to be called ${i} 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(i){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(i&&this.context.error.message!==i)throw Error(`Expected error message "${i}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function Ec(i){return new ys(i)}var Sc={passthrough:()=>Ie(async(i,c)=>await c()),response:(i=200,c)=>Ie(async()=>new Response(c?JSON.stringify(c):null,{status:i})),error:(i="Middleware error")=>Ie(async()=>{throw Error(i)}),modifyRequest:(i)=>Ie(async(c,P)=>(i(c),await P())),addContext:(i,c)=>Ie(async(P,M)=>(P.context=P.context||{},P.context[i]=c,await M())),auth:(i)=>Ie(async(c,P)=>{if(i)return c.user=i,await P();else return new Response("Unauthorized",{status:401})}),rateLimit:(i=!1)=>Ie(async(c,P)=>{if(i)return new Response("Too Many Requests",{status:429});return await P()}),cors:(i="*")=>Ie(async(c,P)=>{let M=await P();if(M)M.headers.set("Access-Control-Allow-Origin",i);return M})};class ws{middlewares;request;finalHandler;constructor(i){this.middlewares=i,this.request=De(),this.finalHandler=Ie(async()=>new Response("Final handler",{status:200}))}withRequest(i){return this.request=i,this}withFinalHandler(i){return this.finalHandler=Ie(i),this}async execute(){let i=0,c=async()=>{if(i<this.middlewares.length){let P=this.middlewares[i++];return await P(this.request,c)}else return await this.finalHandler()};return await c()}getExecutionOrder(){return this.middlewares.map((i,c)=>c)}}function kc(i){return new ws(i)}function Hc(i){return io(i,"call")}function Ac(){let i=Ie(async(c,P)=>await P());return{middleware:i,spy:i}}async function qc(i,c=1000){let P=[],M=De(),U=Ie(async()=>new Response("OK"));for(let Te=0;Te<c;Te++){let xe=performance.now();await i(M,U);let ve=performance.now();P.push(ve-xe)}let z=P.reduce((Te,xe)=>Te+xe,0),de=z/c,pe=Math.min(...P),Re=Math.max(...P);return{averageTime:de,minTime:pe,maxTime:Re,totalTime:z}}import{mock as Et}from"bun:test";class oo{id;attributes;constructor(i={}){this.id=i.id,this.attributes=i}static modelName="GenericMockModel";static async find(i){return null}static async findOrFail(i){throw Error("Not implemented")}static async where(i){return[]}static async create(i){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class ao{id;email;name;constructor(i={id:1}){this.id=i.id,this.email=i.email||"test@example.com",this.name=i.name||"Test User"}static async find(i){return null}static async findOrFail(i){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class uo{id;title;content;userId;constructor(i={id:1}){this.id=i.id,this.title=i.title||"Test Post",this.content=i.content||"Test content",this.userId=i.userId||1}static async find(i){return null}static async findOrFail(i){throw Error("Not implemented")}async belongsTo(i){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class bs{request;options;constructor(i={}){this.options=i,this.request=De()}withRequest(i){return this.request=i,this}withParams(i){return this.request.params={...this.request.params,...i},this}withModel(i){return this.options.modelClass=i,this}withRouteKey(i){return this.options.routeKey=i,this}withConstraints(i){return this.options.constraints=i,this}withResolver(i){return this.options.customResolver=i,this}async testResolution(i){if(this.options.customResolver)return await this.options.customResolver(i);if(this.options.modelClass)return new this.options.modelClass({id:i});return{id:i}}async testNotFound(i){try{throw await this.testResolution(i),Error("Expected model not found error")}catch(c){if(c instanceof Error&&c.message!=="Model not found")throw c}}getRequest(){return this.request}}var Dc={createModel:(i,c={})=>class P{id;attributes;constructor(M={}){this.id=M.id,this.attributes={...c,...M}}static modelName=i;static async find(M){if(M==="not-found")return null;return new P({id:M,...c})}static async findOrFail(M){let U=await this.find(M);if(!U)throw Error("Model not found");return U}static async where(M){return[new P({id:1,...c,...M})]}static async create(M){return new P({id:Date.now(),...M})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}},User:class i{id;email;name;constructor(c={id:1}){this.id=c.id,this.email=c.email||"test@example.com",this.name=c.name||"Test User"}static async find(c){if(c==="not-found")return null;return new i({id:Number.parseInt(c)})}static async findOrFail(c){let P=await this.find(c);if(!P)throw Error("User not found");return P}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class i{id;title;content;userId;constructor(c={id:1}){this.id=c.id,this.title=c.title||"Test Post",this.content=c.content||"Test content",this.userId=c.userId||1}static async find(c){if(c==="not-found")return null;return new i({id:Number.parseInt(c)})}static async findOrFail(c){let P=await this.find(c);if(!P)throw Error("Post not found");return P}async belongsTo(c){return this.userId===c}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},Nc={belongsTo:(i="userId")=>Et(async(P,M)=>{if(!M.user)return!1;return P[i]===M.user.id}),belongsToUser:()=>Et(async(c,P)=>{if(!P.user)return!1;return c.userId===P.user.id}),published:()=>Et(async(c)=>c.published===!0||c.status==="published"),visible:()=>Et(async(c)=>c.visible!==!1&&c.hidden!==!0),custom:(i)=>Et(i),combine:(...i)=>Et(async(P,M)=>{for(let U of i)if(!await U(P,M))return!1;return!0})};class Ts{resolvers=new Map;register(i,c){return this.resolvers.set(i,Et(c)),this}registerModel(i,c){let P=Et(async(M)=>{if(c.find){let U=await c.find(M);if(!U)throw Error(`${c.name||"Model"} not found`);return U}return new c({id:M})});return this.resolvers.set(i,P),this}async resolve(i,c){let P=this.resolvers.get(i);if(!P)throw Error(`No resolver registered for key: ${i}`);return await P(c)}async testAll(i="1"){let c={};for(let[P,M]of this.resolvers)try{c[P]=await M(i)}catch(U){c[P]={error:U instanceof Error?U.message:"Unknown error"}}return c}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var Fc={testRoute:async(i,c,P)=>{let M=De("GET",i);M.params=c;for(let[U,z]of Object.entries(P))M.context=M.context||{},M.context[U]=z;return M},createHandler:(i)=>Et(async(P)=>{let M=P.context||{};for(let U of i)if(!M[U])return new Response(`Model ${U} not found`,{status:404});return new Response(JSON.stringify({params:P.params,models:Object.fromEntries(i.map((U)=>[U,M[U]]))}),{headers:{"Content-Type":"application/json"}})}),testBindingMiddleware:(i)=>Et(async(P,M)=>{P.context=P.context||{};for(let[U,z]of Object.entries(i)){let de=P.params[U];if(de)try{if(typeof z==="function")P.context[U]=await z(de);else P.context[U]=z}catch(pe){return console.error(`Error resolving model ${U}:`,pe),new Response(`${U} not found`,{status:404})}}return await M()})};function Uc(i){return new bs(i)}function Ic(){return new Ts}var co=async(i,c)=>i.userId===c.id,_c={testUserScoped:async(i,c,P=co)=>await P(i,c),testRoleAccess:async(i,c,P)=>{if(!c.roles)return!1;return P.some((M)=>c.roles.includes(M))},testPermissionAccess:async(i,c,P)=>{if(!c.permissions)return!1;return P.every((M)=>c.permissions.includes(M))}};import{mock as lo}from"bun:test";import $t from"process";class vs{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(i){return this.metrics.push(i),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((c,P)=>c+P.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let i=this.metrics.map((P)=>P.memoryUsage.heapUsed),c=this.metrics.map((P)=>P.memoryUsage.rss);return{averageHeapUsed:i.reduce((P,M)=>P+M,0)/i.length,maxHeapUsed:Math.max(...i),averageRSS:c.reduce((P,M)=>P+M,0)/c.length,maxRSS:Math.max(...c)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class Wt{client;config;constructor(i,c){this.client=i,this.config=c}async run(i,c="GET",P={}){let M={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},U=[],z=new Map,de=Date.now(),pe=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),Re=[];for(let ve=0;ve<pe;ve++){let Ce=this.makeRequest(i,c,P).then((Me)=>{U.push(Me),M.successfulRequests++}).catch((Me)=>{let Pe=Me instanceof Error?Me.message:"Unknown error";z.set(Pe,(z.get(Pe)||0)+1),M.failedRequests++});if(Re.push(Ce),this.config.requestsPerSecond){let Me=1000/this.config.requestsPerSecond;await new Promise((Pe)=>setTimeout(Pe,Me))}if(Re.length>=this.config.concurrency)await Promise.race(Re),Re.filter((Pe)=>Pe.then(()=>!0).catch(()=>!0)).forEach((Pe)=>{let Ee=Re.indexOf(Pe);if(Ee>-1)Re.splice(Ee,1)})}await Promise.allSettled(Re);let xe=(Date.now()-de)/1000;return M.totalRequests=pe,M.averageResponseTime=U.length>0?U.reduce((ve,Ce)=>ve+Ce,0)/U.length:0,M.requestsPerSecond=pe/xe,M.errors=Array.from(z.entries()).map(([ve,Ce])=>({error:ve,count:Ce})),M}async makeRequest(i,c,P){let M=performance.now();try{return await this.client.request(c,i,P),performance.now()-M}catch(U){let z=performance.now();throw U}}}var Wc={routeHandler:async(i,c=1000)=>{let P=[],M=De();for(let Te=0;Te<c;Te++){let xe=performance.now();await i(M);let ve=performance.now();P.push(ve-xe)}let U=P.reduce((Te,xe)=>Te+xe,0),z=U/c,de=Math.min(...P),pe=Math.max(...P),Re=c/U*1000;return{averageTime:z,minTime:de,maxTime:pe,totalTime:U,throughput:Re}},middleware:async(i,c=1000)=>{let P=[],M=De(),U=lo(async()=>new Response("OK"));for(let Te=0;Te<c;Te++){let xe=performance.now();await i(M,U);let ve=performance.now();P.push(ve-xe)}let z=P.reduce((Te,xe)=>Te+xe,0),de=z/c,pe=Math.min(...P),Re=Math.max(...P);return{averageTime:de,minTime:pe,maxTime:Re,totalTime:z}},jsonSerialization:async(i,c=1e4)=>{let P=[];for(let Re=0;Re<c;Re++){let Te=performance.now(),xe=JSON.stringify(i),ve=performance.now();P.push(ve-Te)}let M=P.reduce((Re,Te)=>Re+Te,0),U=M/c,z=Math.min(...P),de=Math.max(...P),pe=JSON.stringify(i).length;return{averageTime:U,minTime:z,maxTime:de,totalTime:M,dataSize:pe}},routeMatching:async(i,c,P=1000)=>{let M=[],U=0;for(let xe=0;xe<P;xe++){let ve=c[xe%c.length],Ce=performance.now();if(i.find((Ee)=>{let Ae=Ee.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${Ae}$`).test(ve)}))U++;let Pe=performance.now();M.push(Pe-Ce)}let z=M.reduce((xe,ve)=>xe+ve,0),de=z/P,pe=Math.min(...M),Re=Math.max(...M),Te=U/P;return{averageTime:de,minTime:pe,maxTime:Re,totalTime:z,matchRate:Te}}},Vc={measureMemoryUsage:async(i,c=100)=>{let P=[],M=[];if(globalThis.gc)globalThis.gc();let U=$t.memoryUsage().heapUsed;for(let Te=0;Te<c;Te++){let xe=await i();P.push(xe);let ve=$t.memoryUsage();if(M.push(ve.heapUsed),Te%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let z=$t.memoryUsage().heapUsed,de=M.reduce((Te,xe)=>Te+xe,0)/M.length,pe=Math.max(...M),Re=z-U>1048576;return{averageHeapUsed:de,maxHeapUsed:pe,memoryLeakDetected:Re,results:P}},testRouteHandlerMemoryLeaks:async(i,c=1000)=>{if(globalThis.gc)globalThis.gc();let P=$t.memoryUsage().heapUsed;for(let de=0;de<c;de++){let pe=De();if(await i(pe),de%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let M=$t.memoryUsage().heapUsed,U=M-P;return{memoryLeakDetected:U>5242880,initialMemory:P,finalMemory:M,memoryGrowth:U}}},Jc={rampUpTest:async(i,c,P)=>{let M=[],U=10,z=P.testDuration/10,de=(P.endConcurrency-P.startConcurrency)/10;for(let pe=0;pe<10;pe++){let Re=Math.round(P.startConcurrency+de*pe),xe=await new Wt(i,{duration:z,concurrency:Re,requestsPerSecond:Re*2}).run(c);M.push({concurrency:Re,requestsPerSecond:xe.requestsPerSecond,averageResponseTime:xe.averageResponseTime,errorRate:xe.failedRequests/xe.totalRequests})}return M},spikeTest:async(i,c,P)=>{let U=await new Wt(i,{duration:30000,concurrency:P.normalLoad}).run(c),de=await new Wt(i,{duration:P.spikeDuration,concurrency:P.spikeLoad}).run(c),Re=await new Wt(i,{duration:30000,concurrency:P.normalLoad}).run(c);return{normalPhase:U,spikePhase:de,recoveryPhase:Re}}},Kc={responseTimeWithin:(i,c)=>{if(i>c)throw Error(`Response time ${i}ms exceeds maximum ${c}ms`)},throughputAtLeast:(i,c)=>{if(i<c)throw Error(`Throughput ${i} RPS is below minimum ${c} RPS`)},errorRateBelow:(i,c)=>{if(i>c)throw Error(`Error rate ${(i*100).toFixed(2)}% exceeds maximum ${(c*100).toFixed(2)}%`)},memoryUsageWithin:(i,c)=>{if(i>c)throw Error(`Memory usage ${(i/1024/1024).toFixed(2)}MB exceeds maximum ${(c/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(i,c=5242880)=>{if(i>c)throw Error(`Potential memory leak detected: ${(i/1024/1024).toFixed(2)}MB growth`)}};function Xc(){return new vs}function Qc(i,c){return new Wt(i,c)}var xs={getCurrentMemoryUsage:()=>{let i=$t.memoryUsage();return{heapUsed:i.heapUsed,heapTotal:i.heapTotal,external:i.external,rss:i.rss}},getCPUUsage:()=>{let i=$t.cpuUsage();return{user:i.user,system:i.system}},createMetricSnapshot:(i)=>({responseTime:i,memoryUsage:xs.getCurrentMemoryUsage(),cpuUsage:xs.getCPUUsage()}),formatResults:(i)=>JSON.stringify(i,null,2)};class en{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(i,c){this.originalResponse=i,this.status=i.status,this.statusText=i.statusText,this.headers=this.parseHeaders(i.headers),this.cookies=this.parseCookies(i.headers.get("set-cookie")),this.redirected=i.redirected,this.url=i.url,this.ok=i.ok,this.type=i.type,this.body=c,this.text=typeof c==="string"?c:JSON.stringify(c);try{this.json=typeof c==="string"?JSON.parse(c):c}catch{this.json=null}}parseHeaders(i){let c={};return i.forEach((P,M)=>{c[M.toLowerCase()]=P}),c}parseCookies(i){if(!i)return{};let c={};return i.split(",").forEach((P)=>{let[M]=P.trim().split(";"),[U,z]=M.split("=");if(U&&z)c[U.trim()]=z.trim()}),c}expectStatus(i){if(this.status!==i)throw Error(`Expected status ${i}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(i,c){let P=this.headers[i.toLowerCase()];if(P===void 0)throw Error(`Expected header '${i}' to be present`);if(c!==void 0&&P!==c)throw Error(`Expected header '${i}' to be '${c}', got '${P}'`);return this}expectBody(i){if(typeof i==="string"){if(this.text!==i)throw Error(`Expected body '${i}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(i))throw Error(`Expected body ${JSON.stringify(i)}, got ${JSON.stringify(this.json)}`);return this}expectJson(i){if(JSON.stringify(this.json)!==JSON.stringify(i))throw Error(`Expected JSON ${JSON.stringify(i)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(i){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(i).forEach(([c,P])=>{let M=this.json[c];if(typeof P==="object"&&P!==null&&typeof M==="object"&&M!==null){let U=JSON.stringify(P),z=JSON.stringify(M);if(U!==z)throw Error(`Expected JSON property '${c}' to be ${U}, got ${z}`)}else if(M!==P)throw Error(`Expected JSON property '${c}' to be '${P}', got '${M}'`)}),this}expectCookie(i,c){let P=this.cookies[i];if(P===void 0)throw Error(`Expected cookie '${i}' to be present`);if(c!==void 0&&P!==c)throw Error(`Expected cookie '${i}' to be '${c}', got '${P}'`);return this}expectRedirect(i){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(i){let c=this.headers.location;if(c!==i)throw Error(`Expected redirect to '${i}', got '${c}'`)}return this}expectValidationError(i,c){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(i){let P=this.json?.errors||this.json?.message;if(!P||!P[i])throw Error(`Expected validation error for field '${i}'`);if(c){if(!(Array.isArray(P[i])?P[i]:[P[i]]).includes(c))throw Error(`Expected validation error message '${c}' for field '${i}'`)}}return this}expectContentType(i){let c=this.headers["content-type"];if(!c||!c.includes(i))throw Error(`Expected content type '${i}', got '${c}'`);return this}expectBodyContains(i){if(!this.text.includes(i))throw Error(`Expected body to contain '${i}'`);return this}expectBodyMatches(i){if(!i.test(this.text))throw Error(`Expected body to match pattern ${i}`);return this}expectJsonStructure(i){return this.validateStructure(this.json,i,"root"),this}validateStructure(i,c,P){if(c&&typeof c==="object"&&c.$$typeof)return;if(Array.isArray(c)){if(!Array.isArray(i))throw TypeError(`Expected ${P} to be an array`);if(c.length>0&&i.length>0)this.validateStructure(i[0],c[0],`${P}[0]`)}else if(typeof c==="object"&&c!==null){if(typeof i!=="object"||i===null)throw Error(`Expected ${P} to be an object`);Object.keys(c).forEach((M)=>{if(!(M in i))throw Error(`Expected ${P} to have property '${M}'`);this.validateStructure(i[M],c[M],`${P}.${M}`)})}}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 Cs(i){let c=await i.text();return new en(i,c)}function Yc(i=200,c,P){let M=new Headers(P);if(c&&typeof c==="object"&&!M.has("content-type"))M.set("content-type","application/json");let U=new Response(c?typeof c==="string"?c:JSON.stringify(c):null,{status:i,headers:M});return new en(U,c)}class Sr{router;config;defaultHeaders;constructor(i,c={}){this.router=i,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:(P)=>P>=200&&P<300,...c},this.defaultHeaders=c.defaultHeaders||{}}async get(i,c={}){return this.request("GET",i,c)}async post(i,c={}){return this.request("POST",i,c)}async put(i,c={}){return this.request("PUT",i,c)}async patch(i,c={}){return this.request("PATCH",i,c)}async delete(i,c={}){return this.request("DELETE",i,c)}async options(i,c={}){return this.request("OPTIONS",i,c)}async head(i,c={}){return this.request("HEAD",i,c)}async request(i,c,P={}){let M={...this.defaultHeaders,...P.headers},U={...P,headers:M},z=new mt(i,c,U).build();try{let de=await this.handleRequest(z);return await Cs(de)}catch(de){throw Error(`Test request failed: ${de instanceof Error?de.message:"Unknown error"}`)}}async handleRequest(i){let c=new URL(i.url),P=this.findMatchingRoute(i.method,c.pathname);if(!P)return new Response("Not Found",{status:404});let{route:M,params:U}=P;i.params={...i.params,...U};try{return await this.executeMiddlewareChain(i,M)||new Response("No response",{status:500})}catch(z){return new Response(JSON.stringify({error:z instanceof Error?z.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(i,c){for(let P of this.router.routes){if(P.method.toLowerCase()!==i.toLowerCase())continue;let M=this.matchPath(P.path,c);if(M!==null)return{route:P,params:M}}return null}matchPath(i,c){let P=i.split("/"),M=c.split("/");if(P.length!==M.length)return null;let U={};for(let z=0;z<P.length;z++){let de=P[z],pe=M[z];if(de.startsWith(":")){let Re=de.slice(1);U[Re]=pe}else if(de!==pe)return null}return U}async executeMiddlewareChain(i,c){let P=[...this.router.globalMiddleware,...c.middleware],M=0,U=async()=>{if(M<P.length){let de=P[M++];return await de(i,U)}else return await this.executeHandler(c.handler,i)};return await U()||new Response("No response",{status:500})}async executeHandler(i,c){if(typeof i==="function")return await i(c);else if(typeof i==="string")throw TypeError(`String handlers not supported in test environment: ${i}`);else if(typeof i==="object"&&i.handle)return await new i().handle(c);throw Error("Invalid handler type")}setDefaultHeaders(i){return this.defaultHeaders={...this.defaultHeaders,...i},this}auth(i,c="Bearer"){return this.defaultHeaders.Authorization=`${c} ${i}`,this}userAgent(i){return this.defaultHeaders["User-Agent"]=i,this}withConfig(i){return new Sr(this.router,{...this.config,...i})}withHeaders(i){return new Sr(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...i}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function Er(i,c){return new Sr(i,c)}var nl={for:(i,c)=>Er(i,c),withConfig:(i)=>(c)=>Er(c,i),withAuth:(i,c="Bearer")=>(P)=>Er(P).auth(i,c),withHeaders:(i)=>(c)=>Er(c).withHeaders(i)};import{mock as Bt}from"bun:test";class Ct{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(i=1000,c="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:i,reason:c}),this}send(i){if(!this.isConnected)throw Error("WebSocket is not connected");let c={type:typeof i==="string"?"text":"binary",data:i,timestamp:Date.now()};return this.messages.push(c),this}receive(i){if(!this.isConnected)throw Error("WebSocket is not connected");let c={type:typeof i==="string"?"text":"binary",data:i,timestamp:Date.now()};return this.emit("message",{type:"message",data:i}),this}ping(i){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:i}),this}pong(i){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:i}),this}on(i,c){if(!this.eventHandlers.has(i))this.eventHandlers.set(i,[]);return this.eventHandlers.get(i).push(c),this}off(i,c){let P=this.eventHandlers.get(i);if(P){let M=P.indexOf(c);if(M>-1)P.splice(M,1)}return this}emit(i,c){(this.eventHandlers.get(i)||[]).forEach((M)=>M(c))}getSentMessages(){return[...this.messages]}getMessagesByType(i){return this.messages.filter((c)=>c.type===i)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(i)=>this.send(i),close:(i,c)=>this.disconnect(i,c),ping:(i)=>this.ping(i),pong:(i)=>this.pong(i),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class Ps{tester;_data;constructor(i={}){this.tester=new Ct,this._data=i}send(i){this.tester.send(i)}close(i,c){this.tester.disconnect(i,c)}ping(i){this.tester.ping(i)}pong(i){this.tester.pong(i)}publish(i,c){this.tester.send(c)}subscribe(i){}unsubscribe(i){}isSubscribed(i){return!0}cork(i){i()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(i){this._data=i}getTester(){return this.tester}}var ol={onOpen:()=>Bt(async(i)=>{}),onMessage:(i)=>Bt(async(c,P)=>{if(i)c.send(i)}),onClose:()=>Bt(async(i,c,P)=>{}),onError:()=>Bt(async(i,c)=>{}),echo:()=>Bt(async(i,c)=>{i.send(c)}),broadcast:(i)=>Bt(async(c,P)=>{i.forEach((M)=>{if(M!==c&&M.readyState===1)M.send(P)})}),chatRoom:(i)=>Bt(async(c,P)=>{c.publish(i,P)})},al={basicConnection:()=>new Ct().connect().send("Hello WebSocket").receive("Hello Client"),connectionFailure:()=>{let i=new Ct;return i.on("error",()=>{}),i},messageBroadcast:(i=3)=>{let c=Array.from({length:i},()=>new Ct().connect());return c[0].send("Broadcast message"),c.slice(1).forEach((P)=>P.receive("Broadcast message")),c},pingPong:()=>new Ct().connect().ping().pong(),connectionTimeout:()=>{let i=new Ct;return setTimeout(()=>{i.disconnect(1006,"Connection timeout")},100),i}},ul={isConnected:(i)=>{if(!i.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(i)=>{if(i.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(i,c)=>{if(!i.getSentMessages().some((U)=>{if(typeof c==="string"&&typeof U.data==="string")return U.data===c;return U.data===c}))throw Error("Expected message not found in sent messages")},messageCount:(i,c)=>{let P=i.getSentMessages();if(P.length!==c)throw Error(`Expected ${c} messages, but got ${P.length}`)},messageType:(i,c,P)=>{let M=i.getSentMessages();if(c>=M.length)throw Error(`Message at index ${c} does not exist`);if(M[c].type!==P)throw Error(`Expected message type '${P}', got '${M[c].type}'`)},readyState:(i,c)=>{let P=i.getState();if(P.readyState!==c)throw Error(`Expected ready state ${c}, got ${P.readyState}`)}},cl={testThroughput:async(i=1000,c=1024)=>{let P=new Ct().connect(),M="x".repeat(c),U=performance.now();for(let Te=0;Te<i;Te++)P.send(M);let de=performance.now()-U,pe=i/de*1000,Re=de/i;return{messagesPerSecond:pe,totalTime:de,averageLatency:Re}},testConcurrentConnections:async(i=100)=>{let c={successfulConnections:0,failedConnections:0,averageConnectionTime:0},P=[],M=Array.from({length:i},async()=>{let U=performance.now();try{new Ct().connect();let de=performance.now();P.push(de-U),c.successfulConnections++}catch(z){console.error("WebSocket connection failed:",z),c.failedConnections++}});return await Promise.all(M),c.averageConnectionTime=P.length>0?P.reduce((U,z)=>U+z,0)/P.length:0,c}};function ll(){return new Ct}function dl(i){return new Ps(i)}var pl={createClients:(i)=>Array.from({length:i},()=>new Ct().connect()),withLatency:(i,c)=>{let P=i.send.bind(i);return i.send=(M)=>(setTimeout(()=>P(M),c),i),i},withPacketLoss:(i,c)=>{let P=i.send.bind(i);return i.send=(M)=>{if(Math.random()>c)P(M);return i},i},*messageGenerator(i,c="Message"){for(let P=1;P<=i;P++)yield`${c} ${P}`}};class tn extends Error{status;response;body;constructor(i,c){let P=typeof c?.message==="string"?c.message:i.statusText||"Request failed";super(`${i.status} ${P}`);this.name="TypedClientError",this.status=i.status,this.response=i,this.body=c}}function Ms(i,c){if(!c)return i;let P=i;for(let[M,U]of Object.entries(c)){let z=encodeURIComponent(U);P=P.split(`{${M}}`).join(z),P=P.replace(new RegExp(`:${M}(?![A-Z0-9_])`,"gi"),z)}return P}function Es(i,c){if(!c)return i;let P=new URLSearchParams;for(let[U,z]of Object.entries(c))if(z!==void 0&&z!==null)P.append(U,String(z));let M=P.toString();if(!M)return i;return i.includes("?")?`${i}&${M}`:`${i}?${M}`}async function po(i){if(i.status===204||i.headers.get("content-length")==="0")return;if((i.headers.get("content-type")??"").includes("json"))try{return await i.json()}catch{return}return await i.text()}function ho(i){let c=i.baseUrl.replace(/\/+$/,""),P=i.fetch??globalThis.fetch;async function M(){if(typeof i.headers==="function")return await i.headers();return i.headers??{}}async function U(z,de,pe,Re,Te){let xe=Es(`${c}${Ms(de,Te?.params)}`,Te?.query),ve={accept:"application/json",...await M(),...Te?.headers};if(Re&&ve["content-type"]===void 0&&ve["Content-Type"]===void 0)ve["content-type"]="application/json";let Ce=await P(xe,{method:z,headers:ve,...Re?{body:JSON.stringify(pe)}:{},...i.credentials?{credentials:i.credentials}:{},...Te?.signal?{signal:Te.signal}:{}}),Me=await po(Ce);if(!Ce.ok){let Pe=new tn(Ce,Me);if(i.onError)return i.onError(Pe);throw Pe}return Me}return{get:(z,de)=>U("GET",z,void 0,!1,de),post:(z,de,pe)=>U("POST",z,de,!0,pe),put:(z,de,pe)=>U("PUT",z,de,!0,pe),patch:(z,de,pe)=>U("PATCH",z,de,!0,pe),delete:(z,de)=>U("DELETE",z,void 0,!1,de),async raw(z,de,pe){let{params:Re,query:Te,...xe}=pe??{},ve=Es(`${c}${Ms(de,Re)}`,Te);return await P(ve,{method:z,...xe,headers:{...await M(),...xe.headers},...i.credentials?{credentials:i.credentials}:{}})}}}function go(i){return i}var mo=["get","post","put","patch","delete"];function fo(i,c,P,M){if(!M)return;let U=i,z=(de)=>{let pe=U?.[de];if(typeof pe!=="function")throw TypeError(`[typed-router] ${c.toUpperCase()} ${P}: this router's route does not support .${String(de)}(), so the \`${String(de)}\` option cannot be applied. Register the route directly instead of dropping it.`);return pe};if(M.middleware)z("middleware").call(U,M.middleware);if(M.name)z("name").call(U,M.name);if(M.skipCsrf)z("skipCsrf").call(U);if(M.requireCsrf)z("requireCsrf").call(U);if(M.rateLimit)z("rateLimit").call(U,M.rateLimit.max,M.rateLimit.window??"minute")}function Ro(i){let c={};for(let P of mo)c[P]=(M,U,z)=>(fo(i[P](M,U),P,M,z),c);return c}export{nn as ApiKeyManager,Us as Auth,sr as AuthTester,L as BindingBuilder,so as BuiltInRules,ca as CacheInvalidation,o as Container,y as ContentSecurityPolicy,le as ContextualContainer,p as Cors,r as Csrf,w as DDoSProtection,pn as DEFAULT_COMPRESSION,Tu as DatabaseRules,I as DatabaseSessionStore,ue as DefaultServiceProviderManager,si as Dependencies,Qt as DomainGroup,Nn as DomainGroupBuilder,pt as DomainMatcher,qu as EnhancementPresets,_ as EnvironmentManager,ln as Errors,C as FileSecurity,A as FileSessionStore,a as FileUpload,Ht as FileUploadTester,Yr as FileValidationTester,Se as FluentRouteBuilder,Yt as FluentRouter,oo as GenericMockModel,S as Helmet,fe as InMemoryNonceStore,b as InputValidation,rn as JWT,Qr as JWTTester,h as JsonBody,Wt as LoadTester,l as MemorySessionStore,ws as MiddlewareChainTester,ii as MiddlewareFactory,Kr as MiddlewareGroupRegistry,ms as MiddlewareHelpers,Nr as MiddlewarePipeline,ys as MiddlewareTester,uo as MockPostClass,Ps as MockServerWebSocket,ao as MockUserClass,bs as ModelBindingTester,Ts as ModelResolverTester,sn as OAuth2Helper,D as PerformanceAlerting,N as PerformanceDashboard,q as PerformanceMonitor,vs as PerformanceTester,k as RateLimit,Bn as RateLimitRegistry,pa as RateLimitUtils,yr as RateLimiter,O as RedisSessionStore,m as RequestId,g as RequestSigning,H as RequestTracer,mn as ResponseBuilder,at as RouteBuilder,$n as RouteCacheFactory,An as RouteCacheKeyGenerator,qn as RouteCacheManager,Li as RouteFactory,Fn as RouteGroupBuilder,Hu as RouteHelpers,Oe as Router,zi as RouterUtils,R as Security,B as SecuritySuite,f as Session,G as SessionManager,Zr as SessionTester,n as SignatureError,ni as SkipConditions,fa as SubdomainPatterns,Ur as SubdomainRouter,ma as SubdomainUtils,Sr as TestClient,mt as TestRequestBuilder,en as TestResponseWrapper,Ai as ThrottleFactory,tn as TypedClientError,fs as ValidationFluentRouter,Cu as ValidationHelpers,Rs as ValidationMiddlewareBuilder,Vr as ValidationRuleBuilder,Pr as Validator,Ct as WebSocketTester,Be as apiKeyAuth,Dr as appendVary,Yi as applyRequestEnhancements,Br as applyResponseCompression,Tt as auth,pc as authHelpers,dc as authMocks,Ne as basicAuth,qe as bearerAuth,qc as benchmarkMiddleware,Wc as benchmarkTests,Xo as buildUrlWithPreservedParams,$i as clearNamedRoutes,Io as compressResponse,e as config,Nc as constraintHelpers,ze as contentSecurityPolicy,wt as cors,hc as createAuthTester,be as createContainer,cr as createCookieAccessor,Jr as createEnhancementMiddleware,xc as createFileUploadTester,Au as createFluentRouter,Ji as createHandlerResolver,Ut as createInMemoryCookieAccessor,gc as createJWTTester,Qc as createLoadTester,Ac as createMiddlewareSpy,De as createMockRequest,Yc as createMockResponse,dl as createMockServerWebSocket,Uc as createModelBindingTester,Ic as createModelResolverTester,Ca as createPathRegex,Xc as createPerformanceTester,jt as createRateLimitMiddleware,On as createRouteCacheMiddleware,yt as createSessionStore,mc as createSessionTester,ga as createSubdomainMiddleware,Er as createTestClient,Cs as createTestResponse,ho as createTypedClient,Ro as createTypedRouter,Mr as createValidationMiddleware,ll as createWebSocketTester,xt as csrf,Ve as ddosProtection,Ft as decodeParam,he as defaultConfig,Ko as defaultQueryPreservationConfig,go as defineEndpoint,Xe as documentUpload,Xs as enableRequestContext,ge as extractApiKey,me as extractBasicAuth,V as extractBearerToken,wr as extractParamNames,jn as fileExists,We as fileUpload,Tc as fileUploadAssertions,wc as fileUploadMocks,bc as fileUploadScenarios,fi as generateQueryPreservationScript,F as generateSessionId,ft as getConfig,ye as getContainer,dn as getCurrentRequest,Ir as getNamedRoutePath,Oi as getNamedRoutes,oi as globalMiddlewarePipeline,xu as globalValidator,Je as imageUpload,hr as injectQueryPreservationScript,Ye as inputValidation,Di as isActionClass,hn as isCompressible,va as isRouteHandler,Mt as joinPaths,bt as jsonBody,He as jwtAuth,ht as matchPath,Vc as memoryTests,K as middleware,ut as middlewareGroups,Sc as mockMiddleware,Dc as modelMocks,Ke as multipleFileUpload,Zs as negotiateEncoding,Zt as normalizePath,je as oauth2Auth,Lt as parseThrottleString,ti as peekBody,Qe as performanceAlerting,Kc as performanceAssertions,Ze as performanceDashboard,et as performanceMonitor,xs as performanceUtils,Ln as processHtmlTemplate,W as rateLimit,Dn as rateLimitRegistry,St as registerNamedRoute,Qs as request,Rt as requestId,Ue as requestSigning,tt as requestTracer,er as resolveHandler,_r as resolveViewPath,ke as response,jo as responseBuilder,_t as routeCacheManager,Fc as routeModelHelpers,Gi as router,vu as rule,dr as runWithRequest,_c as scopedBindingHelpers,rt as security,nt as securitySuite,vt as session,we as setContainer,pr as setCurrentRequest,Ys as shouldCompress,Le as signRequest,Ge as singleFileUpload,Hc as spyOnMiddleware,Jc as stressTests,nl as testClient,vc as testFiles,Ec as testMiddleware,kc as testMiddlewareChain,oc as testRequest,xa as toActionPath,Bi as url,ku as validate,Pa as validatePath,_e as verifySignature,lt as wrapResponse,ul as wsAssertions,ol as wsHandlerMocks,cl as wsPerformance,al as wsTestScenarios,pl as wsTestUtils};
105
+ `,new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(o="healthy",l={})=>{let M=o==="healthy"?200:o==="degraded"?200:503,k={status:o,timestamp:new Date().toISOString(),checks:l,uptime:no.uptime?.()||0};return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})}};function so(){Object.entries(yt).forEach(([o,l])=>{ur.macro(o,l)})}so();var io=/^[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,oo={required:{name:"required",validate:(o)=>{if(o===null||o===void 0)return!1;if(typeof o==="string")return o.trim().length>0;if(Array.isArray(o))return o.length>0;if(typeof o==="object")return Object.keys(o).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(o)=>typeof o==="string",message:"The :field field must be a string."},number:{name:"number",validate:(o)=>typeof o==="number"&&!Number.isNaN(o),message:"The :field field must be a number."},integer:{name:"integer",validate:(o)=>Number.isInteger(Number(o)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(o)=>typeof o==="boolean"||o==="true"||o==="false"||o==="1"||o==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(o)=>typeof o==="string"&&io.test(o),message:"The :field field must be a valid email address."},url:{name:"url",validate:(o)=>{try{let l=new URL(o);return Boolean(l)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(o,l)=>{let M=Number(l[0]);if(typeof o==="string")return o.length>=M;if(typeof o==="number")return o>=M;if(Array.isArray(o))return o.length>=M;return!1},message:(o,l)=>`The ${o} field must be at least ${l[0]} characters.`},max:{name:"max",validate:(o,l)=>{let M=Number(l[0]);if(typeof o==="string")return o.length<=M;if(typeof o==="number")return o<=M;if(Array.isArray(o))return o.length<=M;return!1},message:(o,l)=>`The ${o} field must not exceed ${l[0]} characters.`},between:{name:"between",validate:(o,l)=>{let M=Number(l[0]),k=Number(l[1]);if(typeof o==="string")return o.length>=M&&o.length<=k;if(typeof o==="number")return o>=M&&o<=k;if(Array.isArray(o))return o.length>=M&&o.length<=k;return!1},message:(o,l)=>`The ${o} field must be between ${l[0]} and ${l[1]}.`},in:{name:"in",validate:(o,l)=>l.includes(String(o)),message:(o,l)=>`The ${o} field must be one of: ${l.join(", ")}.`},notIn:{name:"not_in",validate:(o,l)=>!l.includes(String(o)),message:(o,l)=>`The ${o} field must not be one of: ${l.join(", ")}.`},regex:{name:"regex",validate:(o,l)=>{let M=new RegExp(l[0]);return typeof o==="string"&&M.test(o)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(o)=>typeof o==="string"&&/^[a-z]+$/i.test(o),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(o)=>typeof o==="string"&&/^[a-z0-9]+$/i.test(o),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(o)=>typeof o==="string"&&/^[\w-]+$/.test(o),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(o)=>{let l=new Date(o);return!Number.isNaN(l.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(o,l)=>{let M=new Date(o),k=new Date(l[0]);return!Number.isNaN(M.getTime())&&!Number.isNaN(k.getTime())&&M>k},message:(o,l)=>`The ${o} field must be after ${l[0]}.`},dateBefore:{name:"before",validate:(o,l)=>{let M=new Date(o),k=new Date(l[0]);return!Number.isNaN(M.getTime())&&!Number.isNaN(k.getTime())&&M<k},message:(o,l)=>`The ${o} field must be before ${l[0]}.`},confirmed:{name:"confirmed",validate:(o,l,M,k)=>{let L=l[0]||`${M}_confirmation`;return o===k[L]},message:"The :field confirmation does not match."},same:{name:"same",validate:(o,l,M,k)=>o===k[l[0]],message:(o,l)=>`The ${o} field must match ${l[0]}.`},different:{name:"different",validate:(o,l,M,k)=>o!==k[l[0]],message:(o,l)=>`The ${o} field must be different from ${l[0]}.`},json:{name:"json",validate:(o)=>{try{return JSON.parse(o),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(o)=>typeof o==="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(o),message:"The :field field must be a valid UUID."},array:{name:"array",validate:(o)=>Array.isArray(o),message:"The :field field must be an array."},object:{name:"object",validate:(o)=>typeof o==="object"&&o!==null&&!Array.isArray(o),message:"The :field field must be an object."}},Pu={unique:{name:"unique",validate:async(o,l)=>(console.warn('Database validation rule "unique" requires external implementation'),!0),message:"The :field field must be unique."},exists:{name:"exists",validate:async(o,l)=>(console.warn('Database validation rule "exists" requires external implementation'),!0),message:"The selected :field is invalid."}};class kr{rules={};config;constructor(o={}){this.config={stopOnFirstFailure:!1,bail:!1,...o},this.registerRules(oo)}registerRule(o){this.rules[o.name]=o}registerRules(o){Object.values(o).forEach((l)=>this.registerRule(l))}parseRuleString(o){return o.split("|").map((l)=>{let[M,...k]=l.split(":"),L=k.length>0?k.join(":").split(","):[];return{name:M.trim(),parameters:L}})}async validate(o,l){let M={};for(let[k,L]of Object.entries(l)){let V=[],pe=this.getNestedValue(o,k),he=typeof L==="string"?this.parseRuleString(L):L.map((Te)=>({name:Te.name,parameters:[]}));for(let{name:Te,parameters:xe}of he){let ve=this.rules[Te];if(!ve){console.warn(`Validation rule "${Te}" not found`);continue}try{if(!await ve.validate(pe,xe,k,o)){let Ce=this.formatErrorMessage(ve,k,xe);if(V.push(Ce),this.config.stopOnFirstFailure||this.config.bail)break}}catch(Pe){console.error(`Error validating rule "${Te}" for field "${k}":`,Pe),V.push(`Validation error for ${k}`)}}if(V.length>0)M[k]=V}return M}async validateOrFail(o,l){let M=await this.validate(o,l);if(Object.keys(M).length>0)throw new d("Validation failed",M)}getNestedValue(o,l){return l.split(".").reduce((M,k)=>M&&M[k]!==void 0?M[k]:void 0,o)}formatErrorMessage(o,l,M){let k=this.config.customMessages?.[`${l}.${o.name}`]||this.config.customMessages?.[o.name];if(k)return this.replacePlaceholders(k,l,M);let L=typeof o.message==="function"?o.message(l,M):o.message;return this.replacePlaceholders(L,l,M)}replacePlaceholders(o,l,M){let k=this.config.customAttributes?.[l]||l.replace(/_/g," ");return o.replace(/:field/g,k).replace(/:attribute/g,k).replace(/:value/g,M[0]||"").replace(/:other/g,M[1]||"")}}var Cu=new kr;function Hr(o,l){let M=new kr(l);return async(k,L)=>{try{let V={...k.query,...k.params,...k.jsonBody||{},...k.formBody||{}};return await M.validateOrFail(V,o),k.validated=V,await L()}catch(V){if(V instanceof d)throw V;throw new d("Validation error occurred")}}}class Qr{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(o){return this.rules.push(`min:${o}`),this}max(o){return this.rules.push(`max:${o}`),this}between(o,l){return this.rules.push(`between:${o},${l}`),this}in(...o){return this.rules.push(`in:${o.join(",")}`),this}notIn(...o){return this.rules.push(`not_in:${o.join(",")}`),this}regex(o){return this.rules.push(`regex:${o}`),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(o){return this.rules.push(`after:${o}`),this}before(o){return this.rules.push(`before:${o}`),this}confirmed(o){return this.rules.push(o?`confirmed:${o}`:"confirmed"),this}same(o){return this.rules.push(`same:${o}`),this}different(o){return this.rules.push(`different:${o}`),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(o,l){return this.rules.push(l?`unique:${o},${l}`:`unique:${o}`),this}exists(o,l){return this.rules.push(l?`exists:${o},${l}`:`exists:${o}`),this}custom(o,...l){return this.rules.push(l.length>0?`${o}:${l.join(",")}`:o),this}build(){return this.rules.join("|")}}function Mu(){return new Qr}var Eu={rules(o){let l={};for(let[M,k]of Object.entries(o))l[M]=k instanceof Qr?k.build():k;return l},async validateValue(o,l,M="value"){return(await new kr().validate({[M]:o},{[M]:l}))[M]||[]},async passes(o,l){return(await this.validateValue(o,l)).length===0},async fails(o,l){return!await this.passes(o,l)}};class lt{method;path;handler;validationRules;validatorConfig;constructor(o,l,M){this.method=o;this.path=l;this.handler=M}validate(o,l){return this.validationRules=o,this.validatorConfig=l,this}build(){let o=[];if(this.validationRules)o.push(Hr(this.validationRules,this.validatorConfig));return o.push(async(l,M)=>(De.applyMacros(l),await M()||new Response("Not Found",{status:404}))),{method:this.method,path:this.path,handler:this.handler,middleware:o.length>0?o:void 0}}}class xs{routes=[];get(o,l){return new lt("GET",o,l)}post(o,l){return new lt("POST",o,l)}put(o,l){return new lt("PUT",o,l)}patch(o,l){return new lt("PATCH",o,l)}delete(o,l){return new lt("DELETE",o,l)}register(o){let l=o.build();this.routes.push(l)}getRoutes(){return this.routes}}function Zr(){return async(o,l)=>(De.applyMacros(o),o.startTime=Date.now(),await l())}class vs{rules={};config={};field(o,l){return this.rules[o]=l,this}fields(o){return Object.assign(this.rules,o),this}configure(o){return Object.assign(this.config,o),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(o){return this.config.customMessages=o,this}attributes(o){return this.config.customAttributes=o,this}build(){return Hr(this.rules,this.config)}}function qu(){return new vs}var Ou={validated:(o,l,M,k,L)=>new lt(o,l,M).validate(k,L),apiRoute:(o,l,M,k)=>{let L=new lt(o,l,async(V)=>{if(!V.expectsJson())return ur.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return await M(V)});if(k)L.validate(k);return L},resourceRoute:(o,l,M)=>{let k=[];if(l.index)k.push(new lt("GET",o,l.index));if(l.show)k.push(new lt("GET",`${o}/{id}`,l.show));if(l.store){let L=new lt("POST",o,l.store);if(M?.store)L.validate(M.store);k.push(L)}if(l.update){let L=new lt("PUT",`${o}/{id}`,l.update);if(M?.update)L.validate(M.update);k.push(L)}if(l.destroy)k.push(new lt("DELETE",`${o}/{id}`,l.destroy));return k}};function $u(){return new xs}var Ts={compose:(...o)=>async(l,M)=>{let k=0,L=async()=>{if(k>=o.length)return await M();let V=o[k++];return await V(l,L)};return await L()},when:(o,l)=>async(M,k)=>{if(o(M))return await l(M,k);return await k()},unless:(o,l)=>Ts.when((M)=>!o(M),l),group:(o)=>Ts.compose(...o)},Bu={api:()=>[Zr(),async(o,l)=>{try{let M=await l(),k=new Headers(M.headers);return k.set("X-API-Version","1.0"),k.set("X-Response-Time",new Date().toISOString()),new Response(M.body,{status:M.status,statusText:M.statusText,headers:k})}catch(M){return console.error(M),ur.callMacro("error","Internal server error",void 0,500)}}],web:()=>[Zr(),async(o,l)=>(o.session={},await l())],validation:(o,l)=>[Zr(),Hr(o,l)]};Zn($e);Yn($e);us($e);os($e);rs($e);ys($e);ws($e);Hn($e);Qn($e);Rs($e);as($e);is($e);kn($e);Cn($e);class Yr{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(o,l){return this.groups.set(o,[...l]),this}extend(o,l){let M=this.groups.get(o)||[];return this.groups.set(o,[...M,...l]),this}prepend(o,l){let M=this.groups.get(o)||[];return this.groups.set(o,[...l,...M]),this}get(o){return this.groups.get(o)||[]}has(o){return this.groups.has(o)}remove(o){return this.groups.delete(o),this}resolve(o){if(typeof o==="function")return[o];if(this.groups.has(o))return this.get(o);return[o]}resolveAll(o){let l=[];for(let M of o)l.push(...this.resolve(M));return l}pushGlobal(...o){return this.globalMiddleware.push(...o),this}prependGlobal(...o){return this.globalMiddleware.unshift(...o),this}removeGlobal(o){return this.globalMiddleware=this.globalMiddleware.filter((l)=>typeof l==="string"?l!==o:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(o,l){return this.middlewarePriority.set(o,l),this}sortByPriority(o){return[...o].sort((l,M)=>{let k=typeof l==="string"?l.split(":")[0]:"",L=typeof M==="string"?M.split(":")[0]:"",V=this.middlewarePriority.get(k)??100,pe=this.middlewarePriority.get(L)??100;return V-pe})}filter(o,l){if(l.only&&l.only.length>0)return o.filter((M)=>{if(typeof M==="string"){let k=M.split(":")[0];return l.only.includes(k)}return!1});if(l.except&&l.except.length>0)return o.filter((M)=>{if(typeof M==="string"){let k=M.split(":")[0];return!l.except.includes(k)}return!0});return o}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var dt=new Yr;dt.define("web",["session","csrf","cors"]);dt.define("api",["throttle:60,1","cors"]);dt.setPriority("session",10);dt.setPriority("cors",20);dt.setPriority("csrf",30);dt.setPriority("auth",40);dt.setPriority("throttle",50);dt.setPriority("role",60);dt.setPriority("permission",60);dt.setPriority("can",70);dt.setPriority("abilities",70);dt.setPriority("verified",80);import{mock as en}from"bun:test";class Pt{request;url;constructor(o,l,M={}){if(this.url=new URL(l,"http://localhost:3000"),M.query)Object.entries(M.query).forEach(([k,L])=>{if(Array.isArray(L))L.forEach((V)=>this.url.searchParams.append(k,V));else this.url.searchParams.set(k,L)});this.request={method:o,url:this.url.toString(),headers:new Headers(M.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:M.body&&typeof M.body==="object"?M.body:void 0,files:M.files?this.convertTestFiles(M.files):void 0,session:M.session,user:M.user,context:M.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:()=>"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:jt(M.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody(M.body)}parseQuery(o){let l={};for(let[M,k]of o.entries())if(l[M])if(Array.isArray(l[M]))l[M].push(k);else l[M]=[l[M],k];else l[M]=k;return l}convertTestFiles(o){return o.map((l)=>({fieldName:l.fieldName,originalName:l.filename,filename:`test-${Date.now()}-${l.filename}`,path:`/tmp/test-uploads/${l.filename}`,size:l.content instanceof ArrayBuffer?l.content.byteLength:new TextEncoder().encode(l.content.toString()).length,mimetype:l.mimetype||"application/octet-stream",buffer:l.content instanceof ArrayBuffer?l.content:new TextEncoder().encode(l.content.toString()).buffer}))}handleBody(o){if(!o)return;let l=this.request.headers?.get("content-type")||"";if(l.includes("application/json")||typeof o==="object"){if(this.request.jsonBody=o,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(l.includes("application/x-www-form-urlencoded"))this.request.formBody=o}params(o){return this.request.params={...this.request.params,...o},this}headers(o){return Object.entries(o).forEach(([l,M])=>{this.request.headers?.set(l,M)}),this}auth(o,l="Bearer"){return this.request.headers?.set("Authorization",`${l} ${o}`),this}user(o){return this.request.user=o,this}session(o){return this.request.session=o,this}cookies(o){let l=this.request.cookies?.getAll()||{};return this.request.cookies=jt({...l,...o}),this}context(o){return this.request.context={...this.request.context,...o},this}json(o){return this.request.jsonBody=o,this.request.headers?.set("content-type","application/json"),this}form(o){return this.request.formBody=o,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(o){return this.request.files=this.convertTestFiles(o),this.request.headers?.set("content-type","multipart/form-data"),this}ip(o){return this.request.ip=()=>o,this}userAgent(o){return this.request.userAgent=()=>o,this.request.headers?.set("User-Agent",o),this}csrf(o){return this.request.csrfToken=o,this.request.headers?.set("X-CSRF-Token",o),this}build(){let o={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)o.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let k=new FormData;Object.entries(this.request.formBody).forEach(([L,V])=>{k.append(L,V)}),o.body=k}let l=new Request(this.url.toString(),o);return Object.assign(l,{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 cc={get:(o,l)=>new Pt("GET",o,l),post:(o,l)=>new Pt("POST",o,l),put:(o,l)=>new Pt("PUT",o,l),patch:(o,l)=>new Pt("PATCH",o,l),delete:(o,l)=>new Pt("DELETE",o,l),options:(o,l)=>new Pt("OPTIONS",o,l),head:(o,l)=>new Pt("HEAD",o,l)};function Ne(o="GET",l="/",M={}){return new Pt(o,l,M).build()}class cr{request;constructor(o){this.request=o||Ne()}as(o){return this.request.user=o,this}withJWT(o,l="Bearer"){let M=new Headers(this.request.headers);return M.set("Authorization",`${l} ${o}`),this.request={...this.request,headers:M},this}withSession(o){return this.request.session=o,this}withApiKey(o,l="X-API-Key"){let M=new Headers(this.request.headers);return M.set(l,o),this.request={...this.request,headers:M},this}withBasicAuth(o,l){let M=btoa(`${o}:${l}`),k=new Headers(this.request.headers);return k.set("Authorization",`Basic ${M}`),this.request={...this.request,headers:k},this}withAuthCookies(o){let l=this.request.cookies?.getAll()||{};return this.request.cookies=jt({...l,...o}),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 tn{options;constructor(o={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...o}}generateToken(o={}){let l={alg:this.options.algorithm,typ:"JWT",...this.options.headers},M=Math.floor(Date.now()/1000),k=M+this.parseExpiresIn(this.options.expiresIn||"1h"),L={iat:M,exp:k,...this.options.payload,...o},V=btoa(JSON.stringify(l)).replace(/=/g,""),pe=btoa(JSON.stringify(L)).replace(/=/g,""),he=btoa(`${V}.${pe}.${this.options.secret}`).replace(/=/g,"");return`${V}.${pe}.${he}`}generateExpiredToken(o={}){let l={alg:this.options.algorithm,typ:"JWT"},M=Math.floor(Date.now()/1000),k={iat:M-7200,exp:M-3600,...o},L=btoa(JSON.stringify(l)).replace(/=/g,""),V=btoa(JSON.stringify(k)).replace(/=/g,""),pe=btoa(`${L}.${V}.${this.options.secret}`).replace(/=/g,"");return`${L}.${V}.${pe}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(o){let[l,M,k]=o.split(".");return{header:JSON.parse(atob(l)),payload:JSON.parse(atob(M)),signature:k}}parseExpiresIn(o){let l=o.match(/^(\d+)([smhd])$/);if(!l)return 3600;let M=Number.parseInt(l[1]);switch(l[2]){case"s":return M;case"m":return M*60;case"h":return M*3600;case"d":return M*86400;default:return 3600}}}class rn{options;constructor(o={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...o}}createSession(o={}){let l={...this.options.data,...o},M=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:l,cookie:M}}generateSessionCookie(o="session"){let l=[];if(this.options.maxAge)l.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)l.push("Secure");if(this.options.httpOnly)l.push("HttpOnly");let M=l.length>0?`; ${l.join("; ")}`:"";return`${o}=${this.options.sessionId}${M}`}createExpiredSession(){let o={...this.options,maxAge:-1};return new rn(o).createSession()}}var gc={user:(o={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...o}),adminUser:(o={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...o}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(o)=>en(async(l,M)=>{if(o)return l.user=o,await M();return new Response("Unauthorized",{status:401})}),roleMiddleware:(o)=>en(async(l,M)=>{if(!l.user)return new Response("Unauthorized",{status:401});let k=l.user.roles||[];if(!o.some((V)=>k.includes(V)))return new Response("Forbidden",{status:403});return await M()}),permissionMiddleware:(o)=>en(async(l,M)=>{if(!l.user)return new Response("Unauthorized",{status:401});let k=l.user.permissions||[];if(!o.every((V)=>k.includes(V)))return new Response("Forbidden",{status:403});return await M()})},mc={authenticatedRequest:(o,l)=>new cr(l).as(o).getRequest(),jwtRequest:(o={},l)=>{let k=new tn().generateToken(o);return new cr(l).withJWT(k).getRequest()},sessionRequest:(o={},l)=>new cr(l).withSession(o).getRequest(),verifyJWTStructure:(o)=>{let l=o.split(".");return l.length===3&&l.every((M)=>M.length>0)},extractJWTPayload:(o)=>{try{let[,l]=o.split(".");return JSON.parse(atob(l))}catch{return null}}};function fc(o){return new cr(o)}function Rc(o){return new tn(o)}function yc(o){return new rn(o)}import{mock as Dt}from"bun:test";class Ot{request;files;constructor(o){this.request=o||Ne(),this.files=[]}addFile(o){let l={fieldName:o.fieldName,originalName:o.filename,filename:`test-${Date.now()}-${o.filename}`,path:`/tmp/test-uploads/${o.filename}`,size:o.content instanceof ArrayBuffer?o.content.byteLength:new TextEncoder().encode(o.content.toString()).length,mimetype:o.mimetype||this.detectMimeType(o.filename),buffer:o.content instanceof ArrayBuffer?o.content:new TextEncoder().encode(o.content.toString()).buffer};return this.files.push(l),this.request.files=[...this.request.files||[],l],this}addFiles(o){return o.forEach((l)=>this.addFile(l)),this}addImage(o,l="test.jpg",M=1024){let k=new ArrayBuffer(M);return this.addFile({fieldName:o,filename:l,content:k,mimetype:"image/jpeg"})}addDocument(o,l="test.pdf",M="Test PDF content"){return this.addFile({fieldName:o,filename:l,content:M,mimetype:"application/pdf"})}addTextFile(o,l="test.txt",M="Test content"){return this.addFile({fieldName:o,filename:l,content:M,mimetype:"text/plain"})}addLargeFile(o,l=10){let M=l*1024*1024,k=new ArrayBuffer(M);return this.addFile({fieldName:o,filename:`large-file-${l}mb.bin`,content:k,mimetype:"application/octet-stream"})}addInvalidFile(o,l="malicious.exe"){return this.addFile({fieldName:o,filename:l,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(o){return this.request.formBody={...this.request.formBody,...o},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(o){let l=o.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"}[l||""]||"application/octet-stream"}}class nn{static testFileSize(o,l){return o.size<=l}static testFileType(o,l){return l.includes(o.mimetype)}static testFileExtension(o,l){let M=o.originalName.split(".").pop()?.toLowerCase();return M?l.includes(M):!1}static testFilename(o){let l=o.originalName;if(l.includes("..")||l.includes("/")||l.includes("\\"))return!1;if(l.includes("\x00"))return!1;let M=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],k=l.split(".")[0].toUpperCase();if(M.includes(k))return!1;return!0}static testImageFile(o){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(o.mimetype)}static testDocumentFile(o){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(o.mimetype)}}var xc={validationMiddleware:(o={})=>Dt(async(M,k)=>{let L=M.files||[],{maxSize:V=5242880,allowedTypes:pe=[],maxFiles:he=10}=o;if(L.length>he)return new Response(`Too many files. Maximum ${he} allowed.`,{status:400});for(let Te of L){if(Te.size>V)return new Response(`File ${Te.originalName} is too large. Maximum size: ${V} bytes.`,{status:400});if(pe.length>0&&!pe.includes(Te.mimetype))return new Response(`File type ${Te.mimetype} not allowed.`,{status:400});if(!nn.testFilename(Te))return new Response(`Invalid filename: ${Te.originalName}`,{status:400})}return await k()}),imageUploadMiddleware:(o={})=>Dt(async(M,k)=>{let L=M.files||[],{maxSize:V=2097152}=o;for(let pe of L){if(!nn.testImageFile(pe))return new Response(`File ${pe.originalName} is not a valid image.`,{status:400});if(pe.size>V)return new Response(`Image ${pe.originalName} is too large.`,{status:400})}return await k()}),storageService:{store:Dt(async(o,l)=>l||`/uploads/${Date.now()}-${o.filename}`),delete:Dt(async(o)=>{}),exists:Dt(async(o)=>!o.includes("not-found")),getUrl:Dt((o)=>`https://example.com/storage${o}`)},virusScanner:{scan:Dt(async(o)=>{if(o.originalName.endsWith(".exe")||o.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},vc={singleFileUpload:()=>new Ot().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"}),multipleFileUpload:()=>new Ot().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"}),fileSizeExceeded:()=>new Ot().addLargeFile("file",50),invalidFileType:()=>new Ot().addInvalidFile("file","virus.exe"),emptyFileUpload:()=>new Ot().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"}),maliciousFilename:()=>new Ot().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})},Pc={hasFiles:(o,l)=>{let M=o.files||[];if(l!==void 0&&M.length!==l)throw Error(`Expected ${l} files, but got ${M.length}`);if(M.length===0)throw Error("Expected request to have files")},hasFileWithField:(o,l)=>{if(!(o.files||[]).some((L)=>L.fieldName===l))throw Error(`Expected file with field name '${l}'`)},fileMatches:(o,l)=>{Object.entries(l).forEach(([M,k])=>{if(o[M]!==k)throw Error(`Expected file.${M} to be '${k}', got '${o[M]}'`)})},fileSizeWithinLimit:(o,l)=>{if(o.size>l)throw Error(`File size ${o.size} exceeds limit of ${l}`)},fileTypeAllowed:(o,l)=>{if(!l.includes(o.mimetype))throw Error(`File type '${o.mimetype}' is not allowed. Allowed types: ${l.join(", ")}`)}};function Cc(o){return new Ot(o)}var Mc={image:(o="image",l="test.jpg")=>({fieldName:o,filename:l,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(o="document",l="test.pdf")=>({fieldName:o,filename:l,content:"PDF content",mimetype:"application/pdf"}),text:(o="file",l="test.txt",M="Test content")=>({fieldName:o,filename:l,content:M,mimetype:"text/plain"}),large:(o="file",l=10)=>({fieldName:o,filename:`large-${l}mb.bin`,content:new ArrayBuffer(l*1024*1024),mimetype:"application/octet-stream"}),malicious:(o="file")=>({fieldName:o,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as ut,spyOn as ao}from"bun:test";class Ps{middleware;context;constructor(o){this.middleware=o,this.context=this.createContext()}createContext(){let o=Ne(),l=ut(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:o,next:l}}withRequest(o){return this.context.request=o,this}withNext(o){return this.context.next=ut(o),this}withError(o){return this.context.error=o,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(o){throw this.context.error=o,o}}expectNextCalled(o=1){if(this.context.next.mock.calls.length!==o)throw Error(`Expected next to be called ${o} 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(o){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(o&&this.context.error.message!==o)throw Error(`Expected error message "${o}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function Hc(o){return new Ps(o)}var Ac={passthrough:()=>ut(async(o,l)=>await l()),response:(o=200,l)=>ut(async()=>new Response(l?JSON.stringify(l):null,{status:o})),error:(o="Middleware error")=>ut(async()=>{throw Error(o)}),modifyRequest:(o)=>ut(async(l,M)=>(o(l),await M())),addContext:(o,l)=>ut(async(M,k)=>(M.context=M.context||{},M.context[o]=l,await k())),auth:(o)=>ut(async(l,M)=>{if(o)return l.user=o,await M();else return new Response("Unauthorized",{status:401})}),rateLimit:(o=!1)=>ut(async(l,M)=>{if(o)return new Response("Too Many Requests",{status:429});return await M()}),cors:(o="*")=>ut(async(l,M)=>{let k=await M();if(k)k.headers.set("Access-Control-Allow-Origin",o);return k})};class Cs{middlewares;request;finalHandler;constructor(o){this.middlewares=o,this.request=Ne(),this.finalHandler=ut(async()=>new Response("Final handler",{status:200}))}withRequest(o){return this.request=o,this}withFinalHandler(o){return this.finalHandler=ut(o),this}async execute(){let o=0,l=async()=>{if(o<this.middlewares.length){let M=this.middlewares[o++];return await M(this.request,l)}else return await this.finalHandler()};return await l()}getExecutionOrder(){return this.middlewares.map((o,l)=>l)}}function qc(o){return new Cs(o)}function Oc(o){return ao(o,"call")}function $c(){let o=ut(async(l,M)=>await M());return{middleware:o,spy:o}}async function Bc(o,l=1000){let M=[],k=Ne(),L=ut(async()=>new Response("OK"));for(let xe=0;xe<l;xe++){let ve=performance.now();await o(k,L);let Pe=performance.now();M.push(Pe-ve)}let V=M.reduce((xe,ve)=>xe+ve,0),pe=V/l,he=Math.min(...M),Te=Math.max(...M);return{averageTime:pe,minTime:he,maxTime:Te,totalTime:V}}import{mock as Ht}from"bun:test";class uo{id;attributes;constructor(o={}){this.id=o.id,this.attributes=o}static modelName="GenericMockModel";static async find(o){return null}static async findOrFail(o){throw Error("Not implemented")}static async where(o){return[]}static async create(o){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class co{id;email;name;constructor(o={id:1}){this.id=o.id,this.email=o.email||"test@example.com",this.name=o.name||"Test User"}static async find(o){return null}static async findOrFail(o){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class lo{id;title;content;userId;constructor(o={id:1}){this.id=o.id,this.title=o.title||"Test Post",this.content=o.content||"Test content",this.userId=o.userId||1}static async find(o){return null}static async findOrFail(o){throw Error("Not implemented")}async belongsTo(o){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class Ms{request;options;constructor(o={}){this.options=o,this.request=Ne()}withRequest(o){return this.request=o,this}withParams(o){return this.request.params={...this.request.params,...o},this}withModel(o){return this.options.modelClass=o,this}withRouteKey(o){return this.options.routeKey=o,this}withConstraints(o){return this.options.constraints=o,this}withResolver(o){return this.options.customResolver=o,this}async testResolution(o){if(this.options.customResolver)return await this.options.customResolver(o);if(this.options.modelClass)return new this.options.modelClass({id:o});return{id:o}}async testNotFound(o){try{throw await this.testResolution(o),Error("Expected model not found error")}catch(l){if(l instanceof Error&&l.message!=="Model not found")throw l}}getRequest(){return this.request}}var Uc={createModel:(o,l={})=>class M{id;attributes;constructor(k={}){this.id=k.id,this.attributes={...l,...k}}static modelName=o;static async find(k){if(k==="not-found")return null;return new M({id:k,...l})}static async findOrFail(k){let L=await this.find(k);if(!L)throw Error("Model not found");return L}static async where(k){return[new M({id:1,...l,...k})]}static async create(k){return new M({id:Date.now(),...k})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}},User:class o{id;email;name;constructor(l={id:1}){this.id=l.id,this.email=l.email||"test@example.com",this.name=l.name||"Test User"}static async find(l){if(l==="not-found")return null;return new o({id:Number.parseInt(l)})}static async findOrFail(l){let M=await this.find(l);if(!M)throw Error("User not found");return M}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class o{id;title;content;userId;constructor(l={id:1}){this.id=l.id,this.title=l.title||"Test Post",this.content=l.content||"Test content",this.userId=l.userId||1}static async find(l){if(l==="not-found")return null;return new o({id:Number.parseInt(l)})}static async findOrFail(l){let M=await this.find(l);if(!M)throw Error("Post not found");return M}async belongsTo(l){return this.userId===l}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},Ic={belongsTo:(o="userId")=>Ht(async(M,k)=>{if(!k.user)return!1;return M[o]===k.user.id}),belongsToUser:()=>Ht(async(l,M)=>{if(!M.user)return!1;return l.userId===M.user.id}),published:()=>Ht(async(l)=>l.published===!0||l.status==="published"),visible:()=>Ht(async(l)=>l.visible!==!1&&l.hidden!==!0),custom:(o)=>Ht(o),combine:(...o)=>Ht(async(M,k)=>{for(let L of o)if(!await L(M,k))return!1;return!0})};class Es{resolvers=new Map;register(o,l){return this.resolvers.set(o,Ht(l)),this}registerModel(o,l){let M=Ht(async(k)=>{if(l.find){let L=await l.find(k);if(!L)throw Error(`${l.name||"Model"} not found`);return L}return new l({id:k})});return this.resolvers.set(o,M),this}async resolve(o,l){let M=this.resolvers.get(o);if(!M)throw Error(`No resolver registered for key: ${o}`);return await M(l)}async testAll(o="1"){let l={};for(let[M,k]of this.resolvers)try{l[M]=await k(o)}catch(L){l[M]={error:L instanceof Error?L.message:"Unknown error"}}return l}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var _c={testRoute:async(o,l,M)=>{let k=Ne("GET",o);k.params=l;for(let[L,V]of Object.entries(M))k.context=k.context||{},k.context[L]=V;return k},createHandler:(o)=>Ht(async(M)=>{let k=M.context||{};for(let L of o)if(!k[L])return new Response(`Model ${L} not found`,{status:404});return new Response(JSON.stringify({params:M.params,models:Object.fromEntries(o.map((L)=>[L,k[L]]))}),{headers:{"Content-Type":"application/json"}})}),testBindingMiddleware:(o)=>Ht(async(M,k)=>{M.context=M.context||{};for(let[L,V]of Object.entries(o)){let pe=M.params[L];if(pe)try{if(typeof V==="function")M.context[L]=await V(pe);else M.context[L]=V}catch(he){return console.error(`Error resolving model ${L}:`,he),new Response(`${L} not found`,{status:404})}}return await k()})};function jc(o){return new Ms(o)}function Lc(){return new Es}var po=async(o,l)=>o.userId===l.id,zc={testUserScoped:async(o,l,M=po)=>await M(o,l),testRoleAccess:async(o,l,M)=>{if(!l.roles)return!1;return M.some((k)=>l.roles.includes(k))},testPermissionAccess:async(o,l,M)=>{if(!l.permissions)return!1;return M.every((k)=>l.permissions.includes(k))}};import{mock as ho}from"bun:test";import Nt from"process";class ks{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(o){return this.metrics.push(o),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((l,M)=>l+M.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let o=this.metrics.map((M)=>M.memoryUsage.heapUsed),l=this.metrics.map((M)=>M.memoryUsage.rss);return{averageHeapUsed:o.reduce((M,k)=>M+k,0)/o.length,maxHeapUsed:Math.max(...o),averageRSS:l.reduce((M,k)=>M+k,0)/l.length,maxRSS:Math.max(...l)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class Kt{client;config;constructor(o,l){this.client=o,this.config=l}async run(o,l="GET",M={}){let k={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},L=[],V=new Map,pe=Date.now(),he=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),Te=[];for(let Pe=0;Pe<he;Pe++){let Ce=this.makeRequest(o,l,M).then((Ee)=>{L.push(Ee),k.successfulRequests++}).catch((Ee)=>{let Me=Ee instanceof Error?Ee.message:"Unknown error";V.set(Me,(V.get(Me)||0)+1),k.failedRequests++});if(Te.push(Ce),this.config.requestsPerSecond){let Ee=1000/this.config.requestsPerSecond;await new Promise((Me)=>setTimeout(Me,Ee))}if(Te.length>=this.config.concurrency)await Promise.race(Te),Te.filter((Me)=>Me.then(()=>!0).catch(()=>!0)).forEach((Me)=>{let Se=Te.indexOf(Me);if(Se>-1)Te.splice(Se,1)})}await Promise.allSettled(Te);let ve=(Date.now()-pe)/1000;return k.totalRequests=he,k.averageResponseTime=L.length>0?L.reduce((Pe,Ce)=>Pe+Ce,0)/L.length:0,k.requestsPerSecond=he/ve,k.errors=Array.from(V.entries()).map(([Pe,Ce])=>({error:Pe,count:Ce})),k}async makeRequest(o,l,M){let k=performance.now();try{return await this.client.request(l,o,M),performance.now()-k}catch(L){let V=performance.now();throw L}}}var Kc={routeHandler:async(o,l=1000)=>{let M=[],k=Ne();for(let xe=0;xe<l;xe++){let ve=performance.now();await o(k);let Pe=performance.now();M.push(Pe-ve)}let L=M.reduce((xe,ve)=>xe+ve,0),V=L/l,pe=Math.min(...M),he=Math.max(...M),Te=l/L*1000;return{averageTime:V,minTime:pe,maxTime:he,totalTime:L,throughput:Te}},middleware:async(o,l=1000)=>{let M=[],k=Ne(),L=ho(async()=>new Response("OK"));for(let xe=0;xe<l;xe++){let ve=performance.now();await o(k,L);let Pe=performance.now();M.push(Pe-ve)}let V=M.reduce((xe,ve)=>xe+ve,0),pe=V/l,he=Math.min(...M),Te=Math.max(...M);return{averageTime:pe,minTime:he,maxTime:Te,totalTime:V}},jsonSerialization:async(o,l=1e4)=>{let M=[];for(let Te=0;Te<l;Te++){let xe=performance.now(),ve=JSON.stringify(o),Pe=performance.now();M.push(Pe-xe)}let k=M.reduce((Te,xe)=>Te+xe,0),L=k/l,V=Math.min(...M),pe=Math.max(...M),he=JSON.stringify(o).length;return{averageTime:L,minTime:V,maxTime:pe,totalTime:k,dataSize:he}},routeMatching:async(o,l,M=1000)=>{let k=[],L=0;for(let ve=0;ve<M;ve++){let Pe=l[ve%l.length],Ce=performance.now();if(o.find((Se)=>{let Oe=Se.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${Oe}$`).test(Pe)}))L++;let Me=performance.now();k.push(Me-Ce)}let V=k.reduce((ve,Pe)=>ve+Pe,0),pe=V/M,he=Math.min(...k),Te=Math.max(...k),xe=L/M;return{averageTime:pe,minTime:he,maxTime:Te,totalTime:V,matchRate:xe}}},Xc={measureMemoryUsage:async(o,l=100)=>{let M=[],k=[];if(globalThis.gc)globalThis.gc();let L=Nt.memoryUsage().heapUsed;for(let xe=0;xe<l;xe++){let ve=await o();M.push(ve);let Pe=Nt.memoryUsage();if(k.push(Pe.heapUsed),xe%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let V=Nt.memoryUsage().heapUsed,pe=k.reduce((xe,ve)=>xe+ve,0)/k.length,he=Math.max(...k),Te=V-L>1048576;return{averageHeapUsed:pe,maxHeapUsed:he,memoryLeakDetected:Te,results:M}},testRouteHandlerMemoryLeaks:async(o,l=1000)=>{if(globalThis.gc)globalThis.gc();let M=Nt.memoryUsage().heapUsed;for(let pe=0;pe<l;pe++){let he=Ne();if(await o(he),pe%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let k=Nt.memoryUsage().heapUsed,L=k-M;return{memoryLeakDetected:L>5242880,initialMemory:M,finalMemory:k,memoryGrowth:L}}},Qc={rampUpTest:async(o,l,M)=>{let k=[],L=10,V=M.testDuration/10,pe=(M.endConcurrency-M.startConcurrency)/10;for(let he=0;he<10;he++){let Te=Math.round(M.startConcurrency+pe*he),ve=await new Kt(o,{duration:V,concurrency:Te,requestsPerSecond:Te*2}).run(l);k.push({concurrency:Te,requestsPerSecond:ve.requestsPerSecond,averageResponseTime:ve.averageResponseTime,errorRate:ve.failedRequests/ve.totalRequests})}return k},spikeTest:async(o,l,M)=>{let L=await new Kt(o,{duration:30000,concurrency:M.normalLoad}).run(l),pe=await new Kt(o,{duration:M.spikeDuration,concurrency:M.spikeLoad}).run(l),Te=await new Kt(o,{duration:30000,concurrency:M.normalLoad}).run(l);return{normalPhase:L,spikePhase:pe,recoveryPhase:Te}}},Zc={responseTimeWithin:(o,l)=>{if(o>l)throw Error(`Response time ${o}ms exceeds maximum ${l}ms`)},throughputAtLeast:(o,l)=>{if(o<l)throw Error(`Throughput ${o} RPS is below minimum ${l} RPS`)},errorRateBelow:(o,l)=>{if(o>l)throw Error(`Error rate ${(o*100).toFixed(2)}% exceeds maximum ${(l*100).toFixed(2)}%`)},memoryUsageWithin:(o,l)=>{if(o>l)throw Error(`Memory usage ${(o/1024/1024).toFixed(2)}MB exceeds maximum ${(l/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(o,l=5242880)=>{if(o>l)throw Error(`Potential memory leak detected: ${(o/1024/1024).toFixed(2)}MB growth`)}};function Yc(){return new ks}function el(o,l){return new Kt(o,l)}var Ss={getCurrentMemoryUsage:()=>{let o=Nt.memoryUsage();return{heapUsed:o.heapUsed,heapTotal:o.heapTotal,external:o.external,rss:o.rss}},getCPUUsage:()=>{let o=Nt.cpuUsage();return{user:o.user,system:o.system}},createMetricSnapshot:(o)=>({responseTime:o,memoryUsage:Ss.getCurrentMemoryUsage(),cpuUsage:Ss.getCPUUsage()}),formatResults:(o)=>JSON.stringify(o,null,2)};class sn{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(o,l){this.originalResponse=o,this.status=o.status,this.statusText=o.statusText,this.headers=this.parseHeaders(o.headers),this.cookies=this.parseCookies(o.headers.get("set-cookie")),this.redirected=o.redirected,this.url=o.url,this.ok=o.ok,this.type=o.type,this.body=l,this.text=typeof l==="string"?l:JSON.stringify(l);try{this.json=typeof l==="string"?JSON.parse(l):l}catch{this.json=null}}parseHeaders(o){let l={};return o.forEach((M,k)=>{l[k.toLowerCase()]=M}),l}parseCookies(o){if(!o)return{};let l={};return o.split(",").forEach((M)=>{let[k]=M.trim().split(";"),[L,V]=k.split("=");if(L&&V)l[L.trim()]=V.trim()}),l}expectStatus(o){if(this.status!==o)throw Error(`Expected status ${o}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(o,l){let M=this.headers[o.toLowerCase()];if(M===void 0)throw Error(`Expected header '${o}' to be present`);if(l!==void 0&&M!==l)throw Error(`Expected header '${o}' to be '${l}', got '${M}'`);return this}expectBody(o){if(typeof o==="string"){if(this.text!==o)throw Error(`Expected body '${o}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(o))throw Error(`Expected body ${JSON.stringify(o)}, got ${JSON.stringify(this.json)}`);return this}expectJson(o){if(JSON.stringify(this.json)!==JSON.stringify(o))throw Error(`Expected JSON ${JSON.stringify(o)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(o){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(o).forEach(([l,M])=>{let k=this.json[l];if(typeof M==="object"&&M!==null&&typeof k==="object"&&k!==null){let L=JSON.stringify(M),V=JSON.stringify(k);if(L!==V)throw Error(`Expected JSON property '${l}' to be ${L}, got ${V}`)}else if(k!==M)throw Error(`Expected JSON property '${l}' to be '${M}', got '${k}'`)}),this}expectCookie(o,l){let M=this.cookies[o];if(M===void 0)throw Error(`Expected cookie '${o}' to be present`);if(l!==void 0&&M!==l)throw Error(`Expected cookie '${o}' to be '${l}', got '${M}'`);return this}expectRedirect(o){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(o){let l=this.headers.location;if(l!==o)throw Error(`Expected redirect to '${o}', got '${l}'`)}return this}expectValidationError(o,l){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(o){let M=this.json?.errors||this.json?.message;if(!M||!M[o])throw Error(`Expected validation error for field '${o}'`);if(l){if(!(Array.isArray(M[o])?M[o]:[M[o]]).includes(l))throw Error(`Expected validation error message '${l}' for field '${o}'`)}}return this}expectContentType(o){let l=this.headers["content-type"];if(!l||!l.includes(o))throw Error(`Expected content type '${o}', got '${l}'`);return this}expectBodyContains(o){if(!this.text.includes(o))throw Error(`Expected body to contain '${o}'`);return this}expectBodyMatches(o){if(!o.test(this.text))throw Error(`Expected body to match pattern ${o}`);return this}expectJsonStructure(o){return this.validateStructure(this.json,o,"root"),this}validateStructure(o,l,M){if(l&&typeof l==="object"&&l.$$typeof)return;if(Array.isArray(l)){if(!Array.isArray(o))throw TypeError(`Expected ${M} to be an array`);if(l.length>0&&o.length>0)this.validateStructure(o[0],l[0],`${M}[0]`)}else if(typeof l==="object"&&l!==null){if(typeof o!=="object"||o===null)throw Error(`Expected ${M} to be an object`);Object.keys(l).forEach((k)=>{if(!(k in o))throw Error(`Expected ${M} to have property '${k}'`);this.validateStructure(o[k],l[k],`${M}.${k}`)})}}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 Hs(o){let l=await o.text();return new sn(o,l)}function rl(o=200,l,M){let k=new Headers(M);if(l&&typeof l==="object"&&!k.has("content-type"))k.set("content-type","application/json");let L=new Response(l?typeof l==="string"?l:JSON.stringify(l):null,{status:o,headers:k});return new sn(L,l)}class qr{router;config;defaultHeaders;constructor(o,l={}){this.router=o,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:(M)=>M>=200&&M<300,...l},this.defaultHeaders=l.defaultHeaders||{}}async get(o,l={}){return this.request("GET",o,l)}async post(o,l={}){return this.request("POST",o,l)}async put(o,l={}){return this.request("PUT",o,l)}async patch(o,l={}){return this.request("PATCH",o,l)}async delete(o,l={}){return this.request("DELETE",o,l)}async options(o,l={}){return this.request("OPTIONS",o,l)}async head(o,l={}){return this.request("HEAD",o,l)}async request(o,l,M={}){let k={...this.defaultHeaders,...M.headers},L={...M,headers:k},V=new Pt(o,l,L).build();try{let pe=await this.handleRequest(V);return await Hs(pe)}catch(pe){throw Error(`Test request failed: ${pe instanceof Error?pe.message:"Unknown error"}`)}}async handleRequest(o){let l=new URL(o.url),M=this.findMatchingRoute(o.method,l.pathname);if(!M)return new Response("Not Found",{status:404});let{route:k,params:L}=M;o.params={...o.params,...L};try{return await this.executeMiddlewareChain(o,k)||new Response("No response",{status:500})}catch(V){return new Response(JSON.stringify({error:V instanceof Error?V.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(o,l){for(let M of this.router.routes){if(M.method.toLowerCase()!==o.toLowerCase())continue;let k=this.matchPath(M.path,l);if(k!==null)return{route:M,params:k}}return null}matchPath(o,l){let M=o.split("/"),k=l.split("/");if(M.length!==k.length)return null;let L={};for(let V=0;V<M.length;V++){let pe=M[V],he=k[V];if(pe.startsWith(":")){let Te=pe.slice(1);L[Te]=he}else if(pe!==he)return null}return L}async executeMiddlewareChain(o,l){let M=[...this.router.globalMiddleware,...l.middleware],k=0,L=async()=>{if(k<M.length){let pe=M[k++];return await pe(o,L)}else return await this.executeHandler(l.handler,o)};return await L()||new Response("No response",{status:500})}async executeHandler(o,l){if(typeof o==="function")return await o(l);else if(typeof o==="string")throw TypeError(`String handlers not supported in test environment: ${o}`);else if(typeof o==="object"&&o.handle)return await new o().handle(l);throw Error("Invalid handler type")}setDefaultHeaders(o){return this.defaultHeaders={...this.defaultHeaders,...o},this}auth(o,l="Bearer"){return this.defaultHeaders.Authorization=`${l} ${o}`,this}userAgent(o){return this.defaultHeaders["User-Agent"]=o,this}withConfig(o){return new qr(this.router,{...this.config,...o})}withHeaders(o){return new qr(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...o}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function Ar(o,l){return new qr(o,l)}var ol={for:(o,l)=>Ar(o,l),withConfig:(o)=>(l)=>Ar(l,o),withAuth:(o,l="Bearer")=>(M)=>Ar(M).auth(o,l),withHeaders:(o)=>(l)=>Ar(l).withHeaders(o)};import{mock as Ft}from"bun:test";class Mt{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(o=1000,l="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:o,reason:l}),this}send(o){if(!this.isConnected)throw Error("WebSocket is not connected");let l={type:typeof o==="string"?"text":"binary",data:o,timestamp:Date.now()};return this.messages.push(l),this}receive(o){if(!this.isConnected)throw Error("WebSocket is not connected");let l={type:typeof o==="string"?"text":"binary",data:o,timestamp:Date.now()};return this.emit("message",{type:"message",data:o}),this}ping(o){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:o}),this}pong(o){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:o}),this}on(o,l){if(!this.eventHandlers.has(o))this.eventHandlers.set(o,[]);return this.eventHandlers.get(o).push(l),this}off(o,l){let M=this.eventHandlers.get(o);if(M){let k=M.indexOf(l);if(k>-1)M.splice(k,1)}return this}emit(o,l){(this.eventHandlers.get(o)||[]).forEach((k)=>k(l))}getSentMessages(){return[...this.messages]}getMessagesByType(o){return this.messages.filter((l)=>l.type===o)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(o)=>this.send(o),close:(o,l)=>this.disconnect(o,l),ping:(o)=>this.ping(o),pong:(o)=>this.pong(o),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class As{tester;_data;constructor(o={}){this.tester=new Mt,this._data=o}send(o){this.tester.send(o)}close(o,l){this.tester.disconnect(o,l)}ping(o){this.tester.ping(o)}pong(o){this.tester.pong(o)}publish(o,l){this.tester.send(l)}subscribe(o){}unsubscribe(o){}isSubscribed(o){return!0}cork(o){o()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(o){this._data=o}getTester(){return this.tester}}var cl={onOpen:()=>Ft(async(o)=>{}),onMessage:(o)=>Ft(async(l,M)=>{if(o)l.send(o)}),onClose:()=>Ft(async(o,l,M)=>{}),onError:()=>Ft(async(o,l)=>{}),echo:()=>Ft(async(o,l)=>{o.send(l)}),broadcast:(o)=>Ft(async(l,M)=>{o.forEach((k)=>{if(k!==l&&k.readyState===1)k.send(M)})}),chatRoom:(o)=>Ft(async(l,M)=>{l.publish(o,M)})},ll={basicConnection:()=>new Mt().connect().send("Hello WebSocket").receive("Hello Client"),connectionFailure:()=>{let o=new Mt;return o.on("error",()=>{}),o},messageBroadcast:(o=3)=>{let l=Array.from({length:o},()=>new Mt().connect());return l[0].send("Broadcast message"),l.slice(1).forEach((M)=>M.receive("Broadcast message")),l},pingPong:()=>new Mt().connect().ping().pong(),connectionTimeout:()=>{let o=new Mt;return setTimeout(()=>{o.disconnect(1006,"Connection timeout")},100),o}},dl={isConnected:(o)=>{if(!o.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(o)=>{if(o.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(o,l)=>{if(!o.getSentMessages().some((L)=>{if(typeof l==="string"&&typeof L.data==="string")return L.data===l;return L.data===l}))throw Error("Expected message not found in sent messages")},messageCount:(o,l)=>{let M=o.getSentMessages();if(M.length!==l)throw Error(`Expected ${l} messages, but got ${M.length}`)},messageType:(o,l,M)=>{let k=o.getSentMessages();if(l>=k.length)throw Error(`Message at index ${l} does not exist`);if(k[l].type!==M)throw Error(`Expected message type '${M}', got '${k[l].type}'`)},readyState:(o,l)=>{let M=o.getState();if(M.readyState!==l)throw Error(`Expected ready state ${l}, got ${M.readyState}`)}},pl={testThroughput:async(o=1000,l=1024)=>{let M=new Mt().connect(),k="x".repeat(l),L=performance.now();for(let xe=0;xe<o;xe++)M.send(k);let pe=performance.now()-L,he=o/pe*1000,Te=pe/o;return{messagesPerSecond:he,totalTime:pe,averageLatency:Te}},testConcurrentConnections:async(o=100)=>{let l={successfulConnections:0,failedConnections:0,averageConnectionTime:0},M=[],k=Array.from({length:o},async()=>{let L=performance.now();try{new Mt().connect();let pe=performance.now();M.push(pe-L),l.successfulConnections++}catch(V){console.error("WebSocket connection failed:",V),l.failedConnections++}});return await Promise.all(k),l.averageConnectionTime=M.length>0?M.reduce((L,V)=>L+V,0)/M.length:0,l}};function hl(){return new Mt}function gl(o){return new As(o)}var ml={createClients:(o)=>Array.from({length:o},()=>new Mt().connect()),withLatency:(o,l)=>{let M=o.send.bind(o);return o.send=(k)=>(setTimeout(()=>M(k),l),o),o},withPacketLoss:(o,l)=>{let M=o.send.bind(o);return o.send=(k)=>{if(Math.random()>l)M(k);return o},o},*messageGenerator(o,l="Message"){for(let M=1;M<=o;M++)yield`${l} ${M}`}};class on extends Error{status;response;body;constructor(o,l){let M=typeof l?.message==="string"?l.message:o.statusText||"Request failed";super(`${o.status} ${M}`);this.name="TypedClientError",this.status=o.status,this.response=o,this.body=l}}function qs(o,l){if(!l)return o;let M=o;for(let[k,L]of Object.entries(l)){let V=encodeURIComponent(L);M=M.split(`{${k}}`).join(V),M=M.replace(new RegExp(`:${k}(?![A-Z0-9_])`,"gi"),V)}return M}function Os(o,l){if(!l)return o;let M=new URLSearchParams;for(let[L,V]of Object.entries(l))if(V!==void 0&&V!==null)M.append(L,String(V));let k=M.toString();if(!k)return o;return o.includes("?")?`${o}&${k}`:`${o}?${k}`}async function go(o){if(o.status===204||o.headers.get("content-length")==="0")return;if((o.headers.get("content-type")??"").includes("json"))try{return await o.json()}catch{return}return await o.text()}function mo(o){let l=o.baseUrl.replace(/\/+$/,""),M=o.fetch??globalThis.fetch;async function k(){if(typeof o.headers==="function")return await o.headers();return o.headers??{}}async function L(V,pe,he,Te,xe){let ve=Os(`${l}${qs(pe,xe?.params)}`,xe?.query),Pe={accept:"application/json",...await k(),...xe?.headers};if(Te&&Pe["content-type"]===void 0&&Pe["Content-Type"]===void 0)Pe["content-type"]="application/json";let Ce=await M(ve,{method:V,headers:Pe,...Te?{body:JSON.stringify(he)}:{},...o.credentials?{credentials:o.credentials}:{},...xe?.signal?{signal:xe.signal}:{}}),Ee=await go(Ce);if(!Ce.ok){let Me=new on(Ce,Ee);if(o.onError)return o.onError(Me);throw Me}return Ee}return{get:(V,pe)=>L("GET",V,void 0,!1,pe),post:(V,pe,he)=>L("POST",V,pe,!0,he),put:(V,pe,he)=>L("PUT",V,pe,!0,he),patch:(V,pe,he)=>L("PATCH",V,pe,!0,he),delete:(V,pe)=>L("DELETE",V,void 0,!1,pe),async raw(V,pe,he){let{params:Te,query:xe,...ve}=he??{},Pe=Os(`${l}${qs(pe,Te)}`,xe);return await M(Pe,{method:V,...ve,headers:{...await k(),...ve.headers},...o.credentials?{credentials:o.credentials}:{}})}}}function fo(o){return o}var Ro=["get","post","put","patch","delete"];function yo(o,l,M,k){if(!k)return;let L=o,V=(pe)=>{let he=L?.[pe];if(typeof he!=="function")throw TypeError(`[typed-router] ${l.toUpperCase()} ${M}: this router's route does not support .${String(pe)}(), so the \`${String(pe)}\` option cannot be applied. Register the route directly instead of dropping it.`);return he};if(k.middleware)V("middleware").call(L,k.middleware);if(k.name)V("name").call(L,k.name);if(k.skipCsrf)V("skipCsrf").call(L);if(k.requireCsrf)V("requireCsrf").call(L);if(k.rateLimit)V("rateLimit").call(L,k.rateLimit.max,k.rateLimit.window??"minute")}function wo(o){let l={};for(let M of Ro)l[M]=(k,L,V)=>(yo(o[M](k,L),M,k,V),l);return l}export{un as ApiKeyManager,Is as Auth,cr as AuthTester,_ as BindingBuilder,oo as BuiltInRules,pa as CacheInvalidation,a as Container,w as ContentSecurityPolicy,ue as ContextualContainer,h as Cors,r as Csrf,b as DDoSProtection,fn as DEFAULT_COMPRESSION,Pu as DatabaseRules,F as DatabaseSessionStore,de as DefaultServiceProviderManager,si as Dependencies,rr as DomainGroup,_n as DomainGroupBuilder,mt as DomainMatcher,Bu as EnhancementPresets,z as EnvironmentManager,gn as Errors,S as FileSecurity,O as FileSessionStore,c as FileUpload,Ot as FileUploadTester,nn as FileValidationTester,ke as FluentRouteBuilder,sr as FluentRouter,uo as GenericMockModel,E as Helmet,ye as InMemoryNonceStore,R as InputValidation,an as JWT,tn as JWTTester,m as JsonBody,Kt as LoadTester,u as MemorySessionStore,Cs as MiddlewareChainTester,ii as MiddlewareFactory,Yr as MiddlewareGroupRegistry,Ts as MiddlewareHelpers,_r as MiddlewarePipeline,Ps as MiddlewareTester,lo as MockPostClass,As as MockServerWebSocket,co as MockUserClass,Ms as ModelBindingTester,Es as ModelResolverTester,cn as OAuth2Helper,N as PerformanceAlerting,q as PerformanceDashboard,H as PerformanceMonitor,ks as PerformanceTester,A as RateLimit,Un as RateLimitRegistry,ma as RateLimitUtils,xr as RateLimiter,I as RedisSessionStore,g as RequestId,f as RequestSigning,B as RequestTracer,wn as ResponseBuilder,lt as RouteBuilder,Fn as RouteCacheFactory,Bn as RouteCacheKeyGenerator,Dn as RouteCacheManager,Li as RouteFactory,jn as RouteGroupBuilder,Ou as RouteHelpers,$e as Router,zi as RouterUtils,v as Security,j as SecuritySuite,y as Session,K as SessionManager,rn as SessionTester,n as SignatureError,ni as SkipConditions,wa as SubdomainPatterns,Lr as SubdomainRouter,ya as SubdomainUtils,qr as TestClient,Pt as TestRequestBuilder,sn as TestResponseWrapper,Ai as ThrottleFactory,on as TypedClientError,xs as ValidationFluentRouter,Eu as ValidationHelpers,vs as ValidationMiddlewareBuilder,Qr as ValidationRuleBuilder,kr as Validator,Mt as WebSocketTester,Ue as apiKeyAuth,Yt as appendVary,Yi as applyRequestEnhancements,$t as applyResponseCompression,St as auth,mc as authHelpers,gc as authMocks,He as basicAuth,Be as bearerAuth,Bc as benchmarkMiddleware,Kc as benchmarkTests,Yo as buildUrlWithPreservedParams,$i as clearNamedRoutes,Lo as compressResponse,e as config,Ic as constraintHelpers,We as contentSecurityPolicy,Rt as cors,fc as createAuthTester,Re as createContainer,gr as createCookieAccessor,Zr as createEnhancementMiddleware,Cc as createFileUploadTester,$u as createFluentRouter,Ji as createHandlerResolver,jt as createInMemoryCookieAccessor,Rc as createJWTTester,el as createLoadTester,$c as createMiddlewareSpy,Ne as createMockRequest,rl as createMockResponse,gl as createMockServerWebSocket,jc as createModelBindingTester,Lc as createModelResolverTester,Ea as createPathRegex,Yc as createPerformanceTester,Gt as createRateLimitMiddleware,Nn as createRouteCacheMiddleware,bt as createSessionStore,yc as createSessionTester,Ra as createSubdomainMiddleware,Ar as createTestClient,Hs as createTestResponse,mo as createTypedClient,wo as createTypedRouter,Hr as createValidationMiddleware,hl as createWebSocketTester,Ct as csrf,Ge as ddosProtection,_t as decodeParam,me as defaultConfig,Zo as defaultQueryPreservationConfig,fo as defineEndpoint,Qe as documentUpload,Qs as enableRequestContext,fe as extractApiKey,ge as extractBasicAuth,W as extractBearerToken,vr as extractParamNames,Wn as fileExists,Ke as fileUpload,Pc as fileUploadAssertions,xc as fileUploadMocks,vc as fileUploadScenarios,fi as generateQueryPreservationScript,D as generateSessionId,wt as getConfig,we as getContainer,mn as getCurrentRequest,zr as getNamedRoutePath,Oi as getNamedRoutes,oi as globalMiddlewarePipeline,Cu as globalValidator,Ye as imageUpload,Rr as injectQueryPreservationScript,Ze as inputValidation,Di as isActionClass,Rn as isCompressible,Ma as isRouteHandler,kt as joinPaths,vt as jsonBody,je as jwtAuth,ft as matchPath,Xc as memoryTests,J as middleware,dt as middlewareGroups,Ac as mockMiddleware,Uc as modelMocks,Xe as multipleFileUpload,_o as negotiateEncoding,nr as normalizePath,Le as oauth2Auth,Wt as parseThrottleString,ti as peekBody,et as performanceAlerting,Zc as performanceAssertions,tt as performanceDashboard,rt as performanceMonitor,Ss as performanceUtils,Vn as processHtmlTemplate,G as rateLimit,In as rateLimitRegistry,At as registerNamedRoute,Zs as request,xt as requestId,_e as requestSigning,nt as requestTracer,ir as resolveHandler,Gr as resolveViewPath,Ae as response,Go as responseBuilder,zt as routeCacheManager,_c as routeModelHelpers,Gi as router,Mu as rule,Fr as runWithRequest,Ur as runWithRequestArguments,zc as scopedBindingHelpers,st as security,it as securitySuite,Tt as session,be as setContainer,fr as setCurrentRequest,jo as shouldCompress,ze as signRequest,Je as singleFileUpload,Oc as spyOnMiddleware,Qc as stressTests,ol as testClient,Mc as testFiles,Hc as testMiddleware,qc as testMiddlewareChain,cc as testRequest,Ca as toActionPath,Bi as url,qu as validate,Sa as validatePath,Ve as verifySignature,Ie as wrapResponse,dl as wsAssertions,cl as wsHandlerMocks,pl as wsPerformance,ll as wsTestScenarios,ml as wsTestUtils};