UNPKG

@visulima/email

Version:

A comprehensive email library with multi-provider support, crypto utilities, and template engines

2 lines (1 loc) 5.55 kB
var A=Object.defineProperty;var h=(i,r)=>A(i,"name",{value:r,configurable:!0});import{createRequire as T}from"node:module";import d from"./EmailError-zm2ffVav.js";import k from"./RequiredOptionError-CevW3u2K.js";import z from"./generateMessageId-11Ls5JsR.js";import E from"./headersToRecord-BKUTr40L.js";import{makeRequest as f}from"./makeRequest-DwxHX0xo.js";import v from"./retry-D1MBqS49.js";import{s as w,a as M}from"./sanitize-header-wWav-Scu.js";import q from"./validateEmailOptions-BzlJECG5.js";import{defineProvider as K}from"./defineProvider-B9rSklAJ.js";import{g as y}from"./address-formatter-Cm_E_ZMa.js";import{c as N,P as O,h as _}from"./provider-base-_hbWXBdK.js";const C=T(import.meta.url),g=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,I=h(i=>{if(typeof g<"u"&&g.versions&&g.versions.node){const[r,m]=g.versions.node.split(".").map(Number);if(r>22||r===22&&m>=3||r===20&&m>=16)return g.getBuiltinModule(i)}return C(i)},"__cjs_getBuiltinModule"),{Buffer:S}=I("node:buffer"),s="mandrill",V="https://mandrillapp.com/api/1.0",D=3e4,R=3,Z=K((i={})=>{if(!i.apiKey)throw new k(s,"apiKey");const r={apiKey:i.apiKey,debug:i.debug||!1,endpoint:i.endpoint||V,retries:i.retries||R,timeout:i.timeout||D,...i.logger&&{logger:i.logger}},m=new O,o=N(s,i.logger);return{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 d(s,"Email ID is required to retrieve email details"),success:!1};await m.ensureInitialized(()=>this.initialize(),s),o.debug("Retrieving email details",{id:e});const l={id:e,key:r.apiKey},t={"Content-Type":"application/json"},n=await v(async()=>f(`${r.endpoint}/messages/info.json`,{headers:t,method:"POST",timeout:r.timeout},JSON.stringify(l)),r.retries);return n.success?(o.debug("Email details retrieved successfully"),{data:n.data?.body,success:!0}):(o.debug("API request failed when retrieving email",n.error),{error:new d(s,`Failed to retrieve email: ${n.error instanceof Error?n.error.message:"Unknown error"}`,{cause:n.error}),success:!1})}catch(l){return{error:_(s,"retrieve email",l,o),success:!1}}},async initialize(){await m.ensureInitialized(async()=>{if(!await this.isAvailable())throw new d(s,"Mandrill API not available or invalid API key");o.debug("Provider initialized successfully")},s)},async isAvailable(){try{o.debug("Checking Mandrill API availability");const e={key:r.apiKey},l={"Content-Type":"application/json"},t=await f(`${r.endpoint}/users/info.json`,{headers:l,method:"POST",timeout:r.timeout},JSON.stringify(e));return o.debug("Mandrill API availability check response:",{error:t.error instanceof Error?t.error.message:void 0,statusCode:t.data?.statusCode,success:t.success}),!!(t.success&&t.data&&typeof t.data=="object"&&"statusCode"in t.data&&typeof t.data.statusCode=="number"&&t.data.statusCode>=200&&t.data.statusCode<300)}catch(e){return o.debug("Error checking availability:",e),!1}},name:s,options:r,async sendEmail(e){try{const l=q(e);if(l.length>0)return{error:new d(s,`Invalid email options: ${l.join(", ")}`),success:!1};await m.ensureInitialized(()=>this.initialize(),s);const t={from_email:e.from.email,html:e.html||"",subject:e.subject,text:e.text||"",...e.from.name&&{from_name:e.from.name},to:y(e.to,"to")};if(e.cc){const a=y(e.cc,"cc");for(const c of a)c.type="cc";t.to=[...t.to,...a]}if(e.bcc){const a=y(e.bcc,"bcc");for(const c of a)c.type="bcc";t.to=[...t.to,...a]}if(e.replyTo){const a=e.replyTo.name?`${w(e.replyTo.name)} <${e.replyTo.email}>`:e.replyTo.email;t.headers={"Reply-To":a}}if(e.headers){const a=E(e.headers),c={};Object.entries(a).forEach(([p,P])=>{c[M(p)]=w(P)}),t.headers={...t.headers,...c}}e.tags&&e.tags.length>0&&(t.tags=e.tags),e.metadata&&(t.metadata=e.metadata),(e.googleAnalyticsDomains||e.googleAnalyticsCampaign)&&(t.google_analytics_domains=e.googleAnalyticsDomains,t.google_analytics_campaign=e.googleAnalyticsCampaign),e.subaccount&&(t.subaccount=e.subaccount),e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async a=>{let c;if(a.content)if(typeof a.content=="string")c=a.content;else if(a.content instanceof Promise){const p=await a.content;c=S.from(p).toString("base64")}else c=a.content.toString("base64");else if(a.raw)c=typeof a.raw=="string"?a.raw:a.raw.toString("base64");else throw new d(s,`Attachment ${a.filename} has no content`);return{content:c,name:a.filename,type:a.contentType||"application/octet-stream"}})));const n={key:r.apiKey,message:t};e.templateName&&(n.template_name=e.templateName,e.templateContent&&(n.template_content=e.templateContent),e.templateVariables&&(n.template_vars=e.templateVariables)),e.globalMergeVars&&(t.global_merge_vars=e.globalMergeVars),e.mergeVars&&(t.merge_vars=e.mergeVars),e.sendAt&&(n.send_at=e.sendAt),o.debug("Sending email via Mandrill API",{subject:t.subject,to:t.to});const j={"Content-Type":"application/json"},u=await v(async()=>f(`${r.endpoint}/messages/send.json`,{headers:j,method:"POST",timeout:r.timeout},JSON.stringify(n)),r.retries);if(!u.success)return o.debug("API request failed when sending email",u.error),{error:u.error||new d(s,"Failed to send email"),success:!1};const b=u.data?.body?.[0]?.id||z();return o.debug("Email sent successfully",{messageId:b}),{data:{messageId:b,provider:s,response:u.data,sent:!0,timestamp:new Date},success:!0}}catch(l){return{error:_(s,"send email",l,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{Z as default};