@liascript/exporter
Version:
A generic exporter for LiaScript
1 lines • 12.2 kB
JavaScript
!function(e,t,n,s,r){var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},o="function"==typeof i[s]&&i[s],a=o.cache||{},c="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function u(t,n){if(!a[t]){if(!e[t]){var r="function"==typeof i[s]&&i[s];if(!n&&r)return r(t,!0);if(o)return o(t,!0);if(c&&"string"==typeof t)return c(t);var h=new Error("Cannot find module '"+t+"'");throw h.code="MODULE_NOT_FOUND",h}l.resolve=function(n){var s=e[t][1][n];return null!=s?s:n},l.cache={};var d=a[t]=new u.Module(t);e[t][0].call(d.exports,l,d,d.exports,this)}return a[t].exports;function l(e){var t=l.resolve(e);return!1===t?{}:u(t)}}u.isParcelRequire=!0,u.Module=function(e){this.id=e,this.bundle=u,this.exports={}},u.modules=e,u.cache=a,u.parent=o,u.register=function(t,n){e[t]=[function(e,t){t.exports=n},{}]},Object.defineProperty(u,"root",{get:function(){return i[s]}}),i[s]=u;for(var h=0;h<t.length;h++)u(t[h])}({bgO1Z:[function(e,t,n){var s=e("@parcel/transformer-js/src/esmodule-helpers.js");s.defineInteropFlag(n),s.export(n,"Sync",(()=>a));var r=e("../Base/index"),i=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,n){return t.concat(Array.isArray(n)&&e>1?n.flat(e-1):n)}),[])}});class a extends r.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 n=this.uniqueID();if(e&&window.Gun&&n){this.transport=new(0,i.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=n,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 n=e.state;console.log(`Status changed: ${n}`,"info"),"connected"===n?this.syncFallbackTimer=setTimeout((()=>{console.log("Sync fallback: no remote peers, proceeding as first peer"),t()}),2e3):"disconnected"===n?console.warn("Disconnected from GunDB relay server"):console.warn(`GunDB status: ${n}`)})),this.provider.pubsub.subscribe("*",((e,t)=>{this.onReceive?.(t,e)})),this.provider.connect({room:this.store})}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,n){var s=e("@parcel/transformer-js/src/esmodule-helpers.js");s.defineInteropFlag(n),s.export(n,"GunTransport",(()=>r));class r{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,!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");this._room=e.room,this.connectionTime=Date.now(),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}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 n=e[t];if(!n||!n.data)return;const s=`${t}-${n.sequence||Math.floor(n.timestamp/100)}`;this.processedUpdates.has(s)||this.pendingUpdates.set(s,n)})),this.processPendingUpdates(),t=!0,this.log("✅ Initial state loaded")})),this.updateListener=this.roomNode.get("updates").map().on(((n,s)=>{if(!t)return;if(!n||!n.data)return;if(n.timestamp&&n.timestamp<this.connectionTime)return;const r=`${s}-${n.sequence||Math.floor(n.timestamp/100)}`;if(this.processedUpdates.has(r))return;this.pendingUpdates.set(r,n);const i=Date.now();i-e<300?this.throttleTimeout||(this.throttleTimeout=setTimeout((()=>{this.processPendingUpdates(),e=Date.now(),this.throttleTimeout=void 0}),300)):(e=i,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,n]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=n.data;if(n.encrypted&&this.encryptionEnabled&&(t=await this.decrypt(t),!t)){this.log("❌ Failed to decrypt update (wrong password?)");continue}const s=this.base64ToUint8Array(t);this._callback&&this._callback(s),1===e.length&&this.log("📥 Received update:",s.length,"bytes",n.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.throttleTimeout&&(clearTimeout(this.throttleTimeout),this.throttleTimeout=void 0),this.processPendingUpdates(),this.flushBatch(),this.updateListener&&(this.updateListener=null),this.awarenessListener&&(this.awarenessListener=null),this.roomNode=null,this.gun=null,this._connected=!1,this.processedUpdates.clear(),this.pendingUpdates.clear(),this.log("✅ Disconnected"))}send(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.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 n=`aware-${Date.now()}-${Math.random().toString(36).substr(2,5)}`;this.lastAwarenessId=n,this.roomNode.get("awareness").put({data:t,id:n,timestamp:Date.now(),encrypted:this.encryptionEnabled}),this.log("📤 Sent awareness update",this.encryptionEnabled?"(encrypted)":"")}setupAwarenessListener(){this.awarenessListener=this.roomNode.get("awareness").on((async 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 n=this.base64ToUint8Array(t);this._callback&&this._callback(n),this.log("📥 Received awareness update",e.encrypted?"(decrypted)":"")}catch(e){this.log("❌ Error processing awareness:",e)}})),this.log("👂 Listening for awareness updates...")}async flushBatch(){if(0===this.updateBatch.length)return;const e=this.updateBatch.reduce(((e,t)=>e+t.length),0),t=new Uint8Array(e);let n=0;for(const e of this.updateBatch)t.set(e,n),n+=e.length;this.updateBatch=[];let s=this.uint8ArrayToBase64(t);this.encryptionEnabled&&(s=await this.encrypt(s));const r=this.generateUpdateId(),i=Date.now(),o=Math.floor(i/100);this.processedUpdates.add(`${r}-${o}`);this.roomNode.get("updates").get(r).put({data:s,timestamp:i,sequence:o,size:t.length,encrypted:this.encryptionEnabled}),this.log("📤 Sent update:",t.length,"bytes",this.encryptionEnabled?"(encrypted)":"")}onMessage(e){return this._callback=e,()=>{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}uint8ArrayToBase64(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}base64ToUint8Array(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}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)}}},{"@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}],fDdlt:[function(e,t,n){var s,r,i=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function c(e){if(s===setTimeout)return setTimeout(e,0);if((s===o||!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:o}catch(e){s=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var u,h=[],d=!1,l=-1;function p(){d&&u&&(d=!1,u.length?h=u.concat(h):l=-1,h.length&&g())}function g(){if(!d){var e=c(p);d=!0;for(var t=h.length;t;){for(u=h,h=[];++l<t;)u&&u[l].run();l=-1,t=h.length}u=null,d=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===a||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function m(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];h.push(new f(e,t)),1!==h.length||d||c(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");