@stacksjs/newsletter 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/campaigns.js +1 -1
- package/dist/delivery.js +1 -1
- package/dist/headers.js +1 -1
- package/dist/lists.js +1 -1
- package/dist/subscriptions.js +1 -1
- package/dist/sync.js +1 -1
- package/dist/usage.js +1 -1
- package/package.json +9 -9
package/dist/campaigns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{lists}from"./lists";async function resolveListId(input){if(input.emailListId)return input.emailListId;if(input.emailListSlug){const list=await lists.find(input.emailListSlug);if(!list)throw Error(`[newsletter] List '${input.emailListSlug}' not found`);return list.id}throw Error("[newsletter] Campaign requires emailListId or emailListSlug")}export class CampaignStateConflictError extends Error{constructor(id){super(`[newsletter] Campaign ${id} changed before delivery could be queued`);this.name="CampaignStateConflictError"}}function campaignValue(campaign,snakeKey,camelKey){if(typeof campaign?.get==="function"){const snakeValue=campaign.get(snakeKey);if(snakeValue!==
|
|
1
|
+
import{db,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{lists}from"./lists";async function resolveListId(input){if(input.emailListId)return input.emailListId;if(input.emailListSlug){const list=await lists.find(input.emailListSlug);if(!list)throw new Error(`[newsletter] List '${input.emailListSlug}' not found`);return list.id}throw new Error("[newsletter] Campaign requires emailListId or emailListSlug")}export class CampaignStateConflictError extends Error{constructor(id){super(`[newsletter] Campaign ${id} changed before delivery could be queued`);this.name="CampaignStateConflictError"}}function campaignValue(campaign,snakeKey,camelKey){if(typeof campaign?.get==="function"){const snakeValue=campaign.get(snakeKey);if(snakeValue!==undefined)return snakeValue;return campaign.get(camelKey)}return campaign?.[snakeKey]??campaign?.[camelKey]}function snapshotTimestamp(value){if(value===null||value===undefined||value==="")return null;if(typeof value==="string")return value;const parsed=parseSqlDateTime(value);return parsed===null?null:sqlDateTime(parsed)}export function campaignDeliverySnapshot(campaign){const status=String(campaignValue(campaign,"status","status")||"");if(!isStoredCampaignStatus(status))throw new TypeError(`[newsletter] Invalid campaign status '${status}'`);return{status,scheduledAt:snapshotTimestamp(campaignValue(campaign,"scheduled_at","scheduledAt")),updatedAt:snapshotTimestamp(campaignValue(campaign,"updated_at","updatedAt"))}}function isStoredCampaignStatus(value){const statuses=["draft","scheduled","sending","sent","paused","cancelled","failed","active","completed","archived"];return statuses.some((status)=>status===value)}export function campaignDeliveryDispatchKey(id,mode,attempt,scheduledAt){return`newsletter:campaign:${id}:${mode}:${scheduledAt||"now"}:${attempt}`}export function canQueueCampaignStatus(status){return["draft","scheduled","paused","failed"].includes(String(status||"").toLowerCase())}function withScheduledAtMatch(query,scheduledAt){return scheduledAt===null?query.whereNull("scheduled_at"):query.where("scheduled_at","=",scheduledAt)}function withUpdatedAtMatch(query,updatedAt){return updatedAt===null?query.whereNull("updated_at"):query.where("updated_at","=",updatedAt)}async function transitionCampaignDelivery(id,expected,target){const matchingSnapshot=(query)=>withUpdatedAtMatch(withScheduledAtMatch(query.where("id","=",id).where("status","=",expected.status),expected.scheduledAt),expected.updatedAt);const write=(connection)=>matchingSnapshot(connection.updateTable("campaigns").set({status:target.status,scheduled_at:target.scheduledAt,updated_at:target.updatedAt}));if(!sqlHelpers(getDatabaseDialect()).isMysql){if(mutationCount(await write(db).executeTakeFirst())!==1)throw new CampaignStateConflictError(id);return}await db.transaction(async(rawTrx)=>{const trx=rawTrx;const current=await matchingSnapshot(trx.selectFrom("campaigns")).select(["id"]).lockForUpdate().executeTakeFirst();if(!current)throw new CampaignStateConflictError(id);await write(trx).execute()})}async function restoreCampaignDelivery(id,expected,restore){const query=withScheduledAtMatch(db.updateTable("campaigns").set({status:restore.status,scheduled_at:restore.scheduledAt,updated_at:sqlDateTime()}).where("id","=",id).where("status","=",expected.status).where("updated_at","=",expected.updatedAt),expected.scheduledAt);await query.execute()}async function dispatchCampaign(id,target,previous,options,scheduledAt,delaySeconds=0){const{job}=await import("@stacksjs/queue");const mode=scheduledAt?"scheduled":"immediate";try{await job("SendCampaignJob",{campaignId:id,chunkSize:options.chunkSize??50,dryRun:options.dryRun??false,...scheduledAt?{scheduledAt}:{}}).onQueue("campaigns").delay(delaySeconds).withIdempotencyKey(campaignDeliveryDispatchKey(id,mode,target.attemptId,scheduledAt)).dispatch()}catch(dispatchError){try{await restoreCampaignDelivery(id,target,previous)}catch(restoreError){throw new AggregateError([dispatchError,restoreError],`[newsletter] Campaign ${id} could not be dispatched or restored`)}throw dispatchError}}export function shouldRunScheduledCampaign(campaign,expectedScheduledAt){if(!expectedScheduledAt)return true;if(String(campaign.status||"")!=="scheduled")return false;const currentScheduledAt=campaign.scheduled_at??campaign.scheduledAt;const currentTime=new Date(String(currentScheduledAt||"")).getTime();const expectedTime=new Date(expectedScheduledAt).getTime();return Number.isFinite(currentTime)&&Number.isFinite(expectedTime)&¤tTime===expectedTime}export function campaignCreateData(input,emailListId){return{name:input.name,description:input.description??null,type:"email",status:input.scheduledAt?"scheduled":"draft",subject:input.subject,template:input.template,text:input.text??null,from_name:input.fromName??null,from_address:input.fromAddress??null,email_list_id:emailListId,scheduled_at:input.scheduledAt??null,sent_count:0}}export function campaignUpdateData(patch,emailListId){const data={};if(patch.name!==undefined)data.name=patch.name;if(patch.description!==undefined)data.description=patch.description;if(patch.subject!==undefined)data.subject=patch.subject;if(patch.template!==undefined)data.template=patch.template;if(patch.text!==undefined)data.text=patch.text;if(patch.fromName!==undefined)data.from_name=patch.fromName;if(patch.fromAddress!==undefined)data.from_address=patch.fromAddress;if(emailListId!==undefined)data.email_list_id=emailListId;if(patch.scheduledAt!==undefined){data.scheduled_at=patch.scheduledAt||null;data.status=patch.scheduledAt?"scheduled":"draft"}return data}export const campaigns={async create(input){const emailListId=await resolveListId(input);const data=campaignCreateData(input,emailListId);const uuid=crypto.randomUUID();await db.insertInto("campaigns").values({...data,uuid}).execute();const row=await db.selectFrom("campaigns").selectAll().where("uuid","=",uuid).executeTakeFirst();if(!row)throw new Error("[newsletter] Campaign could not be read back after creation");return row},async find(id){return await db.selectFrom("campaigns").selectAll().where("id","=",id).executeTakeFirst()},async update(id,patch){const campaign=await campaigns.find(id);if(!campaign)throw new Error(`[newsletter] Campaign ${id} not found`);if(campaign.status!=="draft"&&campaign.status!=="scheduled")throw new Error(`[newsletter] Cannot edit campaign in status '${campaign.status}'`);const shouldResolveList=patch.emailListId!==undefined||patch.emailListSlug!==undefined;const emailListId=shouldResolveList?await resolveListId(patch):undefined;return campaign.update(campaignUpdateData(patch,emailListId))},async sendNow(id,options={}){const campaign=await campaigns.find(id);if(!campaign)throw new Error(`[newsletter] Campaign ${id} not found`);if(!canQueueCampaignStatus(campaign.status))throw new Error(`[newsletter] Campaign ${id} in status '${campaign.status}' cannot be queued`);const previous=campaignDeliverySnapshot(campaign);const target={status:"sending",scheduledAt:previous.scheduledAt,updatedAt:sqlDateTime(),attemptId:crypto.randomUUID()};await transitionCampaignDelivery(id,previous,target);await dispatchCampaign(id,target,previous,options);return{ok:true,campaignId:id}},async schedule(id,scheduledAt,options={}){const campaign=await campaigns.find(id);if(!campaign)throw new Error(`[newsletter] Campaign ${id} not found`);if(!canQueueCampaignStatus(campaign.status))throw new Error(`[newsletter] Campaign ${id} in status '${campaign.status}' cannot be scheduled`);const at=scheduledAt instanceof Date?scheduledAt:new Date(scheduledAt);if(!Number.isFinite(at.getTime()))throw new Error("[newsletter] scheduledAt must be a valid date");const delaySeconds=Math.max(0,Math.floor((at.getTime()-Date.now())/1000));const scheduledAtIso=at.toISOString();const previous=campaignDeliverySnapshot(campaign);const target={status:delaySeconds===0?"sending":"scheduled",scheduledAt:scheduledAtIso,updatedAt:sqlDateTime(),attemptId:crypto.randomUUID()};await transitionCampaignDelivery(id,previous,target);await dispatchCampaign(id,target,previous,options,delaySeconds>0?scheduledAtIso:undefined,delaySeconds);return{ok:true,campaignId:id,scheduledAt:scheduledAtIso}},async cancel(id){const campaign=await campaigns.find(id);if(!campaign)throw new Error(`[newsletter] Campaign ${id} not found`);if(campaign.status==="sent")throw new Error(`[newsletter] Campaign ${id} already sent. It cannot be cancelled`);const previous=campaignDeliverySnapshot(campaign);const target={status:"cancelled",scheduledAt:previous.scheduledAt,updatedAt:sqlDateTime(),attemptId:crypto.randomUUID()};await transitionCampaignDelivery(id,previous,target);return campaigns.find(id)}};
|
package/dist/delivery.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function stableHash(value){let hash=2166136261;for(let index=0;index<value.length;index++){hash^=value.charCodeAt(index);hash=Math.imul(hash,16777619)}return hash>>>0}export function allocateDeliveryVariant(recipientKey,variants){if(variants.length===0)throw Error("At least one delivery variant is required");const total=variants.reduce((sum,variant)=>sum+variant.allocation,0);if(total<=0)throw Error("Delivery variant allocation must be greater than zero");const bucket=stableHash(recipientKey)%total;let cursor=0;for(const variant of variants){if(!Number.isFinite(variant.allocation)||variant.allocation<0)throw Error("Delivery variant allocation must be a non-negative number");cursor+=variant.allocation;if(bucket<cursor)return variant}return variants[variants.length-1]}export function deliveryIdempotencyKey(input){return["delivery",input.teamId,input.campaignId,input.channel,input.recipient.trim().toLowerCase(),input.occurrence||"once"].join(":")}export function assertUsageAvailable(limits){const exceeded=limits.find((entry)=>{if(entry.limit===null)return
|
|
1
|
+
function stableHash(value){let hash=2166136261;for(let index=0;index<value.length;index++){hash^=value.charCodeAt(index);hash=Math.imul(hash,16777619)}return hash>>>0}export function allocateDeliveryVariant(recipientKey,variants){if(variants.length===0)throw new Error("At least one delivery variant is required");const total=variants.reduce((sum,variant)=>sum+variant.allocation,0);if(total<=0)throw new Error("Delivery variant allocation must be greater than zero");const bucket=stableHash(recipientKey)%total;let cursor=0;for(const variant of variants){if(!Number.isFinite(variant.allocation)||variant.allocation<0)throw new Error("Delivery variant allocation must be a non-negative number");cursor+=variant.allocation;if(bucket<cursor)return variant}return variants[variants.length-1]}export function deliveryIdempotencyKey(input){return["delivery",input.teamId,input.campaignId,input.channel,input.recipient.trim().toLowerCase(),input.occurrence||"once"].join(":")}export function assertUsageAvailable(limits){const exceeded=limits.find((entry)=>{if(entry.limit===null)return false;return entry.used+(entry.requested??1)>entry.limit});if(exceeded)throw new Error(`Usage limit exceeded for ${exceeded.meter}`)}export function classifyDeliveryFailure(status,code=""){const normalizedCode=code.toLowerCase();if(["suppressed","unsubscribe","complaint","stop"].some((value)=>normalizedCode.includes(value)))return"suppressed";if(Number(status)===429||normalizedCode.includes("rate"))return"rate_limited";if(Number(status)>=500||["timeout","temporary","unavailable"].some((value)=>normalizedCode.includes(value)))return"transient";return"permanent"}
|
package/dist/headers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function buildUnsubscribeHeaders(opts){if(!opts.url||!/^https?:\/\//i.test(opts.url))throw Error("[newsletter] List-Unsubscribe URL must be absolute (http/https)");const parts=[];if(opts.mailto)parts.push(`<mailto:${opts.mailto}>`);parts.push(`<${opts.url}>`);return{"List-Unsubscribe":parts.join(", "),"List-Unsubscribe-Post":"List-Unsubscribe=One-Click"}}
|
|
1
|
+
export function buildUnsubscribeHeaders(opts){if(!opts.url||!/^https?:\/\//i.test(opts.url))throw new Error("[newsletter] List-Unsubscribe URL must be absolute (http/https)");const parts=[];if(opts.mailto)parts.push(`<mailto:${opts.mailto}>`);parts.push(`<${opts.url}>`);return{"List-Unsubscribe":parts.join(", "),"List-Unsubscribe-Post":"List-Unsubscribe=One-Click"}}
|
package/dist/lists.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,matchedRows}from"@stacksjs/database/runtime";function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]+/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}export function emailListCreateData(input){return{name:input.name,slug:input.slug??slugify(input.name),description:input.description??null,status:"active",is_public:input.isPublic
|
|
1
|
+
import{db,matchedRows}from"@stacksjs/database/runtime";function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]+/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}export function emailListCreateData(input){return{name:input.name,slug:input.slug??slugify(input.name),description:input.description??null,status:"active",is_public:input.isPublic===false?0:1,double_opt_in:input.doubleOptIn===false?0:1,subscriber_count:0,active_count:0,unsubscribed_count:0,bounced_count:0}}export const lists={async create(input){const data=emailListCreateData(input);await db.insertInto("email_lists").values(data).execute();const row=await lists.find(String(data.slug));if(!row)throw new Error(`[newsletter] List '${String(data.slug)}' could not be read back after creation`);return row},async find(idOrSlug){const query=db.selectFrom("email_lists").selectAll();const row=typeof idOrSlug==="number"?await query.where("id","=",idOrSlug).executeTakeFirst():await query.where("slug","=",idOrSlug).executeTakeFirst();return row},async all(){return await db.selectFrom("email_lists").selectAll().where("status","=","active").execute()},async archive(idOrSlug){const list=await lists.find(idOrSlug);if(!list)throw new Error(`[newsletter] List '${String(idOrSlug)}' not found`);const matched=await matchedRows(db.updateTable("email_lists").set({status:"archived"}).where("id","=",Number(list.id)));return matched.length}};
|
package/dist/subscriptions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,getDatabaseDialect,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{lists}from"./lists";export function normalizeEmail(email){return email.trim().toLowerCase()}export async function subscriberIdsForEmail(email){const param=sqlHelpers(getDatabaseDialect()).param(1);
|
|
1
|
+
import{db,getDatabaseDialect,sqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{lists}from"./lists";export function normalizeEmail(email){return email.trim().toLowerCase()}export async function subscriberIdsForEmail(email){const param=sqlHelpers(getDatabaseDialect()).param(1);const rows=await db.unsafe(`SELECT id FROM subscribers WHERE lower(email) = ${param} ORDER BY id`,[normalizeEmail(email)]);return rows.map((row)=>Number(row.id))}async function listMemberships(subscriberIds,listId){const found=[];for(const subscriberId of subscriberIds){const row=await db.selectFrom("email_list_subscribers").selectAll().where("subscriber_id","=",subscriberId).where("email_list_id","=",listId).executeTakeFirst();if(row)found.push(row)}return found}export async function listStatusForEmail(email,listId){const memberships=await listMemberships(await subscriberIdsForEmail(email),listId);if(memberships.some((row)=>row.status==="unsubscribed"))return"unsubscribed";return memberships.find((row)=>row.status==="subscribed")?.status??memberships[0]?.status??null}async function resolveListId(listRef){if(listRef==null){let list=await lists.find("default");if(!list)list=await lists.create({name:"Default",slug:"default"});return list.id}const list=await lists.find(listRef);if(!list)throw new Error(`[newsletter] List '${String(listRef)}' not found`);return list.id}export async function subscribe(email,options={}){if(!email||!email.includes("@"))throw new Error("[newsletter] subscribe() requires a valid email address");email=normalizeEmail(email);const listId=await resolveListId(options.list);const source=options.source??"api";let subscriberIds=await subscriberIdsForEmail(email);if(!subscriberIds.length){await db.insertInto("subscribers").values({uuid:crypto.randomUUID(),email,status:"subscribed",source}).execute();subscriberIds=await subscriberIdsForEmail(email)}const subscriberId=subscriberIds[0];const existing=(await listMemberships(subscriberIds,listId))[0];if(existing){if(existing.status==="unsubscribed"){await db.updateTable("email_list_subscribers").set({status:"subscribed",unsubscribed_at:null}).where("id","=",Number(existing.id)).execute()}return{created:false,email,listId,token:existing.uuid}}const uuid=crypto.randomUUID();await db.insertInto("email_list_subscribers").values({uuid,subscriber_id:subscriberId,email_list_id:listId,status:"subscribed",source}).execute();return{created:true,email,listId,token:uuid}}export async function unsubscribe(token){if(!token)return{ok:false};const pivot=await db.selectFrom("email_list_subscribers").selectAll().where("uuid","=",token).executeTakeFirst();if(!pivot)return{ok:false};const subscriberEmail=async()=>{const row=await db.selectFrom("subscribers").select(["email"]).where("id","=",Number(pivot.subscriber_id)).executeTakeFirst();return row?.email};if(pivot.status==="unsubscribed"){return{ok:true,alreadyUnsubscribed:true,email:await subscriberEmail(),listId:pivot.email_list_id}}await db.updateTable("email_list_subscribers").set({status:"unsubscribed",unsubscribed_at:sqlDateTime()}).where("id","=",Number(pivot.id)).execute();return{ok:true,email:await subscriberEmail(),listId:pivot.email_list_id}}export async function unsubscribeAll(email){const pivots=[];for(const subscriberId of await subscriberIdsForEmail(email)){pivots.push(...await db.selectFrom("email_list_subscribers").select(["id"]).where("subscriber_id","=",subscriberId).where("status","=","subscribed").execute())}for(const pivot of pivots){await db.updateTable("email_list_subscribers").set({status:"unsubscribed",unsubscribed_at:sqlDateTime()}).where("id","=",Number(pivot.id)).execute()}return pivots.length}
|
package/dist/sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db}from"@stacksjs/database/runtime";import{listStatusForEmail,normalizeEmail,subscribe}from"./subscriptions";export function looksLikeEmail(value){return Boolean(value)&&value.includes("@")&&!value.startsWith("@")&&!value.endsWith("@")}export function syncDecision(email,state){if(!looksLikeEmail(email))return"skip-invalid";if(state.duplicate)return"skip-duplicate";if(state.suppressed)return"skip-suppressed";if(state.listStatus==="unsubscribed")return"skip-unsubscribed";return state.listStatus==="subscribed"?"existing":"add"}export async function syncListSubscribers(list,contacts,options={}){const result={added:0,existing:0,unsubscribed:0,suppressed:0,invalid:0,skipped:{unsubscribed:[],suppressed:[],invalid:[]}}
|
|
1
|
+
import{db}from"@stacksjs/database/runtime";import{listStatusForEmail,normalizeEmail,subscribe}from"./subscriptions";export function looksLikeEmail(value){return Boolean(value)&&value.includes("@")&&!value.startsWith("@")&&!value.endsWith("@")}export function syncDecision(email,state){if(!looksLikeEmail(email))return"skip-invalid";if(state.duplicate)return"skip-duplicate";if(state.suppressed)return"skip-suppressed";if(state.listStatus==="unsubscribed")return"skip-unsubscribed";return state.listStatus==="subscribed"?"existing":"add"}export async function syncListSubscribers(list,contacts,options={}){const result={added:0,existing:0,unsubscribed:0,suppressed:0,invalid:0,skipped:{unsubscribed:[],suppressed:[],invalid:[]}};const seen=new Set;for(const contact of contacts){const raw=String(contact.email??"");const email=normalizeEmail(raw);const listStatus=looksLikeEmail(email)&&!seen.has(email)?await listStatusForEmail(email,await resolveId(list)):null;const decision=syncDecision(email,{duplicate:seen.has(email),suppressed:looksLikeEmail(email)?await suppressed(email):false,listStatus});if(looksLikeEmail(email))seen.add(email);switch(decision){case"skip-invalid":result.invalid++;result.skipped.invalid.push(raw);continue;case"skip-duplicate":continue;case"skip-suppressed":result.suppressed++;result.skipped.suppressed.push(email);continue;case"skip-unsubscribed":result.unsubscribed++;result.skipped.unsubscribed.push(email);continue;case"existing":result.existing++;continue;case"add":break}const outcome=await subscribe(email,{list,source:contact.source??options.source??"sync",upsert:true});if(outcome.created)result.added++;else result.existing++}return result}async function suppressed(email){try{const{isSuppressed}=await import("@stacksjs/email");return await isSuppressed(email)}catch{return false}}async function resolveId(list){if(typeof list==="number")return list;const row=await db.selectFrom("email_lists").select(["id"]).where("slug","=",list).executeTakeFirst();return Number(row?.id??0)}
|
package/dist/usage.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class UsageQuotaError extends Error{code;constructor(code,meter){const messages={unavailable:`Usage meter unavailable for ${meter}`,invalid:`Usage meter state is invalid for ${meter}`,exceeded:`Usage limit exceeded for ${meter}`,contention:`Usage reservation contention for ${meter}`};super(messages[code]);this.code=code;this.name="UsageQuotaError"}}function validQuantity(value){return Number.isFinite(value)&&value>0}function validSnapshot(snapshot,meter){return snapshot.meter===meter&&Number.isFinite(snapshot.used)&&snapshot.used>=0&&(snapshot.limit===null||Number.isFinite(snapshot.limit)&&snapshot.limit>=0)}function attempts(value){return Number.isInteger(value)&&value>0?value:1}export async function reserveUsage(store,meter,quantity=1,maxAttempts=5){if(!meter||!validQuantity(quantity))throw new UsageQuotaError("invalid",meter||"unknown");for(let attempt=0;attempt<attempts(maxAttempts);attempt++){const snapshot=await store.read(meter);if(!snapshot)throw new UsageQuotaError("unavailable",meter);if(!validSnapshot(snapshot,meter))throw new UsageQuotaError("invalid",meter);const nextUsed=snapshot.used+quantity;if(snapshot.limit!==null&&nextUsed>snapshot.limit)throw new UsageQuotaError("exceeded",meter);if(await store.compareAndSet(snapshot,nextUsed))return{meter,quantity,previousUsed:snapshot.used,used:nextUsed,limit:snapshot.limit}}throw new UsageQuotaError("contention",meter)}export async function releaseUsage(store,reservation,maxAttempts=5){if(!reservation.meter||!validQuantity(reservation.quantity))throw new UsageQuotaError("invalid",reservation.meter||"unknown");for(let attempt=0;attempt<attempts(maxAttempts);attempt++){const snapshot=await store.read(reservation.meter);if(!snapshot)throw new UsageQuotaError("unavailable",reservation.meter);if(!validSnapshot(snapshot,reservation.meter)||snapshot.used<reservation.quantity)throw new UsageQuotaError("invalid",reservation.meter);if(await store.compareAndSet(snapshot,snapshot.used-reservation.quantity))return}throw new UsageQuotaError("contention",reservation.meter)}
|
|
1
|
+
export class UsageQuotaError extends Error{code;constructor(code,meter){const messages={unavailable:`Usage meter unavailable for ${meter}`,invalid:`Usage meter state is invalid for ${meter}`,exceeded:`Usage limit exceeded for ${meter}`,contention:`Usage reservation contention for ${meter}`};super(messages[code]);this.code=code;this.name="UsageQuotaError"}}function validQuantity(value){return Number.isFinite(value)&&value>0}function validSnapshot(snapshot,meter){return snapshot.meter===meter&&Number.isFinite(snapshot.used)&&snapshot.used>=0&&(snapshot.limit===null||Number.isFinite(snapshot.limit)&&snapshot.limit>=0)}function attempts(value){return Number.isInteger(value)&&value>0?value:1}export async function reserveUsage(store,meter,quantity=1,maxAttempts=5){if(!meter||!validQuantity(quantity))throw new UsageQuotaError("invalid",meter||"unknown");for(let attempt=0;attempt<attempts(maxAttempts);attempt++){const snapshot=await store.read(meter);if(!snapshot)throw new UsageQuotaError("unavailable",meter);if(!validSnapshot(snapshot,meter))throw new UsageQuotaError("invalid",meter);const nextUsed=snapshot.used+quantity;if(snapshot.limit!==null&&nextUsed>snapshot.limit)throw new UsageQuotaError("exceeded",meter);if(await store.compareAndSet(snapshot,nextUsed)){return{meter,quantity,previousUsed:snapshot.used,used:nextUsed,limit:snapshot.limit}}}throw new UsageQuotaError("contention",meter)}export async function releaseUsage(store,reservation,maxAttempts=5){if(!reservation.meter||!validQuantity(reservation.quantity))throw new UsageQuotaError("invalid",reservation.meter||"unknown");for(let attempt=0;attempt<attempts(maxAttempts);attempt++){const snapshot=await store.read(reservation.meter);if(!snapshot)throw new UsageQuotaError("unavailable",reservation.meter);if(!validSnapshot(snapshot,reservation.meter)||snapshot.used<reservation.quantity)throw new UsageQuotaError("invalid",reservation.meter);if(await store.compareAndSet(snapshot,snapshot.used-reservation.quantity))return}throw new UsageQuotaError("contention",reservation.meter)}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/newsletter",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.518",
|
|
6
6
|
"description": "Promotional email & newsletter primitives for Stacks. Lists, campaigns, subscribers, and one-click unsubscribe — sent through @stacksjs/email.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -61,16 +61,16 @@
|
|
|
61
61
|
"prepublishOnly": "bun run build"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@stacksjs/database": "0.75.
|
|
65
|
-
"@stacksjs/email": "0.75.
|
|
66
|
-
"@stacksjs/orm": "0.75.
|
|
67
|
-
"@stacksjs/queue": "0.75.
|
|
64
|
+
"@stacksjs/database": "0.75.518",
|
|
65
|
+
"@stacksjs/email": "0.75.518",
|
|
66
|
+
"@stacksjs/orm": "0.75.518",
|
|
67
|
+
"@stacksjs/queue": "0.75.518"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
|
-
"@stacksjs/cli": "0.75.
|
|
71
|
-
"@stacksjs/config": "0.75.
|
|
72
|
-
"@stacksjs/error-handling": "0.75.
|
|
73
|
-
"@stacksjs/types": "0.75.
|
|
70
|
+
"@stacksjs/cli": "0.75.518",
|
|
71
|
+
"@stacksjs/config": "0.75.518",
|
|
72
|
+
"@stacksjs/error-handling": "0.75.518",
|
|
73
|
+
"@stacksjs/types": "0.75.518",
|
|
74
74
|
"better-dx": "^0.2.24"
|
|
75
75
|
}
|
|
76
76
|
}
|