@visulima/email 2.1.9 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/crypto/index.d.ts +50 -47
- package/dist/crypto/index.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/middleware/index.d.ts +19 -6
- package/dist/middleware/index.js +1 -1
- package/dist/packem_chunks/index.js +27 -0
- package/dist/packem_shared/DkimSigner-CCxFKitN.js +4 -0
- package/dist/packem_shared/{DraftMailMessage-Tj3sH8nn.js → DraftMailMessage-B0gwf8n_.js} +1 -1
- package/dist/packem_shared/{Mail-Cm24B3w0.js → Mail-DmYNQ0KK.js} +1 -1
- package/dist/packem_shared/{MailMessage-BtI4qMU1.js → MailMessage-DmmaNHHc.js} +1 -1
- package/dist/packem_shared/{SmimeEncrypter-BjBwjaTg.js → SmimeEncrypter-DnlfpjUX.js} +3 -3
- package/dist/packem_shared/{SmimeSigner-CK5TITxI.js → SmimeSigner-DTvclzLq.js} +2 -2
- package/dist/packem_shared/{address-formatter-CXZ1aWBX.js → address-formatter-w36S9ZYj.js} +1 -1
- package/dist/packem_shared/{ahaSendProvider-DY559XjD.js → ahaSendProvider-C1qvG8Cj.js} +1 -1
- package/dist/packem_shared/arcMessageSignatureBase-su9VTRB7.js +9 -0
- package/dist/packem_shared/{autoSendProvider-BgdWf422.js → autoSendProvider-yxUx3sEj.js} +1 -1
- package/dist/packem_shared/{azureProvider-Bs4BGYR1.js → azureProvider-CLLRKtOf.js} +1 -1
- package/dist/packem_shared/{brevoProvider-xoRTeFIx.js → brevoProvider-CHlodyzV.js} +1 -1
- package/dist/packem_shared/build-mime-message-BCFKPqaW.js +3 -0
- package/dist/packem_shared/canonicalize-BEjQUnUe.js +11 -0
- package/dist/packem_shared/cloudflareEmailProvider-Ckh_u-0D.js +1 -0
- package/dist/packem_shared/{createTestEmail-CPnHNKBT.js → createTestEmail-sB6z8m6Z.js} +1 -1
- package/dist/packem_shared/detectMimeType-BRz3Qjyz.js +1 -0
- package/dist/packem_shared/format-address-Bb7xk8G_.js +1 -0
- package/dist/packem_shared/{infobipProvider-mEYgfWJ7.js → infobipProvider-BEu1ycxS.js} +1 -1
- package/dist/packem_shared/{mail.d-8M9NjOr0.d.ts → mail.d-BdyyyQO5.d.ts} +10 -7
- package/dist/packem_shared/{mailCrabProvider-Cx9rnuyE.js → mailCrabProvider-BQ5ELwPU.js} +1 -1
- package/dist/packem_shared/{mailPaceProvider-DvSlan-v.js → mailPaceProvider-Ca3cz8JU.js} +1 -1
- package/dist/packem_shared/{mailchannelsProvider-Cgb8el7C.js → mailchannelsProvider-BZeuZk3d.js} +1 -1
- package/dist/packem_shared/{mailerSendProvider-BvRIjuVE.js → mailerSendProvider-C_Db652T.js} +1 -1
- package/dist/packem_shared/{mailgunProvider-kNcvF_z6.js → mailgunProvider-CU2b8ie8.js} +1 -1
- package/dist/packem_shared/{mailjetProvider-DqJUhLuH.js → mailjetProvider-VqvqCS7I.js} +1 -1
- package/dist/packem_shared/{mailomatProvider-BBOqRhV_.js → mailomatProvider-FMk4FZZz.js} +1 -1
- package/dist/packem_shared/{mailtrapProvider-CeBW2Gzg.js → mailtrapProvider-Qs0exKiJ.js} +1 -1
- package/dist/packem_shared/{mandrillProvider-Dab8i0gF.js → mandrillProvider-Co_EfMxl.js} +1 -1
- package/dist/packem_shared/{netcoreProvider-DMJsQ8IM.js → netcoreProvider-_kXjZ0bE.js} +1 -1
- package/dist/packem_shared/oauth2Middleware-C0M1w3_2.js +1 -0
- package/dist/packem_shared/{postalProvider-COVY4T94.js → postalProvider-tEBNXL3h.js} +1 -1
- package/dist/packem_shared/{postmarkProvider-Cj64C4dc.js → postmarkProvider-DdavP5x5.js} +1 -1
- package/dist/packem_shared/{resendProvider-Da5r7dMe.js → resendProvider-CMtlyIye.js} +1 -1
- package/dist/packem_shared/{scalewayProvider-CDjpYmJc.js → scalewayProvider-BFA1PQ73.js} +1 -1
- package/dist/packem_shared/{sendGridProvider-C1rp9hpg.js → sendGridProvider-DV80Lg7a.js} +1 -1
- package/dist/packem_shared/smtpProvider-BCEzJmay.js +14 -0
- package/dist/packem_shared/{sparkpostProvider-DKon_hyx.js → sparkpostProvider-C3pATjJX.js} +1 -1
- package/dist/packem_shared/{sweegoProvider-BclZuNBf.js → sweegoProvider-CkFtUAzq.js} +1 -1
- package/dist/packem_shared/{types.d-B0t3PQ3t.d.ts → types.d-Cb5fls_X.d.ts} +1 -1
- package/dist/packem_shared/{zeptomailProvider-D5B3kqFm.js → zeptomailProvider-tqRYpQlv.js} +1 -1
- package/dist/providers/ahasend/index.js +1 -1
- package/dist/providers/autosend/index.js +1 -1
- package/dist/providers/azure/index.js +1 -1
- package/dist/providers/brevo/index.js +1 -1
- package/dist/providers/cloudflare-email/index.d.ts +17 -1
- package/dist/providers/cloudflare-email/index.js +1 -1
- package/dist/providers/infobip/index.js +1 -1
- package/dist/providers/mailchannels/index.js +1 -1
- package/dist/providers/mailcrab/index.js +1 -1
- package/dist/providers/mailersend/index.js +1 -1
- package/dist/providers/mailgun/index.js +1 -1
- package/dist/providers/mailjet/index.js +1 -1
- package/dist/providers/mailomat/index.js +1 -1
- package/dist/providers/mailpace/index.js +1 -1
- package/dist/providers/mailtrap/index.js +1 -1
- package/dist/providers/mandrill/index.js +1 -1
- package/dist/providers/netcore/index.js +1 -1
- package/dist/providers/postal/index.js +1 -1
- package/dist/providers/postmark/index.js +1 -1
- package/dist/providers/resend/index.js +1 -1
- package/dist/providers/scaleway/index.js +1 -1
- package/dist/providers/sendgrid/index.js +1 -1
- package/dist/providers/smtp/index.d.ts +9 -5
- package/dist/providers/smtp/index.js +1 -1
- package/dist/providers/sparkpost/index.js +1 -1
- package/dist/providers/sweego/index.js +1 -1
- package/dist/providers/zeptomail/index.js +1 -1
- package/dist/test/index.d.ts +2 -2
- package/dist/test/index.js +1 -1
- package/dist/utils/format-email-address.js +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/DkimSigner-B_pEwGCS.js +0 -18
- package/dist/packem_shared/arcMessageSignatureBase-B0Qi-724.js +0 -17
- package/dist/packem_shared/build-mime-message-QNCMA6oQ.js +0 -3
- package/dist/packem_shared/cloudflareEmailProvider-BkR-P0YD.js +0 -1
- package/dist/packem_shared/detectMimeType-DVC9Uvy9.js +0 -1
- package/dist/packem_shared/format-address-BDKhXcXV.js +0 -1
- package/dist/packem_shared/index-B8wiKJdh.js +0 -1
- package/dist/packem_shared/oauth2Middleware-DbKGd7Z9.js +0 -1
- package/dist/packem_shared/smtpProvider-Dr2XAFQu.js +0 -27
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as p}from"node:module";import{readFileAsBuffer as c,detectMimeType as d,generateContentId as u}from"./detectMimeType-
|
|
1
|
+
import{createRequire as p}from"node:module";import{readFileAsBuffer as c,detectMimeType as d,generateContentId as u}from"./detectMimeType-BRz3Qjyz.js";import{c as T}from"./create-logger-CazqtXcL.js";import{h as l}from"./headers-to-record-ZOZ7Dubo.js";let y;const A=n=>(y??=p(import.meta.url))(n),o=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,f=n=>{if(typeof o<"u"&&o.versions&&o.versions.node){const[t,e]=o.versions.node.split(".").map(Number);if(t>22||t===22&&e>=3||t===20&&e>=16)return o.getBuiltinModule(n)}return A(n)},{basename:g}=f("node:path"),{fileURLToPath:b}=f("node:url"),m=async()=>(await import("../template-engines/html-to-text.js")).default,x=async()=>(await import("ical-generator")).default,a=n=>Array.isArray(n)?n.map(t=>typeof t=="string"?{email:t}:t):typeof n=="string"?[{email:n}]:[n];class D{fromAddress;toAddresses=[];ccAddresses=[];bccAddresses=[];subjectText="";textContent;textCharset="utf8";autoTextEnabled=!0;htmlContent;htmlCharset="utf8";dateValue;returnPathAddress;senderAddress;headers={};attachments=[];replyToAddress;priorityValue;tagsValue=[];signer;encrypter;logger;icalEventData;icalEventBuilder;from(t){return this.fromAddress=typeof t=="string"?{email:t}:t,this}to(t){return this.toAddresses.length=0,this.toAddresses.push(...a(t)),this}cc(t){return this.ccAddresses.length=0,this.ccAddresses.push(...a(t)),this}bcc(t){return this.bccAddresses.length=0,this.bccAddresses.push(...a(t)),this}subject(t){return this.subjectText=t,this}text(t,e="utf8"){return this.textContent=t,this.textCharset=e,this}html(t,e="utf8"){return this.htmlContent=t,this.htmlCharset=e,this}header(t,e){return this.headers[t]=e,this}setHeaders(t){const e=l(t);return Object.assign(this.headers,e),this}async attachFromPath(t,e){try{const r=await c(t),i=e?.filename??(g(t)||"attachment"),s=e?.contentType??d(i);this.attachments.push({cid:e?.cid,content:r,contentDisposition:e?.contentDisposition??"attachment",contentType:s,encoding:e?.encoding,filename:i,headers:e?.headers}),this.logger&&this.logger.debug(`Attachment added from path: ${t}`,{contentType:s,filename:i})}catch(r){throw this.logger&&this.logger.error(`Failed to attach file from path: ${t}`,r),r}return this}attachData(t,e){const r=e.contentType??d(e.filename);return this.attachments.push({cid:e.cid,content:t,contentDisposition:e.contentDisposition??"attachment",contentType:r,encoding:e.encoding,filename:e.filename,headers:e.headers}),this.logger&&this.logger.debug("Attachment added from data",{contentType:r,filename:e.filename}),this}async embedFromPath(t,e){try{const r=await c(t),i=e?.filename??(g(t)||"inline"),s=e?.contentType??d(i),h=u(i);return this.attachments.push({cid:h,content:r,contentDisposition:"inline",contentType:s,filename:i}),this.logger&&this.logger.debug(`Inline attachment embedded from path: ${t}`,{cid:h,contentType:s,filename:i}),h}catch(r){throw this.logger&&this.logger.error(`Failed to embed file from path: ${t}`,r),r}}embedData(t,e,r){const i=r?.contentType??d(e),s=u(e);return this.attachments.push({cid:s,content:t,contentDisposition:"inline",contentType:i,filename:e}),this.logger&&this.logger.debug("Inline attachment embedded from data",{cid:s,contentType:i,filename:e}),s}replyTo(t){return this.replyToAddress=typeof t=="string"?{email:t}:t,this}date(t){return this.dateValue=typeof t=="string"?new Date(t):t,this.logger&&this.logger.debug("Date header set",{date:this.dateValue.toISOString()}),this}returnPath(t){return this.returnPathAddress=typeof t=="string"?{email:t}:t,this.logger&&this.logger.debug("Return-path address set",{returnPath:this.returnPathAddress.email}),this}sender(t){return this.senderAddress=typeof t=="string"?{email:t}:t,this.logger&&this.logger.debug("Sender address set",{sender:this.senderAddress.email}),this}addTo(t){return this.toAddresses.push(...a(t)),this}addCc(t){return this.ccAddresses.push(...a(t)),this}addBcc(t){return this.bccAddresses.push(...a(t)),this}addReplyTo(t){const e=Array.isArray(t)?t:[t];if(e.length>0){const r=e[0];this.replyToAddress=typeof r=="string"?{email:r}:r}return this}addFrom(t){const e=Array.isArray(t)?t:[t];if(e.length>0){const r=e[0];this.fromAddress=typeof r=="string"?{email:r}:r}return this}priority(t){return this.priorityValue=t,this}tags(t){return this.tagsValue=Array.isArray(t)?t:[t],this}sign(t){return this.signer=t,this.logger&&this.logger.debug("Email signer configured"),this}encrypt(t){return this.encrypter=t,this.logger&&this.logger.debug("Email encrypter configured"),this}setLogger(t){return this.logger=T("MailMessage",t),this}icalEvent(t,e){return typeof t=="function"?(this.icalEventBuilder={build:t,options:e},this.icalEventData=void 0):(this.icalEventBuilder=void 0,this.icalEventData={content:t,...e}),this.logger&&this.logger.debug("Calendar event attached",{method:e?.method}),this}icalEventFromFile(t,e){const r=typeof t=="string"?t:b(t);return this.icalEventData={path:r,...e},this.logger&&this.logger.debug(`Calendar event attached from file: ${r}`,{method:e?.method}),this}icalEventFromUrl(t,e){return this.icalEventData={href:t,...e},this.logger&&this.logger.debug(`Calendar event attached from URL: ${t}`,{method:e?.method}),this}async view(t,e,r,i){try{const s=i?.autoText!==!1;this.autoTextEnabled=s,this.logger&&this.logger.debug("Rendering template",{autoText:s});const h=await t(e,r,i);this.html(h),s&&h&&await this.tryAutoGenerateText(h),this.logger&&this.logger.debug("Template rendered successfully")}catch(s){throw this.logger&&this.logger.error("Failed to render template",s),new Error(`Failed to render template: ${s.message}`)}return this}async viewText(t,e,r,i){try{this.logger&&this.logger.debug("Rendering text template");const s=await t(e,r,i);if(typeof s=="string")this.text(s),this.logger&&this.logger.debug("Text template rendered successfully");else throw new TypeError("Text renderer must return a string")}catch(s){throw this.logger&&this.logger.error("Failed to render text template",s),new Error(`Failed to render text template: ${s.message}`)}return this}async build(){if(this.logger&&this.logger.debug("Building email message"),this.fromAddress||this.throwAndLogError("From address is required","Build failed: from address is required"),this.toAddresses.length===0&&this.throwAndLogError("At least one recipient is required","Build failed: at least one recipient is required"),this.subjectText||this.throwAndLogError("Subject is required","Build failed: subject is required"),this.htmlContent&&!this.textContent&&this.autoTextEnabled)try{const e=await m();this.textContent=e(this.htmlContent),this.logger&&this.logger.debug("Auto-generated text content from HTML")}catch{this.logger&&this.logger.debug("Failed to convert HTML to text; proceeding without text content.")}!this.textContent&&!this.htmlContent&&this.throwAndLogError("Either text or html content is required","Build failed: either text or html content is required");let t={from:this.fromAddress,html:this.htmlContent,subject:this.subjectText,text:this.textContent,to:this.toAddresses.length===1?this.toAddresses[0]:this.toAddresses};if(this.ccAddresses.length>0&&(t.cc=this.ccAddresses.length===1?this.ccAddresses[0]:this.ccAddresses),this.bccAddresses.length>0&&(t.bcc=this.bccAddresses.length===1?this.bccAddresses[0]:this.bccAddresses),Object.keys(this.headers).length>0&&(t.headers=this.headers),this.attachments.length>0&&(t.attachments=this.attachments,this.logger&&this.logger.debug(`Email includes ${this.attachments.length} attachment(s)`)),this.replyToAddress&&(t.replyTo=this.replyToAddress),this.priorityValue&&(t.priority=this.priorityValue),this.tagsValue.length>0&&(t.tags=this.tagsValue),this.icalEventBuilder){const r=(await x())();this.icalEventBuilder.build(r),this.icalEventData={content:r.toString(),...this.icalEventBuilder.options}}return this.icalEventData&&(t.icalEvent=this.icalEventData,this.logger&&this.logger.debug("Email includes calendar event")),this.dateValue&&(t.headers={...l(t.headers??{}),Date:this.dateValue.toUTCString()}),this.returnPathAddress&&(t.headers={...l(t.headers??{}),"Return-Path":this.returnPathAddress.email}),this.senderAddress&&(t.headers={...l(t.headers??{}),Sender:this.senderAddress.email}),this.signer&&(this.logger&&this.logger.debug("Signing email message"),t=await this.signer.sign(t),this.logger&&this.logger.debug("Email message signed successfully")),this.encrypter&&(this.logger&&this.logger.debug("Encrypting email message"),t=await this.encrypter.encrypt(t),this.logger&&this.logger.debug("Email message encrypted successfully")),this.logger&&this.logger.debug("Email message built successfully",{bcc:this.bccAddresses.length,cc:this.ccAddresses.length,hasHtml:!!this.htmlContent,hasText:!!this.textContent,to:this.toAddresses.length}),t}getSubject(){return this.subjectText}getFrom(){return this.fromAddress}getTo(){return[...this.toAddresses]}getCc(){return[...this.ccAddresses]}getBcc(){return[...this.bccAddresses]}getReplyTo(){return this.replyToAddress}getSender(){return this.senderAddress}getReturnPath(){return this.returnPathAddress}getDate(){return this.dateValue}getPriority(){return this.priorityValue}getTextBody(){return this.textContent}getTextCharset(){return this.textCharset}getHtmlBody(){return this.htmlContent}getHtmlCharset(){return this.htmlCharset}getAttachments(){return[...this.attachments]}async tryAutoGenerateText(t){try{const r=(await m())(t);r&&!this.textContent&&this.text(r),this.logger&&this.logger.debug("Auto-generated text content from HTML template")}catch(e){this.logger&&this.logger.warn("Failed to auto-generate text from HTML template",e)}}throwAndLogError(t,e){const r=new Error(t);throw this.logger&&this.logger.error(e??t),r}}export{D as default};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createRequire as O}from"node:module";import{
|
|
1
|
+
import{createRequire as O}from"node:module";import{readFile as I}from"../packem_chunks/index.js";import{fromBER as S,OctetString as B}from"asn1js";import{Certificate as P,EnvelopedData as G,EncryptedContentInfo as V,id_ContentType_Data as J,RecipientInfo as Q,KeyTransRecipientInfo as W,IssuerAndSerialNumber as X,AlgorithmIdentifier as $,ContentInfo as Y,id_ContentType_EnvelopedData as Z}from"pkijs";let F;const L=o=>(F??=O(import.meta.url))(o),y=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,q=o=>{if(typeof y<"u"&&y.versions&&y.versions.node){const[e,t]=y.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return y.getBuiltinModule(o)}return L(o)},{randomBytes:T,createCipheriv:U,createPublicKey:z,publicEncrypt:H}=q("node:crypto"),g=globalThis.Buffer!==void 0,D=o=>{const e=o.replaceAll(/-----BEGIN[^-]+-----/g,"").replaceAll(/-----END[^-]+-----/g,"").replaceAll(/\s/g,"");if(g)return Buffer.from(e,"base64");const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.charCodeAt(n);return r},j=(o,e)=>{let t;if(g)t=Buffer.from(o).toString("base64");else{const n=new Uint8Array(o);let l="";const s=8192;for(let c=0;c<n.length;c+=s){const h=n.subarray(c,Math.min(c+s,n.length));l+=String.fromCharCode(...h)}t=btoa(l)}const r=t.match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}
|
|
4
4
|
-----END ${e}-----
|
|
5
|
-
`};class i{static collectRecipients(e){const t=[],r=n=>{if(!n)return;const l=Array.isArray(n)?n:[n];for(const
|
|
6
|
-
`)}}const
|
|
5
|
+
`};class i{static collectRecipients(e){const t=[],r=n=>{if(!n)return;const l=Array.isArray(n)?n:[n];for(const s of l){const c=typeof s=="string"?s:s.email;c&&t.push(c)}};return r(e.to),r(e.cc),r(e.bcc),[...new Set(t)]}static formatAddress(e){return typeof e=="string"?e:e.name?`"${e.name}" <${e.email}>`:e.email}static formatAddresses(e){return(Array.isArray(e)?e:[e]).map(r=>i.formatAddress(r)).join(", ")}options;constructor(e){this.options=e}async encrypt(e){const t=i.collectRecipients(e),r=[];if(typeof this.options.certificates=="string"){const a=await I(this.options.certificates,{encoding:"utf8"}),f=D(a),u=S(f);if(u.offset===-1)throw new Error("Failed to parse certificate: Invalid ASN.1 structure");r.push(new P({schema:u.result}))}else{const a=t.map(async f=>{const u=this.options.certificates[f];if(!u)throw new Error(`No certificate found for recipient: ${f}`);const A=await I(u,{encoding:"utf8"}),E=D(A),p=S(E);if(p.offset===-1)throw new Error(`Failed to parse certificate for ${f}: Invalid ASN.1 structure`);return new P({schema:p.result})});r.push(...await Promise.all(a))}const n=await this.buildMessage(e),l=new TextEncoder().encode(n),s=new G({version:0});s.encryptedContentInfo=new V({contentType:J});const h=(this.options.algorithm??"aes-256-cbc").toLowerCase();if(h==="3des"||h==="des-ede3-cbc")throw new Error("3DES/DES-EDE3-CBC is deprecated and insecure (Sweet32 vulnerability). Please use AES-256-CBC, AES-192-CBC, or AES-128-CBC instead.");let m,d;switch(h){case"aes128":case"aes-128-cbc":{m="2.16.840.1.101.3.4.1.2",d=16;break}case"aes192":case"aes-192-cbc":{m="2.16.840.1.101.3.4.1.22",d=24;break}default:{m="2.16.840.1.101.3.4.1.42",d=32;break}}const w=T(d),k=g?w:new Uint8Array(w),C=T(16),_=g?C:new Uint8Array(C),v=U(`aes-${d*8}-cbc`,w,C),x=Buffer.from(l),N=[v.update(x),v.final()],b=Buffer.concat(N);s.encryptedContentInfo.encryptedContent=new B({valueHex:b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength)});const R=await Promise.all(r.map(async a=>{const f=a.toSchema().toBER(!1),u=j(f,"CERTIFICATE"),A=z(u),E=Buffer.from(k),p=H({key:A,padding:1},E);return new Q({value:new W({encryptedKey:new B({valueHex:p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength)}),keyEncryptionAlgorithm:new $({algorithmId:"1.2.840.113549.1.1.1"}),rid:new X({issuer:a.issuer,serialNumber:a.serialNumber}),version:0}),variant:0})}));s.recipientInfos.push(...R),s.encryptedContentInfo.contentEncryptionAlgorithm=new $({algorithmId:m,algorithmParams:new B({valueHex:_.buffer})});const K=new Y({content:s.toSchema(),contentType:Z}).toSchema().toBER(!1),M=j(K,"PKCS7");return{...e,headers:{...e.headers,"Content-Disposition":"attachment; filename=smime.p7m","Content-Transfer-Encoding":"base64","Content-Type":"application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m"},html:void 0,text:M}}async buildMessage(e){const t=[`From: ${i.formatAddress(e.from)}`,`To: ${i.formatAddresses(e.to)}`,...e.cc?[`Cc: ${i.formatAddresses(e.cc)}`]:[]];if(e.replyTo&&t.push(`Reply-To: ${i.formatAddress(e.replyTo)}`),t.push(`Subject: ${e.subject}`,"MIME-Version: 1.0"),e.headers)for(const[r,n]of Object.entries(e.headers))t.push(`${r}: ${n}`);return e.html?t.push("Content-Type: text/html; charset=utf-8"):e.text&&t.push("Content-Type: text/plain; charset=utf-8"),t.push(""),e.html?t.push(e.html):e.text&&t.push(e.text),t.join(`\r
|
|
6
|
+
`)}}const oe=o=>new i(o);export{i as SmimeEncrypter,oe as createSmimeEncrypter};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{createRequire as
|
|
1
|
+
import{createRequire as q}from"node:module";import{readFile as y}from"../packem_chunks/index.js";import{fromBER as D,ObjectIdentifier as W,OctetString as I,UTCTime as X}from"asn1js";import{Certificate as j,SignedData as Y,EncapsulatedContentInfo as Z,id_ContentType_Data as x,SignerInfo as ee,AlgorithmIdentifier as E,IssuerAndSerialNumber as te,id_sha256 as ne,SignedAndUnsignedAttributes as se,Attribute as b,ContentInfo as re,id_ContentType_SignedData as oe}from"pkijs";import{g as ie}from"./generate-boundary-BCSUEi6x.js";let V;const z=o=>(V??=q(import.meta.url))(o),p=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,G=o=>{if(typeof p<"u"&&p.versions&&p.versions.node){const[e,t]=p.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return p.getBuiltinModule(o)}return z(o)},{createPrivateKey:B,createHash:L,createSign:J,randomBytes:Q}=G("node:crypto"),ae="1.2.840.113549.1.9.3",ce="1.2.840.113549.1.9.4",ue="1.2.840.113549.1.9.5",fe="1.2.840.113549.1.1.1",pe={v1:1},le={v1:1},l=globalThis.Buffer!==void 0,N=o=>{const e=o.replaceAll(/-----BEGIN[^-]+-----/g,"").replaceAll(/-----END[^-]+-----/g,"").replaceAll(/\s/g,"");if(l)return Buffer.from(e,"base64");const t=atob(e),s=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)s[n]=t.codePointAt(n);return s},de=(o,e)=>{let t;if(l)t=Buffer.from(o).toString("base64");else{const n=new Uint8Array(o);let r="";const a=8192;for(let i=0;i<n.length;i+=a){const h=n.subarray(i,Math.min(i+a,n.length));r+=String.fromCharCode(...h)}t=btoa(r)}const s=t.match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----
|
|
2
2
|
${s.join(`
|
|
3
3
|
`)}
|
|
4
4
|
-----END ${e}-----
|
|
5
|
-
`};class d{static formatAddress(e){return e.name?`"${e.name.replaceAll("\\","\\\\").replaceAll('"',String.raw`\"`)}" <${e.email}>`:e.email}options;constructor(e){this.options=e}async sign(e){const t=await y(this.options.certificate,{encoding:"utf8"}),s=await y(this.options.privateKey,{encoding:"utf8"}),n=N(t),r=D(n);if(r.offset===-1)throw new Error("Failed to parse certificate: Invalid ASN.1 structure");const a=new j({schema:r.result});let i;try{i=this.options.passphrase?B({key:s,passphrase:this.options.passphrase}):B(s)}catch(c){throw new Error(`Failed to parse private key: ${c.message}`)}const h=[];if(this.options.intermediateCerts){const c=this.options.intermediateCerts.map(async _=>{const
|
|
5
|
+
`};class d{static formatAddress(e){return e.name?`"${e.name.replaceAll("\\","\\\\").replaceAll('"',String.raw`\"`)}" <${e.email}>`:e.email}options;constructor(e){this.options=e}async sign(e){const t=await y(this.options.certificate,{encoding:"utf8"}),s=await y(this.options.privateKey,{encoding:"utf8"}),n=N(t),r=D(n);if(r.offset===-1)throw new Error("Failed to parse certificate: Invalid ASN.1 structure");const a=new j({schema:r.result});let i;try{i=this.options.passphrase?B({key:s,passphrase:this.options.passphrase}):B(s)}catch(c){throw new Error(`Failed to parse private key: ${c.message}`)}const h=[];if(this.options.intermediateCerts){const c=this.options.intermediateCerts.map(async _=>{const F=await y(_,{encoding:"utf8"}),H=N(F),$=D(H);if($.offset===-1)throw new Error(`Failed to parse intermediate certificate ${_}: Invalid ASN.1 structure`);return new j({schema:$.result})});h.push(...await Promise.all(c))}const A=this.buildMessage(e),w=new TextEncoder().encode(A),m=new Y({version:pe.v1});m.encapContentInfo=new Z({eContentType:x});const g=new ee({digestAlgorithm:new E({algorithmId:ne}),sid:new te({issuer:a.issuer,serialNumber:a.serialNumber}),signatureAlgorithm:new E({algorithmId:fe}),version:le.v1}),C=L("sha256");C.update(l?Buffer.from(w):w);const P=C.digest(),M=new Uint8Array(P),T=new se({attributes:[new b({type:ae,values:[new W({value:x})]}),new b({type:ce,values:[new I({valueHex:M.buffer.slice(0)})]}),new b({type:ue,values:[new X({valueDate:new Date})]})]});g.signedAttrs=T;const v=T.toSchema().toBER(!1),R=l?Buffer.from(v):new Uint8Array(v),S=J("RSA-SHA256");S.update(R);const u=S.sign(i),k=l?u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength):u.buffer;g.signature=new I({valueHex:k}),m.signerInfos.push(g),m.certificates=[a,...h];const K=new re({content:m.toSchema(),contentType:oe}).toSchema().toBER(!1),O=de(K,"PKCS7"),f=`----_=_NextPart_${Date.now()}_${Q(8).toString("hex")}`,U=[`Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256; boundary="${f}"`,"",`--${f}`,A,`--${f}`,"Content-Type: application/pkcs7-signature; name=smime.p7s","Content-Transfer-Encoding: base64","Content-Disposition: attachment; filename=smime.p7s","",O.split(`
|
|
6
6
|
`).filter(c=>c.trim()&&!c.includes("-----")).join(""),`--${f}--`].join(`\r
|
|
7
7
|
`);return{...e,headers:{...e.headers,"Content-Type":`multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256; boundary="${f}"`},html:void 0,text:U}}buildMessage(e){const t=[`From: ${d.formatAddress(e.from)}`,`To: ${this.formatAddresses(e.to)}`];if(e.cc&&t.push(`Cc: ${this.formatAddresses(e.cc)}`),e.replyTo&&t.push(`Reply-To: ${d.formatAddress(e.replyTo)}`),t.push(`Subject: ${e.subject}`,"MIME-Version: 1.0"),e.headers)for(const[a,i]of Object.entries(e.headers))t.push(`${a}: ${i}`);const s=!!e.text,n=!!e.html;let r;return s&&n?(r=ie(),t.push(`Content-Type: multipart/alternative; boundary="${r}"`)):n?t.push("Content-Type: text/html; charset=utf-8"):t.push("Content-Type: text/plain; charset=utf-8"),t.push(""),s&&n&&r?t.push(`--${r}`,"Content-Type: text/plain; charset=utf-8","",e.text,"",`--${r}`,"Content-Type: text/html; charset=utf-8","",e.html,"",`--${r}--`):s?t.push(e.text):n&&t.push(e.html),t.join(`\r
|
|
8
8
|
`)}formatAddresses(e){return(Array.isArray(e)?e:[e]).map(s=>d.formatAddress(s)).join(", ")}}const we=o=>new d(o);export{d as SmimeSigner,we as createSmimeSigner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{f as m}from"./format-address-Bb7xk8G_.js";const e=r=>m(r),o=r=>(Array.isArray(r)?r:[r]).map(t=>e(t)),i=r=>{const a={email:r.email};return r.name&&(a.name=r.name),a},f=r=>(Array.isArray(r)?r:[r]).map(t=>i(t)),u=r=>(Array.isArray(r)?r:[r]).map(t=>t.email),A=r=>({email:r.email,...r.name&&{displayName:r.name}}),y=r=>(Array.isArray(r)?r:[r]).map(t=>A(t)),c=r=>{const a={Email:r.email};return r.name&&(a.Name=r.name),a},L=r=>(Array.isArray(r)?r:[r]).map(t=>c(t)),l=(r,a="to")=>({email:r.email,...r.name&&{name:r.name},type:a}),p=(r,a="to")=>(Array.isArray(r)?r:[r]).map(n=>l(n,a)),s=r=>({address:r.email,...r.name&&{name:r.name}}),M=r=>(Array.isArray(r)?r:[r]).map(t=>s(t)),j=r=>o(r),z=r=>s(r);export{i as a,y as b,A as c,u as d,o as e,f,e as g,L as h,c as i,j,p as k,M as l,s as m,z as n};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"./EmailError-BIaHK1Uw.js";import b from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as u}from"./make-request-Cyz5_yu8.js";import{r as h}from"./retry-aghj7y8m.js";import{v as w}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as A}from"./defineProvider-C9q-7iwt.js";import{c as T,h as g,P as I}from"./provider-base-BEz00m9R.js";import{f as l,a as P}from"./address-formatter-
|
|
1
|
+
import c from"./EmailError-BIaHK1Uw.js";import b from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as u}from"./make-request-Cyz5_yu8.js";import{r as h}from"./retry-aghj7y8m.js";import{v as w}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as A}from"./defineProvider-C9q-7iwt.js";import{c as T,h as g,P as I}from"./provider-base-BEz00m9R.js";import{f as l,a as P}from"./address-formatter-w36S9ZYj.js";import{p as S}from"./attachment-processor-BJFDS343.js";const t="ahasend",C="https://api.ahasend.com",R=3e4,$=3,N=A((o={})=>{if(!o.apiKey)throw new b(t,"apiKey");const a={apiKey:o.apiKey,debug:o.debug??!1,endpoint:o.endpoint??C,retries:o.retries??$,timeout:o.timeout??R,...o.logger&&{logger:o.logger}},y=new I,s=T(t,o.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new c(t,"Email ID is required to retrieve email details"),success:!1};await this.initialize();const i={Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"};s.debug("Retrieving email details",{id:e});const r=await h(async()=>u(`${a.endpoint}/emails/${e}`,{headers:i,method:"GET",timeout:a.timeout}),a.retries);return r.success?(s.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(s.debug("API request failed when retrieving email",r.error),{error:new c(t,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(i){return{error:g(t,"retrieve email",i,s),success:!1}}},async initialize(){await y.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(t,"AhaSend API not available or invalid API key");s.debug("Provider initialized successfully")},t)},async isAvailable(){try{s.debug("Checking AhaSend API availability");const e=await u(`${a.endpoint}/v2/ping`,{headers:{Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"},method:"GET",timeout:a.timeout});if(e.success)return!0;const i=e.data?.statusCode??e.error?.statusCode;return!1}catch(e){return s.debug("Error checking availability:",e),!1}},name:t,options:a,async sendEmail(e){try{const i=w(e);if(i.length>0)return{error:new c(t,`Invalid email options: ${i.join(", ")}`),success:!1};await this.initialize();const r={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:l(e.to)};if(e.html&&(r.html=e.html),e.text&&(r.text=e.text),e.cc&&(r.cc=l(e.cc)),e.bcc&&(r.bcc=l(e.bcc)),e.replyTo&&(r.replyTo=P(e.replyTo)),e.templateId&&(r.templateId=e.templateId,e.templateVariables&&(r.templateVariables=e.templateVariables)),e.tags&&e.tags.length>0&&(r.tags=e.tags),e.headers){const n=E(e.headers);r.headers=n}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async n=>({content:await S(n,t),contentType:n.contentType??"application/octet-stream",filename:n.filename,...n.cid&&{cid:n.cid}})))),s.debug("Sending email via AhaSend API",{subject:r.subject,to:r.to});const p={Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json"},d=await h(async()=>u(`${a.endpoint}/send`,{headers:p,method:"POST",timeout:a.timeout},JSON.stringify(r)),a.retries);if(!d.success)return s.debug("API request failed when sending email",d.error),{error:d.error??new c(t,"Failed to send email"),success:!1};const m=d.data?.body,f=m?.messageId??m?.id??v();return s.debug("Email sent successfully",{messageId:f}),{data:{messageId:f,provider:t,response:d.data,sent:!0,timestamp:new Date},success:!0}}catch(i){return{error:g(t,"send email",i,s),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{N as default};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{createRequire as I}from"node:module";import{readFile as W}from"../packem_chunks/index.js";import{s as T,o as J,p as D,c as K,a as y}from"./canonicalize-BEjQUnUe.js";let V;const F=a=>(V??=I(import.meta.url))(a),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,E=a=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[e,s]=f.versions.node.split(".").map(Number);if(e>22||e===22&&s>=3||e===20&&s>=16)return f.getBuiltinModule(a)}return F(a)},{Buffer:H}=E("node:buffer"),{createHash:b,createPublicKey:O,createPrivateKey:q,sign:G,createSign:U,verify:M}=E("node:crypto"),Q=/^\s*i=(\d+)\s*;/,X=["from","to","cc","subject","date","message-id","mime-version"],m=(a,e)=>y(a,e,"relaxed"),_=a=>{const e={};for(const s of a.split(";")){const t=s.indexOf("=");t!==-1&&(e[s.slice(0,t).trim()]=s.slice(t+1).trim())}return e},j=a=>{const e=a.lastIndexOf("b=");return e===-1?a:a.slice(0,e+2)},B=(a,e,s)=>s==="ed25519-sha256"?G(null,b("sha256").update(a).digest(),e).toString("base64"):U("RSA-SHA256").update(a).sign(e,"base64"),x=(a,e,s,t)=>{const n=H.from(e,"base64");try{return t==="ed25519-sha256"?M(null,b("sha256").update(a).digest(),s,n):M("RSA-SHA256",H.from(a),s,n)}catch{return!1}},Y=(a,e)=>{const s=T(a);if(s===void 0)throw new Error("Failed to seal with ARC: the message has no CRLFCRLF header/body separator, so it is not a complete MIME message.");const t=e.instance??1,n=e.algorithm??"rsa-sha256",l=e.timestamp??Math.floor(Date.now()/1e3),d=new Set(e.headersToSign??X),r=J(D(s.headersPart).filter(c=>d.has(c.name.toLowerCase())&&c.value.trim()!=="")),o=b("sha256").update(K(s.body,"relaxed")).digest("base64"),i=[`i=${String(t)}`,`a=${n}`,"c=relaxed/relaxed",`d=${e.domainName}`,`s=${e.keySelector}`,`t=${String(l)}`,`h=${r.map(c=>c.name.toLowerCase()).join(":")}`,`bh=${o}`,"b="].join("; "),g=`${r.map(c=>y(c.name,c.value,"relaxed")).join(`\r
|
|
2
|
+
`)}\r
|
|
3
|
+
${m("ARC-Message-Signature",i)}`;return{header:i,signBase:g}},Z=(a,e,s)=>{const t=s.instance??1,n=s.algorithm??"rsa-sha256",l=s.timestamp??Math.floor(Date.now()/1e3),d=s.cv??"none",r=[`i=${String(t)}`,`a=${n}`,`cv=${d}`,`d=${s.domainName}`,`s=${s.keySelector}`,`t=${String(l)}`,"b="].join("; "),o=[m("ARC-Authentication-Results",a),m("ARC-Message-Signature",e),m("ARC-Seal",r)].join(`\r
|
|
4
|
+
`);return{header:r,signBase:o}},ee=async(a,e)=>{let s=a;return s.startsWith("file://")&&(s=await W(s.slice(7),{encoding:"utf8"})),q({key:s,passphrase:e})},re=async(a,e)=>{const s=e.instance??1,t=e.cv??"none";if(s!==1)throw new Error(`signArc only supports an originating sealer (instance 1); received i=${String(s)}`);if(t!=="none")throw new Error(`signArc only supports cv=none for an originating sealer; received cv=${t}`);const n=e.algorithm??"rsa-sha256",l={...e,cv:"none",timestamp:e.timestamp??Math.floor(Date.now()/1e3)},d=await ee(e.privateKey,e.passphrase),r=`i=${String(s)}; ${e.authenticationResults}`,o=Y(a,l),i=`${o.header}${B(o.signBase,d,n)}`,p=Z(r,i,l),g=`${p.header}${B(p.signBase,d,n)}`,c={"ARC-Authentication-Results":r,"ARC-Message-Signature":i,"ARC-Seal":g},h=[`ARC-Seal: ${g}`,`ARC-Message-Signature: ${i}`,`ARC-Authentication-Results: ${r}`].join(`\r
|
|
5
|
+
`);return{headers:c,message:`${h}\r
|
|
6
|
+
${a}`}},oe=(a,e,s)=>{const t=Object.fromEntries(Object.entries(e).map(([u,v])=>[u.toLowerCase(),v])),n=t["arc-message-signature"],l=t["arc-seal"],d=t["arc-authentication-results"];if(!n||!l||!d)return{components:{ams:!1,bodyHash:!1,seal:!1},reason:"missing-arc-headers",valid:!1};let r;try{r=typeof s.publicKey=="string"?O(s.publicKey):s.publicKey}catch{return{components:{ams:!1,bodyHash:!1,seal:!1},reason:"invalid-public-key",valid:!1}}const o=_(n),i=_(l);if(Q.exec(d)?.[1]!=="1"||o.i!=="1"||i.i!=="1"||i.cv!=="none")return{components:{ams:!1,bodyHash:!1,seal:!1},cv:i.cv,reason:"unsupported-arc-instance",valid:!1};const g=o.a==="ed25519-sha256"?"ed25519-sha256":"rsa-sha256",c=i.a==="ed25519-sha256"?"ed25519-sha256":"rsa-sha256",h=T(a);if(h===void 0)return{components:{ams:!1,bodyHash:!1,seal:!1},reason:"malformed-message",valid:!1};const A=o.bh!==void 0&&o.bh===b("sha256").update(K(h.body,"relaxed")).digest("base64"),L=D(h.headersPart),N=(o.h??"").split(":").map(u=>u.trim().toLowerCase()).filter(Boolean),S=new Map,z=`${N.map(u=>{const v=L.filter(k=>k.name.toLowerCase()===u),w=S.get(u)??0;return S.set(u,w+1),y(u,v[v.length-1-w]?.value??"","relaxed")}).join(`\r
|
|
7
|
+
`)}\r
|
|
8
|
+
${m("ARC-Message-Signature",j(n))}`,$=x(z,o.b??"",r,g),P=[m("ARC-Authentication-Results",d),m("ARC-Message-Signature",n),m("ARC-Seal",j(l))].join(`\r
|
|
9
|
+
`),R=x(P,i.b??"",r,c),C=$&&R&&A;return{components:{ams:$,bodyHash:A,seal:R},cv:i.cv,reason:C?void 0:"signature-mismatch",valid:C}};export{Y as arcMessageSignatureBase,Z as arcSealBase,re as signArc,oe as verifyArc};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import d from"./EmailError-BIaHK1Uw.js";import _ from"./RequiredOptionError-ctDEEB1s.js";import{h as N}from"./headers-to-record-ZOZ7Dubo.js";import{m as k}from"./make-request-Cyz5_yu8.js";import{r as D}from"./retry-aghj7y8m.js";import{s as M,a as j}from"./sanitize-header-CW0f3IT7.js";import{v as C}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as H}from"./defineProvider-C9q-7iwt.js";import{c as P,h as L,P as U}from"./provider-base-BEz00m9R.js";import{a as b,f as y}from"./address-formatter-
|
|
1
|
+
import d from"./EmailError-BIaHK1Uw.js";import _ from"./RequiredOptionError-ctDEEB1s.js";import{h as N}from"./headers-to-record-ZOZ7Dubo.js";import{m as k}from"./make-request-Cyz5_yu8.js";import{r as D}from"./retry-aghj7y8m.js";import{s as M,a as j}from"./sanitize-header-CW0f3IT7.js";import{v as C}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as H}from"./defineProvider-C9q-7iwt.js";import{c as P,h as L,P as U}from"./provider-base-BEz00m9R.js";import{a as b,f as y}from"./address-formatter-w36S9ZYj.js";import{c as z}from"./attachment-processor-BJFDS343.js";const n="autosend",G="https://api.autosend.com/v1",x=3e4,B=3,p=50,v=20,T=40*1024*1024,w=20,$=1e3,I=998,F=/^[A-Z0-9-]{1,76}$/i,K="^[A-Za-z0-9-]{1,76}$",X="Either text or html content is required",h=t=>[t].flat(),q=async t=>{const s=await z(t,n);return{content:s.content,contentType:s.contentType,fileName:s.filename}},V=(t,s)=>{const c=h(t.to);if(c.length!==1)return`AutoSend's send endpoint takes exactly one 'to' recipient, but ${String(c.length)} were given — use 'cc'/'bcc', or send one message per recipient`;const o=c.length+(t.cc?h(t.cc).length:0)+(t.bcc?h(t.bcc).length:0);if(o>p)return`AutoSend allows at most ${String(p)} recipients across to/cc/bcc, but ${String(o)} were given`;if(t.attachments&&t.attachments.length>v)return`AutoSend allows at most ${String(v)} attachments, but ${String(t.attachments.length)} were given`;const e=t.attachments?.find(r=>r.cid);if(e)return`AutoSend does not support inline (cid) attachments, but '${e.filename}' sets one — host the image and reference it by URL instead`;if(t.subject.length>I)return`AutoSend allows a subject of at most ${String(I)} characters, but ${String(t.subject.length)} were given`;const a=Object.keys(s);if(a.length>w)return`AutoSend allows at most ${String(w)} custom headers, but ${String(a.length)} were given`;const i=a.find(r=>!F.test(r));if(i!==void 0)return`AutoSend header names must match ${K}, but '${i}' does not`;const l=a.find(r=>s[r].length>$);if(l!==void 0)return`AutoSend allows header values of at most ${String($)} characters, but '${l}' is longer`},J=t=>{if(typeof t!="object"||t===null)return{};const s=t;if(s.success===!0)return{emailId:typeof s.data?.emailId=="string"?s.data.emailId:void 0};const c=[s.message,s.error].find(o=>typeof o=="string");return{reason:typeof c=="string"?c:void 0}},ce=H((t={})=>{if(!t.apiKey)throw new _(n,"apiKey");const s={apiKey:t.apiKey,debug:t.debug??!1,endpoint:t.endpoint??G,logger:t.logger,retries:t.retries??B,timeout:t.timeout??x},c=new U,o=P(n,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!0,tracking:!0},async initialize(){c.setInitialized()},async isAvailable(){return s.apiKey.length>0},name:n,options:s,async sendEmail(e){try{const a=C(e).filter(u=>!(e.templateId!==void 0&&u===X));if(a.length>0)return{error:new d(n,`Invalid email options: ${a.join(", ")}`),success:!1};const i=e.headers?N(e.headers):{},l=V(e,i);if(l)return{error:new d(n,l),success:!1};const r={from:b(e.from),subject:e.subject,to:b(h(e.to)[0])};if(e.templateId?r.templateId=e.templateId:(e.html&&(r.html=e.html),e.text&&(r.text=e.text)),e.cc&&(r.cc=y(e.cc)),e.bcc&&(r.bcc=y(e.bcc)),e.replyTo&&(r.replyTo=b(e.replyTo)),e.dynamicData&&(r.dynamicData=e.dynamicData),e.unsubscribeGroupId&&(r.unsubscribeGroupId=e.unsubscribeGroupId),e.trackingClick!==void 0&&(r.trackingClick=e.trackingClick),e.trackingOpen!==void 0&&(r.trackingOpen=e.trackingOpen),e.bypassSuppressions!==void 0&&(r.bypassSuppressions=e.bypassSuppressions),Object.keys(i).length>0&&(r.headers=Object.fromEntries(Object.entries(i).map(([u,m])=>[M(u),j(m)]))),e.attachments&&e.attachments.length>0){const u=await Promise.all(e.attachments.map(async A=>q(A))),m=u.reduce((A,R)=>A+R.content.length,0);if(m>T)return{error:new d(n,`AutoSend allows at most ${String(T)} bytes of attachments after Base64 encoding, but this message carries ${String(m)}`),success:!1};r.attachments=u}const g=await D(async()=>k(`${s.endpoint}/mails/send`,{headers:{Authorization:`Bearer ${s.apiKey}`,"Content-Type":"application/json"},method:"POST",timeout:s.timeout},JSON.stringify(r)),s.retries),S=g.data?.body,{emailId:E,reason:f}=J(S);return g.success?f?{error:new d(n,`Failed to send email: ${f}`),success:!1}:E?(o.debug(`Email queued successfully: ${E}`),{data:{messageId:E,provider:n,response:S,sent:!0,timestamp:new Date},success:!0}):{error:new d(n,"AutoSend accepted the message but returned no emailId"),success:!1}:{error:f?new d(n,`Failed to send email: ${f}`):g.error??new d(n,"Failed to send email"),success:!1}}catch(a){return{error:L(n,"send email",a,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{ce as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as A}from"node:module";import u from"./EmailError-BIaHK1Uw.js";import v from"./RequiredOptionError-ctDEEB1s.js";import{g as I}from"./generate-message-id-B2n2yqR6.js";import{h as _}from"./headers-to-record-ZOZ7Dubo.js";import{m as h}from"./make-request-Cyz5_yu8.js";import{r as T}from"./retry-aghj7y8m.js";import{v as P}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as j}from"./defineProvider-C9q-7iwt.js";import{c as $,P as B,h as w}from"./provider-base-BEz00m9R.js";import{b as y,c as R}from"./address-formatter-
|
|
1
|
+
import{createRequire as A}from"node:module";import u from"./EmailError-BIaHK1Uw.js";import v from"./RequiredOptionError-ctDEEB1s.js";import{g as I}from"./generate-message-id-B2n2yqR6.js";import{h as _}from"./headers-to-record-ZOZ7Dubo.js";import{m as h}from"./make-request-Cyz5_yu8.js";import{r as T}from"./retry-aghj7y8m.js";import{v as P}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as j}from"./defineProvider-C9q-7iwt.js";import{c as $,P as B,h as w}from"./provider-base-BEz00m9R.js";import{b as y,c as R}from"./address-formatter-w36S9ZYj.js";let E;const z=s=>(E??=A(import.meta.url))(s),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,k=s=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[l,r]=m.versions.node.split(".").map(Number);if(l>22||l===22&&r>=3||l===20&&r>=16)return m.getBuiltinModule(s)}return z(s)},{Buffer:p}=k("node:buffer"),o="azure",C=3e4,q=3,Q=j((s={})=>{if(!s.region)throw new v(o,"region");if(!s.connectionString&&!s.accessToken)throw new v(o,"connectionString or accessToken");const l=s.endpoint??`https://${s.region}.communication.azure.com`,r={debug:s.debug??!1,endpoint:l,region:s.region,retries:s.retries??q,timeout:s.timeout??C,...s.connectionString&&{connectionString:s.connectionString},...s.accessToken&&{accessToken:s.accessToken},...s.logger&&{logger:s.logger}},g=new B,a=$(o,s.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(o,"Email ID is required to retrieve email details"),success:!1};await g.ensureInitialized(()=>this.initialize(),o);const i={"Content-Type":"application/json"};if(r.accessToken)i.Authorization=`Bearer ${r.accessToken}`;else if(r.connectionString){const c=r.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);c&&(i.Authorization=`Bearer ${c[2]}`)}a.debug("Retrieving email details",{id:e});const t=await T(async()=>h(`${r.endpoint}/emails/${e}`,{headers:i,method:"GET",timeout:r.timeout}),r.retries);return t.success?(a.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(a.debug("API request failed when retrieving email",t.error),{error:new u(o,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(i){return{error:w(o,"retrieve email",i,a),success:!1}}},async initialize(){await g.ensureInitialized(async()=>{if(!await this.isAvailable())throw new u(o,"Azure Communication Services API not available or invalid credentials");a.debug("Provider initialized successfully")},o)},async isAvailable(){try{const e={"Content-Type":"application/json"};if(r.accessToken)e.Authorization=`Bearer ${r.accessToken}`;else if(r.connectionString){const c=r.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(c)e.Authorization=`Bearer ${c[2]}`;else return!1}else return!1;a.debug("Checking Azure Communication Services API availability");const i=await h(`${r.endpoint}/emails:send`,{headers:e,method:"POST",timeout:r.timeout},JSON.stringify({}));if(i.success)return!0;const t=i.data?.statusCode;return t===401||t===403?!1:t===400}catch(e){if(a.debug("Error checking availability:",e),e instanceof Error){const i=e.message;if(i.includes("401")||i.includes("403"))return!1}return!1}},name:o,options:r,async sendEmail(e){try{const i=P(e);if(i.length>0)return{error:new u(o,`Invalid email options: ${i.join(", ")}`),success:!1};await g.ensureInitialized(()=>this.initialize(),o);const t={content:{subject:e.subject},recipients:{to:y(e.to)},senderAddress:e.from.email};if(e.html&&(t.content.html=e.html),e.text&&(t.content.plainText=e.text),e.cc&&(t.recipients.cc=y(e.cc)),e.bcc&&(t.recipients.bcc=y(e.bcc)),e.replyTo&&(t.replyTo=R(e.replyTo).email),e.importance&&(t.importance=e.importance),e.headers){const n=_(e.headers);t.headers=n}e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async n=>{let f;if(n.content)if(typeof n.content=="string")f=p.from(n.content,"utf8").toString("base64");else if(n.content&&typeof n.content.then=="function"){const S=await n.content;f=p.from(S).toString("base64")}else f=n.content.toString("base64");else if(n.raw)f=typeof n.raw=="string"?p.from(n.raw,"utf8").toString("base64"):n.raw.toString("base64");else throw new u(o,`Attachment ${n.filename} has no content`);return{contentInBase64:f,contentType:n.contentType??"application/octet-stream",name:n.filename}}))),a.debug("Sending email via Azure Communication Services API",{subject:t.content.subject,to:t.recipients.to});const c={"Content-Type":"application/json"};if(r.accessToken)c.Authorization=`Bearer ${r.accessToken}`;else if(r.connectionString){const n=r.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(n)c.Authorization=`Bearer ${n[2]}`;else return{error:new u(o,"Invalid connection string format"),success:!1}}const d=await T(async()=>h(`${r.endpoint}/emails:send`,{headers:c,method:"POST",timeout:r.timeout},JSON.stringify(t)),r.retries);if(!d.success)return a.debug("API request failed when sending email",d.error),{error:d.error??new u(o,"Failed to send email"),success:!1};const b=d.data?.body?.messageId??I();return a.debug("Email sent successfully",{messageId:b}),{data:{messageId:b,provider:o,response:d.data,sent:!0,timestamp:new Date},success:!0}}catch(i){return{error:w(o,"send email",i,a),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{Q as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"./EmailError-BIaHK1Uw.js";import w from"./RequiredOptionError-ctDEEB1s.js";import{g as A}from"./generate-message-id-B2n2yqR6.js";import{h as I}from"./headers-to-record-ZOZ7Dubo.js";import{m as y}from"./make-request-Cyz5_yu8.js";import{r as g}from"./retry-aghj7y8m.js";import{v as E}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{c as C,P as R,h as b}from"./provider-base-BEz00m9R.js";import{f,a as m}from"./address-formatter-
|
|
1
|
+
import c from"./EmailError-BIaHK1Uw.js";import w from"./RequiredOptionError-ctDEEB1s.js";import{g as A}from"./generate-message-id-B2n2yqR6.js";import{h as I}from"./headers-to-record-ZOZ7Dubo.js";import{m as y}from"./make-request-Cyz5_yu8.js";import{r as g}from"./retry-aghj7y8m.js";import{v as E}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{c as C,P as R,h as b}from"./provider-base-BEz00m9R.js";import{f,a as m}from"./address-formatter-w36S9ZYj.js";import{p as S}from"./attachment-processor-BJFDS343.js";const t="brevo",k="https://api.brevo.com/v3",j=3e4,z=3,M=P((d={})=>{if(!d.apiKey)throw new w(t,"apiKey");const v=d.endpoint??k,s={apiKey:d.apiKey,debug:d.debug??!1,endpoint:v,hardValidation:d.hardValidation??!1,retries:d.retries??z,timeout:d.timeout??j,...d.logger&&{logger:d.logger}},l=new R,o=C(t,d.logger);return{endpoint:s.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(t,"Email ID is required to retrieve email details"),success:!1};await l.ensureInitialized(()=>this.initialize(),t);const r={"api-key":s.apiKey,"Content-Type":"application/json"};o.debug("Retrieving email details",{id:e});const i=await g(async()=>y(`${s.endpoint}/smtp/emails/${e}`,{headers:r,method:"GET",timeout:s.timeout}),s.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(t,`Failed to retrieve email: ${i.error instanceof Error?i.error.message:"Unknown error"}`,{cause:i.error}),success:!1})}catch(r){return{error:b(t,"retrieve email",r,o),success:!1}}},async initialize(){await l.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(t,"Brevo API not available or invalid API key");o.debug("Provider initialized successfully")},t)},async isAvailable(){try{const e={"api-key":s.apiKey,"Content-Type":"application/json"};o.debug("Checking Brevo API availability");const r=await y(`${s.endpoint}/account`,{headers:e,method:"GET",timeout:s.timeout});return o.debug("Brevo API availability check response:",{error:r.error instanceof Error?r.error.message:void 0,statusCode:r.data?.statusCode,success:r.success}),!!(r.success&&r.data&&typeof r.data=="object"&&"statusCode"in r.data&&typeof r.data.statusCode=="number"&&r.data.statusCode>=200&&r.data.statusCode<300)}catch(e){return o.debug("Error checking availability:",e),!1}},name:t,options:s,async sendEmail(e){try{let r;Array.isArray(e.replyTo)?r=e.replyTo.length>0?e.replyTo[0]:void 0:r=e.replyTo;const i={...e,replyTo:r},h=E(i);if(h.length>0)return{error:new c(t,`Invalid email options: ${h.join(", ")}`),success:!1};await l.ensureInitialized(()=>this.initialize(),t);const a={sender:m(e.from),subject:e.subject,to:f(e.to)};if(e.html&&(a.htmlContent=e.html),e.text&&(a.textContent=e.text),e.cc&&(a.cc=f(e.cc)),e.bcc&&(a.bcc=f(e.bcc)),e.replyTo)if(Array.isArray(e.replyTo)){if(s.hardValidation)return{error:new c(t,"Only one replyTo address is allowed"),success:!1};if(e.replyTo.length===0)return{error:new c(t,"replyTo array cannot be empty"),success:!1};const n=e.replyTo[0];if(!n)return{error:new c(t,"replyTo array cannot be empty"),success:!1};a.replyTo=m(n)}else a.replyTo=m(e.replyTo);if(e.templateId&&(a.templateId=e.templateId,e.templateParams&&(a.params=e.templateParams)),e.tags&&e.tags.length>0&&(a.tags=e.tags),e.scheduledAt){const n=typeof e.scheduledAt=="number"?new Date(e.scheduledAt*1e3).toISOString():e.scheduledAt;a.scheduledAt=n}if(e.batchId&&(a.batchId=e.batchId),e.headers){const n=I(e.headers);a.headers=n}e.attachments&&e.attachments.length>0&&(a.attachment=await Promise.all(e.attachments.map(async n=>({content:await S(n,t),name:n.filename,...n.contentType&&{type:n.contentType}})))),o.debug("Sending email via Brevo API",{subject:a.subject,to:a.to});const T={"api-key":s.apiKey,"Content-Type":"application/json"},u=await g(async()=>y(`${s.endpoint}/smtp/email`,{headers:T,method:"POST",timeout:s.timeout},JSON.stringify(a)),s.retries);if(!u.success)return o.debug("API request failed when sending email",u.error),{error:u.error??new c(t,"Failed to send email"),success:!1};const p=u.data?.body?.messageId??A();return o.debug("Email sent successfully",{messageId:p}),{data:{messageId:p,provider:t,response:u.data,sent:!0,timestamp:new Date},success:!0}}catch(r){return{error:b(t,"send email",r,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{M as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import M from"./EmailError-BIaHK1Uw.js";import m from"../utils/format-email-address.js";import{g as y}from"./generate-boundary-BCSUEi6x.js";import{h as v}from"./headers-to-record-ZOZ7Dubo.js";import{e as z}from"./quoted-printable-BgiHOYdV.js";import{s as T,a as u}from"./sanitize-header-CW0f3IT7.js";const g=globalThis.Buffer!==void 0,b=e=>{if(typeof e=="string"){if(g)return Buffer.from(e,"utf8").toString("base64");const s=new TextEncoder().encode(e);let r="";const n=8192;for(let o=0;o<s.length;o+=n){const c=s.subarray(o,Math.min(o+n,s.length));r+=String.fromCharCode(...c)}return btoa(r)}if(g&&e instanceof Buffer)return e.toString("base64");const i=e instanceof Uint8Array?e:new Uint8Array(e);if(g)return Buffer.from(i).toString("base64");let l="";const a=8192;for(let t=0;t<i.length;t+=a){const s=i.subarray(t,Math.min(t+a,i.length));l+=String.fromCharCode(...s)}return btoa(l)},I=globalThis.Buffer!==void 0,N=/[^\u0000-\u007F]/,j=e=>!N.test(e),k=e=>{if(j(e))return e;const i=45,l=new TextDecoder,a=I?Buffer.from(e,"utf8"):new TextEncoder().encode(e),t=[];let s=0;for(;s<a.length;){let r=Math.min(s+i,a.length);if(r<a.length)for(;r>s&&(a[r]&192)===128;)r-=1;const n=a.subarray(s,r),o=l.decode(n);t.push(`=?UTF-8?B?${b(o)}?=`),s=r}return t.join(" ")},$=e=>Array.isArray(e)?e.map(i=>m(i)).join(", "):m(e),B=/[^ -~\r\n\t]/,E=e=>k(u(e)),R=globalThis.Buffer!==void 0,C=e=>e.replaceAll(/.{1,76}/g,`$&\r
|
|
2
|
+
`).trimEnd(),_=/\r\n|\r|\n/,w=e=>e.split(_),U=async(e,i={})=>{const{includeBcc:l=!1}=i,a=y(),t=[`From: ${m(e.from)}`,`To: ${$(e.to)}`];if(e.cc&&t.push(`Cc: ${$(e.cc)}`),l&&e.bcc&&t.push(`Bcc: ${$(e.bcc)}`),e.replyTo&&t.push(`Reply-To: ${m(e.replyTo)}`),t.push(`Subject: ${E(e.subject)}`,"MIME-Version: 1.0"),e.headers){const r=v(e.headers);Object.entries(r).forEach(([n,o])=>{const c=T(n),p=u(o);t.push(`${c}: ${p}`)})}t.push(`Content-Type: multipart/mixed; boundary="${a}"`,"");const s=(r,n)=>{const o=B.test(n)?z(n):n,c=B.test(n)?"quoted-printable":"7bit";return[`Content-Type: ${r}; charset=UTF-8`,`Content-Transfer-Encoding: ${c}`,"",...w(o),""]};if(e.text&&e.html){const r=y();t.push(`--${a}`,`Content-Type: multipart/alternative; boundary="${r}"`,"",`--${r}`,...s("text/plain",e.text),`--${r}`,...s("text/html",e.html),`--${r}--`,"")}else e.text?t.push(`--${a}`,...s("text/plain",e.text)):e.html&&t.push(`--${a}`,...s("text/html",e.html));if(e.attachments&&e.attachments.length>0){const r=await Promise.all(e.attachments.map(async n=>{let o;if(n.raw!==void 0)o=n.raw;else{if(n.content===void 0)throw new M("attachment",`Attachment '${n.filename}' must have content, raw, or be resolved from path/href before building MIME message`);o=n.content instanceof Promise?await n.content:n.content}return{...n,resolvedContent:o}}));for(const n of r){t.push(`--${a}`);const o=u(n.contentType??"application/octet-stream"),c=E(n.filename);t.push(`Content-Type: ${o}; name="${c}"`);const p=u(n.contentDisposition??"attachment");t.push(`Content-Disposition: ${p}; filename="${c}"`),n.cid&&t.push(`Content-ID: <${u(n.cid)}>`),n.headers&&Object.entries(n.headers).forEach(([h,x])=>{const A=T(h),S=u(x);t.push(`${A}: ${S}`)});const d=u(n.encoding??"base64");t.push(`Content-Transfer-Encoding: ${d}`,"");const f=n.resolvedContent;if(d==="base64")t.push(C(b(f)));else if(d==="7bit"||d==="8bit"){let h;typeof f=="string"?h=f:R&&f instanceof Buffer?h=f.toString("utf8"):h=new TextDecoder().decode(f),t.push(...w(h))}else t.push(C(b(f)));t.push("")}}return t.push(`--${a}--`),t.join(`\r
|
|
3
|
+
`)};export{U as b};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const l=/[ \t]+/g,c=t=>{let n=0,e=t.length;for(;n<e&&(t[n]===" "||t[n]===" ");)n+=1;for(;e>n&&(t[e-1]===" "||t[e-1]===" ");)e-=1;return t.slice(n,e)},a=t=>{const n=t.indexOf(`\r
|
|
2
|
+
\r
|
|
3
|
+
`);if(n!==-1)return{body:t.slice(n+4),headersPart:t.slice(0,n)}},p=t=>{const n=[];for(const e of t.split(`\r
|
|
4
|
+
`)){const s=n.at(-1);if(s!==void 0&&(e.startsWith(" ")||e.startsWith(" "))){s.raw+=`\r
|
|
5
|
+
${e}`,s.value+=`\r
|
|
6
|
+
${e}`;continue}const r=e.indexOf(":");r!==-1&&n.push({name:e.slice(0,r),raw:e,value:e.slice(r+1)})}return n},d=(t,n)=>{const e=t.split(`\r
|
|
7
|
+
`);if(n==="relaxed")for(const[r,i]of e.entries()){const o=i.replaceAll(l," ");e[r]=o.endsWith(" ")?o.slice(0,-1):o}let s=e.length;for(;s>0&&e[s-1]==="";)s-=1;return s===0?n==="simple"?`\r
|
|
8
|
+
`:"":`${e.slice(0,s).join(`\r
|
|
9
|
+
`)}\r
|
|
10
|
+
`},f=(t,n,e)=>{if(e==="simple")return`${t}:${n}`;const s=n.replaceAll(`\r
|
|
11
|
+
`,"").replaceAll(l," ");return`${c(t.toLowerCase())}:${c(s)}`},h=t=>{const n=new Map;for(const s of t){const r=s.name.toLowerCase();n.set(r,[...n.get(r)??[],s])}const e=new Map;return t.map(s=>{const r=s.name.toLowerCase(),i=n.get(r),o=e.get(r)??0;return e.set(r,o+1),i[i.length-1-o]})};export{f as a,d as c,h as o,p,a as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createTransportDkimSigner as l}from"./DkimSigner-CCxFKitN.js";import o from"./EmailError-BIaHK1Uw.js";import m from"./RequiredOptionError-ctDEEB1s.js";import{b as u}from"./build-mime-message-BCFKPqaW.js";import{g as f}from"./generate-message-id-B2n2yqR6.js";import{h as g}from"./headers-to-record-ZOZ7Dubo.js";import{v as p}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as h}from"./defineProvider-C9q-7iwt.js";import{c as v,h as w}from"./provider-base-BEz00m9R.js";const r="cloudflare-email",R=h((s={})=>{if(typeof s.send!="function")throw new m(r,"send");const d=v(r,s.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){await Promise.resolve()},async isAvailable(){return typeof s.send=="function"},name:r,async sendEmail(e){try{const a=p(e);if(a.length>0)return{error:new o(r,`Invalid email options: ${a.join(", ")}`),success:!1};const i=Array.isArray(e.to)?e.to:[e.to];if(i.length!==1||e.cc!==void 0||e.bcc!==void 0)return{error:new o(r,"Cloudflare Email supports exactly one `to` recipient and does not support cc/bcc"),success:!1};const[n]=i;if(!n)return{error:new o(r,"A single `to` recipient is required"),success:!1};const c=f();let t=await u({...e,headers:{...e.headers?g(e.headers):{},"Message-ID":c}});return s.dkim&&e.useDkim!==!1&&(t=await l(s.dkim).signMimeMessage(t)),await s.send(e.from.email,n.email,t),{data:{messageId:c,provider:r,sent:!0,timestamp:new Date},success:!0}}catch(a){return{error:w(r,"send email",a,d),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{R as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createMail as d}from"./Mail-
|
|
1
|
+
import{createMail as d}from"./Mail-DmYNQ0KK.js";import w from"./mockProvider-Bf5eJ_rl.js";const l=(t,o,e,n)=>{const r=Date.now()+e;return new Promise((i,s)=>{const a=()=>{const c=t.find(m=>o(m));if(c){i(c);return}if(Date.now()>=r){s(new Error("waitFor timed out before a matching message was captured"));return}setTimeout(a,n)};a()})},h=()=>{const t=w(),o=d(t),e=t.getInstance?.();if(!e)throw new Error("mockProvider() did not expose getInstance(); cannot create a test harness");return{mail:o,reset:()=>{e.length=0},sent:()=>e,waitFor:(n,r={})=>l(e,n,r.timeout??1e3,r.interval??10)}};export{h as createTestEmail};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFile as o}from"../packem_chunks/index.js";import a from"mime";const c=e=>a.getType(e)??"application/octet-stream",i=e=>{const t=e.replaceAll(/[^a-z0-9]/gi,"-").replaceAll(/-+/g,"-").replaceAll(/^-|-$/g,"").toLowerCase(),r=Math.random().toString(36).slice(2,9);return`${t}-${r}@email`},m=e=>o(e,{buffer:!0});export{c as detectMimeType,i as generateContentId,m as readFileAsBuffer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l=/[\r\n<>]/,o=t=>{let e=t.replaceAll(/[\r\n\t]+/g," ");e=[...e].filter(i=>{const a=i.codePointAt(0);return a===void 0?!1:a>=32&&a<=126||a>159}).join("");const r="\\",n='"';return e=e.replaceAll(r,r+r).replaceAll(n,r+n),e.trim().replaceAll(/\s+/g," ")},s=t=>{if(l.test(t.email))throw new Error("Invalid email address for header formatting");if(t.name){const e=o(t.name);if(e)return`"${e}" <${t.email}>`}return t.email};export{s as f,o as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import d from"./EmailError-BIaHK1Uw.js";import v from"./RequiredOptionError-ctDEEB1s.js";import{g as A}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as u}from"./make-request-Cyz5_yu8.js";import{r as y}from"./retry-aghj7y8m.js";import{v as I}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as w}from"./defineProvider-C9q-7iwt.js";import{c as T,P,h}from"./provider-base-BEz00m9R.js";import{d as m}from"./address-formatter-
|
|
1
|
+
import d from"./EmailError-BIaHK1Uw.js";import v from"./RequiredOptionError-ctDEEB1s.js";import{g as A}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as u}from"./make-request-Cyz5_yu8.js";import{r as y}from"./retry-aghj7y8m.js";import{v as I}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as w}from"./defineProvider-C9q-7iwt.js";import{c as T,P,h}from"./provider-base-BEz00m9R.js";import{d as m}from"./address-formatter-w36S9ZYj.js";import{p as U}from"./attachment-processor-BJFDS343.js";const t="infobip",R="https://api.infobip.com",z=3e4,k=3,V=w((i={})=>{if(!i.apiKey)throw new v(t,"apiKey");const f=i.baseUrl??R,g=i.endpoint??`${f}/email/3/send`,a={apiKey:i.apiKey,baseUrl:f,debug:i.debug??!1,endpoint:g,retries:i.retries??k,timeout:i.timeout??z,...i.logger&&{logger:i.logger}},l=new P,s=T(t,i.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 d(t,"Email ID is required to retrieve email details"),success:!1};await l.ensureInitialized(()=>this.initialize(),t);const o={Authorization:`App ${a.apiKey}`,"Content-Type":"application/json"};s.debug("Retrieving email details",{id:e});const r=await y(async()=>u(`${a.baseUrl}/email/3/reports/${e}`,{headers:o,method:"GET",timeout:a.timeout}),a.retries);return r.success?(s.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(s.debug("API request failed when retrieving email",r.error),{error:new d(t,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(o){return{error:h(t,"retrieve email",o,s),success:!1}}},async initialize(){await l.ensureInitialized(async()=>{if(!await this.isAvailable())throw new d(t,"Infobip API not available or invalid API key");s.debug("Provider initialized successfully")},t)},async isAvailable(){try{s.debug("Checking Infobip API availability");const e={Authorization:`App ${a.apiKey}`,"Content-Type":"application/json"};return(await u(`${a.baseUrl}/account/1/me`,{headers:e,method:"GET",timeout:a.timeout})).success}catch(e){return s.debug("Error checking availability:",e),!1}},name:t,options:a,async sendEmail(e){try{const o=I(e);if(o.length>0)return{error:new d(t,`Invalid email options: ${o.join(", ")}`),success:!1};await l.ensureInitialized(()=>this.initialize(),t);const r={from:typeof e.from=="string"?e.from:e.from.email,subject:e.subject,to:m(e.to)};if(e.html&&(r.html=e.html),e.text&&(r.text=e.text),e.cc&&(r.cc=m(e.cc)),e.bcc&&(r.bcc=m(e.bcc)),e.replyTo&&(r.replyTo=typeof e.replyTo=="string"?e.replyTo:e.replyTo.email),e.templateId&&(r.templateId=e.templateId,e.templateVariables&&(r.templateData=e.templateVariables)),e.trackingUrl&&(r.trackingUrl=e.trackingUrl),e.notifyUrl&&(r.notifyUrl=e.notifyUrl),e.intermediateReport!==void 0&&(r.intermediateReport=e.intermediateReport),e.sendAt&&(r.sendAt=e.sendAt),e.headers){const c=E(e.headers);r.headers=c}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async c=>({content:await U(c,t),contentType:c.contentType??"application/octet-stream",name:c.filename})))),s.debug("Sending email via Infobip API",{subject:r.subject,to:r.to});const b={Authorization:`App ${a.apiKey}`,"Content-Type":"application/json"},n=await y(async()=>u(a.endpoint,{headers:b,method:"POST",timeout:a.timeout},JSON.stringify(r)),a.retries);if(!n.success)return s.debug("API request failed when sending email",n.error),{error:n.error??new d(t,"Failed to send email"),success:!1};const p=n.data?.body?.messages?.[0]?.messageId??A();return s.debug("Email sent successfully",{messageId:p}),{data:{messageId:p,provider:t,response:n.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:h(t,"send email",o,s),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{V as default};
|
|
@@ -2,7 +2,7 @@ import { ICalCalendar } from 'ical-generator';
|
|
|
2
2
|
import { Buffer as Buffer$1 } from 'node:buffer';
|
|
3
3
|
import { T as TemplateRenderer } from "./types.d-I-KeZ5w2.js";
|
|
4
4
|
import { c as EmailAddress, e as EmailHeaders, P as Priority, C as CalendarEventOptions, E as EmailOptions, A as Attachment, M as MaybePromise, a as EmailResult, R as Result, b as Receipt } from "./types.d-B9295M4_.js";
|
|
5
|
-
import {
|
|
5
|
+
import { b as EmailSigner, E as EmailEncrypter } from "./types.d-Cb5fls_X.js";
|
|
6
6
|
import { M as Middleware } from "./types.d-GKqPNk0I.js";
|
|
7
7
|
import { a as Provider } from "./provider.d-Cx5YQJdP.js";
|
|
8
8
|
/**
|
|
@@ -277,15 +277,18 @@ declare class MailMessage {
|
|
|
277
277
|
*/
|
|
278
278
|
tags(tags: string | string[]): this;
|
|
279
279
|
/**
|
|
280
|
-
* Signs the email message
|
|
280
|
+
* Signs the email message with an S/MIME signer.
|
|
281
|
+
*
|
|
282
|
+
* DKIM is not accepted here and `DkimSigner` deliberately does not satisfy `EmailSigner`: a
|
|
283
|
+
* DKIM signature commits to the serialized MIME message, which does not exist at this layer.
|
|
284
|
+
* Configure it on a transport that writes raw MIME instead — `smtpProvider({ dkim: {...} })`.
|
|
281
285
|
* @param signer The signer instance to use.
|
|
282
286
|
* @example
|
|
283
287
|
* ```ts
|
|
284
|
-
* import {
|
|
285
|
-
* const signer =
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
* privateKey: '-----BEGIN PRIVATE KEY-----...'
|
|
288
|
+
* import { createSmimeSigner } from '@visulima/email/crypto';
|
|
289
|
+
* const signer = createSmimeSigner({
|
|
290
|
+
* certificate: '/path/to/certificate.crt',
|
|
291
|
+
* privateKey: '/path/to/private-key.pem'
|
|
289
292
|
* });
|
|
290
293
|
* message.sign(signer)
|
|
291
294
|
* ```
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineProvider as l}from"./defineProvider-C9q-7iwt.js";import o from"./smtpProvider-
|
|
1
|
+
import{defineProvider as l}from"./defineProvider-C9q-7iwt.js";import o from"./smtpProvider-BCEzJmay.js";const a="mailcrab",u="localhost",n=1025,m=l((t={})=>{const e={debug:t.debug??!1,host:t.host??u,logger:t.logger,port:t.port??n,retries:t.retries,secure:t.secure??!1,timeout:t.timeout},r=o({debug:e.debug,host:e.host,logger:e.logger,port:e.port,retries:e.retries,secure:e.secure,timeout:e.timeout});return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){await r.initialize()},async isAvailable(){return r.isAvailable()},name:a,options:e,async sendEmail(i){const s=await r.sendEmail(i);return s.success&&s.data?{data:{...s.data,provider:a},success:!0}:s},async validateCredentials(){return r.validateCredentials?.()??!1}}});export{m as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"./EmailError-BIaHK1Uw.js";import T from"./RequiredOptionError-ctDEEB1s.js";import{g as P}from"./generate-message-id-B2n2yqR6.js";import{h as w}from"./headers-to-record-ZOZ7Dubo.js";import{m as u}from"./make-request-Cyz5_yu8.js";import{r as h}from"./retry-aghj7y8m.js";import{s as I,a as A}from"./sanitize-header-CW0f3IT7.js";import{v as k}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as z}from"./defineProvider-C9q-7iwt.js";import{c as j,P as C,h as g}from"./provider-base-BEz00m9R.js";import{j as l,g as b}from"./address-formatter-
|
|
1
|
+
import c from"./EmailError-BIaHK1Uw.js";import T from"./RequiredOptionError-ctDEEB1s.js";import{g as P}from"./generate-message-id-B2n2yqR6.js";import{h as w}from"./headers-to-record-ZOZ7Dubo.js";import{m as u}from"./make-request-Cyz5_yu8.js";import{r as h}from"./retry-aghj7y8m.js";import{s as I,a as A}from"./sanitize-header-CW0f3IT7.js";import{v as k}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as z}from"./defineProvider-C9q-7iwt.js";import{c as j,P as C,h as g}from"./provider-base-BEz00m9R.js";import{j as l,g as b}from"./address-formatter-w36S9ZYj.js";const a="mailpace",R="https://app.mailpace.com/api/v1",$=3e4,M=3,G=z((o={})=>{if(!o.apiToken)throw new T(a,"apiToken");const s={apiToken:o.apiToken,debug:o.debug??!1,endpoint:o.endpoint??R,retries:o.retries??M,timeout:o.timeout??$,...o.logger&&{logger:o.logger}},d=new C,i=j(a,o.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!1},async getEmail(e){try{if(!e)return{error:new c(a,"Email ID is required to retrieve email details"),success:!1};await d.ensureInitialized(()=>this.initialize(),a);const t={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const r=await h(async()=>u(`${s.endpoint}/emails/${e}`,{headers:t,method:"GET",timeout:s.timeout}),s.retries);return r.success?(i.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(i.debug("API request failed when retrieving email",r.error),{error:new c(a,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(t){return{error:g(a,"retrieve email",t,i),success:!1}}},async initialize(){await d.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(a,"MailPace API not available or invalid API token");i.debug("Provider initialized successfully")},a)},async isAvailable(){try{const e={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};i.debug("Checking MailPace API availability");const t=await u(`${s.endpoint}/account`,{headers:e,method:"GET",timeout:s.timeout});return i.debug("MailPace 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 i.debug("Error checking availability:",e),!1}},name:a,options:s,async sendEmail(e){try{const t=k(e);if(t.length>0)return{error:new c(a,`Invalid email options: ${t.join(", ")}`),success:!1};await d.ensureInitialized(()=>this.initialize(),a);const r={from:b(e.from),subject:e.subject,to:l(e.to)};if(e.html&&(r.htmlbody=e.html),e.text&&(r.textbody=e.text),e.cc&&(r.cc=l(e.cc)),e.bcc&&(r.bcc=l(e.bcc)),e.replyTo&&(r.replyto=b(e.replyTo)),e.templateId&&(r.template_id=e.templateId,e.templateVariables&&(r.template_variables=e.templateVariables)),e.tags&&e.tags.length>0&&(r.tags=e.tags),e.listUnsubscribe&&(r.list_unsubscribe=e.listUnsubscribe),e.headers){const y=w(e.headers),f={};Object.entries(y).forEach(([v,E])=>{f[I(v)]=A(E)}),r.headers=f}e.attachments&&e.attachments.length>0&&(r.attachments=e.attachments),i.debug("Sending email via MailPace API",{subject:r.subject,to:r.to});const p={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"},n=await h(async()=>u(`${s.endpoint}/send`,{headers:p,method:"POST",timeout:s.timeout},JSON.stringify(r)),s.retries);if(!n.success)return i.debug("API request failed when sending email",n.error),{error:n.error??new c(a,"Failed to send email"),success:!1};const m=n.data?.body?.id??P();return i.debug("Email sent successfully",{messageId:m}),{data:{messageId:m,provider:a,response:n.data,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:g(a,"send email",t,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{G as default};
|
package/dist/packem_shared/{mailchannelsProvider-Cgb8el7C.js → mailchannelsProvider-BZeuZk3d.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import u from"./EmailError-BIaHK1Uw.js";import g from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as T}from"./make-request-Cyz5_yu8.js";import{r as b}from"./retry-aghj7y8m.js";import{v as A}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{c as w,h as I,P as S}from"./provider-base-BEz00m9R.js";import{f as l,a as f}from"./address-formatter-
|
|
1
|
+
import u from"./EmailError-BIaHK1Uw.js";import g from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as T}from"./make-request-Cyz5_yu8.js";import{r as b}from"./retry-aghj7y8m.js";import{v as A}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{c as w,h as I,P as S}from"./provider-base-BEz00m9R.js";import{f as l,a as f}from"./address-formatter-w36S9ZYj.js";import{c as K}from"./attachment-processor-BJFDS343.js";const r="mailchannels",R="https://api.mailchannels.net/tx/v1/send",_=3e4,x=3,H=P((t={})=>{if(!t.apiKey)throw new g(r,"apiKey");const a={apiKey:t.apiKey,debug:t.debug??!1,endpoint:t.endpoint??R,logger:t.logger,retries:t.retries??x,timeout:t.timeout??_},h=new S,p=w(r,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){h.setInitialized()},async isAvailable(){return a.apiKey.length>0},name:r,options:a,async sendEmail(e){try{const s=A(e);if(s.length>0)return{error:new u(r,`Invalid email options: ${s.join(", ")}`),success:!1};const c=[];e.text&&c.push({type:"text/plain",value:e.text}),e.html&&c.push({type:"text/html",value:e.html});const i={to:l(e.to)};e.cc&&(i.cc=l(e.cc)),e.bcc&&(i.bcc=l(e.bcc));const n={content:c,from:f(e.from),personalizations:[i],subject:e.subject};e.replyTo&&(n.reply_to=f(e.replyTo)),e.headers&&(n.headers=E(e.headers)),e.attachments&&e.attachments.length>0&&(n.attachments=await Promise.all(e.attachments.map(async y=>{const d=await K(y,r);return{content:d.content,filename:d.filename,type:d.contentType}})));const o=await b(async()=>T(a.endpoint,{headers:{"Content-Type":"application/json","X-Api-Key":a.apiKey},method:"POST",timeout:a.timeout},JSON.stringify(n)),a.retries);if(!o.success)return{error:o.error??new u(r,"Failed to send email"),success:!1};const{body:m}=o.data;return{data:{messageId:m?.message_id??m?.request_id??v(),provider:r,response:o.data,sent:!0,timestamp:new Date},success:!0}}catch(s){return{error:I(r,"send email",s,p),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{H as default};
|
package/dist/packem_shared/{mailerSendProvider-BvRIjuVE.js → mailerSendProvider-C_Db652T.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"./EmailError-BIaHK1Uw.js";import p from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as b}from"./headers-to-record-ZOZ7Dubo.js";import{m as l}from"./make-request-Cyz5_yu8.js";import{r as g}from"./retry-aghj7y8m.js";import{v as T}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as E}from"./defineProvider-C9q-7iwt.js";import{c as w,P as A,h}from"./provider-base-BEz00m9R.js";import{f as m,a as I}from"./address-formatter-
|
|
1
|
+
import c from"./EmailError-BIaHK1Uw.js";import p from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as b}from"./headers-to-record-ZOZ7Dubo.js";import{m as l}from"./make-request-Cyz5_yu8.js";import{r as g}from"./retry-aghj7y8m.js";import{v as T}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as E}from"./defineProvider-C9q-7iwt.js";import{c as w,P as A,h}from"./provider-base-BEz00m9R.js";import{f as m,a as I}from"./address-formatter-w36S9ZYj.js";import{p as P}from"./attachment-processor-BJFDS343.js";const a="mailersend",k="https://api.mailersend.com",z=3e4,S=3,L=E((i={})=>{if(!i.apiToken)throw new p(a,"apiToken");const s={apiToken:i.apiToken,debug:i.debug??!1,endpoint:i.endpoint??k,retries:i.retries??S,timeout:i.timeout??z,...i.logger&&{logger:i.logger}},u=new A,o=w(a,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 c(a,"Email ID is required to retrieve email details"),success:!1};await u.ensureInitialized(()=>this.initialize(),a);const t={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};o.debug("Retrieving email details",{id:e});const r=await g(async()=>l(`${s.endpoint}/v1/activity/${e}`,{headers:t,method:"GET",timeout:s.timeout}),s.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 c(a,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(t){return{error:h(a,"retrieve email",t,o),success:!1}}},async initialize(){await u.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(a,"MailerSend API not available or invalid API token");o.debug("Provider initialized successfully")},a)},async isAvailable(){try{const e={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};o.debug("Checking MailerSend API availability");const t=await l(`${s.endpoint}/v1/tokens/verify`,{headers:e,method:"GET",timeout:s.timeout});return o.debug("MailerSend 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:a,options:s,async sendEmail(e){try{const t=T(e);if(t.length>0)return{error:new c(a,`Invalid email options: ${t.join(", ")}`),success:!1};await u.ensureInitialized(()=>this.initialize(),a);const r={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:m(e.to)};if(e.html&&(r.html=e.html),e.text&&(r.text=e.text),e.cc&&(r.cc=m(e.cc)),e.bcc&&(r.bcc=m(e.bcc)),e.replyTo&&(r.reply_to=I(e.replyTo)),e.templateId&&(r.template_id=e.templateId,e.templateVariables&&(r.variables=e.templateVariables)),e.personalization&&e.personalization.length>0&&(r.personalization=e.personalization),e.tags&&e.tags.length>0&&(r.tags=e.tags),e.scheduledAt&&(r.send_at=e.scheduledAt),e.domainId&&(r.domain_id=e.domainId),e.headers){const n=b(e.headers);r.headers=n}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async n=>({content:await P(n,a),filename:n.filename,...n.contentType&&{type:n.contentType},...n.cid&&{id:n.cid}})))),o.debug("Sending email via MailerSend API",{subject:r.subject,to:r.to});const y={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"},d=await g(async()=>l(`${s.endpoint}/v1/email`,{headers:y,method:"POST",timeout:s.timeout},JSON.stringify(r)),s.retries);if(!d.success)return o.debug("API request failed when sending email",d.error),{error:d.error??new c(a,"Failed to send email"),success:!1};const f=d.data?.body?.message_id??v();return o.debug("Email sent successfully",{messageId:f}),{data:{messageId:f,provider:a,response:d.data,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:h(a,"send email",t,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{L as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as j}from"node:module";import f from"./EmailError-BIaHK1Uw.js";import w from"./RequiredOptionError-ctDEEB1s.js";import{g as P}from"./generate-message-id-B2n2yqR6.js";import{h as _}from"./headers-to-record-ZOZ7Dubo.js";import{m as p}from"./make-request-Cyz5_yu8.js";import{r as I}from"./retry-aghj7y8m.js";import{v as C}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as D}from"./defineProvider-C9q-7iwt.js";import{c as S,P as U,h as k}from"./provider-base-BEz00m9R.js";import{e as v,g as E}from"./address-formatter-
|
|
1
|
+
import{createRequire as j}from"node:module";import f from"./EmailError-BIaHK1Uw.js";import w from"./RequiredOptionError-ctDEEB1s.js";import{g as P}from"./generate-message-id-B2n2yqR6.js";import{h as _}from"./headers-to-record-ZOZ7Dubo.js";import{m as p}from"./make-request-Cyz5_yu8.js";import{r as I}from"./retry-aghj7y8m.js";import{v as C}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as D}from"./defineProvider-C9q-7iwt.js";import{c as S,P as U,h as k}from"./provider-base-BEz00m9R.js";import{e as v,g as E}from"./address-formatter-w36S9ZYj.js";import{a as q}from"./attachment-processor-BJFDS343.js";let $;const A=o=>($??=j(import.meta.url))(o),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,R=o=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[r,n]=m.versions.node.split(".").map(Number);if(r>22||r===22&&n>=3||r===20&&n>=16)return m.getBuiltinModule(o)}return A(o)},{Buffer:y}=R("node:buffer"),s="mailgun",M="https://api.mailgun.net",z=3e4,B=3,K=o=>{const r=[];for(const[n,a]of Object.entries(o))if(a!=null)if(Array.isArray(a))for(const e of a)r.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(e))}`);else typeof a=="object"?r.push(`${encodeURIComponent(n)}=${encodeURIComponent(JSON.stringify(a))}`):r.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(a))}`);return r.join("&")},O=D((o={})=>{if(!o.apiKey)throw new w(s,"apiKey");if(!o.domain)throw new w(s,"domain");const r={apiKey:o.apiKey,debug:o.debug??!1,domain:o.domain,endpoint:o.endpoint??M,retries:o.retries??B,timeout:o.timeout??z,...o.logger&&{logger:o.logger}},n=new U,a=S(s,o.logger);return{endpoint:r.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 f(s,"Email ID is required to retrieve email details"),success:!1};await n.ensureInitialized(()=>this.initialize(),s);const t={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};a.debug("Retrieving email details",{id:e});const i=await I(async()=>p(`${r.endpoint}/v3/${r.domain}/events?message-id=${encodeURIComponent(e)}&limit=1`,{headers:t,method:"GET",timeout:r.timeout}),r.retries);if(!i.success)return a.debug("API request failed when retrieving email",i.error),{error:new f(s,`Failed to retrieve email: ${i.error instanceof Error?i.error.message:"Unknown error"}`,{cause:i.error}),success:!1};a.debug("Email details retrieved successfully");const g=i.data?.items??[],u=g.length>0?g[0]:void 0;return{data:u?.message?.headers??u?.storage??void 0,success:!0}}catch(c){return{error:k(s,"retrieve email",c,a),success:!1}}},async initialize(){await n.ensureInitialized(async()=>{if(!await this.isAvailable())throw new f(s,"Mailgun API not available or invalid API key/domain");a.debug("Provider initialized successfully")},s)},async isAvailable(){try{const c={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};a.debug("Checking Mailgun API availability");const t=await p(`${r.endpoint}/v3/domains/${r.domain}`,{headers:c,method:"GET",timeout:r.timeout});if(a.debug("Mailgun 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")return!1;const{statusCode:i}=t.data;return typeof i=="number"&&i>=200&&i<300}catch(e){return a.debug("Error checking availability:",e),!1}},name:s,options:r,async sendEmail(e){try{const c=C(e);if(c.length>0)return{error:new f(s,`Invalid email options: ${c.join(", ")}`),success:!1};await n.ensureInitialized(()=>this.initialize(),s);const t={from:E(e.from),to:v(e.to).join(",")};if(e.subject&&(t.subject=e.subject),e.cc&&(t.cc=v(e.cc).join(",")),e.bcc&&(t.bcc=v(e.bcc).join(",")),e.replyTo&&(t["h:Reply-To"]=E(e.replyTo)),e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.template&&(t.template=e.template,e.templateVariables))for(const[l,d]of Object.entries(e.templateVariables))t[`v:${l}`]=d;if(e.tags&&e.tags.length>0&&(t["o:tag"]=e.tags),e.campaignId&&(t["o:campaign"]=e.campaignId),e.deliveryTime&&(t["o:deliverytime"]=typeof e.deliveryTime=="number"?new Date(e.deliveryTime*1e3).toUTCString():e.deliveryTime),e.clickTracking!==void 0&&(t["o:clicktracking"]=e.clickTracking?"yes":"no"),e.openTracking!==void 0&&(t["o:tracking"]=e.openTracking?"yes":"no"),e.unsubscribeTracking!==void 0&&(t["o:tracking-clicks"]=e.unsubscribeTracking?"yes":"no"),e.testMode&&(t["o:testmode"]="yes"),e.requireTls&&(t["o:require-tls"]="yes"),e.skipVerification&&(t["o:skip-verification"]="yes"),e.headers){const l=_(e.headers);for(const[d,h]of Object.entries(l))t[`h:${d}`]=h}if(e.attachments&&e.attachments.length>0){const l=await Promise.all(e.attachments.map((d,h)=>q(d,s,h)));for(const d of l)t[d.key]=d.content}a.debug("Sending email via Mailgun API",{subject:t.subject,to:t.to});const b={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},g=K(t),u=await I(async()=>p(`${r.endpoint}/v3/${r.domain}/messages`,{headers:b,method:"POST",timeout:r.timeout},g),r.retries);if(!u.success)return a.debug("API request failed when sending email",u.error),{error:u.error??new f(s,"Failed to send email"),success:!1};const T=u.data?.body?.id??P();return a.debug("Email sent successfully",{messageId:T}),{data:{messageId:T,provider:s,response:u.data,sent:!0,timestamp:new Date},success:!0}}catch(c){return{error:k(s,"send email",c,a),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{O as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as S}from"node:module";import g from"./EmailError-BIaHK1Uw.js";import v from"./RequiredOptionError-ctDEEB1s.js";import{g as _}from"./generate-message-id-B2n2yqR6.js";import{h as R}from"./headers-to-record-ZOZ7Dubo.js";import{m as p}from"./make-request-Cyz5_yu8.js";import{r as b}from"./retry-aghj7y8m.js";import{v as M}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as $}from"./defineProvider-C9q-7iwt.js";import{c as D,P as B,h as T}from"./provider-base-BEz00m9R.js";import{h as y,i as E}from"./address-formatter-
|
|
1
|
+
import{createRequire as S}from"node:module";import g from"./EmailError-BIaHK1Uw.js";import v from"./RequiredOptionError-ctDEEB1s.js";import{g as _}from"./generate-message-id-B2n2yqR6.js";import{h as R}from"./headers-to-record-ZOZ7Dubo.js";import{m as p}from"./make-request-Cyz5_yu8.js";import{r as b}from"./retry-aghj7y8m.js";import{v as M}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as $}from"./defineProvider-C9q-7iwt.js";import{c as D,P as B,h as T}from"./provider-base-BEz00m9R.js";import{h as y,i as E}from"./address-formatter-w36S9ZYj.js";import{p as z}from"./attachment-processor-BJFDS343.js";let P;const C=a=>(P??=S(import.meta.url))(a),l=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,A=a=>{if(typeof l<"u"&&l.versions&&l.versions.node){const[r,u]=l.versions.node.split(".").map(Number);if(r>22||r===22&&u>=3||r===20&&u>=16)return l.getBuiltinModule(a)}return C(a)},{Buffer:f}=A("node:buffer"),s="mailjet",q="https://api.mailjet.com",L=3e4,k=3,O=$((a={})=>{if(!a.apiKey)throw new v(s,"apiKey");if(!a.apiSecret)throw new v(s,"apiSecret");const r={apiKey:a.apiKey,apiSecret:a.apiSecret,debug:a.debug??!1,endpoint:a.endpoint??q,retries:a.retries??k,timeout:a.timeout??L,...a.logger&&{logger:a.logger}},u=new B,i=D(s,a.logger);return{endpoint:r.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 g(s,"Email ID is required to retrieve email details"),success:!1};await u.ensureInitialized(()=>this.initialize(),s);const t={Authorization:`Basic ${f.from(`${r.apiKey}:${r.apiSecret}`).toString("base64")}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const n=await b(async()=>p(`${r.endpoint}/v3.1/REST/message/${e}`,{headers:t,method:"GET",timeout:r.timeout}),r.retries);return n.success?(i.debug("Email details retrieved successfully"),{data:n.data?.body,success:!0}):(i.debug("API request failed when retrieving email",n.error),{error:new g(s,`Failed to retrieve email: ${n.error instanceof Error?n.error.message:"Unknown error"}`,{cause:n.error}),success:!1})}catch(o){return{error:T(s,"retrieve email",o,i),success:!1}}},async initialize(){await u.ensureInitialized(async()=>{if(!await this.isAvailable())throw new g(s,"Mailjet API not available or invalid API credentials");i.debug("Provider initialized successfully")},s)},async isAvailable(){try{const o={Authorization:`Basic ${f.from(`${r.apiKey}:${r.apiSecret}`).toString("base64")}`,"Content-Type":"application/json"};i.debug("Checking Mailjet API availability");const t=await p(`${r.endpoint}/v3.1/REST/user`,{headers:o,method:"GET",timeout:r.timeout});return i.debug("Mailjet 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 i.debug("Error checking availability:",e),!1}},name:s,options:r,async sendEmail(e){try{const o=M(e);if(o.length>0)return{error:new g(s,`Invalid email options: ${o.join(", ")}`),success:!1};await u.ensureInitialized(()=>this.initialize(),s);const t={From:E(e.from),Subject:e.subject,To:y(e.to)};if(e.html&&(t.HTMLPart=e.html),e.text&&(t.TextPart=e.text),e.cc&&(t.Cc=y(e.cc)),e.bcc&&(t.Bcc=y(e.bcc)),e.replyTo&&(t.ReplyTo=E(e.replyTo)),e.templateId&&(t.TemplateID=e.templateId,t.TemplateLanguage=e.templateLanguage??!0,e.templateVariables&&(t.Variables=e.templateVariables)),e.customId&&(t.CustomID=e.customId),e.eventPayload&&(t.EventPayload=e.eventPayload),e.campaign&&(t.Campaign=e.campaign),e.deduplicateCampaign!==void 0&&(t.DeduplicateCampaign=e.deduplicateCampaign),e.deliveryTime&&(t.Deliverytime=new Date(e.deliveryTime*1e3).toISOString()),e.priority!==void 0&&(t.Priority=e.priority),e.urlTags&&(t.URLTags=e.urlTags),e.tags&&e.tags.length>0&&(t.CustomCampaign=e.tags.join(",")),e.headers){const c=R(e.headers),m=[];for(const[j,w]of Object.entries(c))m.push({Name:j,Value:String(w)});m.length>0&&(t.Headers=m)}e.attachments&&e.attachments.length>0&&(t.Attachments=await Promise.all(e.attachments.map(async c=>({Base64Content:await z(c,s),ContentType:c.contentType??"application/octet-stream",Filename:c.filename,...c.cid&&{ContentID:c.cid}}))));const n={Messages:[t]};i.debug("Sending email via Mailjet API",{subject:t.Subject,to:t.To});const I={Authorization:`Basic ${f.from(`${r.apiKey}:${r.apiSecret}`).toString("base64")}`,"Content-Type":"application/json"},d=await b(async()=>p(`${r.endpoint}/v3.1/send`,{headers:I,method:"POST",timeout:r.timeout},JSON.stringify(n)),r.retries);if(!d.success)return i.debug("API request failed when sending email",d.error),{error:d.error??new g(s,"Failed to send email"),success:!1};const h=d.data?.body?.Messages?.[0]?.To?.[0]?.MessageID?.toString()??_();return i.debug("Email sent successfully",{messageId:h}),{data:{messageId:h,provider:s,response:d.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:T(s,"send email",o,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{O as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import d from"./EmailError-BIaHK1Uw.js";import b from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as g}from"./make-request-Cyz5_yu8.js";import{r as y}from"./retry-aghj7y8m.js";import{v as I}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as w}from"./defineProvider-C9q-7iwt.js";import{c as P,P as A,h}from"./provider-base-BEz00m9R.js";import{f as u,a as T}from"./address-formatter-
|
|
1
|
+
import d from"./EmailError-BIaHK1Uw.js";import b from"./RequiredOptionError-ctDEEB1s.js";import{g as v}from"./generate-message-id-B2n2yqR6.js";import{h as E}from"./headers-to-record-ZOZ7Dubo.js";import{m as g}from"./make-request-Cyz5_yu8.js";import{r as y}from"./retry-aghj7y8m.js";import{v as I}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as w}from"./defineProvider-C9q-7iwt.js";import{c as P,P as A,h}from"./provider-base-BEz00m9R.js";import{f as u,a as T}from"./address-formatter-w36S9ZYj.js";import{p as R}from"./attachment-processor-BJFDS343.js";const t="mailomat",S="https://api.mailomat.com",K=3e4,j=3,V=w((s={})=>{if(!s.apiKey)throw new b(t,"apiKey");const i={apiKey:s.apiKey,debug:s.debug??!1,endpoint:s.endpoint??S,retries:s.retries??j,timeout:s.timeout??K,...s.logger&&{logger:s.logger}},l=new A,a=P(t,s.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new d(t,"Email ID is required to retrieve email details"),success:!1};await l.ensureInitialized(()=>this.initialize(),t);const o={"Content-Type":"application/json","X-API-Key":i.apiKey};a.debug("Retrieving email details",{id:e});const r=await y(async()=>g(`${i.endpoint}/emails/${e}`,{headers:o,method:"GET",timeout:i.timeout}),i.retries);return r.success?(a.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(a.debug("API request failed when retrieving email",r.error),{error:new d(t,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(o){return{error:h(t,"retrieve email",o,a),success:!1}}},async initialize(){await l.ensureInitialized(async()=>{if(!await this.isAvailable())throw new d(t,"Mailomat API not available or invalid API key");a.debug("Provider initialized successfully")},t)},async isAvailable(){try{return a.debug("Checking Mailomat API availability"),!0}catch(e){return a.debug("Error checking availability:",e),!1}},name:t,options:i,async sendEmail(e){try{const o=I(e);if(o.length>0)return{error:new d(t,`Invalid email options: ${o.join(", ")}`),success:!1};await l.ensureInitialized(()=>this.initialize(),t);const r={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:u(e.to)};if(e.html&&(r.html=e.html),e.text&&(r.text=e.text),e.cc&&(r.cc=u(e.cc)),e.bcc&&(r.bcc=u(e.bcc)),e.replyTo&&(r.replyTo=T(e.replyTo)),e.templateId&&(r.templateId=e.templateId,e.templateVariables&&(r.templateVariables=e.templateVariables)),e.tags&&e.tags.length>0&&(r.tags=e.tags),e.headers){const n=E(e.headers);r.headers=n}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async n=>({content:await R(n,t),contentType:n.contentType??"application/octet-stream",filename:n.filename,...n.cid&&{cid:n.cid}})))),a.debug("Sending email via Mailomat API",{subject:r.subject,to:r.to});const p={"Content-Type":"application/json","X-API-Key":i.apiKey},c=await y(async()=>g(`${i.endpoint}/send`,{headers:p,method:"POST",timeout:i.timeout},JSON.stringify(r)),i.retries);if(!c.success)return a.debug("API request failed when sending email",c.error),{error:c.error??new d(t,"Failed to send email"),success:!1};const m=c.data?.body,f=m?.messageId??m?.id??v();return a.debug("Email sent successfully",{messageId:f}),{data:{messageId:f,provider:t,response:c.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:h(t,"send email",o,a),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{V as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import d from"./EmailError-BIaHK1Uw.js";import y from"./RequiredOptionError-ctDEEB1s.js";import{g as b}from"./generate-message-id-B2n2yqR6.js";import{h as v}from"./headers-to-record-ZOZ7Dubo.js";import{m as l}from"./make-request-Cyz5_yu8.js";import{r as p}from"./retry-aghj7y8m.js";import{v as T}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as E}from"./defineProvider-C9q-7iwt.js";import{c as w,P as A,h as g}from"./provider-base-BEz00m9R.js";import{f as m,a as I}from"./address-formatter-
|
|
1
|
+
import d from"./EmailError-BIaHK1Uw.js";import y from"./RequiredOptionError-ctDEEB1s.js";import{g as b}from"./generate-message-id-B2n2yqR6.js";import{h as v}from"./headers-to-record-ZOZ7Dubo.js";import{m as l}from"./make-request-Cyz5_yu8.js";import{r as p}from"./retry-aghj7y8m.js";import{v as T}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as E}from"./defineProvider-C9q-7iwt.js";import{c as w,P as A,h as g}from"./provider-base-BEz00m9R.js";import{f as m,a as I}from"./address-formatter-w36S9ZYj.js";import{p as P}from"./attachment-processor-BJFDS343.js";const a="mailtrap",k="https://send.api.mailtrap.io",C=3e4,j=3,L=E((o={})=>{if(!o.apiToken)throw new y(a,"apiToken");const s={apiToken:o.apiToken,debug:o.debug??!1,endpoint:o.endpoint??k,retries:o.retries??j,timeout:o.timeout??C,...o.logger&&{logger:o.logger}},u=new A,i=w(a,o.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new d(a,"Email ID is required to retrieve email details"),success:!1};await u.ensureInitialized(()=>this.initialize(),a);const t={"Api-Token":s.apiToken,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const r=await p(async()=>l(`${s.endpoint}/api/send/${e}`,{headers:t,method:"GET",timeout:s.timeout}),s.retries);return r.success?(i.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(i.debug("API request failed when retrieving email",r.error),{error:new d(a,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(t){return{error:g(a,"retrieve email",t,i),success:!1}}},async initialize(){await u.ensureInitialized(async()=>{if(!await this.isAvailable())throw new d(a,"Mailtrap API not available or invalid API token");i.debug("Provider initialized successfully")},a)},async isAvailable(){try{const e={"Api-Token":s.apiToken,"Content-Type":"application/json"};i.debug("Checking Mailtrap API availability");const t=await l(`${s.endpoint}/api/account`,{headers:e,method:"GET",timeout:s.timeout});return i.debug("Mailtrap 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 i.debug("Error checking availability:",e),!1}},name:a,options:s,async sendEmail(e){try{const t=T(e);if(t.length>0)return{error:new d(a,`Invalid email options: ${t.join(", ")}`),success:!1};await u.ensureInitialized(()=>this.initialize(),a);const r={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:m(e.to)};if(e.html&&(r.html=e.html),e.text&&(r.text=e.text),e.cc&&(r.cc=m(e.cc)),e.bcc&&(r.bcc=m(e.bcc)),e.replyTo&&(r.reply_to=I(e.replyTo)),e.templateUuid&&(r.template_uuid=e.templateUuid,e.templateVariables&&(r.template_variables=e.templateVariables)),e.category&&(r.category=e.category),e.customVariables&&(r.custom_variables=e.customVariables),e.tags&&e.tags.length>0&&(r.tags=e.tags),e.headers){const n=v(e.headers);r.headers=n}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async n=>({content:await P(n,a),filename:n.filename,type:n.contentType??"application/octet-stream",...n.cid&&{cid:n.cid}})))),i.debug("Sending email via Mailtrap API",{subject:r.subject,to:r.to});const h={"Api-Token":s.apiToken,"Content-Type":"application/json"},c=await p(async()=>l(`${s.endpoint}/api/send`,{headers:h,method:"POST",timeout:s.timeout},JSON.stringify(r)),s.retries);if(!c.success)return i.debug("API request failed when sending email",c.error),{error:c.error??new d(a,"Failed to send email"),success:!1};const f=c.data?.body?.message_ids?.[0]??b();return i.debug("Email sent successfully",{messageId:f}),{data:{messageId:f,provider:a,response:c.data,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:g(a,"send email",t,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{L as default};
|