UNPKG

@visulima/email

Version:

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

2 lines (1 loc) 4.69 kB
var T=Object.defineProperty;var b=(r,n)=>T(r,"name",{value:n,configurable:!0});import{createRequire as P}from"node:module";import c from"./EmailError-zm2ffVav.js";import z from"./RequiredOptionError-CevW3u2K.js";import E from"./generateMessageId-11Ls5JsR.js";import U from"./headersToRecord-BKUTr40L.js";import{makeRequest as g}from"./makeRequest-DwxHX0xo.js";import w from"./retry-D1MBqS49.js";import k from"./validateEmailOptions-BzlJECG5.js";import{defineProvider as S}from"./defineProvider-B9rSklAJ.js";import{c as q,P as K,h as v}from"./provider-base-_hbWXBdK.js";import{l as y}from"./address-formatter-Cm_E_ZMa.js";const $=P(import.meta.url),d=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,j=b(r=>{if(typeof d<"u"&&d.versions&&d.versions.node){const[n,p]=d.versions.node.split(".").map(Number);if(n>22||n===22&&p>=3||n===20&&p>=16)return d.getBuiltinModule(r)}return $(r)},"__cjs_getBuiltinModule"),{Buffer:_}=j("node:buffer"),a="infobip",R="https://api.infobip.com",C=3e4,x=3,W=S((r={})=>{if(!r.apiKey)throw new z(a,"apiKey");const n=r.baseUrl||R,p=r.endpoint||`${n}/email/3/send`,s={apiKey:r.apiKey,baseUrl:n,debug:r.debug||!1,endpoint:p,retries:r.retries||x,timeout:r.timeout||C,...r.logger&&{logger:r.logger}},f=new K,o=q(a,r.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!1,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new c(a,"Email ID is required to retrieve email details"),success:!1};await f.ensureInitialized(()=>this.initialize(),a);const l={Authorization:`App ${s.apiKey}`,"Content-Type":"application/json"};o.debug("Retrieving email details",{id:e});const t=await w(async()=>g(`${s.baseUrl}/email/3/reports/${e}`,{headers:l,method:"GET",timeout:s.timeout}),s.retries);return t.success?(o.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(o.debug("API request failed when retrieving email",t.error),{error:new c(a,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(l){return{error:v(a,"retrieve email",l,o),success:!1}}},async initialize(){await f.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(a,"Infobip API not available or invalid API key");o.debug("Provider initialized successfully")},a)},async isAvailable(){try{o.debug("Checking Infobip API availability");const e={Authorization:`App ${s.apiKey}`,"Content-Type":"application/json"};return(await g(`${s.baseUrl}/account/1/me`,{headers:e,method:"GET",timeout:s.timeout})).success}catch(e){return o.debug("Error checking availability:",e),!1}},name:a,options:s,async sendEmail(e){try{const l=k(e);if(l.length>0)return{error:new c(a,`Invalid email options: ${l.join(", ")}`),success:!1};await f.ensureInitialized(()=>this.initialize(),a);const t={from:typeof e.from=="string"?e.from:e.from.email,subject:e.subject,to:y(e.to)};if(e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.cc&&(t.cc=y(e.cc)),e.bcc&&(t.bcc=y(e.bcc)),e.replyTo&&(t.replyTo=typeof e.replyTo=="string"?e.replyTo:e.replyTo.email),e.templateId&&(t.templateId=e.templateId,e.templateVariables&&(t.templateData=e.templateVariables)),e.trackingUrl&&(t.trackingUrl=e.trackingUrl),e.notifyUrl&&(t.notifyUrl=e.notifyUrl),e.intermediateReport!==void 0&&(t.intermediateReport=e.intermediateReport),e.sendAt&&(t.sendAt=e.sendAt),e.headers){const i=U(e.headers);t.headers=i}e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async i=>{let u;if(i.content)if(typeof i.content=="string")u=i.content;else if(i.content instanceof Promise){const A=await i.content;u=_.from(A).toString("base64")}else u=i.content.toString("base64");else if(i.raw)u=typeof i.raw=="string"?i.raw:i.raw.toString("base64");else throw new c(a,`Attachment ${i.filename} has no content`);return{content:u,contentType:i.contentType||"application/octet-stream",name:i.filename}}))),o.debug("Sending email via Infobip API",{subject:t.subject,to:t.to});const I={Authorization:`App ${s.apiKey}`,"Content-Type":"application/json"},m=await w(async()=>g(s.endpoint,{headers:I,method:"POST",timeout:s.timeout},JSON.stringify(t)),s.retries);if(!m.success)return o.debug("API request failed when sending email",m.error),{error:m.error||new c(a,"Failed to send email"),success:!1};const h=m.data?.body?.messages?.[0]?.messageId||E();return o.debug("Email sent successfully",{messageId:h}),{data:{messageId:h,provider:a,response:m.data,sent:!0,timestamp:new Date},success:!0}}catch(l){return{error:v(a,"send email",l,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{W as default};