Comparing version 0.1.0 to 0.2.0
@@ -1,2 +0,1 @@ | ||
import { Devices } from './resources/devices'; | ||
import { NotificationPreferences } from './resources/notification-preferences'; | ||
@@ -6,7 +5,6 @@ import { Notifications } from './resources/notifications'; | ||
import { Users } from './resources/users'; | ||
import { ClientOptions, RequestClientOptions, RequestOptions } from './types'; | ||
import { ClientOptions, RequestArgs, RequestOptions } from './types'; | ||
export declare const DEFAULT_OPTIONS: Partial<ClientOptions>; | ||
export declare class Client { | ||
#private; | ||
devices: Devices; | ||
notificationPreferences: NotificationPreferences; | ||
@@ -17,3 +15,3 @@ notifications: Notifications; | ||
constructor(options: ClientOptions); | ||
request({ method, path, data, params }: RequestOptions, options?: RequestClientOptions): Promise<any>; | ||
request({ method, path, data, params }: RequestArgs, options?: RequestOptions): Promise<any>; | ||
} |
@@ -1,1 +0,2 @@ | ||
export { Client as default } from './client'; | ||
export { Client, Client as default } from './client'; | ||
export type { ClientOptions, RequestOptions } from './types'; |
/** | ||
* @license magicbell v0.1.0 | ||
* @license magicbell v0.2.0 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) MagicBell Inc. and its affiliates. |
/** | ||
* @license magicbell v0.1.0 | ||
* @license magicbell v0.2.0 | ||
* | ||
@@ -158,3 +158,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "0.1.0", | ||
binding_version: "0.2.0", | ||
publisher: "magicbell", | ||
@@ -508,16 +508,2 @@ runtime: ((_a = process.release) == null ? void 0 : _a.name) || "node", | ||
} | ||
class Devices extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "push_subscriptions"); | ||
__publicField(this, "entity", "push_subscription"); | ||
__publicField(this, "create", createMethod({ | ||
method: "POST" | ||
})); | ||
__publicField(this, "delete", createMethod({ | ||
method: "DELETE", | ||
path: "{device_token}" | ||
})); | ||
} | ||
} | ||
class NotificationPreferences extends Resource { | ||
@@ -528,3 +514,3 @@ constructor() { | ||
__publicField(this, "entity", "notification_preferences"); | ||
__publicField(this, "retrieve", createMethod({ | ||
__publicField(this, "get", createMethod({ | ||
method: "GET" | ||
@@ -549,3 +535,3 @@ })); | ||
})); | ||
__publicField(this, "retrieve", createMethod({ | ||
__publicField(this, "get", createMethod({ | ||
method: "GET", | ||
@@ -564,3 +550,3 @@ path: "{notification_id}" | ||
method: "POST", | ||
path: "{notification_id}/read" | ||
path: "{notification_id}/unread" | ||
})); | ||
@@ -590,5 +576,2 @@ __publicField(this, "archive", createMethod({ | ||
__publicField(this, "entity", "subscription"); | ||
__publicField(this, "create", createMethod({ | ||
method: "POST" | ||
})); | ||
__publicField(this, "list", createMethod({ | ||
@@ -598,3 +581,10 @@ method: "GET", | ||
})); | ||
__publicField(this, "retrieve", createMethod({ | ||
__publicField(this, "create", createMethod({ | ||
method: "POST" | ||
})); | ||
__publicField(this, "unsubscribe", createMethod({ | ||
method: "POST", | ||
path: "{topic}/unsubscribe" | ||
})); | ||
__publicField(this, "get", createMethod({ | ||
method: "GET", | ||
@@ -607,6 +597,2 @@ path: "{topic}" | ||
})); | ||
__publicField(this, "unsubscribe", createMethod({ | ||
method: "POST", | ||
path: "{topic}/unsubscribe" | ||
})); | ||
} | ||
@@ -626,10 +612,2 @@ } | ||
})); | ||
__publicField(this, "updateByEmail", createMethod({ | ||
method: "PUT", | ||
path: "email:{user_id}" | ||
})); | ||
__publicField(this, "updateByExternalId", createMethod({ | ||
method: "PUT", | ||
path: "external_id:{user_id}" | ||
})); | ||
__publicField(this, "delete", createMethod({ | ||
@@ -639,9 +617,17 @@ method: "DELETE", | ||
})); | ||
__publicField(this, "updateByEmail", createMethod({ | ||
method: "PUT", | ||
path: "email:{user_email}" | ||
})); | ||
__publicField(this, "deleteByEmail", createMethod({ | ||
method: "DELETE", | ||
path: "email:{user_id}" | ||
path: "email:{user_email}" | ||
})); | ||
__publicField(this, "updateByExternalId", createMethod({ | ||
method: "PUT", | ||
path: "external_id:{external_id}" | ||
})); | ||
__publicField(this, "deleteByExternalId", createMethod({ | ||
method: "DELETE", | ||
path: "external_id:{user_id}" | ||
path: "external_id:{external_id}" | ||
})); | ||
@@ -671,3 +657,2 @@ } | ||
__privateAdd(this, _lastRequest, []); | ||
__publicField(this, "devices", new Devices(this)); | ||
__publicField(this, "notificationPreferences", new NotificationPreferences(this)); | ||
@@ -813,3 +798,4 @@ __publicField(this, "notifications", new Notifications(this)); | ||
}; | ||
exports.Client = Client; | ||
exports.default = Client; | ||
//# sourceMappingURL=magicbell.cjs.js.map |
/** | ||
* @license magicbell v0.1.0 | ||
* @license magicbell v0.2.0 | ||
* | ||
@@ -10,3 +10,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
"use strict";var me=Object.defineProperty,ye=Object.defineProperties;var ge=Object.getOwnPropertyDescriptors;var ee=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var F=(e,t,r)=>t in e?me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,T=(e,t)=>{for(var r in t||(t={}))pe.call(t,r)&&F(e,r,t[r]);if(ee)for(var r of ee(t))Ee.call(t,r)&&F(e,r,t[r]);return e},X=(e,t)=>ye(e,ge(t));var n=(e,t,r)=>(F(e,typeof t!="symbol"?t+"":t,r),r),Y=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var E=(e,t,r)=>(Y(e,t,"read from private field"),r?r.call(e):t.get(e)),d=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},P=(e,t,r,i)=>(Y(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);var A=(e,t,r)=>(Y(e,t,"access private method"),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const xe=require("axios"),Te=require("crypto"),B=require("fs"),_e=require("os"),j=require("path"),ne=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Ae=ne(xe),be=ne(Te);function Se(e,t){return!e||!t?"":be.default.createHmac("sha256",e).update(t).digest("base64")}const v=new Map,Pe={configDir:j.join(_e.homedir(),".magicbell"),get(e,t=null){if(v.has(e))return v.get(e);let r=null;try{r=JSON.parse(B.readFileSync(j.join(this.configDir,e),"utf-8")||"null")}catch(i){}return r!=null?(v.set(e,r),r):t!=null?(this.set(e,t),t):null},set(e,t){v.set(e,t),B.mkdirSync(this.configDir,{recursive:!0}),B.writeFileSync(j.join(this.configDir,e),JSON.stringify(t,null,2),"utf-8")},delete(e){v.delete(e),B.unlinkSync(j.join(this.configDir,e))}},Z=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function b(e){return typeof e=="string"}function O(e){return typeof e=="boolean"}function ie(e){return Array.isArray(e)}function te(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function H(e){return typeof e=="number"}function G(e){return e&&typeof e=="object"}function ve(e){if(typeof e!="object")throw new Error("Argument must be an object");const t={};for(const r of Object.keys(e))e[r]!=null&&(t[r]=e[r]);return t}function se(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}async function Oe(e){return new Promise(t=>setTimeout(t,e))}function Le(...e){if(e.length<=2)return e.join(" and ");const t=e.slice(-1)[0];return[e.slice(0,-1).join(", "),t].join(", and ")}function we(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}function oe(){var e;return{binding:"magicbell",binding_version:"0.1.0",publisher:"magicbell",runtime:((e=process.release)==null?void 0:e.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch}}function Ie(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function Me(e){const t=oe();return[`${t.binding}/${t.binding_version}`,`${t.runtime}/${t.runtime_version}`,Ie(e)].filter(Boolean).join(" ")}function De(e){return JSON.stringify(X(T({},oe()),{application:e}))}function Ue(){return Pe.get("client-id",`client_${se()}`)}function Be(e){for(const t of["code","type","status"])switch(e[t]){case"user_identifier_not_provided":return new re(e);case"invalid_request_error":return new je(e);case"api_error":return new Ne(e);case"authentication_error":return new re(e);case"rate_limit_error":return new $e(e);case"idempotency_error":return new Ce(e);case 404:return new qe(e);case 422:return new ke(e)}return new Re(e)}class _ extends Error{constructor(r){super(r.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=r.code,this.status=r.status,this.statusText=r.statusText,this.message=r.message,this.suggestion=r.suggestion,this.docs_url=r.docs_url||r.help_link}}class je extends _{}class ke extends _{}class Ne extends _{}class re extends _{}class $e extends _{}class Ce extends _{}class Re extends _{}class qe extends _{}function J(e){if(!e||typeof e!="object")return e;const t={};for(const r of Object.keys(e))t[Ge(r)]=e[r];return t}function Ge(e){const t={etag:"ETag",magicbell:"MagicBell"};return e.split("-").map(r=>t[r.toLowerCase()]||r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("-")}const z={reset:"\x1B[0m",magenta:"\x1B[35m"};class Ke{constructor(){n(this,"active",!1)}debug(t){!this.active||console.log(`${z.reset}${z.magenta}magicbell:${z.reset} ${t}`)}}const Q={host:b,maxRetryDelay:H,timeout:H,apiKey:b,maxRetries:H,userEmail:b,idempotencyKey:b,telemetry:O,apiSecret:b,appInfo:G,debug:O};function V(e){var t;if(!G(e))return!1;for(const r of Object.keys(e))if(!((t=Q[r])!=null&&t.call(Q,e[r])))return!1;return!0}const Fe=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Xe(e){return Z(e,"current_page")&&Z(e,"total_pages")&&e.current_page<e.total_pages}function Ye(e,{data:t,params:r}){const i={currentPromise:null},g=typeof r.after<"u";let a=0,o=e({data:t,params:r});const h=u=>{const m=u.current_page+1;return e({data:t,params:X(T({},r),{page:m})})};function p(u){const m=Object.keys(u).find(K=>Array.isArray(u[K])),y=u[m]||u.data;if(!y||typeof y.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(a<y.length){const K=g?y.length-1-a:a,fe=y[K];return a+=1,{value:fe,done:!1}}return Xe(u)?(a=0,o=h(u),o.then(p)):{value:void 0,done:!0}}function l(){return He(i,(u,m)=>o.then(p).then(u).catch(m))}const f=Je(l),x=ze(f),c={forEach:f,toArray:x,next:l,return:()=>({}),[Fe]:()=>c};return Object.assign(o,c)}function He(e,t){return e.currentPromise||(e.currentPromise=new Promise(t).then(r=>(e.currentPromise=void 0,r))),e.currentPromise}function Je(e){return function(r){return new Promise((i,g)=>{let a=0;function o(h){if(h.done){i();return}const p=h.value;return new Promise(l=>{l(r(p,a))}).then(l=>l===!1?o({done:!0}):(a++,e().then(o)))}e().then(o).catch(g)})}}function ze(e){return function(r){const i=r==null?void 0:r.limit;if(!i)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(i>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((g,a)=>{const o=[];e(h=>{if(o.push(h),o.length>=i)return!1}).then(()=>{g(o)}).catch(a)})}}function s({method:e,path:t,type:r}){return function(...g){const{path:a,data:o,params:h,options:p}=tt({path:we(this.path,t),method:e,args:g}),l=({data:f,params:x})=>{const c=this.entity||this.path;return f=f&&{[c]:f},this.client.request({method:e,path:a,data:f,params:x},p).then(u=>u[c]||u)};return r==="list"?Ye(l,{data:o,params:h}):l({data:o,params:h})}}const W={archived:O,read:O,seen:O,categories:e=>b(e)||te(e),topics:e=>b(e)||te(e)};function Qe(e){var t;if(!G(e))return!1;for(const r of Object.keys(e))if(!((t=W[r])!=null&&t.call(W,e[r])))return!1;return!0}function We(e,t){return e.replace(/{([\s\S]+?)}/g,(r,i)=>encodeURIComponent(t[i]||""))}function Ze(e){return(e.match(/{\w+}/g)||[]||[]).map(r=>r.replace(/[{}]/g,""))}function Ve(e){return!ie(e)||!G(e[0])?{}:V(e[0])?{}:e.shift()}function et(e){if(!ie(e)||e.length===0)return{};const t=e[e.length-1];return V(t)?T({},e.pop()):{}}function tt({path:e,method:t,args:r}){const i=[...r],a=Ze(e).reduce((c,u)=>{const m=i.shift();if(typeof m!="string")throw new Error(`MagicBell: Argument "${u}" must be a string, but got ${typeof m}: ${JSON.stringify(m)} (on API request to \`${t} ${e}\`)`);return c[u]=m,c},{}),o=We(e,a),h=Ve(i),p=et(i);if(i.filter(c=>c!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(i)}). (on API request to \`${t} ${o}\`)`);let l=t==="GET"||t==="DELETE";return t==="POST"&&Qe(h)&&(l=!0),{path:o,data:l?{}:h,params:l?h:{},options:p}}class U{constructor(t){n(this,"path");n(this,"entity");n(this,"client");this.client=t}}class rt extends U{constructor(){super(...arguments);n(this,"path","push_subscriptions");n(this,"entity","push_subscription");n(this,"create",s({method:"POST"}));n(this,"delete",s({method:"DELETE",path:"{device_token}"}))}}class nt extends U{constructor(){super(...arguments);n(this,"path","notification_preferences");n(this,"entity","notification_preferences");n(this,"retrieve",s({method:"GET"}));n(this,"update",s({method:"PUT"}))}}class it extends U{constructor(){super(...arguments);n(this,"path","notifications");n(this,"entity","notification");n(this,"create",s({method:"POST"}));n(this,"list",s({method:"GET",type:"list"}));n(this,"retrieve",s({method:"GET",path:"{notification_id}"}));n(this,"delete",s({method:"DELETE",path:"{notification_id}"}));n(this,"markAsRead",s({method:"POST",path:"{notification_id}/read"}));n(this,"markAsUnread",s({method:"POST",path:"{notification_id}/read"}));n(this,"archive",s({method:"POST",path:"{notification_id}/archive"}));n(this,"unarchive",s({method:"DELETE",path:"{notification_id}/archive"}));n(this,"markAllRead",s({method:"POST",path:"read"}));n(this,"markAllSeen",s({method:"POST",path:"seen"}))}}class st extends U{constructor(){super(...arguments);n(this,"path","subscriptions");n(this,"entity","subscription");n(this,"create",s({method:"POST"}));n(this,"list",s({method:"GET",type:"list"}));n(this,"retrieve",s({method:"GET",path:"{topic}"}));n(this,"delete",s({method:"DELETE",path:"{topic}"}));n(this,"unsubscribe",s({method:"POST",path:"{topic}/unsubscribe"}))}}class ot extends U{constructor(){super(...arguments);n(this,"path","users");n(this,"entity","user");n(this,"create",s({method:"POST"}));n(this,"update",s({method:"PUT",path:"{user_id}"}));n(this,"updateByEmail",s({method:"PUT",path:"email:{user_id}"}));n(this,"updateByExternalId",s({method:"PUT",path:"external_id:{user_id}"}));n(this,"delete",s({method:"DELETE",path:"{user_id}"}));n(this,"deleteByEmail",s({method:"DELETE",path:"email:{user_id}"}));n(this,"deleteByExternalId",s({method:"DELETE",path:"external_id:{user_id}"}))}}const at={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var L,w,I,S,M,D,k,ae,N,ce,$,ue,C,le,R,he,q,de;class ct{constructor(t){d(this,k);d(this,N);d(this,$);d(this,C);d(this,R);d(this,q);d(this,L,void 0);d(this,w,void 0);d(this,I,void 0);d(this,S,void 0);d(this,M,new Ke);d(this,D,[]);n(this,"devices",new rt(this));n(this,"notificationPreferences",new nt(this));n(this,"notifications",new it(this));n(this,"subscriptions",new st(this));n(this,"users",new ot(this));const r=["apiKey"].filter(i=>!Z(t,i));if(r.length)throw new Error(`You haven't provided all required options, please provide ${Le(...r)} to Client(options)`);if(!V(t))throw new Error("You have provided invalid options. Please check your client options.");P(this,S,Object.assign({},at,t)),E(this,M).active=Boolean(E(this,S).debug),P(this,I,De(t.appInfo)),P(this,L,Me(t.appInfo)),P(this,w,Ue())}async request({method:t,path:r,data:i,params:g},a){var l,f;const o=T(T({},E(this,S)),a),h=A(this,k,ae).call(this,o,t),p=Math.max(0,o.maxRetries);for(let x=1;x<=p;x++){let c,u;const m=Date.now();if(E(this,M).debug(`${t} ${r}`),await Ae.default({method:t,url:r,baseURL:o.host,headers:T(T({},h),J({"X-MAGICBELL-CLIENT-TELEMETRY":A(this,$,ue).call(this)})),data:i,params:g,timeout:o.timeout}).then(y=>{c=y}).catch(y=>{u=y,c=y.response}),A(this,N,ce).call(this,c,{startTime:m}),A(this,C,le).call(this,c,x,p)){const y=Number(c.headers["retry-after"]);await Oe(A(this,R,he).call(this,x,y,o.maxRetryDelay));continue}if(u)throw Be(T({name:u.name,message:u.message,type:u.type,status:c.status,statusText:c.statusText},(f=(l=c==null?void 0:c.data)==null?void 0:l.errors)==null?void 0:f[0]));return c.data}}}L=new WeakMap,w=new WeakMap,I=new WeakMap,S=new WeakMap,M=new WeakMap,D=new WeakMap,k=new WeakSet,ae=function(t,r){return ve(J({"User-Agent":E(this,L),"Idempotency-Key":t.idempotencyKey||A(this,q,de).call(this,r,t.maxRetries),"X-MAGICBELL-API-KEY":t.apiKey,"X-MAGICBELL-API-SECRET":t.apiSecret,"X-MAGICBELL-CLIENT-ID":E(this,w),"X-MAGICBELL-CLIENT-USER-AGENT":E(this,I),"X-MAGICBELL-USER-EMAIL":t.userEmail,"X-MAGICBELL-USER-KEY":Se(t.apiSecret,t.userEmail)}))},N=new WeakSet,ce=function(t,{startTime:r}){if(!E(this,S).telemetry||!(t!=null&&t.status))return;const i=J(t.headers);E(this,D).push({id:i["X-Request-Id"],runtime:Number(i["X-Runtime"]),duration:Date.now()-r,status:t.status})},$=new WeakSet,ue=function(){const t=E(this,D).pop();return t?JSON.stringify(t):null},C=new WeakSet,le=function(t,r,i){return r>=i?!1:t?t.headers["should-retry"]?t.headers["should-retry"]==="true":t.status===409||t.status===503||t.status>=500&&t.request.method!=="POST":!0},R=new WeakSet,he=function(t,r=null,i){let a=Math.min(.5*Math.pow(t,2),i);return a*=.75*(1+Math.random()),a=Math.min(Math.max(.5,a),i),Number.isInteger(r)&&r<=60&&(a=Math.max(a,r)),a*1e3},q=new WeakSet,de=function(t,r){if(!(t!=="POST"||r===0))return`magicbell-retry-${se()}`};exports.default=ct; | ||
"use strict";var ge=Object.defineProperty,ye=Object.defineProperties;var pe=Object.getOwnPropertyDescriptors;var ee=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var F=(e,t,r)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,T=(e,t)=>{for(var r in t||(t={}))xe.call(t,r)&&F(e,r,t[r]);if(ee)for(var r of ee(t))Ee.call(t,r)&&F(e,r,t[r]);return e},X=(e,t)=>ye(e,pe(t));var n=(e,t,r)=>(F(e,typeof t!="symbol"?t+"":t,r),r),Y=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var x=(e,t,r)=>(Y(e,t,"read from private field"),r?r.call(e):t.get(e)),h=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},P=(e,t,r,i)=>(Y(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);var _=(e,t,r)=>(Y(e,t,"access private method"),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const Te=require("axios"),Ae=require("crypto"),B=require("fs"),_e=require("os"),D=require("path"),ne=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},be=ne(Te),Se=ne(Ae);function Pe(e,t){return!e||!t?"":Se.default.createHmac("sha256",e).update(t).digest("base64")}const O=new Map,Oe={configDir:D.join(_e.homedir(),".magicbell"),get(e,t=null){if(O.has(e))return O.get(e);let r=null;try{r=JSON.parse(B.readFileSync(D.join(this.configDir,e),"utf-8")||"null")}catch(i){}return r!=null?(O.set(e,r),r):t!=null?(this.set(e,t),t):null},set(e,t){O.set(e,t),B.mkdirSync(this.configDir,{recursive:!0}),B.writeFileSync(D.join(this.configDir,e),JSON.stringify(t,null,2),"utf-8")},delete(e){O.delete(e),B.unlinkSync(D.join(this.configDir,e))}},Z=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function b(e){return typeof e=="string"}function v(e){return typeof e=="boolean"}function ie(e){return Array.isArray(e)}function te(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function H(e){return typeof e=="number"}function q(e){return e&&typeof e=="object"}function ve(e){if(typeof e!="object")throw new Error("Argument must be an object");const t={};for(const r of Object.keys(e))e[r]!=null&&(t[r]=e[r]);return t}function se(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}async function Le(e){return new Promise(t=>setTimeout(t,e))}function we(...e){if(e.length<=2)return e.join(" and ");const t=e.slice(-1)[0];return[e.slice(0,-1).join(", "),t].join(", and ")}function Ie(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}function oe(){var e;return{binding:"magicbell",binding_version:"0.2.0",publisher:"magicbell",runtime:((e=process.release)==null?void 0:e.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch}}function Me(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function Ue(e){const t=oe();return[`${t.binding}/${t.binding_version}`,`${t.runtime}/${t.runtime_version}`,Me(e)].filter(Boolean).join(" ")}function Be(e){return JSON.stringify(X(T({},oe()),{application:e}))}function De(){return Oe.get("client-id",`client_${se()}`)}function je(e){for(const t of["code","type","status"])switch(e[t]){case"user_identifier_not_provided":return new re(e);case"invalid_request_error":return new ke(e);case"api_error":return new Ce(e);case"authentication_error":return new re(e);case"rate_limit_error":return new $e(e);case"idempotency_error":return new Re(e);case 404:return new Ge(e);case 422:return new Ne(e)}return new qe(e)}class A extends Error{constructor(r){super(r.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=r.code,this.status=r.status,this.statusText=r.statusText,this.message=r.message,this.suggestion=r.suggestion,this.docs_url=r.docs_url||r.help_link}}class ke extends A{}class Ne extends A{}class Ce extends A{}class re extends A{}class $e extends A{}class Re extends A{}class qe extends A{}class Ge extends A{}function J(e){if(!e||typeof e!="object")return e;const t={};for(const r of Object.keys(e))t[Ke(r)]=e[r];return t}function Ke(e){const t={etag:"ETag",magicbell:"MagicBell"};return e.split("-").map(r=>t[r.toLowerCase()]||r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("-")}const z={reset:"\x1B[0m",magenta:"\x1B[35m"};class Fe{constructor(){n(this,"active",!1)}debug(t){!this.active||console.log(`${z.reset}${z.magenta}magicbell:${z.reset} ${t}`)}}const Q={host:b,maxRetryDelay:H,timeout:H,apiKey:b,maxRetries:H,userEmail:b,idempotencyKey:b,telemetry:v,apiSecret:b,appInfo:q,debug:v};function V(e){var t;if(!q(e))return!1;for(const r of Object.keys(e))if(!((t=Q[r])!=null&&t.call(Q,e[r])))return!1;return!0}const Xe=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Ye(e){return Z(e,"current_page")&&Z(e,"total_pages")&&e.current_page<e.total_pages}function He(e,{data:t,params:r}){const i={currentPromise:null},y=typeof r.after<"u";let a=0,s=e({data:t,params:r});const f=u=>{const m=u.current_page+1;return e({data:t,params:X(T({},r),{page:m})})};function p(u){const m=Object.keys(u).find(K=>Array.isArray(u[K])),g=u[m]||u.data;if(!g||typeof g.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(a<g.length){const K=y?g.length-1-a:a,me=g[K];return a+=1,{value:me,done:!1}}return Ye(u)?(a=0,s=f(u),s.then(p)):{value:void 0,done:!0}}function l(){return Je(i,(u,m)=>s.then(p).then(u).catch(m))}const d=ze(l),E=Qe(d),c={forEach:d,toArray:E,next:l,return:()=>({}),[Xe]:()=>c};return Object.assign(s,c)}function Je(e,t){return e.currentPromise||(e.currentPromise=new Promise(t).then(r=>(e.currentPromise=void 0,r))),e.currentPromise}function ze(e){return function(r){return new Promise((i,y)=>{let a=0;function s(f){if(f.done){i();return}const p=f.value;return new Promise(l=>{l(r(p,a))}).then(l=>l===!1?s({done:!0}):(a++,e().then(s)))}e().then(s).catch(y)})}}function Qe(e){return function(r){const i=r==null?void 0:r.limit;if(!i)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(i>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((y,a)=>{const s=[];e(f=>{if(s.push(f),s.length>=i)return!1}).then(()=>{y(s)}).catch(a)})}}function o({method:e,path:t,type:r}){return function(...y){const{path:a,data:s,params:f,options:p}=rt({path:Ie(this.path,t),method:e,args:y}),l=({data:d,params:E})=>{const c=this.entity||this.path;return d=d&&{[c]:d},this.client.request({method:e,path:a,data:d,params:E},p).then(u=>u[c]||u)};return r==="list"?He(l,{data:s,params:f}):l({data:s,params:f})}}const W={archived:v,read:v,seen:v,categories:e=>b(e)||te(e),topics:e=>b(e)||te(e)};function We(e){var t;if(!q(e))return!1;for(const r of Object.keys(e))if(!((t=W[r])!=null&&t.call(W,e[r])))return!1;return!0}function Ze(e,t){return e.replace(/{([\s\S]+?)}/g,(r,i)=>encodeURIComponent(t[i]||""))}function Ve(e){return(e.match(/{\w+}/g)||[]||[]).map(r=>r.replace(/[{}]/g,""))}function et(e){return!ie(e)||!q(e[0])?{}:V(e[0])?{}:e.shift()}function tt(e){if(!ie(e)||e.length===0)return{};const t=e[e.length-1];return V(t)?T({},e.pop()):{}}function rt({path:e,method:t,args:r}){const i=[...r],a=Ve(e).reduce((c,u)=>{const m=i.shift();if(typeof m!="string")throw new Error(`MagicBell: Argument "${u}" must be a string, but got ${typeof m}: ${JSON.stringify(m)} (on API request to \`${t} ${e}\`)`);return c[u]=m,c},{}),s=Ze(e,a),f=et(i),p=tt(i);if(i.filter(c=>c!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(i)}). (on API request to \`${t} ${s}\`)`);let l=t==="GET"||t==="DELETE";return t==="POST"&&We(f)&&(l=!0),{path:s,data:l?{}:f,params:l?f:{},options:p}}class G{constructor(t){n(this,"path");n(this,"entity");n(this,"client");this.client=t}}class nt extends G{constructor(){super(...arguments);n(this,"path","notification_preferences");n(this,"entity","notification_preferences");n(this,"get",o({method:"GET"}));n(this,"update",o({method:"PUT"}))}}class it extends G{constructor(){super(...arguments);n(this,"path","notifications");n(this,"entity","notification");n(this,"create",o({method:"POST"}));n(this,"list",o({method:"GET",type:"list"}));n(this,"get",o({method:"GET",path:"{notification_id}"}));n(this,"delete",o({method:"DELETE",path:"{notification_id}"}));n(this,"markAsRead",o({method:"POST",path:"{notification_id}/read"}));n(this,"markAsUnread",o({method:"POST",path:"{notification_id}/unread"}));n(this,"archive",o({method:"POST",path:"{notification_id}/archive"}));n(this,"unarchive",o({method:"DELETE",path:"{notification_id}/archive"}));n(this,"markAllRead",o({method:"POST",path:"read"}));n(this,"markAllSeen",o({method:"POST",path:"seen"}))}}class st extends G{constructor(){super(...arguments);n(this,"path","subscriptions");n(this,"entity","subscription");n(this,"list",o({method:"GET",type:"list"}));n(this,"create",o({method:"POST"}));n(this,"unsubscribe",o({method:"POST",path:"{topic}/unsubscribe"}));n(this,"get",o({method:"GET",path:"{topic}"}));n(this,"delete",o({method:"DELETE",path:"{topic}"}))}}class ot extends G{constructor(){super(...arguments);n(this,"path","users");n(this,"entity","user");n(this,"create",o({method:"POST"}));n(this,"update",o({method:"PUT",path:"{user_id}"}));n(this,"delete",o({method:"DELETE",path:"{user_id}"}));n(this,"updateByEmail",o({method:"PUT",path:"email:{user_email}"}));n(this,"deleteByEmail",o({method:"DELETE",path:"email:{user_email}"}));n(this,"updateByExternalId",o({method:"PUT",path:"external_id:{external_id}"}));n(this,"deleteByExternalId",o({method:"DELETE",path:"external_id:{external_id}"}))}}const at={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var L,w,I,S,M,U,j,ce,k,ue,N,le,C,fe,$,he,R,de;class ae{constructor(t){h(this,j);h(this,k);h(this,N);h(this,C);h(this,$);h(this,R);h(this,L,void 0);h(this,w,void 0);h(this,I,void 0);h(this,S,void 0);h(this,M,new Fe);h(this,U,[]);n(this,"notificationPreferences",new nt(this));n(this,"notifications",new it(this));n(this,"subscriptions",new st(this));n(this,"users",new ot(this));const r=["apiKey"].filter(i=>!Z(t,i));if(r.length)throw new Error(`You haven't provided all required options, please provide ${we(...r)} to Client(options)`);if(!V(t))throw new Error("You have provided invalid options. Please check your client options.");P(this,S,Object.assign({},at,t)),x(this,M).active=Boolean(x(this,S).debug),P(this,I,Be(t.appInfo)),P(this,L,Ue(t.appInfo)),P(this,w,De())}async request({method:t,path:r,data:i,params:y},a){var l,d;const s=T(T({},x(this,S)),a),f=_(this,j,ce).call(this,s,t),p=Math.max(0,s.maxRetries);for(let E=1;E<=p;E++){let c,u;const m=Date.now();if(x(this,M).debug(`${t} ${r}`),await be.default({method:t,url:r,baseURL:s.host,headers:T(T({},f),J({"X-MAGICBELL-CLIENT-TELEMETRY":_(this,N,le).call(this)})),data:i,params:y,timeout:s.timeout}).then(g=>{c=g}).catch(g=>{u=g,c=g.response}),_(this,k,ue).call(this,c,{startTime:m}),_(this,C,fe).call(this,c,E,p)){const g=Number(c.headers["retry-after"]);await Le(_(this,$,he).call(this,E,g,s.maxRetryDelay));continue}if(u)throw je(T({name:u.name,message:u.message,type:u.type,status:c.status,statusText:c.statusText},(d=(l=c==null?void 0:c.data)==null?void 0:l.errors)==null?void 0:d[0]));return c.data}}}L=new WeakMap,w=new WeakMap,I=new WeakMap,S=new WeakMap,M=new WeakMap,U=new WeakMap,j=new WeakSet,ce=function(t,r){return ve(J({"User-Agent":x(this,L),"Idempotency-Key":t.idempotencyKey||_(this,R,de).call(this,r,t.maxRetries),"X-MAGICBELL-API-KEY":t.apiKey,"X-MAGICBELL-API-SECRET":t.apiSecret,"X-MAGICBELL-CLIENT-ID":x(this,w),"X-MAGICBELL-CLIENT-USER-AGENT":x(this,I),"X-MAGICBELL-USER-EMAIL":t.userEmail,"X-MAGICBELL-USER-KEY":Pe(t.apiSecret,t.userEmail)}))},k=new WeakSet,ue=function(t,{startTime:r}){if(!x(this,S).telemetry||!(t!=null&&t.status))return;const i=J(t.headers);x(this,U).push({id:i["X-Request-Id"],runtime:Number(i["X-Runtime"]),duration:Date.now()-r,status:t.status})},N=new WeakSet,le=function(){const t=x(this,U).pop();return t?JSON.stringify(t):null},C=new WeakSet,fe=function(t,r,i){return r>=i?!1:t?t.headers["should-retry"]?t.headers["should-retry"]==="true":t.status===409||t.status===503||t.status>=500&&t.request.method!=="POST":!0},$=new WeakSet,he=function(t,r=null,i){let a=Math.min(.5*Math.pow(t,2),i);return a*=.75*(1+Math.random()),a=Math.min(Math.max(.5,a),i),Number.isInteger(r)&&r<=60&&(a=Math.max(a,r)),a*1e3},R=new WeakSet,de=function(t,r){if(!(t!=="POST"||r===0))return`magicbell-retry-${se()}`};exports.Client=ae;exports.default=ae; | ||
//# sourceMappingURL=magicbell.cjs.min.js.map |
/** | ||
* @license magicbell v0.1.0 | ||
* @license magicbell v0.2.0 | ||
* | ||
@@ -153,3 +153,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "0.1.0", | ||
binding_version: "0.2.0", | ||
publisher: "magicbell", | ||
@@ -503,16 +503,2 @@ runtime: ((_a = process.release) == null ? void 0 : _a.name) || "node", | ||
} | ||
class Devices extends Resource { | ||
constructor() { | ||
super(...arguments); | ||
__publicField(this, "path", "push_subscriptions"); | ||
__publicField(this, "entity", "push_subscription"); | ||
__publicField(this, "create", createMethod({ | ||
method: "POST" | ||
})); | ||
__publicField(this, "delete", createMethod({ | ||
method: "DELETE", | ||
path: "{device_token}" | ||
})); | ||
} | ||
} | ||
class NotificationPreferences extends Resource { | ||
@@ -523,3 +509,3 @@ constructor() { | ||
__publicField(this, "entity", "notification_preferences"); | ||
__publicField(this, "retrieve", createMethod({ | ||
__publicField(this, "get", createMethod({ | ||
method: "GET" | ||
@@ -544,3 +530,3 @@ })); | ||
})); | ||
__publicField(this, "retrieve", createMethod({ | ||
__publicField(this, "get", createMethod({ | ||
method: "GET", | ||
@@ -559,3 +545,3 @@ path: "{notification_id}" | ||
method: "POST", | ||
path: "{notification_id}/read" | ||
path: "{notification_id}/unread" | ||
})); | ||
@@ -585,5 +571,2 @@ __publicField(this, "archive", createMethod({ | ||
__publicField(this, "entity", "subscription"); | ||
__publicField(this, "create", createMethod({ | ||
method: "POST" | ||
})); | ||
__publicField(this, "list", createMethod({ | ||
@@ -593,3 +576,10 @@ method: "GET", | ||
})); | ||
__publicField(this, "retrieve", createMethod({ | ||
__publicField(this, "create", createMethod({ | ||
method: "POST" | ||
})); | ||
__publicField(this, "unsubscribe", createMethod({ | ||
method: "POST", | ||
path: "{topic}/unsubscribe" | ||
})); | ||
__publicField(this, "get", createMethod({ | ||
method: "GET", | ||
@@ -602,6 +592,2 @@ path: "{topic}" | ||
})); | ||
__publicField(this, "unsubscribe", createMethod({ | ||
method: "POST", | ||
path: "{topic}/unsubscribe" | ||
})); | ||
} | ||
@@ -621,10 +607,2 @@ } | ||
})); | ||
__publicField(this, "updateByEmail", createMethod({ | ||
method: "PUT", | ||
path: "email:{user_id}" | ||
})); | ||
__publicField(this, "updateByExternalId", createMethod({ | ||
method: "PUT", | ||
path: "external_id:{user_id}" | ||
})); | ||
__publicField(this, "delete", createMethod({ | ||
@@ -634,9 +612,17 @@ method: "DELETE", | ||
})); | ||
__publicField(this, "updateByEmail", createMethod({ | ||
method: "PUT", | ||
path: "email:{user_email}" | ||
})); | ||
__publicField(this, "deleteByEmail", createMethod({ | ||
method: "DELETE", | ||
path: "email:{user_id}" | ||
path: "email:{user_email}" | ||
})); | ||
__publicField(this, "updateByExternalId", createMethod({ | ||
method: "PUT", | ||
path: "external_id:{external_id}" | ||
})); | ||
__publicField(this, "deleteByExternalId", createMethod({ | ||
method: "DELETE", | ||
path: "external_id:{user_id}" | ||
path: "external_id:{external_id}" | ||
})); | ||
@@ -666,3 +652,2 @@ } | ||
__privateAdd(this, _lastRequest, []); | ||
__publicField(this, "devices", new Devices(this)); | ||
__publicField(this, "notificationPreferences", new NotificationPreferences(this)); | ||
@@ -809,4 +794,5 @@ __publicField(this, "notifications", new Notifications(this)); | ||
export { | ||
Client, | ||
Client as default | ||
}; | ||
//# sourceMappingURL=magicbell.esm.js.map |
/** | ||
* @license magicbell v0.1.0 | ||
* @license magicbell v0.2.0 | ||
* | ||
@@ -13,9 +13,9 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
var V = Object.getOwnPropertySymbols; | ||
var ye = Object.prototype.hasOwnProperty, ge = Object.prototype.propertyIsEnumerable; | ||
var K = (e, t, r) => t in e ? me(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r, T = (e, t) => { | ||
var ge = Object.prototype.hasOwnProperty, ye = Object.prototype.propertyIsEnumerable; | ||
var K = (e, t, r) => t in e ? me(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r, A = (e, t) => { | ||
for (var r in t || (t = {})) | ||
ye.call(t, r) && K(e, r, t[r]); | ||
ge.call(t, r) && K(e, r, t[r]); | ||
if (V) | ||
for (var r of V(t)) | ||
ge.call(t, r) && K(e, r, t[r]); | ||
ye.call(t, r) && K(e, r, t[r]); | ||
return e; | ||
@@ -27,39 +27,39 @@ }, F = (e, t) => fe(e, de(t)); | ||
}; | ||
var E = (e, t, r) => (X(e, t, "read from private field"), r ? r.call(e) : t.get(e)), m = (e, t, r) => { | ||
var x = (e, t, r) => (X(e, t, "read from private field"), r ? r.call(e) : t.get(e)), m = (e, t, r) => { | ||
if (t.has(e)) | ||
throw TypeError("Cannot add the same private member more than once"); | ||
t instanceof WeakSet ? t.add(e) : t.set(e, r); | ||
}, S = (e, t, r, i) => (X(e, t, "write to private field"), i ? i.call(e, r) : t.set(e, r), r); | ||
}, _ = (e, t, r, i) => (X(e, t, "write to private field"), i ? i.call(e, r) : t.set(e, r), r); | ||
var b = (e, t, r) => (X(e, t, "access private method"), r); | ||
import pe from "axios"; | ||
import Ee from "crypto"; | ||
import { readFileSync as xe, mkdirSync as Te, writeFileSync as Ae, unlinkSync as be } from "fs"; | ||
import { homedir as _e } from "os"; | ||
import xe from "crypto"; | ||
import { readFileSync as Ee, mkdirSync as Ae, writeFileSync as Te, unlinkSync as be } from "fs"; | ||
import { homedir as Pe } from "os"; | ||
import { join as $ } from "path"; | ||
function Pe(e, t) { | ||
return !e || !t ? "" : Ee.createHmac("sha256", e).update(t).digest("base64"); | ||
function Se(e, t) { | ||
return !e || !t ? "" : xe.createHmac("sha256", e).update(t).digest("base64"); | ||
} | ||
const v = /* @__PURE__ */ new Map(), Se = { | ||
configDir: $(_e(), ".magicbell"), | ||
const O = /* @__PURE__ */ new Map(), _e = { | ||
configDir: $(Pe(), ".magicbell"), | ||
get(e, t = null) { | ||
if (v.has(e)) | ||
return v.get(e); | ||
if (O.has(e)) | ||
return O.get(e); | ||
let r = null; | ||
try { | ||
r = JSON.parse(xe($(this.configDir, e), "utf-8") || "null"); | ||
r = JSON.parse(Ee($(this.configDir, e), "utf-8") || "null"); | ||
} catch (i) { | ||
} | ||
return r != null ? (v.set(e, r), r) : t != null ? (this.set(e, t), t) : null; | ||
return r != null ? (O.set(e, r), r) : t != null ? (this.set(e, t), t) : null; | ||
}, | ||
set(e, t) { | ||
v.set(e, t), Te(this.configDir, { recursive: !0 }), Ae($(this.configDir, e), JSON.stringify(t, null, 2), "utf-8"); | ||
O.set(e, t), Ae(this.configDir, { recursive: !0 }), Te($(this.configDir, e), JSON.stringify(t, null, 2), "utf-8"); | ||
}, | ||
delete(e) { | ||
v.delete(e), be($(this.configDir, e)); | ||
O.delete(e), be($(this.configDir, e)); | ||
} | ||
}, W = (e, t) => Object.prototype.hasOwnProperty.call(e, t); | ||
function _(e) { | ||
function P(e) { | ||
return typeof e == "string"; | ||
} | ||
function O(e) { | ||
function L(e) { | ||
return typeof e == "boolean"; | ||
@@ -76,6 +76,6 @@ } | ||
} | ||
function G(e) { | ||
function j(e) { | ||
return e && typeof e == "object"; | ||
} | ||
function ve(e) { | ||
function Oe(e) { | ||
if (typeof e != "object") | ||
@@ -94,6 +94,6 @@ throw new Error("Argument must be an object"); | ||
} | ||
async function Oe(e) { | ||
async function Le(e) { | ||
return new Promise((t) => setTimeout(t, e)); | ||
} | ||
function Le(...e) { | ||
function ve(...e) { | ||
if (e.length <= 2) | ||
@@ -111,3 +111,3 @@ return e.join(" and "); | ||
binding: "magicbell", | ||
binding_version: "0.1.0", | ||
binding_version: "0.2.0", | ||
publisher: "magicbell", | ||
@@ -127,9 +127,9 @@ runtime: ((e = process.release) == null ? void 0 : e.name) || "node", | ||
} | ||
function De(e) { | ||
return JSON.stringify(F(T({}, ie()), { application: e })); | ||
function Ue(e) { | ||
return JSON.stringify(F(A({}, ie()), { application: e })); | ||
} | ||
function Ue() { | ||
return Se.get("client-id", `client_${ne()}`); | ||
function $e() { | ||
return _e.get("client-id", `client_${ne()}`); | ||
} | ||
function $e(e) { | ||
function Be(e) { | ||
for (const t of ["code", "type", "status"]) | ||
@@ -140,3 +140,3 @@ switch (e[t]) { | ||
case "invalid_request_error": | ||
return new Be(e); | ||
return new De(e); | ||
case "api_error": | ||
@@ -157,3 +157,3 @@ return new Ne(e); | ||
} | ||
class A extends Error { | ||
class T extends Error { | ||
constructor(r) { | ||
@@ -172,17 +172,17 @@ super(r.message); | ||
} | ||
class Be extends A { | ||
class De extends T { | ||
} | ||
class ke extends A { | ||
class ke extends T { | ||
} | ||
class Ne extends A { | ||
class Ne extends T { | ||
} | ||
class te extends A { | ||
class te extends T { | ||
} | ||
class Ce extends A { | ||
class Ce extends T { | ||
} | ||
class Re extends A { | ||
class Re extends T { | ||
} | ||
class je extends A { | ||
class je extends T { | ||
} | ||
class Ge extends A { | ||
class Ge extends T { | ||
} | ||
@@ -217,17 +217,17 @@ function H(e) { | ||
const z = { | ||
host: _, | ||
host: P, | ||
maxRetryDelay: Y, | ||
timeout: Y, | ||
apiKey: _, | ||
apiKey: P, | ||
maxRetries: Y, | ||
userEmail: _, | ||
idempotencyKey: _, | ||
telemetry: O, | ||
apiSecret: _, | ||
appInfo: G, | ||
debug: O | ||
userEmail: P, | ||
idempotencyKey: P, | ||
telemetry: L, | ||
apiSecret: P, | ||
appInfo: j, | ||
debug: L | ||
}; | ||
function Z(e) { | ||
var t; | ||
if (!G(e)) | ||
if (!j(e)) | ||
return !1; | ||
@@ -244,24 +244,24 @@ for (const r of Object.keys(e)) | ||
function Ye(e, { data: t, params: r }) { | ||
const i = { currentPromise: null }, g = typeof r.after < "u"; | ||
let a = 0, o = e({ data: t, params: r }); | ||
const i = { currentPromise: null }, y = typeof r.after < "u"; | ||
let a = 0, s = e({ data: t, params: r }); | ||
const h = (u) => { | ||
const d = u.current_page + 1; | ||
return e({ data: t, params: F(T({}, r), { page: d }) }); | ||
return e({ data: t, params: F(A({}, r), { page: d }) }); | ||
}; | ||
function p(u) { | ||
const d = Object.keys(u).find((q) => Array.isArray(u[q])), y = u[d] || u.data; | ||
if (!y || typeof y.length != "number") | ||
const d = Object.keys(u).find((q) => Array.isArray(u[q])), g = u[d] || u.data; | ||
if (!g || typeof g.length != "number") | ||
throw Error("Unexpected: MagicBell API response does not have a well-formed response."); | ||
if (a < y.length) { | ||
const q = g ? y.length - 1 - a : a, he = y[q]; | ||
if (a < g.length) { | ||
const q = y ? g.length - 1 - a : a, he = g[q]; | ||
return a += 1, { value: he, done: !1 }; | ||
} | ||
return Xe(u) ? (a = 0, o = h(u), o.then(p)) : { value: void 0, done: !0 }; | ||
return Xe(u) ? (a = 0, s = h(u), s.then(p)) : { value: void 0, done: !0 }; | ||
} | ||
function l() { | ||
return He(i, (u, d) => o.then(p).then(u).catch(d)); | ||
return He(i, (u, d) => s.then(p).then(u).catch(d)); | ||
} | ||
const f = Je(l), x = ze(f), c = { | ||
const f = Je(l), E = ze(f), c = { | ||
forEach: f, | ||
toArray: x, | ||
toArray: E, | ||
next: l, | ||
@@ -271,3 +271,3 @@ return: () => ({}), | ||
}; | ||
return Object.assign(o, c); | ||
return Object.assign(s, c); | ||
} | ||
@@ -279,5 +279,5 @@ function He(e, t) { | ||
return function(r) { | ||
return new Promise((i, g) => { | ||
return new Promise((i, y) => { | ||
let a = 0; | ||
function o(h) { | ||
function s(h) { | ||
if (h.done) { | ||
@@ -290,5 +290,5 @@ i(); | ||
l(r(p, a)); | ||
}).then((l) => l === !1 ? o({ done: !0 }) : (a++, e().then(o))); | ||
}).then((l) => l === !1 ? s({ done: !0 }) : (a++, e().then(s))); | ||
} | ||
e().then(o).catch(g); | ||
e().then(s).catch(y); | ||
}); | ||
@@ -306,9 +306,9 @@ }; | ||
); | ||
return new Promise((g, a) => { | ||
const o = []; | ||
return new Promise((y, a) => { | ||
const s = []; | ||
e((h) => { | ||
if (o.push(h), o.length >= i) | ||
if (s.push(h), s.length >= i) | ||
return !1; | ||
}).then(() => { | ||
g(o); | ||
y(s); | ||
}).catch(a); | ||
@@ -318,28 +318,28 @@ }); | ||
} | ||
function s({ method: e, path: t, type: r }) { | ||
return function(...g) { | ||
const { path: a, data: o, params: h, options: p } = tt({ | ||
function o({ method: e, path: t, type: r }) { | ||
return function(...y) { | ||
const { path: a, data: s, params: h, options: p } = tt({ | ||
path: we(this.path, t), | ||
method: e, | ||
args: g | ||
}), l = ({ data: f, params: x }) => { | ||
args: y | ||
}), l = ({ data: f, params: E }) => { | ||
const c = this.entity || this.path; | ||
return f = f && { [c]: f }, this.client.request({ method: e, path: a, data: f, params: x }, p).then((u) => u[c] || u); | ||
return f = f && { [c]: f }, this.client.request({ method: e, path: a, data: f, params: E }, p).then((u) => u[c] || u); | ||
}; | ||
return r === "list" ? Ye(l, { | ||
data: o, | ||
data: s, | ||
params: h | ||
}) : l({ data: o, params: h }); | ||
}) : l({ data: s, params: h }); | ||
}; | ||
} | ||
const Q = { | ||
archived: O, | ||
read: O, | ||
seen: O, | ||
categories: (e) => _(e) || ee(e), | ||
topics: (e) => _(e) || ee(e) | ||
archived: L, | ||
read: L, | ||
seen: L, | ||
categories: (e) => P(e) || ee(e), | ||
topics: (e) => P(e) || ee(e) | ||
}; | ||
function Qe(e) { | ||
var t; | ||
if (!G(e)) | ||
if (!j(e)) | ||
return !1; | ||
@@ -358,3 +358,3 @@ for (const r of Object.keys(e)) | ||
function Ve(e) { | ||
return !re(e) || !G(e[0]) ? {} : Z(e[0]) ? {} : e.shift(); | ||
return !re(e) || !j(e[0]) ? {} : Z(e[0]) ? {} : e.shift(); | ||
} | ||
@@ -365,3 +365,3 @@ function et(e) { | ||
const t = e[e.length - 1]; | ||
return Z(t) ? T({}, e.pop()) : {}; | ||
return Z(t) ? A({}, e.pop()) : {}; | ||
} | ||
@@ -382,11 +382,11 @@ function tt({ | ||
return c[u] = d, c; | ||
}, {}), o = We(e, a), h = Ve(i), p = et(i); | ||
}, {}), s = We(e, a), h = Ve(i), p = et(i); | ||
if (i.filter((c) => c != null).length) | ||
throw new Error( | ||
`MagicBell: Unknown arguments (${JSON.stringify(i)}). (on API request to \`${t} ${o}\`)` | ||
`MagicBell: Unknown arguments (${JSON.stringify(i)}). (on API request to \`${t} ${s}\`)` | ||
); | ||
let l = t === "GET" || t === "DELETE"; | ||
return t === "POST" && Qe(h) && (l = !0), { path: o, data: l ? {} : h, params: l ? h : {}, options: p }; | ||
return t === "POST" && Qe(h) && (l = !0), { path: s, data: l ? {} : h, params: l ? h : {}, options: p }; | ||
} | ||
class U { | ||
class G { | ||
constructor(t) { | ||
@@ -399,25 +399,11 @@ n(this, "path"); | ||
} | ||
class rt extends U { | ||
class rt extends G { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "push_subscriptions"); | ||
n(this, "entity", "push_subscription"); | ||
n(this, "create", s({ | ||
method: "POST" | ||
})); | ||
n(this, "delete", s({ | ||
method: "DELETE", | ||
path: "{device_token}" | ||
})); | ||
} | ||
} | ||
class nt extends U { | ||
constructor() { | ||
super(...arguments); | ||
n(this, "path", "notification_preferences"); | ||
n(this, "entity", "notification_preferences"); | ||
n(this, "retrieve", s({ | ||
n(this, "get", o({ | ||
method: "GET" | ||
})); | ||
n(this, "update", s({ | ||
n(this, "update", o({ | ||
method: "PUT" | ||
@@ -427,3 +413,3 @@ })); | ||
} | ||
class it extends U { | ||
class nt extends G { | ||
constructor() { | ||
@@ -433,38 +419,38 @@ super(...arguments); | ||
n(this, "entity", "notification"); | ||
n(this, "create", s({ | ||
n(this, "create", o({ | ||
method: "POST" | ||
})); | ||
n(this, "list", s({ | ||
n(this, "list", o({ | ||
method: "GET", | ||
type: "list" | ||
})); | ||
n(this, "retrieve", s({ | ||
n(this, "get", o({ | ||
method: "GET", | ||
path: "{notification_id}" | ||
})); | ||
n(this, "delete", s({ | ||
n(this, "delete", o({ | ||
method: "DELETE", | ||
path: "{notification_id}" | ||
})); | ||
n(this, "markAsRead", s({ | ||
n(this, "markAsRead", o({ | ||
method: "POST", | ||
path: "{notification_id}/read" | ||
})); | ||
n(this, "markAsUnread", s({ | ||
n(this, "markAsUnread", o({ | ||
method: "POST", | ||
path: "{notification_id}/read" | ||
path: "{notification_id}/unread" | ||
})); | ||
n(this, "archive", s({ | ||
n(this, "archive", o({ | ||
method: "POST", | ||
path: "{notification_id}/archive" | ||
})); | ||
n(this, "unarchive", s({ | ||
n(this, "unarchive", o({ | ||
method: "DELETE", | ||
path: "{notification_id}/archive" | ||
})); | ||
n(this, "markAllRead", s({ | ||
n(this, "markAllRead", o({ | ||
method: "POST", | ||
path: "read" | ||
})); | ||
n(this, "markAllSeen", s({ | ||
n(this, "markAllSeen", o({ | ||
method: "POST", | ||
@@ -475,3 +461,3 @@ path: "seen" | ||
} | ||
class st extends U { | ||
class it extends G { | ||
constructor() { | ||
@@ -481,24 +467,24 @@ super(...arguments); | ||
n(this, "entity", "subscription"); | ||
n(this, "create", s({ | ||
method: "POST" | ||
})); | ||
n(this, "list", s({ | ||
n(this, "list", o({ | ||
method: "GET", | ||
type: "list" | ||
})); | ||
n(this, "retrieve", s({ | ||
n(this, "create", o({ | ||
method: "POST" | ||
})); | ||
n(this, "unsubscribe", o({ | ||
method: "POST", | ||
path: "{topic}/unsubscribe" | ||
})); | ||
n(this, "get", o({ | ||
method: "GET", | ||
path: "{topic}" | ||
})); | ||
n(this, "delete", s({ | ||
n(this, "delete", o({ | ||
method: "DELETE", | ||
path: "{topic}" | ||
})); | ||
n(this, "unsubscribe", s({ | ||
method: "POST", | ||
path: "{topic}/unsubscribe" | ||
})); | ||
} | ||
} | ||
class ot extends U { | ||
class st extends G { | ||
constructor() { | ||
@@ -508,32 +494,32 @@ super(...arguments); | ||
n(this, "entity", "user"); | ||
n(this, "create", s({ | ||
n(this, "create", o({ | ||
method: "POST" | ||
})); | ||
n(this, "update", s({ | ||
n(this, "update", o({ | ||
method: "PUT", | ||
path: "{user_id}" | ||
})); | ||
n(this, "updateByEmail", s({ | ||
method: "PUT", | ||
path: "email:{user_id}" | ||
n(this, "delete", o({ | ||
method: "DELETE", | ||
path: "{user_id}" | ||
})); | ||
n(this, "updateByExternalId", s({ | ||
n(this, "updateByEmail", o({ | ||
method: "PUT", | ||
path: "external_id:{user_id}" | ||
path: "email:{user_email}" | ||
})); | ||
n(this, "delete", s({ | ||
n(this, "deleteByEmail", o({ | ||
method: "DELETE", | ||
path: "{user_id}" | ||
path: "email:{user_email}" | ||
})); | ||
n(this, "deleteByEmail", s({ | ||
method: "DELETE", | ||
path: "email:{user_id}" | ||
n(this, "updateByExternalId", o({ | ||
method: "PUT", | ||
path: "external_id:{external_id}" | ||
})); | ||
n(this, "deleteByExternalId", s({ | ||
n(this, "deleteByExternalId", o({ | ||
method: "DELETE", | ||
path: "external_id:{user_id}" | ||
path: "external_id:{external_id}" | ||
})); | ||
} | ||
} | ||
const at = { | ||
const ot = { | ||
host: "https://api.magicbell.com", | ||
@@ -545,6 +531,7 @@ timeout: 3e4, | ||
}; | ||
var L, w, I, P, M, D, B, se, k, oe, N, ae, C, ce, R, ue, j, le; | ||
class dt { | ||
var v, w, I, S, M, U, B, se, D, oe, k, ae, N, ce, C, ue, R, le; | ||
class ft { | ||
constructor(t) { | ||
m(this, B); | ||
m(this, D); | ||
m(this, k); | ||
@@ -554,50 +541,48 @@ m(this, N); | ||
m(this, R); | ||
m(this, j); | ||
m(this, L, void 0); | ||
m(this, v, void 0); | ||
m(this, w, void 0); | ||
m(this, I, void 0); | ||
m(this, P, void 0); | ||
m(this, S, void 0); | ||
m(this, M, new Ke()); | ||
m(this, D, []); | ||
n(this, "devices", new rt(this)); | ||
n(this, "notificationPreferences", new nt(this)); | ||
n(this, "notifications", new it(this)); | ||
n(this, "subscriptions", new st(this)); | ||
n(this, "users", new ot(this)); | ||
m(this, U, []); | ||
n(this, "notificationPreferences", new rt(this)); | ||
n(this, "notifications", new nt(this)); | ||
n(this, "subscriptions", new it(this)); | ||
n(this, "users", new st(this)); | ||
const r = ["apiKey"].filter((i) => !W(t, i)); | ||
if (r.length) | ||
throw new Error( | ||
`You haven't provided all required options, please provide ${Le(...r)} to Client(options)` | ||
`You haven't provided all required options, please provide ${ve(...r)} to Client(options)` | ||
); | ||
if (!Z(t)) | ||
throw new Error("You have provided invalid options. Please check your client options."); | ||
S(this, P, Object.assign({}, at, t)), E(this, M).active = Boolean(E(this, P).debug), S(this, I, De(t.appInfo)), S(this, L, Me(t.appInfo)), S(this, w, Ue()); | ||
_(this, S, Object.assign({}, ot, t)), x(this, M).active = Boolean(x(this, S).debug), _(this, I, Ue(t.appInfo)), _(this, v, Me(t.appInfo)), _(this, w, $e()); | ||
} | ||
async request({ method: t, path: r, data: i, params: g }, a) { | ||
async request({ method: t, path: r, data: i, params: y }, a) { | ||
var l, f; | ||
const o = T(T({}, E(this, P)), a), h = b(this, B, se).call(this, o, t), p = Math.max(0, o.maxRetries); | ||
for (let x = 1; x <= p; x++) { | ||
const s = A(A({}, x(this, S)), a), h = b(this, B, se).call(this, s, t), p = Math.max(0, s.maxRetries); | ||
for (let E = 1; E <= p; E++) { | ||
let c, u; | ||
const d = Date.now(); | ||
if (E(this, M).debug(`${t} ${r}`), await pe({ | ||
if (x(this, M).debug(`${t} ${r}`), await pe({ | ||
method: t, | ||
url: r, | ||
baseURL: o.host, | ||
headers: T(T({}, h), H({ | ||
"X-MAGICBELL-CLIENT-TELEMETRY": b(this, N, ae).call(this) | ||
baseURL: s.host, | ||
headers: A(A({}, h), H({ | ||
"X-MAGICBELL-CLIENT-TELEMETRY": b(this, k, ae).call(this) | ||
})), | ||
data: i, | ||
params: g, | ||
timeout: o.timeout | ||
}).then((y) => { | ||
c = y; | ||
}).catch((y) => { | ||
u = y, c = y.response; | ||
}), b(this, k, oe).call(this, c, { startTime: d }), b(this, C, ce).call(this, c, x, p)) { | ||
const y = Number(c.headers["retry-after"]); | ||
await Oe(b(this, R, ue).call(this, x, y, o.maxRetryDelay)); | ||
params: y, | ||
timeout: s.timeout | ||
}).then((g) => { | ||
c = g; | ||
}).catch((g) => { | ||
u = g, c = g.response; | ||
}), b(this, D, oe).call(this, c, { startTime: d }), b(this, N, ce).call(this, c, E, p)) { | ||
const g = Number(c.headers["retry-after"]); | ||
await Le(b(this, C, ue).call(this, E, g, s.maxRetryDelay)); | ||
continue; | ||
} | ||
if (u) | ||
throw $e(T({ | ||
throw Be(A({ | ||
name: u.name, | ||
@@ -613,20 +598,20 @@ message: u.message, | ||
} | ||
L = new WeakMap(), w = new WeakMap(), I = new WeakMap(), P = new WeakMap(), M = new WeakMap(), D = new WeakMap(), B = new WeakSet(), se = function(t, r) { | ||
return ve( | ||
v = new WeakMap(), w = new WeakMap(), I = new WeakMap(), S = new WeakMap(), M = new WeakMap(), U = new WeakMap(), B = new WeakSet(), se = function(t, r) { | ||
return Oe( | ||
H({ | ||
"User-Agent": E(this, L), | ||
"Idempotency-Key": t.idempotencyKey || b(this, j, le).call(this, r, t.maxRetries), | ||
"User-Agent": x(this, v), | ||
"Idempotency-Key": t.idempotencyKey || b(this, R, le).call(this, r, t.maxRetries), | ||
"X-MAGICBELL-API-KEY": t.apiKey, | ||
"X-MAGICBELL-API-SECRET": t.apiSecret, | ||
"X-MAGICBELL-CLIENT-ID": E(this, w), | ||
"X-MAGICBELL-CLIENT-USER-AGENT": E(this, I), | ||
"X-MAGICBELL-CLIENT-ID": x(this, w), | ||
"X-MAGICBELL-CLIENT-USER-AGENT": x(this, I), | ||
"X-MAGICBELL-USER-EMAIL": t.userEmail, | ||
"X-MAGICBELL-USER-KEY": Pe(t.apiSecret, t.userEmail) | ||
"X-MAGICBELL-USER-KEY": Se(t.apiSecret, t.userEmail) | ||
}) | ||
); | ||
}, k = new WeakSet(), oe = function(t, { startTime: r }) { | ||
if (!E(this, P).telemetry || !(t != null && t.status)) | ||
}, D = new WeakSet(), oe = function(t, { startTime: r }) { | ||
if (!x(this, S).telemetry || !(t != null && t.status)) | ||
return; | ||
const i = H(t.headers); | ||
E(this, D).push({ | ||
x(this, U).push({ | ||
id: i["X-Request-Id"], | ||
@@ -637,11 +622,11 @@ runtime: Number(i["X-Runtime"]), | ||
}); | ||
}, N = new WeakSet(), ae = function() { | ||
const t = E(this, D).pop(); | ||
}, k = new WeakSet(), ae = function() { | ||
const t = x(this, U).pop(); | ||
return t ? JSON.stringify(t) : null; | ||
}, C = new WeakSet(), ce = function(t, r, i) { | ||
}, N = new WeakSet(), ce = function(t, r, i) { | ||
return r >= i ? !1 : t ? t.headers["should-retry"] ? t.headers["should-retry"] === "true" : t.status === 409 || t.status === 503 || t.status >= 500 && t.request.method !== "POST" : !0; | ||
}, R = new WeakSet(), ue = function(t, r = null, i) { | ||
}, C = new WeakSet(), ue = function(t, r = null, i) { | ||
let a = Math.min(0.5 * Math.pow(t, 2), i); | ||
return a *= 0.75 * (1 + Math.random()), a = Math.min(Math.max(0.5, a), i), Number.isInteger(r) && r <= 60 && (a = Math.max(a, r)), a * 1e3; | ||
}, j = new WeakSet(), le = function(t, r) { | ||
}, R = new WeakSet(), le = function(t, r) { | ||
if (!(t !== "POST" || r === 0)) | ||
@@ -651,4 +636,5 @@ return `magicbell-retry-${ne()}`; | ||
export { | ||
dt as default | ||
ft as Client, | ||
ft as default | ||
}; | ||
//# sourceMappingURL=magicbell.esm.min.js.map |
@@ -5,4 +5,10 @@ import { Resource } from '../resource'; | ||
entity: string; | ||
retrieve: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Fetch user notification preferences | ||
**/ | ||
get: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Update user notification preferences | ||
**/ | ||
update: (this: Resource, ...args: any[]) => Promise<any>; | ||
} |
@@ -5,3 +5,9 @@ import { Resource } from '../resource'; | ||
entity: string; | ||
/** | ||
* Create notifications | ||
**/ | ||
create: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Fetch notifications | ||
**/ | ||
list: (this: Resource, ...args: any[]) => Promise<any> & { | ||
@@ -14,10 +20,34 @@ forEach(cb: (node: any, index: number) => boolean | void | Promise<boolean | void>): Promise<void>; | ||
}; | ||
retrieve: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Fetch a notification | ||
**/ | ||
get: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Delete a notification | ||
**/ | ||
delete: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Mark a notification as read | ||
**/ | ||
markAsRead: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Mark a notification as unread | ||
**/ | ||
markAsUnread: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Archive a notification | ||
**/ | ||
archive: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Unarchive a notification | ||
**/ | ||
unarchive: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Mark all notifications as read | ||
**/ | ||
markAllRead: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Mark all notifications as seen | ||
**/ | ||
markAllSeen: (this: Resource, ...args: any[]) => Promise<any>; | ||
} |
@@ -5,3 +5,5 @@ import { Resource } from '../resource'; | ||
entity: string; | ||
create: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* List subscriptions | ||
**/ | ||
list: (this: Resource, ...args: any[]) => Promise<any> & { | ||
@@ -14,5 +16,18 @@ forEach(cb: (node: any, index: number) => boolean | void | Promise<boolean | void>): Promise<void>; | ||
}; | ||
retrieve: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Create a topic subscription | ||
**/ | ||
create: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Unsubscribe from a topic | ||
**/ | ||
unsubscribe: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Show a topic subscription | ||
**/ | ||
get: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Delete topic subscription(s) | ||
**/ | ||
delete: (this: Resource, ...args: any[]) => Promise<any>; | ||
unsubscribe: (this: Resource, ...args: any[]) => Promise<any>; | ||
} |
@@ -5,9 +5,30 @@ import { Resource } from '../resource'; | ||
entity: string; | ||
/** | ||
* Create a user | ||
**/ | ||
create: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Update a user | ||
**/ | ||
update: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Delete a user | ||
**/ | ||
delete: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Update a user by email | ||
**/ | ||
updateByEmail: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Delete a user by email | ||
**/ | ||
deleteByEmail: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Update a user by external ID | ||
**/ | ||
updateByExternalId: (this: Resource, ...args: any[]) => Promise<any>; | ||
delete: (this: Resource, ...args: any[]) => Promise<any>; | ||
deleteByEmail: (this: Resource, ...args: any[]) => Promise<any>; | ||
/** | ||
* Delete a user by external ID | ||
**/ | ||
deleteByExternalId: (this: Resource, ...args: any[]) => Promise<any>; | ||
} |
@@ -18,5 +18,5 @@ export declare type ClientOptions = { | ||
}; | ||
export declare type RequestClientOptions = Pick<ClientOptions, 'userEmail' | 'idempotencyKey' | 'timeout' | 'maxRetries' | 'maxRetryDelay'>; | ||
export declare type RequestOptions = Pick<ClientOptions, 'userEmail' | 'idempotencyKey' | 'timeout' | 'maxRetries' | 'maxRetryDelay'>; | ||
export declare type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; | ||
export declare type RequestOptions = { | ||
export declare type RequestArgs = { | ||
method: RequestMethod; | ||
@@ -23,0 +23,0 @@ path: string; |
{ | ||
"name": "magicbell", | ||
"version": "0.1.0", | ||
"version": "0.2.0", | ||
"description": "MagicBell API wrapper", | ||
@@ -39,2 +39,3 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com)", | ||
"build:prod": "vite build -c ../../scripts/vite/vite.config.js --minify", | ||
"generate:resources": "tsx scripts/generate-resources.ts -- --no-cache", | ||
"start": "yarn build:dev --watch", | ||
@@ -54,3 +55,8 @@ "size": "size-limit" | ||
"devDependencies": { | ||
"@size-limit/preset-small-lib": "^8.0.1" | ||
"@apidevtools/swagger-parser": "^10.1.0", | ||
"@size-limit/preset-small-lib": "^8.0.1", | ||
"ast-types": "^0.14.2", | ||
"json5": "^2.2.1", | ||
"openapi-types": "^12.0.2", | ||
"recast": "^0.21.2" | ||
}, | ||
@@ -60,4 +66,5 @@ "dependencies": { | ||
"axios-retry": "^3.3.1", | ||
"qs": "^6.11.0" | ||
"qs": "^6.11.0", | ||
"tsx": "^3.9.0" | ||
} | ||
} |
410
README.md
@@ -5,3 +5,5 @@ # MagicBell Node.js Library | ||
> note: This package is in early release and is subject to change. TypeScript is supported, but api responses are untyped at the moment. We'll add types before we reach v1.0.0. | ||
> **Note** | ||
> | ||
> This package is in early release and is subject to change. TypeScript is supported, but api responses are untyped at the moment. We'll add types before we reach v1.0.0. | ||
@@ -32,5 +34,5 @@ ## Requirements | ||
```js | ||
const MagicBell = new require('magicbell'); | ||
import MagicBell from 'magicbell'; | ||
const magicbell = new Client({ | ||
const magicbell = new MagicBell({ | ||
apiKey: 'your-api-key', | ||
@@ -55,5 +57,5 @@ apiSecret: 'your-api-secret', | ||
```js | ||
const MagicBell = new require('magicbell'); | ||
const MagicBell = require('magicbell').default; | ||
const magicbell = new Client({ | ||
const magicbell = new MagicBell({ | ||
apiKey: 'your-api-key', | ||
@@ -76,3 +78,3 @@ apiSecret: 'your-api-secret', | ||
```js | ||
const magicbell = new Client({ | ||
const magicbell = new MagicBell({ | ||
apiKey: 'your-api-key', | ||
@@ -297,2 +299,397 @@ apiSecret: 'your-api-secret', | ||
## Resource methods | ||
Below you'll find the all supported resource methods, with their signatures. The full documentation can be found in our [api-reference][api-reference]. When comparing the api-reference with these methods, you'll notice that the SDK removes any wrapping entities for your convenience. Meaning, instead of posting `{ notification: { title: 'hi' } }`, you'll call `create({ title: 'hi' })`. | ||
Apart from the removal of the wrappers, returned entities and provided parameters are identical between our REST API and this SDK. | ||
<!-- AUTO-GENERATED-CONTENT:START (RESOURCE_METHODS) --> | ||
### Notifications | ||
#### Create notifications | ||
Send a notification to one or multiple users. You can identify users by their email address or by an external_id. | ||
You don't have to import your users into MagicBell. If a user does not exist we'll create it automatically. | ||
You can send user attributes like first_name, custom_attributes, and more when creating a notification. | ||
The new notification will be shown in the notification inbox of each recipient in real-time. It will also be delivered to each recipient through all channels your have enabled for your MagicBell project. | ||
```js | ||
await magicbell.notifications.create({ | ||
title: "We're processing your order", | ||
content: "<p>Thank you for your order. We'll notify you when these items are ready.</p>", | ||
category: 'order_created', | ||
topic: 'order:33098', | ||
recipients: [ | ||
{ | ||
email: 'dan@example.com', | ||
}, | ||
{ | ||
external_id: '83d987a-83fd034', | ||
first_name: 'Hana', | ||
last_name: 'Mohan', | ||
custom_attributes: { | ||
plan: 'enterprise', | ||
pricing_version: 'v10', | ||
preferred_pronoun: 'She', | ||
}, | ||
phone_numbers: ['+15005550001'], | ||
}, | ||
{ | ||
matches: 'custom_attributes.order.id = 88492', | ||
}, | ||
], | ||
overrides: { | ||
email: { | ||
title: "[MagicBell] We're processing your order", | ||
content: | ||
"Thank you for your order. If you need help, or have any questions please don't hesitate to reach out to us directly at hello@magicbell.com", | ||
}, | ||
}, | ||
}); | ||
``` | ||
#### Fetch notifications | ||
Fetch a user's notifications. Notifications are sorted in descendent order by the sent_at timestamp. | ||
```js | ||
await magicbell.notifications.list( | ||
{ | ||
per_page: 1, | ||
page: 1, | ||
read: true, | ||
seen: true, | ||
archived: true, | ||
categories: ['…'], | ||
topics: ['…'], | ||
}, | ||
{ | ||
userEmail: 'person@example.com', | ||
}, | ||
); | ||
``` | ||
#### Fetch a notification | ||
Fetch a user's notification by its ID. | ||
```js | ||
await magicbell.notifications.get('{notification_id}', { | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Delete a notification | ||
Delete a user's notification by its ID. The notification is deleted immediately and removed from the user's notification inbox in real-time. | ||
```js | ||
await magicbell.notifications.delete('{notification_id}', { | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Mark a notification as read | ||
Mark a user notification as read. The notification will be automatically marked as seen, too. | ||
The new state will be reflected in the user's notification inbox in real-time. | ||
```js | ||
await magicbell.notifications.markAsRead('{notification_id}', { | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Mark a notification as unread | ||
Mark a user notification as unread. The new state will be reflected in the user's notification inbox in real-time. | ||
```js | ||
await magicbell.notifications.markAsUnread('{notification_id}', { | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Archive a notification | ||
Mark a user notification as archived. | ||
```js | ||
await magicbell.notifications.archive('{notification_id}', { | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Unarchive a notification | ||
Mark a user notification as unarchived. | ||
```js | ||
await magicbell.notifications.unarchive('{notification_id}', { | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Mark all notifications as read | ||
Mark all notifications of a user as read. When you call this endpoint, the notification inboxes of this user will be updated in real-time. | ||
```js | ||
await magicbell.notifications.markAllRead( | ||
{ | ||
archived: true, | ||
read: true, | ||
seen: true, | ||
categories: ['…'], | ||
topics: ['…'], | ||
}, | ||
{ | ||
userEmail: 'person@example.com', | ||
}, | ||
); | ||
``` | ||
#### Mark all notifications as seen | ||
Mark all notifications of a user as seen. When you call this endpoint, the notification inboxes of this user will be updated in real-time. | ||
```js | ||
await magicbell.notifications.markAllSeen( | ||
{ | ||
archived: true, | ||
read: true, | ||
seen: true, | ||
categories: ['…'], | ||
topics: ['…'], | ||
}, | ||
{ | ||
userEmail: 'person@example.com', | ||
}, | ||
); | ||
``` | ||
### Users | ||
#### Create a user | ||
Create a user. Please note that you must provide the user's email or the external id so MagicBell can uniquely identify the user. | ||
The external id, if provided, must be unique to the user. | ||
```js | ||
await magicbell.users.create({ | ||
external_id: '56780', | ||
email: 'hana@supportbee.com', | ||
first_name: 'Hana', | ||
last_name: 'Mohan', | ||
custom_attributes: { | ||
plan: 'enterprise', | ||
pricing_version: 'v10', | ||
preferred_pronoun: 'She', | ||
}, | ||
phone_numbers: ['+15005550001'], | ||
}); | ||
``` | ||
#### Update a user | ||
Update a user's data. If you identify users by their email addresses, you need to update the MagicBell data, so this user can still access their notifications. | ||
```js | ||
await magicbell.users.update('{user_id}', { | ||
email: 'hana@magicbell.io', | ||
}); | ||
``` | ||
#### Delete a user | ||
Immediately deletes a user. | ||
```js | ||
await magicbell.users.delete('{user_id}'); | ||
``` | ||
#### Update a user by email | ||
Update a user's data. If you identify users by their email addresses, you need to update the MagicBell data, so this user can still access their notifications. | ||
```js | ||
await magicbell.users.updateByEmail('{user_email}', { | ||
external_id: '56780', | ||
email: 'hana@supportbee.com', | ||
first_name: 'Hana', | ||
last_name: 'Mohan', | ||
custom_attributes: { | ||
plan: 'enterprise', | ||
pricing_version: 'v10', | ||
preferred_pronoun: 'She', | ||
}, | ||
phone_numbers: ['+15005550001'], | ||
}); | ||
``` | ||
#### Delete a user by email | ||
Immediately deletes a user. | ||
```js | ||
await magicbell.users.deleteByEmail('{user_email}'); | ||
``` | ||
#### Update a user by external ID | ||
Update a user's data. If you identify users by their email addresses, you need to update the MagicBell data, so this user can still access their notifications. | ||
```js | ||
await magicbell.users.updateByExternalId('{external_id}', { | ||
external_id: '56780', | ||
email: 'hana@supportbee.com', | ||
first_name: 'Hana', | ||
last_name: 'Mohan', | ||
custom_attributes: { | ||
plan: 'enterprise', | ||
pricing_version: 'v10', | ||
preferred_pronoun: 'She', | ||
}, | ||
phone_numbers: ['+15005550001'], | ||
}); | ||
``` | ||
#### Delete a user by external ID | ||
Immediately deletes a user. | ||
```js | ||
await magicbell.users.deleteByExternalId('{external_id}'); | ||
``` | ||
### Notification Preferences | ||
#### Fetch user notification preferences | ||
Fetch a user's notification preferences. If a user does not disable a channel explicitly, we would send notifications through that channel as long as your project is enabled. | ||
```js | ||
await magicbell.notificationPreferences.get({ | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Update user notification preferences | ||
Update a user's notification preferences. These preferences will be applied only to channels you enabled for your project. | ||
```js | ||
await magicbell.notificationPreferences.update( | ||
{ | ||
categories: [ | ||
{ | ||
slug: 'billing', | ||
channels: [ | ||
{ | ||
slug: 'email', | ||
enabled: false, | ||
}, | ||
{ | ||
slug: 'web_push', | ||
enabled: false, | ||
}, | ||
], | ||
}, | ||
], | ||
}, | ||
{ | ||
userEmail: 'person@example.com', | ||
}, | ||
); | ||
``` | ||
### Subscriptions | ||
#### List subscriptions | ||
List a user's subscriptions status for all topics and categories. | ||
```js | ||
await magicbell.subscriptions.list({ | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Create a topic subscription | ||
Set a user's subscription status to subscribed for a particular topic (and optional categories). If the user previously unsubscribed, the user will be resubscribed. | ||
```js | ||
await magicbell.subscriptions.create( | ||
{ | ||
categories: [ | ||
{ | ||
slug: 'comments', | ||
reason: 'watching-the-repo', | ||
}, | ||
], | ||
topic: 'acme-inc.orders.1234', | ||
}, | ||
{ | ||
userEmail: 'person@example.com', | ||
}, | ||
); | ||
``` | ||
#### Unsubscribe from a topic | ||
Unusbscribe a user from a particular topic (and optional categories). | ||
```js | ||
await magicbell.subscriptions.unsubscribe( | ||
'{topic}', | ||
{ | ||
categories: [ | ||
{ | ||
slug: 'comments', | ||
}, | ||
], | ||
}, | ||
{ | ||
userEmail: 'person@example.com', | ||
}, | ||
); | ||
``` | ||
#### Show a topic subscription | ||
Show a user's subscription status for a particular topic and categories. | ||
```js | ||
await magicbell.subscriptions.get('{topic}', { | ||
userEmail: 'person@example.com', | ||
}); | ||
``` | ||
#### Delete topic subscription(s) | ||
```js | ||
await magicbell.subscriptions.delete( | ||
'{topic}', | ||
{ | ||
categories: [ | ||
{ | ||
slug: '…', | ||
}, | ||
], | ||
}, | ||
{ | ||
userEmail: 'person@example.com', | ||
}, | ||
); | ||
``` | ||
<!-- AUTO-GENERATED-CONTENT:END (RESOURCE_METHODS) --> | ||
## Support | ||
@@ -309,1 +706,2 @@ | ||
[hmac-authentication]: https://www.magicbell.com/docs/hmac-authentication | ||
[api-reference]: https://www.magicbell.com/docs/rest-api/reference |
@@ -10,3 +10,2 @@ import axios, { AxiosError, AxiosResponse } from 'axios'; | ||
import { isOptionsHash } from './options'; | ||
import { Devices } from './resources/devices'; | ||
import { NotificationPreferences } from './resources/notification-preferences'; | ||
@@ -16,3 +15,3 @@ import { Notifications } from './resources/notifications'; | ||
import { Users } from './resources/users'; | ||
import { ClientOptions, RequestClientOptions, RequestMethod, RequestOptions } from './types'; | ||
import { ClientOptions, RequestArgs, RequestMethod, RequestOptions } from './types'; | ||
@@ -36,4 +35,2 @@ export const DEFAULT_OPTIONS: Partial<ClientOptions> = { | ||
// resources | ||
devices = new Devices(this); | ||
notificationPreferences = new NotificationPreferences(this); | ||
@@ -63,3 +60,3 @@ notifications = new Notifications(this); | ||
async request({ method, path, data, params }: RequestOptions, options?: RequestClientOptions) { | ||
async request({ method, path, data, params }: RequestArgs, options?: RequestOptions) { | ||
const requestOptions = { ...this.#options, ...options }; | ||
@@ -66,0 +63,0 @@ |
@@ -1,1 +0,2 @@ | ||
export { Client as default } from './client'; | ||
export { Client, Client as default } from './client'; | ||
export type { ClientOptions, RequestOptions } from './types'; |
@@ -0,1 +1,2 @@ | ||
// This file is generated. Do not update manually! | ||
import { createMethod } from '../method'; | ||
@@ -8,6 +9,12 @@ import { Resource } from '../resource'; | ||
retrieve = createMethod({ | ||
/** | ||
* Fetch user notification preferences | ||
**/ | ||
get = createMethod({ | ||
method: 'GET', | ||
}); | ||
/** | ||
* Update user notification preferences | ||
**/ | ||
update = createMethod({ | ||
@@ -14,0 +21,0 @@ method: 'PUT', |
@@ -0,1 +1,2 @@ | ||
// This file is generated. Do not update manually! | ||
import { createMethod } from '../method'; | ||
@@ -8,2 +9,5 @@ import { Resource } from '../resource'; | ||
/** | ||
* Create notifications | ||
**/ | ||
create = createMethod({ | ||
@@ -13,2 +17,5 @@ method: 'POST', | ||
/** | ||
* Fetch notifications | ||
**/ | ||
list = createMethod({ | ||
@@ -19,3 +26,6 @@ method: 'GET', | ||
retrieve = createMethod({ | ||
/** | ||
* Fetch a notification | ||
**/ | ||
get = createMethod({ | ||
method: 'GET', | ||
@@ -25,2 +35,5 @@ path: '{notification_id}', | ||
/** | ||
* Delete a notification | ||
**/ | ||
delete = createMethod({ | ||
@@ -31,2 +44,5 @@ method: 'DELETE', | ||
/** | ||
* Mark a notification as read | ||
**/ | ||
markAsRead = createMethod({ | ||
@@ -37,7 +53,13 @@ method: 'POST', | ||
/** | ||
* Mark a notification as unread | ||
**/ | ||
markAsUnread = createMethod({ | ||
method: 'POST', | ||
path: '{notification_id}/read', | ||
path: '{notification_id}/unread', | ||
}); | ||
/** | ||
* Archive a notification | ||
**/ | ||
archive = createMethod({ | ||
@@ -48,2 +70,5 @@ method: 'POST', | ||
/** | ||
* Unarchive a notification | ||
**/ | ||
unarchive = createMethod({ | ||
@@ -54,2 +79,5 @@ method: 'DELETE', | ||
/** | ||
* Mark all notifications as read | ||
**/ | ||
markAllRead = createMethod({ | ||
@@ -60,2 +88,5 @@ method: 'POST', | ||
/** | ||
* Mark all notifications as seen | ||
**/ | ||
markAllSeen = createMethod({ | ||
@@ -62,0 +93,0 @@ method: 'POST', |
@@ -0,1 +1,2 @@ | ||
// This file is generated. Do not update manually! | ||
import { createMethod } from '../method'; | ||
@@ -8,2 +9,13 @@ import { Resource } from '../resource'; | ||
/** | ||
* List subscriptions | ||
**/ | ||
list = createMethod({ | ||
method: 'GET', | ||
type: 'list', | ||
}); | ||
/** | ||
* Create a topic subscription | ||
**/ | ||
create = createMethod({ | ||
@@ -13,8 +25,14 @@ method: 'POST', | ||
list = createMethod({ | ||
method: 'GET', | ||
type: 'list', | ||
/** | ||
* Unsubscribe from a topic | ||
**/ | ||
unsubscribe = createMethod({ | ||
method: 'POST', | ||
path: '{topic}/unsubscribe', | ||
}); | ||
retrieve = createMethod({ | ||
/** | ||
* Show a topic subscription | ||
**/ | ||
get = createMethod({ | ||
method: 'GET', | ||
@@ -24,2 +42,5 @@ path: '{topic}', | ||
/** | ||
* Delete topic subscription(s) | ||
**/ | ||
delete = createMethod({ | ||
@@ -29,7 +50,2 @@ method: 'DELETE', | ||
}); | ||
unsubscribe = createMethod({ | ||
method: 'POST', | ||
path: '{topic}/unsubscribe', | ||
}); | ||
} |
@@ -0,1 +1,2 @@ | ||
// This file is generated. Do not update manually! | ||
import { createMethod } from '../method'; | ||
@@ -8,2 +9,5 @@ import { Resource } from '../resource'; | ||
/** | ||
* Create a user | ||
**/ | ||
create = createMethod({ | ||
@@ -13,2 +17,5 @@ method: 'POST', | ||
/** | ||
* Update a user | ||
**/ | ||
update = createMethod({ | ||
@@ -19,26 +26,41 @@ method: 'PUT', | ||
updateByEmail = createMethod({ | ||
method: 'PUT', | ||
path: 'email:{user_id}', | ||
/** | ||
* Delete a user | ||
**/ | ||
delete = createMethod({ | ||
method: 'DELETE', | ||
path: '{user_id}', | ||
}); | ||
updateByExternalId = createMethod({ | ||
/** | ||
* Update a user by email | ||
**/ | ||
updateByEmail = createMethod({ | ||
method: 'PUT', | ||
path: 'external_id:{user_id}', | ||
path: 'email:{user_email}', | ||
}); | ||
delete = createMethod({ | ||
/** | ||
* Delete a user by email | ||
**/ | ||
deleteByEmail = createMethod({ | ||
method: 'DELETE', | ||
path: '{user_id}', | ||
path: 'email:{user_email}', | ||
}); | ||
deleteByEmail = createMethod({ | ||
method: 'DELETE', | ||
path: 'email:{user_id}', | ||
/** | ||
* Update a user by external ID | ||
**/ | ||
updateByExternalId = createMethod({ | ||
method: 'PUT', | ||
path: 'external_id:{external_id}', | ||
}); | ||
/** | ||
* Delete a user by external ID | ||
**/ | ||
deleteByExternalId = createMethod({ | ||
method: 'DELETE', | ||
path: 'external_id:{user_id}', | ||
path: 'external_id:{external_id}', | ||
}); | ||
} |
@@ -19,3 +19,3 @@ export type ClientOptions = { | ||
export type RequestClientOptions = Pick< | ||
export type RequestOptions = Pick< | ||
ClientOptions, | ||
@@ -27,3 +27,3 @@ 'userEmail' | 'idempotencyKey' | 'timeout' | 'maxRetries' | 'maxRetryDelay' | ||
export type RequestOptions = { | ||
export type RequestArgs = { | ||
method: RequestMethod; | ||
@@ -30,0 +30,0 @@ path: 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
333289
3748
702
4
6
50
+ Addedtsx@^3.9.0
+ Added@esbuild/android-arm@0.18.20(transitive)
+ Added@esbuild/android-arm64@0.18.20(transitive)
+ Added@esbuild/android-x64@0.18.20(transitive)
+ Added@esbuild/darwin-arm64@0.18.20(transitive)
+ Added@esbuild/darwin-x64@0.18.20(transitive)
+ Added@esbuild/freebsd-arm64@0.18.20(transitive)
+ Added@esbuild/freebsd-x64@0.18.20(transitive)
+ Added@esbuild/linux-arm@0.18.20(transitive)
+ Added@esbuild/linux-arm64@0.18.20(transitive)
+ Added@esbuild/linux-ia32@0.18.20(transitive)
+ Added@esbuild/linux-loong64@0.18.20(transitive)
+ Added@esbuild/linux-mips64el@0.18.20(transitive)
+ Added@esbuild/linux-ppc64@0.18.20(transitive)
+ Added@esbuild/linux-riscv64@0.18.20(transitive)
+ Added@esbuild/linux-s390x@0.18.20(transitive)
+ Added@esbuild/linux-x64@0.18.20(transitive)
+ Added@esbuild/netbsd-x64@0.18.20(transitive)
+ Added@esbuild/openbsd-x64@0.18.20(transitive)
+ Added@esbuild/sunos-x64@0.18.20(transitive)
+ Added@esbuild/win32-arm64@0.18.20(transitive)
+ Added@esbuild/win32-ia32@0.18.20(transitive)
+ Added@esbuild/win32-x64@0.18.20(transitive)
+ Addedbuffer-from@1.1.2(transitive)
+ Addedesbuild@0.18.20(transitive)
+ Addedfsevents@2.3.3(transitive)
+ Addedget-tsconfig@4.10.0(transitive)
+ Addedobject-inspect@1.13.3(transitive)
+ Addedresolve-pkg-maps@1.0.0(transitive)
+ Addedsource-map@0.6.1(transitive)
+ Addedsource-map-support@0.5.21(transitive)
+ Addedtsx@3.14.0(transitive)
- Removedobject-inspect@1.13.4(transitive)