/** * yjs - A framework for real-time p2p shared editing on any data * @version v13.0.0-18 * @license MIT */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.Y=e()}(this,function(){"use strict";function t(t,e){return e={exports:{}},t(e,e.exports),e.exports}function e(t){var e=new E(t);e.readVarString();var n=e.readVarString(),i=[];return i.push("\n === "+n+" ===\n"),"update"===n?r(e,i):"sync step 1"===n?o(e,i):"sync step 2"===n?h(e,i):i.push("-- Unknown message type - probably an encoding issue!!!"),i.join("")}function n(t){var e=new E(t);return e.readVarString(),e.readVarString()}function r(t,e){for(var n=t.readUint32(),r=0;r0&&(n.y.db.forwardAppliedOperations&&n.broadcastOps(s),n.y.persistence&&n.y.persistence.saveOperations(s)),t.pos=r}n.y.db.applyOperations(t)}function s(t,e){t.y.db.requestTransaction(function(){var n=new U;n.writeVarString(t.opts.room||""),n.writeVarString("sync step 1"),n.writeVarString(t.authInfo||""),n.writeVarUint(t.protocolVersion);var r=t.preferUntransformed&&0===this.os.length;n.writeUint8(r?1:0),this.writeStateSet(n),t.send(e,n.createBuffer())})}function o(t,e){var n=t.readVarString(),r=t.readVarUint(),i=1===t.readUint8();e.push('\n - auth: "'+n+'"\n - protocolVersion: '+r+"\n - preferUntransformed: "+i+"\n"),l(t,e)}function a(t,e,n,r,i){var o=t.readVarUint(),a=1===t.readUint8();return o!==n.protocolVersion&&(console.warn("You tried to sync with a yjs instance that has a different protocol version\n (You: "+o+", Client: "+o+").\n The sync was stopped. You need to upgrade your dependencies (especially Yjs & the Connector)!\n "),n.y.destroy()),n.y.db.whenTransactionsFinished().then(function(){return n.y.db.requestTransaction(function(){e.writeVarString("sync step 2"),e.writeVarString(n.authInfo||""),a?(e.writeUint8(1),this.writeOperationsUntransformed(e)):(e.writeUint8(0),this.writeOperations(e,t)),this.writeDeleteSet(e),n.send(r.uid,e.createBuffer()),r.receivedSyncStep2=!0}),n.y.db.whenTransactionsFinished().then(function(){"slave"===n.role&&s(n,i)})})}function l(t,e){e.push(" == SS: \n");for(var n=t.readUint32(),r=0;r100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*j;case"days":case"day":case"d":return n*N;case"hours":case"hour":case"hrs":case"hr":case"h":return n*V;case"minutes":case"minute":case"mins":case"min":case"m":return n*x;case"seconds":case"second":case"secs":case"sec":case"s":return n*P;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function g(t){return t>=N?Math.round(t/N)+"d":t>=V?Math.round(t/V)+"h":t>=x?Math.round(t/x)+"m":t>=P?Math.round(t/P)+"s":t+"ms"}function v(t){return y(t,N,"day")||y(t,V,"hour")||y(t,x,"minute")||y(t,P,"second")||t+" ms"}function y(t,e,n){if(!(t=0&&setTimeout(function(){i||(r(new Error("Yjs init timeout")),e.destroy())},t.timeout),null!=e.persistence&&e.persistence.retrieveContent(),e.db.whenUserIdSet(function(){e.init(function(){i=!0,n(e)},r)})}).catch(r))})}String.fromCodePoint||function(){var t=function(){try{var t={},e=Object.defineProperty,n=e(t,t,t)&&e}catch(t){}return n}(),e=String.fromCharCode,n=Math.floor,r=function(t){var r,i,s=[],o=-1,a=arguments.length;if(!a)return"";for(var l="";++o1114111||n(u)!=u)throw RangeError("Invalid code point: "+u);u<=65535?s.push(u):(u-=65536,r=55296+(u>>10),i=u%1024+56320,s.push(r,i)),(o+1==a||s.length>16384)&&(l+=e.apply(null,s),s.length=0)}return l};t?t(String,"fromCodePoint",{value:r,configurable:!0,writable:!0}):String.fromCodePoint=r}(),String.prototype.codePointAt||function(){var t=function(){try{var t={},e=Object.defineProperty,n=e(t,t,t)&&e}catch(t){}return n}(),e=function(t){if(null==this)throw TypeError();var e=String(this),n=e.length,r=t?Number(t):0;if(r!=r&&(r=0),!(r<0||r>=n)){var i,s=e.charCodeAt(r);return s>=55296&&s<=56319&&n>r+1&&(i=e.charCodeAt(r+1))>=56320&&i<=57343?1024*(s-55296)+i-56320+65536:s}};t?t(String.prototype,"codePointAt",{value:e,configurable:!0,writable:!0}):String.prototype.codePointAt=e}();var b=t(function(t){t.require;var e={isNotUTF8:function(t,n,r){try{e.getStringFromBytes(t,n,r,!0)}catch(t){return!0}return!1},getCharLength:function(t){return 240==(240&t)?4:224==(224&t)?3:192==(192&t)?2:t==(127&t)?1:0},getCharCode:function(t,n,r){var i=0,s="";if(n=n||0,0==(r=r||e.getCharLength(t[n])))throw new Error(t[n].toString(2)+" is not a significative byte (offset:"+n+").");if(1===r)return t[n];if(s="00000000".slice(0,r)+1+"00000000".slice(r+1),t[n]&parseInt(s,2))throw Error("Index "+n+": A "+r+" bytes encoded char cannot encode the "+(r+1)+"th rank bit to 1.");for(s="0000".slice(0,r+1)+"11111111".slice(r+1),i+=(t[n]&parseInt(s,2))<<6*--r;r;){if(128!=(128&t[n+1])||64==(64&t[n+1]))throw Error("Index "+(n+1)+': Next bytes of encoded char must begin with a "10" bit sequence.');i+=(63&t[++n])<<6*--r}return i},getStringFromBytes:function(t,n,r,i){var s,o=[];for(n|=0,r="number"==typeof r?r:t.byteLength||t.length;nr){if(i)throw Error("Index "+n+": Found a "+s+" bytes encoded char declaration but only "+(r-n)+" bytes are available.")}else o.push(String.fromCodePoint(e.getCharCode(t,n,s,i)));n+=s-1}return o.join("")},getBytesForCharCode:function(t){if(t<128)return 1;if(t<2048)return 2;if(t<65536)return 3;if(t<2097152)return 4;throw new Error("CharCode "+t+" cannot be encoded with UTF8.")},setBytesFromCharCode:function(t,n,r,i){if(t|=0,n=n||[],r|=0,1==(i=i||e.getBytesForCharCode(t)))n[r]=t;else for(n[r++]=(parseInt("1111".slice(0,i),2)<<8-i)+(t>>>6*--i);i>0;)n[r++]=t>>>6*--i&63|128;return n},setBytesFromString:function(t,n,r,i,s){t=t||"",n=n||[],r|=0,i="number"==typeof i?i:n.byteLength||1/0;for(var o=0,a=t.length;oi)throw new Error('Not enought bytes to encode the char "'+t[o]+'" at the offset "'+r+'".');e.setBytesFromCharCode(t[o].codePointAt(0),n,r,l,s),r+=l}return n}};t.exports=e}),O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},k=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},S=function(){function t(t,e){for(var n=0;n>>8&255)}},{key:"setUint16",value:function(t,e){this.data[t]=255&e,this.data[t+1]=e>>>8&255}},{key:"writeUint32",value:function(t){for(var e=0;e<4;e++)this.data.push(255&t),t>>>=8}},{key:"setUint32",value:function(t,e){for(var n=0;n<4;n++)this.data[t+n]=255&e,e>>>=8}},{key:"writeVarUint",value:function(t){for(;t>=128;)this.data.push(128|127&t),t>>>=7;this.data.push(127&t)}},{key:"writeVarString",value:function(t){var e=b.setBytesFromString(t),n=e.length;this.writeVarUint(n);for(var r=0;r>>0;if(e>35)throw new Error("Integer out of range!")}}},{key:"readVarString",value:function(){for(var t=this.readVarUint(),e=new Array(t),n=0;n0)return p(t);if("number"===n&&!1===isNaN(t))return e.long?v(t):g(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))},F=t(function(t,e){function n(t){var n,r=0;for(n in t)r=(r<<5)-r+t.charCodeAt(n),r|=0;return e.colors[Math.abs(r)%e.colors.length]}function r(t){function r(){if(r.enabled){var t=r,n=+new Date,i=n-(l||n);t.diff=i,t.prev=l,t.curr=n,l=n;for(var s=new Array(arguments.length),o=0;o=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function r(t){var n=this.useColors;if(t[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+t[0]+(n?"%c ":" ")+"+"+e.humanize(this.diff),n){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var i=0,s=0;t[0].replace(/%[a-zA-Z%]/g,function(t){"%%"!==t&&(i++,"%c"===t&&(s=i))}),t.splice(s,0,r)}}function i(){return"object"===("undefined"==typeof console?"undefined":O(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function s(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(t){}}function o(){var t;try{t=e.storage.debug}catch(t){}return!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG),t}e=t.exports=F,e.log=i,e.formatArgs=r,e.save=s,e.load=o,e.useColors=n,e.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(t){}}(),e.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},e.enable(o())});!function(t){var e=function(){function e(n,r){if(k(this,e),this.y=n,null==r&&(r={}),this.opts=r,this.preferUntransformed=r.preferUntransformed||!1,null==r.role||"master"===r.role)this.role="master";else{if("slave"!==r.role)throw new Error("Role must be either 'master' or 'slave'!");this.role="slave"}this.log=t.debug("y:connector"),this.logMessage=t.debug("y:connector-message"),this.y.db.forwardAppliedOperations=r.forwardAppliedOperations||!1,this.role=r.role,this.connections=new Map,this.isSynced=!1,this.userEventListeners=[],this.whenSyncedListeners=[],this.currentSyncTarget=null,this.debug=!0===r.debug,this.broadcastOpBuffer=[],this.protocolVersion=11,this.authInfo=r.auth||null,this.checkAuth=r.checkAuth||function(){return Promise.resolve("write")},!1!==r.generateUserId&&this.setUserId(t.utils.generateUserId())}return S(e,[{key:"reconnect",value:function(){return this.log("reconnecting.."),this.y.db.startGarbageCollector()}},{key:"disconnect",value:function(){return this.log("discronnecting.."),this.connections=new Map,this.isSynced=!1,this.currentSyncTarget=null,this.whenSyncedListeners=[],this.y.db.stopGarbageCollector(),this.y.db.whenTransactionsFinished()}},{key:"repair",value:function(){var t=this;this.log("Repairing the state of Yjs. This can happen if messages get lost, and Yjs detects that something is wrong. If this happens often, please report an issue here: https://github.com/y-js/yjs/issues"),this.isSynced=!1,this.connections.forEach(function(e,n){e.isSynced=!1,t._syncWithUser(n)})}},{key:"setUserId",value:function(t){if(null==this.userId){if(!Number.isInteger(t)){var e=new Error("UserId must be an integer!");throw this.y.emit("error",e),e}return this.log('Set userId to "%s"',t),this.userId=t,this.y.db.setUserId(t)}return null}},{key:"onUserEvent",value:function(t){this.userEventListeners.push(t)}},{key:"removeUserEventListener",value:function(t){this.userEventListeners=this.userEventListeners.filter(function(e){return t!==e})}},{key:"userLeft",value:function(t){if(this.connections.has(t)){this.log("%s: User left %s",this.userId,t),this.connections.delete(t),this._setSyncedWith(null);var e=!0,n=!1,r=void 0;try{for(var i,s=this.userEventListeners[Symbol.iterator]();!(e=(i=s.next()).done);e=!0)(0,i.value)({action:"userLeft",user:t})}catch(t){n=!0,r=t}finally{try{!e&&s.return&&s.return()}finally{if(n)throw r}}}}},{key:"userJoined",value:function(t,e,n){if(null==e)throw new Error("You must specify the role of the joined user!");if(this.connections.has(t))throw new Error("This user already joined!");this.log("%s: User joined %s",this.userId,t),this.connections.set(t,{uid:t,isSynced:!1,role:e,processAfterAuth:[],auth:n||null,receivedSyncStep2:!1});var r={};r.promise=new Promise(function(t){r.resolve=t}),this.connections.get(t).syncStep2=r;var i=!0,s=!1,o=void 0;try{for(var a,l=this.userEventListeners[Symbol.iterator]();!(i=(a=l.next()).done);i=!0)(0,a.value)({action:"userJoined",user:t,role:e})}catch(t){s=!0,o=t}finally{try{!i&&l.return&&l.return()}finally{if(s)throw o}}this._syncWithUser(t)}},{key:"whenSynced",value:function(t){this.isSynced?t():this.whenSyncedListeners.push(t)}},{key:"_syncWithUser",value:function(t){"slave"!==this.role&&s(this,t)}},{key:"_fireIsSyncedListeners",value:function(){var t=this;this.y.db.whenTransactionsFinished().then(function(){if(!t.isSynced){t.isSynced=!0;var e=!0,n=!1,r=void 0;try{for(var i,s=t.whenSyncedListeners[Symbol.iterator]();!(e=(i=s.next()).done);e=!0)(0,i.value)()}catch(t){n=!0,r=t}finally{try{!e&&s.return&&s.return()}finally{if(n)throw r}}t.whenSyncedListeners=[]}})}},{key:"send",value:function(t,e){if(!(e instanceof ArrayBuffer||e instanceof Uint8Array))throw new Error("Expected Message to be an ArrayBuffer or Uint8Array - please don't use this method to send custom messages");this.log("%s: Send '%y' to %s",this.userId,e,t),this.logMessage("Message: %Y",e)}},{key:"broadcast",value:function(t){if(!(t instanceof ArrayBuffer||t instanceof Uint8Array))throw new Error("Expected Message to be an ArrayBuffer or Uint8Array - please don't use this method to send custom messages");this.log("%s: Broadcast '%y'",this.userId,t),this.logMessage("Message: %Y",t)}},{key:"broadcastOps",value:function(e){function n(){if(r.broadcastOpBuffer.length>0){var e=new U;e.writeVarString(r.opts.room),e.writeVarString("update");var n=r.broadcastOpBuffer;r.broadcastOpBuffer=[];var i=n.length;e.writeUint32(i);for(var s=0;s0&&e.every(function(t){return t.isSynced})&&this._fireIsSyncedListeners()}}]),e}();t.AbstractConnector=e}(w),function(t){var e=function(){function e(n,r){k(this,e),this.y=n,this.opts=r,this.saveOperationsBuffer=[],this.log=t.debug("y:persistence")}return S(e,[{key:"saveToMessageQueue",value:function(t){this.log("Room %s: Save message to message queue",this.y.options.connector.room)}},{key:"saveOperations",value:function(e){var n=this;e=e.map(function(e){return t.Struct[e.struct].encode(e)});var r=function(){if(n.saveOperationsBuffer.length>0){var e=new U;e.writeVarString(n.opts.room),e.writeVarString("update");var r=n.saveOperationsBuffer;n.saveOperationsBuffer=[];var i=r.length;e.writeUint32(i);for(var s=0;s0&&(i.gc1.length>0||i.gc2.length>0)?(i.y.connector.isSynced||console.warn("gc should be empty when not synced!"),new Promise(function(t){i.requestTransaction(function(){if(null!=i.y.connector&&i.y.connector.isSynced){for(var e=0;e0&&(i.gcInterval=setTimeout(r,i.gcTimeout)),t()})})):(i.gcTimeout>0&&(i.gcInterval=setTimeout(r,i.gcTimeout)),Promise.resolve())})}k(this,e),this.y=t,n.gc=!0===n.gc,this.dbOpts=n;var i=this;this.userId=null;var s;this.userIdPromise=new Promise(function(t){s=t}),this.userIdPromise.resolve=s,this.forwardAppliedOperations=!1,this.listenersById={},this.listenersByIdExecuteNow=[],this.listenersByIdRequestPending=!1,this.initializedTypes={},this.waitingTransactions=[],this.transactionInProgress=!1,this.transactionIsFlushed=!1,"undefined"!=typeof YConcurrencyTestingMode&&(this.executeOrder=[]),this.gc1=[],this.gc2=[],this.garbageCollect=r,this.startGarbageCollector(),this.repairCheckInterval=n.repairCheckInterval?n.repairCheckInterval:6e3,this.opsReceivedTimestamp=new Date,this.startRepairCheck()}return S(e,[{key:"startGarbageCollector",value:function(){this.gc=this.dbOpts.gc,this.gc?this.gcTimeout=this.dbOpts.gcTimeout?this.dbOpts.gcTimeout:3e4:this.gcTimeout=-1,this.gcTimeout>0&&this.garbageCollect()}},{key:"startRepairCheck",value:function(){var t=this;this.repairCheckInterval>0&&(this.repairCheckIntervalHandler=setInterval(function(){new Date-t.opsReceivedTimestamp>t.repairCheckInterval&&Object.keys(t.listenersById).length>0&&(t.listenersById={},t.opsReceivedTimestamp=new Date,t.y.connector.repair())},this.repairCheckInterval))}},{key:"stopRepairCheck",value:function(){clearInterval(this.repairCheckIntervalHandler)}},{key:"queueGarbageCollector",value:function(t){this.y.connector.isSynced&&this.gc&&this.gc1.push(t)}},{key:"emptyGarbageCollector",value:function(){ var t=this;return new Promise(function(e){var n=function n(){t.gc1.length>0||t.gc2.length>0?t.garbageCollect().then(n):e()};setTimeout(n,0)})}},{key:"addToDebug",value:function(){if("undefined"!=typeof YConcurrencyTestingMode){var t=Array.prototype.map.call(arguments,function(t){return"string"==typeof t?t:JSON.stringify(t)}).join("").replace(/"/g,"'").replace(/,/g,", ").replace(/:/g,": ");this.executeOrder.push(t)}}},{key:"getDebugData",value:function(){console.log(this.executeOrder.join("\n"))}},{key:"stopGarbageCollector",value:function(){var t=this;return this.gc=!1,this.gcTimeout=-1,new Promise(function(e){t.requestTransaction(function(){var n=t.gc1.concat(t.gc2);t.gc1=[],t.gc2=[];for(var r=0;r1&&(t=this.getInsertionCleanStart([t.id[0],t.id[1]+1]),n=!0),n)return t.gc=!0,this.setOperation(t),this.store.queueGarbageCollector(t.id),!0}return!1}},{key:"removeFromGarbageCollector",value:function(e){function n(n){return!t.utils.compareIds(n,e.id)}this.gc1=this.gc1.filter(n),this.gc2=this.gc2.filter(n),delete e.gc}},{key:"destroyTypes",value:function(){for(var t in this.initializedTypes){var e=this.initializedTypes[t];null!=e._destroy?e._destroy():console.error("The type you included does not provide destroy functionality, it will remain in memory (updating your packages will help).")}}},{key:"destroy",value:function(){clearTimeout(this.gcInterval),this.gcInterval=null,this.stopRepairCheck()}},{key:"setUserId",value:function(t){if(!this.userIdPromise.inProgress){this.userIdPromise.inProgress=!0;var e=this;e.requestTransaction(function(){e.userId=t;var n=this.getState(t);e.opClock=n.clock,e.userIdPromise.resolve(t)})}return this.userIdPromise}},{key:"whenUserIdSet",value:function(t){this.userIdPromise.then(t)}},{key:"getNextOpId",value:function(t){if(null==t)throw new Error("getNextOpId expects the number of created ids to create!");if(null==this.userId)throw new Error("OperationStore not yet initialized!");var e=[this.userId,this.opClock];return this.opClock+=t,e}},{key:"applyOperations",value:function(e){this.opsReceivedTimestamp=new Date;for(var n=e.readUint32(),r=0;r0)for(var n={op:e,missing:t.length},r=0;r0&&(this.store.y.connector.broadcastOps(n),null!=this.store.y.persistence&&this.store.y.persistence.saveOperations(n))}},{key:"deleteList",value:function(t){for(;null!=t;){if(t=this.getOperation(t),!t.gc){t.gc=!0,t.deleted=!0,this.setOperation(t);var e=null!=t.content?t.content.length:1;this.markDeleted(t.id,e),null!=t.opContent&&this.deleteOperation(t.opContent),this.store.queueGarbageCollector(t.id)}t=t.right}}},{key:"deleteOperation",value:function(t,e,n){for(null==e&&(e=1),this.markDeleted(t,e);e>0;){var r=!1,i=this.os.findWithUpperBound([t[0],t[1]+e-1]),s=null!=i&&null!=i.content?i.content.length:1;if(null==i||i.id[0]!==t[0]||i.id[1]+s<=t[1]?(i=null,e=0):(i.deleted||(i.id[1]t[1]+e&&(i=this.getInsertionCleanEnd([t[0],t[1]+e-1]),s=i.content.length)),e=i.id[1]-t[1]),null!=i){if(!i.deleted){if(r=!0,i.deleted=!0,null!=i.start&&this.deleteList(i.start),null!=i.map)for(var o in i.map)this.deleteList(i.map[o]);if(null!=i.opContent&&this.deleteOperation(i.opContent),null!=i.requires)for(var a=0;a0))return n;if(n.gc){if(!((r=n.id[1]+n.len-t[1])=i.id[1])for(r=n.id[1]+n.len-i.id[1];r>=0;){if(i.gc){n.len-=r,r>=i.len&&(r-=i.len)>0&&(this.ds.put(n),this.markDeleted([i.id[0],i.id[1]+i.len],r));break}if(!(r>i.len)){n.len+=i.len-r,this.ds.delete(i.id);break}var s=this.ds.findNext(i.id);if(this.ds.delete(i.id),null==s||n.id[0]!==s.id[0])break;i=s,r=n.id[1]+n.len-i.id[1]}return this.ds.put(n),n}},{key:"garbageCollectAfterSync",value:function(){(this.store.gc1.length>0||this.store.gc2.length>0)&&console.warn("gc should be empty after sync"),this.store.gc&&this.os.iterate(this,null,null,function(t){if(t.gc&&(delete t.gc,this.setOperation(t)),null!=t.parent&&this.isDeleted(t.parent)){if(t.gc=!0,!t.deleted&&(this.markDeleted(t.id,null!=t.content?t.content.length:1),t.deleted=!0,null!=t.opContent&&this.deleteOperation(t.opContent),null!=t.requires))for(var e=0;e0){var l=n.left;for(var u in n.originOf){var c=this.getOperation(n.originOf[u]);null!=c&&(c.origin=l,this.setOperation(c))}if(null!=l){var h=this.getInsertion(l);null==h.originOf?h.originOf=n.originOf:h.originOf=n.originOf.concat(h.originOf),this.setOperation(h)}}}if(null!=n.origin){var f=this.getInsertion(n.origin);f.originOf=f.originOf.filter(function(n){return!t.utils.compareIds(e,n)}),this.setOperation(f)}var d;if(null!=n.parent&&(d=this.getOperation(n.parent)),null!=d){var p=!1;null!=n.parentSub?t.utils.compareIds(d.map[n.parentSub],n.id)&&(p=!0,null!=n.right?d.map[n.parentSub]=n.right:delete d.map[n.parentSub]):(t.utils.compareIds(d.start,n.id)&&(p=!0,d.start=n.right),t.utils.matchesId(n,d.end)&&(p=!0,d.end=n.left)),p&&this.setOperation(d)}this.removeOperation(n.id)}}},{key:"checkDeleteStoreForState",value:function(t){var e=this.ds.findWithUpperBound([t.user,t.clock]);null!=e&&e.id[0]===t.user&&e.gc&&(t.clock=Math.max(t.clock,e.id[1]+e.len))}},{key:"updateState",value:function(t){var e=this.getState(t);this.checkDeleteStoreForState(e);for(var n=this.getInsertion([t,e.clock]),r=null!=n&&null!=n.content?n.content.length:1;null!=n&&t===n.id[0]&&n.id[1]<=e.clock&&n.id[1]+r>e.clock;)e.clock+=r,this.checkDeleteStoreForState(e),n=this.os.findNext(n.id),r=null!=n&&null!=n.content?n.content.length:1;this.setState(e)}},{key:"applyDeleteSet",value:function(t){for(var e=this,n=[],r=t.readUint32(),i=0;i=l[1];){var c=this.os.findWithUpperBound([l[0],u-1]);if(null==c)break;var h=null!=c.content?c.content.length:1;if(c.id[0]!==l[0]||c.id[1]+h<=l[1])break;c.id[1]+h>l[1]+l[2]&&(c=this.getInsertionCleanEnd([l[0],l[1]+l[2]-1])),c.id[1]1){var i=r[0],s=t[r[1]],o=null;null!=s&&(o=t.utils.parseTypeDefinition(s,r[3]));var a=t.Struct[i].create(e,o);return a.type=r[1],this.setOperation(a),a}throw new Error("Unexpected case. Operation cannot be generated correctly!Incompatible Yjs version?")}},{key:"removeOperation",value:function(t){this.os.delete(t)}},{key:"setState",value:function(t){var e={id:[t.user],clock:t.clock};this.ss.put(e)}},{key:"getState",value:function(t){var e=this.ss.find([t]),n=null==e?null:e.clock;return null==n&&(n=0),{user:t,clock:n}}},{key:"getStateVector",value:function(){var t=[];return this.ss.iterate(this,null,null,function(e){t.push({user:e.id[0],clock:e.clock})}),t}},{key:"getStateSet",value:function(){var t={};return this.ss.iterate(this,null,null,function(e){t[e.id[0]]=e.clock}),t}},{key:"writeStateSet",value:function(t){var e=t.pos,n=0;return t.writeUint32(0),this.ss.iterate(this,null,null,function(e){t.writeVarUint(e.id[0]),t.writeVarUint(e.clock),n++}),t.setUint32(e,n),0===n}},{key:"getOperations",value:function(e){null==e&&(e=new Map);var n=[],r=this.getStateVector(),i=!0,s=!1,o=void 0;try{for(var a,l=r[Symbol.iterator]();!(i=(a=l.next()).done);i=!0){var u=a.value,c=u.user;if(16777215!==c){var h=e.get(c)||0;if(h>0){var f=this.getInsertion([c,h]);null!=f&&(h=f.id[1])}e.set(c,h)}}}catch(t){s=!0,o=t}finally{try{!i&&l.return&&l.return()}finally{if(s)throw o}}var d=!0,p=!1,g=void 0;try{for(var v,y=r[Symbol.iterator]();!(d=(v=y.next()).done);d=!0){var m=v.value,w=m.user,b=e.get(w);16777215!==w&&this.os.iterate(this,[w,b],[w,Number.MAX_VALUE],function(r){if(r=t.Struct[r.struct].encode(r),"Insert"!==r.struct)n.push(r);else if(null==r.right||r.right[1]<(e.get(r.right[0])||0))for(var i=r,s=[r],o=r.right;;){if(null==i.left){r.left=null,n.push(r);break}for(i=this.getInsertion(i.left);s.length>0&&t.utils.matchesId(i,s[s.length-1].origin);)s.pop();if(i.id[1]<(e.get(i.id[0])||0)){r.left=t.utils.getLastId(i),n.push(r);break}if(t.utils.matchesId(i,r.origin)){if(r.left=r.origin,n.push(r),r=t.Struct[r.struct].encode(i),r.right=o,s.length>0)throw new Error("Reached inconsistent OS state.Operations are not correctly connected.");s=[r]}else{var a=t.Struct[r.struct].encode(i);a.right=s[s.length-1].id,a.left=a.origin,n.push(a),s.push(i)}}})}}catch(t){p=!0,g=t}finally{try{!d&&y.return&&y.return()}finally{if(p)throw g}}return n.reverse()}},{key:"writeOperations",value:function(e,n){for(var r=new Map,i=n.readUint32(),s=0;s1&&(d=this.getInsertionCleanEnd(d.id)),this.store.removeFromGarbageCollector(d)),this.setOperation(d)),null!=n.parentSub?(null==f&&(a.map[n.parentSub]=n.id,this.setOperation(a)),null!=n.right&&this.deleteOperation(n.right,1,!0),null!=n.left&&this.deleteOperation(n.id,1,!0)):null!=d&&null!=f||(null==d&&(a.end=t.utils.getLastId(n)),null==f&&(a.start=n.id),this.setOperation(a)),r=0;r=0&&null!=r.right;)r=this.getOperation(r.right);return n},map:function(t,e){t=t.start;for(var n=[];null!=t;){var r=this.getOperation(t);r.deleted||n.push(e(r)),t=r.right}return n}},e.Map={create:function(t){return{id:t,map:{},struct:"Map"}},encode:function(t){return{struct:"Map",type:t.type,id:t.id,map:{}}},binaryEncode:function(t,e){t.writeUint8(A),t.writeOpID(e.id),t.writeVarString(e.type)},binaryDecode:function(t){return t.skip8(),{id:t.readOpID(),type:t.readVarString(),struct:"Map",map:{}}},requiredOps:function(){return[]},execute:function(t){t.start=null,t.end=null},get:function(t,e){var n=t.map[e];if(null!=n){var r=this.getOperation(n);return null==r||r.deleted?void 0:null==r.opContent?r.content[0]:this.getType(r.opContent)}}},e.Xml={create:function(t,e){return{id:t,map:{},start:null,end:null,struct:"Xml",nodeName:null!=e?e.nodeName:null}},encode:function(t){return{struct:"Xml",type:t.type,id:t.id,map:{},nodeName:t.nodeName}},binaryEncode:function(t,e){t.writeUint8(L),t.writeOpID(e.id),t.writeVarString(e.type),t.writeVarString(e.nodeName)},binaryDecode:function(t){return t.skip8(),{id:t.readOpID(),type:t.readVarString(),struct:"Xml",map:{},start:null,end:null,nodeName:t.readVarString()}},requiredOps:function(){return[]},execute:function(){},ref:e.List.ref,map:e.List.map,get:e.Map.get}}(w),function(t){function e(t){var e={};for(var n in t)e[n]=t[n];return e}function n(t){return t=e(t),null!=t.content&&(t.content=t.content.map(function(t){return t})),t}function r(t,e){return t[0]=t.id[1]&&e[1]=0;r--)if(i=this.readBuffer[r],i.id[1]===t[1]&&i.id[0]===t[0]){for(;r=0;r--)if(i=this.writeBuffer[r],i.id[1]===t[1]&&i.id[0]===t[0]){s=i;break}if(r<0&&void 0===n&&(s=I(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"find",this).call(this,t)),null!=s){for(r=0;r=0;n--)if(r=this.writeBuffer[n],r.id[1]===i[1]&&r.id[0]===i[0]){for(;n0&&this.awaiting--,0===this.awaiting&&this.waiting.length>0){for(var s=0;s0;)for(var r=0;r=0;s--){var o=this.waiting[s];"Insert"===o.struct&&(t.utils.matchesId(o,i.left)?(o.right=i.id,i.left=o.left):t.utils.compareIds(o.id,i.right)&&(o.left=t.utils.getLastId(i),i.right=o.right))}}this._tryCallEvents(e)}},{key:"awaitedDeletes",value:function(e,n){for(var r=this.waiting.splice(this.waiting.length-e),i=0;i0&&this.awaiting--,0===this.awaiting&&this.waiting.length>0){var e=[],n=[];this.waiting.forEach(function(t){"Delete"===t.struct?n.push(t):e.push(t)}),e=function(e){for(var n=[];e.length>0;)for(var r=0;r0||this.store.gc2.length>0)&&console.warn("GC1|2 not empty!",this.store.gc1,this.store.gc2),"{}"!==JSON.stringify(this.store.listenersById)&&console.warn("listenersById not empty!"),"[]"!==JSON.stringify(this.store.listenersByIdExecuteNow)&&console.warn("listenersByIdExecuteNow not empty!"),this.store.transactionInProgress&&console.warn("Transaction still in progress!")},!0)}},{key:"transact",value:function(t){var n=new e(this);try{for(;null!=t;)t.call(n),t=this.getNextRequest()}catch(t){this.y.emit("error",t)}}},{key:"destroy",value:function(){I(i.prototype.__proto__||Object.getPrototypeOf(i.prototype),"destroy",this).call(this),delete this.os,delete this.ss,delete this.ds}}]),i}(t.AbstractDatabase);t.memory=i}(w),w.debug=M,M.formatters.Y=e,M.formatters.y=n;var R={};w.requiringModules=R,w.extend=function(t,e){if(2===arguments.length&&"string"==typeof t)e instanceof w.utils.CustomTypeDefinition?w[t]=e.parseArguments:w[t]=e,null!=R[t]&&(R[t].resolve(),delete R[t]);else for(var n=0;n