rossa 0.0.5 → 0.0.6
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/LICENSE +1 -1
- package/README.md +226 -1
- package/dist/index.d.ts +1518 -238
- package/dist/index.js +74 -3
- package/package.json +19 -20
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
|
-
|
|
4
|
-
|
|
2
|
+
class ne{data;constructor(e={}){this.data={...e}}_add(e,t){return this.data[e]=t,this}add(e,t){return this._add(e,t)}}class se extends ne{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 ie extends se{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 ae extends ie{authenticate(e,t){let r=t?`${e} ${t}`:e;return this._add("WWW-Authenticate",r)}proxyAuthenticate(e){return this._add("Proxy-Authenticate",e)}}class oe extends ae{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 ce extends oe{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",dt(e,t,r))}}var dt=(e,t="",r={})=>{let{maxAge:n,expires:s,path:i,domain:a,secure:o,httpOnly:c,sameSite:d}=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(d!=null)f.push(`SameSite=${d}`);return[`${e}=${t}`,...f].join("; ")};class D extends ce{get copy(){return new D(this.data)}use(e){return e(this),this}merge(e){return Object.assign(this.data,e instanceof D?e.data:e),this}static init(e){return new this(e)}static get $(){return new this}get done(){return this.data}}class L{res;params={};headr;url;data={};jwtData={};session;body;query={};form={};req;method="GET";methods=[];clientDirectory="";constructor(e){this.res=e;this.headr=new D,this.req=e.req,this.url=this.req.url}}import{isAbsolute as _e,relative as Le,resolve as Ie,sep as Pe}from"path";import{realpath as ke}from"fs/promises";var ue=new Map,qe=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 Ue(e){let t=e.trim().toLowerCase();if(!t)return"";return t.startsWith(".")?t:`.${t}`}function le(e,t=new Set){let r=e.slice(e.lastIndexOf("/")+1).toLowerCase();return[...qe,...t].map(Ue).filter(Boolean).some((s)=>r.endsWith(s))}class de{absoluteClientPath;additionalExtensions;SMALL_FILE_THRESHOLD=51200;CACHE_TTL=900000;constructor(e,t=[]){this.absoluteClientPath=Ie(e),this.additionalExtensions=new Set(t.map(Ue).filter(Boolean))}isFile(e){return le(e,this.additionalExtensions)}async serve(e,t){let r=e.url.pathname,n=Ie(this.absoluteClientPath,`.${r}`),s=Le(this.absoluteClientPath,n);if(s===".."||s.startsWith(`..${Pe}`)||_e(s))return t.error(403,"Forbidden");let i,a;try{[i,a]=await Promise.all([ke(this.absoluteClientPath),ke(n)])}catch{return t.null(404)}let o=Le(i,a);if(o===".."||o.startsWith(`..${Pe}`)||_e(o))return t.error(403,"Forbidden");let c=Date.now(),d=ue.get(a);if(d&&c>d.expiresAt)ue.delete(a),d=void 0;if(!d){let m=Bun.file(a);if(!await m.exists())return t.null(404);if(m.size<=this.SMALL_FILE_THRESHOLD){let f=await m.arrayBuffer(),h=new Uint8Array(f),A=`W/"${Bun.hash(h).toString(16)}"`;d={buffer:h,contentType:m.type||"application/octet-stream",etag:A,expiresAt:c+this.CACHE_TTL},ue.set(a,d)}}if(d){let m=e.headers.get("If-None-Match"),f={ETag:d.etag,"Cache-Control":`public, max-age=${this.CACHE_TTL/1000}, must-revalidate`};if(m===d.etag)return new Response(null,{status:304,headers:f});return t.file(d.buffer,{type:d.contentType,size:d.buffer.length},f)}let u=Bun.file(a);if(await u.exists())return t.file(u);return t.null(404)}}class I{request;server;fileDetector;params={};_url;_query;_cookies;_formData;_json;_txt;constructor(e,t,r=le){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 ft={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 l(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??ft[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:mt,deflateSync:pt,zstdCompressSync:ht}=globalThis.Bun;import{brotliCompressSync as gt}from"zlib";var yt=["br","gzip","deflate","zstd"];class P{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 d of o){let u=d.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:mt(r),encoding:"gzip"};case"deflate":return{payload:pt(r),encoding:"deflate"};case"br":return{payload:gt(r),encoding:"br"};case"zstd":return{payload:ht(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 K{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 fe{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:d,end:u,fn:m}=t(n);if(u){this.close();try{e.close()}catch(f){}return}if(o)e.enqueue(K.retry(Math.max(o,2000)));if(a)e.enqueue(K.id(a));if(d)e.enqueue(K.event(d));if(e.enqueue(K.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)}}}import"reflect-metadata";var bt=(e)=>typeof e==="string";var wt=(e)=>Array.isArray(e);var Tt=(e)=>Fe(e)&&typeof e==="object",St=(e)=>Fe(e)&&Tt(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null);var je=(e)=>St(e);var Fe=(e)=>e!==null;var k=(e)=>wt(e)?e:[e];function me(e=3){let t=((Error().stack?.split(`
|
|
8
|
+
`)??[])[e]||"").match(/at\s+([^(]+)\s*\(/);return(t?t[1].split(".").pop()?.trim():"?")??"?"}class He{name;constructor(e){this.name=e}log=(...e)=>{let t=me(3);console.log(`[${this.name}.${t}]`,...e)};set i(e){let t=me(3);console.log(`[${this.name}.${t}]`,...k(e))}}class pe{static logger=(e)=>new He(bt(e)?e:e.constructor.name);static set f(e){let t=me();console.log(`[${t}]`,...k(e))}static set i(e){console.info(...k(e))}static set e(e){console.error(...k(e))}static set w(e){console.warn(...k(e))}static set d(e){let t=new Date().toLocaleTimeString();console.log(...k(e),`@ ${t}`)}static get d(){let e=new Date().toLocaleTimeString();console.log(`@ ${e}`);return}}class b{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=b.getContextKey(e,i),o=r(s);if(i==="class"||i==="method"||i==="getter"||i==="setter")new b(a,n).push(o);else s.addInitializer(function(){new b(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=b.getContextKey(e,i);if(i==="class"||i==="method"||i==="getter"||i==="setter")for(let o of r)new b(a,n).push(o);else s.addInitializer(function(){for(let o of r)new b(a,this,s.name).push(o)});return n}}}class q{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(P.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 D?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=P.toUint8(e),{payload:n,encoding:s}=P.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(je(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 m=e,f={...a};if(this._encoding&&this._encoding!=="none")try{let h=n?new Uint8Array(await e.arrayBuffer()):e,{payload:A,encoding:v}=P.handle(h,this._encoding);if(m=A,v)f["Content-Encoding"]=v;f["Content-Length"]=A.length.toString()}catch(h){return this.error(500,"Error reading file")}else f["Content-Length"]=s.toString();return new Response(m,{status:this._code,headers:f})}let c=o.replace(/bytes=/,"").split("-"),d=parseInt(c[0],10),u=c[1]?parseInt(c[1],10):s-1;if(d>=s||u>=s)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`,...this._headers}});return new Response(e.slice(d,u+1),{status:206,headers:{...a,"Content-Range":`bytes ${d}-${u}/${s}`,"Content-Length":(u-d+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 fe,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 We=["GET","POST","PUT","HEAD","DELETE","PATCH","EVENT","OPTIONS"];class he{options({res:e,methods:t}){let r=[...new Set([...t])];return e.header({Allow:r.join(", ")}).null(204)}}var U="rossa:route";function ge(e="/"){return b.decorateClass(U,()=>({basePath:e}))}function Be(e="/"){return b.decorateClass(U,()=>({basePath:e,wss:!0}))}import"reflect-metadata";var j="rossa:guard";function Et(...e){return b.decorateArray(j,["class","method"],e)}function Ke(e,t){let r=b.get.method(j,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 z{globalBasePath;httpRoutes=[];wssRoutes=[];globalGuards=[];registeredSignatures=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)}compiler(e){let t=[],r=e.replace(/:([a-zA-Z0-9_]+)/g,(n,s)=>(t.push(s),"([^/]+)"));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 wss route collision detected: ${e} in controller ${t}`);this.registeredSignatures.add(n)}registerWSS(...e){for(let t of e){let r=b.get.class(U,t),n=b.get.class(j,t);if(!r.length)return;for(let s of r){let i=s.basePath??"/",a=`${this.globalBasePath}${i}`.replace(/\/+/g,"/").replace(/\/$/,"")||"/";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=b.get.class(U,t);if(!r.length)return;let n={};for(let c of r){let d=c.basePath??"/",u=`${this.globalBasePath}${d}`.replace(/\/+/g,"/").replace(/\/$/,"")||"/";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=b.get.class(j,t),a=new Set,o={};for(let c of We){let d=s[c.toLowerCase()];if(typeof d!=="function")continue;if(o[c]={guards:Ke(i,d),handler:d.bind(s)},c!=="EVENT")a.add(c)}for(let[c,d]of Object.entries(n))this.httpRoutes.push({path:c,...d,methods:o,methodKeys:[...a]})}}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"))}}import{dirname as xt,isAbsolute as ze,join as Ge}from"path";class G{ws;id;constructor(e,t){this.ws=e;this.id=E.register(e,t)}subscribe(e){E.subscribe(this.id,e)}unsubscribe(e){E.unsubscribe(this.id,e)}cleanup(){E.cleanup(this.id)}unregister(){E.unregister(this.id)}setAdmin(e){E.setAdmin(this.id,e)}isAdmin(e){return E.isAdmin(this.id,e)}isSubscribed(e){return E.isSubscribed(this.id,e)}setTopicConfig(e,t={}){E.setTopicConfig(e,t)}broadcast(e,t){return E.broadcastToTopics(this.ws,e,t)}}class V{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 E=new V;function ye(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 G(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(Rt(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 wn=ye();function Rt(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}}class Ve extends z{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 de(this.clientRoot,e.fileExtensions||[])}get getClientRoot(){let e;if(ze(this.options.clientPath))e=this.options.clientPath;else{let t=ze(this.options.dirPath)?this.options.dirPath:Ge(process.cwd(),this.options.dirPath),r=xt(t);e=Ge(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 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:d}=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 L(new q({encoding:t??this.options.Encoding},new I(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,d=Bun.serve({...s,port:c,fetch:async(u,m)=>{let f=new L(new q({encoding:this.options.Encoding},new I(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,...ye(i)}});if(o)o(c);else{let u=s.tls?"https":"http";pe.i=`${u}://localhost:${d.port??c}`}return d}errorHandler(e,t){if(this.options.logError)console.error(t.message);return e.null(500)}}class R{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 Ct={text:()=>new R("text"),int:()=>new R("integer"),bigint:()=>new R("bigint"),boolean:()=>new R("boolean"),json:()=>new R("json"),timestamp:()=>new R("timestamp"),serial:()=>new R("serial"),numeric:(e=10,t=2)=>new R("numeric",e,t)};class O extends Error{constructor(e){super(e);this.name="DatabaseError"}}class J extends O{constructor(e){super(e);this.name="UniqueConstraintError"}}class Y extends O{constructor(e="Cannot modify a record referenced by another table."){super(e);this.name="ForeignKeyError"}}var{sql:N}=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 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.map(g).join(".")}function S(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 be(e){return N.unsafe(T(e.table))}function Je(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 Ye(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 At(e,t){return[g(e),Ye(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",Je(t).trim()].filter(Boolean).join(" ")}async function Ot(e,t){let[r,n]=S(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 we={name:"postgres",quoteIdentifier:g,quoteTable:T,normalizeColumnName(e){return e},buildColumn:At,buildColumnType(e){return[Ye(e),e.primaryKey?"PRIMARY KEY":"",e.required?"NOT NULL":"",e.isUnique?"UNIQUE":"",Je(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`${N.unsafe(t.createSQL(this))}`},getColumns:Ot,async addColumn(e,t,r,n){await e`${N.unsafe(`ALTER TABLE ${T(t.table)} ADD COLUMN ${g(r)} ${n}`)}`},async dropColumn(e,t,r){await e`${N.unsafe(`ALTER TABLE ${T(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 ${be(t)} ${N(r)}
|
|
19
|
+
ON CONFLICT (${N.unsafe(g(String(n)))})
|
|
20
|
+
DO UPDATE SET ${N(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`${N.unsafe(`DROP TABLE ${T(t.table)}`)}`},async truncateTable(e,t){await e`${N.unsafe(`TRUNCATE TABLE ${T(t.table)} RESTART IDENTITY`)}`},async getTableStats(e,t){let[r,n]=S(t.table),[s]=await e`
|
|
26
|
+
SELECT COUNT(*) AS total FROM ${be(t)}
|
|
27
|
+
`,i=T(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]=S(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]=S(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 ${be(t)}
|
|
49
|
+
LIMIT ${r} OFFSET ${n}
|
|
50
|
+
`},async optimize(e,t){await e.unsafe(`VACUUM ANALYZE ${T(t.table)}`)}};var{sql:w}=globalThis.Bun;function Te(e){return w.unsafe(T(e.table))}function Nt(e){return e.reduce((t,r,n)=>n===0?r:w`${t}, ${r}`)}function Qe(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 Xe(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 vt(e,t){return[g(e),Xe(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",Qe(t).trim()].filter(Boolean).join(" ")}async function Dt(e,t){let[r,n]=S(t.table),s=r?`${g(r)}.`:"";return(await e`${w.unsafe(`PRAGMA ${s}table_info(${g(n)})`)}`).map((a)=>a.name)}var Se={name:"sqlite",quoteIdentifier:g,quoteTable:T,normalizeColumnName(e){return e.toLowerCase()},buildColumn:vt,buildColumnType(e){return[Xe(e),e.primaryKey?"PRIMARY KEY":"",e.required?"NOT NULL":"",e.isUnique?"UNIQUE":"",Qe(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`${w.unsafe(t.createSQL(this))}`},getColumns:Dt,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`${w.unsafe(`ALTER TABLE ${T(t.table)} ADD COLUMN ${g(r)} ${n}`)}`},async dropColumn(e,t,r){await e`${w.unsafe(`ALTER TABLE ${T(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=Nt(o.map((u)=>w`${w.unsafe(g(u))} = excluded.${w.unsafe(g(u))}`)),[d]=await e`
|
|
51
|
+
INSERT INTO ${Te(t)} ${w(r)}
|
|
52
|
+
ON CONFLICT (${w.unsafe(g(i))})
|
|
53
|
+
DO UPDATE SET ${c}
|
|
54
|
+
RETURNING *
|
|
55
|
+
`;return d},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`${w.unsafe(`DROP TABLE ${T(t.table)}`)}`},async truncateTable(e,t){await e.begin(async(r)=>{await r`${w.unsafe(`DELETE FROM ${T(t.table)}`)}`;let[n,s]=S(t.table),i=g(n??"main"),[a]=await r`${w.unsafe(`SELECT name FROM ${i}.sqlite_schema WHERE type = 'table' AND name = 'sqlite_sequence'`)}`;if(a)await r`${w.unsafe(`DELETE FROM ${i}.sqlite_sequence WHERE name = `)}${s}`})},async getTableStats(e,t){let[r,n]=S(t.table),[s]=await e`
|
|
59
|
+
SELECT COUNT(*) AS total FROM ${Te(t)}
|
|
60
|
+
`,i=r?`${g(r)}.`:"",a=await e`${w.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]=S(t.table),s=r?`${g(r)}.`:"";return e`${w.unsafe(`PRAGMA ${s}index_list(${g(n)})`)}`},async getTableSchema(e,t){let[r,n]=S(t.table),s=r?`${g(r)}.`:"";return e`${w.unsafe(`PRAGMA ${s}table_info(${g(n)})`)}`},async getTableData(e,t,r,n){return await e`
|
|
61
|
+
SELECT * FROM ${Te(t)}
|
|
62
|
+
LIMIT ${r} OFFSET ${n}
|
|
63
|
+
`},async optimize(e){await e`${w.unsafe("VACUUM")}`}};var{sql:x}=globalThis.Bun;var C=(e)=>{if(!e||e.includes("\x00"))throw Error("SQL identifiers must be non-empty and cannot contain NUL.");return"`"+e.replace(/`/g,"``")+"`"},M=(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(C).join(".")},Q=(e)=>x.unsafe(M(e.table));function Ze(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 et(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 Mt(e,t){return[C(e),Ze(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",et(t).trim()].filter(Boolean).join(" ")}async function $t(e,t){let[r,n]=S(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 tt(e){return{name:e,quoteIdentifier:C,quoteTable:M,normalizeColumnName(t){return t.toLowerCase()},buildColumn:Mt,buildColumnType(t){return[Ze(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",et(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`${x.unsafe(r.createSQL(this))}`},getColumns:$t,async addColumn(t,r,n,s){await t`${x.unsafe(`ALTER TABLE ${M(r.table)} ADD COLUMN ${C(n)} ${s}`)}`},async dropColumn(t,r,n){await t`${x.unsafe(`ALTER TABLE ${M(r.table)} DROP COLUMN ${C(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)=>`${C(u)} = VALUES(${C(u)})`).join(", "):`${C(String(s))} = VALUES(${C(String(s))})`;await t`INSERT INTO ${Q(r)} ${x(n)} ON DUPLICATE KEY UPDATE ${x.unsafe(o)}`;let c=n[s];if(c===void 0)return;let[d]=await t`SELECT * FROM ${Q(r)} WHERE ${x.unsafe(C(String(s)))} = ${c} LIMIT 1`;return d},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`${x.unsafe(`DROP TABLE ${M(r.table)}`)}`},async truncateTable(t,r){await t`${x.unsafe(`TRUNCATE TABLE ${M(r.table)}`)}`},async getTableStats(t,r){let[n,s]=S(r.table),[i]=await t`SELECT COUNT(*) AS total FROM ${Q(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]=S(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]=S(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 ${Q(r)} LIMIT ${n} OFFSET ${s}`},async optimize(t,r){await t`${x.unsafe(`OPTIMIZE TABLE ${M(r.table)}`)}`}}}var Ee=tt("mysql"),Re=tt("mariadb");var _t={sqlite:Se,postgres:we,mysql:Ee,mariadb:Re};function X(e){let t=_t[e];if(!t)throw Error(`Unsupported database dialect: ${e}`);return t}class F{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 F(e,t.withDialect(X("sqlite")))}static postgres(e,t){return new F(e,t.withDialect(X("postgres")))}}var{sql:y}=globalThis.Bun;var Lt=new Set(["=","!=","<","<=",">",">=","LIKE","ILIKE","IS","IS NOT","IN","NOT IN"]);class xe{db;schema;constructor(e,t){this.db=e;this.schema=t}get dialect(){return this.schema.dialect}get inspect(){return new F(this.db,this.schema)}withContext(e){return new xe(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 y.unsafe(this.dialect.quoteIdentifier(e))}get table(){return y.unsafe(this.dialect.quoteTable(this.schema.table))}joinSql(e,t){if(e.length===0)return y``;return e.slice(1).reduce((r,n)=>y`${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(!Lt.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"?y`1=0`:y`1=1`;let o=this.joinSql(a.map((c)=>y`${c}`),y`, `);return y`${this.identifier(r)} ${y.unsafe(i)} (${o})`}if(a===null&&(i==="="||i==="IS"))return y`${this.identifier(r)} IS NULL`;if(a===null&&(i==="!="||i==="IS NOT"))return y`${this.identifier(r)} IS NOT NULL`;return y`${this.identifier(r)} ${y.unsafe(i)} ${a}`}return n===null?y`${this.identifier(r)} IS NULL`:y`${this.identifier(r)} = ${n}`});return t.length?this.joinSql(t,y` AND `):y`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} ${y(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} ${y(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 O("Refusing to update rows without a WHERE condition.");if(Object.keys(t).length===0)throw new O("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 ${y(t)} WHERE ${this.buildWhere(e)}`,n.map((s)=>({...s,...t}))});return await this.db`
|
|
68
|
+
UPDATE ${this.table} SET ${y(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 O("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 J(`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 Y("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 O("The database is busy. Please retry the operation.");throw e}}class Ce{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 Ce(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,d)=>e(c,d,r,a);if(s)o._middlewareId=s,o.id=s;return o}}var ps=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 l(n);return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),hs=p(async(e,t,r,n)=>{let s=e.req.headers.get("x-api-key");if(!s)return l({code:401,message:"Missing api key"});if(!await r(e,s))return l({code:401,message:"Invalid API Key."});return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),gs=p(async(e,t,r,n)=>{for(let[s,i]of Object.entries(r)){let a=e.req.headers.get(s);if(!a)return l({code:401,message:`Missing ${s} header.`});if(!await i(e,a))return l({code:401,message:"Invalid."})}return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),ys=p(async(e,t,r,n)=>{if(!r||!await r(e))return l(n);return t()},{id:"authorize-guard",code:403,message:"Forbidden"});var _=new Map,It=1000,Pt=new Set(["no-cache","no-store"]),kt=new Set(["private","no-store","no-cache"]),qt=/(?:^|,)\s*(?:max-age|s-maxage)\s*=\s*["']?0(?:\s|,|$)/i;function rt(e,t){return e?.split(",").some((r)=>t.has(r.trim().split("=",1)[0].toLowerCase()))??!1}function Ut(e){let t=e.req.headers;if(t.has("authorization")||t.has("cookie")||t.has("range"))return!0;return rt(t.get("cache-control"),Pt)||t.get("pragma")?.toLowerCase().includes("no-cache")===!0}function jt(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")&&!rt(t,kt)&&!qt.test(t)}var Ts=p(async(e,t,r)=>{if(e.req.method!=="GET"||Ut(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 _)if(m.expires<=s)_.delete(u);let i=e.req.url.href,a=_.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(!jt(o))return o;let c=o.clone(),d=new Uint8Array(await c.arrayBuffer());if(_.size>=It){let u=_.keys().next().value;if(u!==void 0)_.delete(u)}return _.set(i,{expires:s+n,body:d,headers:new Headers(c.headers),status:c.status,statusText:c.statusText}),o});var xs=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(nt):[nt(r)];a=i!==null&&o.includes(i)}if(!a)return l(n);return t()},{id:"content-type",code:415,message:"Unsupported Media Type. The request Content-Type is invalid or missing."});function nt(e){return e.split(";")[0].trim().toLowerCase()}var Ns=p(async(e,t,r,n)=>{if(!e.req.cookies.has(r))return l(n);return await t()},{id:"cookie-checker",code:401,message:"Required cookie is missing."});function Ae(e){if(!e)return;return Array.isArray(e)?e.join(", "):e}var $s=p(async(e,t,r,n)=>{let{origin:s="*",allowHeaders:i="*",methods:a,exposeHeaders:o,credentials:c=!1,maxAge:d=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 l(n);let f={};if(m)f["Access-Control-Allow-Origin"]=m;if(c)f["Access-Control-Allow-Credentials"]="true";if(o){let h=Ae(o);if(h)f["Access-Control-Expose-Headers"]=h}if(i){let h=Ae(i);if(h)f["Access-Control-Allow-Headers"]=h}if(a){let h=Ae(a);if(h)f["Access-Control-Allow-Methods"]=h}if(d!==void 0)f["Access-Control-Max-Age"]=d.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 Ps=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 l(n)}return await t()},{id:"csrf-guard",code:403,message:"CSRF Token Validation Failed"});var Us=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 Ws=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 l({code:401,message:`Missing required ${a} property.`})}else for(let[a,o]of Object.entries(r)){let c=s(a);if(!c)return l({code:401,message:`Missing required ${a} property.`});if(!o(e,a,c))return l(n)}}return await t()},{code:400,message:"Required headers are missing or invalid."});var Z=(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 ee(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}class te{rules=[];constructor(e){this.compileRules(e)}test(e){let t=e.split(",")[0]?.trim()??"",r=ee(t);if(r===null)return!1;return this.rules.some((n)=>n(t,r))}compileRules(e){for(let t of e){let r=t.trim();if(r.includes("/"))this.rules.push(this.compileCidr(r));else if(r.includes("*"))this.rules.push(this.compileWildcard(r));else{let n=ee(r);if(n===null)throw RangeError(`Invalid IPv4 rule: ${t}`);this.rules.push((s,i)=>i===n)}}}compileCidr(e){let t=e.match(/^([^/]+)\/(0|[1-9]\d?)$/);if(!t)throw RangeError(`Invalid IPv4 CIDR rule: ${e}`);let r=ee(t[1]),n=Number(t[2]);if(r===null||n>32)throw RangeError(`Invalid IPv4 CIDR rule: ${e}`);let s=n===0?0:4294967295<<32-n>>>0,i=(r&s)>>>0;return(a,o)=>(o&s)>>>0===i}compileWildcard(e){let t=e.split(".");if(t.length!==4||t.some((r)=>r!=="*"&&ee(`0.0.0.${r}`)===null))throw RangeError(`Invalid IPv4 wildcard rule: ${e}`);return(r)=>r.split(".").every((n,s)=>{let i=t[s];return i==="*"||n===i})}}var Qs=p(async(e,t,r,n)=>{let s=Z(e),{blacklist:i=[],whitelist:a=[]}=r??{};if(i.length){if(new te(i).test(s))return l(n)}if(a.length){if(!new te(a).test(s))return l(n)}return await t()},{id:"ip-filter",code:403,message:"Forbidden"});var Ft=["POST","PUT","PATCH"],Ht=1048576,ti=p(async(e,t,r,n)=>{if(!Ft.includes(e.req.method.toUpperCase()))return await t();if(e.req.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json")return l({code:415,message:"Content-Type must be application/json"});let i=n.maxSize,a=typeof i==="number"&&i>0?i:Ht,o=e.req.headers.get("content-length");if(o!==null){if(!/^\d+$/.test(o))return l({code:400,message:"Invalid Content-Length header"});let f=Number(o);if(!Number.isSafeInteger(f)||f<0)return l({code:400,message:"Invalid Content-Length header"});if(f>a)return l({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`})}let c="";try{c=await e.req.text()}catch{return l({code:400,message:"Failed to read request stream"})}if(new TextEncoder().encode(c).byteLength>a)return l({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`});if(!c||c.trim().length===0)return l({code:400,message:"Request body cannot be empty"});let d;try{d=JSON.parse(c)}catch(f){return l({code:400,message:`Invalid JSON syntax: ${f.message}`})}if(typeof d!=="object"||d===null)return l({code:400,message:"JSON payload must be a valid JSON object or array"});let{errors:u,processedData:m}=r.validate(d);if(u.length>0)return l({...n,message:`Validation failed: ${u.join(", ")}`});return e.req._json=m,await t()},{id:"json-validator",code:400}),ri=p(async(e,t,r)=>{let n=await e.req.json();if(!n||typeof n!=="object"||Array.isArray(n))return l({code:400,message:"JSON body must be an object"});let s=r.filter((i)=>!Object.hasOwn(n,i));if(s.length>0)return l({code:400,message:`Missing required fields: ${s.join(", ")}`});return e.body=n,await t()},{id:"require-keys",code:400});var ai=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 l(n);let a=r.verify(i[1]);if(!a)return l(n);return e.jwtData=a,await t()},{id:"jwt-auth-guard",code:401,message:"Unauthorized Access"}),oi=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 l(n);let i=await r.consume(s);if(!i)return l(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 li=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()}),di=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 H(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 yi=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=H(n)}catch{return l({code:400,message:"Invalid multipart form data"})}return t()},{id:"multipart-parser",code:400,message:"Invalid multipart form data"});class Oe{schema={};rules={};defaults={};string(e,t){if(this.schema[e]="string",t!==void 0)this.defaults[e]=t;return this}number(e,t){if(this.schema[e]="number",t!==void 0)this.defaults[e]=t;return this}boolean(e,t){if(this.schema[e]="boolean",t!==void 0)this.defaults[e]=t;return this}min(e,t){return this.noKey(e,"min"),this.addRule(e,(r)=>(this.noBool(r,"min"),(typeof r==="string"?r.length:r)>=t),`must have at least ${t} ${typeof t==="number"?"characters/value":""}`),this}max(e,t){return this.noKey(e,"max"),this.addRule(e,(r)=>(this.noBool(r,"max"),(typeof r==="string"?r.length:r)<=t),`must have at most ${t} ${typeof t==="number"?"characters/value":""}`),this}email(e){let t=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return this.addRule(e,(r)=>typeof r==="string"&&t.test(r),"must be a valid email"),this}addRule(e,t,r){if(!this.rules[e])this.rules[e]=[];this.rules[e].push({fn:t,message:r})}noBool(e,t){if(typeof e==="boolean")throw Error(`Can't use ${t} with Boolean`)}noKey(e,t){if(!this.schema[e])throw Error(`Can't use ${t} with missing key: ${String(e)}`)}validate(e){if(Array.isArray(e)){let t=[],r=[];return e.forEach((n,s)=>{let{errors:i,processedData:a}=this.validateObject(n);i.forEach((o)=>t.push(`[Item ${s}] ${o}`)),r.push(a)}),{errors:t,processedData:r}}return this.validateObject(e)}validateObject(e){let t=[],r={...e};for(let[n,s]of Object.entries(this.schema)){if(!(n in r))if(n in this.defaults)r[n]=this.defaults[n];else{t.push(`Missing field: '${n}'`);continue}if(typeof r[n]!==s){t.push(`Invalid type for '${n}': Expected ${s}, got ${typeof r[n]}`);continue}if(this.rules[n]){for(let i of this.rules[n])if(!i.fn(r[n]))t.push(`'${n}' ${i.message}`)}}return{errors:t,processedData:r}}}function Wt(){return new Oe}function Ne(e,t){let r=t.schema,n={...e};for(let[s,i]of Object.entries(r)){if(!(s in e)||e[s]===void 0)continue;let a=e[s];if(i==="number"&&typeof a==="string"){let o=Number(a);if(Number.isFinite(o)&&a.trim()!=="")n[s]=o}else if(i==="boolean"&&typeof a==="string"){if(a.toLowerCase()==="true"||a==="1")n[s]=!0;if(a.toLowerCase()==="false"||a==="0")n[s]=!1}}return n}var xi=p(async(e,t,r,n)=>{let s=r;if(!s||typeof s.validate!=="function")return l({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 l({code:n.code??400,message:"Malformed URL structure."})}let a=Object.create(null);i.searchParams.forEach((u,m)=>{a[m]=u});let o=Ne(a,s),{errors:c,processedData:d}=s.validate(o);if(c.length>0)return l({code:n.code??400,message:`Query Validation Error: ${c.join("; ")}`});return e.query=d,await t()},{id:"query-validator",code:400,message:"Query validation failed"}),Ci=p(async(e,t,r,n)=>{let s=r;if(!s||typeof s.validate!=="function")return l({code:500,message:"Framework Error: Missing schema in validateForm guard."});let i;try{let d=await e.req.form();i=H(d)}catch{return l({code:n.code??400,message:"Invalid or malformed form payload."})}let a=Ne(i,s),{errors:o,processedData:c}=s.validate(a);if(o.length>0)return l({code:n.code??400,message:`Form Validation Error: ${o.join("; ")}`});return e.form=c,await t()},{id:"form-validator",code:400,message:"Form validation failed"});var st=new Map;function it(e,t,r){let n=Date.now(),s=st.get(e);if(!s||s.reset<n){let i=n+r;return st.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 $i=p(async(e,t,r,n)=>{let{max:s=100,windowMs:i=60000,expose:a=!0}=r||{},o=Z(e),c=e.req.method,d=`rate_${o}_${c}_${new URL(e.req.url).pathname}`,{allowed:u,remaining:m,resetTime:f}=it(d,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 v=Math.max(1,Math.ceil((f-Date.now())/1000));h["Retry-After"]=v.toString()}return l({...n,headers:h})}let A=await t();if(a)Object.entries(h).forEach(([v,re])=>{A.headers.set(v,re)});return A},{id:"rate-limiter",code:429,message:"Too Many Requests"});function Bt(e){return e.replace(/[&<>"']/g,(t)=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function W(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(W(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]=W(i,t,r);return n}var Ii=p(async(e,t,r)=>{let n=r?.sanitizeString??Bt;if(r?.query!==!1)e.query=W(e.query,n);if(r?.form!==!1)e.form=W(e.form,n);if(r?.body!==!1){if(e.body!==void 0)e.body=W(e.body,n);let s=e.req._json;if(s!==void 0)e.req._json=W(s,n)}return t()},{id:"sanitize-guard"});function Kt(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 qi=p(async(e,t,r)=>{let n=await t();return Kt(n,r??{})},{id:"security-headers"});var Fi=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"});var Bi=p(async(e,t)=>{if(!e.req.isFile||!["GET","HEAD"].includes(e.req.method))return t();let r=await e.res.fileServer();if(e.req.method!=="HEAD")return r;return new Response(null,{status:r.status,statusText:r.statusText,headers:r.headers})},{id:"static-files"});var Vi=p(async(e,t,r,n)=>{let s,i=new Promise((a)=>{s=setTimeout(()=>a(l(n)),r)});try{return await Promise.race([t(),i])}finally{if(s)clearTimeout(s)}},{id:"timeout-guard",code:408,message:"Request Timeout"});var zt=2048,Gt=1024,Xi=p(async(e,t,r,n)=>{let s=typeof r==="number"?{maxUrlLength:r}:r||{},i=s.maxUrlLength??zt,a=s.maxQueryLength??Gt,o;try{o=typeof e.req.url==="string"?new URL(e.req.url,"http://localhost"):e.req.url}catch{return l({code:400,message:"Malformed URL structure."})}let c=o.href;if(c.length>i)return l({code:414,message:`URI Too Long. Exceeds limit of ${i} characters.`});if((o.search.startsWith("?")?o.search.slice(1):o.search).length>a)return l({code:414,message:`Query string too long. Exceeds limit of ${a} characters.`});if(s.sanitizePaths!==!1){let f=c;try{let h="";while(f!==h&&f.includes("%"))h=f,f=decodeURIComponent(f)}catch{return l({code:400,message:"Malformed percent-encoding in URL."})}if(f.includes("\x00"))return l({code:400,message:"Null byte injection detected in URL."});if(f.includes("../")||f.includes("..\\")||f.includes("/.."))return l({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 l({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 l({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 l({code:n.code??400,message:`Forbidden query parameter: '${h}'`})}if(s.patterns)for(let[f,h]of Object.entries(s.patterns)){let A=u.getAll(f);for(let v of A){h.lastIndex=0;let re=h.test(v);if(h.lastIndex=0,!re)return l({code:n.code??400,message:`Invalid format for query parameter '${f}'.`})}}}return await t()},{id:"url-validator",code:400,message:"URL validation failed"});var na=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=H(n)}catch{return l({code:400,message:"Invalid URL-encoded form data"})}return t()},{id:"urlencoded-parser",code:400,message:"Invalid URL-encoded form data"});import{createHmac as at,timingSafeEqual as Vt}from"crypto";class ve{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},i=Buffer.from(JSON.stringify(r)).toString("base64url"),a=Buffer.from(JSON.stringify(s)).toString("base64url"),o=`${i}.${a}`,c=at("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=at("sha256",this.secretKey).update(i).digest("base64url"),c=Buffer.from(o),d=Buffer.from(s||"");if(c.length!==d.length||!Vt(c,d))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 ot{refreshTokens;config;engine;constructor(e,t,r={}){this.refreshTokens=e;this.engine=new ve(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 B{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 Xt}from"crypto";import{createHmac as Jt,createHash as Yt,timingSafeEqual as Qt}from"crypto";class De{salt;key;constructor(e){this.salt=e;this.key=Yt("sha256").update(e).digest()}getSignature(e){return Jt("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 Qt(r,n)}}class Me{signer;constructor(e){this.signer=new De(e)}generate(e=21){let t=Xt(e).toString("base64url");return this.signer.sign(t)}}class ct extends Me{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:d=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:d,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 B(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 B(e??this.generate(),{},r,!0,t).session}get readonly(){return new B(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 ut{contextData={};data={};constructor(){}open(){}message({text:e,json:t,topic:r}){}drain(){}close(e,t){}set send(e){this.ws.send(e)}}class $e{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=$e.registry.get(e);return i?i[r]:void 0}}})}}var Zt=$e;class lt{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 er=lt;export{R as Column,Ht as DEFAULT_MAX_SIZE,O as DatabaseError,F as DbInspector,xe as DbRepository,Zt as Field,Y as ForeignKeyError,ot as JWTAuthService,he as Methods,I as Req,q as Res,Ve as Rossa,z as RouterManager,Ce as Schema,Oe as SchemaBuilder,er as Scope,B as ServerSide,ct as SessionAuthInterface,J as UniqueConstraintError,E as WSSMAN,ut as Websocket,V as WssManager,hs as apiKey,gs as auth,ps as authBearer,ys as authorize,xs as contentType,Ns as cookies,$s as cors,p as createGuard,Ps as csrf,L as ctx,Us as errorHandler,X as getDialect,Ws as header,Qs as ipFilter,ti as json,ai as jwtAuth,oi as jwtRefresh,ri as keys,li as logger,di as loggerFN,Re as mariadbDialect,yi as multipart,Ee as mysqlDialect,we as postgresDialect,$i as rateLimit,ge as route,Ii as sanitize,qi as security,l as sendError,Fi as session,Ts as smartCache,Se as sqliteDialect,Bi as staticFiles,G as subManager,Ct as t,Vi as timeout,na as urlencoded,Et as use,Ci as validateForm,xi as validateQuery,Xi as validateUrl,Be as wss,Wt as z};
|
package/package.json
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rossa",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.0.6",
|
|
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,9 @@
|
|
|
13
20
|
"test": "test"
|
|
14
21
|
},
|
|
15
22
|
"scripts": {
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
"
|
|
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"
|
|
22
26
|
},
|
|
23
27
|
"keywords": [
|
|
24
28
|
"ts",
|
|
@@ -32,19 +36,14 @@
|
|
|
32
36
|
"url": "https://github.com/MARKjotep/rossa/issues"
|
|
33
37
|
},
|
|
34
38
|
"homepage": "https://github.com/MARKjotep/rossa#readme",
|
|
35
|
-
"dependencies": {
|
|
36
|
-
"jsonwebtoken": "^9.0.2",
|
|
37
|
-
"authored": "latest",
|
|
38
|
-
"dotenv": "^16.6.1"
|
|
39
|
-
},
|
|
39
|
+
"dependencies": {},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@
|
|
42
|
-
"@
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"typescript": "^5.7.2"
|
|
41
|
+
"@ohmyqt/oven": "link:@ohmyqt/oven",
|
|
42
|
+
"@ohmyqt/u": "link:@ohmyqt/u",
|
|
43
|
+
"@types/bun": "^1.4.4",
|
|
44
|
+
"fake-indexeddb": "^6.2.8",
|
|
45
|
+
"reflect-metadata": "^0.2.2",
|
|
46
|
+
"typescript": "^5.9.3"
|
|
48
47
|
},
|
|
49
48
|
"type": "module"
|
|
50
49
|
}
|