UNPKG

@visulima/email

Version:

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

2 lines (1 loc) 5.46 kB
var I=Object.defineProperty;var h=(r,a)=>I(r,"name",{value:a,configurable:!0});import c from"./EmailError-zm2ffVav.js";import P from"./RequiredOptionError-CevW3u2K.js";import $ from"./generateMessageId-11Ls5JsR.js";import j from"./headersToRecord-BKUTr40L.js";import{makeRequest as f}from"./makeRequest-DwxHX0xo.js";import y from"./retry-D1MBqS49.js";import T from"./validateEmailOptions-BzlJECG5.js";import{defineProvider as C}from"./defineProvider-B9rSklAJ.js";import{c as E,P as S,h as b}from"./provider-base-_hbWXBdK.js";import{b as z,c as v,l as w}from"./address-formatter-Cm_E_ZMa.js";var k=Object.defineProperty,K=h((r,a)=>k(r,"name",{value:a,configurable:!0}),"p");const n="resend",R="https://api.resend.com",_=3e4,x=3,D=K(r=>{const a=[],l=/^[\w-]+$/;return l.test(r.name)||a.push(`Tag name '${r.name}' must only contain ASCII letters, numbers, underscores, or dashes`),r.name.length>256&&a.push(`Tag name '${r.name}' exceeds maximum length of 256 characters`),l.test(r.value)||a.push(`Tag value '${r.value}' for tag '${r.name}' must only contain ASCII letters, numbers, underscores, or dashes`),a},"validateTag"),M=C(((r={})=>{if(!r.apiKey)throw new P(n,"apiKey");const a={apiKey:r.apiKey,debug:r.debug||!1,endpoint:r.endpoint||R,logger:r.logger,retries:r.retries||x,timeout:r.timeout||_},l=new S,o=E(n,r.logger);return{endpoint:a.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 c(n,"Email ID is required to retrieve email details"),success:!1};await l.ensureInitialized(()=>this.initialize(),n);const t={Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"};o.debug("Retrieving email details",{id:e});const i=await y(async()=>f(`${a.endpoint}/emails/${e}`,{headers:t,method:"GET",timeout:a.timeout}),a.retries);return i.success?(o.debug("Email details retrieved successfully"),{data:i.data?.body,success:!0}):(o.debug("API request failed when retrieving email",i.error),{error:new c(n,`Failed to retrieve email: ${i.error instanceof Error?i.error.message:"Unknown error"}`,{cause:i.error}),success:!1})}catch(t){return{error:b(n,"retrieve email",t,o),success:!1}}},async initialize(){await l.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(n,"Resend API not available or invalid API key");o.debug("Provider initialized successfully")},n)},async isAvailable(){try{if(a.apiKey&&a.apiKey.startsWith("re_"))return o.debug("API key format is valid, assuming Resend is available"),!0;const e={Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"};o.debug("Checking Resend API availability");const t=await f(`${a.endpoint}/domains`,{headers:e,method:"GET",timeout:a.timeout});return t.data&&typeof t.data=="object"&&"body"in t.data&&t.data.body&&typeof t.data.body=="object"&&"name"in t.data.body&&t.data.body.name==="restricted_api_key"?(o.debug("API key is valid but restricted to only sending emails"),!0):(o.debug("Resend 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:n,options:a,async sendEmail(e){try{const t=T(e);if(t.length>0)return{error:new c(n,`Invalid email options: ${t.join(", ")}`),success:!1};await l.ensureInitialized(()=>this.initialize(),n);const i={from:v(e.from),headers:e.headers?j(e.headers):{},html:e.html,subject:e.subject,text:e.text,to:z(e.to)};if(e.cc&&(i.cc=w(e.cc)),e.bcc&&(i.bcc=w(e.bcc)),e.replyTo&&(i.reply_to=v(e.replyTo)),e.templateId&&(i.template=e.templateId,e.templateData&&(i.data=e.templateData)),e.scheduledAt&&(i.scheduled_at=typeof e.scheduledAt=="string"?e.scheduledAt:e.scheduledAt.toISOString()),e.tags&&e.tags.length>0){const s=[];if(e.tags.forEach(d=>{const p=D(d);p.length>0&&s.push(...p)}),s.length>0)return{error:new c(n,`Invalid email tags: ${s.join(", ")}`),success:!1};i.tags=e.tags.map(d=>({name:d.name,value:d.value}))}e.attachments&&e.attachments.length>0&&(i.attachments=await Promise.all(e.attachments.map(async s=>{let d;if(s.content)if(typeof s.content=="string")d=s.content;else if(s.content instanceof Promise){const p=await s.content;d=Buffer.from(p).toString("base64")}else d=s.content.toString("base64");else if(s.raw)d=typeof s.raw=="string"?s.raw:s.raw.toString("base64");else throw new c(n,`Attachment ${s.filename} has no content`);return{content:d,content_type:s.contentType,filename:s.filename,...s.path&&{path:s.path}}}))),o.debug("Sending email via Resend API",{subject:i.subject,to:i.to});const A={Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"},u=await y(async()=>f(`${a.endpoint}/emails`,{headers:A,method:"POST",timeout:a.timeout},JSON.stringify(i)),a.retries);if(!u.success)return o.debug("API request failed when sending email",u.error),{error:u.error||new c(n,"Failed to send email"),success:!1};const m=u.data,g=m?.body&&typeof m.body=="object"&&m.body.id?m.body.id:$();return o.debug("Email sent successfully",{messageId:g}),{data:{messageId:g,provider:n,response:u.data,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:b(n,"send email",t,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}}));export{M as default};