@stacksjs/email 0.75.514 → 0.75.518

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.
@@ -1,6 +1,6 @@
1
- export function inlineCss(html,options={}){const{inline=!0,important=!0}=options;if(!inline)return html;let working=html;const passthroughBlocks=[];working=working.replace(/<style\b[^>]*\bdata-inline=["']false["'][^>]*>[\s\S]*?<\/style>/gi,(match)=>{passthroughBlocks.push(match);return`\x00STX_PASSTHROUGH_${passthroughBlocks.length-1}\x00`});const styleBlocks=[];working=working.replace(/<style\b[^>]*>([\s\S]*?)<\/style>/gi,(_match,body)=>{styleBlocks.push(body);return""});if(styleBlocks.length===0)return restorePassthroughs(working,passthroughBlocks);const inlinableRules=[],leftover=[];for(const body of styleBlocks)for(const rule of splitRules(body)){const{selector,declarations,body:ruleBody}=rule;if(!selector)continue;if(declarations!==null&&isInlinable(selector))inlinableRules.push({selector,decls:declarations});else leftover.push(`${selector} { ${ruleBody} }`)}for(const{selector,decls}of inlinableRules)working=applyRule(working,selector,decls,important);if(leftover.length>0){const styleTag=`<style>
1
+ export function inlineCss(html,options={}){const{inline=true,important=true}=options;if(!inline)return html;let working=html;const passthroughBlocks=[];working=working.replace(/<style\b[^>]*\bdata-inline=["']false["'][^>]*>[\s\S]*?<\/style>/gi,(match)=>{passthroughBlocks.push(match);return`\x00STX_PASSTHROUGH_${passthroughBlocks.length-1}\x00`});const styleBlocks=[];working=working.replace(/<style\b[^>]*>([\s\S]*?)<\/style>/gi,(_match,body)=>{styleBlocks.push(body);return""});if(styleBlocks.length===0){return restorePassthroughs(working,passthroughBlocks)}const inlinableRules=[];const leftover=[];for(const body of styleBlocks){for(const rule of splitRules(body)){const{selector,declarations,body:ruleBody}=rule;if(!selector)continue;if(declarations!==null&&isInlinable(selector)){inlinableRules.push({selector,decls:declarations})}else{leftover.push(`${selector} { ${ruleBody} }`)}}}for(const{selector,decls}of inlinableRules){working=applyRule(working,selector,decls,important)}if(leftover.length>0){const styleTag=`<style>
2
2
  ${leftover.join(`
3
3
  `)}
4
4
  </style>`;working=/<\/head>/i.test(working)?working.replace(/<\/head>/i,`${styleTag}
5
5
  </head>`):`${styleTag}
6
- ${working}`}return restorePassthroughs(working,passthroughBlocks)}function restorePassthroughs(html,blocks){if(blocks.length===0)return html;return html.replace(/\0STX_PASSTHROUGH_(\d+)\0/g,(_match,idx)=>{return blocks[Number.parseInt(idx,10)]??""})}function splitRules(body){const cleaned=body.replace(/\/\*[\s\S]*?\*\//g,""),rules=[];let i=0;while(i<cleaned.length){const open=cleaned.indexOf("{",i);if(open===-1)break;const selector=cleaned.slice(i,open).trim();let depth=1,j=open+1;while(j<cleaned.length&&depth>0){const ch=cleaned[j];if(ch==="{")depth++;else if(ch==="}")depth--;j++}const inner=cleaned.slice(open+1,j-1);if(selector.startsWith("@")||inner.includes("{"))rules.push({selector:selector||"@unknown",body:inner.trim(),declarations:null});else rules.push({selector,body:inner.trim(),declarations:parseDeclarations(inner)});i=j}return rules}function parseDeclarations(body){return body.split(";").map((decl)=>decl.trim()).filter(Boolean).map((decl)=>{const colon=decl.indexOf(":");if(colon===-1)return null;return{prop:decl.slice(0,colon).trim(),value:decl.slice(colon+1).trim()}}).filter((d)=>d!==null)}function isInlinable(selector){if(!selector)return!1;if(selector.includes(","))return selector.split(",").every((s)=>isInlinable(s.trim()));if(selector.startsWith("@"))return!1;if(/[\s>+~:[]/.test(selector))return!1;return/^[a-z][a-z0-9-]*?$|^([a-z][a-z0-9-]*)?([.#][a-z][\w-]*)+$/i.test(selector)}function applyRule(html,selector,decls,important){if(selector.includes(",")){let acc=html;for(const branch of selector.split(","))acc=applyRule(acc,branch.trim(),decls,important);return acc}const{tag,classes,ids}=parseSimpleSelector(selector),tagRe=new RegExp(`<(${tag??"[a-z][a-z0-9-]*"})\\b([^>]*?)(/?)>`,"gi"),newDeclString=decls.map((d)=>`${d.prop}:${d.value}${important&&!/!important\b/i.test(d.value)?" !important":""};`).join("");return html.replace(tagRe,(match,_tagName,attrs)=>{if(!elementMatches(attrs,classes,ids))return match;return mergeStyleAttr(match,attrs,newDeclString)})}function parseSimpleSelector(selector){let tag=null;const classes=[],ids=[];let i=0;while(i<selector.length&&/[a-z0-9-]/i.test(selector[i])){tag=(tag??"")+selector[i];i++}if(tag==="")tag=null;while(i<selector.length){const ch=selector[i];if(ch!=="."&&ch!=="#")break;let j=i+1;while(j<selector.length&&/[\w-]/.test(selector[j]))j++;const name=selector.slice(i+1,j);if(ch===".")classes.push(name);else ids.push(name);i=j}return{tag,classes,ids}}function elementMatches(attrs,classes,ids){if(classes.length>0){const classMatch=attrs.match(/\bclass\s*=\s*["']([^"']*)["']/i);if(!classMatch)return!1;const present=classMatch[1].split(/\s+/).filter(Boolean);if(!classes.every((c)=>present.includes(c)))return!1}if(ids.length>0){const idMatch=attrs.match(/\bid\s*=\s*["']([^"']+)["']/i);if(!idMatch)return!1;if(!ids.every((id)=>idMatch[1]===id))return!1}return!0}function mergeStyleAttr(originalTag,attrs,newDeclString){const styleMatch=attrs.match(/\bstyle\s*=\s*["']([^"']*)["']/i);if(styleMatch){const existing=styleMatch[1].trim(),merged=`${newDeclString}${existing}${existing.endsWith(";")||existing===""?"":";"}`,replaced=attrs.replace(styleMatch[0],`style="${merged}"`);return originalTag.replace(attrs,replaced)}const extra=` style="${newDeclString}"`;return originalTag.replace(/(\s*\/?)>$/,`${extra}$1>`)}export function shouldInlineByDefault(){return(globalThis.process?.env?.APP_ENV??globalThis.process?.env?.NODE_ENV??"").toLowerCase()==="production"}
6
+ ${working}`}return restorePassthroughs(working,passthroughBlocks)}function restorePassthroughs(html,blocks){if(blocks.length===0)return html;return html.replace(/\0STX_PASSTHROUGH_(\d+)\0/g,(_match,idx)=>{return blocks[Number.parseInt(idx,10)]??""})}function splitRules(body){const cleaned=body.replace(/\/\*[\s\S]*?\*\//g,"");const rules=[];let i=0;while(i<cleaned.length){const open=cleaned.indexOf("{",i);if(open===-1)break;const selector=cleaned.slice(i,open).trim();let depth=1;let j=open+1;while(j<cleaned.length&&depth>0){const ch=cleaned[j];if(ch==="{")depth++;else if(ch==="}")depth--;j++}const inner=cleaned.slice(open+1,j-1);if(selector.startsWith("@")||inner.includes("{")){rules.push({selector:selector||"@unknown",body:inner.trim(),declarations:null})}else{rules.push({selector,body:inner.trim(),declarations:parseDeclarations(inner)})}i=j}return rules}function parseDeclarations(body){return body.split(";").map((decl)=>decl.trim()).filter(Boolean).map((decl)=>{const colon=decl.indexOf(":");if(colon===-1)return null;return{prop:decl.slice(0,colon).trim(),value:decl.slice(colon+1).trim()}}).filter((d)=>d!==null)}function isInlinable(selector){if(!selector)return false;if(selector.includes(",")){return selector.split(",").every((s)=>isInlinable(s.trim()))}if(selector.startsWith("@"))return false;if(/[\s>+~:[]/.test(selector))return false;return/^[a-z][a-z0-9-]*?$|^([a-z][a-z0-9-]*)?([.#][a-z][\w-]*)+$/i.test(selector)}function applyRule(html,selector,decls,important){if(selector.includes(",")){let acc=html;for(const branch of selector.split(",")){acc=applyRule(acc,branch.trim(),decls,important)}return acc}const{tag,classes,ids}=parseSimpleSelector(selector);const tagPattern=tag??"[a-z][a-z0-9-]*";const tagRe=new RegExp(`<(${tagPattern})\\b([^>]*?)(/?)>`,"gi");const newDeclString=decls.map((d)=>`${d.prop}:${d.value}${important&&!/!important\b/i.test(d.value)?" !important":""};`).join("");return html.replace(tagRe,(match,_tagName,attrs)=>{if(!elementMatches(attrs,classes,ids))return match;return mergeStyleAttr(match,attrs,newDeclString)})}function parseSimpleSelector(selector){let tag=null;const classes=[];const ids=[];let i=0;while(i<selector.length&&/[a-z0-9-]/i.test(selector[i])){tag=(tag??"")+selector[i];i++}if(tag==="")tag=null;while(i<selector.length){const ch=selector[i];if(ch!=="."&&ch!=="#")break;let j=i+1;while(j<selector.length&&/[\w-]/.test(selector[j]))j++;const name=selector.slice(i+1,j);if(ch===".")classes.push(name);else ids.push(name);i=j}return{tag,classes,ids}}function elementMatches(attrs,classes,ids){if(classes.length>0){const classMatch=attrs.match(/\bclass\s*=\s*["']([^"']*)["']/i);if(!classMatch)return false;const present=classMatch[1].split(/\s+/).filter(Boolean);if(!classes.every((c)=>present.includes(c)))return false}if(ids.length>0){const idMatch=attrs.match(/\bid\s*=\s*["']([^"']+)["']/i);if(!idMatch)return false;if(!ids.every((id)=>idMatch[1]===id))return false}return true}function mergeStyleAttr(originalTag,attrs,newDeclString){const styleMatch=attrs.match(/\bstyle\s*=\s*["']([^"']*)["']/i);if(styleMatch){const existing=styleMatch[1].trim();const merged=`${newDeclString}${existing}${existing.endsWith(";")||existing===""?"":";"}`;const replaced=attrs.replace(styleMatch[0],`style="${merged}"`);return originalTag.replace(attrs,replaced)}const extra=` style="${newDeclString}"`;return originalTag.replace(/(\s*\/?)>$/,`${extra}$1>`)}export function shouldInlineByDefault(){const env=(globalThis.process?.env?.APP_ENV??globalThis.process?.env?.NODE_ENV??"").toLowerCase();return env==="production"}
@@ -1 +1 @@
1
- import{config as appConfig}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{assertEnvelopeAddress,assertHeaderSafeSubject,assertHeaderValue}from"../validation";export class BaseEmailDriver{config;constructor(config){this.config={maxRetries:config?.maxRetries||3,retryTimeout:config?.retryTimeout||1000,...config}}configure(config){this.config={...this.config,...config}}validateMessage(message){if(!message.from?.address&&!appConfig.email.from?.address)throw Error("Email sender address is required either in message or config");if(!message.to||Array.isArray(message.to)&&message.to.length===0)throw Error("At least one recipient is required");if(!message.subject)throw Error("Email subject is required");assertHeaderSafeSubject(message.subject);const checkAddresses=(value,role)=>{if(value===void 0||value===null)return;if(Array.isArray(value))for(const item of value)checkAddresses(item,role);else if(typeof value==="string")assertEnvelopeAddress(value,role);else{const address=value;assertEnvelopeAddress(address.address,role);if(address.name!==void 0)assertHeaderValue(address.name,`${role} name`)}};checkAddresses(message.from??appConfig.email.from,"from");checkAddresses(message.to,"to");checkAddresses(message.cc,"cc");checkAddresses(message.bcc,"bcc");checkAddresses(message.replyTo,"replyTo");return!0}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((_addr)=>{if(typeof _addr==="string")return _addr;if(!_addr.name)return _addr.address;return`${/[",()<>[\]:;@\\]/.test(_addr.name)?`"${_addr.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:_addr.name} <${_addr.address}>`})}formatAddressList(value){if(!value)return[];if(Array.isArray(value))return this.formatAddresses(value);if(typeof value==="string")return this.formatAddresses(value);return this.formatAddresses([value])}async handleError(error,message){const err=error instanceof Error?error:Error(String(error));log.error(`[${this.name}] Email sending failed`,{error:err.message,stack:err.stack,to:message.to,subject:message.subject});let result={message:`Email sending failed: ${err.message}`,success:!1,provider:this.name};if(message.onError){const customResult=message.onError(err),handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:!1,provider:this.name}}return result}async handleSuccess(message,messageId){let result={message:"Email sent successfully",success:!0,provider:this.name,messageId};try{if(message.handle){const customResult=message.handle(),handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:!0,provider:this.name,messageId}}if(message.onSuccess){const successResult=message.onSuccess(),handlerResult=successResult instanceof Promise?await successResult:successResult;result={...result,...handlerResult,success:!0,provider:this.name,messageId}}}catch(error){return this.handleError(error,message)}return result}}
1
+ import{config as appConfig}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{assertEnvelopeAddress,assertHeaderSafeSubject,assertHeaderValue}from"../validation";export class BaseEmailDriver{config;constructor(config){this.config={maxRetries:config?.maxRetries||3,retryTimeout:config?.retryTimeout||1000,...config}}configure(config){this.config={...this.config,...config}}validateMessage(message){if(!message.from?.address&&!appConfig.email.from?.address){throw new Error("Email sender address is required either in message or config")}if(!message.to||Array.isArray(message.to)&&message.to.length===0){throw new Error("At least one recipient is required")}if(!message.subject){throw new Error("Email subject is required")}assertHeaderSafeSubject(message.subject);const checkAddresses=(value,role)=>{if(value===undefined||value===null)return;if(Array.isArray(value)){for(const item of value)checkAddresses(item,role)}else if(typeof value==="string"){assertEnvelopeAddress(value,role)}else{const address=value;assertEnvelopeAddress(address.address,role);if(address.name!==undefined)assertHeaderValue(address.name,`${role} name`)}};checkAddresses(message.from??appConfig.email.from,"from");checkAddresses(message.to,"to");checkAddresses(message.cc,"cc");checkAddresses(message.bcc,"bcc");checkAddresses(message.replyTo,"replyTo");return true}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string"){return[addresses]}return addresses.map((_addr)=>{if(typeof _addr==="string")return _addr;if(!_addr.name)return _addr.address;const needsQuoting=/[",()<>[\]:;@\\]/.test(_addr.name);const safeName=needsQuoting?`"${_addr.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:_addr.name;return`${safeName} <${_addr.address}>`})}formatAddressList(value){if(!value)return[];if(Array.isArray(value))return this.formatAddresses(value);if(typeof value==="string")return this.formatAddresses(value);return this.formatAddresses([value])}async handleError(error,message){const err=error instanceof Error?error:new Error(String(error));log.error(`[${this.name}] Email sending failed`,{error:err.message,stack:err.stack,to:message.to,subject:message.subject});let result={message:`Email sending failed: ${err.message}`,success:false,provider:this.name};if(message.onError){const customResult=message.onError(err);const handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:false,provider:this.name}}return result}async handleSuccess(message,messageId){let result={message:"Email sent successfully",success:true,provider:this.name,messageId};try{if(message.handle){const customResult=message.handle();const handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:true,provider:this.name,messageId}}if(message.onSuccess){const successResult=message.onSuccess();const handlerResult=successResult instanceof Promise?await successResult:successResult;result={...result,...handlerResult,success:true,provider:this.name,messageId}}}catch(error){return this.handleError(error,message)}return result}}
@@ -1 +1 @@
1
- import{BaseEmailDriver}from"./base";const captured=[];let nextId=1;export class CaptureEmailDriver extends BaseEmailDriver{name="capture";async send(message,_options){try{this.validateMessage(message);const sentAt=new Date,messageId=`capture-${sentAt.getTime()}-${nextId++}`;captured.push({...message,sentAt,messageId});return this.handleSuccess(message,messageId)}catch(error){return this.handleError(error,message)}}static all(){return captured}static last(){return captured[captured.length-1]}static count(){return captured.length}static clear(){captured.length=0;nextId=1}}
1
+ import{BaseEmailDriver}from"./base";const captured=[];let nextId=1;export class CaptureEmailDriver extends BaseEmailDriver{name="capture";async send(message,_options){try{this.validateMessage(message);const sentAt=new Date;const messageId=`capture-${sentAt.getTime()}-${nextId++}`;captured.push({...message,sentAt,messageId});return this.handleSuccess(message,messageId)}catch(error){return this.handleError(error,message)}}static all(){return captured}static last(){return captured[captured.length-1]}static count(){return captured.length}static clear(){captured.length=0;nextId=1}}
@@ -1,4 +1,4 @@
1
- import{mkdir,writeFile}from"node:fs/promises";import{join,resolve}from"node:path";import{log}from"@stacksjs/logging";import{logsPath}from"@stacksjs/path";import{templateByName}from"../template";import{BaseEmailDriver}from"./base";const STORE_LIMIT=100,captured=[];export class LogEmailDriver extends BaseEmailDriver{name="log";static directory(){const fromEnv=process.env.LOG_MAIL_DIR;return fromEnv?resolve(fromEnv):logsPath("mail")}async send(message,options){try{this.validateMessage(message);let rendered;if(message.template){const t=await templateByName(message.template,options);if(t)rendered={html:t.html,text:t.text}}const html=rendered?.html??message.html,text=rendered?.text??message.text,stamp=new Date,safeSubject=(message.subject||"no-subject").replace(/[^\w.-]+/g,"-").slice(0,60),filename=`${stamp.toISOString().replace(/[:.]/g,"-")}-${safeSubject}.html`,dir=LogEmailDriver.directory();try{await mkdir(dir,{recursive:!0});const filePath=join(dir,filename),body=html?html:text?`<pre>${escapeHtml(text)}</pre>`:"<em>(empty body)</em>",headerBlock=renderHeader({stamp,message});await writeFile(filePath,`${headerBlock}
1
+ import{mkdir,writeFile}from"node:fs/promises";import{join,resolve}from"node:path";import{log}from"@stacksjs/logging";import{logsPath}from"@stacksjs/path";import{templateByName}from"../template";import{BaseEmailDriver}from"./base";const STORE_LIMIT=100;const captured=[];export class LogEmailDriver extends BaseEmailDriver{name="log";static directory(){const fromEnv=process.env.LOG_MAIL_DIR;return fromEnv?resolve(fromEnv):logsPath("mail")}async send(message,options){try{this.validateMessage(message);let rendered;if(message.template){const t=await templateByName(message.template,options);if(t)rendered={html:t.html,text:t.text}}const html=rendered?.html??message.html;const text=rendered?.text??message.text;const stamp=new Date;const safeSubject=(message.subject||"no-subject").replace(/[^\w.-]+/g,"-").slice(0,60);const filename=`${stamp.toISOString().replace(/[:.]/g,"-")}-${safeSubject}.html`;const dir=LogEmailDriver.directory();try{await mkdir(dir,{recursive:true});const filePath=join(dir,filename);const body=html?html:text?`<pre>${escapeHtml(text)}</pre>`:"<em>(empty body)</em>";const headerBlock=renderHeader({stamp,message});await writeFile(filePath,`${headerBlock}
2
2
  ${body}
3
- `)}catch(err){log.warn(`[email:log] could not write inspection file: ${err.message}`)}const flatTo=Array.isArray(message.to)?message.to.map((t)=>typeof t==="string"?t:t.address).join(", "):typeof message.to==="string"?message.to:message.to.address;log.info(`[email:log] would send \u2192 ${flatTo} :: ${message.subject}`);captured.push({...message,sentAt:stamp,rendered});if(captured.length>STORE_LIMIT)captured.splice(0,captured.length-STORE_LIMIT);return this.handleSuccess(message,`log-${stamp.getTime()}`)}catch(error){return this.handleError(error,message)}}static captured(){return captured}static reset(){captured.length=0}}function renderHeader({stamp,message}){return["<!--",` Captured by @stacksjs/email log driver at ${stamp.toISOString()}`,` From: ${formatAddr(message.from)}`,` To: ${formatList(message.to)}`,message.cc?` Cc: ${formatList(message.cc)}`:null,message.bcc?` Bcc: ${formatList(message.bcc)}`:null,` Subject: ${message.subject}`,"-->"].filter(Boolean).join(`
3
+ `)}catch(err){log.warn(`[email:log] could not write inspection file: ${err.message}`)}const flatTo=Array.isArray(message.to)?message.to.map((t)=>typeof t==="string"?t:t.address).join(", "):typeof message.to==="string"?message.to:message.to.address;log.info(`[email:log] would send → ${flatTo} :: ${message.subject}`);captured.push({...message,sentAt:stamp,rendered});if(captured.length>STORE_LIMIT)captured.splice(0,captured.length-STORE_LIMIT);return this.handleSuccess(message,`log-${stamp.getTime()}`)}catch(error){return this.handleError(error,message)}}static captured(){return captured}static reset(){captured.length=0}}function renderHeader({stamp,message}){const lines=["<!--",` Captured by @stacksjs/email log driver at ${stamp.toISOString()}`,` From: ${formatAddr(message.from)}`,` To: ${formatList(message.to)}`,message.cc?` Cc: ${formatList(message.cc)}`:null,message.bcc?` Bcc: ${formatList(message.bcc)}`:null,` Subject: ${message.subject}`,"-->"].filter(Boolean);return lines.join(`
4
4
  `)}function formatAddr(v){if(!v)return"";if(typeof v==="string")return v;const o=v;return o.name?`${o.name} <${o.address??""}>`:o.address??""}function formatList(v){if(Array.isArray(v))return v.map(formatAddr).join(", ");return formatAddr(v)}function escapeHtml(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}export default LogEmailDriver;
@@ -1 +1 @@
1
- import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{BaseEmailDriver}from"./base";export class MailgunDriver extends BaseEmailDriver{name="mailgun";apiKey=null;domain=null;endpoint=null;getConfig(){if(!this.apiKey||!this.domain||!this.endpoint){this.apiKey=config.services.mailgun?.apiKey??"";this.domain=config.services.mailgun?.domain??"";this.endpoint=config.services.mailgun?.endpoint??"api.mailgun.net"}return{apiKey:this.apiKey,domain:this.domain,endpoint:this.endpoint}}async send(message,options){const{domain}=this.getConfig(),logContext={provider:this.name,to:message.to,subject:message.subject,domain};log.info("Sending email via Mailgun...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ)htmlContent=templ.html}const finalHtml=htmlContent||message.html,formData=new FormData,fromAddress={address:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name};formData.append("from",this.formatMailgunAddress(fromAddress));this.formatMailgunAddresses(message.to).forEach((to)=>formData.append("to",to));if(message.cc)this.formatMailgunAddresses(message.cc).forEach((cc)=>formData.append("cc",cc));if(message.bcc)this.formatMailgunAddresses(message.bcc).forEach((bcc)=>formData.append("bcc",bcc));formData.append("subject",message.subject);if(message.replyTo){const formatted=this.formatMailgunAddresses(Array.isArray(message.replyTo)||typeof message.replyTo==="string"?message.replyTo:[message.replyTo]);if(formatted.length>0)formData.append("h:Reply-To",formatted.join(", "))}if(message.headers){for(const[k,v]of Object.entries(message.headers))if(typeof v==="string")formData.append(`h:${k}`,v)}if(finalHtml)formData.append("html",finalHtml);if(message.text)formData.append("text",message.text);if(message.attachments)message.attachments.forEach((attachment)=>{const content=typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content);formData.append("attachment",new Blob([content],{type:attachment.contentType}),attachment.filename)});const response=await this.sendWithRetry(formData);return this.handleSuccess(message,response.id)}catch(error){return this.handleError(error,message)}}formatMailgunAddress(address){return address.name?`${address.name} <${address.address}>`:address.address}formatMailgunAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((_addr)=>{if(typeof _addr==="string")return _addr;if(!_addr.name)return _addr.address;return`${/[",()<>[\]:;@\\]/.test(_addr.name)?`"${_addr.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:_addr.name} <${_addr.address}>`})}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer),len=bytes.byteLength;for(let i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]??0);return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(formData,attempt=1){const{apiKey,domain,endpoint}=this.getConfig(),url=`https://${endpoint}/v3/${domain}/messages`,auth=Buffer.from(`api:${apiKey}`).toString("base64");try{const response=await fetch(url,{method:"POST",headers:{Authorization:`Basic ${auth}`},body:formData});if(!response.ok){const errorData=await response.json();throw Error(`Mailgun API error: ${response.status} - ${JSON.stringify(errorData)}`)}const data=await response.json();log.info(`[${this.name}] Email sent successfully`,{attempt,messageId:data.id});return data}catch(error){if(attempt<(config.services.mailgun?.maxRetries??3)){const retryTimeout=config.services.mailgun?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.mailgun?.maxRetries??3})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(formData,attempt+1)}throw error}}}export default MailgunDriver;
1
+ import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{BaseEmailDriver}from"./base";export class MailgunDriver extends BaseEmailDriver{name="mailgun";apiKey=null;domain=null;endpoint=null;getConfig(){if(!this.apiKey||!this.domain||!this.endpoint){this.apiKey=config.services.mailgun?.apiKey??"";this.domain=config.services.mailgun?.domain??"";this.endpoint=config.services.mailgun?.endpoint??"api.mailgun.net"}return{apiKey:this.apiKey,domain:this.domain,endpoint:this.endpoint}}async send(message,options){const{domain}=this.getConfig();const logContext={provider:this.name,to:message.to,subject:message.subject,domain};log.info("Sending email via Mailgun...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ){htmlContent=templ.html}}const finalHtml=htmlContent||message.html;const formData=new FormData;const fromAddress={address:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name};formData.append("from",this.formatMailgunAddress(fromAddress));this.formatMailgunAddresses(message.to).forEach((to)=>formData.append("to",to));if(message.cc)this.formatMailgunAddresses(message.cc).forEach((cc)=>formData.append("cc",cc));if(message.bcc)this.formatMailgunAddresses(message.bcc).forEach((bcc)=>formData.append("bcc",bcc));formData.append("subject",message.subject);if(message.replyTo){const formatted=this.formatMailgunAddresses(Array.isArray(message.replyTo)||typeof message.replyTo==="string"?message.replyTo:[message.replyTo]);if(formatted.length>0)formData.append("h:Reply-To",formatted.join(", "))}if(message.headers){for(const[k,v]of Object.entries(message.headers)){if(typeof v==="string")formData.append(`h:${k}`,v)}}if(finalHtml){formData.append("html",finalHtml)}if(message.text)formData.append("text",message.text);if(message.attachments){message.attachments.forEach((attachment)=>{const content=typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content);formData.append("attachment",new Blob([content],{type:attachment.contentType}),attachment.filename)})}const response=await this.sendWithRetry(formData);return this.handleSuccess(message,response.id)}catch(error){return this.handleError(error,message)}}formatMailgunAddress(address){return address.name?`${address.name} <${address.address}>`:address.address}formatMailgunAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((_addr)=>{if(typeof _addr==="string")return _addr;if(!_addr.name)return _addr.address;const needsQuoting=/[",()<>[\]:;@\\]/.test(_addr.name);const safeName=needsQuoting?`"${_addr.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:_addr.name;return`${safeName} <${_addr.address}>`})}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer);const len=bytes.byteLength;for(let i=0;i<len;i++){binary+=String.fromCharCode(bytes[i]??0)}return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(formData,attempt=1){const{apiKey,domain,endpoint}=this.getConfig();const url=`https://${endpoint}/v3/${domain}/messages`;const auth=Buffer.from(`api:${apiKey}`).toString("base64");try{const response=await fetch(url,{method:"POST",headers:{Authorization:`Basic ${auth}`},body:formData});if(!response.ok){const errorData=await response.json();throw new Error(`Mailgun API error: ${response.status} - ${JSON.stringify(errorData)}`)}const data=await response.json();log.info(`[${this.name}] Email sent successfully`,{attempt,messageId:data.id});return data}catch(error){if(attempt<(config.services.mailgun?.maxRetries??3)){const retryTimeout=config.services.mailgun?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.mailgun?.maxRetries??3})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(formData,attempt+1)}throw error}}}export default MailgunDriver;
@@ -1 +1 @@
1
- import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export const MAILTRAP_SENDING_URL="https://send.api.mailtrap.io/api/send",MAILTRAP_SANDBOX_URL="https://sandbox.api.mailtrap.io/api/send";function present(value){const text=value==null?"":String(value).trim();return text?text:void 0}export function mailtrapEndpoint(options){const host=present(options.host)?.replace(/\/+$/,""),inboxId=present(options.inboxId);if(inboxId)return`${host??MAILTRAP_SANDBOX_URL}/${encodeURIComponent(inboxId)}`;if(host&&/sandbox\.api\.mailtrap\.io/i.test(host))throw Error("MAILTRAP_HOST points at the Mailtrap sandbox, which needs MAILTRAP_INBOX_ID. Set the inbox id to capture mail for testing, or unset MAILTRAP_HOST to deliver it.");return host??MAILTRAP_SENDING_URL}export class MailtrapDriver extends BaseEmailDriver{name="mailtrap";getConfig(){const mailtrap=config.services.mailtrap,token=present(mailtrap?.token);if(!token)throw Error("Mailtrap API token is required but not provided. Please set MAILTRAP_TOKEN in your environment variables.");return{endpoint:mailtrapEndpoint({host:mailtrap?.host,inboxId:mailtrap?.inboxId}),token,inboxId:present(mailtrap?.inboxId)}}async send(message,options){const inboxId=present(config.services.mailtrap?.inboxId),logContext={provider:this.name,to:message.to,subject:message.subject,inboxId};log.info("Sending email via Mailtrap...",logContext);try{this.validateMessage(message);let templ;if(message.template)templ=await templateByName(message.template,options);const htmlContent=templ?.html||message.html,replyTo=this.firstMailtrapAddress(message.replyTo),customHeaders=filterStringHeaders(message.headers),mailtrapPayload={from:{email:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name},to:this.formatMailtrapAddresses(message.to),...message.cc&&{cc:this.formatMailtrapAddresses(message.cc)},...message.bcc&&{bcc:this.formatMailtrapAddresses(message.bcc)},...replyTo?{reply_to:replyTo}:{},...customHeaders?{headers:customHeaders}:{},subject:message.subject,...htmlContent&&{html:htmlContent},...message.text&&{text:message.text},...message.attachments&&{attachments:message.attachments.map((attachment)=>({filename:attachment.filename,content:typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content),type:attachment.contentType||"application/octet-stream"}))}},response=await this.sendWithRetry(mailtrapPayload);return this.handleSuccess(message,response.message_ids?.[0])}catch(error){return this.handleError(error,message)}}formatMailtrapAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[{email:addresses}];return addresses.map((addr)=>{if(typeof addr==="string")return{email:addr};return{email:addr.address,...addr.name&&{name:addr.name}}})}firstMailtrapAddress(value){if(!value)return;if(typeof value==="string")return{email:value};if(Array.isArray(value)){const first=value[0];if(first===void 0)return;if(typeof first==="string")return{email:first};return{email:first.address,...first.name&&{name:first.name}}}return{email:value.address,...value.name&&{name:value.name}}}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer),len=bytes.byteLength;for(let i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]??0);return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(payload,attempt=1){const{endpoint,token}=this.getConfig();try{const response=await fetch(endpoint,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});if(!response.ok){const errorData=await response.json().catch(()=>({})),err=Error(`Mailtrap API error: ${response.status} - ${JSON.stringify(errorData)}`);err.status=response.status;throw err}const data=await response.json();log.info(`[${this.name}] Email sent successfully`,{attempt,messageId:data.message_ids?.[0]});return data}catch(error){const status=error?.status,nonRetryable=typeof status==="number"&&status>=400&&status<500&&status!==429,maxRetries=config.services.mailtrap?.maxRetries??3;if(!nonRetryable&&attempt<maxRetries){const retryTimeout=config.services.mailtrap?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${maxRetries})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(payload,attempt+1)}throw error}}}export default MailtrapDriver;
1
+ import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export const MAILTRAP_SENDING_URL="https://send.api.mailtrap.io/api/send";export const MAILTRAP_SANDBOX_URL="https://sandbox.api.mailtrap.io/api/send";function present(value){const text=value==null?"":String(value).trim();return text?text:undefined}export function mailtrapEndpoint(options){const host=present(options.host)?.replace(/\/+$/,"");const inboxId=present(options.inboxId);if(inboxId)return`${host??MAILTRAP_SANDBOX_URL}/${encodeURIComponent(inboxId)}`;if(host&&/sandbox\.api\.mailtrap\.io/i.test(host))throw new Error("MAILTRAP_HOST points at the Mailtrap sandbox, which needs MAILTRAP_INBOX_ID. Set the inbox id to capture mail for testing, or unset MAILTRAP_HOST to deliver it.");return host??MAILTRAP_SENDING_URL}export class MailtrapDriver extends BaseEmailDriver{name="mailtrap";getConfig(){const mailtrap=config.services.mailtrap;const token=present(mailtrap?.token);if(!token)throw new Error("Mailtrap API token is required but not provided. Please set MAILTRAP_TOKEN in your environment variables.");return{endpoint:mailtrapEndpoint({host:mailtrap?.host,inboxId:mailtrap?.inboxId}),token,inboxId:present(mailtrap?.inboxId)}}async send(message,options){const inboxId=present(config.services.mailtrap?.inboxId);const logContext={provider:this.name,to:message.to,subject:message.subject,inboxId};log.info("Sending email via Mailtrap...",logContext);try{this.validateMessage(message);let templ;if(message.template)templ=await templateByName(message.template,options);const htmlContent=templ?.html||message.html;const replyTo=this.firstMailtrapAddress(message.replyTo);const customHeaders=filterStringHeaders(message.headers);const mailtrapPayload={from:{email:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name},to:this.formatMailtrapAddresses(message.to),...message.cc&&{cc:this.formatMailtrapAddresses(message.cc)},...message.bcc&&{bcc:this.formatMailtrapAddresses(message.bcc)},...replyTo?{reply_to:replyTo}:{},...customHeaders?{headers:customHeaders}:{},subject:message.subject,...htmlContent&&{html:htmlContent},...message.text&&{text:message.text},...message.attachments&&{attachments:message.attachments.map((attachment)=>({filename:attachment.filename,content:typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content),type:attachment.contentType||"application/octet-stream"}))}};const response=await this.sendWithRetry(mailtrapPayload);return this.handleSuccess(message,response.message_ids?.[0])}catch(error){return this.handleError(error,message)}}formatMailtrapAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string"){return[{email:addresses}]}return addresses.map((addr)=>{if(typeof addr==="string")return{email:addr};return{email:addr.address,...addr.name&&{name:addr.name}}})}firstMailtrapAddress(value){if(!value)return;if(typeof value==="string")return{email:value};if(Array.isArray(value)){const first=value[0];if(first===undefined)return;if(typeof first==="string")return{email:first};return{email:first.address,...first.name&&{name:first.name}}}return{email:value.address,...value.name&&{name:value.name}}}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer);const len=bytes.byteLength;for(let i=0;i<len;i++){binary+=String.fromCharCode(bytes[i]??0)}return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(payload,attempt=1){const{endpoint,token}=this.getConfig();try{const response=await fetch(endpoint,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});if(!response.ok){const errorData=await response.json().catch(()=>({}));const err=new Error(`Mailtrap API error: ${response.status} - ${JSON.stringify(errorData)}`);err.status=response.status;throw err}const data=await response.json();log.info(`[${this.name}] Email sent successfully`,{attempt,messageId:data.message_ids?.[0]});return data}catch(error){const status=error?.status;const nonRetryable=typeof status==="number"&&status>=400&&status<500&&status!==429;const maxRetries=config.services.mailtrap?.maxRetries??3;if(!nonRetryable&&attempt<maxRetries){const retryTimeout=config.services.mailtrap?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${maxRetries})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(payload,attempt+1)}throw error}}}export default MailtrapDriver;
@@ -1 +1 @@
1
- import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export class SendGridDriver extends BaseEmailDriver{name="sendgrid";apiKey=null;getApiKey(){if(!this.apiKey)this.apiKey=config.services.sendgrid?.apiKey??"";return this.apiKey}async send(message,options){const logContext={provider:this.name,to:message.to,subject:message.subject};log.info("Sending email via SendGrid...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ)htmlContent=templ.html}const finalHtml=htmlContent||message.html,content=[];if(finalHtml)content.push({type:"text/html",value:finalHtml});if(message.text)content.push({type:"text/plain",value:message.text});if(content.length===0)throw Error("Email must have either HTML or text content");const replyTo=this.firstSendGridAddress(message.replyTo),customHeaders=filterStringHeaders(message.headers),sendgridPayload={personalizations:[{to:this.formatSendGridAddresses(message.to),...message.cc&&{cc:this.formatSendGridAddresses(message.cc)},...message.bcc&&{bcc:this.formatSendGridAddresses(message.bcc)},subject:message.subject}],from:{email:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name},...replyTo?{reply_to:replyTo}:{},...customHeaders?{headers:customHeaders}:{},content,...message.attachments&&{attachments:message.attachments.map((attachment)=>({filename:attachment.filename,content:typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content),type:attachment.contentType,disposition:"attachment"}))}},response=await this.sendWithRetry(sendgridPayload);return this.handleSuccess(message,response.headers?.get("x-message-id")??void 0)}catch(error){return this.handleError(error,message)}}formatSendGridAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[{email:addresses}];return addresses.map((addr)=>{if(typeof addr==="string")return{email:addr};return{email:addr.address,...addr.name&&{name:addr.name}}})}firstSendGridAddress(value){if(!value)return;if(typeof value==="string")return{email:value};if(Array.isArray(value)){const first=value[0];if(first===void 0)return;if(typeof first==="string")return{email:first};return{email:first.address,...first.name&&{name:first.name}}}return{email:value.address,...value.name&&{name:value.name}}}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer),len=bytes.byteLength;for(let i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]??0);return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(payload,attempt=1){try{const response=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{Authorization:`Bearer ${this.getApiKey()}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});if(!response.ok){const errorData=await response.json(),err=Error(`SendGrid API error: ${response.status} - ${JSON.stringify(errorData)}`);err.status=response.status;throw err}log.info(`[${this.name}] Email sent successfully`,{attempt});return response}catch(error){const status=error?.status;if(!(typeof status==="number"&&status>=400&&status<500&&status!==429)&&attempt<(config.services.sendgrid?.maxRetries??3)){const retryTimeout=config.services.sendgrid?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.sendgrid?.maxRetries??3})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(payload,attempt+1)}throw error}}}export default SendGridDriver;
1
+ import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export class SendGridDriver extends BaseEmailDriver{name="sendgrid";apiKey=null;getApiKey(){if(!this.apiKey){this.apiKey=config.services.sendgrid?.apiKey??""}return this.apiKey}async send(message,options){const logContext={provider:this.name,to:message.to,subject:message.subject};log.info("Sending email via SendGrid...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ){htmlContent=templ.html}}const finalHtml=htmlContent||message.html;const content=[];if(finalHtml){content.push({type:"text/html",value:finalHtml})}if(message.text){content.push({type:"text/plain",value:message.text})}if(content.length===0){throw new Error("Email must have either HTML or text content")}const replyTo=this.firstSendGridAddress(message.replyTo);const customHeaders=filterStringHeaders(message.headers);const sendgridPayload={personalizations:[{to:this.formatSendGridAddresses(message.to),...message.cc&&{cc:this.formatSendGridAddresses(message.cc)},...message.bcc&&{bcc:this.formatSendGridAddresses(message.bcc)},subject:message.subject}],from:{email:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name},...replyTo?{reply_to:replyTo}:{},...customHeaders?{headers:customHeaders}:{},content,...message.attachments&&{attachments:message.attachments.map((attachment)=>({filename:attachment.filename,content:typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content),type:attachment.contentType,disposition:"attachment"}))}};const response=await this.sendWithRetry(sendgridPayload);return this.handleSuccess(message,response.headers?.get("x-message-id")??undefined)}catch(error){return this.handleError(error,message)}}formatSendGridAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string"){return[{email:addresses}]}return addresses.map((addr)=>{if(typeof addr==="string")return{email:addr};return{email:addr.address,...addr.name&&{name:addr.name}}})}firstSendGridAddress(value){if(!value)return;if(typeof value==="string")return{email:value};if(Array.isArray(value)){const first=value[0];if(first===undefined)return;if(typeof first==="string")return{email:first};return{email:first.address,...first.name&&{name:first.name}}}return{email:value.address,...value.name&&{name:value.name}}}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer);const len=bytes.byteLength;for(let i=0;i<len;i++){binary+=String.fromCharCode(bytes[i]??0)}return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(payload,attempt=1){try{const response=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{Authorization:`Bearer ${this.getApiKey()}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});if(!response.ok){const errorData=await response.json();const err=new Error(`SendGrid API error: ${response.status} - ${JSON.stringify(errorData)}`);err.status=response.status;throw err}log.info(`[${this.name}] Email sent successfully`,{attempt});return response}catch(error){const status=error?.status;const nonRetryable=typeof status==="number"&&status>=400&&status<500&&status!==429;if(!nonRetryable&&attempt<(config.services.sendgrid?.maxRetries??3)){const retryTimeout=config.services.sendgrid?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.sendgrid?.maxRetries??3})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(payload,attempt+1)}throw error}}}export default SendGridDriver;
@@ -1,4 +1,4 @@
1
- import{config}from"@stacksjs/config";import{templateByName}from"../template";import{buildMimeMessage}from"../mime";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export class SESDriver extends BaseEmailDriver{name="ses";client=null;clientPromise=null;async getClient(){if(this.client)return this.client;if(!this.clientPromise)this.clientPromise=import("@stacksjs/ts-cloud").then(({SESClient})=>{const sesConfig=config?.services?.ses,explicit=sesConfig?.credentials,hasExplicit=!!(explicit?.accessKeyId&&explicit?.secretAccessKey);this.client=new SESClient(sesConfig?.region||"us-east-1",hasExplicit?{accessKeyId:explicit.accessKeyId,secretAccessKey:explicit.secretAccessKey,sessionToken:explicit.sessionToken}:void 0);return this.client});return this.clientPromise}async send(message,options){try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ)htmlContent=templ.html}const finalHtml=htmlContent||message.html;if(!finalHtml&&!message.text)throw Error("Email must have either HTML or text content");const fromAddress=this.formatSourceAddress({address:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name}),toAddresses=this.formatAddresses(message.to),ccAddresses=this.formatAddresses(message.cc),bccAddresses=this.formatAddresses(message.bcc),replyToAddresses=message.replyTo?this.formatAddressList(message.replyTo):[],customHeaders=filterStringHeaders(message.headers),hasAttachments=!!(message.attachments&&message.attachments.length>0),hasCustomHeaders=!!customHeaders,client=await this.getClient();if(hasAttachments||hasCustomHeaders){const raw=buildMimeMessage({from:fromAddress,to:toAddresses.join(", "),cc:ccAddresses.length>0?ccAddresses.join(", "):void 0,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):void 0,customHeaders,subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain}),result=await client.sendRawEmail({source:fromAddress,destinations:[...toAddresses,...ccAddresses,...bccAddresses],rawMessage:raw});return this.handleSuccess(message,result.MessageId)}const body={};if(finalHtml)body.Html={Charset:config.email.charset||"UTF-8",Data:finalHtml};if(message.text)body.Text={Charset:config.email.charset||"UTF-8",Data:message.text};const result=await client.sendEmail({FromEmailAddress:fromAddress,Destination:{ToAddresses:toAddresses,CcAddresses:ccAddresses,BccAddresses:bccAddresses},...replyToAddresses.length>0?{ReplyToAddresses:replyToAddresses}:{},Content:{Simple:{Subject:{Charset:config.email.charset||"UTF-8",Data:message.subject},Body:body}}});return this.handleSuccess(message,result.MessageId)}catch(error){return this.handleError(this.enrichSesError(error),message)}}formatSourceAddress(from){if(!from.name)return from.address;return`${/[",()<>[\]:;@\\]/.test(from.name)?`"${from.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:from.name} <${from.address}>`}enrichSesError(error){const err=error instanceof Error?error:Error(String(error)),text=`${err.message} ${err.name??""}`.toLowerCase(),region=config?.services?.ses?.region||"us-east-1";if(text.includes("email address is not verified")||text.includes("not authorized to send")||text.includes("messagerejected")&&text.includes("verified")){err.message=`${err.message}
1
+ import{config}from"@stacksjs/config";import{templateByName}from"../template";import{buildMimeMessage}from"../mime";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export class SESDriver extends BaseEmailDriver{name="ses";client=null;clientPromise=null;async getClient(){if(this.client)return this.client;if(!this.clientPromise){this.clientPromise=import("@stacksjs/ts-cloud").then(({SESClient})=>{const sesConfig=config?.services?.ses;const explicit=sesConfig?.credentials;const hasExplicit=!!(explicit?.accessKeyId&&explicit?.secretAccessKey);this.client=new SESClient(sesConfig?.region||"us-east-1",hasExplicit?{accessKeyId:explicit.accessKeyId,secretAccessKey:explicit.secretAccessKey,sessionToken:explicit.sessionToken}:undefined);return this.client})}return this.clientPromise}async send(message,options){try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ){htmlContent=templ.html}}const finalHtml=htmlContent||message.html;if(!finalHtml&&!message.text){throw new Error("Email must have either HTML or text content")}const fromAddress=this.formatSourceAddress({address:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name});const toAddresses=this.formatAddresses(message.to);const ccAddresses=this.formatAddresses(message.cc);const bccAddresses=this.formatAddresses(message.bcc);const replyToAddresses=message.replyTo?this.formatAddressList(message.replyTo):[];const customHeaders=filterStringHeaders(message.headers);const hasAttachments=!!(message.attachments&&message.attachments.length>0);const hasCustomHeaders=!!customHeaders;const client=await this.getClient();if(hasAttachments||hasCustomHeaders){const raw=buildMimeMessage({from:fromAddress,to:toAddresses.join(", "),cc:ccAddresses.length>0?ccAddresses.join(", "):undefined,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):undefined,customHeaders,subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain});const result=await client.sendRawEmail({source:fromAddress,destinations:[...toAddresses,...ccAddresses,...bccAddresses],rawMessage:raw});return this.handleSuccess(message,result.MessageId)}const body={};if(finalHtml){body.Html={Charset:config.email.charset||"UTF-8",Data:finalHtml}}if(message.text){body.Text={Charset:config.email.charset||"UTF-8",Data:message.text}}const result=await client.sendEmail({FromEmailAddress:fromAddress,Destination:{ToAddresses:toAddresses,CcAddresses:ccAddresses,BccAddresses:bccAddresses},...replyToAddresses.length>0?{ReplyToAddresses:replyToAddresses}:{},Content:{Simple:{Subject:{Charset:config.email.charset||"UTF-8",Data:message.subject},Body:body}}});return this.handleSuccess(message,result.MessageId)}catch(error){return this.handleError(this.enrichSesError(error),message)}}formatSourceAddress(from){if(!from.name)return from.address;const needsQuoting=/[",()<>[\]:;@\\]/.test(from.name);const safeName=needsQuoting?`"${from.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:from.name;return`${safeName} <${from.address}>`}enrichSesError(error){const err=error instanceof Error?error:new Error(String(error));const text=`${err.message} ${err.name??""}`.toLowerCase();const region=config?.services?.ses?.region||"us-east-1";if(text.includes("email address is not verified")||text.includes("not authorized to send")||text.includes("messagerejected")&&text.includes("verified")){err.message=`${err.message}
2
2
 
3
3
  SES sandbox restriction: the From and (in sandbox) every To address must be verified. Verify identities in the SES console under "Verified identities" (region: ${region}), or request production access to lift the recipient restriction.`;return err}if(text.includes("signaturedoesnotmatch")||text.includes("invalidclienttokenid")||text.includes("unable to locate credentials")||text.includes("the security token included in the request is invalid")){err.message=`${err.message}
4
4
 
@@ -1,7 +1,7 @@
1
- import{Buffer}from"node:buffer";import process from"node:process";import*as tls from"node:tls";import*as net from"node:net";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{buildMimeMessage}from"../mime";import{ENVELOPE_ADDRESS,filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr))throw Error(`[smtp] Refusing to send: ${role} envelope address contains forbidden characters or is malformed: ${JSON.stringify(addr)}`)}export class SMTPDriver extends BaseEmailDriver{static SMTP_TIMEOUT=30000;name="smtp";getConfig(){const smtp=config.services?.smtp,env=process.env,host=smtp?.host||env.MAIL_HOST||"127.0.0.1",port=smtp?.port||(env.MAIL_PORT?Number(env.MAIL_PORT):void 0)||587,fromAddress=typeof config.email?.from?.address==="string"?config.email.from.address:"",username=smtp?.username||env.MAIL_USERNAME||fromAddress||"",localPart=(username.includes("@")?username.split("@")[0]:username).toUpperCase().replace(/[^A-Z0-9]/g,"_"),password=smtp?.password||env.MAIL_PASSWORD||(localPart?env[`MAIL_PASSWORD_${localPart}`]:void 0)||"",rawEncryption=smtp?.encryption??env.MAIL_ENCRYPTION??null;return{host,port,username,password,encryption:rawEncryption==="tls"?"starttls":rawEncryption||null}}async send(message,options){const smtpConfig=this.getConfig();if(!smtpConfig.host||smtpConfig.host==="")throw Error("[SMTP] Host is not configured. Set MAIL_HOST in your .env file.");const logContext={provider:this.name,to:message.to,subject:message.subject,host:smtpConfig.host,port:smtpConfig.port};log.info("Sending email via SMTP...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ)htmlContent=templ.html}const finalHtml=htmlContent||message.html,fromAddress=message.from?.address||config.email.from?.address||"",fromName=message.from?.name||config.email.from?.name||"",toAddresses=this.formatAddresses(message.to),replyToAddresses=this.formatAddressList(message.replyTo),emailContent=buildMimeMessage({from:fromName?`${fromName} <${fromAddress}>`:fromAddress,to:toAddresses.join(", "),cc:message.cc?this.formatAddresses(message.cc).join(", "):void 0,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):void 0,customHeaders:filterStringHeaders(message.headers),subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain}),recipients=[...new Set([...toAddresses,...this.formatAddresses(message.cc),...this.formatAddresses(message.bcc)])],messageId=await this.sendViaSMTP(smtpConfig,fromAddress,recipients,emailContent);return this.handleSuccess(message,messageId)}catch(error){return this.handleError(error,message)}}async sendViaSMTP(smtpConfig,from,to,content){return new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{reject(Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))},SMTPDriver.SMTP_TIMEOUT),originalResolve=resolve,originalReject=reject;resolve=(value)=>{clearTimeout(timeout);originalResolve(value)};reject=(reason)=>{clearTimeout(timeout);originalReject(reason)};let socket,buffer="";const _currentCommand="",commandQueue=[],_isProcessing=!1;let completed=!1;const processResponse=(response)=>{log.debug(`[SMTP] Server: ${response.trim()}`);if(parseInt(response.substring(0,3),10)>=400){const error=Error(`SMTP Error: ${response.trim()}`);if(commandQueue.length>0)commandQueue.shift()?.reject(error);return}if(commandQueue.length>0)commandQueue.shift()?.resolve(response)},sendCommand=(cmd,sensitive=!1)=>{return new Promise((res,rej)=>{commandQueue.push({cmd:sensitive?"[redacted authentication]":cmd,resolve:res,reject:rej});log.debug(`[SMTP] Client: ${sensitive?"[redacted authentication]":cmd}`);socket.write(`${cmd}\r
2
- `)})},handleData=(data)=>{buffer+=data.toString();const lines=buffer.split(`\r
3
- `);buffer=lines.pop()||"";for(const line of lines)if(line.length>=3){if(line.length===3||line[3]===" ")processResponse(line)}},runSmtpSession=async()=>{try{await new Promise((res,rej)=>{commandQueue.push({cmd:"GREETING",resolve:res,reject:rej})});const _ehloResponse=await sendCommand(`EHLO ${config.email.domain||"localhost"}`);if(smtpConfig.encryption==="starttls"&&!(socket instanceof tls.TLSSocket)){await sendCommand("STARTTLS");const plainSocket=socket;plainSocket.removeAllListeners("data");socket=await new Promise((res,rej)=>{const tlsSocket=tls.connect({socket:plainSocket,host:smtpConfig.host,servername:smtpConfig.host},()=>{log.debug("[SMTP] TLS connection established");res(tlsSocket)});tlsSocket.on("error",(err)=>{log.error("[SMTP] TLS socket error:",err);rej(err)});tlsSocket.on("data",handleData);tlsSocket.on("close",(hadError)=>{log.debug(`[SMTP] TLS socket closed (hadError: ${hadError})`);while(commandQueue.length>0)commandQueue.shift()?.reject(Error("TLS connection closed unexpectedly"))})});await sendCommand(`EHLO ${config.email.domain||"localhost"}`)}if(smtpConfig.username&&smtpConfig.password){await sendCommand("AUTH LOGIN");await sendCommand(Buffer.from(smtpConfig.username).toString("base64"),!0);await sendCommand(Buffer.from(smtpConfig.password).toString("base64"),!0)}assertEnvelopeAddress(from,"MAIL FROM");for(const recipient of to)assertEnvelopeAddress(recipient,"RCPT TO");await sendCommand(`MAIL FROM:<${from}>`);for(const recipient of to)await sendCommand(`RCPT TO:<${recipient}>`);await sendCommand("DATA");const stuffed=content.replace(/\r\n|\r|\n/g,`\r
4
- `).replace(/(^|\r\n)\./g,"$1..");socket.write(`${stuffed}\r
1
+ import{Buffer}from"node:buffer";import process from"node:process";import*as tls from"node:tls";import*as net from"node:net";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{buildMimeMessage}from"../mime";import{ENVELOPE_ADDRESS,filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr)){throw new Error(`[smtp] Refusing to send: ${role} envelope address contains forbidden characters or is malformed: ${JSON.stringify(addr)}`)}}export class SMTPDriver extends BaseEmailDriver{static SMTP_TIMEOUT=30000;name="smtp";getConfig(){const smtp=config.services?.smtp;const env=process.env;const host=smtp?.host||env.MAIL_HOST||"127.0.0.1";const port=smtp?.port||(env.MAIL_PORT?Number(env.MAIL_PORT):undefined)||587;const fromAddress=typeof config.email?.from?.address==="string"?config.email.from.address:"";const username=smtp?.username||env.MAIL_USERNAME||fromAddress||"";const localPart=(username.includes("@")?username.split("@")[0]:username).toUpperCase().replace(/[^A-Z0-9]/g,"_");const password=smtp?.password||env.MAIL_PASSWORD||(localPart?env[`MAIL_PASSWORD_${localPart}`]:undefined)||"";const rawEncryption=smtp?.encryption??env.MAIL_ENCRYPTION??null;return{host,port,username,password,encryption:rawEncryption==="tls"?"starttls":rawEncryption||null}}async send(message,options){const smtpConfig=this.getConfig();if(!smtpConfig.host||smtpConfig.host===""){throw new Error("[SMTP] Host is not configured. Set MAIL_HOST in your .env file.")}const logContext={provider:this.name,to:message.to,subject:message.subject,host:smtpConfig.host,port:smtpConfig.port};log.info("Sending email via SMTP...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ){htmlContent=templ.html}}const finalHtml=htmlContent||message.html;const fromAddress=message.from?.address||config.email.from?.address||"";const fromName=message.from?.name||config.email.from?.name||"";const toAddresses=this.formatAddresses(message.to);const replyToAddresses=this.formatAddressList(message.replyTo);const emailContent=buildMimeMessage({from:fromName?`${fromName} <${fromAddress}>`:fromAddress,to:toAddresses.join(", "),cc:message.cc?this.formatAddresses(message.cc).join(", "):undefined,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):undefined,customHeaders:filterStringHeaders(message.headers),subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain});const recipients=[...new Set([...toAddresses,...this.formatAddresses(message.cc),...this.formatAddresses(message.bcc)])];const messageId=await this.sendViaSMTP(smtpConfig,fromAddress,recipients,emailContent);return this.handleSuccess(message,messageId)}catch(error){return this.handleError(error,message)}}async sendViaSMTP(smtpConfig,from,to,content){return new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{reject(new Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))},SMTPDriver.SMTP_TIMEOUT);const originalResolve=resolve;const originalReject=reject;resolve=(value)=>{clearTimeout(timeout);originalResolve(value)};reject=(reason)=>{clearTimeout(timeout);originalReject(reason)};let socket;let buffer="";const _currentCommand="";const commandQueue=[];const _isProcessing=false;let completed=false;const processResponse=(response)=>{log.debug(`[SMTP] Server: ${response.trim()}`);const code=parseInt(response.substring(0,3),10);if(code>=400){const error=new Error(`SMTP Error: ${response.trim()}`);if(commandQueue.length>0){const current=commandQueue.shift();current?.reject(error)}return}if(commandQueue.length>0){const current=commandQueue.shift();current?.resolve(response)}};const sendCommand=(cmd,sensitive=false)=>{return new Promise((res,rej)=>{commandQueue.push({cmd:sensitive?"[redacted authentication]":cmd,resolve:res,reject:rej});log.debug(`[SMTP] Client: ${sensitive?"[redacted authentication]":cmd}`);socket.write(`${cmd}\r
2
+ `)})};const handleData=(data)=>{buffer+=data.toString();const lines=buffer.split(`\r
3
+ `);buffer=lines.pop()||"";for(const line of lines){if(line.length>=3){const isLastLine=line.length===3||line[3]===" ";if(isLastLine){processResponse(line)}}}};const runSmtpSession=async()=>{try{await new Promise((res,rej)=>{commandQueue.push({cmd:"GREETING",resolve:res,reject:rej})});const _ehloResponse=await sendCommand(`EHLO ${config.email.domain||"localhost"}`);if(smtpConfig.encryption==="starttls"&&!(socket instanceof tls.TLSSocket)){await sendCommand("STARTTLS");const plainSocket=socket;plainSocket.removeAllListeners("data");socket=await new Promise((res,rej)=>{const tlsSocket=tls.connect({socket:plainSocket,host:smtpConfig.host,servername:smtpConfig.host},()=>{log.debug("[SMTP] TLS connection established");res(tlsSocket)});tlsSocket.on("error",(err)=>{log.error("[SMTP] TLS socket error:",err);rej(err)});tlsSocket.on("data",handleData);tlsSocket.on("close",(hadError)=>{log.debug(`[SMTP] TLS socket closed (hadError: ${hadError})`);while(commandQueue.length>0){const pending=commandQueue.shift();pending?.reject(new Error("TLS connection closed unexpectedly"))}})});await sendCommand(`EHLO ${config.email.domain||"localhost"}`)}if(smtpConfig.username&&smtpConfig.password){await sendCommand("AUTH LOGIN");await sendCommand(Buffer.from(smtpConfig.username).toString("base64"),true);await sendCommand(Buffer.from(smtpConfig.password).toString("base64"),true)}assertEnvelopeAddress(from,"MAIL FROM");for(const recipient of to)assertEnvelopeAddress(recipient,"RCPT TO");await sendCommand(`MAIL FROM:<${from}>`);for(const recipient of to){await sendCommand(`RCPT TO:<${recipient}>`)}await sendCommand("DATA");const normalized=content.replace(/\r\n|\r|\n/g,`\r
4
+ `);const stuffed=normalized.replace(/(^|\r\n)\./g,"$1..");socket.write(`${stuffed}\r
5
5
  .\r
6
- `);await new Promise((res,rej)=>{commandQueue.push({cmd:"DATA_END",resolve:res,reject:rej})});completed=!0;const messageId=`${Date.now()}.${Math.random().toString(36).substring(2)}@${smtpConfig.host}`;try{socket.write(`QUIT\r
7
- `)}catch{}socket.end();resolve(messageId)}catch(error){if(completed){socket.end();return}socket.end();reject(error)}};if(smtpConfig.encryption==="ssl")socket=tls.connect({host:smtpConfig.host,port:smtpConfig.port,servername:smtpConfig.host},()=>{log.debug(`[SMTP] TLS connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()});else socket=net.connect({host:smtpConfig.host,port:smtpConfig.port},()=>{log.debug(`[SMTP] Connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()});socket.on("data",handleData);socket.setTimeout(SMTPDriver.SMTP_TIMEOUT);socket.on("timeout",()=>{socket.destroy(Error(`SMTP socket timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))});socket.on("error",(error)=>{if(completed)return;log.error(`[SMTP] Connection error to ${smtpConfig.host}:${smtpConfig.port}:`,error);reject(error)});socket.on("close",(hadError)=>{log.debug(`[SMTP] Connection closed (hadError: ${hadError})`);if(completed)return;while(commandQueue.length>0)commandQueue.shift()?.reject(Error("Connection closed unexpectedly"))})})}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((addr)=>{if(typeof addr==="string")return addr;return addr.address})}}export default SMTPDriver;
6
+ `);await new Promise((res,rej)=>{commandQueue.push({cmd:"DATA_END",resolve:res,reject:rej})});completed=true;const messageId=`${Date.now()}.${Math.random().toString(36).substring(2)}@${smtpConfig.host}`;try{socket.write(`QUIT\r
7
+ `)}catch{}socket.end();resolve(messageId)}catch(error){if(completed){socket.end();return}socket.end();reject(error)}};if(smtpConfig.encryption==="ssl"){socket=tls.connect({host:smtpConfig.host,port:smtpConfig.port,servername:smtpConfig.host},()=>{log.debug(`[SMTP] TLS connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()})}else{socket=net.connect({host:smtpConfig.host,port:smtpConfig.port},()=>{log.debug(`[SMTP] Connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()})}socket.on("data",handleData);socket.setTimeout(SMTPDriver.SMTP_TIMEOUT);socket.on("timeout",()=>{socket.destroy(new Error(`SMTP socket timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))});socket.on("error",(error)=>{if(completed)return;log.error(`[SMTP] Connection error to ${smtpConfig.host}:${smtpConfig.port}:`,error);reject(error)});socket.on("close",(hadError)=>{log.debug(`[SMTP] Connection closed (hadError: ${hadError})`);if(completed)return;while(commandQueue.length>0){const pending=commandQueue.shift();pending?.reject(new Error("Connection closed unexpectedly"))}})})}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((addr)=>{if(typeof addr==="string")return addr;return addr.address})}}export default SMTPDriver;
package/dist/email.js CHANGED
@@ -1 +1 @@
1
- import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{CaptureEmailDriver}from"./drivers/capture";import{LogEmailDriver}from"./drivers/log";import{MailgunDriver}from"./drivers/mailgun";import{MailtrapDriver}from"./drivers/mailtrap";import{SendGridDriver}from"./drivers/sendgrid";import{SESDriver}from"./drivers/ses";import{SMTPDriver}from"./drivers/smtp";import{findEmailByIdempotencyKey,recordEmailIdempotency}from"./idempotency";import{checkSuppressionFor}from"./suppression";export class EmailDeliveryError extends Error{result;constructor(result){super(result.message||`Email delivery failed through ${result.provider||"the configured provider"}.`);this.name="EmailDeliveryError";this.result=result}}export class Email{name;subject;to;from;template;handle;onError;onSuccess;constructor(options){this.name=options.name;this.subject=options.subject;this.to=options.to;this.from=options.from;this.template=options.template;this.handle=options.handle;this.onError=options.onError;this.onSuccess=options.onSuccess}async renderTemplate(){if(!this.template)return"";try{const{path:p}=await import("@stacksjs/path"),templatePath=p.resourcesPath(`views/emails/${this.template}.html`),file=Bun.file(templatePath);if(await file.exists())return await file.text()}catch{}if(this.template.includes("<"))return this.template;return`<p>${this.template}</p>`}async send(to){const target=to??this.to,recipients=Array.isArray(target)?target:target?[target]:[];if(recipients.length===0)throw Error("No recipient specified for email");try{await mail.sendOrFail({to:recipients,from:this.from||{name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"},subject:this.subject,html:await this.renderTemplate()});if(this.onSuccess)this.onSuccess();if(this.handle)return this.handle();return{message:"Email sent"}}catch(error){if(this.onError)return this.onError(error instanceof Error?error:Error(String(error)));throw error}}}export class Mail{drivers=new Map;defaultDriver;constructor(options={}){this.defaultDriver=options.defaultDriver||config.email.default||"ses";this.registerDefaultDrivers()}registerDefaultDrivers(){this.drivers.set("log",new LogEmailDriver);this.drivers.set("ses",new SESDriver);this.drivers.set("sendgrid",new SendGridDriver);this.drivers.set("mailgun",new MailgunDriver);this.drivers.set("mailtrap",new MailtrapDriver);this.drivers.set("smtp",new SMTPDriver);this.drivers.set("capture",new CaptureEmailDriver)}async send(message){const driver=this.drivers.get(this.defaultDriver);if(!driver){const available=[...this.drivers.keys()].sort().join(", ");throw Error(`Email driver '${this.defaultDriver}' is not registered. Available drivers: [${available}]. Check config.email.default or the MAIL_MAILER environment variable.`)}if(message.idempotencyKey){const cached=await findEmailByIdempotencyKey(message.idempotencyKey);if(cached)return cached}const suppressionType=await checkSuppressionForFirstRecipient(message);if(suppressionType)return{success:!1,message:`suppressed:${suppressionType}`,provider:"suppression"};const defaultFrom={name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"},result=await driver.send({...message,from:message.from||defaultFrom});if(message.idempotencyKey)await recordEmailIdempotency(message.idempotencyKey,message,result);return result}async sendOrFail(message){const result=await this.send(message);if(!result.success)throw new EmailDeliveryError(result);return result}use(driver){if(!this.drivers.has(driver))throw Error(`Email driver '${driver}' is not available`);return new Mail({defaultDriver:driver})}fake(){const previous=this.defaultDriver;this.defaultDriver="capture";return previous}restoreDriver(driver){this.defaultDriver=driver}async queue(message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").dispatch()},{context:"queue"})}async later(delaySeconds,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").delay(delaySeconds).dispatch()},{context:"later",delaySeconds})}async queueOn(queueName,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue(queueName).dispatch()},{context:"queueOn",queueName})}async dispatchOrFallback(message,dispatch,logExtra){try{await dispatch();return}catch(error){const reason=error instanceof Error?error.message:String(error);log.warn("[email] Queue dispatch failed; falling back to synchronous send. Background email pipeline is degraded - check the queue worker / broker.",{...logExtra,reason})}await this.send(message)}}async function checkSuppressionForFirstRecipient(message){const recipients=collectRecipientAddresses(message);if(recipients.length===0)return null;for(const addr of recipients){const matched=await checkSuppressionFor(addr,message.tag);if(matched)return matched}return null}function collectRecipientAddresses(message){const out=[],pushOne=(v)=>{if(typeof v==="string"){out.push(v);return}if(v&&typeof v==="object"&&"address"in v&&typeof v.address==="string")out.push(v.address)};for(const field of["to","cc","bcc"]){const v=message[field];if(!v)continue;if(Array.isArray(v))for(const item of v)pushOne(item);else pushOne(v)}return out}let _mail;function getMail(){if(!_mail){const driver=config?.email?.default||process.env.MAIL_MAILER||"ses";_mail=new Mail({defaultDriver:driver})}return _mail}export const mail=new Proxy({},{get(_t,prop){return getMail()[prop]},set(_t,prop,value){getMail()[prop]=value;return!0}});
1
+ import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{CaptureEmailDriver}from"./drivers/capture";import{LogEmailDriver}from"./drivers/log";import{MailgunDriver}from"./drivers/mailgun";import{MailtrapDriver}from"./drivers/mailtrap";import{SendGridDriver}from"./drivers/sendgrid";import{SESDriver}from"./drivers/ses";import{SMTPDriver}from"./drivers/smtp";import{findEmailByIdempotencyKey,recordEmailIdempotency}from"./idempotency";import{checkSuppressionFor}from"./suppression";export class EmailDeliveryError extends Error{result;constructor(result){super(result.message||`Email delivery failed through ${result.provider||"the configured provider"}.`);this.name="EmailDeliveryError";this.result=result}}export class Email{name;subject;to;from;template;handle;onError;onSuccess;constructor(options){this.name=options.name;this.subject=options.subject;this.to=options.to;this.from=options.from;this.template=options.template;this.handle=options.handle;this.onError=options.onError;this.onSuccess=options.onSuccess}async renderTemplate(){if(!this.template)return"";try{const{path:p}=await import("@stacksjs/path");const templatePath=p.resourcesPath(`views/emails/${this.template}.html`);const file=Bun.file(templatePath);if(await file.exists()){return await file.text()}}catch{}if(this.template.includes("<")){return this.template}return`<p>${this.template}</p>`}async send(to){const target=to??this.to;const recipients=Array.isArray(target)?target:target?[target]:[];if(recipients.length===0){throw new Error("No recipient specified for email")}try{await mail.sendOrFail({to:recipients,from:this.from||{name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"},subject:this.subject,html:await this.renderTemplate()});if(this.onSuccess){this.onSuccess()}if(this.handle){return this.handle()}return{message:"Email sent"}}catch(error){if(this.onError){return this.onError(error instanceof Error?error:new Error(String(error)))}throw error}}}export class Mail{drivers=new Map;defaultDriver;constructor(options={}){this.defaultDriver=options.defaultDriver||config.email.default||"ses";this.registerDefaultDrivers()}registerDefaultDrivers(){this.drivers.set("log",new LogEmailDriver);this.drivers.set("ses",new SESDriver);this.drivers.set("sendgrid",new SendGridDriver);this.drivers.set("mailgun",new MailgunDriver);this.drivers.set("mailtrap",new MailtrapDriver);this.drivers.set("smtp",new SMTPDriver);this.drivers.set("capture",new CaptureEmailDriver)}async send(message){const driver=this.drivers.get(this.defaultDriver);if(!driver){const available=[...this.drivers.keys()].sort().join(", ");throw new Error(`Email driver '${this.defaultDriver}' is not registered. Available drivers: [${available}]. Check config.email.default or the MAIL_MAILER environment variable.`)}if(message.idempotencyKey){const cached=await findEmailByIdempotencyKey(message.idempotencyKey);if(cached)return cached}const suppressionType=await checkSuppressionForFirstRecipient(message);if(suppressionType){return{success:false,message:`suppressed:${suppressionType}`,provider:"suppression"}}const defaultFrom={name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"};const result=await driver.send({...message,from:message.from||defaultFrom});if(message.idempotencyKey){await recordEmailIdempotency(message.idempotencyKey,message,result)}return result}async sendOrFail(message){const result=await this.send(message);if(!result.success)throw new EmailDeliveryError(result);return result}use(driver){if(!this.drivers.has(driver)){throw new Error(`Email driver '${driver}' is not available`)}const instance=new Mail({defaultDriver:driver});return instance}fake(){const previous=this.defaultDriver;this.defaultDriver="capture";return previous}restoreDriver(driver){this.defaultDriver=driver}async queue(message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").dispatch()},{context:"queue"})}async later(delaySeconds,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").delay(delaySeconds).dispatch()},{context:"later",delaySeconds})}async queueOn(queueName,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue(queueName).dispatch()},{context:"queueOn",queueName})}async dispatchOrFallback(message,dispatch,logExtra){try{await dispatch();return}catch(error){const reason=error instanceof Error?error.message:String(error);log.warn("[email] Queue dispatch failed; falling back to synchronous send. Background email pipeline is degraded - check the queue worker / broker.",{...logExtra,reason})}await this.send(message)}}async function checkSuppressionForFirstRecipient(message){const recipients=collectRecipientAddresses(message);if(recipients.length===0)return null;for(const addr of recipients){const matched=await checkSuppressionFor(addr,message.tag);if(matched)return matched}return null}function collectRecipientAddresses(message){const out=[];const pushOne=(v)=>{if(typeof v==="string"){out.push(v);return}if(v&&typeof v==="object"&&"address"in v&&typeof v.address==="string")out.push(v.address)};for(const field of["to","cc","bcc"]){const v=message[field];if(!v)continue;if(Array.isArray(v)){for(const item of v)pushOne(item)}else{pushOne(v)}}return out}let _mail;function getMail(){if(!_mail){const driver=config?.email?.default||process.env.MAIL_MAILER||"ses";_mail=new Mail({defaultDriver:driver})}return _mail}export const mail=new Proxy({},{get(_t,prop){return getMail()[prop]},set(_t,prop,value){getMail()[prop]=value;return true}});
@@ -1 +1 @@
1
- import{db}from"@stacksjs/database/runtime";let warnedAboutMissingEmailIdempotencyTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingEmailIdempotencyTable)return;warnedAboutMissingEmailIdempotencyTable=!0;console.warn("[email/idempotency] email_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.")}function isMissingTableError(err){const msg=(err?.message??"").toLowerCase();return msg.includes("no such table")||msg.includes("doesn't exist")||msg.includes("connection closed")||msg.includes("unable to open database")||msg.includes("econnrefused")||msg.includes("connection terminated")||msg.includes("no database")||msg.includes("database connection")}export async function findEmailByIdempotencyKey(key){try{const row=await db.selectFrom("email_idempotency").where("idempotency_key","=",key).selectAll().executeTakeFirst();if(!row)return null;const message=`Idempotent replay - original send recorded ${row.created_at}`,provider=String(row.provider??"cache");if(!row.success)return{success:!1,message,provider};return{success:!0,message,provider,messageId:row.message_id==null?void 0:String(row.message_id)}}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return null}throw err}}export async function recordEmailIdempotency(key,message,result){if(!result.success)return;const recipient=Array.isArray(message.to)?message.to.map((t)=>typeof t==="string"?t:t.address).join(", "):typeof message.to==="string"?message.to:message.to.address;try{await db.insertInto("email_idempotency").values({idempotency_key:key,message_id:result.messageId??null,recipient,subject:message.subject,provider:result.provider,success:1,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}const msg=err?.message??"";if(msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry"))return;throw err}}
1
+ import{db}from"@stacksjs/database/runtime";let warnedAboutMissingEmailIdempotencyTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingEmailIdempotencyTable)return;warnedAboutMissingEmailIdempotencyTable=true;console.warn("[email/idempotency] email_idempotency table missing - idempotency keys are accepted but NOT enforced. "+"Run migrations to enable dedup.")}function isMissingTableError(err){const msg=(err?.message??"").toLowerCase();return msg.includes("no such table")||msg.includes("doesn't exist")||msg.includes("connection closed")||msg.includes("unable to open database")||msg.includes("econnrefused")||msg.includes("connection terminated")||msg.includes("no database")||msg.includes("database connection")}export async function findEmailByIdempotencyKey(key){try{const row=await db.selectFrom("email_idempotency").where("idempotency_key","=",key).selectAll().executeTakeFirst();if(!row)return null;const message=`Idempotent replay - original send recorded ${row.created_at}`;const provider=String(row.provider??"cache");if(!row.success)return{success:false,message,provider};return{success:true,message,provider,messageId:row.message_id==null?undefined:String(row.message_id)}}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return null}throw err}}export async function recordEmailIdempotency(key,message,result){if(!result.success)return;const recipient=Array.isArray(message.to)?message.to.map((t)=>typeof t==="string"?t:t.address).join(", "):typeof message.to==="string"?message.to:message.to.address;try{await db.insertInto("email_idempotency").values({idempotency_key:key,message_id:result.messageId??null,recipient,subject:message.subject,provider:result.provider,success:1,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}const msg=err?.message??"";if(msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry"))return;throw err}}
@@ -1 +1 @@
1
- import{MimeParser}from"@stacksjs/mail/mime";import{inboundMailboxRecipient}from"./inbox-mailbox";import{inboxAttachmentContentType}from"./sdk/inbox-attachments";export{inboundMailboxRecipient}from"./inbox-mailbox";const MAX_RAW_EMAIL_BYTES=52428800,MAX_ATTACHMENTS=1000;function flattenAddresses(addresses){return(addresses||[]).flatMap((address)=>{if("group"in address&&Array.isArray(address.group))return address.group;return[address]})}function mailbox(address){if(!address)return;if("group"in address&&Array.isArray(address.group))return address.group[0];return address}export function inboundAttachmentName(filename,index){return String(filename||"").replace(/[\u0000-\u001F\u007F]/g,"").replace(/[\\/]/g,"_").trim().slice(0,220)||`attachment-${index+1}`}export function inboundAttachmentStorageName(filename,index){return`stacks-${String(index+1).padStart(4,"0")}--${encodeURIComponent(filename)}`}export function inboundMessageStorageId(messageId){const normalized=messageId.replace(/[\u0000-\u001F\u007F\\/]/g,"_").trim().slice(0,240);if(!normalized||normalized==="."||normalized==="..")throw TypeError("Inbound email object has no safe message identifier.");return normalized}export async function parseInboundEmail(rawEmail){if((typeof rawEmail==="string"?Buffer.byteLength(rawEmail):rawEmail.byteLength)>MAX_RAW_EMAIL_BYTES)throw RangeError(`Raw email exceeds the ${MAX_RAW_EMAIL_BYTES} byte parsing limit.`);const parsed=await MimeParser.parse(rawEmail,{attachmentEncoding:"arraybuffer",maxHeadersSize:524288,maxNestingDepth:64,maxRfc822NestingDepth:4});if(parsed.attachments.length>MAX_ATTACHMENTS)throw RangeError(`Email contains more than ${MAX_ATTACHMENTS} attachments.`);const sender=mailbox(parsed.from),recipients=flattenAddresses(parsed.to).map((recipient)=>recipient.address?.trim().toLowerCase()).filter((address)=>Boolean(address));if(parsed.deliveredTo)recipients.push(parsed.deliveredTo.trim().toLowerCase());const attachments=parsed.attachments.map((attachment,index)=>{const name=inboundAttachmentName(attachment.filename,index),content=typeof attachment.content==="string"?new TextEncoder().encode(attachment.content):new Uint8Array(attachment.content);return{name,storageName:inboundAttachmentStorageName(name,index),contentType:inboxAttachmentContentType(attachment.mimeType),content,...attachment.contentId?{contentId:attachment.contentId}:{},...attachment.disposition?{disposition:attachment.disposition}:{}}});return{from:sender?.address?.trim().toLowerCase()||"",fromName:sender?.name?.trim()||"",recipients:[...new Set(recipients)],subject:parsed.subject?.trim()||"No Subject",...parsed.date?{date:parsed.date}:{},html:parsed.html?.trim()||"",text:parsed.text?.trim()||"",attachments}}
1
+ import{MimeParser}from"@stacksjs/mail/mime";import{inboundMailboxRecipient}from"./inbox-mailbox";import{inboxAttachmentContentType}from"./sdk/inbox-attachments";export{inboundMailboxRecipient}from"./inbox-mailbox";const MAX_RAW_EMAIL_BYTES=50*1024*1024;const MAX_ATTACHMENTS=1000;function flattenAddresses(addresses){return(addresses||[]).flatMap((address)=>{if("group"in address&&Array.isArray(address.group))return address.group;return[address]})}function mailbox(address){if(!address)return;if("group"in address&&Array.isArray(address.group))return address.group[0];return address}export function inboundAttachmentName(filename,index){const normalized=String(filename||"").replace(/[\u0000-\u001F\u007F]/g,"").replace(/[\\/]/g,"_").trim().slice(0,220);return normalized||`attachment-${index+1}`}export function inboundAttachmentStorageName(filename,index){return`stacks-${String(index+1).padStart(4,"0")}--${encodeURIComponent(filename)}`}export function inboundMessageStorageId(messageId){const normalized=messageId.replace(/[\u0000-\u001F\u007F\\/]/g,"_").trim().slice(0,240);if(!normalized||normalized==="."||normalized==="..")throw new TypeError("Inbound email object has no safe message identifier.");return normalized}export async function parseInboundEmail(rawEmail){const byteLength=typeof rawEmail==="string"?Buffer.byteLength(rawEmail):rawEmail.byteLength;if(byteLength>MAX_RAW_EMAIL_BYTES)throw new RangeError(`Raw email exceeds the ${MAX_RAW_EMAIL_BYTES} byte parsing limit.`);const parsed=await MimeParser.parse(rawEmail,{attachmentEncoding:"arraybuffer",maxHeadersSize:512*1024,maxNestingDepth:64,maxRfc822NestingDepth:4});if(parsed.attachments.length>MAX_ATTACHMENTS)throw new RangeError(`Email contains more than ${MAX_ATTACHMENTS} attachments.`);const sender=mailbox(parsed.from);const recipients=flattenAddresses(parsed.to).map((recipient)=>recipient.address?.trim().toLowerCase()).filter((address)=>Boolean(address));if(parsed.deliveredTo)recipients.push(parsed.deliveredTo.trim().toLowerCase());const attachments=parsed.attachments.map((attachment,index)=>{const name=inboundAttachmentName(attachment.filename,index);const content=typeof attachment.content==="string"?new TextEncoder().encode(attachment.content):new Uint8Array(attachment.content);return{name,storageName:inboundAttachmentStorageName(name,index),contentType:inboxAttachmentContentType(attachment.mimeType),content,...attachment.contentId?{contentId:attachment.contentId}:{},...attachment.disposition?{disposition:attachment.disposition}:{}}});return{from:sender?.address?.trim().toLowerCase()||"",fromName:sender?.name?.trim()||"",recipients:[...new Set(recipients)],subject:parsed.subject?.trim()||"No Subject",...parsed.date?{date:parsed.date}:{},html:parsed.html?.trim()||"",text:parsed.text?.trim()||"",attachments}}
@@ -1 +1 @@
1
- export class InvalidInboxMailboxError extends TypeError{constructor(message="Mailbox must be a valid address on the configured email domain."){super(message);this.name="InvalidInboxMailboxError"}}export class InvalidInboxPathError extends TypeError{constructor(message="Inbox metadata contains an invalid message path."){super(message);this.name="InvalidInboxPathError"}}export function inboundMailboxRecipient(address,expectedDomain){const normalizedAddress=address.trim().toLowerCase(),separator=normalizedAddress.lastIndexOf("@");if(separator<=0)return null;const localPart=normalizedAddress.slice(0,separator),domain=normalizedAddress.slice(separator+1);if(domain!==expectedDomain.trim().toLowerCase())return null;if(!/^[a-z0-9.!#$%&'*+?^_`{|}~=-]+$/i.test(localPart)||localPart.includes(".."))return null;if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/i.test(domain))return null;return{address:normalizedAddress,domain,localPart}}export function inboxMailboxPath(mailbox,expectedDomain){const address=mailbox.includes("@")?mailbox:`${mailbox}@${expectedDomain}`,parsed=inboundMailboxRecipient(address,expectedDomain);if(!parsed)throw new InvalidInboxMailboxError;const prefix=`mailboxes/${parsed.domain}/${parsed.localPart}`;return{...parsed,prefix,indexKey:`${prefix}/inbox.json`}}export function inboxMessagePath(path,mailbox){const normalized=path.trim(),prefix=`${mailbox.prefix}/`;if(!normalized.startsWith(prefix))throw new InvalidInboxPathError;const segments=normalized.slice(prefix.length).split("/");if(segments.length===0||segments.some((segment)=>!segment||segment==="."||segment===".."||segment.includes("\\")||/[\u0000-\u001F\u007F]/.test(segment)))throw new InvalidInboxPathError;return normalized}
1
+ export class InvalidInboxMailboxError extends TypeError{constructor(message="Mailbox must be a valid address on the configured email domain."){super(message);this.name="InvalidInboxMailboxError"}}export class InvalidInboxPathError extends TypeError{constructor(message="Inbox metadata contains an invalid message path."){super(message);this.name="InvalidInboxPathError"}}export function inboundMailboxRecipient(address,expectedDomain){const normalizedAddress=address.trim().toLowerCase();const separator=normalizedAddress.lastIndexOf("@");if(separator<=0)return null;const localPart=normalizedAddress.slice(0,separator);const domain=normalizedAddress.slice(separator+1);if(domain!==expectedDomain.trim().toLowerCase())return null;if(!/^[a-z0-9.!#$%&'*+?^_`{|}~=-]+$/i.test(localPart)||localPart.includes(".."))return null;if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/i.test(domain))return null;return{address:normalizedAddress,domain,localPart}}export function inboxMailboxPath(mailbox,expectedDomain){const address=mailbox.includes("@")?mailbox:`${mailbox}@${expectedDomain}`;const parsed=inboundMailboxRecipient(address,expectedDomain);if(!parsed)throw new InvalidInboxMailboxError;const prefix=`mailboxes/${parsed.domain}/${parsed.localPart}`;return{...parsed,prefix,indexKey:`${prefix}/inbox.json`}}export function inboxMessagePath(path,mailbox){const normalized=path.trim();const prefix=`${mailbox.prefix}/`;if(!normalized.startsWith(prefix))throw new InvalidInboxPathError;const segments=normalized.slice(prefix.length).split("/");if(segments.length===0||segments.some((segment)=>!segment||segment==="."||segment===".."||segment.includes("\\")||/[\u0000-\u001F\u007F]/.test(segment))){throw new InvalidInboxPathError}return normalized}
package/dist/mailable.js CHANGED
@@ -1 +1 @@
1
- import{config}from"@stacksjs/config";import{mail}from"./email";import{template as renderTemplate}from"./template";export class Mailable{_to=[];_cc=[];_bcc=[];_replyTo;_from;_subject;_text;_html;_template;_attachments=[];to(address){this._to=normalizeAddresses(address);return this}cc(address){this._cc=normalizeAddresses(address);return this}bcc(address){this._bcc=normalizeAddresses(address);return this}replyTo(address){this._replyTo=typeof address==="string"?{address}:address;return this}from(addr){this._from=addr;return this}subject(s){this._subject=s;return this}text(body){this._text=body;return this}html(body){this._html=body;return this}template(name,...rest){const props=rest[0]??{};this._template={name,props};return this}inspect(){return{to:this._to,cc:this._cc,bcc:this._bcc,from:this._from,replyTo:this._replyTo,subject:this._subject,text:this._text,html:this._html,template:this._template,attachments:this._attachments}}attach(path,name){this._attachments.push({filename:name||basename(path),content:`__file__:${path}`,encoding:"binary"});return this}attachData(buffer,name,mime){this._attachments.push({filename:name,content:buffer,contentType:mime,encoding:typeof buffer==="string"?"utf8":"binary"});return this}async send(options={}){await Promise.resolve(this.build());if(this._to.length===0)throw Error("[Mailable] no recipients - call this.to(...) inside build()");if(!this._subject)throw Error("[Mailable] no subject - call this.subject(...) inside build()");let html=this._html,text=this._text;if(this._template){const rendered=await renderTemplate(this._template.name,{variables:this._template.props,subject:this._subject});if(!html)html=rendered.html;if(!text)text=rendered.text}const message={to:this._to,subject:this._subject,from:this._from||resolveDefaultFrom(),...this._cc.length?{cc:this._cc}:{},...this._bcc.length?{bcc:this._bcc}:{},...html?{html}:{},...text?{text}:{},...this._attachments.length?{attachments:await materializeAttachments(this._attachments)}:{}};if(this._replyTo)message.replyTo=this._replyTo;return(options.driver?mail.use(options.driver):mail).send(message)}}function normalizeAddresses(input){const arr=Array.isArray(input)?input:[input];if(arr.some((a)=>typeof a==="object"&&a!==null))return arr.map((a)=>typeof a==="string"?{address:a}:a);return arr}function resolveDefaultFrom(){return{name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"}}function basename(p){const idx=Math.max(p.lastIndexOf("/"),p.lastIndexOf("\\"));return idx===-1?p:p.slice(idx+1)}async function materializeAttachments(atts){return Promise.all(atts.map(async(att)=>{if(typeof att.content==="string"&&att.content.startsWith("__file__:")){const filePath=att.content.slice(9),file=Bun.file(filePath),buf=new Uint8Array(await file.arrayBuffer());return{...att,content:buf,contentType:att.contentType||file.type||void 0,encoding:"binary"}}return att}))}
1
+ import{config}from"@stacksjs/config";import{mail}from"./email";import{template as renderTemplate}from"./template";export class Mailable{_to=[];_cc=[];_bcc=[];_replyTo;_from;_subject;_text;_html;_template;_attachments=[];to(address){this._to=normalizeAddresses(address);return this}cc(address){this._cc=normalizeAddresses(address);return this}bcc(address){this._bcc=normalizeAddresses(address);return this}replyTo(address){this._replyTo=typeof address==="string"?{address}:address;return this}from(addr){this._from=addr;return this}subject(s){this._subject=s;return this}text(body){this._text=body;return this}html(body){this._html=body;return this}template(name,...rest){const props=rest[0]??{};this._template={name,props};return this}inspect(){return{to:this._to,cc:this._cc,bcc:this._bcc,from:this._from,replyTo:this._replyTo,subject:this._subject,text:this._text,html:this._html,template:this._template,attachments:this._attachments}}attach(path,name){this._attachments.push({filename:name||basename(path),content:`__file__:${path}`,encoding:"binary"});return this}attachData(buffer,name,mime){this._attachments.push({filename:name,content:buffer,contentType:mime,encoding:typeof buffer==="string"?"utf8":"binary"});return this}async send(options={}){await Promise.resolve(this.build());if(this._to.length===0)throw new Error("[Mailable] no recipients - call this.to(...) inside build()");if(!this._subject)throw new Error("[Mailable] no subject - call this.subject(...) inside build()");let html=this._html;let text=this._text;if(this._template){const rendered=await renderTemplate(this._template.name,{variables:this._template.props,subject:this._subject});if(!html)html=rendered.html;if(!text)text=rendered.text}const message={to:this._to,subject:this._subject,from:this._from||resolveDefaultFrom(),...this._cc.length?{cc:this._cc}:{},...this._bcc.length?{bcc:this._bcc}:{},...html?{html}:{},...text?{text}:{},...this._attachments.length?{attachments:await materializeAttachments(this._attachments)}:{}};if(this._replyTo){message.replyTo=this._replyTo}const transport=options.driver?mail.use(options.driver):mail;return transport.send(message)}}function normalizeAddresses(input){const arr=Array.isArray(input)?input:[input];const hasObject=arr.some((a)=>typeof a==="object"&&a!==null);if(hasObject){return arr.map((a)=>typeof a==="string"?{address:a}:a)}return arr}function resolveDefaultFrom(){return{name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"}}function basename(p){const idx=Math.max(p.lastIndexOf("/"),p.lastIndexOf("\\"));return idx===-1?p:p.slice(idx+1)}async function materializeAttachments(atts){return Promise.all(atts.map(async(att)=>{if(typeof att.content==="string"&&att.content.startsWith("__file__:")){const filePath=att.content.slice("__file__:".length);const file=Bun.file(filePath);const buf=new Uint8Array(await file.arrayBuffer());return{...att,content:buf,contentType:att.contentType||file.type||undefined,encoding:"binary"}}return att}))}
@@ -1,9 +1,9 @@
1
1
  function splitHeaders(value){const normalized=value.replace(/\r\n/g,`
2
- `),separator=normalized.indexOf(`
2
+ `);const separator=normalized.indexOf(`
3
3
 
4
4
  `);if(separator<0)return{headers:{},body:normalized};const headerLines=normalized.slice(0,separator).replace(/\n[ \t]+/g," ").split(`
5
- `),headers={};for(const line of headerLines){const match=line.match(/^([^:]+):\s*(.*)$/);if(match)headers[match[1].toLowerCase()]=match[2]||""}return{headers,body:normalized.slice(separator+2)}}function decodeQuotedPrintable(value){const input=value.replace(/\r\n/g,`
6
- `).replace(/=\n/g,""),bytes=[],encoder=new TextEncoder;for(let index=0;index<input.length;index++){const encoded=input.slice(index,index+3);if(/^=[0-9a-f]{2}$/i.test(encoded)){bytes.push(Number.parseInt(encoded.slice(1),16));index+=2}else bytes.push(...encoder.encode(input[index]))}return new TextDecoder().decode(Uint8Array.from(bytes))}function normalizedMimeBody(value,requestedType){const normalized=value.replace(/\r\n/g,`
7
- `).trim(),fragmentBoundary=normalized.match(/^--([^\n]+)\n/)?.[1]?.replace(/--$/,""),hasMimeHeaders=/^(?:content-type|content-transfer-encoding|mime-version):/i.test(normalized),source=fragmentBoundary?`Content-Type: multipart/mixed; boundary="${fragmentBoundary.replace(/["\\]/g,"")}"
5
+ `);const headers={};for(const line of headerLines){const match=line.match(/^([^:]+):\s*(.*)$/);if(match)headers[match[1].toLowerCase()]=match[2]||""}return{headers,body:normalized.slice(separator+2)}}function decodeQuotedPrintable(value){const input=value.replace(/\r\n/g,`
6
+ `).replace(/=\n/g,"");const bytes=[];const encoder=new TextEncoder;for(let index=0;index<input.length;index++){const encoded=input.slice(index,index+3);if(/^=[0-9a-f]{2}$/i.test(encoded)){bytes.push(Number.parseInt(encoded.slice(1),16));index+=2}else{bytes.push(...encoder.encode(input[index]))}}return new TextDecoder().decode(Uint8Array.from(bytes))}function normalizedMimeBody(value,requestedType){const normalized=value.replace(/\r\n/g,`
7
+ `).trim();const fragmentBoundary=normalized.match(/^--([^\n]+)\n/)?.[1]?.replace(/--$/,"");const hasMimeHeaders=/^(?:content-type|content-transfer-encoding|mime-version):/i.test(normalized);const source=fragmentBoundary?`Content-Type: multipart/mixed; boundary="${fragmentBoundary.replace(/["\\]/g,"")}"
8
8
 
9
- ${normalized}`:normalized;if(fragmentBoundary||hasMimeHeaders){const selected=mimeParts(source).find((part)=>part.contentType.startsWith(requestedType));if(selected)return decodeBody(selected.body,selected.encoding).trim()}return decodeQuotedPrintable(stripLegacyMimePreamble(normalized)).trim()}function decodeBody(body,encoding){if(encoding==="base64")try{return Buffer.from(body.replace(/\s+/g,""),"base64").toString("utf8")}catch{return body}if(encoding==="quoted-printable")return decodeQuotedPrintable(body);return body}function mimeParts(value){const{headers,body}=splitHeaders(value),contentType=(headers["content-type"]||"text/plain").toLowerCase(),boundary=headers["content-type"]?.match(/boundary\s*=\s*(?:"([^"]+)"|([^;\s]+))/i)?.slice(1).find(Boolean);if(contentType.startsWith("multipart/")&&boundary)return body.split(`--${boundary}`).slice(1).filter((part)=>!part.trimStart().startsWith("--")).flatMap(mimeParts);return[{contentType,encoding:(headers["content-transfer-encoding"]||"").toLowerCase(),body}]}function stripLegacyMimePreamble(value){let result=value.trim();result=result.replace(/^[-=_]{2,}[^\s]*\s+/,"");for(let pass=0;pass<6;pass++){const next=result.replace(/^content-transfer-encoding:\s*[^\s]+\s*/i,"").replace(/^mime-version:\s*[^\s]+\s*/i,"").replace(/^content-description:\s*[^\s]+\s*/i,"").replace(/^content-type:\s*[^\s;]+(?:;\s*(?:charset|boundary|name)\s*=\s*(?:"[^"]*"|[^\s]+))*\s*/i,"");if(next===result)break;result=next}return result.replace(/^[-=_]{4,}[^\s]*\s*/,"")}function plainText(value){return decodeQuotedPrintable(stripLegacyMimePreamble(value)).replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s+/g," ").trim()}export function extractEmailPreview(rawEmail,maxLength=200){const parts=mimeParts(rawEmail),selected=parts.find((part)=>part.contentType.startsWith("text/plain"))||parts.find((part)=>part.contentType.startsWith("text/html"));return plainText(selected?decodeBody(selected.body,selected.encoding):rawEmail).slice(0,maxLength)}export function normalizeEmailPreview(preview,maxLength=200){return plainText(preview).slice(0,maxLength)}export function normalizeEmailTextBody(body){return normalizedMimeBody(body,"text/plain")}export function normalizeEmailHtmlBody(body){return normalizedMimeBody(body,"text/html")}
9
+ ${normalized}`:normalized;if(fragmentBoundary||hasMimeHeaders){const parts=mimeParts(source);const selected=parts.find((part)=>part.contentType.startsWith(requestedType));if(selected)return decodeBody(selected.body,selected.encoding).trim()}return decodeQuotedPrintable(stripLegacyMimePreamble(normalized)).trim()}function decodeBody(body,encoding){if(encoding==="base64"){try{return Buffer.from(body.replace(/\s+/g,""),"base64").toString("utf8")}catch{return body}}if(encoding==="quoted-printable")return decodeQuotedPrintable(body);return body}function mimeParts(value){const{headers,body}=splitHeaders(value);const contentType=(headers["content-type"]||"text/plain").toLowerCase();const boundary=headers["content-type"]?.match(/boundary\s*=\s*(?:"([^"]+)"|([^;\s]+))/i)?.slice(1).find(Boolean);if(contentType.startsWith("multipart/")&&boundary){return body.split(`--${boundary}`).slice(1).filter((part)=>!part.trimStart().startsWith("--")).flatMap(mimeParts)}return[{contentType,encoding:(headers["content-transfer-encoding"]||"").toLowerCase(),body}]}function stripLegacyMimePreamble(value){let result=value.trim();result=result.replace(/^[-=_]{2,}[^\s]*\s+/,"");for(let pass=0;pass<6;pass++){const next=result.replace(/^content-transfer-encoding:\s*[^\s]+\s*/i,"").replace(/^mime-version:\s*[^\s]+\s*/i,"").replace(/^content-description:\s*[^\s]+\s*/i,"").replace(/^content-type:\s*[^\s;]+(?:;\s*(?:charset|boundary|name)\s*=\s*(?:"[^"]*"|[^\s]+))*\s*/i,"");if(next===result)break;result=next}return result.replace(/^[-=_]{4,}[^\s]*\s*/,"")}function plainText(value){return decodeQuotedPrintable(stripLegacyMimePreamble(value)).replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s+/g," ").trim()}export function extractEmailPreview(rawEmail,maxLength=200){const parts=mimeParts(rawEmail);const selected=parts.find((part)=>part.contentType.startsWith("text/plain"))||parts.find((part)=>part.contentType.startsWith("text/html"));return plainText(selected?decodeBody(selected.body,selected.encoding):rawEmail).slice(0,maxLength)}export function normalizeEmailPreview(preview,maxLength=200){return plainText(preview).slice(0,maxLength)}export function normalizeEmailTextBody(body){return normalizedMimeBody(body,"text/plain")}export function normalizeEmailHtmlBody(body){return normalizedMimeBody(body,"text/html")}
package/dist/mime.js CHANGED
@@ -1,3 +1,3 @@
1
- import{Buffer}from"node:buffer";import{assertHeaderValue,isHeaderName}from"./validation";export function encodeRfc2047IfNeeded(value){assertHeaderValue(value,"encoded header");if(/^[\x00-\x7F]*$/.test(value))return value;return`=?UTF-8?B?${Buffer.from(value,"utf-8").toString("base64")}?=`}export function buildMimeMessage(options){const{from,to,cc,replyTo,subject,text,html,attachments,messageIdDomain,customHeaders}=options;for(const[role,value]of Object.entries({from,to,cc,replyTo,subject,messageIdDomain}))if(value!==void 0)assertHeaderValue(value,role);for(const[name,value]of Object.entries(customHeaders??{})){if(!isHeaderName(name))throw Error("Email custom header name contains forbidden characters");assertHeaderValue(value,name)}const lines=[],hasAttachments=!!(attachments&&attachments.length>0),boundary=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`;lines.push(`From: ${from}`);lines.push(`To: ${to}`);if(cc)lines.push(`Cc: ${cc}`);if(replyTo)lines.push(`Reply-To: ${replyTo}`);lines.push(`Subject: ${encodeRfc2047IfNeeded(subject)}`);lines.push("MIME-Version: 1.0");lines.push(`Date: ${new Date().toUTCString()}`);lines.push(`Message-ID: <${Date.now()}.${Math.random().toString(36).substring(2)}@${messageIdDomain||"localhost"}>`);if(customHeaders)for(const[k,v]of Object.entries(customHeaders))lines.push(`${k}: ${v}`);if(hasAttachments){const mixedBoundary=boundary,altBoundary=`${boundary}_alt`;lines.push(`Content-Type: multipart/mixed; boundary="${mixedBoundary}"`);lines.push("");lines.push(`--${mixedBoundary}`);pushBodyParts(lines,{text,html,altBoundary});for(const attachment of attachments){lines.push(`--${mixedBoundary}`);pushAttachmentPart(lines,attachment)}lines.push(`--${mixedBoundary}--`)}else pushBodyParts(lines,{text,html,altBoundary:boundary});return lines.join(`\r
2
- `)}function pushBodyParts(lines,options){const{text,html,altBoundary}=options;if(html&&text){lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html);lines.push("");lines.push(`--${altBoundary}--`)}else if(html){lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html)}else if(text){lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text)}}function pushAttachmentPart(lines,attachment){assertHeaderValue(attachment.filename,"attachment filename");if(attachment.contentType)assertHeaderValue(attachment.contentType,"attachment content type");const contentType=attachment.contentType||"application/octet-stream",safeFilename=encodeRfc2047IfNeeded(attachment.filename.replace(/\\/g,"\\\\").replace(/"/g,"\\\""));lines.push(`Content-Type: ${contentType}; name="${safeFilename}"`);lines.push(`Content-Disposition: attachment; filename="${safeFilename}"`);lines.push("Content-Transfer-Encoding: base64");lines.push("");const raw=typeof attachment.content==="string"?Buffer.from(attachment.content,"utf-8").toString("base64"):Buffer.from(attachment.content).toString("base64"),wrapped=raw.match(/.{1,76}/g)?.join(`\r
1
+ import{Buffer}from"node:buffer";import{assertHeaderValue,isHeaderName}from"./validation";export function encodeRfc2047IfNeeded(value){assertHeaderValue(value,"encoded header");if(/^[\x00-\x7F]*$/.test(value))return value;return`=?UTF-8?B?${Buffer.from(value,"utf-8").toString("base64")}?=`}export function buildMimeMessage(options){const{from,to,cc,replyTo,subject,text,html,attachments,messageIdDomain,customHeaders}=options;for(const[role,value]of Object.entries({from,to,cc,replyTo,subject,messageIdDomain})){if(value!==undefined)assertHeaderValue(value,role)}for(const[name,value]of Object.entries(customHeaders??{})){if(!isHeaderName(name))throw new Error("Email custom header name contains forbidden characters");assertHeaderValue(value,name)}const lines=[];const hasAttachments=!!(attachments&&attachments.length>0);const boundary=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`;lines.push(`From: ${from}`);lines.push(`To: ${to}`);if(cc)lines.push(`Cc: ${cc}`);if(replyTo)lines.push(`Reply-To: ${replyTo}`);lines.push(`Subject: ${encodeRfc2047IfNeeded(subject)}`);lines.push("MIME-Version: 1.0");lines.push(`Date: ${new Date().toUTCString()}`);lines.push(`Message-ID: <${Date.now()}.${Math.random().toString(36).substring(2)}@${messageIdDomain||"localhost"}>`);if(customHeaders){for(const[k,v]of Object.entries(customHeaders)){lines.push(`${k}: ${v}`)}}if(hasAttachments){const mixedBoundary=boundary;const altBoundary=`${boundary}_alt`;lines.push(`Content-Type: multipart/mixed; boundary="${mixedBoundary}"`);lines.push("");lines.push(`--${mixedBoundary}`);pushBodyParts(lines,{text,html,altBoundary});for(const attachment of attachments){lines.push(`--${mixedBoundary}`);pushAttachmentPart(lines,attachment)}lines.push(`--${mixedBoundary}--`)}else{pushBodyParts(lines,{text,html,altBoundary:boundary})}return lines.join(`\r
2
+ `)}function pushBodyParts(lines,options){const{text,html,altBoundary}=options;if(html&&text){lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html);lines.push("");lines.push(`--${altBoundary}--`)}else if(html){lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html)}else if(text){lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text)}}function pushAttachmentPart(lines,attachment){assertHeaderValue(attachment.filename,"attachment filename");if(attachment.contentType)assertHeaderValue(attachment.contentType,"attachment content type");const contentType=attachment.contentType||"application/octet-stream";const safeFilename=encodeRfc2047IfNeeded(attachment.filename.replace(/\\/g,"\\\\").replace(/"/g,"\\\""));lines.push(`Content-Type: ${contentType}; name="${safeFilename}"`);lines.push(`Content-Disposition: attachment; filename="${safeFilename}"`);lines.push("Content-Transfer-Encoding: base64");lines.push("");const raw=typeof attachment.content==="string"?Buffer.from(attachment.content,"utf-8").toString("base64"):Buffer.from(attachment.content).toString("base64");const wrapped=raw.match(/.{1,76}/g)?.join(`\r
3
3
  `)??raw;lines.push(wrapped);lines.push("")}
@@ -3,7 +3,7 @@ const ROOT="/_stacks/mail/preview";function escape(s){return String(s??"").repla
3
3
  <head>
4
4
  <meta charset="UTF-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>${escape(title)} \u2014 Stacks Mail Preview</title>
6
+ <title>${escape(title)} — Stacks Mail Preview</title>
7
7
  <style>
8
8
  :root { color-scheme: light dark; }
9
9
  * { box-sizing: border-box; }
@@ -51,15 +51,15 @@ const ROOT="/_stacks/mail/preview";function escape(s){return String(s??"").repla
51
51
  </header>
52
52
  <main>${body}</main>
53
53
  </body>
54
- </html>`}export function renderIndexHtml(mailables){if(mailables.length===0)return shell("Index",`
54
+ </html>`}export function renderIndexHtml(mailables){if(mailables.length===0){return shell("Index",`
55
55
  <div class="empty panel">
56
56
  <p>No Mailables found in <code>app/Mail/</code>.</p>
57
57
  <p class="muted">Run <code>./buddy make:mail Welcome</code> to scaffold one.</p>
58
58
  </div>
59
- `);const items=mailables.map((m)=>`
59
+ `)}const items=mailables.map((m)=>`
60
60
  <li>
61
61
  <a href="${ROOT}/${escape(m.slug)}">${escape(m.name)}</a>
62
- <div class="muted">app/Mail/${escape(m.name)}.ts \xB7 template: ${escape(m.slug)}.stx</div>
62
+ <div class="muted">app/Mail/${escape(m.name)}.ts · template: ${escape(m.slug)}.stx</div>
63
63
  </li>
64
64
  `).join("");return shell("Index",`
65
65
  <div class="panel">
@@ -67,7 +67,7 @@ const ROOT="/_stacks/mail/preview";function escape(s){return String(s??"").repla
67
67
  <code>resources/emails/_previews/&lt;slug&gt;.ts</code> for richer previews.</p>
68
68
  <ul class="list">${items}</ul>
69
69
  </div>
70
- `)}export function renderPreviewHtml(mailable,preview,view="desktop"){const{inspection,text,sampleProps,error}=preview,baseUrl=`${ROOT}/${mailable.slug}`,rawUrl=`${baseUrl}/raw`,errorBlock=error?`<div class="panel"><div class="error"><strong>${escape(mailable.name)} failed to render:</strong> ${escape(error)}</div></div>`:"",iframeBlock=error?"":view==="text"?`<div class="panel"><pre>${escape(text||"(no plain-text body)")}</pre></div>`:`<div class="panel"><iframe src="${rawUrl}" class="${view==="mobile"?"mobile":""}" title="${escape(mailable.name)} body" sandbox="allow-same-origin"></iframe></div>`,sampleHint=sampleProps?`<dd><code>resources/emails/_previews/${escape(mailable.slug)}.ts</code></dd>`:`<dd class="muted">No sample file - edit <code>resources/emails/_previews/${escape(mailable.slug)}.ts</code> to customize.</dd>`;return shell(mailable.name,`
70
+ `)}export function renderPreviewHtml(mailable,preview,view="desktop"){const{inspection,text,sampleProps,error}=preview;const baseUrl=`${ROOT}/${mailable.slug}`;const rawUrl=`${baseUrl}/raw`;const errorBlock=error?`<div class="panel"><div class="error"><strong>${escape(mailable.name)} failed to render:</strong> ${escape(error)}</div></div>`:"";const iframeBlock=error?"":view==="text"?`<div class="panel"><pre>${escape(text||"(no plain-text body)")}</pre></div>`:`<div class="panel"><iframe src="${rawUrl}" class="${view==="mobile"?"mobile":""}" title="${escape(mailable.name)} body" sandbox="allow-same-origin"></iframe></div>`;const sampleHint=sampleProps?`<dd><code>resources/emails/_previews/${escape(mailable.slug)}.ts</code></dd>`:`<dd class="muted">No sample file - edit <code>resources/emails/_previews/${escape(mailable.slug)}.ts</code> to customize.</dd>`;return shell(mailable.name,`
71
71
  ${errorBlock}
72
72
 
73
73
  <div class="grid">
package/dist/preview.js CHANGED
@@ -1 +1 @@
1
- import{readdirSync}from"node:fs";import{join}from"node:path";import{existsSync}from"@stacksjs/storage";import{userEmailsPath,userMailPath}from"@stacksjs/path";import{kebabCase}from"@stacksjs/strings";import{Mailable}from"./mailable";import{template}from"./template";export function discoverMailables(){const dir=userMailPath();if(!existsSync(dir))return[];const entries=readdirSync(dir,{withFileTypes:!0}),out=[];for(const entry of entries){if(!entry.isFile())continue;if(!entry.name.endsWith(".ts"))continue;if(entry.name.endsWith(".d.ts"))continue;if(entry.name.endsWith(".test.ts"))continue;if(entry.name.endsWith(".spec.ts"))continue;const base=entry.name.replace(/\.ts$/,"");out.push({name:base,path:join(dir,entry.name),slug:kebabCase(base)})}out.sort((a,b)=>a.name.localeCompare(b.name));return out}export async function loadSampleProps(slug){const samplePath=userEmailsPath(`_previews/${slug}.ts`);if(!existsSync(samplePath))return null;try{const mod=await import(samplePath),props=mod.default??mod.props??null;return props&&typeof props==="object"?props:null}catch(err){return{__preview_error__:`Failed to load sample props: ${err instanceof Error?err.message:String(err)}`}}}export async function renderMailablePreview(mailable){const empty={inspection:{to:[],cc:[],bcc:[],attachments:[]},html:"",text:"",sampleProps:null};try{const mod=await import(mailable.path),Cls=pickMailableConstructor(mod);if(!Cls)return{...empty,error:`No subclass of \`Mailable\` exported from ${mailable.path}.`};const sampleProps=await loadSampleProps(mailable.slug),instance=new Cls(sampleProps??{});if(!(instance instanceof Mailable))return{...empty,sampleProps,error:"Constructor did not produce a Mailable instance."};await instance.build();const inspection=instance.inspect();if(!inspection.template)return{inspection,html:inspection.html??"",text:inspection.text??"",sampleProps};const rendered=await template(inspection.template.name,{variables:inspection.template.props,subject:inspection.subject});return{inspection,html:rendered.html,text:rendered.text,sampleProps}}catch(err){return{...empty,error:err instanceof Error?`${err.name}: ${err.message}`:String(err)}}}function pickMailableConstructor(mod){const candidates=[];if(mod.default)candidates.push(mod.default);for(const key of Object.keys(mod))if(key!=="default")candidates.push(mod[key]);for(const candidate of candidates){if(typeof candidate!=="function")continue;if(!(candidate.prototype instanceof Mailable))continue;return candidate}return null}
1
+ import{readdirSync}from"node:fs";import{join}from"node:path";import{existsSync}from"@stacksjs/storage";import{userEmailsPath,userMailPath}from"@stacksjs/path";import{kebabCase}from"@stacksjs/strings";import{Mailable}from"./mailable";import{template}from"./template";export function discoverMailables(){const dir=userMailPath();if(!existsSync(dir))return[];const entries=readdirSync(dir,{withFileTypes:true});const out=[];for(const entry of entries){if(!entry.isFile())continue;if(!entry.name.endsWith(".ts"))continue;if(entry.name.endsWith(".d.ts"))continue;if(entry.name.endsWith(".test.ts"))continue;if(entry.name.endsWith(".spec.ts"))continue;const base=entry.name.replace(/\.ts$/,"");out.push({name:base,path:join(dir,entry.name),slug:kebabCase(base)})}out.sort((a,b)=>a.name.localeCompare(b.name));return out}export async function loadSampleProps(slug){const samplePath=userEmailsPath(`_previews/${slug}.ts`);if(!existsSync(samplePath))return null;try{const mod=await import(samplePath);const props=mod.default??mod.props??null;return props&&typeof props==="object"?props:null}catch(err){const msg=err instanceof Error?err.message:String(err);return{__preview_error__:`Failed to load sample props: ${msg}`}}}export async function renderMailablePreview(mailable){const empty={inspection:{to:[],cc:[],bcc:[],attachments:[]},html:"",text:"",sampleProps:null};try{const mod=await import(mailable.path);const Cls=pickMailableConstructor(mod);if(!Cls){return{...empty,error:`No subclass of \`Mailable\` exported from ${mailable.path}.`}}const sampleProps=await loadSampleProps(mailable.slug);const instance=new Cls(sampleProps??{});if(!(instance instanceof Mailable)){return{...empty,sampleProps,error:"Constructor did not produce a Mailable instance."}}await instance.build();const inspection=instance.inspect();if(!inspection.template){return{inspection,html:inspection.html??"",text:inspection.text??"",sampleProps}}const rendered=await template(inspection.template.name,{variables:inspection.template.props,subject:inspection.subject});return{inspection,html:rendered.html,text:rendered.text,sampleProps}}catch(err){return{...empty,error:err instanceof Error?`${err.name}: ${err.message}`:String(err)}}}function pickMailableConstructor(mod){const candidates=[];if(mod.default)candidates.push(mod.default);for(const key of Object.keys(mod)){if(key!=="default")candidates.push(mod[key])}for(const candidate of candidates){if(typeof candidate!=="function")continue;if(!(candidate.prototype instanceof Mailable))continue;return candidate}return null}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";export function inboxAttachmentPrefix(basePath){return`${basePath.replace(/\/+$/,"")}/attachments/`}export function inboxAttachmentId(key){return createHash("sha256").update(key).digest("base64url").slice(0,22)}export function inboxAttachmentName(key,prefix){const storedName=(key.startsWith(prefix)?key.slice(prefix.length):key.split("/").pop()||"").replace(/^stacks-\d{4}--/,"");let decodedName=storedName;try{decodedName=decodeURIComponent(storedName)}catch{}return decodedName.replace(/[\u0000-\u001F\u007F]/g,"").replace(/[\\/]/g,"_").trim().slice(0,240)||"attachment"}export function mapInboxAttachmentObjects(basePath,objects){const prefix=inboxAttachmentPrefix(basePath);return objects.filter((object)=>object.Key.startsWith(prefix)&&object.Key.length>prefix.length&&!object.Key.endsWith("/")).map((object)=>({id:inboxAttachmentId(object.Key),key:object.Key,name:inboxAttachmentName(object.Key,prefix),size:Math.max(0,Number(object.Size)||0),...object.LastModified?{lastModified:object.LastModified}:{}})).sort((left,right)=>left.name.localeCompare(right.name))}export function inboxAttachmentContentDisposition(filename){const asciiName=filename.normalize("NFKD").replace(/[^\x20-\x7E]/g,"").replace(/["\\]/g,"_").trim()||"attachment",utf8Name=encodeURIComponent(filename).replace(/['()]/g,(character)=>`%${character.charCodeAt(0).toString(16).toUpperCase()}`);return`attachment; filename="${asciiName}"; filename*=UTF-8''${utf8Name}`}export function inboxAttachmentContentType(contentType){const mediaType=contentType?.split(";",1)[0]?.trim().toLowerCase()||"";return/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(mediaType)?mediaType:"application/octet-stream"}
1
+ import{createHash}from"node:crypto";export function inboxAttachmentPrefix(basePath){return`${basePath.replace(/\/+$/,"")}/attachments/`}export function inboxAttachmentId(key){return createHash("sha256").update(key).digest("base64url").slice(0,22)}export function inboxAttachmentName(key,prefix){const rawStoredName=key.startsWith(prefix)?key.slice(prefix.length):key.split("/").pop()||"";const storedName=rawStoredName.replace(/^stacks-\d{4}--/,"");let decodedName=storedName;try{decodedName=decodeURIComponent(storedName)}catch{}const safeName=decodedName.replace(/[\u0000-\u001F\u007F]/g,"").replace(/[\\/]/g,"_").trim();return safeName.slice(0,240)||"attachment"}export function mapInboxAttachmentObjects(basePath,objects){const prefix=inboxAttachmentPrefix(basePath);return objects.filter((object)=>object.Key.startsWith(prefix)&&object.Key.length>prefix.length&&!object.Key.endsWith("/")).map((object)=>({id:inboxAttachmentId(object.Key),key:object.Key,name:inboxAttachmentName(object.Key,prefix),size:Math.max(0,Number(object.Size)||0),...object.LastModified?{lastModified:object.LastModified}:{}})).sort((left,right)=>left.name.localeCompare(right.name))}export function inboxAttachmentContentDisposition(filename){const asciiName=filename.normalize("NFKD").replace(/[^\x20-\x7E]/g,"").replace(/["\\]/g,"_").trim()||"attachment";const utf8Name=encodeURIComponent(filename).replace(/['()]/g,(character)=>`%${character.charCodeAt(0).toString(16).toUpperCase()}`);return`attachment; filename="${asciiName}"; filename*=UTF-8''${utf8Name}`}export function inboxAttachmentContentType(contentType){const mediaType=contentType?.split(";",1)[0]?.trim().toLowerCase()||"";return/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(mediaType)?mediaType:"application/octet-stream"}
package/dist/sdk/index.js CHANGED
@@ -1 +1 @@
1
- import{email as emailConfig}from"@stacksjs/config";import{getErrorMessage}from"@stacksjs/utils";import{inboxMailboxPath,inboxMessagePath}from"../inbox-mailbox";import{normalizeEmailHtmlBody,normalizeEmailTextBody}from"../mime-preview";import{inboxAttachmentPrefix,mapInboxAttachmentObjects}from"./inbox-attachments";export*from"./inbox-attachments";function inboxString(value,field,index){if(typeof value!=="string")throw TypeError(`Inbox entry ${index} has an invalid ${field}.`);const normalized=value.trim();if(!normalized||/[\u0000-\u001F\u007F]/.test(normalized))throw TypeError(`Inbox entry ${index} has an invalid ${field}.`);return normalized}function normalizeInboxEntry(value,index,mailbox){if(!value||typeof value!=="object"||Array.isArray(value))throw TypeError(`Inbox entry ${index} must be an object.`);const entry=value,messageId=inboxString(entry.messageId,"messageId",index);if(messageId.length>512)throw TypeError(`Inbox entry ${index} has an invalid messageId.`);const path=inboxMessagePath(inboxString(entry.path,"path",index),mailbox);return{messageId,from:inboxString(entry.from,"from",index),...typeof entry.fromName==="string"&&entry.fromName.trim()?{fromName:entry.fromName.trim()}:{},to:inboxString(entry.to,"to",index),subject:typeof entry.subject==="string"?entry.subject:"",date:inboxString(entry.date,"date",index),read:entry.read===!0,...typeof entry.preview==="string"?{preview:entry.preview}:{},hasAttachments:entry.hasAttachments===!0,path}}export class EmailSDK{bucket;region;domain;storageFactory;constructor(options){const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");this.bucket=options?.bucket||process.env.AWS_BUCKET||`${appName}-production-email`;this.region=options?.region||process.env.AWS_REGION||"us-east-1";const fromAddress=emailConfig?.from?.address,parsedDomain=fromAddress?.includes("@")?fromAddress.split("@")[1]:void 0;this.domain=options?.domain||emailConfig?.domain||parsedDomain||"stacksjs.com";this.storageFactory=options?.storage}async send(message){try{const{SESClient}=await import("@stacksjs/ts-cloud"),ses=new SESClient(this.region),from=this.normalizeAddress(message.from||emailConfig?.from||{address:`noreply@${this.domain}`}),toAddresses=this.normalizeAddresses(message.to),ccAddresses=message.cc?this.normalizeAddresses(message.cc):void 0,bccAddresses=message.bcc?this.normalizeAddresses(message.bcc):void 0;return{success:!0,messageId:(await ses.sendEmail({FromEmailAddress:typeof from==="string"?from:`${from.name} <${from.address}>`,Destination:{ToAddresses:toAddresses,CcAddresses:ccAddresses,BccAddresses:bccAddresses},ReplyToAddresses:message.replyTo?[typeof message.replyTo==="string"?message.replyTo:message.replyTo.address]:void 0,Content:{Simple:{Subject:{Data:message.subject,Charset:"UTF-8"},Body:{...message.html&&{Html:{Data:message.html,Charset:"UTF-8"}},...message.text&&{Text:{Data:message.text,Charset:"UTF-8"}}}}}})).MessageId}}catch(error){return{success:!1,error:getErrorMessage(error)}}}async sendTemplate(options){const html=this.renderTemplate(options.template,options.data),subject=options.subject||options.template;return this.send({to:options.to,from:options.from,subject,html})}async getInbox(mailbox,options){try{const mailboxPath=inboxMailboxPath(mailbox,this.domain),result=await(await this.storage()).getObject(this.bucket,mailboxPath.indexKey);if(!result)return[];const parsed=JSON.parse(result);if(!Array.isArray(parsed))throw TypeError("Inbox index must be a JSON array.");const inbox=parsed.map((entry,index)=>normalizeInboxEntry(entry,index,mailboxPath)),offset=Math.max(0,Math.trunc(Number(options?.offset)||0)),limit=Math.min(1000,Math.max(1,Math.trunc(Number(options?.limit)||50)));return inbox.slice(offset,offset+limit)}catch(error){if(getErrorMessage(error).includes("NoSuchKey")||getErrorMessage(error).includes("404"))return[];throw error}}async getInboxStats(mailbox){const inbox=await this.getInbox(mailbox,{limit:1000}),unread=inbox.filter((e)=>!e.read).length;return{total:inbox.length,unread,read:inbox.length-unread}}async getUnreadCount(mailbox){return(await this.getInboxStats(mailbox)).unread}async getEmail(mailbox,messageId){try{const email=(await this.getInbox(mailbox,{limit:1000})).find((e)=>e.messageId===messageId);if(!email)return null;const s3=await this.storage(),basePath=email.path,metaResult=await s3.getObject(this.bucket,`${basePath}/metadata.json`);let metadata={};if(metaResult)try{metadata=JSON.parse(metaResult)}catch(parseError){console.debug(`[email-sdk] Failed to parse email metadata: ${parseError.message}`)}let html;try{const htmlResult=await s3.getObject(this.bucket,`${basePath}/body.html`);html=htmlResult?normalizeEmailHtmlBody(htmlResult):void 0}catch(error){if(!getErrorMessage(error)?.includes("NoSuchKey")&&!getErrorMessage(error)?.includes("404"))console.debug(`[email-sdk] Failed to fetch HTML body: ${getErrorMessage(error)}`)}let text;try{const textResult=await s3.getObject(this.bucket,`${basePath}/body.txt`);text=textResult?normalizeEmailTextBody(textResult):void 0}catch(error){if(!getErrorMessage(error)?.includes("NoSuchKey")&&!getErrorMessage(error)?.includes("404"))console.debug(`[email-sdk] Failed to fetch text body: ${getErrorMessage(error)}`)}const attachments=await this.listAttachments(s3,email);return{metadata,html,text,attachments}}catch(error){if(getErrorMessage(error).includes("NoSuchKey")||getErrorMessage(error).includes("404"))return null;throw error}}async getAttachments(mailbox,messageId){const email=(await this.getInbox(mailbox,{limit:1000})).find((entry)=>entry.messageId===messageId);if(!email)return null;return this.listAttachments(await this.storage(),email)}async getAttachment(mailbox,messageId,attachmentId){const email=(await this.getInbox(mailbox,{limit:1000})).find((entry)=>entry.messageId===messageId);if(!email)return null;const s3=await this.storage(),attachment=(await this.listStoredAttachments(s3,email)).find((item)=>item.id===attachmentId);if(!attachment)return null;const result=await s3.getObjectBytes(this.bucket,attachment.key);return{attachment:{id:attachment.id,name:attachment.name,size:attachment.size||result.contentLength||result.body.byteLength,...attachment.lastModified?{lastModified:attachment.lastModified}:{}},body:result.body,contentType:result.contentType||"application/octet-stream"}}async search(mailbox,options){let results=await this.getInbox(mailbox,{limit:1000});if(options.from){const fromLower=options.from.toLowerCase();results=results.filter((e)=>e.from.toLowerCase().includes(fromLower))}if(options.subject){const subjectLower=options.subject.toLowerCase();results=results.filter((e)=>e.subject.toLowerCase().includes(subjectLower))}if(options.after)results=results.filter((e)=>new Date(e.date)>=options.after);if(options.before)results=results.filter((e)=>new Date(e.date)<=options.before);if(options.hasAttachments!==void 0)results=results.filter((e)=>e.hasAttachments===options.hasAttachments);const offset=options.offset||0,limit=options.limit||50;return results.slice(offset,offset+limit)}async delete(mailbox,messageId){const mailboxPath=inboxMailboxPath(mailbox,this.domain),s3=await this.storage(),inbox=await this.getInbox(mailbox,{limit:1000}),emailIndex=inbox.findIndex((e)=>e.messageId===messageId);if(emailIndex===-1)return!1;const email=inbox[emailIndex];if(!email)return!1;const basePath=email.path,keysToDelete=await this.listStoredObjectKeys(s3,`${basePath}/`);for(let offset=0;offset<keysToDelete.length;offset+=1000)await s3.deleteObjects(this.bucket,keysToDelete.slice(offset,offset+1000));inbox.splice(emailIndex,1);await s3.putObject({bucket:this.bucket,key:mailboxPath.indexKey,body:JSON.stringify(inbox,null,2),contentType:"application/json"});return!0}async listAttachments(s3,email){return(await this.listStoredAttachments(s3,email)).map((attachment)=>({id:attachment.id,name:attachment.name,size:attachment.size,...attachment.lastModified?{lastModified:attachment.lastModified}:{}}))}async listStoredAttachments(s3,email){const result=await s3.listObjects({bucket:this.bucket,prefix:inboxAttachmentPrefix(email.path),maxKeys:1000});return mapInboxAttachmentObjects(email.path,result.objects)}async listStoredObjectKeys(s3,prefix){const keys=[];let continuationToken;do{const result=await s3.listObjects({bucket:this.bucket,prefix,maxKeys:1000,...continuationToken?{continuationToken}:{}});keys.push(...result.objects.map((object)=>object.Key).filter(Boolean));continuationToken=result.nextContinuationToken}while(continuationToken);return keys}async markAsRead(mailbox,messageId){return this.updateEmailStatus(mailbox,messageId,{read:!0})}async markAsUnread(mailbox,messageId){return this.updateEmailStatus(mailbox,messageId,{read:!1})}async updateEmailStatus(mailbox,messageId,updates){const mailboxPath=inboxMailboxPath(mailbox,this.domain),s3=await this.storage(),inbox=await this.getInbox(mailbox,{limit:1000}),emailIndex=inbox.findIndex((e)=>e.messageId===messageId);if(emailIndex===-1)return!1;Object.assign(inbox[emailIndex],updates);await s3.putObject({bucket:this.bucket,key:mailboxPath.indexKey,body:JSON.stringify(inbox,null,2),contentType:"application/json"});return!0}async storage(){if(this.storageFactory)return this.storageFactory();const{S3Client}=await import("@stacksjs/ts-cloud");return new S3Client(this.region)}normalizeAddress(addr){if(typeof addr==="string"){const match=addr.match(/^(.+?)\s*<(.+)>$/);if(match)return{name:match[1].trim(),address:match[2].trim()};return{address:addr}}return addr}normalizeAddresses(addrs){return(Array.isArray(addrs)?addrs:[addrs]).map((a)=>{if(typeof a==="string")return a;return a.name?`${a.name} <${a.address}>`:a.address})}renderTemplate(template,data){let result=template;for(const[key,value]of Object.entries(data)){const escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");result=result.replace(new RegExp(`{{\\s*${escapedKey}\\s*}}`,"g"),String(value))}return result}}export const emailSDK=new EmailSDK,sendEmail=(message)=>emailSDK.send(message),getInbox=(mailbox,options)=>emailSDK.getInbox(mailbox,options),getInboxStats=(mailbox)=>emailSDK.getInboxStats(mailbox),getUnreadCount=(mailbox)=>emailSDK.getUnreadCount(mailbox),searchEmails=(mailbox,options)=>emailSDK.search(mailbox,options),deleteEmail=(mailbox,messageId)=>emailSDK.delete(mailbox,messageId);export default EmailSDK;
1
+ import{email as emailConfig}from"@stacksjs/config";import{getErrorMessage}from"@stacksjs/utils";import{inboxMailboxPath,inboxMessagePath}from"../inbox-mailbox";import{normalizeEmailHtmlBody,normalizeEmailTextBody}from"../mime-preview";import{inboxAttachmentPrefix,mapInboxAttachmentObjects}from"./inbox-attachments";export*from"./inbox-attachments";function inboxString(value,field,index){if(typeof value!=="string")throw new TypeError(`Inbox entry ${index} has an invalid ${field}.`);const normalized=value.trim();if(!normalized||/[\u0000-\u001F\u007F]/.test(normalized))throw new TypeError(`Inbox entry ${index} has an invalid ${field}.`);return normalized}function normalizeInboxEntry(value,index,mailbox){if(!value||typeof value!=="object"||Array.isArray(value))throw new TypeError(`Inbox entry ${index} must be an object.`);const entry=value;const messageId=inboxString(entry.messageId,"messageId",index);if(messageId.length>512)throw new TypeError(`Inbox entry ${index} has an invalid messageId.`);const path=inboxMessagePath(inboxString(entry.path,"path",index),mailbox);return{messageId,from:inboxString(entry.from,"from",index),...typeof entry.fromName==="string"&&entry.fromName.trim()?{fromName:entry.fromName.trim()}:{},to:inboxString(entry.to,"to",index),subject:typeof entry.subject==="string"?entry.subject:"",date:inboxString(entry.date,"date",index),read:entry.read===true,...typeof entry.preview==="string"?{preview:entry.preview}:{},hasAttachments:entry.hasAttachments===true,path}}export class EmailSDK{bucket;region;domain;storageFactory;constructor(options){const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");this.bucket=options?.bucket||process.env.AWS_BUCKET||`${appName}-production-email`;this.region=options?.region||process.env.AWS_REGION||"us-east-1";const fromAddress=emailConfig?.from?.address;const parsedDomain=fromAddress?.includes("@")?fromAddress.split("@")[1]:undefined;this.domain=options?.domain||emailConfig?.domain||parsedDomain||"stacksjs.com";this.storageFactory=options?.storage}async send(message){try{const{SESClient}=await import("@stacksjs/ts-cloud");const ses=new SESClient(this.region);const from=this.normalizeAddress(message.from||emailConfig?.from||{address:`noreply@${this.domain}`});const toAddresses=this.normalizeAddresses(message.to);const ccAddresses=message.cc?this.normalizeAddresses(message.cc):undefined;const bccAddresses=message.bcc?this.normalizeAddresses(message.bcc):undefined;const result=await ses.sendEmail({FromEmailAddress:typeof from==="string"?from:`${from.name} <${from.address}>`,Destination:{ToAddresses:toAddresses,CcAddresses:ccAddresses,BccAddresses:bccAddresses},ReplyToAddresses:message.replyTo?[typeof message.replyTo==="string"?message.replyTo:message.replyTo.address]:undefined,Content:{Simple:{Subject:{Data:message.subject,Charset:"UTF-8"},Body:{...message.html&&{Html:{Data:message.html,Charset:"UTF-8"}},...message.text&&{Text:{Data:message.text,Charset:"UTF-8"}}}}}});return{success:true,messageId:result.MessageId}}catch(error){return{success:false,error:getErrorMessage(error)}}}async sendTemplate(options){const html=this.renderTemplate(options.template,options.data);const subject=options.subject||options.template;return this.send({to:options.to,from:options.from,subject,html})}async getInbox(mailbox,options){try{const mailboxPath=inboxMailboxPath(mailbox,this.domain);const s3=await this.storage();const result=await s3.getObject(this.bucket,mailboxPath.indexKey);if(!result){return[]}const parsed=JSON.parse(result);if(!Array.isArray(parsed))throw new TypeError("Inbox index must be a JSON array.");const inbox=parsed.map((entry,index)=>normalizeInboxEntry(entry,index,mailboxPath));const offset=Math.max(0,Math.trunc(Number(options?.offset)||0));const limit=Math.min(1000,Math.max(1,Math.trunc(Number(options?.limit)||50)));return inbox.slice(offset,offset+limit)}catch(error){if(getErrorMessage(error).includes("NoSuchKey")||getErrorMessage(error).includes("404")){return[]}throw error}}async getInboxStats(mailbox){const inbox=await this.getInbox(mailbox,{limit:1000});const unread=inbox.filter((e)=>!e.read).length;return{total:inbox.length,unread,read:inbox.length-unread}}async getUnreadCount(mailbox){const stats=await this.getInboxStats(mailbox);return stats.unread}async getEmail(mailbox,messageId){try{const inbox=await this.getInbox(mailbox,{limit:1000});const email=inbox.find((e)=>e.messageId===messageId);if(!email){return null}const s3=await this.storage();const basePath=email.path;const metaResult=await s3.getObject(this.bucket,`${basePath}/metadata.json`);let metadata={};if(metaResult){try{metadata=JSON.parse(metaResult)}catch(parseError){console.debug(`[email-sdk] Failed to parse email metadata: ${parseError.message}`)}}let html;try{const htmlResult=await s3.getObject(this.bucket,`${basePath}/body.html`);html=htmlResult?normalizeEmailHtmlBody(htmlResult):undefined}catch(error){if(!getErrorMessage(error)?.includes("NoSuchKey")&&!getErrorMessage(error)?.includes("404")){console.debug(`[email-sdk] Failed to fetch HTML body: ${getErrorMessage(error)}`)}}let text;try{const textResult=await s3.getObject(this.bucket,`${basePath}/body.txt`);text=textResult?normalizeEmailTextBody(textResult):undefined}catch(error){if(!getErrorMessage(error)?.includes("NoSuchKey")&&!getErrorMessage(error)?.includes("404")){console.debug(`[email-sdk] Failed to fetch text body: ${getErrorMessage(error)}`)}}const attachments=await this.listAttachments(s3,email);return{metadata,html,text,attachments}}catch(error){if(getErrorMessage(error).includes("NoSuchKey")||getErrorMessage(error).includes("404")){return null}throw error}}async getAttachments(mailbox,messageId){const inbox=await this.getInbox(mailbox,{limit:1000});const email=inbox.find((entry)=>entry.messageId===messageId);if(!email)return null;return this.listAttachments(await this.storage(),email)}async getAttachment(mailbox,messageId,attachmentId){const inbox=await this.getInbox(mailbox,{limit:1000});const email=inbox.find((entry)=>entry.messageId===messageId);if(!email)return null;const s3=await this.storage();const stored=await this.listStoredAttachments(s3,email);const attachment=stored.find((item)=>item.id===attachmentId);if(!attachment)return null;const result=await s3.getObjectBytes(this.bucket,attachment.key);return{attachment:{id:attachment.id,name:attachment.name,size:attachment.size||result.contentLength||result.body.byteLength,...attachment.lastModified?{lastModified:attachment.lastModified}:{}},body:result.body,contentType:result.contentType||"application/octet-stream"}}async search(mailbox,options){const inbox=await this.getInbox(mailbox,{limit:1000});let results=inbox;if(options.from){const fromLower=options.from.toLowerCase();results=results.filter((e)=>e.from.toLowerCase().includes(fromLower))}if(options.subject){const subjectLower=options.subject.toLowerCase();results=results.filter((e)=>e.subject.toLowerCase().includes(subjectLower))}if(options.after){results=results.filter((e)=>new Date(e.date)>=options.after)}if(options.before){results=results.filter((e)=>new Date(e.date)<=options.before)}if(options.hasAttachments!==undefined){results=results.filter((e)=>e.hasAttachments===options.hasAttachments)}const offset=options.offset||0;const limit=options.limit||50;return results.slice(offset,offset+limit)}async delete(mailbox,messageId){const mailboxPath=inboxMailboxPath(mailbox,this.domain);const s3=await this.storage();const inbox=await this.getInbox(mailbox,{limit:1000});const emailIndex=inbox.findIndex((e)=>e.messageId===messageId);if(emailIndex===-1){return false}const email=inbox[emailIndex];if(!email)return false;const basePath=email.path;const keysToDelete=await this.listStoredObjectKeys(s3,`${basePath}/`);for(let offset=0;offset<keysToDelete.length;offset+=1000)await s3.deleteObjects(this.bucket,keysToDelete.slice(offset,offset+1000));inbox.splice(emailIndex,1);await s3.putObject({bucket:this.bucket,key:mailboxPath.indexKey,body:JSON.stringify(inbox,null,2),contentType:"application/json"});return true}async listAttachments(s3,email){const attachments=await this.listStoredAttachments(s3,email);return attachments.map((attachment)=>({id:attachment.id,name:attachment.name,size:attachment.size,...attachment.lastModified?{lastModified:attachment.lastModified}:{}}))}async listStoredAttachments(s3,email){const result=await s3.listObjects({bucket:this.bucket,prefix:inboxAttachmentPrefix(email.path),maxKeys:1000});return mapInboxAttachmentObjects(email.path,result.objects)}async listStoredObjectKeys(s3,prefix){const keys=[];let continuationToken;do{const result=await s3.listObjects({bucket:this.bucket,prefix,maxKeys:1000,...continuationToken?{continuationToken}:{}});keys.push(...result.objects.map((object)=>object.Key).filter(Boolean));continuationToken=result.nextContinuationToken}while(continuationToken);return keys}async markAsRead(mailbox,messageId){return this.updateEmailStatus(mailbox,messageId,{read:true})}async markAsUnread(mailbox,messageId){return this.updateEmailStatus(mailbox,messageId,{read:false})}async updateEmailStatus(mailbox,messageId,updates){const mailboxPath=inboxMailboxPath(mailbox,this.domain);const s3=await this.storage();const inbox=await this.getInbox(mailbox,{limit:1000});const emailIndex=inbox.findIndex((e)=>e.messageId===messageId);if(emailIndex===-1){return false}Object.assign(inbox[emailIndex],updates);await s3.putObject({bucket:this.bucket,key:mailboxPath.indexKey,body:JSON.stringify(inbox,null,2),contentType:"application/json"});return true}async storage(){if(this.storageFactory)return this.storageFactory();const{S3Client}=await import("@stacksjs/ts-cloud");return new S3Client(this.region)}normalizeAddress(addr){if(typeof addr==="string"){const match=addr.match(/^(.+?)\s*<(.+)>$/);if(match){return{name:match[1].trim(),address:match[2].trim()}}return{address:addr}}return addr}normalizeAddresses(addrs){const arr=Array.isArray(addrs)?addrs:[addrs];return arr.map((a)=>{if(typeof a==="string")return a;return a.name?`${a.name} <${a.address}>`:a.address})}renderTemplate(template,data){let result=template;for(const[key,value]of Object.entries(data)){const escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");result=result.replace(new RegExp(`{{\\s*${escapedKey}\\s*}}`,"g"),String(value))}return result}}export const emailSDK=new EmailSDK;export const sendEmail=(message)=>emailSDK.send(message);export const getInbox=(mailbox,options)=>emailSDK.getInbox(mailbox,options);export const getInboxStats=(mailbox)=>emailSDK.getInboxStats(mailbox);export const getUnreadCount=(mailbox)=>emailSDK.getUnreadCount(mailbox);export const searchEmails=(mailbox,options)=>emailSDK.search(mailbox,options);export const deleteEmail=(mailbox,messageId)=>emailSDK.delete(mailbox,messageId);export default EmailSDK;
@@ -1 +1 @@
1
- import{db}from"@stacksjs/database/runtime";let warnedAboutMissingTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=!0;console.warn("[email/suppression] email_suppressions table missing - suppression checks accepted but NOT enforced. Run migrations to enable enforcement.")}export function isMissingTableError(err){const e=err,msg=e?.message??"";return e?.code==="42P01"||msg.includes("no such table")||msg.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(msg)}function isSuppressionStoreUnavailable(err){if(isMissingTableError(err))return!0;const msg=(err?.message??"").toLowerCase();return msg.includes("connection closed")||msg.includes("unable to open database")||msg.includes("econnrefused")||msg.includes("connection terminated")||msg.includes("no database")||msg.includes("database connection")}function canonicalize(email){return String(email).trim().toLowerCase()}export async function isSuppressed(email,type){const canon=canonicalize(email);try{let query=db.selectFrom("email_suppressions").where("email","=",canon).select(["email"]);if(type)query=query.where("type","=",type);const row=await query.executeTakeFirst();return Boolean(row)}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return!1}throw err}}export async function getSuppressions(email){const canon=canonicalize(email);try{return await db.selectFrom("email_suppressions").where("email","=",canon).selectAll().execute()??[]}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return[]}throw err}}export async function suppress(email,type,reason){const canon=canonicalize(email),createdAt=new Date().toISOString().slice(0,19).replace("T"," ");try{await db.insertInto("email_suppressions").values({email:canon,type,reason:reason??null,created_at:createdAt}).execute()}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return}const msg=err?.message??"";if(msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry"))return;throw err}}export async function unsuppress(email,type){const canon=canonicalize(email);try{await db.deleteFrom("email_suppressions").where("email","=",canon).where("type","=",type).execute()}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return}throw err}}export async function getSuppressionPolicy(){try{const{config}=await import("@stacksjs/config"),policy=config?.email?.suppressionPolicy;if(policy==="strict"||policy==="transactional-allowed"||policy==="off")return policy}catch{}return"strict"}export async function checkSuppressionFor(email,tag){const policy=await getSuppressionPolicy();if(policy==="off")return null;if(policy==="transactional-allowed"&&tag==="transactional")return null;const suppressions=await getSuppressions(email);if(suppressions.length===0)return null;const priority=["unsubscribe","complaint","bounce","manual"];for(const p of priority)if(suppressions.some((s)=>s.type===p))return p;return suppressions[0].type}
1
+ import{db}from"@stacksjs/database/runtime";let warnedAboutMissingTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=true;console.warn("[email/suppression] email_suppressions table missing - suppression checks accepted but NOT enforced. "+"Run migrations to enable enforcement.")}export function isMissingTableError(err){const e=err;const msg=e?.message??"";return e?.code==="42P01"||msg.includes("no such table")||msg.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(msg)}function isSuppressionStoreUnavailable(err){if(isMissingTableError(err))return true;const msg=(err?.message??"").toLowerCase();return msg.includes("connection closed")||msg.includes("unable to open database")||msg.includes("econnrefused")||msg.includes("connection terminated")||msg.includes("no database")||msg.includes("database connection")}function canonicalize(email){return String(email).trim().toLowerCase()}export async function isSuppressed(email,type){const canon=canonicalize(email);try{let query=db.selectFrom("email_suppressions").where("email","=",canon).select(["email"]);if(type)query=query.where("type","=",type);const row=await query.executeTakeFirst();return Boolean(row)}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return false}throw err}}export async function getSuppressions(email){const canon=canonicalize(email);try{const rows=await db.selectFrom("email_suppressions").where("email","=",canon).selectAll().execute();return rows??[]}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return[]}throw err}}export async function suppress(email,type,reason){const canon=canonicalize(email);const createdAt=new Date().toISOString().slice(0,19).replace("T"," ");try{await db.insertInto("email_suppressions").values({email:canon,type,reason:reason??null,created_at:createdAt}).execute()}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return}const msg=err?.message??"";if(msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry"))return;throw err}}export async function unsuppress(email,type){const canon=canonicalize(email);try{await db.deleteFrom("email_suppressions").where("email","=",canon).where("type","=",type).execute()}catch(err){if(isSuppressionStoreUnavailable(err)){warnOnceAboutMissingTable();return}throw err}}export async function getSuppressionPolicy(){try{const{config}=await import("@stacksjs/config");const policy=config?.email?.suppressionPolicy;if(policy==="strict"||policy==="transactional-allowed"||policy==="off")return policy}catch{}return"strict"}export async function checkSuppressionFor(email,tag){const policy=await getSuppressionPolicy();if(policy==="off")return null;if(policy==="transactional-allowed"&&tag==="transactional")return null;const suppressions=await getSuppressions(email);if(suppressions.length===0)return null;const priority=["unsubscribe","complaint","bounce","manual"];for(const p of priority){if(suppressions.some((s)=>s.type===p))return p}return suppressions[0].type}
package/dist/template.js CHANGED
@@ -1,7 +1,7 @@
1
- var {require}=import.meta;import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{fs}from"@stacksjs/storage";import{defaultsResourcesPath,resolveModulePath,resourcesPath,storagePath}from"@stacksjs/path";import{join}from"node:path";import{inlineCss,shouldInlineByDefault}from"./css-inliner";export class SafeHtml{value;__safeHtml=!0;constructor(value){this.value=value}}export function safe(html){return new SafeHtml(html)}function getDefaultVariables(){const primaryColor=config.app.primaryColor||"#3b82f6";return{appName:config.app.name||"Stacks",appUrl:config.app.url||"https://localhost",primaryColor,primaryColorDark:darkenColor(primaryColor,15),year:new Date().getFullYear()}}function darkenColor(hex,percent){const num=Number.parseInt(hex.replace("#",""),16),amt=Math.round(2.55*percent),R=Math.max(0,(num>>16)-amt),G=Math.max(0,(num>>8&255)-amt),B=Math.max(0,(num&255)-amt);return`#${(16777216+R*65536+G*256+B).toString(16).slice(1)}`}export function escapeHtml(input){return input.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function replaceVariables(html,variables){let result=html;for(const[key,value]of Object.entries(variables)){const escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),regex=new RegExp(`\\{\\{\\s*${escapedKey}\\s*\\}\\}`,"g");result=result.replace(regex,renderTemplateValue(value))}return result}function renderTemplateValue(value){if(value===null||value===void 0)return"";if(value instanceof SafeHtml)return value.value;if(typeof value==="object")return"";return escapeHtml(String(value))}function stxProps(value){if(value instanceof SafeHtml)return value.value;if(Array.isArray(value))return value.map(stxProps);if(value!==null&&typeof value==="object"&&Object.getPrototypeOf(value)===Object.prototype)return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,stxProps(entry)]));return value}const templateRoots=[(relativePath)=>resourcesPath(join("emails",relativePath)),(relativePath)=>defaultsResourcesPath(join("emails",relativePath))];let templateRegistry=null,templateRegistryLoaded=!1,templateRegistryCwd=null;function loadTemplateRegistry(){const cwd=process.cwd();if(templateRegistryLoaded&&templateRegistryCwd===cwd)return templateRegistry;templateRegistry=null;templateRegistryLoaded=!1;templateRegistryCwd=cwd;const dir=storagePath("framework/auto-imports"),registryPath=`${dir}/emails.ts`;if(!fs.existsSync(registryPath)){templateRegistryLoaded=!0;return null}const module=require(registryPath);if(!module.emails)throw Error(`Invalid emails registry: ${registryPath}`);templateRegistry=Object.fromEntries(Object.entries(module.emails).map(([name,file])=>[name,{path:resolveModulePath(file,dir),type:file.endsWith(".stx")?"stx":"html"}]));templateRegistryLoaded=!0;return templateRegistry}export function resetTemplateRegistry(){templateRegistry=null;templateRegistryLoaded=!1;templateRegistryCwd=null}function resolveTemplatePath(templateName){const registry=loadTemplateRegistry();if(registry){const bare=templateName.replace(/\.(?:stx|html)$/,""),hit=registry[bare];if(hit){if(templateName.endsWith(".stx")&&hit.type!=="stx");else if(templateName.endsWith(".html")&&hit.type!=="html");else if(fs.existsSync(hit.path))return hit}}for(const root of templateRoots){if(templateName.endsWith(".stx")){const fullPath=root(templateName);if(fs.existsSync(fullPath))return{path:fullPath,type:"stx"};continue}if(templateName.endsWith(".html")){const fullPath=root(templateName);if(fs.existsSync(fullPath))return{path:fullPath,type:"html"};continue}const stxPath=root(`${templateName}.stx`);if(fs.existsSync(stxPath))return{path:stxPath,type:"stx"};const htmlPath=root(`${templateName}.html`);if(fs.existsSync(htmlPath))return{path:htmlPath,type:"html"}}return null}function loadHtmlTemplate(templatePath){const path=templatePath.endsWith(".html")?templatePath:`${templatePath}.html`;for(const root of templateRoots){const fullPath=root(path);if(fs.existsSync(fullPath))return fs.readFileSync(fullPath,"utf-8")}return null}function loadLayout(layoutName){return loadHtmlTemplate(`layouts/${layoutName}`)}export function htmlToText(html){return((value)=>value.replace(/&nbsp;/g," ").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;|&apos;/g,"'").replace(/&copy;/g,"(c)").replace(/&#(\d+);/g,(_,code)=>String.fromCodePoint(Number(code))).replace(/&#x([\da-f]+);/gi,(_,code)=>String.fromCodePoint(Number.parseInt(code,16))).replace(/&amp;/g,"&"))(html.replace(/<(head|style|script|title)\b[^>]*>[\s\S]*?<\/\1>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<a\b[^>]*?\bhref\s*=\s*(["'])(.*?)\1[^>]*>([\s\S]*?)<\/a>/gi,(_,_quote,href,inner)=>{const label=inner.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim(),url=href.trim();if(!url||url==="#"||url.startsWith("javascript:"))return label;if(`mailto:${label}`===url)return label;if(!label||label===url)return url;return`${label} (${url})`}).replace(/<br\s*\/?>/gi,`
1
+ import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{fs}from"@stacksjs/storage";import{defaultsResourcesPath,resolveModulePath,resourcesPath,storagePath}from"@stacksjs/path";import{join}from"node:path";import{inlineCss,shouldInlineByDefault}from"./css-inliner";export class SafeHtml{value;__safeHtml=true;constructor(value){this.value=value}}export function safe(html){return new SafeHtml(html)}function getDefaultVariables(){const primaryColor=config.app.primaryColor||"#3b82f6";return{appName:config.app.name||"Stacks",appUrl:config.app.url||"https://localhost",primaryColor,primaryColorDark:darkenColor(primaryColor,15),year:new Date().getFullYear()}}function darkenColor(hex,percent){const num=Number.parseInt(hex.replace("#",""),16);const amt=Math.round(2.55*percent);const R=Math.max(0,(num>>16)-amt);const G=Math.max(0,(num>>8&255)-amt);const B=Math.max(0,(num&255)-amt);return`#${(16777216+R*65536+G*256+B).toString(16).slice(1)}`}export function escapeHtml(input){return input.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function replaceVariables(html,variables){let result=html;for(const[key,value]of Object.entries(variables)){const escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const regex=new RegExp(`\\{\\{\\s*${escapedKey}\\s*\\}\\}`,"g");result=result.replace(regex,renderTemplateValue(value))}return result}function renderTemplateValue(value){if(value===null||value===undefined)return"";if(value instanceof SafeHtml)return value.value;if(typeof value==="object")return"";return escapeHtml(String(value))}function stxProps(value){if(value instanceof SafeHtml)return value.value;if(Array.isArray(value))return value.map(stxProps);if(value!==null&&typeof value==="object"&&Object.getPrototypeOf(value)===Object.prototype)return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,stxProps(entry)]));return value}const templateRoots=[(relativePath)=>resourcesPath(join("emails",relativePath)),(relativePath)=>defaultsResourcesPath(join("emails",relativePath))];let templateRegistry=null;let templateRegistryLoaded=false;let templateRegistryCwd=null;function loadTemplateRegistry(){const cwd=process.cwd();if(templateRegistryLoaded&&templateRegistryCwd===cwd)return templateRegistry;templateRegistry=null;templateRegistryLoaded=false;templateRegistryCwd=cwd;const dir=storagePath("framework/auto-imports");const registryPath=`${dir}/emails.ts`;if(!fs.existsSync(registryPath)){templateRegistryLoaded=true;return null}const module=require(registryPath);if(!module.emails)throw new Error(`Invalid emails registry: ${registryPath}`);templateRegistry=Object.fromEntries(Object.entries(module.emails).map(([name,file])=>[name,{path:resolveModulePath(file,dir),type:file.endsWith(".stx")?"stx":"html"}]));templateRegistryLoaded=true;return templateRegistry}export function resetTemplateRegistry(){templateRegistry=null;templateRegistryLoaded=false;templateRegistryCwd=null}function resolveTemplatePath(templateName){const registry=loadTemplateRegistry();if(registry){const bare=templateName.replace(/\.(?:stx|html)$/,"");const hit=registry[bare];if(hit){if(templateName.endsWith(".stx")&&hit.type!=="stx"){}else if(templateName.endsWith(".html")&&hit.type!=="html"){}else if(fs.existsSync(hit.path))return hit}}for(const root of templateRoots){if(templateName.endsWith(".stx")){const fullPath=root(templateName);if(fs.existsSync(fullPath))return{path:fullPath,type:"stx"};continue}if(templateName.endsWith(".html")){const fullPath=root(templateName);if(fs.existsSync(fullPath))return{path:fullPath,type:"html"};continue}const stxPath=root(`${templateName}.stx`);if(fs.existsSync(stxPath))return{path:stxPath,type:"stx"};const htmlPath=root(`${templateName}.html`);if(fs.existsSync(htmlPath))return{path:htmlPath,type:"html"}}return null}function loadHtmlTemplate(templatePath){const path=templatePath.endsWith(".html")?templatePath:`${templatePath}.html`;for(const root of templateRoots){const fullPath=root(path);if(fs.existsSync(fullPath))return fs.readFileSync(fullPath,"utf-8")}return null}function loadLayout(layoutName){return loadHtmlTemplate(`layouts/${layoutName}`)}export function htmlToText(html){const decode=(value)=>value.replace(/&nbsp;/g," ").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,`"`).replace(/&#39;|&apos;/g,`'`).replace(/&copy;/g,"(c)").replace(/&#(\d+);/g,(_,code)=>String.fromCodePoint(Number(code))).replace(/&#x([\da-f]+);/gi,(_,code)=>String.fromCodePoint(Number.parseInt(code,16))).replace(/&amp;/g,"&");return decode(html.replace(/<(head|style|script|title)\b[^>]*>[\s\S]*?<\/\1>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<a\b[^>]*?\bhref\s*=\s*(["'])(.*?)\1[^>]*>([\s\S]*?)<\/a>/gi,(_,_quote,href,inner)=>{const label=inner.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const url=href.trim();if(!url||url==="#"||url.startsWith("javascript:"))return label;if(`mailto:${label}`===url)return label;if(!label||label===url)return url;return`${label} (${url})`}).replace(/<br\s*\/?>/gi,`
2
2
  `).replace(/<\/(p|div|h[1-6]|li|tr|table)>/gi,`
3
3
  `).replace(/<\/td>/gi,"\t").replace(/<[^>]*>/g,"")).split(`
4
4
  `).map((line)=>line.replace(/[ \t]+/g," ").trim()).join(`
5
5
  `).replace(/\n{3,}/g,`
6
6
 
7
- `).trim()}export async function template(templateName,options={}){return templateByName(templateName,options)}export async function templateByName(templateName,options={}){const{variables={},layout="base",subject="",inline=shouldInlineByDefault()}=options,allVariables={...getDefaultVariables(),subject,...variables},resolved=resolveTemplatePath(templateName);if(!resolved){console.warn(`[Email Template] Template "${templateName}" not found`);return{html:"",text:""}}if(resolved.type==="stx")try{const{renderEmail}=await import("@stacksjs/stx"),result=await renderEmail(resolved.path,stxProps(allVariables),{componentsDir:resourcesPath("components/Email"),additionalComponentsDirs:[defaultsResourcesPath("components/Email")]});return{...result,html:inlineCss(result.html,{inline})}}catch(error){log.warn(`[email] STX template rendering failed for ${templateName}: ${error instanceof Error?error.message:String(error)}`);return{html:"",text:""}}let content=fs.readFileSync(resolved.path,"utf-8");content=replaceVariables(content,allVariables);let html;if(layout!==!1){const layoutHtml=loadLayout(layout);if(!layoutHtml){console.warn(`[Email Template] Layout "${layout}" not found, using content only`);html=content}else{allVariables.content=safe(content);html=replaceVariables(layoutHtml,allVariables)}}else html=content;html=inlineCss(html,{inline});const text=htmlToText(html);return{html,text}}export function renderHtml(htmlContent,variables={}){const allVariables={...getDefaultVariables(),...variables},html=replaceVariables(htmlContent,allVariables),text=htmlToText(html);return{html,text}}export function templateExists(templateName){return resolveTemplatePath(templateName)!==null}export function listTemplates(){const emailsPath=resourcesPath("emails");if(!fs.existsSync(emailsPath))return[];const templates=[];function scanDir(dir,prefix=""){const entries=fs.readdirSync(dir,{withFileTypes:!0});for(const entry of entries)if(entry.isDirectory()&&entry.name!=="layouts")scanDir(join(dir,entry.name),`${prefix}${entry.name}/`);else if(entry.isFile()&&(entry.name.endsWith(".html")||entry.name.endsWith(".stx"))){const name=entry.name.replace(/\.(html|stx)$/,"");if(!templates.includes(`${prefix}${name}`))templates.push(`${prefix}${name}`)}}scanDir(emailsPath);return templates}
7
+ `).trim()}export async function template(templateName,options={}){return templateByName(templateName,options)}export async function templateByName(templateName,options={}){const{variables={},layout="base",subject="",inline=shouldInlineByDefault()}=options;const allVariables={...getDefaultVariables(),subject,...variables};const resolved=resolveTemplatePath(templateName);if(!resolved){console.warn(`[Email Template] Template "${templateName}" not found`);return{html:"",text:""}}if(resolved.type==="stx"){try{const{renderEmail}=await import("@stacksjs/stx");const result=await renderEmail(resolved.path,stxProps(allVariables),{componentsDir:resourcesPath("components/Email"),additionalComponentsDirs:[defaultsResourcesPath("components/Email")]});return{...result,html:inlineCss(result.html,{inline})}}catch(error){log.warn(`[email] STX template rendering failed for ${templateName}: ${error instanceof Error?error.message:String(error)}`);return{html:"",text:""}}}let content=fs.readFileSync(resolved.path,"utf-8");content=replaceVariables(content,allVariables);let html;if(layout!==false){const layoutHtml=loadLayout(layout);if(!layoutHtml){console.warn(`[Email Template] Layout "${layout}" not found, using content only`);html=content}else{allVariables.content=safe(content);html=replaceVariables(layoutHtml,allVariables)}}else{html=content}html=inlineCss(html,{inline});const text=htmlToText(html);return{html,text}}export function renderHtml(htmlContent,variables={}){const allVariables={...getDefaultVariables(),...variables};const html=replaceVariables(htmlContent,allVariables);const text=htmlToText(html);return{html,text}}export function templateExists(templateName){return resolveTemplatePath(templateName)!==null}export function listTemplates(){const emailsPath=resourcesPath("emails");if(!fs.existsSync(emailsPath)){return[]}const templates=[];function scanDir(dir,prefix=""){const entries=fs.readdirSync(dir,{withFileTypes:true});for(const entry of entries){if(entry.isDirectory()&&entry.name!=="layouts"){scanDir(join(dir,entry.name),`${prefix}${entry.name}/`)}else if(entry.isFile()&&(entry.name.endsWith(".html")||entry.name.endsWith(".stx"))){const name=entry.name.replace(/\.(html|stx)$/,"");if(!templates.includes(`${prefix}${name}`)){templates.push(`${prefix}${name}`)}}}}scanDir(emailsPath);return templates}
@@ -1 +1 @@
1
- import{createHmac,timingSafeEqual}from"node:crypto";import process from"node:process";import{Buffer}from"node:buffer";const DEFAULT_TTL_SECONDS=2592000,DEFAULT_ROUTE="/_stacks/email/unsubscribe";function getAppKey(){const k=process.env.APP_KEY;if(!k||k.length<16){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production")throw Error("[email/unsubscribe] APP_KEY is missing or too short (need \u226516 chars). Cannot sign unsubscribe URL.")}return k||"stacks-default-key-dev-only-do-not-use-prod"}function b64UrlEncode(buf){return buf.toString("base64url")}function b64UrlDecode(s){return Buffer.from(s,"base64url")}export function createUnsubscribeToken(email,ttlSeconds=DEFAULT_TTL_SECONDS,scope){if(!email)throw Error("[email/unsubscribe] email is required");const exp=Math.floor(Date.now()/1000)+Math.floor(ttlSeconds),claims={email:String(email).trim().toLowerCase(),exp,iss:"stacks",...scope?{scope:String(scope)}:{}},payload=b64UrlEncode(Buffer.from(JSON.stringify(claims))),sig=b64UrlEncode(createHmac("sha256",getAppKey()).update(payload).digest());return`${payload}.${sig}`}export function verifyUnsubscribeToken(token){if(typeof token!=="string")return{valid:!1,reason:"malformed"};const parts=token.split(".");if(parts.length!==2)return{valid:!1,reason:"malformed"};const[payload,sig]=parts,expectedSig=createHmac("sha256",getAppKey()).update(payload).digest();let provided;try{provided=b64UrlDecode(sig)}catch{return{valid:!1,reason:"malformed"}}if(provided.length!==expectedSig.length||!timingSafeEqual(provided,expectedSig))return{valid:!1,reason:"bad_signature"};let claims;try{claims=JSON.parse(b64UrlDecode(payload).toString("utf8"))}catch{return{valid:!1,reason:"malformed"}}if(typeof claims.exp!=="number"||Math.floor(Date.now()/1000)>=claims.exp)return{valid:!1,reason:"expired"};if(!claims.email||typeof claims.email!=="string")return{valid:!1,reason:"malformed"};return{valid:!0,email:claims.email,...typeof claims.scope==="string"&&claims.scope?{scope:claims.scope}:{}}}export function buildUnsubscribeUrl(email,ttlSeconds,options={}){const token=createUnsubscribeToken(email,ttlSeconds,options.scope),base=(options.baseUrl||process.env.APP_URL||"http://localhost").replace(/\/$/,""),route=(options.routePrefix||DEFAULT_ROUTE).replace(/\/$/,"");return`${base}${route}/${token}`}export function buildListUnsubscribeHeaders(email,ttlSeconds,options){return{"List-Unsubscribe":`<${buildUnsubscribeUrl(email,ttlSeconds,options)}>`,"List-Unsubscribe-Post":"List-Unsubscribe=One-Click"}}
1
+ import{createHmac,timingSafeEqual}from"node:crypto";import process from"node:process";import{Buffer}from"node:buffer";const DEFAULT_TTL_SECONDS=30*24*60*60;const DEFAULT_ROUTE="/_stacks/email/unsubscribe";function getAppKey(){const k=process.env.APP_KEY;if(!k||k.length<16){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production"){throw new Error("[email/unsubscribe] APP_KEY is missing or too short (need ≥16 chars). Cannot sign unsubscribe URL.")}}return k||"stacks-default-key-dev-only-do-not-use-prod"}function b64UrlEncode(buf){return buf.toString("base64url")}function b64UrlDecode(s){return Buffer.from(s,"base64url")}export function createUnsubscribeToken(email,ttlSeconds=DEFAULT_TTL_SECONDS,scope){if(!email)throw new Error("[email/unsubscribe] email is required");const exp=Math.floor(Date.now()/1000)+Math.floor(ttlSeconds);const claims={email:String(email).trim().toLowerCase(),exp,iss:"stacks",...scope?{scope:String(scope)}:{}};const payload=b64UrlEncode(Buffer.from(JSON.stringify(claims)));const sig=b64UrlEncode(createHmac("sha256",getAppKey()).update(payload).digest());return`${payload}.${sig}`}export function verifyUnsubscribeToken(token){if(typeof token!=="string")return{valid:false,reason:"malformed"};const parts=token.split(".");if(parts.length!==2)return{valid:false,reason:"malformed"};const[payload,sig]=parts;const expectedSig=createHmac("sha256",getAppKey()).update(payload).digest();let provided;try{provided=b64UrlDecode(sig)}catch{return{valid:false,reason:"malformed"}}if(provided.length!==expectedSig.length||!timingSafeEqual(provided,expectedSig)){return{valid:false,reason:"bad_signature"}}let claims;try{claims=JSON.parse(b64UrlDecode(payload).toString("utf8"))}catch{return{valid:false,reason:"malformed"}}if(typeof claims.exp!=="number"||Math.floor(Date.now()/1000)>=claims.exp){return{valid:false,reason:"expired"}}if(!claims.email||typeof claims.email!=="string"){return{valid:false,reason:"malformed"}}return{valid:true,email:claims.email,...typeof claims.scope==="string"&&claims.scope?{scope:claims.scope}:{}}}export function buildUnsubscribeUrl(email,ttlSeconds,options={}){const token=createUnsubscribeToken(email,ttlSeconds,options.scope);const base=(options.baseUrl||process.env.APP_URL||"http://localhost").replace(/\/$/,"");const route=(options.routePrefix||DEFAULT_ROUTE).replace(/\/$/,"");return`${base}${route}/${token}`}export function buildListUnsubscribeHeaders(email,ttlSeconds,options){const url=buildUnsubscribeUrl(email,ttlSeconds,options);return{"List-Unsubscribe":`<${url}>`,"List-Unsubscribe-Post":"List-Unsubscribe=One-Click"}}
@@ -1 +1 @@
1
- export const ENVELOPE_ADDRESS=/^[^\s<>"\\\r\n\t]+@[^\s<>"\\\r\n\t]+$/;export function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr))throw Error(`Email ${role} address is malformed or contains forbidden characters: ${JSON.stringify(addr)}`)}export function assertHeaderSafeSubject(subject){if(/[\r\n]/.test(subject))throw Error("Email subject contains forbidden line break characters (CR/LF)")}export function filterStringHeaders(headers){if(!headers)return;const out={};for(const[k,v]of Object.entries(headers)){if(typeof v!=="string")continue;if(!isHeaderName(k)||/[\r\n\0]/.test(v))continue;out[k]=v}return Object.keys(out).length>0?out:void 0}export function assertHeaderValue(value,role){if(typeof value!=="string"||/[\r\n\0]/.test(value))throw Error(`Email ${role} contains forbidden header characters`)}export function isHeaderName(name){return/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)}
1
+ export const ENVELOPE_ADDRESS=/^[^\s<>"\\\r\n\t]+@[^\s<>"\\\r\n\t]+$/;export function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr)){throw new Error(`Email ${role} address is malformed or contains forbidden characters: ${JSON.stringify(addr)}`)}}export function assertHeaderSafeSubject(subject){if(/[\r\n]/.test(subject)){throw new Error("Email subject contains forbidden line break characters (CR/LF)")}}export function filterStringHeaders(headers){if(!headers)return;const out={};for(const[k,v]of Object.entries(headers)){if(typeof v!=="string")continue;if(!isHeaderName(k)||/[\r\n\0]/.test(v))continue;out[k]=v}return Object.keys(out).length>0?out:undefined}export function assertHeaderValue(value,role){if(typeof value!=="string"||/[\r\n\0]/.test(value))throw new Error(`Email ${role} contains forbidden header characters`)}export function isHeaderName(name){return/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)}
@@ -1 +1 @@
1
- import{db}from"@stacksjs/database/runtime";let warnedAboutMissingTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=!0;console.warn("[email/webhook-dedup] email_webhook_events table missing - webhook idempotency NOT enforced. Providers may double-deliver retries; run migrations to enable dedup.")}function isMissingTableError(err){const msg=err?.message??"";return msg.includes("no such table")||msg.includes("doesn't exist")}export async function recordWebhookEventOrSkip(provider,eventId){if(!eventId)return!0;try{await db.insertInto("email_webhook_events").values({provider,event_id:eventId,processed_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute();return!0}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return!0}const msg=err?.message??"";if(msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry"))return!1;throw err}}
1
+ import{db}from"@stacksjs/database/runtime";let warnedAboutMissingTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=true;console.warn("[email/webhook-dedup] email_webhook_events table missing - webhook idempotency NOT enforced. "+"Providers may double-deliver retries; run migrations to enable dedup.")}function isMissingTableError(err){const msg=err?.message??"";return msg.includes("no such table")||msg.includes("doesn't exist")}export async function recordWebhookEventOrSkip(provider,eventId){if(!eventId)return true;try{await db.insertInto("email_webhook_events").values({provider,event_id:eventId,processed_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute();return true}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return true}const msg=err?.message??"";if(msg.includes("UNIQUE constraint")||msg.includes("Duplicate entry"))return false;throw err}}
@@ -1 +1 @@
1
- import{suppress}from"./suppression";import{recordWebhookEventOrSkip}from"./webhook-dedup";import{emitEmailBounceHard,emitEmailBounceSoft,emitEmailComplaint,emitEmailUnsubscribe,suppressionTypeFor}from"./webhook-events";import{verifyMailgunSignature,verifyPostmarkAuth,verifySendgridSignature,verifySesSnsSignature}from"./webhook-signatures";const OK_DUPLICATE={status:200,body:{ok:!0,processed:!1,reason:"duplicate"}};function unauthorized(reason){return{status:401,body:{ok:!1,reason}}}function badRequest(reason){return{status:400,body:{ok:!1,reason}}}async function dispatchClassifiedEvent(classification,payload){const suppressionType=suppressionTypeFor(classification);if(suppressionType)await suppress(payload.email,suppressionType,payload.reason);switch(classification){case"bounce-hard":await emitEmailBounceHard(payload);break;case"bounce-soft":await emitEmailBounceSoft(payload);break;case"complaint":await emitEmailComplaint(payload);break;case"unsubscribe":await emitEmailUnsubscribe(payload);break;case"delivered":break}}export async function handleMailgunWebhook(rawBody,config){let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const sig=parsed.signature,event=parsed["event-data"];if(!sig||!event)return badRequest("missing-fields");const v=verifyMailgunSignature({timestamp:sig.timestamp,token:sig.token,signature:sig.signature,signingKey:config.signingKey,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);if(!await recordWebhookEventOrSkip("mailgun",event.id))return OK_DUPLICATE;const classification=classifyMailgunEvent(event.event,event.severity);if(!classification)return{status:200,body:{ok:!0,processed:!1,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email:event.recipient,provider:"mailgun",reason:event.reason,raw:event});return{status:200,body:{ok:!0,processed:!0,classification}}}function classifyMailgunEvent(event,severity){switch(event){case"failed":return severity==="temporary"?"bounce-soft":"bounce-hard";case"complained":return"complaint";case"unsubscribed":return"unsubscribe";case"delivered":return"delivered";default:return null}}export async function handlePostmarkWebhook(rawBody,authorizationHeader,sourceIp,config){const v=verifyPostmarkAuth({authorizationHeader,expectedUsername:config.username,expectedPassword:config.password,sourceIp,ipAllowlist:config.ipAllowlist});if(!v.ok)return unauthorized(v.reason);let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const eventId=String(parsed.ID??parsed.MessageID??""),email=String(parsed.Email??parsed.Recipient??"");if(!email)return badRequest("missing-recipient");if(!await recordWebhookEventOrSkip("postmark",eventId))return OK_DUPLICATE;const classification=classifyPostmarkEvent(parsed);if(!classification)return{status:200,body:{ok:!0,processed:!1,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email,provider:"postmark",reason:parsed.Description,raw:parsed});return{status:200,body:{ok:!0,processed:!0,classification}}}function classifyPostmarkEvent(msg){switch(msg.RecordType){case"Bounce":return msg.TypeCode===1?"bounce-hard":"bounce-soft";case"SpamComplaint":return"complaint";case"SubscriptionChange":return msg.SuppressSending?"unsubscribe":null;case"Delivery":return"delivered";default:return null}}export async function handleSesWebhook(rawBody,config={}){let snsMessage;try{snsMessage=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const v=await verifySesSnsSignature({message:snsMessage,certUrlHostAllowlist:config.certUrlHostAllowlist,fetchCert:config.fetchCert});if(!v.ok)return unauthorized(v.reason);if(snsMessage.Type==="SubscriptionConfirmation"){if(config.autoConfirmSubscriptions!==!1&&snsMessage.SubscribeURL)try{await fetch(snsMessage.SubscribeURL)}catch{}return{status:200,body:{ok:!0,processed:!0,reason:"subscription-confirmed"}}}if(snsMessage.Type==="UnsubscribeConfirmation")return{status:200,body:{ok:!0,processed:!0,reason:"subscription-removed"}};let innerMessage;try{innerMessage=JSON.parse(snsMessage.Message)}catch{return badRequest("invalid-inner-json")}if(!await recordWebhookEventOrSkip("ses",snsMessage.MessageId))return OK_DUPLICATE;const dispatched=[];if(innerMessage.notificationType==="Bounce"&&innerMessage.bounce){const classification=innerMessage.bounce.bounceType==="Permanent"?"bounce-hard":"bounce-soft";for(const r of innerMessage.bounce.bouncedRecipients){await dispatchClassifiedEvent(classification,{email:r.emailAddress,provider:"ses",reason:r.diagnosticCode,raw:innerMessage});dispatched.push(classification)}}else if(innerMessage.notificationType==="Complaint"&&innerMessage.complaint)for(const r of innerMessage.complaint.complainedRecipients){await dispatchClassifiedEvent("complaint",{email:r.emailAddress,provider:"ses",reason:innerMessage.complaint.complaintFeedbackType,raw:innerMessage});dispatched.push("complaint")}else if(innerMessage.notificationType==="Delivery"&&innerMessage.delivery)for(const r of innerMessage.delivery.recipients){await dispatchClassifiedEvent("delivered",{email:r,provider:"ses",raw:innerMessage});dispatched.push("delivered")}return{status:200,body:{ok:!0,processed:dispatched.length>0,classification:dispatched[0]}}}export async function handleSendgridWebhook(rawBody,signatureHeader,timestampHeader,config){const v=verifySendgridSignature({body:rawBody,signature:signatureHeader,timestamp:timestampHeader,publicKeyPem:config.publicKeyPem,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);let events;try{events=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}if(!Array.isArray(events))return badRequest("expected-array");let processed=0;const classifications=[];for(const ev of events){if(!ev.email)continue;const id=ev.sg_event_id??`${ev.event}:${ev.email}:${Date.now()}`;if(!await recordWebhookEventOrSkip("sendgrid",id))continue;const classification=classifySendgridEvent(ev.event,ev.type);if(!classification)continue;await dispatchClassifiedEvent(classification,{email:ev.email,provider:"sendgrid",reason:ev.reason,raw:ev});processed++;classifications.push(classification)}return{status:200,body:{ok:!0,processed:processed>0,classification:classifications[0]}}}function classifySendgridEvent(event,type){switch(event){case"bounce":return type==="blocked"?"bounce-soft":"bounce-hard";case"dropped":return"bounce-hard";case"spamreport":return"complaint";case"unsubscribe":return"unsubscribe";case"group_unsubscribe":return"unsubscribe";case"delivered":return"delivered";default:return null}}
1
+ import{suppress}from"./suppression";import{recordWebhookEventOrSkip}from"./webhook-dedup";import{emitEmailBounceHard,emitEmailBounceSoft,emitEmailComplaint,emitEmailUnsubscribe,suppressionTypeFor}from"./webhook-events";import{verifyMailgunSignature,verifyPostmarkAuth,verifySendgridSignature,verifySesSnsSignature}from"./webhook-signatures";const OK_DUPLICATE={status:200,body:{ok:true,processed:false,reason:"duplicate"}};function unauthorized(reason){return{status:401,body:{ok:false,reason}}}function badRequest(reason){return{status:400,body:{ok:false,reason}}}async function dispatchClassifiedEvent(classification,payload){const suppressionType=suppressionTypeFor(classification);if(suppressionType){await suppress(payload.email,suppressionType,payload.reason)}switch(classification){case"bounce-hard":await emitEmailBounceHard(payload);break;case"bounce-soft":await emitEmailBounceSoft(payload);break;case"complaint":await emitEmailComplaint(payload);break;case"unsubscribe":await emitEmailUnsubscribe(payload);break;case"delivered":break}}export async function handleMailgunWebhook(rawBody,config){let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const sig=parsed.signature;const event=parsed["event-data"];if(!sig||!event)return badRequest("missing-fields");const v=verifyMailgunSignature({timestamp:sig.timestamp,token:sig.token,signature:sig.signature,signingKey:config.signingKey,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);const fresh=await recordWebhookEventOrSkip("mailgun",event.id);if(!fresh)return OK_DUPLICATE;const classification=classifyMailgunEvent(event.event,event.severity);if(!classification)return{status:200,body:{ok:true,processed:false,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email:event.recipient,provider:"mailgun",reason:event.reason,raw:event});return{status:200,body:{ok:true,processed:true,classification}}}function classifyMailgunEvent(event,severity){switch(event){case"failed":return severity==="temporary"?"bounce-soft":"bounce-hard";case"complained":return"complaint";case"unsubscribed":return"unsubscribe";case"delivered":return"delivered";default:return null}}export async function handlePostmarkWebhook(rawBody,authorizationHeader,sourceIp,config){const v=verifyPostmarkAuth({authorizationHeader,expectedUsername:config.username,expectedPassword:config.password,sourceIp,ipAllowlist:config.ipAllowlist});if(!v.ok)return unauthorized(v.reason);let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const eventId=String(parsed.ID??parsed.MessageID??"");const email=String(parsed.Email??parsed.Recipient??"");if(!email)return badRequest("missing-recipient");const fresh=await recordWebhookEventOrSkip("postmark",eventId);if(!fresh)return OK_DUPLICATE;const classification=classifyPostmarkEvent(parsed);if(!classification)return{status:200,body:{ok:true,processed:false,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email,provider:"postmark",reason:parsed.Description,raw:parsed});return{status:200,body:{ok:true,processed:true,classification}}}function classifyPostmarkEvent(msg){switch(msg.RecordType){case"Bounce":return msg.TypeCode===1?"bounce-hard":"bounce-soft";case"SpamComplaint":return"complaint";case"SubscriptionChange":return msg.SuppressSending?"unsubscribe":null;case"Delivery":return"delivered";default:return null}}export async function handleSesWebhook(rawBody,config={}){let snsMessage;try{snsMessage=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const v=await verifySesSnsSignature({message:snsMessage,certUrlHostAllowlist:config.certUrlHostAllowlist,fetchCert:config.fetchCert});if(!v.ok)return unauthorized(v.reason);if(snsMessage.Type==="SubscriptionConfirmation"){if(config.autoConfirmSubscriptions!==false&&snsMessage.SubscribeURL){try{await fetch(snsMessage.SubscribeURL)}catch{}}return{status:200,body:{ok:true,processed:true,reason:"subscription-confirmed"}}}if(snsMessage.Type==="UnsubscribeConfirmation"){return{status:200,body:{ok:true,processed:true,reason:"subscription-removed"}}}let innerMessage;try{innerMessage=JSON.parse(snsMessage.Message)}catch{return badRequest("invalid-inner-json")}const fresh=await recordWebhookEventOrSkip("ses",snsMessage.MessageId);if(!fresh)return OK_DUPLICATE;const dispatched=[];if(innerMessage.notificationType==="Bounce"&&innerMessage.bounce){const classification=innerMessage.bounce.bounceType==="Permanent"?"bounce-hard":"bounce-soft";for(const r of innerMessage.bounce.bouncedRecipients){await dispatchClassifiedEvent(classification,{email:r.emailAddress,provider:"ses",reason:r.diagnosticCode,raw:innerMessage});dispatched.push(classification)}}else if(innerMessage.notificationType==="Complaint"&&innerMessage.complaint){for(const r of innerMessage.complaint.complainedRecipients){await dispatchClassifiedEvent("complaint",{email:r.emailAddress,provider:"ses",reason:innerMessage.complaint.complaintFeedbackType,raw:innerMessage});dispatched.push("complaint")}}else if(innerMessage.notificationType==="Delivery"&&innerMessage.delivery){for(const r of innerMessage.delivery.recipients){await dispatchClassifiedEvent("delivered",{email:r,provider:"ses",raw:innerMessage});dispatched.push("delivered")}}return{status:200,body:{ok:true,processed:dispatched.length>0,classification:dispatched[0]}}}export async function handleSendgridWebhook(rawBody,signatureHeader,timestampHeader,config){const v=verifySendgridSignature({body:rawBody,signature:signatureHeader,timestamp:timestampHeader,publicKeyPem:config.publicKeyPem,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);let events;try{events=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}if(!Array.isArray(events))return badRequest("expected-array");let processed=0;const classifications=[];for(const ev of events){if(!ev.email)continue;const id=ev.sg_event_id??`${ev.event}:${ev.email}:${Date.now()}`;const fresh=await recordWebhookEventOrSkip("sendgrid",id);if(!fresh)continue;const classification=classifySendgridEvent(ev.event,ev.type);if(!classification)continue;await dispatchClassifiedEvent(classification,{email:ev.email,provider:"sendgrid",reason:ev.reason,raw:ev});processed++;classifications.push(classification)}return{status:200,body:{ok:true,processed:processed>0,classification:classifications[0]}}}function classifySendgridEvent(event,type){switch(event){case"bounce":return type==="blocked"?"bounce-soft":"bounce-hard";case"dropped":return"bounce-hard";case"spamreport":return"complaint";case"unsubscribe":return"unsubscribe";case"group_unsubscribe":return"unsubscribe";case"delivered":return"delivered";default:return null}}
@@ -1,2 +1,2 @@
1
- import{createHmac,createVerify,timingSafeEqual}from"node:crypto";import{Buffer}from"node:buffer";export function verifyMailgunSignature(input){if(!input.signingKey)return{ok:!1,reason:"missing-config"};if(!input.timestamp||!input.token||!input.signature)return{ok:!1,reason:"missing-signature"};const tolerance=input.toleranceSeconds??300,ts=Number(input.timestamp);if(!Number.isFinite(ts))return{ok:!1,reason:"bad-signature"};const now=Math.floor(Date.now()/1000);if(Math.abs(now-ts)>tolerance)return{ok:!1,reason:"expired"};const expected=createHmac("sha256",input.signingKey).update(`${input.timestamp}${input.token}`).digest("hex");let provided;try{provided=Buffer.from(input.signature,"hex")}catch{return{ok:!1,reason:"bad-signature"}}const expectedBuf=Buffer.from(expected,"hex");if(provided.length!==expectedBuf.length)return{ok:!1,reason:"bad-signature"};if(!timingSafeEqual(provided,expectedBuf))return{ok:!1,reason:"bad-signature"};return{ok:!0}}export function verifyPostmarkAuth(input){if(!input.expectedUsername||!input.expectedPassword)return{ok:!1,reason:"missing-config"};if(!input.authorizationHeader||!input.authorizationHeader.startsWith("Basic "))return{ok:!1,reason:"missing-signature"};let decoded;try{decoded=Buffer.from(input.authorizationHeader.slice(6),"base64").toString("utf8")}catch{return{ok:!1,reason:"bad-signature"}}const[user,pass]=decoded.split(":");if(!user||pass===void 0)return{ok:!1,reason:"bad-signature"};const userMatch=safeStringEquals(user,input.expectedUsername),passMatch=safeStringEquals(pass,input.expectedPassword);if(!userMatch||!passMatch)return{ok:!1,reason:"bad-signature"};if(input.ipAllowlist&&input.ipAllowlist.length>0){if(!input.sourceIp||!input.ipAllowlist.includes(input.sourceIp))return{ok:!1,reason:"bad-signature"}}return{ok:!0}}function safeStringEquals(a,b){const aBuf=Buffer.from(a,"utf8"),bBuf=Buffer.from(b,"utf8");if(aBuf.length!==bBuf.length){const dummy=Buffer.alloc(Math.max(aBuf.length,bBuf.length));timingSafeEqual(dummy,dummy);return!1}return timingSafeEqual(aBuf,bBuf)}const DEFAULT_SNS_HOST_ALLOWLIST=/^sns\.[a-z0-9-]+\.amazonaws\.com$/;async function defaultCertFetcher(url){const res=await fetch(url,{redirect:"error"});if(!res.ok)throw Error(`SNS cert fetch returned ${res.status}`);return await res.text()}export async function verifySesSnsSignature(input){const msg=input.message;if(!msg||!msg.Signature||!msg.SigningCertURL)return{ok:!1,reason:"missing-signature"};const allowlist=input.certUrlHostAllowlist??DEFAULT_SNS_HOST_ALLOWLIST;let certUrl;try{certUrl=new URL(msg.SigningCertURL)}catch{return{ok:!1,reason:"untrusted-cert-url"}}if(certUrl.protocol!=="https:")return{ok:!1,reason:"untrusted-cert-url"};if(!allowlist.test(certUrl.host))return{ok:!1,reason:"untrusted-cert-url"};let certPem;try{certPem=await(input.fetchCert??defaultCertFetcher)(msg.SigningCertURL)}catch{return{ok:!1,reason:"cert-fetch-failed"}}const canonical=canonicalSnsString(msg);if(!canonical)return{ok:!1,reason:"bad-signature"};let sigBuf;try{sigBuf=Buffer.from(msg.Signature,"base64")}catch{return{ok:!1,reason:"bad-signature"}}const algo=msg.SignatureVersion==="2"?"SHA256":"SHA1",verifier=createVerify(`RSA-${algo}`);verifier.update(canonical,"utf8");return verifier.verify(certPem,sigBuf)?{ok:!0}:{ok:!1,reason:"bad-signature"}}function canonicalSnsString(msg){const fields=[];if(msg.Type==="Notification"){fields.push("Message",msg.Message);fields.push("MessageId",msg.MessageId);if(msg.Subject!==void 0)fields.push("Subject",msg.Subject);fields.push("Timestamp",msg.Timestamp);fields.push("TopicArn",msg.TopicArn);fields.push("Type",msg.Type)}else if(msg.Type==="SubscriptionConfirmation"||msg.Type==="UnsubscribeConfirmation"){fields.push("Message",msg.Message);fields.push("MessageId",msg.MessageId);if(!msg.SubscribeURL||!msg.Token)return null;fields.push("SubscribeURL",msg.SubscribeURL);fields.push("Timestamp",msg.Timestamp);fields.push("Token",msg.Token);fields.push("TopicArn",msg.TopicArn);fields.push("Type",msg.Type)}else return null;let out="";for(const f of fields)out+=`${f}
2
- `;return out}export function verifySendgridSignature(input){if(!input.publicKeyPem)return{ok:!1,reason:"missing-config"};if(!input.signature||!input.timestamp)return{ok:!1,reason:"missing-signature"};const tolerance=input.toleranceSeconds??300,ts=Number(input.timestamp);if(!Number.isFinite(ts))return{ok:!1,reason:"bad-signature"};if(Math.abs(Math.floor(Date.now()/1000)-ts)>tolerance)return{ok:!1,reason:"expired"};let sigBuf;try{sigBuf=Buffer.from(input.signature,"base64")}catch{return{ok:!1,reason:"bad-signature"}}const verifier=createVerify("SHA256");verifier.update(`${input.timestamp}${input.body}`,"utf8");return verifier.verify(input.publicKeyPem,sigBuf)?{ok:!0}:{ok:!1,reason:"bad-signature"}}
1
+ import{createHmac,createVerify,timingSafeEqual}from"node:crypto";import{Buffer}from"node:buffer";export function verifyMailgunSignature(input){if(!input.signingKey)return{ok:false,reason:"missing-config"};if(!input.timestamp||!input.token||!input.signature)return{ok:false,reason:"missing-signature"};const tolerance=input.toleranceSeconds??300;const ts=Number(input.timestamp);if(!Number.isFinite(ts))return{ok:false,reason:"bad-signature"};const now=Math.floor(Date.now()/1000);if(Math.abs(now-ts)>tolerance)return{ok:false,reason:"expired"};const expected=createHmac("sha256",input.signingKey).update(`${input.timestamp}${input.token}`).digest("hex");let provided;try{provided=Buffer.from(input.signature,"hex")}catch{return{ok:false,reason:"bad-signature"}}const expectedBuf=Buffer.from(expected,"hex");if(provided.length!==expectedBuf.length)return{ok:false,reason:"bad-signature"};if(!timingSafeEqual(provided,expectedBuf))return{ok:false,reason:"bad-signature"};return{ok:true}}export function verifyPostmarkAuth(input){if(!input.expectedUsername||!input.expectedPassword)return{ok:false,reason:"missing-config"};if(!input.authorizationHeader||!input.authorizationHeader.startsWith("Basic "))return{ok:false,reason:"missing-signature"};let decoded;try{decoded=Buffer.from(input.authorizationHeader.slice(6),"base64").toString("utf8")}catch{return{ok:false,reason:"bad-signature"}}const[user,pass]=decoded.split(":");if(!user||pass===undefined)return{ok:false,reason:"bad-signature"};const userMatch=safeStringEquals(user,input.expectedUsername);const passMatch=safeStringEquals(pass,input.expectedPassword);if(!userMatch||!passMatch)return{ok:false,reason:"bad-signature"};if(input.ipAllowlist&&input.ipAllowlist.length>0){if(!input.sourceIp||!input.ipAllowlist.includes(input.sourceIp))return{ok:false,reason:"bad-signature"}}return{ok:true}}function safeStringEquals(a,b){const aBuf=Buffer.from(a,"utf8");const bBuf=Buffer.from(b,"utf8");if(aBuf.length!==bBuf.length){const dummy=Buffer.alloc(Math.max(aBuf.length,bBuf.length));timingSafeEqual(dummy,dummy);return false}return timingSafeEqual(aBuf,bBuf)}const DEFAULT_SNS_HOST_ALLOWLIST=/^sns\.[a-z0-9-]+\.amazonaws\.com$/;async function defaultCertFetcher(url){const res=await fetch(url,{redirect:"error"});if(!res.ok)throw new Error(`SNS cert fetch returned ${res.status}`);return await res.text()}export async function verifySesSnsSignature(input){const msg=input.message;if(!msg||!msg.Signature||!msg.SigningCertURL)return{ok:false,reason:"missing-signature"};const allowlist=input.certUrlHostAllowlist??DEFAULT_SNS_HOST_ALLOWLIST;let certUrl;try{certUrl=new URL(msg.SigningCertURL)}catch{return{ok:false,reason:"untrusted-cert-url"}}if(certUrl.protocol!=="https:")return{ok:false,reason:"untrusted-cert-url"};if(!allowlist.test(certUrl.host))return{ok:false,reason:"untrusted-cert-url"};let certPem;try{certPem=await(input.fetchCert??defaultCertFetcher)(msg.SigningCertURL)}catch{return{ok:false,reason:"cert-fetch-failed"}}const canonical=canonicalSnsString(msg);if(!canonical)return{ok:false,reason:"bad-signature"};let sigBuf;try{sigBuf=Buffer.from(msg.Signature,"base64")}catch{return{ok:false,reason:"bad-signature"}}const algo=msg.SignatureVersion==="2"?"SHA256":"SHA1";const verifier=createVerify(`RSA-${algo}`);verifier.update(canonical,"utf8");const valid=verifier.verify(certPem,sigBuf);return valid?{ok:true}:{ok:false,reason:"bad-signature"}}function canonicalSnsString(msg){const fields=[];if(msg.Type==="Notification"){fields.push("Message",msg.Message);fields.push("MessageId",msg.MessageId);if(msg.Subject!==undefined)fields.push("Subject",msg.Subject);fields.push("Timestamp",msg.Timestamp);fields.push("TopicArn",msg.TopicArn);fields.push("Type",msg.Type)}else if(msg.Type==="SubscriptionConfirmation"||msg.Type==="UnsubscribeConfirmation"){fields.push("Message",msg.Message);fields.push("MessageId",msg.MessageId);if(!msg.SubscribeURL||!msg.Token)return null;fields.push("SubscribeURL",msg.SubscribeURL);fields.push("Timestamp",msg.Timestamp);fields.push("Token",msg.Token);fields.push("TopicArn",msg.TopicArn);fields.push("Type",msg.Type)}else{return null}let out="";for(const f of fields)out+=`${f}
2
+ `;return out}export function verifySendgridSignature(input){if(!input.publicKeyPem)return{ok:false,reason:"missing-config"};if(!input.signature||!input.timestamp)return{ok:false,reason:"missing-signature"};const tolerance=input.toleranceSeconds??300;const ts=Number(input.timestamp);if(!Number.isFinite(ts))return{ok:false,reason:"bad-signature"};if(Math.abs(Math.floor(Date.now()/1000)-ts)>tolerance)return{ok:false,reason:"expired"};let sigBuf;try{sigBuf=Buffer.from(input.signature,"base64")}catch{return{ok:false,reason:"bad-signature"}}const verifier=createVerify("SHA256");verifier.update(`${input.timestamp}${input.body}`,"utf8");const valid=verifier.verify(input.publicKeyPem,sigBuf);return valid?{ok:true}:{ok:false,reason:"bad-signature"}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/email",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.514",
5
+ "version": "0.75.518",
6
6
  "description": "The Stacks Email integration. Painlessly create & manage your inboxes, templates, and send emails.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -61,26 +61,26 @@
61
61
  "prepublishOnly": "bun run build"
62
62
  },
63
63
  "dependencies": {
64
- "@stacksjs/config": "0.75.514",
65
- "@stacksjs/database": "0.75.514",
66
- "@stacksjs/events": "0.75.514",
67
- "@stacksjs/logging": "0.75.514",
64
+ "@stacksjs/config": "0.75.518",
65
+ "@stacksjs/database": "0.75.518",
66
+ "@stacksjs/events": "0.75.518",
67
+ "@stacksjs/logging": "0.75.518",
68
68
  "@stacksjs/mail": "^0.3.11",
69
- "@stacksjs/path": "0.75.514",
70
- "@stacksjs/storage": "0.75.514",
71
- "@stacksjs/strings": "0.75.514",
69
+ "@stacksjs/path": "0.75.518",
70
+ "@stacksjs/storage": "0.75.518",
71
+ "@stacksjs/strings": "0.75.518",
72
72
  "@stacksjs/stx": "0.2.807",
73
73
  "@stacksjs/ts-cloud": "^0.16.109",
74
- "@stacksjs/utils": "0.75.514"
74
+ "@stacksjs/utils": "0.75.518"
75
75
  },
76
76
  "devDependencies": {
77
- "@stacksjs/cli": "0.75.514",
78
- "@stacksjs/error-handling": "0.75.514",
79
- "@stacksjs/types": "0.75.514",
77
+ "@stacksjs/cli": "0.75.518",
78
+ "@stacksjs/error-handling": "0.75.518",
79
+ "@stacksjs/types": "0.75.518",
80
80
  "better-dx": "^0.2.24"
81
81
  },
82
82
  "peerDependencies": {
83
- "@stacksjs/queue": "0.75.514"
83
+ "@stacksjs/queue": "0.75.518"
84
84
  },
85
85
  "peerDependenciesMeta": {
86
86
  "@stacksjs/queue": {