balda 0.0.8 → 0.0.9

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/lib/index.js CHANGED
@@ -437,7 +437,7 @@ ${d}\r
437
437
  `)),p instanceof File){let h=await p.arrayBuffer();s.push(new Uint8Array(h)),s.push(r.encode(`\r
438
438
  `));}else s.push(r.encode(`${String(p)}\r
439
439
  `));}s.push(r.encode(`--${t}--\r
440
- `));let o=s.reduce((c,p)=>c+p.byteLength,0),n=new Uint8Array(o),a=0;for(let c of s)n.set(c,a),a+=c.byteLength;return n}validateOptions(e){let{body:t,formData:r,urlencoded:s}=e;if(t&&(r||s))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(s||t))throw new Error("Only one of formData, urlencoded can be provided");if(s&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var Be=new AsyncLocalStorage,Ot=i=>async(e,t,r)=>{let s={};for(let[o,n]of Object.entries(i))s[o]=n(e);Be.run(s,()=>{e.ctx=new Proxy({},{get(o,n){return Be.getStore()?.[n]},set(o,n,a){let c=Be.getStore();return c?(c[n]=a,true):false},ownKeys(){let o=Be.getStore();return o?Object.keys(o):[]},has(o,n){let a=Be.getStore();return a?n in a:false}}),r();});};var Kt=()=>async(i,e,t)=>(ne(i.method)&&(i.rawBody=await i.arrayBuffer(),Object.defineProperty(i,"body",{value:void 0,writable:true,configurable:true,enumerable:true})),t());var cs=1024,ps=6,ls=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Vt=i=>{let e=i?.threshold??cs,t=Math.max(0,Math.min(9,i?.level??ps)),r=i?.filter??ls;return async(s,o,n)=>{if(!(s.headers.get("accept-encoding")||"").includes("gzip"))return n();let p=o.send.bind(o),l=o.json.bind(o),d=o.text.bind(o),h=(m,f)=>{if(!ds(m,f,e,r))return m;let b=Zt(m);if(!b||b.length<e)return m;let q=gzipSync(b,{level:t});return o.setHeader("Content-Encoding","gzip"),o.setHeader("Content-Length",q.length.toString()),q};o.send=function(m){let f=o.headers["content-type"],b=h(m,f);return p(b)},o.json=function(m){let f=JSON.stringify(m),b=h(f,"application/json");return b!==f?(o.setHeader("Content-Type","application/json"),p(b)):l(m)},o.text=function(m){let f=h(m,"text/plain");return f!==m?(o.setHeader("Content-Type","text/plain"),p(f)):d(m)},await n();}},ds=(i,e,t,r)=>{if(!i||!e)return false;let s=Zt(i);return !s||s.length<t?false:r.some(o=>o.test(e))},Zt=i=>typeof i=="string"?Buffer.from(i,"utf-8"):Buffer.isBuffer(i)?i:i instanceof Uint8Array?Buffer.from(i):typeof i=="object"?Buffer.from(JSON.stringify(i),"utf-8"):null;var Jt=i=>{let e={secret:i?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...i?.defaults},parse:i?.parse??true,sign:i?.sign??false};return async(t,r,s)=>{if(e.parse){let o=us(t.headers.get("cookie")||"");t.cookies={};for(let[n,a]of Object.entries(o)){if(e.sign&&e.secret){let c=await gs(a,e.secret);c!==false&&(t.cookies[n]=c);continue}t.cookies[n]=a;}}r.cookie=(o,n,a)=>{Yt(r,o,n,{...e.defaults,...a},e);},r.clearCookie=(o,n)=>{ms(r,o,{...e.defaults,...n});},await s();}};function us(i){let e={};if(!i)return e;let t=i.split(";");for(let r of t){let[s,o]=r.trim().split("=");s&&o&&(e[decodeURIComponent(s)]=decodeURIComponent(o));}return e}async function Yt(i,e,t,r,s){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires&&(o+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(o+=`; Max-Age=${r.maxAge}`),r.secure&&(o+="; Secure"),r.httpOnly&&(o+="; HttpOnly"),r.sameSite&&(o+=`; SameSite=${r.sameSite}`),r.priority&&(o+=`; Priority=${r.priority}`),s.sign&&s.secret&&(o=await hs(o,s.secret));let n=i.headers["set-cookie"]||"",a=n?`${n}, ${o}`:o;i.setHeader("Set-Cookie",a);}function ms(i,e,t){let r={...t,expires:new Date(0),maxAge:0};Yt(i,e,"",r,{secret:"",sign:false});}async function hs(i,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(i),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),n=await crypto.subtle.sign("HMAC",o,s),a=new Uint8Array(n),c=Array.from(a).map(p=>p.toString(16).padStart(2,"0")).join("");return `${i}.${c}`}async function gs(i,e){let t=i.split(".");if(t.length!==2)return false;let[r,s]=t,o=new TextEncoder,n=o.encode(e),a=o.encode(r),c=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},false,["sign"]),p=await crypto.subtle.sign("HMAC",c,a),l=new Uint8Array(p),d=Array.from(l).map(h=>h.toString(16).padStart(2,"0")).join("");return s===d?r:false}var Xt=i=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...i};return async(t,r,s)=>{let o=t.headers.get("origin")||"";if(t.method==="OPTIONS")return fs(t,r,e,o,s);ys(t,r,e,o),await s();}};function fs(i,e,t,r,s){let o=er(t,r);if(!o){e.forbidden("CORS origin not allowed");return}if(tr(e,t,o),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function ys(i,e,t,r){let s=er(t,r);s&&tr(e,t,s);}function er(i,e){if(typeof i.origin=="string")return i.origin;if(Array.isArray(i.origin)){let t=i.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function tr(i,e,t){if(i.setHeader("Access-Control-Allow-Origin",t),e.credentials&&i.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;i.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;i.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;i.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&i.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function rr(i,e=""){let t=new URL(i.url),r=Object.fromEntries(i.headers.entries());return {body:i.body,query:i.query,params:i.params,cookies:i.cookies,session:i.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:i.method,ip:i.ip,headers:r,url:t.pathname,get(o){return i.headers.get(o.toLowerCase())??void 0},header(o){return i.headers.get(o.toLowerCase())??void 0},app:{},res:null,route:null,protocol:t.protocol.replace(":",""),secure:t.protocol==="https:",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:o=>i.params[o]??i.query[o],files:i.files,file:i.file,rawBody:i.rawBody}}function sr(i){return {locals:{},headersSent:false,statusCode:i.responseStatus,status(t){return i.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!i.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return i.html(t),this}return i.send(t),this},json(t){return this.headersSent=true,i.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,o=typeof t=="number"?t:302;return i.status(o).setHeader("Location",s),i.send(""),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return i.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,o]of Object.entries(t))i.setHeader(s,o);else r!==void 0&&i.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return i.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,i.send(t??""),this},write(t){return true},get(t){return i.headers[t]},getHeader(t){return i.headers[t]},removeHeader(t){return delete i.headers[t],this},append(t,r){let s=i.headers[t],o=Array.isArray(r)?r.join(", "):r;return i.setHeader(t,s?`${s}, ${o}`:o),this},cookie(t,r,s){return i.cookie?.(t,r,s),this},clearCookie(t,r){return i.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?i.setHeader("Content-Disposition",`attachment; filename="${t}"`):i.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){i.file(t);},download(t,r,s,o){let n=typeof r=="string"?r:t.split("/").pop();this.attachment(n),i.file(t);},links(t){let r=Object.entries(t).map(([s,o])=>`<${o}>; rel="${s}"`).join(", ");return i.setHeader("Link",r),this},location(t){return i.setHeader("Location",t),this},vary(t){return i.setHeader("Vary",t),this},app:{},req:null}}function Ne(i,e=""){return async(t,r,s)=>{let o=rr(t,e),n=sr(r);await new Promise((a,c)=>{let p=l=>{if(l){c(l);return}a();};try{let l=i(o,n,p);l instanceof Promise&&l.catch(c);}catch(l){c(l);}}),await s();}}function vs(i,e=""){return async(t,r)=>{let s=rr(t,e),o=sr(r);await i(s,o,()=>{});}}function rt(i,e){let t=jt(i),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let s of r)or(s,t);}function or(i,e){if(i.route){let t=jt(e+i.route.path),r=Object.keys(i.route.methods).filter(s=>i.route.methods[s]);for(let s of r){let o=i.route.stack.map(n=>n.handle);ws(s.toUpperCase(),t,o,e);}return}if(i.handle&&typeof i.handle=="function"){let t=i.path||"",r=jt(e+t),s=i.handle.stack;if(s&&Array.isArray(s)){for(let c of s)or(c,r);return}let o=r==="/"?"/*":`${r}/*`,n=Ne(i.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)C.addOrUpdate(c,o,[n],async()=>{},{excludeFromSwagger:true});}}function ws(i,e,t,r){let s=t.slice(0,-1).map(a=>Ne(a,r)),o=t[t.length-1],n=vs(o,r);C.addOrUpdate(i,e,s,n,{excludeFromSwagger:true});}function jt(i){let e=i.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function ir(i){return {use(e,t){if(typeof e=="string"){let o=e,n=t,a=n.stack;if(a&&Array.isArray(a)){rt(o,n);return}i.use(Ne(n,o));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){rt("/",r);return}i.use(Ne(r));}}}var st=class extends T{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};Q();var Et=class{async tmpdir(){switch(R.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},nr=new Et;var ar=1024*1024,pr=i=>async(e,t,r)=>{let s=[];try{let o=e.headers.get("content-type")??e.headers.get("Content-Type");if(!o||!o.startsWith("multipart/form-data")||!e.rawBody)return r();let n=o.match(/boundary=(.*)(;|$)/i);if(!n)return r();let a=n[1].replace(/(^\s*"?|"?\s*$)/g,""),c=new Uint8Array(e.rawBody),p=new TextEncoder().encode(`--${a}`),l=new Uint8Array([13,10,13,10]),d=[],h=(P,E,F=0)=>{e:for(let S=F;S<=P.length-E.length;S++){for(let O=0;O<E.length;O++)if(P[S+O]!==E[O])continue e;return S}return -1},m=h(c,p);for(;m!==-1&&(m+=p.length,!(c[m]===45&&c[m+1]===45));){c[m]===13&&c[m+1]===10&&(m+=2);let P=h(c,l,m);if(P===-1)break;let E=c.subarray(m,P),F=new TextDecoder().decode(E),S=P+l.length,O=h(c,p,S);if(O===-1)break;let B=O-1;c[B]===10&&B--,c[B]===13&&B--;let lt=c.subarray(S,B+1);d.push({headers:F,data:lt}),m=O;}let f=[],b={},q=Pe(i?.maxFileSize,ar)??ar;for(let P of d){let E=P.headers.split(`\r
440
+ `));let o=s.reduce((c,p)=>c+p.byteLength,0),n=new Uint8Array(o),a=0;for(let c of s)n.set(c,a),a+=c.byteLength;return n}validateOptions(e){let{body:t,formData:r,urlencoded:s}=e;if(t&&(r||s))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(s||t))throw new Error("Only one of formData, urlencoded can be provided");if(s&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var Be=new AsyncLocalStorage,Ot=i=>async(e,t,r)=>{let s={};for(let[o,n]of Object.entries(i))s[o]=n(e);Be.run(s,()=>{e.ctx=new Proxy({},{get(o,n){return Be.getStore()?.[n]},set(o,n,a){let c=Be.getStore();return c?(c[n]=a,true):false},ownKeys(){let o=Be.getStore();return o?Object.keys(o):[]},has(o,n){let a=Be.getStore();return a?n in a:false}}),r();});};var Kt=()=>async(i,e,t)=>(!ne(i.method)||i.bodyUsed||i.rawBody!==void 0||(i.rawBody=await i.arrayBuffer(),Object.defineProperty(i,"body",{value:void 0,writable:true,configurable:true,enumerable:true})),t());var cs=1024,ps=6,ls=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Vt=i=>{let e=i?.threshold??cs,t=Math.max(0,Math.min(9,i?.level??ps)),r=i?.filter??ls;return async(s,o,n)=>{if(!(s.headers.get("accept-encoding")||"").includes("gzip"))return n();let p=o.send.bind(o),l=o.json.bind(o),d=o.text.bind(o),h=(m,f)=>{if(!ds(m,f,e,r))return m;let b=Zt(m);if(!b||b.length<e)return m;let q=gzipSync(b,{level:t});return o.setHeader("Content-Encoding","gzip"),o.setHeader("Content-Length",q.length.toString()),q};o.send=function(m){let f=o.headers["content-type"],b=h(m,f);return p(b)},o.json=function(m){let f=JSON.stringify(m),b=h(f,"application/json");return b!==f?(o.setHeader("Content-Type","application/json"),p(b)):l(m)},o.text=function(m){let f=h(m,"text/plain");return f!==m?(o.setHeader("Content-Type","text/plain"),p(f)):d(m)},await n();}},ds=(i,e,t,r)=>{if(!i||!e)return false;let s=Zt(i);return !s||s.length<t?false:r.some(o=>o.test(e))},Zt=i=>typeof i=="string"?Buffer.from(i,"utf-8"):Buffer.isBuffer(i)?i:i instanceof Uint8Array?Buffer.from(i):typeof i=="object"?Buffer.from(JSON.stringify(i),"utf-8"):null;var Jt=i=>{let e={secret:i?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...i?.defaults},parse:i?.parse??true,sign:i?.sign??false};return async(t,r,s)=>{if(e.parse){let o=us(t.headers.get("cookie")||"");t.cookies={};for(let[n,a]of Object.entries(o)){if(e.sign&&e.secret){let c=await gs(a,e.secret);c!==false&&(t.cookies[n]=c);continue}t.cookies[n]=a;}}r.cookie=(o,n,a)=>{Yt(r,o,n,{...e.defaults,...a},e);},r.clearCookie=(o,n)=>{ms(r,o,{...e.defaults,...n});},await s();}};function us(i){let e={};if(!i)return e;let t=i.split(";");for(let r of t){let[s,o]=r.trim().split("=");s&&o&&(e[decodeURIComponent(s)]=decodeURIComponent(o));}return e}async function Yt(i,e,t,r,s){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires&&(o+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(o+=`; Max-Age=${r.maxAge}`),r.secure&&(o+="; Secure"),r.httpOnly&&(o+="; HttpOnly"),r.sameSite&&(o+=`; SameSite=${r.sameSite}`),r.priority&&(o+=`; Priority=${r.priority}`),s.sign&&s.secret&&(o=await hs(o,s.secret));let n=i.headers["set-cookie"]||"",a=n?`${n}, ${o}`:o;i.setHeader("Set-Cookie",a);}function ms(i,e,t){let r={...t,expires:new Date(0),maxAge:0};Yt(i,e,"",r,{secret:"",sign:false});}async function hs(i,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(i),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),n=await crypto.subtle.sign("HMAC",o,s),a=new Uint8Array(n),c=Array.from(a).map(p=>p.toString(16).padStart(2,"0")).join("");return `${i}.${c}`}async function gs(i,e){let t=i.split(".");if(t.length!==2)return false;let[r,s]=t,o=new TextEncoder,n=o.encode(e),a=o.encode(r),c=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},false,["sign"]),p=await crypto.subtle.sign("HMAC",c,a),l=new Uint8Array(p),d=Array.from(l).map(h=>h.toString(16).padStart(2,"0")).join("");return s===d?r:false}var Xt=i=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...i};return async(t,r,s)=>{let o=t.headers.get("origin")||"";if(t.method==="OPTIONS")return fs(t,r,e,o,s);ys(t,r,e,o),await s();}};function fs(i,e,t,r,s){let o=er(t,r);if(!o){e.forbidden("CORS origin not allowed");return}if(tr(e,t,o),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function ys(i,e,t,r){let s=er(t,r);s&&tr(e,t,s);}function er(i,e){if(typeof i.origin=="string")return i.origin;if(Array.isArray(i.origin)){let t=i.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function tr(i,e,t){if(i.setHeader("Access-Control-Allow-Origin",t),e.credentials&&i.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;i.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;i.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;i.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&i.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function rr(i,e=""){let t=new URL(i.url),r=Object.fromEntries(i.headers.entries());return {body:i.body,query:i.query,params:i.params,cookies:i.cookies,session:i.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:i.method,ip:i.ip,headers:r,url:t.pathname,get(o){return i.headers.get(o.toLowerCase())??void 0},header(o){return i.headers.get(o.toLowerCase())??void 0},app:{},res:null,route:null,protocol:t.protocol.replace(":",""),secure:t.protocol==="https:",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:o=>i.params[o]??i.query[o],files:i.files,file:i.file,rawBody:i.rawBody}}function sr(i){return {locals:{},headersSent:false,statusCode:i.responseStatus,status(t){return i.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!i.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return i.html(t),this}return i.send(t),this},json(t){return this.headersSent=true,i.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,o=typeof t=="number"?t:302;return i.status(o).setHeader("Location",s),i.send(""),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return i.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,o]of Object.entries(t))i.setHeader(s,o);else r!==void 0&&i.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return i.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,i.send(t??""),this},write(t){return true},get(t){return i.headers[t]},getHeader(t){return i.headers[t]},removeHeader(t){return delete i.headers[t],this},append(t,r){let s=i.headers[t],o=Array.isArray(r)?r.join(", "):r;return i.setHeader(t,s?`${s}, ${o}`:o),this},cookie(t,r,s){return i.cookie?.(t,r,s),this},clearCookie(t,r){return i.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?i.setHeader("Content-Disposition",`attachment; filename="${t}"`):i.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){i.file(t);},download(t,r,s,o){let n=typeof r=="string"?r:t.split("/").pop();this.attachment(n),i.file(t);},links(t){let r=Object.entries(t).map(([s,o])=>`<${o}>; rel="${s}"`).join(", ");return i.setHeader("Link",r),this},location(t){return i.setHeader("Location",t),this},vary(t){return i.setHeader("Vary",t),this},app:{},req:null}}function Ne(i,e=""){return async(t,r,s)=>{let o=rr(t,e),n=sr(r);await new Promise((a,c)=>{let p=l=>{if(l){c(l);return}a();};try{let l=i(o,n,p);l instanceof Promise&&l.catch(c);}catch(l){c(l);}}),await s();}}function vs(i,e=""){return async(t,r)=>{let s=rr(t,e),o=sr(r);await i(s,o,()=>{});}}function rt(i,e){let t=jt(i),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let s of r)or(s,t);}function or(i,e){if(i.route){let t=jt(e+i.route.path),r=Object.keys(i.route.methods).filter(s=>i.route.methods[s]);for(let s of r){let o=i.route.stack.map(n=>n.handle);ws(s.toUpperCase(),t,o,e);}return}if(i.handle&&typeof i.handle=="function"){let t=i.path||"",r=jt(e+t),s=i.handle.stack;if(s&&Array.isArray(s)){for(let c of s)or(c,r);return}let o=r==="/"?"/*":`${r}/*`,n=Ne(i.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)C.addOrUpdate(c,o,[n],async()=>{},{excludeFromSwagger:true});}}function ws(i,e,t,r){let s=t.slice(0,-1).map(a=>Ne(a,r)),o=t[t.length-1],n=vs(o,r);C.addOrUpdate(i,e,s,n,{excludeFromSwagger:true});}function jt(i){let e=i.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function ir(i){return {use(e,t){if(typeof e=="string"){let o=e,n=t,a=n.stack;if(a&&Array.isArray(a)){rt(o,n);return}i.use(Ne(n,o));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){rt("/",r);return}i.use(Ne(r));}}}var st=class extends T{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};Q();var Et=class{async tmpdir(){switch(R.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},nr=new Et;var ar=1024*1024,pr=i=>async(e,t,r)=>{let s=[];try{let o=e.headers.get("content-type")??e.headers.get("Content-Type");if(!o||!o.startsWith("multipart/form-data")||!e.rawBody)return r();let n=o.match(/boundary=(.*)(;|$)/i);if(!n)return r();let a=n[1].replace(/(^\s*"?|"?\s*$)/g,""),c=new Uint8Array(e.rawBody),p=new TextEncoder().encode(`--${a}`),l=new Uint8Array([13,10,13,10]),d=[],h=(P,E,F=0)=>{e:for(let S=F;S<=P.length-E.length;S++){for(let O=0;O<E.length;O++)if(P[S+O]!==E[O])continue e;return S}return -1},m=h(c,p);for(;m!==-1&&(m+=p.length,!(c[m]===45&&c[m+1]===45));){c[m]===13&&c[m+1]===10&&(m+=2);let P=h(c,l,m);if(P===-1)break;let E=c.subarray(m,P),F=new TextDecoder().decode(E),S=P+l.length,O=h(c,p,S);if(O===-1)break;let B=O-1;c[B]===10&&B--,c[B]===13&&B--;let lt=c.subarray(S,B+1);d.push({headers:F,data:lt}),m=O;}let f=[],b={},q=Pe(i?.maxFileSize,ar)??ar;for(let P of d){let E=P.headers.split(`\r
441
441
  `).find(Qe=>Qe.toLowerCase().startsWith("content-disposition:"));if(!E)continue;let F=E.match(/name="([^"]+)"/);if(!F)continue;let S=F[1],O=E.match(/filename="([^"]*)"/),B=O?O[1]:"";if(!!B){if(i?.maxFiles&&f.length>=i.maxFiles)return t.badRequest({...M(new T(`Too many files: Maximum ${i.maxFiles} files allowed`))});if(q&&P.data.length>q)return t.badRequest({...M(new st(B,P.data.length,q))});let Qe=P.headers.split(`\r
442
442
  `).find(Hr=>Hr.toLowerCase().startsWith("content-type:")),dt=Qe?Qe.split(":")[1].trim():"application/octet-stream";if(i?.allowedMimeTypes&&!i.allowedMimeTypes.includes(dt))return t.badRequest({...M(new T(`Invalid file type: "${dt}" is not allowed. Allowed types: ${i.allowedMimeTypes.join(", ")}`))});let kr=bs(B),$r=g.extName(kr),ut=g.join(await nr.tmpdir(),`${X.randomUUID()}${$r}`);await u.writeFile(ut,P.data),s.push(ut),f.push({formName:S,mimeType:dt,size:P.data.length,tmpPath:ut,originalName:B});}else b[S]=new TextDecoder().decode(P.data);}e.files=f,e.body=b,await r(),await cr(s);}catch(o){throw await cr(s),o}},cr=async i=>{await Promise.allSettled(i.map(e=>u.unlink(e)));},bs=i=>i.replace(/\.\./g,"").replace(/[\/\\]/g,"").replace(/\0/g,"").replace(/[\x00-\x1f\x80-\x9f]/g,"").trim();var lr=i=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...i};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let o="SAMEORIGIN";typeof e.frameguard=="object"&&(o=e.frameguard.action),r.setHeader("X-Frame-Options",o);}if(e.hsts){let o={};typeof e.hsts=="object"&&(o=e.hsts);let n=o.maxAge!==void 0?o.maxAge:15552e3,a=o.includeSubDomains!==void 0?o.includeSubDomains:true,c=o.preload!==void 0?o.preload:false,p=`max-age=${n}`;a!==false&&(p+="; includeSubDomains"),c&&(p+="; preload"),r.setHeader("Strict-Transport-Security",p);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await s();}};var Ie=class extends T{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var dr=100*1024,ur=i=>async(e,t,r)=>{if(!Ss(e)||!ne(e.method))return r();let s=Pe(i?.sizeLimit,dr)??dr,o=e.rawBody;if(!o)return i?.parseEmptyBodyAsObject&&(e.body={}),r();let n=o.byteLength;if(!n)return i?.parseEmptyBodyAsObject&&(e.body={}),r();if(n>s){let a={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...i?.customErrorMessage};return t.status(a.status).json({error:a.message})}try{let a=i?.encoding??"utf-8",c=new TextDecoder(a).decode(o);e.body=JSON.parse(c);}catch(a){return a instanceof SyntaxError?t.badRequest({...M(new Ie("Invalid JSON syntax"))}):t.badRequest({...M(new Ie("Invalid request body encoding"))})}await r();};function Ss(i){let e=xs(i);return e?Ps(e)==="application/json":false}function xs(i){let e=i.headers.get("content-type")??i.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function Ps(i){let e=i.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var hr=i=>async(e,t,r)=>{try{let s=e.body;(i?.logRequest??!0)&&v.info({type:"request",requestId:e.id,method:i?.requestPayload?.method??!0?e.method:void 0,url:i?.requestPayload?.url??!0?e.url:void 0,ip:i?.requestPayload?.ip??!0?e.ip:void 0,headers:i?.requestPayload?.headers??!0?e.headers:void 0,body:i?.requestPayload?.body??!1?mr(s):void 0});let o=performance.now();await r();let a=performance.now()-o;(i?.logResponse??!0)&&v.info({type:"response",requestId:e.id,status:i?.responsePayload?.status??t.responseStatus,duration:`${a.toFixed(2)}ms`,body:i?.responsePayload?.body??!1?mr(t.getBody()):void 0,headers:i?.responsePayload?.headers??!1?t.headers:void 0});}catch(s){throw v.error(s),s}};function mr(i){if(typeof i=="string"||i&&typeof i=="object"&&i.constructor===Object)return i}var Rs=["POST"],Ts="X-HTTP-Method-Override",Cs=["GET","POST","PUT","PATCH","DELETE"],gr=i=>{let e=(i?.methods??Rs).map(r=>r.toUpperCase()),t=i?.header??Ts;return async(r,s,o)=>{let n=r.method.toUpperCase();if(!e.includes(n))return o();let a=r.headers.get(t);if(!a)return o();let c=a.toUpperCase();if(!Cs.includes(c))return o();r.method=c,await o();}};var ot=class{storage=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){this.storage.set(e,t),setTimeout(()=>{this.storage.delete(e);},this.windowMs);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){this.storage.delete(e);}};var fr=(i,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...i},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new ot(r.windowMs):{get:r.get,set:r.set};return async(o,n,a)=>{let c=t.type==="ip"?o.ip:t.key(o),p=await s.get(c);return p>=t.limit?n.status(t.statusCode).json({message:t.message}):(await s.set(c,p+1),a())}};var it=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let s=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:s});}async destroy(e){this.store.delete(e);}};var yr=i=>{let e=i?.name??"sid",t=i?.ttl??3600*24,r=i?.store??new it,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...i?.cookie??{}};return async(o,n,a)=>{let p=o.cookies&&o.cookies[e],l=p?await r.get(p):void 0;(!p||!l)&&(p||=X.randomUUID(),l||={},await r.set(p,l,t),n.cookie?.(e,p,s)),o.session=l,o.saveSession=async()=>r.set(p,l,t),o.destroySession=async()=>{await r.destroy(p),n.clearCookie?.(e,s);},await a(),await r.set(p,l,t);}};var wr=i=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};i&&typeof i!="boolean"&&(e={...e,...i});let t=Os(e),r=`${e.path}`,s=`${r}/json`,o;e.type==="rapidoc"?o=Es(s,e):e.type==="scalar"?o=qs(s,e):e.type==="elements"?o=Ms(s,e):e.type==="custom"?o=e.customUIGenerator(s,e):o=js(s,e),C.addOrUpdate("GET",r,[],(n,a)=>{a.html(o);}),C.addOrUpdate("GET",s,[],(n,a)=>{a.json(t);});},ae=i=>i?i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function Se(i){return !i||typeof i!="object"?{type:"string"}:i}function Os(i){let e=C.getRoutes(),t={},r;if(i.models)if(Array.isArray(i.models))r=i.models.reduce((o,n,a)=>{let c=Se(n),p=c.$id||c.title||`Model${a}`;return o[p]=c,o},{});else {r={};for(let[o,n]of Object.entries(i.models))r[o]=Se(n);}let s={...i.components,securitySchemes:i.securitySchemes||{},schemas:r?{...i.components?.schemas||{},...r}:i.components?.schemas?{...i.components.schemas}:void 0};for(let o of e){let n=o.swaggerOptions;if(n?.excludeFromSwagger)continue;t[o.path]||(t[o.path]={});let a=o.method.toLowerCase(),c={summary:n?.name||`${a.toUpperCase()} ${o.path}`,description:n?.description||"",tags:n?.service?[n.service]:[],deprecated:n?.deprecated||false},p=[];if(n?.query&&n.query.type==="object"&&n.query.shape)for(let[l,d]of Object.entries(n.query.shape))!d||typeof d!="object"||p.push({name:l,in:"query",required:Array.isArray(n.query.shape[l].required)?n.query.shape[l].required.includes(l):false,schema:Se(d)});if(n&&n.params?p=p.concat(vr(o.path,n.params)):p=p.concat(vr(o.path)),p.length>0&&(c.parameters=p),n?.requestBody){let l="application/json";n.bodyType==="form-data"?l="multipart/form-data":n.bodyType==="urlencoded"&&(l="application/x-www-form-urlencoded"),c.requestBody={content:{[l]:{schema:Se(n.requestBody)}},required:true};}else n?.bodyType&&(n.bodyType.includes("form-data")||n.bodyType.includes("urlencoded"))&&(c.requestBody={content:{[n.bodyType]:{schema:{type:"object"}}},required:true});if(c.responses={},n?.responses)for(let[l,d]of Object.entries(n.responses))c.responses[l]={description:`Response for ${l}`,content:{"application/json":{schema:Se(d)}}};if(n?.errors)for(let[l,d]of Object.entries(n.errors))c.responses[l]={description:`Error response for ${l}`,content:{"application/json":{schema:Se(d)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),n?.security){let l=[];Array.isArray(n.security)||(n.security=[n.security]);for(let d of n.security)if(d.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:d.bearerFormat||"JWT",description:d.description}),l.push({bearer:[]});else if(d.type==="apiKey")s.securitySchemes[d.name]||(s.securitySchemes[d.name]={type:"apiKey",name:d.name,in:d.in,description:d.description}),l.push({[d.name]:[]});else if(d.type==="oauth2"){let h=d.name||"oauth2";s.securitySchemes[h]||(s.securitySchemes[h]={type:"oauth2",flows:d.flows,description:d.description}),l.push({[h]:[]});}else if(d.type==="openIdConnect"){let h=d.name||"openIdConnect";s.securitySchemes[h]||(s.securitySchemes[h]={type:"openIdConnect",openIdConnectUrl:d.openIdConnectUrl,description:d.description}),l.push({[h]:[]});}l.length&&(c.security=l);}else i.security&&(c.security=i.security);t[o.path][a]=c;}return {openapi:"3.0.0",info:{title:i.title,description:i.description,version:i.version,...i.info},servers:i.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:s,security:i.security||[],tags:i.tags?Object.entries(i.tags).map(([o,n])=>({name:o,...n})):[]}}function js(i,e){return `
443
443
  <!DOCTYPE html>