balda 0.0.34 → 0.0.35

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.cjs CHANGED
@@ -1218,6 +1218,6 @@ ${p}\r
1218
1218
  <script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
1219
1219
  </body>
1220
1220
  </html>
1221
- `}function hs(n,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(n))!==null;){let o=s[1],i={type:"string"};e&&e.shape&&e.shape[o]&&(i=_e(e.shape[o])||{type:"string"}),t.push({name:o,in:"path",required:true,schema:i});}return t}var gr=n=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},n.ms);try{await r();}finally{clearTimeout(s);}};var yr=n=>{let e=n?.header??"x-forwarded-for",t=n?.trust??true,r=n?.hop??"first";return async(s,o,i)=>{if(!t)return i();let a=s.headers.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(d=>d.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return i()}};var vr=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),o=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},o,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(i));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),o=e.split(":");if(o.length!==2)throw new Error("Invalid hash format");let[i,a]=o,c=this.decodeBase64(i),d=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),p=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),u=new Uint8Array(p);if(u.length!==d.length)return !1;let m=0;for(let h=0;h<u.length;h++)m|=u[h]^d[h];return m===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let o=0;o<r;o++)s[o]=t.charCodeAt(o);return s}},tt=new vr;var Pt=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},o=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,c)=>{let d=a.url,l=d.indexOf("://")+3,p=d.indexOf("/",l),u=p===-1?"/":d.slice(p),m=u.indexOf("?"),h=m===-1?u:u.slice(0,m),f=m===-1?"":u.slice(m+1),g=$.find(a.method,h),y=oe.fromRequest(a);y.params=g?.params??{},y.setQueryString(f);let T=a.headers.get("x-forwarded-for");if(y.ip=T?T.split(",")[0].trim():c.requestIP(a)?.address,await t?.call(this,y,c),o&&h.startsWith(i)){let S=await this.ensureGraphQLHandler();if(S){let R=y.toWebApi();return vt(S.server,R,a.method,f,{req:y,server:c})}}if(r&&y.headers.get("upgrade")==="websocket"){let S=y.toWebApi();if(c.upgrade(S,{data:{}}))return}let w=new D;return w.setRouteResponseSchemas(g?.responseSchemas),await he(g?.middleware??[],g?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),y,w),D.toWebResponse(w)},...r?{websocket:r}:{},...s}),this.url=this.runtimeServer.url.toString();}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Ot=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,o="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let c=i.url,d=c.indexOf("://")+3,l=c.indexOf("/",d),p=l===-1?"/":c.slice(l),u=p.indexOf("?"),m=u===-1?p:p.slice(0,u),h=u===-1?"":p.slice(u+1),f=$.find(i.method,m),g=oe.fromRequest(i);g.params=f?.params??{},g.setQueryString(h);let y=i.headers.get("x-forwarded-for");if(g.ip=y?y.split(",")[0].trim():a.remoteAddr?.hostname,await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&m.startsWith(o)){let S=await this.ensureGraphQLHandler();if(S){let R=g.toWebApi();return vt(S.server,R,i.method,h,{req:g,info:a})}}if(g.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let S=g.toWebApi(),{socket:R,response:M}=Deno.upgradeWebSocket(S);return this.tapOptions?.deno?.websocket?.open&&(R.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(R)),this.tapOptions?.deno?.websocket?.message&&(R.onmessage=B=>{this.tapOptions?.deno?.websocket?.message?.(R,B.data);}),this.tapOptions?.deno?.websocket?.close&&(R.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(R)),M}let w=new D;return w.setRouteResponseSchemas(f?.responseSchemas),await he(f?.middleware??[],f?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),g,w),D.toWebResponse(w)},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Wo=async(n,e)=>{let t=stream.Readable.fromWeb(n);return promises.pipeline(t,e)},Ct=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure";let r=this.graphql.isEnabled,s="/graphql";this.runtimeServer=this.createServer(async(o,i)=>{if(this.tapOptions&&this.tapOptions.node){let y=this.tapOptions.node;await y?.(o);}let a=o.url,c=a.indexOf("?"),d=c===-1?a:a.slice(0,c),l=c===-1?"":a.slice(c+1);if(r&&d.startsWith(s)){let y=await this.ensureGraphQLHandler();if(y){let T=ae(o.method)?await this.readRequestBody(o):"";await Jr(y.server,o.headers,o.method??"POST",T,l,{req:o},async(w,b,S)=>{for(let[R,M]of w)i.setHeader(R,M);if(i.statusCode=b,typeof S=="string")i.end(S);else {for await(let R of S)i.write(R);i.end();}});return}}let p=$.find(o.method,d),u=this.processHeaders(o.headers),m=new oe;m.url=`${this.url}${a}`,m.method=o.method,ae(o.method)&&m.setNodeRequest(o),m.headers=new Headers(u),m.ip=this.extractClientIp(o),m.setQueryString(l),m.params=p?.params??{};let h=new D;h.nodeResponse=i,h.setRouteResponseSchemas(p?.responseSchemas);let f=await he(p?.middleware??[],p?.handler??((y,T)=>{T.notFound({...L(new z(y.url,y.method))});}),m,h);if(i.headersSent||i.writableEnded)return;let g=f.getBody();if(g instanceof ReadableStream){i.writeHead(f.responseStatus,f.headers),Wo(g,i);return}i.writeHead(f.responseStatus,f.headers),g instanceof Buffer||g instanceof Uint8Array||typeof g=="string"?i.end(g):f.headers["Content-Type"]==="application/json"?i.end(typeof g=="string"?g:JSON.stringify(g)):i.end(g!=null?String(g):void 0);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let o=e[s];o!==void 0&&(t[s]=Array.isArray(o)?o.join(", "):o);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",o=>s.push(Buffer.from(o))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var Rt=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Pt(e);if(e?.runtime==="node")return new Ct(e);if(e?.runtime==="deno")return new Ot(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};G();var jt=class{_brand="BaldaServer";serverOptions;router=$;#t=new Qe;logger;isListening;isProduction;graphql;#s;#e;#r=[];#n=["node_modules"];#o;#i;constructor(e){this.#s=false,this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.#t.get("PORT"))??80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal,cronUI:e?.cronUI},this.logger=(e?.logger??q).child({scope:"Balda"}),e?.ajvInstance&&A.setGlobalInstance(e.ajvInstance),this.#i=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new se(this.serverOptions.graphql),this.#e=new Rt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:E.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#i,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}get host(){return this.#e.host}get routes(){return $.getRoutes()||[]}get fs(){return v}async hash(e){return tt.hash(e)}async compareHash(e,t){return tt.compare(e,t)}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}get(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("GET",e,s,o,l,d);}post(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("POST",e,s,o,l,d);}patch(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PATCH",e,s,o,l,d);}put(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PUT",e,s,o,l,d);}delete(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("DELETE",e,s,o,l,d);}options(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("OPTIONS",e,s,o,l,d);}head(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("HEAD",e,s,o,l,d);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(E.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(E.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(E.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){Fe.exit(e);}on(e,t){switch(E.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}once(e,t){switch(E.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}use(...e){this.#r.push(...e);}useExpress(e,t){pr(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){et(e,t);}setErrorHandler(e){this.#r.unshift(async(t,r,s)=>{try{await s();}catch(o){await e?.(t,r,s,o);}});}setNotFoundHandler(e){this.#o=e?.bind(this);}listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let t={port:this.port,host:this.host,url:this.url};this.bootstrap().then(()=>{this.#e.listen(),this.isListening=true,e?.({...t,error:void 0});}).catch(r=>{e?.({...t,error:r});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e();});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}configureHash(e){tt.configure(e);}async getMockServer(e){return await this.bootstrap(e),new wt(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>v.glob(s,{cwd:N.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#n.some(o=>s.includes(o))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(o=>{this.logger.error(`Error importing controller ${s}: ${o}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,body:r.body,query:r.query,all:r.all,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(os(r));break;case "cors":this.use(cr(r));break;case "static":this.use(rr(r));break;case "helmet":this.use(dr(r));break;case "cookie":this.use(ar(r));break;case "methodOverride":this.use(mr(r));break;case "compression":this.use(ir(r));break;case "log":this.use(ur(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:o}=r;this.use(hr(s,o));break;case "trustProxy":this.use(yr(r));break;case "timeout":this.use(gr(r));break;case "session":this.use(fr(r));break;case "asyncLocalStorage":this.use(or(r));break;default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#s||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.cronUI&&await Hr(this.serverOptions.cronUI),this.serverOptions.swagger&&fs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#r.length&&$.applyGlobalMiddlewaresToAllRoutes(this.#r),this.#s=true);}handleNotFound=(e,t)=>{if(this.#o){this.#o(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],o=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=$.find(a,r);c&&c.handler!==this.handleNotFound&&o.push(a);}if(o.length){t.setHeader("Allow",o.join(", "));let a=new Ue(r,e.method);t.methodNotAllowed({...L(a)});return}let i=new z(r,e.method);t.notFound({...L(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)$.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true});}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var gs=()=>{let n=A.getCacheStats(),e=n.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:n.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:n.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Vo=()=>{let n=gs();q.info({validators:n.validators.size,totalSchemaRefs:n.totalSchemaReferences,memoryEstimate:n.memoryEstimate.total},"Schema cache metrics");},Ko=()=>{A.clearAllCaches(),q.debug("All schema caches cleared");};var K=class extends O{constructor(e){super(`File not found: ${e}`);}};var br=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new K(e);let o=t;if(o==="stream")return stream.Readable.toWeb(s.readableStreamBody);let i=[];for await(let c of s.readableStreamBody)i.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(i);switch(o){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new O("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new K(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),o=t;await s.upload(o,o.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new O("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new O("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var wr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new O("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await v.exists(r))return [];let o=[];return await this.listFilesRecursively(r,t,o),o}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await v.exists(r))throw new K(e);switch(t){case "raw":return await v.readFile(r);case "text":return await v.readFile(r,{encoding:"utf8"});case "stream":return await v.streamFile(r);default:throw new O("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),o=x.join(s,"..");await v.mkdir(o,{recursive:true}),await v.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await v.exists(t)&&await v.unlink(t);}async listFilesRecursively(e,t,r){let s=await v.stat(e);if(s.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!s.isDirectory)return;let o=await this.readDirectory(e);for(let i of o){let a=x.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(G(),jr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new O("Unsupported runtime")}}async ensureDirectoryExists(){if(await v.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await v.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};G();var Sr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=E.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:o}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:o,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new O("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new K(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new O("Invalid return type")}}catch(s){throw s instanceof K?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new K(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new K(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new O("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new K(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var xr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var qt=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new O("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var Mt=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new O("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var Et=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new O("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var At=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new O("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var kt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,o)=>{let i=t[s];return i===void 0?r:o&&this.helpers.has(o)?this.helpers.get(o)(i):String(i)})}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var rt=class extends O{constructor(e){super(e),this.name="MailerError";}},st=class extends rt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},$t=class extends rt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},_t=class extends rt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var ot=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,o=s.build();return s.hasTemplate()?this.sendWithTemplate(o):this.sendDirect(o)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new $t;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var Tr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new _t(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new ot(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new st(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,o=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:o,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=Xt("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let o=s;o.isFilePath?r.templateFile(o.template,o.data):r.template(o.template,o.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new st(String(this.defaultProvider));return e}};var Pr=class{};var Or=n=>(e,t)=>(r,s,o)=>{let i={scope:e,handler:t,manager:n};if(typeof s>"u"){let c=j.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),j.set(r.prototype,"__class__",c),r}let a=j.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),j.set(r,s,a),o};var Cr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Or(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new O(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Zh=$,Yh=jt;
1221
+ `}function hs(n,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(n))!==null;){let o=s[1],i={type:"string"};e&&e.shape&&e.shape[o]&&(i=_e(e.shape[o])||{type:"string"}),t.push({name:o,in:"path",required:true,schema:i});}return t}var gr=n=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},n.ms);try{await r();}finally{clearTimeout(s);}};var yr=n=>{let e=n?.header??"x-forwarded-for",t=n?.trust??true,r=n?.hop??"first";return async(s,o,i)=>{if(!t)return i();let a=s.headers.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(d=>d.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return i()}};var vr=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),o=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},o,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(i));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),o=e.split(":");if(o.length!==2)throw new Error("Invalid hash format");let[i,a]=o,c=this.decodeBase64(i),d=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),p=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),u=new Uint8Array(p);if(u.length!==d.length)return !1;let m=0;for(let h=0;h<u.length;h++)m|=u[h]^d[h];return m===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let o=0;o<r;o++)s[o]=t.charCodeAt(o);return s}},tt=new vr;var Pt=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},o=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,c)=>{let d=a.url,l=d.indexOf("://")+3,p=d.indexOf("/",l),u=p===-1?"/":d.slice(p),m=u.indexOf("?"),h=m===-1?u:u.slice(0,m),f=m===-1?"":u.slice(m+1),g=$.find(a.method,h),y=oe.fromRequest(a);y.params=g?.params??{},y.setQueryString(f);let T=a.headers.get("x-forwarded-for");if(y.ip=T?T.split(",")[0].trim():c.requestIP(a)?.address,await t?.call(this,y,c),o&&h.startsWith(i)){let S=await this.ensureGraphQLHandler();if(S){let R=y.toWebApi();return vt(S.server,R,a.method,f,{req:y,server:c})}}if(r&&y.headers.get("upgrade")==="websocket"){let S=y.toWebApi();if(c.upgrade(S,{data:{}}))return}let w=new D;return w.setRouteResponseSchemas(g?.responseSchemas),await he(g?.middleware??[],g?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),y,w),D.toWebResponse(w)},...r?{websocket:r}:{},...s}),this.url=this.runtimeServer.url.toString();}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Ot=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,o="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let c=i.url,d=c.indexOf("://")+3,l=c.indexOf("/",d),p=l===-1?"/":c.slice(l),u=p.indexOf("?"),m=u===-1?p:p.slice(0,u),h=u===-1?"":p.slice(u+1),f=$.find(i.method,m),g=oe.fromRequest(i);g.params=f?.params??{},g.setQueryString(h);let y=i.headers.get("x-forwarded-for");if(g.ip=y?y.split(",")[0].trim():a.remoteAddr?.hostname,await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&m.startsWith(o)){let S=await this.ensureGraphQLHandler();if(S){let R=g.toWebApi();return vt(S.server,R,i.method,h,{req:g,info:a})}}if(g.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let S=g.toWebApi(),{socket:R,response:M}=Deno.upgradeWebSocket(S);return this.tapOptions?.deno?.websocket?.open&&(R.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(R)),this.tapOptions?.deno?.websocket?.message&&(R.onmessage=B=>{this.tapOptions?.deno?.websocket?.message?.(R,B.data);}),this.tapOptions?.deno?.websocket?.close&&(R.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(R)),M}let w=new D;return w.setRouteResponseSchemas(f?.responseSchemas),await he(f?.middleware??[],f?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),g,w),D.toWebResponse(w)},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Wo=async(n,e)=>{let t=stream.Readable.fromWeb(n);return promises.pipeline(t,e)},Ct=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure";let r=this.graphql.isEnabled,s="/graphql";this.runtimeServer=this.createServer(async(o,i)=>{if(this.tapOptions&&this.tapOptions.node){let y=this.tapOptions.node;await y?.(o);}let a=o.url,c=a.indexOf("?"),d=c===-1?a:a.slice(0,c),l=c===-1?"":a.slice(c+1);if(r&&d.startsWith(s)){let y=await this.ensureGraphQLHandler();if(y){let T=ae(o.method)?await this.readRequestBody(o):"";await Jr(y.server,o.headers,o.method??"POST",T,l,{req:o},async(w,b,S)=>{for(let[R,M]of w)i.setHeader(R,M);if(i.statusCode=b,typeof S=="string")i.end(S);else {for await(let R of S)i.write(R);i.end();}});return}}let p=$.find(o.method,d),u=this.processHeaders(o.headers),m=new oe;m.url=`${this.url}${a}`,m.method=o.method,ae(o.method)&&m.setNodeRequest(o),m.headers=new Headers(u),m.ip=this.extractClientIp(o),m.setQueryString(l),m.params=p?.params??{};let h=new D;h.nodeResponse=i,h.setRouteResponseSchemas(p?.responseSchemas);let f=await he(p?.middleware??[],p?.handler??((y,T)=>{T.notFound({...L(new z(y.url,y.method))});}),m,h);if(i.headersSent||i.writableEnded)return;let g=f.getBody();if(g instanceof ReadableStream){i.writeHead(f.responseStatus,f.headers),Wo(g,i);return}i.writeHead(f.responseStatus,f.headers),g instanceof Buffer||g instanceof Uint8Array||typeof g=="string"?i.end(g):f.headers["Content-Type"]==="application/json"?i.end(typeof g=="string"?g:JSON.stringify(g)):i.end(g!=null?String(g):void 0);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let o=e[s];o!==void 0&&(t[s]=Array.isArray(o)?o.join(", "):o);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",o=>s.push(Buffer.from(o))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var Rt=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Pt(e);if(e?.runtime==="node")return new Ct(e);if(e?.runtime==="deno")return new Ot(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};G();var jt=class{_brand="BaldaServer";#t=new Qe;serverOptions;router=$;logger;isListening;isProduction;graphql;#s;#e;#r=[];#n=["node_modules"];#o;#i;constructor(e){this.#s=false,this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.#t.get("PORT"))??80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal,cronUI:e?.cronUI},this.logger=(e?.logger??q).child({scope:"Balda"}),e?.ajvInstance&&A.setGlobalInstance(e.ajvInstance),this.#i=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new se(this.serverOptions.graphql),this.#e=new Rt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:E.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#i,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}get host(){return this.#e.host}get routes(){return $.getRoutes()||[]}get fs(){return v}async hash(e){return tt.hash(e)}async compareHash(e,t){return tt.compare(e,t)}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}get(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("GET",e,s,o,l,d);}post(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("POST",e,s,o,l,d);}patch(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PATCH",e,s,o,l,d);}put(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PUT",e,s,o,l,d);}delete(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("DELETE",e,s,o,l,d);}options(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("OPTIONS",e,s,o,l,d);}head(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("HEAD",e,s,o,l,d);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(E.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(E.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(E.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){Fe.exit(e);}on(e,t){switch(E.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}once(e,t){switch(E.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}use(...e){this.#r.push(...e);}useExpress(e,t){pr(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){et(e,t);}setErrorHandler(e){this.#r.unshift(async(t,r,s)=>{try{await s();}catch(o){await e?.(t,r,s,o);}});}setNotFoundHandler(e){this.#o=e?.bind(this);}listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let t={port:this.port,host:this.host,url:this.url};this.bootstrap().then(()=>{this.#e.listen(),this.isListening=true,e?.({...t,error:void 0});}).catch(r=>{e?.({...t,error:r});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e();});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}configureHash(e){tt.configure(e);}async getMockServer(e){return await this.bootstrap(e),new wt(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>v.glob(s,{cwd:N.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#n.some(o=>s.includes(o))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(o=>{this.logger.error(`Error importing controller ${s}: ${o}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,body:r.body,query:r.query,all:r.all,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(os(r));break;case "cors":this.use(cr(r));break;case "static":this.use(rr(r));break;case "helmet":this.use(dr(r));break;case "cookie":this.use(ar(r));break;case "methodOverride":this.use(mr(r));break;case "compression":this.use(ir(r));break;case "log":this.use(ur(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:o}=r;this.use(hr(s,o));break;case "trustProxy":this.use(yr(r));break;case "timeout":this.use(gr(r));break;case "session":this.use(fr(r));break;case "asyncLocalStorage":this.use(or(r));break;default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#s||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.cronUI&&await Hr(this.serverOptions.cronUI),this.serverOptions.swagger&&fs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#r.length&&$.applyGlobalMiddlewaresToAllRoutes(this.#r),this.#s=true);}handleNotFound=(e,t)=>{if(this.#o){this.#o(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],o=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=$.find(a,r);c&&c.handler!==this.handleNotFound&&o.push(a);}if(o.length){t.setHeader("Allow",o.join(", "));let a=new Ue(r,e.method);t.methodNotAllowed({...L(a)});return}let i=new z(r,e.method);t.notFound({...L(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)$.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true});}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var gs=()=>{let n=A.getCacheStats(),e=n.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:n.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:n.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Vo=()=>{let n=gs();q.info({validators:n.validators.size,totalSchemaRefs:n.totalSchemaReferences,memoryEstimate:n.memoryEstimate.total},"Schema cache metrics");},Ko=()=>{A.clearAllCaches(),q.debug("All schema caches cleared");};var K=class extends O{constructor(e){super(`File not found: ${e}`);}};var br=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new K(e);let o=t;if(o==="stream")return stream.Readable.toWeb(s.readableStreamBody);let i=[];for await(let c of s.readableStreamBody)i.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(i);switch(o){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new O("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new K(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),o=t;await s.upload(o,o.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new O("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new O("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var wr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new O("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await v.exists(r))return [];let o=[];return await this.listFilesRecursively(r,t,o),o}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await v.exists(r))throw new K(e);switch(t){case "raw":return await v.readFile(r);case "text":return await v.readFile(r,{encoding:"utf8"});case "stream":return await v.streamFile(r);default:throw new O("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),o=x.join(s,"..");await v.mkdir(o,{recursive:true}),await v.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await v.exists(t)&&await v.unlink(t);}async listFilesRecursively(e,t,r){let s=await v.stat(e);if(s.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!s.isDirectory)return;let o=await this.readDirectory(e);for(let i of o){let a=x.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(G(),jr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new O("Unsupported runtime")}}async ensureDirectoryExists(){if(await v.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await v.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};G();var Sr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=E.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:o}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:o,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new O("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new K(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new O("Invalid return type")}}catch(s){throw s instanceof K?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new K(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new K(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new O("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new K(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var xr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var qt=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new O("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var Mt=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new O("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var Et=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new O("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var At=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new O("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var kt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,o)=>{let i=t[s];return i===void 0?r:o&&this.helpers.has(o)?this.helpers.get(o)(i):String(i)})}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var rt=class extends O{constructor(e){super(e),this.name="MailerError";}},st=class extends rt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},$t=class extends rt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},_t=class extends rt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var ot=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,o=s.build();return s.hasTemplate()?this.sendWithTemplate(o):this.sendDirect(o)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new $t;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var Tr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new _t(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new ot(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new st(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,o=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:o,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=Xt("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let o=s;o.isFilePath?r.templateFile(o.template,o.data):r.template(o.template,o.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new st(String(this.defaultProvider));return e}};var Pr=class{};var Or=n=>(e,t)=>(r,s,o)=>{let i={scope:e,handler:t,manager:n};if(typeof s>"u"){let c=j.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),j.set(r.prototype,"__class__",c),r}let a=j.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),j.set(r,s,a),o};var Cr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Or(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new O(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Zh=$,Yh=jt;
1222
1222
  exports.AzureBlobStorageProvider=br;exports.BaseCron=Vt;exports.BasePlugin=Pr;exports.BullMQPubSub=Je;exports.Command=k;exports.CronService=J;exports.CustomAdapter=kt;exports.EdgeAdapter=Mt;exports.EjsAdapter=At;exports.GraphQL=se;exports.HandlebarsAdapter=qt;exports.LocalStorageProvider=wr;exports.MailOptionsBuilder=Be;exports.MailProvider=ot;exports.Mailer=Tr;exports.MemoryPubSub=We;exports.MqttService=Le;exports.MustacheAdapter=Et;exports.PGBossPubSub=Ve;exports.PolicyManager=Cr;exports.QueueManager=re;exports.QueueService=W;exports.S3StorageProvider=Sr;exports.SQSPubSub=Ke;exports.Server=jt;exports.Storage=xr;exports.arg=H;exports.asyncLocalStorage=or;exports.asyncStorage=ze;exports.bullmqQueue=Xs;exports.clearAllSchemaCaches=Ko;exports.commandRegistry=Te;exports.compression=ir;exports.controller=Bs;exports.cookie=ar;exports.cors=cr;exports.createExpressAdapter=pr;exports.createPolicyDecorator=Or;exports.createQueue=Ys;exports.cron=ks;exports.default=Yh;exports.defineQueueConfiguration=eo;exports.del=Hs;exports.expressHandler=ds;exports.expressMiddleware=$e;exports.flag=C;exports.get=Ns;exports.getSchemaCacheMetrics=gs;exports.hash=tt;exports.helmet=dr;exports.log=ur;exports.logSchemaCacheMetrics=Vo;exports.logger=q;exports.memoryQueue=Xt;exports.methodOverride=mr;exports.middleware=Ds;exports.mountExpressRouter=et;exports.mqtt=Vs;exports.patch=Ls;exports.pgbossQueue=Zs;exports.post=Fs;exports.put=Is;exports.rateLimiter=hr;exports.router=Zh;exports.serialize=zs;exports.serveStatic=rr;exports.session=fr;exports.setCronGlobalErrorHandler=As;exports.setMqttGlobalErrorHandler=Ws;exports.sqsQueue=Ks;exports.timeoutMw=gr;exports.trustProxy=yr;exports.validate=Gs;//# sourceMappingURL=index.cjs.map
1223
1223
  //# sourceMappingURL=index.cjs.map