@liascript/exporter 3.3.5--1.0.10 → 3.3.7--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.
Files changed (114) hide show
  1. package/README.md +7 -0
  2. package/dist/assets/capacitor/Gun.772ecc6f.js +1 -0
  3. package/dist/assets/capacitor/Gun.b9900b92.js +1 -0
  4. package/dist/assets/capacitor/PeerJS.b46119d0.js +1 -0
  5. package/dist/assets/capacitor/index.43dbd5d9.js +2 -0
  6. package/dist/assets/capacitor/index.58ce16fc.js +1 -0
  7. package/dist/assets/capacitor/{index.406bbc6e.css → index.ccf429fe.css} +1 -1
  8. package/dist/assets/capacitor/index.html +1 -1
  9. package/dist/assets/indexeddb/Gun.17d6e5b9.js +1 -0
  10. package/dist/assets/indexeddb/Gun.203c9130.js +1 -0
  11. package/dist/assets/indexeddb/Gun.5dcdf1ee.js +1 -0
  12. package/dist/assets/indexeddb/Gun.8bed516b.js +1 -0
  13. package/dist/assets/indexeddb/PeerJS.37c67b75.js +1 -0
  14. package/dist/assets/indexeddb/PeerJS.ab0680e6.js +1 -0
  15. package/dist/assets/indexeddb/index.80cb06a8.js +1 -0
  16. package/dist/assets/indexeddb/index.a9ef23c3.js +1 -0
  17. package/dist/assets/indexeddb/{index.75ce53cb.css → index.b9f6b7ec.css} +1 -1
  18. package/dist/assets/indexeddb/index.html +1 -1
  19. package/dist/assets/pdf/index.7a9a3f34.js +1 -0
  20. package/dist/assets/pdf/index.eae65701.js +1 -0
  21. package/dist/assets/pdf/{index.fda685a7.css → index.fc297547.css} +1 -1
  22. package/dist/assets/pdf/index.html +1 -1
  23. package/dist/assets/pdf/{jszip.min.4fbcc13f.js → jszip.min.63142cc8.js} +1 -1
  24. package/dist/assets/scorm1.2/Gun.17d6e5b9.js +1 -0
  25. package/dist/assets/scorm1.2/Gun.203c9130.js +1 -0
  26. package/dist/assets/scorm1.2/Gun.5dcdf1ee.js +1 -0
  27. package/dist/assets/scorm1.2/Gun.8bed516b.js +1 -0
  28. package/dist/assets/scorm1.2/PeerJS.37c67b75.js +1 -0
  29. package/dist/assets/scorm1.2/PeerJS.ab0680e6.js +1 -0
  30. package/dist/assets/scorm1.2/index.817342ed.js +1 -0
  31. package/dist/assets/scorm1.2/index.927439eb.js +1 -0
  32. package/dist/assets/{web/index.75ce53cb.css → scorm1.2/index.b9f6b7ec.css} +1 -1
  33. package/dist/assets/scorm1.2/index.html +1 -1
  34. package/dist/assets/scorm2004/Gun.17d6e5b9.js +1 -0
  35. package/dist/assets/scorm2004/Gun.203c9130.js +1 -0
  36. package/dist/assets/scorm2004/Gun.5dcdf1ee.js +1 -0
  37. package/dist/assets/scorm2004/Gun.8bed516b.js +1 -0
  38. package/dist/assets/scorm2004/PeerJS.37c67b75.js +1 -0
  39. package/dist/assets/scorm2004/PeerJS.ab0680e6.js +1 -0
  40. package/dist/assets/scorm2004/index.2736d6ff.js +1 -0
  41. package/dist/assets/{scorm1.2/index.75ce53cb.css → scorm2004/index.b9f6b7ec.css} +1 -1
  42. package/dist/assets/scorm2004/index.f63ce2bc.js +1 -0
  43. package/dist/assets/scorm2004/index.html +1 -1
  44. package/dist/assets/scorm2004/{jszip.min.eaecf580.js → jszip.min.19c66d77.js} +1 -1
  45. package/dist/assets/web/Gun.17d6e5b9.js +1 -0
  46. package/dist/assets/web/Gun.203c9130.js +1 -0
  47. package/dist/assets/web/Gun.5dcdf1ee.js +1 -0
  48. package/dist/assets/web/Gun.8bed516b.js +1 -0
  49. package/dist/assets/web/PeerJS.37c67b75.js +1 -0
  50. package/dist/assets/web/PeerJS.ab0680e6.js +1 -0
  51. package/dist/assets/web/index.2d76b7ef.js +1 -0
  52. package/dist/assets/web/index.63a26ad2.js +1 -0
  53. package/dist/assets/{scorm2004/index.75ce53cb.css → web/index.b9f6b7ec.css} +1 -1
  54. package/dist/assets/web/index.html +1 -1
  55. package/dist/assets/web/{jszip.min.eaecf580.js → jszip.min.19c66d77.js} +1 -1
  56. package/dist/assets/xapi/Gun.17d6e5b9.js +1 -0
  57. package/dist/assets/xapi/Gun.5dcdf1ee.js +1 -0
  58. package/dist/assets/xapi/Gun.86201f0c.js +1 -0
  59. package/dist/assets/xapi/Gun.8bed516b.js +1 -0
  60. package/dist/assets/xapi/{PeerJS.c6cb8f4b.js → PeerJS.a9660005.js} +1 -1
  61. package/dist/assets/xapi/PeerJS.ab0680e6.js +1 -0
  62. package/dist/assets/xapi/index.9eb4d766.js +1 -0
  63. package/dist/assets/xapi/index.a108bd91.js +1 -0
  64. package/dist/assets/xapi/index.b9f6b7ec.css +1 -0
  65. package/dist/assets/xapi/index.html +1 -1
  66. package/dist/index.js +131 -128
  67. package/package.json +9 -9
  68. package/dist/assets/capacitor/Gun.4c0ee714.js +0 -1
  69. package/dist/assets/capacitor/Gun.4caccb95.js +0 -1
  70. package/dist/assets/capacitor/PeerJS.a3900a77.js +0 -1
  71. package/dist/assets/capacitor/index.076fddd4.js +0 -1
  72. package/dist/assets/capacitor/index.21c64724.js +0 -2
  73. package/dist/assets/indexeddb/Gun.1b2824ad.js +0 -1
  74. package/dist/assets/indexeddb/Gun.52ff6547.js +0 -1
  75. package/dist/assets/indexeddb/Gun.c27cd89a.js +0 -1
  76. package/dist/assets/indexeddb/Gun.e5be0383.js +0 -1
  77. package/dist/assets/indexeddb/PeerJS.877663fc.js +0 -1
  78. package/dist/assets/indexeddb/PeerJS.daf2ca21.js +0 -1
  79. package/dist/assets/indexeddb/index.e14ebc2b.js +0 -1
  80. package/dist/assets/indexeddb/index.e704211b.js +0 -1
  81. package/dist/assets/pdf/index.6c7e8237.js +0 -1
  82. package/dist/assets/pdf/index.73b6c962.js +0 -1
  83. package/dist/assets/scorm1.2/Gun.1b2824ad.js +0 -1
  84. package/dist/assets/scorm1.2/Gun.52ff6547.js +0 -1
  85. package/dist/assets/scorm1.2/Gun.c27cd89a.js +0 -1
  86. package/dist/assets/scorm1.2/Gun.e5be0383.js +0 -1
  87. package/dist/assets/scorm1.2/PeerJS.877663fc.js +0 -1
  88. package/dist/assets/scorm1.2/PeerJS.daf2ca21.js +0 -1
  89. package/dist/assets/scorm1.2/index.0a7eae2e.js +0 -1
  90. package/dist/assets/scorm1.2/index.7e823f9b.js +0 -1
  91. package/dist/assets/scorm2004/Gun.1b2824ad.js +0 -1
  92. package/dist/assets/scorm2004/Gun.52ff6547.js +0 -1
  93. package/dist/assets/scorm2004/Gun.c27cd89a.js +0 -1
  94. package/dist/assets/scorm2004/Gun.e5be0383.js +0 -1
  95. package/dist/assets/scorm2004/PeerJS.877663fc.js +0 -1
  96. package/dist/assets/scorm2004/PeerJS.daf2ca21.js +0 -1
  97. package/dist/assets/scorm2004/index.27259952.js +0 -1
  98. package/dist/assets/scorm2004/index.f77042f6.js +0 -1
  99. package/dist/assets/web/Gun.1b2824ad.js +0 -1
  100. package/dist/assets/web/Gun.52ff6547.js +0 -1
  101. package/dist/assets/web/Gun.c27cd89a.js +0 -1
  102. package/dist/assets/web/Gun.e5be0383.js +0 -1
  103. package/dist/assets/web/PeerJS.877663fc.js +0 -1
  104. package/dist/assets/web/PeerJS.daf2ca21.js +0 -1
  105. package/dist/assets/web/index.6f7231d7.js +0 -1
  106. package/dist/assets/web/index.beeaa029.js +0 -1
  107. package/dist/assets/xapi/Gun.1b2824ad.js +0 -1
  108. package/dist/assets/xapi/Gun.52ff6547.js +0 -1
  109. package/dist/assets/xapi/Gun.618f30fa.js +0 -1
  110. package/dist/assets/xapi/Gun.e5be0383.js +0 -1
  111. package/dist/assets/xapi/PeerJS.daf2ca21.js +0 -1
  112. package/dist/assets/xapi/index.720250aa.js +0 -1
  113. package/dist/assets/xapi/index.75ce53cb.css +0 -1
  114. package/dist/assets/xapi/index.efbd1f0a.js +0 -1
