UNPKG

lacis

Version:

Zero-dependency TypeScript web framework

29 lines (20 loc) 43.4 kB
import X,{join}from'path';import et from'fs/promises';import {existsSync}from'fs';import K from'cluster';import He,{IncomingMessage,ServerResponse}from'http';import St from'https';import*as k from'os';import k__default from'os';import {EventEmitter}from'events';import {Socket}from'net';var N={beforeRequest:[],afterRequest:[],onError:[]},G={onNotFound:[],onShutdown:[]},z=new Map,J=new Map;function we(t,e){return N[t].push(e),{remove:()=>{let r=N[t].indexOf(e);r!==-1&&N[t].splice(r,1);}}}function qe(t,e,r,s){return t.has(e)||t.set(e,{beforeRequest:[],afterRequest:[],onError:[]}),t.get(e)[r].push(s),{remove:()=>{let o=t.get(e);if(!o)return;let n=o[r].indexOf(s);n!==-1&&o[r].splice(n,1);}}}function tt(t,e,r){return qe(z,t==="/"?"/":t.replace(/\/+$/,""),e,r)}function rt(t,e,r){return qe(J,t==="/"?"/":t.replace(/\/+$/,""),e,r)}function ae(t,e,r){let s=t.get(e);s&&(r.beforeRequest.push(...s.beforeRequest),r.afterRequest.push(...s.afterRequest),r.onError.push(...s.onError));}function st(t){let e=t==="/"?"/":t.replace(/\/+$/,""),r=e.split("/").filter(Boolean),s={beforeRequest:[...N.beforeRequest],afterRequest:[...N.afterRequest],onError:[...N.onError]};ae(z,"/",s),e==="/"&&ae(J,"/",s);let o="";for(let n of r)o+="/"+n,ae(z,o,s),o===e&&ae(J,o,s);return s}function _(){return N.beforeRequest.length>0||N.afterRequest.length>0||N.onError.length>0||z.size>0||J.size>0}async function H(t,e,r,s){let o=e.url?.split("?")[0]||"/",n=st(o);if(n[t].length===0)return true;for(let i of n[t])try{if(await i(e,r,s)===!1)return !1}catch(d){if(t!=="onError")try{for(let a of n.onError)await a(e,r,{error:d,phase:t});}catch(a){console.error("Error in error handler:",a);}return false}return true}function nt(t,e,r){e.has(r)||e.set(r,{beforeRequest:[],afterRequest:[],onError:[]});let s=e.get(r);for(let o of ["beforeRequest","afterRequest","onError"])if(t[o]){let n=Array.isArray(t[o])?t[o]:[t[o]];s[o].push(...n);}}async function Re(t){z.clear(),J.clear();async function e(r,s=""){try{let o=await et.readdir(r,{withFileTypes:!0});for(let[n,i]of [["+middleware.global.ts",z],["+middleware.global.js",z],["+middleware.ts",J],["+middleware.js",J]]){let d=o.find(a=>a.name===n);if(d)try{let l=await import(`${X.resolve(X.join(r,d.name))}?update=${Date.now()}`);nt(l,i,s);}catch(a){console.error(`Error loading middleware for ${s}:`,a);}}for(let n of o)n.isDirectory()&&await e(X.join(r,n.name),`${s==="/"?"":s}/${n.name}`);}catch(o){console.error(`Error scanning directory ${r}:`,o);}}await e(t,"/");}function V(t){if(t?.length)for(let e of t){let r=e.type==="cascade"?tt:rt;for(let s of ["beforeRequest","afterRequest","onError"]){let o=e.module[s];if(!o)continue;let n=Array.isArray(o)?o:[o];for(let i of n)r(e.path,s,i);}}}function L(t){t&&(t.onNotFound&&G.onNotFound.push(t.onNotFound),t.onShutdown&&G.onShutdown.push(t.onShutdown));}function j(){return G.onNotFound.length>0}async function U(t,e){for(let r of G.onNotFound)if(await r(t,e),e.headersSent)return}async function Pt(){for(let t of G.onShutdown)try{await t();}catch(e){console.error("Error in onShutdown hook:",e);}}function It(){N.beforeRequest=[],N.afterRequest=[],N.onError=[],z.clear(),J.clear(),G.onNotFound=[],G.onShutdown=[];}function F(t){if(t)for(let e of ["beforeRequest","afterRequest","onError"]){let r=t[e];if(r){let s=Array.isArray(r)?r:[r];for(let o of s)we(e,o);}}}function ot(t,e){return !e||e==="*"?true:typeof e=="string"?t===e:Array.isArray(e)?e.includes(t):e instanceof RegExp?e.test(t):typeof e=="function"?e(t):false}function at(t){let e=(t.methods??["GET","POST","PUT","DELETE","PATCH","OPTIONS"]).join(", "),r=(t.allowedHeaders??["Content-Type","Authorization"]).join(", "),s=t.exposedHeaders?.join(", "),o=t.maxAge!=null?String(t.maxAge):null,n=!t.origin||t.origin==="*";return async(i,d)=>{let a=i.getHeader("origin");if(!a||!ot(a,t.origin))return;let l=n&&!t.credentials;if(d.setHeader("Access-Control-Allow-Origin",l?"*":a),l||d.setHeader("Vary","Origin"),t.credentials&&d.setHeader("Access-Control-Allow-Credentials","true"),s&&d.setHeader("Access-Control-Expose-Headers",s),i.method==="OPTIONS")return d.setHeader("Access-Control-Allow-Methods",e),d.setHeader("Access-Control-Allow-Headers",r),o&&d.setHeader("Access-Control-Max-Age",o),d.status(204),d.end(),false}}function B(t){t&&we("beforeRequest",at(t));}function y(...t){K.isPrimary&&console.log(...t);}function ut(t){let e=t.match(/^\[(\w+)(\??)]/);return e?{name:e[1],isParam:true,isOptional:e[2]==="?"}:{name:t,isParam:false,isOptional:false}}var ft=1e3,ht=100,Se=class{rootNode;cachedRoutes;routeCount;lastLoaded;verbose;constructor(){this.rootNode=this.createNode(),this.cachedRoutes=new Map,this.routeCount=0,this.lastLoaded=0,this.verbose=false;}createNode(){return {handlers:Object.create(null),staticChildren:new Map,paramChild:null,wildcardHandler:null,isEndpoint:false}}addRoute(e,r,s){let o=r.split("/").filter(Boolean),n=this.rootNode;for(let i of o){let d=ut(i);if(d.isParam){if(!n.paramChild)n.paramChild={name:d.name,node:this.createNode(),isOptional:d.isOptional};else if(n.paramChild.name!==d.name)throw new Error(`Route conflict: param name "[${d.name}]" conflicts with existing "[${n.paramChild.name}]" at the same path position. Use the same param name for all methods at this level.`);n=n.paramChild.node;}else {if(i==="*")return n.wildcardHandler||(n.wildcardHandler=Object.create(null)),n.wildcardHandler[e]=s,this.cachedRoutes.clear(),this;n.staticChildren.has(i)||n.staticChildren.set(i,this.createNode()),n=n.staticChildren.get(i);}}return n.isEndpoint=true,n.handlers[e]||this.routeCount++,n.handlers[e]=s,this.cachedRoutes.clear(),this}findRoute(e,r){let s=r==="/"?"/":r.replace(/\/+$/,""),o=e+":"+s,n=this.cachedRoutes.get(o);if(n)return this.cachedRoutes.delete(o),this.cachedRoutes.set(o,n),n;let i=s==="/"?[]:s.split("/").filter(Boolean),d=Object.create(null),a=this.traverse(this.rootNode,i,e,d,0)??{handler:null,params:Object.create(null)};if(a.handler!==null||a.allowedMethods?.length){if(this.cachedRoutes.size>=ft){let l=0;for(let c of this.cachedRoutes.keys())if(this.cachedRoutes.delete(c),++l>=ht)break}this.cachedRoutes.set(o,a);}return a}traverse(e,r,s,o,n){if(n===r.length){if(e.isEndpoint){let l=e.handlers[s]??(s==="HEAD"?e.handlers.GET:void 0)??e.handlers[""];if(l)return {handler:l,params:Object.assign(Object.create(null),o)};let c=Object.keys(e.handlers).filter(p=>p!=="");return {handler:null,params:Object.create(null),allowedMethods:c}}let a=e.paramChild;if(a?.isOptional&&a.node.isEndpoint){let l=a.node.handlers[s]??(s==="HEAD"?a.node.handlers.GET:void 0)??a.node.handlers[""];if(l)return {handler:l,params:Object.assign(Object.create(null),o)}}return null}let i=r[n],d=e.staticChildren.get(i);if(d){let a=this.traverse(d,r,s,o,n+1);if(a)return a}if(e.paramChild){let{name:a,node:l}=e.paramChild;o[a]=i;let c=this.traverse(l,r,s,o,n+1);if(c)return c;delete o[a];}if(e.wildcardHandler){let a=e.wildcardHandler[s]??e.wildcardHandler[""],l=r.slice(n).join("/");if(a)return {handler:a,params:Object.assign(Object.create(null),o,{"*":l})};let c=Object.keys(e.wildcardHandler).filter(p=>p!=="");if(c.length>0)return {handler:null,params:Object.assign(Object.create(null),o,{"*":l}),allowedMethods:c}}return null}async loadRoutes(e){this.rootNode=this.createNode(),this.cachedRoutes.clear(),this.routeCount=0,await Re(e);let r=this;async function s(o,n=[]){try{let i=await et.readdir(o,{withFileTypes:!0}),d=i.find(a=>!a.isDirectory()&&(a.name==="index.ts"||a.name==="index.js"));if(d)try{let l=await import(`${X.resolve(X.join(o,d.name))}?update=${Date.now()}`),c=["GET","POST","PUT","DELETE","PATCH"],p="/"+n.join("/"),E=!1;for(let m of c)typeof l[m]=="function"&&(r.addRoute(m,p,l[m]),E=!0);!E&&typeof l.default=="function"&&r.addRoute("GET",p,l.default),r.verbose&&y(`Route loaded: ${p}`);}catch(a){console.error(`Error loading index in ${o}:`,a);}for(let a of i)if(a.isDirectory()){let l=a.name.match(/^\[(\w+)(\??)]/),c=l?`[${l[1]}${l[2]}]`:a.name;await s(X.join(o,a.name),[...n,c]);}}catch(i){console.error(`Error scanning directory ${o}:`,i);}}return await s(e),this.lastLoaded=Date.now(),this.verbose&&y(`Loading completed: ${this.routeCount} routes`),true}getRoutes(){let e=[];return this.collectRoutes(this.rootNode,[],e),e}collectRoutes(e,r,s){if(e.isEndpoint){let o=r.length===0?"/":"/"+r.join("/");for(let[n,i]of Object.entries(e.handlers))n!==""&&s.push({method:n,path:o,handler:i});}for(let[o,n]of e.staticChildren)this.collectRoutes(n,[...r,o],s);if(e.paramChild){let{name:o,isOptional:n,node:i}=e.paramChild;this.collectRoutes(i,[...r,n?`:${o}?`:`:${o}`],s);}if(e.wildcardHandler){let o="/"+[...r,"*"].join("/");for(let[n,i]of Object.entries(e.wildcardHandler))n!==""&&s.push({method:n,path:o,handler:i});}}getStats(){return {routeCount:this.routeCount,lastLoaded:this.lastLoaded,uptime:Date.now()-this.lastLoaded,cacheSize:this.cachedRoutes.size}}setVerbose(e){return this.verbose=e,this}reset(){this.rootNode=this.createNode(),this.cachedRoutes=new Map,this.routeCount=0;}},se=new Se;function D(t){return t&&typeof t=="object"&&"error"in t}function Y(t){for(let{path:e,handlers:r}of t){let s=e.replace(/:(\w+\??)/g,(o,n)=>n.endsWith("?")?`[${n.slice(0,-1)}?]`:`[${n}]`);for(let[o,n]of Object.entries(r))typeof n=="function"&&se.addRoute(o,s,n);}}async function ie(t){let e=join(t,"_manifest.js");if(existsSync(e)){se.reset();let r=await import(e);Y(r.routes),r.middlewares?V(r.middlewares):await Re(t);return}return se.loadRoutes(t)}function W(t,e="GET"){let r=se.findRoute(e,t);return r.handler?{handler:r.handler,params:r.params}:r.allowedMethods?.length?{error:"Method Not Allowed",status:405,allowedMethods:r.allowedMethods}:null}function Vt(t){let e=process.env.NODE_ENV==="production",r=process.env.ROUTES_DIR??t??(e?"dist/routes":"routes"),s=e&&!X.isAbsolute(r)&&!r.startsWith("dist/")?X.join("dist",r):r;return X.resolve(process.cwd(),s)}function Gt(){se.reset();}var P={OK:200,CREATED:201,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,CONFLICT:409,UNPROCESSABLE_ENTITY:422,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504},$e={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",503:"Service Unavailable",504:"Gateway Timeout"};function x(t){let e=t.code||P.INTERNAL_SERVER_ERROR,r=t.message||$e[e]||"Unknown Error",s=t.name||`HttpError${e}`,o=new Error(r);return Error.captureStackTrace?.(o,x),{name:s,code:e,message:r,details:t.details,expose:t.expose!==void 0?t.expose:e<500,log:t.log!==void 0?t.log:e>=500,stack:o.stack}}function pt(t){let r={error:t.expose?t.message:$e[t.code]||"Internal Server Error",code:t.code};return t.expose&&t.details?{...r,details:t.details}:r}function Le(t,e){e.headersSent||(e.statusCode=t.code,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify(pt(t)))),t.log&&mt(t);}function mt(t){let e={name:t.name,message:t.message,code:t.code,details:t.details,stack:t.stack};t.code>=500?y("\u274C ERROR:",JSON.stringify(e,null,2)):y("\u26A0\uFE0F WARNING:",JSON.stringify(e,null,2));}function Xt(t,e){return x({name:"BadRequestError",code:P.BAD_REQUEST,message:t,details:e})}function Zt(t,e){return x({name:"UnauthorizedError",code:P.UNAUTHORIZED,message:t,details:e})}function Kt(t,e){return x({name:"ForbiddenError",code:P.FORBIDDEN,message:t,details:e})}function er(t,e){return x({name:"NotFoundError",code:P.NOT_FOUND,message:t,details:e})}function tr(t,e){return x({name:"MethodNotAllowedError",code:P.METHOD_NOT_ALLOWED,message:t,details:e})}function rr(t,e){return x({name:"ConflictError",code:P.CONFLICT,message:t,details:e})}function sr(t,e){return x({name:"ValidationError",code:P.UNPROCESSABLE_ENTITY,message:t,details:e,expose:true})}function nr(t,e){return x({name:"RateLimitError",code:P.TOO_MANY_REQUESTS,message:t,details:e})}function gt(t,e){return x({name:"InternalServerError",code:P.INTERNAL_SERVER_ERROR,message:t,details:e})}function yt(t,e){return x({name:"ServiceUnavailableError",code:P.SERVICE_UNAVAILABLE,message:t,details:e})}function wt(t,e){return x({name:"GatewayTimeoutError",code:P.GATEWAY_TIMEOUT,message:t,details:e})}function je(t){if(t&&typeof t=="object"&&typeof t.code=="number"&&"message"in t)return t;let e=t?.message||"Unknown error occurred",r=t?.stack?{stack:t.stack}:void 0,s=t?.code||t?.statusCode;return s==="ECONNREFUSED"||s==="ENOTFOUND"?yt(`Service connection failed: ${e}`,r):s==="ETIMEDOUT"?wt(`Request timed out: ${e}`,r):typeof s=="number"&&s>=400&&s<600?x({code:s,message:e,details:r}):gt(e,r)}function Ue(t){return !!(t&&typeof t=="object"&&typeof t.code=="number"&&"message"in t&&"name"in t)}function Fe(t,e={},r={},s){let o=false,n=0,i={},d=[],a=[],l=[],c=null;r.onMessage&&d.push(r.onMessage),r.onClose&&a.push(r.onClose),r.onError&&l.push(r.onError),r.onEvent&&Object.entries(r.onEvent).forEach(([f,g])=>{i[f]||(i[f]=[]),i[f].push(g);});let p=e.reconnectInterval||3e3,E=e.maxRetries||3,m=e.disableReconnect||false,w=e.body,h=e.contentType||(w?"application/json":void 0),u=e.method||(w?"POST":"GET");if(typeof t!="string"){let f=t;return o=true,f.on("data",g=>{S(g.toString());}),f.on("end",()=>{o=false;}),f.on("error",g=>{o=false,console.error("SSE Error:",g);}),b()}if(typeof t=="string")return new Promise((f,g)=>{$().then(()=>f(b())).catch(g);});function S(f){let g=f,C=g.split(` `);g=C.pop()||"";for(let T of C){let O=T.split(` `),R="",v="";for(let A of O)A.startsWith("event:")?v=A.slice(6).trim():A.startsWith("data:")&&(R=A.slice(5).trim());if(R)try{let A=JSON.parse(R);v&&i[v]?i[v].forEach(re=>re(A)):d.forEach(re=>re(A));}catch{v&&i[v]?i[v].forEach(A=>A(R)):d.forEach(A=>A(R));}}}function b(){return {onMessage(f){return d.push(f),this},onEvent(f,g){return i[f]||(i[f]=[]),i[f].push(g),this},onClose(f){return a.push(f),this},close(){c&&(c.destroy(),c=null),o=false,a.forEach(f=>f());}}}async function $(){if(!o){o=true;try{await M();}catch(f){!m&&n<E?(n++,setTimeout(()=>{$();},p)):l.forEach(g=>g(f));}}}async function M(){return new Promise((f,g)=>{let C=new URL(t);e.params&&(typeof e.params=="object"?Object.entries(e.params).forEach(([R,v])=>{C.searchParams.append(R,String(v));}):typeof e.params=="string"&&new URLSearchParams(e.params).forEach((v,A)=>{C.searchParams.append(A,v);}));let T={hostname:C.hostname,port:C.port||(C.protocol==="https:"?443:80),path:C.pathname+C.search,method:u,headers:{Accept:"text/event-stream",...s?.headers||{},"Cache-Control":"no-cache",Connection:"keep-alive",...h&&{"Content-Type":h},...w&&typeof w=="string"&&{"Content-Length":Buffer.byteLength(w).toString()},...w&&typeof w!="string"&&{"Content-Length":Buffer.byteLength(JSON.stringify(w)).toString()}}};c=(C.protocol==="https:"?St:He).request(T,R=>{if(R.statusCode!==200){o=false,g(new Error(`Server responded with status: ${R.statusCode}`));return}R.setEncoding("utf8"),R.on("data",S),R.on("end",()=>{o=false,c?.destroy(),c=null,a.forEach(v=>v()),f(null);}),R.on("close",()=>{o=false,c?.destroy(),c=null,a.forEach(v=>v()),f(null);}),R.on("error",v=>{o=false,c?.destroy(),c=null,a.forEach(A=>A()),g(v);});}),c.on("error",R=>{o=false,c?.destroy(),c=null,g(R);}),w&&(typeof w=="string"?c.write(w):c.write(JSON.stringify(w))),c.end();})}return b()}var Ce=class{constructor(e,r){this._res=e;this._timeoutId=setTimeout(()=>e.end(),r),e.on("close",()=>clearTimeout(this._timeoutId));}_res;_timeoutId;send(e){return this._res.writableEnded?false:this._res.write(`data: ${e} `)}json(e){return this._res.writableEnded?false:this._res.write(`data: ${JSON.stringify(e)} `)}event(e,r){return this._res.writableEnded?false:(this._res.write(`event: ${e} `),this._res.write(`data: ${JSON.stringify(r)} `))}comment(e){return this._res.writableEnded?false:this._res.write(`: ${e} `)}id(e){return this._res.writableEnded?false:this._res.write(`id: ${e} `)}retry(e){return this._res.writableEnded?false:this._res.write(`retry: ${e} `)}close(e="Connection closed"){clearTimeout(this._timeoutId),this._res.write(`: ${e} `),this._res.end();}error(e,r,s=500,o){clearTimeout(this._timeoutId),this._res.write(`event: ${e} `),this._res.write(`data: ${JSON.stringify({message:r,code:s,details:o??null})} `),this._res.end();}};function Be(t,e){let r=e?.headers?.["Cache-Control"]??"no-cache",s=e?.headers?.Connection??"keep-alive",o=e?.timeout??3e5;return t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":r,Connection:s,...e?.headers??{}}),new Ce(t,o)}var le=class{_parsed=null;_raw;constructor(e){this._raw=e;}_parse(){if(this._parsed!==null)return this._parsed;if(this._parsed={},!this._raw)return this._parsed;for(let e of this._raw.split(";")){let r=e.indexOf("=");if(r===-1)continue;let s=e.slice(0,r).trim(),o=e.slice(r+1).trim();if(s){let n=o.startsWith('"')&&o.endsWith('"')?o.slice(1,-1):o;try{this._parsed[s]=decodeURIComponent(n);}catch{this._parsed[s]=n;}}}return this._parsed}get(e){return this._parse()[e]}all(){return {...this._parse()}}},ce=class{_pending=[];set(e,r,s={}){return this._pending.push({name:e,value:r,opts:s}),this}delete(e,r={}){return this.set(e,"",{...r,maxAge:0,expires:new Date(0)})}serialize(){return this._pending.map(({name:e,value:r,opts:s})=>{let o=`${e}=${encodeURIComponent(r)}`,n=s.path!==void 0?s.path:"/";return n&&(o+=`; Path=${n}`),s.domain&&(o+=`; Domain=${s.domain}`),s.maxAge!=null&&(o+=`; Max-Age=${s.maxAge}`),s.expires&&(o+=`; Expires=${s.expires.toUTCString()}`),s.httpOnly&&(o+="; HttpOnly"),s.secure&&(o+="; Secure"),s.sameSite&&(o+=`; SameSite=${s.sameSite}`),o})}};function De(t){if(typeof t.get=="function")return t.get("cookie")??void 0;let e=t.cookie;return Array.isArray(e)?e.join("; "):e}function Q(t){return class extends t{_zreqCookies;getHeader(e){let r=this.headers;if(typeof r.get=="function")return r.get(e)??void 0;let s=r[e.toLowerCase()];return Array.isArray(s)?s[0]:s}get cookies(){return this._zreqCookies||(this._zreqCookies=new le(De(this.headers))),this._zreqCookies}json(){return this.body().then(e=>JSON.parse(e.toString()))}form(){let e=this.headers,r=typeof e.get=="function"?e.get("content-type")??"":e["content-type"]??"";return r.startsWith("application/x-www-form-urlencoded")?this.body().then(s=>Object.fromEntries(new URLSearchParams(s.toString()))):r.startsWith("multipart/form-data")?new Promise((s,o)=>{let n=r.match(/boundary=(.+)$/);if(!n){o(new Error("Boundary not found"));return}let i=n[1].trim();this.body().then(d=>{let a={},l=Buffer.from(`--${i}`),c=[],p=0,E;for(;(E=d.indexOf(l,p))!==-1;)c.push(d.subarray(p,E)),p=E+l.length;c.push(d.subarray(p));for(let m=1;m<c.length-1;m++){let w=c[m].subarray(2),h=w.indexOf(`\r \r `);if(h===-1)continue;let u=w.subarray(0,h).toString(),S=w.subarray(h+4,w.length-2),b=u.match(/Content-Disposition: form-data; name="([^"]+)"(?:; filename="([^"]+)")?/i);if(b)if(b[2]){let $=u.match(/Content-Type:\s*([^\r\n]+)/i);a[b[1]]={filename:b[2],mimetype:$?$[1].trim():"application/octet-stream",data:S,size:S.length};}else a[b[1]]=S.toString("utf-8");}s(a);}).catch(o);}):Promise.reject(new Error("Content-Type must be multipart/form-data or application/x-www-form-urlencoded"))}createSSEClient(e,r){return Fe(this,e,r)}}}function ue(){let t=[],e=this._maxBodySize??10485760,r=0,s=false;return new Promise((o,n)=>{let i=d=>{if(!s){if(r+=d.length,r>e){s=true,this.pause(),this.removeListener("data",i),n(Object.assign(new Error("Payload Too Large"),{code:413}));return}t.push(d);}};this.on("data",i).on("end",()=>{s||(s=true,o(Buffer.concat(t)));}).on("error",d=>{s||(s=true,n(d));});})}function We(t,e){let r=t.serialize();r.length>0&&!e.headersSent&&e.setHeader("Set-Cookie",r);}function ne(t){return class extends t{_zresCookies;get cookies(){return this._zresCookies||(this._zresCookies=new ce),this._zresCookies}end(e){return this._zresCookies&&We(this._zresCookies,this),super.end(e)}status(e){return this.statusCode=e,this}send(e){return typeof e=="string"?(this.setHeader("Content-Type","text/plain"),this.end(e)):this.json(e),this}json(e){return this.setHeader("Content-Type","application/json"),this.end(JSON.stringify(e)),this}html(e){return this.setHeader("Content-Type","text/html; charset=utf-8"),this.end(e),this}redirect(e,r=302){return this.statusCode=r,this.setHeader("Location",e),this.end(),this}initSSE(e){return Be(this,e)}async stream(e){if(this.setHeader("Cache-Control","no-cache"),this.setHeader("X-Accel-Buffering","no"),e instanceof ReadableStream){let r=e.getReader();try{for(;;){let{done:s,value:o}=await r.read();if(s)break;this.write(o);}}finally{this.end();}}else {for await(let r of e)this.write(r);this.end();}}async ndjson(e){let r=new TextEncoder;this.setHeader("Content-Type","application/x-ndjson"),this.setHeader("Cache-Control","no-cache"),this.setHeader("X-Accel-Buffering","no");for await(let s of e)this.write(r.encode(JSON.stringify(s)+` `));this.end();}}}var Ee=class{params={};headers={};body(){return ue.call(this)}},de=Q(Ee).prototype,be=class{statusCode=200;headersSent=false;setHeader(e,r){}end(e){}write(e){}},Ct=ne(be).prototype;function fe(t){t.body=ue,t.json=de.json,t.form=de.form,t.getHeader=de.getHeader,t.createSSEClient=de.createSSEClient,t.cookies=new le(De(t.headers)),t.locals={},t.platform={};}function he(t){let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}function Z(t){let e=t.indexOf("?");return e===-1?{}:Object.fromEntries(new URLSearchParams(t.slice(e+1)).entries())}async function I(t,e,r){let s=Ue(r)?r:je(r);s.log&&console.error("[lacis] Error:",r),_()&&await H("onError",t,e,{error:s}),e.headersSent||Le(s,e);}function pe(t){let e=Ct;t.status=e.status,t.send=e.send,t.json=e.json,t.html=e.html,t.redirect=e.redirect,t.initSSE=e.initSSE;let r=new ce;t.cookies=r;let s=t.end.bind(t);t.end=function(...o){return We(r,this),s(...o)},t.stream=async function(o){let n=[];if(o instanceof ReadableStream){let l=o.getReader();for(;;){let{done:c,value:p}=await l.read();if(c)break;n.push(p);}}else for await(let l of o)n.push(l);let i=n.reduce((l,c)=>l+c.length,0),d=new Uint8Array(i),a=0;for(let l of n)d.set(l,a),a+=l.length;this.end(Buffer.from(d));},t.ndjson=async function(o){this.setHeader("Content-Type","application/x-ndjson");let n=[];for await(let i of o)n.push(JSON.stringify(i)+` `);this.end(n.join(""));};}var me=null;function bt(t={}){let e=new EventEmitter,r={sampleInterval:t.sampleInterval||5e3,reportInterval:t.reportInterval||6e4,resetInterval:t.resetInterval||1440*60*1e3,enableHistogram:t.enableHistogram!==void 0?t.enableHistogram:true,logToConsole:t.logToConsole!==void 0?t.logToConsole:true,thresholds:{cpu:t.thresholds?.cpu||80,memory:t.thresholds?.memory||80,responseTime:t.thresholds?.responseTime||1e3,errorRate:t.thresholds?.errorRate||5}},s=Date.now(),o={requestCount:0,activeRequests:0,errorCount:0,responseTimes:[],responseTimesBucket:Array(100).fill(0),statusCodes:{},lastReport:s,lastReset:s},n=l(),i=[],d=process.cpuUsage(),a={cpu:false,memory:false,responseTime:false,errorRate:false};function l(){return {timestamp:Date.now(),uptime:process.uptime(),requestCount:0,activeRequests:0,errorCount:0,responseTimes:{min:0,max:0,avg:0,count:0,sum:0},statusCodes:{},memory:process.memoryUsage(),cpu:{usage:0,system:0,user:0},systemLoad:k.loadavg(),systemMemory:{total:k.totalmem(),free:k.freemem(),used:k.totalmem()-k.freemem()}}}function c(){let f=o.responseTimes;if(f.length===0)return {min:0,max:0,avg:0,count:0,sum:0};let g=1/0,C=-1/0,T=0;for(let v of f)g=Math.min(g,v),C=Math.max(C,v),T+=v;let O=T/f.length,R={min:g,max:C,avg:O,count:f.length,sum:T};if(r.enableHistogram){let v=[...f].sort((A,re)=>A-re);R.p50=v[Math.floor(v.length*.5)],R.p90=v[Math.floor(v.length*.9)],R.p99=v[Math.floor(v.length*.99)];}return R}function p(){let f=Date.now(),g=process.uptime(),C=process.memoryUsage(),T=process.cpuUsage(d);d=process.cpuUsage();let R=(T.user+T.system)/1e3/r.sampleInterval*100;n={timestamp:f,uptime:g,requestCount:o.requestCount,activeRequests:o.activeRequests,errorCount:o.errorCount,responseTimes:c(),statusCodes:{...o.statusCodes},memory:C,cpu:{usage:R,system:T.system,user:T.user},systemLoad:k.loadavg(),systemMemory:{total:k.totalmem(),free:k.freemem(),used:k.totalmem()-k.freemem()}},i.push({...n}),i.length>100&&i.shift(),w(),K.isWorker&&process.send&&process.send({type:"metrics",metrics:n});}function E(){if(!r.logToConsole||K.isPrimary===false)return;let f={rss:(n.memory.rss/1024/1024).toFixed(2),heapTotal:(n.memory.heapTotal/1024/1024).toFixed(2),heapUsed:(n.memory.heapUsed/1024/1024).toFixed(2)},g=Date.now()-o.lastReport,C=(n.requestCount/(g/1e3)).toFixed(2),T=n.requestCount?(n.errorCount/n.requestCount*100).toFixed(2):"0.00";y(` \u{1F4CA} Server Performance Metrics \u{1F4CA}`),y(`Uptime: ${h(n.uptime)}`),y(`Load: ${n.systemLoad[0].toFixed(2)}, ${n.systemLoad[1].toFixed(2)}, ${n.systemLoad[2].toFixed(2)}`),y(`Requests: ${n.requestCount} total, ${C} req/sec`),y(`Active Requests: ${n.activeRequests}`),y(`Errors: ${n.errorCount} (${T}%)`),n.responseTimes.count>0&&(y(`Response Times: avg ${n.responseTimes.avg.toFixed(2)}ms, min ${n.responseTimes.min}ms, max ${n.responseTimes.max}ms`),n.responseTimes.p50&&y(`Response Time Percentiles: p50 ${n.responseTimes.p50}ms, p90 ${n.responseTimes.p90}ms, p99 ${n.responseTimes.p99}ms`)),y(`Memory: ${f.rss}MB (RSS), ${f.heapUsed}MB / ${f.heapTotal}MB (Heap)`),y(`CPU Usage: ${n.cpu.usage.toFixed(2)}%`),Object.keys(n.statusCodes).length>0&&(y("Status Codes:"),Object.entries(n.statusCodes).sort(([O],[R])=>parseInt(O)-parseInt(R)).forEach(([O,R])=>{y(` ${O}: ${R}`);})),y(""),o.lastReport=Date.now();}function m(){let f=Date.now();o.requestCount=0,o.activeRequests=0,o.errorCount=0,o.responseTimes=[],o.responseTimesBucket=Array(100).fill(0),o.statusCodes={},o.lastReport=f,o.lastReset=f,y("\u{1F504} Performance metrics have been reset");}function w(){let f=n.memory.heapUsed/n.memory.heapTotal*100,g=n.requestCount?n.errorCount/n.requestCount*100:0,C=n.responseTimes.avg;n.cpu.usage>r.thresholds.cpu&&!a.cpu?(a.cpu=true,e.emit("alarm","cpu",`High CPU usage: ${n.cpu.usage.toFixed(2)}%`)):n.cpu.usage<=r.thresholds.cpu&&a.cpu&&(a.cpu=false,e.emit("alarm-clear","cpu",`CPU usage returned to normal: ${n.cpu.usage.toFixed(2)}%`)),f>r.thresholds.memory&&!a.memory?(a.memory=true,e.emit("alarm","memory",`High memory usage: ${f.toFixed(2)}%`)):f<=r.thresholds.memory&&a.memory&&(a.memory=false,e.emit("alarm-clear","memory",`Memory usage returned to normal: ${f.toFixed(2)}%`)),C>r.thresholds.responseTime&&!a.responseTime?(a.responseTime=true,e.emit("alarm","responseTime",`High response time: ${C.toFixed(2)}ms`)):C<=r.thresholds.responseTime&&a.responseTime&&(a.responseTime=false,e.emit("alarm-clear","responseTime",`Response time returned to normal: ${C.toFixed(2)}ms`)),g>r.thresholds.errorRate&&!a.errorRate?(a.errorRate=true,e.emit("alarm","errorRate",`High error rate: ${g.toFixed(2)}%`)):g<=r.thresholds.errorRate&&a.errorRate&&(a.errorRate=false,e.emit("alarm-clear","errorRate",`Error rate returned to normal: ${g.toFixed(2)}%`));}function h(f){let g=Math.floor(f/86400),C=Math.floor(f%86400/3600),T=Math.floor(f%3600/60),O=Math.floor(f%60),R=[];return g>0&&R.push(`${g}d`),C>0&&R.push(`${C}h`),T>0&&R.push(`${T}m`),(O>0||R.length===0)&&R.push(`${O}s`),R.join(" ")}function u(){let f=setInterval(p,r.sampleInterval),g=setInterval(E,r.reportInterval),C=setInterval(m,r.resetInterval);return {stop:()=>{clearInterval(f),clearInterval(g),clearInterval(C);}}}function S(){let f=Date.now();return o.activeRequests++,{end:(g,C=false)=>{let T=Date.now()-f;return o.activeRequests--,o.requestCount++,o.responseTimes.push(T),o.responseTimes.length>1e3&&o.responseTimes.shift(),o.statusCodes[g]=(o.statusCodes[g]||0)+1,(C||g>=500)&&o.errorCount++,T}}}function b(){return !Object.values(a).some(f=>f)}function $(){let f=n.memory.heapUsed/n.memory.heapTotal*100,g=n.requestCount?n.errorCount/n.requestCount*100:0;return {status:b()?"healthy":"unhealthy",uptime:n.uptime,responseTimes:{avg:n.responseTimes.avg,p90:n.responseTimes.p90||null,p99:n.responseTimes.p99||null},memory:{usedMB:Math.round(n.memory.heapUsed/1024/1024),totalMB:Math.round(n.memory.heapTotal/1024/1024),percent:f.toFixed(2)},cpu:n.cpu.usage.toFixed(2),requests:{total:n.requestCount,active:n.activeRequests,errors:n.errorCount,errorRate:g.toFixed(2)},alerts:Object.entries(a).filter(([C,T])=>T).map(([C])=>C)}}let M=u();return {trackRequest:S,getMetrics:()=>({...n}),getMetricsHistory:()=>[...i],getHealthMetrics:$,isHealthy:b,stop:M.stop,on:e.on.bind(e),once:e.once.bind(e),off:e.off.bind(e)}}function Je(t){if(!me){let e=bt(t),r=e.stop;e.stop=()=>{r(),me=null;},me=e;}return me}function Ge(){let t={workerIds:[]};function e(){let i=K.fork();t.workerIds.push(i.id),y(`Worker ${i.process.pid} started`);}let r=false,s=[];function o(i=k.cpus().length){if(K.isPrimary){y(`\u{1F9F5} Launching ${i} workers...`);for(let d=0;d<i;d++)e();K.on("exit",(d,a,l)=>{if(t.workerIds=t.workerIds.filter(c=>c!==d.id),r){s.forEach(c=>c());return}y(`Worker ${d.process.pid} died (${l||a}). Restarting...`),setTimeout(()=>e(),1e3);});}}function n(i){r=true;let d=Object.keys(K.workers??{});if(d.length===0){i?.();return}let a=d.length;s.push(()=>{a--,a===0&&i?.();});for(let l of d)K.workers?.[l]?.kill();}return {start:o,shutdown:n,getActiveWorkerCount:()=>t.workerIds.length}}var Me=class extends He.IncomingMessage{params={};body=ue;locals={};platform={}},Te=class extends Q(Me){},_e=class extends ne(He.ServerResponse){},Ye={name:"node",createHandler:t=>{if(typeof t!="string")throw new Error("nodeAdapter requires a routesDir string, not a ServerlessConfig.");let e=t;return async(r={})=>{let{port:s=3e3,defaultHeaders:o,isDev:n,cluster:i,monitoring:d={enabled:false}}=r,a=null;n&&d.enabled&&(a=Je({sampleInterval:d.sampleInterval||5e3,reportInterval:d.reportInterval||6e4,thresholds:d.thresholds,logToConsole:true}),K.isPrimary&&(y("\u{1F4CA} Development performance monitoring enabled"),a.on("alarm",(c,p)=>{y(`\u26A0\uFE0F ALERT: ${p}`);}),a.on("alarm-clear",(c,p)=>{y(`\u2705 RESOLVED: ${p}`);})));let l=o?Object.entries(o):[];if(i?.enabled&&K.isPrimary){let c=i.workers??k__default.cpus().length,p=r.httpsOptions?"https":"http";if(y(`\u{1F9F5} Starting server with ${c} workers`),K.schedulingPolicy!==void 0)try{K.schedulingPolicy=K.SCHED_RR;}catch{}let E=Ge();return E.start(c),y(`\u{1F680} Server running at ${p}://localhost:${s}/`+(n?" (dev)":"")),n&&a&&y(`\u{1F4CA} Performance monitoring available at http://localhost:${s}/health`),{close:m=>{a&&a.stop(),E.shutdown(m);}}}if(K.isWorker||!i?.enabled){r.routes||await ie(e),B(r.cors),F(r.middleware),L(r.hooks);let c=async(h,u,S)=>{try{if(n&&a&&h.url==="/health"){u.setHeader("Content-Type","application/json"),u.end(JSON.stringify(a.getHealthMetrics())),S?.end(200);return}let b=h.url||"/",$=he(b);if(h.query=Z(b),h._maxBodySize=r.maxBodySize,_()&&(await H("beforeRequest",h,u)===!1||u.headersSent)){S?.end(u.statusCode||204);return}let M=W($,h.method||"GET");if(!M){if(j()&&(await U(h,u),u.headersSent)){S?.end(u.statusCode);return}u.status(404).json({error:"Route not found"}),S?.end(404);return}if(D(M)){let f=M.status||500;M.allowedMethods?.length&&u.setHeader("Allow",M.allowedMethods.join(", ")),u.status(f).json({error:M.error}),S?.end(f,!0);return}h.params=M.params,await M.handler(h,u),_()&&await H("afterRequest",h,u),u.headersSent||u.end(),S?.end(u.statusCode||200);}catch(b){await I(h,u,b),u.headersSent||u.status(500).json({error:"Internal Server Error"}),S?.end(u.statusCode||500,true);}},p=(h,u)=>{let S=n&&a?a.trackRequest():null;if(l.length>0)for(let b=0;b<l.length;b++)u.setHeader(l[b][0],l[b][1]);c(h,u,S).catch(b=>{n&&console.error("Fatal error:",b),u.headersSent||(u.statusCode=500,u.end("Server Error")),S?.end(500,true);});},E={IncomingMessage:Te,ServerResponse:_e},m=r.httpsOptions?St.createServer({...E,...r.httpsOptions},p):He.createServer(E,p);m.on("clientError",(h,u)=>{u.destroyed||u.destroy();});let w=r.httpsOptions?"https":"http";return m.listen(s,()=>{i?.enabled?n&&y(`Worker ${process.pid} is listening on port ${s}`):(y(`\u{1F680} Server running at ${w}://localhost:${s}/`+(n?" (dev)":"")),n&&a&&y(`\u{1F4CA} Performance monitoring available at http://localhost:${s}/health`));}),m}return null}}};var Qe={name:"vercel",createHandler:t=>{if(typeof t=="string")throw new Error("vercelAdapter.createHandler() requires a ServerlessConfig object, not a routesDir string. Import your routes manifest and pass { routes } instead.");let e=null,r=()=>e||(e=(async()=>{Y(t.routes),B(t.cors),F(t.middleware),V(t.middlewares),L(t.hooks);})(),e);return async(s,o)=>{await r(),fe(s),pe(o),s._maxBodySize=t.maxBodySize;let n=s,i=o;try{if(_()&&(await H("beforeRequest",n,i)===!1||i.headersSent))return;let d=W(he(n.url??"/"),n.method??"GET");if(!d){if(j()&&(await U(n,i),i.headersSent))return;i.status(404).json({error:"Route not found"});return}if(D(d)){d.allowedMethods?.length&&i.setHeader("Allow",d.allowedMethods.join(", ")),i.status(d.status??500).json({error:d.error});return}n.params=d.params,await d.handler(n,i),_()&&await H("afterRequest",n,i);}catch(d){await I(n,i,d),i.headersSent||i.status(500).json({error:"Internal server error"});}}}};function ge(t,e,r,s){let o=Object.keys(r).length>0;return {statusCode:t,headers:e,...o?{multiValueHeaders:r}:{},body:s}}var Xe={name:"netlify",createHandler:t=>{if(typeof t=="string")throw new Error("netlifyAdapter.createHandler() requires a ServerlessConfig object. Run `lacis build` to generate routes/_manifest.ts and pass { routes } instead.");let e=null,r=()=>e||(e=(async()=>{Y(t.routes),B(t.cors),F(t.middleware),V(t.middlewares),L(t.hooks);})(),e);return async(s,o)=>{await r();let n=s.queryStringParameters?"?"+new URLSearchParams(s.queryStringParameters).toString():"",i=s.path+n,d=new IncomingMessage(new Socket);if(d.url=i,d.method=s.httpMethod,d.headers=s.headers,s.body){let h=s.isBase64Encoded?"base64":"utf-8";d.push(Buffer.from(s.body,h));}d.push(null);let a="",l={},c={},p=false,E=new ServerResponse(d);E.writeHead=function(h,u){return E.statusCode=h,u&&(l={...l,...u}),this},E.setHeader=function(h,u){let S=h.toLowerCase();return Array.isArray(u)?(c[S]=u.map(String),l[S]=String(u[0])):l[S]=String(u),this},E.getHeader=function(h){return l[h.toLowerCase()]},E.end=function(h){return p=true,h!==void 0&&(a=typeof h=="string"?h:h.toString()),this},Object.defineProperty(E,"headersSent",{get:()=>p}),fe(d),pe(E),d._maxBodySize=t.maxBodySize;let m=d,w=E;m.query=s.queryStringParameters??{};try{if(_()&&(await H("beforeRequest",m,w)===!1||p))return ge(w.statusCode,l,c,a);let h=W(s.path,s.httpMethod);return h?D(h)?{statusCode:h.status??500,...h.allowedMethods?.length?{headers:{Allow:h.allowedMethods.join(", ")}}:{},body:JSON.stringify({error:h.error})}:(m.params=h.params,await h.handler(m,w),_()&&await H("afterRequest",m,w),ge(w.statusCode,l,c,a)):j()&&(await U(m,w),p)?ge(w.statusCode,l,c,a):{statusCode:404,body:JSON.stringify({error:"Route not found"})}}catch(h){return await I(m,w,h),p?ge(w.statusCode,l,c,a):{statusCode:500,body:JSON.stringify({error:"Internal server error"})}}}}};var At=new TextEncoder,ee=class{params={};url;method;headers;connection;socket={setTimeout:e=>{}};_maxBodySize;locals={};platform={};_req;constructor(e,r,s){this._req=e,this.url=r,this.method=e.method,this.headers=e.headers,this.connection={remoteAddress:s};}setTimeout(e){}body(){let e=this._maxBodySize??10485760;return this._req.arrayBuffer().then(r=>{if(r.byteLength>e)throw Object.assign(new Error("Payload Too Large"),{code:413});return Buffer.from(r)})}json(){return this._req.json()}},Ae=class{_adapterName="unknown";statusCode=200;headersSent=false;get finished(){return this.headersSent}get writableEnded(){return this.headersSent}_body=null;_headers=null;_sseReadable=null;_streamBody=null;_sseWriter=null;_sseWindowClosed=false;_listeners=null;on(e,r){return (e==="finish"||e==="close")&&(this._listeners||(this._listeners=[]),this._listeners.push(r)),this}once(e,r){return this.on(e,r)}emit(e){if((e==="finish"||e==="close")&&this._listeners)for(let r=0;r<this._listeners.length;r++)this._listeners[r]();return true}setHeader(e,r){if(this._headers||(this._headers=[]),Array.isArray(r))for(let s of r)this._headers.push(e,s);else this._headers.push(e,r);return this}getHeader(e){if(!this._headers)return;let r=e.toLowerCase();for(let s=0;s<this._headers.length;s+=2)if(this._headers[s].toLowerCase()===r)return this._headers[s+1]}removeHeader(e){if(!this._headers)return this;let r=e.toLowerCase();for(let s=0;s<this._headers.length;s+=2)if(this._headers[s].toLowerCase()===r){this._headers.splice(s,2);break}return this}hasHeader(e){if(!this._headers)return false;let r=e.toLowerCase();for(let s=0;s<this._headers.length;s+=2)if(this._headers[s].toLowerCase()===r)return true;return false}writeHead(e,r){if(this.statusCode=e,r)for(let[s,o]of Object.entries(r))this.setHeader(s,o);return this}write(e){return this._sseWriter?(this._sseWriter.write(At.encode(String(e))),true):(this._body=(this._body??"")+e,true)}end(e){if(e!==void 0&&this.write(e),this._sseWriter&&this._sseWriter.close(),this.headersSent=true,this._listeners)for(let r=0;r<this._listeners.length;r++)this._listeners[r]();return this}_initSseStream(){if(this._sseWindowClosed)throw new Error(`[lacis/${this._adapterName}] initSSE() must be called synchronously before any \`await\` in your handler.`);let{readable:e,writable:r}=new TransformStream;this._sseReadable=e,this._sseWriter=r.getWriter();}_closeSseWindow(){this._sseWindowClosed=true;}},te=class extends ne(Ae){initSSE(e){return this._initSseStream(),super.initSSE(e)}stream(e){return this.setHeader("Cache-Control","no-cache"),this.setHeader("X-Accel-Buffering","no"),e instanceof ReadableStream?this._streamBody=e:this._streamBody=new ReadableStream({async start(r){for await(let s of e)r.enqueue(s);r.close();}}),this.headersSent=true,Promise.resolve()}ndjson(e){let r=new TextEncoder;return this.setHeader("Content-Type","application/x-ndjson"),this.setHeader("Cache-Control","no-cache"),this.setHeader("X-Accel-Buffering","no"),this._streamBody=new ReadableStream({async start(s){for await(let o of e)s.enqueue(r.encode(JSON.stringify(o)+` `));s.close();}}),this.headersSent=true,Promise.resolve()}};function q(t,e){let r=e??t._streamBody??t._body;if(!t._headers)return new globalThis.Response(r,{status:t.statusCode});let s=new Headers;for(let o=0;o<t._headers.length;o+=2){let n=t._headers[o],i=t._headers[o+1];n.toLowerCase()==="set-cookie"?s.append(n,i):s.set(n,i);}return new globalThis.Response(r,{status:t.statusCode,headers:s})}var xe=class extends ee{text(){return this._req.text()}},ke=class extends Q(xe){},Oe=class extends te{_adapterName="bun"},Ze={name:"bun",createHandler:t=>{if(typeof t!="string")throw new Error("bunAdapter requires a routesDir string, not a ServerlessConfig.");let e=t;return async(r={})=>{let{isDev:s,port:o=3e3,defaultHeaders:n,cluster:i}=r,d=parseInt(process.env.LACIS_BUN_WORKER??"0"),a=d>0;if(i?.enabled&&!a){let p=i.workers??k__default.cpus().length;y(`\u{1F9F5} Starting Bun server with ${p} workers (reusePort)`);let E=Array.from({length:p},()=>Bun.spawn(process.argv,{env:{...process.env,LACIS_BUN_WORKER:String(process.pid)},stdout:"ignore",stderr:"inherit"}));return y(`\u{1F680} Server running at http://localhost:${o}/`),{close:m=>{for(let w of E)w.kill();m?.();}}}if(a){let p=setInterval(()=>{try{process.kill(d,0);}catch{clearInterval(p),process.exit(0);}},2e3);p.unref();}y("\u{1F680} Bun high-performance mode enabled"),r.routes||await ie(e),B(r.cors),F(r.middleware),L(r.hooks);let l=n?Object.entries(n):[],c=Bun.serve({port:o,reusePort:a,async fetch(p,E){let m=new URL(p.url),w=m.pathname,h=new ke(p,w+m.search,E?.requestIP(p)?.address??"");h._maxBodySize=r.maxBodySize,h.query=Z(m.search);let u=new Oe;try{for(let M=0;M<l.length;M++)u.setHeader(l[M][0],l[M][1]);if(_()&&(!await H("beforeRequest",h,u)||u.headersSent))return q(u);let S=W(w,p.method);if(!S)return j()&&(await U(h,u),u.headersSent)?q(u):new Response(JSON.stringify({error:"Route not found"}),{status:404,headers:{"Content-Type":"application/json"}});if(D(S)){_()&&await H("onError",h,u);let M={"Content-Type":"application/json"};return S.allowedMethods?.length&&(M.Allow=S.allowedMethods.join(", ")),new Response(JSON.stringify({error:S.error}),{status:S.status||500,headers:M})}h.params=S.params;let b=null,$=(async()=>{await S.handler(h,u),_()&&await H("afterRequest",h,u),u.headersSent||u.end();})().catch(M=>{b=M,s&&console.error("Server error:",M),u._sseReadable&&!u.headersSent&&u.end();});return u._closeSseWindow(),u._sseReadable?q(u,u._sseReadable):(await $,b&&(await I(h,u,b),!u.headersSent)?new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}}):q(u))}catch(S){return await I(h,u,S),u.headersSent?q(u):new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}});return y(`\u{1F680} Server started on http://localhost:${o}${s?" (dev)":""}`),{close:()=>{c.stop();}}}}};var Ne=class extends ee{constructor(e,r,s,o){super(e,r.pathname+r.search,e.headers.get?.("cf-connecting-ip")??""),this.platform={env:s,ctx:o,cf:e.cf};}},Pe=class extends Q(Ne){},Ie=class extends te{_adapterName="cloudflare"},Ke={name:"cloudflare",createHandler:t=>{if(typeof t=="string")throw new Error("cloudflareAdapter.createHandler() requires a ServerlessConfig object, not a routesDir string. Import your routes manifest and pass { routes } instead.");let e=t.defaultHeaders?Object.entries(t.defaultHeaders):[],r=null,s=()=>r||(r=(async()=>{Y(t.routes),B(t.cors),F(t.middleware),V(t.middlewares??[]),L(t.hooks);})(),r);return {async fetch(o,n,i){await s();let d=new URL(o.url),a=new Pe(o,d,n,i);a._maxBodySize=t.maxBodySize,a.query=Z(d.search);let l=new Ie;try{for(let m=0;m<e.length;m++)l.setHeader(e[m][0],e[m][1]);if(_()&&(!await H("beforeRequest",a,l)||l.headersSent))return q(l);let c=W(d.pathname,o.method);if(!c)return j()&&(await U(a,l),l.headersSent)?q(l):new globalThis.Response(JSON.stringify({error:"Route not found"}),{status:404,headers:{"Content-Type":"application/json"}});if(D(c)){_()&&await H("onError",a,l);let m={"Content-Type":"application/json"};return c.allowedMethods?.length&&(m.Allow=c.allowedMethods.join(", ")),new globalThis.Response(JSON.stringify({error:c.error}),{status:c.status??500,headers:m})}a.params=c.params;let p=null,E=(async()=>{await c.handler(a,l),_()&&await H("afterRequest",a,l),l.headersSent||l.end();})().catch(m=>{p=m;});return l._closeSseWindow(),l._sseReadable?q(l,l._sseReadable):(await E,p&&(await I(a,l,p),!l.headersSent)?new globalThis.Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}}):q(l))}catch(c){return await I(a,l,c),l.headersSent?q(l):new globalThis.Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}}}};var kt={node:Ye,vercel:Qe,netlify:Xe,bun:Ze,cloudflare:Ke};function ws(t="node"){let e=kt[t];if(!e)throw new Error(`Platform "${t}" not supported`);return e} export{Ye as A,Qe as B,Xe as C,Ze as D,Ke as E,ws as F,Pt as a,It as b,at as c,y as d,se as e,Y as f,ie as g,Vt as h,Gt as i,P as j,x as k,Le as l,Xt as m,Zt as n,Kt as o,er as p,tr as q,rr as r,sr as s,nr as t,gt as u,yt as v,wt as w,Ue as x,Fe as y,Be as z};