Socket
Socket
Sign inDemoInstall

@roomservice/browser

Package Overview
Dependencies
Maintainers
1
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 1.0.0-13-staging to 1.0.0

dist/versionstamp.d.ts

323

dist/browser.cjs.development.js

@@ -12,9 +12,64 @@ 'use strict';

// export const PRESENCE_URL = 'http://localhost:3454/presence';
// export const WS_URL = 'wss://super.roomservice.dev/ws';
// export const DOCS_URL = 'https://super.roomservice.dev/docs';
// export const PRESENCE_URL = 'https://super.roomservice.dev/presence';
var WS_URL = 'wss://super.stagingmcstagingface.com/ws';
var DOCS_URL = 'https://super.stagingmcstagingface.com/docs';
var PRESENCE_URL = 'https://super.stagingmcstagingface.com/presence';
var WS_URL = 'wss://super.roomservice.dev/ws';
var DOCS_URL = 'https://super.roomservice.dev/docs';
var PRESENCE_URL = 'https://super.roomservice.dev/presence';
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
var SuperlumeWebSocket = /*#__PURE__*/function () {

@@ -52,2 +107,4 @@ function SuperlumeWebSocket(conn) {

_proto.send = function send(msgType, body) {
var _this2 = this;
var ts = this.timestamp();

@@ -59,3 +116,12 @@ var msg = {

body: body
};
}; // If the client is connecting, buffer a bit and retry
if (this.conn.readyState === this.conn.CONNECTING) {
setTimeout(function () {
// @ts-ignore
_this2.send(msgType, body);
}, 100 + Math.random() * 100);
return;
}
this.conn.send(JSON.stringify(msg));

@@ -96,2 +162,5 @@ };

method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({

@@ -192,3 +261,20 @@ resources: [{

})).then(function (res) {
return Promise.resolve(res.json());
return Promise.resolve(res.json()).then(function (doc) {
// Parse JSON values
for (var k in doc) {
if (typeof doc[k].value === 'string') {
var json = void 0;
try {
json = JSON.parse(doc[k].value);
} catch (err) {}
if (json) {
doc[k].value = json;
}
}
}
return doc;
});
});

@@ -200,60 +286,2 @@ } catch (e) {

function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
function unescapeID(checkpoint, id) {

@@ -346,2 +374,3 @@ if (id === 'root') return 'root';

_proto["delete"] = function _delete(itemID) {
if (!this.nodes[itemID]) return;
this.nodes[itemID].value = {

@@ -468,10 +497,6 @@ t: ''

function escape(value) {
if (typeof value === 'number') return "" + value;else return "\"" + value + "\"";
return JSON.stringify(value);
}
function unescape$1(value) {
if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
return value.slice(1, value.length - 1);
}
return parseInt(value);
return JSON.parse(value);
}

@@ -494,2 +519,8 @@

for (var i = 0; i < ids.length; i++) {
var val = checkpoint.lists[listID].values[i];
if (typeof val === 'object' && val['t'] === '') {
continue; // skip tombstones
}
this.itemIDs.push(unescapeID(checkpoint, ids[i]));

@@ -509,6 +540,7 @@ }

_proto.clone = function clone() {
return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
var cl = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
return cl;
};
_proto.update = function update(cmd) {
_proto.dangerouslyUpdateClientDirectly = function dangerouslyUpdateClientDirectly(cmd) {
if (cmd.length < 3) {

@@ -531,2 +563,5 @@ throw new Error('Unexpected command: ' + cmd);

var insValue = cmd[5];
this.itemIDs.splice(this.itemIDs.findIndex(function (f) {
return f === insAfter;
}) + 1, 0, insItemID);
this.rt.insert(insAfter, insValue, insItemID);

@@ -544,2 +579,5 @@ break;

this.rt["delete"](delItemID);
this.itemIDs.splice(this.itemIDs.findIndex(function (f) {
return f === delItemID;
}), 1);
break;

@@ -575,3 +613,3 @@

if (!itemID) {
throw new Error('Unexpected');
throw new Error("Index '" + index + "' doesn't already exist. Try .push() or .insertAfter() instead.");
}

@@ -588,9 +626,18 @@

_proto["delete"] = function _delete(index) {
if (this.itemIDs.length === 0) {
return this.clone();
}
var itemID = this.itemIDs[index];
if (!itemID) return Object.assign({}, this); // Local
this.rt["delete"](itemID); // Remote
if (!itemID) {
console.warn('Unknown index: ', index, this.itemIDs);
return this.clone();
} // Local
this.rt["delete"](itemID);
this.itemIDs.splice(index, 1); // Remote
this.sendCmd(['ldel', this.docID, this.id, itemID]);
Object.assign(Object.create(Object.getPrototypeOf(this)), this);
return this.clone();

@@ -665,3 +712,3 @@ };

_proto.update = function update(cmd) {
_proto.dangerouslyUpdateClientDirectly = function dangerouslyUpdateClientDirectly(cmd) {
if (cmd.length < 3) {

@@ -795,3 +842,3 @@ throw new Error('Unexpected command: ' + cmd);

_proto.withoutExpiredAndSelf = function withoutExpiredAndSelf(key) {
var vals = {};
var result = {};

@@ -804,11 +851,34 @@ for (var actor in this.cache[key]) {

continue;
} // Remove self
}
result[actor] = obj.value;
}
if (this.actor == actor) {
delete vals[actor];
return result;
};
_proto.withoutActorOrExpired = function withoutActorOrExpired(actor) {
var result = {};
for (var key in this.cache) {
for (var a in this.cache[key]) {
var obj = this.cache[key][a];
if (!obj) continue; // remove this actor
if (a === actor && this.cache[key][a]) {
delete this.cache[key][a];
continue;
} // Remove expired
if (new Date() > obj.expAt) {
delete this.cache[key][a];
continue;
}
result[a] = obj.value;
}
}
return vals;
return result;
} // Deprecated

@@ -845,6 +915,10 @@ ;

_proto.update = function update(body) {
if (body.room !== this.roomID) return;
if (body.from === this.actor) return; // ignore validation msgs
_proto.dangerouslyUpdateClientDirectly = function dangerouslyUpdateClientDirectly(type, body) {
if (type === 'room:rm_guest') {
return this.withoutActorOrExpired(body.guest);
}
if (body.room !== this.roomID) return false;
if (body.from === this.actor) return false; // ignore validation msgs
var obj = {

@@ -874,2 +948,28 @@ expAt: new Date(body.expAt * 1000),

function base64toArrayBuffer(vs) {
var binary = window.atob(vs);
var len = binary.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
function isOlderVS(older, newer) {
if (!older) return true;
if (!newer) return false; // These are ALWAYS 10 bytes
var olderArr = new Uint8Array(base64toArrayBuffer(older).slice(0, 9));
var newerArr = new Uint8Array(base64toArrayBuffer(newer).slice(0, 9));
for (var i = 0; i < olderArr.byteLength; i++) {
if (newerArr[i] > olderArr[i]) return true;
if (newerArr[i] < olderArr[i]) return false;
}
return false;
}
var createRoom = function createRoom(conn, docsURL, authStrategy, room, document) {

@@ -905,2 +1005,3 @@ try {

this.checkpoint = params.checkpoint;
this.vs = this.checkpoint.vs;
}

@@ -1023,13 +1124,25 @@

!obj ? invariant(false, 'subscribe() expects the first argument to not be undefined.') : void 0;
var _bound = this.ws.bind('presence:fwd', function (body) {
var fwdListener = this.ws.bind('presence:fwd', function (body) {
if (body.room !== _this11.roomID) return;
if (body.key !== onChangeFnOrString) return;
if (body.from === _this11.actor) return;
var newObj = obj.update(body);
var newObj = obj.dangerouslyUpdateClientDirectly('presence:fwd', body);
if (!newObj) return;
!onChangeFn ? invariant(false) : void 0;
onChangeFn(newObj, body.from);
});
return _bound;
var leaveListener = this.ws.bind('room:rm_guest', function (body) {
if (body.room !== _this11.roomID) return;
var newObj = obj.dangerouslyUpdateClientDirectly('room:rm_guest', body);
if (!newObj) return;
!onChangeFn ? invariant(false) : void 0;
onChangeFn(newObj, body.guest);
});
return [{
event: 'presence:fwd',
fn: fwdListener
}, {
event: 'room:rm_guest',
fn: leaveListener
}];
} // Map and list handler

@@ -1046,5 +1159,7 @@

return;
} // Ignore validated commands
} // Ignore out of order version stamps
if (isOlderVS(body.vs, _this11.vs)) return; // Ignore validated commands
if (body.from === _this11.actor) return;

@@ -1056,12 +1171,26 @@ var _ref = [body.args[1], body.args[2]],

if (objID !== obj.id) return;
var newObj = obj.update(body.args);
_this11.vs = body.vs;
var newObj = obj.dangerouslyUpdateClientDirectly(body.args);
onChangeFnOrString(newObj, body.from);
});
return bound;
return [{
event: 'doc:fwd',
fn: bound
}];
};
_proto.unsubscribe = function unsubscribe(listener) {
this.ws.unbind('doc:fwd', listener);
_proto.unsubscribe = function unsubscribe(listeners) {
for (var _iterator = _createForOfIteratorHelperLoose(listeners), _step; !(_step = _iterator()).done;) {
var l = _step.value;
this.ws.unbind(l.event, l.fn);
}
};
_createClass(RoomClient, [{
key: "me",
get: function get() {
return this.actor;
}
}]);
return RoomClient;

@@ -1068,0 +1197,0 @@ }();

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=(t=require("tiny-invariant"))&&"object"==typeof t&&"default"in t?t.default:t,r=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.timestamp();this.conn.send(JSON.stringify({type:t,ts:r,ver:0,body:e}))},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 n(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 o(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),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)}function c(t,e){if("root"===e)return"root";var r=e.split(":");return r[0]+":"+t.actors[parseInt(r[1])]}var h=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],o=n.afters||[],i=n.ids||[],s=n.values||[],h=0;h<o.length;h++){var u={after:c(t,o[h]),id:c(t,i[h]),value:s[h]};this.nodes[u.id]=u,this.log.push(u)}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 o=n;o||(o=this.count+":"+this.actor),this.count++;var i={after:t,value:r,id:o};return this.nodes[o]=i,this.log.push(i),o},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].value={t:""}},r.toTree=function(){for(var t,e={children:[],id:"root",value:""},r={root:e},n=s(this.log);!(t=n()).done;){var o=t.value,i={children:[],id:o.id,value:o.value};if(r[o.id]=i,"root"===o.after)e.children.push(i);else{if(!r[o.after])throw new Error("Unexpectedly missing node "+o.after);r[o.after].children.push(i)}}return e},r.sortLog=function(){this.log.sort((function(t,e){var r=t.id.split(":"),n=r[0],o=r[1],i=e.id.split(":"),s=i[0];return n===s?o.localeCompare(i[1]):parseInt(n)-parseInt(s)}))},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.toArray=function(){return this.sortLog(),function t(e){if(!e.children||0===e.children.length)return[];for(var r,n=[],o=s(e.children);!(r=o()).done;){var i=r.value,c=i.value;if("string"!=typeof i.value){if(""===i.value.t){n=n.concat([].concat(t(i)));continue}throw new Error("Unimplemented")}n=n.concat([c].concat(t(i)))}return n}(this.toTree())},o(t,[{key:"length",get:function(){return Object.keys(this.nodes).length}}]),t}();function u(t){return"number"==typeof t?""+t:'"'+t+'"'}function a(t){return t.length>=2&&'"'===t[0]&&'"'===t[t.length-1]?t.slice(1,t.length-1):parseInt(t)}var d=function(){function t(t,r,n,o,i,s){this.itemIDs=[],this.roomID=r,this.docID=n,this.id=o,this.ws=i,this.rt=new h(s),t.lists[o]||e(!1),this.rt.import(t,o);for(var u=t.lists[o].ids||[],a=0;a<u.length;a++)this.itemIDs.push(c(t,u[a]))}var r=t.prototype;return r.sendCmd=function(t){this.ws.send("doc:cmd",{room:this.roomID,args:t})},r.clone=function(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)},r.update=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":this.rt.insert(t[3],t[5],t[4]);break;case"lput":this.rt.put(t[3],t[4]);break;case"ldel":this.rt.delete(t[3]);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 a(r)}}},r.set=function(t,e){var r=this.itemIDs[t];if(!r)throw new Error("Unexpected");var n=u(e);return this.rt.put(r,n),this.sendCmd(["lput",this.docID,this.id,r,n]),this.clone()},r.delete=function(t){var e=this.itemIDs[t];return e?(this.rt.delete(e),this.sendCmd(["ldel",this.docID,this.id,e]),Object.assign(Object.create(Object.getPrototypeOf(this)),this),this.clone()):Object.assign({},this)},r.insertAfter=function(t,e){var r=this.itemIDs[t];if(!r)throw new RangeError("List '"+this.id+"' has no index: '"+t+"'");var n=u(e),o=this.rt.insert(r,n);return this.itemIDs.splice(t,0,o),this.sendCmd(["lins",this.docID,this.id,r,o,n]),this.clone()},r.push=function(t){var e=this.rt.lastID(),r=u(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.toArray=function(){return this.rt.toArray().map((function(t){return a(t)}))},t}(),f=function(){function t(t,e,r,n,o){for(var i in this.roomID=e,this.docID=r,this.id=n,this.ws=o,this.store={},t){var s=t[i];"string"==typeof s&&(this.store[i]=unescape(s))}}var e=t.prototype;return e.sendCmd=function(t){this.ws.send("doc:cmd",{room:this.roomID,args:t})},e.clone=function(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)},e.update=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]]=unescape(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=u(e);return this.store[t]=e,this.sendCmd(["mput",this.docID,this.id,t,r]),this.clone()},e.delete=function(t){return delete this.store[t],this.sendCmd(["mdel",this.docID,this.id,t]),this.clone()},t}(),l=function(){function t(t,e,r,n){this.roomID=t,this.ws=e,this.actor=r,this.token=n,this.cache={},this.send=function(t,e,r){void 0===r&&(r=!1);var n=null,o=!0;return function(){var e=arguments,i=this,s=r&&o,c=function(){t.apply(i,e),n=null};s&&(o=!1,c()),n||(n=setTimeout(c,40))}}(this.ws.send.bind(this.ws))}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.stagingmcstagingface.com/presence/"+r+"/"+encodeURIComponent(n),{headers:{Authorization:"Bearer: "+e}})).then((function(t){return Promise.resolve(t.json())}))}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];new Date>n.expAt?delete this.cache[t][r]:this.actor==r&&delete e[r]}return e},e.set=function(t,e,r){var n=r||60,o=Math.round((new Date).getTime()/1e3)+n;return this.send("presence:cmd",{room:this.roomID,key:t,value:JSON.stringify(e),expAt:o}),this.cache[t]||(this.cache[t]={}),this.cache[t][this.actor]={value:e,expAt:new Date(1e3*o)},this.withoutExpiredAndSelf(t)},e.update=function(t){if(t.room===this.roomID&&t.from!==this.actor){var e={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]=e,this.withoutExpiredAndSelf(t.key)}},o(t,[{key:"me",get:function(){return console.warn("presence.me() is deprecated and will be removed in a future version!"),this.actor}}]),t}(),m=function(){function t(t){this.ws=new r(t.conn),this.token=t.token,this.roomID=t.roomID,this.docID=t.checkpoint.id,this.actor=t.actor,this.checkpoint=t.checkpoint}var n=t.prototype;return n.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)}},n.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)}},n.list=function(t){try{this.checkpoint.lists[t]||(this.ws.send("doc:cmd",{args:["lcreate",this.docID,t],room:this.roomID}),this.checkpoint.lists[t]={afters:[],ids:[],values:[]});var e=new d(this.checkpoint,this.roomID,this.docID,t,this.ws,this.actor);return Promise.resolve(e)}catch(t){return Promise.reject(t)}},n.map=function(t){try{this.checkpoint.maps[t]||this.ws.send("doc:cmd",{args:["mcreate",this.docID,t],room:this.roomID});var e=new f(this.checkpoint.maps[t]||{},this.roomID,this.docID,t,this.ws);return Promise.resolve(e)}catch(t){return Promise.reject(t)}},n.presence=function(){try{var t=new l(this.roomID,this.ws,this.actor,this.token);return Promise.resolve(t)}catch(t){return Promise.reject(t)}},n.subscribe=function(t,r,n){var o=this;return"string"==typeof r?(t||e(!1),this.ws.bind("presence:fwd",(function(i){if(i.room===o.roomID&&i.key===r&&i.from!==o.actor){var s=t.update(i);n||e(!1),n(s,i.from)}}))):this.ws.bind("doc:fwd",(function(e){if(e.room===o.roomID)if(!e.args||e.args.length<3)console.error("Unexpected command: ",e.args);else if(e.from!==o.actor){var n=[e.args[1],e.args[2]];if(n[0]===o.docID&&n[1]===t.id){var i=t.update(e.args);r(i,e.from)}}}))},n.unsubscribe=function(t){this.ws.unbind("doc:fwd",t)},t}();exports.RoomService=function(){function t(t){this.auth=t.auth}return t.prototype.room=function(t){try{var e=new WebSocket("wss://super.stagingmcstagingface.com/ws");return Promise.resolve(function(t,e,r,n,o){try{return Promise.resolve(function(t,e,r){try{var n=function(r){if(o)return r;var n=t;return Promise.resolve(fetch(n,{method:"POST",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("AuthURL returned unauthorized");return Promise.resolve(t.json()).then((function(t){var e=t.token,r=t.user,o=t.resources;if(!o||!e||!r)throw new Error("Invalid response from the AuthURL: "+n);return{token:e,guestReference:r,docID:o.find((function(t){return"document"===t.object})).id,roomID:o.find((function(t){return"room"===t.object})).id}}))}))},o=!1,i=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 o=!0,{token:t.token,guestReference:t.user,docID:e,roomID:r}}))}();return Promise.resolve(i&&i.then?i.then(n):n(i))}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.stagingmcstagingface.com/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 m({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)}}(e,0,this.auth,t))}catch(t){return Promise.reject(t)}},t}();
"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 o(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 s=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 u=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||[],o=n.ids||[],s=n.values||[],u=0;u<i.length;u++){var h={after:c(t,i[u]),id:c(t,o[u]),value:s[u]};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 o={after:t,value:r,id:i};return this.nodes[i]=o,this.log.push(o),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=o(this.log);!(t=n()).done;){var i=t.value,s={children:[],id:i.id,value:i.value};if(r[i.id]=s,"root"===i.after)e.children.push(s);else{if(!r[i.after])throw new Error("Unexpectedly missing node "+i.after);r[i.after].children.push(s)}}return e},r.sortLog=function(){this.log.sort((function(t,e){var r=t.id.split(":"),n=r[0],i=r[1],o=e.id.split(":"),s=o[0];return n===s?i.localeCompare(o[1]):parseInt(n)-parseInt(s)}))},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.toArray=function(){return this.sortLog(),function t(e){if(!e.children||0===e.children.length)return[];for(var r,n=[],i=o(e.children);!(r=i()).done;){var s=r.value,c=s.value;if("string"!=typeof s.value){if(""===s.value.t){n=n.concat([].concat(t(s)));continue}throw new Error("Unimplemented")}n=n.concat([c].concat(t(s)))}return n}(this.toTree())},n(t,[{key:"length",get:function(){return Object.keys(this.nodes).length}}]),t}();function h(t){return JSON.stringify(t)}function a(t){return JSON.parse(t)}var d=function(){function t(t,r,n,i,o,s){this.itemIDs=[],this.roomID=r,this.docID=n,this.id=i,this.ws=o,this.rt=new u(s),t.lists[i]||e(!1),this.rt.import(t,i);for(var h=t.lists[i].ids||[],a=0;a<h.length;a++){var d=t.lists[i].values[a];"object"==typeof d&&""===d.t||this.itemIDs.push(c(t,h[a]))}}var r=t.prototype;return r.sendCmd=function(t){this.ws.send("doc:cmd",{room:this.roomID,args:t})},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 o=t[3];this.rt.delete(o),this.itemIDs.splice(this.itemIDs.findIndex((function(t){return t===o})),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 a(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.push=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.toArray=function(){return this.rt.toArray().map((function(t){return a(t)}))},t}(),f=function(){function t(t,e,r,n,i){for(var o in this.roomID=e,this.docID=r,this.id=n,this.ws=i,this.store={},t){var s=t[o];"string"==typeof s&&(this.store[o]=unescape(s))}}var e=t.prototype;return e.sendCmd=function(t){this.ws.send("doc:cmd",{room:this.roomID,args:t})},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]]=unescape(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.delete=function(t){return delete this.store[t],this.sendCmd(["mdel",this.docID,this.id,t]),this.clone()},t}(),l=function(){function t(t,e,r,n){this.roomID=t,this.ws=e,this.actor=r,this.token=n,this.cache={},this.send=function(t,e,r){void 0===r&&(r=!1);var n=null,i=!0;return function(){var e=arguments,o=this,s=r&&i,c=function(){t.apply(o,e),n=null};s&&(i=!1,c()),n||(n=setTimeout(c,40))}}(this.ws.send.bind(this.ws))}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];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.send("presence:cmd",{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(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 m(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(t){this.ws=new s(t.conn),this.token=t.token,this.roomID=t.roomID,this.docID=t.checkpoint.id,this.actor=t.actor,this.checkpoint=t.checkpoint,this.vs=this.checkpoint.vs}var r=t.prototype;return 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.list=function(t){try{this.checkpoint.lists[t]||(this.ws.send("doc:cmd",{args:["lcreate",this.docID,t],room:this.roomID}),this.checkpoint.lists[t]={afters:[],ids:[],values:[]});var e=new d(this.checkpoint,this.roomID,this.docID,t,this.ws,this.actor);return Promise.resolve(e)}catch(t){return Promise.reject(t)}},r.map=function(t){try{this.checkpoint.maps[t]||this.ws.send("doc:cmd",{args:["mcreate",this.docID,t],room:this.roomID});var e=new f(this.checkpoint.maps[t]||{},this.roomID,this.docID,t,this.ws);return Promise.resolve(e)}catch(t){return Promise.reject(t)}},r.presence=function(){try{var t=new l(this.roomID,this.ws,this.actor,this.token);return Promise.resolve(t)}catch(t){return Promise.reject(t)}},r.subscribe=function(t,r,n){var i=this;return"string"==typeof r?(t||e(!1),[{event:"presence:fwd",fn:this.ws.bind("presence:fwd",(function(o){if(o.room===i.roomID&&o.key===r&&o.from!==i.actor){var s=t.dangerouslyUpdateClientDirectly("presence:fwd",o);s&&(n||e(!1),n(s,o.from))}}))},{event:"room:rm_guest",fn:this.ws.bind("room:rm_guest",(function(r){if(r.room===i.roomID){var o=t.dangerouslyUpdateClientDirectly("room:rm_guest",r);o&&(n||e(!1),n(o,r.guest))}}))}]):[{event:"doc:fwd",fn:this.ws.bind("doc:fwd",(function(e){if(e.room===i.roomID)if(!e.args||e.args.length<3)console.error("Unexpected command: ",e.args);else if(!function(t,e){if(!t)return!0;if(!e)return!1;for(var r=new Uint8Array(m(t).slice(0,9)),n=new Uint8Array(m(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}(e.vs,i.vs)&&e.from!==i.actor){var n=[e.args[1],e.args[2]];if(n[0]===i.docID&&n[1]===t.id){i.vs=e.vs;var o=t.dangerouslyUpdateClientDirectly(e.args);r(o,e.from)}}}))}]},r.unsubscribe=function(t){for(var e,r=o(t);!(e=r()).done;){var n=e.value;this.ws.unbind(n.event,n.fn)}},n(t,[{key:"me",get:function(){return this.actor}}]),t}();exports.RoomService=function(){function t(t){this.auth=t.auth}return t.prototype.room=function(t){try{var e=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){if(i)return r;var n=t;return Promise.resolve(fetch(n,{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("AuthURL returned unauthorized");return Promise.resolve(t.json()).then((function(t){var e=t.token,r=t.user,i=t.resources;if(!i||!e||!r)throw new Error("Invalid response from the AuthURL: "+n);return{token:e,guestReference:r,docID:i.find((function(t){return"document"===t.object})).id,roomID:i.find((function(t){return"room"===t.object})).id}}))}))},i=!1,o=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(o&&o.then?o.then(n):n(o))}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 v({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)}}(e,0,this.auth,t))}catch(t){return Promise.reject(t)}},t}();
//# sourceMappingURL=browser.cjs.production.min.js.map

