import{ok,err}from"./_deps/shared/index.js";import{renderInviteEmail}from"./email-templates.js";import nodemailer from"nodemailer";export class EmailTransport{config;transporter;rateLimits;constructor(t){this.config={...t,rateLimit:t.rateLimit??10,tokenExpiryHours:t.tokenExpiryHours??48},this.transporter=nodemailer.createTransport({host:this.config.smtpHost,port:this.config.smtpPort,secure:!1,auth:{user:this.config.smtpUser,pass:this.config.smtpPass}}),this.rateLimits=new Map}async send(t,e){const{from:r,to:i,payload:s}=t;if(!this.isValidEmail(i))return err("SEND_FAILED");if(!this.checkRateLimit(r).ok)return err("SEND_FAILED");try{const e=await this.generateInviteToken(t),o=`${this.config.acceptBaseUrl}/${e}`,a=renderInviteEmail({agentName:s.agentName||r,did:r,acceptUrl:o,message:s.message});return await this.transporter.sendMail({from:`"${this.config.fromName}" <${this.config.fromEmail}>`,to:i,subject:`${s.agentName||"Agent"} wants to connect`,html:a}),this.incrementRateLimit(r),ok(void 0)}catch{return err("NETWORK_ERROR")}}isValidEmail(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}checkRateLimit(t){const e=Date.now(),r=this.rateLimits.get(t);return r?e>=r.resetAt?(this.rateLimits.delete(t),ok(void 0)):r.count>=this.config.rateLimit?err(void 0):ok(void 0):ok(void 0)}incrementRateLimit(t){const e=Date.now(),r=this.rateLimits.get(t);r?r.count+=1:this.rateLimits.set(t,{count:1,resetAt:e+36e5})}async generateInviteToken(t){const e={from:t.from,publicKey:t.payload.publicKey,endpoint:t.payload.endpoint,timestamp:Date.now(),expiresAt:Date.now()+60*this.config.tokenExpiryHours*60*1e3},r=JSON.stringify(e);return Buffer.from(r).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async verify(){try{return await this.transporter.verify(),ok(void 0)}catch{return err("NETWORK_ERROR")}}async close(){this.transporter.close()}onReceive(t){}dispose(){this.transporter.close()}}