@stacksjs/bun-router 0.1.17 → 0.1.18
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/cli.js +1 -1
- package/dist/index.js +13 -13
- package/dist/response/response-factory.d.ts +0 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
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 $r(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 un{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=$r(JSON.stringify(M)),pe=$r(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 $r(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 cn{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 ln{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 Is={JWT:un,ApiKeyManager:cn,OAuth2Helper:ln},_s=Is;var mn={};qe(mn,{AuthenticationException:()=>X,AuthorizationException:()=>Y,BugsnagReporter:()=>Nr,BusinessLogicException:()=>se,CircuitBreaker:()=>hr,CircuitBreakerHttpClient:()=>dn,CircuitBreakerOpenException:()=>C,CircuitBreakerPresets:()=>zs,CircuitBreakerRegistry:()=>It,CircularDependencyException:()=>p,ConfigurationException:()=>ie,CustomReporter:()=>pn,DatabaseException:()=>ne,DegradationStrategies:()=>Xs,ErrorFactory:()=>i,ErrorReportingManager:()=>Xt,ErrorReportingPresets:()=>Js,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:()=>Dr,ServiceHealthMonitor:()=>Ur,ServiceUnavailableException:()=>re,TimeoutException:()=>x,ValidationException:()=>d,circuitBreaker:()=>js,createAdvancedErrorHandler:()=>gn,createCircuitBreaker:()=>Gs,createCircuitBreakerMiddleware:()=>Ls,createErrorReporting:()=>Vs,createGracefulDegradationMiddleware:()=>Ks,detectRouteConflicts:()=>at,findSimilarRoutes:()=>ot,globalCircuitBreakerRegistry:()=>Br,withCircuitBreaker:()=>Ws});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 js(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 dn{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 Ls(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 zs={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}})},Br=new It;function Gs(o){return Br.register(o)}async function Ws(o,l){return Br.execute(o,l)}class Dr{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 Nr{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 pn{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 Dr(l));break;case"bugsnag":this.reporters.push(new Nr(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 Vs(o){return new Xt(o)}var Js={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 Ur{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 Ur(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 Ks(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 Xs={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 hn{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 gn(o={}){let l=new hn(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 Qs}from"async_hooks";var mr=new Qs,Zt=!1,ht=null;function Zs(){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 Ir(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 fn(){if(!Zt)return Zt=!0,ht??void 0;return mr.getStore()?.current??ht??void 0}function Ys(){let o=fn();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 Rn={enabled:!0,level:6,threshold:1024};function yn(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 Go(o){return wn(o).encoding}function wn(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 Wo(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(!yn(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??Rn.enabled))return o;let L=o.headers;if(L.has("content-encoding"))return o;if(o.status===204)return o;let V=M.threshold??Rn.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}=wn(pe),Pe=yn(L.get("content-type"))&&o.status!==206;if(!ve&&o.status!==304&&o.body){if(!xe||!Pe)return ei(o);return _r(o,o.body,xe)}if(!xe||Te||!Pe||o.status===304||!o.body)return Yt(L,"Accept-Encoding"),o;if(!Number.isFinite(he))return ti(o,xe,V);return _r(o,o.body,xe)}function ei(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 Vo(o,l,M={}){return $t(o,l,M)}async function ti(o,l,M){let k=await si(o.body,M);if(k.ended&&k.size<M){let L=new Headers(o.headers);return Yt(L,"Accept-Encoding"),L.set("Content-Length",String(k.size)),new Response(k.body,{status:o.status,statusText:o.statusText,headers:L})}return _r(o,ni(k),l)}function _r(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})}function ri(o,l){if(o.length===1)return o[0];let M=new Uint8Array(l),k=0;for(let L of o)M.set(L,k),k+=L.byteLength;return M}function ni(o){return o.body instanceof Uint8Array?new Response(o.body).body:o.body}async function si(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}if(V)return M.releaseLock(),{body:ri(k,L),size:L,ended:V};return{body:new ReadableStream({start(he){for(let Te of k)he.enqueue(Te)},async pull(he){let{value:Te,done:xe}=await M.read();if(xe){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 bn{_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 Ko(){return new bn}import ii from"process";class jr{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 oi={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=ii.env.NODE_ENV||"development";return o.includes(l)}})},ai={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})},ui={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}},ci=new jr;import{existsSync as xn,readdirSync as li,statSync as di}from"fs";import{basename as vn,extname as Tn,join as pi,resolve as Pn}from"path";var hi=[".ts",".js"],gi=["routes","src/routes"],mi=["web","index"];function fi(){let o=process.cwd();for(let l of gi){let M=Pn(o,l);if(xn(M)&&di(M).isDirectory())return M}return null}function Cn(o,l){let M=[];if(!xn(o))return M;let k=li(o,{withFileTypes:!0});for(let L of k){if(L.name.startsWith(".")||L.name.startsWith("_"))continue;let V=pi(o,L.name);if(L.isDirectory())M.push(...Cn(V,l));else if(hi.includes(Tn(L.name))){let pe=o===l?"":o.slice(l.length),he=vn(L.name,Tn(L.name)),Te=mi.includes(he)?pe||"":`${pe}/${he}`;M.push({filePath:V,prefix:Te})}}return M}async function Ri(o,l,M,k){try{let L=await import(l),V=0,pe=o.routes?.length||0;if(typeof L.default==="function"){let he=yi(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 ${vn(l)} (${V} routes)`);return V}catch(L){return console.error(`[bun-router] Failed to load route file ${l}:`,L),0}}function yi(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 Mn(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||fi();if(!l){this._apiRoutesInitialized=!0;return}let M=this.config?.verbose||!1,k=Cn(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 Ri(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=Pn(l),this},writable:!0,configurable:!0}})}import{join as er,relative as Lr,resolve as Et,dirname as bi}from"path";import{readdirSync as En,statSync as Ti,existsSync as yr}from"fs";var ra={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function wi(o){let{preserve:l=[],exclude:M=[],routes:k=[]}=o;if(!l.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 Br(o){return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function hr(o){o=o.replace(/-/g,"+").replace(/_/g,"/");while(o.length%4)o+="=";return atob(o)}class cn{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=Br(JSON.stringify(M)),pe=Br(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(hr(k)),he=JSON.parse(hr(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(hr(M)),payload:JSON.parse(hr(k))}}catch{return null}}createSignature(o,l,M){return Br(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 ln{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 dn{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 _s={JWT:cn,ApiKeyManager:ln,OAuth2Helper:dn},js=_s;var fn={};qe(fn,{AuthenticationException:()=>X,AuthorizationException:()=>Y,BugsnagReporter:()=>Ur,BusinessLogicException:()=>se,CircuitBreaker:()=>gr,CircuitBreakerHttpClient:()=>pn,CircuitBreakerOpenException:()=>C,CircuitBreakerPresets:()=>Gs,CircuitBreakerRegistry:()=>It,CircularDependencyException:()=>p,ConfigurationException:()=>ie,CustomReporter:()=>hn,DatabaseException:()=>ne,DegradationStrategies:()=>Qs,ErrorFactory:()=>i,ErrorReportingManager:()=>Xt,ErrorReportingPresets:()=>Ks,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:()=>Nr,ServiceHealthMonitor:()=>Fr,ServiceUnavailableException:()=>re,TimeoutException:()=>x,ValidationException:()=>d,circuitBreaker:()=>Ls,createAdvancedErrorHandler:()=>mn,createCircuitBreaker:()=>Ws,createCircuitBreakerMiddleware:()=>zs,createErrorReporting:()=>Js,createGracefulDegradationMiddleware:()=>Xs,detectRouteConflicts:()=>at,findSimilarRoutes:()=>ot,globalCircuitBreakerRegistry:()=>Dr,withCircuitBreaker:()=>Vs});class gr{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 gr(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 Ls(o){let l=new gr(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 pn{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 zs(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 Gs={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}})},Dr=new It;function Ws(o){return Dr.register(o)}async function Vs(o,l){return Dr.execute(o,l)}class Nr{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 Ur{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 hn{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 Nr(l));break;case"bugsnag":this.reporters.push(new Ur(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 Js(o){return new Xt(o)}var Ks={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 Fr{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 Fr(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 Xs(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 Qs={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 gn{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 mn(o={}){let l=new gn(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 mr(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 mr({read:()=>l,write:(M,k)=>{l[M]=k},remove:(M)=>{delete l[M]}})}import{AsyncLocalStorage as Zs}from"async_hooks";var fr=new Zs,Zt=!1,ht=null;function Ys(){Zt=!0}function Ir(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 fr.run({current:o},l)}function _r(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 fr.run({current:o},l,M,k)}function Rr(o){let l=fr.getStore();if(l){l.current=o;return}if(ht!==null)ht=o}function Rn(){if(!Zt)return Zt=!0,ht??void 0;return fr.getStore()?.current??ht??void 0}function ei(){let o=Rn();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 yn={enabled:!0,level:6,threshold:1024};function wn(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 Vo(o){return bn(o).encoding}function bn(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(!wn(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??yn.enabled))return o;let L=o.headers;if(L.has("content-encoding"))return o;if(o.status===204)return o;let V=M.threshold??yn.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}=bn(pe),Pe=wn(L.get("content-type"))&&o.status!==206;if(!ve&&o.status!==304&&o.body){if(!xe||!Pe)return ti(o);return jr(o,o.body,xe)}if(!xe||Te||!Pe||o.status===304||!o.body)return Yt(L,"Accept-Encoding"),o;if(!Number.isFinite(he))return ri(o,xe,V);return jr(o,o.body,xe)}function ti(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 Ko(o,l,M={}){return $t(o,l,M)}async function ri(o,l,M){let k=await ii(o.body,M);if(k.ended&&k.size<M){let L=new Headers(o.headers);return Yt(L,"Accept-Encoding"),L.set("Content-Length",String(k.size)),new Response(k.body,{status:o.status,statusText:o.statusText,headers:L})}return jr(o,si(k),l)}function jr(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})}function ni(o,l){if(o.length===1)return o[0];let M=new Uint8Array(l),k=0;for(let L of o)M.set(L,k),k+=L.byteLength;return M}function si(o){return o.body instanceof Uint8Array?new Response(o.body).body:o.body}async function ii(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}if(V)return M.releaseLock(),{body:ni(k,L),size:L,ended:V};return{body:new ReadableStream({start(he){for(let Te of k)he.enqueue(Te)},async pull(he){let{value:Te,done:xe}=await M.read();if(xe){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}`)}import{Buffer as oi}from"buffer";function er(o,l,M,k){return new Response(o,{status:M,headers:{"Content-Type":l,"Content-Length":String(oi.byteLength(o)),...k}})}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 er(pe,"application/json",k,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={})=>er(o,"text/html; charset=utf-8",l,M),text:(o,l=200,M={})=>er(o,"text/plain; charset=utf-8",l,M),xml:(o,l=200,M={})=>er(o,"application/xml; charset=utf-8",l,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 er(JSON.stringify({message:o}),"application/json",429,M)}};class Tn{_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 Zo(){return new Tn}import ai from"process";class Lr{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 ui={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=ai.env.NODE_ENV||"development";return o.includes(l)}})},ci={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})},li={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}},di=new Lr;import{existsSync as vn,readdirSync as pi,statSync as hi}from"fs";import{basename as Pn,extname as xn,join as gi,resolve as Cn}from"path";var mi=[".ts",".js"],fi=["routes","src/routes"],Ri=["web","index"];function yi(){let o=process.cwd();for(let l of fi){let M=Cn(o,l);if(vn(M)&&hi(M).isDirectory())return M}return null}function Mn(o,l){let M=[];if(!vn(o))return M;let k=pi(o,{withFileTypes:!0});for(let L of k){if(L.name.startsWith(".")||L.name.startsWith("_"))continue;let V=gi(o,L.name);if(L.isDirectory())M.push(...Mn(V,l));else if(mi.includes(xn(L.name))){let pe=o===l?"":o.slice(l.length),he=Pn(L.name,xn(L.name)),Te=Ri.includes(he)?pe||"":`${pe}/${he}`;M.push({filePath:V,prefix:Te})}}return M}async function wi(o,l,M,k){try{let L=await import(l),V=0,pe=o.routes?.length||0;if(typeof L.default==="function"){let he=bi(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 ${Pn(l)} (${V} routes)`);return V}catch(L){return console.error(`[bun-router] Failed to load route file ${l}:`,L),0}}function bi(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 En(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||yi();if(!l){this._apiRoutesInitialized=!0;return}let M=this.config?.verbose||!1,k=Mn(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 wi(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=Cn(l),this},writable:!0,configurable:!0}})}import{join as tr,relative as zr,resolve as Et,dirname as xi}from"path";import{readdirSync as Sn,statSync as vi,existsSync as wr}from"fs";var ia={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function Ti(o){let{preserve:l=[],exclude:M=[],routes:k=[]}=o;if(!l.length)return"";return`<script data-query-preservation>
|
|
3
3
|
(function(){
|
|
4
4
|
var preserve = ${JSON.stringify(l)};
|
|
5
5
|
var exclude = ${JSON.stringify(M)};
|
|
@@ -76,30 +76,30 @@ catch (e) { return false; }
|
|
|
76
76
|
}
|
|
77
77
|
};
|
|
78
78
|
})();
|
|
79
|
-
</script>`}function
|
|
79
|
+
</script>`}function yr(o,l){if(!l.enabled||!l.preserve?.length)return o;let M=Ti(l);if(!M)return o;if(o.includes("</head>"))return o.replace("</head>",`${M}
|
|
80
80
|
</head>`);if(o.includes("</body>"))return o.replace("</body>",`${M}
|
|
81
|
-
</body>`);return o+M}function
|
|
81
|
+
</body>`);return o+M}function oa(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 Pi=["src/views","views","resources/views","app/views"],Ci=["_","components","layouts","partials","scripts","styles"],Mi=[".stx",".html"];function Ei(o=process.cwd()){for(let l of Pi){let M=Et(o,l);if(wr(M)&&vi(M).isDirectory())return M}return null}function kn(o,l,M){if(!wr(o))return!1;try{let k=Sn(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=tr(o,L.name);if(kn(V,l,M))return!0}}}catch{}return!1}function Si(o,l,M){let k=zr(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 Hn(o,l,M,k){let L=[];if(!wr(o))return L;let V=Sn(o,{withFileTypes:!0});for(let he of V){let Te=tr(o,he.name);if(k.some((xe)=>he.name.startsWith(xe)||he.name===xe))continue;if(he.isDirectory())L.push(...Hn(Te,l,M,k));else if(he.isFile()){if(M.some((ve)=>he.name.endsWith(ve))){let{routePath:ve,params:Pe}=Si(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
82
|
- ${Te.filePath}
|
|
83
83
|
- ${he.filePath}
|
|
84
|
-
Using: ${Te.filePath}`);else pe.set(he.routePath,he)}return Array.from(pe.values())}function
|
|
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
|
|
84
|
+
Using: ${Te.filePath}`);else pe.set(he.routePath,he)}return Array.from(pe.values())}function ki(o,l){let M=zr(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(wr(L))return L;return null}function Hi(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 Ai(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:Hi(Ee),ip:"",locale:null,params:M.params??{},method:String(M.method??"GET"),request:L},Ie={__filename:o,__dirname:xi(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,Is)=>{if(pt)Pe.headers[String(pt)]=String(Is)},definePageMeta:()=>{}};if(xe)await pe.extractVariables(xe,Ie,o);let Ft=k?.componentsDir?Et(k.componentsDir):tr(l,"components"),dr=k?.layoutsDir?Et(k.layoutsDir):tr(l,"layouts"),Ds=k?.partialsDir?Et(k.partialsDir):tr(l,"partials"),Ns={...pe.defaultConfig,componentsDir:Ft,layoutsDir:dr,partialsDir:Ds},Us=await pe.processDirectives(ve,Ie,o,Ns,new Set),pr=Number(Ie.__stxResponseStatus),Fs=Ie.__stxResponseHeaders;return{html:Us,status:Number.isInteger(pr)&&pr>=100&&pr<=599?pr:Pe.status,headers:{...Pe.headers,...Fs??{}}}}function qi(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 yr(Te,k);return Te}try{let Te=ki(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 Ai(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 An(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||Ei();if(!l){this._fileRoutesInitialized=!0;return}let M=this._fileRoutingConfig||{};if(M.enabled===!1){this._fileRoutesInitialized=!0;return}let k=M.extensions||Mi,L=M.exclude||Ci;if(!kn(l,k,L)){this._fileRoutesInitialized=!0;return}let V=Hn(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} -> ${zr(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=qi(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 br{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 br(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 Ie=gt.formatData(Oe,M);if(Ce.push(Ie),Ee+=Ie.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 br(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
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
|
|
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
|
|
87
|
+
`))}V.close()}catch(pe){V.error(pe)}}});return new br(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 Tr(o,l){try{o.close()}catch{}}function qn(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){Tr(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){Tr(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
89
|
`;if(he.event)Te+=`event: ${he.event}
|
|
90
90
|
`;if(he.retry)Te+=`retry: ${he.retry}
|
|
91
91
|
`;let xe=typeof he.data==="string"?he.data:JSON.stringify(he.data);Te+=`data: ${xe}
|
|
92
92
|
|
|
93
|
-
`,V.enqueue(pe.encode(Te))}V.close()}catch(he){
|
|
93
|
+
`,V.enqueue(pe.encode(Te))}V.close()}catch(he){Tr(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){Tr(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}})}import{Buffer as Oi}from"buffer";function xr(o,l){return new Response(o,{headers:{"Content-Type":l,"Content-Length":String(Oi.byteLength(o))}})}function $e(o){if(o instanceof Response)return o;if(o===null||o===void 0)return new Response(null,{status:204});if(typeof o==="string")return xr(o,"text/plain; charset=utf-8");if(typeof o==="number"||typeof o==="boolean")return xr(String(o),"text/plain; charset=utf-8");if(o instanceof ArrayBuffer||o instanceof Uint8Array)return new Response(o,{headers:{"Content-Type":"application/octet-stream","Content-Length":String(o.byteLength)}});if(o instanceof ReadableStream)return new Response(o);if(typeof o==="object")return xr(JSON.stringify(o),"application/json; charset=utf-8");return xr(String(o),"text/plain; charset=utf-8")}async function $i(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
94
|
Tried paths: ${V.join(", ")}
|
|
95
|
-
Last error: ${pe?.message||"Unknown error"}`)}function
|
|
95
|
+
Last error: ${pe?.message||"Unknown error"}`)}function On(o){return typeof o==="function"&&!o.prototype?.handle}async function rr(o,l,M){if(o instanceof Response)return o.clone();if(On(o)){let k=await o(l);return $e(k)}if(typeof o==="string")return Bi(o,l,M);if(typeof o==="function"&&o.prototype&&typeof o.prototype.handle==="function"){let V=await new o().handle(l);return $e(V)}if(o&&typeof o==="object"&&"handle"in o){let k=o;if(typeof k.handle==="function"){let L=await k.handle(l);return $e(L)}}throw Error(`Invalid handler type: ${typeof o}`)}async function Bi(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
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 $e(Me)}throw Error(`Controller "${pe}" is not a valid class`)}let L=await qi(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 $e(Te)}let pe=await V(l);return $e(pe)}if(V&&typeof V==="object"&&"handle"in V){let pe=V;if(typeof pe.handle==="function"){let he=await pe.handle(l);return $e(he)}}throw Error(`Handler "${o}" does not export a valid handler function or class`)}function $i(o){return(l,M)=>tr(l,M,o)}function On(o,l){if(o instanceof Response)return()=>o.clone();if(qn(o))return(M)=>{let k=o(M);if(k instanceof Response)return k;return k instanceof Promise?k.then($e):$e(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($e):$e(L)}}return(M)=>tr(o,M,l)}class xr 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 Bn{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 Bi=new Bn;async function $n(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 Dn(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=Bi.getBinding(V.name);if(he){let ve=null;if(typeof he==="function")ve=await he(pe);else ve=await $n(V.name,pe,he,V.key,L);if(!ve)throw new xr(V.name,pe,V.key||"id");L[V.name]=ve;continue}let Te=l[V.name];if(!Te)continue;let xe=await $n(V.name,pe,Te,V.key,L);if(!xe)throw new xr(V.name,pe,V.key||"id");L[V.name]=xe}return M.models=L,await k()}catch(V){if(V instanceof xr)return new Response(`${V.modelName} not found`,{status:404});throw V}}}class Nn{key;entry;prev;next;constructor(o,l,M=null,k=null){this.key=o;this.entry=l;this.prev=M;this.next=k}}class rr{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 Nn(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 Un{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 Fn{cache;tagIndex=new Map;keyTags=new Map;constructor(o=1000){this.cache=new rr({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 Fn;function In(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=Un.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 Di(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 Di(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 _n={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")})},ya={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 vr{cache;config;constructor(o,l=1e4){this.config=o,this.cache=new rr({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 jn{limiters=new Map;register(o,l){let M=new vr(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 Ln=new jn;function Gt(o,l){let M=l?Ln.getOrCreate(l,o):new vr(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=Ni(L)}return{maxAttempts:M,windowMs:k}}function Ni(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 Ui={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"})},Ta={fromString:(o,l)=>{let M=Wt(o);return Gt(M,l)},getInfo:async(o,l)=>{let M=new vr(l),{info:k}=await M.checkLimit(o);return k},reset:(o,l)=>{let M=Ln.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 nr{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 zr{domainGroups=[];wildcardGroup;domain(o){let l=mt.parseDomainPattern(o);return new zn(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 zn{router;pattern;group;constructor(o,l){this.router=o;this.pattern=l;this.group=new nr(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 Gn(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 Gn{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 va(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 Pa={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},Ca={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 Fi from"process";var Vt=new Map;function At(o,l){Vt.set(o,l)}function Gr(o){return Vt.get(o)}function Ii(){return new Map(Vt)}function _i(){Vt.clear()}function ji(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??Fi.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${Te.startsWith("http")?Te:`https://${Te}`}${V.startsWith("/")?V:`/${V}`}`}return V}import{join as Wn}from"path";function sr(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 Aa(o){return o.replace(/\//g,"_").toLowerCase()}function Li(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 qa(o){return typeof o==="function"&&!Li(o)}function Pr(o){let l=o.match(/\{([^}]+)\}/g);return l?l.map((M)=>M.slice(1,-1).replace("?","")):[]}function Oa(o){let l=o.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${l}$`)}var zi=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,Gi=/\{[^}]+\?\}/,Vn=new Map,Jn=new Map;function Wi(o){let l=Vn.get(o);if(l)return l;let M=o.endsWith("/*"),k=sr(o),L=0,V=k.split("/").filter(Boolean).map((he)=>{let Te=Gi.test(he);if(Te)L++;let xe=he.match(zi);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 Vn.set(o,pe),pe}function Vi(o){let l=Jn.get(o);if(l!==void 0)return l;let M;try{M=new RegExp(`^${o}$`)}catch{M=null}return Jn.set(o,M),M}function ft(o,l,M,k){let L=Wi(o);if(L.isWildcard&&l.startsWith(L.wildcardBase))return!0;let V=L.segments,pe=sr(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=Vi(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 sr(o.join("/"))}function $a(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 Kn(o){try{return await Bun.file(o).exists()}catch{return!1}}async function Wr(o,l,M){if(M.some((k)=>o.endsWith(k))){let k=sr(Wn(l,o));if(await Kn(k))return k;return null}for(let k of M){let L=sr(Wn(l,`${o}${k}`));if(await Kn(L))return L}return null}function Xn(o,l){let M=o.replace(/\{\{([^}]+)\}\}/g,(k,L)=>{let V=L.trim(),pe=Vr(l,V);return pe!==void 0?String(pe):k});return M=Ji(M,l),M=Ki(M,l),M}function Ji(o,l){return o.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(M,k,L,V="")=>{let pe=k.trim();return Vr(l,pe)?L:V})}function Ki(o,l){return o.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(M,k,L)=>{let V=Vr(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 Vr(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={..._n.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=Dn(l,this.modelBindings);o.push(M)}if(this.throttleConfig){let l=Gt(this.throttleConfig);o.push(l)}if(this.cacheConfig){let l=In(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 Qn{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 Zn{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 Yn{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 ir{routes=[];globalMiddleware=[];subdomainRouter=new zr;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 Yn(this,l)}when(o){return new Qn(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 Zn(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 ir;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 nr(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 ir;l(M);let k=mt.parseDomainPattern(o),L=new nr(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 $e(await o.handler(l))};return await V()}}var Xi={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}},Qi={route:(o,l={},M={})=>{let k=Gr(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"}})},Zi=new ir;function es(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 ts(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=Pr(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 rs(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 ns(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 tr(l,M,this.config)},writable:!0,configurable:!0},wrapResponse:{value:$e,writable:!0,configurable:!0},onError:{value(l){return this.errorHandler=l,this},writable:!0,configurable:!0}})}class ss{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 is=new ss;function os(o){Object.defineProperties(o.prototype,{modelRegistry:{value:is,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 Jr{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 Cr{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 Jr}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),Ie=l?.[Se]??Oe??"[^/]+",Ft=`(?<${Se}>${Ie})`,lr=xe.startsWith("/")?"/":"";return Ce?`(?:${lr}${Ft})?`:`${lr}${Ft}`}),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 as(o){Object.defineProperties(o.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new Cr({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 Cr({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 us(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,Ie)=>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 cs(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 Yi=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,eo=/bot|crawler|spider|crawling/i,Mr=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 ps{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 ps,ls=Symbol("bunRouterMacroProto"),Kr=Symbol("bunRouterMacroBase"),Er=new WeakMap,ds=-1;class Ne{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!==ds)Er=new WeakMap,ds=l;let M=Object.getPrototypeOf(o)??Object.prototype;if(M[ls]){if(Er.get(M[Kr])===M)return o;M=M[Kr]}let k=Er.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,ls,{value:!0}),Object.defineProperty(k,Kr,{value:M}),Er.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 Yi.test(this.headers.get("user-agent")||"")},isBot(){return eo.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=Mr.get(o);if(!M){let k=o.replace(/\*/g,".*").replace(/\?/g,".");if(M=new RegExp(`^${k}$`),Mr.size>=1000)Mr.clear();Mr.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 to(){Object.entries(ar).forEach(([o,l])=>{Ne.macro(o,l)})}to();function Sr(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 De{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 ms(this,l)}when(o){return new hs(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 gs(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=Pr(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(`
|
|
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 $e(Me)}throw Error(`Controller "${pe}" is not a valid class`)}let L=await $i(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 $e(Te)}let pe=await V(l);return $e(pe)}if(V&&typeof V==="object"&&"handle"in V){let pe=V;if(typeof pe.handle==="function"){let he=await pe.handle(l);return $e(he)}}throw Error(`Handler "${o}" does not export a valid handler function or class`)}function Di(o){return(l,M)=>rr(l,M,o)}function $n(o,l){if(o instanceof Response)return()=>o.clone();if(On(o))return(M)=>{let k=o(M);if(k instanceof Response)return k;return k instanceof Promise?k.then($e):$e(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($e):$e(L)}}return(M)=>rr(o,M,l)}class vr 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 Dn{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 Ni=new Dn;async function Bn(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 Nn(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=Ni.getBinding(V.name);if(he){let ve=null;if(typeof he==="function")ve=await he(pe);else ve=await Bn(V.name,pe,he,V.key,L);if(!ve)throw new vr(V.name,pe,V.key||"id");L[V.name]=ve;continue}let Te=l[V.name];if(!Te)continue;let xe=await Bn(V.name,pe,Te,V.key,L);if(!xe)throw new vr(V.name,pe,V.key||"id");L[V.name]=xe}return M.models=L,await k()}catch(V){if(V instanceof vr)return new Response(`${V.modelName} not found`,{status:404});throw V}}}class Un{key;entry;prev;next;constructor(o,l,M=null,k=null){this.key=o;this.entry=l;this.prev=M;this.next=k}}class nr{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 Un(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 Fn{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 In{cache;tagIndex=new Map;keyTags=new Map;constructor(o=1000){this.cache=new nr({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 In;function _n(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=Fn.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 Ui(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 Ui(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 jn={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")})},Ta={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 Pr{cache;config;constructor(o,l=1e4){this.config=o,this.cache=new nr({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 Ln{limiters=new Map;register(o,l){let M=new Pr(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 zn=new Ln;function Gt(o,l){let M=l?zn.getOrCreate(l,o):new Pr(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=Fi(L)}return{maxAttempts:M,windowMs:k}}function Fi(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 Ii={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"})},Pa={fromString:(o,l)=>{let M=Wt(o);return Gt(M,l)},getInfo:async(o,l)=>{let M=new Pr(l),{info:k}=await M.checkLimit(o);return k},reset:(o,l)=>{let M=zn.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 sr{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 Gr{domainGroups=[];wildcardGroup;domain(o){let l=mt.parseDomainPattern(o);return new Gn(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 Gn{router;pattern;group;constructor(o,l){this.router=o;this.pattern=l;this.group=new sr(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 Wn(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 Wn{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 Ma(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 Ea={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},Sa={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 _i from"process";var Vt=new Map;function At(o,l){Vt.set(o,l)}function Wr(o){return Vt.get(o)}function ji(){return new Map(Vt)}function Li(){Vt.clear()}function zi(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??_i.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${Te.startsWith("http")?Te:`https://${Te}`}${V.startsWith("/")?V:`/${V}`}`}return V}import{join as Vn}from"path";function ir(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 $a(o){return o.replace(/\//g,"_").toLowerCase()}function Gi(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 Ba(o){return typeof o==="function"&&!Gi(o)}function Cr(o){let l=o.match(/\{([^}]+)\}/g);return l?l.map((M)=>M.slice(1,-1).replace("?","")):[]}function Da(o){let l=o.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${l}$`)}var Wi=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,Vi=/\{[^}]+\?\}/,Jn=new Map,Kn=new Map;function Ji(o){let l=Jn.get(o);if(l)return l;let M=o.endsWith("/*"),k=ir(o),L=0,V=k.split("/").filter(Boolean).map((he)=>{let Te=Vi.test(he);if(Te)L++;let xe=he.match(Wi);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 Jn.set(o,pe),pe}function Ki(o){let l=Kn.get(o);if(l!==void 0)return l;let M;try{M=new RegExp(`^${o}$`)}catch{M=null}return Kn.set(o,M),M}function ft(o,l,M,k){let L=Ji(o);if(L.isWildcard&&l.startsWith(L.wildcardBase))return!0;let V=L.segments,pe=ir(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=Ki(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 ir(o.join("/"))}function Na(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 Xn(o){try{return await Bun.file(o).exists()}catch{return!1}}async function Vr(o,l,M){if(M.some((k)=>o.endsWith(k))){let k=ir(Vn(l,o));if(await Xn(k))return k;return null}for(let k of M){let L=ir(Vn(l,`${o}${k}`));if(await Xn(L))return L}return null}function Qn(o,l){let M=o.replace(/\{\{([^}]+)\}\}/g,(k,L)=>{let V=L.trim(),pe=Jr(l,V);return pe!==void 0?String(pe):k});return M=Xi(M,l),M=Qi(M,l),M}function Xi(o,l){return o.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(M,k,L,V="")=>{let pe=k.trim();return Jr(l,pe)?L:V})}function Qi(o,l){return o.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(M,k,L)=>{let V=Jr(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 Jr(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={...jn.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=Nn(l,this.modelBindings);o.push(M)}if(this.throttleConfig){let l=Gt(this.throttleConfig);o.push(l)}if(this.cacheConfig){let l=_n(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 Zn{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 Yn{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 es{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 or{routes=[];globalMiddleware=[];subdomainRouter=new Gr;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 es(this,l)}when(o){return new Zn(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 Yn(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 or;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 sr(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 or;l(M);let k=mt.parseDomainPattern(o),L=new sr(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 $e(await o.handler(l))};return await V()}}var Zi={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}},Yi={route:(o,l={},M={})=>{let k=Wr(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"}})},eo=new or;function ts(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 rs(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=Cr(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 ns(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 ss(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 rr(l,M,this.config)},writable:!0,configurable:!0},wrapResponse:{value:$e,writable:!0,configurable:!0},onError:{value(l){return this.errorHandler=l,this},writable:!0,configurable:!0}})}class is{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 os=new is;function as(o){Object.defineProperties(o.prototype,{modelRegistry:{value:os,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 Kr{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 Mr{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 Kr}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),Ie=l?.[Se]??Oe??"[^/]+",Ft=`(?<${Se}>${Ie})`,dr=xe.startsWith("/")?"/":"";return Ce?`(?:${dr}${Ft})?`:`${dr}${Ft}`}),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 us(o){Object.defineProperties(o.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new Mr({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 Mr({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 cs(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,Ie)=>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 ls(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 to=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,ro=/bot|crawler|spider|crawling/i,Er=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 hs{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 ar=new hs,ds=Symbol("bunRouterMacroProto"),Xr=Symbol("bunRouterMacroBase"),Sr=new WeakMap,ps=-1;class Ne{static macro(o,l){ar.register(o,l)}static macroAccessor(o,l){ar.register(o,l,!0)}static applyMacros(o){let l=ar.getEpoch();if(l!==ps)Sr=new WeakMap,ps=l;let M=Object.getPrototypeOf(o)??Object.prototype;if(M[ds]){if(Sr.get(M[Xr])===M)return o;M=M[Xr]}let k=Sr.get(M);if(!k){k=Object.create(M);for(let L of ar.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,ds,{value:!0}),Object.defineProperty(k,Xr,{value:M}),Sr.set(M,k)}return Object.setPrototypeOf(o,k),o}static hasMacro(o){return ar.has(o)}}var ur={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 to.test(this.headers.get("user-agent")||"")},isBot(){return ro.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[ur.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=Er.get(o);if(!M){let k=o.replace(/\*/g,".*").replace(/\?/g,".");if(M=new RegExp(`^${k}$`),Er.size>=1000)Er.clear();Er.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:ur.ip.call(this)};return btoa(JSON.stringify(l))},signature(o){let l=`${this.method}${this.url}${ur.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=ur.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 no(){Object.entries(ur).forEach(([o,l])=>{Ne.macro(o,l)})}no();function kr(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 De{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 fs(this,l)}when(o){return new gs(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 ms(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=Cr(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
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=Sr(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 hs{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 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}}class ms{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 Xr=null;function ro(){if(Xr===null)Xr=new De;return Xr}function no(o,l={}){if(typeof o.bearerToken==="function")return o;return ro().enhanceRequest(o,l)}function so(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 fs(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 Rs(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 io(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 Rs(M,l,he)}return pe instanceof Promise?pe.then((he)=>$t(he,l,M.config.compression),(he)=>Rs(M,l,he)):$t(pe,l,M.config.compression)}if(!Ne.hasMacro("getParam"))Ne.macro("getParam",function(o,l){let M=this.params?.[o];return M!==void 0?M:l});if(!Ne.hasMacro("getParamAsInt"))Ne.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(!Ne.hasMacro("get"))Ne.macro("get",function(o,l){let M=Jt(this).searchParams.get(o);return M!==null&&M!==void 0?M:l});Ne.macroAccessor("query",function(){return Sr(this)});Ne.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 ys(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(`
|
|
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=kr(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=mr({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 gs{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 ms{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 fs{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 Qr=null;function so(){if(Qr===null)Qr=new De;return Qr}function io(o,l={}){if(typeof o.bearerToken==="function")return o;return so().enhanceRequest(o,l)}function oo(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 Rs(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 ys(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 ao(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 ys(M,l,he)}return pe instanceof Promise?pe.then((he)=>$t(he,l,M.config.compression),(he)=>ys(M,l,he)):$t(pe,l,M.config.compression)}if(!Ne.hasMacro("getParam"))Ne.macro("getParam",function(o,l){let M=this.params?.[o];return M!==void 0?M:l});if(!Ne.hasMacro("getParamAsInt"))Ne.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(!Ne.hasMacro("get"))Ne.macro("get",function(o,l){let M=Jt(this).searchParams.get(o);return M!==null&&M!==void 0?M:l});Ne.macroAccessor("query",function(){return kr(this)});Ne.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 ws(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
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=On(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 fs(this,ve,L);if(ve instanceof Promise)return fs(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)=>Ir(ve,io,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=so(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 Ne.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 oo}from"path";function ws(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 Wr(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 Wr(oo("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=Xn(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[Ie,Ft]of Object.entries(xe.headers))Oe.set(Ie,Ft);return new Response(Me,{status:xe.status||200,headers:Oe})};return this.get(l,Ce,ve,Pe),this},writable:!0,configurable:!0}})}function bs(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 ao from"process";class Ts{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 Qr=new Ts;class ur extends Response{static macro(o,l){Qr.register(o,l),Response[o]=l}static callMacro(o,...l){let M=Qr.get(o);if(!M)throw Error(`Response macro "${o}" not found`);return M.handler(...l)}static hasMacro(o){return Qr.has(o)}}function kr(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}=kr(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}=kr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/html",...L}})},text:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=kr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/plain",...L}})},xml:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=kr(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}
|
|
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 Ir(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);Rr(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=$n(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 Rs(this,ve,L);if(ve instanceof Promise)return Rs(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)=>_r(ve,ao,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=oo(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,{});Rr(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 Ne.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 uo}from"path";function bs(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 Vr(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 Vr(uo("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=Qn(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=yr(Me,Se);let Oe=new Headers;if(Oe.set("Content-Type","text/html; charset=utf-8"),xe.headers)for(let[Ie,Ft]of Object.entries(xe.headers))Oe.set(Ie,Ft);return new Response(Me,{status:xe.status||200,headers:Oe})};return this.get(l,Ce,ve,Pe),this},writable:!0,configurable:!0}})}function Ts(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 co from"process";class xs{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 Zr=new xs;class cr extends Response{static macro(o,l){Zr.register(o,l),Response[o]=l}static callMacro(o,...l){let M=Zr.get(o);if(!M)throw Error(`Response macro "${o}" not found`);return M.handler(...l)}static hasMacro(o){return Zr.has(o)}}function Hr(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}=Hr(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}=Hr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/html",...L}})},text:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Hr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/plain",...L}})},xml:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Hr(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
102
|
`;if(l)k+=`event: ${l}
|
|
103
103
|
`;return k+=`data: ${o}
|
|
104
104
|
|
|
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:ao.uptime?.()||0};return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})}};function uo(){Object.entries(yt).forEach(([o,l])=>{ur.macro(o,l)})}uo();var co=/^[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,lo={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"&&co.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."}},Hu={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 Hr{rules={};config;constructor(o={}){this.config={stopOnFirstFailure:!1,bail:!1,...o},this.registerRules(lo)}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 Au=new Hr;function Ar(o,l){let M=new Hr(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 Zr{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 qu(){return new Zr}var Ou={rules(o){let l={};for(let[M,k]of Object.entries(o))l[M]=k instanceof Zr?k.build():k;return l},async validateValue(o,l,M="value"){return(await new Hr().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(Ar(this.validationRules,this.validatorConfig));return o.push(async(l,M)=>(Ne.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 vs{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 Yr(){return async(o,l)=>(Ne.applyMacros(o),o.startTime=Date.now(),await l())}class Ps{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 Ar(this.rules,this.config)}}function Fu(){return new Ps}var Iu={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 $e(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 vs}var xs={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)=>xs.when((M)=>!o(M),l),group:(o)=>xs.compose(...o)},ju={api:()=>[Yr(),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:()=>[Yr(),async(o,l)=>(o.session={},await l())],validation:(o,l)=>[Yr(),Ar(o,l)]};ts(De);rs(De);cs(De);as(De);ns(De);ws(De);bs(De);An(De);es(De);ys(De);us(De);os(De);Hn(De);Mn(De);class en{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 en;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 tn}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 fc={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 Fe(o="GET",l="/",M={}){return new Pt(o,l,M).build()}class cr{request;constructor(o){this.request=o||Fe()}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 rn{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 nn{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 nn(o).createSession()}}var Tc={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)=>tn(async(l,M)=>{if(o)return l.user=o,await M();return new Response("Unauthorized",{status:401})}),roleMiddleware:(o)=>tn(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)=>tn(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()})},xc={authenticatedRequest:(o,l)=>new cr(l).as(o).getRequest(),jwtRequest:(o={},l)=>{let k=new rn().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 vc(o){return new cr(o)}function Pc(o){return new rn(o)}function Cc(o){return new nn(o)}import{mock as Dt}from"bun:test";class Ot{request;files;constructor(o){this.request=o||Fe(),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 sn{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 kc={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(!sn.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(!sn.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}})}},Hc={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"})},Ac={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 qc(o){return new Ot(o)}var Oc={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 po}from"bun:test";class Cs{middleware;context;constructor(o){this.middleware=o,this.context=this.createContext()}createContext(){let o=Fe(),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 Nc(o){return new Cs(o)}var Uc={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 Ms{middlewares;request;finalHandler;constructor(o){this.middlewares=o,this.request=Fe(),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 Fc(o){return new Ms(o)}function Ic(o){return po(o,"call")}function _c(){let o=ut(async(l,M)=>await M());return{middleware:o,spy:o}}async function jc(o,l=1000){let M=[],k=Fe(),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 ho{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 go{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 mo{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 Es{request;options;constructor(o={}){this.options=o,this.request=Fe()}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 Wc={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}}}},Vc={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 Ss{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 Jc={testRoute:async(o,l,M)=>{let k=Fe("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 Kc(o){return new Es(o)}function Xc(){return new Ss}var fo=async(o,l)=>o.userId===l.id,Qc={testUserScoped:async(o,l,M=fo)=>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 Ro}from"bun:test";import Nt from"process";class Hs{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 rl={routeHandler:async(o,l=1000)=>{let M=[],k=Fe();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=Fe(),L=Ro(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}}},nl={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=Fe();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}}},sl={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}}},il={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 ol(){return new Hs}function al(o,l){return new Kt(o,l)}var ks={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:ks.getCurrentMemoryUsage(),cpuUsage:ks.getCPUUsage()}),formatResults:(o)=>JSON.stringify(o,null,2)};class on{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 As(o){let l=await o.text();return new on(o,l)}function cl(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 on(L,l)}class Or{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 As(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 Or(this.router,{...this.config,...o})}withHeaders(o){return new Or(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...o}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function qr(o,l){return new Or(o,l)}var hl={for:(o,l)=>qr(o,l),withConfig:(o)=>(l)=>qr(l,o),withAuth:(o,l="Bearer")=>(M)=>qr(M).auth(o,l),withHeaders:(o)=>(l)=>qr(l).withHeaders(o)};import{mock as Ut}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 qs{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 fl={onOpen:()=>Ut(async(o)=>{}),onMessage:(o)=>Ut(async(l,M)=>{if(o)l.send(o)}),onClose:()=>Ut(async(o,l,M)=>{}),onError:()=>Ut(async(o,l)=>{}),echo:()=>Ut(async(o,l)=>{o.send(l)}),broadcast:(o)=>Ut(async(l,M)=>{o.forEach((k)=>{if(k!==l&&k.readyState===1)k.send(M)})}),chatRoom:(o)=>Ut(async(l,M)=>{l.publish(o,M)})},Rl={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}},yl={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}`)}},wl={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 bl(){return new Mt}function Tl(o){return new qs(o)}var xl={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 an 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 Os(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 $s(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 yo(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 wo(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=$s(`${l}${Os(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 yo(Ce);if(!Ce.ok){let Me=new an(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=$s(`${l}${Os(pe,Te)}`,xe);return await M(Pe,{method:V,...ve,headers:{...await k(),...ve.headers},...o.credentials?{credentials:o.credentials}:{}})}}}function bo(o){return o}var To=["get","post","put","patch","delete"];function xo(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 vo(o){let l={};for(let M of To)l[M]=(k,L,V)=>(xo(o[M](k,L),M,k,V),l);return l}export{cn as ApiKeyManager,_s as Auth,cr as AuthTester,_ as BindingBuilder,lo as BuiltInRules,ya as CacheInvalidation,a as Container,w as ContentSecurityPolicy,ue as ContextualContainer,h as Cors,r as Csrf,b as DDoSProtection,Rn as DEFAULT_COMPRESSION,Hu as DatabaseRules,F as DatabaseSessionStore,de as DefaultServiceProviderManager,ai as Dependencies,nr as DomainGroup,zn as DomainGroupBuilder,mt as DomainMatcher,ju as EnhancementPresets,z as EnvironmentManager,mn as Errors,S as FileSecurity,O as FileSessionStore,c as FileUpload,Ot as FileUploadTester,sn as FileValidationTester,ke as FluentRouteBuilder,ir as FluentRouter,ho as GenericMockModel,E as Helmet,ye as InMemoryNonceStore,R as InputValidation,un as JWT,rn as JWTTester,m as JsonBody,Kt as LoadTester,u as MemorySessionStore,Ms as MiddlewareChainTester,ui as MiddlewareFactory,en as MiddlewareGroupRegistry,xs as MiddlewareHelpers,jr as MiddlewarePipeline,Cs as MiddlewareTester,mo as MockPostClass,qs as MockServerWebSocket,go as MockUserClass,Es as ModelBindingTester,Ss as ModelResolverTester,ln as OAuth2Helper,N as PerformanceAlerting,q as PerformanceDashboard,H as PerformanceMonitor,Hs as PerformanceTester,A as RateLimit,jn as RateLimitRegistry,Ta as RateLimitUtils,vr as RateLimiter,I as RedisSessionStore,g as RequestId,f as RequestSigning,B as RequestTracer,bn as ResponseBuilder,lt as RouteBuilder,_n as RouteCacheFactory,Un as RouteCacheKeyGenerator,Fn as RouteCacheManager,Xi as RouteFactory,Gn as RouteGroupBuilder,Iu as RouteHelpers,De as Router,Qi as RouterUtils,v as Security,j as SecuritySuite,y as Session,K as SessionManager,nn as SessionTester,n as SignatureError,oi as SkipConditions,Ca as SubdomainPatterns,zr as SubdomainRouter,Pa as SubdomainUtils,Or as TestClient,Pt as TestRequestBuilder,on as TestResponseWrapper,Ui as ThrottleFactory,an as TypedClientError,vs as ValidationFluentRouter,Ou as ValidationHelpers,Ps as ValidationMiddlewareBuilder,Zr as ValidationRuleBuilder,Hr as Validator,Mt as WebSocketTester,Ue as apiKeyAuth,Yt as appendVary,no as applyRequestEnhancements,$t as applyResponseCompression,St as auth,xc as authHelpers,Tc as authMocks,He as basicAuth,Be as bearerAuth,jc as benchmarkMiddleware,rl as benchmarkTests,na as buildUrlWithPreservedParams,_i as clearNamedRoutes,Vo as compressResponse,e as config,Vc as constraintHelpers,We as contentSecurityPolicy,Rt as cors,vc as createAuthTester,Re as createContainer,gr as createCookieAccessor,Yr as createEnhancementMiddleware,qc as createFileUploadTester,_u as createFluentRouter,$i as createHandlerResolver,jt as createInMemoryCookieAccessor,Pc as createJWTTester,al as createLoadTester,_c as createMiddlewareSpy,Fe as createMockRequest,cl as createMockResponse,Tl as createMockServerWebSocket,Kc as createModelBindingTester,Xc as createModelResolverTester,Oa as createPathRegex,ol as createPerformanceTester,Gt as createRateLimitMiddleware,In as createRouteCacheMiddleware,bt as createSessionStore,Cc as createSessionTester,va as createSubdomainMiddleware,qr as createTestClient,As as createTestResponse,wo as createTypedClient,vo as createTypedRouter,Ar as createValidationMiddleware,bl as createWebSocketTester,Ct as csrf,Ge as ddosProtection,_t as decodeParam,me as defaultConfig,ra as defaultQueryPreservationConfig,bo as defineEndpoint,Qe as documentUpload,Zs as enableRequestContext,fe as extractApiKey,ge as extractBasicAuth,W as extractBearerToken,Pr as extractParamNames,Kn as fileExists,Ke as fileUpload,Ac as fileUploadAssertions,kc as fileUploadMocks,Hc as fileUploadScenarios,wi as generateQueryPreservationScript,D as generateSessionId,wt as getConfig,we as getContainer,fn as getCurrentRequest,Gr as getNamedRoutePath,Ii as getNamedRoutes,ci as globalMiddlewarePipeline,Au as globalValidator,Ye as imageUpload,Rr as injectQueryPreservationScript,Ze as inputValidation,Li as isActionClass,yn as isCompressible,qa as isRouteHandler,kt as joinPaths,vt as jsonBody,je as jwtAuth,ft as matchPath,nl as memoryTests,J as middleware,dt as middlewareGroups,Uc as mockMiddleware,Wc as modelMocks,Xe as multipleFileUpload,Go as negotiateEncoding,sr as normalizePath,Le as oauth2Auth,Wt as parseThrottleString,si as peekBody,ni as peekedStream,et as performanceAlerting,il as performanceAssertions,tt as performanceDashboard,rt as performanceMonitor,ks as performanceUtils,Xn as processHtmlTemplate,G as rateLimit,Ln as rateLimitRegistry,At as registerNamedRoute,Ys as request,xt as requestId,_e as requestSigning,nt as requestTracer,tr as resolveHandler,Wr as resolveViewPath,Ae as response,Ko as responseBuilder,zt as routeCacheManager,Jc as routeModelHelpers,Zi as router,qu as rule,Fr as runWithRequest,Ir as runWithRequestArguments,Qc as scopedBindingHelpers,st as security,it as securitySuite,Tt as session,be as setContainer,fr as setCurrentRequest,Wo as shouldCompress,ze as signRequest,Je as singleFileUpload,Ic as spyOnMiddleware,sl as stressTests,hl as testClient,Oc as testFiles,Nc as testMiddleware,Fc as testMiddlewareChain,fc as testRequest,Aa as toActionPath,ji as url,Fu as validate,$a as validatePath,Ve as verifySignature,$e as wrapResponse,yl as wsAssertions,fl as wsHandlerMocks,wl as wsPerformance,Rl as wsTestScenarios,xl 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:co.uptime?.()||0};return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})}};function lo(){Object.entries(yt).forEach(([o,l])=>{cr.macro(o,l)})}lo();var po=/^[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,ho={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"&&po.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."}},Ou={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 Ar{rules={};config;constructor(o={}){this.config={stopOnFirstFailure:!1,bail:!1,...o},this.registerRules(ho)}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 $u=new Ar;function qr(o,l){let M=new Ar(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 Yr{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 Bu(){return new Yr}var Du={rules(o){let l={};for(let[M,k]of Object.entries(o))l[M]=k instanceof Yr?k.build():k;return l},async validateValue(o,l,M="value"){return(await new Ar().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(qr(this.validationRules,this.validatorConfig));return o.push(async(l,M)=>(Ne.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 Ps{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 en(){return async(o,l)=>(Ne.applyMacros(o),o.startTime=Date.now(),await l())}class Cs{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 qr(this.rules,this.config)}}function ju(){return new Cs}var Lu={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 cr.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return $e(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 zu(){return new Ps}var vs={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)=>vs.when((M)=>!o(M),l),group:(o)=>vs.compose(...o)},Gu={api:()=>[en(),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),cr.callMacro("error","Internal server error",void 0,500)}}],web:()=>[en(),async(o,l)=>(o.session={},await l())],validation:(o,l)=>[en(),qr(o,l)]};rs(De);ns(De);ls(De);us(De);ss(De);bs(De);Ts(De);qn(De);ts(De);ws(De);cs(De);as(De);An(De);En(De);class tn{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 tn;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 rn}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 wc={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 Fe(o="GET",l="/",M={}){return new Pt(o,l,M).build()}class lr{request;constructor(o){this.request=o||Fe()}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 nn{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 sn{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 sn(o).createSession()}}var Pc={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)=>rn(async(l,M)=>{if(o)return l.user=o,await M();return new Response("Unauthorized",{status:401})}),roleMiddleware:(o)=>rn(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)=>rn(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()})},Cc={authenticatedRequest:(o,l)=>new lr(l).as(o).getRequest(),jwtRequest:(o={},l)=>{let k=new nn().generateToken(o);return new lr(l).withJWT(k).getRequest()},sessionRequest:(o={},l)=>new lr(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 Mc(o){return new lr(o)}function Ec(o){return new nn(o)}function Sc(o){return new sn(o)}import{mock as Dt}from"bun:test";class Ot{request;files;constructor(o){this.request=o||Fe(),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 on{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 qc={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(!on.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(!on.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}})}},Oc={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"})},$c={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 Bc(o){return new Ot(o)}var Dc={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 go}from"bun:test";class Ms{middleware;context;constructor(o){this.middleware=o,this.context=this.createContext()}createContext(){let o=Fe(),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 Ic(o){return new Ms(o)}var _c={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 Es{middlewares;request;finalHandler;constructor(o){this.middlewares=o,this.request=Fe(),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 jc(o){return new Es(o)}function Lc(o){return go(o,"call")}function zc(){let o=ut(async(l,M)=>await M());return{middleware:o,spy:o}}async function Gc(o,l=1000){let M=[],k=Fe(),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 mo{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 fo{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 Ro{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 Ss{request;options;constructor(o={}){this.options=o,this.request=Fe()}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 Kc={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}}}},Xc={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 ks{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 Qc={testRoute:async(o,l,M)=>{let k=Fe("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 Zc(o){return new Ss(o)}function Yc(){return new ks}var yo=async(o,l)=>o.userId===l.id,el={testUserScoped:async(o,l,M=yo)=>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 wo}from"bun:test";import Nt from"process";class As{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 il={routeHandler:async(o,l=1000)=>{let M=[],k=Fe();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=Fe(),L=wo(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}}},ol={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=Fe();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}}},al={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}}},ul={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 cl(){return new As}function ll(o,l){return new Kt(o,l)}var Hs={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:Hs.getCurrentMemoryUsage(),cpuUsage:Hs.getCPUUsage()}),formatResults:(o)=>JSON.stringify(o,null,2)};class an{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 qs(o){let l=await o.text();return new an(o,l)}function pl(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 an(L,l)}class $r{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 qs(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 $r(this.router,{...this.config,...o})}withHeaders(o){return new $r(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...o}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function Or(o,l){return new $r(o,l)}var fl={for:(o,l)=>Or(o,l),withConfig:(o)=>(l)=>Or(l,o),withAuth:(o,l="Bearer")=>(M)=>Or(M).auth(o,l),withHeaders:(o)=>(l)=>Or(l).withHeaders(o)};import{mock as Ut}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 Os{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 wl={onOpen:()=>Ut(async(o)=>{}),onMessage:(o)=>Ut(async(l,M)=>{if(o)l.send(o)}),onClose:()=>Ut(async(o,l,M)=>{}),onError:()=>Ut(async(o,l)=>{}),echo:()=>Ut(async(o,l)=>{o.send(l)}),broadcast:(o)=>Ut(async(l,M)=>{o.forEach((k)=>{if(k!==l&&k.readyState===1)k.send(M)})}),chatRoom:(o)=>Ut(async(l,M)=>{l.publish(o,M)})},bl={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}},Tl={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}`)}},xl={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 vl(){return new Mt}function Pl(o){return new Os(o)}var Cl={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 un 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 $s(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 Bs(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 bo(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 To(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=Bs(`${l}${$s(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 bo(Ce);if(!Ce.ok){let Me=new un(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=Bs(`${l}${$s(pe,Te)}`,xe);return await M(Pe,{method:V,...ve,headers:{...await k(),...ve.headers},...o.credentials?{credentials:o.credentials}:{}})}}}function xo(o){return o}var vo=["get","post","put","patch","delete"];function Po(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 Co(o){let l={};for(let M of vo)l[M]=(k,L,V)=>(Po(o[M](k,L),M,k,V),l);return l}export{ln as ApiKeyManager,js as Auth,lr as AuthTester,_ as BindingBuilder,ho as BuiltInRules,Ta as CacheInvalidation,a as Container,w as ContentSecurityPolicy,ue as ContextualContainer,h as Cors,r as Csrf,b as DDoSProtection,yn as DEFAULT_COMPRESSION,Ou as DatabaseRules,F as DatabaseSessionStore,de as DefaultServiceProviderManager,ci as Dependencies,sr as DomainGroup,Gn as DomainGroupBuilder,mt as DomainMatcher,Gu as EnhancementPresets,z as EnvironmentManager,fn as Errors,S as FileSecurity,O as FileSessionStore,c as FileUpload,Ot as FileUploadTester,on as FileValidationTester,ke as FluentRouteBuilder,or as FluentRouter,mo as GenericMockModel,E as Helmet,ye as InMemoryNonceStore,R as InputValidation,cn as JWT,nn as JWTTester,m as JsonBody,Kt as LoadTester,u as MemorySessionStore,Es as MiddlewareChainTester,li as MiddlewareFactory,tn as MiddlewareGroupRegistry,vs as MiddlewareHelpers,Lr as MiddlewarePipeline,Ms as MiddlewareTester,Ro as MockPostClass,Os as MockServerWebSocket,fo as MockUserClass,Ss as ModelBindingTester,ks as ModelResolverTester,dn as OAuth2Helper,N as PerformanceAlerting,q as PerformanceDashboard,H as PerformanceMonitor,As as PerformanceTester,A as RateLimit,Ln as RateLimitRegistry,Pa as RateLimitUtils,Pr as RateLimiter,I as RedisSessionStore,g as RequestId,f as RequestSigning,B as RequestTracer,Tn as ResponseBuilder,lt as RouteBuilder,jn as RouteCacheFactory,Fn as RouteCacheKeyGenerator,In as RouteCacheManager,Zi as RouteFactory,Wn as RouteGroupBuilder,Lu as RouteHelpers,De as Router,Yi as RouterUtils,v as Security,j as SecuritySuite,y as Session,K as SessionManager,sn as SessionTester,n as SignatureError,ui as SkipConditions,Sa as SubdomainPatterns,Gr as SubdomainRouter,Ea as SubdomainUtils,$r as TestClient,Pt as TestRequestBuilder,an as TestResponseWrapper,Ii as ThrottleFactory,un as TypedClientError,Ps as ValidationFluentRouter,Du as ValidationHelpers,Cs as ValidationMiddlewareBuilder,Yr as ValidationRuleBuilder,Ar as Validator,Mt as WebSocketTester,Ue as apiKeyAuth,Yt as appendVary,io as applyRequestEnhancements,$t as applyResponseCompression,St as auth,Cc as authHelpers,Pc as authMocks,He as basicAuth,Be as bearerAuth,Gc as benchmarkMiddleware,il as benchmarkTests,oa as buildUrlWithPreservedParams,Li as clearNamedRoutes,Ko as compressResponse,e as config,Xc as constraintHelpers,We as contentSecurityPolicy,Rt as cors,Mc as createAuthTester,Re as createContainer,mr as createCookieAccessor,en as createEnhancementMiddleware,Bc as createFileUploadTester,zu as createFluentRouter,Di as createHandlerResolver,jt as createInMemoryCookieAccessor,Ec as createJWTTester,ll as createLoadTester,zc as createMiddlewareSpy,Fe as createMockRequest,pl as createMockResponse,Pl as createMockServerWebSocket,Zc as createModelBindingTester,Yc as createModelResolverTester,Da as createPathRegex,cl as createPerformanceTester,Gt as createRateLimitMiddleware,_n as createRouteCacheMiddleware,bt as createSessionStore,Sc as createSessionTester,Ma as createSubdomainMiddleware,Or as createTestClient,qs as createTestResponse,To as createTypedClient,Co as createTypedRouter,qr as createValidationMiddleware,vl as createWebSocketTester,Ct as csrf,Ge as ddosProtection,_t as decodeParam,me as defaultConfig,ia as defaultQueryPreservationConfig,xo as defineEndpoint,Qe as documentUpload,Ys as enableRequestContext,fe as extractApiKey,ge as extractBasicAuth,W as extractBearerToken,Cr as extractParamNames,Xn as fileExists,Ke as fileUpload,$c as fileUploadAssertions,qc as fileUploadMocks,Oc as fileUploadScenarios,Ti as generateQueryPreservationScript,D as generateSessionId,wt as getConfig,we as getContainer,Rn as getCurrentRequest,Wr as getNamedRoutePath,ji as getNamedRoutes,di as globalMiddlewarePipeline,$u as globalValidator,Ye as imageUpload,yr as injectQueryPreservationScript,Ze as inputValidation,Gi as isActionClass,wn as isCompressible,Ba as isRouteHandler,kt as joinPaths,vt as jsonBody,je as jwtAuth,ft as matchPath,ol as memoryTests,J as middleware,dt as middlewareGroups,_c as mockMiddleware,Kc as modelMocks,Xe as multipleFileUpload,Vo as negotiateEncoding,ir as normalizePath,Le as oauth2Auth,Wt as parseThrottleString,ii as peekBody,si as peekedStream,et as performanceAlerting,ul as performanceAssertions,tt as performanceDashboard,rt as performanceMonitor,Hs as performanceUtils,Qn as processHtmlTemplate,G as rateLimit,zn as rateLimitRegistry,At as registerNamedRoute,ei as request,xt as requestId,_e as requestSigning,nt as requestTracer,rr as resolveHandler,Vr as resolveViewPath,Ae as response,Zo as responseBuilder,zt as routeCacheManager,Qc as routeModelHelpers,eo as router,Bu as rule,Ir as runWithRequest,_r as runWithRequestArguments,el as scopedBindingHelpers,st as security,it as securitySuite,Tt as session,be as setContainer,Rr as setCurrentRequest,Jo as shouldCompress,ze as signRequest,Je as singleFileUpload,Lc as spyOnMiddleware,al as stressTests,fl as testClient,Dc as testFiles,Ic as testMiddleware,jc as testMiddlewareChain,wc as testRequest,$a as toActionPath,zi as url,ju as validate,Na as validatePath,Ve as verifySignature,$e as wrapResponse,Tl as wsAssertions,wl as wsHandlerMocks,xl as wsPerformance,bl as wsTestScenarios,Cl as wsTestUtils};
|