Socket
Socket
Sign inDemoInstall

@roomservice/browser

Package Overview
Dependencies
Maintainers
2
Versions
126
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@roomservice/browser - npm Package Compare versions

Comparing version 2.1.5-0 to 2.1.5-1

dist/errs.d.ts

178

dist/browser.cjs.development.js

@@ -528,18 +528,27 @@ 'use strict';

var errNoInfiniteLoop = function errNoInfiniteLoop() {
return new Error('Infinite loop detected, see more: See more: https://err.sh/getroomservice/browser/infinite-loop');
};
var InnerListClient = /*#__PURE__*/function () {
function InnerListClient(checkpoint, roomID, docID, listID, ws, actor) {
// Map indexes to item ids
function InnerListClient(props) {
// If true, this client will throw an error if it's trying to
// mutate itself to prevent an infinite loop.
this.throwsOnMutate = false; // Map indexes to item ids
this.itemIDs = [];
this.roomID = roomID;
this.docID = docID;
this.id = listID;
this.ws = ws;
this.rt = new ReverseTree(actor);
!checkpoint.lists[listID] ? invariant(false, "Unknown listid '" + listID + "' in checkpoint.") : void 0;
this.rt["import"](checkpoint, listID);
var list = checkpoint.lists[listID];
this.roomID = props.roomID;
this.docID = props.docID;
this.id = props.listID;
this.ws = props.ws;
this.rt = new ReverseTree(props.actor);
this.bus = props.bus;
this.actor = props.actor;
!props.checkpoint.lists[props.listID] ? invariant(false, "Unknown listid '" + props.listID + "' in checkpoint.") : void 0;
this.rt["import"](props.checkpoint, props.listID);
var list = props.checkpoint.lists[props.listID];
var ids = list.ids || [];
for (var i = 0; i < ids.length; i++) {
var val = checkpoint.lists[listID].values[i];
var val = props.checkpoint.lists[props.listID].values[i];

@@ -550,3 +559,3 @@ if (typeof val === 'object' && val['t'] === '') {

this.itemIDs.push(unescapeID(checkpoint, ids[i]));
this.itemIDs.push(unescapeID(props.checkpoint, ids[i]));
}

@@ -558,2 +567,6 @@ }

_proto.sendCmd = function sendCmd(cmd) {
if (this.throwsOnMutate) {
throw errNoInfiniteLoop();
}
this.ws.send('doc:cmd', {

@@ -563,2 +576,8 @@ room: this.roomID,

});
this.throwsOnMutate = true;
this.bus.publish({
args: cmd,
from: this.actor
});
this.throwsOnMutate = false;
};

@@ -726,11 +745,16 @@

var InnerMapClient = /*#__PURE__*/function () {
function InnerMapClient(checkpoint, roomID, docID, mapID, ws) {
this.roomID = roomID;
this.docID = docID;
this.id = mapID;
this.ws = ws;
this.store = {}; // import
function InnerMapClient(props) {
// If true, this client will throw an error if it's trying to
// mutate itself to prevent an infinite loop.
this.throwsOnMutate = false;
this.roomID = props.roomID;
this.docID = props.docID;
this.id = props.mapID;
this.ws = props.ws;
this.store = {};
this.bus = props.bus;
this.actor = props.actor; // import
for (var k in checkpoint) {
var val = checkpoint[k];
for (var k in props.checkpoint) {
var val = props.checkpoint[k];

@@ -746,2 +770,6 @@ if (typeof val === 'string') {

_proto.sendCmd = function sendCmd(cmd) {
if (this.throwsOnMutate) {
throw errNoInfiniteLoop();
}
this.ws.send('doc:cmd', {

@@ -751,2 +779,8 @@ room: this.roomID,

});
this.throwsOnMutate = true;
this.bus.publish({
from: this.actor,
args: cmd
});
this.throwsOnMutate = false;
};

@@ -876,9 +910,9 @@

var InnerPresenceClient = /*#__PURE__*/function () {
function InnerPresenceClient(roomID, ws, actor, token) {
function InnerPresenceClient(props) {
var _this = this;
this.roomID = roomID;
this.ws = ws;
this.actor = actor;
this.token = token;
this.roomID = props.roomID;
this.ws = props.ws;
this.actor = props.actor;
this.token = props.token;
this.cache = {};

@@ -1052,2 +1086,31 @@

// 🚌
// Local pubsub, so that if you call .set in one place
// it will trigger a .subscribe elsewhere, without
// needing to go through the websockets
var LocalBus = /*#__PURE__*/function () {
function LocalBus() {
this.subs = new Set();
}
var _proto = LocalBus.prototype;
_proto.subscribe = function subscribe(fn) {
this.subs.add(fn);
return fn;
};
_proto.unsubscribe = function unsubscribe(fn) {
this.subs["delete"](fn);
};
_proto.publish = function publish(msg) {
this.subs.forEach(function (fn) {
fn(msg);
});
};
return LocalBus;
}();
var createRoom = function createRoom(conn, docsURL, authStrategy, room, document) {

@@ -1119,3 +1182,3 @@ try {

} else {
console.warn("Unhandled Room Service doc:fwd command: " + cmd + ". Consider updating the Room Service client.");
console.warn('Unhandled Room Service doc:fwd command: ' + cmd + '. Consider updating the Room Service client.');
}

@@ -1149,4 +1212,3 @@ });

if (!this.mapClients[objID]) {
var m = new InnerMapClient(this.checkpoint.maps[objID] || {}, this.roomID, this.docID, objID, this.ws);
this.mapClients[objID] = m;
this.createMapLocally(objID);
}

@@ -1165,4 +1227,3 @@

if (!this.listClients[objID]) {
var l = new InnerListClient(this.checkpoint, this.roomID, this.docID, objID, this.ws, this.actor);
this.listClients[objID] = l;
this.createListLocally(objID);
}

@@ -1278,2 +1339,22 @@

_proto.createListLocally = function createListLocally(name) {
var _this7 = this;
var bus = new LocalBus();
bus.subscribe(function (body) {
_this7.dispatchListCmd(name, body);
});
var l = new InnerListClient({
checkpoint: this.checkpoint,
roomID: this.roomID,
docID: this.docID,
listID: name,
ws: this.ws,
actor: this.actor,
bus: bus
});
this.listClients[name] = l;
return l;
};
_proto.list = function list(name) {

@@ -1298,7 +1379,25 @@ if (this.listClients[name]) {

var l = new InnerListClient(this.checkpoint, this.roomID, this.docID, name, this.ws, this.actor);
this.listClients[name] = l;
return l;
return this.createListLocally(name);
};
_proto.createMapLocally = function createMapLocally(name) {
var _this8 = this;
var bus = new LocalBus();
bus.subscribe(function (body) {
_this8.dispatchMapCmd(name, body);
});
var m = new InnerMapClient({
checkpoint: this.checkpoint.maps[name] || {},
roomID: this.roomID,
docID: this.docID,
mapID: name,
ws: this.ws,
bus: bus,
actor: this.actor
});
this.mapClients[name] = m;
return m;
};
_proto.map = function map(name) {

@@ -1317,5 +1416,3 @@ if (this.mapClients[name]) {

var m = new InnerMapClient(this.checkpoint.maps[name] || {}, this.roomID, this.docID, name, this.ws);
this.mapClients[name] = m;
return m;
return this.createMapLocally(name);
};

@@ -1328,3 +1425,8 @@

var p = new InnerPresenceClient(this.roomID, this.ws, this.actor, this.token);
var p = new InnerPresenceClient({
roomID: this.roomID,
ws: this.ws,
actor: this.actor,
token: this.token
});

@@ -1344,3 +1446,3 @@ try {

return this.subscribePresence(obj, onChangeFnOrString, onChangeFn);
} // create new closure so fns can be subscribed/unsubscribed multiple times
} // create new closure so fns can be subscribed/unsubscribed multiple times

@@ -1347,0 +1449,0 @@

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=(e=require("tiny-invariant"))&&"object"==typeof e&&"default"in e?e.default:e;function r(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function n(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function s(e,t){var r;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return i(e,void 0);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,void 0):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=e[Symbol.iterator]()).next.bind(r)}var o=function(){function e(e){var t=this;this.callbacks={},this.lastTime=0,this.msgsThisMilisecond=0,this.conn=e,this.conn.onmessage=function(e){var r=JSON.parse(e.data);t.dispatch(r.type,r.body)}}var t=e.prototype;return t.timestamp=function(){var e=Date.now();return e===this.lastTime?this.msgsThisMilisecond++:(this.lastTime=e,this.msgsThisMilisecond=0),e+":"+this.msgsThisMilisecond},t.send=function(e,t){var r=this,n=this.timestamp();this.conn.readyState!==this.conn.CONNECTING?this.conn.send(JSON.stringify({type:e,ts:n,ver:0,body:t})):setTimeout((function(){r.send(e,t)}),100+100*Math.random())},t.bind=function(e,t){return this.callbacks[e]=this.callbacks[e]||[],this.callbacks[e].push(t),t},t.unbind=function(e,t){this.callbacks[e]=this.callbacks[e].filter((function(e){return e!==t}))},t.dispatch=function(e,t){var r=this.callbacks[e];if(r)for(var n=0;n<r.length;n++)r[n](t)},e}();function c(e,t){if("root"===t)return"root";var r=t.split(":");return r[0]+":"+e.actors[parseInt(r[1])]}var a=function(){function e(e){this.count=0,this.actor=e,this.nodes={},this.log=[]}var r=e.prototype;return r.import=function(e,r){e||t(!1);for(var n=e.lists[r],i=n.afters||[],s=n.ids||[],o=n.values||[],a=0;a<i.length;a++){var h={after:c(e,i[a]),id:c(e,s[a]),value:o[a]};this.nodes[h.id]=h,this.log.push(h)}this.count=this.log.length},r.get=function(e){if(this.nodes[e])return this.nodes[e].value},r.insert=function(e,r,n){this.log||t(!1);var i=n;i||(i=this.count+":"+this.actor),this.count++;var s={after:e,value:r,id:i};return this.nodes[i]=s,this.log.push(s),i},r.put=function(e,t){this.nodes[e]&&(this.nodes[e].value=t)},r.has=function(e){return!!this.nodes[e]},r.delete=function(e){this.nodes[e]&&(this.nodes[e].value={t:""})},r.toTree=function(){for(var e,t={children:[],id:"root",value:""},r={root:t},n=s(this.log);!(e=n()).done;){var i=e.value,o={children:[],id:i.id,value:i.value};if(r[i.id]=o,"root"===i.after)t.children.push(o);else{if(!r[i.after])continue;r[i.after].children.push(o)}}return t},r.sortLog=function(){this.log.sort((function(e,t){var r=e.id.split(":"),n=r[0],i=r[1],s=t.id.split(":"),o=s[0];return n===o?i.localeCompare(s[1]):parseInt(n)-parseInt(o)}))},r.lastID=function(){return 0===this.log.length?"root":(this.sortLog(),function e(t){return t.children&&0!==t.children.length?e(t.children[t.children.length-1]):t}(this.toTree()).id)},r.postOrderTraverse=function(){return this.sortLog(),function e(t){if(!t.children||0===t.children.length)return[];for(var r,n=[],i=s(t.children);!(r=i()).done;){var o=r.value;if("string"!=typeof o.value){if(""===o.value.t){n=n.concat([].concat(e(o)));continue}throw new Error("Unimplemented")}n=n.concat([o].concat(e(o)))}return n}(this.toTree())},r.toArray=function(){return this.postOrderTraverse().map((function(e){return e.value}))},n(e,[{key:"length",get:function(){return Object.keys(this.nodes).length}}]),e}();function h(e){return JSON.stringify(e)}function u(e){try{return JSON.parse(e)}catch(t){return e}}var l=function(){function e(e,r,n,i,s,o){this.itemIDs=[],this.roomID=r,this.docID=n,this.id=i,this.ws=s,this.rt=new a(o),e.lists[i]||t(!1),this.rt.import(e,i);for(var h=e.lists[i].ids||[],u=0;u<h.length;u++){var l=e.lists[i].values[u];"object"==typeof l&&""===l.t||this.itemIDs.push(c(e,h[u]))}}var r=e.prototype;return r.sendCmd=function(e){this.ws.send("doc:cmd",{room:this.roomID,args:e})},r.clone=function(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)},r.dangerouslyUpdateClientDirectly=function(e){if(e.length<3)throw new Error("Unexpected command: "+e);var t=e[0];if(e[1]!==this.docID||e[2]!==this.id)throw new Error("Command unexpectedly routed to the wrong client");switch(t){case"lins":var r=e[3],n=e[4],i=e[5];this.itemIDs.splice(this.itemIDs.findIndex((function(e){return e===r}))+1,0,n),this.rt.insert(r,i,n);break;case"lput":this.rt.put(e[3],e[4]);break;case"ldel":var s=e[3];this.rt.delete(s),this.itemIDs.splice(this.itemIDs.findIndex((function(e){return e===s})),1);break;default:throw new Error("Unexpected command keyword: "+t)}return this.clone()},r.get=function(e){var t=this.itemIDs[e];if(t){var r=this.rt.get(t);if(r){if("object"==typeof r){if(""===r.t)return;throw new Error("Unimplemented references")}return u(r)}}},r.set=function(e,t){var r=this.itemIDs[e];if(!r)throw new Error("Index '"+e+"' doesn't already exist. Try .push() or .insertAfter() instead.");var n=h(t);return this.rt.put(r,n),this.sendCmd(["lput",this.docID,this.id,r,n]),this.clone()},r.delete=function(e){if(0===this.itemIDs.length)return this.clone();var t=this.itemIDs[e];return t?(this.rt.delete(t),this.itemIDs.splice(e,1),this.sendCmd(["ldel",this.docID,this.id,t]),this.clone()):(console.warn("Unknown index: ",e,this.itemIDs),this.clone())},r.insertAfter=function(e,t){var r=this.itemIDs[e];if(!r)throw new RangeError("List '"+this.id+"' has no index: '"+e+"'");var n=h(t),i=this.rt.insert(r,n);return this.itemIDs.splice(e,0,i),this.sendCmd(["lins",this.docID,this.id,r,i,n]),this.clone()},r.pushOne=function(e){var t=this.rt.lastID(),r=h(e),n=this.rt.insert(t,r);return this.itemIDs.push(n),this.sendCmd(["lins",this.docID,this.id,t,n,r]),this.clone()},r.push=function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];for(var i=0,s=r;i<s.length;i++){var o=s[i];e=this.pushOne(o)}return e},r.map=function(e){return this.rt.postOrderTraverse().map((function(t,r){return e(u(t.value),r,t.id)}))},r.toArray=function(){return this.rt.toArray().map((function(e){return u(e)}))},e}(),d=function(){function e(e,t,r,n,i){for(var s in this.roomID=t,this.docID=r,this.id=n,this.ws=i,this.store={},e){var o=e[s];"string"==typeof o&&(this.store[s]=u(o))}}var t=e.prototype;return t.sendCmd=function(e){this.ws.send("doc:cmd",{room:this.roomID,args:e})},t.clone=function(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)},t.dangerouslyUpdateClientDirectly=function(e){if(e.length<3)throw new Error("Unexpected command: "+e);var t=e[0];if(e[1]!==this.docID||e[2]!==this.id)throw new Error("Command unexpectedly routed to the wrong client");switch(t){case"mput":if(5!==e.length){console.error("Malformed command ",e);break}this.store[e[3]]=u(e[4]);break;case"mdel":if(4!==e.length){console.error("Malformed command ",e);break}delete this.store[e[3]];break;default:throw new Error("Unexpected command keyword: "+t)}return this.clone()},t.get=function(e){return this.store[e]},t.set=function(e,t){var r=h(t);return this.store[e]=t,this.sendCmd(["mput",this.docID,this.id,e,r]),this.clone()},t.toObject=function(){for(var e,t={},r=s(this.keys);!(e=r()).done;){var n=e.value;t[n]=this.get(n)}return t},t.delete=function(e){return delete this.store[e],this.sendCmd(["mdel",this.docID,this.id,e]),this.clone()},n(e,[{key:"keys",get:function(){return Object.keys(this.store)}}]),e}(),f=function(){function e(e,t,r,n){var i=this;this.roomID=e,this.ws=t,this.actor=r,this.token=n,this.cache={},this.sendPres=function(e,t,r){void 0===r&&(r=!1);var n={},i=!0;return function(){var t=arguments,s=this,o=r&&i,c=function(){e.apply(s,t),n[t[0]]=null};o&&(i=!1,c()),n[arguments[0]]||(n[arguments[0]]=setTimeout(c,40))}}((function(e,t){i.ws.send("presence:cmd",t)}))}var t=e.prototype;return t.getAll=function(e){try{var t=this;return Promise.resolve(function(e,t,r,n){try{return Promise.resolve(fetch("https://super.roomservice.dev/presence/"+r+"/"+encodeURIComponent(n),{headers:{Authorization:"Bearer: "+t}})).then((function(e){return Promise.resolve(e.json()).then((function(e){for(var t in e)if("string"==typeof e[t].value){var r=void 0;try{r=JSON.parse(e[t].value)}catch(e){}r&&(e[t].value=r)}return e}))}))}catch(e){return Promise.reject(e)}}(0,t.token,t.roomID,e)).then((function(r){return t.cache[e]=r,t.withoutExpiredAndSelf(e)}))}catch(e){return Promise.reject(e)}},t.withoutExpiredAndSelf=function(e){var t={};for(var r in this.cache[e]){var n=this.cache[e][r];r===this.actor&&delete this.cache[e][r],new Date>n.expAt?delete this.cache[e][r]:t[r]=n.value}return t},t.withoutActorOrExpired=function(e){var t={};for(var r in this.cache)for(var n in this.cache[r]){var i=this.cache[r][n];i&&(n===e&&this.cache[r][n]||new Date>i.expAt?delete this.cache[r][n]:t[n]=i.value)}return t},t.set=function(e,t,r){var n=r||60,i=Math.round((new Date).getTime()/1e3)+n;return this.sendPres(e,{room:this.roomID,key:e,value:JSON.stringify(t),expAt:i}),this.cache[e]||(this.cache[e]={}),this.cache[e][this.actor]={value:t,expAt:new Date(1e3*i)},this.withoutExpiredAndSelf(e)},t.dangerouslyUpdateClientDirectly=function(e,t){if("room:rm_guest"===e)return this.withoutActorOrExpired(t.guest);if("presence:expire"===e)return this.withoutExpiredAndSelf(t.key);if(t.room!==this.roomID)return!1;if(t.from===this.actor)return!1;var r={expAt:new Date(1e3*t.expAt),value:JSON.parse(t.value)};return this.cache[t.key]||(this.cache[t.key]={}),this.cache[t.key][t.from]=r,this.withoutExpiredAndSelf(t.key)},n(e,[{key:"me",get:function(){return console.warn("presence.me() is deprecated and will be removed in a future version!"),this.actor}}]),e}();function m(e){for(var t=window.atob(e),r=t.length,n=new Uint8Array(r),i=0;i<r;i++)n[i]=t.charCodeAt(i);return n.buffer}var p=["mcreate","mput","mputref","mdel"],v=["lcreate","lins","linsref","lput","lputref","ldel"],y=function(){function e(e){var t=this;this.listClients={},this.mapClients={},this.expires={},this.mapCallbacksByObjID={},this.listCallbacksByObjID={},this.presenceCallbacksByKey={},this.ws=new o(e.conn),this.token=e.token,this.roomID=e.roomID,this.docID=e.checkpoint.id,this.actor=e.actor,this.checkpoint=e.checkpoint,this.InnerPresenceClient=void 0,this.ws.bind("doc:fwd",(function(e){if(e.room===t.roomID)if(!e.args||e.args.length<3)console.error("Unexpected command: ",e.args);else if(!function(e,t){if(!e)return!0;if(!t)return!1;for(var r=new Uint8Array(m(e).slice(0,9)),n=new Uint8Array(m(t).slice(0,9)),i=0;i<r.byteLength;i++){if(n[i]>r[i])return!0;if(n[i]<r[i])return!1}return!1}(e.vs,t.checkpoint.vs)&&e.from!==t.actor){var r=[e.args[0],e.args[1],e.args[2]],n=r[0],i=r[2];r[1]===t.docID&&(p.includes(n)?t.dispatchMapCmd(i,e):v.includes(n)?t.dispatchListCmd(i,e):console.warn("Unhandled Room Service doc:fwd command: "+n+". Consider updating the Room Service client."))}})),this.ws.bind("presence:fwd",(function(e){t.dispatchPresenceCmd(e)})),this.ws.bind("room:rm_guest",(function(e){if(e.room===t.roomID)for(var r=t.presence().dangerouslyUpdateClientDirectly("room:rm_guest",e),n=0,i=Object.entries(t.presenceCallbacksByKey);n<i.length;n++)for(var o,c=s(i[n][1]);!(o=c()).done;)(0,o.value)(r,e.guest)}))}var r=e.prototype;return r.dispatchMapCmd=function(e,t){if(!this.mapClients[e]){var r=new d(this.checkpoint.maps[e]||{},this.roomID,this.docID,e,this.ws);this.mapClients[e]=r}for(var n,i=this.mapClients[e].dangerouslyUpdateClientDirectly(t.args),o=s(this.mapCallbacksByObjID[e]||[]);!(n=o()).done;)(0,n.value)(i,t.from)},r.dispatchListCmd=function(e,t){if(!this.listClients[e]){var r=new l(this.checkpoint,this.roomID,this.docID,e,this.ws,this.actor);this.listClients[e]=r}for(var n,i=this.listClients[e].dangerouslyUpdateClientDirectly(t.args),o=s(this.listCallbacksByObjID[e]||[]);!(n=o()).done;)(0,n.value)(i,t.from)},r.dispatchPresenceCmd=function(e){var t=this;if(e.room===this.roomID&&e.from!==this.actor){var r=this.presence(),n=e.key,i=(new Date).getTime()/1e3,o=e.expAt-i;if(!(o<0)){if(o<43200){this.expires[n]&&clearTimeout(this.expires[n]);var c=setTimeout((function(){var i=r.dangerouslyUpdateClientDirectly("presence:expire",{key:e.key});if(i)for(var o,c=s(null!==(a=t.presenceCallbacksByKey[n])&&void 0!==a?a:[]);!(o=c()).done;){var a;(0,o.value)(i,e.from)}}),1e3*o);this.expires[n]=c}var a=r.dangerouslyUpdateClientDirectly("presence:fwd",e);if(a)for(var h,u=s(null!==(l=this.presenceCallbacksByKey[n])&&void 0!==l?l:[]);!(h=u()).done;){var l;(0,h.value)(a,e.from)}}}},r.once=function(e){try{var t,r=this;return Promise.race([new Promise((function(e,t){return setTimeout((function(){return t("timeout")}),2e3)})),new Promise((function(n){t=r.ws.bind(e,(function(e){n(e)}))}))]).then((function(){t&&r.ws.unbind(e,t)}))}catch(e){return Promise.reject(e)}},r.reconnect=function(){try{var e=this;e.errorListener||(e.errorListener=e.ws.bind("error",(function(e){console.error("Room Service encountered a server-side error. If you see this, please let us know; this could be a bug.",e)})));var t=e.once("guest:authenticated");return e.ws.send("guest:authenticate",e.token),Promise.resolve(t).then((function(){var t=e.once("room:joined");return e.ws.send("room:join",e.roomID),Promise.resolve(t).then((function(){}))}))}catch(e){return Promise.reject(e)}},r.list=function(e){if(this.listClients[e])return this.listClients[e];this.checkpoint.lists[e]||(this.ws.send("doc:cmd",{args:["lcreate",this.docID,e],room:this.roomID}),this.checkpoint.lists[e]={afters:[],ids:[],values:[]});var t=new l(this.checkpoint,this.roomID,this.docID,e,this.ws,this.actor);return this.listClients[e]=t,t},r.map=function(e){if(this.mapClients[e])return this.mapClients[e];this.checkpoint.maps[e]||this.ws.send("doc:cmd",{args:["mcreate",this.docID,e],room:this.roomID});var t=new d(this.checkpoint.maps[e]||{},this.roomID,this.docID,e,this.ws);return this.mapClients[e]=t,t},r.presence=function(){if(this.InnerPresenceClient)return this.InnerPresenceClient;var e=new f(this.roomID,this.ws,this.actor,this.token);try{this.InnerPresenceClient=e}catch(e){throw new Error("Don't Freeze State. See more: https://err.sh/getroomservice/browser/dont-freeze")}return this.InnerPresenceClient},r.subscribe=function(e,t,r){if("string"==typeof t)return this.subscribePresence(e,t,r);var n,i=function(e,r){t(e,r)};return e instanceof d&&(this.mapCallbacksByObjID[n=e.id]=this.mapCallbacksByObjID[n]||[],this.mapCallbacksByObjID[n].push(i)),e instanceof l&&(this.listCallbacksByObjID[n=e.id]=this.listCallbacksByObjID[n]||[],this.listCallbacksByObjID[n].push(i)),[{objID:n,fn:i}]},r.subscribePresence=function(e,r,n){e||t(!1);var i=function(e,t){n&&n(e,t)};return this.presenceCallbacksByKey[r]=this.presenceCallbacksByKey[r]||[],this.presenceCallbacksByKey[r].push(i),[{objID:r,fn:i}]},r.unsubscribe=function(e){for(var t,r=s(e);!(t=r()).done;){var n=t.value;n.objID&&(this.mapCallbacksByObjID[n.objID]=b(this.mapCallbacksByObjID[n.objID],n.fn),this.listCallbacksByObjID[n.objID]=b(this.listCallbacksByObjID[n.objID],n.fn),this.presenceCallbacksByKey[n.objID]=b(this.presenceCallbacksByKey[n.objID],n.fn)),n.event&&this.ws.unbind(n.event,n.fn)}},n(e,[{key:"me",get:function(){return this.actor}}]),e}();function b(e,t){return e?e.filter((function(e){return e!==t})):[]}var w=function(){function e(e){this.roomClients={},this.auth=e.auth}return e.prototype.room=function(e){try{var t=this;if(t.roomClients[e])return Promise.resolve(t.roomClients[e]);var r=new WebSocket("wss://super.roomservice.dev/ws");return Promise.resolve(function(e,t,r,n,i){try{return Promise.resolve(function(e,t,r){try{var n=function(r){return i?r:Promise.resolve(fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resources:[{object:"document",reference:"default",permission:"read_write",room:t},{object:"room",reference:t,permission:"join"}]})})).then((function(e){if(401===e.status)throw new Error("The Auth Webhook returned unauthorized.");if(200!==e.status)throw new Error("The Auth Webhook returned a status code other than 200.");return Promise.resolve(e.json()).then((function(e){var t=e.resources,r=e.token,n=e.user;if(!t||!r||!n){if("Unauthorized"===e.body)throw new Error("The Auth Webhook unexpectedly return unauthorized. You may be using an invalid API key.");throw new Error("The Auth Webhook has an incorrectly formatted JSON response.")}return{token:r,guestReference:n,docID:t.find((function(e){return"document"===e.object})).id,roomID:t.find((function(e){return"room"===e.object})).id}}))}))},i=!1,s=function(){if("function"==typeof e)return Promise.resolve(e(t)).then((function(e){if(!e.user)throw new Error("The auth function must return a 'user' key.");var t=e.resources.find((function(e){return"document"===e.object})).id,r=e.resources.find((function(e){return"room"===e.object})).id;return i=!0,{token:e.token,guestReference:e.user,docID:t,roomID:r}}))}();return Promise.resolve(s&&s.then?s.then(n):n(s))}catch(e){return Promise.reject(e)}}(r,n)).then((function(t){return Promise.resolve(function(e,t,r){try{return Promise.resolve(fetch("https://super.roomservice.dev/docs/"+r,{headers:{Authorization:"Bearer: "+t}})).then((function(e){return Promise.resolve(e.json())}))}catch(e){return Promise.reject(e)}}(0,t.token,t.docID)).then((function(r){var n=new y({conn:e,actor:t.guestReference,checkpoint:r.body,token:t.token,roomID:t.roomID});return Promise.resolve(n.reconnect()).then((function(){return n}))}))}))}catch(e){return Promise.reject(e)}}(r,0,t.auth,e)).then((function(r){return t.roomClients[e]=r,r}))}catch(e){return Promise.reject(e)}},e}();exports.RoomClient=y,exports.RoomService=w,exports.default=w;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=(t=require("tiny-invariant"))&&"object"==typeof t&&"default"in t?t.default:t;function r(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function n(t,e,n){return e&&r(t.prototype,e),n&&r(t,n),t}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function s(t,e){var r;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return i(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(t,void 0):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=t[Symbol.iterator]()).next.bind(r)}var o=function(){function t(t){var e=this;this.callbacks={},this.lastTime=0,this.msgsThisMilisecond=0,this.conn=t,this.conn.onmessage=function(t){var r=JSON.parse(t.data);e.dispatch(r.type,r.body)}}var e=t.prototype;return e.timestamp=function(){var t=Date.now();return t===this.lastTime?this.msgsThisMilisecond++:(this.lastTime=t,this.msgsThisMilisecond=0),t+":"+this.msgsThisMilisecond},e.send=function(t,e){var r=this,n=this.timestamp();this.conn.readyState!==this.conn.CONNECTING?this.conn.send(JSON.stringify({type:t,ts:n,ver:0,body:e})):setTimeout((function(){r.send(t,e)}),100+100*Math.random())},e.bind=function(t,e){return this.callbacks[t]=this.callbacks[t]||[],this.callbacks[t].push(e),e},e.unbind=function(t,e){this.callbacks[t]=this.callbacks[t].filter((function(t){return t!==e}))},e.dispatch=function(t,e){var r=this.callbacks[t];if(r)for(var n=0;n<r.length;n++)r[n](e)},t}();function c(t,e){if("root"===e)return"root";var r=e.split(":");return r[0]+":"+t.actors[parseInt(r[1])]}var a=function(){function t(t){this.count=0,this.actor=t,this.nodes={},this.log=[]}var r=t.prototype;return r.import=function(t,r){t||e(!1);for(var n=t.lists[r],i=n.afters||[],s=n.ids||[],o=n.values||[],a=0;a<i.length;a++){var h={after:c(t,i[a]),id:c(t,s[a]),value:o[a]};this.nodes[h.id]=h,this.log.push(h)}this.count=this.log.length},r.get=function(t){if(this.nodes[t])return this.nodes[t].value},r.insert=function(t,r,n){this.log||e(!1);var i=n;i||(i=this.count+":"+this.actor),this.count++;var s={after:t,value:r,id:i};return this.nodes[i]=s,this.log.push(s),i},r.put=function(t,e){this.nodes[t]&&(this.nodes[t].value=e)},r.has=function(t){return!!this.nodes[t]},r.delete=function(t){this.nodes[t]&&(this.nodes[t].value={t:""})},r.toTree=function(){for(var t,e={children:[],id:"root",value:""},r={root:e},n=s(this.log);!(t=n()).done;){var i=t.value,o={children:[],id:i.id,value:i.value};if(r[i.id]=o,"root"===i.after)e.children.push(o);else{if(!r[i.after])continue;r[i.after].children.push(o)}}return e},r.sortLog=function(){this.log.sort((function(t,e){var r=t.id.split(":"),n=r[0],i=r[1],s=e.id.split(":"),o=s[0];return n===o?i.localeCompare(s[1]):parseInt(n)-parseInt(o)}))},r.lastID=function(){return 0===this.log.length?"root":(this.sortLog(),function t(e){return e.children&&0!==e.children.length?t(e.children[e.children.length-1]):e}(this.toTree()).id)},r.postOrderTraverse=function(){return this.sortLog(),function t(e){if(!e.children||0===e.children.length)return[];for(var r,n=[],i=s(e.children);!(r=i()).done;){var o=r.value;if("string"!=typeof o.value){if(""===o.value.t){n=n.concat([].concat(t(o)));continue}throw new Error("Unimplemented")}n=n.concat([o].concat(t(o)))}return n}(this.toTree())},r.toArray=function(){return this.postOrderTraverse().map((function(t){return t.value}))},n(t,[{key:"length",get:function(){return Object.keys(this.nodes).length}}]),t}();function h(t){return JSON.stringify(t)}function u(t){try{return JSON.parse(t)}catch(e){return t}}var l=function(){return new Error("Infinite loop detected, see more: See more: https://err.sh/getroomservice/browser/infinite-loop")},d=function(){function t(t){this.throwsOnMutate=!1,this.itemIDs=[],this.roomID=t.roomID,this.docID=t.docID,this.id=t.listID,this.ws=t.ws,this.rt=new a(t.actor),this.bus=t.bus,this.actor=t.actor,t.checkpoint.lists[t.listID]||e(!1),this.rt.import(t.checkpoint,t.listID);for(var r=t.checkpoint.lists[t.listID].ids||[],n=0;n<r.length;n++){var i=t.checkpoint.lists[t.listID].values[n];"object"==typeof i&&""===i.t||this.itemIDs.push(c(t.checkpoint,r[n]))}}var r=t.prototype;return r.sendCmd=function(t){if(this.throwsOnMutate)throw l();this.ws.send("doc:cmd",{room:this.roomID,args:t}),this.throwsOnMutate=!0,this.bus.publish({args:t,from:this.actor}),this.throwsOnMutate=!1},r.clone=function(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)},r.dangerouslyUpdateClientDirectly=function(t){if(t.length<3)throw new Error("Unexpected command: "+t);var e=t[0];if(t[1]!==this.docID||t[2]!==this.id)throw new Error("Command unexpectedly routed to the wrong client");switch(e){case"lins":var r=t[3],n=t[4],i=t[5];this.itemIDs.splice(this.itemIDs.findIndex((function(t){return t===r}))+1,0,n),this.rt.insert(r,i,n);break;case"lput":this.rt.put(t[3],t[4]);break;case"ldel":var s=t[3];this.rt.delete(s),this.itemIDs.splice(this.itemIDs.findIndex((function(t){return t===s})),1);break;default:throw new Error("Unexpected command keyword: "+e)}return this.clone()},r.get=function(t){var e=this.itemIDs[t];if(e){var r=this.rt.get(e);if(r){if("object"==typeof r){if(""===r.t)return;throw new Error("Unimplemented references")}return u(r)}}},r.set=function(t,e){var r=this.itemIDs[t];if(!r)throw new Error("Index '"+t+"' doesn't already exist. Try .push() or .insertAfter() instead.");var n=h(e);return this.rt.put(r,n),this.sendCmd(["lput",this.docID,this.id,r,n]),this.clone()},r.delete=function(t){if(0===this.itemIDs.length)return this.clone();var e=this.itemIDs[t];return e?(this.rt.delete(e),this.itemIDs.splice(t,1),this.sendCmd(["ldel",this.docID,this.id,e]),this.clone()):(console.warn("Unknown index: ",t,this.itemIDs),this.clone())},r.insertAfter=function(t,e){var r=this.itemIDs[t];if(!r)throw new RangeError("List '"+this.id+"' has no index: '"+t+"'");var n=h(e),i=this.rt.insert(r,n);return this.itemIDs.splice(t,0,i),this.sendCmd(["lins",this.docID,this.id,r,i,n]),this.clone()},r.pushOne=function(t){var e=this.rt.lastID(),r=h(t),n=this.rt.insert(e,r);return this.itemIDs.push(n),this.sendCmd(["lins",this.docID,this.id,e,n,r]),this.clone()},r.push=function(){for(var t,e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];for(var i=0,s=r;i<s.length;i++){var o=s[i];t=this.pushOne(o)}return t},r.map=function(t){return this.rt.postOrderTraverse().map((function(e,r){return t(u(e.value),r,e.id)}))},r.toArray=function(){return this.rt.toArray().map((function(t){return u(t)}))},t}(),f=function(){function t(t){for(var e in this.throwsOnMutate=!1,this.roomID=t.roomID,this.docID=t.docID,this.id=t.mapID,this.ws=t.ws,this.store={},this.bus=t.bus,this.actor=t.actor,t.checkpoint){var r=t.checkpoint[e];"string"==typeof r&&(this.store[e]=u(r))}}var e=t.prototype;return e.sendCmd=function(t){if(this.throwsOnMutate)throw l();this.ws.send("doc:cmd",{room:this.roomID,args:t}),this.throwsOnMutate=!0,this.bus.publish({from:this.actor,args:t}),this.throwsOnMutate=!1},e.clone=function(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)},e.dangerouslyUpdateClientDirectly=function(t){if(t.length<3)throw new Error("Unexpected command: "+t);var e=t[0];if(t[1]!==this.docID||t[2]!==this.id)throw new Error("Command unexpectedly routed to the wrong client");switch(e){case"mput":if(5!==t.length){console.error("Malformed command ",t);break}this.store[t[3]]=u(t[4]);break;case"mdel":if(4!==t.length){console.error("Malformed command ",t);break}delete this.store[t[3]];break;default:throw new Error("Unexpected command keyword: "+e)}return this.clone()},e.get=function(t){return this.store[t]},e.set=function(t,e){var r=h(e);return this.store[t]=e,this.sendCmd(["mput",this.docID,this.id,t,r]),this.clone()},e.toObject=function(){for(var t,e={},r=s(this.keys);!(t=r()).done;){var n=t.value;e[n]=this.get(n)}return e},e.delete=function(t){return delete this.store[t],this.sendCmd(["mdel",this.docID,this.id,t]),this.clone()},n(t,[{key:"keys",get:function(){return Object.keys(this.store)}}]),t}(),m=function(){function t(t){var e=this;this.roomID=t.roomID,this.ws=t.ws,this.actor=t.actor,this.token=t.token,this.cache={},this.sendPres=function(t,e,r){void 0===r&&(r=!1);var n={},i=!0;return function(){var e=arguments,s=this,o=r&&i,c=function(){t.apply(s,e),n[e[0]]=null};o&&(i=!1,c()),n[arguments[0]]||(n[arguments[0]]=setTimeout(c,40))}}((function(t,r){e.ws.send("presence:cmd",r)}))}var e=t.prototype;return e.getAll=function(t){try{var e=this;return Promise.resolve(function(t,e,r,n){try{return Promise.resolve(fetch("https://super.roomservice.dev/presence/"+r+"/"+encodeURIComponent(n),{headers:{Authorization:"Bearer: "+e}})).then((function(t){return Promise.resolve(t.json()).then((function(t){for(var e in t)if("string"==typeof t[e].value){var r=void 0;try{r=JSON.parse(t[e].value)}catch(t){}r&&(t[e].value=r)}return t}))}))}catch(t){return Promise.reject(t)}}(0,e.token,e.roomID,t)).then((function(r){return e.cache[t]=r,e.withoutExpiredAndSelf(t)}))}catch(t){return Promise.reject(t)}},e.withoutExpiredAndSelf=function(t){var e={};for(var r in this.cache[t]){var n=this.cache[t][r];r===this.actor&&delete this.cache[t][r],new Date>n.expAt?delete this.cache[t][r]:e[r]=n.value}return e},e.withoutActorOrExpired=function(t){var e={};for(var r in this.cache)for(var n in this.cache[r]){var i=this.cache[r][n];i&&(n===t&&this.cache[r][n]||new Date>i.expAt?delete this.cache[r][n]:e[n]=i.value)}return e},e.set=function(t,e,r){var n=r||60,i=Math.round((new Date).getTime()/1e3)+n;return this.sendPres(t,{room:this.roomID,key:t,value:JSON.stringify(e),expAt:i}),this.cache[t]||(this.cache[t]={}),this.cache[t][this.actor]={value:e,expAt:new Date(1e3*i)},this.withoutExpiredAndSelf(t)},e.dangerouslyUpdateClientDirectly=function(t,e){if("room:rm_guest"===t)return this.withoutActorOrExpired(e.guest);if("presence:expire"===t)return this.withoutExpiredAndSelf(e.key);if(e.room!==this.roomID)return!1;if(e.from===this.actor)return!1;var r={expAt:new Date(1e3*e.expAt),value:JSON.parse(e.value)};return this.cache[e.key]||(this.cache[e.key]={}),this.cache[e.key][e.from]=r,this.withoutExpiredAndSelf(e.key)},n(t,[{key:"me",get:function(){return console.warn("presence.me() is deprecated and will be removed in a future version!"),this.actor}}]),t}();function p(t){for(var e=window.atob(t),r=e.length,n=new Uint8Array(r),i=0;i<r;i++)n[i]=e.charCodeAt(i);return n.buffer}var v=function(){function t(){this.subs=new Set}var e=t.prototype;return e.subscribe=function(t){return this.subs.add(t),t},e.unsubscribe=function(t){this.subs.delete(t)},e.publish=function(t){this.subs.forEach((function(e){e(t)}))},t}(),b=["mcreate","mput","mputref","mdel"],y=["lcreate","lins","linsref","lput","lputref","ldel"],w=function(){function t(t){var e=this;this.listClients={},this.mapClients={},this.expires={},this.mapCallbacksByObjID={},this.listCallbacksByObjID={},this.presenceCallbacksByKey={},this.ws=new o(t.conn),this.token=t.token,this.roomID=t.roomID,this.docID=t.checkpoint.id,this.actor=t.actor,this.checkpoint=t.checkpoint,this.InnerPresenceClient=void 0,this.ws.bind("doc:fwd",(function(t){if(t.room===e.roomID)if(!t.args||t.args.length<3)console.error("Unexpected command: ",t.args);else if(!function(t,e){if(!t)return!0;if(!e)return!1;for(var r=new Uint8Array(p(t).slice(0,9)),n=new Uint8Array(p(e).slice(0,9)),i=0;i<r.byteLength;i++){if(n[i]>r[i])return!0;if(n[i]<r[i])return!1}return!1}(t.vs,e.checkpoint.vs)&&t.from!==e.actor){var r=[t.args[0],t.args[1],t.args[2]],n=r[0],i=r[2];r[1]===e.docID&&(b.includes(n)?e.dispatchMapCmd(i,t):y.includes(n)?e.dispatchListCmd(i,t):console.warn("Unhandled Room Service doc:fwd command: "+n+". Consider updating the Room Service client."))}})),this.ws.bind("presence:fwd",(function(t){e.dispatchPresenceCmd(t)})),this.ws.bind("room:rm_guest",(function(t){if(t.room===e.roomID)for(var r=e.presence().dangerouslyUpdateClientDirectly("room:rm_guest",t),n=0,i=Object.entries(e.presenceCallbacksByKey);n<i.length;n++)for(var o,c=s(i[n][1]);!(o=c()).done;)(0,o.value)(r,t.guest)}))}var r=t.prototype;return r.dispatchMapCmd=function(t,e){this.mapClients[t]||this.createMapLocally(t);for(var r,n=this.mapClients[t].dangerouslyUpdateClientDirectly(e.args),i=s(this.mapCallbacksByObjID[t]||[]);!(r=i()).done;)(0,r.value)(n,e.from)},r.dispatchListCmd=function(t,e){this.listClients[t]||this.createListLocally(t);for(var r,n=this.listClients[t].dangerouslyUpdateClientDirectly(e.args),i=s(this.listCallbacksByObjID[t]||[]);!(r=i()).done;)(0,r.value)(n,e.from)},r.dispatchPresenceCmd=function(t){var e=this;if(t.room===this.roomID&&t.from!==this.actor){var r=this.presence(),n=t.key,i=(new Date).getTime()/1e3,o=t.expAt-i;if(!(o<0)){if(o<43200){this.expires[n]&&clearTimeout(this.expires[n]);var c=setTimeout((function(){var i=r.dangerouslyUpdateClientDirectly("presence:expire",{key:t.key});if(i)for(var o,c=s(null!==(a=e.presenceCallbacksByKey[n])&&void 0!==a?a:[]);!(o=c()).done;){var a;(0,o.value)(i,t.from)}}),1e3*o);this.expires[n]=c}var a=r.dangerouslyUpdateClientDirectly("presence:fwd",t);if(a)for(var h,u=s(null!==(l=this.presenceCallbacksByKey[n])&&void 0!==l?l:[]);!(h=u()).done;){var l;(0,h.value)(a,t.from)}}}},r.once=function(t){try{var e,r=this;return Promise.race([new Promise((function(t,e){return setTimeout((function(){return e("timeout")}),2e3)})),new Promise((function(n){e=r.ws.bind(t,(function(t){n(t)}))}))]).then((function(){e&&r.ws.unbind(t,e)}))}catch(t){return Promise.reject(t)}},r.reconnect=function(){try{var t=this;t.errorListener||(t.errorListener=t.ws.bind("error",(function(t){console.error("Room Service encountered a server-side error. If you see this, please let us know; this could be a bug.",t)})));var e=t.once("guest:authenticated");return t.ws.send("guest:authenticate",t.token),Promise.resolve(e).then((function(){var e=t.once("room:joined");return t.ws.send("room:join",t.roomID),Promise.resolve(e).then((function(){}))}))}catch(t){return Promise.reject(t)}},r.createListLocally=function(t){var e=this,r=new v;r.subscribe((function(r){e.dispatchListCmd(t,r)}));var n=new d({checkpoint:this.checkpoint,roomID:this.roomID,docID:this.docID,listID:t,ws:this.ws,actor:this.actor,bus:r});return this.listClients[t]=n,n},r.list=function(t){return this.listClients[t]?this.listClients[t]:(this.checkpoint.lists[t]||(this.ws.send("doc:cmd",{args:["lcreate",this.docID,t],room:this.roomID}),this.checkpoint.lists[t]={afters:[],ids:[],values:[]}),this.createListLocally(t))},r.createMapLocally=function(t){var e=this,r=new v;r.subscribe((function(r){e.dispatchMapCmd(t,r)}));var n=new f({checkpoint:this.checkpoint.maps[t]||{},roomID:this.roomID,docID:this.docID,mapID:t,ws:this.ws,bus:r,actor:this.actor});return this.mapClients[t]=n,n},r.map=function(t){return this.mapClients[t]?this.mapClients[t]:(this.checkpoint.maps[t]||this.ws.send("doc:cmd",{args:["mcreate",this.docID,t],room:this.roomID}),this.createMapLocally(t))},r.presence=function(){if(this.InnerPresenceClient)return this.InnerPresenceClient;var t=new m({roomID:this.roomID,ws:this.ws,actor:this.actor,token:this.token});try{this.InnerPresenceClient=t}catch(t){throw new Error("Don't Freeze State. See more: https://err.sh/getroomservice/browser/dont-freeze")}return this.InnerPresenceClient},r.subscribe=function(t,e,r){if("string"==typeof e)return this.subscribePresence(t,e,r);var n,i=function(t,r){e(t,r)};return t instanceof f&&(this.mapCallbacksByObjID[n=t.id]=this.mapCallbacksByObjID[n]||[],this.mapCallbacksByObjID[n].push(i)),t instanceof d&&(this.listCallbacksByObjID[n=t.id]=this.listCallbacksByObjID[n]||[],this.listCallbacksByObjID[n].push(i)),[{objID:n,fn:i}]},r.subscribePresence=function(t,r,n){t||e(!1);var i=function(t,e){n&&n(t,e)};return this.presenceCallbacksByKey[r]=this.presenceCallbacksByKey[r]||[],this.presenceCallbacksByKey[r].push(i),[{objID:r,fn:i}]},r.unsubscribe=function(t){for(var e,r=s(t);!(e=r()).done;){var n=e.value;n.objID&&(this.mapCallbacksByObjID[n.objID]=I(this.mapCallbacksByObjID[n.objID],n.fn),this.listCallbacksByObjID[n.objID]=I(this.listCallbacksByObjID[n.objID],n.fn),this.presenceCallbacksByKey[n.objID]=I(this.presenceCallbacksByKey[n.objID],n.fn)),n.event&&this.ws.unbind(n.event,n.fn)}},n(t,[{key:"me",get:function(){return this.actor}}]),t}();function I(t,e){return t?t.filter((function(t){return t!==e})):[]}var D=function(){function t(t){this.roomClients={},this.auth=t.auth}return t.prototype.room=function(t){try{var e=this;if(e.roomClients[t])return Promise.resolve(e.roomClients[t]);var r=new WebSocket("wss://super.roomservice.dev/ws");return Promise.resolve(function(t,e,r,n,i){try{return Promise.resolve(function(t,e,r){try{var n=function(r){return i?r:Promise.resolve(fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resources:[{object:"document",reference:"default",permission:"read_write",room:e},{object:"room",reference:e,permission:"join"}]})})).then((function(t){if(401===t.status)throw new Error("The Auth Webhook returned unauthorized.");if(200!==t.status)throw new Error("The Auth Webhook returned a status code other than 200.");return Promise.resolve(t.json()).then((function(t){var e=t.resources,r=t.token,n=t.user;if(!e||!r||!n){if("Unauthorized"===t.body)throw new Error("The Auth Webhook unexpectedly return unauthorized. You may be using an invalid API key.");throw new Error("The Auth Webhook has an incorrectly formatted JSON response.")}return{token:r,guestReference:n,docID:e.find((function(t){return"document"===t.object})).id,roomID:e.find((function(t){return"room"===t.object})).id}}))}))},i=!1,s=function(){if("function"==typeof t)return Promise.resolve(t(e)).then((function(t){if(!t.user)throw new Error("The auth function must return a 'user' key.");var e=t.resources.find((function(t){return"document"===t.object})).id,r=t.resources.find((function(t){return"room"===t.object})).id;return i=!0,{token:t.token,guestReference:t.user,docID:e,roomID:r}}))}();return Promise.resolve(s&&s.then?s.then(n):n(s))}catch(t){return Promise.reject(t)}}(r,n)).then((function(e){return Promise.resolve(function(t,e,r){try{return Promise.resolve(fetch("https://super.roomservice.dev/docs/"+r,{headers:{Authorization:"Bearer: "+e}})).then((function(t){return Promise.resolve(t.json())}))}catch(t){return Promise.reject(t)}}(0,e.token,e.docID)).then((function(r){var n=new w({conn:t,actor:e.guestReference,checkpoint:r.body,token:e.token,roomID:e.roomID});return Promise.resolve(n.reconnect()).then((function(){return n}))}))}))}catch(t){return Promise.reject(t)}}(r,0,e.auth,t)).then((function(r){return e.roomClients[t]=r,r}))}catch(t){return Promise.reject(t)}},t}();exports.RoomClient=w,exports.RoomService=D,exports.default=D;
//# sourceMappingURL=browser.cjs.production.min.js.map

