Comparing version 1.7.2 to 1.8.0
import { Broadcasts } from './resources/broadcasts'; | ||
import { Imports } from './resources/imports'; | ||
import { Metrics } from './resources/metrics'; | ||
import { NotificationPreferences } from './resources/notification-preferences'; | ||
@@ -15,2 +16,3 @@ import { Notifications } from './resources/notifications'; | ||
imports: Imports; | ||
metrics: Metrics; | ||
notificationPreferences: NotificationPreferences; | ||
@@ -22,4 +24,4 @@ notifications: Notifications; | ||
constructor(options: ClientOptions); | ||
hasFlag(flag: FeatureFlag): boolean; | ||
request<TResponse = any>({ method, path, data, params }: RequestArgs, options?: RequestOptions): Promise<TResponse>; | ||
hasFlag(flag: FeatureFlag): never; | ||
request<TResponse = any>({ method, path: url, data, params, headers: reqHeaders }: RequestArgs, options?: RequestOptions): Promise<TResponse>; | ||
} |
/** | ||
* @license magicbell v1.7.2 | ||
* @license magicbell v1.8.0 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) MagicBell Inc. and its affiliates. |
/** | ||
* @license magicbell v1.7.2 | ||
* @license magicbell v1.8.0 | ||
* | ||
@@ -77,3 +77,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "1.7.2", | ||
binding_version: "1.8.0", | ||
publisher: "magicbell" | ||
@@ -631,3 +631,2 @@ }; | ||
list(broadcastId, dataOrOptions, options) { | ||
this.assertFeatureFlag("broadcasts-notifications-list"); | ||
return this.request( | ||
@@ -653,3 +652,2 @@ { | ||
list(dataOrOptions, options) { | ||
this.assertFeatureFlag("broadcasts-list"); | ||
return this.request( | ||
@@ -665,3 +663,2 @@ { | ||
get(broadcastId, options) { | ||
this.assertFeatureFlag("broadcasts-get"); | ||
return this.request( | ||
@@ -684,3 +681,2 @@ { | ||
create(dataOrOptions, options) { | ||
this.assertFeatureFlag("imports-create"); | ||
return this.request( | ||
@@ -695,3 +691,2 @@ { | ||
get(importId, options) { | ||
this.assertFeatureFlag("imports-get"); | ||
return this.request( | ||
@@ -707,2 +702,51 @@ { | ||
} | ||
class MetricsCategories extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "metrics"); | ||
__publicField(this, "entity", "categorie"); | ||
} | ||
get(options) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "categories" | ||
}, | ||
options | ||
); | ||
} | ||
} | ||
class MetricsTopics extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "metrics"); | ||
__publicField(this, "entity", "topic"); | ||
} | ||
get(options) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "topics" | ||
}, | ||
options | ||
); | ||
} | ||
} | ||
class Metrics extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "metrics"); | ||
__publicField(this, "entity", "metric"); | ||
__publicField(this, "categories", new MetricsCategories(this.client)); | ||
__publicField(this, "topics", new MetricsTopics(this.client)); | ||
} | ||
get(options) { | ||
return this.request( | ||
{ | ||
method: "GET" | ||
}, | ||
options | ||
); | ||
} | ||
} | ||
class NotificationPreferences extends Resource { | ||
@@ -921,2 +965,21 @@ constructor() { | ||
} | ||
class UsersNotifications extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "users"); | ||
__publicField(this, "entity", "notification"); | ||
} | ||
list(userId, dataOrOptions, options) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "{user_id}/notifications", | ||
paged: true | ||
}, | ||
userId, | ||
dataOrOptions, | ||
options | ||
); | ||
} | ||
} | ||
class UsersPushSubscriptions extends Resource { | ||
@@ -929,3 +992,2 @@ constructor() { | ||
list(userId, dataOrOptions, options) { | ||
this.assertFeatureFlag("users-push-subscriptions-list"); | ||
return this.request( | ||
@@ -943,3 +1005,2 @@ { | ||
delete(userId, subscriptionId, options) { | ||
this.assertFeatureFlag("users-push-subscriptions-delete"); | ||
return this.request( | ||
@@ -961,2 +1022,3 @@ { | ||
__publicField(this, "entity", "user"); | ||
__publicField(this, "notifications", new UsersNotifications(this.client)); | ||
__publicField(this, "pushSubscriptions", new UsersPushSubscriptions(this.client)); | ||
@@ -1084,2 +1146,3 @@ } | ||
__publicField(this, "imports", new Imports(this)); | ||
__publicField(this, "metrics", new Metrics(this)); | ||
__publicField(this, "notificationPreferences", new NotificationPreferences(this)); | ||
@@ -1108,5 +1171,5 @@ __publicField(this, "notifications", new Notifications(this)); | ||
} | ||
async request({ method, path, data, params }, options) { | ||
async request({ method, path: url, data, params, headers: reqHeaders }, options) { | ||
var _a, _b, _c; | ||
const requestOptions = __spreadValues(__spreadValues({}, __privateGet(this, _options)), options); | ||
const requestOptions = __spreadProps(__spreadValues(__spreadValues({}, __privateGet(this, _options)), options), { headers: __spreadValues(__spreadValues({}, __privateGet(this, _options).headers), reqHeaders) }); | ||
const headers = __privateMethod(this, _getHeaders, getHeaders_fn).call(this, requestOptions, method); | ||
@@ -1118,6 +1181,6 @@ const maxRetries = Math.max(0, requestOptions.maxRetries); | ||
const startTime = Date.now(); | ||
__privateGet(this, _logger).debug(`${method} ${path}`); | ||
__privateGet(this, _logger).debug(`${method} ${url}`); | ||
await axios__default.default({ | ||
method, | ||
url: path, | ||
url, | ||
baseURL: requestOptions.host, | ||
@@ -1133,3 +1196,3 @@ headers: __spreadValues(__spreadValues({}, headers), normalizeHeaders({ | ||
}).catch((e) => { | ||
const curl = toCurl({ method, baseURL: requestOptions.host, url: path, data, params, headers }); | ||
const curl = toCurl({ method, baseURL: requestOptions.host, url, data, params, headers }); | ||
__privateGet(this, _logger).error(`${e.message}: ${curl}`); | ||
@@ -1176,3 +1239,3 @@ error = e; | ||
"Idempotency-Key": options.idempotencyKey || __privateMethod(this, _getDefaultIdempotencyKey, getDefaultIdempotencyKey_fn).call(this, method, options.maxRetries) | ||
}, __privateGet(this, _options).headers), { | ||
}, options.headers), { | ||
"User-Agent": isBrowser ? null : __privateGet(this, _userAgent), | ||
@@ -1179,0 +1242,0 @@ "X-MAGICBELL-API-KEY": options.apiKey, |
/** | ||
* @license magicbell v1.7.2 | ||
* @license magicbell v1.8.0 | ||
* | ||
@@ -10,3 +10,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
"use strict";var ge=Object.defineProperty,ye=Object.defineProperties;var Ee=Object.getOwnPropertyDescriptors;var ee=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var D=(e,r,t)=>r in e?ge(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t,T=(e,r)=>{for(var t in r||(r={}))xe.call(r,t)&&D(e,t,r[t]);if(ee)for(var t of ee(r))be.call(r,t)&&D(e,t,r[t]);return e},L=(e,r)=>ye(e,Ee(r));var n=(e,r,t)=>(D(e,typeof r!="symbol"?r+"":r,t),t),X=(e,r,t)=>{if(!r.has(e))throw TypeError("Cannot "+t)};var x=(e,r,t)=>(X(e,r,"read from private field"),t?t.call(e):r.get(e)),b=(e,r,t)=>{if(r.has(e))throw TypeError("Cannot add the same private member more than once");r instanceof WeakSet?r.add(e):r.set(e,t)},$=(e,r,t,s)=>(X(e,r,"write to private field"),s?s.call(e,t):r.set(e,t),t);var q=(e,r,t)=>(X(e,r,"access private method"),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const Te=require("axios"),_e=require("crypto"),Pe=require("eventsource"),W=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Z=W(Te),K=W(_e),Se=W(Pe);function ne(e,r){if(!e||!r)return"";if(!K.default||!K.default.createHmac)throw new Error("This method is not available in the browser. Please provide a userHmac.");return K.default.createHmac("sha256",e).update(r).digest("base64")}function ie(){var r;const e={binding:"magicbell",binding_version:"1.7.2",publisher:"magicbell"};return typeof process>"u"?e:L(T({},e),{runtime:((r=process==null?void 0:process.release)==null?void 0:r.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch})}function ve(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function qe(e){const r=ie();return[`${r.binding}/${r.binding_version}`,"runtime"in r&&`${r.runtime}/${r.runtime_version}`,ve(e)].filter(Boolean).join(" ")}function Ae(e){return JSON.stringify(L(T({},ie()),{application:e}))}function we(e){for(const r of["code","type","status"])switch(e[r]){case"user_identifier_not_provided":return new te(e);case"invalid_request_error":return new Oe(e);case"api_error":return new $e(e);case"authentication_error":return new te(e);case"rate_limit_error":return new Ie(e);case"idempotency_error":return new Me(e);case 404:return new Be(e);case 422:return new Le(e)}return new Ue(e)}class v extends Error{constructor(t){super(t.message);n(this,"name");n(this,"message");n(this,"type");n(this,"docs_url");n(this,"code");n(this,"status");n(this,"statusText");n(this,"suggestion");this.type=this.constructor.name,this.name="MagicBellError",this.code=t.code,this.status=t.status,this.statusText=t.statusText,this.message=t.message,this.suggestion=t.suggestion,this.docs_url=t.docs_url||t.help_link}}class Oe extends v{}class Le extends v{}class $e extends v{}class te extends v{}class Ie extends v{}class Me extends v{}class Ue extends v{}class Be extends v{}function J(e){if(!e||typeof e!="object")return e;const r={};for(const t of Object.keys(e))r[ke(t)]=e[t];return r}function ke(e){const r={etag:"ETag",magicbell:"MagicBell"};return e.split("-").map(t=>r[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("-")}const A={reset:"\x1B[0m",magenta:"\x1B[35m",red:"\x1B[31m"};class Fe{constructor(){n(this,"active",!1)}debug(r){!this.active||console.log(`${A.reset}${A.magenta}magicbell:${A.reset} ${r}`)}error(r){!this.active||console.error(`${A.reset}${A.red}magicbell:${A.reset} ${r}`)}}function Ne(e){return`${e.slice(0,4)}\u2026${e.slice(-4)}`}const je=/secret|token|key|password/i;function Ge(e){return je.test(e)}function Re({method:e,baseURL:r,url:t,data:s,headers:a}){return[`curl -X ${e.toUpperCase()}`,`${r}/${t.replace(/^\//,"")}`,Object.entries(a).map(([u,o])=>`-H '${u}: ${Ge(u)?Ne(String(o)):o}'`).join(" "),s&&`-d '${JSON.stringify(s)}'`].join(" ")}const F=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);function _(e){return typeof e=="string"}function I(e){return typeof e=="boolean"}function ae(e){return Array.isArray(e)}function re(e){return Array.isArray(e)&&e.every(r=>typeof r=="string")}function Y(e){return typeof e=="number"}function w(e){return e&&typeof e=="object"}function He(e,r=!1){if(typeof e!="object")throw new Error("Argument must be an object");const t={};for(const s of Object.keys(e))e[s]!=null&&(r&&e[s]===""||(t[s]=e[s]));return t}function Ce(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}async function De(e){return new Promise(r=>setTimeout(r,e))}function Xe(...e){if(e.length<=2)return e.join(" and ");const r=e.slice(-1)[0];return[e.slice(0,-1).join(", "),r].join(", and ")}function Ke(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}const oe=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Je(e,r){return!F(e,"current_page")||!F(e,"per_page")?!1:F(e,"total_pages")?e.current_page<e.total_pages:r===e.per_page}function Ye(e,{data:r,params:t}){const s={currentPromise:null},a=typeof t.after<"u";let u=0,o=e({data:r,params:t});const h=i=>{const d=i.current_page+1;return e({data:r,params:L(T({},t),{page:d})})};function p(i){const d=Object.keys(i).find(c=>Array.isArray(i[c])),m=i[d]||i.data;if(!m||typeof m.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(u<m.length){const c=a?m.length-1-u:u,E=m[c];return u+=1,{value:E,done:!1}}return Je(i,m.length)?(u=0,o=h(i),o.then(p)):{value:void 0,done:!0}}function g(){return ze(s,(i,d)=>o.then(p).then(i).catch(d))}const y=ue(g),f=Qe(y),l={forEach:y,toArray:f,next:g,return:()=>({}),[oe]:()=>l};return Object.assign(o,l)}function ze(e,r){return e.currentPromise||(e.currentPromise=new Promise(r).then(t=>(e.currentPromise=void 0,t))),e.currentPromise}function ue(e,r){return function(s){return new Promise((a,u)=>{let o=0;function h(p){if(p.done){a();return}const g=p.value;return new Promise(y=>{y(s(g,o))}).then(y=>y===!1?(r==null||r(),h({done:!0})):(o++,e().then(h)))}e().then(h).catch(u)})}}function Qe(e){return function(t){const s=t==null?void 0:t.limit;if(!s)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(s>1e4)throw Error("You cannot specify a limit of more than 10,000 items to fetch in `toArray`; use `forEach` to iterate through longer lists.");return new Promise((a,u)=>{const o=[];e(h=>{if(o.push(h),o.length>=s)return!1}).then(()=>{a(o)}).catch(u)})}}function We(e,r={}){let t,s,a,u;const o=[];let h;const p=f=>{o.push(f),h&&(h(),h=null)};async function g(f){!s&&!u&&(u=e.request({method:"GET",path:"/config"},f).then(c=>s=c.ws.channel));const l=await e.request({method:"POST",path:"/ws/auth"},f),{token:i}=await Z.default.post(`https://rest.ably.io/keys/${l.keyName}/requestToken`,l).then(c=>c.data);await u;const d=r.sseHost||"https://realtime.ably.io",m=new URL("sse",d);m.searchParams.append("v","1.1"),m.searchParams.append("accessToken",i),m.searchParams.append("channels",s),m.searchParams.append("heartbeats","true"),a&&m.searchParams.append("lastEvent",a),t&&t.close(),t=new Se.default(m.toString()),t.onmessage=c=>{if(c.origin!==d||(a=c.lastEventId,!("data"in c)))return;const E=JSON.parse(c.data);if(E.type==="close")return p({value:null,done:!0});E.data=E.encoding==="json"?JSON.parse(E.data):E.data,p({value:E,done:!1})},t.onerror=c=>{const E="data"in c?JSON.parse(c.data):{};E.code>=40140&&E.code<40150?(t.close(),g(f)):/invalid channel id/i.test(E.message)?(t.close(),p({value:null,done:!0})):console.log("err",c)}}function y(f){g(f);const l=async()=>{o.length||await new Promise(E=>h=E);const c=o.pop();return c.done&&t&&t.close(),c},i=()=>(t.close(),p({done:!0,value:void 0}),{done:!0,value:void 0}),m={forEach:ue(l,i),close:()=>void i(),next:l,return:i,[oe]:()=>m};return m}return y}const z={host:_,maxRetryDelay:Y,timeout:Y,apiKey:_,maxRetries:Y,userEmail:_,userExternalId:_,userHmac:_,idempotencyKey:_,telemetry:I,apiSecret:_,appInfo:w,debug:I,features:w,headers:w};function V(e){var r;if(!w(e))return!1;for(const t of Object.keys(e))if(!((r=z[t])!=null&&r.call(z,e[t])))return!1;return!0}const Q={archived:I,read:I,seen:I,categories:e=>_(e)||re(e),topics:e=>_(e)||re(e)};function Ze(e){var r;if(!w(e))return!1;for(const t of Object.keys(e))if(!((r=Q[t])!=null&&r.call(Q,e[t])))return!1;return!0}function Ve(e,r,t={encode:!0}){return e.replace(/{([\s\S]+?)}/g,(s,a)=>t.encode?encodeURIComponent(r[a]||""):r[a]||"")}function et(e){return(e.match(/{\w+}/g)||[]||[]).map(t=>t.replace(/[{}]/g,""))}function tt(e){return!ae(e)||!w(e[0])?{}:V(e[0])?{}:e.shift()}function rt(e){if(!ae(e)||e.length===0)return{};const r=e[e.length-1];return V(r)?T({},e.pop()):{}}function st({path:e,method:r,args:t}){const s=[...t].filter(l=>l!==void 0),u=et(e).reduce((l,i)=>{const d=s.shift();if(typeof d!="string")throw new Error(`MagicBell: Argument "${i}" must be a string, but got ${typeof d}: ${JSON.stringify(d)} (on API request to \`${r} ${e}\`)`);return l[i]=d,l},{}),o=Ve(e,u,{encode:!1}),h=tt(s),p=rt(s);if(s.filter(l=>l!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(s)}). (on API request to \`${r} ${o}\`)`);let g=r==="GET";return r==="POST"&&Ze(h)&&(g=!0),{path:o,data:g?{}:h,params:g?h:{},options:p}}function se(e){return e?Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1:!0}class P{constructor(r){n(this,"path");n(this,"entity");n(this,"client");this.client=r}request({method:r,paged:t,path:s},...a){const{path:u,data:o,params:h,options:p}=st({path:Ke(this.path,s),method:r,args:a}),g=({data:y,params:f})=>{const l=this.entity||this.path;return y=se(y)?void 0:{[l]:y},f=se(f)?void 0:f,this.client.request({method:r,path:u,data:y,params:f},p).then(i=>i[l]||i)};return t?Ye(g,{data:o,params:h}):g({data:o,params:h})}assertFeatureFlag(r){if(!this.client.hasFlag(r))throw new Error(`This is a beta feature, please enable it by providing the "${r}" feature flag.`)}}class nt extends P{constructor(){super(...arguments);n(this,"path","broadcasts");n(this,"entity","notification")}list(t,s,a){return this.assertFeatureFlag("broadcasts-notifications-list"),this.request({method:"GET",path:"{broadcast_id}/notifications",paged:!0},t,s,a)}}class it extends P{constructor(){super(...arguments);n(this,"path","broadcasts");n(this,"entity","broadcast");n(this,"notifications",new nt(this.client))}list(t,s){return this.assertFeatureFlag("broadcasts-list"),this.request({method:"GET",paged:!0},t,s)}get(t,s){return this.assertFeatureFlag("broadcasts-get"),this.request({method:"GET",path:"{broadcast_id}"},t,s)}}class at extends P{constructor(){super(...arguments);n(this,"path","imports");n(this,"entity","import")}create(t,s){return this.assertFeatureFlag("imports-create"),this.request({method:"POST"},t,s)}get(t,s){return this.assertFeatureFlag("imports-get"),this.request({method:"GET",path:"{import_id}"},t,s)}}class ot extends P{constructor(){super(...arguments);n(this,"path","notification_preferences");n(this,"entity","notification_preferences")}get(t){return this.request({method:"GET"},t)}update(t,s){return this.request({method:"PUT"},t,s)}}class ut extends P{constructor(){super(...arguments);n(this,"path","notifications");n(this,"entity","notification")}create(t,s){return this.request({method:"POST"},t,s)}list(t,s){return this.request({method:"GET",paged:!0},t,s)}get(t,s){return this.request({method:"GET",path:"{notification_id}"},t,s)}delete(t,s){return this.request({method:"DELETE",path:"{notification_id}"},t,s)}markAsRead(t,s){return this.request({method:"POST",path:"{notification_id}/read"},t,s)}markAsUnread(t,s){return this.request({method:"POST",path:"{notification_id}/unread"},t,s)}archive(t,s){return this.request({method:"POST",path:"{notification_id}/archive"},t,s)}unarchive(t,s){return this.request({method:"DELETE",path:"{notification_id}/archive"},t,s)}markAllRead(t,s){return this.request({method:"POST",path:"read"},t,s)}markAllSeen(t,s){return this.request({method:"POST",path:"seen"},t,s)}}class ct extends P{constructor(){super(...arguments);n(this,"path","push_subscriptions");n(this,"entity","push_subscription")}create(t,s){return this.request({method:"POST"},t,s)}delete(t,s){return this.request({method:"DELETE",path:"{device_token}"},t,s)}}class lt extends P{constructor(){super(...arguments);n(this,"path","subscriptions");n(this,"entity","subscription")}list(t){return this.request({method:"GET",paged:!0},t)}create(t,s){return this.request({method:"POST"},t,s)}unsubscribe(t,s,a){return this.request({method:"POST",path:"{topic}/unsubscribe"},t,s,a)}get(t,s){return this.request({method:"GET",path:"{topic}"},t,s)}delete(t,s,a){return this.request({method:"DELETE",path:"{topic}"},t,s,a)}}class ht extends P{constructor(){super(...arguments);n(this,"path","users");n(this,"entity","push_subscription")}list(t,s,a){return this.assertFeatureFlag("users-push-subscriptions-list"),this.request({method:"GET",path:"{user_id}/push_subscriptions",paged:!0},t,s,a)}delete(t,s,a){return this.assertFeatureFlag("users-push-subscriptions-delete"),this.request({method:"DELETE",path:"{user_id}/push_subscriptions/{subscription_id}"},t,s,a)}}class dt extends P{constructor(){super(...arguments);n(this,"path","users");n(this,"entity","user");n(this,"pushSubscriptions",new ht(this.client))}create(t,s){return this.request({method:"POST"},t,s)}list(t,s){return this.request({method:"GET",paged:!0},t,s)}get(t,s){return this.request({method:"GET",path:"{user_id}"},t,s)}update(t,s,a){return this.request({method:"PUT",path:"{user_id}"},t,s,a)}delete(t,s){return this.request({method:"DELETE",path:"{user_id}"},t,s)}updateByEmail(t,s,a){return this.request({method:"PUT",path:"email:{user_email}"},t,s,a)}deleteByEmail(t,s){return this.request({method:"DELETE",path:"email:{user_email}"},t,s)}updateByExternalId(t,s,a){return this.request({method:"PUT",path:"external_id:{external_id}"},t,s,a)}deleteByExternalId(t,s){return this.request({method:"DELETE",path:"external_id:{external_id}"},t,s)}}typeof XMLHttpRequest!="function"&&(Z.default.defaults.adapter=require("axios/lib/adapters/http"));const ft={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var M,U,S,O,B,k,N,le,j,he,G,de,R,fe,H,me,C,pe;class ce{constructor(r){b(this,N);b(this,j);b(this,G);b(this,R);b(this,H);b(this,C);b(this,M,void 0);b(this,U,void 0);b(this,S,void 0);b(this,O,new Fe);b(this,B,{});b(this,k,[]);n(this,"listen",We(this));n(this,"broadcasts",new it(this));n(this,"imports",new at(this));n(this,"notificationPreferences",new ot(this));n(this,"notifications",new ut(this));n(this,"pushSubscriptions",new ct(this));n(this,"subscriptions",new lt(this));n(this,"users",new dt(this));const t=["apiKey"].filter(s=>!F(r,s));if(t.length)throw new Error(`You haven't provided all required options, please provide ${Xe(...t)} to Client(options)`);if(!V(r))throw new Error("You have provided invalid options. Please check your client options.");$(this,S,Object.assign({},ft,r)),x(this,O).active=Boolean(x(this,S).debug),$(this,U,Ae(r.appInfo)),$(this,M,qe(r.appInfo)),$(this,B,r.features||{})}hasFlag(r){return x(this,B)[r]||!1}async request({method:r,path:t,data:s,params:a},u){var g,y,f;const o=T(T({},x(this,S)),u),h=q(this,N,le).call(this,o,r),p=Math.max(0,o.maxRetries);for(let l=1;l<=p;l++){let i,d;const m=Date.now();if(x(this,O).debug(`${r} ${t}`),await Z.default({method:r,url:t,baseURL:o.host,headers:T(T({},h),J({"X-MAGICBELL-CLIENT-TELEMETRY":q(this,G,de).call(this)})),data:s,params:a,timeout:o.timeout}).then(c=>{i=c}).catch(c=>{const E=Re({method:r,baseURL:o.host,url:t,data:s,params:a,headers:h});x(this,O).error(`${c.message}: ${E}`),d=c,i=c.response}),q(this,j,he).call(this,i,{startTime:m}),q(this,R,fe).call(this,i,l,p)){const c=Number((g=i==null?void 0:i.headers)==null?void 0:g["retry-after"]);await De(q(this,H,me).call(this,l,c,o.maxRetryDelay));continue}if(d)throw we(T({code:d.code,name:d.name,message:d.message,type:d.type,status:i==null?void 0:i.status,statusText:i==null?void 0:i.statusText},(f=(y=i==null?void 0:i.data)==null?void 0:y.errors)==null?void 0:f[0]));return i.data}}}M=new WeakMap,U=new WeakMap,S=new WeakMap,O=new WeakMap,B=new WeakMap,k=new WeakMap,N=new WeakSet,le=function(r,t){let s=r.userHmac;!s&&r.apiSecret&&(r.userExternalId||r.userEmail)&&(s=ne(r.apiSecret,r.userExternalId||r.userEmail));const a=typeof document<"u";return He(J(L(T({"Accept-Version":"v2","Idempotency-Key":r.idempotencyKey||q(this,C,pe).call(this,t,r.maxRetries)},x(this,S).headers),{"User-Agent":a?null:x(this,M),"X-MAGICBELL-API-KEY":r.apiKey,"X-MAGICBELL-API-SECRET":r.apiSecret,"X-MAGICBELL-CLIENT-USER-AGENT":x(this,U),"X-MAGICBELL-USER-EMAIL":r.userEmail,"X-MAGICBELL-USER-EXTERNAL-ID":r.userExternalId,"X-MAGICBELL-USER-HMAC":s})),!0)},j=new WeakSet,he=function(r,{startTime:t}){if(!x(this,S).telemetry||!(r!=null&&r.status))return;const s=J(r.headers);x(this,k).push({id:s["X-Request-Id"],runtime:Number(s["X-Runtime"]),duration:Date.now()-t,status:r.status})},G=new WeakSet,de=function(){const r=x(this,k).pop();return r?JSON.stringify(r):null},R=new WeakSet,fe=function(r,t,s){return t>=s?!1:r?r.headers["should-retry"]?r.headers["should-retry"]==="true":r.status===409||r.status===503||r.status>=500&&r.request.method!=="POST":!0},H=new WeakSet,me=function(r,t=null,s){let u=Math.min(.5*Math.pow(r,2),s);return u*=.75*(1+Math.random()),u=Math.min(Math.max(.5,u),s),Number.isInteger(t)&&t<=60&&(u=Math.max(u,t)),u*1e3},C=new WeakSet,pe=function(r,t){if(!(r!=="POST"||t===0))return`magicbell-retry-${Ce()}`};exports.Client=ce;exports.createHmac=ne;exports.default=ce; | ||
"use strict";var ye=Object.defineProperty,Ee=Object.defineProperties;var xe=Object.getOwnPropertyDescriptors;var te=Object.getOwnPropertySymbols;var Te=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var X=(e,r,t)=>r in e?ye(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t,x=(e,r)=>{for(var t in r||(r={}))Te.call(r,t)&&X(e,t,r[t]);if(te)for(var t of te(r))be.call(r,t)&&X(e,t,r[t]);return e},w=(e,r)=>Ee(e,xe(r));var n=(e,r,t)=>(X(e,typeof r!="symbol"?r+"":r,t),t),F=(e,r,t)=>{if(!r.has(e))throw TypeError("Cannot "+t)};var T=(e,r,t)=>(F(e,r,"read from private field"),t?t.call(e):r.get(e)),b=(e,r,t)=>{if(r.has(e))throw TypeError("Cannot add the same private member more than once");r instanceof WeakSet?r.add(e):r.set(e,t)},$=(e,r,t,s)=>(F(e,r,"write to private field"),s?s.call(e,t):r.set(e,t),t);var v=(e,r,t)=>(F(e,r,"access private method"),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const _e=require("axios"),Pe=require("crypto"),Se=require("eventsource"),W=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Z=W(_e),K=W(Pe),qe=W(Se);function ie(e,r){if(!e||!r)return"";if(!K.default||!K.default.createHmac)throw new Error("This method is not available in the browser. Please provide a userHmac.");return K.default.createHmac("sha256",e).update(r).digest("base64")}function ae(){var r;const e={binding:"magicbell",binding_version:"1.8.0",publisher:"magicbell"};return typeof process>"u"?e:w(x({},e),{runtime:((r=process==null?void 0:process.release)==null?void 0:r.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch})}function ve(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function we(e){const r=ae();return[`${r.binding}/${r.binding_version}`,"runtime"in r&&`${r.runtime}/${r.runtime_version}`,ve(e)].filter(Boolean).join(" ")}function Ae(e){return JSON.stringify(w(x({},ae()),{application:e}))}function Oe(e){for(const r of["code","type","status"])switch(e[r]){case"user_identifier_not_provided":return new re(e);case"invalid_request_error":return new Le(e);case"api_error":return new Ie(e);case"authentication_error":return new re(e);case"rate_limit_error":return new Me(e);case"idempotency_error":return new Ue(e);case 404:return new Ge(e);case 422:return new $e(e)}return new Be(e)}class q extends Error{constructor(t){super(t.message);n(this,"name");n(this,"message");n(this,"type");n(this,"docs_url");n(this,"code");n(this,"status");n(this,"statusText");n(this,"suggestion");this.type=this.constructor.name,this.name="MagicBellError",this.code=t.code,this.status=t.status,this.statusText=t.statusText,this.message=t.message,this.suggestion=t.suggestion,this.docs_url=t.docs_url||t.help_link}}class Le extends q{}class $e extends q{}class Ie extends q{}class re extends q{}class Me extends q{}class Ue extends q{}class Be extends q{}class Ge extends q{}function J(e){if(!e||typeof e!="object")return e;const r={};for(const t of Object.keys(e))r[Ne(t)]=e[t];return r}function Ne(e){const r={etag:"ETag",magicbell:"MagicBell"};return e.split("-").map(t=>r[t.toLowerCase()]||t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("-")}const A={reset:"\x1B[0m",magenta:"\x1B[35m",red:"\x1B[31m"};class ke{constructor(){n(this,"active",!1)}debug(r){!this.active||console.log(`${A.reset}${A.magenta}magicbell:${A.reset} ${r}`)}error(r){!this.active||console.error(`${A.reset}${A.red}magicbell:${A.reset} ${r}`)}}function je(e){return`${e.slice(0,4)}\u2026${e.slice(-4)}`}const Re=/secret|token|key|password/i;function He(e){return Re.test(e)}function Ce({method:e,baseURL:r,url:t,data:s,headers:i}){return[`curl -X ${e.toUpperCase()}`,`${r}/${t.replace(/^\//,"")}`,Object.entries(i).map(([o,c])=>`-H '${o}: ${He(o)?je(String(c)):c}'`).join(" "),s&&`-d '${JSON.stringify(s)}'`].join(" ")}const N=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);function P(e){return typeof e=="string"}function I(e){return typeof e=="boolean"}function oe(e){return Array.isArray(e)}function se(e){return Array.isArray(e)&&e.every(r=>typeof r=="string")}function Y(e){return typeof e=="number"}function O(e){return e&&typeof e=="object"}function De(e,r=!1){if(typeof e!="object")throw new Error("Argument must be an object");const t={};for(const s of Object.keys(e))e[s]!=null&&(r&&e[s]===""||(t[s]=e[s]));return t}function Xe(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}async function Fe(e){return new Promise(r=>setTimeout(r,e))}function Ke(...e){if(e.length<=2)return e.join(" and ");const r=e.slice(-1)[0];return[e.slice(0,-1).join(", "),r].join(", and ")}function Je(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}const ue=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Ye(e,r){return!N(e,"current_page")||!N(e,"per_page")?!1:N(e,"total_pages")?e.current_page<e.total_pages:r===e.per_page}function ze(e,{data:r,params:t}){const s={currentPromise:null},i=typeof t.after<"u";let o=0,c=e({data:r,params:t});const h=u=>{const a=u.current_page+1;return e({data:r,params:w(x({},t),{page:a})})};function g(u){const a=Object.keys(u).find(m=>Array.isArray(u[m])),l=u[a]||u.data;if(!l||typeof l.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(o<l.length){const m=i?l.length-1-o:o,d=l[m];return o+=1,{value:d,done:!1}}return Ye(u,l.length)?(o=0,c=h(u),c.then(g)):{value:void 0,done:!0}}function y(){return Qe(s,(u,a)=>c.then(g).then(u).catch(a))}const E=ce(y),p=We(E),f={forEach:E,toArray:p,next:y,return:()=>({}),[ue]:()=>f};return Object.assign(c,f)}function Qe(e,r){return e.currentPromise||(e.currentPromise=new Promise(r).then(t=>(e.currentPromise=void 0,t))),e.currentPromise}function ce(e,r){return function(s){return new Promise((i,o)=>{let c=0;function h(g){if(g.done){i();return}const y=g.value;return new Promise(E=>{E(s(y,c))}).then(E=>E===!1?(r==null||r(),h({done:!0})):(c++,e().then(h)))}e().then(h).catch(o)})}}function We(e){return function(t){const s=t==null?void 0:t.limit;if(!s)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(s>1e4)throw Error("You cannot specify a limit of more than 10,000 items to fetch in `toArray`; use `forEach` to iterate through longer lists.");return new Promise((i,o)=>{const c=[];e(h=>{if(c.push(h),c.length>=s)return!1}).then(()=>{i(c)}).catch(o)})}}function Ze(e,r={}){let t,s,i,o;const c=[];let h;const g=p=>{c.push(p),h&&(h(),h=null)};async function y(p){!s&&!o&&(o=e.request({method:"GET",path:"/config"},p).then(m=>s=m.ws.channel));const f=await e.request({method:"POST",path:"/ws/auth"},p),{token:u}=await Z.default.post(`https://rest.ably.io/keys/${f.keyName}/requestToken`,f).then(m=>m.data);await o;const a=r.sseHost||"https://realtime.ably.io",l=new URL("sse",a);l.searchParams.append("v","1.1"),l.searchParams.append("accessToken",u),l.searchParams.append("channels",s),l.searchParams.append("heartbeats","true"),i&&l.searchParams.append("lastEvent",i),t&&t.close(),t=new qe.default(l.toString()),t.onmessage=m=>{if(m.origin!==a||(i=m.lastEventId,!("data"in m)))return;const d=JSON.parse(m.data);if(d.type==="close")return g({value:null,done:!0});d.data=d.encoding==="json"?JSON.parse(d.data):d.data,g({value:d,done:!1})},t.onerror=m=>{const d="data"in m?JSON.parse(m.data):{};d.code>=40140&&d.code<40150?(t.close(),y(p)):/invalid channel id/i.test(d.message)?(t.close(),g({value:null,done:!0})):console.log("err",m)}}function E(p){y(p);const f=async()=>{c.length||await new Promise(d=>h=d);const m=c.pop();return m.done&&t&&t.close(),m},u=()=>(t.close(),g({done:!0,value:void 0}),{done:!0,value:void 0}),l={forEach:ce(f,u),close:()=>void u(),next:f,return:u,[ue]:()=>l};return l}return E}const z={host:P,maxRetryDelay:Y,timeout:Y,apiKey:P,maxRetries:Y,userEmail:P,userExternalId:P,userHmac:P,idempotencyKey:P,telemetry:I,apiSecret:P,appInfo:O,debug:I,features:O,headers:O};function V(e){var r;if(!O(e))return!1;for(const t of Object.keys(e))if(!((r=z[t])!=null&&r.call(z,e[t])))return!1;return!0}const Q={archived:I,read:I,seen:I,categories:e=>P(e)||se(e),topics:e=>P(e)||se(e)};function Ve(e){var r;if(!O(e))return!1;for(const t of Object.keys(e))if(!((r=Q[t])!=null&&r.call(Q,e[t])))return!1;return!0}function et(e,r,t={encode:!0}){return e.replace(/{([\s\S]+?)}/g,(s,i)=>t.encode?encodeURIComponent(r[i]||""):r[i]||"")}function tt(e){return(e.match(/{\w+}/g)||[]||[]).map(t=>t.replace(/[{}]/g,""))}function rt(e){return!oe(e)||!O(e[0])?{}:V(e[0])?{}:e.shift()}function st(e){if(!oe(e)||e.length===0)return{};const r=e[e.length-1];return V(r)?x({},e.pop()):{}}function nt({path:e,method:r,args:t}){const s=[...t].filter(f=>f!==void 0),o=tt(e).reduce((f,u)=>{const a=s.shift();if(typeof a!="string")throw new Error(`MagicBell: Argument "${u}" must be a string, but got ${typeof a}: ${JSON.stringify(a)} (on API request to \`${r} ${e}\`)`);return f[u]=a,f},{}),c=et(e,o,{encode:!1}),h=rt(s),g=st(s);if(s.filter(f=>f!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(s)}). (on API request to \`${r} ${c}\`)`);let y=r==="GET";return r==="POST"&&Ve(h)&&(y=!0),{path:c,data:y?{}:h,params:y?h:{},options:g}}function ne(e){return e?Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1:!0}class _{constructor(r){n(this,"path");n(this,"entity");n(this,"client");this.client=r}request({method:r,paged:t,path:s},...i){const{path:o,data:c,params:h,options:g}=nt({path:Je(this.path,s),method:r,args:i}),y=({data:E,params:p})=>{const f=this.entity||this.path;return E=ne(E)?void 0:{[f]:E},p=ne(p)?void 0:p,this.client.request({method:r,path:o,data:E,params:p},g).then(u=>u[f]||u)};return t?ze(y,{data:c,params:h}):y({data:c,params:h})}assertFeatureFlag(r){if(!this.client.hasFlag(r))throw new Error(`This is a beta feature, please enable it by providing the "${r}" feature flag.`)}}class it extends _{constructor(){super(...arguments);n(this,"path","broadcasts");n(this,"entity","notification")}list(t,s,i){return this.request({method:"GET",path:"{broadcast_id}/notifications",paged:!0},t,s,i)}}class at extends _{constructor(){super(...arguments);n(this,"path","broadcasts");n(this,"entity","broadcast");n(this,"notifications",new it(this.client))}list(t,s){return this.request({method:"GET",paged:!0},t,s)}get(t,s){return this.request({method:"GET",path:"{broadcast_id}"},t,s)}}class ot extends _{constructor(){super(...arguments);n(this,"path","imports");n(this,"entity","import")}create(t,s){return this.request({method:"POST"},t,s)}get(t,s){return this.request({method:"GET",path:"{import_id}"},t,s)}}class ut extends _{constructor(){super(...arguments);n(this,"path","metrics");n(this,"entity","categorie")}get(t){return this.request({method:"GET",path:"categories"},t)}}class ct extends _{constructor(){super(...arguments);n(this,"path","metrics");n(this,"entity","topic")}get(t){return this.request({method:"GET",path:"topics"},t)}}class ht extends _{constructor(){super(...arguments);n(this,"path","metrics");n(this,"entity","metric");n(this,"categories",new ut(this.client));n(this,"topics",new ct(this.client))}get(t){return this.request({method:"GET"},t)}}class lt extends _{constructor(){super(...arguments);n(this,"path","notification_preferences");n(this,"entity","notification_preferences")}get(t){return this.request({method:"GET"},t)}update(t,s){return this.request({method:"PUT"},t,s)}}class dt extends _{constructor(){super(...arguments);n(this,"path","notifications");n(this,"entity","notification")}create(t,s){return this.request({method:"POST"},t,s)}list(t,s){return this.request({method:"GET",paged:!0},t,s)}get(t,s){return this.request({method:"GET",path:"{notification_id}"},t,s)}delete(t,s){return this.request({method:"DELETE",path:"{notification_id}"},t,s)}markAsRead(t,s){return this.request({method:"POST",path:"{notification_id}/read"},t,s)}markAsUnread(t,s){return this.request({method:"POST",path:"{notification_id}/unread"},t,s)}archive(t,s){return this.request({method:"POST",path:"{notification_id}/archive"},t,s)}unarchive(t,s){return this.request({method:"DELETE",path:"{notification_id}/archive"},t,s)}markAllRead(t,s){return this.request({method:"POST",path:"read"},t,s)}markAllSeen(t,s){return this.request({method:"POST",path:"seen"},t,s)}}class ft extends _{constructor(){super(...arguments);n(this,"path","push_subscriptions");n(this,"entity","push_subscription")}create(t,s){return this.request({method:"POST"},t,s)}delete(t,s){return this.request({method:"DELETE",path:"{device_token}"},t,s)}}class mt extends _{constructor(){super(...arguments);n(this,"path","subscriptions");n(this,"entity","subscription")}list(t){return this.request({method:"GET",paged:!0},t)}create(t,s){return this.request({method:"POST"},t,s)}unsubscribe(t,s,i){return this.request({method:"POST",path:"{topic}/unsubscribe"},t,s,i)}get(t,s){return this.request({method:"GET",path:"{topic}"},t,s)}delete(t,s,i){return this.request({method:"DELETE",path:"{topic}"},t,s,i)}}class pt extends _{constructor(){super(...arguments);n(this,"path","users");n(this,"entity","notification")}list(t,s,i){return this.request({method:"GET",path:"{user_id}/notifications",paged:!0},t,s,i)}}class gt extends _{constructor(){super(...arguments);n(this,"path","users");n(this,"entity","push_subscription")}list(t,s,i){return this.request({method:"GET",path:"{user_id}/push_subscriptions",paged:!0},t,s,i)}delete(t,s,i){return this.request({method:"DELETE",path:"{user_id}/push_subscriptions/{subscription_id}"},t,s,i)}}class yt extends _{constructor(){super(...arguments);n(this,"path","users");n(this,"entity","user");n(this,"notifications",new pt(this.client));n(this,"pushSubscriptions",new gt(this.client))}create(t,s){return this.request({method:"POST"},t,s)}list(t,s){return this.request({method:"GET",paged:!0},t,s)}get(t,s){return this.request({method:"GET",path:"{user_id}"},t,s)}update(t,s,i){return this.request({method:"PUT",path:"{user_id}"},t,s,i)}delete(t,s){return this.request({method:"DELETE",path:"{user_id}"},t,s)}updateByEmail(t,s,i){return this.request({method:"PUT",path:"email:{user_email}"},t,s,i)}deleteByEmail(t,s){return this.request({method:"DELETE",path:"email:{user_email}"},t,s)}updateByExternalId(t,s,i){return this.request({method:"PUT",path:"external_id:{external_id}"},t,s,i)}deleteByExternalId(t,s){return this.request({method:"DELETE",path:"external_id:{external_id}"},t,s)}}typeof XMLHttpRequest!="function"&&(Z.default.defaults.adapter=require("axios/lib/adapters/http"));const Et={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var M,U,S,L,B,G,k,le,j,de,R,fe,H,me,C,pe,D,ge;class he{constructor(r){b(this,k);b(this,j);b(this,R);b(this,H);b(this,C);b(this,D);b(this,M,void 0);b(this,U,void 0);b(this,S,void 0);b(this,L,new ke);b(this,B,{});b(this,G,[]);n(this,"listen",Ze(this));n(this,"broadcasts",new at(this));n(this,"imports",new ot(this));n(this,"metrics",new ht(this));n(this,"notificationPreferences",new lt(this));n(this,"notifications",new dt(this));n(this,"pushSubscriptions",new ft(this));n(this,"subscriptions",new mt(this));n(this,"users",new yt(this));const t=["apiKey"].filter(s=>!N(r,s));if(t.length)throw new Error(`You haven't provided all required options, please provide ${Ke(...t)} to Client(options)`);if(!V(r))throw new Error("You have provided invalid options. Please check your client options.");$(this,S,Object.assign({},Et,r)),T(this,L).active=Boolean(T(this,S).debug),$(this,U,Ae(r.appInfo)),$(this,M,we(r.appInfo)),$(this,B,r.features||{})}hasFlag(r){return T(this,B)[r]||!1}async request({method:r,path:t,data:s,params:i,headers:o},c){var E,p,f;const h=w(x(x({},T(this,S)),c),{headers:x(x({},T(this,S).headers),o)}),g=v(this,k,le).call(this,h,r),y=Math.max(0,h.maxRetries);for(let u=1;u<=y;u++){let a,l;const m=Date.now();if(T(this,L).debug(`${r} ${t}`),await Z.default({method:r,url:t,baseURL:h.host,headers:x(x({},g),J({"X-MAGICBELL-CLIENT-TELEMETRY":v(this,R,fe).call(this)})),data:s,params:i,timeout:h.timeout}).then(d=>{a=d}).catch(d=>{const ee=Ce({method:r,baseURL:h.host,url:t,data:s,params:i,headers:g});T(this,L).error(`${d.message}: ${ee}`),l=d,a=d.response}),v(this,j,de).call(this,a,{startTime:m}),v(this,H,me).call(this,a,u,y)){const d=Number((E=a==null?void 0:a.headers)==null?void 0:E["retry-after"]);await Fe(v(this,C,pe).call(this,u,d,h.maxRetryDelay));continue}if(l)throw Oe(x({code:l.code,name:l.name,message:l.message,type:l.type,status:a==null?void 0:a.status,statusText:a==null?void 0:a.statusText},(f=(p=a==null?void 0:a.data)==null?void 0:p.errors)==null?void 0:f[0]));return a.data}}}M=new WeakMap,U=new WeakMap,S=new WeakMap,L=new WeakMap,B=new WeakMap,G=new WeakMap,k=new WeakSet,le=function(r,t){let s=r.userHmac;!s&&r.apiSecret&&(r.userExternalId||r.userEmail)&&(s=ie(r.apiSecret,r.userExternalId||r.userEmail));const i=typeof document<"u";return De(J(w(x({"Accept-Version":"v2","Idempotency-Key":r.idempotencyKey||v(this,D,ge).call(this,t,r.maxRetries)},r.headers),{"User-Agent":i?null:T(this,M),"X-MAGICBELL-API-KEY":r.apiKey,"X-MAGICBELL-API-SECRET":r.apiSecret,"X-MAGICBELL-CLIENT-USER-AGENT":T(this,U),"X-MAGICBELL-USER-EMAIL":r.userEmail,"X-MAGICBELL-USER-EXTERNAL-ID":r.userExternalId,"X-MAGICBELL-USER-HMAC":s})),!0)},j=new WeakSet,de=function(r,{startTime:t}){if(!T(this,S).telemetry||!(r!=null&&r.status))return;const s=J(r.headers);T(this,G).push({id:s["X-Request-Id"],runtime:Number(s["X-Runtime"]),duration:Date.now()-t,status:r.status})},R=new WeakSet,fe=function(){const r=T(this,G).pop();return r?JSON.stringify(r):null},H=new WeakSet,me=function(r,t,s){return t>=s?!1:r?r.headers["should-retry"]?r.headers["should-retry"]==="true":r.status===409||r.status===503||r.status>=500&&r.request.method!=="POST":!0},C=new WeakSet,pe=function(r,t=null,s){let o=Math.min(.5*Math.pow(r,2),s);return o*=.75*(1+Math.random()),o=Math.min(Math.max(.5,o),s),Number.isInteger(t)&&t<=60&&(o=Math.max(o,t)),o*1e3},D=new WeakSet,ge=function(r,t){if(!(r!=="POST"||t===0))return`magicbell-retry-${Xe()}`};exports.Client=he;exports.createHmac=ie;exports.default=he; | ||
//# sourceMappingURL=magicbell.cjs.min.js.map |
/** | ||
* @license magicbell v1.7.2 | ||
* @license magicbell v1.8.0 | ||
* | ||
@@ -71,3 +71,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "1.7.2", | ||
binding_version: "1.8.0", | ||
publisher: "magicbell" | ||
@@ -625,3 +625,2 @@ }; | ||
list(broadcastId, dataOrOptions, options) { | ||
this.assertFeatureFlag("broadcasts-notifications-list"); | ||
return this.request( | ||
@@ -647,3 +646,2 @@ { | ||
list(dataOrOptions, options) { | ||
this.assertFeatureFlag("broadcasts-list"); | ||
return this.request( | ||
@@ -659,3 +657,2 @@ { | ||
get(broadcastId, options) { | ||
this.assertFeatureFlag("broadcasts-get"); | ||
return this.request( | ||
@@ -678,3 +675,2 @@ { | ||
create(dataOrOptions, options) { | ||
this.assertFeatureFlag("imports-create"); | ||
return this.request( | ||
@@ -689,3 +685,2 @@ { | ||
get(importId, options) { | ||
this.assertFeatureFlag("imports-get"); | ||
return this.request( | ||
@@ -701,2 +696,51 @@ { | ||
} | ||
class MetricsCategories extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "metrics"); | ||
__publicField(this, "entity", "categorie"); | ||
} | ||
get(options) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "categories" | ||
}, | ||
options | ||
); | ||
} | ||
} | ||
class MetricsTopics extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "metrics"); | ||
__publicField(this, "entity", "topic"); | ||
} | ||
get(options) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "topics" | ||
}, | ||
options | ||
); | ||
} | ||
} | ||
class Metrics extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "metrics"); | ||
__publicField(this, "entity", "metric"); | ||
__publicField(this, "categories", new MetricsCategories(this.client)); | ||
__publicField(this, "topics", new MetricsTopics(this.client)); | ||
} | ||
get(options) { | ||
return this.request( | ||
{ | ||
method: "GET" | ||
}, | ||
options | ||
); | ||
} | ||
} | ||
class NotificationPreferences extends Resource { | ||
@@ -915,2 +959,21 @@ constructor() { | ||
} | ||
class UsersNotifications extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "users"); | ||
__publicField(this, "entity", "notification"); | ||
} | ||
list(userId, dataOrOptions, options) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "{user_id}/notifications", | ||
paged: true | ||
}, | ||
userId, | ||
dataOrOptions, | ||
options | ||
); | ||
} | ||
} | ||
class UsersPushSubscriptions extends Resource { | ||
@@ -923,3 +986,2 @@ constructor() { | ||
list(userId, dataOrOptions, options) { | ||
this.assertFeatureFlag("users-push-subscriptions-list"); | ||
return this.request( | ||
@@ -937,3 +999,2 @@ { | ||
delete(userId, subscriptionId, options) { | ||
this.assertFeatureFlag("users-push-subscriptions-delete"); | ||
return this.request( | ||
@@ -955,2 +1016,3 @@ { | ||
__publicField(this, "entity", "user"); | ||
__publicField(this, "notifications", new UsersNotifications(this.client)); | ||
__publicField(this, "pushSubscriptions", new UsersPushSubscriptions(this.client)); | ||
@@ -1078,2 +1140,3 @@ } | ||
__publicField(this, "imports", new Imports(this)); | ||
__publicField(this, "metrics", new Metrics(this)); | ||
__publicField(this, "notificationPreferences", new NotificationPreferences(this)); | ||
@@ -1102,5 +1165,5 @@ __publicField(this, "notifications", new Notifications(this)); | ||
} | ||
async request({ method, path, data, params }, options) { | ||
async request({ method, path: url, data, params, headers: reqHeaders }, options) { | ||
var _a, _b, _c; | ||
const requestOptions = __spreadValues(__spreadValues({}, __privateGet(this, _options)), options); | ||
const requestOptions = __spreadProps(__spreadValues(__spreadValues({}, __privateGet(this, _options)), options), { headers: __spreadValues(__spreadValues({}, __privateGet(this, _options).headers), reqHeaders) }); | ||
const headers = __privateMethod(this, _getHeaders, getHeaders_fn).call(this, requestOptions, method); | ||
@@ -1112,6 +1175,6 @@ const maxRetries = Math.max(0, requestOptions.maxRetries); | ||
const startTime = Date.now(); | ||
__privateGet(this, _logger).debug(`${method} ${path}`); | ||
__privateGet(this, _logger).debug(`${method} ${url}`); | ||
await axios({ | ||
method, | ||
url: path, | ||
url, | ||
baseURL: requestOptions.host, | ||
@@ -1127,3 +1190,3 @@ headers: __spreadValues(__spreadValues({}, headers), normalizeHeaders({ | ||
}).catch((e) => { | ||
const curl = toCurl({ method, baseURL: requestOptions.host, url: path, data, params, headers }); | ||
const curl = toCurl({ method, baseURL: requestOptions.host, url, data, params, headers }); | ||
__privateGet(this, _logger).error(`${e.message}: ${curl}`); | ||
@@ -1170,3 +1233,3 @@ error = e; | ||
"Idempotency-Key": options.idempotencyKey || __privateMethod(this, _getDefaultIdempotencyKey, getDefaultIdempotencyKey_fn).call(this, method, options.maxRetries) | ||
}, __privateGet(this, _options).headers), { | ||
}, options.headers), { | ||
"User-Agent": isBrowser ? null : __privateGet(this, _userAgent), | ||
@@ -1173,0 +1236,0 @@ "X-MAGICBELL-API-KEY": options.apiKey, |
/** | ||
* @license magicbell v1.7.2 | ||
* @license magicbell v1.8.0 | ||
* | ||
@@ -10,28 +10,28 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
var fe = Object.defineProperty, me = Object.defineProperties; | ||
var pe = Object.getOwnPropertyDescriptors; | ||
var V = Object.getOwnPropertySymbols; | ||
var ge = Object.prototype.hasOwnProperty, ye = Object.prototype.propertyIsEnumerable; | ||
var D = (e, r, t) => r in e ? fe(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t, T = (e, r) => { | ||
var fe = Object.defineProperty, pe = Object.defineProperties; | ||
var ge = Object.getOwnPropertyDescriptors; | ||
var ee = Object.getOwnPropertySymbols; | ||
var ye = Object.prototype.hasOwnProperty, Ee = Object.prototype.propertyIsEnumerable; | ||
var X = (e, r, t) => r in e ? fe(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t, x = (e, r) => { | ||
for (var t in r || (r = {})) | ||
ge.call(r, t) && D(e, t, r[t]); | ||
if (V) | ||
for (var t of V(r)) | ||
ye.call(r, t) && D(e, t, r[t]); | ||
ye.call(r, t) && X(e, t, r[t]); | ||
if (ee) | ||
for (var t of ee(r)) | ||
Ee.call(r, t) && X(e, t, r[t]); | ||
return e; | ||
}, L = (e, r) => me(e, pe(r)); | ||
var n = (e, r, t) => (D(e, typeof r != "symbol" ? r + "" : r, t), t), X = (e, r, t) => { | ||
}, A = (e, r) => pe(e, ge(r)); | ||
var n = (e, r, t) => (X(e, typeof r != "symbol" ? r + "" : r, t), t), F = (e, r, t) => { | ||
if (!r.has(e)) | ||
throw TypeError("Cannot " + t); | ||
}; | ||
var x = (e, r, t) => (X(e, r, "read from private field"), t ? t.call(e) : r.get(e)), b = (e, r, t) => { | ||
var T = (e, r, t) => (F(e, r, "read from private field"), t ? t.call(e) : r.get(e)), b = (e, r, t) => { | ||
if (r.has(e)) | ||
throw TypeError("Cannot add the same private member more than once"); | ||
r instanceof WeakSet ? r.add(e) : r.set(e, t); | ||
}, $ = (e, r, t, s) => (X(e, r, "write to private field"), s ? s.call(e, t) : r.set(e, t), t); | ||
var v = (e, r, t) => (X(e, r, "access private method"), t); | ||
}, $ = (e, r, t, s) => (F(e, r, "write to private field"), s ? s.call(e, t) : r.set(e, t), t); | ||
var w = (e, r, t) => (F(e, r, "access private method"), t); | ||
import W from "axios"; | ||
import K from "crypto"; | ||
import Ee from "eventsource"; | ||
function xe(e, r) { | ||
import xe from "eventsource"; | ||
function Te(e, r) { | ||
if (!e || !r) | ||
@@ -43,10 +43,10 @@ return ""; | ||
} | ||
function se() { | ||
function ne() { | ||
var r; | ||
const e = { | ||
binding: "magicbell", | ||
binding_version: "1.7.2", | ||
binding_version: "1.8.0", | ||
publisher: "magicbell" | ||
}; | ||
return typeof process > "u" ? e : L(T({}, e), { | ||
return typeof process > "u" ? e : A(x({}, e), { | ||
runtime: ((r = process == null ? void 0 : process.release) == null ? void 0 : r.name) || "node", | ||
@@ -61,4 +61,4 @@ runtime_version: process.version, | ||
} | ||
function Te(e) { | ||
const r = se(); | ||
function Pe(e) { | ||
const r = ne(); | ||
return [ | ||
@@ -70,28 +70,28 @@ `${r.binding}/${r.binding_version}`, | ||
} | ||
function Pe(e) { | ||
return JSON.stringify(L(T({}, se()), { application: e })); | ||
function Se(e) { | ||
return JSON.stringify(A(x({}, ne()), { application: e })); | ||
} | ||
function Se(e) { | ||
function _e(e) { | ||
for (const r of ["code", "type", "status"]) | ||
switch (e[r]) { | ||
case "user_identifier_not_provided": | ||
return new ee(e); | ||
return new te(e); | ||
case "invalid_request_error": | ||
return new _e(e); | ||
return new qe(e); | ||
case "api_error": | ||
return new ve(e); | ||
return new Ae(e); | ||
case "authentication_error": | ||
return new ee(e); | ||
return new te(e); | ||
case "rate_limit_error": | ||
return new qe(e); | ||
return new ve(e); | ||
case "idempotency_error": | ||
return new we(e); | ||
return new Oe(e); | ||
case 404: | ||
return new Le(e); | ||
return new $e(e); | ||
case 422: | ||
return new Ae(e); | ||
return new we(e); | ||
} | ||
return new Oe(e); | ||
return new Le(e); | ||
} | ||
class A extends Error { | ||
class q extends Error { | ||
constructor(t) { | ||
@@ -110,17 +110,17 @@ super(t.message); | ||
} | ||
class _e extends A { | ||
class qe extends q { | ||
} | ||
class Ae extends A { | ||
class we extends q { | ||
} | ||
class ve extends A { | ||
class Ae extends q { | ||
} | ||
class ee extends A { | ||
class te extends q { | ||
} | ||
class qe extends A { | ||
class ve extends q { | ||
} | ||
class we extends A { | ||
class Oe extends q { | ||
} | ||
class Oe extends A { | ||
class Le extends q { | ||
} | ||
class Le extends A { | ||
class $e extends q { | ||
} | ||
@@ -132,6 +132,6 @@ function J(e) { | ||
for (const t of Object.keys(e)) | ||
r[$e(t)] = e[t]; | ||
r[Ie(t)] = e[t]; | ||
return r; | ||
} | ||
function $e(e) { | ||
function Ie(e) { | ||
const r = { | ||
@@ -143,3 +143,3 @@ etag: "ETag", | ||
} | ||
const q = { | ||
const v = { | ||
reset: "\x1B[0m", | ||
@@ -149,3 +149,3 @@ magenta: "\x1B[35m", | ||
}; | ||
class Ie { | ||
class Me { | ||
constructor() { | ||
@@ -155,25 +155,25 @@ n(this, "active", !1); | ||
debug(r) { | ||
!this.active || console.log(`${q.reset}${q.magenta}magicbell:${q.reset} ${r}`); | ||
!this.active || console.log(`${v.reset}${v.magenta}magicbell:${v.reset} ${r}`); | ||
} | ||
error(r) { | ||
!this.active || console.error(`${q.reset}${q.red}magicbell:${q.reset} ${r}`); | ||
!this.active || console.error(`${v.reset}${v.red}magicbell:${v.reset} ${r}`); | ||
} | ||
} | ||
function Me(e) { | ||
function Ue(e) { | ||
return `${e.slice(0, 4)}\u2026${e.slice(-4)}`; | ||
} | ||
const Ue = /secret|token|key|password/i; | ||
function Be(e) { | ||
return Ue.test(e); | ||
const Be = /secret|token|key|password/i; | ||
function Ge(e) { | ||
return Be.test(e); | ||
} | ||
function ke({ method: e, baseURL: r, url: t, data: s, headers: a }) { | ||
function Ne({ method: e, baseURL: r, url: t, data: s, headers: i }) { | ||
return [ | ||
`curl -X ${e.toUpperCase()}`, | ||
`${r}/${t.replace(/^\//, "")}`, | ||
Object.entries(a).map(([u, o]) => `-H '${u}: ${Be(u) ? Me(String(o)) : o}'`).join(" "), | ||
Object.entries(i).map(([a, c]) => `-H '${a}: ${Ge(a) ? Ue(String(c)) : c}'`).join(" "), | ||
s && `-d '${JSON.stringify(s)}'` | ||
].join(" "); | ||
} | ||
const F = (e, r) => Object.prototype.hasOwnProperty.call(e, r); | ||
function P(e) { | ||
const N = (e, r) => Object.prototype.hasOwnProperty.call(e, r); | ||
function S(e) { | ||
return typeof e == "string"; | ||
@@ -184,6 +184,6 @@ } | ||
} | ||
function ne(e) { | ||
function ie(e) { | ||
return Array.isArray(e); | ||
} | ||
function te(e) { | ||
function re(e) { | ||
return Array.isArray(e) && e.every((r) => typeof r == "string"); | ||
@@ -194,6 +194,6 @@ } | ||
} | ||
function w(e) { | ||
function O(e) { | ||
return e && typeof e == "object"; | ||
} | ||
function Fe(e, r = !1) { | ||
function ke(e, r = !1) { | ||
if (typeof e != "object") | ||
@@ -206,3 +206,3 @@ throw new Error("Argument must be an object"); | ||
} | ||
function Ne() { | ||
function Re() { | ||
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => { | ||
@@ -213,6 +213,6 @@ const r = Math.random() * 16 | 0; | ||
} | ||
async function Ge(e) { | ||
async function je(e) { | ||
return new Promise((r) => setTimeout(r, e)); | ||
} | ||
function Re(...e) { | ||
function He(...e) { | ||
if (e.length <= 2) | ||
@@ -223,39 +223,39 @@ return e.join(" and "); | ||
} | ||
function je(...e) { | ||
function Ce(...e) { | ||
return ["/", ...e].join("/").replace(/\/+/g, "/").replace(/\/$/, ""); | ||
} | ||
const ie = typeof Symbol < "u" && Symbol.asyncIterator ? Symbol.asyncIterator : "@@asyncIterator"; | ||
function He(e, r) { | ||
return !F(e, "current_page") || !F(e, "per_page") ? !1 : F(e, "total_pages") ? e.current_page < e.total_pages : r === e.per_page; | ||
const oe = typeof Symbol < "u" && Symbol.asyncIterator ? Symbol.asyncIterator : "@@asyncIterator"; | ||
function De(e, r) { | ||
return !N(e, "current_page") || !N(e, "per_page") ? !1 : N(e, "total_pages") ? e.current_page < e.total_pages : r === e.per_page; | ||
} | ||
function Ce(e, { data: r, params: t }) { | ||
const s = { currentPromise: null }, a = typeof t.after < "u"; | ||
let u = 0, o = e({ data: r, params: t }); | ||
const l = (i) => { | ||
const d = i.current_page + 1; | ||
return e({ data: r, params: L(T({}, t), { page: d }) }); | ||
function Xe(e, { data: r, params: t }) { | ||
const s = { currentPromise: null }, i = typeof t.after < "u"; | ||
let a = 0, c = e({ data: r, params: t }); | ||
const h = (u) => { | ||
const o = u.current_page + 1; | ||
return e({ data: r, params: A(x({}, t), { page: o }) }); | ||
}; | ||
function p(i) { | ||
const d = Object.keys(i).find((c) => Array.isArray(i[c])), m = i[d] || i.data; | ||
if (!m || typeof m.length != "number") | ||
function g(u) { | ||
const o = Object.keys(u).find((f) => Array.isArray(u[f])), l = u[o] || u.data; | ||
if (!l || typeof l.length != "number") | ||
throw Error("Unexpected: MagicBell API response does not have a well-formed response."); | ||
if (u < m.length) { | ||
const c = a ? m.length - 1 - u : u, E = m[c]; | ||
return u += 1, { value: E, done: !1 }; | ||
if (a < l.length) { | ||
const f = i ? l.length - 1 - a : a, d = l[f]; | ||
return a += 1, { value: d, done: !1 }; | ||
} | ||
return He(i, m.length) ? (u = 0, o = l(i), o.then(p)) : { value: void 0, done: !0 }; | ||
return De(u, l.length) ? (a = 0, c = h(u), c.then(g)) : { value: void 0, done: !0 }; | ||
} | ||
function g() { | ||
return De(s, (i, d) => o.then(p).then(i).catch(d)); | ||
function y() { | ||
return Fe(s, (u, o) => c.then(g).then(u).catch(o)); | ||
} | ||
const y = ae(g), f = Xe(y), h = { | ||
forEach: y, | ||
toArray: f, | ||
next: g, | ||
const E = ae(y), p = Ke(E), m = { | ||
forEach: E, | ||
toArray: p, | ||
next: y, | ||
return: () => ({}), | ||
[ie]: () => h | ||
[oe]: () => m | ||
}; | ||
return Object.assign(o, h); | ||
return Object.assign(c, m); | ||
} | ||
function De(e, r) { | ||
function Fe(e, r) { | ||
return e.currentPromise || (e.currentPromise = new Promise(r).then((t) => (e.currentPromise = void 0, t))), e.currentPromise; | ||
@@ -265,19 +265,19 @@ } | ||
return function(s) { | ||
return new Promise((a, u) => { | ||
let o = 0; | ||
function l(p) { | ||
if (p.done) { | ||
a(); | ||
return new Promise((i, a) => { | ||
let c = 0; | ||
function h(g) { | ||
if (g.done) { | ||
i(); | ||
return; | ||
} | ||
const g = p.value; | ||
return new Promise((y) => { | ||
y(s(g, o)); | ||
}).then((y) => y === !1 ? (r == null || r(), l({ done: !0 })) : (o++, e().then(l))); | ||
const y = g.value; | ||
return new Promise((E) => { | ||
E(s(y, c)); | ||
}).then((E) => E === !1 ? (r == null || r(), h({ done: !0 })) : (c++, e().then(h))); | ||
} | ||
e().then(l).catch(u); | ||
e().then(h).catch(a); | ||
}); | ||
}; | ||
} | ||
function Xe(e) { | ||
function Ke(e) { | ||
return function(t) { | ||
@@ -291,74 +291,74 @@ const s = t == null ? void 0 : t.limit; | ||
); | ||
return new Promise((a, u) => { | ||
const o = []; | ||
e((l) => { | ||
if (o.push(l), o.length >= s) | ||
return new Promise((i, a) => { | ||
const c = []; | ||
e((h) => { | ||
if (c.push(h), c.length >= s) | ||
return !1; | ||
}).then(() => { | ||
a(o); | ||
}).catch(u); | ||
i(c); | ||
}).catch(a); | ||
}); | ||
}; | ||
} | ||
function Ke(e, r = {}) { | ||
let t, s, a, u; | ||
const o = []; | ||
let l; | ||
const p = (f) => { | ||
o.push(f), l && (l(), l = null); | ||
function Je(e, r = {}) { | ||
let t, s, i, a; | ||
const c = []; | ||
let h; | ||
const g = (p) => { | ||
c.push(p), h && (h(), h = null); | ||
}; | ||
async function g(f) { | ||
!s && !u && (u = e.request({ method: "GET", path: "/config" }, f).then((c) => s = c.ws.channel)); | ||
const h = await e.request({ method: "POST", path: "/ws/auth" }, f), { token: i } = await W.post(`https://rest.ably.io/keys/${h.keyName}/requestToken`, h).then((c) => c.data); | ||
await u; | ||
const d = r.sseHost || "https://realtime.ably.io", m = new URL("sse", d); | ||
m.searchParams.append("v", "1.1"), m.searchParams.append("accessToken", i), m.searchParams.append("channels", s), m.searchParams.append("heartbeats", "true"), a && m.searchParams.append("lastEvent", a), t && t.close(), t = new Ee(m.toString()), t.onmessage = (c) => { | ||
if (c.origin !== d || (a = c.lastEventId, !("data" in c))) | ||
async function y(p) { | ||
!s && !a && (a = e.request({ method: "GET", path: "/config" }, p).then((f) => s = f.ws.channel)); | ||
const m = await e.request({ method: "POST", path: "/ws/auth" }, p), { token: u } = await W.post(`https://rest.ably.io/keys/${m.keyName}/requestToken`, m).then((f) => f.data); | ||
await a; | ||
const o = r.sseHost || "https://realtime.ably.io", l = new URL("sse", o); | ||
l.searchParams.append("v", "1.1"), l.searchParams.append("accessToken", u), l.searchParams.append("channels", s), l.searchParams.append("heartbeats", "true"), i && l.searchParams.append("lastEvent", i), t && t.close(), t = new xe(l.toString()), t.onmessage = (f) => { | ||
if (f.origin !== o || (i = f.lastEventId, !("data" in f))) | ||
return; | ||
const E = JSON.parse(c.data); | ||
if (E.type === "close") | ||
return p({ value: null, done: !0 }); | ||
E.data = E.encoding === "json" ? JSON.parse(E.data) : E.data, p({ value: E, done: !1 }); | ||
}, t.onerror = (c) => { | ||
const E = "data" in c ? JSON.parse(c.data) : {}; | ||
E.code >= 40140 && E.code < 40150 ? (t.close(), g(f)) : /invalid channel id/i.test(E.message) ? (t.close(), p({ value: null, done: !0 })) : console.log("err", c); | ||
const d = JSON.parse(f.data); | ||
if (d.type === "close") | ||
return g({ value: null, done: !0 }); | ||
d.data = d.encoding === "json" ? JSON.parse(d.data) : d.data, g({ value: d, done: !1 }); | ||
}, t.onerror = (f) => { | ||
const d = "data" in f ? JSON.parse(f.data) : {}; | ||
d.code >= 40140 && d.code < 40150 ? (t.close(), y(p)) : /invalid channel id/i.test(d.message) ? (t.close(), g({ value: null, done: !0 })) : console.log("err", f); | ||
}; | ||
} | ||
function y(f) { | ||
g(f); | ||
const h = async () => { | ||
o.length || await new Promise((E) => l = E); | ||
const c = o.pop(); | ||
return c.done && t && t.close(), c; | ||
}, i = () => (t.close(), p({ done: !0, value: void 0 }), { done: !0, value: void 0 }), m = { | ||
forEach: ae(h, i), | ||
close: () => void i(), | ||
next: h, | ||
return: i, | ||
[ie]: () => m | ||
function E(p) { | ||
y(p); | ||
const m = async () => { | ||
c.length || await new Promise((d) => h = d); | ||
const f = c.pop(); | ||
return f.done && t && t.close(), f; | ||
}, u = () => (t.close(), g({ done: !0, value: void 0 }), { done: !0, value: void 0 }), l = { | ||
forEach: ae(m, u), | ||
close: () => void u(), | ||
next: m, | ||
return: u, | ||
[oe]: () => l | ||
}; | ||
return m; | ||
return l; | ||
} | ||
return y; | ||
return E; | ||
} | ||
const z = { | ||
host: P, | ||
host: S, | ||
maxRetryDelay: Y, | ||
timeout: Y, | ||
apiKey: P, | ||
apiKey: S, | ||
maxRetries: Y, | ||
userEmail: P, | ||
userExternalId: P, | ||
userHmac: P, | ||
idempotencyKey: P, | ||
userEmail: S, | ||
userExternalId: S, | ||
userHmac: S, | ||
idempotencyKey: S, | ||
telemetry: I, | ||
apiSecret: P, | ||
appInfo: w, | ||
apiSecret: S, | ||
appInfo: O, | ||
debug: I, | ||
features: w, | ||
headers: w | ||
features: O, | ||
headers: O | ||
}; | ||
function Z(e) { | ||
var r; | ||
if (!w(e)) | ||
if (!O(e)) | ||
return !1; | ||
@@ -374,8 +374,8 @@ for (const t of Object.keys(e)) | ||
seen: I, | ||
categories: (e) => P(e) || te(e), | ||
topics: (e) => P(e) || te(e) | ||
categories: (e) => S(e) || re(e), | ||
topics: (e) => S(e) || re(e) | ||
}; | ||
function Je(e) { | ||
function Ye(e) { | ||
var r; | ||
if (!w(e)) | ||
if (!O(e)) | ||
return !1; | ||
@@ -387,21 +387,21 @@ for (const t of Object.keys(e)) | ||
} | ||
function Ye(e, r, t = { encode: !0 }) { | ||
function ze(e, r, t = { encode: !0 }) { | ||
return e.replace( | ||
/{([\s\S]+?)}/g, | ||
(s, a) => t.encode ? encodeURIComponent(r[a] || "") : r[a] || "" | ||
(s, i) => t.encode ? encodeURIComponent(r[i] || "") : r[i] || "" | ||
); | ||
} | ||
function ze(e) { | ||
function Qe(e) { | ||
return (e.match(/{\w+}/g) || [] || []).map((t) => t.replace(/[{}]/g, "")); | ||
} | ||
function Qe(e) { | ||
return !ne(e) || !w(e[0]) ? {} : Z(e[0]) ? {} : e.shift(); | ||
function We(e) { | ||
return !ie(e) || !O(e[0]) ? {} : Z(e[0]) ? {} : e.shift(); | ||
} | ||
function We(e) { | ||
if (!ne(e) || e.length === 0) | ||
function Ze(e) { | ||
if (!ie(e) || e.length === 0) | ||
return {}; | ||
const r = e[e.length - 1]; | ||
return Z(r) ? T({}, e.pop()) : {}; | ||
return Z(r) ? x({}, e.pop()) : {}; | ||
} | ||
function Ze({ | ||
function Ve({ | ||
path: e, | ||
@@ -411,23 +411,23 @@ method: r, | ||
}) { | ||
const s = [...t].filter((h) => h !== void 0), u = ze(e).reduce((h, i) => { | ||
const d = s.shift(); | ||
if (typeof d != "string") | ||
const s = [...t].filter((m) => m !== void 0), a = Qe(e).reduce((m, u) => { | ||
const o = s.shift(); | ||
if (typeof o != "string") | ||
throw new Error( | ||
`MagicBell: Argument "${i}" must be a string, but got ${typeof d}: ${JSON.stringify( | ||
d | ||
`MagicBell: Argument "${u}" must be a string, but got ${typeof o}: ${JSON.stringify( | ||
o | ||
)} (on API request to \`${r} ${e}\`)` | ||
); | ||
return h[i] = d, h; | ||
}, {}), o = Ye(e, u, { encode: !1 }), l = Qe(s), p = We(s); | ||
if (s.filter((h) => h != null).length) | ||
return m[u] = o, m; | ||
}, {}), c = ze(e, a, { encode: !1 }), h = We(s), g = Ze(s); | ||
if (s.filter((m) => m != null).length) | ||
throw new Error( | ||
`MagicBell: Unknown arguments (${JSON.stringify(s)}). (on API request to \`${r} ${o}\`)` | ||
`MagicBell: Unknown arguments (${JSON.stringify(s)}). (on API request to \`${r} ${c}\`)` | ||
); | ||
let g = r === "GET"; | ||
return r === "POST" && Je(l) && (g = !0), { path: o, data: g ? {} : l, params: g ? l : {}, options: p }; | ||
let y = r === "GET"; | ||
return r === "POST" && Ye(h) && (y = !0), { path: c, data: y ? {} : h, params: y ? h : {}, options: g }; | ||
} | ||
function re(e) { | ||
function se(e) { | ||
return e ? Array.isArray(e) ? e.length === 0 : typeof e == "object" ? Object.keys(e).length === 0 : !1 : !0; | ||
} | ||
class S { | ||
class P { | ||
constructor(r) { | ||
@@ -439,15 +439,15 @@ n(this, "path"); | ||
} | ||
request({ method: r, paged: t, path: s }, ...a) { | ||
const { path: u, data: o, params: l, options: p } = Ze({ | ||
path: je(this.path, s), | ||
request({ method: r, paged: t, path: s }, ...i) { | ||
const { path: a, data: c, params: h, options: g } = Ve({ | ||
path: Ce(this.path, s), | ||
method: r, | ||
args: a | ||
}), g = ({ data: y, params: f }) => { | ||
const h = this.entity || this.path; | ||
return y = re(y) ? void 0 : { [h]: y }, f = re(f) ? void 0 : f, this.client.request({ method: r, path: u, data: y, params: f }, p).then((i) => i[h] || i); | ||
args: i | ||
}), y = ({ data: E, params: p }) => { | ||
const m = this.entity || this.path; | ||
return E = se(E) ? void 0 : { [m]: E }, p = se(p) ? void 0 : p, this.client.request({ method: r, path: a, data: E, params: p }, g).then((u) => u[m] || u); | ||
}; | ||
return t ? Ce(g, { | ||
data: o, | ||
params: l | ||
}) : g({ data: o, params: l }); | ||
return t ? Xe(y, { | ||
data: c, | ||
params: h | ||
}) : y({ data: c, params: h }); | ||
} | ||
@@ -459,3 +459,3 @@ assertFeatureFlag(r) { | ||
} | ||
class Ve extends S { | ||
class et extends P { | ||
constructor() { | ||
@@ -466,4 +466,4 @@ super(...arguments); | ||
} | ||
list(t, s, a) { | ||
return this.assertFeatureFlag("broadcasts-notifications-list"), this.request( | ||
list(t, s, i) { | ||
return this.request( | ||
{ | ||
@@ -476,7 +476,7 @@ method: "GET", | ||
s, | ||
a | ||
i | ||
); | ||
} | ||
} | ||
class et extends S { | ||
class tt extends P { | ||
constructor() { | ||
@@ -486,6 +486,6 @@ super(...arguments); | ||
n(this, "entity", "broadcast"); | ||
n(this, "notifications", new Ve(this.client)); | ||
n(this, "notifications", new et(this.client)); | ||
} | ||
list(t, s) { | ||
return this.assertFeatureFlag("broadcasts-list"), this.request( | ||
return this.request( | ||
{ | ||
@@ -500,3 +500,3 @@ method: "GET", | ||
get(t, s) { | ||
return this.assertFeatureFlag("broadcasts-get"), this.request( | ||
return this.request( | ||
{ | ||
@@ -511,3 +511,3 @@ method: "GET", | ||
} | ||
class tt extends S { | ||
class rt extends P { | ||
constructor() { | ||
@@ -519,3 +519,3 @@ super(...arguments); | ||
create(t, s) { | ||
return this.assertFeatureFlag("imports-create"), this.request( | ||
return this.request( | ||
{ | ||
@@ -529,3 +529,3 @@ method: "POST" | ||
get(t, s) { | ||
return this.assertFeatureFlag("imports-get"), this.request( | ||
return this.request( | ||
{ | ||
@@ -540,5 +540,54 @@ method: "GET", | ||
} | ||
class rt extends S { | ||
class st extends P { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "metrics"); | ||
n(this, "entity", "categorie"); | ||
} | ||
get(t) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "categories" | ||
}, | ||
t | ||
); | ||
} | ||
} | ||
class nt extends P { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "metrics"); | ||
n(this, "entity", "topic"); | ||
} | ||
get(t) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "topics" | ||
}, | ||
t | ||
); | ||
} | ||
} | ||
class it extends P { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "metrics"); | ||
n(this, "entity", "metric"); | ||
n(this, "categories", new st(this.client)); | ||
n(this, "topics", new nt(this.client)); | ||
} | ||
get(t) { | ||
return this.request( | ||
{ | ||
method: "GET" | ||
}, | ||
t | ||
); | ||
} | ||
} | ||
class ot extends P { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "notification_preferences"); | ||
@@ -565,3 +614,3 @@ n(this, "entity", "notification_preferences"); | ||
} | ||
class st extends S { | ||
class at extends P { | ||
constructor() { | ||
@@ -672,3 +721,3 @@ super(...arguments); | ||
} | ||
class nt extends S { | ||
class ut extends P { | ||
constructor() { | ||
@@ -699,3 +748,3 @@ super(...arguments); | ||
} | ||
class it extends S { | ||
class ct extends P { | ||
constructor() { | ||
@@ -724,3 +773,3 @@ super(...arguments); | ||
} | ||
unsubscribe(t, s, a) { | ||
unsubscribe(t, s, i) { | ||
return this.request( | ||
@@ -733,3 +782,3 @@ { | ||
s, | ||
a | ||
i | ||
); | ||
@@ -747,3 +796,3 @@ } | ||
} | ||
delete(t, s, a) { | ||
delete(t, s, i) { | ||
return this.request( | ||
@@ -756,14 +805,33 @@ { | ||
s, | ||
a | ||
i | ||
); | ||
} | ||
} | ||
class at extends S { | ||
class ht extends P { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "users"); | ||
n(this, "entity", "notification"); | ||
} | ||
list(t, s, i) { | ||
return this.request( | ||
{ | ||
method: "GET", | ||
path: "{user_id}/notifications", | ||
paged: !0 | ||
}, | ||
t, | ||
s, | ||
i | ||
); | ||
} | ||
} | ||
class lt extends P { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "users"); | ||
n(this, "entity", "push_subscription"); | ||
} | ||
list(t, s, a) { | ||
return this.assertFeatureFlag("users-push-subscriptions-list"), this.request( | ||
list(t, s, i) { | ||
return this.request( | ||
{ | ||
@@ -776,7 +844,7 @@ method: "GET", | ||
s, | ||
a | ||
i | ||
); | ||
} | ||
delete(t, s, a) { | ||
return this.assertFeatureFlag("users-push-subscriptions-delete"), this.request( | ||
delete(t, s, i) { | ||
return this.request( | ||
{ | ||
@@ -788,7 +856,7 @@ method: "DELETE", | ||
s, | ||
a | ||
i | ||
); | ||
} | ||
} | ||
class ot extends S { | ||
class dt extends P { | ||
constructor() { | ||
@@ -798,3 +866,4 @@ super(...arguments); | ||
n(this, "entity", "user"); | ||
n(this, "pushSubscriptions", new at(this.client)); | ||
n(this, "notifications", new ht(this.client)); | ||
n(this, "pushSubscriptions", new lt(this.client)); | ||
} | ||
@@ -830,3 +899,3 @@ create(t, s) { | ||
} | ||
update(t, s, a) { | ||
update(t, s, i) { | ||
return this.request( | ||
@@ -839,3 +908,3 @@ { | ||
s, | ||
a | ||
i | ||
); | ||
@@ -853,3 +922,3 @@ } | ||
} | ||
updateByEmail(t, s, a) { | ||
updateByEmail(t, s, i) { | ||
return this.request( | ||
@@ -862,3 +931,3 @@ { | ||
s, | ||
a | ||
i | ||
); | ||
@@ -876,3 +945,3 @@ } | ||
} | ||
updateByExternalId(t, s, a) { | ||
updateByExternalId(t, s, i) { | ||
return this.request( | ||
@@ -885,3 +954,3 @@ { | ||
s, | ||
a | ||
i | ||
); | ||
@@ -901,3 +970,3 @@ } | ||
typeof XMLHttpRequest != "function" && (W.defaults.adapter = require("axios/lib/adapters/http")); | ||
const ut = { | ||
const mt = { | ||
host: "https://api.magicbell.com", | ||
@@ -909,7 +978,6 @@ timeout: 3e4, | ||
}; | ||
var M, U, _, O, B, k, N, oe, G, ue, R, ce, j, he, H, le, C, de; | ||
class mt { | ||
var M, U, _, L, B, G, k, ue, R, ce, j, he, H, le, C, de, D, me; | ||
class Et { | ||
constructor(r) { | ||
b(this, N); | ||
b(this, G); | ||
b(this, k); | ||
b(this, R); | ||
@@ -919,80 +987,82 @@ b(this, j); | ||
b(this, C); | ||
b(this, D); | ||
b(this, M, void 0); | ||
b(this, U, void 0); | ||
b(this, _, void 0); | ||
b(this, O, new Ie()); | ||
b(this, L, new Me()); | ||
b(this, B, {}); | ||
b(this, k, []); | ||
n(this, "listen", Ke(this)); | ||
n(this, "broadcasts", new et(this)); | ||
n(this, "imports", new tt(this)); | ||
n(this, "notificationPreferences", new rt(this)); | ||
n(this, "notifications", new st(this)); | ||
n(this, "pushSubscriptions", new nt(this)); | ||
n(this, "subscriptions", new it(this)); | ||
n(this, "users", new ot(this)); | ||
const t = ["apiKey"].filter((s) => !F(r, s)); | ||
b(this, G, []); | ||
n(this, "listen", Je(this)); | ||
n(this, "broadcasts", new tt(this)); | ||
n(this, "imports", new rt(this)); | ||
n(this, "metrics", new it(this)); | ||
n(this, "notificationPreferences", new ot(this)); | ||
n(this, "notifications", new at(this)); | ||
n(this, "pushSubscriptions", new ut(this)); | ||
n(this, "subscriptions", new ct(this)); | ||
n(this, "users", new dt(this)); | ||
const t = ["apiKey"].filter((s) => !N(r, s)); | ||
if (t.length) | ||
throw new Error( | ||
`You haven't provided all required options, please provide ${Re(...t)} to Client(options)` | ||
`You haven't provided all required options, please provide ${He(...t)} to Client(options)` | ||
); | ||
if (!Z(r)) | ||
throw new Error("You have provided invalid options. Please check your client options."); | ||
$(this, _, Object.assign({}, ut, r)), x(this, O).active = Boolean(x(this, _).debug), $(this, U, Pe(r.appInfo)), $(this, M, Te(r.appInfo)), $(this, B, r.features || {}); | ||
$(this, _, Object.assign({}, mt, r)), T(this, L).active = Boolean(T(this, _).debug), $(this, U, Se(r.appInfo)), $(this, M, Pe(r.appInfo)), $(this, B, r.features || {}); | ||
} | ||
hasFlag(r) { | ||
return x(this, B)[r] || !1; | ||
return T(this, B)[r] || !1; | ||
} | ||
async request({ method: r, path: t, data: s, params: a }, u) { | ||
var g, y, f; | ||
const o = T(T({}, x(this, _)), u), l = v(this, N, oe).call(this, o, r), p = Math.max(0, o.maxRetries); | ||
for (let h = 1; h <= p; h++) { | ||
let i, d; | ||
const m = Date.now(); | ||
if (x(this, O).debug(`${r} ${t}`), await W({ | ||
async request({ method: r, path: t, data: s, params: i, headers: a }, c) { | ||
var E, p, m; | ||
const h = A(x(x({}, T(this, _)), c), { headers: x(x({}, T(this, _).headers), a) }), g = w(this, k, ue).call(this, h, r), y = Math.max(0, h.maxRetries); | ||
for (let u = 1; u <= y; u++) { | ||
let o, l; | ||
const f = Date.now(); | ||
if (T(this, L).debug(`${r} ${t}`), await W({ | ||
method: r, | ||
url: t, | ||
baseURL: o.host, | ||
headers: T(T({}, l), J({ | ||
"X-MAGICBELL-CLIENT-TELEMETRY": v(this, R, ce).call(this) | ||
baseURL: h.host, | ||
headers: x(x({}, g), J({ | ||
"X-MAGICBELL-CLIENT-TELEMETRY": w(this, j, he).call(this) | ||
})), | ||
data: s, | ||
params: a, | ||
timeout: o.timeout | ||
}).then((c) => { | ||
i = c; | ||
}).catch((c) => { | ||
const E = ke({ method: r, baseURL: o.host, url: t, data: s, params: a, headers: l }); | ||
x(this, O).error(`${c.message}: ${E}`), d = c, i = c.response; | ||
}), v(this, G, ue).call(this, i, { startTime: m }), v(this, j, he).call(this, i, h, p)) { | ||
const c = Number((g = i == null ? void 0 : i.headers) == null ? void 0 : g["retry-after"]); | ||
await Ge(v(this, H, le).call(this, h, c, o.maxRetryDelay)); | ||
params: i, | ||
timeout: h.timeout | ||
}).then((d) => { | ||
o = d; | ||
}).catch((d) => { | ||
const V = Ne({ method: r, baseURL: h.host, url: t, data: s, params: i, headers: g }); | ||
T(this, L).error(`${d.message}: ${V}`), l = d, o = d.response; | ||
}), w(this, R, ce).call(this, o, { startTime: f }), w(this, H, le).call(this, o, u, y)) { | ||
const d = Number((E = o == null ? void 0 : o.headers) == null ? void 0 : E["retry-after"]); | ||
await je(w(this, C, de).call(this, u, d, h.maxRetryDelay)); | ||
continue; | ||
} | ||
if (d) | ||
throw Se(T({ | ||
code: d.code, | ||
name: d.name, | ||
message: d.message, | ||
type: d.type, | ||
status: i == null ? void 0 : i.status, | ||
statusText: i == null ? void 0 : i.statusText | ||
}, (f = (y = i == null ? void 0 : i.data) == null ? void 0 : y.errors) == null ? void 0 : f[0])); | ||
return i.data; | ||
if (l) | ||
throw _e(x({ | ||
code: l.code, | ||
name: l.name, | ||
message: l.message, | ||
type: l.type, | ||
status: o == null ? void 0 : o.status, | ||
statusText: o == null ? void 0 : o.statusText | ||
}, (m = (p = o == null ? void 0 : o.data) == null ? void 0 : p.errors) == null ? void 0 : m[0])); | ||
return o.data; | ||
} | ||
} | ||
} | ||
M = new WeakMap(), U = new WeakMap(), _ = new WeakMap(), O = new WeakMap(), B = new WeakMap(), k = new WeakMap(), N = new WeakSet(), oe = function(r, t) { | ||
M = new WeakMap(), U = new WeakMap(), _ = new WeakMap(), L = new WeakMap(), B = new WeakMap(), G = new WeakMap(), k = new WeakSet(), ue = function(r, t) { | ||
let s = r.userHmac; | ||
!s && r.apiSecret && (r.userExternalId || r.userEmail) && (s = xe(r.apiSecret, r.userExternalId || r.userEmail)); | ||
const a = typeof document < "u"; | ||
return Fe( | ||
J(L(T({ | ||
!s && r.apiSecret && (r.userExternalId || r.userEmail) && (s = Te(r.apiSecret, r.userExternalId || r.userEmail)); | ||
const i = typeof document < "u"; | ||
return ke( | ||
J(A(x({ | ||
"Accept-Version": "v2", | ||
"Idempotency-Key": r.idempotencyKey || v(this, C, de).call(this, t, r.maxRetries) | ||
}, x(this, _).headers), { | ||
"User-Agent": a ? null : x(this, M), | ||
"Idempotency-Key": r.idempotencyKey || w(this, D, me).call(this, t, r.maxRetries) | ||
}, r.headers), { | ||
"User-Agent": i ? null : T(this, M), | ||
"X-MAGICBELL-API-KEY": r.apiKey, | ||
"X-MAGICBELL-API-SECRET": r.apiSecret, | ||
"X-MAGICBELL-CLIENT-USER-AGENT": x(this, U), | ||
"X-MAGICBELL-CLIENT-USER-AGENT": T(this, U), | ||
"X-MAGICBELL-USER-EMAIL": r.userEmail, | ||
@@ -1004,7 +1074,7 @@ "X-MAGICBELL-USER-EXTERNAL-ID": r.userExternalId, | ||
); | ||
}, G = new WeakSet(), ue = function(r, { startTime: t }) { | ||
if (!x(this, _).telemetry || !(r != null && r.status)) | ||
}, R = new WeakSet(), ce = function(r, { startTime: t }) { | ||
if (!T(this, _).telemetry || !(r != null && r.status)) | ||
return; | ||
const s = J(r.headers); | ||
x(this, k).push({ | ||
T(this, G).push({ | ||
id: s["X-Request-Id"], | ||
@@ -1015,19 +1085,19 @@ runtime: Number(s["X-Runtime"]), | ||
}); | ||
}, R = new WeakSet(), ce = function() { | ||
const r = x(this, k).pop(); | ||
}, j = new WeakSet(), he = function() { | ||
const r = T(this, G).pop(); | ||
return r ? JSON.stringify(r) : null; | ||
}, j = new WeakSet(), he = function(r, t, s) { | ||
}, H = new WeakSet(), le = function(r, t, s) { | ||
return t >= s ? !1 : r ? r.headers["should-retry"] ? r.headers["should-retry"] === "true" : r.status === 409 || r.status === 503 || r.status >= 500 && r.request.method !== "POST" : !0; | ||
}, H = new WeakSet(), le = function(r, t = null, s) { | ||
let u = Math.min(0.5 * Math.pow(r, 2), s); | ||
return u *= 0.75 * (1 + Math.random()), u = Math.min(Math.max(0.5, u), s), Number.isInteger(t) && t <= 60 && (u = Math.max(u, t)), u * 1e3; | ||
}, C = new WeakSet(), de = function(r, t) { | ||
}, C = new WeakSet(), de = function(r, t = null, s) { | ||
let a = Math.min(0.5 * Math.pow(r, 2), s); | ||
return a *= 0.75 * (1 + Math.random()), a = Math.min(Math.max(0.5, a), s), Number.isInteger(t) && t <= 60 && (a = Math.max(a, t)), a * 1e3; | ||
}, D = new WeakSet(), me = function(r, t) { | ||
if (!(r !== "POST" || t === 0)) | ||
return `magicbell-retry-${Ne()}`; | ||
return `magicbell-retry-${Re()}`; | ||
}; | ||
export { | ||
mt as Client, | ||
xe as createHmac, | ||
mt as default | ||
Et as Client, | ||
Te as createHmac, | ||
Et as default | ||
}; | ||
//# sourceMappingURL=magicbell.esm.min.js.map |
@@ -20,4 +20,2 @@ import { type FromSchema } from 'json-schema-to-ts'; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -32,4 +30,2 @@ list(options?: RequestOptions): IterablePromise<ListBroadcastsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -43,4 +39,2 @@ list(data: ListBroadcastsPayload, options?: RequestOptions): IterablePromise<ListBroadcastsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -47,0 +41,0 @@ get(broadcastId: string, options?: RequestOptions): Promise<GetBroadcastsResponse>; |
@@ -17,4 +17,2 @@ import { type FromSchema } from 'json-schema-to-ts'; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -29,4 +27,2 @@ list(broadcastId: string, options?: RequestOptions): IterablePromise<ListBroadcastsNotificationsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -33,0 +29,0 @@ list(broadcastId: string, data: ListBroadcastsNotificationsPayload, options?: RequestOptions): IterablePromise<ListBroadcastsNotificationsResponse>; |
@@ -18,4 +18,2 @@ import { type FromSchema } from 'json-schema-to-ts'; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -31,4 +29,2 @@ create(options?: RequestOptions): Promise<CreateImportsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -44,4 +40,2 @@ create(data: CreateImportsPayload, options?: RequestOptions): Promise<CreateImportsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -48,0 +42,0 @@ get(importId: string, options?: RequestOptions): Promise<GetImportsResponse>; |
@@ -6,2 +6,3 @@ import { type FromSchema } from 'json-schema-to-ts'; | ||
import { type RequestOptions } from '../types'; | ||
import { UsersNotifications } from './users/notifications'; | ||
import { UsersPushSubscriptions } from './users/push-subscriptions'; | ||
@@ -22,2 +23,3 @@ declare type CreateUsersResponse = FromSchema<typeof schemas.CreateUsersResponseSchema>; | ||
entity: string; | ||
notifications: UsersNotifications; | ||
pushSubscriptions: UsersPushSubscriptions; | ||
@@ -24,0 +26,0 @@ /** |
@@ -18,4 +18,2 @@ import { type FromSchema } from 'json-schema-to-ts'; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -31,4 +29,2 @@ list(userId: string, options?: RequestOptions): IterablePromise<ListUsersPushSubscriptionsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -46,4 +42,2 @@ list(userId: string, data: ListUsersPushSubscriptionsPayload, options?: RequestOptions): IterablePromise<ListUsersPushSubscriptionsResponse>; | ||
* @param options - override client request options. | ||
* | ||
* @beta | ||
**/ | ||
@@ -50,0 +44,0 @@ delete(userId: string, subscriptionId: string, options?: RequestOptions): Promise<void>; |
@@ -19,11 +19,3 @@ export declare type ClientOptions = { | ||
debug?: boolean; | ||
features?: { | ||
'broadcasts-get'?: true; | ||
'broadcasts-list'?: true; | ||
'broadcasts-notifications-list'?: true; | ||
'imports-create'?: true; | ||
'imports-get'?: true; | ||
'users-push-subscriptions-delete'?: true; | ||
'users-push-subscriptions-list'?: true; | ||
}; | ||
features?: Record<string, never>; | ||
headers?: Record<string, string>; | ||
@@ -47,2 +39,3 @@ }; | ||
params?: Record<string, string>; | ||
headers?: Record<string, string>; | ||
}; |
{ | ||
"name": "magicbell", | ||
"version": "1.7.2", | ||
"version": "1.8.0", | ||
"description": "MagicBell API wrapper", | ||
@@ -54,3 +54,3 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com)", | ||
"devDependencies": { | ||
"@magicbell/codegen": "^0.0.2", | ||
"@magicbell/codegen": "^0.1.0", | ||
"@size-limit/preset-small-lib": "^8.0.1", | ||
@@ -57,0 +57,0 @@ "ast-types": "^0.14.2", |
@@ -317,11 +317,3 @@ # MagicBell Node.js Library | ||
| Feature Flag | Description | | ||
| --------------------------------- | ----------------------------------------------------------------------------- | | ||
| `broadcasts-get` | Fetch a notification broadcast by its ID ([docs](#broadcasts-get)) | | ||
| `broadcasts-list` | List notification broadcasts ([docs](#broadcasts-list)) | | ||
| `broadcasts-notifications-list` | Fetch notifications by broadcast id. ([docs](#broadcasts-notifications-list)) | | ||
| `imports-create` | Create a import ([docs](#imports-create)) | | ||
| `imports-get` | Get the status of an import ([docs](#imports-get)) | | ||
| `users-push-subscriptions-delete` | Delete user's push subscription ([docs](#users-push-subscriptions-delete)) | | ||
| `users-push-subscriptions-list` | Fetch user's push subscriptions ([docs](#users-push-subscriptions-list)) | | ||
_There are no features in beta at this time._ | ||
@@ -342,6 +334,2 @@ <!-- AUTO-GENERATED-CONTENT:END (FEATURE_FLAGS) --> | ||
> **Warning** | ||
> | ||
> This method is in preview and is subject to change. It needs to be enabled via the `broadcasts-list` [feature flag](#feature-flags). | ||
List all notification broadcasts. Broadcasts are sorted in descending order by the sent_at timestamp. | ||
@@ -358,6 +346,2 @@ | ||
> **Warning** | ||
> | ||
> This method is in preview and is subject to change. It needs to be enabled via the `broadcasts-get` [feature flag](#feature-flags). | ||
Fetch a notification broadcast by its ID. | ||
@@ -373,6 +357,2 @@ | ||
> **Warning** | ||
> | ||
> This method is in preview and is subject to change. It needs to be enabled via the `broadcasts-notifications-list` [feature flag](#feature-flags). | ||
Fetch the notifications on a notification broadcast. | ||
@@ -674,2 +654,15 @@ | ||
### Users Notifications | ||
#### Fetch notifications by user id. | ||
Fetch the notifications and deliveries for a user. | ||
```js | ||
await magicbell.users.notifications.list('{user_id}', { | ||
page: 1, | ||
per_page: 1, | ||
}); | ||
``` | ||
### Users Push Subscriptions | ||
@@ -679,6 +672,2 @@ | ||
> **Warning** | ||
> | ||
> This method is in preview and is subject to change. It needs to be enabled via the `users-push-subscriptions-list` [feature flag](#feature-flags). | ||
Fetch a user's push subscriptions. Returns a paginated list of web and mobile push subscriptions for all platforms. | ||
@@ -695,6 +684,2 @@ | ||
> **Warning** | ||
> | ||
> This method is in preview and is subject to change. It needs to be enabled via the `users-push-subscriptions-delete` [feature flag](#feature-flags). | ||
Delete a user's push subscriptions. Identifies the user by the user's ID and the push subscription by the subscription's ID. | ||
@@ -862,6 +847,2 @@ | ||
> **Warning** | ||
> | ||
> This method is in preview and is subject to change. It needs to be enabled via the `imports-create` [feature flag](#feature-flags). | ||
Enqueues an import - currently only supported for users. Amongst other things, the users import allows associating slack channels (if you have already setup the oauth apps). | ||
@@ -903,6 +884,2 @@ | ||
> **Warning** | ||
> | ||
> This method is in preview and is subject to change. It needs to be enabled via the `imports-get` [feature flag](#feature-flags). | ||
Query the status of the import for a summary of imported records and failures for each record that could not be imported successfully. | ||
@@ -914,2 +891,32 @@ | ||
### Metrics | ||
#### Get notification metrics | ||
Query the metrics of notification broadcasts and their recipients. | ||
```js | ||
await magicbell.metrics.get(); | ||
``` | ||
### Metrics Categories | ||
#### Get notification metrics grouped by category | ||
Query the metrics of notification broadcasts and their recipients, grouped by category. | ||
```js | ||
await magicbell.metrics.categories.get(); | ||
``` | ||
### Metrics Topics | ||
#### Get notification metrics grouped by topic | ||
Query the metrics of notification broadcasts and their recipients, grouped by topic. | ||
```js | ||
await magicbell.metrics.topics.get(); | ||
``` | ||
<!-- AUTO-GENERATED-CONTENT:END (RESOURCE_METHODS) --> | ||
@@ -916,0 +923,0 @@ |
@@ -166,1 +166,24 @@ import { basename } from 'path'; | ||
}); | ||
test('custom headers can be provided per request basis', async () => { | ||
const status = server.intercept('all', () => ({ id: 1 })); | ||
const client = new Client({ | ||
apiKey: 'my-api-key', | ||
maxRetryDelay: 0, | ||
headers: { | ||
'x-custom-header-one': 'one', | ||
}, | ||
}); | ||
await client.request({ | ||
method: 'POST', | ||
path: '/me', | ||
headers: { | ||
'x-custom-header-two': 'two', | ||
}, | ||
}); | ||
expect(status.lastRequest.headers.get('x-custom-header-one')).toEqual('one'); | ||
expect(status.lastRequest.headers.get('x-custom-header-two')).toEqual('two'); | ||
}); |
@@ -13,2 +13,3 @@ import axios, { AxiosError, AxiosResponse } from 'axios'; | ||
import { Imports } from './resources/imports'; | ||
import { Metrics } from './resources/metrics'; | ||
import { NotificationPreferences } from './resources/notification-preferences'; | ||
@@ -47,2 +48,3 @@ import { Notifications } from './resources/notifications'; | ||
imports = new Imports(this); | ||
metrics = new Metrics(this); | ||
notificationPreferences = new NotificationPreferences(this); | ||
@@ -77,4 +79,7 @@ notifications = new Notifications(this); | ||
async request<TResponse = any>({ method, path, data, params }: RequestArgs, options?: RequestOptions) { | ||
const requestOptions = { ...this.#options, ...options }; | ||
async request<TResponse = any>( | ||
{ method, path: url, data, params, headers: reqHeaders }: RequestArgs, | ||
options?: RequestOptions, | ||
) { | ||
const requestOptions = { ...this.#options, ...options, headers: { ...this.#options.headers, ...reqHeaders } }; | ||
@@ -90,6 +95,6 @@ // compute headers out of the retry-loop, only append the telemetry later | ||
this.#logger.debug(`${method} ${path}`); | ||
this.#logger.debug(`${method} ${url}`); | ||
await axios({ | ||
method, | ||
url: path, | ||
url, | ||
baseURL: requestOptions.host, | ||
@@ -111,5 +116,4 @@ headers: { | ||
.catch((e) => { | ||
const curl = toCurl({ method, baseURL: requestOptions.host, url: path, data, params, headers }); | ||
const curl = toCurl({ method, baseURL: requestOptions.host, url, data, params, headers }); | ||
this.#logger.error(`${e.message}: ${curl}`); | ||
error = e; | ||
@@ -158,3 +162,3 @@ response = e.response; | ||
// user-provided headers | ||
...this.#options.headers, | ||
...options.headers, | ||
@@ -161,0 +165,0 @@ // can't set user-agent in the browser, see https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name |
@@ -26,4 +26,2 @@ // This file is generated. Do not update manually! | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -39,4 +37,2 @@ list(options?: RequestOptions): IterablePromise<ListBroadcastsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -49,4 +45,2 @@ list(data: ListBroadcastsPayload, options?: RequestOptions): IterablePromise<ListBroadcastsResponse>; | ||
): IterablePromise<ListBroadcastsResponse> { | ||
this.assertFeatureFlag('broadcasts-list'); | ||
return this.request( | ||
@@ -68,8 +62,4 @@ { | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
get(broadcastId: string, options?: RequestOptions): Promise<GetBroadcastsResponse> { | ||
this.assertFeatureFlag('broadcasts-get'); | ||
return this.request( | ||
@@ -76,0 +66,0 @@ { |
@@ -23,4 +23,2 @@ // This file is generated. Do not update manually! | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -36,4 +34,2 @@ list(broadcastId: string, options?: RequestOptions): IterablePromise<ListBroadcastsNotificationsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -51,4 +47,2 @@ list( | ||
): IterablePromise<ListBroadcastsNotificationsResponse> { | ||
this.assertFeatureFlag('broadcasts-notifications-list'); | ||
return this.request( | ||
@@ -55,0 +49,0 @@ { |
@@ -24,4 +24,2 @@ // This file is generated. Do not update manually! | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -38,4 +36,2 @@ create(options?: RequestOptions): Promise<CreateImportsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -48,4 +44,2 @@ create(data: CreateImportsPayload, options?: RequestOptions): Promise<CreateImportsResponse>; | ||
): Promise<CreateImportsResponse> { | ||
this.assertFeatureFlag('imports-create'); | ||
return this.request( | ||
@@ -68,8 +62,4 @@ { | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
get(importId: string, options?: RequestOptions): Promise<GetImportsResponse> { | ||
this.assertFeatureFlag('imports-get'); | ||
return this.request( | ||
@@ -76,0 +66,0 @@ { |
@@ -9,2 +9,3 @@ // This file is generated. Do not update manually! | ||
import { type RequestOptions } from '../types'; | ||
import { UsersNotifications } from './users/notifications'; | ||
import { UsersPushSubscriptions } from './users/push-subscriptions'; | ||
@@ -27,2 +28,3 @@ | ||
entity = 'user'; | ||
notifications = new UsersNotifications(this.client); | ||
pushSubscriptions = new UsersPushSubscriptions(this.client); | ||
@@ -29,0 +31,0 @@ |
@@ -24,4 +24,2 @@ // This file is generated. Do not update manually! | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -38,4 +36,2 @@ list(userId: string, options?: RequestOptions): IterablePromise<ListUsersPushSubscriptionsResponse>; | ||
* @returns | ||
* | ||
* @beta | ||
**/ | ||
@@ -53,4 +49,2 @@ list( | ||
): IterablePromise<ListUsersPushSubscriptionsResponse> { | ||
this.assertFeatureFlag('users-push-subscriptions-list'); | ||
return this.request( | ||
@@ -78,8 +72,4 @@ { | ||
* @param options - override client request options. | ||
* | ||
* @beta | ||
**/ | ||
delete(userId: string, subscriptionId: string, options?: RequestOptions): Promise<void> { | ||
this.assertFeatureFlag('users-push-subscriptions-delete'); | ||
return this.request( | ||
@@ -86,0 +76,0 @@ { |
@@ -19,11 +19,3 @@ export type ClientOptions = { | ||
debug?: boolean; | ||
features?: { | ||
'broadcasts-get'?: true; | ||
'broadcasts-list'?: true; | ||
'broadcasts-notifications-list'?: true; | ||
'imports-create'?: true; | ||
'imports-get'?: true; | ||
'users-push-subscriptions-delete'?: true; | ||
'users-push-subscriptions-list'?: true; | ||
}; | ||
features?: Record<string, never>; | ||
headers?: Record<string, string>; | ||
@@ -51,2 +43,3 @@ }; | ||
params?: Record<string, string>; | ||
headers?: Record<string, string>; | ||
}; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
877524
96
12753
1004