@stacksjs/sms 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.
- package/dist/compliance.js +2 -2
- package/dist/drivers/twilio.js +1 -1
- package/dist/drivers/vonage.js +1 -1
- package/dist/inbound.js +1 -1
- package/dist/keywords.js +1 -1
- package/dist/opt-out.js +1 -1
- package/dist/sms.js +1 -1
- package/package.json +7 -7
package/dist/compliance.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createHmac,timingSafeEqual}from"node:crypto";import{SMS_KEYWORDS}from"./keywords";const allKeywords=(kind)=>Object.values(SMS_KEYWORDS).flatMap((set)=>set[kind].map((word)=>word.toUpperCase()))
|
|
2
|
-
|
|
1
|
+
import{createHmac,timingSafeEqual}from"node:crypto";import{SMS_KEYWORDS}from"./keywords";const allKeywords=(kind)=>Object.values(SMS_KEYWORDS).flatMap((set)=>set[kind].map((word)=>word.toUpperCase()));const DEFAULT_OPT_OUT=allKeywords("stop");const DEFAULT_OPT_IN=allKeywords("start");const DEFAULT_HELP=allKeywords("help");const GSM_7_BASIC=new Set(`@£$¥èéùìòÇ
|
|
2
|
+
Øø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà`);const GSM_7_EXTENDED=new Set("^{}\\[~]|€");function normalizedKeyword(body){return body.trim().split(/\s+/,1)[0]?.toUpperCase()??""}export function classifySmsIntent(body,options={}){const keyword=normalizedKeyword(body);const includes=(values,defaults)=>(values??defaults).some((value)=>value.trim().toUpperCase()===keyword);if(includes(options.optOut,DEFAULT_OPT_OUT))return{intent:"opt-out",keyword};if(includes(options.optIn,DEFAULT_OPT_IN))return{intent:"opt-in",keyword};if(includes(options.help,DEFAULT_HELP))return{intent:"help",keyword};return{intent:"message"}}export function smsComplianceReply(intent,options={}){const name=options.appName?.trim()||"This service";if(intent==="opt-out")return`${name}: you are unsubscribed. No more messages will be sent. Reply START to resubscribe.`;if(intent==="opt-in")return`${name}: you are resubscribed. Reply STOP to unsubscribe.`;if(intent==="help")return`${name}: reply STOP to unsubscribe or START to resubscribe.${options.helpContact?` Contact ${options.helpContact}.`:""}`;return null}export function parseTwilioInbound(fields,options={}){const body=fields.Body??"";return{from:fields.From??"",to:fields.To??"",body,messageId:fields.MessageSid??fields.SmsSid,...classifySmsIntent(body,options)}}export function verifyTwilioWebhook(url,fields,signature,authToken){if(!url||!signature||!authToken)return false;const payload=Object.keys(fields).sort().reduce((value,key)=>`${value}${key}${fields[key]??""}`,url);const expected=createHmac("sha1",authToken).update(payload).digest("base64");const expectedBuffer=Buffer.from(expected);const actualBuffer=Buffer.from(signature);if(expectedBuffer.length!==actualBuffer.length){timingSafeEqual(expectedBuffer,expectedBuffer);return false}return timingSafeEqual(expectedBuffer,actualBuffer)}export function estimateSmsSegments(body){let septets=0;let gsm7=true;for(const character of body){if(GSM_7_BASIC.has(character))septets+=1;else if(GSM_7_EXTENDED.has(character))septets+=2;else{gsm7=false;break}}if(gsm7){const perSegment=septets<=160?160:153;return{encoding:"gsm-7",characters:body.length,segments:Math.max(1,Math.ceil(septets/perSegment)),perSegment}}const characters=[...body].length;const perSegment=characters<=70?70:67;return{encoding:"ucs-2",characters,segments:Math.max(1,Math.ceil(characters/perSegment)),perSegment}}export function isWithinSmsQuietHours(at,options){const hour=Number(new Intl.DateTimeFormat("en-US",{hour:"numeric",hourCycle:"h23",timeZone:options.timezone??"UTC"}).format(at));const start=Math.min(23,Math.max(0,Math.floor(options.startHour)));const end=Math.min(23,Math.max(0,Math.floor(options.endHour)));if(start===end)return true;return start<end?hour>=start&&hour<end:hour>=start||hour<end}
|
package/dist/drivers/twilio.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const API_BASE="https://api.twilio.com/2010-04-01"
|
|
1
|
+
const API_BASE="https://api.twilio.com/2010-04-01";const VERIFY_API_BASE="https://verify.twilio.com/v2";async function fetchWithRetry(url,init,maxRetries=3){let attempt=0;while(true){const response=await fetch(url,init);if(response.status!==429&&response.status!==503)return response;if(attempt>=maxRetries)return response;const retryAfter=Number(response.headers.get("retry-after"))||2**attempt;await new Promise((r)=>setTimeout(r,Math.min(retryAfter,30)*1000));attempt++}}export class TwilioDriver{config;verifyServiceSid;constructor(config,verifyServiceSid){this.config=config;this.verifyServiceSid=verifyServiceSid}async send(message){const recipients=Array.isArray(message.to)?message.to:[message.to];if(recipients.length>1){const results=await this.sendBulk(recipients.map((to)=>({...message,to})));return results[0]??{success:false,to:recipients[0]??"",error:"No recipients supplied",provider:"twilio"}}const to=recipients[0];if(!to){return{success:false,to:"",error:"No recipient supplied",provider:"twilio"}}const from=message.from||this.config.from;if(!from&&!this.config.messagingServiceSid){return{success:false,to,error:'No "from" number or messaging service SID configured',provider:"twilio"}}try{const body=new URLSearchParams;body.append("To",to);body.append("Body",message.body);if(this.config.messagingServiceSid){body.append("MessagingServiceSid",this.config.messagingServiceSid)}else if(from){body.append("From",from)}if(message.statusCallback||this.config.statusCallback){body.append("StatusCallback",message.statusCallback||this.config.statusCallback)}if(message.mediaUrls&&message.mediaUrls.length>0){for(const mediaUrl of message.mediaUrls){body.append("MediaUrl",mediaUrl)}}const response=await fetchWithRetry(`${API_BASE}/Accounts/${this.config.accountSid}/Messages.json`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,to,error:data.message||`HTTP ${response.status}`,provider:"twilio"}}return{success:true,messageId:data.sid,status:mapTwilioStatus(data.status),to,provider:"twilio",segments:data.num_segments?Number.parseInt(data.num_segments,10):undefined,price:data.price?Math.abs(Number.parseFloat(data.price)):undefined,currency:data.price_unit}}catch(error){return{success:false,to,error:error instanceof Error?error.message:"Unknown error",provider:"twilio"}}}async sendBulk(messages){return Promise.all(messages.map((msg)=>this.send(msg)))}async getStatus(messageId){const response=await fetch(`${API_BASE}/Accounts/${this.config.accountSid}/Messages/${messageId}.json`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){throw new Error(`Twilio message status API error: ${response.status}`)}const data=await response.json();return{messageId:data.sid,to:data.to,status:mapTwilioStatus(data.status),timestamp:new Date(data.date_updated||data.date_created),errorCode:data.error_code?.toString(),errorMessage:data.error_message}}async verify(phoneNumber){try{const response=await fetch(`https://lookups.twilio.com/v2/PhoneNumbers/${encodeURIComponent(phoneNumber)}?Fields=line_type_intelligence`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){return{valid:false}}const data=await response.json();return{valid:data.valid,carrier:data.line_type_intelligence?.carrier_name,type:data.line_type_intelligence?.type}}catch{return{valid:false}}}async getBalance(){const response=await fetch(`${API_BASE}/Accounts/${this.config.accountSid}/Balance.json`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){throw new Error(`Twilio balance API error: ${response.status}`)}const data=await response.json();return{balance:Number.parseFloat(data.balance),currency:data.currency}}async startVerification(request){if(!this.verifyServiceSid){return{success:false,status:"denied",error:"Verify service SID not configured"}}try{const body=new URLSearchParams;body.append("To",request.to);body.append("Channel",request.channel||"sms");if(request.locale){body.append("Locale",request.locale)}if(request.customMessage){body.append("CustomMessage",request.customMessage)}const response=await fetch(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/Verifications`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.message||`HTTP ${response.status}`}}return{success:true,verificationId:data.sid,status:data.status==="pending"?"pending":"denied"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async checkVerification(request){if(!this.verifyServiceSid){return{success:false,status:"denied",error:"Verify service SID not configured"}}try{const body=new URLSearchParams;body.append("To",request.to);body.append("Code",request.code);const response=await fetch(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/VerificationCheck`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.message||`HTTP ${response.status}`}}return{success:data.status==="approved",verificationId:data.sid,status:data.status==="approved"?"approved":"denied"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async cancelVerification(verificationId){if(!this.verifyServiceSid){return false}try{const body=new URLSearchParams;body.append("Status","canceled");const response=await fetch(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/Verifications/${verificationId}`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});return response.ok}catch{return false}}}function mapTwilioStatus(status){const statusMap={queued:"queued",sending:"sending",sent:"sent",delivered:"delivered",undelivered:"undelivered",failed:"failed",canceled:"failed"};return statusMap[status]||"unknown"}export function createTwilioDriver(config,verifyServiceSid){return new TwilioDriver(config,verifyServiceSid)}export{TwilioDriver as default};
|
package/dist/drivers/vonage.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const API_BASE="https://rest.nexmo.com"
|
|
1
|
+
const API_BASE="https://rest.nexmo.com";const MESSAGES_API_BASE="https://api.nexmo.com/v1/messages";const _VERIFY_API_BASE="https://api.nexmo.com/verify";const VERIFY_V2_API_BASE="https://api.nexmo.com/v2/verify";export class VonageDriver{config;useMessagesApi;constructor(config,useMessagesApi=false){this.config=config;this.useMessagesApi=useMessagesApi}async send(message){const recipients=Array.isArray(message.to)?message.to:[message.to];if(recipients.length>1){const results=await this.sendBulk(recipients.map((to)=>({...message,to})));return results[0]??{success:false,to:recipients[0]??"",error:"No recipients supplied",provider:"vonage"}}const to=recipients[0];if(!to){return{success:false,to:"",error:"No recipient supplied",provider:"vonage"}}const from=message.from||this.config.from;if(!from){return{success:false,to,error:'No "from" number configured',provider:"vonage"}}if(!/^\+?[1-9]\d{1,14}$/.test(to)){return{success:false,to,error:`Invalid E.164 phone number: ${to}. Expected +<country><number> with 8-15 digits.`,provider:"vonage"}}try{if(this.useMessagesApi){return await this.sendWithMessagesApi(to,from,message)}return await this.sendWithSmsApi(to,from,message)}catch(error){return{success:false,to,error:error instanceof Error?error.message:"Unknown error",provider:"vonage"}}}async sendWithSmsApi(to,from,message){const body=new URLSearchParams;body.append("api_key",this.config.apiKey);body.append("api_secret",this.config.apiSecret);body.append("to",to);body.append("from",from);body.append("text",message.body);if(message.statusCallback){body.append("callback",message.statusCallback)}const response=await fetch(`${API_BASE}/sms/json`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});if(!response.ok){throw new Error(`Vonage SMS API error: ${response.status}`)}const data=await response.json();const[msg]=data.messages??[];if(msg){if(msg.status!=="0"){return{success:false,to,error:msg["error-text"]||`Status: ${msg.status}`,provider:"vonage"}}return{success:true,messageId:msg["message-id"],status:"sent",to,provider:"vonage",price:msg["message-price"]?Number.parseFloat(msg["message-price"]):undefined,currency:"EUR"}}return{success:false,to,error:"No response from Vonage",provider:"vonage"}}async sendWithMessagesApi(to,from,message){const headers={"Content-Type":"application/json"};let authHeader;if(this.config.applicationId&&this.config.privateKey){const jwt=await this.generateJwt();authHeader=`Bearer ${jwt}`}else{authHeader=`Basic ${btoa(`${this.config.apiKey}:${this.config.apiSecret}`)}`}headers.Authorization=authHeader;const body={message_type:"text",channel:"sms",to,from,text:message.body};if(message.statusCallback){body.webhook_url=message.statusCallback}const response=await fetch(MESSAGES_API_BASE,{method:"POST",headers,body:JSON.stringify(body)});const data=await response.json();if(!response.ok){return{success:false,to,error:data.title||data.detail||`HTTP ${response.status}`,provider:"vonage"}}return{success:true,messageId:data.message_uuid,status:"sent",to,provider:"vonage"}}async sendBulk(messages){return Promise.all(messages.map((msg)=>this.send(msg)))}async getStatus(messageId){const headers={};if(this.config.applicationId&&this.config.privateKey){const jwt=await this.generateJwt();headers.Authorization=`Bearer ${jwt}`}else{headers.Authorization=`Basic ${btoa(`${this.config.apiKey}:${this.config.apiSecret}`)}`}const response=await fetch(`${MESSAGES_API_BASE}/${messageId}`,{headers});if(!response.ok){throw new Error(`Vonage message status API error: ${response.status}`)}const data=await response.json();return{messageId:data.message_uuid,to:data.to,status:mapVonageStatus(data.status),timestamp:new Date(data.timestamp),errorCode:data.error?.code?.toString(),errorMessage:data.error?.reason}}async verify(phoneNumber){try{const body=new URLSearchParams;body.append("api_key",this.config.apiKey);body.append("api_secret",this.config.apiSecret);body.append("number",phoneNumber);const response=await fetch(`${API_BASE}/ni/basic/json`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});if(!response.ok){throw new Error(`Vonage number insight API error: ${response.status}`)}const data=await response.json();if(data.status!==0){return{valid:false}}return{valid:true,carrier:data.current_carrier?.name,type:data.current_carrier?.network_type}}catch{return{valid:false}}}async getBalance(){const auth=typeof Buffer!=="undefined"?Buffer.from(`${this.config.apiKey}:${this.config.apiSecret}`).toString("base64"):btoa(`${this.config.apiKey}:${this.config.apiSecret}`);const response=await fetch(`${API_BASE}/account/get-balance`,{headers:{Authorization:`Basic ${auth}`}});if(!response.ok){throw new Error(`Vonage balance API error: ${response.status}`)}const data=await response.json();return{balance:data.value,currency:"EUR"}}async startVerification(request){try{const headers={"Content-Type":"application/json"};if(this.config.applicationId&&this.config.privateKey){const jwt=await this.generateJwt();headers.Authorization=`Bearer ${jwt}`}else{headers.Authorization=`Basic ${btoa(`${this.config.apiKey}:${this.config.apiSecret}`)}`}const body={brand:this.config.from||"Verification",workflow:[{channel:request.channel==="whatsapp"?"whatsapp_interactive":"sms",to:request.to}]};if(request.codeLength){body.code_length=request.codeLength}if(request.locale){body.locale=request.locale}const response=await fetch(VERIFY_V2_API_BASE,{method:"POST",headers,body:JSON.stringify(body)});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.title||data.detail||`HTTP ${response.status}`}}return{success:true,verificationId:data.request_id,status:"pending"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async checkVerification(request){if(!request.verificationId){return{success:false,status:"denied",error:"Verification ID is required"}}try{const headers={"Content-Type":"application/json"};if(this.config.applicationId&&this.config.privateKey){const jwt=await this.generateJwt();headers.Authorization=`Bearer ${jwt}`}else{headers.Authorization=`Basic ${btoa(`${this.config.apiKey}:${this.config.apiSecret}`)}`}const response=await fetch(`${VERIFY_V2_API_BASE}/${request.verificationId}`,{method:"POST",headers,body:JSON.stringify({code:request.code})});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.title||data.detail||`HTTP ${response.status}`}}return{success:data.status==="completed",verificationId:request.verificationId,status:data.status==="completed"?"approved":"denied"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async cancelVerification(verificationId){try{const headers={};if(this.config.applicationId&&this.config.privateKey){const jwt=await this.generateJwt();headers.Authorization=`Bearer ${jwt}`}else{headers.Authorization=`Basic ${btoa(`${this.config.apiKey}:${this.config.apiSecret}`)}`}const response=await fetch(`${VERIFY_V2_API_BASE}/${verificationId}`,{method:"DELETE",headers});return response.ok}catch{return false}}async generateJwt(){if(!this.config.applicationId||!this.config.privateKey){throw new Error("Application ID and private key required for JWT auth")}const header={typ:"JWT",alg:"RS256"};const now=Math.floor(Date.now()/1000);const payload={application_id:this.config.applicationId,iat:now,exp:now+900,jti:crypto.randomUUID()};const encodedHeader=btoa(JSON.stringify(header));const encodedPayload=btoa(JSON.stringify(payload));return`${encodedHeader}.${encodedPayload}.signature`}}function mapVonageStatus(status){const statusMap={submitted:"queued",delivered:"delivered",expired:"undelivered",failed:"failed",rejected:"failed",accepted:"sent"};return statusMap[status]||"unknown"}export function createVonageDriver(config,useMessagesApi=false){return new VonageDriver(config,useMessagesApi)}export{VonageDriver as default};
|
package/dist/inbound.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{verifyTwilioWebhook}from"./compliance";import{inboundSmsReply,matchSmsKeyword,PROVIDER_HANDLED_LOCALE}from"./keywords";import{normalizePhone,optInPhone,optOutPhone}from"./opt-out";function twiml(message){const escaped=message?.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])
|
|
1
|
+
import process from"node:process";import{verifyTwilioWebhook}from"./compliance";import{inboundSmsReply,matchSmsKeyword,PROVIDER_HANDLED_LOCALE}from"./keywords";import{normalizePhone,optInPhone,optOutPhone}from"./opt-out";function twiml(message){const escaped=message?.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c]);const body=escaped?`<?xml version="1.0" encoding="UTF-8"?><Response><Message>${escaped}</Message></Response>`:'<?xml version="1.0" encoding="UTF-8"?><Response></Response>';return new Response(body,{status:200,headers:{"Content-Type":"text/xml; charset=utf-8"}})}function signedUrl(request,publicUrl){if(publicUrl)return publicUrl;const url=new URL(request.url,"http://localhost");const base=String(process.env.APP_URL||"").replace(/\/$/,"");return base?`${base}${url.pathname}${url.search}`:url.href}export function inboundSmsKind(fields){const optOutType=String(fields.OptOutType||"").toUpperCase();const match=matchSmsKeyword(fields.Body??"");if(optOutType==="STOP"||optOutType==="START"||optOutType==="HELP"){const kind=optOutType.toLowerCase();return{...match.kind===kind?match:{keyword:match.keyword},kind,providerHandled:true}}return{...match,providerHandled:match.locale===PROVIDER_HANDLED_LOCALE}}function shouldReply(match,reply){if(match.kind==="message"||!reply)return false;return reply===true||!match.providerHandled}export async function handleTwilioInbound(request,options={}){const authToken=options.authToken??process.env.TWILIO_AUTH_TOKEN??"";if(!authToken)return new Response("Inbound SMS is not configured",{status:503});const fields={};for(const[key,value]of new URLSearchParams(await request.text()))fields[key]=value;const signature=request.headers.get("x-twilio-signature")||"";if(!verifyTwilioWebhook(signedUrl(request,options.publicUrl),fields,signature,authToken))return new Response("Invalid signature",{status:403});const from=normalizePhone(fields.From??"");if(!from)return twiml();const match=inboundSmsKind(fields);const{kind}=match;if(kind==="stop")await optOutPhone(from);if(kind==="start")await optInPhone(from);if(kind==="stop"||kind==="start")await options.onConsentChange?.({phone:from,kind,...match.locale?{locale:match.locale}:{}});await options.onMessage?.({from,to:fields.To??"",body:fields.Body??"",messageId:fields.MessageSid??fields.SmsSid,kind,...match.locale?{locale:match.locale}:{}});return twiml(shouldReply(match,options.reply)?inboundSmsReply(kind,{...options,locale:match.locale}):undefined)}
|
package/dist/keywords.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const SMS_KEYWORDS={en:{stop:["stop","stopall","unsubscribe","cancel","end","quit"],start:["start","yes","unstop"],help:["help","info"]},de:{stop:["stopp","abmelden","abbestellen"],start:["starten"],help:["hilfe"]}}
|
|
1
|
+
export const SMS_KEYWORDS={en:{stop:["stop","stopall","unsubscribe","cancel","end","quit"],start:["start","yes","unstop"],help:["help","info"]},de:{stop:["stopp","abmelden","abbestellen"],start:["starten"],help:["hilfe"]}};export const PROVIDER_HANDLED_LOCALE="en";export function matchSmsKeyword(body,locales=Object.keys(SMS_KEYWORDS)){const word=String(body??"").trim().toLowerCase().split(/\s+/)[0]??"";if(!word)return{kind:"message"};for(const kind of["stop","start","help"]){for(const locale of locales){if(SMS_KEYWORDS[locale]?.[kind].includes(word))return{kind,locale,keyword:word}}}return{kind:"message"}}const REPLIES={en:{stop:(name)=>`You are unsubscribed from ${name} texts. No more messages will be sent. Reply START to resubscribe.`,start:(name)=>`You are resubscribed to ${name} texts. Reply STOP to unsubscribe.`,help:(name,contact)=>`${name}: reply STOP to unsubscribe, START to resubscribe.${contact?` Contact: ${contact}`:""}`},de:{stop:(name)=>`Du bist von den SMS von ${name} abgemeldet und bekommst keine weiteren. Antworte STARTEN, um sie wieder zu erhalten.`,start:(name)=>`Du bekommst wieder SMS von ${name}. Antworte STOPP zum Abmelden.`,help:(name,contact)=>`${name}: Antworte STOPP zum Abmelden oder STARTEN zum erneuten Anmelden.${contact?` Kontakt: ${contact}`:""}`}};export function inboundSmsReply(kind,options={}){if(kind==="message")return;const base=String(options.locale||"").toLowerCase().split(/[-_]/)[0]??"";const copy=REPLIES[base]??REPLIES.en;const name=options.appName??(base==="de"?"diesem Dienst":"this service");return copy[kind](name,options.helpContact)}
|
package/dist/opt-out.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,sqlDateTime}from"@stacksjs/database/runtime";import{inboundSmsReply,matchSmsKeyword}from"./keywords";export function normalizePhone(raw){const digits=raw.replace(/[^\d+]/g,"");if(/^\d{10}$/.test(digits))return`+1${digits}`;if(/^1\d{10}$/.test(digits))return`+${digits}`;return digits}export function classifyInboundSms(body){return matchSmsKeyword(body).kind}export async function optOutPhone(phone,reason="stop-keyword"){const normalized=normalizePhone(phone);if(!normalized)return;const now=sqlDateTime(new Date);await db.insertOrIgnore("sms_opt_outs",{phone:normalized,reason,opted_out_at:now,created_at:now,updated_at:now})}export async function optInPhone(phone){const normalized=normalizePhone(phone);if(!normalized)return;await db.deleteFrom("sms_opt_outs").where("phone","=",normalized).execute()}export async function isPhoneOptedOut(phone){const normalized=normalizePhone(phone);if(!normalized)return
|
|
1
|
+
import{db,sqlDateTime}from"@stacksjs/database/runtime";import{inboundSmsReply,matchSmsKeyword}from"./keywords";export function normalizePhone(raw){const digits=raw.replace(/[^\d+]/g,"");if(/^\d{10}$/.test(digits))return`+1${digits}`;if(/^1\d{10}$/.test(digits))return`+${digits}`;return digits}export function classifyInboundSms(body){return matchSmsKeyword(body).kind}export async function optOutPhone(phone,reason="stop-keyword"){const normalized=normalizePhone(phone);if(!normalized)return;const now=sqlDateTime(new Date);await db.insertOrIgnore("sms_opt_outs",{phone:normalized,reason,opted_out_at:now,created_at:now,updated_at:now})}export async function optInPhone(phone){const normalized=normalizePhone(phone);if(!normalized)return;await db.deleteFrom("sms_opt_outs").where("phone","=",normalized).execute()}export async function isPhoneOptedOut(phone){const normalized=normalizePhone(phone);if(!normalized)return false;const row=await db.selectFrom("sms_opt_outs").where("phone","=",normalized).select(["id"]).executeTakeFirst();return!!row}export async function handleInboundSms(input,options={}){const{kind,locale}=matchSmsKeyword(input.body);if(kind==="stop")await optOutPhone(input.from);if(kind==="start")await optInPhone(input.from);const reply=inboundSmsReply(kind,{...options,locale});return reply?{kind,reply}:{kind}}
|
package/dist/sms.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TwilioDriver}from"./drivers/twilio";import{VonageDriver}from"./drivers/vonage";let defaultDriver=null
|
|
1
|
+
import{TwilioDriver}from"./drivers/twilio";import{VonageDriver}from"./drivers/vonage";let defaultDriver=null;let verificationDriver=null;let smsConfig={};let configuredOverrides={};let _configPromise=null;async function loadConfig(){const{config,overridesReady}=await import("@stacksjs/config/runtime");await overridesReady;smsConfig={...config.sms,...configuredOverrides}}async function ensureConfig(){if(!_configPromise){_configPromise=loadConfig()}await _configPromise}export function configure(config){configuredOverrides={...configuredOverrides,...config};smsConfig={...smsConfig,...config};defaultDriver=null;verificationDriver=null}export function getDriver(provider){const targetProvider=provider||smsConfig.provider||"twilio";switch(targetProvider){case"twilio":{const twilioConfig=smsConfig.drivers?.twilio;if(!twilioConfig?.accountSid||!twilioConfig?.authToken){throw new Error("Twilio configuration is incomplete. Please provide accountSid and authToken.")}return new TwilioDriver({...twilioConfig,from:twilioConfig.from||smsConfig.from},twilioConfig.verifyServiceSid)}case"vonage":{const vonageConfig=smsConfig.drivers?.vonage;if(!vonageConfig?.apiKey||!vonageConfig?.apiSecret){throw new Error("Vonage configuration is incomplete. Please provide apiKey and apiSecret.")}return new VonageDriver({...vonageConfig,from:vonageConfig.from||smsConfig.from})}default:throw new Error(`Unsupported SMS provider: ${targetProvider}`)}}export function getVerificationDriver(provider){const driver=getDriver(provider);if(!("startVerification"in driver)){throw new Error(`Provider does not support verification: ${provider||smsConfig.provider}`)}return driver}function getDefaultDriver(){if(!defaultDriver){defaultDriver=getDriver()}return defaultDriver}function getDefaultVerificationDriver(){if(!verificationDriver){verificationDriver=getVerificationDriver()}return verificationDriver}export async function send(message){await ensureConfig();const driver=getDefaultDriver();return driver.send(message)}export const sendSms=send;export async function sendBulk(messages){await ensureConfig();const driver=getDefaultDriver();const concurrency=Math.max(1,Math.floor(smsConfig.bulk?.concurrency??10));const delayMs=Math.max(0,Math.floor(smsConfig.bulk?.delayMs??0));const results=[];for(let offset=0;offset<messages.length;offset+=concurrency){const batch=messages.slice(offset,offset+concurrency);results.push(...await driver.sendBulk(batch));if(delayMs>0&&offset+concurrency<messages.length)await new Promise((resolve)=>setTimeout(resolve,delayMs))}return results}export async function getStatus(messageId){await ensureConfig();const driver=getDefaultDriver();if(driver.getStatus){return driver.getStatus(messageId)}return null}export async function verifyNumber(phoneNumber){await ensureConfig();const driver=getDefaultDriver();if(driver.verify){return driver.verify(phoneNumber)}return{valid:true}}export async function getBalance(){await ensureConfig();const driver=getDefaultDriver();if(driver.getBalance){return driver.getBalance()}return null}export async function startVerification(request){await ensureConfig();const driver=getDefaultVerificationDriver();return driver.startVerification(request)}export async function checkVerification(request){await ensureConfig();const driver=getDefaultVerificationDriver();return driver.checkVerification(request)}export async function cancelVerification(verificationId){await ensureConfig();const driver=getDefaultVerificationDriver();if(driver.cancelVerification){return driver.cancelVerification(verificationId)}return false}export class SmsBuilder{message={};provider;to(phoneNumber){this.message.to=phoneNumber;return this}body(text){this.message.body=text;return this}text(text){return this.body(text)}from(sender){this.message.from=sender;return this}media(urls){this.message.mediaUrls=Array.isArray(urls)?urls:[urls];return this}callback(url){this.message.statusCallback=url;return this}via(provider){this.provider=provider;return this}async send(){await ensureConfig();if(!this.message.to){return{success:false,to:"",error:"Recipient is required",provider:this.provider||smsConfig.provider||"twilio"}}if(!this.message.body){return{success:false,to:Array.isArray(this.message.to)?this.message.to[0]??"":this.message.to,error:"Message body is required",provider:this.provider||smsConfig.provider||"twilio"}}const driver=this.provider?getDriver(this.provider):getDefaultDriver();return driver.send(this.message)}}export function sms(){return new SmsBuilder}export async function sendTemplate(to,templateName,variables={}){await ensureConfig();const template=smsConfig.templates?.find((t)=>t.name===templateName);if(!template){return{success:false,to:Array.isArray(to)?to[0]??"":to,error:`Template not found: ${templateName}`,provider:smsConfig.provider||"twilio"}}let body=template.body;for(const[key,value]of Object.entries(variables)){const escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");body=body.replace(new RegExp(`\\{${escapedKey}\\}`,"g"),value)}return send({to,body})}export function formatE164(phoneNumber,defaultCountryCode){let cleaned=phoneNumber.replace(/[\s\-()]/g,"");if(cleaned.startsWith("+")){return cleaned}const countryCode=String(defaultCountryCode||smsConfig.defaultCountryCode||"1").replace(/^\+/,"");if(!/^[1-9]\d{0,3}$/.test(countryCode))throw new Error("Default SMS country code must be a numeric dialing prefix, such as 1 for the US.");if(cleaned.startsWith("00")){cleaned=`+${cleaned.slice(2)}`}else if(!cleaned.startsWith("+")){cleaned=`+${countryCode}${cleaned}`}return cleaned}export function isValidPhoneNumber(phoneNumber){const e164Regex=/^\+[1-9]\d{6,14}$/;const formatted=formatE164(phoneNumber);return e164Regex.test(formatted)}export async function init(){await loadConfig()}export function isEnabled(){return smsConfig.enabled===true}export function getConfig(){return{...smsConfig}}export const SMS={init,configure,isEnabled,getConfig,send,sendSms,sendBulk,sendTemplate,getStatus,getBalance,verifyNumber,startVerification,checkVerification,cancelVerification,formatE164,isValidPhoneNumber,sms,getDriver,getVerificationDriver};export default SMS;
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/sms",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.518",
|
|
6
6
|
"description": "The Stacks SMS integration. Painlessly create & manage your inboxes, templates, and send sms.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -63,14 +63,14 @@
|
|
|
63
63
|
"prepublishOnly": "bun run build"
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
|
-
"@stacksjs/config": "0.75.
|
|
67
|
-
"@stacksjs/database": "0.75.
|
|
66
|
+
"@stacksjs/config": "0.75.518",
|
|
67
|
+
"@stacksjs/database": "0.75.518"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
|
-
"@stacksjs/cli": "0.75.
|
|
71
|
-
"@stacksjs/error-handling": "0.75.
|
|
72
|
-
"@stacksjs/testing": "0.75.
|
|
73
|
-
"@stacksjs/types": "0.75.
|
|
70
|
+
"@stacksjs/cli": "0.75.518",
|
|
71
|
+
"@stacksjs/error-handling": "0.75.518",
|
|
72
|
+
"@stacksjs/testing": "0.75.518",
|
|
73
|
+
"@stacksjs/types": "0.75.518",
|
|
74
74
|
"better-dx": "^0.2.24"
|
|
75
75
|
}
|
|
76
76
|
}
|