@liascript/exporter 3.3.6--1.0.10 → 3.3.8--1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/capacitor/Gun.772ecc6f.js +1 -0
- package/dist/assets/capacitor/Gun.b9900b92.js +1 -0
- package/dist/assets/capacitor/PeerJS.b46119d0.js +1 -0
- package/dist/assets/capacitor/index.50355c36.js +2 -0
- package/dist/assets/capacitor/index.58ce16fc.js +1 -0
- package/dist/assets/capacitor/{index.406bbc6e.css → index.ccf429fe.css} +1 -1
- package/dist/assets/capacitor/index.html +1 -1
- package/dist/assets/capacitor/{jszip.min.8d875ed3.js → jszip.min.5cd662bc.js} +1 -1
- package/dist/assets/indexeddb/Gun.17d6e5b9.js +1 -0
- package/dist/assets/indexeddb/Gun.203c9130.js +1 -0
- package/dist/assets/indexeddb/Gun.5dcdf1ee.js +1 -0
- package/dist/assets/indexeddb/Gun.8bed516b.js +1 -0
- package/dist/assets/indexeddb/PeerJS.37c67b75.js +1 -0
- package/dist/assets/indexeddb/PeerJS.ab0680e6.js +1 -0
- package/dist/assets/indexeddb/index.38c8ee75.js +1 -0
- package/dist/assets/indexeddb/index.a9ef23c3.js +1 -0
- package/dist/assets/{scorm2004/index.75ce53cb.css → indexeddb/index.b9f6b7ec.css} +1 -1
- package/dist/assets/indexeddb/index.html +1 -1
- package/dist/assets/indexeddb/{jszip.min.4fbcc13f.js → jszip.min.63142cc8.js} +1 -1
- package/dist/assets/pdf/index.04bea7d8.js +1 -0
- package/dist/assets/pdf/index.f63b4d54.js +1 -0
- package/dist/assets/pdf/{index.fda685a7.css → index.fc297547.css} +1 -1
- package/dist/assets/pdf/index.html +1 -1
- package/dist/assets/scorm1.2/Gun.17d6e5b9.js +1 -0
- package/dist/assets/scorm1.2/Gun.203c9130.js +1 -0
- package/dist/assets/scorm1.2/Gun.5dcdf1ee.js +1 -0
- package/dist/assets/scorm1.2/Gun.8bed516b.js +1 -0
- package/dist/assets/scorm1.2/PeerJS.37c67b75.js +1 -0
- package/dist/assets/scorm1.2/PeerJS.ab0680e6.js +1 -0
- package/dist/assets/scorm1.2/index.4649d9aa.js +1 -0
- package/dist/assets/scorm1.2/index.817342ed.js +1 -0
- package/dist/assets/{indexeddb/index.75ce53cb.css → scorm1.2/index.b9f6b7ec.css} +1 -1
- package/dist/assets/scorm1.2/index.html +1 -1
- package/dist/assets/scorm2004/Gun.17d6e5b9.js +1 -0
- package/dist/assets/scorm2004/Gun.203c9130.js +1 -0
- package/dist/assets/scorm2004/Gun.5dcdf1ee.js +1 -0
- package/dist/assets/scorm2004/Gun.8bed516b.js +1 -0
- package/dist/assets/scorm2004/PeerJS.37c67b75.js +1 -0
- package/dist/assets/scorm2004/PeerJS.ab0680e6.js +1 -0
- package/dist/assets/{web/index.75ce53cb.css → scorm2004/index.b9f6b7ec.css} +1 -1
- package/dist/assets/scorm2004/index.e49d8c81.js +1 -0
- package/dist/assets/scorm2004/index.f63ce2bc.js +1 -0
- package/dist/assets/scorm2004/index.html +1 -1
- package/dist/assets/web/Gun.17d6e5b9.js +1 -0
- package/dist/assets/web/Gun.203c9130.js +1 -0
- package/dist/assets/web/Gun.5dcdf1ee.js +1 -0
- package/dist/assets/web/Gun.8bed516b.js +1 -0
- package/dist/assets/web/PeerJS.37c67b75.js +1 -0
- package/dist/assets/web/PeerJS.ab0680e6.js +1 -0
- package/dist/assets/{scorm1.2/index.75ce53cb.css → web/index.b9f6b7ec.css} +1 -1
- package/dist/assets/web/index.cdc5c4af.js +1 -0
- package/dist/assets/web/index.d3734c27.js +1 -0
- package/dist/assets/web/index.html +1 -1
- package/dist/assets/xapi/Gun.17d6e5b9.js +1 -0
- package/dist/assets/xapi/Gun.5dcdf1ee.js +1 -0
- package/dist/assets/xapi/Gun.86201f0c.js +1 -0
- package/dist/assets/xapi/Gun.8bed516b.js +1 -0
- package/dist/assets/xapi/{PeerJS.c6cb8f4b.js → PeerJS.a9660005.js} +1 -1
- package/dist/assets/xapi/PeerJS.ab0680e6.js +1 -0
- package/dist/assets/xapi/index.b94732ac.js +1 -0
- package/dist/assets/xapi/index.b9f6b7ec.css +1 -0
- package/dist/assets/xapi/index.d8062eef.js +1 -0
- package/dist/assets/xapi/index.html +1 -1
- package/dist/index.js +4 -21
- package/package.json +9 -9
- package/dist/assets/capacitor/Gun.4c0ee714.js +0 -1
- package/dist/assets/capacitor/Gun.4caccb95.js +0 -1
- package/dist/assets/capacitor/PeerJS.a3900a77.js +0 -1
- package/dist/assets/capacitor/index.076fddd4.js +0 -1
- package/dist/assets/capacitor/index.6532983b.js +0 -2
- package/dist/assets/indexeddb/Gun.1b2824ad.js +0 -1
- package/dist/assets/indexeddb/Gun.52ff6547.js +0 -1
- package/dist/assets/indexeddb/Gun.c27cd89a.js +0 -1
- package/dist/assets/indexeddb/Gun.e5be0383.js +0 -1
- package/dist/assets/indexeddb/PeerJS.877663fc.js +0 -1
- package/dist/assets/indexeddb/PeerJS.daf2ca21.js +0 -1
- package/dist/assets/indexeddb/index.11cfd3a5.js +0 -1
- package/dist/assets/indexeddb/index.2dc41135.js +0 -1
- package/dist/assets/pdf/index.6c7e8237.js +0 -1
- package/dist/assets/pdf/index.e21e9c0d.js +0 -1
- package/dist/assets/scorm1.2/Gun.1b2824ad.js +0 -1
- package/dist/assets/scorm1.2/Gun.52ff6547.js +0 -1
- package/dist/assets/scorm1.2/Gun.c27cd89a.js +0 -1
- package/dist/assets/scorm1.2/Gun.e5be0383.js +0 -1
- package/dist/assets/scorm1.2/PeerJS.877663fc.js +0 -1
- package/dist/assets/scorm1.2/PeerJS.daf2ca21.js +0 -1
- package/dist/assets/scorm1.2/index.0a7eae2e.js +0 -1
- package/dist/assets/scorm1.2/index.ee6a673a.js +0 -1
- package/dist/assets/scorm2004/Gun.1b2824ad.js +0 -1
- package/dist/assets/scorm2004/Gun.52ff6547.js +0 -1
- package/dist/assets/scorm2004/Gun.c27cd89a.js +0 -1
- package/dist/assets/scorm2004/Gun.e5be0383.js +0 -1
- package/dist/assets/scorm2004/PeerJS.877663fc.js +0 -1
- package/dist/assets/scorm2004/PeerJS.daf2ca21.js +0 -1
- package/dist/assets/scorm2004/index.1425a438.js +0 -1
- package/dist/assets/scorm2004/index.27259952.js +0 -1
- package/dist/assets/web/Gun.1b2824ad.js +0 -1
- package/dist/assets/web/Gun.52ff6547.js +0 -1
- package/dist/assets/web/Gun.c27cd89a.js +0 -1
- package/dist/assets/web/Gun.e5be0383.js +0 -1
- package/dist/assets/web/PeerJS.877663fc.js +0 -1
- package/dist/assets/web/PeerJS.daf2ca21.js +0 -1
- package/dist/assets/web/index.68795b8d.js +0 -1
- package/dist/assets/web/index.6f7231d7.js +0 -1
- package/dist/assets/xapi/Gun.1b2824ad.js +0 -1
- package/dist/assets/xapi/Gun.52ff6547.js +0 -1
- package/dist/assets/xapi/Gun.618f30fa.js +0 -1
- package/dist/assets/xapi/Gun.e5be0383.js +0 -1
- package/dist/assets/xapi/PeerJS.daf2ca21.js +0 -1
- package/dist/assets/xapi/index.720250aa.js +0 -1
- package/dist/assets/xapi/index.75ce53cb.css +0 -1
- package/dist/assets/xapi/index.9225cbf5.js +0 -1
- /package/dist/assets/{xapi → scorm2004}/jszip.min.eaecf580.js +0 -0
- /package/dist/assets/{scorm2004 → xapi}/jszip.min.19c66d77.js +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e,t,s,n){Object.defineProperty(e,t,{get:s,set:n,enumerable:!0,configurable:!0})}var t=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;t.register("akyql",(function(s,n){e(s.exports,"GenericProvider",(function(){return t("hJFk3").GenericProvider}));t("hJFk3"),t("k5rhS")})),t.register("hJFk3",(function(s,n){e(s.exports,"GenericProvider",(function(){return g}));var i=t("9a6qY"),r=t("933AX"),a=t("beHgD"),o=t("8fTKk"),c=t("4VypT"),d=t("ewMJf"),h=t("iabNZ");const l=(()=>{const e=new Uint32Array(256);for(let t=0;t<256;t++){let s=t;for(let e=0;e<8;e++)s=1&s?s>>>1^3988292384:s>>>1;e[t]=s}return e})();function u(e){let t=4294967295;for(let s=0;s<e.length;s++)t=t>>>8^l[255&(t^e[s])];return(4294967295^t)>>>0}function p(e){const t=u(e),s=new Uint8Array(4+e.length);return s[0]=t>>>24&255,s[1]=t>>>16&255,s[2]=t>>>8&255,s[3]=255&t,s.set(e,4),s}function _(e){const t=i.encodeStateAsUpdate(e);let s=0;for(let e=0;e<t.length;e++)s=(s<<5)-s+t[e]|0;return s}class w extends d.Observable{publish(e,t){this.provider._sendPubSub(e,t)}subscribe(e,t){const s=(s,n)=>{"*"!==e&&e!==n||t(s,n)};return this.on("message",s),()=>this.off("message",s)}_handleMessage(e,t){this.emit("message",[t,e])}constructor(e){super(),this.provider=e}}class g extends d.Observable{async connect(e){if(this._destroying)throw new Error("Provider is being destroyed");if("connected"!==this._status.state)if("connecting"!==this._status.state){this._setStatus({state:"connecting"});try{if(this._setupBroadcastChannel(e),await this.transport.connect(e),this._unsubscribeTransport=this.transport.onMessage((e=>{this._handleIncomingMessage(e)})),this.transport.onPeerConnect){const e=this.transport.onPeerConnect((e=>{this._destroying||this.syncNow()})),t=this._unsubscribeTransport;this._unsubscribeTransport=()=>{null==t||t(),e()}}this._setStatus({state:"connected"}),this.syncNow(),this._broadcastAwareness([this.doc.clientID]),this._syncInterval>0&&(this._syncIntervalId=setInterval((()=>{if(this.transport.isConnected&&!this._destroying){const e=Date.now();this._syncRequestTimes=this._syncRequestTimes.filter((t=>e-t<this._syncRequestWindowMs)),this._syncRequestTimes.length<this._maxSyncRequestsPerWindow&&this._sendSyncStep1()}}),this._syncInterval))}catch(e){throw this._setStatus({state:"error",error:e instanceof Error?e:new Error(String(e))}),e}}else console.warn("[GenericProvider] Connection already in progress, ignoring connect() call");else console.warn("[GenericProvider] Already connected, ignoring connect() call")}disconnect(){if(void 0!==this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._corruptedMessageCount=0,this._lastCorruptedMessageTime=0,void 0!==this._batchTimeoutId&&(clearTimeout(this._batchTimeoutId),this._batchTimeoutId=void 0,this._pendingUpdate&&this.transport.isConnected&&this._sendUpdate(this._pendingUpdate),this._pendingUpdate=null),void 0!==this._awarenessTimeoutId&&(clearTimeout(this._awarenessTimeoutId),this._awarenessTimeoutId=void 0,this._pendingAwarenessClients.size>0&&this.transport.isConnected)){const e=Array.from(this._pendingAwarenessClients);this._sendAwarenessNow(e)}this._pendingAwarenessClients.clear(),this._disconnectBroadcastChannel(),this._unsubscribeTransport&&(this._unsubscribeTransport(),this._unsubscribeTransport=void 0),r.removeAwarenessStates(this.awareness,[this.doc.clientID],"disconnect"),this.transport.disconnect(),this._synced=!1,this._setStatus({state:"disconnected"})}destroy(){this._destroying=!0,void 0!==this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),void 0!==this._batchTimeoutId&&(clearTimeout(this._batchTimeoutId),this._batchTimeoutId=void 0,this._pendingUpdate&&this.transport.isConnected&&this._sendUpdate(this._pendingUpdate),this._pendingUpdate=null),this.disconnect(),this._updateHandler&&(this.doc.off("update",this._updateHandler),this._updateHandler=void 0),this._awarenessUpdateHandler&&(this.awareness.off("update",this._awarenessUpdateHandler),this._awarenessUpdateHandler=void 0),this._beforeUnloadHandler&&"undefined"!=typeof window&&(window.removeEventListener("beforeunload",this._beforeUnloadHandler),this._beforeUnloadHandler=void 0),this.awareness.destroy(),super.destroy()}get status(){return this._status}get connected(){return this.transport.isConnected}get bcConnected(){return this._bcConnected}get synced(){return this._synced}syncNow(){if(!this.transport.isConnected)return void console.warn("Cannot sync: transport not connected");const e=i.encodeStateAsUpdate(this.doc);e.length>0&&this._sendUpdate(e),this._sendSyncStep1(),this._broadcastAwareness([this.doc.clientID])}_setupDocumentSync(){this._updateHandler=(e,t)=>{t!==this&&(this._batchUpdates>0?this._batchUpdate(e):this._sendUpdate(e))},this.doc.on("update",this._updateHandler)}_batchUpdate(e){if(this._pendingUpdate)try{this._pendingUpdate=i.mergeUpdates([this._pendingUpdate,e])}catch(t){console.error("[GenericProvider] Failed to merge updates:",t),this._sendUpdate(this._pendingUpdate),this._pendingUpdate=e}else this._pendingUpdate=e;void 0!==this._batchTimeoutId&&clearTimeout(this._batchTimeoutId),this._batchTimeoutId=setTimeout((()=>{this._pendingUpdate&&(this._sendUpdate(this._pendingUpdate),this._pendingUpdate=null),this._batchTimeoutId=void 0}),this._batchUpdates)}_setupAwarenessSync(){this._awarenessUpdateHandler=({added:e,updated:t,removed:s},n)=>{const i=e.concat(t).concat(s);this._broadcastAwareness(i)},this.awareness.on("update",this._awarenessUpdateHandler),"undefined"!=typeof window&&(this._beforeUnloadHandler=()=>{r.removeAwarenessStates(this.awareness,[this.doc.clientID],"window unload"),this._disconnectBroadcastChannel()},window.addEventListener("beforeunload",this._beforeUnloadHandler))}_handleIncomingMessage(e){const t=function(e){if(e.length<4)return null;const t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,s=e.subarray(4);return u(s)!==t?null:s}(e);if(null!==t)try{const e=c.createDecoder(t),n=c.readVarUint(e);switch(n){case 0:{const t=o.createEncoder();o.writeVarUint(t,0);a.readSyncMessage(e,t,this.doc,this)!==a.messageYjsSyncStep2||this._synced||(this._synced=!0,this.emit("synced",[!0])),o.length(t)>1&&this._send(o.toUint8Array(t));break}case 1:r.applyAwarenessUpdate(this.awareness,c.readVarUint8Array(e),this);break;case 2:{const t=c.readVarString(e),s=c.readVarUint8Array(e);try{const e=(new TextDecoder).decode(s),n=JSON.parse(e);this.pubsub._handleMessage(t,n)}catch(e){console.error("Error decoding pub/sub message:",e)}break}case 3:{const t=c.readVarUint(e),n=c.readVarUint(e);var s;const i=null!==(s=this._remoteSeqNums.get(n))&&void 0!==s?s:-1;if(t<=i){console.warn(`[GenericProvider] Duplicate or out-of-order update detected from client ${n}: seqNum ${t} <= lastSeen ${i}`);break}if(i>=0&&t>i+1){const e=t-i-1;console.warn(`[GenericProvider] Sequence gap detected from client ${n}: expected ${i+1}, got ${t} (gap of ${e} messages)`),this._sendSyncStep1()}this._remoteSeqNums.set(n,t);const r=o.createEncoder();o.writeVarUint(r,0);const d=a.readSyncMessage(e,r,this.doc,this),h=c.readVarInt(e),l=_(this.doc);if(l!==h){this._hashMismatchCount++;const e=Date.now();e-this._lastHashMismatchTime>1e4&&(this._hashMismatchCount=1),this._lastHashMismatchTime=e;const t=Math.min(1e4,10*Math.pow(5,this._hashMismatchCount-1));console.warn(`[GenericProvider] Hash mismatch #${this._hashMismatchCount} detected! Local: ${l}, Expected: ${h}`),console.warn(`[GenericProvider] Re-sync scheduled in ${t}ms...`),setTimeout((()=>{this.transport.isConnected&&!this._destroying&&this.syncNow()}),t)}else this._hashMismatchCount=0;d!==a.messageYjsSyncStep2||this._synced||l!==h||(this._synced=!0,this.emit("synced",[!0])),o.length(r)>1&&this._send(o.toUint8Array(r));break}default:console.warn("Unknown message type:",n)}}catch(e){console.error("[GenericProvider] Error handling message:",e)}else{this._corruptedMessageCount++;const e=Date.now();e-this._lastCorruptedMessageTime>1e4&&(this._corruptedMessageCount=1),this._lastCorruptedMessageTime=e,console.warn(`[GenericProvider] 💥 Corrupted message rejected (#${this._corruptedMessageCount}): CRC32 checksum mismatch. This is expected if data corruption simulation is enabled.`);const t=Math.min(5e3,100*Math.pow(5,Math.min(this._corruptedMessageCount-1,3)));setTimeout((()=>{this.transport.isConnected&&!this._destroying&&this._sendSyncStep1()}),t)}}_sendSyncStep1(){const e=Date.now();if(this._syncRequestTimes=this._syncRequestTimes.filter((t=>e-t<this._syncRequestWindowMs)),this._syncRequestTimes.length>=this._maxSyncRequestsPerWindow)return void console.warn(`[GenericProvider] Sync rate limit exceeded (${this._maxSyncRequestsPerWindow} requests per ${this._syncRequestWindowMs/1e3}s), throttling...`);this._syncRequestTimes.push(e);const t=o.createEncoder();o.writeVarUint(t,0),a.writeSyncStep1(t,this.doc),this._send(o.toUint8Array(t))}_sendUpdate(e){const t=o.createEncoder();if(this._verifyUpdates){o.writeVarUint(t,3),o.writeVarUint(t,this._localSeqNum++),o.writeVarUint(t,this.doc.clientID),a.writeUpdate(t,e);const s=_(this.doc);o.writeVarInt(t,s)}else o.writeVarUint(t,0),a.writeUpdate(t,e);this._send(o.toUint8Array(t))}_sendAwarenessUpdate(e){const t=o.createEncoder();o.writeVarUint(t,1),o.writeVarUint8Array(t,r.encodeAwarenessUpdate(this.awareness,e)),this._send(o.toUint8Array(t))}_sendPubSub(e,t){if(this.transport.isConnected)try{const s=o.createEncoder();o.writeVarUint(s,2),o.writeVarString(s,e);const n=JSON.stringify(t),i=(new TextEncoder).encode(n);o.writeVarUint8Array(s,i),this._send(o.toUint8Array(s))}catch(e){console.error("Error sending pub/sub message:",e)}else console.warn("Cannot send pub/sub message: not connected")}_broadcastAwareness(e){if(0===e.length)return;if(this._awarenessInterval<=0)return void this._sendAwarenessNow(e);for(const t of e)this._pendingAwarenessClients.add(t);if(void 0!==this._awarenessTimeoutId)return;const t=Date.now()-this._lastAwarenessTime,s=Math.max(0,this._awarenessInterval-t);this._awarenessTimeoutId=setTimeout((()=>{this._awarenessTimeoutId=void 0,this._lastAwarenessTime=Date.now();const e=Array.from(this._pendingAwarenessClients);this._pendingAwarenessClients.clear(),e.length>0&&this._sendAwarenessNow(e)}),s)}_sendAwarenessNow(e){const t=o.createEncoder();o.writeVarUint(t,1),o.writeVarUint8Array(t,r.encodeAwarenessUpdate(this.awareness,e)),this._send(o.toUint8Array(t))}_setupBroadcastChannel(e){if(this._disableBc||"undefined"==typeof BroadcastChannel||"undefined"==typeof window)return;this._bcChannel=`yjs-${e.room}`,this._bcSubscriber=(e,t)=>{if(t===this)return;const s=new Uint8Array(e);this._handleIncomingMessage(s)},h.subscribe(this._bcChannel,this._bcSubscriber),this._bcConnected=!0;const t=o.createEncoder();o.writeVarUint(t,0),a.writeSyncStep1(t,this.doc),h.publish(this._bcChannel,p(o.toUint8Array(t)),this);const s=o.createEncoder();if(o.writeVarUint(s,0),a.writeSyncStep2(s,this.doc),h.publish(this._bcChannel,p(o.toUint8Array(s)),this),null!==this.awareness.getLocalState()){const e=o.createEncoder();o.writeVarUint(e,1),o.writeVarUint8Array(e,r.encodeAwarenessUpdate(this.awareness,[this.doc.clientID])),h.publish(this._bcChannel,p(o.toUint8Array(e)),this)}}_disconnectBroadcastChannel(){if(!this._bcConnected||!this._bcSubscriber)return;const e=o.createEncoder();o.writeVarUint(e,1),o.writeVarUint8Array(e,r.encodeAwarenessUpdate(this.awareness,[this.doc.clientID],new Map)),h.publish(this._bcChannel,p(o.toUint8Array(e)),this),h.unsubscribe(this._bcChannel,this._bcSubscriber),this._bcConnected=!1,this._bcSubscriber=void 0}_send(e){const t=p(e);if(this._bcConnected&&h.publish(this._bcChannel,t,this),this.transport.isConnected)try{const e=this.transport.send(t);e instanceof Promise&&e.catch((e=>{console.error("Error sending data:",e)}))}catch(e){console.error("Error sending data:",e)}}_setStatus(e){this._status=e,this.emit("status",[e])}_testSetSequenceNumber(e){this._localSeqNum=e,console.warn(`[GenericProvider TEST] Sequence number set to ${e} (MAX_SAFE_INTEGER: ${Number.MAX_SAFE_INTEGER})`)}_testGetSequenceNumber(){return this._localSeqNum}constructor(e,t,s={}){var n,i,a,o,c;super(),this._status={state:"disconnected"},this._synced=!1,this._destroying=!1,this._bcChannel="",this._bcConnected=!1,this._hashMismatchCount=0,this._lastHashMismatchTime=0,this._syncRequestTimes=[],this._maxSyncRequestsPerWindow=20,this._syncRequestWindowMs=1e4,this._localSeqNum=0,this._remoteSeqNums=new Map,this._corruptedMessageCount=0,this._lastCorruptedMessageTime=0,this._batchUpdates=0,this._pendingUpdate=null,this._awarenessInterval=100,this._pendingAwarenessClients=new Set,this._lastAwarenessTime=0,this.doc=e,this.transport=t,this.pubsub=new w(this),this.awareness=s.awareness||new r.Awareness(e),this._syncInterval=null!==(n=s.syncInterval)&&void 0!==n?n:5e3,this._verifyUpdates=null===(i=s.verifyUpdates)||void 0===i||i,this._batchUpdates=null!==(a=s.batchUpdates)&&void 0!==a?a:0,this._disableBc=null!==(o=s.disableBc)&&void 0!==o&&o,this._awarenessInterval=null!==(c=s.awarenessInterval)&&void 0!==c?c:100,this._setupDocumentSync(),this._setupAwarenessSync()}}})),t.register("933AX",(function(s,n){e(s.exports,"Awareness",(function(){return p})),e(s.exports,"removeAwarenessStates",(function(){return _})),e(s.exports,"encodeAwarenessUpdate",(function(){return w})),e(s.exports,"applyAwarenessUpdate",(function(){return g}));var i=t("dM3DM"),r=t("aQXMn"),a=t("8fTKk"),o=t("4VypT"),c=t("fyQrk"),d=t("bktFk"),h=t("ewMJf"),l=t("3oYST");const u=3e4;class p extends h.Observable{destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,s=this.meta.get(t),n=void 0===s?0:s.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:n,lastUpdated:c.getUnixTime()});const r=[],a=[],o=[],d=[];null===e?d.push(t):null==i?null!=e&&r.push(t):(a.push(t),l.equalityDeep(i,e)||o.push(t)),(r.length>0||o.length>0||d.length>0)&&this.emit("change",[{added:r,updated:o,removed:d},"local"]),this.emit("update",[{added:r,updated:a,removed:d},"local"])}setLocalStateField(e,t){const s=this.getLocalState();null!==s&&this.setLocalState((0,r.default)((0,i.default)({},s),{[e]:t}))}getStates(){return this.states}constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval((()=>{const e=c.getUnixTime();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach(((s,n)=>{n!==this.clientID&&u<=e-s.lastUpdated&&this.states.has(n)&&t.push(n)})),t.length>0&&_(this,t,"timeout")}),d.floor(3e3)),e.on("destroy",(()=>{this.destroy()})),this.setLocalState({})}}const _=(e,t,s)=>{const n=[];for(let s=0;s<t.length;s++){const i=t[s];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){const t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:c.getUnixTime()})}n.push(i)}}n.length>0&&(e.emit("change",[{added:[],updated:[],removed:n},s]),e.emit("update",[{added:[],updated:[],removed:n},s]))},w=(e,t,s=e.states)=>{const n=t.length,i=a.createEncoder();a.writeVarUint(i,n);for(let r=0;r<n;r++){const n=t[r],o=s.get(n)||null,c=e.meta.get(n).clock;a.writeVarUint(i,n),a.writeVarUint(i,c),a.writeVarString(i,JSON.stringify(o))}return a.toUint8Array(i)},g=(e,t,s)=>{const n=o.createDecoder(t),i=c.getUnixTime(),r=[],a=[],d=[],h=[],u=o.readVarUint(n);for(let t=0;t<u;t++){const t=o.readVarUint(n);let s=o.readVarUint(n);const c=JSON.parse(o.readVarString(n)),u=e.meta.get(t),p=e.states.get(t),_=void 0===u?0:u.clock;(_<s||_===s&&null===c&&e.states.has(t))&&(null===c?t===e.clientID&&null!=e.getLocalState()?s++:e.states.delete(t):e.states.set(t,c),e.meta.set(t,{clock:s,lastUpdated:i}),void 0===u&&null!==c?r.push(t):void 0!==u&&null===c?h.push(t):null!==c&&(l.equalityDeep(c,p)||d.push(t),a.push(t)))}(r.length>0||d.length>0||h.length>0)&&e.emit("change",[{added:r,updated:d,removed:h},s]),(r.length>0||a.length>0||h.length>0)&&e.emit("update",[{added:r,updated:a,removed:h},s])}})),t.register("beHgD",(function(s,n){e(s.exports,"messageYjsSyncStep2",(function(){return o})),e(s.exports,"writeSyncStep1",(function(){return c})),e(s.exports,"writeSyncStep2",(function(){return d})),e(s.exports,"writeUpdate",(function(){return l})),e(s.exports,"readSyncMessage",(function(){return p}));var i=t("8fTKk"),r=t("4VypT"),a=t("9a6qY");const o=1,c=(e,t)=>{i.writeVarUint(e,0);const s=a.encodeStateVector(t);i.writeVarUint8Array(e,s)},d=(e,t,s)=>{i.writeVarUint(e,o),i.writeVarUint8Array(e,a.encodeStateAsUpdate(t,s))},h=(e,t,s,n)=>{try{a.applyUpdate(t,r.readVarUint8Array(e),s)}catch(e){null!=n&&n(e),console.error("Caught error while handling a Yjs update",e)}},l=(e,t)=>{i.writeVarUint(e,2),i.writeVarUint8Array(e,t)},u=h,p=(e,t,s,n,i)=>{const a=r.readVarUint(e);switch(a){case 0:((e,t,s)=>{d(t,s,r.readVarUint8Array(e))})(e,t,s);break;case o:h(e,s,n,i);break;case 2:u(e,s,n,i);break;default:throw new Error("Unknown message type")}return a}})),t.register("iabNZ",(function(s,n){e(s.exports,"subscribe",(function(){return l})),e(s.exports,"unsubscribe",(function(){return u})),e(s.exports,"publish",(function(){return p}));var i=t("l1iu4"),r=t("2JauM"),a=t("ggKo5"),o=t("lqOdn");const c=new Map;const d="undefined"==typeof BroadcastChannel?class{postMessage(e){o.varStorage.setItem(this.room,a.toBase64(a.createUint8ArrayFromArrayBuffer(e)))}close(){o.offChange(this._onChange)}constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:a.fromBase64(t.newValue||"")}),o.onChange(this._onChange)}}:BroadcastChannel,h=e=>i.setIfUndefined(c,e,(()=>{const t=r.create(),s=new d(e);return s.onmessage=e=>t.forEach((t=>t(e.data,"broadcastchannel"))),{bc:s,subs:t}})),l=(e,t)=>(h(e).subs.add(t),t),u=(e,t)=>{const s=h(e),n=s.subs.delete(t);return n&&0===s.subs.size&&(s.bc.close(),c.delete(e)),n},p=(e,t,s=null)=>{const n=h(e);n.bc.postMessage(t),n.subs.forEach((e=>e(t,s)))}})),t.register("k5rhS",(function(e,s){t("9a6qY")}));
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
!function(){function e(e,t,n,s){Object.defineProperty(e,t,{get:n,set:s,enumerable:!0,configurable:!0})}var t=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;t.register("733OA",(function(n,s){e(n.exports,"GenericProvider",(function(){return t("5ZgK3").GenericProvider}));t("5ZgK3"),t("8fqfz")})),t.register("5ZgK3",(function(n,s){e(n.exports,"GenericProvider",(function(){return C}));var a=t("f1evb"),r=t("hnmIs"),i=t("9Klpk"),o=t("3bWnf"),c=t("9WzNc"),d=t("div3d"),u=t("kb0qF"),l=t("bWNdT"),h=t("32Euv"),p=t("bymyA"),f=t("baNMt"),_=t("6f3qJ"),v=t("iwMp2"),y=t("i9WxE"),w=t("l6jCY"),g=t("3EWWz"),b=function(){for(var e=new Uint32Array(256),t=0;t<256;t++){for(var n=t,s=0;s<8;s++)n=1&n?n>>>1^3988292384:n>>>1;e[t]=n}return e}();function m(e){for(var t=4294967295,n=0;n<e.length;n++)t=t>>>8^b[255&(t^e[n])];return(4294967295^t)>>>0}function U(e){var t=m(e),n=new Uint8Array(4+e.length);return n[0]=t>>>24&255,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n.set(e,4),n}function S(e){for(var t=p.encodeStateAsUpdate(e),n=0,s=0;s<t.length;s++)n=(n<<5)-n+t[s]|0;return n}var A=function(e){"use strict";(0,u.default)(n,e);var t=(0,l.default)(n);function n(e){var s;return(0,i.default)(this,n),(s=t.call(this)).provider=e,s}return(0,o.default)(n,[{key:"publish",value:function(e,t){this.provider._sendPubSub(e,t)}},{key:"subscribe",value:function(e,t){var n=this,s=function(n,s){"*"!==e&&e!==s||t(n,s)};return this.on("message",s),function(){return n.off("message",s)}}},{key:"_handleMessage",value:function(e,t){this.emit("message",[t,e])}}]),n}(w.Observable),C=function(e){"use strict";(0,u.default)(n,e);var t=(0,l.default)(n);function n(e,s){var r,o,c,d,u,l,h=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(0,i.default)(this,n),(r=t.call(this))._status={state:"disconnected"},r._synced=!1,r._destroying=!1,r._bcChannel="",r._bcConnected=!1,r._hashMismatchCount=0,r._lastHashMismatchTime=0,r._syncRequestTimes=[],r._maxSyncRequestsPerWindow=20,r._syncRequestWindowMs=1e4,r._localSeqNum=0,r._remoteSeqNums=new Map,r._corruptedMessageCount=0,r._lastCorruptedMessageTime=0,r._batchUpdates=0,r._pendingUpdate=null,r._awarenessInterval=100,r._pendingAwarenessClients=new Set,r._lastAwarenessTime=0,r.doc=e,r.transport=s,r.pubsub=new A((0,a.default)(r)),r.awareness=h.awareness||new f.Awareness(e),r._syncInterval=null!==(o=h.syncInterval)&&void 0!==o?o:5e3,r._verifyUpdates=null===(c=h.verifyUpdates)||void 0===c||c,r._batchUpdates=null!==(d=h.batchUpdates)&&void 0!==d?d:0,r._disableBc=null!==(u=h.disableBc)&&void 0!==u&&u,r._awarenessInterval=null!==(l=h.awarenessInterval)&&void 0!==l?l:100,r._setupDocumentSync(),r._setupAwarenessSync(),r}return(0,o.default)(n,[{key:"connect",value:function(e){var t=this;return(0,r.default)((function(){var n,s,a;return(0,h.__generator)(this,(function(r){switch(r.label){case 0:if(t._destroying)throw new Error("Provider is being destroyed");if("connected"===t._status.state)return console.warn("[GenericProvider] Already connected, ignoring connect() call"),[2];if("connecting"===t._status.state)return console.warn("[GenericProvider] Connection already in progress, ignoring connect() call"),[2];t._setStatus({state:"connecting"}),r.label=1;case 1:return r.trys.push([1,3,,4]),t._setupBroadcastChannel(e),[4,t.transport.connect(e)];case 2:return r.sent(),t._unsubscribeTransport=t.transport.onMessage((function(e){t._handleIncomingMessage(e)})),t.transport.onPeerConnect&&(n=t.transport.onPeerConnect((function(e){t._destroying||t.syncNow()})),s=t._unsubscribeTransport,t._unsubscribeTransport=function(){null==s||s(),n()}),t._setStatus({state:"connected"}),t.syncNow(),t._broadcastAwareness([t.doc.clientID]),t._syncInterval>0&&(t._syncIntervalId=setInterval((function(){if(t.transport.isConnected&&!t._destroying){var e=Date.now();t._syncRequestTimes=t._syncRequestTimes.filter((function(n){return e-n<t._syncRequestWindowMs})),t._syncRequestTimes.length<t._maxSyncRequestsPerWindow&&t._sendSyncStep1()}}),t._syncInterval)),[3,4];case 3:throw a=r.sent(),t._setStatus({state:"error",error:a instanceof Error?a:new Error(String(a))}),a;case 4:return[2]}}))}))()}},{key:"disconnect",value:function(){if(void 0!==this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._corruptedMessageCount=0,this._lastCorruptedMessageTime=0,void 0!==this._batchTimeoutId&&(clearTimeout(this._batchTimeoutId),this._batchTimeoutId=void 0,this._pendingUpdate&&this.transport.isConnected&&this._sendUpdate(this._pendingUpdate),this._pendingUpdate=null),void 0!==this._awarenessTimeoutId&&(clearTimeout(this._awarenessTimeoutId),this._awarenessTimeoutId=void 0,this._pendingAwarenessClients.size>0&&this.transport.isConnected)){var e=Array.from(this._pendingAwarenessClients);this._sendAwarenessNow(e)}this._pendingAwarenessClients.clear(),this._disconnectBroadcastChannel(),this._unsubscribeTransport&&(this._unsubscribeTransport(),this._unsubscribeTransport=void 0),f.removeAwarenessStates(this.awareness,[this.doc.clientID],"disconnect"),this.transport.disconnect(),this._synced=!1,this._setStatus({state:"disconnected"})}},{key:"destroy",value:function(){this._destroying=!0,void 0!==this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),void 0!==this._batchTimeoutId&&(clearTimeout(this._batchTimeoutId),this._batchTimeoutId=void 0,this._pendingUpdate&&this.transport.isConnected&&this._sendUpdate(this._pendingUpdate),this._pendingUpdate=null),this.disconnect(),this._updateHandler&&(this.doc.off("update",this._updateHandler),this._updateHandler=void 0),this._awarenessUpdateHandler&&(this.awareness.off("update",this._awarenessUpdateHandler),this._awarenessUpdateHandler=void 0),this._beforeUnloadHandler&&"undefined"!=typeof window&&(window.removeEventListener("beforeunload",this._beforeUnloadHandler),this._beforeUnloadHandler=void 0),this.awareness.destroy(),(0,c.default)((0,d.default)(n.prototype),"destroy",this).call(this)}},{key:"status",get:function(){return this._status}},{key:"connected",get:function(){return this.transport.isConnected}},{key:"bcConnected",get:function(){return this._bcConnected}},{key:"synced",get:function(){return this._synced}},{key:"syncNow",value:function(){if(this.transport.isConnected){var e=p.encodeStateAsUpdate(this.doc);e.length>0&&this._sendUpdate(e),this._sendSyncStep1(),this._broadcastAwareness([this.doc.clientID])}else console.warn("Cannot sync: transport not connected")}},{key:"_setupDocumentSync",value:function(){var e=this;this._updateHandler=function(t,n){n!==e&&(e._batchUpdates>0?e._batchUpdate(t):e._sendUpdate(t))},this.doc.on("update",this._updateHandler)}},{key:"_batchUpdate",value:function(e){var t=this;if(this._pendingUpdate)try{this._pendingUpdate=p.mergeUpdates([this._pendingUpdate,e])}catch(t){console.error("[GenericProvider] Failed to merge updates:",t),this._sendUpdate(this._pendingUpdate),this._pendingUpdate=e}else this._pendingUpdate=e;void 0!==this._batchTimeoutId&&clearTimeout(this._batchTimeoutId),this._batchTimeoutId=setTimeout((function(){t._pendingUpdate&&(t._sendUpdate(t._pendingUpdate),t._pendingUpdate=null),t._batchTimeoutId=void 0}),this._batchUpdates)}},{key:"_setupAwarenessSync",value:function(){var e=this;this._awarenessUpdateHandler=function(t,n){var s=t.added,a=t.updated,r=t.removed,i=s.concat(a).concat(r);e._broadcastAwareness(i)},this.awareness.on("update",this._awarenessUpdateHandler),"undefined"!=typeof window&&(this._beforeUnloadHandler=function(){f.removeAwarenessStates(e.awareness,[e.doc.clientID],"window unload"),e._disconnectBroadcastChannel()},window.addEventListener("beforeunload",this._beforeUnloadHandler))}},{key:"_handleIncomingMessage",value:function(e){var t=this,n=function(e){if(e.length<4)return null;var t=(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0,n=e.subarray(4);return m(n)!==t?null:n}(e);if(null!==n)try{var s=y.createDecoder(n),a=y.readVarUint(s);switch(a){case 0:var r=v.createEncoder();v.writeVarUint(r,0),_.readSyncMessage(s,r,this.doc,this)!==_.messageYjsSyncStep2||this._synced||(this._synced=!0,this.emit("synced",[!0])),v.length(r)>1&&this._send(v.toUint8Array(r));break;case 1:f.applyAwarenessUpdate(this.awareness,y.readVarUint8Array(s),this);break;case 2:var i=y.readVarString(s),o=y.readVarUint8Array(s);try{var c=(new TextDecoder).decode(o),d=JSON.parse(c);this.pubsub._handleMessage(i,d)}catch(e){console.error("Error decoding pub/sub message:",e)}break;case 3:var u,l=y.readVarUint(s),h=y.readVarUint(s),p=null!==(u=this._remoteSeqNums.get(h))&&void 0!==u?u:-1;if(l<=p){console.warn("[GenericProvider] Duplicate or out-of-order update detected from client ".concat(h,": seqNum ").concat(l," <= lastSeen ").concat(p));break}if(p>=0&&l>p+1){var w=l-p-1;console.warn("[GenericProvider] Sequence gap detected from client ".concat(h,": expected ").concat(p+1,", got ").concat(l," (gap of ").concat(w," messages)")),this._sendSyncStep1()}this._remoteSeqNums.set(h,l);var g=v.createEncoder();v.writeVarUint(g,0);var b=_.readSyncMessage(s,g,this.doc,this),U=y.readVarInt(s),A=S(this.doc);if(A!==U){this._hashMismatchCount++;var C=Date.now();C-this._lastHashMismatchTime>1e4&&(this._hashMismatchCount=1),this._lastHashMismatchTime=C;var I=Math.min(1e4,10*Math.pow(5,this._hashMismatchCount-1));console.warn("[GenericProvider] Hash mismatch #".concat(this._hashMismatchCount," detected! Local: ").concat(A,", Expected: ").concat(U)),console.warn("[GenericProvider] Re-sync scheduled in ".concat(I,"ms...")),setTimeout((function(){t.transport.isConnected&&!t._destroying&&t.syncNow()}),I)}else this._hashMismatchCount=0;b!==_.messageYjsSyncStep2||this._synced||A!==U||(this._synced=!0,this.emit("synced",[!0])),v.length(g)>1&&this._send(v.toUint8Array(g));break;default:console.warn("Unknown message type:",a)}}catch(e){console.error("[GenericProvider] Error handling message:",e)}else{this._corruptedMessageCount++;var T=Date.now();T-this._lastCorruptedMessageTime>1e4&&(this._corruptedMessageCount=1),this._lastCorruptedMessageTime=T,console.warn("[GenericProvider] 💥 Corrupted message rejected (#".concat(this._corruptedMessageCount,"): CRC32 checksum mismatch. ")+"This is expected if data corruption simulation is enabled.");var k=Math.min(5e3,100*Math.pow(5,Math.min(this._corruptedMessageCount-1,3)));setTimeout((function(){t.transport.isConnected&&!t._destroying&&t._sendSyncStep1()}),k)}}},{key:"_sendSyncStep1",value:function(){var e=this,t=Date.now();if(this._syncRequestTimes=this._syncRequestTimes.filter((function(n){return t-n<e._syncRequestWindowMs})),this._syncRequestTimes.length>=this._maxSyncRequestsPerWindow)console.warn("[GenericProvider] Sync rate limit exceeded (".concat(this._maxSyncRequestsPerWindow," requests per ").concat(this._syncRequestWindowMs/1e3,"s), throttling..."));else{this._syncRequestTimes.push(t);var n=v.createEncoder();v.writeVarUint(n,0),_.writeSyncStep1(n,this.doc),this._send(v.toUint8Array(n))}}},{key:"_sendUpdate",value:function(e){var t=v.createEncoder();if(this._verifyUpdates){v.writeVarUint(t,3),v.writeVarUint(t,this._localSeqNum++),v.writeVarUint(t,this.doc.clientID),_.writeUpdate(t,e);var n=S(this.doc);v.writeVarInt(t,n)}else v.writeVarUint(t,0),_.writeUpdate(t,e);this._send(v.toUint8Array(t))}},{key:"_sendAwarenessUpdate",value:function(e){var t=v.createEncoder();v.writeVarUint(t,1),v.writeVarUint8Array(t,f.encodeAwarenessUpdate(this.awareness,e)),this._send(v.toUint8Array(t))}},{key:"_sendPubSub",value:function(e,t){if(this.transport.isConnected)try{var n=v.createEncoder();v.writeVarUint(n,2),v.writeVarString(n,e);var s=JSON.stringify(t),a=(new TextEncoder).encode(s);v.writeVarUint8Array(n,a),this._send(v.toUint8Array(n))}catch(e){console.error("Error sending pub/sub message:",e)}else console.warn("Cannot send pub/sub message: not connected")}},{key:"_broadcastAwareness",value:function(e){var t=this;if(0!==e.length)if(this._awarenessInterval<=0)this._sendAwarenessNow(e);else{var n=!0,s=!1,a=void 0;try{for(var r,i=e[Symbol.iterator]();!(n=(r=i.next()).done);n=!0){var o=r.value;this._pendingAwarenessClients.add(o)}}catch(e){s=!0,a=e}finally{try{n||null==i.return||i.return()}finally{if(s)throw a}}if(void 0===this._awarenessTimeoutId){var c=Date.now()-this._lastAwarenessTime,d=Math.max(0,this._awarenessInterval-c);this._awarenessTimeoutId=setTimeout((function(){t._awarenessTimeoutId=void 0,t._lastAwarenessTime=Date.now();var e=Array.from(t._pendingAwarenessClients);t._pendingAwarenessClients.clear(),e.length>0&&t._sendAwarenessNow(e)}),d)}}}},{key:"_sendAwarenessNow",value:function(e){var t=v.createEncoder();v.writeVarUint(t,1),v.writeVarUint8Array(t,f.encodeAwarenessUpdate(this.awareness,e)),this._send(v.toUint8Array(t))}},{key:"_setupBroadcastChannel",value:function(e){var t=this;if(!this._disableBc&&"undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){this._bcChannel="yjs-".concat(e.room),this._bcSubscriber=function(e,n){if(n!==t){var s=new Uint8Array(e);t._handleIncomingMessage(s)}},g.subscribe(this._bcChannel,this._bcSubscriber),this._bcConnected=!0;var n=v.createEncoder();v.writeVarUint(n,0),_.writeSyncStep1(n,this.doc),g.publish(this._bcChannel,U(v.toUint8Array(n)),this);var s=v.createEncoder();if(v.writeVarUint(s,0),_.writeSyncStep2(s,this.doc),g.publish(this._bcChannel,U(v.toUint8Array(s)),this),null!==this.awareness.getLocalState()){var a=v.createEncoder();v.writeVarUint(a,1),v.writeVarUint8Array(a,f.encodeAwarenessUpdate(this.awareness,[this.doc.clientID])),g.publish(this._bcChannel,U(v.toUint8Array(a)),this)}}}},{key:"_disconnectBroadcastChannel",value:function(){if(this._bcConnected&&this._bcSubscriber){var e=v.createEncoder();v.writeVarUint(e,1),v.writeVarUint8Array(e,f.encodeAwarenessUpdate(this.awareness,[this.doc.clientID],new Map)),g.publish(this._bcChannel,U(v.toUint8Array(e)),this),g.unsubscribe(this._bcChannel,this._bcSubscriber),this._bcConnected=!1,this._bcSubscriber=void 0}}},{key:"_send",value:function(e){var t=U(e);if(this._bcConnected&&g.publish(this._bcChannel,t,this),this.transport.isConnected)try{var n=this.transport.send(t);n instanceof Promise&&n.catch((function(e){console.error("Error sending data:",e)}))}catch(e){console.error("Error sending data:",e)}}},{key:"_setStatus",value:function(e){this._status=e,this.emit("status",[e])}},{key:"_testSetSequenceNumber",value:function(e){this._localSeqNum=e,console.warn("[GenericProvider TEST] Sequence number set to ".concat(e," (MAX_SAFE_INTEGER: ").concat(Number.MAX_SAFE_INTEGER,")"))}},{key:"_testGetSequenceNumber",value:function(){return this._localSeqNum}}]),n}(w.Observable)})),t.register("baNMt",(function(n,s){e(n.exports,"Awareness",(function(){return m})),e(n.exports,"removeAwarenessStates",(function(){return U})),e(n.exports,"encodeAwarenessUpdate",(function(){return S})),e(n.exports,"applyAwarenessUpdate",(function(){return A}));var a=t("f1evb"),r=t("9Klpk"),i=t("3bWnf"),o=t("eT7f3"),c=t("9WzNc"),d=t("div3d"),u=t("kb0qF"),l=t("bgoEC"),h=t("7j4mF"),p=t("bWNdT"),f=t("iwMp2"),_=t("i9WxE"),v=t("c01oj"),y=t("3db39"),w=t("l6jCY"),g=t("dNOud"),b=3e4,m=function(e){"use strict";(0,u.default)(n,e);var t=(0,p.default)(n);function n(e){var s;return(0,r.default)(this,n),(s=t.call(this)).doc=e,s.clientID=e.clientID,s.states=new Map,s.meta=new Map,s._checkInterval=setInterval((function(){var e=v.getUnixTime();null!==s.getLocalState()&&15e3<=e-s.meta.get(s.clientID).lastUpdated&&s.setLocalState(s.getLocalState());var t=[];s.meta.forEach((function(n,a){a!==s.clientID&&b<=e-n.lastUpdated&&s.states.has(a)&&t.push(a)})),t.length>0&&U((0,a.default)(s),t,"timeout")}),y.floor(3e3)),e.on("destroy",(function(){s.destroy()})),s.setLocalState({}),s}return(0,i.default)(n,[{key:"destroy",value:function(){this.emit("destroy",[this]),this.setLocalState(null),(0,c.default)((0,d.default)(n.prototype),"destroy",this).call(this),clearInterval(this._checkInterval)}},{key:"getLocalState",value:function(){return this.states.get(this.clientID)||null}},{key:"setLocalState",value:function(e){var t=this.clientID,n=this.meta.get(t),s=void 0===n?0:n.clock+1,a=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:s,lastUpdated:v.getUnixTime()});var r=[],i=[],o=[],c=[];null===e?c.push(t):null==a?null!=e&&r.push(t):(i.push(t),g.equalityDeep(a,e)||o.push(t)),(r.length>0||o.length>0||c.length>0)&&this.emit("change",[{added:r,updated:o,removed:c},"local"]),this.emit("update",[{added:r,updated:i,removed:c},"local"])}},{key:"setLocalStateField",value:function(e,t){var n=this.getLocalState();null!==n&&this.setLocalState((0,h.default)((0,l.default)({},n),(0,o.default)({},e,t)))}},{key:"getStates",value:function(){return this.states}}]),n}(w.Observable),U=function(e,t,n){for(var s=[],a=0;a<t.length;a++){var r=t[a];if(e.states.has(r)){if(e.states.delete(r),r===e.clientID){var i=e.meta.get(r);e.meta.set(r,{clock:i.clock+1,lastUpdated:v.getUnixTime()})}s.push(r)}}s.length>0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},S=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.states,s=t.length,a=f.createEncoder();f.writeVarUint(a,s);for(var r=0;r<s;r++){var i=t[r],o=n.get(i)||null,c=e.meta.get(i).clock;f.writeVarUint(a,i),f.writeVarUint(a,c),f.writeVarString(a,JSON.stringify(o))}return f.toUint8Array(a)},A=function(e,t,n){for(var s=_.createDecoder(t),a=v.getUnixTime(),r=[],i=[],o=[],c=[],d=_.readVarUint(s),u=0;u<d;u++){var l=_.readVarUint(s),h=_.readVarUint(s),p=JSON.parse(_.readVarString(s)),f=e.meta.get(l),y=e.states.get(l),w=void 0===f?0:f.clock;(w<h||w===h&&null===p&&e.states.has(l))&&(null===p?l===e.clientID&&null!=e.getLocalState()?h++:e.states.delete(l):e.states.set(l,p),e.meta.set(l,{clock:h,lastUpdated:a}),void 0===f&&null!==p?r.push(l):void 0!==f&&null===p?c.push(l):null!==p&&(g.equalityDeep(p,y)||o.push(l),i.push(l)))}(r.length>0||o.length>0||c.length>0)&&e.emit("change",[{added:r,updated:o,removed:c},n]),(r.length>0||i.length>0||c.length>0)&&e.emit("update",[{added:r,updated:i,removed:c},n])}})),t.register("6f3qJ",(function(n,s){e(n.exports,"messageYjsSyncStep2",(function(){return o})),e(n.exports,"writeSyncStep1",(function(){return c})),e(n.exports,"writeSyncStep2",(function(){return d})),e(n.exports,"writeUpdate",(function(){return l})),e(n.exports,"readSyncMessage",(function(){return p}));var a=t("iwMp2"),r=t("i9WxE"),i=t("bymyA"),o=1,c=function(e,t){a.writeVarUint(e,0);var n=i.encodeStateVector(t);a.writeVarUint8Array(e,n)},d=function(e,t,n){a.writeVarUint(e,o),a.writeVarUint8Array(e,i.encodeStateAsUpdate(t,n))},u=function(e,t,n,s){try{i.applyUpdate(t,r.readVarUint8Array(e),n)}catch(e){null!=s&&s(e),console.error("Caught error while handling a Yjs update",e)}},l=function(e,t){a.writeVarUint(e,2),a.writeVarUint8Array(e,t)},h=u,p=function(e,t,n,s,a){var i=r.readVarUint(e);switch(i){case 0:!function(e,t,n){d(t,n,r.readVarUint8Array(e))}(e,t,n);break;case o:u(e,n,s,a);break;case 2:h(e,n,s,a);break;default:throw new Error("Unknown message type")}return i}})),t.register("3EWWz",(function(n,s){e(n.exports,"subscribe",(function(){return p})),e(n.exports,"unsubscribe",(function(){return f})),e(n.exports,"publish",(function(){return _}));var a=t("9Klpk"),r=t("3bWnf"),i=t("lOVDE"),o=t("iitZb"),c=t("jKUB9"),d=t("a1im1"),u=new Map,l="undefined"==typeof BroadcastChannel?function(){"use strict";function e(t){var n=this;(0,a.default)(this,e),this.room=t,this.onmessage=null,this._onChange=function(e){return e.key===t&&null!==n.onmessage&&n.onmessage({data:c.fromBase64(e.newValue||"")})},d.onChange(this._onChange)}return(0,r.default)(e,[{key:"postMessage",value:function(e){d.varStorage.setItem(this.room,c.toBase64(c.createUint8ArrayFromArrayBuffer(e)))}},{key:"close",value:function(){d.offChange(this._onChange)}}]),e}():BroadcastChannel,h=function(e){return i.setIfUndefined(u,e,(function(){var t=o.create(),n=new l(e);return n.onmessage=function(e){return t.forEach((function(t){return t(e.data,"broadcastchannel")}))},{bc:n,subs:t}}))},p=function(e,t){return h(e).subs.add(t),t},f=function(e,t){var n=h(e),s=n.subs.delete(t);return s&&0===n.subs.size&&(n.bc.close(),u.delete(e)),s},_=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=h(e);s.bc.postMessage(t),s.subs.forEach((function(e){return e(t,n)}))}})),t.register("8fqfz",(function(e,n){t("9Klpk"),t("3bWnf"),t("bymyA")}))}();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
!function(){function e(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var t=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;t.register("izF7z",(function(n,r){e(n.exports,"Sync",(function(){return y}));var o=t("f1evb"),s=t("hnmIs"),i=t("9Klpk"),a=t("3bWnf"),u=t("eT7f3"),c=t("9WzNc"),l=t("div3d"),d=t("kb0qF"),p=t("bWNdT"),h=t("32Euv"),f=t("auvHb"),g=t("2lzFl"),v=t("733OA");Object.defineProperty(Array.prototype,"flat",{value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;return this.reduce((function(t,n){return t.concat(Array.isArray(n)&&e>1?n.flat(e-1):n)}),[])}});var y=function(e){"use strict";(0,d.default)(n,e);var t=(0,p.default)(n);function n(){var e;return(0,i.default)(this,n),e=t.apply(this,arguments),(0,u.default)((0,o.default)(e),"store",""),(0,u.default)((0,o.default)(e),"gunServer",[]),(0,u.default)((0,o.default)(e),"persistent",!1),(0,u.default)((0,o.default)(e),"syncFallbackTimer",null),e}return(0,a.default)(n,[{key:"destroy",value:function(){var e;null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),(0,c.default)((0,l.default)(n.prototype),"destroy",this).call(this),this.gunServer=[],null===(e=this.provider)||void 0===e||e.disconnect()}},{key:"uniqueID",value:function(){var e=(0,c.default)((0,l.default)(n.prototype),"uniqueID",this).call(this);return e?btoa(e+(this.persistent?"p":"")):null}},{key:"connect",value:function(e){var t=this,r=this;return(0,s.default)((function(){var o,s,i;return(0,h.__generator)(this,(function(a){return(0,c.default)((0,l.default)(n.prototype),"connect",t).call(r,e),r.gunServer=(null===(o=e.config)||void 0===o?void 0:o.urls)||[],r.persistent=(null===(s=e.config)||void 0===s?void 0:s.persistent)||!1,window.Gun&&(null===(i=window.Gun)||void 0===i?void 0:i.SEA)?r.init(!0):r.load(["https://cdn.jsdelivr.net/npm/gun/gun.js","https://cdn.jsdelivr.net/npm/gun/sea.js"],r),[2]}))}))()}},{key:"init",value:function(e,t){var n=this;if(0==this.gunServer.length)return this.sendDisconnectError("You have to provide at least one relay server.");var r=this.uniqueID();if(e&&window.Gun&&r){var o;this.transport=new(0,g.GunTransport)({gun:window.Gun,sea:null===(o=window.Gun)||void 0===o?void 0:o.SEA,peers:this.gunServer,debug:!1,batchInterval:200,gunOptions:{localStorage:!1,radisk:!1},password:this.password}),this.store=r,this.provider=new(0,v.GenericProvider)(this.db.doc,this.transport),this.db.setAwareness(this.provider.awareness);var s=!1,i=function(){s||(s=!0,null!==n.syncFallbackTimer&&(clearTimeout(n.syncFallbackTimer),n.syncFallbackTimer=null),n.sendConnect())};this.provider.on("synced",(function(e){console.log("Document synchronized",e.synced),i()})),this.provider.on("status",(function(e){var t=e.state;console.log("Status changed: ".concat(t),"info"),"connected"===t?n.syncFallbackTimer=setTimeout((function(){console.log("Sync fallback: no remote peers, proceeding as first peer"),i()}),2e3):"disconnected"===t?console.warn("Disconnected from GunDB relay server"):console.warn("GunDB status: ".concat(t))})),this.provider.pubsub.subscribe("*",(function(e,t){var r,o;null===(o=(r=n).onReceive)||void 0===o||o.call(r,t,e)})),this.provider.connect({room:this.store})}else{var a,u="GunDB unknown error";t?u="Could not load resource: "+t:window.Gun?(null===(a=window.Gun)||void 0===a?void 0:a.SEA)||(u="Could not load GunDB SEA security module"):u="Could not load GunDB interface",this.sendDisconnectError(u)}}},{key:"pubsubSend",value:function(e,t){var n;this.provider&&(this.provider.pubsub.publish(e,t),this.replyOnReceive&&(null===(n=this.onReceive)||void 0===n||n.call(this,e,t)))}}]),n}(f.Sync)})),t.register("2lzFl",(function(n,r){e(n.exports,"GunTransport",(function(){return d}));var o=t("hnmIs"),s=t("9Klpk"),i=t("3bWnf"),a=t("bgoEC"),u=t("5ENmm"),c=t("6Wo7Q"),l=t("32Euv"),d=function(){"use strict";function e(t){if((0,s.default)(this,e),this._connected=!1,this._room="",this.gun=null,this.roomNode=null,this.updateListener=null,this.lastUpdateTime=0,this.updateBatch=[],this.processedUpdates=new Set,this.connectionTime=0,this.pendingUpdates=new Map,this.updateSlot=0,this.BUFFER_SIZE=20,this.awarenessListener=null,this.lastAwarenessId="",this.encryptionEnabled=!1,!t.gun)throw new Error('GunTransport requires the "gun" option. Please provide the Gun constructor: import Gun from "gun"; new GunTransport({ gun: Gun, ... })');if(t.password&&!t.sea)throw new Error('GunTransport requires the "sea" option when using password encryption. Please provide Gun.SEA: import "gun/sea"; new GunTransport({ gun: Gun, sea: Gun.SEA, password: "..." })');var n,r,o,i;this.options={gun:t.gun,peers:null!==(n=t.peers)&&void 0!==n?n:[],gunOptions:null!==(r=t.gunOptions)&&void 0!==r?r:{},debug:null!==(o=t.debug)&&void 0!==o&&o,batchInterval:null!==(i=t.batchInterval)&&void 0!==i?i:100,password:t.password,sea:t.sea},this.encryptionEnabled=!(!t.password||!t.sea),this.encryptionEnabled&&this.log("🔐 Encryption enabled")}return(0,i.default)(e,[{key:"connect",value:function(e){var t=this;return(0,o.default)((function(){var n;return(0,l.__generator)(this,(function(r){if(t._connected)throw new Error("Already connected");return t._room=e.room,t.connectionTime=Date.now(),t.log("🔗 Initializing Gun..."),n=(0,a.default)({localStorage:!1,radisk:!1},t.options.gunOptions),t.options.peers.length>0&&(n.peers=t.options.peers,t.log("📡 Connecting to peers:",t.options.peers)),t.gun=new t.options.gun(n),t.roomNode=t.gun.get("yjs-room-".concat(t._room)),t.log("✅ Gun initialized for room:",t._room),t.setupUpdateListener(),t.setupAwarenessListener(),t._connected=!0,[2]}))}))()}},{key:"setupUpdateListener",value:function(){var e=this,t=0,n=!1;this.roomNode.get("updates").once((function(t){if(!t)return n=!0,void e.log("📭 No existing updates found");e.log("📥 Loading initial state..."),Object.keys(t).forEach((function(n){if("_"!==n){var r=t[n];if(r&&r.data){var o=r.sequence||Math.floor(r.timestamp/100),s="".concat(n,"-").concat(o);e.processedUpdates.has(s)||e.pendingUpdates.set(s,r)}}})),e.processPendingUpdates(),n=!0,e.log("✅ Initial state loaded")})),this.updateListener=this.roomNode.get("updates").map().on((function(r,o){if(n&&r&&r.data&&!(r.timestamp&&r.timestamp<e.connectionTime)){var s=r.sequence||Math.floor(r.timestamp/100),i="".concat(o,"-").concat(s);if(!e.processedUpdates.has(i)){e.pendingUpdates.set(i,r);var a=Date.now();a-t<300?e.throttleTimeout||(e.throttleTimeout=setTimeout((function(){e.processPendingUpdates(),t=Date.now(),e.throttleTimeout=void 0}),300)):(t=a,e.processPendingUpdates())}}})),this.log("👂 Listening for new updates...")}},{key:"processPendingUpdates",value:function(){var e=this;return(0,o.default)((function(){var t,n,r,o,s,i,a,c,d,p,h,f,g,v;return(0,l.__generator)(this,(function(l){switch(l.label){case 0:if(0===e.pendingUpdates.size)return[2];t=Array.from(e.pendingUpdates.entries()),e.pendingUpdates.clear(),n=!0,r=!1,o=void 0,l.label=1;case 1:l.trys.push([1,9,10,11]),s=t[Symbol.iterator](),l.label=2;case 2:if(n=(i=s.next()).done)return[3,8];a=(0,u.default)(i.value,2),c=a[0],d=a[1],e.processedUpdates.add(c),e.processedUpdates.size>200&&(p=Array.from(e.processedUpdates)).slice(0,p.length-200).forEach((function(t){e.processedUpdates.delete(t)})),l.label=3;case 3:return l.trys.push([3,6,,7]),h=d.data,d.encrypted&&e.encryptionEnabled?[4,e.decrypt(h)]:[3,5];case 4:if(!(h=l.sent()))return e.log("❌ Failed to decrypt update (wrong password?)"),[3,7];l.label=5;case 5:return f=e.base64ToUint8Array(h),e._callback&&e._callback(f),1===t.length&&e.log("📥 Received update:",f.length,"bytes",d.encrypted?"(decrypted)":""),[3,7];case 6:return g=l.sent(),e.log("❌ Error processing update:",g),[3,7];case 7:return n=!0,[3,2];case 8:return[3,11];case 9:return v=l.sent(),r=!0,o=v,[3,11];case 10:try{n||null==s.return||s.return()}finally{if(r)throw o}return[7];case 11:return t.length>1&&e.log("📥 Processed ".concat(t.length," batched updates")),[2]}}))}))()}},{key:"disconnect",value:function(){this._connected&&(this.log("👋 Disconnecting..."),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=void 0),this.throttleTimeout&&(clearTimeout(this.throttleTimeout),this.throttleTimeout=void 0),this.processPendingUpdates(),this.flushBatch(),this.updateListener&&(this.updateListener=null),this.awarenessListener&&(this.awarenessListener=null),this.roomNode=null,this.gun=null,this._connected=!1,this.processedUpdates.clear(),this.pendingUpdates.clear(),this.log("✅ Disconnected"))}},{key:"send",value:function(e){var t=this;this._connected&&this.roomNode?1!==this.peekMessageType(e)?(this.updateBatch.push(e),this.batchTimeout&&clearTimeout(this.batchTimeout),this.batchTimeout=setTimeout((function(){t.flushBatch()}),this.options.batchInterval)):this.sendAwareness(e):this.log("⚠️ Not connected, cannot send")}},{key:"peekMessageType",value:function(e){return e.length<5?-1:e[4]}},{key:"sendAwareness",value:function(e){var t=this;return(0,o.default)((function(){var n,r;return(0,l.__generator)(this,(function(o){switch(o.label){case 0:return n=t.uint8ArrayToBase64(e),t.encryptionEnabled?[4,t.encrypt(n)]:[3,2];case 1:n=o.sent(),o.label=2;case 2:return r="aware-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,5)),t.lastAwarenessId=r,t.roomNode.get("awareness").put({data:n,id:r,timestamp:Date.now(),encrypted:t.encryptionEnabled}),t.log("📤 Sent awareness update",t.encryptionEnabled?"(encrypted)":""),[2]}}))}))()}},{key:"setupAwarenessListener",value:function(){var e,t=this;this.awarenessListener=this.roomNode.get("awareness").on((e=(0,o.default)((function(e){var n,r,o;return(0,l.__generator)(this,(function(s){switch(s.label){case 0:if(!e||!e.data)return[2];if(e.id===t.lastAwarenessId)return[2];if(e.timestamp&&e.timestamp<t.connectionTime)return[2];s.label=1;case 1:return s.trys.push([1,4,,5]),n=e.data,e.encrypted&&t.encryptionEnabled?[4,t.decrypt(n)]:[3,3];case 2:if(!(n=s.sent()))return t.log("❌ Failed to decrypt awareness (wrong password?)"),[2];s.label=3;case 3:return r=t.base64ToUint8Array(n),t._callback&&t._callback(r),t.log("📥 Received awareness update",e.encrypted?"(decrypted)":""),[3,5];case 4:return o=s.sent(),t.log("❌ Error processing awareness:",o),[3,5];case 5:return[2]}}))})),function(t){return e.apply(this,arguments)})),this.log("👂 Listening for awareness updates...")}},{key:"flushBatch",value:function(){var e=this;return(0,o.default)((function(){var t,n,r,o,s,i,a,u,c,d,p,h,f;return(0,l.__generator)(this,(function(l){switch(l.label){case 0:if(0===e.updateBatch.length)return[2];t=e.updateBatch.reduce((function(e,t){return e+t.length}),0),n=new Uint8Array(t),r=0,o=!0,s=!1,i=void 0;try{for(a=e.updateBatch[Symbol.iterator]();!(o=(u=a.next()).done);o=!0)c=u.value,n.set(c,r),r+=c.length}catch(e){s=!0,i=e}finally{try{o||null==a.return||a.return()}finally{if(s)throw i}}return e.updateBatch=[],d=e.uint8ArrayToBase64(n),e.encryptionEnabled?[4,e.encrypt(d)]:[3,2];case 1:d=l.sent(),l.label=2;case 2:return p=e.generateUpdateId(),h=Date.now(),f=Math.floor(h/100),e.processedUpdates.add("".concat(p,"-").concat(f)),e.roomNode.get("updates").get(p).put({data:d,timestamp:h,sequence:f,size:n.length,encrypted:e.encryptionEnabled}),e.log("📤 Sent update:",n.length,"bytes",e.encryptionEnabled?"(encrypted)":""),[2]}}))}))()}},{key:"onMessage",value:function(e){var t=this;return this._callback=e,function(){t._callback=void 0}}},{key:"isConnected",get:function(){return this._connected}},{key:"generateUpdateId",value:function(){var e="slot-".concat(this.updateSlot);return this.updateSlot=(this.updateSlot+1)%this.BUFFER_SIZE,e}},{key:"uint8ArrayToBase64",value:function(e){for(var t="",n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}},{key:"base64ToUint8Array",value:function(e){for(var t=atob(e),n=new Uint8Array(t.length),r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}},{key:"encrypt",value:function(e){var t=this;return(0,o.default)((function(){return(0,l.__generator)(this,(function(n){switch(n.label){case 0:return t.options.sea&&t.options.password?[4,t.options.sea.encrypt(e,t.options.password)]:[2,e];case 1:return[2,n.sent()]}}))}))()}},{key:"decrypt",value:function(e){var t=this;return(0,o.default)((function(){var n;return(0,l.__generator)(this,(function(r){switch(r.label){case 0:if(!t.options.sea||!t.options.password)return[2,e];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,t.options.sea.decrypt(e,t.options.password)];case 2:return[2,r.sent()||null];case 3:return n=r.sent(),t.log("❌ Decryption failed:",n),[2,null];case 4:return[2]}}))}))()}},{key:"log",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r;this.options.debug&&(r=console).log.apply(r,["[GunTransport]"].concat((0,c.default)(t)))}}]),e}()})),t.register("84cK9",(function(e,t){var n,r,o=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function a(e){if(n===setTimeout)return setTimeout(e,0);if((n===s||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:s}catch(e){n=s}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=i}}();var u,c=[],l=!1,d=-1;function p(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&h())}function h(){if(!l){var e=a(p);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d<t;)u&&u[d].run();d=-1,t=c.length}u=null,l=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===i||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function g(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];c.push(new f(e,t)),1!==c.length||l||a(h)},f.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=g,o.addListener=g,o.once=g,o.off=g,o.removeListener=g,o.removeAllListeners=g,o.emit=g,o.prependListener=g,o.prependOnceListener=g,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}}))}();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function t(t,e,n,s){Object.defineProperty(t,e,{get:n,set:s,enumerable:!0,configurable:!0})}var e=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;e.register("1dThA",(function(n,s){t(n.exports,"Sync",(function(){return c}));var i=e("2Xs1f"),r=e("5Owdb"),o=e("1bOJi"),a=e("akyql");Object.defineProperty(Array.prototype,"flat",{value:function(t=1){return this.reduce((function(e,n){return e.concat(Array.isArray(n)&&t>1?n.flat(t-1):n)}),[])}});class c extends r.Sync{destroy(){var t;null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),super.destroy(),this.gunServer=[],null===(t=this.provider)||void 0===t||t.disconnect()}uniqueID(){const t=super.uniqueID();return t?btoa(t+(this.persistent?"p":"")):null}async connect(t){var e,n,s;super.connect(t),this.gunServer=(null===(e=t.config)||void 0===e?void 0:e.urls)||[],this.persistent=(null===(n=t.config)||void 0===n?void 0:n.persistent)||!1,window.Gun&&(null===(s=window.Gun)||void 0===s?void 0:s.SEA)?this.init(!0):this.load(["https://cdn.jsdelivr.net/npm/gun/gun.js","https://cdn.jsdelivr.net/npm/gun/sea.js"],this)}init(t,e){if(0==this.gunServer.length)return this.sendDisconnectError("You have to provide at least one relay server.");const n=this.uniqueID();if(t&&window.Gun&&n){var s;this.transport=new(0,o.GunTransport)({gun:window.Gun,sea:null===(s=window.Gun)||void 0===s?void 0:s.SEA,peers:this.gunServer,debug:!1,batchInterval:200,gunOptions:{localStorage:!1,radisk:!1},password:this.password}),this.store=n,this.provider=new(0,a.GenericProvider)(this.db.doc,this.transport),this.db.setAwareness(this.provider.awareness);let t=!1;const e=()=>{t||(t=!0,null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),this.sendConnect())};this.provider.on("synced",(t=>{console.log("Document synchronized",t.synced),e()})),this.provider.on("status",(t=>{const n=t.state;console.log(`Status changed: ${n}`,"info"),"connected"===n?this.syncFallbackTimer=setTimeout((()=>{console.log("Sync fallback: no remote peers, proceeding as first peer"),e()}),2e3):"disconnected"===n?console.warn("Disconnected from GunDB relay server"):console.warn(`GunDB status: ${n}`)})),this.provider.pubsub.subscribe("*",((t,e)=>{var n;null===(n=this.onReceive)||void 0===n||n.call(this,e,t)})),this.provider.connect({room:this.store})}else{var i;let t="GunDB unknown error";e?t="Could not load resource: "+e:window.Gun?(null===(i=window.Gun)||void 0===i?void 0:i.SEA)||(t="Could not load GunDB SEA security module"):t="Could not load GunDB interface",this.sendDisconnectError(t)}}pubsubSend(t,e){var n;this.provider&&(this.provider.pubsub.publish(t,e),this.replyOnReceive&&(null===(n=this.onReceive)||void 0===n||n.call(this,t,e)))}constructor(...t){super(...t),(0,i.default)(this,"store",""),(0,i.default)(this,"gunServer",[]),(0,i.default)(this,"persistent",!1),(0,i.default)(this,"syncFallbackTimer",null)}}})),e.register("1bOJi",(function(n,s){t(n.exports,"GunTransport",(function(){return r}));var i=e("dM3DM");class r{async connect(t){if(this._connected)throw new Error("Already connected");this._room=t.room,this.connectionTime=Date.now(),this.log("🔗 Initializing Gun...");const e=(0,i.default)({localStorage:!1,radisk:!1},this.options.gunOptions);this.options.peers.length>0&&(e.peers=this.options.peers,this.log("📡 Connecting to peers:",this.options.peers)),this.gun=new this.options.gun(e),this.roomNode=this.gun.get(`yjs-room-${this._room}`),this.log("✅ Gun initialized for room:",this._room),this.setupUpdateListener(),this.setupAwarenessListener(),this._connected=!0}setupUpdateListener(){let t=0;let e=!1;this.roomNode.get("updates").once((t=>{if(!t)return e=!0,void this.log("📭 No existing updates found");this.log("📥 Loading initial state..."),Object.keys(t).forEach((e=>{if("_"===e)return;const n=t[e];if(!n||!n.data)return;const s=`${e}-${n.sequence||Math.floor(n.timestamp/100)}`;this.processedUpdates.has(s)||this.pendingUpdates.set(s,n)})),this.processPendingUpdates(),e=!0,this.log("✅ Initial state loaded")})),this.updateListener=this.roomNode.get("updates").map().on(((n,s)=>{if(!e)return;if(!n||!n.data)return;if(n.timestamp&&n.timestamp<this.connectionTime)return;const i=`${s}-${n.sequence||Math.floor(n.timestamp/100)}`;if(this.processedUpdates.has(i))return;this.pendingUpdates.set(i,n);const r=Date.now();r-t<300?this.throttleTimeout||(this.throttleTimeout=setTimeout((()=>{this.processPendingUpdates(),t=Date.now(),this.throttleTimeout=void 0}),300)):(t=r,this.processPendingUpdates())})),this.log("👂 Listening for new updates...")}async processPendingUpdates(){if(0===this.pendingUpdates.size)return;const t=Array.from(this.pendingUpdates.entries());this.pendingUpdates.clear();for(const[e,n]of t){if(this.processedUpdates.add(e),this.processedUpdates.size>200){const t=Array.from(this.processedUpdates);t.slice(0,t.length-200).forEach((t=>{this.processedUpdates.delete(t)}))}try{let e=n.data;if(n.encrypted&&this.encryptionEnabled&&(e=await this.decrypt(e),!e)){this.log("❌ Failed to decrypt update (wrong password?)");continue}const s=this.base64ToUint8Array(e);this._callback&&this._callback(s),1===t.length&&this.log("📥 Received update:",s.length,"bytes",n.encrypted?"(decrypted)":"")}catch(t){this.log("❌ Error processing update:",t)}}t.length>1&&this.log(`📥 Processed ${t.length} batched updates`)}disconnect(){this._connected&&(this.log("👋 Disconnecting..."),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=void 0),this.throttleTimeout&&(clearTimeout(this.throttleTimeout),this.throttleTimeout=void 0),this.processPendingUpdates(),this.flushBatch(),this.updateListener&&(this.updateListener=null),this.awarenessListener&&(this.awarenessListener=null),this.roomNode=null,this.gun=null,this._connected=!1,this.processedUpdates.clear(),this.pendingUpdates.clear(),this.log("✅ Disconnected"))}send(t){if(!this._connected||!this.roomNode)return void this.log("⚠️ Not connected, cannot send");1!==this.peekMessageType(t)?(this.updateBatch.push(t),this.batchTimeout&&clearTimeout(this.batchTimeout),this.batchTimeout=setTimeout((()=>{this.flushBatch()}),this.options.batchInterval)):this.sendAwareness(t)}peekMessageType(t){return t.length<5?-1:t[4]}async sendAwareness(t){let e=this.uint8ArrayToBase64(t);this.encryptionEnabled&&(e=await this.encrypt(e));const n=`aware-${Date.now()}-${Math.random().toString(36).substr(2,5)}`;this.lastAwarenessId=n,this.roomNode.get("awareness").put({data:e,id:n,timestamp:Date.now(),encrypted:this.encryptionEnabled}),this.log("📤 Sent awareness update",this.encryptionEnabled?"(encrypted)":"")}setupAwarenessListener(){this.awarenessListener=this.roomNode.get("awareness").on((async t=>{if(t&&t.data&&t.id!==this.lastAwarenessId&&!(t.timestamp&&t.timestamp<this.connectionTime))try{let e=t.data;if(t.encrypted&&this.encryptionEnabled&&(e=await this.decrypt(e),!e))return void this.log("❌ Failed to decrypt awareness (wrong password?)");const n=this.base64ToUint8Array(e);this._callback&&this._callback(n),this.log("📥 Received awareness update",t.encrypted?"(decrypted)":"")}catch(t){this.log("❌ Error processing awareness:",t)}})),this.log("👂 Listening for awareness updates...")}async flushBatch(){if(0===this.updateBatch.length)return;const t=this.updateBatch.reduce(((t,e)=>t+e.length),0),e=new Uint8Array(t);let n=0;for(const t of this.updateBatch)e.set(t,n),n+=t.length;this.updateBatch=[];let s=this.uint8ArrayToBase64(e);this.encryptionEnabled&&(s=await this.encrypt(s));const i=this.generateUpdateId(),r=Date.now(),o=Math.floor(r/100);this.processedUpdates.add(`${i}-${o}`);this.roomNode.get("updates").get(i).put({data:s,timestamp:r,sequence:o,size:e.length,encrypted:this.encryptionEnabled}),this.log("📤 Sent update:",e.length,"bytes",this.encryptionEnabled?"(encrypted)":"")}onMessage(t){return this._callback=t,()=>{this._callback=void 0}}get isConnected(){return this._connected}generateUpdateId(){const t=`slot-${this.updateSlot}`;return this.updateSlot=(this.updateSlot+1)%this.BUFFER_SIZE,t}uint8ArrayToBase64(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}base64ToUint8Array(t){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}async encrypt(t){return this.options.sea&&this.options.password?await this.options.sea.encrypt(t,this.options.password):t}async decrypt(t){if(!this.options.sea||!this.options.password)return t;try{return await this.options.sea.decrypt(t,this.options.password)||null}catch(t){return this.log("❌ Decryption failed:",t),null}}log(...t){this.options.debug&&console.log("[GunTransport]",...t)}constructor(t){if(this._connected=!1,this._room="",this.gun=null,this.roomNode=null,this.updateListener=null,this.lastUpdateTime=0,this.updateBatch=[],this.processedUpdates=new Set,this.connectionTime=0,this.pendingUpdates=new Map,this.updateSlot=0,this.BUFFER_SIZE=20,this.awarenessListener=null,this.lastAwarenessId="",this.encryptionEnabled=!1,!t.gun)throw new Error('GunTransport requires the "gun" option. Please provide the Gun constructor: import Gun from "gun"; new GunTransport({ gun: Gun, ... })');if(t.password&&!t.sea)throw new Error('GunTransport requires the "sea" option when using password encryption. Please provide Gun.SEA: import "gun/sea"; new GunTransport({ gun: Gun, sea: Gun.SEA, password: "..." })');var e,n,s,i;this.options={gun:t.gun,peers:null!==(e=t.peers)&&void 0!==e?e:[],gunOptions:null!==(n=t.gunOptions)&&void 0!==n?n:{},debug:null!==(s=t.debug)&&void 0!==s&&s,batchInterval:null!==(i=t.batchInterval)&&void 0!==i?i:100,password:t.password,sea:t.sea},this.encryptionEnabled=!(!t.password||!t.sea),this.encryptionEnabled&&this.log("🔐 Encryption enabled")}}})),e.register("jhEmn",(function(t,e){var n,s,i=t.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===r||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:r}catch(t){n=r}try{s="function"==typeof clearTimeout?clearTimeout:o}catch(t){s=o}}();var c,h=[],d=!1,u=-1;function l(){d&&c&&(d=!1,c.length?h=c.concat(h):u=-1,h.length&&p())}function p(){if(!d){var t=a(l);d=!0;for(var e=h.length;e;){for(c=h,h=[];++u<e;)c&&c[u].run();u=-1,e=h.length}c=null,d=!1,function(t){if(s===clearTimeout)return clearTimeout(t);if((s===o||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(t);try{return s(t)}catch(e){try{return s.call(null,t)}catch(e){return s.call(this,t)}}}(t)}}function g(t,e){this.fun=t,this.array=e}function f(){}i.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];h.push(new g(t,e)),1!==h.length||d||a(p)},g.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=f,i.addListener=f,i.once=f,i.off=f,i.removeListener=f,i.removeAllListeners=f,i.emit=f,i.prependListener=f,i.prependOnceListener=f,i.listeners=function(t){return[]},i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}}));
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
!function(){function e(e,r,o,n){Object.defineProperty(e,r,{get:o,set:n,enumerable:!0,configurable:!0})}var r=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;r.register("kjbyJ",(function(o,n){e(o.exports,"Sync",(function(){return m}));var t=r("f1evb"),i=r("hnmIs"),a=r("9Klpk"),s=r("3bWnf"),c=r("eT7f3"),l=r("9WzNc"),d=r("div3d"),u=r("kb0qF"),p=r("bgoEC"),h=r("bWNdT"),f=r("32Euv"),v=r("auvHb"),y=r("48SmG"),g=r("733OA"),m=function(e){"use strict";(0,u.default)(o,e);var r=(0,h.default)(o);function o(){var e;return(0,a.default)(this,o),e=r.apply(this,arguments),(0,c.default)((0,t.default)(e),"syncFallbackTimer",null),e}return(0,s.default)(o,[{key:"destroy",value:function(){var e;null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),(0,l.default)((0,d.default)(o.prototype),"destroy",this).call(this),null===(e=this.provider)||void 0===e||e.disconnect()}},{key:"connect",value:function(e){var r=this,n=this;return(0,i.default)((function(){var t,i,a,s;return(0,f.__generator)(this,(function(c){if((0,l.default)((0,d.default)(o.prototype),"connect",r).call(n,e),n.host=(null===(t=e.config)||void 0===t?void 0:t.host)||void 0,n.port=(null===(i=e.config)||void 0===i?void 0:i.port)?parseInt(e.config.port,10):void 0,n.peerPath=(null===(a=e.config)||void 0===a?void 0:a.path)||void 0,null===(s=e.config)||void 0===s?void 0:s.iceServers)try{n.iceServers=JSON.parse(e.config.iceServers)}catch(r){console.warn("PeerJS: invalid iceServers JSON, ignoring:",e.config.iceServers)}return window.Peer?n.init(!0):n.load(["//unpkg.com/peerjs@1.5.4/dist/peerjs.min.js"],n),[2]}))}))()}},{key:"init",value:function(e,r){var o=this,n=this.uniqueID();if(e&&window.Peer&&n)(function(e){return w.apply(this,arguments)})(n).then((function(e){var r={};o.host&&(r.host=o.host,r.secure=!0),void 0!==o.port&&(r.port=o.port),o.peerPath&&(r.path=o.peerPath),o.iceServers&&(r.config={iceServers:o.iceServers}),o.transport=new(0,y.PeerJSTransport)((0,p.default)({peer:window.Peer},Object.keys(r).length>0?{peerOptions:r}:{},o.password?{password:o.password}:{})),o.provider=new(0,g.GenericProvider)(o.db.doc,o.transport),o.db.setAwareness(o.provider.awareness);var n=!1,t=function(){n||(n=!0,null!==o.syncFallbackTimer&&(clearTimeout(o.syncFallbackTimer),o.syncFallbackTimer=null),o.sendConnect())};o.provider.on("synced",(function(e){console.log("PeerJS: document synchronized",e.synced),t()})),o.provider.on("status",(function(e){var r=e.state;console.log("PeerJS status: ".concat(r)),"connected"===r?o.syncFallbackTimer=setTimeout((function(){console.log("PeerJS: sync fallback, proceeding as first peer"),t()}),2e3):"disconnected"===r&&console.warn("PeerJS: disconnected")})),o.provider.pubsub.subscribe("*",(function(e,r){var n,t;null===(t=(n=o).onReceive)||void 0===t||t.call(n,r,e)})),o.provider.connect((0,p.default)({room:e},o.password?{password:o.password}:{}))}));else{var t="PeerJS unknown error";r?t="Could not load resource: "+r:window.Peer||(t="Could not load PeerJS library"),this.sendDisconnectError(t)}}},{key:"pubsubSend",value:function(e,r){var o;this.provider&&(this.provider.pubsub.publish(e,r),this.replyOnReceive&&(null===(o=this.onReceive)||void 0===o||o.call(this,e,r)))}}]),o}(v.Sync);function w(){return(w=(0,i.default)((function(e){var r,o;return(0,f.__generator)(this,(function(n){switch(n.label){case 0:return r=(new TextEncoder).encode(e),[4,crypto.subtle.digest("SHA-256",r)];case 1:return o=n.sent(),[2,Array.from(new Uint8Array(o)).map((function(e){return e.toString(16).padStart(2,"0")})).join("")]}}))}))).apply(this,arguments)}})),r.register("48SmG",(function(o,n){e(o.exports,"PeerJSTransport",(function(){return u}));var t=r("hnmIs"),i=r("9Klpk"),a=r("3bWnf"),s=r("bgoEC"),c=r("5ENmm"),l=r("6Wo7Q"),d=r("32Euv"),u=function(){"use strict";function e(r){if((0,i.default)(this,e),this._connected=!1,this._room="",this.peer=null,this.peerId="",this.peers=new Map,this.knownPeers=new Set,this.isCoordinator=!1,this.coordinatorPeerId="",this.roomPeers=new Set,this.reElectionInProgress=!1,!r.peer)throw new Error('PeerJSTransport requires the "peer" option. Please provide the PeerJS constructor: import Peer from "peerjs"; new PeerJSTransport({ peer: Peer, ... })');var o,n,t,a;this.options={peer:r.peer,peerOptions:null!==(o=r.peerOptions)&&void 0!==o?o:{},password:null!==(n=r.password)&&void 0!==n?n:"",maxConns:null!==(t=r.maxConns)&&void 0!==t?t:20+Math.floor(15*Math.random()),debug:null!==(a=r.debug)&&void 0!==a&&a}}return(0,a.default)(e,[{key:"connect",value:function(e){var r=this;return(0,t.default)((function(){return(0,d.__generator)(this,(function(o){if(r._connected)throw new Error("Already connected");return r._room=e.room,r.coordinatorPeerId="yjs-coordinator-".concat(r._room),[2,new Promise((function(e,o){try{var n=new r.options.peer(r.coordinatorPeerId,(0,s.default)({debug:r.options.debug?3:0},r.options.peerOptions)),t=setTimeout((function(){n.destroy(),r.createRegularPeer(e,o)}),3e3);n.on("open",(function(o){clearTimeout(t),o===r.coordinatorPeerId&&(r.log("Coordinator: claimed ID"),r.peer=n,r.peerId=o,r.isCoordinator=!0,r.roomPeers.add(r.peerId),r._connected=!0,r.setupPeerDiscovery(),r.peer.on("connection",(function(e){r.handleIncomingConnection(e)})),e())})),n.on("error",(function(i){clearTimeout(t),i.message.includes("ID is taken")||i.message.includes("taken")||i.message.includes("already")||"unavailable-id"===i.type?(n.destroy(),r.createRegularPeer(e,o)):(r.log("❌ Unexpected error claiming coordinator:",i),n.destroy(),r.createRegularPeer(e,o))}))}catch(e){o(e)}}))]}))}))()}},{key:"createRegularPeer",value:function(e,r){var o=this,n=Math.random().toString(36).substring(7);this.peerId="yjs-".concat(this._room,"-").concat(n),this.peer=new this.options.peer(this.peerId,(0,s.default)({debug:this.options.debug?3:0},this.options.peerOptions)),this.peer.on("open",(function(r){o.peerId=r,o._connected=!0,o.setupPeerDiscovery(),o.peer.on("connection",(function(e){o.handleIncomingConnection(e)})),o.setupCrossBrowserDiscovery().then((function(){e()})).catch((function(r){o.log("⚠️ Cross-browser discovery failed, continuing with BroadcastChannel only:",r),e()}))})),this.peer.on("error",(function(e){o.log("Peer error:",e),o._connected||r(e)})),this.peer.on("disconnected",(function(){o.log("Peer disconnected, attempting reconnect...")}))}},{key:"disconnect",value:function(){if(this._connected){if(this.discoveryInterval&&(clearInterval(this.discoveryInterval),this.discoveryInterval=void 0),this.broadcastChannel&&(this.broadcastChannel.postMessage({type:"leave",peerId:this.peerId}),this.broadcastChannel.close(),this.broadcastChannel=void 0),this.coordinatorConn){try{this.sendCoordinationMessage(this.coordinatorConn,{type:"leave",peerId:this.peerId}),this.coordinatorConn.close()}catch(e){}this.coordinatorConn=void 0}if(this.isCoordinator){var e=!0,r=!1,o=void 0;try{for(var n,t=this.roomPeers[Symbol.iterator]();!(e=(n=t.next()).done);e=!0){var i=n.value;if(i!==this.peerId){var a=this.peers.get(i);if(a&&a.connected)try{this.sendCoordinationMessage(a.conn,{type:"coordinator-leaving",peerId:this.peerId})}catch(e){}}}}catch(e){r=!0,o=e}finally{try{e||null==t.return||t.return()}finally{if(r)throw o}}this.isCoordinator=!1,this.roomPeers.clear()}var s=!0,c=!1,l=void 0;try{for(var d,u=this.peers.values()[Symbol.iterator]();!(s=(d=u.next()).done);s=!0){var p=d.value;try{p.conn.close()}catch(e){}}}catch(e){c=!0,l=e}finally{try{s||null==u.return||u.return()}finally{if(c)throw l}}this.peers.clear(),this.knownPeers.clear(),this.reElectionInProgress=!1,this.peer&&(this.peer.destroy(),this.peer=null),this._connected=!1}}},{key:"onPeerConnect",value:function(e){var r=this;return this._peerConnectCallback=e,function(){r._peerConnectCallback=void 0}}},{key:"send",value:function(e){if(this._connected){var r=this.options.password?this.encrypt(e,this.options.password):e,o=!0,n=!1,t=void 0;try{for(var i,a=this.peers.values()[Symbol.iterator]();!(o=(i=a.next()).done);o=!0){var s=i.value;if(s.connected)try{s.conn.send(r)}catch(e){this.log("Error sending to peer:",s.peerId,e)}}}catch(e){n=!0,t=e}finally{try{o||null==a.return||a.return()}finally{if(n)throw t}}}else this.log("Not connected, cannot send")}},{key:"onMessage",value:function(e){var r=this;return this._callback=e,function(){r._callback=void 0}}},{key:"isConnected",get:function(){return this._connected}},{key:"connectedPeers",get:function(){return Array.from(this.peers.values()).filter((function(e){return e.connected})).length}},{key:"setupPeerDiscovery",value:function(){var e=this;if("undefined"!=typeof BroadcastChannel){var r="yjs-peerjs-".concat(this._room);this.broadcastChannel=new BroadcastChannel(r),this.broadcastChannel.onmessage=function(r){var o=r.data;o.peerId!==e.peerId&&("announce"===o.type?(e.knownPeers.add(o.peerId),e.connectToPeer(o.peerId)):"leave"===o.type&&(e.knownPeers.delete(o.peerId),e.removePeer(o.peerId)))},this.announcePeer(),this.discoveryInterval=setInterval((function(){e._connected&&e.peers.size<e.options.maxConns&&e.announcePeer()}),5e3)}else this.log("❌ BroadcastChannel not available in this browser")}},{key:"announcePeer",value:function(){if(this.broadcastChannel){var e={type:"announce",peerId:this.peerId};this.broadcastChannel.postMessage(e)}}},{key:"setupCrossBrowserDiscovery",value:function(){var e=this;return(0,t.default)((function(){return(0,d.__generator)(this,(function(r){switch(r.label){case 0:return[4,new Promise((function(e){return setTimeout(e,500)}))];case 1:return r.sent(),[2,new Promise((function(r,o){var n=!1,t=setTimeout((function(){if(!n){n=!0;var r=new Error("Timeout connecting to coordinator");e.log("⏱️ Timeout connecting to coordinator"),o(r)}}),5e3);try{var i=e.peer.connect(e.coordinatorPeerId,{reliable:!0,serialization:"binary",metadata:{role:"peer",peerId:e.peerId}});i.on("open",(function(){var o,a;if(!n){n=!0,clearTimeout(t),e.log("Connected to coordinator"),e.coordinatorConn=i;var s={conn:i,connected:!0,peerId:e.coordinatorPeerId};e.peers.set(e.coordinatorPeerId,s),e.knownPeers.add(e.coordinatorPeerId),null===(a=(o=e)._peerConnectCallback)||void 0===a||a.call(o,e.coordinatorPeerId),e.sendCoordinationMessage(i,{type:"join",peerId:e.peerId}),i.on("data",(function(r){var o=r instanceof Uint8Array?r:new Uint8Array(r),n=e.tryDecodeCoordinationMessage(o);if(n)e.handleCoordinatorMessage(n);else if(e._callback)try{var t=e.options.password?e.decrypt(o,e.options.password):o;e._callback(t)}catch(r){e.log("Error handling coordinator data:",r)}})),i.on("close",(function(){e.log("Coordinator disconnected"),e.peers.delete(e.coordinatorPeerId),e.knownPeers.delete(e.coordinatorPeerId),e.handleCoordinatorDisconnect()})),r()}})),i.on("error",(function(r){n||(n=!0,clearTimeout(t),e.log("❌ Failed to connect to coordinator:",r.message),o(r))}))}catch(r){n||(n=!0,clearTimeout(t),e.log("⚠️ Error connecting to coordinator:",r),o(r))}}))]}}))}))()}},{key:"becomeCoordinator",value:function(){var e=this;this.isCoordinator=!0,this.roomPeers.add(this.peerId),this.log("👑 I am now the coordinator. Room peers:",Array.from(this.roomPeers)),setInterval((function(){if(e.isCoordinator){var r=Array.from(e.roomPeers).sort();r.length>0&&r[0]!==e.peerId&&(e.log("⚠️ I am no longer the lowest ID peer, stepping down as coordinator"),e.isCoordinator=!1)}}),1e4)}},{key:"handleCoordinatorMessage",value:function(e){switch(e.type){case"peer-list":var r=!0,o=!1,n=void 0;try{for(var t,i=e.peers[Symbol.iterator]();!(r=(t=i.next()).done);r=!0){var a=t.value;a===this.peerId||this.peers.has(a)||(this.knownPeers.add(a),this.connectToPeer(a))}}catch(e){o=!0,n=e}finally{try{r||null==i.return||i.return()}finally{if(o)throw n}}break;case"peer-joined":e.peerId===this.peerId||this.peers.has(e.peerId)||(this.knownPeers.add(e.peerId),this.connectToPeer(e.peerId));break;case"peer-left":this.knownPeers.delete(e.peerId),this.removePeer(e.peerId);break;case"coordinator-change":this.coordinatorPeerId=e.coordinatorId;break;case"coordinator-leaving":this.log("Coordinator leaving, re-election starting"),this.handleCoordinatorDisconnect()}}},{key:"handleCoordinatorDisconnect",value:function(){var e=this;if(this.reElectionInProgress)this.log("⏭️ Re-election already in progress, skipping");else if("undefined"==typeof navigator||navigator.onLine){this.log("🗳️ Coordinator disconnected, starting re-election"),this.reElectionInProgress=!0,this.coordinatorConn=void 0;var r=[this.peerId].concat((0,l.default)(Array.from(this.knownPeers)),(0,l.default)(Array.from(this.peers.keys()))).filter((function(r){return r!==e.coordinatorPeerId}));r.sort();var o=r[0];this.log("🗳️ Coordinator election: Lowest peer ID is",o),o===this.peerId?(this.log("👑 I have the lowest ID, attempting to claim coordinator role"),this.transitionToCoordinator()):(this.log("⏳ Waiting for new coordinator:",o),setTimeout((function(){e.attemptCoordinatorConnection()}),2e3))}else{this.log("📴 Offline – deferring re-election until network returns");window.addEventListener("online",(function(){e.log("🌐 Network restored – resuming re-election"),e.handleCoordinatorDisconnect()}),{once:!0})}}},{key:"attemptCoordinatorConnection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=this;if(e>=5)return this.log("❌ Failed to connect to coordinator after",5,"attempts"),this.log("🔄 Attempting to become coordinator as fallback"),void this.transitionToCoordinator();this.log("🔌 Attempting to connect to coordinator (attempt ".concat(e+1,"/").concat(5,")")),this.setupCrossBrowserDiscovery().then((function(){r.log("✅ Successfully connected to new coordinator"),r.reElectionInProgress=!1})).catch((function(o){r.log("⚠️ Failed to connect to coordinator (attempt ".concat(e+1,"):"),o);var n=1e3*Math.pow(1.5,e);setTimeout((function(){r.attemptCoordinatorConnection(e+1)}),n)}))}},{key:"transitionToCoordinator",value:function(){var e=this;return(0,t.default)((function(){var r,o,n;return(0,d.__generator)(this,(function(t){switch(t.label){case 0:e.log("🔄 Transitioning to coordinator role..."),r=Array.from(e.peers.entries()),o=e._callback,e._room,e.peer&&e.peer.destroy(),e.peers.clear(),e._connected=!1,t.label=1;case 1:return t.trys.push([1,3,,4]),[4,new Promise((function(n,t){var i=new e.options.peer(e.coordinatorPeerId,(0,s.default)({debug:e.options.debug?3:0},e.options.peerOptions)),a=setTimeout((function(){e.log("❌ Timeout claiming coordinator ID"),i.destroy(),t(new Error("Timeout claiming coordinator ID"))}),5e3);i.on("open",(function(t){if(clearTimeout(a),t===e.coordinatorPeerId){e.log("✅ Successfully claimed coordinator ID:",t),e.peer=i,e.peerId=t,e.isCoordinator=!0,e.roomPeers.clear(),e.roomPeers.add(e.peerId),e._connected=!0,e._callback=o,e.reElectionInProgress=!1,e.setupPeerDiscovery(),e.peer.on("connection",(function(r){e.handleIncomingConnection(r)})),e.log("🔗 Re-establishing connections with",r.length,"known peers");var s=!0,l=!1,d=void 0;try{for(var u,p=r[Symbol.iterator]();!(s=(u=p.next()).done);s=!0){var h=(0,c.default)(u.value,2),f=h[0];h[1];f!==e.coordinatorPeerId&&(e.knownPeers.add(f),e.roomPeers.add(f))}}catch(e){l=!0,d=e}finally{try{s||null==p.return||p.return()}finally{if(l)throw d}}n()}})),i.on("error",(function(r){clearTimeout(a),e.log("❌ Error claiming coordinator ID:",r),i.destroy(),t(r)}))}))];case 2:return t.sent(),[3,4];case 3:return n=t.sent(),e.log("❌ Failed to transition to coordinator:",n),e.reElectionInProgress=!1,e.log("🔄 Falling back to regular peer"),e.reestablishAsRegularPeer(),[3,4];case 4:return[2]}}))}))()}},{key:"reestablishAsRegularPeer",value:function(){var e=this,r=Math.random().toString(36).substring(7);this.peerId="yjs-".concat(this._room,"-").concat(r),this.isCoordinator=!1,this.peer=new this.options.peer(this.peerId,(0,s.default)({debug:this.options.debug?3:0},this.options.peerOptions)),this.peer.on("open",(function(r){e.peerId=r,e._connected=!0,e.log("✅ Reestablished as regular peer:",r),e.setupPeerDiscovery(),e.peer.on("connection",(function(r){e.handleIncomingConnection(r)})),e.peer.on("disconnected",(function(){e.log("Peer disconnected, attempting reconnect...")})),e.attemptCoordinatorConnection()})),this.peer.on("error",(function(r){e.log("❌ Error reestablishing as regular peer:",r);try{var o;null===(o=e.peer)||void 0===o||o.destroy()}catch(e){}e.peer=null,e._connected=!1;var n=function(){e.log("🌐 Network restored – retrying reestablish as regular peer"),e.reestablishAsRegularPeer()};"undefined"==typeof navigator||navigator.onLine?setTimeout(n,3e3):window.addEventListener("online",n,{once:!0})}))}},{key:"connectToPeer",value:function(e){if(e!==this.peerId&&!this.peers.has(e)&&!(this.peers.size>=this.options.maxConns||this.peerId&&this.peerId>e))try{var r=this.peer.connect(e,{reliable:!0,serialization:"binary"});if(!r)return void this.log("Failed to create connection object for:",e);this.setupConnection(r,e)}catch(r){this.log("Error connecting to peer:",e,r)}}},{key:"handleIncomingConnection",value:function(e){var r=this,o=e.peer;if(this.peers.has(o))e.close();else{if(this.peers.size>=this.options.maxConns)return this.log("Max connections reached, rejecting peer:",o),void e.close();this.isCoordinator&&(this.roomPeers.add(o),e.on("close",(function(){r.roomPeers.delete(o);var e=!0,n=!1,t=void 0;try{for(var i,a=r.roomPeers[Symbol.iterator]();!(e=(i=a.next()).done);e=!0){var s=i.value;if(s!==r.peerId){var c=r.peers.get(s);if(c&&c.connected)try{r.sendCoordinationMessage(c.conn,{type:"peer-left",peerId:o})}catch(e){r.log("⚠️ Failed to notify peer of departure:",s)}}}}catch(e){n=!0,t=e}finally{try{e||null==a.return||a.return()}finally{if(n)throw t}}}))),this.setupConnection(e,o)}}},{key:"setupConnection",value:function(e,r){var o=this,n={conn:e,connected:!1,peerId:r};this.peers.set(r,n),e.on("open",(function(){var e,t;n.connected=!0,o.knownPeers.add(r),null===(t=(e=o)._peerConnectCallback)||void 0===t||t.call(e,r)})),e.on("data",(function(n){var t=n instanceof Uint8Array?n:new Uint8Array(n),i=o.tryDecodeCoordinationMessage(t);if(i){if("coordinator-change"===i.type||"coordinator-leaving"===i.type||"peer-joined"===i.type||"peer-left"===i.type||"peer-list"===i.type)return void o.handleCoordinatorMessage(i);if("join"===i.type&&o.isCoordinator){var a=Array.from(o.roomPeers).filter((function(e){return e!==o.peerId&&e!==r}));o.sendCoordinationMessage(e,{type:"peer-list",peers:a});var s=!0,c=!1,l=void 0;try{for(var d,u=o.roomPeers[Symbol.iterator]();!(s=(d=u.next()).done);s=!0){var p=d.value;if(p!==o.peerId&&p!==r){var h=o.peers.get(p);if(h&&h.connected)try{o.sendCoordinationMessage(h.conn,{type:"peer-joined",peerId:r})}catch(e){o.log("⚠️ Failed to notify peer of new joiner:",p)}}}}catch(e){c=!0,l=e}finally{try{s||null==u.return||u.return()}finally{if(c)throw l}}return}}if(o._callback)try{var f=o.options.password?o.decrypt(t,o.options.password):t;o._callback(f)}catch(e){o.log("Error handling peer data:",e)}})),e.on("close",(function(){o.removePeer(r)})),e.on("error",(function(e){o.log("⚠️ Connection error:",r,e),o.removePeer(r)})),setTimeout((function(){}),1e3)}},{key:"removePeer",value:function(e){var r=this.peers.get(e);if(r){try{r.conn.close()}catch(e){}this.peers.delete(e)}}},{key:"sendCoordinationMessage",value:function(e,r){try{var o=JSON.stringify(r),n=(new TextEncoder).encode(o);e.send(n)}catch(e){this.log("Error encoding coordination message:",e)}}},{key:"tryDecodeCoordinationMessage",value:function(e){try{var r=(new TextDecoder).decode(e),o=JSON.parse(r);return o&&"object"==typeof o&&o.type&&"string"==typeof o.type?o:null}catch(e){return null}}},{key:"encrypt",value:function(e,r){for(var o=this.hashPassword(r),n=new Uint8Array(e.length),t=0;t<e.length;t++)n[t]=e[t]^o[t%o.length];return n}},{key:"decrypt",value:function(e,r){return this.encrypt(e,r)}},{key:"hashPassword",value:function(e){return(new TextEncoder).encode(e)}},{key:"log",value:function(){for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];var n;this.options.debug&&(n=console).log.apply(n,["[PeerJSTransport]"].concat((0,l.default)(r)))}}]),e}()})),r.register("84cK9",(function(e,r){var o,n,t=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(o===setTimeout)return setTimeout(e,0);if((o===i||!o)&&setTimeout)return o=setTimeout,setTimeout(e,0);try{return o(e,0)}catch(r){try{return o.call(null,e,0)}catch(r){return o.call(this,e,0)}}}!function(){try{o="function"==typeof setTimeout?setTimeout:i}catch(e){o=i}try{n="function"==typeof clearTimeout?clearTimeout:a}catch(e){n=a}}();var c,l=[],d=!1,u=-1;function p(){d&&c&&(d=!1,c.length?l=c.concat(l):u=-1,l.length&&h())}function h(){if(!d){var e=s(p);d=!0;for(var r=l.length;r;){for(c=l,l=[];++u<r;)c&&c[u].run();u=-1,r=l.length}c=null,d=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===a||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{return n(e)}catch(r){try{return n.call(null,e)}catch(r){return n.call(this,e)}}}(e)}}function f(e,r){this.fun=e,this.array=r}function v(){}t.nextTick=function(e){var r=new Array(arguments.length-1);if(arguments.length>1)for(var o=1;o<arguments.length;o++)r[o-1]=arguments[o];l.push(new f(e,r)),1!==l.length||d||s(h)},f.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={},t.on=v,t.addListener=v,t.once=v,t.off=v,t.removeListener=v,t.removeAllListeners=v,t.emit=v,t.prependListener=v,t.prependOnceListener=v,t.listeners=function(e){return[]},t.binding=function(e){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(e){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}))}();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e,t,o,r){Object.defineProperty(e,t,{get:o,set:r,enumerable:!0,configurable:!0})}var t=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;t.register("b8krL",(function(o,r){e(o.exports,"Sync",(function(){return h}));var n=t("2Xs1f"),i=t("dM3DM"),s=t("5Owdb"),c=t("khIMP"),a=t("akyql");class h extends s.Sync{destroy(){var e;null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),super.destroy(),null===(e=this.provider)||void 0===e||e.disconnect()}async connect(e){var t,o,r,n;if(super.connect(e),this.host=(null===(t=e.config)||void 0===t?void 0:t.host)||void 0,this.port=(null===(o=e.config)||void 0===o?void 0:o.port)?parseInt(e.config.port,10):void 0,this.peerPath=(null===(r=e.config)||void 0===r?void 0:r.path)||void 0,null===(n=e.config)||void 0===n?void 0:n.iceServers)try{this.iceServers=JSON.parse(e.config.iceServers)}catch(t){console.warn("PeerJS: invalid iceServers JSON, ignoring:",e.config.iceServers)}window.Peer?this.init(!0):this.load(["//unpkg.com/peerjs@1.5.4/dist/peerjs.min.js"],this)}init(e,t){const o=this.uniqueID();if(e&&window.Peer&&o)(async function(e){const t=(new TextEncoder).encode(e),o=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(o)).map((e=>e.toString(16).padStart(2,"0"))).join("")})(o).then((e=>{const t={};this.host&&(t.host=this.host,t.secure=!0),void 0!==this.port&&(t.port=this.port),this.peerPath&&(t.path=this.peerPath),this.iceServers&&(t.config={iceServers:this.iceServers}),this.transport=new(0,c.PeerJSTransport)((0,i.default)({peer:window.Peer},Object.keys(t).length>0?{peerOptions:t}:{},this.password?{password:this.password}:{})),this.provider=new(0,a.GenericProvider)(this.db.doc,this.transport),this.db.setAwareness(this.provider.awareness);let o=!1;const r=()=>{o||(o=!0,null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),this.sendConnect())};this.provider.on("synced",(e=>{console.log("PeerJS: document synchronized",e.synced),r()})),this.provider.on("status",(e=>{const t=e.state;console.log(`PeerJS status: ${t}`),"connected"===t?this.syncFallbackTimer=setTimeout((()=>{console.log("PeerJS: sync fallback, proceeding as first peer"),r()}),2e3):"disconnected"===t&&console.warn("PeerJS: disconnected")})),this.provider.pubsub.subscribe("*",((e,t)=>{var o;null===(o=this.onReceive)||void 0===o||o.call(this,t,e)})),this.provider.connect((0,i.default)({room:e},this.password?{password:this.password}:{}))}));else{let e="PeerJS unknown error";t?e="Could not load resource: "+t:window.Peer||(e="Could not load PeerJS library"),this.sendDisconnectError(e)}}pubsubSend(e,t){var o;this.provider&&(this.provider.pubsub.publish(e,t),this.replyOnReceive&&(null===(o=this.onReceive)||void 0===o||o.call(this,e,t)))}constructor(...e){super(...e),(0,n.default)(this,"syncFallbackTimer",null)}}})),t.register("khIMP",(function(o,r){e(o.exports,"PeerJSTransport",(function(){return i}));var n=t("dM3DM");class i{async connect(e){if(this._connected)throw new Error("Already connected");return this._room=e.room,this.coordinatorPeerId=`yjs-coordinator-${this._room}`,new Promise(((e,t)=>{try{let o=new this.options.peer(this.coordinatorPeerId,(0,n.default)({debug:this.options.debug?3:0},this.options.peerOptions));const r=setTimeout((()=>{o.destroy(),this.createRegularPeer(e,t)}),3e3);o.on("open",(t=>{clearTimeout(r),t===this.coordinatorPeerId&&(this.log("Coordinator: claimed ID"),this.peer=o,this.peerId=t,this.isCoordinator=!0,this.roomPeers.add(this.peerId),this._connected=!0,this.setupPeerDiscovery(),this.peer.on("connection",(e=>{this.handleIncomingConnection(e)})),e())})),o.on("error",(n=>{clearTimeout(r),n.message.includes("ID is taken")||n.message.includes("taken")||n.message.includes("already")||"unavailable-id"===n.type?(o.destroy(),this.createRegularPeer(e,t)):(this.log("❌ Unexpected error claiming coordinator:",n),o.destroy(),this.createRegularPeer(e,t))}))}catch(e){t(e)}}))}createRegularPeer(e,t){const o=Math.random().toString(36).substring(7);this.peerId=`yjs-${this._room}-${o}`,this.peer=new this.options.peer(this.peerId,(0,n.default)({debug:this.options.debug?3:0},this.options.peerOptions)),this.peer.on("open",(t=>{this.peerId=t,this._connected=!0,this.setupPeerDiscovery(),this.peer.on("connection",(e=>{this.handleIncomingConnection(e)})),this.setupCrossBrowserDiscovery().then((()=>{e()})).catch((t=>{this.log("⚠️ Cross-browser discovery failed, continuing with BroadcastChannel only:",t),e()}))})),this.peer.on("error",(e=>{this.log("Peer error:",e),this._connected||t(e)})),this.peer.on("disconnected",(()=>{this.log("Peer disconnected, attempting reconnect...")}))}disconnect(){if(this._connected){if(this.discoveryInterval&&(clearInterval(this.discoveryInterval),this.discoveryInterval=void 0),this.broadcastChannel&&(this.broadcastChannel.postMessage({type:"leave",peerId:this.peerId}),this.broadcastChannel.close(),this.broadcastChannel=void 0),this.coordinatorConn){try{this.sendCoordinationMessage(this.coordinatorConn,{type:"leave",peerId:this.peerId}),this.coordinatorConn.close()}catch(e){}this.coordinatorConn=void 0}if(this.isCoordinator){for(const e of this.roomPeers)if(e!==this.peerId){const t=this.peers.get(e);if(t&&t.connected)try{this.sendCoordinationMessage(t.conn,{type:"coordinator-leaving",peerId:this.peerId})}catch(e){}}this.isCoordinator=!1,this.roomPeers.clear()}for(const e of this.peers.values())try{e.conn.close()}catch(e){}this.peers.clear(),this.knownPeers.clear(),this.reElectionInProgress=!1,this.peer&&(this.peer.destroy(),this.peer=null),this._connected=!1}}onPeerConnect(e){return this._peerConnectCallback=e,()=>{this._peerConnectCallback=void 0}}send(e){if(!this._connected)return void this.log("Not connected, cannot send");const t=this.options.password?this.encrypt(e,this.options.password):e;for(const e of this.peers.values())if(e.connected)try{e.conn.send(t)}catch(t){this.log("Error sending to peer:",e.peerId,t)}}onMessage(e){return this._callback=e,()=>{this._callback=void 0}}get isConnected(){return this._connected}get connectedPeers(){return Array.from(this.peers.values()).filter((e=>e.connected)).length}setupPeerDiscovery(){if("undefined"==typeof BroadcastChannel)return void this.log("❌ BroadcastChannel not available in this browser");const e=`yjs-peerjs-${this._room}`;this.broadcastChannel=new BroadcastChannel(e),this.broadcastChannel.onmessage=e=>{const t=e.data;t.peerId!==this.peerId&&("announce"===t.type?(this.knownPeers.add(t.peerId),this.connectToPeer(t.peerId)):"leave"===t.type&&(this.knownPeers.delete(t.peerId),this.removePeer(t.peerId)))},this.announcePeer(),this.discoveryInterval=setInterval((()=>{this._connected&&this.peers.size<this.options.maxConns&&this.announcePeer()}),5e3)}announcePeer(){if(this.broadcastChannel){const e={type:"announce",peerId:this.peerId};this.broadcastChannel.postMessage(e)}}async setupCrossBrowserDiscovery(){return await new Promise((e=>setTimeout(e,500))),new Promise(((e,t)=>{let o=!1;const r=setTimeout((()=>{if(!o){o=!0;const e=new Error("Timeout connecting to coordinator");this.log("⏱️ Timeout connecting to coordinator"),t(e)}}),5e3);try{const n=this.peer.connect(this.coordinatorPeerId,{reliable:!0,serialization:"binary",metadata:{role:"peer",peerId:this.peerId}});n.on("open",(()=>{var t;if(o)return;o=!0,clearTimeout(r),this.log("Connected to coordinator"),this.coordinatorConn=n;const i={conn:n,connected:!0,peerId:this.coordinatorPeerId};this.peers.set(this.coordinatorPeerId,i),this.knownPeers.add(this.coordinatorPeerId),null===(t=this._peerConnectCallback)||void 0===t||t.call(this,this.coordinatorPeerId),this.sendCoordinationMessage(n,{type:"join",peerId:this.peerId}),n.on("data",(e=>{const t=e instanceof Uint8Array?e:new Uint8Array(e),o=this.tryDecodeCoordinationMessage(t);if(o)this.handleCoordinatorMessage(o);else if(this._callback)try{const e=this.options.password?this.decrypt(t,this.options.password):t;this._callback(e)}catch(e){this.log("Error handling coordinator data:",e)}})),n.on("close",(()=>{this.log("Coordinator disconnected"),this.peers.delete(this.coordinatorPeerId),this.knownPeers.delete(this.coordinatorPeerId),this.handleCoordinatorDisconnect()})),e()})),n.on("error",(e=>{o||(o=!0,clearTimeout(r),this.log("❌ Failed to connect to coordinator:",e.message),t(e))}))}catch(e){o||(o=!0,clearTimeout(r),this.log("⚠️ Error connecting to coordinator:",e),t(e))}}))}becomeCoordinator(){this.isCoordinator=!0,this.roomPeers.add(this.peerId),this.log("👑 I am now the coordinator. Room peers:",Array.from(this.roomPeers)),setInterval((()=>{if(this.isCoordinator){const e=Array.from(this.roomPeers).sort();e.length>0&&e[0]!==this.peerId&&(this.log("⚠️ I am no longer the lowest ID peer, stepping down as coordinator"),this.isCoordinator=!1)}}),1e4)}handleCoordinatorMessage(e){switch(e.type){case"peer-list":for(const t of e.peers)t===this.peerId||this.peers.has(t)||(this.knownPeers.add(t),this.connectToPeer(t));break;case"peer-joined":e.peerId===this.peerId||this.peers.has(e.peerId)||(this.knownPeers.add(e.peerId),this.connectToPeer(e.peerId));break;case"peer-left":this.knownPeers.delete(e.peerId),this.removePeer(e.peerId);break;case"coordinator-change":this.coordinatorPeerId=e.coordinatorId;break;case"coordinator-leaving":this.log("Coordinator leaving, re-election starting"),this.handleCoordinatorDisconnect()}}handleCoordinatorDisconnect(){if(this.reElectionInProgress)return void this.log("⏭️ Re-election already in progress, skipping");if("undefined"!=typeof navigator&&!navigator.onLine){this.log("📴 Offline – deferring re-election until network returns");const e=()=>{this.log("🌐 Network restored – resuming re-election"),this.handleCoordinatorDisconnect()};return void window.addEventListener("online",e,{once:!0})}this.log("🗳️ Coordinator disconnected, starting re-election"),this.reElectionInProgress=!0,this.coordinatorConn=void 0;const e=[this.peerId,...Array.from(this.knownPeers),...Array.from(this.peers.keys())].filter((e=>e!==this.coordinatorPeerId));e.sort();const t=e[0];this.log("🗳️ Coordinator election: Lowest peer ID is",t),t===this.peerId?(this.log("👑 I have the lowest ID, attempting to claim coordinator role"),this.transitionToCoordinator()):(this.log("⏳ Waiting for new coordinator:",t),setTimeout((()=>{this.attemptCoordinatorConnection()}),2e3))}attemptCoordinatorConnection(e=0){if(e>=5)return this.log("❌ Failed to connect to coordinator after",5,"attempts"),this.log("🔄 Attempting to become coordinator as fallback"),void this.transitionToCoordinator();this.log(`🔌 Attempting to connect to coordinator (attempt ${e+1}/5)`),this.setupCrossBrowserDiscovery().then((()=>{this.log("✅ Successfully connected to new coordinator"),this.reElectionInProgress=!1})).catch((t=>{this.log(`⚠️ Failed to connect to coordinator (attempt ${e+1}):`,t);const o=1e3*Math.pow(1.5,e);setTimeout((()=>{this.attemptCoordinatorConnection(e+1)}),o)}))}async transitionToCoordinator(){this.log("🔄 Transitioning to coordinator role...");const e=Array.from(this.peers.entries()),t=this._callback;this._room;this.peer&&this.peer.destroy(),this.peers.clear(),this._connected=!1;try{await new Promise(((o,r)=>{const i=new this.options.peer(this.coordinatorPeerId,(0,n.default)({debug:this.options.debug?3:0},this.options.peerOptions)),s=setTimeout((()=>{this.log("❌ Timeout claiming coordinator ID"),i.destroy(),r(new Error("Timeout claiming coordinator ID"))}),5e3);i.on("open",(r=>{if(clearTimeout(s),r===this.coordinatorPeerId){this.log("✅ Successfully claimed coordinator ID:",r),this.peer=i,this.peerId=r,this.isCoordinator=!0,this.roomPeers.clear(),this.roomPeers.add(this.peerId),this._connected=!0,this._callback=t,this.reElectionInProgress=!1,this.setupPeerDiscovery(),this.peer.on("connection",(e=>{this.handleIncomingConnection(e)})),this.log("🔗 Re-establishing connections with",e.length,"known peers");for(const[t,o]of e)t!==this.coordinatorPeerId&&(this.knownPeers.add(t),this.roomPeers.add(t));o()}})),i.on("error",(e=>{clearTimeout(s),this.log("❌ Error claiming coordinator ID:",e),i.destroy(),r(e)}))}))}catch(e){this.log("❌ Failed to transition to coordinator:",e),this.reElectionInProgress=!1,this.log("🔄 Falling back to regular peer"),this.reestablishAsRegularPeer()}}reestablishAsRegularPeer(){const e=Math.random().toString(36).substring(7);this.peerId=`yjs-${this._room}-${e}`,this.isCoordinator=!1,this.peer=new this.options.peer(this.peerId,(0,n.default)({debug:this.options.debug?3:0},this.options.peerOptions)),this.peer.on("open",(e=>{this.peerId=e,this._connected=!0,this.log("✅ Reestablished as regular peer:",e),this.setupPeerDiscovery(),this.peer.on("connection",(e=>{this.handleIncomingConnection(e)})),this.peer.on("disconnected",(()=>{this.log("Peer disconnected, attempting reconnect...")})),this.attemptCoordinatorConnection()})),this.peer.on("error",(e=>{this.log("❌ Error reestablishing as regular peer:",e);try{var t;null===(t=this.peer)||void 0===t||t.destroy()}catch(e){}this.peer=null,this._connected=!1;const o=()=>{this.log("🌐 Network restored – retrying reestablish as regular peer"),this.reestablishAsRegularPeer()};"undefined"==typeof navigator||navigator.onLine?setTimeout(o,3e3):window.addEventListener("online",o,{once:!0})}))}connectToPeer(e){if(e!==this.peerId&&!this.peers.has(e)&&!(this.peers.size>=this.options.maxConns||this.peerId&&this.peerId>e))try{const t=this.peer.connect(e,{reliable:!0,serialization:"binary"});if(!t)return void this.log("Failed to create connection object for:",e);this.setupConnection(t,e)}catch(t){this.log("Error connecting to peer:",e,t)}}handleIncomingConnection(e){const t=e.peer;if(this.peers.has(t))e.close();else{if(this.peers.size>=this.options.maxConns)return this.log("Max connections reached, rejecting peer:",t),void e.close();this.isCoordinator&&(this.roomPeers.add(t),e.on("close",(()=>{this.roomPeers.delete(t);for(const e of this.roomPeers)if(e!==this.peerId){const o=this.peers.get(e);if(o&&o.connected)try{this.sendCoordinationMessage(o.conn,{type:"peer-left",peerId:t})}catch(t){this.log("⚠️ Failed to notify peer of departure:",e)}}}))),this.setupConnection(e,t)}}setupConnection(e,t){const o={conn:e,connected:!1,peerId:t};this.peers.set(t,o),e.on("open",(()=>{var e;o.connected=!0,this.knownPeers.add(t),null===(e=this._peerConnectCallback)||void 0===e||e.call(this,t)})),e.on("data",(o=>{const r=o instanceof Uint8Array?o:new Uint8Array(o),n=this.tryDecodeCoordinationMessage(r);if(n){if("coordinator-change"===n.type||"coordinator-leaving"===n.type||"peer-joined"===n.type||"peer-left"===n.type||"peer-list"===n.type)return void this.handleCoordinatorMessage(n);if("join"===n.type&&this.isCoordinator){const o=Array.from(this.roomPeers).filter((e=>e!==this.peerId&&e!==t));this.sendCoordinationMessage(e,{type:"peer-list",peers:o});for(const e of this.roomPeers)if(e!==this.peerId&&e!==t){const o=this.peers.get(e);if(o&&o.connected)try{this.sendCoordinationMessage(o.conn,{type:"peer-joined",peerId:t})}catch(t){this.log("⚠️ Failed to notify peer of new joiner:",e)}}return}}if(this._callback)try{const e=this.options.password?this.decrypt(r,this.options.password):r;this._callback(e)}catch(e){this.log("Error handling peer data:",e)}})),e.on("close",(()=>{this.removePeer(t)})),e.on("error",(e=>{this.log("⚠️ Connection error:",t,e),this.removePeer(t)})),setTimeout((()=>{}),1e3)}removePeer(e){const t=this.peers.get(e);if(t){try{t.conn.close()}catch(e){}this.peers.delete(e)}}sendCoordinationMessage(e,t){try{const o=JSON.stringify(t),r=(new TextEncoder).encode(o);e.send(r)}catch(e){this.log("Error encoding coordination message:",e)}}tryDecodeCoordinationMessage(e){try{const t=(new TextDecoder).decode(e),o=JSON.parse(t);return o&&"object"==typeof o&&o.type&&"string"==typeof o.type?o:null}catch(e){return null}}encrypt(e,t){const o=this.hashPassword(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e[t]^o[t%o.length];return r}decrypt(e,t){return this.encrypt(e,t)}hashPassword(e){return(new TextEncoder).encode(e)}log(...e){this.options.debug&&console.log("[PeerJSTransport]",...e)}constructor(e){if(this._connected=!1,this._room="",this.peer=null,this.peerId="",this.peers=new Map,this.knownPeers=new Set,this.isCoordinator=!1,this.coordinatorPeerId="",this.roomPeers=new Set,this.reElectionInProgress=!1,!e.peer)throw new Error('PeerJSTransport requires the "peer" option. Please provide the PeerJS constructor: import Peer from "peerjs"; new PeerJSTransport({ peer: Peer, ... })');var t,o,r,n;this.options={peer:e.peer,peerOptions:null!==(t=e.peerOptions)&&void 0!==t?t:{},password:null!==(o=e.password)&&void 0!==o?o:"",maxConns:null!==(r=e.maxConns)&&void 0!==r?r:20+Math.floor(15*Math.random()),debug:null!==(n=e.debug)&&void 0!==n&&n}}}})),t.register("jhEmn",(function(e,t){var o,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function c(e){if(o===setTimeout)return setTimeout(e,0);if((o===i||!o)&&setTimeout)return o=setTimeout,setTimeout(e,0);try{return o(e,0)}catch(t){try{return o.call(null,e,0)}catch(t){return o.call(this,e,0)}}}!function(){try{o="function"==typeof setTimeout?setTimeout:i}catch(e){o=i}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(e){r=s}}();var a,h=[],d=!1,l=-1;function p(){d&&a&&(d=!1,a.length?h=a.concat(h):l=-1,h.length&&u())}function u(){if(!d){var e=c(p);d=!0;for(var t=h.length;t;){for(a=h,h=[];++l<t;)a&&a[l].run();l=-1,t=h.length}a=null,d=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===s||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function g(e,t){this.fun=e,this.array=t}function f(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var o=1;o<arguments.length;o++)t[o-1]=arguments[o];h.push(new g(e,t)),1!==h.length||d||c(u)},g.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=f,n.addListener=f,n.once=f,n.off=f,n.removeListener=f,n.removeAllListeners=f,n.emit=f,n.prependListener=f,n.prependOnceListener=f,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}}));
|