@@ -0,0 +1 @@
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("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("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 y}));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.encodeStateVector(e);let s=0;for(let e=0;e<t.length;e++)s=(s<<5)-s+t[e]|0;return s}class g 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 y 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((()=>{this.transport.isConnected&&!this._destroying&&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._pendingHashMismatchResyncId&&(clearTimeout(this._pendingHashMismatchResyncId),this._pendingHashMismatchResyncId=void 0),this._syncRequestTimes=[],this._cancelPendingSyncReply(),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);for(const e of this._gapCheckTimers.values())clearTimeout(e);this._gapCheckTimers.clear(),this._cancelPendingSyncReply(),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){if(this._tryReserveSyncSlot()){const e=i.encodeStateAsUpdate(this.doc);e.length>0&&this._sendUpdate(e),this._writeSyncStep1()}this._broadcastAwareness([this.doc.clientID])}else console.warn("Cannot sync: transport not connected")}_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),s=c.readVarUint(e);switch(s){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])),this._cancelPendingSyncReply()),o.length(t)>1&&(this.awareness.getStates().size>=3?this._scheduleSyncReply(o.toUint8Array(t)):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),s=c.readVarUint(e);this._trackRemoteSeq(s,t);const n=o.createEncoder();o.writeVarUint(n,0);const i=a.readSyncMessage(e,n,this.doc,this);i===a.messageYjsSyncStep2&&this._cancelPendingSyncReply();const r=c.readVarInt(e),d=_(this.doc);if(d!==r){if(!this._gapCheckTimers.has(s)){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: ${d}, Expected: ${r}`),console.warn(`[GenericProvider] Re-sync scheduled in ${t}ms...`),void 0===this._pendingHashMismatchResyncId&&(this._pendingHashMismatchResyncId=setTimeout((()=>{this._pendingHashMismatchResyncId=void 0,this.transport.isConnected&&!this._destroying&&this.syncNow()}),t))}}else this._hashMismatchCount=0;i!==a.messageYjsSyncStep2||this._synced||d!==r||(this._synced=!0,this.emit("synced",[!0])),o.length(n)>1&&(this.awareness.getStates().size>=3?this._scheduleSyncReply(o.toUint8Array(n)):this._send(o.toUint8Array(n)));break}default:console.warn("Unknown message type:",s)}}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)}}_scheduleSyncReply(e){void 0!==this._pendingSyncReplyTimeoutId&&(this._pendingSyncReply&&this._send(this._pendingSyncReply),clearTimeout(this._pendingSyncReplyTimeoutId),this._pendingSyncReplyTimeoutId=void 0),this._pendingSyncReply=e;const t=Math.random()*this._syncReplySuppressionMs;this._pendingSyncReplyTimeoutId=setTimeout((()=>{this._pendingSyncReplyTimeoutId=void 0,this._pendingSyncReply&&(this._send(this._pendingSyncReply),this._pendingSyncReply=null)}),t)}_cancelPendingSyncReply(){void 0!==this._pendingSyncReplyTimeoutId&&(clearTimeout(this._pendingSyncReplyTimeoutId),this._pendingSyncReplyTimeoutId=void 0),this._pendingSyncReply=null}_trackRemoteSeq(e,t){let s=this._remoteSeqInfo.get(e);if(s||(s={highest:-1,seen:new Set},this._remoteSeqInfo.set(e,s)),s.seen.has(t))return;s.seen.add(t),t>s.highest&&(s.highest>=0&&t>s.highest+1&&this._scheduleGapCheck(e,s.highest+1,t-1),s.highest=t);const n=s.highest-this._seqWindowSize;if(n>0)for(const e of s.seen)e<n&&s.seen.delete(e)}_scheduleGapCheck(e,t,s){if(this._gapCheckTimers.has(e))return;const n=setTimeout((()=>{this._gapCheckTimers.delete(e);const n=this._remoteSeqInfo.get(e);if(!n||this._destroying)return;let i=0;for(let e=t;e<=s;e++)n.seen.has(e)||i++;i>0&&this.transport.isConnected&&(console.warn(`[GenericProvider] Sequence gap confirmed from client ${e}: ${i} message(s) still missing after ${this._gapGraceMs}ms grace period`),this._sendSyncStep1())}),this._gapGraceMs);this._gapCheckTimers.set(e,n)}_tryReserveSyncSlot(){const e=Date.now();return this._syncRequestTimes=this._syncRequestTimes.filter((t=>e-t<this._syncRequestWindowMs)),!(this._syncRequestTimes.length>=this._maxSyncRequestsPerWindow)&&(this._syncRequestTimes.push(e),!0)}_writeSyncStep1(){const e=o.createEncoder();o.writeVarUint(e,0),a.writeSyncStep1(e,this.doc),this._send(o.toUint8Array(e))}_sendSyncStep1(){this._tryReserveSyncSlot()?this._writeSyncStep1():console.warn(`[GenericProvider] Sync rate limit exceeded (${this._maxSyncRequestsPerWindow} requests per ${this._syncRequestWindowMs/1e3}s), throttling...`)}_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,d,h,l,u,p,_;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._pendingSyncReply=null,this._localSeqNum=0,this._remoteSeqInfo=new Map,this._gapCheckTimers=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 g(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!==(o=null!==(a=s.batchUpdates)&&void 0!==a?a:t.preferredBatchMs)&&void 0!==o?o:0,this._disableBc=null!==(c=s.disableBc)&&void 0!==c&&c,this._awarenessInterval=null!==(d=s.awarenessInterval)&&void 0!==d?d:100,this._maxSyncRequestsPerWindow=null!==(h=s.maxSyncRequestsPerWindow)&&void 0!==h?h:20,this._syncRequestWindowMs=null!==(l=s.syncRequestWindowMs)&&void 0!==l?l:1e4,this._syncReplySuppressionMs=null!==(u=s.syncReplySuppressionMs)&&void 0!==u?u:30,this._gapGraceMs=null!==(p=s.gapGraceMs)&&void 0!==p?p:300,this._seqWindowSize=null!==(_=s.seqWindowSize)&&void 0!==_?_:64,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 g})),e(s.exports,"applyAwarenessUpdate",(function(){return y}));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]))},g=(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)},y=(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("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")}));
@@ -0,0 +1 @@
1
+ !function(){function e(e,r,n,o){Object.defineProperty(e,r,{get:n,set:o,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(n,o){e(n.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)(n,e);var r=(0,h.default)(n);function n(){var e;return(0,a.default)(this,n),e=r.apply(this,arguments),(0,c.default)((0,t.default)(e),"syncFallbackTimer",null),e}return(0,s.default)(n,[{key:"destroy",value:function(){var e;null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),(0,l.default)((0,d.default)(n.prototype),"destroy",this).call(this),null===(e=this.provider)||void 0===e||e.disconnect()}},{key:"connect",value:function(e){var r=this,o=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)(n.prototype),"connect",r).call(o,e),o.host=(null===(t=e.config)||void 0===t?void 0:t.host)||void 0,o.port=(null===(i=e.config)||void 0===i?void 0:i.port)?parseInt(e.config.port,10):void 0,o.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{o.iceServers=JSON.parse(e.config.iceServers)}catch(r){console.warn("PeerJS: invalid iceServers JSON, ignoring:",e.config.iceServers)}return window.Peer?o.init(!0):o.load(["//unpkg.com/peerjs@1.5.4/dist/peerjs.min.js"],o),[2]}))}))()}},{key:"init",value:function(e,r){var n=this,o=this.uniqueID();if(e&&window.Peer&&o)(function(e){return w.apply(this,arguments)})(o).then((function(e){var r={};n.host&&(r.host=n.host,r.secure=!0),void 0!==n.port&&(r.port=n.port),n.peerPath&&(r.path=n.peerPath),n.iceServers&&(r.config={iceServers:n.iceServers}),n.transport=new(0,y.PeerJSTransport)((0,p.default)({peer:window.Peer},Object.keys(r).length>0?{peerOptions:r}:{},n.password?{password:n.password}:{})),n.provider=new(0,g.GenericProvider)(n.db.doc,n.transport),n.db.setAwareness(n.provider.awareness);var o=!1,t=function(){o||(o=!0,null!==n.syncFallbackTimer&&(clearTimeout(n.syncFallbackTimer),n.syncFallbackTimer=null),n.sendConnect())};n.provider.on("synced",(function(e){console.log("PeerJS: document synchronized",e.synced),t()})),n.provider.on("status",(function(e){var r=e.state;console.log("PeerJS status: ".concat(r)),"connected"===r?n.syncFallbackTimer=setTimeout((function(){console.log("PeerJS: sync fallback, proceeding as first peer"),t()}),2e3):"disconnected"===r&&console.warn("PeerJS: disconnected")})),n.provider.pubsub.subscribe("*",(function(e,r){var o,t;null===(t=(o=n).onReceive)||void 0===t||t.call(o,r,e)})),n.provider.connect((0,p.default)({room:e},n.password?{password:n.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 n;this.provider&&(this.provider.pubsub.publish(e,r),this.replyOnReceive&&(null===(n=this.onReceive)||void 0===n||n.call(this,e,r)))}}]),n}(v.Sync);function w(){return(w=(0,i.default)((function(e){var r,n;return(0,f.__generator)(this,(function(o){switch(o.label){case 0:return r=(new TextEncoder).encode(e),[4,crypto.subtle.digest("SHA-256",r)];case 1:return n=o.sent(),[2,Array.from(new Uint8Array(n)).map((function(e){return e.toString(16).padStart(2,"0")})).join("")]}}))}))).apply(this,arguments)}})),r.register("48SmG",(function(n,o){e(n.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,this._destroying=!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 n,o,t,a;this.options={peer:r.peer,peerOptions:null!==(n=r.peerOptions)&&void 0!==n?n:{},password:null!==(o=r.password)&&void 0!==o?o:"",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(n){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,n){try{var o=new r.options.peer(r.coordinatorPeerId,(0,s.default)({debug:r.options.debug?3:0},r.options.peerOptions)),t=setTimeout((function(){o.destroy(),r.createRegularPeer(e,n)}),3e3);o.on("open",(function(n){clearTimeout(t),n===r.coordinatorPeerId&&(r.log("Coordinator: claimed ID"),r.peer=o,r.peerId=n,r.isCoordinator=!0,r.roomPeers.add(r.peerId),r._connected=!0,r.setupPeerDiscovery(),r.peer.on("connection",(function(e){r.handleIncomingConnection(e)})),r.peer.on("disconnected",(function(){r.log("Peer disconnected from PeerJS server, attempting reconnect..."),r._handlePeerServerDisconnect()})),e())})),o.on("error",(function(i){clearTimeout(t),i.message.includes("ID is taken")||i.message.includes("taken")||i.message.includes("already")||"unavailable-id"===i.type?(o.destroy(),r.createRegularPeer(e,n)):(r.log("❌ Unexpected error claiming coordinator:",i),o.destroy(),r.createRegularPeer(e,n))}))}catch(e){n(e)}}))]}))}))()}},{key:"createRegularPeer",value:function(e,r){var n=this,o=Math.random().toString(36).substring(7);this.peerId="yjs-".concat(this._room,"-").concat(o),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){n.peerId=r,n._connected=!0,n.setupPeerDiscovery(),n.peer.on("connection",(function(e){n.handleIncomingConnection(e)})),n.setupCrossBrowserDiscovery().then((function(){e()})).catch((function(r){n.log("⚠️ Cross-browser discovery failed, continuing with BroadcastChannel only:",r),e()}))})),this.peer.on("error",(function(e){n.log("Peer error:",e),n._connected||r(e)})),this.peer.on("disconnected",(function(){n.log("Peer disconnected from PeerJS server, attempting reconnect..."),n._handlePeerServerDisconnect()}))}},{key:"disconnect",value:function(){if(this._connected){if(this._destroying=!0,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,n=void 0;try{for(var o,t=this.roomPeers[Symbol.iterator]();!(e=(o=t.next()).done);e=!0){var i=o.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,n=e}finally{try{e||null==t.return||t.return()}finally{if(r)throw n}}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,this._destroying=!1}}},{key:"_handlePeerServerDisconnect",value:function(){var e=this;if(!this._destroying){if("undefined"!=typeof navigator&&!navigator.onLine)return this.log("📴 Offline – deferring PeerJS reconnect until network returns"),void window.addEventListener("online",(function(){e.log("🌐 Network restored – reconnecting to PeerJS server"),e._handlePeerServerDisconnect()}),{once:!0});try{this.peer.reconnect(),this.log("🔄 PeerJS reconnect initiated (peer ID: ".concat(this.peerId,")"))}catch(e){return void this.log("❌ peer.reconnect() failed:",e)}this.peer.once("open",(function(){e.log("✅ Reconnected to PeerJS server — re-connecting to ".concat(e.knownPeers.size," known peer(s)"));var r=!0,n=!1,o=void 0;try{for(var t,i=e.peers.entries()[Symbol.iterator]();!(r=(t=i.next()).done);r=!0){var a=(0,c.default)(t.value,2),s=a[0],l=a[1];if(!l.connected){try{l.conn.close()}catch(e){}e.peers.delete(s)}}}catch(e){n=!0,o=e}finally{try{r||null==i.return||i.return()}finally{if(n)throw o}}var d=!0,u=!1,p=void 0;try{for(var h,f=e.knownPeers[Symbol.iterator]();!(d=(h=f.next()).done);d=!0){var v=h.value;e.peers.has(v)||v===e.peerId||(e.log("🔌 Re-connecting to known peer: ".concat(v)),e.connectToPeer(v))}}catch(e){u=!0,p=e}finally{try{d||null==f.return||f.return()}finally{if(u)throw p}}e.isCoordinator||null!=e.coordinatorConn||setTimeout((function(){return e.attemptCoordinatorConnection()}),1e3)}))}}},{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,n=!0,o=!1,t=void 0;try{for(var i,a=this.peers.values()[Symbol.iterator]();!(n=(i=a.next()).done);n=!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){o=!0,t=e}finally{try{n||null==a.return||a.return()}finally{if(o)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 n=r.data;n.peerId!==e.peerId&&("announce"===n.type?(e.knownPeers.add(n.peerId),e.connectToPeer(n.peerId)):"leave"===n.type&&(e.knownPeers.delete(n.peerId),e.removePeer(n.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,n){var o=!1,t=setTimeout((function(){if(!o){o=!0;var r=new Error("Timeout connecting to coordinator");e.log("⏱️ Timeout connecting to coordinator"),n(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 n,a;if(!o){o=!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=(n=e)._peerConnectCallback)||void 0===a||a.call(n,e.coordinatorPeerId),e.sendCoordinationMessage(i,{type:"join",peerId:e.peerId}),i.on("data",(function(r){var n=r instanceof Uint8Array?r:new Uint8Array(r),o=e.tryDecodeCoordinationMessage(n);if(o)e.handleCoordinatorMessage(o);else if(e._callback)try{var t=e.options.password?e.decrypt(n,e.options.password):n;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){o||(o=!0,clearTimeout(t),e.log("❌ Failed to connect to coordinator:",r.message),n(r))}))}catch(r){o||(o=!0,clearTimeout(t),e.log("⚠️ Error connecting to coordinator:",r),n(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,n=!1,o=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){n=!0,o=e}finally{try{r||null==i.return||i.return()}finally{if(n)throw o}}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 n=r[0];this.log("🗳️ Coordinator election: Lowest peer ID is",n),n===this.peerId?(this.log("👑 I have the lowest ID, attempting to claim coordinator role"),this.transitionToCoordinator()):(this.log("⏳ Waiting for new coordinator:",n),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(n){r.log("⚠️ Failed to connect to coordinator (attempt ".concat(e+1,"):"),n);var o=1e3*Math.pow(1.5,e);setTimeout((function(){r.attemptCoordinatorConnection(e+1)}),o)}))}},{key:"transitionToCoordinator",value:function(){var e=this;return(0,t.default)((function(){var r,n,o;return(0,d.__generator)(this,(function(t){switch(t.label){case 0:e.log("🔄 Transitioning to coordinator role..."),r=Array.from(e.peers.entries()),n=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(o,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=n,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}}o()}})),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 o=t.sent(),e.log("❌ Failed to transition to coordinator:",o),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 from PeerJS server, attempting reconnect..."),e._handlePeerServerDisconnect()})),e.attemptCoordinatorConnection()})),this.peer.on("error",(function(r){e.log("❌ Error reestablishing as regular peer:",r);try{var n;null===(n=e.peer)||void 0===n||n.destroy()}catch(e){}e.peer=null,e._connected=!1;var o=function(){e.log("🌐 Network restored – retrying reestablish as regular peer"),e.reestablishAsRegularPeer()};"undefined"==typeof navigator||navigator.onLine?setTimeout(o,3e3):window.addEventListener("online",o,{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,n=e.peer;if(this.peers.has(n))e.close();else{if(this.peers.size>=this.options.maxConns)return this.log("Max connections reached, rejecting peer:",n),void e.close();this.isCoordinator&&(this.roomPeers.add(n),e.on("close",(function(){r.roomPeers.delete(n);var e=!0,o=!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:n})}catch(e){r.log("⚠️ Failed to notify peer of departure:",s)}}}}catch(e){o=!0,t=e}finally{try{e||null==a.return||a.return()}finally{if(o)throw t}}}))),this.setupConnection(e,n)}}},{key:"setupConnection",value:function(e,r){var n=this,o={conn:e,connected:!1,peerId:r};this.peers.set(r,o),e.on("open",(function(){var e,t;o.connected=!0,n.knownPeers.add(r),null===(t=(e=n)._peerConnectCallback)||void 0===t||t.call(e,r)})),e.on("data",(function(o){var t=o instanceof Uint8Array?o:new Uint8Array(o),i=n.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 n.handleCoordinatorMessage(i);if("join"===i.type&&n.isCoordinator){var a=Array.from(n.roomPeers).filter((function(e){return e!==n.peerId&&e!==r}));n.sendCoordinationMessage(e,{type:"peer-list",peers:a});var s=!0,c=!1,l=void 0;try{for(var d,u=n.roomPeers[Symbol.iterator]();!(s=(d=u.next()).done);s=!0){var p=d.value;if(p!==n.peerId&&p!==r){var h=n.peers.get(p);if(h&&h.connected)try{n.sendCoordinationMessage(h.conn,{type:"peer-joined",peerId:r})}catch(e){n.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(n._callback)try{var f=n.options.password?n.decrypt(t,n.options.password):t;n._callback(f)}catch(e){n.log("Error handling peer data:",e)}})),e.on("close",(function(){n.removePeer(r)})),e.on("error",(function(e){n.log("⚠️ Connection error:",r,e),n.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 n=JSON.stringify(r),o=(new TextEncoder).encode(n);e.send(o)}catch(e){this.log("Error encoding coordination message:",e)}}},{key:"tryDecodeCoordinationMessage",value:function(e){try{var r=(new TextDecoder).decode(e),n=JSON.parse(r);return n&&"object"==typeof n&&n.type&&"string"==typeof n.type?n:null}catch(e){return null}}},{key:"encrypt",value:function(e,r){for(var n=this.hashPassword(r),o=new Uint8Array(e.length),t=0;t<e.length;t++)o[t]=e[t]^n[t%n.length];return o}},{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),n=0;n<e;n++)r[n]=arguments[n];var o;this.options.debug&&(o=console).log.apply(o,["[PeerJSTransport]"].concat((0,l.default)(r)))}}]),e}()})),r.register("84cK9",(function(e,r){var n,o,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(n===setTimeout)return setTimeout(e,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(r){try{return n.call(null,e,0)}catch(r){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(e){n=i}try{o="function"==typeof clearTimeout?clearTimeout:a}catch(e){o=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(o===clearTimeout)return clearTimeout(e);if((o===a||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(e);try{return o(e)}catch(r){try{return o.call(null,e)}catch(r){return o.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 n=1;n<arguments.length;n++)r[n-1]=arguments[n];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}}))}();
@@ -0,0 +1 @@
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)})),this.peer.on("disconnected",(()=>{this.log("Peer disconnected from PeerJS server, attempting reconnect..."),this._handlePeerServerDisconnect()})),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 from PeerJS server, attempting reconnect..."),this._handlePeerServerDisconnect()}))}disconnect(){if(this._connected){if(this._destroying=!0,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,this._destroying=!1}}_handlePeerServerDisconnect(){if(!this._destroying){if("undefined"!=typeof navigator&&!navigator.onLine)return this.log("📴 Offline – deferring PeerJS reconnect until network returns"),void window.addEventListener("online",(()=>{this.log("🌐 Network restored – reconnecting to PeerJS server"),this._handlePeerServerDisconnect()}),{once:!0});try{this.peer.reconnect(),this.log(`🔄 PeerJS reconnect initiated (peer ID: ${this.peerId})`)}catch(e){return void this.log("❌ peer.reconnect() failed:",e)}this.peer.once("open",(()=>{this.log(`✅ Reconnected to PeerJS server — re-connecting to ${this.knownPeers.size} known peer(s)`);for(const[e,t]of this.peers.entries())if(!t.connected){try{t.conn.close()}catch(e){}this.peers.delete(e)}for(const e of this.knownPeers)this.peers.has(e)||e===this.peerId||(this.log(`🔌 Re-connecting to known peer: ${e}`),this.connectToPeer(e));this.isCoordinator||null!=this.coordinatorConn||setTimeout((()=>this.attemptCoordinatorConnection()),1e3)}))}}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 from PeerJS server, attempting reconnect..."),this._handlePeerServerDisconnect()})),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,this._destroying=!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}}));