UNPKG

@visulima/email

Version:

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

2 lines (1 loc) 5.58 kB
var k=Object.defineProperty;var w=(n,l)=>k(n,"name",{value:l,configurable:!0});import{createRequire as z}from"node:module";import u from"./EmailError-zm2ffVav.js";import v from"./RequiredOptionError-CevW3u2K.js";import P from"./generateMessageId-11Ls5JsR.js";import j from"./headersToRecord-BKUTr40L.js";import{makeRequest as h}from"./makeRequest-DwxHX0xo.js";import T from"./retry-D1MBqS49.js";import _ from"./validateEmailOptions-BzlJECG5.js";import{defineProvider as B}from"./defineProvider-B9rSklAJ.js";import{j as y,k as C}from"./address-formatter-Cm_E_ZMa.js";import{c as E,P as q,h as S}from"./provider-base-_hbWXBdK.js";const $=z(import.meta.url),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,I=w(n=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[l,t]=f.versions.node.split(".").map(Number);if(l>22||l===22&&t>=3||l===20&&t>=16)return f.getBuiltinModule(n)}return $(n)},"__cjs_getBuiltinModule"),{Buffer:p}=I("node:buffer"),s="azure",x=3e4,O=3,V=B((n={})=>{if(!n.region)throw new v(s,"region");if(!n.connectionString&&!n.accessToken)throw new v(s,"connectionString or accessToken");const l=n.endpoint||`https://${n.region}.communication.azure.com`,t={debug:n.debug||!1,endpoint:l,region:n.region,retries:n.retries||O,timeout:n.timeout||x,...n.connectionString&&{connectionString:n.connectionString},...n.accessToken&&{accessToken:n.accessToken},...n.logger&&{logger:n.logger}},g=new q,o=E(s,n.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!0,tracking:!1},async getEmail(e){try{if(!e)return{error:new u(s,"Email ID is required to retrieve email details"),success:!1};await g.ensureInitialized(()=>this.initialize(),s);const a={"Content-Type":"application/json"};if(t.accessToken)a.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const c=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);c&&(a.Authorization=`Bearer ${c[2]}`)}o.debug("Retrieving email details",{id:e});const r=await T(async()=>h(`${t.endpoint}/emails/${e}`,{headers:a,method:"GET",timeout:t.timeout}),t.retries);return r.success?(o.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(o.debug("API request failed when retrieving email",r.error),{error:new u(s,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(a){return{error:S(s,"retrieve email",a,o),success:!1}}},async initialize(){await g.ensureInitialized(async()=>{if(!await this.isAvailable())throw new u(s,"Azure Communication Services API not available or invalid credentials");o.debug("Provider initialized successfully")},s)},async isAvailable(){try{const e={"Content-Type":"application/json"};if(t.accessToken)e.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const c=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(c)e.Authorization=`Bearer ${c[2]}`;else return!1}else return!1;o.debug("Checking Azure Communication Services API availability");const a=await h(`${t.endpoint}/emails:send`,{headers:e,method:"POST",timeout:t.timeout},JSON.stringify({}));if(a.success)return!0;const r=a.data?.statusCode;return r===401||r===403?!1:r===400}catch(e){if(o.debug("Error checking availability:",e),e instanceof Error){const a=e.message;if(a.includes("401")||a.includes("403"))return!1}return!1}},name:s,options:t,async sendEmail(e){try{const a=_(e);if(a.length>0)return{error:new u(s,`Invalid email options: ${a.join(", ")}`),success:!1};await g.ensureInitialized(()=>this.initialize(),s);const r={content:{subject:e.subject},recipients:{to:y(e.to)},senderAddress:e.from.email};if(e.html&&(r.content.html=e.html),e.text&&(r.content.plainText=e.text),e.cc&&(r.recipients.cc=y(e.cc)),e.bcc&&(r.recipients.bcc=y(e.bcc)),e.replyTo&&(r.replyTo=C(e.replyTo).email),e.importance&&(r.importance=e.importance),e.headers){const i=j(e.headers);r.headers=i}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async i=>{let d;if(i.content)if(typeof i.content=="string")d=p.from(i.content,"utf8").toString("base64");else if(i.content&&typeof i.content.then=="function"){const A=await i.content;d=p.from(A).toString("base64")}else d=i.content.toString("base64");else if(i.raw)d=typeof i.raw=="string"?p.from(i.raw,"utf8").toString("base64"):i.raw.toString("base64");else throw new u(s,`Attachment ${i.filename} has no content`);return{contentInBase64:d,contentType:i.contentType||"application/octet-stream",name:i.filename}}))),o.debug("Sending email via Azure Communication Services API",{subject:r.content.subject,to:r.recipients.to});const c={"Content-Type":"application/json"};if(t.accessToken)c.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const i=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(i)c.Authorization=`Bearer ${i[2]}`;else return{error:new u(s,"Invalid connection string format"),success:!1}}const m=await T(async()=>h(`${t.endpoint}/emails:send`,{headers:c,method:"POST",timeout:t.timeout},JSON.stringify(r)),t.retries);if(!m.success)return o.debug("API request failed when sending email",m.error),{error:m.error||new u(s,"Failed to send email"),success:!1};const b=m.data?.body?.messageId||P();return o.debug("Email sent successfully",{messageId:b}),{data:{messageId:b,provider:s,response:m.data,sent:!0,timestamp:new Date},success:!0}}catch(a){return{error:S(s,"send email",a,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{V as default};