rossa 0.0.5 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,75 @@
1
1
  // @bun
2
- var nt=function(t,n,r,o){var i=arguments.length,s=i<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,r):o,e;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")s=Reflect.decorate(t,n,r,o);else for(var f=t.length-1;f>=0;f--)if(e=t[f])s=(i<3?e(s):i>3?e(n,r,s):e(n,r))||s;return i>3&&s&&Object.defineProperty(n,r,s),s};var rt=(t,n)=>{if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(t,n)};import{Auth as bn}from"authored";var ot=(t)=>typeof t==="function";var C=(t)=>{return!isNaN(parseFloat(t))&&isFinite(t)};var it=(t)=>{return t instanceof Uint8Array||t instanceof ArrayBuffer||typeof t==="string"};var G=(t)=>typeof t==="string",x=(t)=>Array.isArray(t),st=(t)=>typeof t==="object";var et=(t)=>{return Number.isInteger(Number(t))};function ft(t,n){l(n).forEach(([r,o])=>{mt(t,r,{value:o,writable:!1,configurable:!1,enumerable:!0})})}var Y=(t)=>{return x(t)?t:[t]};class d{static set i(t){console.info(...Y(t))}static set e(t){console.error(...Y(t))}static set w(t){console.warn(...Y(t))}}var ut=(t,n)=>{let[r,o]=n.replace(/bytes=/,"").split("-").map((i,s)=>{let e=parseInt(i,10);return isNaN(e)?s===0?0:t-1:e});return[r,o,t]};var zt=(t)=>Array.from({length:t},(n,r)=>r),Ft="ABCDEFGHIJKLMNOPQRSTUVWXYZ",jt="abcdefghijklmnopqrstuvwxyz";var E=(t)=>JSON.stringify(t),pt=(t)=>{return JSON.parse(t)};var b=(t)=>{let n=Ft+jt,r=zt(10).join("");return Array.from({length:t},(o,i)=>n+(i?r:"")).reduce((o,i)=>{return o+=i.charAt(Math.floor(Math.random()*i.length))},"")};var J=(t,n)=>{let r=n==="/"?"":n;if(n.startsWith("#"))return t+n;return n.startsWith("/")?t+r:n};class a extends Map{obj(t){t&&l(t).forEach(([n,r])=>this.set(n,r))}map(t){t.forEach((n,r)=>{if(n instanceof a)this.set(r,n);else if(x(n)){if(this.lacks(r))this.set(r,[]);this.get(r).push(...n)}else if(st(n))this.ass(r,n);else this.set(r,n)})}ass(t,n){if(!this.has(t))this.set(t,{});R(this.get(t),n)}lacks(t){return!this.has(t)}init(t,n){return this.has(t)?this.get(t):this.set(t,n).get(t)}}var{values:N,keys:Z,entries:l}=Object;var{defineProperty:mt,assign:R}=Object;var q=(t)=>{return Object.keys(t).length};function ht(t){return class extends t{constructor(...n){super(...n);let r=new Map;return new Proxy(this,{get(o,i){let s=`__${i}`;if(!r.has(s)){let e=o[i];if(ot(e))e=function(...f){let u=`${s}_${JSON.stringify(f)}`;if(!r.has(u)){let m=o[i].apply(o,f);r.set(u,m)}return r.get(u)};r.set(s,e)}return r.get(s)},set(o,i,s){let e=`__${i}`;return r.set(e,s),!0}})}}}var lt=(t,n="",{maxAge:r,expires:o,path:i,domain:s,secure:e,httpOnly:f,sameSite:u})=>{if(r instanceof Date)r=r.getSeconds();if(o instanceof Date)o=o.toUTCString();else if(o===0)o=new Date().toUTCString();return[["Domain",s],["Expires",o],["Max-Age",r],["Secure",e],["HttpOnly",f],["Path",i],["SameSite",u]].reduce((p,[S,c])=>{if(c!==void 0)p.push(`${S}=${c}`);return p},[`${t}=${n}`]).join("; ")};var W=(t,n=!1)=>{if(C(t))return[+t,et(t)?"int":"float"];if(n&&/\.\w+$/.test(t))return[t,"file"];if(t==="/")return[t,"-"];if(t.length===36&&t.match(/\-/g)?.length===4)return[t,"uuid"];return[t,"string"]},y=(t)=>{let n=t.startsWith("/")?t:"/"+t,r=n.match(/(?<=\/)[^/].*?(?=\/|$)/g)??["/"],[o,i]=r.reduce(([s,e],f)=>{if(f.includes("<")){let u=f.match(/(?<=<)[^/].*?(?=>|$)/g);if(u?.length){let[m,p]=u[0].split(":");if(m)s.push(m),e.push(p||"_")}}else s.push(f===">"?"/":f);return[s,e]},[[],[]]);if(n.endsWith("/")&&n.length>1)o.push("/");return{parsed:o,args:i}};class ${storage;constructor(){this.storage=new a}cache(t,n){if(this.storage.lacks(t))this.storage.set(t,n());return this.storage.get(t)}}var Vt=["int","float","file","uuid","string"];class H{_storage;CC;constructor(){this._storage=new a,this.CC=new $}set(t){let{parsed:n,path:r}=t,o=E(n);if(!this._storage.get(o))this._storage.set(o,t);else throw`path: ${r} already used.`}get(t){let{parsed:n}=this.CC.cache(t,()=>y(t)),r={},o=this._storage.get(E(n));if(!o&&t!=="/")for(let i of this._storage.keys()){let s=[],e=pt(i);if(n.length===e.length){let f=e.map((p,S)=>{let c=W(n[S],n.length-1===S);if(p===c[0])return c[0];if(Vt.includes(c[1]))return s.push(c[0]),c[1];return p}),u=E(f);if(this._storage.has(u)){o=this._storage.get(u),o?.args.forEach((p,S)=>{r[p]=s[S]});break}}}return[o,r]}}class I{constructor(...t){t.forEach((n)=>{if(!this[n])this[n]=new H})}get(t){return this[t]}}class U{path="";parsed=[];args=[];constructor(t){ft(this,{path:t,...y(t)})}}class B{date;constructor(t){this.date=t?new Date(t):new Date}delta(t=null,n=!1){let r=B.delta(this.date.getTime(),t);return n?new Date(r):r}timed(t){if(!t)return this.date;return[["year","FullYear"],["month","Month"],["day","Date"],["hour","Hours"],["minute","Minutes"],["second","Seconds"]].reduce((r,[o,i])=>{let s=t[o];return s?new Date(r[`set${i}`](r[`get${i}`]()+s)):r},new Date(this.date))}static delta(t,n=null){return n?n-t:t-Date.now()}static local(t){return new Date(t).toLocaleString()}static get now(){return Date.now()}}var{file:tn}=globalThis.Bun;import{JWTInterface as kt}from"authored";class at{session;jwt;jwtInt;constructor(){this.jwtInt=new kt}init(t){this.session=t.session,this.jwt=t.jwt}}var h=new at;class T{__session;__jwt;get session(){if(!this.__session)this.__session=h.session.new;return this.__session}set session(t){this.__session=t}get jwt(){if(!this.__jwt)this.__jwt=h.jwt.new;return this.__jwt}set jwt(t){this.__jwt=t}get timedJWT(){return h.jwtInt.jwt()}setServerSession(t){let{__jwt:n,__session:r}=t;this.__session=r,this.__jwt=n}}var ct=async(t,n)=>{await h.session.saveSession(t,n)};async function gt({sid:t,jwtv:n,refreshjwt:r},o){let i=new T;if(t){if(i.session=await h.session.openSession(t),!i.session.new)o.session=!0}if(n){if(i.jwt=h.jwtInt.open(n,{hours:6}),!i.jwt.new)o.jwt=!0;if(r){if(!(await h.jwt.openSession(r)).new)o.jwt_refresh=!0}}if("session"in o||"jwt"in o)return i}var vt={session(...t){return A(t[0],t[2],"session")},jwt(...t){return A(t[0],t[2],"jwt")},jwt_refresh(...t){return A(t[0],t[2],"jwt_refresh")}},A=(t,n,r)=>{let o=n.value;return n.value=async function(i={}){if(r in i&&i.session)return delete i[r],o.call(t,i);return{error:401}},n};var nn=["GET","POST","PUT","DELETE","OPTIONS"];class St extends U{config;_class;options="";bytes;fileType="text/plain";fileSize=0;constructor(t,n={}){super(t);this.config=n}set serverClass(t){this._class=t,this.options=nn.filter((n)=>t.prototype[n.toLowerCase()]).join(", ")}get serverClass(){return this._class}async loadBytes(t="."){if(!this.config.preload)return;try{d.i=this.path;let n=this.path.startsWith("/")?this.path:"/"+this.path,r=tn(t+this.path);this.fileType=r.type,this.bytes=await r.bytes(),this.fileSize=this.bytes.byteLength}catch{throw`error: can't preload ${this.path}. File not found.`}}}var bt={path:Symbol("path"),wss:Symbol("wss"),file:Symbol("file"),folder:Symbol("folder"),error:Symbol("error")},rn=new I(...N(bt)),wt=(t)=>{let n=bt[t];if(!n)throw new Error("Invalid storage type");return rn[n]},w=(t,n,r={},o)=>{return(i)=>{let s=new St(n,r);if(i)s.serverClass=i;if(t==="file")s.loadBytes(o);return wt(t).set(s),i}},yt={args:{}};async function g(t){let[n,r]=wt(t).get(this.path);if(!n)return yt;let{requireSession:o}=n.config,i=void 0;if(o){if(i=await gt(await this.request.authgroup(),r),!i)return yt}return{serverPath:n,args:r,session:i}}class dt{}class L extends dt{dir;apt;base;_statics;constructor(t=".",n={}){super();this.dir=t;let{dir:r,base:o,clientDir:i}=n;if(r)this.dir=r;this.apt=i?i:"./client",this.base=o??"",this.files=(...s)=>{s.forEach((e)=>{let[f,u]=xt.call(this,e),m=f.replace(/^\.+/,""),p=m.startsWith("/")?m:"/"+m;w("file",p,u,this.apt)()})},this.folders=(...s)=>{s.forEach((e)=>{w("folder",...xt.call(this,e))()})},this.statics=(s={})=>{if(!this._statics)this._statics={};R(this._statics,s)},this.route=(s)=>{return w("path",this._base(s))},this.wss=(s,e={})=>{return w("wss",this._base(s),e)},this.error=(...s)=>{return(e)=>{if(s.length)s.forEach((f)=>{w("error",this._base(f.toString()),{})(e)});else w("error",this._base("404"),{})(e);return e}},this.redirect=(s,e={})=>{return new Response("",{status:302,headers:new Headers({...e,Location:this._base(s)})})}}_base(t){return J(this.base,t)}}function xt(t){let n=G(t);return[n?this._base(t):this._base(t[0]),n?{}:t[1]]}var{inflateSync:gn,serve:yn,write:Sn}=globalThis.Bun;class Rt extends a{}var z=new Rt;var F={async open(t){let n=t.data.wclass,{args:r,client:o}=t.data;if(n){n.ws=t;let i=n.id,s=q(o);if(!(i in o)){let e=s?"joiner":"maker";o[i]={role:e}}if(typeof n.init=="function")await n.init(r);if(n.broadcasting)n.ws.subscribe(n.path);await n.open()}else t.close()},async message(t,n){let r=t.data.wclass;if(r)await r.message(n)},async close(t,n,r){let o=t.data.wclass,i=t.data.client;if(o){if(await o.close(n,r),o.broadcasting)o.ws.unsubscribe(o.path);let s=o.id;if(delete i[s],q(i)===1)Z(i).forEach((e)=>{i[e].role="maker"})}}};async function j(){let{serverPath:t,args:n,session:r}=await g.call(this,"wss");if(!t)return this.status=426,"upgrade error";let{serverClass:o}=t;if(!o)return"upgrade error";let i=new o(this.request);r&&i.setServerSession(r);let s=i.path,e=Tt(s),f=e?.size??0,{broadcast:u,maxClient:m}=t.config;if(i.broadcasting=!!u,i.max=m??0,m&&f>=m)return this.status=400,"upgrade error";return this.request.upgradeConnection({data:{wclass:i,args:n,client:e}}),null}class Ct extends T{request;ws;path;id;broadcasting=!1;max=0;constructor(t){super();this.request=t;this.path=t.path,this.id=b(10)}open(){}message(t){}close(t,n){}set send(t){if(t)if(this.broadcasting)this.ws.publish(this.path,t);else this.ws.send(t)}get role(){let t=z.get(this.path);if(t&&t.has(this.id))return t.get(this.id)?.role}}var Tt=(t)=>{return z.init(t,new a)};var{deflateSync:pn,gzipSync:hn}=globalThis.Bun;var{Server:on,file:sn}=globalThis.Bun;class M{req;server;formData;url;method;__cookies=new Map;constructor(t,n){this.req=t;this.server=n;this.url=new URL(t.url),this.method=this.req.method.toLowerCase()}async json(){return await this.req.json()}async form(){if(this.isForm){if(!this.formData)this.formData=await this.req.formData();return this.formData}return new FormData}async authgroup(){let{cookies:t,auth:n}=this,r=t.get("session")??"",o=n??"",i="",s=this.isForm?await this.form():void 0;if(s){let e=s.get("refresh_token");i=e?e.toString():""}return{sid:r,jwtv:o,refreshjwt:i}}upgradeConnection(t={}){return!!this.server?.upgrade(this.req,t)}get auth(){let t=this.headers.get("authorization");if(t){let[n,r]=t.split(" ",2);if(n.trim()=="Bearer")return r.trim()}}get accept(){return this.headers.get("accept")}get contentType(){return this.headers.get("content-type")}get cookies(){if(!this.__cookies.size){let t=this.headers.get("cookie");if(t){let n=t.split(";").reduce((r,o)=>{let[i,s]=o.trim().split(/=(.*)/s);return r.push([i,s]),r},[]);this.__cookies=new Map(n)}}return this.__cookies}get headers(){return this.req.headers??new Headers}get ip(){return this.server?.requestIP(this.req)}get isForm(){let t=this.contentType;return t?t.indexOf("multipart/form-data")>=0||t.indexOf("x-www-form-urlencoded")>=0:!1}get path(){return this.url.pathname}get hash(){return this.url.hash}get fullPath(){let{pathname:t,hash:n}=this.url;return t+n}get parsed(){let{parsed:t}=y(this.path);return t}get searchParams(){return this.url.searchParams}get range(){return this.headers.get("range")??void 0}get isEventStream(){return this.accept?.includes("text/event-stream")}get isWSS(){return!!this.headers.get("upgrade")}get isFile(){let t=this.parsed.slice().pop();return t?W(t,!0).pop()==="file":!1}get type(){return sn(this.path).type}get upgrade(){return this.headers.get("upgrade")}get request(){return this.req}get signal(){return this.req.signal}}M=nt([ht,rt("design:paramtypes",[typeof Request==="undefined"?Object:Request,typeof on==="undefined"?Object:on])],M);class Et{ctrl;intervalID=[];constructor(t){this.ctrl=t}push(t,n=2000){if(this.ctrl){let r=setInterval(()=>{let{id:o,retry:i,data:s,event:e,end:f}=t();if(this.ctrl){let u=f?"end":s;if(i){let m=i>2000?i:2000;this.ctrl.enqueue(`retry: ${m}\\n`)}if(this.ctrl.enqueue(`id: ${o}\\n`),e&&this.ctrl.enqueue(`event: ${e}\\n`),typeof u=="object")this.ctrl.enqueue("data: "+JSON.stringify(u)+"\\n\\\n");else this.ctrl.enqueue("data: "+JSON.stringify({message:u})+"\\n\\n");f&&this.close()}},n>1000?n:1000);this.intervalID.push(r)}}close(){if(this.intervalID.length)this.intervalID.forEach((t)=>{clearInterval(t)}),this.intervalID=[];this.ctrl?.close()}}async function qt(t,n,r){this.status=200,this.header={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};let o=this.request,i=new ReadableStream({async start(e){t.stream=new Et(e),await r.call(t,n),o.signal.addEventListener("abort",()=>{if(t.stream?.close(),t.stream?.intervalID.length)e.close()})}}),s=await r.call(t,n);if(typeof s==="object"&&"error"in s)return this.status=s.error,null;return i}async function Bt(t){let n=h.jwtInt.save(t);return t.access_token=n,await h.jwt.saveSession(t,this.headers),{access_token:n,refresh_token:t.sid,status:"ok"}}function Mt(t){return this.status=403,{error:t}}async function Ot(t){let{jwtv:n,refreshjwt:r}=await this.request.authgroup();if(!r){if(n||!t.modified)return this.status=204,this.type="application/json",JSON.stringify({});return JSON.stringify(await Bt.call(this,t))}let o=await h.jwt.openSession(r),i=o.data.access_token,s={};if(n!==i)s=Mt.call(this,"tokens don't match.");else if(!h.jwtInt.verify(i,{days:5}))await h.jwt.saveSession(o,void 0,!0),s=Mt.call(this,"expired refresh_token.");else s=await Bt.call(this,o);return this.type="application/json",JSON.stringify(s)}var{file:en}=globalThis.Bun;async function Dt(){let t=this.path,{parsed:n}=y(this.path),r=n.slice(0,-1).join("/");this.path=r;let{serverPath:o}=await g.call(this,"folder");if(!o)return null;return this.path=t,await K.call(this)}async function Jt(){let{serverPath:t}=await g.call(this,"file");if(!t)return await Dt.call(this);if(t.bytes)return _.call(this,t.bytes,t.fileSize);return await K.call(this)}async function K(){try{let t=en(this.dir+this.path);if(t.type.startsWith("video/"))return _.call(this,t,t.size);else{let n=await t.bytes();return _.call(this,n,n.byteLength)}}catch{return`${this.path} file not found.`}}function _(t,n){let{type:r,range:o}=this.request;if(this.type=r,this.status=206,!o)return this.header={"Cache-Control":"max-age=86400, must-revalidate"},it(t)?this.compress("gzip",t):t;let[i,s,e]=ut(n,o);return this.header={"Content-Range":`bytes ${i}-${s}/${e}`,"Content-Length":n.toString()},t.slice(i,s+1)}async function Nt(t){return this.status=t.status,this.header=t.headers.toJSON(),await t.arrayBuffer()}import{ServerSide as fn}from"authored";function O(t,n){if(this.status=n||200,typeof t==="object")return this.type="application/json",JSON.stringify(t);return this.type="text/html",String(t)}async function Wt(t){if(t instanceof fn)return Ot.call(this,t);return O.call(this,t)}class D{type;render;data;constructor(t,n,r={}){this.type=t;this.render=n;this.data=r}static async jwt(t){return new D("jwt",t)}}async function $t(t,n=!1){let{type:r,render:o,data:i}=t;switch(r){case"jwt":return"jwt"}return"render"}function un(t){return this.status=t??204,null}async function mn(t){let{header:n,status:r,__session:o}=t;if(q(n))this.header=n;if(r)this.status=r;o&&await ct(o,this.headers)}async function P(t,n,r=!1){if(!n)return un.call(this,t.status);if(typeof n==="object"&&"error"in n&&C(n.error))return this.status=n.error,null;if(await mn.call(this,t),n instanceof Response)return await Nt.call(this,n);if(n instanceof D){if(t.status)this.status=t.status;return await $t.call(this,n,r)}switch(this.request.method){case"post":return Wt.call(this,n);default:return O.call(this,n)}}async function It(){let{serverPath:t,args:n,session:r}=await g.call(this,"path");if(!t)return this.request.isFile?await Jt.call(this):null;let{serverClass:o}=t;if(!o)return null;let i=new o(this.request,n);r&&i.setServerSession(r);let{isEventStream:s,method:e}=this.request;if(s&&i?.eventStream)return await qt.call(this,i,n,i.eventStream);if(e==="options")return this.status=204,this.options(t.options);if(i?.[e]){let f=await i[e]();return this.status=200,this.compress("deflate",await P.call(this,i,f)??"")}return null}async function Ut(){let t=this.path;this.path=this.status.toString();let{serverPath:n,args:r,session:o}=await g.call(this,"error");if(this.path=t,!n)return null;let{serverClass:i}=n;if(!i)return null;let s=new i(this.request,r);s.status=this.status;let{method:e}=this.request;if(s?.[e]){let f=await s[e]();return this.compress("deflate",await P.call(this,s,f,!0)??"")}return null}class Pt extends T{request;args;status;stream;path;hash;headers={};constructor(t,n={}){super();this.request=t;this.args=n;this.path=t.path,this.hash=t.hash}set header(t){R(this.headers,t)}get header(){return this.headers}set type(t){this.header={"Content-Type":t}}setCookie({key:t,val:n,path:r="/",days:o=31,httpOnly:i=!1}){let s=lt(t,n,{expires:new B().timed({day:o}),path:r,httpOnly:i,sameSite:"Strict"});this.header={"Set-Cookie":s}}deleteCookie(t){this.setCookie({key:t,val:"",days:0})}}class Qt{status=404;headers=new Headers({"Content-Type":"text/plain"});set header(t){l(t).forEach(([n,r])=>{this.headers.set(n,r)})}set type(t){this.headers.set("Content-Type",t)}options(t){return t+=", OPTIONS",this.header={Allow:t,"Access-Control-Allow-Methods":t,"Access-Control-Max-Age":"86400"},null}compress(t,n){let o=(t==="gzip"?hn:pn)(n);return this.header={"Content-Length":o.byteLength.toString(),"Content-Encoding":t},o}get init(){return{status:this.status,headers:this.headers}}}class Q extends Qt{dir;base;request;path="";constructor(t,n,r="./",o=""){super();this.dir=r;this.base=o;this.request=new M(t,n)}async response(){let{fullPath:t,isWSS:n}=this.request;this.path=this._base(t);let r=await(n?j:It).call(this);if(!r&&!this.request.isFile)r=await Ut.call(this);return new Response(r,this.init)}_base(t){return J(this.base,t)}}import{mkdirSync as ln,writeFileSync as an,existsSync as Gt}from"fs";var{file:cn}=globalThis.Bun;var{file:X,write:Xt}=globalThis.Bun;class V{fs;f_timed;data;key;dir;constructor({dir:t,fs:n,key:r}){this.dir=t+"/ffs",this.key=r,this.f_timed=Date.now(),this.data=new Map,this.fs=this.dir+`/${n}.json`}async init(){if(v(this.dir)&&k(this.fs,"{}"))X(this.fs).text().then((t)=>{let n=JSON.parse(t);this.data=new Map(l(n))}).catch((t)=>{})}async get(t){let n=this.data.get(t);if(n)return n;return null}async queue(){}async set(t){if(this.key in t){let n=await X(this.fs).text();if(n){let r=JSON.parse(n),o=t[this.key];r[o]=t,await Xt(this.fs,JSON.stringify(r))}this.data.set(t[this.key],t)}return!1}async delete(t){if(await this.get(t)){let n=await X(this.fs).text();if(n){let r=JSON.parse(n.toString());if(t in r)delete r[t],await Xt(this.fs,JSON.stringify(r));this.data.delete(t)}}}async json(){let t=await X(this.fs).text();return JSON.parse(t)}}var k=(t,n="")=>{if(Gt(t))return!0;return an(t,n,{flag:"wx"}),!0},v=(t)=>{if(Gt(t))return!0;return ln(t,{recursive:!0}),!0},Yt=(t,n)=>{if(!n)v(t),k(t+"/.env",`SECRET_KEY="${b(20)}"
3
- TLS_KEY=""
4
- TLS_CERT=""`)},tt=(t)=>{return l(process.env).filter(([n])=>n.startsWith("TLS_")).reduce((n,[r,o])=>{if(o){let i=r.replace("TLS_","").toLowerCase();n[i]=cn(t+o)}return n},{})};async function Zt(t){let{server:n,wss:r}=t,o=n.fn;delete n.fn;let{key:i,cert:s}=tt(this.dir),e=n.port||3000,f=yn({...n,...this._statics&&{static:this._statics},port:e,tls:{key:await i.text(),cert:await s.text()},fetch:async(m,p)=>{return await new Q(m,p,this.apt,this.base).response()},websocket:{sendPings:!0,perMessageDeflate:!0,...r,...F}});o?.(e);let u=()=>{f.stop(),process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u)}var Ht=async(t,n,r="")=>{let{path:o,hostname:i,method:s,port:e,name:f}=t,m=await(await new Q({url:`http://${i??"127.0.0.1"}:${e||3000}${o}`,method:s??"GET"},void 0,n).response()).arrayBuffer(),p=o?.slice(1),c=(f?`/${f}`:p?"/"+p:"").split("#")[0];if(m.byteLength)await Sn(n+r+`${c}/index.html`,gn(m));return c+"/index"};import{config as wn}from"dotenv";class At extends L{html;serve;constructor(t={}){super(".",t);let{envPath:n,session:r}=t,o=this.dir+"/.private";Yt(o,n),wn({path:(n?n:o)+"/.env"});let i=r??new bn({dir:this.dir});h.init(i),this.html=async(s={})=>{s.path=this._base(s.path||"/");let e=await Ht(s,this.apt,this.base),f=new Date().toLocaleTimeString();d.i=`${e}.html @ ${f}`},this.serve=async(s={},e)=>await Zt.call(this,{server:s,wss:e}),this.folders("/")}}export{Ct as websocket,Pt as response,d as log,tt as getTLS,vt as auths,B as Time,At as Rossa,D as Render,a as Mapper,V as JSONCacher};
2
+ var Ft=Object.defineProperty;var jt=(e)=>e;function Ut(e,t){this[e]=jt.bind(null,t)}var Ht=(e,t)=>{for(var r in t)Ft(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ut.bind(t,r)})};var $t={};Ht($t,{array:()=>Hr,boolean:()=>Ur,coerce:()=>Br,number:()=>jr,object:()=>Wr,string:()=>Fr});class ye{data;constructor(e={}){this.data={...e}}_add(e,t){return this.data[e]=t,this}add(e,t){return this._add(e,t)}}class be extends ye{frameOptions(e="DENY"){return this._add("X-Frame-Options",e)}noSniff(){return this._add("X-Content-Type-Options","nosniff")}hsts(e=31536000){return this._add("Strict-Transport-Security",`max-age=${e}; includeSubDomains; preload`)}csp(e="default-src 'self'"){return this._add("Content-Security-Policy",e)}referrer(e="strict-origin-when-cross-origin"){return this._add("Referrer-Policy",e)}coop(e="same-origin"){return this._add("Cross-Origin-Opener-Policy",e)}coep(e="require-corp"){return this._add("Cross-Origin-Embedder-Policy",e)}permissions(e){return this._add("Permissions-Policy",e)}}class Se extends be{cors(e="*"){return this._add("Access-Control-Allow-Origin",e),this._add("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),this._add("Access-Control-Allow-Headers","Content-Type, Authorization"),this}cache(e=3600){return this._add("Cache-Control",`public, max-age=${e}`)}noCache(){return this._add("Cache-Control","no-store, no-cache, must-revalidate")}etag(e){return this._add("ETag",`"${e}"`)}serverTiming(e,t,r=""){return this._add("Server-Timing",`${e};dur=${t};desc="${r}"`)}rateLimit(e,t,r){return this._add("X-RateLimit-Limit",e.toString()),this._add("X-RateLimit-Remaining",t.toString()),this._add("X-RateLimit-Reset",r.toString())}retryAfter(e){return this._add("Retry-After",e.toString())}expires(e){return this._add("Expires",e.toUTCString())}lastModified(e){return this._add("Last-Modified",e.toUTCString())}}class we extends Se{authenticate(e,t){let r=t?`${e} ${t}`:e;return this._add("WWW-Authenticate",r)}proxyAuthenticate(e){return this._add("Proxy-Authenticate",e)}}class Ee extends we{content(e){if(e.length!==void 0)this.contentLength(e.length);if(e.type)this.contentType(e.type);if(e.encoding)this.contentEncoding(e.encoding);if(e.language)this.language(e.language);if(e.range)this.contentRange(e.range);if(e.location)this.contentLocation(e.location);if(e.md5)this.contentMD5(e.md5);if(e.disposition)this.disposition(e.disposition.type,e.disposition.filename);return this}contentLength(e){return this._add("Content-Length",e.toString())}contentMD5(e){return this._add("Content-MD5",e)}contentType(e){return this._add("Content-Type",e)}contentEncoding(e){return this._add("Content-Encoding",e)}contentLocation(e){return this._add("Content-Location",e)}contentRange(e){return this._add("Content-Range",e)}contentSecurity(e){return this._add("Content-Security",e)}disposition(e="attachment",t){let r=t?`${e}; filename="${t}"`:e;return this._add("Content-Disposition",r)}vary(...e){return this._add("Vary",e.join(", "))}language(e){return this._add("Content-Language",e)}}class Te extends Ee{location(e){return this._add("Location",e)}origin(e="*"){return this._add("Access-Control-Allow-Origin",e)}date(e=new Date){return this._add("Date",e.toUTCString())}server(e){return this._add("Server",e)}connection(e){return this._add("Connection",e)}keepAlive(e){return this._add("Keep-Alive",String(e))}cookie(e,t,r={sameSite:"Strict",httpOnly:!0,path:"/"}){if(!r.expires){let n=new Date;n.setDate(n.getDate()+31),r.expires=n}return this._add("Set-Cookie",Wt(e,t,r))}}var Wt=(e,t="",r={})=>{let{maxAge:n,expires:s,path:i,domain:a,secure:o,httpOnly:c,sameSite:l}=r,u=n instanceof Date?Math.floor(n.getTime()/1000):typeof n==="number"?n:void 0,m;if(s instanceof Date)m=s.toUTCString();else if(typeof s==="number")m=new Date(s).toUTCString();else if(typeof s==="string")m=s;else if(s===0)m=new Date().toUTCString();let f=[];if(a)f.push(`Domain=${a}`);if(m)f.push(`Expires=${m}`);if(u!==void 0)f.push(`Max-Age=${u}`);if(o)f.push("Secure");if(c)f.push("HttpOnly");if(i!=null)f.push(`Path=${i}`);if(l!=null)f.push(`SameSite=${l}`);return[`${e}=${t}`,...f].join("; ")};class I extends Te{get copy(){return new I(this.data)}use(e){return e(this),this}merge(e){return Object.assign(this.data,e instanceof I?e.data:e),this}static init(e){return new this(e)}static get $(){return new this}get done(){return this.data}}class F{res;params={};headr;url;data={};jwtData={};session;body;query={};form={};req;method="GET";methods=[];clientDirectory="";constructor(e){this.res=e;this.headr=new I,this.req=e.req,this.url=this.req.url}}import{isAbsolute as Ve,relative as Ye,resolve as Qe,sep as Xe}from"path";import{realpath as Ze}from"fs/promises";var N=new Map,et=1000;function Bt(e){if(N.size<et)return;for(let[t,r]of N)if(r.expiresAt<=e)N.delete(t);while(N.size>=et){let t=N.keys().next().value;if(t===void 0)break;N.delete(t)}}var tt=new Set([".js",".css",".html",".htm",".css",".js",".mjs",".cjs",".jsx",".tsx",".xml",".xhtml",".jpg",".jpeg",".png",".gif",".webp",".avif",".bmp",".tiff",".svg",".txt",".ico",".woff",".woff2",".json"]);function rt(e){let t=e.trim().toLowerCase();if(!t)return"";return t.startsWith(".")?t:`.${t}`}function ee(e,t=new Set){let r=e.slice(e.lastIndexOf("/")+1).toLowerCase();return[...tt,...t].map(rt).filter(Boolean).some((s)=>r.endsWith(s))}class te{absoluteClientPath;additionalExtensions;SMALL_FILE_THRESHOLD=51200;CACHE_TTL=900000;constructor(e,t=[]){this.absoluteClientPath=Qe(e),this.additionalExtensions=new Set(t.map(rt).filter(Boolean))}isFile(e){return ee(e,this.additionalExtensions)}async serve(e,t,r){let n;if(r===void 0)try{n=decodeURIComponent(e.url.pathname)}catch{return t.error(400,"Bad Request")}else n=r;if(n.includes("\x00"))return t.error(400,"Bad Request");let s=Qe(this.absoluteClientPath,`.${n}`),i=Ye(this.absoluteClientPath,s);if(i===".."||i.startsWith(`..${Xe}`)||Ve(i))return t.error(403,"Forbidden");let a,o;try{[a,o]=await Promise.all([Ze(this.absoluteClientPath),Ze(s)])}catch{return t.null(404)}let c=Ye(a,o);if(c===".."||c.startsWith(`..${Xe}`)||Ve(c))return t.error(403,"Forbidden");let l=Date.now(),u=N.get(o);if(u&&l>u.expiresAt)N.delete(o),u=void 0;if(!u){let f=Bun.file(o);if(!await f.exists())return t.null(404);if(f.size<=this.SMALL_FILE_THRESHOLD){let h=await f.arrayBuffer(),R=new Uint8Array(h),x=`W/"${Bun.hash(R).toString(16)}"`;u={buffer:R,contentType:f.type||"application/octet-stream",etag:x,expiresAt:l+this.CACHE_TTL},Bt(l),N.set(o,u)}}if(u){let f=e.headers.get("If-None-Match"),h={ETag:u.etag,"Cache-Control":`public, max-age=${this.CACHE_TTL/1000}, must-revalidate`};if(f===u.etag)return new Response(null,{status:304,headers:h});return t.file(u.buffer,{type:u.contentType,size:u.buffer.length},h)}let m=Bun.file(o);if(await m.exists())return t.file(m);return t.null(404)}}class j{request;server;fileDetector;params={};_url;_query;_cookies;_formData;_json;_txt;constructor(e,t,r=ee){this.request=e;this.server=t;this.fileDetector=r}async text(){if(this._txt!==void 0)return this._txt;try{return this._txt=await this.request.text(),this._txt}catch{return this._txt=""}}async json(){if(this._json!==void 0)return this._json;try{let e=await this.text();return this._json=e?JSON.parse(e):{},this._json}catch{return this._json={}}}async form(){if(!this.isForm)return new FormData;if(this._formData!==void 0)return this._formData;try{return this._formData=await this.request.formData(),this._formData}catch{return this._formData=new FormData}}get url(){return this._url??=new URL(this.request.url)}get query(){if(this._query)return this._query;return this._query=Object.fromEntries(this.url.searchParams.entries()),this._query}get cookies(){if(!this._cookies){let e=this.request.headers.get("cookie");if(this._cookies=new Map,e)e.split(";").forEach((t)=>{let[r,...n]=t.trim().split("=");this._cookies.set(r,n.join("="))})}return this._cookies}get auth(){let e=this.request.headers.get("authorization");if(!e?.startsWith("Bearer "))return;return e.substring(7)}get method(){return this.request.method.toUpperCase()}get headers(){return this.request.headers}header(e){return this.request.headers.get(e)}get ip(){return this.server?.requestIP(this.request)??null}get path(){return this.url.pathname}get isForm(){let e=this.request.headers.get("content-type");return!!e&&(e.includes("multipart/form-data")||e.includes("application/x-www-form-urlencoded"))}get isWSS(){return this.request.headers.get("upgrade")?.toLowerCase()==="websocket"}get isEventStream(){if(this.request.method.toUpperCase()!=="GET")return!1;return(this.request.headers.get("accept")??"").split(",").some((e)=>{let[t,...r]=e.trim().split(";");if(t?.trim().toLowerCase()!=="text/event-stream")return!1;for(let n of r){let s=n.trim().match(/^q\s*=\s*(0(?:\.\d+)?|1(?:\.0+)?)$/i);if(s&&Number(s[1])===0)return!1}return!0})}get isFile(){return this.fileDetector(this.path)}async getAuthCredentials(){let e=this.isForm?await this.form():null;return{sid:this.cookies.get("session")??"",jwt:this.auth??"",refresh:e?.get("refresh_token")?.toString()??""}}upgrade(e={}){return this.server?.upgrade(this.request,{data:e})??!1}}var Kt={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",415:"Unsupported Media Type",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",503:"Service Unavailable"};function d(e,t){let r=e.code??400,n={"Access-Control-Allow-Origin":"*",...e.headers||{}};if(e.redirect)return n.Location=e.redirect,new Response(null,{status:302,headers:n});n["Content-Type"]="application/json; charset=utf-8";let s=e.message??Kt[r]??"An unexpected error occurred",i=JSON.stringify({success:!1,error:s,...t!==void 0&&{details:t}});return new Response(i,{status:r,headers:n})}var{gzipSync:zt,deflateSync:Gt,zstdCompressSync:Jt}=globalThis.Bun;import{brotliCompressSync as Vt}from"zlib";var Yt=["br","gzip","deflate","zstd"];class U{static negotiate(e,t){if(!e||e==="none"||!t)return;let r=new Map;for(let i of t.split(",")){let[a,...o]=i.trim().toLowerCase().split(";");if(!a)continue;let c=1;for(let l of o){let u=l.trim().match(/^q\s*=\s*(0(?:\.\d+)?|1(?:\.0+)?)$/);if(u)c=Number(u[1])}r.set(a,c)}let n=r.get("*"),s=Yt.map((i,a)=>({encoding:i,order:a,q:r.get(i)??n??0})).filter((i)=>i.q>0);if(s.sort((i,a)=>a.q-i.q||i.order-a.order),r.get(e)===0)return s.find((i)=>i.encoding!==e)?.encoding;return s.find((i)=>i.encoding===e)?.encoding??s[0]?.encoding}static handle(e,t){if(!t||t==="none")return{payload:e};try{let r=e;switch(t){case"gzip":return{payload:zt(r),encoding:"gzip"};case"deflate":return{payload:Gt(r),encoding:"deflate"};case"br":return{payload:Vt(r),encoding:"br"};case"zstd":return{payload:Jt(r),encoding:"zstd"};default:return{payload:e}}}catch(r){return console.error(`[Compressor] Failed to compress using ${t}:`,r),{payload:e}}}static toUint8(e){if(e===null||e===void 0)return new Uint8Array;if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);let t=typeof e==="string"?e:JSON.stringify(e);return new TextEncoder().encode(t)}}class re{static data(e){return`data: ${typeof e==="object"?JSON.stringify(e):String(e)}
3
+
4
+ `}static event(e){return`event: ${e}
5
+ `}static id(e){return`id: ${e}
6
+ `}static retry(e){return`retry: ${e}
7
+ `}}class Re{intervalIDs=[];async push(e,t,r=2000){let n,s=Math.max(r,1000),i=setInterval(()=>{try{let{id:a,retry:o,data:c,event:l,end:u,fn:m}=t(n);if(u){this.close();try{e.close()}catch(f){}return}if(o)e.enqueue(re.retry(Math.max(o,2000)));if(a)e.enqueue(re.id(a));if(l)e.enqueue(re.event(l));if(e.enqueue(re.data(c)),m)n=m()}catch(a){console.error("[eStream Error] Interval iteration failed:",a),this.close();try{e.error(a)}catch(o){}}},s);this.intervalIDs.push(i)}close(){while(this.intervalIDs.length>0){let e=this.intervalIDs.pop();if(e)clearInterval(e)}}}var Qt=(e)=>typeof e==="string";var Xt=(e)=>Array.isArray(e);var Zt=(e)=>st(e)&&typeof e==="object",er=(e)=>st(e)&&Zt(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null);var nt=(e)=>er(e);var st=(e)=>e!==null;var H=(e)=>Xt(e)?e:[e];function xe(e=3){let t=((Error().stack?.split(`
8
+ `)??[])[e]||"").match(/at\s+([^(]+)\s*\(/);return(t?t[1].split(".").pop()?.trim():"?")??"?"}class it{name;constructor(e){this.name=e}log=(...e)=>{let t=xe(3);console.log(`[${this.name}.${t}]`,...e)};set i(e){let t=xe(3);console.log(`[${this.name}.${t}]`,...H(e))}}class Ce{static logger=(e)=>new it(Qt(e)?e:e.constructor.name);static set f(e){let t=xe();console.log(`[${t}]`,...H(e))}static set i(e){console.info(...H(e))}static set e(e){console.error(...H(e))}static set w(e){console.warn(...H(e))}static set d(e){let t=new Date().toLocaleTimeString();console.log(...H(e),`@ ${t}`)}static get d(){let e=new Date().toLocaleTimeString();console.log(`@ ${e}`);return}}class y{key;target;propertyKey;constructor(e,t,r){this.key=e,this.target=t,this.propertyKey=r}getReflect(){return this.propertyKey!==void 0?Reflect.getMetadata(this.key,this.target,this.propertyKey):Reflect.getMetadata(this.key,this.target)}setReflect(e){if(this.propertyKey!==void 0)Reflect.defineMetadata(this.key,e,this.target,this.propertyKey);else Reflect.defineMetadata(this.key,e,this.target)}static get get(){let e=(t,r,n)=>new this(`${r}:${t}`,n).get();return{class(t,r){return e("class",t,r)},method(t,r){return e("method",t,r)}}}get(){let e=this.getReflect();return Array.isArray(e)?e:[]}set(e){return this.setReflect(e),this}push(e){let t=this.get();return t.push(e),this.set(t)}unshift(e){let t=this.get();return t.unshift(e),this.set(t)}static getContextKey(e,t){return typeof e==="symbol"?Symbol.for(`${e.description}:${t}`):`${e}:${t}`}static decorate(e,t,r){return function(n,s){if(!s)return r;let i=s.kind??"class";if(t!=="all"&&!t.includes(i))throw Error(`Invalid decorator usage. Expected ${t.join(" or ")}, but applied to a ${i}.`);let a=y.getContextKey(e,i),o=r(s);if(i==="class"||i==="method"||i==="getter"||i==="setter")new y(a,n).push(o);else s.addInitializer(function(){new y(a,this,s.name).push(o)});return n}}static decorateClass(e,t){return this.decorate(e,["class"],t)}static decorateArray(e,t,r){return function(n,s){if(!r.length)return n;let i=s.kind??"class";if(t!=="all"&&!t.includes(i))throw Error(`Invalid decorator usage. Expected ${t.join(" or ")}, but applied to a ${i}.`);let a=y.getContextKey(e,i);if(i==="class"||i==="method"||i==="getter"||i==="setter")for(let o of r)new y(a,n).push(o);else s.addInitializer(function(){for(let o of r)new y(a,this,s.name).push(o)});return n}}}class W{req;staticServer;server;_code=200;_headers={};_encoding;constructor(e={},t,r,n){this.req=t;this.staticServer=r;this.server=n;if(e.encoding)this.encode(U.negotiate(e.encoding,t.headers.get("accept-encoding"))??"none")}status(e){return this._code=e,this}encode(e){if(this._encoding=e,e&&e!=="none")this._headers["Content-Encoding"]=e;else delete this._headers["Content-Encoding"];return this}header(e){let t=e instanceof I?e.done:e;for(let[r,n]of Object.entries(t))if(r.toLowerCase()==="vary"&&this._headers.Vary){let s=this._headers.Vary;if(s.trim()==="*")continue;let i=s.split(",").map((a)=>a.trim());for(let a of n.split(",").map((o)=>o.trim()))if(!i.some((o)=>o.toLowerCase()===a.toLowerCase()))i.push(a);this._headers.Vary=i.join(", ")}else this._headers[r]=n;return this}_assemble(e,t){let r=U.toUint8(e),{payload:n,encoding:s}=U.handle(r,this._encoding);if(s)this._headers["Content-Encoding"]=s;let i=(t.startsWith("text/")||t==="application/json")&&!t.includes("charset=");return new Response(n,{status:this._code,headers:{"Content-Type":i?`${t}; charset=utf-8`:t,"Content-Length":n.length.toString(),...this._headers}})}null(e=this._code){return new Response(null,{status:e,headers:this._headers})}json(e){return this._assemble(e,"application/json")}html(e){return this._assemble(e,"text/html")}text(e=""){return this._assemble(e,"text/plain")}error(e,t){this._code=e;let r="",n="text/plain";if(nt(t))r=JSON.stringify(t),n="application/json";else r=String(t);return this._assemble(r,n)}success(e=200,t,r){return this._code=e,this.json({success:!0,...r&&{message:r},...t!==void 0&&{data:t}})}redirect(e,t=302){return new Response(null,{status:t,headers:{Location:e,...this._headers}})}async fileServer(){return this.staticServer.serve(this.req,this)}async file(e,t,r){if(r)this.header(r);let n="slice"in e&&"type"in e;if(n&&!await e.exists())return this.error(404,"File Not Found");let s=n?e.size:t?.size??0,a={"Content-Type":n?e.type:t?.type??"application/octet-stream","Accept-Ranges":n?"bytes":"none",...this._headers},o=n?this.req.headers.get("range"):null;if(!o){let R=e,x={...a};if(this._encoding&&this._encoding!=="none")try{let q=n?new Uint8Array(await e.arrayBuffer()):e,{payload:Ge,encoding:Je}=U.handle(q,this._encoding);if(R=Ge,Je)x["Content-Encoding"]=Je;x["Content-Length"]=Ge.length.toString()}catch(q){return this.error(500,"Error reading file")}else x["Content-Length"]=s.toString();return new Response(R,{status:this._code,headers:x})}let c=()=>new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`,...this._headers}}),l=/^bytes=(\d*)-(\d*)$/.exec(o.trim());if(!l)return c();let u=l[1]??"",m=l[2]??"",f,h;if(u===""){let R=Number(m);if(!Number.isSafeInteger(R)||R<=0)return c();f=Math.max(s-R,0),h=s-1}else f=Number(u),h=m===""?s-1:Number(m);if(!Number.isSafeInteger(f)||!Number.isSafeInteger(h)||f<0||f>h||f>=s)return c();return h=Math.min(h,s-1),new Response(e.slice(f,h+1),{status:206,headers:{...a,"Content-Range":`bytes ${f}-${h}/${s}`,"Content-Length":(h-f+1).toString()}})}get event(){let e=()=>{this.server?.timeout(this.req.request,0)};return{asyncStream:(t)=>{if(!this.server)return this.null(500);e();let r=t(),n=new ReadableStream({async start(s){try{for await(let i of r){let a=typeof i==="object"?JSON.stringify(i):String(i);s.enqueue(Buffer.from(`data: ${a}
9
+
10
+ `))}s.close()}catch(i){s.error(i)}},cancel(){r.return?.()}});return new Response(n,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...this._headers}})},eStream:(t,{interval:r=2000,onCancel:n}={})=>{if(!this.server)return this.null(500);e();let s=new Re,i=new ReadableStream({async start(a){await s.push(a,t,r)},cancel(){s.close(),n?.()}});return new Response(i,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...this._headers}})},readableStream:(t,r)=>{if(!this.server)return this.null(500);e();let n=new ReadableStream({async start(s){await t(s)},cancel(){r?.()}});return new Response(n,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...this._headers}})}}}}var at=["GET","POST","PUT","HEAD","DELETE","PATCH","EVENT","OPTIONS"];class Oe{options({res:e,methods:t}){let r=[...new Set([...t])];return e.header({Allow:r.join(", ")}).null(204)}}var B="rossa:route";function Ae(e="/"){return y.decorateClass(B,()=>({basePath:e}))}function ot(e="/"){return y.decorateClass(B,()=>({basePath:e,wss:!0}))}import"reflect-metadata";var K="rossa:guard";function tr(...e){return y.decorateArray(K,["class","method"],e)}function ct(e,t){let r=y.get.method(K,t),n=[],s=new Map;for(let i of r)if(i._middlewareId)s.set(i._middlewareId,i);for(let i of e)if(i._middlewareId&&s.has(i._middlewareId))n.push(s.get(i._middlewareId)),s.delete(i._middlewareId);else n.push(i);for(let i of r)if(!i._middlewareId||s.has(i._middlewareId)){if(n.push(i),i._middlewareId)s.delete(i._middlewareId)}return n}class ne{globalBasePath;httpRoutes=[];wssRoutes=[];globalGuards=[];registeredSignatures=new Set;programmaticRoutes=new Set;constructor(e=""){if(this.globalBasePath=e.startsWith("/")?e:`/${e}`,this.globalBasePath==="/")this.globalBasePath=""}use(...e){for(let t of e)this.globalGuards.unshift(t)}fullRoutePath(e){return`${this.globalBasePath}${e}`.replace(/\/+/g,"/").replace(/\/$/,"")||"/"}compiler(e){let t=[],r=e.replace(/[.*+?^${}()|[\]\\]|:([a-zA-Z0-9_]+)/g,(n,s)=>{if(s)return t.push(s),"([^/]+)";return`\\${n}`});return{regex:new RegExp(`^${r}\\/?$`),paramNames:t}}checkSignature(e,t,r="http"){let n=`${r}:${e}`;if(this.registeredSignatures.has(n))throw Error(`[Router Error] Duplicate ${r} route collision detected: ${e} in controller ${t}`);this.registeredSignatures.add(n)}registerWSS(...e){for(let t of e){let r=y.get.class(B,t),n=y.get.class(K,t);if(!r.length)continue;for(let s of r){let i=s.basePath??"/",a=this.fullRoutePath(i);this.checkSignature(a,t.name,"wss");let{regex:o,paramNames:c}=this.compiler(a);this.wssRoutes.push({path:a,regex:o,paramNames:c,instance:t,guards:n})}}}register(...e){for(let t of e){let r=y.get.class(B,t);if(!r.length)continue;let n={};for(let c of r){let l=c.basePath??"/",u=this.fullRoutePath(l);this.checkSignature(u,t.name);let{regex:m,paramNames:f}=this.compiler(u);n[u]={regex:m,paramNames:f,controller:t}}let s=new t,i=y.get.class(K,t),a=new Set,o={};for(let c of at){let l=s[c.toLowerCase()];if(typeof l!=="function")continue;if(o[c]={guards:ct(i,l),handler:l.bind(s)},c!=="EVENT")a.add(c)}for(let[c,l]of Object.entries(n))this.httpRoutes.push({path:c,...l,methods:o,methodKeys:[...a]})}}registerHandlerRoute(e,t,r={}){let n=this.fullRoutePath(e),s=this.httpRoutes.findIndex((c)=>c.path===n);if(s!==-1){if(!r.replace||!this.programmaticRoutes.has(n))throw Error(`[Router Error] Route collision detected: ${n} is already registered as an HTTP route.`);this.httpRoutes.splice(s,1),this.registeredSignatures.delete(`http:${n}`),this.programmaticRoutes.delete(n)}this.checkSignature(n,"programmatic route");let{regex:i,paramNames:a}=this.compiler(n),o={};for(let[c,l]of Object.entries(t)){if(!l)continue;o[c]={guards:[],handler:l}}this.httpRoutes.push({path:n,regex:i,paramNames:a,controller:ut,methods:o,methodKeys:Object.keys(o)}),this.programmaticRoutes.add(n)}matchWSS(e){let t=e.split("?")[0]??e;for(let r of this.wssRoutes){let n=t.match(r.regex);if(!n)continue;let s={};r.paramNames.forEach((i,a)=>{s[i]=n[a+1]??""});try{return{...r,params:s}}catch(i){return console.error(`WSS Route Execution Error [${r.instance.name}]:`,i),{params:s}}}return{params:{}}}match(e,t){let r=t.split("?")[0]??t;for(let n of this.httpRoutes){let s=r.match(n.regex);if(!s)continue;let i=n.methods[e];if(!i)continue;let a={};n.paramNames.forEach((o,c)=>{a[o]=s[c+1]??""});try{return{...i,methodKeys:n.methodKeys,controller:n.controller,params:a}}catch(o){return console.error(`Route Execution Error [${n.controller.name}]:`,o),{params:a}}}return{params:{}}}printRoutes(){console.log("--- Registered HTTP Routes ---"),console.table(this.httpRoutes.map((e)=>({Methods:e.methodKeys.join(", "),Path:e.path,Type:"HTTP"}))),console.log(`
11
+ --- Registered WSS Routes ---`),console.table(this.wssRoutes.map((e)=>({Path:e.path,Controller:e.instance.constructor.name})))}getPaths(){return this.httpRoutes.map(({path:e})=>e.replace(/:([a-zA-Z0-9_]+)/g,"$1"))}}class ut{}import{dirname as cr,isAbsolute as dt,join as mt}from"path";class ce{ws;id;constructor(e,t){this.ws=e;this.id=C.register(e,t)}subscribe(e){C.subscribe(this.id,e)}unsubscribe(e){C.unsubscribe(this.id,e)}cleanup(){C.cleanup(this.id)}unregister(){C.unregister(this.id)}setAdmin(e){C.setAdmin(this.id,e)}isAdmin(e){return C.isAdmin(this.id,e)}isSubscribed(e){return C.isSubscribed(this.id,e)}setTopicConfig(e,t={}){C.setTopicConfig(e,t)}broadcast(e,t){return C.broadcastToTopics(this.ws,e,t)}}class ue{connections=new Map;topicConfigs=new Map;topicRegistry=new Map;memberTopics=new Map;roomAdmins=new Map;defaultTopicConfig={maxClients:1/0,maxPayloadSize:65536};register(e,t){let r=crypto.randomUUID();return e.data={...e.data,id:r,nickname:t},this.connections.set(r,e),r}getMemberDetails(e){let t=this.topicRegistry.get(e)||new Set,r=[];for(let n of t){let s=this.connections.get(n);if(s)r.push({id:n,userId:s.data.contextData?.chatUser?.id,nickname:s.data.nickname})}return r}getUserTopics(e){return Array.from(this.memberTopics.get(e)||[])}get(e){return this.getMemberDetails(e)}unregister(e){this.cleanup(e)}subscribe(e,t){let r=this.connections.get(e);if(!r)throw Error("Connection not found");if(this.isSubscribed(e,t))return;let n=this.getConfigForTopic(t),s=this.topicRegistry.get(t)??new Set;if(s.size>=(n.maxClients??1/0))throw Error("Topic capacity reached");if(!r.subscribe(t))throw Error("WebSocket is closed");if(this.topicRegistry.set(t,s),s.add(e),!this.memberTopics.has(e))this.memberTopics.set(e,new Set);this.memberTopics.get(e).add(t)}isSubscribed(e,t){return this.memberTopics.get(e)?.has(t)??!1}unsubscribe(e,t){let r=this.connections.get(e);if(r)r.unsubscribe(t);let n=this.topicRegistry.get(t);if(n){if(n.delete(e),n.size===0)this.topicRegistry.delete(t),this.roomAdmins.delete(t)}let s=this.roomAdmins.get(t);if(s?.delete(e),s?.size===0)this.roomAdmins.delete(t);if(this.topicRegistry.get(t)?.delete(e),this.topicRegistry.get(t)?.size===0)this.topicRegistry.delete(t);if(this.memberTopics.get(e)?.delete(t),this.memberTopics.get(e)?.size===0)this.memberTopics.delete(e)}setAdmin(e,t){if(!this.roomAdmins.has(t))this.roomAdmins.set(t,new Set);this.roomAdmins.get(t).add(e)}isAdmin(e,t){return this.roomAdmins.get(t)?.has(e)??!1}isPayloadTooLarge(e,t){let r=this.getConfigForTopic(e);return t>(r.maxPayloadSize??65536)}getConfigForTopic(e){if(this.topicConfigs.has(e))return this.topicConfigs.get(e);return this.defaultTopicConfig}setTopicConfig(e,t={}){this.topicConfigs.set(e,t)}broadcastToTopics(e,t,r){let n=typeof r==="string"?r:JSON.stringify(r);if(n===void 0)return[];let s=new TextEncoder().encode(n).byteLength,i=[];for(let a of new Set(t)){if(this.isPayloadTooLarge(a,s)){i.push({topic:a,status:"oversize"});continue}let o=e.publish(a,n);i.push({topic:a,status:o===0?"dropped":o===-1?"backpressured":"sent"})}return i}cleanup(e){let t=this.getUserTopics(e);for(let r of t)this.unsubscribe(e,r);for(let[r,n]of this.roomAdmins)if(n.delete(e),n.size===0)this.roomAdmins.delete(r);this.connections.delete(e)}}var C=new ue;function ve(e){if(e&&(!Number.isSafeInteger(e.max)||e.max<1||!Number.isFinite(e.windowMs)||e.windowMs<=0))throw RangeError("Invalid WebSocket message rate limit");let t=new WeakMap,r=(n)=>{if(!e)return!0;let s=Date.now(),i=t.get(n);if(!i||s>=i.resetAt)return t.set(n,{count:1,resetAt:s+e.windowMs}),!0;if(i.count>=e.max)return!1;return i.count+=1,!0};return{open:async(n)=>{let{instance:s,contextData:i}=n.data;s.ws=n,s.contextData=i??{},s.manager=new ce(n,s.contextData.chatUser?.nickname),await s.open()},message:async(n,s)=>{if(!r(n)){n.close(1008,"Message rate limit exceeded");return}let{instance:i}=n.data;await i.message(rr(s))},drain:async(n)=>{let{instance:s}=n.data;await s.drain()},close:async(n,s,i)=>{let{instance:a}=n.data;try{await a.close(s,i)}finally{a.manager.cleanup()}}}}var ys=ve();function rr(e){let t=typeof e==="string"?e:e.toString(),r={},n=void 0;try{let{topic:s,...i}=JSON.parse(t);r=i,n=typeof s==="string"&&s.length>0?s:void 0,t=""}catch{}return{text:t,json:r,topic:n}}var Ne="rossa:mcp";function Me(e){return y.get.class(Ne,e).at(-1)}function lt(e="/",t={}){return y.decorateClass(Ne,()=>({path:e,options:{...t}}))}class se{}import{createMcpHandler as nr,originValidationResponse as sr,McpServer as ir}from"@modelcontextprotocol/server";function _e(e){return async()=>{let t=new ir({name:e.constructor.name||"McpController",version:"0.0.0"});return await e.build(t),t}}function ar(e){let t={origins:new Set,hostnames:[]};for(let r of Array.isArray(e)?e:[e]){let n=r.trim();if(!n)continue;if(/^[a-z][a-z0-9+.-]*:\/\/\*$/i.test(n)){t.hostnames.push(n);continue}try{t.origins.add(new URL(n).origin)}catch{t.hostnames.push(n)}}return t}function or(e,t){let r=e.headers.get("origin");if(!r)return;try{if(t.origins.has(new URL(r).origin))return}catch{}return sr(e,t.hostnames)}function De(e,t={}){let r=nr(e),n=t.origin===void 0?void 0:ar(t.origin);return async(s)=>{if(n){let i=or(s.req.request,n);if(i)return i}return r.fetch(s.req.request)}}function ur(e){if(e instanceof Response)return e;return console.error("[rossa] Guard factory not invoked? Expected a Response but got:",e),new Response("Internal Server Error: guard factory not invoked",{status:500})}class ft extends ne{options;clientRoot;constructor(e={}){super(e.basePath||"");this.options={basePath:e.basePath||"",clientPath:e.clientPath||"./public",dirPath:e.dirPath||"./src",logError:Boolean(e.logError),Encoding:e.Encoding||"br"},this.clientRoot=this.getClientRoot,this.fileServer=new te(this.clientRoot,e.fileExtensions||[])}registerMCP(e,t={},r={}){if(typeof e==="string"){let l=t;if(typeof l!=="function")throw TypeError("[MCP Error] registerMCP(path, factory) requires an McpServerFactory function.");this.mountMcp(e,l,r);return}let n=e instanceof se,s=n?e.constructor:e,i=Me(s);if(!i)throw Error(`[MCP Error] ${s.name||"Controller"} is missing the @mcp decorator. Decorate it with @mcp("/path") or register it with an explicit path and factory.`);let a=n?e:new e,o=t,c={...i.options,...o.origin!==void 0?{origin:o.origin}:{}};this.mountMcp(i.path,_e(a),c)}mountMcp(e,t,r){let n=De(t,r);this.registerHandlerRoute(e,{POST:n,GET:n,DELETE:n,EVENT:n},{replace:!0})}get getClientRoot(){let e;if(dt(this.options.clientPath))e=this.options.clientPath;else{let t=dt(this.options.dirPath)?this.options.dirPath:mt(process.cwd(),this.options.dirPath),r=cr(t);e=mt(r,this.options.clientPath)}return e}async pipeline(e){let t=0,r=async()=>{if(t>=this.globalGuards.length)return await this.processRouter(e);let n=this.globalGuards[t++];return await n(e,r)};try{return ur(await r())}catch(n){return this.errorHandler(e.res,n)}}async processRouter(e){let t=e.req.url,r=e.req.method,n=t.pathname;if(n.endsWith("/")&&n.length>1)n=n.slice(0,-1);if(e.req.isWSS)return this.processWSS(e,n);let s=e.req.isEventStream?"EVENT":r,{guards:i=[],handler:a,params:o,methodKeys:c=[],controller:l}=this.match(s,n);if(!a)return e.res.null(404);e.params=o,e.method=s,e.methods=c;let u=0,m=async()=>{if(u>=i.length)return await a(e);let f=i[u++];return await f(e,m)};return await m()}async processWSS(e,t){let{instance:r,guards:n=[],params:s={}}=this.matchWSS(t)||{};if(!r)return e.res.error(404,"WebSocket Route Not Found.");e.params=s;let i=0,a=async()=>{if(i>=n.length){let c=new r;if(e.req.server?.upgrade(e.req.request,{data:{instance:c,contextData:e.data}}))return e.res.null(200);return e.res.error(500,"WebSocket Upgrade Failed")}let o=n[i++];return await o(e,a)};return await a()}async test(e,t){let r=new F(new W({encoding:t??this.options.Encoding},new j(e,void 0,this.fileServer.isFile.bind(this.fileServer)),this.fileServer));return r.clientDirectory=this.clientRoot,await this.pipeline(r)}serve(e={},t={}){let{fn:r,port:n,...s}=e,{messageRateLimit:i,...a}=t,o=r,c=n??3000,l=Bun.serve({...s,port:c,fetch:async(u,m)=>{let f=new F(new W({encoding:this.options.Encoding},new j(u,m,this.fileServer.isFile.bind(this.fileServer)),this.fileServer,m));f.clientDirectory=this.clientRoot;try{return await this.pipeline(f)}catch(h){return f.res.error(500,h.message||"Internal Server Error")}},websocket:{...a,...ve(i)}});if(o)o(c);else{let u=s.tls?"https":"http";Ce.i=`${u}://localhost:${l.port??c}`}return l}errorHandler(e,t){if(this.options.logError)console.error(t.message);return e.null(500)}}import{McpServer as ec}from"@modelcontextprotocol/server";class O{type;precision;scale;primaryKey=!1;required=!1;isUnique=!1;hasDefault=!1;defaultIsCurrentTimestamp=!1;defaultValue=null;constructor(e,t,r){this.type=e;this.precision=t;this.scale=r;if(e==="numeric"){let n=t??10,s=r??2;if(!Number.isInteger(n)||!Number.isInteger(s)||n<1||n>1000||s<0||s>n)throw RangeError("Numeric precision and scale must satisfy 1 <= p <= 1000 and 0 <= s <= p.")}}get primary(){return this.primaryKey=!0,this}get notNull(){return this.required=!0,this}get unique(){return this.isUnique=!0,this}get defaultNow(){return this.hasDefault=!0,this.defaultIsCurrentTimestamp=!0,this.defaultValue=null,this}default(e){if(typeof e==="number"&&!Number.isFinite(e))throw RangeError("Numeric SQL defaults must be finite.");return this.hasDefault=!0,this.defaultIsCurrentTimestamp=!1,this.defaultValue=e,this}}var lr={text:()=>new O("text"),int:()=>new O("integer"),bigint:()=>new O("bigint"),boolean:()=>new O("boolean"),json:()=>new O("json"),timestamp:()=>new O("timestamp"),serial:()=>new O("serial"),numeric:(e=10,t=2)=>new O("numeric",e,t)};class M extends Error{constructor(e){super(e);this.name="DatabaseError"}}class le extends M{constructor(e){super(e);this.name="UniqueConstraintError"}}class de extends M{constructor(e="Cannot modify a record referenced by another table."){super(e);this.name="ForeignKeyError"}}var{sql:_}=globalThis.Bun;function g(e){if(!e||e.includes("\x00"))throw Error("SQL identifiers must be non-empty and cannot contain NUL.");return`"${e.replace(/"/g,'""')}"`}function E(e){let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be `table` or `schema.table`.");return t.map(g).join(".")}function T(e){let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be `table` or `schema.table`.");return t.length===2?[t[0],t[1]]:[void 0,t[0]]}function $e(e){return _.unsafe(E(e.table))}function pt(e){if(!e.hasDefault)return"";if(e.defaultIsCurrentTimestamp)return" DEFAULT CURRENT_TIMESTAMP";if(typeof e.defaultValue==="string")return` DEFAULT '${e.defaultValue.replace(/'/g,"''")}'`;return` DEFAULT ${e.defaultValue}`}function ht(e){switch(e.type){case"text":return"TEXT";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"boolean":return"BOOLEAN";case"json":return"JSONB";case"timestamp":return"TIMESTAMPTZ";case"serial":return"SERIAL";case"numeric":return`NUMERIC(${e.precision??10}, ${e.scale??2})`}}function dr(e,t){return[g(e),ht(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",pt(t).trim()].filter(Boolean).join(" ")}async function mr(e,t){let[r,n]=T(t.table);return(r?await e`
12
+ SELECT column_name FROM information_schema.columns
13
+ WHERE table_schema = ${r} AND table_name = ${n}
14
+ `:await e`
15
+ SELECT column_name FROM information_schema.columns
16
+ WHERE table_schema = current_schema() AND table_name = ${n}
17
+ `).map((i)=>i.column_name)}var Ie={name:"postgres",quoteIdentifier:g,quoteTable:E,normalizeColumnName(e){return e},buildColumn:dr,buildColumnType(e){return[ht(e),e.primaryKey?"PRIMARY KEY":"",e.required?"NOT NULL":"",e.isUnique?"UNIQUE":"",pt(e).trim()].filter(Boolean).join(" ")},normalizeOperator(e){return e.toUpperCase()},async version(e){let[t]=await e`SELECT version() AS version`;if(!t?.version)throw Error("PostgreSQL did not return its version.");return t.version},async createTable(e,t){await e`${_.unsafe(t.createSQL(this))}`},getColumns:mr,async addColumn(e,t,r,n){await e`${_.unsafe(`ALTER TABLE ${E(t.table)} ADD COLUMN ${g(r)} ${n}`)}`},async dropColumn(e,t,r){await e`${_.unsafe(`ALTER TABLE ${E(t.table)} DROP COLUMN ${g(r)}`)}`},async upsert(e,t,r,n){if(Object.keys(r).length===0)throw Error("Upsert requires at least one column value.");let[s]=await e`
18
+ INSERT INTO ${$e(t)} ${_(r)}
19
+ ON CONFLICT (${_.unsafe(g(String(n)))})
20
+ DO UPDATE SET ${_(r)}
21
+ RETURNING *
22
+ `;return s},async listTables(e){return(await e`
23
+ SELECT tablename FROM pg_catalog.pg_tables
24
+ WHERE schemaname = current_schema()
25
+ `).map((r)=>r.tablename)},async dropTable(e,t){await e`${_.unsafe(`DROP TABLE ${E(t.table)}`)}`},async truncateTable(e,t){await e`${_.unsafe(`TRUNCATE TABLE ${E(t.table)} RESTART IDENTITY`)}`},async getTableStats(e,t){let[r,n]=T(t.table),[s]=await e`
26
+ SELECT COUNT(*) AS total FROM ${$e(t)}
27
+ `,i=E(t.table),[a]=await e`
28
+ SELECT
29
+ pg_size_pretty(pg_total_relation_size(${i}::regclass)) AS size,
30
+ (SELECT COUNT(*) FROM pg_indexes
31
+ WHERE schemaname = COALESCE(${r??null}, current_schema())
32
+ AND tablename = ${n}) AS index_count
33
+ `;return{rowCount:Number(s?.total??0),diskSize:a?.size??"unknown",indexCount:Number(a?.index_count??0)}},async getTableIndices(e,t){let[r,n]=T(t.table);return r?e`
34
+ SELECT indexname, indexdef FROM pg_indexes
35
+ WHERE schemaname = ${r} AND tablename = ${n}
36
+ `:e`
37
+ SELECT indexname, indexdef FROM pg_indexes
38
+ WHERE schemaname = current_schema() AND tablename = ${n}
39
+ `},async getTableSchema(e,t){let[r,n]=T(t.table);return r?e`
40
+ SELECT column_name, data_type, column_default, is_nullable
41
+ FROM information_schema.columns
42
+ WHERE table_schema = ${r} AND table_name = ${n}
43
+ `:e`
44
+ SELECT column_name, data_type, column_default, is_nullable
45
+ FROM information_schema.columns
46
+ WHERE table_schema = current_schema() AND table_name = ${n}
47
+ `},async getTableData(e,t,r,n){return await e`
48
+ SELECT * FROM ${$e(t)}
49
+ LIMIT ${r} OFFSET ${n}
50
+ `},async optimize(e,t){await e.unsafe(`VACUUM ANALYZE ${E(t.table)}`)}};var{sql:S}=globalThis.Bun;function Pe(e){return S.unsafe(E(e.table))}function fr(e){return e.reduce((t,r,n)=>n===0?r:S`${t}, ${r}`)}function gt(e){if(!e.hasDefault)return"";if(e.defaultIsCurrentTimestamp)return" DEFAULT CURRENT_TIMESTAMP";if(typeof e.defaultValue==="string")return` DEFAULT '${e.defaultValue.replace(/'/g,"''")}'`;if(typeof e.defaultValue==="boolean")return` DEFAULT ${e.defaultValue?1:0}`;return` DEFAULT ${e.defaultValue}`}function yt(e){switch(e.type){case"text":case"json":case"timestamp":return"TEXT";case"integer":case"bigint":case"serial":return"INTEGER";case"boolean":return"INTEGER";case"numeric":return"REAL"}}function pr(e,t){return[g(e),yt(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",gt(t).trim()].filter(Boolean).join(" ")}async function hr(e,t){let[r,n]=T(t.table),s=r?`${g(r)}.`:"";return(await e`${S.unsafe(`PRAGMA ${s}table_info(${g(n)})`)}`).map((a)=>a.name)}var ke={name:"sqlite",quoteIdentifier:g,quoteTable:E,normalizeColumnName(e){return e.toLowerCase()},buildColumn:pr,buildColumnType(e){return[yt(e),e.primaryKey?"PRIMARY KEY":"",e.required?"NOT NULL":"",e.isUnique?"UNIQUE":"",gt(e).trim()].filter(Boolean).join(" ")},normalizeOperator(e){return e.toUpperCase()==="ILIKE"?"LIKE":e.toUpperCase()},async version(e){let[t]=await e`SELECT sqlite_version() AS version`;if(!t?.version)throw Error("SQLite did not return its version.");return t.version},async createTable(e,t){await e`${S.unsafe(t.createSQL(this))}`},getColumns:hr,async addColumn(e,t,r,n){if(/\bPRIMARY KEY\b|\bUNIQUE\b/i.test(n))throw Error("SQLite cannot add PRIMARY KEY or UNIQUE constraints with ADD COLUMN; rebuild the table instead.");await e`${S.unsafe(`ALTER TABLE ${E(t.table)} ADD COLUMN ${g(r)} ${n}`)}`},async dropColumn(e,t,r){await e`${S.unsafe(`ALTER TABLE ${E(t.table)} DROP COLUMN ${g(r)}`)}`},async upsert(e,t,r,n){let s=Object.keys(r);if(s.length===0)throw Error("Upsert requires at least one column value.");let i=String(n),a=s.filter((u)=>u!==i),o=a.length?a:[i],c=fr(o.map((u)=>S`${S.unsafe(g(u))} = excluded.${S.unsafe(g(u))}`)),[l]=await e`
51
+ INSERT INTO ${Pe(t)} ${S(r)}
52
+ ON CONFLICT (${S.unsafe(g(i))})
53
+ DO UPDATE SET ${c}
54
+ RETURNING *
55
+ `;return l},async listTables(e){return(await e`
56
+ SELECT name FROM sqlite_schema
57
+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
58
+ `).map((r)=>r.name)},async dropTable(e,t){await e`${S.unsafe(`DROP TABLE ${E(t.table)}`)}`},async truncateTable(e,t){await e.begin(async(r)=>{await r`${S.unsafe(`DELETE FROM ${E(t.table)}`)}`;let[n,s]=T(t.table),i=g(n??"main"),[a]=await r`${S.unsafe(`SELECT name FROM ${i}.sqlite_schema WHERE type = 'table' AND name = 'sqlite_sequence'`)}`;if(a)await r`${S.unsafe(`DELETE FROM ${i}.sqlite_sequence WHERE name = `)}${s}`})},async getTableStats(e,t){let[r,n]=T(t.table),[s]=await e`
59
+ SELECT COUNT(*) AS total FROM ${Pe(t)}
60
+ `,i=r?`${g(r)}.`:"",a=await e`${S.unsafe(`PRAGMA ${i}index_list(${g(n)})`)}`;return{rowCount:Number(s?.total??0),diskSize:"N/A (SQLite file-level)",indexCount:a.length}},async getTableIndices(e,t){let[r,n]=T(t.table),s=r?`${g(r)}.`:"";return e`${S.unsafe(`PRAGMA ${s}index_list(${g(n)})`)}`},async getTableSchema(e,t){let[r,n]=T(t.table),s=r?`${g(r)}.`:"";return e`${S.unsafe(`PRAGMA ${s}table_info(${g(n)})`)}`},async getTableData(e,t,r,n){return await e`
61
+ SELECT * FROM ${Pe(t)}
62
+ LIMIT ${r} OFFSET ${n}
63
+ `},async optimize(e){await e`${S.unsafe("VACUUM")}`}};var{sql:A}=globalThis.Bun;var v=(e)=>{if(!e||e.includes("\x00"))throw Error("SQL identifiers must be non-empty and cannot contain NUL.");return"`"+e.replace(/`/g,"``")+"`"},P=(e)=>{let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be a table name or a schema-qualified table name.");return t.map(v).join(".")},me=(e)=>A.unsafe(P(e.table));function bt(e){switch(e.type){case"text":return"TEXT";case"integer":return"INT";case"bigint":return"BIGINT";case"boolean":return"BOOLEAN";case"json":return"JSON";case"timestamp":return"DATETIME(3)";case"serial":return"BIGINT AUTO_INCREMENT";case"numeric":return`DECIMAL(${e.precision??10}, ${e.scale??2})`}}function St(e){if(!e.hasDefault)return"";if(e.defaultIsCurrentTimestamp)return" DEFAULT CURRENT_TIMESTAMP";if(typeof e.defaultValue==="string")return` DEFAULT '${e.defaultValue.replace(/'/g,"''")}'`;if(typeof e.defaultValue==="boolean")return` DEFAULT ${e.defaultValue?1:0}`;return` DEFAULT ${e.defaultValue}`}function gr(e,t){return[v(e),bt(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",St(t).trim()].filter(Boolean).join(" ")}async function yr(e,t){let[r,n]=T(t.table);return(r?await e`SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = ${r} AND table_name = ${n}`:await e`SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${n}`).map((i)=>i.COLUMN_NAME)}function wt(e){return{name:e,quoteIdentifier:v,quoteTable:P,normalizeColumnName(t){return t.toLowerCase()},buildColumn:gr,buildColumnType(t){return[bt(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",St(t).trim()].filter(Boolean).join(" ")},normalizeOperator(t){return t.toUpperCase()==="ILIKE"?"LIKE":t.toUpperCase()},async version(t){let[r]=await t`SELECT VERSION() AS version`;if(!r?.version)throw Error("MySQL-compatible server did not return its version.");return r.version},async createTable(t,r){await t`${A.unsafe(r.createSQL(this))}`},getColumns:yr,async addColumn(t,r,n,s){await t`${A.unsafe(`ALTER TABLE ${P(r.table)} ADD COLUMN ${v(n)} ${s}`)}`},async dropColumn(t,r,n){await t`${A.unsafe(`ALTER TABLE ${P(r.table)} DROP COLUMN ${v(n)}`)}`},async upsert(t,r,n,s){let i=Object.keys(n);if(!i.length)throw Error("Upsert requires at least one column value.");let a=i.filter((u)=>u!==String(s)),o=a.length?a.map((u)=>`${v(u)} = VALUES(${v(u)})`).join(", "):`${v(String(s))} = VALUES(${v(String(s))})`;await t`INSERT INTO ${me(r)} ${A(n)} ON DUPLICATE KEY UPDATE ${A.unsafe(o)}`;let c=n[s];if(c===void 0)return;let[l]=await t`SELECT * FROM ${me(r)} WHERE ${A.unsafe(v(String(s)))} = ${c} LIMIT 1`;return l},async listTables(t){return(await t`SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'`).map((n)=>n.TABLE_NAME)},async dropTable(t,r){await t`${A.unsafe(`DROP TABLE ${P(r.table)}`)}`},async truncateTable(t,r){await t`${A.unsafe(`TRUNCATE TABLE ${P(r.table)}`)}`},async getTableStats(t,r){let[n,s]=T(r.table),[i]=await t`SELECT COUNT(*) AS total FROM ${me(r)}`,[a]=n?await t`SELECT data_length + index_length AS size, (SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema = ${n} AND table_name = ${s}) AS index_count FROM information_schema.tables WHERE table_schema = ${n} AND table_name = ${s}`:await t`SELECT data_length + index_length AS size, (SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s}) AS index_count FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${s}`;return{rowCount:Number(i?.total??0),diskSize:a?.size==null?"unknown":`${a.size} bytes`,indexCount:Number(a?.index_count??0)}},async getTableIndices(t,r){let[n,s]=T(r.table);return n?t`SELECT * FROM information_schema.statistics WHERE table_schema = ${n} AND table_name = ${s}`:t`SELECT * FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s}`},async getTableSchema(t,r){let[n,s]=T(r.table);return n?t`SELECT column_name, column_type, column_default, is_nullable FROM information_schema.columns WHERE table_schema = ${n} AND table_name = ${s}`:t`SELECT column_name, column_type, column_default, is_nullable FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${s}`},async getTableData(t,r,n,s){return t`SELECT * FROM ${me(r)} LIMIT ${n} OFFSET ${s}`},async optimize(t,r){await t`${A.unsafe(`OPTIMIZE TABLE ${P(r.table)}`)}`}}}var Le=wt("mysql"),qe=wt("mariadb");var br={sqlite:ke,postgres:Ie,mysql:Le,mariadb:qe};function fe(e){let t=br[e];if(!t)throw Error(`Unsupported database dialect: ${e}`);return t}class z{db;schema;constructor(e,t){this.db=e;this.schema=t}listTables(){return this.schema.dialect.listTables(this.db)}dropTable(){return this.schema.dialect.dropTable(this.db,this.schema)}truncateTable(){return this.schema.dialect.truncateTable(this.db,this.schema)}getTableStats(){return this.schema.dialect.getTableStats(this.db,this.schema)}getTableIndices(){return this.schema.dialect.getTableIndices(this.db,this.schema)}getTableSchema(){return this.schema.dialect.getTableSchema(this.db,this.schema)}getTableData(e=50,t=0){if(!Number.isSafeInteger(e)||e<0)throw RangeError("Limit must be a non-negative safe integer.");if(!Number.isSafeInteger(t)||t<0)throw RangeError("Offset must be a non-negative safe integer.");return this.schema.dialect.getTableData(this.db,this.schema,e,t)}optimize(){return this.schema.dialect.optimize(this.db,this.schema)}static sqlite(e,t){return new z(e,t.withDialect(fe("sqlite")))}static postgres(e,t){return new z(e,t.withDialect(fe("postgres")))}}var{sql:b}=globalThis.Bun;var Sr=new Set(["=","!=","<","<=",">",">=","LIKE","ILIKE","IS","IS NOT","IN","NOT IN"]);class Fe{db;schema;constructor(e,t){this.db=e;this.schema=t}get dialect(){return this.schema.dialect}get inspect(){return new z(this.db,this.schema)}withContext(e){return new Fe(e,this.schema)}create(){return this.dialect.createTable(this.db,this.schema)}testConnection(){return this.dialect.version(this.db)}async syncColumns(e=!1){let t=await this.dialect.getColumns(this.db,this.schema),r=new Map(t.map((a)=>[this.dialect.normalizeColumnName(a),a])),n=this.schema.columnDefinitions(),s=Object.keys(n),i=new Set(s.map((a)=>this.dialect.normalizeColumnName(a)));for(let a of s)if(!r.has(this.dialect.normalizeColumnName(a)))await this.dialect.addColumn(this.db,this.schema,a,n[a]);if(e){for(let[a,o]of r)if(!i.has(a))await this.dialect.dropColumn(this.db,this.schema,o)}}identifier(e){return b.unsafe(this.dialect.quoteIdentifier(e))}get table(){return b.unsafe(this.dialect.quoteTable(this.schema.table))}joinSql(e,t){if(e.length===0)return b``;return e.slice(1).reduce((r,n)=>b`${r}${t}${n}`,e[0])}buildWhere(e={}){let t=Object.entries(e).map(([r,n])=>{if(n!==null&&typeof n==="object"&&"operator"in n&&"value"in n){let s=String(n.operator).toUpperCase();if(!Sr.has(s))throw TypeError(`Unsupported SQL operator: ${s}`);let i=this.dialect.normalizeOperator(s),a=n.value;if(i==="IN"||i==="NOT IN"){if(!Array.isArray(a))throw TypeError(`${i} requires an array value.`);if(a.length===0)return i==="IN"?b`1=0`:b`1=1`;let o=this.joinSql(a.map((c)=>b`${c}`),b`, `);return b`${this.identifier(r)} ${b.unsafe(i)} (${o})`}if(a===null&&(i==="="||i==="IS"))return b`${this.identifier(r)} IS NULL`;if(a===null&&(i==="!="||i==="IS NOT"))return b`${this.identifier(r)} IS NOT NULL`;return b`${this.identifier(r)} ${b.unsafe(i)} ${a}`}return n===null?b`${this.identifier(r)} IS NULL`:b`${this.identifier(r)} = ${n}`});return t.length?this.joinSql(t,b` AND `):b`1=1`}async insert(e){try{if(this.dialect.name==="mysql"||this.dialect.name==="mariadb"){let r=Object.keys(e).length===0?await this.db`INSERT INTO ${this.table} () VALUES ()`:await this.db`INSERT INTO ${this.table} ${b(e)}`,[n]=this.schema.entries().find(([,o])=>o.primaryKey)??[];if(!n)return;let s=e[n],i=s??r.lastInsertRowid;if(i==null||s===void 0&&i===0)return;let[a]=await this.db`SELECT * FROM ${this.table} WHERE ${this.identifier(n)} = ${i} LIMIT 1`;return a}let[t]=Object.keys(e).length===0?await this.db`INSERT INTO ${this.table} DEFAULT VALUES RETURNING *`:await this.db`INSERT INTO ${this.table} ${b(e)} RETURNING *`;return t}catch(t){this.handleDbError(t)}}async upsert(e,t){try{return await this.dialect.upsert(this.db,this.schema,e,t)}catch(r){this.handleDbError(r)}}async find(e){let[t]=await this.db`
64
+ SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)} LIMIT 1
65
+ `;return t??null}async findAll(e){return e&&Object.keys(e).length?await this.db`SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)}`:await this.db`SELECT * FROM ${this.table}`}async count(e){let[t]=e&&Object.keys(e).length?await this.db`SELECT COUNT(*) AS total FROM ${this.table} WHERE ${this.buildWhere(e)}`:await this.db`SELECT COUNT(*) AS total FROM ${this.table}`;return Number(t?.total??0)}async exists(e){let[t]=await this.db`
66
+ SELECT 1 FROM ${this.table} WHERE ${this.buildWhere(e)} LIMIT 1
67
+ `;return t!==void 0}async paginate(e,t,r){if(!Number.isSafeInteger(e)||e<1)throw RangeError("Page must be a positive safe integer.");if(!Number.isSafeInteger(t)||t<1)throw RangeError("Limit must be a positive safe integer.");let n=(e-1)*t;if(!Number.isSafeInteger(n))throw RangeError("Pagination offset exceeds the safe integer range.");return r&&Object.keys(r).length?await this.db`SELECT * FROM ${this.table} WHERE ${this.buildWhere(r)} LIMIT ${t} OFFSET ${n}`:await this.db`SELECT * FROM ${this.table} LIMIT ${t} OFFSET ${n}`}async update(e,t){try{if(Object.keys(e??{}).length===0)throw new M("Refusing to update rows without a WHERE condition.");if(Object.keys(t).length===0)throw new M("Refusing to run an UPDATE with no values.");if(this.dialect.name==="mysql"||this.dialect.name==="mariadb")return await this.db.begin(async(r)=>{let n=await r`SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)} FOR UPDATE`;return await r`UPDATE ${this.table} SET ${b(t)} WHERE ${this.buildWhere(e)}`,n.map((s)=>({...s,...t}))});return await this.db`
68
+ UPDATE ${this.table} SET ${b(t)}
69
+ WHERE ${this.buildWhere(e)} RETURNING *
70
+ `}catch(r){this.handleDbError(r)}}async delete(e){try{if(Object.keys(e??{}).length===0)throw new M("Refusing to delete rows without a WHERE condition.");if(this.dialect.name==="mysql"||this.dialect.name==="mariadb")return await this.db.begin(async(t)=>{let r=await t`SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)} FOR UPDATE`;return await t`DELETE FROM ${this.table} WHERE ${this.buildWhere(e)}`,r});return await this.db`
71
+ DELETE FROM ${this.table} WHERE ${this.buildWhere(e)} RETURNING *
72
+ `}catch(t){this.handleDbError(t)}}async transaction(e){try{return await this.db.begin(async(t)=>e(this.withContext(t),t))}catch(t){this.handleDbError(t)}}handleDbError(e){let r=(e instanceof Error?e.message:String(e)).toLowerCase();if(r.includes("unique constraint failed")||r.includes("duplicate key value violates unique constraint")||r.includes("duplicate entry"))throw new le(`A record with this unique value already exists in ${this.schema.table}.`);if(r.includes("foreign key constraint failed")||r.includes("violates foreign key constraint")||r.includes("foreign key constraint fails"))throw new de("Cannot delete or update this record because it is referenced by another table.");if(r.includes("database is locked")||r.includes("sqlite_busy"))throw new M("The database is busy. Please retry the operation.");throw e}}class je{table;definitions;dialect;constructor(e,t,r){this.table=e;this.definitions=t;this.dialect=r}entries(){return Object.entries(this.definitions)}withDialect(e){let t=Object.fromEntries(this.entries());return new je(this.table,t,e)}createSQL(e=this.dialect){let t=this.entries();if(t.length===0)throw Error(`Cannot create table '${this.table}' without columns.`);return`CREATE TABLE IF NOT EXISTS ${e.quoteTable(this.table)} (
73
+ ${t.map(([r,n])=>e.buildColumn(r,n)).join(`,
74
+ `)}
75
+ );`}columnDefinitions(e=this.dialect){return Object.fromEntries(this.entries().map(([t,r])=>[t,e.buildColumnType(r)]))}get columns(){return new Proxy({},{get:(e,t)=>typeof t==="string"?t:void 0})}}function p(e,t={}){return function(r,n={}){let{id:s,...i}=t,a={...i,...n,code:t.code??400,message:n.message??t.message??"Request Failed",headers:{...t.headers,...n.headers}};if(n.redirect!==void 0||t.redirect!==void 0)a.redirect=n.redirect??t.redirect;let o=async(c,l)=>e(c,l,r,a);if(s)o._middlewareId=s,o.id=s;return o}}var Ti=p(async(e,t,r,n)=>{let i=e.req.headers.get("Authorization")?.trim()?.match(/^Bearer\s+(\S+)$/i);if(!i||!await r(e,i[1]))return d(n);return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),Ri=p(async(e,t,r,n)=>{let s=e.req.headers.get("x-api-key");if(!s)return d({code:401,message:"Missing api key"});if(!await r(e,s))return d({code:401,message:"Invalid API Key."});return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),xi=p(async(e,t,r,n)=>{for(let[s,i]of Object.entries(r)){let a=e.req.headers.get(s);if(!a)return d({code:401,message:`Missing ${s} header.`});if(!await i(e,a))return d({code:401,message:"Invalid."})}return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),Ci=p(async(e,t,r,n)=>{if(!r||!await r(e))return d(n);return t()},{id:"authorize-guard",code:403,message:"Forbidden"});var k=new Map,wr=1000,Er=new Set(["no-cache","no-store"]),Tr=new Set(["private","no-store","no-cache"]),Rr=/(?:^|,)\s*(?:max-age|s-maxage)\s*=\s*["']?0(?:\s|,|$)/i;function Et(e,t){return e?.split(",").some((r)=>t.has(r.trim().split("=",1)[0].toLowerCase()))??!1}function xr(e){let t=e.req.headers;if(t.has("authorization")||t.has("cookie")||t.has("range"))return!0;return Et(t.get("cache-control"),Er)||t.get("pragma")?.toLowerCase().includes("no-cache")===!0}function Cr(e){let t=e.headers.get("cache-control")??"";return e.status===200&&!e.headers.has("set-cookie")&&!e.headers.has("content-range")&&!e.headers.has("vary")&&!Et(t,Tr)&&!Rr.test(t)}var vi=p(async(e,t,r)=>{if(e.req.method!=="GET"||xr(e))return await t();let n=r?.ttlMs;if(!Number.isFinite(n)||n<=0)return await t();let s=Date.now();for(let[u,m]of k)if(m.expires<=s)k.delete(u);let i=e.req.url.href,a=k.get(i);if(a)return new Response(a.body.slice(),{status:a.status,statusText:a.statusText,headers:new Headers(a.headers)});let o=await t();if(!Cr(o))return o;let c=o.clone(),l=new Uint8Array(await c.arrayBuffer());if(k.size>=wr){let u=k.keys().next().value;if(u!==void 0)k.delete(u)}return k.set(i,{expires:s+n,body:l,headers:new Headers(c.headers),status:c.status,statusText:c.statusText}),o});var Di=p(async(e,t,r,n)=>{if(!r)return t();let s=e.req.header("content-type")??null,i=s?s.split(";")[0].trim().toLowerCase():null,a=!1;if(typeof r==="function")a=r(i,e);else{let o=Array.isArray(r)?r.map(Tt):[Tt(r)];a=i!==null&&o.includes(i)}if(!a)return d(n);return t()},{id:"content-type",code:415,message:"Unsupported Media Type. The request Content-Type is invalid or missing."});function Tt(e){return e.split(";")[0].trim().toLowerCase()}var ki=p(async(e,t,r,n)=>{if(!e.req.cookies.has(r))return d(n);return await t()},{id:"cookie-checker",code:401,message:"Required cookie is missing."});function Ue(e){if(!e)return;return Array.isArray(e)?e.join(", "):e}var ji=p(async(e,t,r,n)=>{let{origin:s="*",allowHeaders:i="*",methods:a,exposeHeaders:o,credentials:c=!1,maxAge:l=86400}=r||{},u=e.req?.headers?.get("origin")||null,m=null;if(typeof s==="function"){let h=s(u,e);m=typeof h==="string"?h:h?u:null}else if(Array.isArray(s)){if(u&&s.some((h)=>h===u))m=u}else if(s==="*")m=c?u:"*";else if(u===s)m=u;if(u&&!m)return d(n);let f={};if(m)f["Access-Control-Allow-Origin"]=m;if(c)f["Access-Control-Allow-Credentials"]="true";if(o){let h=Ue(o);if(h)f["Access-Control-Expose-Headers"]=h}if(i){let h=Ue(i);if(h)f["Access-Control-Allow-Headers"]=h}if(a){let h=Ue(a);if(h)f["Access-Control-Allow-Methods"]=h}if(l!==void 0)f["Access-Control-Max-Age"]=l.toString();if(m&&m!=="*")f.Vary="Origin";return e.res.header(f),await t()},{code:403,message:"CORS Origin Not Allowed",id:"cors-guard"});var Bi=p(async(e,t,r,n)=>{if(["POST","PUT","DELETE","PATCH"].includes(e.req.method)){let s=r?.headerName||"x-csrf-token",i=e.req.headers.get(s),a=e.req.cookies.get("csrf_token")||"";if(!i||!a||i!==a)return d(n)}return await t()},{id:"csrf-guard",code:403,message:"CSRF Token Validation Failed"});var Ji=p(async(e,t,r,n)=>{let{when:s,...i}=r??{};if(s&&!await s(e))return await t();let a=Object.fromEntries(Object.entries(i).filter(([,o])=>o!==void 0));return d({...n,...a})},{id:"deny",code:403,message:"Forbidden"});var Qi=p(async(e,t,r)=>{try{return await t()}catch(n){if(r?.logErrors)console.error(n);if(r?.onError)return await r.onError(n,e);return e.res.error(500,r?.message??"Internal Server Error")}},{id:"error-handler"});var ta=p(async(e,t,r,n)=>{let s=(i)=>e.req.headers.get(i);if(r){let i=null;if(Array.isArray(r))i=r;else if(typeof r==="string")i=[r];if(i){for(let a of i)if(!s(a))return d({code:401,message:`Missing required ${a} property.`})}else for(let[a,o]of Object.entries(r)){let c=s(a);if(!c)return d({code:401,message:`Missing required ${a} property.`});if(!o(e,a,c))return d(n)}}return await t()},{code:400,message:"Required headers are missing or invalid."});var pe=(e)=>{let t=e.req.server;if(t)return t.requestIP(e.req.request)?.address??"";return e.req.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||"127.0.0.1"};function G(e){let t=e.split(".");if(t.length!==4)return null;let r=[];for(let n of t){if(!/^(0|[1-9]\d{0,2})$/.test(n))return null;let s=Number(n);if(s>255)return null;r.push(s)}return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0}function he(e){let t=e.trim();if(t.startsWith("[")&&t.endsWith("]"))t=t.slice(1,-1);let r=t.indexOf("%");if(r!==-1)t=t.slice(0,r);if(!t.includes(":"))return null;let n=t.lastIndexOf(":"),s=t.slice(n+1);if(s.includes(".")){let l=G(s);if(l===null)return null;let u=(l>>>16).toString(16),m=(l&65535).toString(16);t=`${t.slice(0,n+1)}${u}:${m}`}let i=(l)=>{if(l==="")return[];let u=[];for(let m of l.split(":")){if(!/^[0-9a-fA-F]{1,4}$/.test(m))return null;u.push(parseInt(m,16))}return u},a=t.split("::");if(a.length>2)return null;let o;if(a.length===2){let l=i(a[0]??""),u=i(a[1]??"");if(!l||!u)return null;let m=8-l.length-u.length;if(m<1)return null;o=[...l,...Array(m).fill(0),...u]}else{let l=i(t);if(!l)return null;o=l}if(o.length!==8)return null;let c=new Uint8Array(16);return o.forEach((l,u)=>{c[u*2]=l>>>8&255,c[u*2+1]=l&255}),c}function Rt(e){let t=e.trim();if(t.startsWith("[")&&t.endsWith("]"))t=t.slice(1,-1);let r=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(t);if(r&&G(r[1])!==null)return r[1];return t}function Or(e,t){return e.every((r,n)=>r===t[n])}function Ar(e,t,r){let n=Math.floor(r/8);for(let a=0;a<n;a++)if(e[a]!==t[a])return!1;let s=r%8;if(s===0)return!0;let i=255<<8-s&255;return(e[n]&i)===(t[n]&i)}class ge{rules=[];constructor(e){this.compileRules(e)}test(e){let t=Rt(e.split(",")[0]?.trim()??""),r=G(t);return this.rules.some((n)=>n(t,r))}compileRules(e){for(let t of e){let r=Rt(t),n=r.lastIndexOf("/");if(n!==-1)this.rules.push(this.compileCidr(r,n));else if(r.includes("*"))this.rules.push(this.compileWildcard(r));else{let s=G(r);if(s!==null){this.rules.push((a,o)=>o===s);continue}let i=he(r);if(i===null)throw RangeError(`Invalid IP rule: ${t}`);this.rules.push((a)=>{let o=he(a);return o!==null&&Or(o,i)})}}}compileCidr(e,t){let r=e.slice(0,t),n=e.slice(t+1),s=G(r);if(s!==null){if(!/^(0|[1-9]\d?)$/.test(n))throw RangeError(`Invalid CIDR rule: ${e}`);let o=Number(n);if(o>32)throw RangeError(`Invalid CIDR rule: ${e}`);let c=o===0?0:4294967295<<32-o>>>0,l=(s&c)>>>0;return(u,m)=>m!==null&&(m&c)>>>0===l}let i=he(r);if(i===null)throw RangeError(`Invalid CIDR rule: ${e}`);if(!/^(0|[1-9]\d{0,2})$/.test(n))throw RangeError(`Invalid CIDR rule: ${e}`);let a=Number(n);if(a>128)throw RangeError(`Invalid CIDR rule: ${e}`);return(o)=>{let c=he(o);return c!==null&&Ar(c,i,a)}}compileWildcard(e){let t=e.split(".");if(t.length!==4||t.some((r)=>r!=="*"&&G(`0.0.0.${r}`)===null))throw RangeError(`Invalid IPv4 wildcard rule: ${e}`);return(r,n)=>n!==null&&r.split(".").every((s,i)=>{let a=t[i];return a==="*"||s===a})}}var ua=p(async(e,t,r,n)=>{let s=pe(e),{blacklist:i=[],whitelist:a=[]}=r??{};if(i.length){if(new ge(i).test(s))return d(n)}if(a.length){if(!new ge(a).test(s))return d(n)}return await t()},{id:"ip-filter",code:403,message:"Forbidden"});var vr=["POST","PUT","PATCH"],Nr=1048576,fa=p(async(e,t,r,n)=>{if(!vr.includes(e.req.method.toUpperCase()))return await t();if(e.req.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json")return d({code:415,message:"Content-Type must be application/json"});let i=n.maxSize,a=typeof i==="number"&&i>0?i:Nr,o=e.req.headers.get("content-length");if(o!==null){if(!/^\d+$/.test(o))return d({code:400,message:"Invalid Content-Length header"});let m=Number(o);if(!Number.isSafeInteger(m)||m<0)return d({code:400,message:"Invalid Content-Length header"});if(m>a)return d({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`})}let c="";try{c=await e.req.text()}catch{return d({code:400,message:"Failed to read request stream"})}if(new TextEncoder().encode(c).byteLength>a)return d({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`});if(!c||c.trim().length===0)return d({code:400,message:"Request body cannot be empty"});let l;try{l=JSON.parse(c)}catch(m){return d({code:400,message:`Invalid JSON syntax: ${m.message}`})}if(typeof l!=="object"||l===null)return d({code:400,message:"JSON payload must be a valid JSON object or array"});let u=r.safeParse(l);if(!u.success)return d({...n,message:`Validation failed: ${u.error.issues.map((m)=>m.message).join(", ")}`});return e.req._json=u.data,await t()},{id:"json-validator",code:400}),pa=p(async(e,t,r)=>{let n=await e.req.json();if(!n||typeof n!=="object"||Array.isArray(n))return d({code:400,message:"JSON body must be an object"});let s=r.filter((i)=>!Object.hasOwn(n,i));if(s.length>0)return d({code:400,message:`Missing required fields: ${s.join(", ")}`});return e.body=n,await t()},{id:"require-keys",code:400});var ba=p(async(e,t,r,n)=>{if(!r)throw Error("jwtAuth requires a JWTAuthService instance.");let i=e.req.headers.get("Authorization")?.trim().match(/^Bearer\s+(\S+)$/i);if(!i)return d(n);let a=r.verify(i[1]);if(!a)return d(n);return e.jwtData=a,await t()},{id:"jwt-auth-guard",code:401,message:"Unauthorized Access"}),Sa=p(async(e,t,r,n)=>{if(!r)throw Error("jwtRefresh requires a JWTAuthService instance.");let s=e.req.headers.get("x-refresh-token")?.trim();if(!s||/\s/.test(s))return d(n);let i=await r.consume(s);if(!i)return d(n);return e.jwtData=i,e.data.jwtTokens=await r.issue(i),await t()},{id:"jwt-refresh-guard",code:401,message:"Refresh Token Failed"});var Ta=p(async(e,t,r="",n)=>{let s=e.req.method,i=new URL(e.req.url).pathname,a=new Date().toLocaleString();return console.log(`${s} ${i} @ ${a}${r?` | ${r}`:""}`),await t()}),Ra=p(async(e,t,r,n)=>{let s=e.req.method,i=new URL(e.req.url).pathname,a=new Date().toLocaleTimeString(),o=await t(),c=r({ctx:e,res:o,timestamp:a,method:s,url:i});if(c)console.log(c);return o});function J(e){let t=Object.create(null);for(let[r,n]of e.entries()){if(!Object.prototype.hasOwnProperty.call(t,r)){t[r]=n;continue}let s=t[r];t[r]=Array.isArray(s)?[...s,n]:[s,n]}return t}var Na=p(async(e,t)=>{if(!(e.req.headers.get("content-type")?.toLowerCase()??"").startsWith("multipart/form-data"))return t();try{let n=await e.req.request.formData();e.req._formData=n,e.form=J(n)}catch{return d({code:400,message:"Invalid multipart form data"})}return t()},{id:"multipart-parser",code:400,message:"Invalid multipart form data"});var Ia=p(async(e,t,r,n)=>{let s=r;if(typeof s?.safeParse!=="function")return d({code:500,message:"Framework Error: Missing schema in validateQuery guard."});let i;try{i=typeof e.req.url==="string"?new URL(e.req.url,"http://localhost"):e.req.url}catch{return d({code:n.code??400,message:"Malformed URL structure."})}let a=Object.create(null);i.searchParams.forEach((c,l)=>{a[l]=c});let o=s.safeParse(a);if(!o.success)return d({code:n.code??400,message:`Query Validation Error: ${o.error.issues.map((c)=>c.message).join("; ")}`});return e.query=o.data,await t()},{id:"query-validator",code:400,message:"Query validation failed"}),Pa=p(async(e,t,r,n)=>{let s=r;if(typeof s?.safeParse!=="function")return d({code:500,message:"Framework Error: Missing schema in validateForm guard."});let i;try{let o=await e.req.form();i=J(o)}catch{return d({code:n.code??400,message:"Invalid or malformed form payload."})}let a=s.safeParse(i);if(!a.success)return d({code:n.code??400,message:`Form Validation Error: ${a.error.issues.map((o)=>o.message).join("; ")}`});return e.form=a.data,await t()},{id:"form-validator",code:400,message:"Form validation failed"});var L=new Map;var xt=0;function Mr(e=Date.now()){for(let[t,r]of L)if(r.reset<=e)L.delete(t);xt=e+60000}function Ct(e,t,r){let n=Date.now();if(n>=xt)Mr(n);let s=L.get(e);if(!s||s.reset<n){let i=n+r;if(!s&&L.size>=1e5){let a=L.keys().next().value;if(a!==void 0)L.delete(a)}return L.set(e,{count:1,reset:i}),{allowed:!0,remaining:Math.max(0,t-1),resetTime:i}}if(s.count>=t)return{allowed:!1,remaining:0,resetTime:s.reset};return s.count+=1,{allowed:!0,remaining:Math.max(0,t-s.count),resetTime:s.reset}}var Ha=p(async(e,t,r,n)=>{let{max:s=100,windowMs:i=60000,expose:a=!0}=r||{},o=pe(e),c=e.req.method,l=`rate_${o}_${c}_${new URL(e.req.url).pathname}`,{allowed:u,remaining:m,resetTime:f}=Ct(l,s,i),h={};if(a)h["X-RateLimit-Limit"]=s.toString(),h["X-RateLimit-Remaining"]=m.toString(),h["X-RateLimit-Reset"]=Math.ceil(f/1000).toString();if(!u){if(a){let x=Math.max(1,Math.ceil((f-Date.now())/1000));h["Retry-After"]=x.toString()}return d({...n,headers:h})}let R=await t();if(a)Object.entries(h).forEach(([x,q])=>{R.headers.set(x,q)});return R},{id:"rate-limiter",code:429,message:"Too Many Requests"});function _r(e){return e.replace(/[&<>"']/g,(t)=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#x27;"}})}function V(e,t,r=new WeakMap){if(typeof e==="string")return t(e);if(Array.isArray(e)){if(r.has(e))return r.get(e);let s=[];r.set(e,s);for(let i of e)s.push(V(i,t,r));return s}if(e===null||typeof e!=="object"||e instanceof Blob)return e;if(r.has(e))return r.get(e);let n=Object.create(null);r.set(e,n);for(let[s,i]of Object.entries(e))n[s]=V(i,t,r);return n}var Ka=p(async(e,t,r)=>{let n=r?.sanitizeString??_r;if(r?.query!==!1)e.query=V(e.query,n);if(r?.form!==!1)e.form=V(e.form,n);if(r?.body!==!1){if(e.body!==void 0)e.body=V(e.body,n);let s=e.req._json;if(s!==void 0)e.req._json=V(s,n)}return t()},{id:"sanitize-guard"});function Dr(e,t){let r={"Content-Security-Policy":t.contentSecurityPolicy,"Cross-Origin-Embedder-Policy":t.crossOriginEmbedderPolicy,"Cross-Origin-Opener-Policy":t.crossOriginOpenerPolicy,"Cross-Origin-Resource-Policy":t.crossOriginResourcePolicy,"Strict-Transport-Security":t.hsts,"Permissions-Policy":t.permissionsPolicy,"Referrer-Policy":t.referrerPolicy??"strict-origin-when-cross-origin","X-Content-Type-Options":t.xContentTypeOptions??"nosniff","X-Frame-Options":t.xFrameOptions??"DENY"},n=new Headers(e.headers);for(let[s,i]of Object.entries(r))if(i===!1)n.delete(s);else if(i)n.set(s,i);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}var Ja=p(async(e,t,r)=>{let n=await t();return Dr(n,r??{})},{id:"security-headers"});var Xa=p(async(e,t,r,n)=>{let[s,i]=await r.loadHeader(e.req.request);e.session=i;let a=await t();if(!e.session.isReadOnly){if(!e.session.length){if(e.session.isNew){if(s)await r.deleteSession(e.session,a.headers)}else if(e.session.isModified)await r.deleteSession(e.session,a.headers)}else if(e.session.isModified)await r.saveSession(e.session,a.headers)}return a},{id:"session-manager"}),Za=p(async(e,t,r,n)=>{let s=e.session;if(!s||!s.isFound||s.isNew)return d(n);if(r&&!await r(s))return d(n);return await t()},{id:"require-session",code:401,message:"Authentication required"});var Ot=new WeakMap;function $r(e){let t=e.root?.trim(),r=e.extensions?.filter((s)=>s.trim())??[];if(!t&&r.length===0)return;let n=Ot.get(e);if(!n){let s=t?new te(t,r):void 0,i=new Set(r);n={server:s,isFile:s?(a)=>s.isFile(a):(a)=>ee(a,i)},Ot.set(e,n)}return n}function Ir(e){if(!e)return;let t=e.trim().replace(/\/+$/,"");if(!t)return;if(!t.startsWith("/"))t=`/${t}`;return t}function Pr(e,t){return e===t||e.startsWith(`${t}/`)}var no=p(async(e,t,r)=>{if(!["GET","HEAD"].includes(e.req.method))return t();let n=r??{},s=Ir(n.prefix),i=e.req.path;if(s){let u;try{u=decodeURIComponent(i)}catch{return t()}if(!Pr(u,s))return t();i=u}let a=$r(n);if(!(e.req.isFile||(a?a.isFile(i):!1)))return t();let c=s&&a?.server?i.slice(s.length)||"/":void 0,l=a?.server?await a.server.serve(e.req,e.res,c):await e.res.fileServer();if(e.req.method!=="HEAD")return l;return new Response(null,{status:l.status,statusText:l.statusText,headers:l.headers})},{id:"static-files"});var oo=p(async(e,t,r,n)=>{let s,i=new Promise((a)=>{s=setTimeout(()=>a(d(n)),r)});try{return await Promise.race([t(),i])}finally{if(s)clearTimeout(s)}},{id:"timeout-guard",code:408,message:"Request Timeout"});var kr=2048,Lr=1024;function At(e){let t=e,r="";while(t!==r&&t.includes("%"))r=t,t=decodeURIComponent(t);return t}var mo=p(async(e,t,r,n)=>{let s=typeof r==="number"?{maxUrlLength:r}:r||{},i=s.maxUrlLength??kr,a=s.maxQueryLength??Lr,o;try{o=typeof e.req.url==="string"?new URL(e.req.url,"http://localhost"):e.req.url}catch{return d({code:400,message:"Malformed URL structure."})}if(o.href.length>i)return d({code:414,message:`URI Too Long. Exceeds limit of ${i} characters.`});if((o.search.startsWith("?")?o.search.slice(1):o.search).length>a)return d({code:414,message:`Query string too long. Exceeds limit of ${a} characters.`});if(s.sanitizePaths!==!1){let f,h;try{f=At(o.pathname),h=At(o.search)}catch{return d({code:400,message:"Malformed percent-encoding in URL."})}if(f.includes("\x00")||h.includes("\x00"))return d({code:400,message:"Null byte injection detected in URL."});if(f.includes("../")||f.includes("..\\")||f.includes("/.."))return d({code:400,message:"Path traversal attempt detected in URL."})}let u=o.searchParams,m=Array.from(u.keys());if(m.length>0){if(s.noDuplicates){if(new Set(m).size!==m.length)return d({code:n.code??400,message:"Duplicate query parameters are not allowed."})}if(s.allowedKeys){let f=new Set(s.allowedKeys);for(let h of m)if(!f.has(h))return d({code:n.code??400,message:`Unauthorized query parameter: '${h}'`})}if(s.disallowedKeys){let f=new Set(s.disallowedKeys);for(let h of m)if(f.has(h))return d({code:n.code??400,message:`Forbidden query parameter: '${h}'`})}if(s.patterns)for(let[f,h]of Object.entries(s.patterns)){let R=u.getAll(f);for(let x of R){h.lastIndex=0;let q=h.test(x);if(h.lastIndex=0,!q)return d({code:n.code??400,message:`Invalid format for query parameter '${f}'.`})}}}return await t()},{id:"url-validator",code:400,message:"URL validation failed"});var yo=p(async(e,t)=>{if(!(e.req.headers.get("content-type")?.toLowerCase()??"").startsWith("application/x-www-form-urlencoded"))return t();try{let n=await e.req.request.formData();e.req._formData=n,e.form=J(n)}catch{return d({code:400,message:"Invalid URL-encoded form data"})}return t()},{id:"urlencoded-parser",code:400,message:"Invalid URL-encoded form data"});class He extends Error{issues;constructor(e){super(e.map((t)=>t.message).join(", "));this.name="SchemaError",this.issues=e}}function qr(){return{optional:!1,nullable:!1,hasDefault:!1,defaultValue:void 0}}function w(e){if(e.length===0)return"value";let t="";for(let r of e)if(typeof r==="number")t+=`[${r}]`;else t+=t===""?r:`.${r}`;return`'${t}'`}class D{"~standard";_state;constructor(e=qr()){this._state=e,this["~standard"]={version:1,vendor:"rossa",validate:(t)=>{let r=this.safeParse(t);if(r.success)return{value:r.data};return{issues:r.error.issues.map((n)=>({message:n.message,path:n.path}))}},jsonSchema:{input:(t)=>this.toJSONSchema(t),output:(t)=>this.toJSONSchema(t)}}}toJSONSchema(e={target:"draft-2020-12"}){return this._jsonSchema(e)}_isRequired(){return!this._state.optional&&!this._state.hasDefault}optional(){let e=this._clone();return e._state.optional=!0,e}nullable(){let e=this._clone();return e._state.nullable=!0,e}default(e){let t=this._clone();return t._state.hasDefault=!0,t._state.defaultValue=e,t}_run(e,t,r){if(e===void 0){if(this._state.hasDefault)return this._state.defaultValue;if(this._state.optional)return;r.push({path:[...t],message:`${w(t)} is required`});return}if(e===null){if(this._state.nullable)return null;r.push({path:[...t],message:`${w(t)} must not be null`});return}return this._validate(e,t,r)}safeParse(e){let t=[],r=this._run(e,[],t);if(t.length>0)return{success:!1,error:new He(t)};return{success:!0,data:r}}parse(e){let t=this.safeParse(e);if(!t.success)throw t.error;return t.data}}function ie(e,t){let r=e;if(t.nullable)r={anyOf:[r,{type:"null"}]};if(t.hasDefault)r={...r,default:t.defaultValue};return r}function vt(e,t){let r,n,s=!1;for(let a of e)if(a.kind==="min"&&a.value!==void 0)r=r===void 0?a.value:Math.max(r,a.value);else if(a.kind==="max"&&a.value!==void 0)n=n===void 0?a.value:Math.min(n,a.value);else if(a.kind==="email")s=!0;let i={type:"string"};if(r!==void 0)i.minLength=r;if(n!==void 0)i.maxLength=n;if(s)i.format="email";return ie(i,t)}function Nt(e,t){let r,n,s=!1;for(let a of e)if(a.kind==="min"&&a.value!==void 0)r=r===void 0?a.value:Math.max(r,a.value);else if(a.kind==="max"&&a.value!==void 0)n=n===void 0?a.value:Math.min(n,a.value);else if(a.kind==="int")s=!0;let i={type:s?"integer":"number"};if(r!==void 0)i.minimum=r;if(n!==void 0)i.maximum=n;return ie(i,t)}function Mt(e){return ie({type:"boolean"},e)}function _t(e,t,r){let n,s;for(let a of t)if(a.kind==="min"&&a.value!==void 0)n=n===void 0?a.value:Math.max(n,a.value);else if(a.kind==="max"&&a.value!==void 0)s=s===void 0?a.value:Math.min(s,a.value);let i={type:"array",items:e};if(n!==void 0)i.minItems=n;if(s!==void 0)i.maxItems=s;return ie(i,r)}function Dt(e,t,r){let n={type:"object"};if(Object.keys(e).length>0){if(n.properties=e,t.length>0)n.required=[...t]}return n.additionalProperties=!1,ie(n,r)}class Y extends D{_rules;_coerce;constructor(e={}){super(e.state);this._rules=e.rules?[...e.rules]:[],this._coerce=e.coerce??!1}_clone(){return new Y({coerce:this._coerce,rules:this._rules,state:{...this._state}})}min(e){return this._withRule({kind:"min",value:e})}max(e){return this._withRule({kind:"max",value:e})}email(){return this._withRule({kind:"email"})}trim(){return this._withRule({kind:"trim"})}_withRule(e){let t=this._clone();return t._rules.push(e),t}_jsonSchema(e){return vt(this._rules,this._state)}_validate(e,t,r){let n=e;if(this._coerce&&typeof n!=="string"){if(typeof n==="number"||typeof n==="boolean"||typeof n==="bigint")n=String(n)}if(typeof n!=="string"){r.push({path:[...t],message:`${w(t)} must be a string`});return}let s=this._rules.some((i)=>i.kind==="trim")?n.trim():n;for(let i of this._rules){if(i.kind==="min"&&s.length<i.value)r.push({path:[...t],message:`${w(t)} must have at least ${i.value} characters`});if(i.kind==="max"&&s.length>i.value)r.push({path:[...t],message:`${w(t)} must have at most ${i.value} characters`});if(i.kind==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))r.push({path:[...t],message:`${w(t)} must be a valid email`})}return s}}class Q extends D{_rules;_coerce;constructor(e={}){super(e.state);this._rules=e.rules?[...e.rules]:[],this._coerce=e.coerce??!1}_clone(){return new Q({coerce:this._coerce,rules:this._rules,state:{...this._state}})}min(e){return this._withRule({kind:"min",value:e})}max(e){return this._withRule({kind:"max",value:e})}int(){return this._withRule({kind:"int"})}_withRule(e){let t=this._clone();return t._rules.push(e),t}_jsonSchema(e){return Nt(this._rules,this._state)}_validate(e,t,r){let n=e;if(this._coerce&&typeof n==="string"){let s=n.trim(),i=s===""?Number.NaN:Number(s);if(!Number.isFinite(i)){r.push({path:[...t],message:`${w(t)} must be a number`});return}n=i}if(typeof n!=="number"||!Number.isFinite(n)){r.push({path:[...t],message:`${w(t)} must be a number`});return}for(let s of this._rules){if(s.kind==="min"&&n<s.value)r.push({path:[...t],message:`${w(t)} must be at least ${s.value}`});if(s.kind==="max"&&n>s.value)r.push({path:[...t],message:`${w(t)} must be at most ${s.value}`});if(s.kind==="int"&&!Number.isInteger(n))r.push({path:[...t],message:`${w(t)} must be an integer`})}return n}}class X extends D{_coerce;constructor(e={}){super(e.state);this._coerce=e.coerce??!1}_clone(){return new X({coerce:this._coerce,state:{...this._state}})}_jsonSchema(e){return Mt(this._state)}_validate(e,t,r){let n=e;if(this._coerce&&typeof n==="string"){let s=n.toLowerCase();if(s==="true"||s==="1")n=!0;else if(s==="false"||s==="0")n=!1;else{r.push({path:[...t],message:`${w(t)} must be a boolean`});return}}if(typeof n!=="boolean"){r.push({path:[...t],message:`${w(t)} must be a boolean`});return}return n}}class ae extends D{_item;_rules;constructor(e,t={}){super(t.state);this._item=e,this._rules=t.rules?[...t.rules]:[]}_clone(){return new ae(this._item,{rules:this._rules,state:{...this._state}})}min(e){return this._withRule({kind:"min",value:e})}max(e){return this._withRule({kind:"max",value:e})}_withRule(e){let t=this._clone();return t._rules.push(e),t}_jsonSchema(e){return _t(this._item.toJSONSchema(e),this._rules,this._state)}_validate(e,t,r){if(!Array.isArray(e)){r.push({path:[...t],message:`${w(t)} must be an array`});return}for(let n of this._rules){if(n.kind==="min"&&e.length<n.value)r.push({path:[...t],message:`${w(t)} must have at least ${n.value} items`});if(n.kind==="max"&&e.length>n.value)r.push({path:[...t],message:`${w(t)} must have at most ${n.value} items`})}return e.map((n,s)=>this._item._run(n,[...t,s],r))}}class oe extends D{shape;constructor(e,t={}){super(t.state);this.shape=e}_clone(){return new oe(this.shape,{state:{...this._state}})}_jsonSchema(e){let t={},r=[];for(let n of Object.keys(this.shape)){let s=this.shape[n];if(!s)continue;if(t[n]=s.toJSONSchema(e),s._isRequired())r.push(n)}return Dt(t,r,this._state)}_validate(e,t,r){if(typeof e!=="object"||e===null||Array.isArray(e)){r.push({path:[...t],message:`${w(t)} must be an object`});return}let n=e,s={};for(let i of Object.keys(this.shape)){let a=this.shape[i];if(!a)continue;let o=Object.hasOwn(n,i),c=a._run(o?n[i]:void 0,[...t,i],r);if(!o&&c===void 0)continue;s[i]=c}return s}}var Fr=()=>new Y,jr=()=>new Q,Ur=()=>new X,Hr=(e)=>new ae(e),Wr=(e)=>new oe(e),Br={string:()=>new Y({coerce:!0}),number:()=>new Q({coerce:!0}),boolean:()=>new X({coerce:!0})};import{createHmac as It,randomUUID as Kr,timingSafeEqual as zr}from"crypto";class We{secretKey;constructor(e){if(!e)throw Error("JWT secret key must be provided.");this.secretKey=Buffer.from(e,"utf8")}sign(e,t=15){if(!Number.isFinite(t)||t<=0)throw RangeError("Token validity must be a positive number of minutes.");let r={alg:"HS256",typ:"JWT"},n=Math.floor(Date.now()/1000),s={...e,iat:n,exp:n+t*60,jti:Kr()},i=Buffer.from(JSON.stringify(r)).toString("base64url"),a=Buffer.from(JSON.stringify(s)).toString("base64url"),o=`${i}.${a}`,c=It("sha256",this.secretKey).update(o).digest("base64url");return`${o}.${c}`}verify(e){try{let t=e.split(".");if(t.length!==3)return null;let[r,n,s]=t,i=`${r}.${n}`,a=JSON.parse(Buffer.from(r||"","base64url").toString("utf8"));if(!a||typeof a!=="object"||a.alg!=="HS256"||a.typ!=="JWT")return null;let o=It("sha256",this.secretKey).update(i).digest("base64url"),c=Buffer.from(o),l=Buffer.from(s||"");if(c.length!==l.length||!zr(c,l))return null;let u=JSON.parse(Buffer.from(n||"","base64url").toString("utf8"));if(!u||typeof u!=="object"||!Number.isFinite(u.iat)||!Number.isFinite(u.exp))return null;let m=Math.floor(Date.now()/1000);if(u.exp<=m)return null;return u}catch{return null}}issue(e,t=7){let r=t*24*60;return this.sign(e,r)}}class Pt{refreshTokens;config;engine;constructor(e,t,r={}){this.refreshTokens=e;this.engine=new We(t);let{refreshValidity:n=7,tokenValidity:s=15}=r;if(!Number.isFinite(n)||n<=0)throw RangeError("Refresh token validity must be a positive number of days.");if(!Number.isFinite(s)||s<=0)throw RangeError("Access token validity must be a positive number of minutes.");this.config={refreshValidity:n,tokenValidity:s}}async init(){await this.refreshTokens.initialize?.()}sign(e){return this.engine.sign(e,this.config.tokenValidity)}verify(e){return this.engine.verify(e)}async consume(e){let t=this.engine.verify(e);if(!t)return null;return await this.refreshTokens.consume(e)?t:null}async issue(e){let t=this.engine.issue(e,this.config.refreshValidity),r=Date.now()+this.config.refreshValidity*24*60*60*1000;return await this.refreshTokens.save(t,r),{accessToken:this.sign(e),refreshToken:t}}}class Z{sid;data;isNew;isModified;isReadOnly;isFound;length=0;constructor(e="",t={},r=!1,n=!0,s=!1){if(this.sid=e,this.data={...t},this.length=Object.keys(t).length,this.length)n=!1;this.isReadOnly=r,this.isNew=n,this.isModified=!1,this.isFound=s}get session(){return new Proxy(this,{get(e,t){if(t in e)return Reflect.get(e,t);return e.data[t]},set(e,t,r){if(e.isReadOnly)return console.warn("session: readonly"),!0;if(t in e)throw Error(`Cannot overwrite internal session property: ${String(t)}`);if(e.data[t]!==r){if(e.isModified=!0,!(t in e.data))e.length++;e.data[t]=r}return!0},deleteProperty(e,t){if(e.isReadOnly)return console.warn("session: readonly"),!0;if(t in e)return!1;if(t in e.data)e.isModified=!0,delete e.data[t],e.length--;return!0},has(e,t){return t in e||t in e.data},ownKeys(e){return Reflect.ownKeys(e.data)},getOwnPropertyDescriptor(e,t){if(t in e.data)return{enumerable:!0,configurable:!0,value:e.data[t]};return}})}}import{randomBytes as Yr}from"crypto";import{createHmac as Gr,createHash as Jr,timingSafeEqual as Vr}from"crypto";class Be{salt;key;constructor(e){this.salt=e;this.key=Jr("sha256").update(e).digest()}getSignature(e){return Gr("sha256",this.key).update(e).digest("base64url")}sign(e){let t=this.getSignature(e);return`${e}.${t}`}unsign(e){let t=e.indexOf(".");if(t===-1)return null;let r=e.slice(0,t),n=e.slice(t+1);if(this.verifySignature(r,n))return r;return null}verifySignature(e,t){let r=Buffer.from(this.getSignature(e),"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return!1;return Vr(r,n)}}class Ke{signer;constructor(e){this.signer=new Be(e)}generate(e=21){let t=Yr(e).toString("base64url");return this.signer.sign(t)}}class kt extends Ke{config;constructor(e,t){super(t??"salty");e.COOKIE_NAME=e.COOKIE_NAME??"session";let{COOKIE_NAME:r="session",COOKIE_LIFETIME:n=31,COOKIE_DOMAIN:s=void 0,COOKIE_PATH:i="/",COOKIE_HTTPONLY:a=!0,COOKIE_SECURE:o=!0,COOKIE_SAMESITE:c="Lax",MAX_COOKIE_SIZE:l=4093,SESSION_LIFETIME:u=31}=e;this.config={COOKIE_NAME:r,COOKIE_LIFETIME:n,COOKIE_DOMAIN:s,COOKIE_PATH:i,COOKIE_HTTPONLY:a,COOKIE_SECURE:o,COOKIE_SAMESITE:c,MAX_COOKIE_SIZE:l,SESSION_LIFETIME:u}}async init(){}async openSession(e,t=!1){if(e&&this.signer.unsign(e))return await this.fetchSession(e,t);return this.new({})}async fetchSession(e,t){try{let r=await this.fetchData(e);if(r){let n=r.data??{};if(this.isNotExpired(new Date(r.expiration)))return new Z(e,n,t,!1,!0).session;return this.new({sid:e,isFound:!0,readonly:t})}}catch(r){console.error(`[AuthEngine] Failed to parse session ${e}:`,r)}return this.new({sid:e,readonly:t})}new({sid:e,isFound:t=!1,readonly:r=!1}){return new Z(e??this.generate(),{},r,!0,t).session}get readonly(){return new Z(this.generate(),{},!0).session}get getSessionExpirationDate(){let e=new Date,t=this.config.SESSION_LIFETIME;return e.setDate(e.getDate()+t),e}get getCookieExpirationDate(){let e=new Date,t=this.config.COOKIE_LIFETIME;return e.setDate(e.getDate()+t),e}isNotExpired(e){let t=e.getTime(),r=Date.now();return t>r}buildCookieString(e,t,r){let n=[`${this.config.COOKIE_NAME}=${e.sid}`];if(n.push(`Path=${this.config.COOKIE_PATH}`),this.config.COOKIE_DOMAIN)n.push(`Domain=${this.config.COOKIE_DOMAIN}`);if(typeof t==="number")n.push(`Max-Age=${t}`);else{let c=t||this.getCookieExpirationDate;n.push(`Expires=${c.toUTCString()}`)}if(this.config.COOKIE_HTTPONLY)n.push("HttpOnly");if(this.config.COOKIE_SECURE)n.push("Secure");let s=r||this.config.COOKIE_SAMESITE;if(s)n.push(`SameSite=${s}`);let i=n.join("; "),a=Buffer.byteLength(i,"utf8"),o=this.config.MAX_COOKIE_SIZE;if(a>o)throw Error(`[Framework Guard] Cookie exceeds maximum allowed size! Size: ${a} bytes. Max allowed: ${o} bytes. The browser will reject this cookie.`);return i}setCookie(e,t){let r=this.buildCookieString(e);t.append("Set-Cookie",r)}removeCookie(e,t){let r=this.buildCookieString(e,0);t.append("Set-Cookie",r)}async loadHeader(e,t=!1){let r=e.headers.get("cookie");if(r){let n=r.match(new RegExp(`(^| )${this.config.COOKIE_NAME}=([^;]+)`));if(n){let s=n[2];return[s,await this.openSession(s,t)]}}return[void 0,this.new({readonly:t})]}}class Lt{contextData={};data={};constructor(){}open(){}message({text:e,json:t,topic:r}){}drain(){}close(e,t){}set send(e){this.ws.send(e)}}class ze{static registry=new Map;static register(e){for(let[t,r]of Object.entries(e)){let n=Object.seal({...r});this.registry.set(t,n)}return{use:(t)=>this.use(t)}}static use(e){return new Proxy({},{get:(t,r)=>(n,s)=>{if(s.kind!=="field")throw Error("Field decorators can only be used on class fields.");return function(){let i=ze.registry.get(e);return i?i[r]:void 0}}})}}var Qr=ze;class qt{static registry=new Map;static register(e){for(let[t,r]of Object.entries(e))this.registry.set(t,Object.seal({...r}));return{use:(t)=>this.use(t)}}static use(e){let t=this.registry.get(e);if(!t)throw Error(`Scope "${e}" has not been registered.`);return t}}var Xr=qt;export{ae as ArraySchema,X as BooleanSchema,O as Column,Nr as DEFAULT_MAX_SIZE,M as DatabaseError,z as DbInspector,Fe as DbRepository,je as DbSchema,Qr as Field,de as ForeignKeyError,Pt as JWTAuthService,se as McpController,ec as McpServer,Oe as Methods,Q as NumberSchema,oe as ObjectSchema,j as Req,W as Res,ft as Rossa,ne as RouterManager,D as Schema,He as SchemaError,Xr as Scope,Z as ServerSide,kt as SessionAuthInterface,Y as StringSchema,le as UniqueConstraintError,C as WSSMAN,Lt as Websocket,ue as WssManager,Ri as apiKey,xi as auth,Ti as authBearer,Ci as authorize,Di as contentType,ki as cookies,ji as cors,p as createGuard,Bi as csrf,F as ctx,Ji as deny,Qi as errorHandler,fe as getDialect,ta as header,ua as ipFilter,fa as json,ba as jwtAuth,Sa as jwtRefresh,pa as keys,Ta as logger,Ra as loggerFN,qe as mariadbDialect,lt as mcp,Na as multipart,Le as mysqlDialect,Ie as postgresDialect,Ha as rateLimit,Za as requireSession,Ae as route,Ka as sanitize,Ja as security,d as sendError,Xa as session,vi as smartCache,ke as sqliteDialect,no as staticFiles,ce as subManager,lr as t,oo as timeout,yo as urlencoded,tr as use,Pa as validateForm,Ia as validateQuery,mo as validateUrl,ot as wss,$t as z};
package/package.json CHANGED
@@ -1,11 +1,18 @@
1
1
  {
2
2
  "name": "rossa",
3
- "version": "0.0.5",
4
- "description": "Rossa Bun JS framework",
3
+ "version": "0.1.1",
4
+ "description": "A Bun and TypeScript web framework with routing, middleware guards, WebSockets, authentication, and database tools.",
5
5
  "author": "Marky <markjotep@gmail.com>",
6
6
  "license": "MIT",
7
7
  "main": "dist/index.js",
8
8
  "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
9
16
  "files": [
10
17
  "dist"
11
18
  ],
@@ -13,12 +20,11 @@
13
20
  "test": "test"
14
21
  },
15
22
  "scripts": {
16
- "util": "cp -r ../misc/util ./",
17
- "dirs": "for dir in ./src ./dist ./test ./util ./types; do mkdir -p $dir; done",
18
- "@": "ln -sf ../../misc/@/ ./src",
19
- "ts": "ln -sf ../misc/tsconfig.json ./;",
20
- "init": "bun run dirs && bun run util && bun run @ && bun run ts;",
21
- "build": "rm -r ./types ; tsc && bun build ./src/index.ts --outdir ./dist --minify --packages external --target bun && rollup -c ./util/rollup.config.js"
23
+ "init": "bun update && mkdir -p ./src ./dist ./types && { [ ! -f ./src/index.ts ] && touch ./src/index.ts; }",
24
+ "test": "bun test",
25
+ "test:load": "bun run test/load/benchmark.ts",
26
+ "build": "bun run builder.ts",
27
+ "prepublishOnly": "bun test && bun run build"
22
28
  },
23
29
  "keywords": [
24
30
  "ts",
@@ -33,18 +39,15 @@
33
39
  },
34
40
  "homepage": "https://github.com/MARKjotep/rossa#readme",
35
41
  "dependencies": {
36
- "jsonwebtoken": "^9.0.2",
37
- "authored": "latest",
38
- "dotenv": "^16.6.1"
42
+ "@modelcontextprotocol/server": "^2.4.0",
43
+ "reflect-metadata": "^0.2.2"
39
44
  },
40
45
  "devDependencies": {
41
- "@types/jsonwebtoken": "^9.0.10",
42
- "@types/bun": "1.2.2",
43
- "rollup": "^4.46.2",
44
- "rollup-plugin-dts": "^6.2.1"
45
- },
46
- "peerDependencies": {
47
- "typescript": "^5.7.2"
46
+ "@ohmyqt/oven": "link:@ohmyqt/oven",
47
+ "@ohmyqt/u": "link:@ohmyqt/u",
48
+ "@types/bun": "^1.4.4",
49
+ "fake-indexeddb": "^6.2.8",
50
+ "typescript": "^5.9.3"
48
51
  },
49
52
  "type": "module"
50
53
  }