Comparing version 1.1.0 to 1.2.0
/** | ||
* @license magicbell v1.1.0 | ||
* @license magicbell v1.2.0 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) MagicBell Inc. and its affiliates. |
/** | ||
* @license magicbell v1.1.0 | ||
* @license magicbell v1.2.0 | ||
* | ||
@@ -77,3 +77,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "1.1.0", | ||
binding_version: "1.2.0", | ||
publisher: "magicbell" | ||
@@ -455,2 +455,3 @@ }; | ||
eventSource.close(); | ||
pushMessage({ done: true, value: void 0 }); | ||
return { done: true, value: void 0 }; | ||
@@ -461,2 +462,3 @@ }; | ||
forEach, | ||
close: dispose, | ||
next: asyncIteratorNext, | ||
@@ -463,0 +465,0 @@ return: dispose, |
/** | ||
* @license magicbell v1.1.0 | ||
* @license magicbell v1.2.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,Te=Object.prototype.propertyIsEnumerable;var D=(e,t,r)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t)=>{for(var r in t||(t={}))xe.call(t,r)&&D(e,r,t[r]);if(ee)for(var r of ee(t))Te.call(t,r)&&D(e,r,t[r]);return e},k=(e,t)=>ye(e,Ee(t));var i=(e,t,r)=>(D(e,typeof t!="symbol"?t+"":t,r),r),F=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var T=(e,t,r)=>(F(e,t,"read from private field"),r?r.call(e):t.get(e)),x=(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)},O=(e,t,r,n)=>(F(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var v=(e,t,r)=>(F(e,t,"access private method"),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const be=require("axios"),Pe=require("crypto"),Se=require("eventsource"),W=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Z=W(be),X=W(Pe),ve=W(Se);function se(e,t){if(!e||!t)return"";if(!X.default||!X.default.createHmac)throw new Error("This method is not available in the browser. Please provide a userHmac.");return X.default.createHmac("sha256",e).update(t).digest("base64")}function ie(){var t;const e={binding:"magicbell",binding_version:"1.1.0",publisher:"magicbell"};return typeof process>"u"?e:k(b({},e),{runtime:((t=process==null?void 0:process.release)==null?void 0:t.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch})}function Ae(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function _e(e){const t=ie();return[`${t.binding}/${t.binding_version}`,"runtime"in t&&`${t.runtime}/${t.runtime_version}`,Ae(e)].filter(Boolean).join(" ")}function we(e){return JSON.stringify(k(b({},ie()),{application:e}))}function qe(e){for(const t of["code","type","status"])switch(e[t]){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 S extends Error{constructor(r){super(r.message);i(this,"name");i(this,"message");i(this,"type");i(this,"docs_url");i(this,"code");i(this,"status");i(this,"statusText");i(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 Oe extends S{}class Le extends S{}class $e extends S{}class te extends S{}class Ie extends S{}class Me extends S{}class Ue extends S{}class Be extends S{}function K(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 _={reset:"\x1B[0m",magenta:"\x1B[35m",red:"\x1B[31m"};class Ne{constructor(){i(this,"active",!1)}debug(t){!this.active||console.log(`${_.reset}${_.magenta}magicbell:${_.reset} ${t}`)}error(t){!this.active||console.error(`${_.reset}${_.red}magicbell:${_.reset} ${t}`)}}function Re(e){return`${e.slice(0,4)}\u2026${e.slice(-4)}`}const je=/secret|token|key|password/i;function He(e){return je.test(e)}function Ce({method:e,baseURL:t,url:r,data:n,headers:s}){return[`curl -X ${e.toUpperCase()}`,`${t}/${r.replace(/^\//,"")}`,Object.entries(s).map(([u,o])=>`-H '${u}: ${He(u)?Re(String(o)):o}'`).join(" "),n&&`-d '${JSON.stringify(n)}'`].join(" ")}const Q=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function P(e){return typeof e=="string"}function L(e){return typeof e=="boolean"}function oe(e){return Array.isArray(e)}function re(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function J(e){return typeof e=="number"}function $(e){return e&&typeof e=="object"}function Ge(e,t=!1){if(typeof e!="object")throw new Error("Argument must be an object");const r={};for(const n of Object.keys(e))e[n]!=null&&(t&&e[n]===""||(r[n]=e[n]));return r}function De(){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 Fe(e){return new Promise(t=>setTimeout(t,e))}function Xe(...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 Ke(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}const ae=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Je(e){return Q(e,"current_page")&&Q(e,"total_pages")&&e.current_page<e.total_pages}function Ye(e,{data:t,params:r}){const n={currentPromise:null},s=typeof r.after<"u";let u=0,o=e({data:t,params:r});const h=c=>{const y=c.current_page+1;return e({data:t,params:k(b({},r),{page:y})})};function g(c){const y=Object.keys(c).find(d=>Array.isArray(c[d])),l=c[y]||c.data;if(!l||typeof l.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(u<l.length){const d=s?l.length-1-u:u,E=l[d];return u+=1,{value:E,done:!1}}return Je(c)?(u=0,o=h(c),o.then(g)):{value:void 0,done:!0}}function m(){return ze(n,(c,y)=>o.then(g).then(c).catch(y))}const p=ue(m),f=Qe(p),a={forEach:p,toArray:f,next:m,return:()=>({}),[ae]:()=>a};return Object.assign(o,a)}function ze(e,t){return e.currentPromise||(e.currentPromise=new Promise(t).then(r=>(e.currentPromise=void 0,r))),e.currentPromise}function ue(e,t){return function(n){return new Promise((s,u)=>{let o=0;function h(g){if(g.done){s();return}const m=g.value;return new Promise(p=>{p(n(m,o))}).then(p=>p===!1?(t==null||t(),h({done:!0})):(o++,e().then(h)))}e().then(h).catch(u)})}}function Qe(e){return function(r){const n=r==null?void 0:r.limit;if(!n)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(n>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((s,u)=>{const o=[];e(h=>{if(o.push(h),o.length>=n)return!1}).then(()=>{s(o)}).catch(u)})}}function We(e,t={}){let r,n,s,u;const o=[];let h;const g=f=>{o.push(f),h&&(h(),h=null)};async function m(f){!n&&!u&&(u=e.request({method:"GET",path:"/config"},f).then(d=>n=d.ws.channel));const a=await e.request({method:"POST",path:"/ws/auth"},f),{token:c}=await Z.default.post(`https://rest.ably.io/keys/${a.keyName}/requestToken`,a).then(d=>d.data);await u;const y=t.sseHost||"https://realtime.ably.io",l=new URL("sse",y);l.searchParams.append("v","1.1"),l.searchParams.append("accessToken",c),l.searchParams.append("channels",n),l.searchParams.append("heartbeats","true"),s&&l.searchParams.append("lastEvent",s),r&&r.close(),r=new ve.default(l.toString()),r.onmessage=d=>{if(d.origin!==y||(s=d.lastEventId,!("data"in d)))return;const E=JSON.parse(d.data);if(E.type==="close")return g({value:null,done:!0});E.data=E.encoding==="json"?JSON.parse(E.data):E.data,g({value:E,done:!1})},r.onerror=d=>{const E="data"in d?JSON.parse(d.data):{};E.code>=40140&&E.code<40150?(r.close(),m(f)):/invalid channel id/i.test(E.message)?(r.close(),g({value:null,done:!0})):console.log("err",d)}}function p(f){m(f);const a=async()=>{o.length||await new Promise(E=>h=E);const d=o.pop();return d.done&&r&&r.close(),d},c=()=>(r.close(),{done:!0,value:void 0}),l={forEach:ue(a,c),next:a,return:c,[ae]:()=>l};return l}return p}const Y={host:P,maxRetryDelay:J,timeout:J,apiKey:P,maxRetries:J,userEmail:P,userExternalId:P,userHmac:P,idempotencyKey:P,telemetry:L,apiSecret:P,appInfo:$,debug:L,features:$};function V(e){var t;if(!$(e))return!1;for(const r of Object.keys(e))if(!((t=Y[r])!=null&&t.call(Y,e[r])))return!1;return!0}const z={archived:L,read:L,seen:L,categories:e=>P(e)||re(e),topics:e=>P(e)||re(e)};function Ze(e){var t;if(!$(e))return!1;for(const r of Object.keys(e))if(!((t=z[r])!=null&&t.call(z,e[r])))return!1;return!0}function Ve(e,t,r={encode:!0}){return e.replace(/{([\s\S]+?)}/g,(n,s)=>r.encode?encodeURIComponent(t[s]||""):t[s]||"")}function et(e){return(e.match(/{\w+}/g)||[]||[]).map(r=>r.replace(/[{}]/g,""))}function tt(e){return!oe(e)||!$(e[0])?{}:V(e[0])?{}:e.shift()}function rt(e){if(!oe(e)||e.length===0)return{};const t=e[e.length-1];return V(t)?b({},e.pop()):{}}function nt({path:e,method:t,args:r}){const n=[...r].filter(a=>a!==void 0),u=et(e).reduce((a,c)=>{const y=n.shift();if(typeof y!="string")throw new Error(`MagicBell: Argument "${c}" must be a string, but got ${typeof y}: ${JSON.stringify(y)} (on API request to \`${t} ${e}\`)`);return a[c]=y,a},{}),o=Ve(e,u,{encode:!1}),h=tt(n),g=rt(n);if(n.filter(a=>a!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(n)}). (on API request to \`${t} ${o}\`)`);let m=t==="GET";return t==="POST"&&Ze(h)&&(m=!0),{path:o,data:m?{}:h,params:m?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 q{constructor(t){i(this,"path");i(this,"entity");i(this,"client");this.client=t}request({method:t,paged:r,path:n},...s){const{path:u,data:o,params:h,options:g}=nt({path:Ke(this.path,n),method:t,args:s}),m=({data:p,params:f})=>{const a=this.entity||this.path;return p=ne(p)?void 0:{[a]:p},f=ne(f)?void 0:f,this.client.request({method:t,path:u,data:p,params:f},g).then(c=>c[a]||c)};return r?Ye(m,{data:o,params:h}):m({data:o,params:h})}assertFeatureFlag(t){if(!this.client.hasFlag(t))throw new Error(`This is a beta feature, please enable it by providing the "${t}" feature flag.`)}}class st extends q{constructor(){super(...arguments);i(this,"path","imports");i(this,"entity","import")}create(r,n){return this.request({method:"POST"},r,n)}get(r,n){return this.request({method:"GET",path:"{import_id}"},r,n)}}class it extends q{constructor(){super(...arguments);i(this,"path","notification_preferences");i(this,"entity","notification_preferences")}get(r){return this.request({method:"GET"},r)}update(r,n){return this.request({method:"PUT"},r,n)}}class ot extends q{constructor(){super(...arguments);i(this,"path","notifications");i(this,"entity","notification")}create(r,n){return this.request({method:"POST"},r,n)}list(r,n){return this.request({method:"GET",paged:!0},r,n)}get(r,n){return this.request({method:"GET",path:"{notification_id}"},r,n)}delete(r,n){return this.request({method:"DELETE",path:"{notification_id}"},r,n)}markAsRead(r,n){return this.request({method:"POST",path:"{notification_id}/read"},r,n)}markAsUnread(r,n){return this.request({method:"POST",path:"{notification_id}/unread"},r,n)}archive(r,n){return this.request({method:"POST",path:"{notification_id}/archive"},r,n)}unarchive(r,n){return this.request({method:"DELETE",path:"{notification_id}/archive"},r,n)}markAllRead(r,n){return this.request({method:"POST",path:"read"},r,n)}markAllSeen(r,n){return this.request({method:"POST",path:"seen"},r,n)}}class at extends q{constructor(){super(...arguments);i(this,"path","push_subscriptions");i(this,"entity","push_subscription")}create(r,n){return this.assertFeatureFlag("push-subscriptions-create"),this.request({method:"POST"},r,n)}delete(r,n){return this.assertFeatureFlag("push-subscriptions-delete"),this.request({method:"DELETE",path:"{device_token}"},r,n)}}class ut extends q{constructor(){super(...arguments);i(this,"path","subscriptions");i(this,"entity","subscription")}list(r){return this.request({method:"GET",paged:!0},r)}create(r,n){return this.request({method:"POST"},r,n)}unsubscribe(r,n,s){return this.request({method:"POST",path:"{topic}/unsubscribe"},r,n,s)}get(r,n){return this.request({method:"GET",path:"{topic}"},r,n)}delete(r,n,s){return this.request({method:"DELETE",path:"{topic}"},r,n,s)}}class ct extends q{constructor(){super(...arguments);i(this,"path","users");i(this,"entity","user")}create(r,n){return this.request({method:"POST"},r,n)}update(r,n,s){return this.request({method:"PUT",path:"{user_id}"},r,n,s)}delete(r,n){return this.request({method:"DELETE",path:"{user_id}"},r,n)}updateByEmail(r,n,s){return this.request({method:"PUT",path:"email:{user_email}"},r,n,s)}deleteByEmail(r,n){return this.request({method:"DELETE",path:"email:{user_email}"},r,n)}updateByExternalId(r,n,s){return this.request({method:"PUT",path:"external_id:{external_id}"},r,n,s)}deleteByExternalId(r,n){return this.request({method:"DELETE",path:"external_id:{external_id}"},r,n)}}typeof XMLHttpRequest!="function"&&(Z.default.defaults.adapter=require("axios/lib/adapters/http"));const lt={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var I,M,A,w,U,B,N,le,R,he,j,de,H,fe,C,me,G,pe;class ce{constructor(t){x(this,N);x(this,R);x(this,j);x(this,H);x(this,C);x(this,G);x(this,I,void 0);x(this,M,void 0);x(this,A,void 0);x(this,w,new Ne);x(this,U,{});x(this,B,[]);i(this,"listen",We(this));i(this,"imports",new st(this));i(this,"notificationPreferences",new it(this));i(this,"notifications",new ot(this));i(this,"pushSubscriptions",new at(this));i(this,"subscriptions",new ut(this));i(this,"users",new ct(this));const r=["apiKey"].filter(n=>!Q(t,n));if(r.length)throw new Error(`You haven't provided all required options, please provide ${Xe(...r)} to Client(options)`);if(!V(t))throw new Error("You have provided invalid options. Please check your client options.");O(this,A,Object.assign({},lt,t)),T(this,w).active=Boolean(T(this,A).debug),O(this,M,we(t.appInfo)),O(this,I,_e(t.appInfo)),O(this,U,t.features||{})}hasFlag(t){return T(this,U)[t]||!1}async request({method:t,path:r,data:n,params:s},u){var m,p;const o=b(b({},T(this,A)),u),h=v(this,N,le).call(this,o,t),g=Math.max(0,o.maxRetries);for(let f=1;f<=g;f++){let a,c;const y=Date.now();if(T(this,w).debug(`${t} ${r}`),await Z.default({method:t,url:r,baseURL:o.host,headers:b(b({},h),K({"X-MAGICBELL-CLIENT-TELEMETRY":v(this,j,de).call(this)})),data:n,params:s,timeout:o.timeout}).then(l=>{a=l}).catch(l=>{const d=Ce({method:t,baseURL:o.host,url:r,data:n,params:s,headers:h});T(this,w).error(`${l.message}: ${d}`),c=l,a=l.response}),v(this,R,he).call(this,a,{startTime:y}),v(this,H,fe).call(this,a,f,g)){const l=Number(a.headers["retry-after"]);await Fe(v(this,C,me).call(this,f,l,o.maxRetryDelay));continue}if(c)throw qe(b({name:c.name,message:c.message,type:c.type,status:a.status,statusText:a.statusText},(p=(m=a==null?void 0:a.data)==null?void 0:m.errors)==null?void 0:p[0]));return a.data}}}I=new WeakMap,M=new WeakMap,A=new WeakMap,w=new WeakMap,U=new WeakMap,B=new WeakMap,N=new WeakSet,le=function(t,r){let n=t.userHmac;return!n&&t.apiSecret&&(t.userExternalId||t.userEmail)&&(n=se(t.apiSecret,t.userExternalId||t.userEmail)),Ge(K({"User-Agent":typeof document<"u"?null:T(this,I),"Idempotency-Key":t.idempotencyKey||v(this,G,pe).call(this,r,t.maxRetries),"Accept-Version":"v2","X-MAGICBELL-API-KEY":t.apiKey,"X-MAGICBELL-API-SECRET":t.apiSecret,"X-MAGICBELL-CLIENT-USER-AGENT":T(this,M),"X-MAGICBELL-USER-EMAIL":t.userEmail,"X-MAGICBELL-USER-EXTERNAL-ID":t.userExternalId,"X-MAGICBELL-USER-HMAC":n}),!0)},R=new WeakSet,he=function(t,{startTime:r}){if(!T(this,A).telemetry||!(t!=null&&t.status))return;const n=K(t.headers);T(this,B).push({id:n["X-Request-Id"],runtime:Number(n["X-Runtime"]),duration:Date.now()-r,status:t.status})},j=new WeakSet,de=function(){const t=T(this,B).pop();return t?JSON.stringify(t):null},H=new WeakSet,fe=function(t,r,n){return r>=n?!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},C=new WeakSet,me=function(t,r=null,n){let u=Math.min(.5*Math.pow(t,2),n);return u*=.75*(1+Math.random()),u=Math.min(Math.max(.5,u),n),Number.isInteger(r)&&r<=60&&(u=Math.max(u,r)),u*1e3},G=new WeakSet,pe=function(t,r){if(!(t!=="POST"||r===0))return`magicbell-retry-${De()}`};exports.Client=ce;exports.createHmac=se;exports.default=ce; | ||
"use strict";var ge=Object.defineProperty,ye=Object.defineProperties;var Ee=Object.getOwnPropertyDescriptors;var ee=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var D=(e,t,r)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t)=>{for(var r in t||(t={}))xe.call(t,r)&&D(e,r,t[r]);if(ee)for(var r of ee(t))Te.call(t,r)&&D(e,r,t[r]);return e},k=(e,t)=>ye(e,Ee(t));var i=(e,t,r)=>(D(e,typeof t!="symbol"?t+"":t,r),r),F=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var T=(e,t,r)=>(F(e,t,"read from private field"),r?r.call(e):t.get(e)),x=(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)},O=(e,t,r,n)=>(F(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var v=(e,t,r)=>(F(e,t,"access private method"),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const be=require("axios"),Pe=require("crypto"),Se=require("eventsource"),W=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Z=W(be),X=W(Pe),ve=W(Se);function se(e,t){if(!e||!t)return"";if(!X.default||!X.default.createHmac)throw new Error("This method is not available in the browser. Please provide a userHmac.");return X.default.createHmac("sha256",e).update(t).digest("base64")}function ie(){var t;const e={binding:"magicbell",binding_version:"1.2.0",publisher:"magicbell"};return typeof process>"u"?e:k(b({},e),{runtime:((t=process==null?void 0:process.release)==null?void 0:t.name)||"node",runtime_version:process.version,platform:process.platform,arch:process.arch})}function Ae(e){return e!=null&&e.name?[e==null?void 0:e.name,e.version&&`/${e.version}`,e.url&&` (${e.url})`].filter(Boolean).join(""):""}function _e(e){const t=ie();return[`${t.binding}/${t.binding_version}`,"runtime"in t&&`${t.runtime}/${t.runtime_version}`,Ae(e)].filter(Boolean).join(" ")}function we(e){return JSON.stringify(k(b({},ie()),{application:e}))}function qe(e){for(const t of["code","type","status"])switch(e[t]){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 S extends Error{constructor(r){super(r.message);i(this,"name");i(this,"message");i(this,"type");i(this,"docs_url");i(this,"code");i(this,"status");i(this,"statusText");i(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 Oe extends S{}class Le extends S{}class $e extends S{}class te extends S{}class Ie extends S{}class Me extends S{}class Ue extends S{}class Be extends S{}function K(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 _={reset:"\x1B[0m",magenta:"\x1B[35m",red:"\x1B[31m"};class Ne{constructor(){i(this,"active",!1)}debug(t){!this.active||console.log(`${_.reset}${_.magenta}magicbell:${_.reset} ${t}`)}error(t){!this.active||console.error(`${_.reset}${_.red}magicbell:${_.reset} ${t}`)}}function Re(e){return`${e.slice(0,4)}\u2026${e.slice(-4)}`}const je=/secret|token|key|password/i;function He(e){return je.test(e)}function Ce({method:e,baseURL:t,url:r,data:n,headers:s}){return[`curl -X ${e.toUpperCase()}`,`${t}/${r.replace(/^\//,"")}`,Object.entries(s).map(([u,o])=>`-H '${u}: ${He(u)?Re(String(o)):o}'`).join(" "),n&&`-d '${JSON.stringify(n)}'`].join(" ")}const Q=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function P(e){return typeof e=="string"}function L(e){return typeof e=="boolean"}function oe(e){return Array.isArray(e)}function re(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function J(e){return typeof e=="number"}function $(e){return e&&typeof e=="object"}function Ge(e,t=!1){if(typeof e!="object")throw new Error("Argument must be an object");const r={};for(const n of Object.keys(e))e[n]!=null&&(t&&e[n]===""||(r[n]=e[n]));return r}function De(){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 Fe(e){return new Promise(t=>setTimeout(t,e))}function Xe(...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 Ke(...e){return["/",...e].join("/").replace(/\/+/g,"/").replace(/\/$/,"")}const ae=typeof Symbol<"u"&&Symbol.asyncIterator?Symbol.asyncIterator:"@@asyncIterator";function Je(e){return Q(e,"current_page")&&Q(e,"total_pages")&&e.current_page<e.total_pages}function Ye(e,{data:t,params:r}){const n={currentPromise:null},s=typeof r.after<"u";let u=0,o=e({data:t,params:r});const h=c=>{const y=c.current_page+1;return e({data:t,params:k(b({},r),{page:y})})};function m(c){const y=Object.keys(c).find(d=>Array.isArray(c[d])),l=c[y]||c.data;if(!l||typeof l.length!="number")throw Error("Unexpected: MagicBell API response does not have a well-formed response.");if(u<l.length){const d=s?l.length-1-u:u,E=l[d];return u+=1,{value:E,done:!1}}return Je(c)?(u=0,o=h(c),o.then(m)):{value:void 0,done:!0}}function p(){return ze(n,(c,y)=>o.then(m).then(c).catch(y))}const g=ue(p),f=Qe(g),a={forEach:g,toArray:f,next:p,return:()=>({}),[ae]:()=>a};return Object.assign(o,a)}function ze(e,t){return e.currentPromise||(e.currentPromise=new Promise(t).then(r=>(e.currentPromise=void 0,r))),e.currentPromise}function ue(e,t){return function(n){return new Promise((s,u)=>{let o=0;function h(m){if(m.done){s();return}const p=m.value;return new Promise(g=>{g(n(p,o))}).then(g=>g===!1?(t==null||t(),h({done:!0})):(o++,e().then(h)))}e().then(h).catch(u)})}}function Qe(e){return function(r){const n=r==null?void 0:r.limit;if(!n)throw Error("You must pass a `limit` option to toArray, e.g., `toArray({ limit: 1000 });`.");if(n>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((s,u)=>{const o=[];e(h=>{if(o.push(h),o.length>=n)return!1}).then(()=>{s(o)}).catch(u)})}}function We(e,t={}){let r,n,s,u;const o=[];let h;const m=f=>{o.push(f),h&&(h(),h=null)};async function p(f){!n&&!u&&(u=e.request({method:"GET",path:"/config"},f).then(d=>n=d.ws.channel));const a=await e.request({method:"POST",path:"/ws/auth"},f),{token:c}=await Z.default.post(`https://rest.ably.io/keys/${a.keyName}/requestToken`,a).then(d=>d.data);await u;const y=t.sseHost||"https://realtime.ably.io",l=new URL("sse",y);l.searchParams.append("v","1.1"),l.searchParams.append("accessToken",c),l.searchParams.append("channels",n),l.searchParams.append("heartbeats","true"),s&&l.searchParams.append("lastEvent",s),r&&r.close(),r=new ve.default(l.toString()),r.onmessage=d=>{if(d.origin!==y||(s=d.lastEventId,!("data"in d)))return;const E=JSON.parse(d.data);if(E.type==="close")return m({value:null,done:!0});E.data=E.encoding==="json"?JSON.parse(E.data):E.data,m({value:E,done:!1})},r.onerror=d=>{const E="data"in d?JSON.parse(d.data):{};E.code>=40140&&E.code<40150?(r.close(),p(f)):/invalid channel id/i.test(E.message)?(r.close(),m({value:null,done:!0})):console.log("err",d)}}function g(f){p(f);const a=async()=>{o.length||await new Promise(E=>h=E);const d=o.pop();return d.done&&r&&r.close(),d},c=()=>(r.close(),m({done:!0,value:void 0}),{done:!0,value:void 0}),l={forEach:ue(a,c),close:c,next:a,return:c,[ae]:()=>l};return l}return g}const Y={host:P,maxRetryDelay:J,timeout:J,apiKey:P,maxRetries:J,userEmail:P,userExternalId:P,userHmac:P,idempotencyKey:P,telemetry:L,apiSecret:P,appInfo:$,debug:L,features:$};function V(e){var t;if(!$(e))return!1;for(const r of Object.keys(e))if(!((t=Y[r])!=null&&t.call(Y,e[r])))return!1;return!0}const z={archived:L,read:L,seen:L,categories:e=>P(e)||re(e),topics:e=>P(e)||re(e)};function Ze(e){var t;if(!$(e))return!1;for(const r of Object.keys(e))if(!((t=z[r])!=null&&t.call(z,e[r])))return!1;return!0}function Ve(e,t,r={encode:!0}){return e.replace(/{([\s\S]+?)}/g,(n,s)=>r.encode?encodeURIComponent(t[s]||""):t[s]||"")}function et(e){return(e.match(/{\w+}/g)||[]||[]).map(r=>r.replace(/[{}]/g,""))}function tt(e){return!oe(e)||!$(e[0])?{}:V(e[0])?{}:e.shift()}function rt(e){if(!oe(e)||e.length===0)return{};const t=e[e.length-1];return V(t)?b({},e.pop()):{}}function nt({path:e,method:t,args:r}){const n=[...r].filter(a=>a!==void 0),u=et(e).reduce((a,c)=>{const y=n.shift();if(typeof y!="string")throw new Error(`MagicBell: Argument "${c}" must be a string, but got ${typeof y}: ${JSON.stringify(y)} (on API request to \`${t} ${e}\`)`);return a[c]=y,a},{}),o=Ve(e,u,{encode:!1}),h=tt(n),m=rt(n);if(n.filter(a=>a!=null).length)throw new Error(`MagicBell: Unknown arguments (${JSON.stringify(n)}). (on API request to \`${t} ${o}\`)`);let p=t==="GET";return t==="POST"&&Ze(h)&&(p=!0),{path:o,data:p?{}:h,params:p?h:{},options:m}}function ne(e){return e?Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1:!0}class q{constructor(t){i(this,"path");i(this,"entity");i(this,"client");this.client=t}request({method:t,paged:r,path:n},...s){const{path:u,data:o,params:h,options:m}=nt({path:Ke(this.path,n),method:t,args:s}),p=({data:g,params:f})=>{const a=this.entity||this.path;return g=ne(g)?void 0:{[a]:g},f=ne(f)?void 0:f,this.client.request({method:t,path:u,data:g,params:f},m).then(c=>c[a]||c)};return r?Ye(p,{data:o,params:h}):p({data:o,params:h})}assertFeatureFlag(t){if(!this.client.hasFlag(t))throw new Error(`This is a beta feature, please enable it by providing the "${t}" feature flag.`)}}class st extends q{constructor(){super(...arguments);i(this,"path","imports");i(this,"entity","import")}create(r,n){return this.request({method:"POST"},r,n)}get(r,n){return this.request({method:"GET",path:"{import_id}"},r,n)}}class it extends q{constructor(){super(...arguments);i(this,"path","notification_preferences");i(this,"entity","notification_preferences")}get(r){return this.request({method:"GET"},r)}update(r,n){return this.request({method:"PUT"},r,n)}}class ot extends q{constructor(){super(...arguments);i(this,"path","notifications");i(this,"entity","notification")}create(r,n){return this.request({method:"POST"},r,n)}list(r,n){return this.request({method:"GET",paged:!0},r,n)}get(r,n){return this.request({method:"GET",path:"{notification_id}"},r,n)}delete(r,n){return this.request({method:"DELETE",path:"{notification_id}"},r,n)}markAsRead(r,n){return this.request({method:"POST",path:"{notification_id}/read"},r,n)}markAsUnread(r,n){return this.request({method:"POST",path:"{notification_id}/unread"},r,n)}archive(r,n){return this.request({method:"POST",path:"{notification_id}/archive"},r,n)}unarchive(r,n){return this.request({method:"DELETE",path:"{notification_id}/archive"},r,n)}markAllRead(r,n){return this.request({method:"POST",path:"read"},r,n)}markAllSeen(r,n){return this.request({method:"POST",path:"seen"},r,n)}}class at extends q{constructor(){super(...arguments);i(this,"path","push_subscriptions");i(this,"entity","push_subscription")}create(r,n){return this.assertFeatureFlag("push-subscriptions-create"),this.request({method:"POST"},r,n)}delete(r,n){return this.assertFeatureFlag("push-subscriptions-delete"),this.request({method:"DELETE",path:"{device_token}"},r,n)}}class ut extends q{constructor(){super(...arguments);i(this,"path","subscriptions");i(this,"entity","subscription")}list(r){return this.request({method:"GET",paged:!0},r)}create(r,n){return this.request({method:"POST"},r,n)}unsubscribe(r,n,s){return this.request({method:"POST",path:"{topic}/unsubscribe"},r,n,s)}get(r,n){return this.request({method:"GET",path:"{topic}"},r,n)}delete(r,n,s){return this.request({method:"DELETE",path:"{topic}"},r,n,s)}}class ct extends q{constructor(){super(...arguments);i(this,"path","users");i(this,"entity","user")}create(r,n){return this.request({method:"POST"},r,n)}update(r,n,s){return this.request({method:"PUT",path:"{user_id}"},r,n,s)}delete(r,n){return this.request({method:"DELETE",path:"{user_id}"},r,n)}updateByEmail(r,n,s){return this.request({method:"PUT",path:"email:{user_email}"},r,n,s)}deleteByEmail(r,n){return this.request({method:"DELETE",path:"email:{user_email}"},r,n)}updateByExternalId(r,n,s){return this.request({method:"PUT",path:"external_id:{external_id}"},r,n,s)}deleteByExternalId(r,n){return this.request({method:"DELETE",path:"external_id:{external_id}"},r,n)}}typeof XMLHttpRequest!="function"&&(Z.default.defaults.adapter=require("axios/lib/adapters/http"));const lt={host:"https://api.magicbell.com",timeout:3e4,maxRetries:3,maxRetryDelay:60,telemetry:!0};var I,M,A,w,U,B,N,le,R,he,j,de,H,fe,C,me,G,pe;class ce{constructor(t){x(this,N);x(this,R);x(this,j);x(this,H);x(this,C);x(this,G);x(this,I,void 0);x(this,M,void 0);x(this,A,void 0);x(this,w,new Ne);x(this,U,{});x(this,B,[]);i(this,"listen",We(this));i(this,"imports",new st(this));i(this,"notificationPreferences",new it(this));i(this,"notifications",new ot(this));i(this,"pushSubscriptions",new at(this));i(this,"subscriptions",new ut(this));i(this,"users",new ct(this));const r=["apiKey"].filter(n=>!Q(t,n));if(r.length)throw new Error(`You haven't provided all required options, please provide ${Xe(...r)} to Client(options)`);if(!V(t))throw new Error("You have provided invalid options. Please check your client options.");O(this,A,Object.assign({},lt,t)),T(this,w).active=Boolean(T(this,A).debug),O(this,M,we(t.appInfo)),O(this,I,_e(t.appInfo)),O(this,U,t.features||{})}hasFlag(t){return T(this,U)[t]||!1}async request({method:t,path:r,data:n,params:s},u){var p,g;const o=b(b({},T(this,A)),u),h=v(this,N,le).call(this,o,t),m=Math.max(0,o.maxRetries);for(let f=1;f<=m;f++){let a,c;const y=Date.now();if(T(this,w).debug(`${t} ${r}`),await Z.default({method:t,url:r,baseURL:o.host,headers:b(b({},h),K({"X-MAGICBELL-CLIENT-TELEMETRY":v(this,j,de).call(this)})),data:n,params:s,timeout:o.timeout}).then(l=>{a=l}).catch(l=>{const d=Ce({method:t,baseURL:o.host,url:r,data:n,params:s,headers:h});T(this,w).error(`${l.message}: ${d}`),c=l,a=l.response}),v(this,R,he).call(this,a,{startTime:y}),v(this,H,fe).call(this,a,f,m)){const l=Number(a.headers["retry-after"]);await Fe(v(this,C,me).call(this,f,l,o.maxRetryDelay));continue}if(c)throw qe(b({name:c.name,message:c.message,type:c.type,status:a.status,statusText:a.statusText},(g=(p=a==null?void 0:a.data)==null?void 0:p.errors)==null?void 0:g[0]));return a.data}}}I=new WeakMap,M=new WeakMap,A=new WeakMap,w=new WeakMap,U=new WeakMap,B=new WeakMap,N=new WeakSet,le=function(t,r){let n=t.userHmac;return!n&&t.apiSecret&&(t.userExternalId||t.userEmail)&&(n=se(t.apiSecret,t.userExternalId||t.userEmail)),Ge(K({"User-Agent":typeof document<"u"?null:T(this,I),"Idempotency-Key":t.idempotencyKey||v(this,G,pe).call(this,r,t.maxRetries),"Accept-Version":"v2","X-MAGICBELL-API-KEY":t.apiKey,"X-MAGICBELL-API-SECRET":t.apiSecret,"X-MAGICBELL-CLIENT-USER-AGENT":T(this,M),"X-MAGICBELL-USER-EMAIL":t.userEmail,"X-MAGICBELL-USER-EXTERNAL-ID":t.userExternalId,"X-MAGICBELL-USER-HMAC":n}),!0)},R=new WeakSet,he=function(t,{startTime:r}){if(!T(this,A).telemetry||!(t!=null&&t.status))return;const n=K(t.headers);T(this,B).push({id:n["X-Request-Id"],runtime:Number(n["X-Runtime"]),duration:Date.now()-r,status:t.status})},j=new WeakSet,de=function(){const t=T(this,B).pop();return t?JSON.stringify(t):null},H=new WeakSet,fe=function(t,r,n){return r>=n?!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},C=new WeakSet,me=function(t,r=null,n){let u=Math.min(.5*Math.pow(t,2),n);return u*=.75*(1+Math.random()),u=Math.min(Math.max(.5,u),n),Number.isInteger(r)&&r<=60&&(u=Math.max(u,r)),u*1e3},G=new WeakSet,pe=function(t,r){if(!(t!=="POST"||r===0))return`magicbell-retry-${De()}`};exports.Client=ce;exports.createHmac=se;exports.default=ce; | ||
//# sourceMappingURL=magicbell.cjs.min.js.map |
/** | ||
* @license magicbell v1.1.0 | ||
* @license magicbell v1.2.0 | ||
* | ||
@@ -71,3 +71,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "1.1.0", | ||
binding_version: "1.2.0", | ||
publisher: "magicbell" | ||
@@ -449,2 +449,3 @@ }; | ||
eventSource.close(); | ||
pushMessage({ done: true, value: void 0 }); | ||
return { done: true, value: void 0 }; | ||
@@ -455,2 +456,3 @@ }; | ||
forEach, | ||
close: dispose, | ||
next: asyncIteratorNext, | ||
@@ -457,0 +459,0 @@ return: dispose, |
/** | ||
* @license magicbell v1.1.0 | ||
* @license magicbell v1.2.0 | ||
* | ||
@@ -46,3 +46,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
binding: "magicbell", | ||
binding_version: "1.1.0", | ||
binding_version: "1.2.0", | ||
publisher: "magicbell" | ||
@@ -225,3 +225,3 @@ }; | ||
}; | ||
function g(c) { | ||
function m(c) { | ||
const y = Object.keys(c).find((d) => Array.isArray(c[d])), l = c[y] || c.data; | ||
@@ -234,11 +234,11 @@ if (!l || typeof l.length != "number") | ||
} | ||
return Ce(c) ? (u = 0, o = h(c), o.then(g)) : { value: void 0, done: !0 }; | ||
return Ce(c) ? (u = 0, o = h(c), o.then(m)) : { value: void 0, done: !0 }; | ||
} | ||
function m() { | ||
return De(n, (c, y) => o.then(g).then(c).catch(y)); | ||
function p() { | ||
return De(n, (c, y) => o.then(m).then(c).catch(y)); | ||
} | ||
const p = oe(m), f = Xe(p), a = { | ||
forEach: p, | ||
const g = oe(p), f = Xe(g), a = { | ||
forEach: g, | ||
toArray: f, | ||
next: m, | ||
next: p, | ||
return: () => ({}), | ||
@@ -256,11 +256,11 @@ [ie]: () => a | ||
let o = 0; | ||
function h(g) { | ||
if (g.done) { | ||
function h(m) { | ||
if (m.done) { | ||
s(); | ||
return; | ||
} | ||
const m = g.value; | ||
return new Promise((p) => { | ||
p(n(m, o)); | ||
}).then((p) => p === !1 ? (t == null || t(), h({ done: !0 })) : (o++, e().then(h))); | ||
const p = m.value; | ||
return new Promise((g) => { | ||
g(n(p, o)); | ||
}).then((g) => g === !1 ? (t == null || t(), h({ done: !0 })) : (o++, e().then(h))); | ||
} | ||
@@ -295,6 +295,6 @@ e().then(h).catch(u); | ||
let h; | ||
const g = (f) => { | ||
const m = (f) => { | ||
o.push(f), h && (h(), h = null); | ||
}; | ||
async function m(f) { | ||
async function p(f) { | ||
!n && !u && (u = e.request({ method: "GET", path: "/config" }, f).then((d) => n = d.ws.channel)); | ||
@@ -309,11 +309,11 @@ const a = await e.request({ method: "POST", path: "/ws/auth" }, f), { token: c } = await W.post(`https://rest.ably.io/keys/${a.keyName}/requestToken`, a).then((d) => d.data); | ||
if (E.type === "close") | ||
return g({ value: null, done: !0 }); | ||
E.data = E.encoding === "json" ? JSON.parse(E.data) : E.data, g({ value: E, done: !1 }); | ||
return m({ value: null, done: !0 }); | ||
E.data = E.encoding === "json" ? JSON.parse(E.data) : E.data, m({ value: E, done: !1 }); | ||
}, r.onerror = (d) => { | ||
const E = "data" in d ? JSON.parse(d.data) : {}; | ||
E.code >= 40140 && E.code < 40150 ? (r.close(), m(f)) : /invalid channel id/i.test(E.message) ? (r.close(), g({ value: null, done: !0 })) : console.log("err", d); | ||
E.code >= 40140 && E.code < 40150 ? (r.close(), p(f)) : /invalid channel id/i.test(E.message) ? (r.close(), m({ value: null, done: !0 })) : console.log("err", d); | ||
}; | ||
} | ||
function p(f) { | ||
m(f); | ||
function g(f) { | ||
p(f); | ||
const a = async () => { | ||
@@ -323,4 +323,5 @@ o.length || await new Promise((E) => h = E); | ||
return d.done && r && r.close(), d; | ||
}, c = () => (r.close(), { done: !0, value: void 0 }), l = { | ||
}, c = () => (r.close(), m({ done: !0, value: void 0 }), { done: !0, value: void 0 }), l = { | ||
forEach: oe(a, c), | ||
close: c, | ||
next: a, | ||
@@ -332,3 +333,3 @@ return: c, | ||
} | ||
return p; | ||
return g; | ||
} | ||
@@ -408,3 +409,3 @@ const Y = { | ||
return a[c] = y, a; | ||
}, {}), o = Ye(e, u, { encode: !1 }), h = Qe(n), g = We(n); | ||
}, {}), o = Ye(e, u, { encode: !1 }), h = Qe(n), m = We(n); | ||
if (n.filter((a) => a != null).length) | ||
@@ -414,4 +415,4 @@ throw new Error( | ||
); | ||
let m = t === "GET"; | ||
return t === "POST" && Je(h) && (m = !0), { path: o, data: m ? {} : h, params: m ? h : {}, options: g }; | ||
let p = t === "GET"; | ||
return t === "POST" && Je(h) && (p = !0), { path: o, data: p ? {} : h, params: p ? h : {}, options: m }; | ||
} | ||
@@ -429,14 +430,14 @@ function re(e) { | ||
request({ method: t, paged: r, path: n }, ...s) { | ||
const { path: u, data: o, params: h, options: g } = Ze({ | ||
const { path: u, data: o, params: h, options: m } = Ze({ | ||
path: Ge(this.path, n), | ||
method: t, | ||
args: s | ||
}), m = ({ data: p, params: f }) => { | ||
}), p = ({ data: g, params: f }) => { | ||
const a = this.entity || this.path; | ||
return p = re(p) ? void 0 : { [a]: p }, f = re(f) ? void 0 : f, this.client.request({ method: t, path: u, data: p, params: f }, g).then((c) => c[a] || c); | ||
return g = re(g) ? void 0 : { [a]: g }, f = re(f) ? void 0 : f, this.client.request({ method: t, path: u, data: g, params: f }, m).then((c) => c[a] || c); | ||
}; | ||
return r ? Fe(m, { | ||
return r ? Fe(p, { | ||
data: o, | ||
params: h | ||
}) : m({ data: o, params: h }); | ||
}) : p({ data: o, params: h }); | ||
} | ||
@@ -809,5 +810,5 @@ assertFeatureFlag(t) { | ||
async request({ method: t, path: r, data: n, params: s }, u) { | ||
var m, p; | ||
const o = b(b({}, T(this, v)), u), h = S(this, N, ae).call(this, o, t), g = Math.max(0, o.maxRetries); | ||
for (let f = 1; f <= g; f++) { | ||
var p, g; | ||
const o = b(b({}, T(this, v)), u), h = S(this, N, ae).call(this, o, t), m = Math.max(0, o.maxRetries); | ||
for (let f = 1; f <= m; f++) { | ||
let a, c; | ||
@@ -830,3 +831,3 @@ const y = Date.now(); | ||
T(this, q).error(`${l.message}: ${d}`), c = l, a = l.response; | ||
}), S(this, R, ue).call(this, a, { startTime: y }), S(this, H, le).call(this, a, f, g)) { | ||
}), S(this, R, ue).call(this, a, { startTime: y }), S(this, H, le).call(this, a, f, m)) { | ||
const l = Number(a.headers["retry-after"]); | ||
@@ -843,3 +844,3 @@ await je(S(this, G, he).call(this, f, l, o.maxRetryDelay)); | ||
statusText: a.statusText | ||
}, (p = (m = a == null ? void 0 : a.data) == null ? void 0 : m.errors) == null ? void 0 : p[0])); | ||
}, (g = (p = a == null ? void 0 : a.data) == null ? void 0 : p.errors) == null ? void 0 : g[0])); | ||
return a.data; | ||
@@ -846,0 +847,0 @@ } |
{ | ||
"name": "magicbell", | ||
"version": "1.1.0", | ||
"version": "1.2.0", | ||
"description": "MagicBell API wrapper", | ||
@@ -60,12 +60,10 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com)", | ||
"portfinder": "^1.0.32", | ||
"recast": "^0.21.5" | ||
"recast": "^0.21.5", | ||
"tsx": "^3.9.0" | ||
}, | ||
"dependencies": { | ||
"axios": "^0.27.2", | ||
"axios-retry": "^3.3.1", | ||
"eventsource": "^2.0.2", | ||
"json-schema-to-ts": "2.6.0", | ||
"qs": "^6.11.0", | ||
"tsx": "^3.9.0" | ||
"json-schema-to-ts": "2.6.0" | ||
} | ||
} |
@@ -834,2 +834,17 @@ # MagicBell Node.js Library | ||
**close** - stop listening. This will close the connection and stop the auto-reconnect. | ||
```js | ||
const listener = magicbell.listen(); | ||
listener.forEach((notification) => { | ||
console.log(notification.data.id); | ||
}); | ||
// stop listening after 5 seconds | ||
setTimeout(() => { | ||
listener.close(); | ||
}, 5_000); | ||
``` | ||
### Realtime events | ||
@@ -836,0 +851,0 @@ |
@@ -11,2 +11,4 @@ import { beforeEach } from 'vitest'; | ||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | ||
beforeEach(async () => { | ||
@@ -77,1 +79,17 @@ server.intercept('all', (req) => { | ||
}); | ||
test('can close listener', async () => { | ||
const events = []; | ||
const iterator = listen(); | ||
setTimeout(() => { | ||
iterator.close(); | ||
}, 100); | ||
for await (const event of iterator) { | ||
events.push(event); | ||
await sleep(1000); | ||
} | ||
expect(events).toHaveLength(1); | ||
}); |
@@ -148,2 +148,4 @@ import axios from 'axios'; | ||
eventSource.close(); | ||
// push to resolve async iterators, return for sync ones | ||
pushMessage({ done: true, value: undefined }); | ||
return { done: true, value: undefined }; | ||
@@ -155,2 +157,3 @@ }; | ||
forEach, | ||
close: dispose, | ||
@@ -157,0 +160,0 @@ next: asyncIteratorNext, |
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
678726
3
9161
889
8
- Removedaxios-retry@^3.3.1
- Removedqs@^6.11.0
- Removedtsx@^3.9.0
- Removed@babel/runtime@7.26.7(transitive)
- Removed@esbuild/android-arm@0.18.20(transitive)
- Removed@esbuild/android-arm64@0.18.20(transitive)
- Removed@esbuild/android-x64@0.18.20(transitive)
- Removed@esbuild/darwin-arm64@0.18.20(transitive)
- Removed@esbuild/darwin-x64@0.18.20(transitive)
- Removed@esbuild/freebsd-arm64@0.18.20(transitive)
- Removed@esbuild/freebsd-x64@0.18.20(transitive)
- Removed@esbuild/linux-arm@0.18.20(transitive)
- Removed@esbuild/linux-arm64@0.18.20(transitive)
- Removed@esbuild/linux-ia32@0.18.20(transitive)
- Removed@esbuild/linux-loong64@0.18.20(transitive)
- Removed@esbuild/linux-mips64el@0.18.20(transitive)
- Removed@esbuild/linux-ppc64@0.18.20(transitive)
- Removed@esbuild/linux-riscv64@0.18.20(transitive)
- Removed@esbuild/linux-s390x@0.18.20(transitive)
- Removed@esbuild/linux-x64@0.18.20(transitive)
- Removed@esbuild/netbsd-x64@0.18.20(transitive)
- Removed@esbuild/openbsd-x64@0.18.20(transitive)
- Removed@esbuild/sunos-x64@0.18.20(transitive)
- Removed@esbuild/win32-arm64@0.18.20(transitive)
- Removed@esbuild/win32-ia32@0.18.20(transitive)
- Removed@esbuild/win32-x64@0.18.20(transitive)
- Removedaxios-retry@3.9.1(transitive)
- Removedbuffer-from@1.1.2(transitive)
- Removedcall-bind-apply-helpers@1.0.1(transitive)
- Removedcall-bound@1.0.3(transitive)
- Removeddunder-proto@1.0.1(transitive)
- Removedes-define-property@1.0.1(transitive)
- Removedes-errors@1.3.0(transitive)
- Removedes-object-atoms@1.1.1(transitive)
- Removedesbuild@0.18.20(transitive)
- Removedfsevents@2.3.3(transitive)
- Removedfunction-bind@1.1.2(transitive)
- Removedget-intrinsic@1.2.7(transitive)
- Removedget-proto@1.0.1(transitive)
- Removedget-tsconfig@4.10.0(transitive)
- Removedgopd@1.2.0(transitive)
- Removedhas-symbols@1.1.0(transitive)
- Removedhasown@2.0.2(transitive)
- Removedis-retry-allowed@2.2.0(transitive)
- Removedmath-intrinsics@1.1.0(transitive)
- Removedobject-inspect@1.13.3(transitive)
- Removedqs@6.14.0(transitive)
- Removedregenerator-runtime@0.14.1(transitive)
- Removedresolve-pkg-maps@1.0.0(transitive)
- Removedside-channel@1.1.0(transitive)
- Removedside-channel-list@1.0.0(transitive)
- Removedside-channel-map@1.0.1(transitive)
- Removedside-channel-weakmap@1.0.2(transitive)
- Removedsource-map@0.6.1(transitive)
- Removedsource-map-support@0.5.21(transitive)
- Removedtsx@3.14.0(transitive)