@liascript/exporter 3.3.6--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 (120) hide show
  1. package/dist/assets/capacitor/Gun.772ecc6f.js +1 -0
  2. package/dist/assets/capacitor/Gun.b9900b92.js +1 -0
  3. package/dist/assets/capacitor/PeerJS.b46119d0.js +1 -0
  4. package/dist/assets/capacitor/index.43dbd5d9.js +2 -0
  5. package/dist/assets/capacitor/index.58ce16fc.js +1 -0
  6. package/dist/assets/capacitor/{index.406bbc6e.css → index.ccf429fe.css} +1 -1
  7. package/dist/assets/capacitor/index.html +1 -1
  8. package/dist/assets/capacitor/{trystero-ipfs.min.2b844fee.js → trystero-ipfs.min.771a19bf.js} +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/indexeddb/{jszip.min.eaecf580.js → jszip.min.19c66d77.js} +1 -1
  20. package/dist/assets/pdf/index.7a9a3f34.js +1 -0
  21. package/dist/assets/pdf/index.eae65701.js +1 -0
  22. package/dist/assets/pdf/{index.fda685a7.css → index.fc297547.css} +1 -1
  23. package/dist/assets/pdf/index.html +1 -1
  24. package/dist/assets/{web/jszip.min.eaecf580.js → pdf/jszip.min.19c66d77.js} +1 -1
  25. package/dist/assets/scorm1.2/Gun.17d6e5b9.js +1 -0
  26. package/dist/assets/scorm1.2/Gun.203c9130.js +1 -0
  27. package/dist/assets/scorm1.2/Gun.5dcdf1ee.js +1 -0
  28. package/dist/assets/scorm1.2/Gun.8bed516b.js +1 -0
  29. package/dist/assets/scorm1.2/PeerJS.37c67b75.js +1 -0
  30. package/dist/assets/scorm1.2/PeerJS.ab0680e6.js +1 -0
  31. package/dist/assets/scorm1.2/index.817342ed.js +1 -0
  32. package/dist/assets/scorm1.2/index.927439eb.js +1 -0
  33. package/dist/assets/{web/index.75ce53cb.css → scorm1.2/index.b9f6b7ec.css} +1 -1
  34. package/dist/assets/scorm1.2/index.html +1 -1
  35. package/dist/assets/scorm1.2/jszip.min.63142cc8.js +13 -0
  36. package/dist/assets/scorm2004/Gun.17d6e5b9.js +1 -0
  37. package/dist/assets/scorm2004/Gun.203c9130.js +1 -0
  38. package/dist/assets/scorm2004/Gun.5dcdf1ee.js +1 -0
  39. package/dist/assets/scorm2004/Gun.8bed516b.js +1 -0
  40. package/dist/assets/scorm2004/PeerJS.37c67b75.js +1 -0
  41. package/dist/assets/scorm2004/PeerJS.ab0680e6.js +1 -0
  42. package/dist/assets/scorm2004/index.2736d6ff.js +1 -0
  43. package/dist/assets/{scorm1.2/index.75ce53cb.css → scorm2004/index.b9f6b7ec.css} +1 -1
  44. package/dist/assets/scorm2004/index.f63ce2bc.js +1 -0
  45. package/dist/assets/scorm2004/index.html +1 -1
  46. package/dist/assets/web/Gun.17d6e5b9.js +1 -0
  47. package/dist/assets/web/Gun.203c9130.js +1 -0
  48. package/dist/assets/web/Gun.5dcdf1ee.js +1 -0
  49. package/dist/assets/web/Gun.8bed516b.js +1 -0
  50. package/dist/assets/web/PeerJS.37c67b75.js +1 -0
  51. package/dist/assets/web/PeerJS.ab0680e6.js +1 -0
  52. package/dist/assets/web/index.2d76b7ef.js +1 -0
  53. package/dist/assets/web/index.63a26ad2.js +1 -0
  54. package/dist/assets/{scorm2004/index.75ce53cb.css → web/index.b9f6b7ec.css} +1 -1
  55. package/dist/assets/web/index.html +1 -1
  56. package/dist/assets/{pdf/jszip.min.eaecf580.js → web/jszip.min.19c66d77.js} +1 -1
  57. package/dist/assets/xapi/Gun.17d6e5b9.js +1 -0
  58. package/dist/assets/xapi/Gun.5dcdf1ee.js +1 -0
  59. package/dist/assets/xapi/Gun.86201f0c.js +1 -0
  60. package/dist/assets/xapi/Gun.8bed516b.js +1 -0
  61. package/dist/assets/xapi/{PeerJS.c6cb8f4b.js → PeerJS.a9660005.js} +1 -1
  62. package/dist/assets/xapi/PeerJS.ab0680e6.js +1 -0
  63. package/dist/assets/xapi/index.9eb4d766.js +1 -0
  64. package/dist/assets/xapi/index.a108bd91.js +1 -0
  65. package/dist/assets/xapi/index.b9f6b7ec.css +1 -0
  66. package/dist/assets/xapi/index.html +1 -1
  67. package/dist/index.js +3 -3
  68. package/package.json +9 -9
  69. package/dist/assets/capacitor/Gun.4c0ee714.js +0 -1
  70. package/dist/assets/capacitor/Gun.4caccb95.js +0 -1
  71. package/dist/assets/capacitor/PeerJS.a3900a77.js +0 -1
  72. package/dist/assets/capacitor/index.076fddd4.js +0 -1
  73. package/dist/assets/capacitor/index.6532983b.js +0 -2
  74. package/dist/assets/indexeddb/Gun.1b2824ad.js +0 -1
  75. package/dist/assets/indexeddb/Gun.52ff6547.js +0 -1
  76. package/dist/assets/indexeddb/Gun.c27cd89a.js +0 -1
  77. package/dist/assets/indexeddb/Gun.e5be0383.js +0 -1
  78. package/dist/assets/indexeddb/PeerJS.877663fc.js +0 -1
  79. package/dist/assets/indexeddb/PeerJS.daf2ca21.js +0 -1
  80. package/dist/assets/indexeddb/index.11cfd3a5.js +0 -1
  81. package/dist/assets/indexeddb/index.2dc41135.js +0 -1
  82. package/dist/assets/pdf/index.6c7e8237.js +0 -1
  83. package/dist/assets/pdf/index.e21e9c0d.js +0 -1
  84. package/dist/assets/scorm1.2/Gun.1b2824ad.js +0 -1
  85. package/dist/assets/scorm1.2/Gun.52ff6547.js +0 -1
  86. package/dist/assets/scorm1.2/Gun.c27cd89a.js +0 -1
  87. package/dist/assets/scorm1.2/Gun.e5be0383.js +0 -1
  88. package/dist/assets/scorm1.2/PeerJS.877663fc.js +0 -1
  89. package/dist/assets/scorm1.2/PeerJS.daf2ca21.js +0 -1
  90. package/dist/assets/scorm1.2/index.0a7eae2e.js +0 -1
  91. package/dist/assets/scorm1.2/index.ee6a673a.js +0 -1
  92. package/dist/assets/scorm1.2/jszip.min.4fbcc13f.js +0 -13
  93. package/dist/assets/scorm2004/Gun.1b2824ad.js +0 -1
  94. package/dist/assets/scorm2004/Gun.52ff6547.js +0 -1
  95. package/dist/assets/scorm2004/Gun.c27cd89a.js +0 -1
  96. package/dist/assets/scorm2004/Gun.e5be0383.js +0 -1
  97. package/dist/assets/scorm2004/PeerJS.877663fc.js +0 -1
  98. package/dist/assets/scorm2004/PeerJS.daf2ca21.js +0 -1
  99. package/dist/assets/scorm2004/index.1425a438.js +0 -1
  100. package/dist/assets/scorm2004/index.27259952.js +0 -1
  101. package/dist/assets/web/Gun.1b2824ad.js +0 -1
  102. package/dist/assets/web/Gun.52ff6547.js +0 -1
  103. package/dist/assets/web/Gun.c27cd89a.js +0 -1
  104. package/dist/assets/web/Gun.e5be0383.js +0 -1
  105. package/dist/assets/web/PeerJS.877663fc.js +0 -1
  106. package/dist/assets/web/PeerJS.daf2ca21.js +0 -1
  107. package/dist/assets/web/index.68795b8d.js +0 -1
  108. package/dist/assets/web/index.6f7231d7.js +0 -1
  109. package/dist/assets/xapi/Gun.1b2824ad.js +0 -1
  110. package/dist/assets/xapi/Gun.52ff6547.js +0 -1
  111. package/dist/assets/xapi/Gun.618f30fa.js +0 -1
  112. package/dist/assets/xapi/Gun.e5be0383.js +0 -1
  113. package/dist/assets/xapi/PeerJS.daf2ca21.js +0 -1
  114. package/dist/assets/xapi/index.720250aa.js +0 -1
  115. package/dist/assets/xapi/index.75ce53cb.css +0 -1
  116. package/dist/assets/xapi/index.9225cbf5.js +0 -1
  117. /package/dist/assets/{web → indexeddb}/jszip.min.63142cc8.js +0 -0
  118. /package/dist/assets/{xapi → pdf}/jszip.min.63142cc8.js +0 -0
  119. /package/dist/assets/{indexeddb → web}/jszip.min.4fbcc13f.js +0 -0
  120. /package/dist/assets/{pdf → xapi}/jszip.min.4fbcc13f.js +0 -0
