@visulima/email
Version:
A comprehensive email library with multi-provider support, crypto utilities, and template engines
2 lines (1 loc) • 4.72 kB
JavaScript
var j=Object.defineProperty;var b=(i,t)=>j(i,"name",{value:t,configurable:!0});import{createRequire as A}from"node:module";import u from"./EmailError-zm2ffVav.js";import z from"./RequiredOptionError-CevW3u2K.js";import h from"./generateMessageId-11Ls5JsR.js";import E from"./headersToRecord-BKUTr40L.js";import{makeRequest as v}from"./makeRequest-DwxHX0xo.js";import w from"./retry-D1MBqS49.js";import{s as K,a as x}from"./sanitize-header-wWav-Scu.js";import S from"./validateEmailOptions-BzlJECG5.js";import{defineProvider as q}from"./defineProvider-B9rSklAJ.js";import{c as B,P as R,h as P}from"./provider-base-_hbWXBdK.js";const $=A(import.meta.url),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,T=b(i=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[t,m]=f.versions.node.split(".").map(Number);if(t>22||t===22&&m>=3||t===20&&m>=16)return f.getBuiltinModule(i)}return $(i)},"__cjs_getBuiltinModule"),{Buffer:k}=T("node:buffer");var O=Object.defineProperty,C=b((i,t)=>O(i,"name",{value:t,configurable:!0}),"b");const s="plunk",D="https://api.useplunk.com/v1",H=3e4,N=3,ee=q((i={})=>{if(!i.apiKey)throw new z(s,"apiKey");const t={apiKey:i.apiKey,debug:i.debug||!1,endpoint:i.endpoint||D,logger:i.logger,retries:i.retries||N,timeout:i.timeout||H},m=new R,n=B(s,i.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new u(s,"Email ID is required to retrieve email details"),success:!1};await m.ensureInitialized(()=>this.initialize(),s);const c={Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"};n.debug("Retrieving email details",{id:e});const l=await w(async()=>v(`${t.endpoint}/emails/${e}`,{headers:c,method:"GET",timeout:t.timeout}),t.retries);return l.success?(n.debug("Email details retrieved successfully"),{data:l.data?.body,success:!0}):(n.debug("API request failed when retrieving email",l.error),{error:new u(s,`Failed to retrieve email: ${l.error instanceof Error?l.error.message:"Unknown error"}`,{cause:l.error}),success:!1})}catch(c){return{error:P(s,"retrieve email",c,n),success:!1}}},async initialize(){await m.ensureInitialized(async()=>{if(!await this.isAvailable())throw new u(s,"Plunk API not available or invalid API key");n.debug("Provider initialized successfully")},s)},async isAvailable(){try{return t.apiKey&&t.apiKey.length>0?(n.debug("API key exists, assuming Plunk is available"),!0):!1}catch(e){return n.debug("Error checking availability:",e),!1}},name:s,options:t,async sendEmail(e){try{const c=S(e);if(c.length>0)return{error:new u(s,`Invalid email options: ${c.join(", ")}`),success:!1};await m.ensureInitialized(()=>this.initialize(),s);const l=C(r=>Array.isArray(r)?r.map(o=>o.email):[r.email],"formatRecipients"),a={to:e.subscriber||(Array.isArray(e.to)?e.to[0]?.email:e.to.email)};if(e.from&&(a.from=e.from.email,e.from.name&&(a.from_name=e.from.name)),e.subject&&(a.subject=e.subject),e.html?a.body=e.html:e.text&&(a.body=e.text),e.html&&e.text&&(a.text=e.text),e.cc&&(a.cc=l(e.cc)),e.bcc&&(a.bcc=l(e.bcc)),e.replyTo&&(a.reply_to=e.replyTo.email,e.replyTo.name&&(a.reply_to_name=e.replyTo.name)),e.templateId&&(a.template=e.templateId),e.data&&(a.data=e.data),e.subscriberId&&(a.subscriber_id=e.subscriberId),e.headers){const r=E(e.headers),o={};Object.entries(r).forEach(([y,_])=>{o[x(y)]=K(_)}),a.headers=o}e.attachments&&e.attachments.length>0&&(a.attachments=await Promise.all(e.attachments.map(async r=>{let o;if(r.content)if(typeof r.content=="string")o=r.content;else if(r.content instanceof Promise){const y=await r.content;o=k.from(y).toString("base64")}else o=r.content.toString("base64");else if(r.raw)o=typeof r.raw=="string"?r.raw:r.raw.toString("base64");else throw new u(s,`Attachment ${r.filename} has no content`);return{content:o,filename:r.filename,type:r.contentType||"application/octet-stream"}}))),n.debug("Sending email via Plunk API",{subject:a.subject,to:a.to});const I={Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"},d=await w(async()=>v(`${t.endpoint}/send`,{headers:I,method:"POST",timeout:t.timeout},JSON.stringify(a)),t.retries);if(!d.success)return n.debug("API request failed when sending email",d.error),{error:d.error||new u(s,"Failed to send email"),success:!1};const p=d.data,g=p?.body&&typeof p.body=="object"?p.body.id||p.body.messageId||h():h();return n.debug("Email sent successfully",{messageId:g}),{data:{messageId:g,provider:s,response:d.data,sent:!0,timestamp:new Date},success:!0}}catch(c){return{error:P(s,"send email",c,n),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{ee as default};