@@ -522,18 +522,27 @@ import invariant from 'tiny-invariant';

var errNoInfiniteLoop = function errNoInfiniteLoop() {
return new Error('Infinite loop detected, see more: See more: https://err.sh/getroomservice/browser/infinite-loop');
};
var InnerListClient = /*#__PURE__*/function () {
function InnerListClient(checkpoint, roomID, docID, listID, ws, actor) {
// Map indexes to item ids
function InnerListClient(props) {
// If true, this client will throw an error if it's trying to
// mutate itself to prevent an infinite loop.
this.throwsOnMutate = false; // Map indexes to item ids
this.itemIDs = [];
this.roomID = roomID;
this.docID = docID;
this.id = listID;
this.ws = ws;
this.rt = new ReverseTree(actor);
!checkpoint.lists[listID] ? process.env.NODE_ENV !== "production" ? invariant(false, "Unknown listid '" + listID + "' in checkpoint.") : invariant(false) : void 0;
this.rt["import"](checkpoint, listID);
var list = checkpoint.lists[listID];
this.roomID = props.roomID;
this.docID = props.docID;
this.id = props.listID;
this.ws = props.ws;
this.rt = new ReverseTree(props.actor);
this.bus = props.bus;
this.actor = props.actor;
!props.checkpoint.lists[props.listID] ? process.env.NODE_ENV !== "production" ? invariant(false, "Unknown listid '" + props.listID + "' in checkpoint.") : invariant(false) : void 0;
this.rt["import"](props.checkpoint, props.listID);
var list = props.checkpoint.lists[props.listID];
var ids = list.ids || [];
for (var i = 0; i < ids.length; i++) {
var val = checkpoint.lists[listID].values[i];
var val = props.checkpoint.lists[props.listID].values[i];

@@ -544,3 +553,3 @@ if (typeof val === 'object' && val['t'] === '') {

this.itemIDs.push(unescapeID(checkpoint, ids[i]));
this.itemIDs.push(unescapeID(props.checkpoint, ids[i]));
}

@@ -552,2 +561,6 @@ }

_proto.sendCmd = function sendCmd(cmd) {
if (this.throwsOnMutate) {
throw errNoInfiniteLoop();
}
this.ws.send('doc:cmd', {

@@ -557,2 +570,8 @@ room: this.roomID,

});
this.throwsOnMutate = true;
this.bus.publish({
args: cmd,
from: this.actor
});
this.throwsOnMutate = false;
};

@@ -720,11 +739,16 @@

var InnerMapClient = /*#__PURE__*/function () {
function InnerMapClient(checkpoint, roomID, docID, mapID, ws) {
this.roomID = roomID;
this.docID = docID;
this.id = mapID;
this.ws = ws;
this.store = {}; // import
function InnerMapClient(props) {
// If true, this client will throw an error if it's trying to
// mutate itself to prevent an infinite loop.
this.throwsOnMutate = false;
this.roomID = props.roomID;
this.docID = props.docID;
this.id = props.mapID;
this.ws = props.ws;
this.store = {};
this.bus = props.bus;
this.actor = props.actor; // import
for (var k in checkpoint) {
var val = checkpoint[k];
for (var k in props.checkpoint) {
var val = props.checkpoint[k];

@@ -740,2 +764,6 @@ if (typeof val === 'string') {

_proto.sendCmd = function sendCmd(cmd) {
if (this.throwsOnMutate) {
throw errNoInfiniteLoop();
}
this.ws.send('doc:cmd', {

@@ -745,2 +773,8 @@ room: this.roomID,

});
this.throwsOnMutate = true;
this.bus.publish({
from: this.actor,
args: cmd
});
this.throwsOnMutate = false;
};

@@ -870,9 +904,9 @@

var InnerPresenceClient = /*#__PURE__*/function () {
function InnerPresenceClient(roomID, ws, actor, token) {
function InnerPresenceClient(props) {
var _this = this;
this.roomID = roomID;
this.ws = ws;
this.actor = actor;
this.token = token;
this.roomID = props.roomID;
this.ws = props.ws;
this.actor = props.actor;
this.token = props.token;
this.cache = {};

@@ -1046,2 +1080,31 @@

// 🚌
// Local pubsub, so that if you call .set in one place
// it will trigger a .subscribe elsewhere, without
// needing to go through the websockets
var LocalBus = /*#__PURE__*/function () {
function LocalBus() {
this.subs = new Set();
}
var _proto = LocalBus.prototype;
_proto.subscribe = function subscribe(fn) {
this.subs.add(fn);
return fn;
};
_proto.unsubscribe = function unsubscribe(fn) {
this.subs["delete"](fn);
};
_proto.publish = function publish(msg) {
this.subs.forEach(function (fn) {
fn(msg);
});
};
return LocalBus;
}();
var createRoom = function createRoom(conn, docsURL, authStrategy, room, document) {

@@ -1113,3 +1176,3 @@ try {

} else {
console.warn("Unhandled Room Service doc:fwd command: " + cmd + ". Consider updating the Room Service client.");
console.warn('Unhandled Room Service doc:fwd command: ' + cmd + '. Consider updating the Room Service client.');
}

@@ -1143,4 +1206,3 @@ });

if (!this.mapClients[objID]) {
var m = new InnerMapClient(this.checkpoint.maps[objID] || {}, this.roomID, this.docID, objID, this.ws);
this.mapClients[objID] = m;
this.createMapLocally(objID);
}

@@ -1159,4 +1221,3 @@

if (!this.listClients[objID]) {
var l = new InnerListClient(this.checkpoint, this.roomID, this.docID, objID, this.ws, this.actor);
this.listClients[objID] = l;
this.createListLocally(objID);
}

@@ -1272,2 +1333,22 @@

_proto.createListLocally = function createListLocally(name) {
var _this7 = this;
var bus = new LocalBus();
bus.subscribe(function (body) {
_this7.dispatchListCmd(name, body);
});
var l = new InnerListClient({
checkpoint: this.checkpoint,
roomID: this.roomID,
docID: this.docID,
listID: name,
ws: this.ws,
actor: this.actor,
bus: bus
});
this.listClients[name] = l;
return l;
};
_proto.list = function list(name) {

@@ -1292,7 +1373,25 @@ if (this.listClients[name]) {

var l = new InnerListClient(this.checkpoint, this.roomID, this.docID, name, this.ws, this.actor);
this.listClients[name] = l;
return l;
return this.createListLocally(name);
};
_proto.createMapLocally = function createMapLocally(name) {
var _this8 = this;
var bus = new LocalBus();
bus.subscribe(function (body) {
_this8.dispatchMapCmd(name, body);
});
var m = new InnerMapClient({
checkpoint: this.checkpoint.maps[name] || {},
roomID: this.roomID,
docID: this.docID,
mapID: name,
ws: this.ws,
bus: bus,
actor: this.actor
});
this.mapClients[name] = m;
return m;
};
_proto.map = function map(name) {

@@ -1311,5 +1410,3 @@ if (this.mapClients[name]) {

var m = new InnerMapClient(this.checkpoint.maps[name] || {}, this.roomID, this.docID, name, this.ws);
this.mapClients[name] = m;
return m;
return this.createMapLocally(name);
};

@@ -1322,3 +1419,8 @@

var p = new InnerPresenceClient(this.roomID, this.ws, this.actor, this.token);
var p = new InnerPresenceClient({
roomID: this.roomID,
ws: this.ws,
actor: this.actor,
token: this.token
});

@@ -1338,3 +1440,3 @@ try {

return this.subscribePresence(obj, onChangeFnOrString, onChangeFn);
} // create new closure so fns can be subscribed/unsubscribed multiple times
} // create new closure so fns can be subscribed/unsubscribed multiple times

@@ -1341,0 +1443,0 @@

import SuperlumeWebSocket from './ws';
import { ObjectClient, DocumentCheckpoint } from './types';
import { LocalBus } from './localbus';
export declare class InnerListClient<T extends any> implements ObjectClient {

@@ -8,5 +9,19 @@ private roomID;

private rt;
private bus;
private actor;
private throwsOnMutate;
private itemIDs;
id: string;
constructor(checkpoint: DocumentCheckpoint, roomID: string, docID: string, listID: string, ws: SuperlumeWebSocket, actor: string);
constructor(props: {
checkpoint: DocumentCheckpoint;
roomID: string;
docID: string;
listID: string;
ws: SuperlumeWebSocket;
actor: string;
bus: LocalBus<{
args: string[];
from: string;
}>;
});
private sendCmd;

@@ -13,0 +28,0 @@ private clone;

import { ObjectClient, MapCheckpoint } from './types';
import SuperlumeWebSocket from './ws';
import { LocalBus } from 'localbus';
export declare class InnerMapClient<T extends any> implements ObjectClient {

@@ -8,4 +9,18 @@ private roomID;

private store;
private bus;
private actor;
private throwsOnMutate;
id: string;
constructor(checkpoint: MapCheckpoint, roomID: string, docID: string, mapID: string, ws: SuperlumeWebSocket);
constructor(props: {
checkpoint: MapCheckpoint;
roomID: string;
docID: string;
mapID: string;
actor: string;
ws: SuperlumeWebSocket;
bus: LocalBus<{
from: string;
args: string[];
}>;
});
private sendCmd;

@@ -12,0 +27,0 @@ private clone;

@@ -11,3 +11,8 @@ import SuperlumeWebSocket from './ws';

private sendPres;
constructor(roomID: string, ws: SuperlumeWebSocket, actor: string, token: string);
constructor(props: {
roomID: string;
ws: SuperlumeWebSocket;
actor: string;
token: string;
});
/**

@@ -14,0 +19,0 @@ * Gets all values for an identifier, organized by user id.

@@ -5,3 +5,3 @@ import { WebSocketLikeConnection, DocumentCheckpoint, AuthStrategy, Prop } from './types';

import { InnerPresenceClient } from './PresenceClient';
import { WebSocketServerMessage } from 'wsMessages';
import { WebSocketServerMessage } from './wsMessages';
declare type Listener = {

@@ -13,4 +13,5 @@ event?: Prop<WebSocketServerMessage, 'type'>;

declare type ListenerBundle = Array<Listener>;
declare type InternalFunctions = 'dangerouslyUpdateClientDirectly';
declare type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export declare type MapClient<T> = Omit<InnerMapClient<T>, 'dangerouslyUpdateClientDirectly' | 'id'>;
export declare type MapClient<T> = Omit<InnerMapClient<T>, InternalFunctions | 'id'>;
export declare type ListClient<T> = Omit<InnerListClient<T>, 'dangerouslyUpdateClientDirectly' | 'id'>;

@@ -46,3 +47,5 @@ export declare type PresenceClient = Omit<InnerPresenceClient, 'dangerouslyUpdateClientDirectly'>;

get me(): string;
private createListLocally;
list<T extends any>(name: string): ListClient<T>;
private createMapLocally;
map<T extends any>(name: string): MapClient<T>;

@@ -49,0 +52,0 @@ presence(): PresenceClient;

{
"version": "2.1.5-0",
"version": "2.1.5-1",
"license": "MIT",

@@ -15,3 +15,4 @@ "main": "dist/index.js",

"lint": "tsdx lint",
"prepare": "tsdx build"
"prepare": "tsdx build",
"fmt": "prettier -w ."
},

@@ -36,2 +37,3 @@ "peerDependencies": {},

"jest": "^24.9.0",
"prettier": "^2.1.2",
"ts-jest": "^24.2.0",

@@ -38,0 +40,0 @@ "tsdx": "^0.12.3",

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc