@visulima/email
Version:
A comprehensive email library with multi-provider support, crypto utilities, and template engines
2 lines (1 loc) • 5.85 kB
JavaScript
var I=Object.defineProperty;var y=(r,i)=>I(r,"name",{value:i,configurable:!0});import{createRequire as A}from"node:module";import m from"./EmailError-zm2ffVav.js";import T from"./RequiredOptionError-CevW3u2K.js";import R from"./generateMessageId-11Ls5JsR.js";import S from"./headersToRecord-BKUTr40L.js";import{makeRequest as h}from"./makeRequest-DwxHX0xo.js";import $ from"./retry-D1MBqS49.js";import _ from"./validateEmailOptions-BzlJECG5.js";import{defineProvider as z}from"./defineProvider-B9rSklAJ.js";import{a as E}from"./attachment-processor-2rHmfa7j.js";import{c as q,P as U,h as j}from"./provider-base-_hbWXBdK.js";import{b as v,c as k}from"./address-formatter-Cm_E_ZMa.js";const P=A(import.meta.url),u=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,C=y(r=>{if(typeof u<"u"&&u.versions&&u.versions.node){const[i,n]=u.versions.node.split(".").map(Number);if(i>22||i===22&&n>=3||i===20&&n>=16)return u.getBuiltinModule(r)}return P(r)},"__cjs_getBuiltinModule"),{Buffer:b}=C("node:buffer");var M=Object.defineProperty,K=y((r,i)=>M(r,"name",{value:i,configurable:!0}),"k");const o="mailgun",B="https://api.mailgun.net",O=3e4,x=3,D=K(r=>{const i=[];for(const[n,a]of Object.entries(r))if(a!=null)if(Array.isArray(a))for(const e of a)i.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(e))}`);else typeof a=="object"?i.push(`${encodeURIComponent(n)}=${encodeURIComponent(JSON.stringify(a))}`):i.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(a))}`);return i.join("&")},"objectToFormData"),te=z((r={})=>{if(!r.apiKey)throw new T(o,"apiKey");if(!r.domain)throw new T(o,"domain");const i={apiKey:r.apiKey,debug:r.debug||!1,domain:r.domain,endpoint:r.endpoint||B,retries:r.retries||x,timeout:r.timeout||O,...r.logger&&{logger:r.logger}},n=new U,a=q(o,r.logger);return{endpoint:i.endpoint,features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new m(o,"Email ID is required to retrieve email details"),success:!1};await n.ensureInitialized(()=>this.initialize(),o);const s={Authorization:`Basic ${b.from(`api:${i.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};a.debug("Retrieving email details",{id:e});const t=await $(async()=>h(`${i.endpoint}/v3/${i.domain}/events?message-id=${encodeURIComponent(e)}&limit=1`,{headers:s,method:"GET",timeout:i.timeout}),i.retries);if(!t.success)return a.debug("API request failed when retrieving email",t.error),{error:new m(o,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1};a.debug("Email details retrieved successfully");const p=t.data?.items||[],f=p.length>0?p[0]:void 0;return{data:f?.message?.headers||f?.storage||void 0,success:!0}}catch(s){return{error:j(o,"retrieve email",s,a),success:!1}}},async initialize(){await n.ensureInitialized(async()=>{if(!await this.isAvailable())throw new m(o,"Mailgun API not available or invalid API key/domain");a.debug("Provider initialized successfully")},o)},async isAvailable(){try{const e={Authorization:`Basic ${b.from(`api:${i.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};a.debug("Checking Mailgun API availability");const s=await h(`${i.endpoint}/v3/domains/${i.domain}`,{headers:e,method:"GET",timeout:i.timeout});if(a.debug("Mailgun API availability check response:",{error:s.error instanceof Error?s.error.message:void 0,statusCode:s.data?.statusCode,success:s.success}),!s.success||!s.data||typeof s.data!="object")return!1;const{statusCode:t}=s.data;return typeof t=="number"&&t>=200&&t<300}catch(e){return a.debug("Error checking availability:",e),!1}},name:o,options:i,async sendEmail(e){try{const s=_(e);if(s.length>0)return{error:new m(o,`Invalid email options: ${s.join(", ")}`),success:!1};await n.ensureInitialized(()=>this.initialize(),o);const t={from:k(e.from),to:v(e.to).join(",")};if(e.subject&&(t.subject=e.subject),e.cc&&(t.cc=v(e.cc).join(",")),e.bcc&&(t.bcc=v(e.bcc).join(",")),e.replyTo&&(t["h:Reply-To"]=k(e.replyTo)),e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.template&&(t.template=e.template,e.templateVariables))for(const[d,c]of Object.entries(e.templateVariables))t[`v:${d}`]=c;if(e.tags&&e.tags.length>0&&(t["o:tag"]=e.tags),e.campaignId&&(t["o:campaign"]=e.campaignId),e.deliveryTime&&(t["o:deliverytime"]=typeof e.deliveryTime=="number"?new Date(e.deliveryTime*1e3).toUTCString():e.deliveryTime),e.clickTracking!==void 0&&(t["o:clicktracking"]=e.clickTracking?"yes":"no"),e.openTracking!==void 0&&(t["o:tracking"]=e.openTracking?"yes":"no"),e.unsubscribeTracking!==void 0&&(t["o:tracking-clicks"]=e.unsubscribeTracking?"yes":"no"),e.testMode&&(t["o:testmode"]="yes"),e.requireTls&&(t["o:require-tls"]="yes"),e.skipVerification&&(t["o:skip-verification"]="yes"),e.headers){const d=S(e.headers);for(const[c,g]of Object.entries(d))t[`h:${c}`]=g}if(e.attachments&&e.attachments.length>0){const d=await Promise.all(e.attachments.map((c,g)=>E(c,o,g)));for(const c of d)t[c.key]=c.content}a.debug("Sending email via Mailgun API",{subject:t.subject,to:t.to});const p={Authorization:`Basic ${b.from(`api:${i.apiKey}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},f=D(t),l=await $(async()=>h(`${i.endpoint}/v3/${i.domain}/messages`,{headers:p,method:"POST",timeout:i.timeout},f),i.retries);if(!l.success)return a.debug("API request failed when sending email",l.error),{error:l.error||new m(o,"Failed to send email"),success:!1};const w=l.data?.body?.id||R();return a.debug("Email sent successfully",{messageId:w}),{data:{messageId:w,provider:o,response:l.data,sent:!0,timestamp:new Date},success:!0}}catch(s){return{error:j(o,"send email",s,a),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{te as default};