@@ -0,0 +1 @@
1
+ !function(e,t,s,n,i){var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},a="function"==typeof r[n]&&r[n],o=a.cache||{},c="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function h(t,s){if(!o[t]){if(!e[t]){var i="function"==typeof r[n]&&r[n];if(!s&&i)return i(t,!0);if(a)return a(t,!0);if(c&&"string"==typeof t)return c(t);var d=new Error("Cannot find module '"+t+"'");throw d.code="MODULE_NOT_FOUND",d}p.resolve=function(s){var n=e[t][1][s];return null!=n?n:s},p.cache={};var l=o[t]=new h.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return o[t].exports;function p(e){var t=p.resolve(e);return!1===t?{}:h(t)}}h.isParcelRequire=!0,h.Module=function(e){this.id=e,this.bundle=h,this.exports={}},h.modules=e,h.cache=o,h.parent=a,h.register=function(t,s){e[t]=[function(e,t){t.exports=s},{}]},Object.defineProperty(h,"root",{get:function(){return r[n]}}),r[n]=h;for(var d=0;d<t.length;d++)h(t[d])}({"2fRsv":[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"messageYjsSyncStep1",(()=>o)),n.export(s,"messageYjsSyncStep2",(()=>c)),n.export(s,"messageYjsUpdate",(()=>h)),n.export(s,"writeSyncStep1",(()=>d)),n.export(s,"writeSyncStep2",(()=>l)),n.export(s,"readSyncStep1",(()=>p)),n.export(s,"readSyncStep2",(()=>u)),n.export(s,"writeUpdate",(()=>_)),n.export(s,"readUpdate",(()=>y)),n.export(s,"readSyncMessage",(()=>g));var i=e("lib0/encoding"),r=e("lib0/decoding"),a=e("yjs");const o=0,c=1,h=2,d=(e,t)=>{i.writeVarUint(e,o);const s=a.encodeStateVector(t);i.writeVarUint8Array(e,s)},l=(e,t,s)=>{i.writeVarUint(e,c),i.writeVarUint8Array(e,a.encodeStateAsUpdate(t,s))},p=(e,t,s)=>l(t,s,r.readVarUint8Array(e)),u=(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)}},_=(e,t)=>{i.writeVarUint(e,h),i.writeVarUint8Array(e,t)},y=u,g=(e,t,s,n,i)=>{const a=r.readVarUint(e);switch(a){case o:p(e,t,s);break;case c:u(e,s,n,i);break;case h:y(e,s,n,i);break;default:throw new Error("Unknown message type")}return a}},{"lib0/encoding":"iMu7f","lib0/decoding":"gVpVW",yjs:"dugeO","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],"3M9RT":[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"GenericProvider",(()=>i.GenericProvider)),n.export(s,"PubSubChannel",(()=>i.PubSubChannel)),n.export(s,"SyncHealthMonitor",(()=>r.SyncHealthMonitor)),n.export(s,"computeDocumentHash",(()=>r.computeDocumentHash));var i=e("./index"),r=e("./sync-monitor")},{"./index":"9b0Z3","./sync-monitor":"jgKsD","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],"9b0Z3":[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"PubSubChannel",(()=>y)),n.export(s,"GenericProvider",(()=>g));var i=e("yjs"),r=e("y-protocols/awareness"),a=e("y-protocols/sync"),o=e("lib0/encoding"),c=e("lib0/decoding"),h=e("lib0/observable"),d=e("lib0/broadcastchannel");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 p(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 u(e){const t=p(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 y extends h.Observable{constructor(e){super(),this.provider=e}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])}}class g extends h.Observable{constructor(e,t,s={}){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 y(this),this.awareness=s.awareness||new r.Awareness(e),this._syncInterval=s.syncInterval??5e3,this._verifyUpdates=s.verifyUpdates??!0,this._batchUpdates=s.batchUpdates??t.preferredBatchMs??0,this._disableBc=s.disableBc??!1,this._awarenessInterval=s.awarenessInterval??100,this._maxSyncRequestsPerWindow=s.maxSyncRequestsPerWindow??20,this._syncRequestWindowMs=s.syncRequestWindowMs??1e4,this._syncReplySuppressionMs=s.syncReplySuppressionMs??30,this._gapGraceMs=s.gapGraceMs??300,this._seqWindowSize=s.seqWindowSize??64,this._setupDocumentSync(),this._setupAwarenessSync()}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=()=>{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 p(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),h=_(this.doc);if(h!==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: ${h}, 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||h!==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)},d.subscribe(this._bcChannel,this._bcSubscriber),this._bcConnected=!0;const t=o.createEncoder();o.writeVarUint(t,0),a.writeSyncStep1(t,this.doc),d.publish(this._bcChannel,u(o.toUint8Array(t)),this);const s=o.createEncoder();if(o.writeVarUint(s,0),a.writeSyncStep2(s,this.doc),d.publish(this._bcChannel,u(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])),d.publish(this._bcChannel,u(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)),d.publish(this._bcChannel,u(o.toUint8Array(e)),this),d.unsubscribe(this._bcChannel,this._bcSubscriber),this._bcConnected=!1,this._bcSubscriber=void 0}_send(e){const t=u(e);if(this._bcConnected&&d.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}}},{yjs:"dugeO","y-protocols/awareness":"dkAja","y-protocols/sync":"2fRsv","lib0/encoding":"iMu7f","lib0/decoding":"gVpVW","lib0/observable":"ewQE3","lib0/broadcastchannel":"42CYj","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],dkAja:[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"outdatedTimeout",(()=>d)),n.export(s,"Awareness",(()=>l)),n.export(s,"removeAwarenessStates",(()=>p)),n.export(s,"encodeAwarenessUpdate",(()=>u)),n.export(s,"modifyAwarenessUpdate",(()=>_)),n.export(s,"applyAwarenessUpdate",(()=>y));var i=e("lib0/encoding"),r=e("lib0/decoding"),a=e("lib0/time"),o=e("lib0/math"),c=e("lib0/observable"),h=e("lib0/function");e("yjs");const d=3e4;class l extends c.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval((()=>{const e=a.getUnixTime();null!==this.getLocalState()&&d/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach(((s,n)=>{n!==this.clientID&&d<=e-s.lastUpdated&&this.states.has(n)&&t.push(n)})),t.length>0&&p(this,t,"timeout")}),o.floor(d/10)),e.on("destroy",(()=>{this.destroy()})),this.setLocalState({})}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:a.getUnixTime()});const r=[],o=[],c=[],d=[];null===e?d.push(t):null==i?null!=e&&r.push(t):(o.push(t),h.equalityDeep(i,e)||c.push(t)),(r.length>0||c.length>0||d.length>0)&&this.emit("change",[{added:r,updated:c,removed:d},"local"]),this.emit("update",[{added:r,updated:o,removed:d},"local"])}setLocalStateField(e,t){const s=this.getLocalState();null!==s&&this.setLocalState({...s,[e]:t})}getStates(){return this.states}}const p=(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:a.getUnixTime()})}n.push(i)}}n.length>0&&(e.emit("change",[{added:[],updated:[],removed:n},s]),e.emit("update",[{added:[],updated:[],removed:n},s]))},u=(e,t,s=e.states)=>{const n=t.length,r=i.createEncoder();i.writeVarUint(r,n);for(let a=0;a<n;a++){const n=t[a],o=s.get(n)||null,c=e.meta.get(n).clock;i.writeVarUint(r,n),i.writeVarUint(r,c),i.writeVarString(r,JSON.stringify(o))}return i.toUint8Array(r)},_=(e,t)=>{const s=r.createDecoder(e),n=i.createEncoder(),a=r.readVarUint(s);i.writeVarUint(n,a);for(let e=0;e<a;e++){const e=r.readVarUint(s),a=r.readVarUint(s),o=t(JSON.parse(r.readVarString(s)));i.writeVarUint(n,e),i.writeVarUint(n,a),i.writeVarString(n,JSON.stringify(o))}return i.toUint8Array(n)},y=(e,t,s)=>{const n=r.createDecoder(t),i=a.getUnixTime(),o=[],c=[],d=[],l=[],p=r.readVarUint(n);for(let t=0;t<p;t++){const t=r.readVarUint(n);let s=r.readVarUint(n);const a=JSON.parse(r.readVarString(n)),p=e.meta.get(t),u=e.states.get(t),_=void 0===p?0:p.clock;(_<s||_===s&&null===a&&e.states.has(t))&&(null===a?t===e.clientID&&null!=e.getLocalState()?s++:e.states.delete(t):e.states.set(t,a),e.meta.set(t,{clock:s,lastUpdated:i}),void 0===p&&null!==a?o.push(t):void 0!==p&&null===a?l.push(t):null!==a&&(h.equalityDeep(a,u)||d.push(t),c.push(t)))}(o.length>0||d.length>0||l.length>0)&&e.emit("change",[{added:o,updated:d,removed:l},s]),(o.length>0||c.length>0||l.length>0)&&e.emit("update",[{added:o,updated:c,removed:l},s])}},{"lib0/encoding":"iMu7f","lib0/decoding":"gVpVW","lib0/time":"bwglv","lib0/math":"8ydGZ","lib0/observable":"ewQE3","lib0/function":"bmDBb",yjs:"dugeO","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],"42CYj":[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"subscribe",(()=>l)),n.export(s,"unsubscribe",(()=>p)),n.export(s,"publish",(()=>u));var i=e("./map.js"),r=e("./set.js"),a=e("./buffer.js"),o=e("./storage.js");const c=new Map;const h="undefined"==typeof BroadcastChannel?class{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)}postMessage(e){o.varStorage.setItem(this.room,a.toBase64(a.createUint8ArrayFromArrayBuffer(e)))}close(){o.offChange(this._onChange)}}:BroadcastChannel,d=e=>i.setIfUndefined(c,e,(()=>{const t=r.create(),s=new h(e);return s.onmessage=e=>t.forEach((t=>t(e.data,"broadcastchannel"))),{bc:s,subs:t}})),l=(e,t)=>(d(e).subs.add(t),t),p=(e,t)=>{const s=d(e),n=s.subs.delete(t);return n&&0===s.subs.size&&(s.bc.close(),c.delete(e)),n},u=(e,t,s=null)=>{const n=d(e);n.bc.postMessage(t),n.subs.forEach((e=>e(t,s)))}},{"./map.js":"erHG1","./set.js":"3aqr7","./buffer.js":"9uhqR","./storage.js":"3Gk2E","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],jgKsD:[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"computeDocumentHash",(()=>r)),n.export(s,"SyncHealthMonitor",(()=>a));var i=e("yjs");function r(e){return function(e){let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e[s]|0;return t.toString(36)}(i.encodeStateAsUpdate(e))}class a{constructor(e,t={}){this.options=t,this.localHash="",this.peerHashes=new Map,this.provider=e,this.options.checkInterval=t.checkInterval??1e4}start(){this.intervalId||(console.log("[SyncMonitor] Starting health checks..."),this.intervalId=setInterval((()=>{this.checkHealth()}),this.options.checkInterval),this.provider.pubsub.subscribe("sync-health",(e=>{"hash-broadcast"===e.type&&this.handlePeerHash(e.clientId,e.hash)})))}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}checkHealth(){this.provider.connected&&(this.localHash=r(this.provider.doc),this.provider.pubsub.publish("sync-health",{type:"hash-broadcast",clientId:this.provider.doc.clientID,hash:this.localHash}),this.detectDivergence())}handlePeerHash(e,t){this.peerHashes.set(e,t)}detectDivergence(){const e=[];this.peerHashes.forEach(((t,s)=>{t!==this.localHash&&e.push(s)})),e.length>0&&(console.warn("[SyncMonitor] ⚠️ Desync detected with clients:",e),console.warn("[SyncMonitor] Local hash:",this.localHash,"Peer hashes:",Array.from(this.peerHashes.entries())),console.log("[SyncMonitor] 🔄 Triggering automatic re-sync..."),this.provider.syncNow(),this.options.onDesync&&this.options.onDesync({localHash:this.localHash,peerHashes:new Map(this.peerHashes),divergentClients:e,timestamp:Date.now()}))}}},{yjs:"dugeO","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}]},[],0,"parcelRequire55a5");
@@ -0,0 +1 @@
1
+ !function(e,t,s,n,i){var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},o="function"==typeof r[n]&&r[n],a=o.cache||{},h="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function c(t,s){if(!a[t]){if(!e[t]){var i="function"==typeof r[n]&&r[n];if(!s&&i)return i(t,!0);if(o)return o(t,!0);if(h&&"string"==typeof t)return h(t);var d=new Error("Cannot find module '"+t+"'");throw d.code="MODULE_NOT_FOUND",d}u.resolve=function(s){var n=e[t][1][s];return null!=n?n:s},u.cache={};var l=a[t]=new c.Module(t);e[t][0].call(l.exports,u,l,l.exports,this)}return a[t].exports;function u(e){var t=u.resolve(e);return!1===t?{}:c(t)}}c.isParcelRequire=!0,c.Module=function(e){this.id=e,this.bundle=c,this.exports={}},c.modules=e,c.cache=a,c.parent=o,c.register=function(t,s){e[t]=[function(e,t){t.exports=s},{}]},Object.defineProperty(c,"root",{get:function(){return r[n]}}),r[n]=c;for(var d=0;d<t.length;d++)c(t[d])}({bgO1Z:[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"Sync",(()=>a));var i=e("../Base/index"),r=e("../../../../node_modules/y-generic/dist/providers/gun/index"),o=e("y-generic");Object.defineProperty(Array.prototype,"flat",{value:function(e=1){return this.reduce((function(t,s){return t.concat(Array.isArray(s)&&e>1?s.flat(e-1):s)}),[])}});class a extends i.Sync{store="";gunServer=[];persistent=!1;syncFallbackTimer=null;destroy(){null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),super.destroy(),this.gunServer=[],this.provider?.disconnect()}uniqueID(){const e=super.uniqueID();return e?btoa(e+(this.persistent?"p":"")):null}async connect(e){super.connect(e),this.gunServer=e.config?.urls||[],this.persistent=e.config?.persistent||!1,window.Gun&&window.Gun?.SEA?this.init(!0):this.load(["https://cdn.jsdelivr.net/npm/gun/gun.js","https://cdn.jsdelivr.net/npm/gun/sea.js"],this)}init(e,t){if(0==this.gunServer.length)return this.sendDisconnectError("You have to provide at least one relay server.");const s=this.uniqueID();if(e&&window.Gun&&s){this.transport=new(0,r.GunTransport)({gun:window.Gun,sea:window.Gun?.SEA,peers:this.gunServer,debug:!1,batchInterval:200,gunOptions:{localStorage:!1,radisk:!1},password:this.password}),this.store=s,this.provider=new(0,o.GenericProvider)(this.db.doc,this.transport),this.db.setAwareness(this.provider.awareness);let e=!1;const t=()=>{e||(e=!0,null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),this.sendConnect())};this.provider.on("synced",(e=>{console.log("Document synchronized",e.synced),t()})),this.provider.on("status",(e=>{const s=e.state;console.log(`Status changed: ${s}`,"info"),"connected"===s?this.syncFallbackTimer=setTimeout((()=>{console.log("Sync fallback: no remote peers, proceeding as first peer"),t()}),2e3):"disconnected"===s?console.warn("Disconnected from GunDB relay server"):console.warn(`GunDB status: ${s}`)})),this.provider.pubsub.subscribe("*",((e,t)=>{this.onReceive?.(t,e)})),this.provider.connect({room:this.store,persistent:this.persistent,doc:this.persistent?this.db.doc:void 0})}else{let e="GunDB unknown error";t?e="Could not load resource: "+t:window.Gun?window.Gun?.SEA||(e="Could not load GunDB SEA security module"):e="Could not load GunDB interface",this.sendDisconnectError(e)}}pubsubSend(e,t){this.provider&&(this.provider.pubsub.publish(e,t),this.replyOnReceive&&this.onReceive?.(e,t))}}},{"../Base/index":"2cTju","../../../../node_modules/y-generic/dist/providers/gun/index":"dCfeB","y-generic":"3M9RT","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],dCfeB:[function(e,t,s){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(s),n.export(s,"GunTransport",(()=>h));var i=e("lib0/encoding"),r=e("y-protocols/sync");const o=(()=>{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?3988292384^s>>>1:s>>>1;e[t]=s}return e})();function a(e){const t=function(e){let t=4294967295;for(let s=0;s<e.length;s++)t=t>>>8^o[255&(t^e[s])];return(4294967295^t)>>>0}(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}class h{constructor(e){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,this.persistentMode=!1,this.persistDoc=null,this.persistDebounceMs=2e3,this.isWritingToGun=!1,this.savePending=!1,this.pendingLoad=null,!e.gun)throw new Error('GunTransport requires the "gun" option. Please provide the Gun constructor: import Gun from "gun"; new GunTransport({ gun: Gun, ... })');if(e.password&&!e.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: "..." })');this.options={gun:e.gun,peers:e.peers??[],gunOptions:e.gunOptions??{},debug:e.debug??!1,batchInterval:e.batchInterval??100,password:e.password,sea:e.sea},this.encryptionEnabled=!(!e.password||!e.sea),this.encryptionEnabled&&this.log("🔐 Encryption enabled")}async connect(e){if(this._connected)throw new Error("Already connected");if(this._room=e.room,this.connectionTime=Date.now(),this.persistentMode=e.persistent??!1,this.persistDoc=e.doc??null,this.persistDebounceMs=e.persistDebounceMs??2e3,this.persistentMode&&!this.persistDoc)throw new Error("GunTransport: a Y.Doc must be provided via config.doc when persistent is true");this.log("🔗 Initializing Gun...");const t={localStorage:!1,radisk:!1,...this.options.gunOptions};this.options.peers.length>0&&(t.peers=this.options.peers,this.log("📡 Connecting to peers:",this.options.peers)),this.gun=new this.options.gun(t),this.roomNode=this.gun.get(`yjs-room-${this._room}`),this.log("✅ Gun initialized for room:",this._room),this.setupUpdateListener(),this.setupAwarenessListener(),this._connected=!0,this.persistentMode?this.loadSnapshot():this.roomNode.get("snapshot").put({cleared:!0,timestamp:Date.now()})}setupUpdateListener(){let e=0;let t=!1;this.roomNode.get("updates").once((e=>{if(!e)return t=!0,void this.log("📭 No existing updates found");this.log("📥 Loading initial state..."),Object.keys(e).forEach((t=>{if("_"===t)return;const s=e[t];if(!s||!s.data)return;const n=`${t}-${s.sequence||Math.floor(s.timestamp/100)}`;this.processedUpdates.has(n)||this.pendingUpdates.set(n,s)})),this.processPendingUpdates(),t=!0,this.log("✅ Initial state loaded")})),this.updateListener=this.roomNode.get("updates").map().on(((s,n)=>{if(!t)return;if(!s||!s.data)return;if(s.timestamp&&s.timestamp<this.connectionTime)return;const i=`${n}-${s.sequence||Math.floor(s.timestamp/100)}`;if(this.processedUpdates.has(i))return;this.pendingUpdates.set(i,s);const r=Date.now();r-e<300?this.throttleTimeout||(this.throttleTimeout=setTimeout((()=>{this.processPendingUpdates(),e=Date.now(),this.throttleTimeout=void 0}),300)):(e=r,this.processPendingUpdates())})),this.log("👂 Listening for new updates...")}async processPendingUpdates(){if(0===this.pendingUpdates.size)return;const e=Array.from(this.pendingUpdates.entries());this.pendingUpdates.clear();for(const[t,s]of e){if(this.processedUpdates.add(t),this.processedUpdates.size>200){const e=Array.from(this.processedUpdates);e.slice(0,e.length-200).forEach((e=>{this.processedUpdates.delete(e)}))}try{let t=s.data;if(s.encrypted&&this.encryptionEnabled&&(t=await this.decrypt(t),!t)){this.log("❌ Failed to decrypt update (wrong password?)");continue}const n=this.base64ToUint8Array(t),i=this.unframeUpdates(n);if(this._callback)for(const e of i)this._callback(e);1===e.length&&this.log("📥 Received update:",i.length,1===i.length?"message":"messages",s.encrypted?"(decrypted)":"")}catch(e){this.log("❌ Error processing update:",e)}}e.length>1&&this.log(`📥 Processed ${e.length} batched updates`)}disconnect(){this._connected&&(this.log("👋 Disconnecting..."),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=void 0),this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=void 0),this.persistentMode&&this.persistDoc&&this.saveSnapshot(),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.persistentMode=!1,this.persistDoc=null,this.pendingLoad=null,this.log("✅ Disconnected"))}send(e){if(!this._connected||!this.roomNode)return void this.log("⚠️ Not connected, cannot send");1!==this.peekMessageType(e)?(this.updateBatch.push(e),this.batchTimeout&&clearTimeout(this.batchTimeout),this.batchTimeout=setTimeout((()=>{this.flushBatch()}),this.options.batchInterval),this.persistentMode&&this.queuePersist()):this.sendAwareness(e)}peekMessageType(e){return e.length<5?-1:e[4]}async sendAwareness(e){let t=this.uint8ArrayToBase64(e);this.encryptionEnabled&&(t=await this.encrypt(t));const s=`aware-${Date.now()}-${Math.random().toString(36).substr(2,5)}`;this.lastAwarenessId=s,this.roomNode.get("awareness").put({data:t,id:s,timestamp:Date.now(),encrypted:this.encryptionEnabled}),this.log("📤 Sent awareness update",this.encryptionEnabled?"(encrypted)":"")}setupAwarenessListener(){this.awarenessListener=this.roomNode.get("awareness").on((async e=>{if(e&&e.data&&e.id!==this.lastAwarenessId&&!(e.timestamp&&e.timestamp<this.connectionTime))try{let t=e.data;if(e.encrypted&&this.encryptionEnabled&&(t=await this.decrypt(t),!t))return void this.log("❌ Failed to decrypt awareness (wrong password?)");const s=this.base64ToUint8Array(t);this._callback&&this._callback(s),this.log("📥 Received awareness update",e.encrypted?"(decrypted)":"")}catch(e){this.log("❌ Error processing awareness:",e)}})),this.log("👂 Listening for awareness updates...")}frameUpdates(e){const t=e.reduce(((e,t)=>e+4+t.length),0),s=new Uint8Array(t),n=new DataView(s.buffer);let i=0;for(const t of e)n.setUint32(i,t.length,!1),s.set(t,i+4),i+=4+t.length;return s}unframeUpdates(e){const t=[],s=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n+4<=e.length;){const i=s.getUint32(n,!1);if(n+=4,i<0||n+i>e.length){this.log("⚠️ Malformed batch framing, stopping split early");break}t.push(e.subarray(n,n+i)),n+=i}return t}async flushBatch(){if(0===this.updateBatch.length)return;const e=this.frameUpdates(this.updateBatch);this.updateBatch=[];let t=this.uint8ArrayToBase64(e);this.encryptionEnabled&&(t=await this.encrypt(t));const s=this.generateUpdateId(),n=Date.now(),i=Math.floor(n/100);this.processedUpdates.add(`${s}-${i}`);this.roomNode.get("updates").get(s).put({data:t,timestamp:n,sequence:i,size:e.length,encrypted:this.encryptionEnabled}),this.log("📤 Sent update:",e.length,"bytes",this.encryptionEnabled?"(encrypted)":"")}onMessage(e){if(this._callback=e,this.pendingLoad){const t=this.pendingLoad;this.pendingLoad=null,Promise.resolve().then((()=>e(t)))}return()=>{this._callback=void 0}}get isConnected(){return this._connected}generateUpdateId(){const e=`slot-${this.updateSlot}`;return this.updateSlot=(this.updateSlot+1)%this.BUFFER_SIZE,e}queuePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout((()=>this.saveSnapshot()),this.persistDebounceMs)}async saveSnapshot(){if(this.persistDoc&&this.persistentMode&&this.roomNode)if(this.isWritingToGun)this.savePending=!0;else{this.isWritingToGun=!0,this.savePending=!1;try{const e=i.createEncoder();i.writeVarUint(e,0),r.writeSyncStep2(e,this.persistDoc);const t=i.toUint8Array(e);let s=this.uint8ArrayToBase64(t);this.encryptionEnabled&&(s=await this.encrypt(s)),this.roomNode.get("snapshot").put({data:s,timestamp:Date.now(),encrypted:this.encryptionEnabled}),this.log("💾 Snapshot saved",t.length,"bytes")}catch(e){this.log("❌ Error saving snapshot:",e.message),console.warn("GunTransport: Failed to save snapshot. Will retry later.",e),this.savePending=!0}finally{this.isWritingToGun=!1,this.savePending&&setTimeout((()=>this.saveSnapshot()),1e3)}}}loadSnapshot(){this.roomNode.get("snapshot").once((async e=>{if(e&&e.data&&!e.cleared)try{let t=e.data;if(e.encrypted&&this.encryptionEnabled){const e=await this.decrypt(t);if(!e)return void this.log("❌ Failed to decrypt snapshot (wrong password?)");t=e}const s=this.base64ToUint8Array(t);if(s.length>0){const e=a(s);this._callback?this._callback(e):this.pendingLoad=e,this.log("💾 Loaded snapshot:",s.length,"bytes")}}catch(e){this.log("❌ Error loading snapshot:",e),console.warn("GunTransport: Failed to load snapshot:",e)}else this.log("📭 No snapshot found in Gun")}))}uint8ArrayToBase64(e){let t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t)}base64ToUint8Array(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}async encrypt(e){return this.options.sea&&this.options.password?await this.options.sea.encrypt(e,this.options.password):e}async decrypt(e){if(!this.options.sea||!this.options.password)return e;try{return await this.options.sea.decrypt(e,this.options.password)||null}catch(e){return this.log("❌ Decryption failed:",e),null}}log(...e){this.options.debug&&console.log("[GunTransport]",...e)}}},{"lib0/encoding":"iMu7f","y-protocols/sync":"2fRsv","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],fDdlt:[function(e,t,s){var n,i,r=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function h(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!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:o}catch(e){n=o}try{i="function"==typeof clearTimeout?clearTimeout:a}catch(e){i=a}}();var c,d=[],l=!1,u=-1;function p(){l&&c&&(l=!1,c.length?d=c.concat(d):u=-1,d.length&&g())}function g(){if(!l){var e=h(p);l=!0;for(var t=d.length;t;){for(c=d,d=[];++u<t;)c&&c[u].run();u=-1,t=d.length}c=null,l=!1,function(e){if(i===clearTimeout)return clearTimeout(e);if((i===a||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{return i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function m(){}r.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var s=1;s<arguments.length;s++)t[s-1]=arguments[s];d.push(new f(e,t)),1!==d.length||l||h(g)},f.prototype.run=function(){this.fun.apply(null,this.array)},r.title="browser",r.browser=!0,r.env={},r.argv=[],r.version="",r.versions={},r.on=m,r.addListener=m,r.once=m,r.off=m,r.removeListener=m,r.removeAllListeners=m,r.emit=m,r.prependListener=m,r.prependOnceListener=m,r.listeners=function(e){return[]},r.binding=function(e){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(e){throw new Error("process.chdir is not supported")},r.umask=function(){return 0}},{}]},[],0,"parcelRequire55a5");
@@ -0,0 +1 @@
1
+ !function(e,t,o,r,n){var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},s="function"==typeof i[r]&&i[r],c=s.cache||{},a="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function h(t,o){if(!c[t]){if(!e[t]){var n="function"==typeof i[r]&&i[r];if(!o&&n)return n(t,!0);if(s)return s(t,!0);if(a&&"string"==typeof t)return a(t);var d=new Error("Cannot find module '"+t+"'");throw d.code="MODULE_NOT_FOUND",d}p.resolve=function(o){var r=e[t][1][o];return null!=r?r:o},p.cache={};var l=c[t]=new h.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return c[t].exports;function p(e){var t=p.resolve(e);return!1===t?{}:h(t)}}h.isParcelRequire=!0,h.Module=function(e){this.id=e,this.bundle=h,this.exports={}},h.modules=e,h.cache=c,h.parent=s,h.register=function(t,o){e[t]=[function(e,t){t.exports=o},{}]},Object.defineProperty(h,"root",{get:function(){return i[r]}}),i[r]=h;for(var d=0;d<t.length;d++)h(t[d])}({kwJov:[function(e,t,o){var r=e("@parcel/transformer-js/src/esmodule-helpers.js");r.defineInteropFlag(o),r.export(o,"Sync",(()=>c));var n=e("../Base/index"),i=e("../../../../node_modules/y-generic/dist/providers/peerjs/index"),s=e("y-generic");class c extends n.Sync{syncFallbackTimer=null;destroy(){null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),super.destroy(),this.provider?.disconnect()}async connect(e){if(super.connect(e),this.host=e.config?.host||void 0,this.port=e.config?.port?parseInt(e.config.port,10):void 0,this.peerPath=e.config?.path||void 0,e.config?.iceServers)try{this.iceServers=JSON.parse(e.config.iceServers)}catch{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,i.PeerJSTransport)({peer:window.Peer,...Object.keys(t).length>0?{peerOptions:t}:{},...this.password?{password:this.password}:{}}),this.provider=new(0,s.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)=>{this.onReceive?.(t,e)})),this.provider.connect({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){this.provider&&(this.provider.pubsub.publish(e,t),this.replyOnReceive&&this.onReceive?.(e,t))}}},{"../Base/index":"2cTju","../../../../node_modules/y-generic/dist/providers/peerjs/index":"bILLl","y-generic":"3M9RT","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],bILLl:[function(e,t,o){var r=e("@parcel/transformer-js/src/esmodule-helpers.js");r.defineInteropFlag(o),r.export(o,"PeerJSTransport",(()=>n));class n{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, ... })');this.options={peer:e.peer,peerOptions:e.peerOptions??{},password:e.password??"",maxConns:e.maxConns??20+Math.floor(15*Math.random()),debug:e.debug??!1}}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,{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,{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",(()=>{if(o)return;o=!0,clearTimeout(r),this.log("Connected to coordinator"),this.coordinatorConn=n;const t={conn:n,connected:!0,peerId:this.coordinatorPeerId};this.peers.set(this.coordinatorPeerId,t),this.knownPeers.add(this.coordinatorPeerId),this._peerConnectCallback?.(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 n=new this.options.peer(this.coordinatorPeerId,{debug:this.options.debug?3:0,...this.options.peerOptions}),i=setTimeout((()=>{this.log("❌ Timeout claiming coordinator ID"),n.destroy(),r(new Error("Timeout claiming coordinator ID"))}),5e3);n.on("open",(r=>{if(clearTimeout(i),r===this.coordinatorPeerId){this.log("✅ Successfully claimed coordinator ID:",r),this.peer=n,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()}})),n.on("error",(e=>{clearTimeout(i),this.log("❌ Error claiming coordinator ID:",e),n.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,{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{this.peer?.destroy()}catch(e){}this.peer=null,this._connected=!1;const t=()=>{this.log("🌐 Network restored – retrying reestablish as regular peer"),this.reestablishAsRegularPeer()};"undefined"==typeof navigator||navigator.onLine?setTimeout(t,3e3):window.addEventListener("online",t,{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",(()=>{o.connected=!0,this.knownPeers.add(t),this._peerConnectCallback?.(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)}}},{"@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],fDdlt:[function(e,t,o){var r,n,i=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function c(){throw new Error("clearTimeout has not been defined")}function a(e){if(r===setTimeout)return setTimeout(e,0);if((r===s||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{n="function"==typeof clearTimeout?clearTimeout:c}catch(e){n=c}}();var h,d=[],l=!1,p=-1;function u(){l&&h&&(l=!1,h.length?d=h.concat(d):p=-1,d.length&&g())}function g(){if(!l){var e=a(u);l=!0;for(var t=d.length;t;){for(h=d,d=[];++p<t;)h&&h[p].run();p=-1,t=d.length}h=null,l=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===c||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{return n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function m(){}i.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];d.push(new f(e,t)),1!==d.length||l||a(g)},f.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=m,i.addListener=m,i.once=m,i.off=m,i.removeListener=m,i.removeAllListeners=m,i.emit=m,i.prependListener=m,i.prependOnceListener=m,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}]},[],0,"parcelRequire55a5");