@@ -6,9 +6,64 @@ import invariant from 'tiny-invariant';

// export const PRESENCE_URL = 'http://localhost:3454/presence';
// export const WS_URL = 'wss://super.roomservice.dev/ws';
// export const DOCS_URL = 'https://super.roomservice.dev/docs';
// export const PRESENCE_URL = 'https://super.roomservice.dev/presence';
var WS_URL = 'wss://super.stagingmcstagingface.com/ws';
var DOCS_URL = 'https://super.stagingmcstagingface.com/docs';
var PRESENCE_URL = 'https://super.stagingmcstagingface.com/presence';
var WS_URL = 'wss://super.roomservice.dev/ws';
var DOCS_URL = 'https://super.roomservice.dev/docs';
var PRESENCE_URL = 'https://super.roomservice.dev/presence';
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
var SuperlumeWebSocket = /*#__PURE__*/function () {

@@ -46,2 +101,4 @@ function SuperlumeWebSocket(conn) {

_proto.send = function send(msgType, body) {
var _this2 = this;
var ts = this.timestamp();

@@ -53,3 +110,12 @@ var msg = {

body: body
};
}; // If the client is connecting, buffer a bit and retry
if (this.conn.readyState === this.conn.CONNECTING) {
setTimeout(function () {
// @ts-ignore
_this2.send(msgType, body);
}, 100 + Math.random() * 100);
return;
}
this.conn.send(JSON.stringify(msg));

@@ -90,2 +156,5 @@ };

method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({

@@ -186,3 +255,20 @@ resources: [{

})).then(function (res) {
return Promise.resolve(res.json());
return Promise.resolve(res.json()).then(function (doc) {
// Parse JSON values
for (var k in doc) {
if (typeof doc[k].value === 'string') {
var json = void 0;
try {
json = JSON.parse(doc[k].value);
} catch (err) {}
if (json) {
doc[k].value = json;
}
}
}
return doc;
});
});

@@ -194,60 +280,2 @@ } catch (e) {

function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
function unescapeID(checkpoint, id) {

@@ -340,2 +368,3 @@ if (id === 'root') return 'root';

_proto["delete"] = function _delete(itemID) {
if (!this.nodes[itemID]) return;
this.nodes[itemID].value = {

@@ -462,10 +491,6 @@ t: ''

function escape(value) {
if (typeof value === 'number') return "" + value;else return "\"" + value + "\"";
return JSON.stringify(value);
}
function unescape$1(value) {
if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
return value.slice(1, value.length - 1);
}
return parseInt(value);
return JSON.parse(value);
}

@@ -488,2 +513,8 @@

for (var i = 0; i < ids.length; i++) {
var val = checkpoint.lists[listID].values[i];
if (typeof val === 'object' && val['t'] === '') {
continue; // skip tombstones
}
this.itemIDs.push(unescapeID(checkpoint, ids[i]));

@@ -503,6 +534,7 @@ }

_proto.clone = function clone() {
return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
var cl = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
return cl;
};
_proto.update = function update(cmd) {
_proto.dangerouslyUpdateClientDirectly = function dangerouslyUpdateClientDirectly(cmd) {
if (cmd.length < 3) {

@@ -525,2 +557,5 @@ throw new Error('Unexpected command: ' + cmd);

var insValue = cmd[5];
this.itemIDs.splice(this.itemIDs.findIndex(function (f) {
return f === insAfter;
}) + 1, 0, insItemID);
this.rt.insert(insAfter, insValue, insItemID);

@@ -538,2 +573,5 @@ break;

this.rt["delete"](delItemID);
this.itemIDs.splice(this.itemIDs.findIndex(function (f) {
return f === delItemID;
}), 1);
break;

@@ -569,3 +607,3 @@

if (!itemID) {
throw new Error('Unexpected');
throw new Error("Index '" + index + "' doesn't already exist. Try .push() or .insertAfter() instead.");
}

@@ -582,9 +620,18 @@

_proto["delete"] = function _delete(index) {
if (this.itemIDs.length === 0) {
return this.clone();
}
var itemID = this.itemIDs[index];
if (!itemID) return Object.assign({}, this); // Local
this.rt["delete"](itemID); // Remote
if (!itemID) {
console.warn('Unknown index: ', index, this.itemIDs);
return this.clone();
} // Local
this.rt["delete"](itemID);
this.itemIDs.splice(index, 1); // Remote
this.sendCmd(['ldel', this.docID, this.id, itemID]);
Object.assign(Object.create(Object.getPrototypeOf(this)), this);
return this.clone();

@@ -659,3 +706,3 @@ };

_proto.update = function update(cmd) {
_proto.dangerouslyUpdateClientDirectly = function dangerouslyUpdateClientDirectly(cmd) {
if (cmd.length < 3) {

@@ -789,3 +836,3 @@ throw new Error('Unexpected command: ' + cmd);

_proto.withoutExpiredAndSelf = function withoutExpiredAndSelf(key) {
var vals = {};
var result = {};

@@ -798,11 +845,34 @@ for (var actor in this.cache[key]) {

continue;
} // Remove self
}
result[actor] = obj.value;
}
if (this.actor == actor) {
delete vals[actor];
return result;
};
_proto.withoutActorOrExpired = function withoutActorOrExpired(actor) {
var result = {};
for (var key in this.cache) {
for (var a in this.cache[key]) {
var obj = this.cache[key][a];
if (!obj) continue; // remove this actor
if (a === actor && this.cache[key][a]) {
delete this.cache[key][a];
continue;
} // Remove expired
if (new Date() > obj.expAt) {
delete this.cache[key][a];
continue;
}
result[a] = obj.value;
}
}
return vals;
return result;
} // Deprecated

@@ -839,6 +909,10 @@ ;

_proto.update = function update(body) {
if (body.room !== this.roomID) return;
if (body.from === this.actor) return; // ignore validation msgs
_proto.dangerouslyUpdateClientDirectly = function dangerouslyUpdateClientDirectly(type, body) {
if (type === 'room:rm_guest') {
return this.withoutActorOrExpired(body.guest);
}
if (body.room !== this.roomID) return false;
if (body.from === this.actor) return false; // ignore validation msgs
var obj = {

@@ -868,2 +942,28 @@ expAt: new Date(body.expAt * 1000),

function base64toArrayBuffer(vs) {
var binary = window.atob(vs);
var len = binary.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
function isOlderVS(older, newer) {
if (!older) return true;
if (!newer) return false; // These are ALWAYS 10 bytes
var olderArr = new Uint8Array(base64toArrayBuffer(older).slice(0, 9));
var newerArr = new Uint8Array(base64toArrayBuffer(newer).slice(0, 9));
for (var i = 0; i < olderArr.byteLength; i++) {
if (newerArr[i] > olderArr[i]) return true;
if (newerArr[i] < olderArr[i]) return false;
}
return false;
}
var createRoom = function createRoom(conn, docsURL, authStrategy, room, document) {

@@ -899,2 +999,3 @@ try {

this.checkpoint = params.checkpoint;
this.vs = this.checkpoint.vs;
}

@@ -1017,13 +1118,25 @@

!obj ? process.env.NODE_ENV !== "production" ? invariant(false, 'subscribe() expects the first argument to not be undefined.') : invariant(false) : void 0;
var _bound = this.ws.bind('presence:fwd', function (body) {
var fwdListener = this.ws.bind('presence:fwd', function (body) {
if (body.room !== _this11.roomID) return;
if (body.key !== onChangeFnOrString) return;
if (body.from === _this11.actor) return;
var newObj = obj.update(body);
var newObj = obj.dangerouslyUpdateClientDirectly('presence:fwd', body);
if (!newObj) return;
!onChangeFn ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
onChangeFn(newObj, body.from);
});
return _bound;
var leaveListener = this.ws.bind('room:rm_guest', function (body) {
if (body.room !== _this11.roomID) return;
var newObj = obj.dangerouslyUpdateClientDirectly('room:rm_guest', body);
if (!newObj) return;
!onChangeFn ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
onChangeFn(newObj, body.guest);
});
return [{
event: 'presence:fwd',
fn: fwdListener
}, {
event: 'room:rm_guest',
fn: leaveListener
}];
} // Map and list handler

@@ -1040,5 +1153,7 @@

return;
} // Ignore validated commands
} // Ignore out of order version stamps
if (isOlderVS(body.vs, _this11.vs)) return; // Ignore validated commands
if (body.from === _this11.actor) return;

@@ -1050,12 +1165,26 @@ var _ref = [body.args[1], body.args[2]],

if (objID !== obj.id) return;
var newObj = obj.update(body.args);
_this11.vs = body.vs;
var newObj = obj.dangerouslyUpdateClientDirectly(body.args);
onChangeFnOrString(newObj, body.from);
});
return bound;
return [{
event: 'doc:fwd',
fn: bound
}];
};
_proto.unsubscribe = function unsubscribe(listener) {
this.ws.unbind('doc:fwd', listener);
_proto.unsubscribe = function unsubscribe(listeners) {
for (var _iterator = _createForOfIteratorHelperLoose(listeners), _step; !(_step = _iterator()).done;) {
var l = _step.value;
this.ws.unbind(l.event, l.fn);
}
};
_createClass(RoomClient, [{
key: "me",
get: function get() {
return this.actor;
}
}]);
return RoomClient;

@@ -1062,0 +1191,0 @@ }();

@@ -1,3 +0,3 @@

export declare const WS_URL = "wss://super.stagingmcstagingface.com/ws";
export declare const DOCS_URL = "https://super.stagingmcstagingface.com/docs";
export declare const PRESENCE_URL = "https://super.stagingmcstagingface.com/presence";
export declare const WS_URL = "wss://super.roomservice.dev/ws";
export declare const DOCS_URL = "https://super.roomservice.dev/docs";
export declare const PRESENCE_URL = "https://super.roomservice.dev/presence";

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

export declare function escape(value: number | string): string;
export declare function unescape(value: string): string | number;
export declare function escape(value: number | string | object): string;
export declare function unescape(value: string): string | number | object;

@@ -13,9 +13,9 @@ import SuperlumeWebSocket from './ws';

private clone;
update(cmd: string[]): ListClient;
get(index: number): string | number | undefined;
set(index: number, val: string | number): ListClient;
dangerouslyUpdateClientDirectly(cmd: string[]): ListClient;
get(index: number): string | number | object | undefined;
set(index: number, val: string | number | object): ListClient;
delete(index: number): ListClient;
insertAfter(index: number, val: string | number): ListClient;
push(val: string | number): ListClient;
toArray(): (string | number)[];
insertAfter(index: number, val: string | number | object): ListClient;
push(val: string | number | object): ListClient;
toArray(): any[];
}

@@ -12,6 +12,6 @@ import { ObjectClient, MapCheckpoint } from './types';

private clone;
update(cmd: string[]): MapClient;
get(key: string): string | number;
set(key: string, value: string | number): MapClient;
dangerouslyUpdateClientDirectly(cmd: string[]): MapClient;
get(key: string): string | number | object;
set(key: string, value: string | number | object): MapClient;
delete(key: string): MapClient;
}
import SuperlumeWebSocket from './ws';
import { Prop } from './types';
import { WebSocketPresenceFwdMessage } from './wsMessages';
import { WebSocketPresenceFwdMessage, WebSocketLeaveMessage } from './wsMessages';
export declare class PresenceClient {

@@ -20,2 +20,3 @@ private roomID;

private withoutExpiredAndSelf;
private withoutActorOrExpired;
get me(): string;

@@ -31,3 +32,8 @@ /**

};
update(body: Prop<WebSocketPresenceFwdMessage, 'body'>): any;
dangerouslyUpdateClientDirectly(type: 'room:rm_guest', body: Prop<WebSocketLeaveMessage, 'body'>): {
[key: string]: any;
};
dangerouslyUpdateClientDirectly(type: 'presence:fwd', body: Prop<WebSocketPresenceFwdMessage, 'body'>): {
[key: string]: any;
};
}

@@ -1,8 +0,14 @@

import { WebSocketLikeConnection, DocumentCheckpoint, AuthStrategy } from './types';
import { WebSocketLikeConnection, DocumentCheckpoint, AuthStrategy, Prop } from './types';
import { ListClient } from './ListClient';
import { MapClient } from './MapClient';
import { PresenceClient } from './PresenceClient';
declare type Listener = (args: any) => void;
import { WebSocketServerMessage } from 'wsMessages';
declare type Listener = {
event: Prop<WebSocketServerMessage, 'type'>;
fn: (args: any) => void;
};
declare type ListenerBundle = Array<Listener>;
export declare class RoomClient {
private ws;
private vs;
private token;

@@ -26,15 +32,16 @@ private roomID;

reconnect(): Promise<void>;
get me(): string;
list(name: string): Promise<ListClient>;
map(name: string): Promise<MapClient>;
presence(): Promise<PresenceClient>;
subscribe(list: ListClient, onChangeFn: (list: ListClient) => any): Listener;
subscribe(list: ListClient, onChangeFn: (list: ListClient, from: string) => any): Listener;
subscribe(map: MapClient, onChangeFn: (map: MapClient) => {}): Listener;
subscribe(map: MapClient, onChangeFn: (map: MapClient, from: string) => any): Listener;
subscribe(list: ListClient, onChangeFn: (list: ListClient) => any): ListenerBundle;
subscribe(list: ListClient, onChangeFn: (list: ListClient, from: string) => any): ListenerBundle;
subscribe(map: MapClient, onChangeFn: (map: MapClient) => {}): ListenerBundle;
subscribe(map: MapClient, onChangeFn: (map: MapClient, from: string) => any): ListenerBundle;
subscribe<T extends any>(presence: PresenceClient, key: string, onChangeFn: (obj: {
[key: string]: T;
}, from: string) => any): Listener;
unsubscribe(listener: Listener): void;
}, from: string) => any): ListenerBundle;
unsubscribe(listeners: ListenerBundle): void;
}
export declare function createRoom(conn: WebSocketLikeConnection, docsURL: string, authStrategy: AuthStrategy, room: string, document: string): Promise<RoomClient>;
export {};

@@ -22,2 +22,3 @@ import ReverseTree from './ReverseTree';

api_version: number;
vs: string;
actors: {

@@ -75,6 +76,4 @@ [key: number]: string;

}
export interface WebSocketLikeConnection {
onmessage: (ev: MessageEvent) => any;
send: (data: any) => any;
}
declare type RequireSome<T, K extends keyof T> = Partial<Omit<T, K>> & Required<Pick<T, K>>;
export declare type WebSocketLikeConnection = RequireSome<WebSocket, 'send' | 'onmessage'>;
export interface DocumentContext {

@@ -96,3 +95,3 @@ lists: {

id: string;
update(msg: any): ObjectClient;
dangerouslyUpdateClientDirectly(msg: any): ObjectClient;
}

@@ -99,0 +98,0 @@ export interface Resource {

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

import { WebSocketDocFwdMessage, WebSocketDocCmdMessage, WebSocketPresenceCmdMessage, WebSocketPresenceFwdMessage } from './wsMessages';
import { WebSocketDocFwdMessage, WebSocketDocCmdMessage, WebSocketPresenceCmdMessage, WebSocketPresenceFwdMessage, WebSocketLeaveMessage, WebSocketJoinMessage } from './wsMessages';
import { WebSocketLikeConnection, Prop } from 'types';

@@ -11,6 +11,7 @@ declare type Cb = (body: any) => void;

private timestamp;
send(msgType: 'room:join', room: string): void;
send(msgType: 'room:join', room: Prop<WebSocketJoinMessage, 'body'>): void;
send(msgType: 'guest:authenticate', token: string): void;
send(msgType: 'doc:cmd', body: Prop<WebSocketDocCmdMessage, 'body'>): void;
send(msgType: 'presence:cmd', body: Prop<WebSocketPresenceCmdMessage, 'body'>): void;
bind(msgType: 'room:rm_guest', callback: (body: Prop<WebSocketLeaveMessage, 'body'>) => void): Cb;
bind(msgType: 'room:joined', callback: (body: string) => void): Cb;

@@ -17,0 +18,0 @@ bind(msgType: 'doc:fwd', callback: (body: Prop<WebSocketDocFwdMessage, 'body'>) => void): Cb;

@@ -38,2 +38,3 @@ export interface WebSocketAuthenticateMessage {

room: string;
vs: string;
args: string[];

@@ -53,2 +54,10 @@ };

}
export interface WebSocketLeaveMessage {
ver: number;
type: 'room:rm_guest';
body: {
guest: string;
room: string;
};
}
export interface WebSocketPresenceFwdMessage {

@@ -73,3 +82,3 @@ ver: number;

}
export declare type WebSocketServerMessage = WebSocketAuthenticatedMessage | WebSocketDocFwdMessage | WebSocketPresenceFwdMessage | WebSocketJoinedMessage | WebSocketErrorMessage;
export declare type WebSocketServerMessage = WebSocketAuthenticatedMessage | WebSocketDocFwdMessage | WebSocketPresenceFwdMessage | WebSocketJoinedMessage | WebSocketErrorMessage | WebSocketLeaveMessage;
export declare type WebSocketClientMessage = WebSocketAuthenticateMessage | WebSocketDocCmdMessage | WebSocketPresenceCmdMessage | WebSocketJoinMessage;
{
"version": "1.0.0-13-staging",
"version": "1.0.0",
"license": "MIT",

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

@@ -14,3 +14,3 @@ <p align="center">

```bash
npm install --save @roomservice/browser
npm install --save @roomservice/browser@1.0.0-21
```

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