UNPKG

@liascript/exporter

Version:
1 lines 9.1 kB
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("hj5SX",(function(s,n){e(s.exports,"Sync",(function(){return h}));var i=t("2Xs1f"),r=t("dM3DM"),o=t("5Owdb"),u=t("3bajT"),c=t("akyql");class h extends o.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,s;super.connect(e),this.publishKey=null===(t=e.config)||void 0===t?void 0:t.publishKey,this.subscribeKey=null===(s=e.config)||void 0===s?void 0:s.subscribeKey,window.PubNub?this.init(!0):this.load(["//cdn.pubnub.com/sdk/javascript/pubnub.10.2.7.min.js"],this)}init(e,t){if(!this.publishKey||!this.subscribeKey)return this.sendDisconnectError("You have to provide a valid pair of keys");const s=this.uniqueID();if(e&&window.PubNub&&s){this.transport=new(0,u.PubNubTransport),this.provider=new(0,c.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("PubNub: document synchronized",e.synced),t()})),this.provider.on("status",(e=>{const s=e.state;console.log(`PubNub status: ${s}`),"connected"===s?this.syncFallbackTimer=setTimeout((()=>{console.log("PubNub: sync fallback, proceeding as first peer"),t()}),2e3):"disconnected"===s&&console.warn("PubNub: disconnected")})),this.provider.connect((0,r.default)({room:s,publishKey:this.publishKey,subscribeKey:this.subscribeKey},this.password?{cipherKey:this.password}:{}))}else{let e="PubNub unknown error";t?e="Could not load resource: "+t:window.PubNub||(e="Could not load PubNub SDK"),this.sendDisconnectError(e)}}constructor(...e){super(...e),(0,i.default)(this,"syncFallbackTimer",null)}}})),t.register("3bajT",(function(t,s){e(t.exports,"PubNubTransport",(function(){return n}));class n{get isConnected(){return this._isConnected}async connect(e){var t;if(this.config=e,this.debug=null!==(t=e.debug)&&void 0!==t&&t,!e.publishKey||!e.subscribeKey)throw new Error("PubNub requires publishKey and subscribeKey");if(!e.room)throw new Error("Room name is required");if(this.log("Initializing PubNub transport..."),void 0===globalThis.PubNub)throw new Error("PubNub SDK not loaded. Include the PubNub script from CDN: https://cdn.pubnub.com/sdk/javascript/pubnub.10.2.7.min.js");this.uuid=this.generateUUID(),this.channel=btoa(e.room),this.log(`Connecting as ${this.uuid} to channel ${this.channel}`);const s={publishKey:e.publishKey,subscribeKey:e.subscribeKey,userId:this.uuid};return e.cipherKey&&(s.cipherKey=e.cipherKey,this.log("Message encryption enabled")),this.pubnub=new PubNub(s),new Promise(((e,t)=>{const s=setTimeout((()=>{t(new Error("PubNub connection timeout"))}),1e4);this.pubnub.addListener({status:t=>{this.log(`Status: ${t.category}`,t),"PNConnectedCategory"===t.category?(this._isConnected=!0,clearTimeout(s),this.log("✅ Connected to PubNub"),e()):"PNNetworkDownCategory"===t.category?(this.log("⚠️ Network is down"),this._isConnected=!1):"PNNetworkUpCategory"===t.category&&(this.log("✅ Network is back up"),this._isConnected=!0)},message:e=>{if(e.publisher!==this.uuid&&e.message)try{if("object"==typeof e.message&&e.message.chunked)return void this.handleChunkedMessage(e.message,e.publisher);const t="string"==typeof e.message?this.base64ToUint8(e.message):new Uint8Array(e.message);this.log(`📨 Received ${t.length} bytes from ${e.publisher}`),this.messageCallback?this.messageCallback(t):(this.log("⚠️ Message received before callback registered, buffering..."),this.messageBuffer.push(t))}catch(e){this.log("❌ Error processing message:",e)}},presence:e=>{this.log(`Presence: ${e.action}`,e)}}),this.pubnub.subscribe({channels:[this.channel],withPresence:!0})}))}disconnect(){this.pubnub&&(this.log("Disconnecting from PubNub..."),this.pubnub.unsubscribeAll(),this.pubnub=null),this._isConnected=!1}send(e){if(this.pubnub&&this._isConnected)try{var t;const n=this.uint8ToBase64(e),i=n.length;if(i>this.MAX_MESSAGE_SIZE)return this.log(`📦 Message too large (${i} bytes), chunking into smaller pieces...`),void this.sendChunked(n,e.length);var s;this.log(`📤 Sending ${e.length} bytes`),this.pubnub.publish({channel:this.channel,message:n,storeInHistory:null!==(s=null===(t=this.config)||void 0===t?void 0:t.storeInHistory)&&void 0!==s&&s}).then((e=>{this.log("✅ Message published",e)})).catch((e=>{this.log("❌ Publish error:",e)}))}catch(e){this.log("❌ Send error:",e)}else this.log("⚠️ Cannot send: not connected")}sendChunked(e,t){const s=this.generateUUID(),n=[];for(let t=0;t<e.length;t+=this.MAX_MESSAGE_SIZE)n.push(e.slice(t,t+this.MAX_MESSAGE_SIZE));this.log(`📦 Splitting ${t} bytes into ${n.length} chunks (id: ${s.slice(0,8)}...)`),n.forEach(((e,t)=>{const i={chunked:!0,id:s,index:t,total:n.length,data:e};this.pubnub.publish({channel:this.channel,message:i,storeInHistory:!1}).then((()=>{this.log(`✅ Chunk ${t+1}/${n.length} sent`)})).catch((e=>{this.log(`❌ Failed to send chunk ${t+1}:`,e)}))}))}handleChunkedMessage(e,t){const{id:s,index:n,total:i,data:r}=e;this.log(`📨 Received chunk ${n+1}/${i} from ${t}`),this.chunkBuffer.has(s)||this.chunkBuffer.set(s,new Map);const o=this.chunkBuffer.get(s);if(o.set(n,r),o.size===i){this.log(`📦 All chunks received, reassembling message ${s.slice(0,8)}...`);let e="";for(let t=0;t<i;t++){const n=o.get(t);if(!n)return this.log(`❌ Missing chunk ${t}, cannot reassemble`),void this.chunkBuffer.delete(s);e+=n}this.chunkBuffer.delete(s);try{const s=this.base64ToUint8(e);this.log(`✅ Message reassembled: ${s.length} bytes from ${t}`),this.messageCallback?this.messageCallback(s):this.messageBuffer.push(s)}catch(e){this.log("❌ Error reassembling chunked message:",e)}}}onMessage(e){if(this.messageCallback=e,this.messageBuffer.length>0){this.log(`📦 Flushing ${this.messageBuffer.length} buffered messages...`);for(const t of this.messageBuffer)e(t);this.messageBuffer=[]}return()=>{this.messageCallback=void 0}}async getPresence(){if(!this.pubnub||!this._isConnected)return[];try{var e;const t=await this.pubnub.hereNow({channels:[this.channel],includeUUIDs:!0});return((null===(e=t.channels[this.channel])||void 0===e?void 0:e.occupants)||[]).map((e=>e.uuid)).filter((e=>e!==this.uuid))}catch(e){return this.log("Error getting presence:",e),[]}}uint8ToBase64(e){let t="";for(let s=0;s<e.length;s+=8192){const n=e.subarray(s,Math.min(s+8192,e.length));t+=String.fromCharCode(...n)}return btoa(t)}base64ToUint8(e){return new Uint8Array(atob(e).split("").map((e=>e.charCodeAt(0))))}generateUUID(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}log(e,...t){this.debug&&console.log(`[PubNubTransport] ${e}`,...t)}constructor(){this.pubnub=null,this.channel="",this.uuid="",this._isConnected=!1,this.config=null,this.debug=!1,this.messageBuffer=[],this.chunkBuffer=new Map,this.MAX_MESSAGE_SIZE=3e4}}})),t.register("jhEmn",(function(e,t){var s,n,i=e.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function u(e){if(s===setTimeout)return setTimeout(e,0);if((s===r||!s)&&setTimeout)return s=setTimeout,setTimeout(e,0);try{return s(e,0)}catch(t){try{return s.call(null,e,0)}catch(t){return s.call(this,e,0)}}}!function(){try{s="function"==typeof setTimeout?setTimeout:r}catch(e){s=r}try{n="function"==typeof clearTimeout?clearTimeout:o}catch(e){n=o}}();var c,h=[],l=!1,a=-1;function b(){l&&c&&(l=!1,c.length?h=c.concat(h):a=-1,h.length&&d())}function d(){if(!l){var e=u(b);l=!0;for(var t=h.length;t;){for(c=h,h=[];++a<t;)c&&c[a].run();a=-1,t=h.length}c=null,l=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===o||!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 g(e,t){this.fun=e,this.array=t}function f(){}i.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];h.push(new g(e,t)),1!==h.length||l||u(d)},g.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=f,i.addListener=f,i.once=f,i.off=f,i.removeListener=f,i.removeAllListeners=f,i.emit=f,i.prependListener=f,i.prependOnceListener=f,i.listeners=function(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}}));