@needle-tools/engine 3.6.0-alpha → 3.6.0-alpha.1

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.
@@ -3333,11 +3333,11 @@ a=extmap-allow-mixed`)!==-1){const I=g.sdp.split(`
3333
3333
  isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},t}()),kq={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},_W=function(){function t(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=kq,this.browser=Kh.getBrowser(),this.browserVersion=Kh.getVersion(),this.supports=function(){var A={browser:Kh.isBrowserSupported(),webRTC:Kh.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!A.webRTC)return A;var e;try{e=new RTCPeerConnection(kq),A.audioVideo=!0;var g=void 0;try{g=e.createDataChannel("_PEERJSTEST",{ordered:!0}),A.data=!0,A.reliable=!!g.ordered;try{g.binaryType="blob",A.binaryBlob=!Kh.isIOS}catch{}}catch{}finally{g&&g.close()}}catch{}finally{e&&e.close()}return A}(),this.pack=NJ.pack,this.unpack=NJ.unpack,this._dataCount=1}return t.prototype.noop=function(){},t.prototype.validateId=function(A){return!A||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(A)},t.prototype.chunk=function(A){for(var e=[],g=A.size,I=Math.ceil(g/nt.chunkedMTU),i=0,o=0;o<g;){var C=Math.min(g,o+nt.chunkedMTU),s=A.slice(o,C),a={__peerData:this._dataCount,n:i,data:s,total:I};e.push(a),o=C,i++}return this._dataCount++,e},t.prototype.blobToArrayBuffer=function(A,e){var g=new FileReader;return g.onload=function(I){I.target&&e(I.target.result)},g.readAsArrayBuffer(A),g},t.prototype.binaryStringToArrayBuffer=function(A){for(var e=new Uint8Array(A.length),g=0;g<A.length;g++)e[g]=A.charCodeAt(g)&255;return e.buffer},t.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},t.prototype.isSecure=function(){return location.protocol==="https:"},t}(),nt=new _W,Gq={};tC(Gq,"Peer",()=>Hq,t=>Hq=t);var Jh={},OW=Object.prototype.hasOwnProperty,FI="~";function qh(){}Object.create&&(qh.prototype=Object.create(null),new qh().__proto__||(FI=!1));function PW(t,A,e){this.fn=t,this.context=A,this.once=e||!1}function mq(t,A,e,g,I){if(typeof e!="function")throw new TypeError("The listener must be a function");var i=new PW(e,g||t,I),o=FI?FI+A:A;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],i]:t._events[o].push(i):(t._events[o]=i,t._eventsCount++),t}function Su(t,A){--t._eventsCount===0?t._events=new qh:delete t._events[A]}function cI(){this._events=new qh,this._eventsCount=0}cI.prototype.eventNames=function(){var t=[],A,e;if(this._eventsCount===0)return t;for(e in A=this._events)OW.call(A,e)&&t.push(FI?e.slice(1):e);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(A)):t},cI.prototype.listeners=function(t){var A=FI?FI+t:t,e=this._events[A];if(!e)return[];if(e.fn)return[e.fn];for(var g=0,I=e.length,i=new Array(I);g<I;g++)i[g]=e[g].fn;return i},cI.prototype.listenerCount=function(t){var A=FI?FI+t:t,e=this._events[A];return e?e.fn?1:e.length:0},cI.prototype.emit=function(t,A,e,g,I,i){var o=FI?FI+t:t;if(!this._events[o])return!1;var C=this._events[o],s=arguments.length,a,n;if(C.fn){switch(C.once&&this.removeListener(t,C.fn,void 0,!0),s){case 1:return C.fn.call(C.context),!0;case 2:return C.fn.call(C.context,A),!0;case 3:return C.fn.call(C.context,A,e),!0;case 4:return C.fn.call(C.context,A,e,g),!0;case 5:return C.fn.call(C.context,A,e,g,I),!0;case 6:return C.fn.call(C.context,A,e,g,I,i),!0}for(n=1,a=new Array(s-1);n<s;n++)a[n-1]=arguments[n];C.fn.apply(C.context,a)}else{var B=C.length,Q;for(n=0;n<B;n++)switch(C[n].once&&this.removeListener(t,C[n].fn,void 0,!0),s){case 1:C[n].fn.call(C[n].context);break;case 2:C[n].fn.call(C[n].context,A);break;case 3:C[n].fn.call(C[n].context,A,e);break;case 4:C[n].fn.call(C[n].context,A,e,g);break;default:if(!a)for(Q=1,a=new Array(s-1);Q<s;Q++)a[Q-1]=arguments[Q];C[n].fn.apply(C[n].context,a)}}return!0},cI.prototype.on=function(t,A,e){return mq(this,t,A,e,!1)},cI.prototype.once=function(t,A,e){return mq(this,t,A,e,!0)},cI.prototype.removeListener=function(t,A,e,g){var I=FI?FI+t:t;if(!this._events[I])return this;if(!A)return Su(this,I),this;var i=this._events[I];if(i.fn)i.fn===A&&(!g||i.once)&&(!e||i.context===e)&&Su(this,I);else{for(var o=0,C=[],s=i.length;o<s;o++)(i[o].fn!==A||g&&!i[o].once||e&&i[o].context!==e)&&C.push(i[o]);C.length?this._events[I]=C.length===1?C[0]:C:Su(this,I)}return this},cI.prototype.removeAllListeners=function(t){var A;return t?(A=FI?FI+t:t,this._events[A]&&Su(this,A)):(this._events=new qh,this._eventsCount=0),this},cI.prototype.off=cI.prototype.removeListener,cI.prototype.addListener=cI.prototype.on,cI.prefixed=FI,cI.EventEmitter=cI,Jh=cI;var te={};tC(te,"LogLevel",()=>ZI,t=>ZI=t),tC(te,"default",()=>Mq,t=>Mq=t);var ar=function(t,A){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var g=e.call(t),I,i=[],o;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)i.push(I.value)}catch(C){o={error:C}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(o)throw o.error}}return i},nr=function(t,A,e){if(e||arguments.length===2)for(var g=0,I=A.length,i;g<I;g++)(i||!(g in A))&&(i||(i=Array.prototype.slice.call(A,0,g)),i[g]=A[g]);return t.concat(i||Array.prototype.slice.call(A))},jW="PeerJS: ",ZI;(function(t){t[t.Disabled=0]="Disabled",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.All=3]="All"})(ZI||(ZI={}));var WW=function(){function t(){this._logLevel=ZI.Disabled}return Object.defineProperty(t.prototype,"logLevel",{get:function(){return this._logLevel},set:function(A){this._logLevel=A},enumerable:!1,configurable:!0}),t.prototype.log=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=ZI.All&&this._print.apply(this,nr([ZI.All],ar(A),!1))},t.prototype.warn=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=ZI.Warnings&&this._print.apply(this,nr([ZI.Warnings],ar(A),!1))},t.prototype.error=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=ZI.Errors&&this._print.apply(this,nr([ZI.Errors],ar(A),!1))},t.prototype.setLogFunction=function(A){this._print=A},t.prototype._print=function(A){for(var e=[],g=1;g<arguments.length;g++)e[g-1]=arguments[g];var I=nr([jW],ar(e),!1);for(var i in I)I[i]instanceof Error&&(I[i]="("+I[i].name+") "+I[i].message);A>=ZI.All?console.log.apply(console,nr([],ar(I),!1)):A>=ZI.Warnings?console.warn.apply(console,nr(["WARNING"],ar(I),!1)):A>=ZI.Errors&&console.error.apply(console,nr(["ERROR"],ar(I),!1))},t}(),Mq=new WW,Rq={};tC(Rq,"Socket",()=>Uq,t=>Uq=t);var mo;(function(t){t.Data="data",t.Media="media"})(mo||(mo={}));var gg;(function(t){t.BrowserIncompatible="browser-incompatible",t.Disconnected="disconnected",t.InvalidID="invalid-id",t.InvalidKey="invalid-key",t.Network="network",t.PeerUnavailable="peer-unavailable",t.SslUnavailable="ssl-unavailable",t.ServerError="server-error",t.SocketError="socket-error",t.SocketClosed="socket-closed",t.UnavailableID="unavailable-id",t.WebRTC="webrtc"})(gg||(gg={}));var ns;(function(t){t.Binary="binary",t.BinaryUTF8="binary-utf8",t.JSON="json"})(ns||(ns={}));var rs;(function(t){t.Message="message",t.Disconnected="disconnected",t.Error="error",t.Close="close"})(rs||(rs={}));var $g;(function(t){t.Heartbeat="HEARTBEAT",t.Candidate="CANDIDATE",t.Offer="OFFER",t.Answer="ANSWER",t.Open="OPEN",t.Error="ERROR",t.IdTaken="ID-TAKEN",t.InvalidKey="INVALID-KEY",t.Leave="LEAVE",t.Expire="EXPIRE"})($g||($g={}));var sk={};sk=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xFCckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var VW=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),zW=function(t,A){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var g=e.call(t),I,i=[],o;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)i.push(I.value)}catch(C){o={error:C}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(o)throw o.error}}return i},ZW=function(t,A,e){if(e||arguments.length===2)for(var g=0,I=A.length,i;g<I;g++)(i||!(g in A))&&(i||(i=Array.prototype.slice.call(A,0,g)),i[g]=A[g]);return t.concat(i||Array.prototype.slice.call(A))},XW=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},Uq=function(t){VW(A,t);function A(e,g,I,i,o,C){C===void 0&&(C=5e3);var s=t.call(this)||this;s.pingInterval=C,s._disconnected=!0,s._messagesQueue=[];var a=e?"wss://":"ws://";return s._baseUrl=a+g+":"+I+i+"peerjs?key="+o,s}return A.prototype.start=function(e,g){var I=this;this._id=e;var i="".concat(this._baseUrl,"&id=").concat(e,"&token=").concat(g);this._socket||!this._disconnected||(this._socket=new WebSocket(i+"&version="+sk.version),this._disconnected=!1,this._socket.onmessage=function(o){var C;try{C=JSON.parse(o.data),te.default.log("Server message received:",C)}catch{te.default.log("Invalid server message",o.data);return}I.emit(rs.Message,C)},this._socket.onclose=function(o){I._disconnected||(te.default.log("Socket closed.",o),I._cleanup(),I._disconnected=!0,I.emit(rs.Disconnected))},this._socket.onopen=function(){I._disconnected||(I._sendQueuedMessages(),te.default.log("Socket open"),I._scheduleHeartbeat())})},A.prototype._scheduleHeartbeat=function(){var e=this;this._wsPingTimer=setTimeout(function(){e._sendHeartbeat()},this.pingInterval)},A.prototype._sendHeartbeat=function(){if(!this._wsOpen()){te.default.log("Cannot send heartbeat, because socket closed");return}var e=JSON.stringify({type:$g.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()},A.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},A.prototype._sendQueuedMessages=function(){var e,g,I=ZW([],zW(this._messagesQueue),!1);this._messagesQueue=[];try{for(var i=XW(I),o=i.next();!o.done;o=i.next()){var C=o.value;this.send(C)}}catch(s){e={error:s}}finally{try{o&&!o.done&&(g=i.return)&&g.call(i)}finally{if(e)throw e.error}}},A.prototype.send=function(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(rs.Error,"Invalid message");return}if(this._wsOpen()){var g=JSON.stringify(e);this._socket.send(g)}}},A.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},A.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},A}(Jh.EventEmitter),ak={};tC(ak,"MediaConnection",()=>Kq,t=>Kq=t);var nk={};tC(nk,"Negotiator",()=>Fq,t=>Fq=t);var fu=function(){return fu=Object.assign||function(t){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(t[I]=A[I])}return t},fu.apply(this,arguments)},ku=function(t,A,e,g){function I(i){return i instanceof e?i:new e(function(o){o(i)})}return new(e||(e=Promise))(function(i,o){function C(n){try{a(g.next(n))}catch(B){o(B)}}function s(n){try{a(g.throw(n))}catch(B){o(B)}}function a(n){n.done?i(n.value):I(n.value).then(C,s)}a((g=g.apply(t,A||[])).next())})},Gu=function(t,A){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},g,I,i,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(a){return function(n){return s([a,n])}}function s(a){if(g)throw new TypeError("Generator is already executing.");for(;e;)try{if(g=1,I&&(i=a[0]&2?I.return:a[0]?I.throw||((i=I.return)&&i.call(I),0):I.next)&&!(i=i.call(I,a[1])).done)return i;switch(I=0,i&&(a=[a[0]&2,i.value]),a[0]){case 0:case 1:i=a;break;case 4:return e.label++,{value:a[1],done:!1};case 5:e.label++,I=a[1],a=[0];continue;case 7:a=e.ops.pop(),e.trys.pop();continue;default:if(i=e.trys,!(i=i.length>0&&i[i.length-1])&&(a[0]===6||a[0]===2)){e=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){e.label=a[1];break}if(a[0]===6&&e.label<i[1]){e.label=i[1],i=a;break}if(i&&e.label<i[2]){e.label=i[2],e.ops.push(a);break}i[2]&&e.ops.pop(),e.trys.pop();continue}a=A.call(t,e)}catch(n){a=[6,n],I=0}finally{g=i=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},Fq=function(){function t(A){this.connection=A}return t.prototype.startConnection=function(A){var e=this._startPeerConnection();if(this.connection.peerConnection=e,this.connection.type===mo.Media&&A._stream&&this._addTracksToConnection(A._stream,e),A.originator){if(this.connection.type===mo.Data){var g=this.connection,I={ordered:!!A.reliable},i=e.createDataChannel(g.label,I);g.initialize(i)}this._makeOffer()}else this.handleSDP("OFFER",A.sdp)},t.prototype._startPeerConnection=function(){te.default.log("Creating RTCPeerConnection.");var A=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(A),A},t.prototype._setupListeners=function(A){var e=this,g=this.connection.peer,I=this.connection.connectionId,i=this.connection.type,o=this.connection.provider;te.default.log("Listening for ICE candidates."),A.onicecandidate=function(C){!C.candidate||!C.candidate.candidate||(te.default.log("Received ICE candidates for ".concat(g,":"),C.candidate),o.socket.send({type:$g.Candidate,payload:{candidate:C.candidate,type:i,connectionId:I},dst:g}))},A.oniceconnectionstatechange=function(){switch(A.iceConnectionState){case"failed":te.default.log("iceConnectionState is failed, closing connections to "+g),e.connection.emit("error",new Error("Negotiation of connection to "+g+" failed.")),e.connection.close();break;case"closed":te.default.log("iceConnectionState is closed, closing connections to "+g),e.connection.emit("error",new Error("Connection to "+g+" closed.")),e.connection.close();break;case"disconnected":te.default.log("iceConnectionState changed to disconnected on the connection with "+g);break;case"completed":A.onicecandidate=nt.noop;break}e.connection.emit("iceStateChanged",A.iceConnectionState)},te.default.log("Listening for data channel"),A.ondatachannel=function(C){te.default.log("Received data channel");var s=C.channel,a=o.getConnection(g,I);a.initialize(s)},te.default.log("Listening for remote stream"),A.ontrack=function(C){te.default.log("Received remote stream");var s=C.streams[0],a=o.getConnection(g,I);if(a.type===mo.Media){var n=a;e._addStreamToMediaConnection(s,n)}}},t.prototype.cleanup=function(){te.default.log("Cleaning up PeerConnection to "+this.connection.peer);var A=this.connection.peerConnection;if(A){this.connection.peerConnection=null,A.onicecandidate=A.oniceconnectionstatechange=A.ondatachannel=A.ontrack=function(){};var e=A.signalingState!=="closed",g=!1;if(this.connection.type===mo.Data){var I=this.connection,i=I.dataChannel;i&&(g=!!i.readyState&&i.readyState!=="closed")}(e||g)&&A.close()}},t.prototype._makeOffer=function(){return ku(this,void 0,Promise,function(){var A,e,g,I,i,o,C;return Gu(this,function(s){switch(s.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,s.label=1;case 1:return s.trys.push([1,7,,8]),[4,A.createOffer(this.connection.options.constraints)];case 2:g=s.sent(),te.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(g.sdp=this.connection.options.sdpTransform(g.sdp)||g.sdp),s.label=3;case 3:return s.trys.push([3,5,,6]),[4,A.setLocalDescription(g)];case 4:return s.sent(),te.default.log("Set localDescription:",g,"for:".concat(this.connection.peer)),I={sdp:g,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:nt.browser},this.connection.type===mo.Data&&(i=this.connection,I=fu(fu({},I),{label:i.label,reliable:i.reliable,serialization:i.serialization})),e.socket.send({type:$g.Offer,payload:I,dst:this.connection.peer}),[3,6];case 5:return o=s.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(e.emitError(gg.WebRTC,o),te.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return C=s.sent(),e.emitError(gg.WebRTC,C),te.default.log("Failed to createOffer, ",C),[3,8];case 8:return[2]}})})},t.prototype._makeAnswer=function(){return ku(this,void 0,Promise,function(){var A,e,g,I,i;return Gu(this,function(o){switch(o.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,A.createAnswer()];case 2:g=o.sent(),te.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(g.sdp=this.connection.options.sdpTransform(g.sdp)||g.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,A.setLocalDescription(g)];case 4:return o.sent(),te.default.log("Set localDescription:",g,"for:".concat(this.connection.peer)),e.socket.send({type:$g.Answer,payload:{sdp:g,type:this.connection.type,connectionId:this.connection.connectionId,browser:nt.browser},dst:this.connection.peer}),[3,6];case 5:return I=o.sent(),e.emitError(gg.WebRTC,I),te.default.log("Failed to setLocalDescription, ",I),[3,6];case 6:return[3,8];case 7:return i=o.sent(),e.emitError(gg.WebRTC,i),te.default.log("Failed to create answer, ",i),[3,8];case 8:return[2]}})})},t.prototype.handleSDP=function(A,e){return ku(this,void 0,Promise,function(){var g,I,i,o;return Gu(this,function(C){switch(C.label){case 0:e=new RTCSessionDescription(e),g=this.connection.peerConnection,I=this.connection.provider,te.default.log("Setting remote description",e),i=this,C.label=1;case 1:return C.trys.push([1,5,,6]),[4,g.setRemoteDescription(e)];case 2:return C.sent(),te.default.log("Set remoteDescription:".concat(A," for:").concat(this.connection.peer)),A!=="OFFER"?[3,4]:[4,i._makeAnswer()];case 3:C.sent(),C.label=4;case 4:return[3,6];case 5:return o=C.sent(),I.emitError(gg.WebRTC,o),te.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},t.prototype.handleCandidate=function(A){return ku(this,void 0,Promise,function(){var e,g,I,i,o,C;return Gu(this,function(s){switch(s.label){case 0:te.default.log("handleCandidate:",A),e=A.candidate,g=A.sdpMLineIndex,I=A.sdpMid,i=this.connection.peerConnection,o=this.connection.provider,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,i.addIceCandidate(new RTCIceCandidate({sdpMid:I,sdpMLineIndex:g,candidate:e}))];case 2:return s.sent(),te.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return C=s.sent(),o.emitError(gg.WebRTC,C),te.default.log("Failed to handleCandidate, ",C),[3,4];case 4:return[2]}})})},t.prototype._addTracksToConnection=function(A,e){if(te.default.log("add tracks from stream ".concat(A.id," to peer connection")),!e.addTrack)return te.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");A.getTracks().forEach(function(g){e.addTrack(g,A)})},t.prototype._addStreamToMediaConnection=function(A,e){te.default.log("add stream ".concat(A.id," to media connection ").concat(e.connectionId)),e.addStream(A)},t}(),rk={};tC(rk,"BaseConnection",()=>Nq,t=>Nq=t);var $W=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),Nq=function(t){$W(A,t);function A(e,g,I){var i=t.call(this)||this;return i.peer=e,i.provider=g,i.options=I,i._open=!1,i.metadata=I.metadata,i}return Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),A}(Jh.EventEmitter),AV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),mu=function(){return mu=Object.assign||function(t){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(t[I]=A[I])}return t},mu.apply(this,arguments)},eV=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},Kq=function(t){AV(A,t);function A(e,g,I){var i=t.call(this,e,g,I)||this;return i._localStream=i.options._stream,i.connectionId=i.options.connectionId||A.ID_PREFIX+nt.randomToken(),i._negotiator=new nk.Negotiator(i),i._localStream&&i._negotiator.startConnection({_stream:i._localStream,originator:!0}),i}return Object.defineProperty(A.prototype,"type",{get:function(){return mo.Media},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),A.prototype.addStream=function(e){te.default.log("Receiving stream",e),this._remoteStream=e,t.prototype.emit.call(this,"stream",e)},A.prototype.handleMessage=function(e){var g=e.type,I=e.payload;switch(e.type){case $g.Answer:this._negotiator.handleSDP(g,I.sdp),this._open=!0;break;case $g.Candidate:this._negotiator.handleCandidate(I.candidate);break;default:te.default.warn("Unrecognized message type:".concat(g," from peer:").concat(this.peer));break}},A.prototype.answer=function(e,g){var I,i;if(g===void 0&&(g={}),this._localStream){te.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,g&&g.sdpTransform&&(this.options.sdpTransform=g.sdpTransform),this._negotiator.startConnection(mu(mu({},this.options._payload),{_stream:e}));var o=this.provider._getMessages(this.connectionId);try{for(var C=eV(o),s=C.next();!s.done;s=C.next()){var a=s.value;this.handleMessage(a)}}catch(n){I={error:n}}finally{try{s&&!s.done&&(i=C.return)&&i.call(C)}finally{if(I)throw I.error}}this._open=!0},A.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,t.prototype.emit.call(this,"close"))},A.ID_PREFIX="mc_",A}(rk.BaseConnection),Bk={};tC(Bk,"DataConnection",()=>bq,t=>bq=t);var Jq={};tC(Jq,"EncodingQueue",()=>qq,t=>qq=t);var tV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),qq=function(t){tV(A,t);function A(){var e=t.call(this)||this;return e.fileReader=new FileReader,e._queue=[],e._processing=!1,e.fileReader.onload=function(g){e._processing=!1,g.target&&e.emit("done",g.target.result),e.doNextTask()},e.fileReader.onerror=function(g){te.default.error("EncodingQueue error:",g),e._processing=!1,e.destroy(),e.emit("error",g)},e}return Object.defineProperty(A.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),A.prototype.enque=function(e){this.queue.push(e),!this.processing&&this.doNextTask()},A.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},A.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},A}(Jh.EventEmitter),gV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),IV=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},bq=function(t){gV(A,t);function A(e,g,I){var i=t.call(this,e,g,I)||this;return i.stringify=JSON.stringify,i.parse=JSON.parse,i._buffer=[],i._bufferSize=0,i._buffering=!1,i._chunkedData={},i._encodingQueue=new Jq.EncodingQueue,i.connectionId=i.options.connectionId||A.ID_PREFIX+nt.randomToken(),i.label=i.options.label||i.connectionId,i.serialization=i.options.serialization||ns.Binary,i.reliable=!!i.options.reliable,i._encodingQueue.on("done",function(o){i._bufferedSend(o)}),i._encodingQueue.on("error",function(){te.default.error("DC#".concat(i.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),i.close()}),i._negotiator=new nk.Negotiator(i),i._negotiator.startConnection(i.options._payload||{originator:!0}),i}return Object.defineProperty(A.prototype,"type",{get:function(){return mo.Data},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),A.prototype.initialize=function(e){this._dc=e,this._configureDataChannel()},A.prototype._configureDataChannel=function(){var e=this;(!nt.supports.binaryBlob||nt.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){te.default.log("DC#".concat(e.connectionId," dc connection success")),e._open=!0,e.emit("open")},this.dataChannel.onmessage=function(g){te.default.log("DC#".concat(e.connectionId," dc onmessage:"),g.data),e._handleDataMessage(g)},this.dataChannel.onclose=function(){te.default.log("DC#".concat(e.connectionId," dc closed for:"),e.peer),e.close()}},A.prototype._handleDataMessage=function(e){var g=this,I=e.data,i=I.constructor,o=this.serialization===ns.Binary||this.serialization===ns.BinaryUTF8,C=I;if(o){if(i===Blob){nt.blobToArrayBuffer(I,function(a){var n=nt.unpack(a);g.emit("data",n)});return}else if(i===ArrayBuffer)C=nt.unpack(I);else if(i===String){var s=nt.binaryStringToArrayBuffer(I);C=nt.unpack(s)}}else this.serialization===ns.JSON&&(C=this.parse(I));if(C.__peerData){this._handleChunk(C);return}t.prototype.emit.call(this,"data",C)},A.prototype._handleChunk=function(e){var g=e.__peerData,I=this._chunkedData[g]||{data:[],count:0,total:e.total};if(I.data[e.n]=e.data,I.count++,this._chunkedData[g]=I,I.total===I.count){delete this._chunkedData[g];var i=new Blob(I.data);this._handleDataMessage({data:i})}},A.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,t.prototype.emit.call(this,"close"))},A.prototype.send=function(e,g){if(!this.open){t.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===ns.JSON)this._bufferedSend(this.stringify(e));else if(this.serialization===ns.Binary||this.serialization===ns.BinaryUTF8){var I=nt.pack(e);if(!g&&I.size>nt.chunkedMTU){this._sendChunks(I);return}nt.supports.binaryBlob?this._bufferedSend(I):this._encodingQueue.enque(I)}else this._bufferedSend(e)},A.prototype._bufferedSend=function(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)},A.prototype._trySend=function(e){var g=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>A.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){g._buffering=!1,g._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(I){return te.default.error("DC#:".concat(this.connectionId," Error when sending:"),I),this._buffering=!0,this.close(),!1}return!0},A.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},A.prototype._sendChunks=function(e){var g,I,i=nt.chunk(e);te.default.log("DC#".concat(this.connectionId," Try to send ").concat(i.length," chunks..."));try{for(var o=IV(i),C=o.next();!C.done;C=o.next()){var s=C.value;this.send(s,!0)}}catch(a){g={error:a}}finally{try{C&&!C.done&&(I=o.return)&&I.call(o)}finally{if(g)throw g.error}}},A.prototype.handleMessage=function(e){var g=e.payload;switch(e.type){case $g.Answer:this._negotiator.handleSDP(e.type,g.sdp);break;case $g.Candidate:this._negotiator.handleCandidate(g.candidate);break;default:te.default.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}},A.ID_PREFIX="dc_",A.MAX_BUFFERED_AMOUNT=8388608,A}(rk.BaseConnection),vq={};tC(vq,"API",()=>Yq,t=>Yq=t);var Lq=function(t,A,e,g){function I(i){return i instanceof e?i:new e(function(o){o(i)})}return new(e||(e=Promise))(function(i,o){function C(n){try{a(g.next(n))}catch(B){o(B)}}function s(n){try{a(g.throw(n))}catch(B){o(B)}}function a(n){n.done?i(n.value):I(n.value).then(C,s)}a((g=g.apply(t,A||[])).next())})},xq=function(t,A){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},g,I,i,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(a){return function(n){return s([a,n])}}function s(a){if(g)throw new TypeError("Generator is already executing.");for(;e;)try{if(g=1,I&&(i=a[0]&2?I.return:a[0]?I.throw||((i=I.return)&&i.call(I),0):I.next)&&!(i=i.call(I,a[1])).done)return i;switch(I=0,i&&(a=[a[0]&2,i.value]),a[0]){case 0:case 1:i=a;break;case 4:return e.label++,{value:a[1],done:!1};case 5:e.label++,I=a[1],a=[0];continue;case 7:a=e.ops.pop(),e.trys.pop();continue;default:if(i=e.trys,!(i=i.length>0&&i[i.length-1])&&(a[0]===6||a[0]===2)){e=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){e.label=a[1];break}if(a[0]===6&&e.label<i[1]){e.label=i[1],i=a;break}if(i&&e.label<i[2]){e.label=i[2],e.ops.push(a);break}i[2]&&e.ops.pop(),e.trys.pop();continue}a=A.call(t,e)}catch(n){a=[6,n],I=0}finally{g=i=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},Yq=function(){function t(A){this._options=A}return t.prototype._buildRequest=function(A){var e=this._options.secure?"https":"http",g=this._options,I=g.host,i=g.port,o=g.path,C=g.key,s=new URL("".concat(e,"://").concat(I,":").concat(i).concat(o).concat(C,"/").concat(A));return s.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),s.searchParams.set("version",sk.version),fetch(s.href,{referrerPolicy:this._options.referrerPolicy})},t.prototype.retrieveId=function(){return Lq(this,void 0,Promise,function(){var A,e,g;return xq(this,function(I){switch(I.label){case 0:return I.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(A=I.sent(),A.status!==200)throw new Error("Error. Status:".concat(A.status));return[2,A.text()];case 2:throw e=I.sent(),te.default.error("Error retrieving ID",e),g="",this._options.path==="/"&&this._options.host!==nt.CLOUD_HOST&&(g=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+g);case 3:return[2]}})})},t.prototype.listAllPeers=function(){return Lq(this,void 0,Promise,function(){var A,e,g;return xq(this,function(I){switch(I.label){case 0:return I.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(A=I.sent(),A.status!==200)throw A.status===401?(e="",this._options.host===nt.CLOUD_HOST?e="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":e="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+e)):new Error("Error. Status:".concat(A.status));return[2,A.json()];case 2:throw g=I.sent(),te.default.error("Error retrieving list peers",g),new Error("Could not get list peers from the server."+g);case 3:return[2]}})})},t}(),iV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),bh=function(){return bh=Object.assign||function(t){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(t[I]=A[I])}return t},bh.apply(this,arguments)},vh=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},oV=function(t,A){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var g=e.call(t),I,i=[],o;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)i.push(I.value)}catch(C){o={error:C}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(o)throw o.error}}return i},Hq=function(t){iV(A,t);function A(e,g){var I=t.call(this)||this;I._id=null,I._lastServerId=null,I._destroyed=!1,I._disconnected=!1,I._open=!1,I._connections=new Map,I._lostMessages=new Map;var i;return e&&e.constructor==Object?g=e:e&&(i=e.toString()),g=bh({debug:0,host:nt.CLOUD_HOST,port:nt.CLOUD_PORT,path:"/",key:A.DEFAULT_KEY,token:nt.randomToken(),config:nt.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},g),I._options=g,I._options.host==="/"&&(I._options.host=window.location.hostname),I._options.path&&(I._options.path[0]!=="/"&&(I._options.path="/"+I._options.path),I._options.path[I._options.path.length-1]!=="/"&&(I._options.path+="/")),I._options.secure===void 0&&I._options.host!==nt.CLOUD_HOST?I._options.secure=nt.isSecure():I._options.host==nt.CLOUD_HOST&&(I._options.secure=!0),I._options.logFunction&&te.default.setLogFunction(I._options.logFunction),te.default.logLevel=I._options.debug||0,I._api=new vq.API(g),I._socket=I._createServerConnection(),!nt.supports.audioVideo&&!nt.supports.data?(I._delayedAbort(gg.BrowserIncompatible,"The current browser does not support WebRTC"),I):i&&!nt.validateId(i)?(I._delayedAbort(gg.InvalidID,'ID "'.concat(i,'" is invalid')),I):(i?I._initialize(i):I._api.retrieveId().then(function(o){return I._initialize(o)}).catch(function(o){return I._abort(gg.ServerError,o)}),I)}return Object.defineProperty(A.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"connections",{get:function(){var e,g,I=Object.create(null);try{for(var i=vh(this._connections),o=i.next();!o.done;o=i.next()){var C=oV(o.value,2),s=C[0],a=C[1];I[s]=a}}catch(n){e={error:n}}finally{try{o&&!o.done&&(g=i.return)&&g.call(i)}finally{if(e)throw e.error}}return I},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),A.prototype._createServerConnection=function(){var e=this,g=new Rq.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return g.on(rs.Message,function(I){e._handleMessage(I)}),g.on(rs.Error,function(I){e._abort(gg.SocketError,I)}),g.on(rs.Disconnected,function(){e.disconnected||(e.emitError(gg.Network,"Lost connection to server."),e.disconnect())}),g.on(rs.Close,function(){e.disconnected||e._abort(gg.SocketClosed,"Underlying socket is already closed.")}),g},A.prototype._initialize=function(e){this._id=e,this.socket.start(e,this._options.token)},A.prototype._handleMessage=function(e){var g,I,i=e.type,o=e.payload,C=e.src;switch(i){case $g.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case $g.Error:this._abort(gg.ServerError,o.msg);break;case $g.IdTaken:this._abort(gg.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case $g.InvalidKey:this._abort(gg.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case $g.Leave:te.default.log("Received leave message from ".concat(C)),this._cleanupPeer(C),this._connections.delete(C);break;case $g.Expire:this.emitError(gg.PeerUnavailable,"Could not connect to peer ".concat(C));break;case $g.Offer:var h=o.connectionId,c=this.getConnection(C,h);if(c&&(c.close(),te.default.warn("Offer received for existing Connection ID:".concat(h))),o.type===mo.Media){var s=new ak.MediaConnection(C,this,{connectionId:h,_payload:o,metadata:o.metadata});c=s,this._addConnection(C,c),this.emit("call",s)}else if(o.type===mo.Data){var a=new Bk.DataConnection(C,this,{connectionId:h,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});c=a,this._addConnection(C,c),this.emit("connection",a)}else{te.default.warn("Received malformed connection type:".concat(o.type));return}var n=this._getMessages(h);try{for(var B=vh(n),Q=B.next();!Q.done;Q=B.next()){var E=Q.value;c.handleMessage(E)}}catch(l){g={error:l}}finally{try{Q&&!Q.done&&(I=B.return)&&I.call(B)}finally{if(g)throw g.error}}break;default:if(!o){te.default.warn("You received a malformed message from ".concat(C," of type ").concat(i));return}var h=o.connectionId,c=this.getConnection(C,h);c&&c.peerConnection?c.handleMessage(e):h?this._storeMessage(h,e):te.default.warn("You received an unrecognized message:",e);break}},A.prototype._storeMessage=function(e,g){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(g)},A.prototype._getMessages=function(e){var g=this._lostMessages.get(e);return g?(this._lostMessages.delete(e),g):[]},A.prototype.connect=function(e,g){if(g===void 0&&(g={}),this.disconnected){te.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(gg.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var I=new Bk.DataConnection(e,this,g);return this._addConnection(e,I),I},A.prototype.call=function(e,g,I){if(I===void 0&&(I={}),this.disconnected){te.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(gg.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!g){te.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var i=new ak.MediaConnection(e,this,bh(bh({},I),{_stream:g}));return this._addConnection(e,i),i},A.prototype._addConnection=function(e,g){te.default.log("add connection ".concat(g.type,":").concat(g.connectionId," to peerId:").concat(e)),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(g)},A.prototype._removeConnection=function(e){var g=this._connections.get(e.peer);if(g){var I=g.indexOf(e);I!==-1&&g.splice(I,1)}this._lostMessages.delete(e.connectionId)},A.prototype.getConnection=function(e,g){var I,i,o=this._connections.get(e);if(!o)return null;try{for(var C=vh(o),s=C.next();!s.done;s=C.next()){var a=s.value;if(a.connectionId===g)return a}}catch(n){I={error:n}}finally{try{s&&!s.done&&(i=C.return)&&i.call(C)}finally{if(I)throw I.error}}return null},A.prototype._delayedAbort=function(e,g){var I=this;setTimeout(function(){I._abort(e,g)},0)},A.prototype._abort=function(e,g){te.default.error("Aborting!"),this.emitError(e,g),this._lastServerId?this.disconnect():this.destroy()},A.prototype.emitError=function(e,g){te.default.error("Error:",g);var I;typeof g=="string"?I=new Error(g):I=g,I.type=e,this.emit("error",I)},A.prototype.destroy=function(){this.destroyed||(te.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},A.prototype._cleanup=function(){var e,g;try{for(var I=vh(this._connections.keys()),i=I.next();!i.done;i=I.next()){var o=i.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(C){e={error:C}}finally{try{i&&!i.done&&(g=I.return)&&g.call(I)}finally{if(e)throw e.error}}this.socket.removeAllListeners()},A.prototype._cleanupPeer=function(e){var g,I,i=this._connections.get(e);if(i)try{for(var o=vh(i),C=o.next();!C.done;C=o.next()){var s=C.value;s.close()}}catch(a){g={error:a}}finally{try{C&&!C.done&&(I=o.return)&&I.call(o)}finally{if(g)throw g.error}}},A.prototype.disconnect=function(){if(!this.disconnected){var e=this.id;te.default.log("Disconnect peer with ID:".concat(e)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}},A.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)te.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)te.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},A.prototype.listAllPeers=function(e){var g=this;e===void 0&&(e=function(I){}),this._api.listAllPeers().then(function(I){return e(I)}).catch(function(I){return g._abort(gg.ServerError,I)})},A.DEFAULT_KEY="peerjs",A}(Jh.EventEmitter),Mu=Gq.Peer;class CV{constructor(){r(this,"_host"),r(this,"_client"),r(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const A="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(A)}trySetupHost(A){let e=new Mu(A);e.on("error",g=>{console.error(g),this._host=void 0,this.trySetupClient(A)}),e.on("open",g=>{this._host=new aV(e)})}trySetupClient(A){this._client=new Mu,this._client.on("error",e=>{console.error("Client error",e)}),this._client.on("open",e=>{console.log("client connected",e),this._clientData=this._client.connect(A,{metadata:{id:e}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",g=>{console.log("<<",g)})})}}class sV{constructor(A){r(this,"_peer"),this._peer=A}}class aV extends sV{constructor(A){var e;super(A),r(this,"_connections",[]),console.log("I AM THE HOST"),(e=this._peer)==null||e.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(A){console.log("host connection",A),A.on("open",()=>{this._connections.push(A),this.broadcastConnection(A)})}broadcastConnection(A){const e=this._connections.map(g=>{var I;return(I=g.metadata)==null?void 0:I.id}).filter(g=>g!==void 0);this.broadcast({type:"connection-list",connections:e})}broadcast(A){if(A!=null){console.log(">>",A);for(const e in this._peer.connections){const g=this._peer.connections[e];if(g)if(Array.isArray(g))for(const I of g)I&&I.send(A);else console.warn(g)}}}}var XI=(t=>(t[t.OnConnection=0]="OnConnection",t[t.OnRoomJoin=1]="OnRoomJoin",t[t.Queued=2]="Queued",t[t.Immediate=3]="Immediate",t))(XI||{});const Tq="https://urls.needle.tools/default-networking-backend/index";let Ra="wss://needle-tiny-starter.glitch.me/socket";const NI=!!aA("debugnet"),Lh=!!(NI||aA("debugowner"));var _q=(t=>(t.ConnectionInfo="connection-start-info",t))(_q||{}),Pt=(t=>(t.Join="join-room",t.Leave="leave-room",t.JoinedRoom="joined-room",t.LeftRoom="left-room",t.UserJoinedRoom="user-joined-room",t.UserLeftRoom="user-left-room",t))(Pt||{});class nV{constructor(){r(this,"room"),r(this,"viewId"),r(this,"allowEditing"),r(this,"inRoom")}}class rV{constructor(){r(this,"room")}}class BV{constructor(){r(this,"userId")}}var Oq=(t=>(t.RequestHasOwner="request-has-owner",t.ResponseHasOwner="response-has-owner",t.RequestIsOwner="request-is-owner",t.ResponseIsOwner="response-is-owner",t.RequestOwnership="request-ownership",t.GainedOwnership="gained-ownership",t.RemoveOwnership="remove-ownership",t.LostOwnership="lost-ownership",t.GainedOwnershipBroadcast="gained-ownership-broadcast",t.LostOwnershipBroadcast="lost-ownership-broadcast",t))(Oq||{});class Ru{constructor(A,e){r(this,"guid"),r(this,"connection"),r(this,"_hasOwnership",!1),r(this,"_isOwned"),r(this,"_gainSubscription"),r(this,"_lostSubscription"),r(this,"_hasOwnerResponse"),r(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=A,this.guid=e,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),A.beginListen("lost-ownership",this._lostSubscription),A.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),A.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(A){A.guid===this.guid&&(this._isOwned=A.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(A){A.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=A.value,A.value||(Lh&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((A,e)=>{this.requestOwnership();let g=0;const I=()=>{if(g++>10)return e("Timeout");setTimeout(()=>{this.hasOwnership?A(this):I()},100)};I()})}requestOwnership(){return Lh&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(A){A.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===A.owner?(Lh&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(A){A===this.guid&&(Lh&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class Pq{constructor(A){r(this,"context"),r(this,"_peer",null),r(this,"_usersInRoomCopy",[]),r(this,"_defaultMessagesBuffer",[]),r(this,"_defaultMessagesBufferArray",[]),r(this,"netWebSocketUrlProvider"),r(this,"_listeners",{}),r(this,"_listenersBinary",{}),r(this,"connected",!1),r(this,"channelId"),r(this,"_connectionId",null),r(this,"_ws"),r(this,"_waitingForSocket",{}),r(this,"_isInRoom",!1),r(this,"_currentRoomName",null),r(this,"_currentRoomViewId",null),r(this,"_currentRoomAllowEditing",!0),r(this,"_currentInRoom",[]),r(this,"_state",{}),r(this,"_currentDelay",-1),r(this,"_connectingToWebsocketPromise",null),this.context=A}get peer(){return this._peer||(this._peer=new CV),this._peer}tryGetState(A){return A==="invalid"?null:this._state[A]}get connectionId(){return this._connectionId}get isDebugEnabled(){return NI}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(A){return this._currentInRoom.indexOf(A)!==-1}usersInRoom(A=null){A||(A=this._usersInRoomCopy),A.length=0;for(const e of this._currentInRoom)A.push(e);return A}joinRoom(A,e=!1){this.connect(),NI&&console.log("join: "+A),this.send("join-room",{room:A,viewOnly:e},XI.OnConnection)}leaveRoom(A=null){if(A||(A=this.currentRoomName),!A){console.error("Can not leave unknown room");return}this.send("leave-room",{room:A})}send(A,e=null,g=XI.Queued){if(e===null&&(e={}),g===XI.Queued){this._defaultMessagesBuffer.push({key:A,value:e});return}return this.sendWithWebsocket(A,e,g)}sendDeleteRemoteState(A){this.send("delete-state",{guid:A,dontSave:!0}),delete this._state[A]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(A){var e;NI&&console.log("<< bin",A.length),(e=this._ws)==null||e.send(A)}sendBufferedMessagesNow(){var A;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const I in this._defaultMessagesBuffer){const i=this._defaultMessagesBuffer[I];if(e<=1){this.sendWithWebsocket(i.key,i.value,XI.Immediate);break}const o=this.toMessage(i.key,i.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&NI&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const g=JSON.stringify(this._defaultMessagesBufferArray);(A=this._ws)==null||A.send(g)}beginListen(A,e){return this._listeners[A]||(this._listeners[A]=[]),this._listeners[A].push(e),e}stopListening(A,e){return this.stopListen(A,e)}stopListen(A,e){if(!e||!this._listeners[A])return;const g=this._listeners[A].indexOf(e);g>=0&&this._listeners[A].splice(g,1)}beginListenBinary(A,e){return this._listenersBinary[A]||(this._listenersBinary[A]=[]),this._listenersBinary[A].push(e),e}stopListenBinary(A,e){if(!this._listenersBinary[A])return;const g=this._listenersBinary[A].indexOf(e);g>=0&&this._listenersBinary[A].splice(g,1)}registerProvider(A){this.netWebSocketUrlProvider=A}async connect(){var A;if(this.connected)return Promise.resolve(!0);NI&&console.log("connecting");const e=(A=this.netWebSocketUrlProvider)==null?void 0:A.getWebsocketUrl();return e?Ra=e:qU()&&(Ra="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var A;(A=this._ws)==null||A.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(A,e)=>{let g=!1;const I=o=>{g||(g=!0,A(o))};if(Ra===void 0&&(console.log("Fetch default backend url: "+Tq),Ra=await(await fetch(Tq)).text()),Ra===void 0){I(!1);return}console.log(`\u22A1 Connecting to networking backend on
3334
3334
  `+Ra);const i=new SJ.WebsocketBuilder(Ra).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=i,this.connected=!0,console.log(`\u229E Connected to networking backend
3335
3335
  `+Ra),I(!0),this.onSendQueued(XI.OnConnection)}).onClose(o=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,I(!1)}).onError((o,C)=>{console.error("\u22A0 Websocket error",o,C),I(!1)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build()})}onMessage(A,e){const g=e.data;try{if(typeof g!="string"){g.size&&this.handleIncomingBinaryMessage(g);return}const I=JSON.parse(g);if(Array.isArray(I))for(const i of I)this.handleIncomingStringMessage(i);else this.handleIncomingStringMessage(I);return}catch{NI&&g==="pong"&&console.log("<<",g)}}async handleIncomingBinaryMessage(A){const e=await A.arrayBuffer();var g=new Uint8Array(e);const I=new hd(g),i=I.getBufferIdentifier(),o=this._listenersBinary[i],C=fW(I),s=kW(C);if(s&&typeof s=="string"&&(this._state[s]=C),!o)return;const a=C??I;for(const n of o)n(a)}handleIncomingStringMessage(A){var e,g;if(NI&&console.log("<<",A.key??A),A.key)switch(A.key){case"connection-start-info":if(A.data){const C=A.data;C&&(console.assert(C.id!==void 0&&C.id!==null&&C.id.length>0,"server did not send connection id",C.id),console.log("Your id is: "+C.id,this.context.alias??""),this._connectionId=C.id)}else console.warn("Expected connection id in "+A.key);break;case"joined-room":if(NI&&console.log(A),A){this._isInRoom=!0;const C=A;this._currentRoomName=C.room,this._currentRoomViewId=C.viewId,this._currentRoomAllowEditing=C.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...C.inRoom),NI&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(XI.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const C=A.data;this._currentInRoom.push(C.userId),NI&&console.log(C.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const C=A.data,s=this._currentInRoom.indexOf(C.userId);s>=0&&(console.log(C.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),C.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":NI&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=(e=A.data)==null?void 0:e.time;o&&(this._currentDelay=this.context.time.time-o),NI&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+((g=this._currentInRoom)==null?void 0:g.length));break}const I=this._listeners[A.key];if(I)for(const o of I)o(A.data);const i=A.data;i&&(this._state[i.guid]=i)}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,g=XI.OnRoomJoin){if(!this._ws){const i=this._waitingForSocket[g]||[];i.push(()=>this.sendWithWebsocket(A,e,g)),this._waitingForSocket[g]=i;return}const I=JSON.stringify(this.toMessage(A,e));NI&&console.log(">>",A),this._ws.send(I)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const g of e)g();e.length=0}}}function WB(t,A){try{A?t(A):t()}catch(e){return console.error(e),!1}return!0}(0,eval)(`
3336
- if(!globalThis[""null""])
3337
- globalThis[""null""] = "0.0.0";
3336
+ if(!globalThis["NEEDLE_ENGINE_VERSION"])
3337
+ globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";
3338
3338
  if(!globalThis[""undefined""])
3339
3339
  globalThis[""undefined""] = "unknown";
3340
- `);const jq="null",QV="undefined",Bs="needle_isActiveInHierarchy",rr="builtin_components",xh="needle_editor_guid",EV=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function hV(t){return typeof t=="string"&&EV.test(t)}const AI=[];for(let t=0;t<256;++t)AI.push((t+256).toString(16).slice(1));function cV(t,A=0){return(AI[t[A+0]]+AI[t[A+1]]+AI[t[A+2]]+AI[t[A+3]]+"-"+AI[t[A+4]]+AI[t[A+5]]+"-"+AI[t[A+6]]+AI[t[A+7]]+"-"+AI[t[A+8]]+AI[t[A+9]]+"-"+AI[t[A+10]]+AI[t[A+11]]+AI[t[A+12]]+AI[t[A+13]]+AI[t[A+14]]+AI[t[A+15]]).toLowerCase()}function lV(t){if(!hV(t))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(t.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(t.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(t.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(t.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(t.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function dV(t){t=unescape(encodeURIComponent(t));const A=[];for(let e=0;e<t.length;++e)A.push(t.charCodeAt(e));return A}const pV="6ba7b810-9dad-11d1-80b4-00c04fd430c8",uV="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function DV(t,A,e){function g(I,i,o,C){var s;if(typeof I=="string"&&(I=dV(I)),typeof i=="string"&&(i=lV(i)),((s=i)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+I.length);if(a.set(i),a.set(I,i.length),a=e(a),a[6]=a[6]&15|A,a[8]=a[8]&63|128,o){C=C||0;for(let n=0;n<16;++n)o[C+n]=a[n];return o}return cV(a)}try{g.name=t}catch{}return g.DNS=pV,g.URL=uV,g}function wV(t,A,e,g){switch(t){case 0:return A&e^~A&g;case 1:return A^e^g;case 2:return A&e^A&g^e&g;case 3:return A^e^g}}function Qk(t,A){return t<<A|t>>>32-A}function yV(t){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){const o=unescape(encodeURIComponent(t));t=[];for(let C=0;C<o.length;++C)t.push(o.charCodeAt(C))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);const g=t.length/4+2,I=Math.ceil(g/16),i=new Array(I);for(let o=0;o<I;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=t[o*64+s*4]<<24|t[o*64+s*4+1]<<16|t[o*64+s*4+2]<<8|t[o*64+s*4+3];i[o]=C}i[I-1][14]=(t.length-1)*8/Math.pow(2,32),i[I-1][14]=Math.floor(i[I-1][14]),i[I-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<I;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=i[o][E];for(let E=16;E<80;++E)C[E]=Qk(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],a=e[1],n=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const h=Math.floor(E/20),c=Qk(s,5)+wV(h,a,n,B)+Q+A[h]+C[E]>>>0;Q=B,B=n,n=Qk(a,30)>>>0,a=s,s=c}e[0]=e[0]+s>>>0,e[1]=e[1]+a>>>0,e[2]=e[2]+n>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const SV=DV("v5",80,yV),Wq=SV;_t.registerCallback(ci.ContextCreated,t=>{const A=t.context;Ab(A),$q(A)});const Uu=aA("debugcomponents"),Vq="eff8ba80-635d-11ec-90d6-0242ac120003";class VI{constructor(A){r(this,"_originalSeed"),r(this,"_seed"),typeof A=="string"&&(A=VI.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return Wq(A,Vq);const e=this._seed;return this._seed-=1,Wq(e.toString(),Vq)}initialize(A){typeof A=="string"?this._seed=VI.hash(A):this._seed=A}static createFromString(A){return new VI(this.hash(A))}static hash(A){let e=0;for(let g=0;g<A.length;g++)e=A.charCodeAt(g)+((e<<5)-e);return e}}var zq=(t=>(t.NewInstanceCreated="new-instance-created",t.InstanceDestroyed="instance-destroyed",t))(zq||{});class Zq{constructor(A){r(this,"guid"),this.guid=A}}function Fu(t,A,e=!0){if(!t)return;const g=t;if(Qs(t,e),!A){console.warn("Can not send destroy: No networking connection provided",t.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",t.guid);return}let I=t.guid;if(!I&&g.uuid&&(I=g.uuid),!I){console.warn("Can not send destroy: failed to find guid",t);return}const i=new Zq(I);A.send("instance-destroyed",i,XI.Queued)}function Xq(t,A){const e=new Zq(t);A.send("instance-destroyed",e,XI.Queued)}function $q(t){t.connection.beginListen("instance-destroyed",A=>{Uu&&console.log("[Remote] Destroyed",t.scene,A);const e=zh(A.guid,t.scene);e&&Qs(e)})}class fV{constructor(A,e,g){r(this,"filename"),r(this,"hash"),r(this,"size"),this.filename=A,this.hash=e,this.size=g}}class kV{constructor(A,e){r(this,"guid"),r(this,"originalGuid"),r(this,"seed"),r(this,"visible"),r(this,"hostData"),r(this,"dontSave"),r(this,"parent"),r(this,"position"),r(this,"rotation"),r(this,"scale"),this.originalGuid=A,this.guid=e}}function Ek(t,A,e,g){var I;const i=t;if(!i.guid)return console.warn("Can not instantiate: No guid",i),null;if(A.context||(A.context=we.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=A?{...A}:null,{instance:C,seed:s}=GV(i,A);if(C){const a=C;if(a.guid){Uu&&console.log("[Local] new instance","gameobject:",C?.guid);const n=new kV(i.guid,a.guid);n.seed=s,o&&(o.position&&(n.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(n.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(n.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),n.position||(n.position={x:a.position.x,y:a.position.y,z:a.position.z}),n.rotation||(n.rotation={x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w}),n.scale||(n.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z}),n.visible=i.visible,o!=null&&o.parent&&(typeof o.parent=="string"?n.parent=o.parent:n.parent=o.parent.guid),n.hostData=e,g===!1&&(n.dontSave=!0),(I=A?.context)==null||I.connection.send("new-instance-created",n)}else console.warn("Missing guid, can not send new instance event",a)}return C}function Nu(){return Math.random()*9999999}function Ab(t){t.connection.beginListen("new-instance-created",async A=>{const e=await mV(A.originalGuid,t.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const g=new gC;A.position&&(g.position=new f(A.position.x,A.position.y,A.position.z)),A.rotation&&(g.rotation=new GA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(g.scale=new f(A.scale.x,A.scale.y,A.scale.z)),g.parent=A.parent,A.seed&&(g.idProvider=new VI(A.seed)),g.visible=A.visible,g.context=t,Uu&&t.alias&&console.log("[Remote] instantiate in: "+t.alias);const I=Zh(e,g);I&&(A.parent==="scene"&&t.scene.add(I),Uu&&console.log("[Remote] new instance","gameobject:",I?.guid,e))})}function GV(t,A){const e=Nu(),g=A??new gC;g.idProvider=new VI(e);const I=Zh(t,g);return{seed:e,instance:I}}const eb={};function tb(t,A){eb[t]=A}async function mV(t,A){const e=eb[t];if(e!=null){const g=await e(t);if(g)return g}return gb(t,A)}function gb(t,A){if(A===null||!t)return null;if(A.guid===t)return A;if(A.children)for(const e of A.children){const g=gb(t,e);if(g)return g}return null}const Ib=new Map;function MV(t,A){if(!t)return;if(!A){console.warn("No prototype found",t,t.prototype,t.constructor);return}let e=Ib.get(A);e&&e.apply(t)}function RV(t){const A=UV(t.prototype);Ib.set(t,A)}function UV(t){return new FV(t)}class FV{constructor(A){r(this,"$symbol"),r(this,"extensions"),r(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=Object.getOwnPropertyDescriptor(A,g);I&&this.descriptors.push(I)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=this.descriptors[e];I&&Object.defineProperty(A,g,I)}}}}var Yh=(t=>(t.Added="component-added",t.Removing="removing-component",t))(Yh||{});const ib=aA("debugcomponentevents");class Hh{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let g=this.eventListeners.get(A);g||(g=[]),g.push(e),this.eventListeners.set(A,g),ib&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const g=this.eventListeners.get(A);if(!g)return;const I=g.indexOf(e);I<0||g.splice(I,1)}static dispatchComponentLifecycleEvent(A,e){const g=this.eventListeners.get(A);if(ib&&console.log("Dispatching event "+A,g),!!g)for(const I of g)I(e)}}r(Hh,"eventListeners",new Map);const hk=aA("debuggetcomponent");function NV(t){return t==null||t.isObject3D?t:t.object&&t.object.isObject3D?t.object:t}function ck(t,A){if(!t||!t.userData.components)return;const e=t.userData.components.indexOf(A);e<0||(Hh.dispatchComponentLifecycleEvent(Yh.Removing,A),A.gameObject=null,t.userData.components.splice(e,1))}function Ku(t,A){const e=VB(t,A);if(e)return e;const g=new A;return Br(t,g)}const ob=new VI("addComponentIdProvider");function Br(t,A,e=!0){t.userData||(t.userData={}),t.userData.components||(t.userData.components=[]),t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),qu(t),tD(A);try{e&&A.__internalAwake&&(Xh(t),A.__internalAwake()),Hh.dispatchComponentLifecycleEvent(Yh.Added,A)}catch(g){console.error(g)}return A}function lk(t,A){if(A.gameObject===t)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!t.userData.components)t.userData.components=[];else if(t.userData.components.includes(A))return A;return t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),tD(A),A}function Cb(t){if(t.gameObject&&t.gameObject.userData.components){const A=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(A,1)}t.__internalDisable&&t.__internalDisable(),t.onDestroy&&t.onDestroy(),Es(t,t.context??we.Current),t.__internalDestroy(),t.gameObject=null}let sb=!1;function ab(t,A,e){var g;if(t!=null){if(!t.isObject3D){console.error("Object is not object3D");return}if(!((g=t?.userData)!=null&&g.components))return null;if(typeof A=="string"&&(sb||(sb=!0,console.warn(`Accessing components by name is not supported.
3340
+ `);const jq=NEEDLE_ENGINE_VERSION,QV="undefined",Bs="needle_isActiveInHierarchy",rr="builtin_components",xh="needle_editor_guid",EV=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function hV(t){return typeof t=="string"&&EV.test(t)}const AI=[];for(let t=0;t<256;++t)AI.push((t+256).toString(16).slice(1));function cV(t,A=0){return(AI[t[A+0]]+AI[t[A+1]]+AI[t[A+2]]+AI[t[A+3]]+"-"+AI[t[A+4]]+AI[t[A+5]]+"-"+AI[t[A+6]]+AI[t[A+7]]+"-"+AI[t[A+8]]+AI[t[A+9]]+"-"+AI[t[A+10]]+AI[t[A+11]]+AI[t[A+12]]+AI[t[A+13]]+AI[t[A+14]]+AI[t[A+15]]).toLowerCase()}function lV(t){if(!hV(t))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(t.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(t.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(t.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(t.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(t.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function dV(t){t=unescape(encodeURIComponent(t));const A=[];for(let e=0;e<t.length;++e)A.push(t.charCodeAt(e));return A}const pV="6ba7b810-9dad-11d1-80b4-00c04fd430c8",uV="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function DV(t,A,e){function g(I,i,o,C){var s;if(typeof I=="string"&&(I=dV(I)),typeof i=="string"&&(i=lV(i)),((s=i)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+I.length);if(a.set(i),a.set(I,i.length),a=e(a),a[6]=a[6]&15|A,a[8]=a[8]&63|128,o){C=C||0;for(let n=0;n<16;++n)o[C+n]=a[n];return o}return cV(a)}try{g.name=t}catch{}return g.DNS=pV,g.URL=uV,g}function wV(t,A,e,g){switch(t){case 0:return A&e^~A&g;case 1:return A^e^g;case 2:return A&e^A&g^e&g;case 3:return A^e^g}}function Qk(t,A){return t<<A|t>>>32-A}function yV(t){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){const o=unescape(encodeURIComponent(t));t=[];for(let C=0;C<o.length;++C)t.push(o.charCodeAt(C))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);const g=t.length/4+2,I=Math.ceil(g/16),i=new Array(I);for(let o=0;o<I;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=t[o*64+s*4]<<24|t[o*64+s*4+1]<<16|t[o*64+s*4+2]<<8|t[o*64+s*4+3];i[o]=C}i[I-1][14]=(t.length-1)*8/Math.pow(2,32),i[I-1][14]=Math.floor(i[I-1][14]),i[I-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<I;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=i[o][E];for(let E=16;E<80;++E)C[E]=Qk(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],a=e[1],n=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const h=Math.floor(E/20),c=Qk(s,5)+wV(h,a,n,B)+Q+A[h]+C[E]>>>0;Q=B,B=n,n=Qk(a,30)>>>0,a=s,s=c}e[0]=e[0]+s>>>0,e[1]=e[1]+a>>>0,e[2]=e[2]+n>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const SV=DV("v5",80,yV),Wq=SV;_t.registerCallback(ci.ContextCreated,t=>{const A=t.context;Ab(A),$q(A)});const Uu=aA("debugcomponents"),Vq="eff8ba80-635d-11ec-90d6-0242ac120003";class VI{constructor(A){r(this,"_originalSeed"),r(this,"_seed"),typeof A=="string"&&(A=VI.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return Wq(A,Vq);const e=this._seed;return this._seed-=1,Wq(e.toString(),Vq)}initialize(A){typeof A=="string"?this._seed=VI.hash(A):this._seed=A}static createFromString(A){return new VI(this.hash(A))}static hash(A){let e=0;for(let g=0;g<A.length;g++)e=A.charCodeAt(g)+((e<<5)-e);return e}}var zq=(t=>(t.NewInstanceCreated="new-instance-created",t.InstanceDestroyed="instance-destroyed",t))(zq||{});class Zq{constructor(A){r(this,"guid"),this.guid=A}}function Fu(t,A,e=!0){if(!t)return;const g=t;if(Qs(t,e),!A){console.warn("Can not send destroy: No networking connection provided",t.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",t.guid);return}let I=t.guid;if(!I&&g.uuid&&(I=g.uuid),!I){console.warn("Can not send destroy: failed to find guid",t);return}const i=new Zq(I);A.send("instance-destroyed",i,XI.Queued)}function Xq(t,A){const e=new Zq(t);A.send("instance-destroyed",e,XI.Queued)}function $q(t){t.connection.beginListen("instance-destroyed",A=>{Uu&&console.log("[Remote] Destroyed",t.scene,A);const e=zh(A.guid,t.scene);e&&Qs(e)})}class fV{constructor(A,e,g){r(this,"filename"),r(this,"hash"),r(this,"size"),this.filename=A,this.hash=e,this.size=g}}class kV{constructor(A,e){r(this,"guid"),r(this,"originalGuid"),r(this,"seed"),r(this,"visible"),r(this,"hostData"),r(this,"dontSave"),r(this,"parent"),r(this,"position"),r(this,"rotation"),r(this,"scale"),this.originalGuid=A,this.guid=e}}function Ek(t,A,e,g){var I;const i=t;if(!i.guid)return console.warn("Can not instantiate: No guid",i),null;if(A.context||(A.context=we.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=A?{...A}:null,{instance:C,seed:s}=GV(i,A);if(C){const a=C;if(a.guid){Uu&&console.log("[Local] new instance","gameobject:",C?.guid);const n=new kV(i.guid,a.guid);n.seed=s,o&&(o.position&&(n.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(n.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(n.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),n.position||(n.position={x:a.position.x,y:a.position.y,z:a.position.z}),n.rotation||(n.rotation={x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w}),n.scale||(n.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z}),n.visible=i.visible,o!=null&&o.parent&&(typeof o.parent=="string"?n.parent=o.parent:n.parent=o.parent.guid),n.hostData=e,g===!1&&(n.dontSave=!0),(I=A?.context)==null||I.connection.send("new-instance-created",n)}else console.warn("Missing guid, can not send new instance event",a)}return C}function Nu(){return Math.random()*9999999}function Ab(t){t.connection.beginListen("new-instance-created",async A=>{const e=await mV(A.originalGuid,t.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const g=new gC;A.position&&(g.position=new f(A.position.x,A.position.y,A.position.z)),A.rotation&&(g.rotation=new GA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(g.scale=new f(A.scale.x,A.scale.y,A.scale.z)),g.parent=A.parent,A.seed&&(g.idProvider=new VI(A.seed)),g.visible=A.visible,g.context=t,Uu&&t.alias&&console.log("[Remote] instantiate in: "+t.alias);const I=Zh(e,g);I&&(A.parent==="scene"&&t.scene.add(I),Uu&&console.log("[Remote] new instance","gameobject:",I?.guid,e))})}function GV(t,A){const e=Nu(),g=A??new gC;g.idProvider=new VI(e);const I=Zh(t,g);return{seed:e,instance:I}}const eb={};function tb(t,A){eb[t]=A}async function mV(t,A){const e=eb[t];if(e!=null){const g=await e(t);if(g)return g}return gb(t,A)}function gb(t,A){if(A===null||!t)return null;if(A.guid===t)return A;if(A.children)for(const e of A.children){const g=gb(t,e);if(g)return g}return null}const Ib=new Map;function MV(t,A){if(!t)return;if(!A){console.warn("No prototype found",t,t.prototype,t.constructor);return}let e=Ib.get(A);e&&e.apply(t)}function RV(t){const A=UV(t.prototype);Ib.set(t,A)}function UV(t){return new FV(t)}class FV{constructor(A){r(this,"$symbol"),r(this,"extensions"),r(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=Object.getOwnPropertyDescriptor(A,g);I&&this.descriptors.push(I)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=this.descriptors[e];I&&Object.defineProperty(A,g,I)}}}}var Yh=(t=>(t.Added="component-added",t.Removing="removing-component",t))(Yh||{});const ib=aA("debugcomponentevents");class Hh{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let g=this.eventListeners.get(A);g||(g=[]),g.push(e),this.eventListeners.set(A,g),ib&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const g=this.eventListeners.get(A);if(!g)return;const I=g.indexOf(e);I<0||g.splice(I,1)}static dispatchComponentLifecycleEvent(A,e){const g=this.eventListeners.get(A);if(ib&&console.log("Dispatching event "+A,g),!!g)for(const I of g)I(e)}}r(Hh,"eventListeners",new Map);const hk=aA("debuggetcomponent");function NV(t){return t==null||t.isObject3D?t:t.object&&t.object.isObject3D?t.object:t}function ck(t,A){if(!t||!t.userData.components)return;const e=t.userData.components.indexOf(A);e<0||(Hh.dispatchComponentLifecycleEvent(Yh.Removing,A),A.gameObject=null,t.userData.components.splice(e,1))}function Ku(t,A){const e=VB(t,A);if(e)return e;const g=new A;return Br(t,g)}const ob=new VI("addComponentIdProvider");function Br(t,A,e=!0){t.userData||(t.userData={}),t.userData.components||(t.userData.components=[]),t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),qu(t),tD(A);try{e&&A.__internalAwake&&(Xh(t),A.__internalAwake()),Hh.dispatchComponentLifecycleEvent(Yh.Added,A)}catch(g){console.error(g)}return A}function lk(t,A){if(A.gameObject===t)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!t.userData.components)t.userData.components=[];else if(t.userData.components.includes(A))return A;return t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),tD(A),A}function Cb(t){if(t.gameObject&&t.gameObject.userData.components){const A=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(A,1)}t.__internalDisable&&t.__internalDisable(),t.onDestroy&&t.onDestroy(),Es(t,t.context??we.Current),t.__internalDestroy(),t.gameObject=null}let sb=!1;function ab(t,A,e){var g;if(t!=null){if(!t.isObject3D){console.error("Object is not object3D");return}if(!((g=t?.userData)!=null&&g.components))return null;if(typeof A=="string"&&(sb||(sb=!0,console.warn(`Accessing components by name is not supported.
3341
3341
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
3342
3342
 
3343
3343
  You can import other modules your main module to get access to types
@@ -3333,11 +3333,11 @@ a=extmap-allow-mixed`)!==-1){const I=g.sdp.split(`
3333
3333
  isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},i}()),JN={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},jV=function(){function i(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=JN,this.browser=dc.getBrowser(),this.browserVersion=dc.getVersion(),this.supports=function(){var A={browser:dc.isBrowserSupported(),webRTC:dc.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!A.webRTC)return A;var e;try{e=new RTCPeerConnection(JN),A.audioVideo=!0;var t=void 0;try{t=e.createDataChannel("_PEERJSTEST",{ordered:!0}),A.data=!0,A.reliable=!!t.ordered;try{t.binaryType="blob",A.binaryBlob=!dc.isIOS}catch{}}catch{}finally{t&&t.close()}}catch{}finally{e&&e.close()}return A}(),this.pack=yN.pack,this.unpack=yN.unpack,this._dataCount=1}return i.prototype.noop=function(){},i.prototype.validateId=function(A){return!A||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(A)},i.prototype.chunk=function(A){for(var e=[],t=A.size,g=Math.ceil(t/Qt.chunkedMTU),I=0,o=0;o<t;){var C=Math.min(t,o+Qt.chunkedMTU),s=A.slice(o,C),n={__peerData:this._dataCount,n:I,data:s,total:g};e.push(n),o=C,I++}return this._dataCount++,e},i.prototype.blobToArrayBuffer=function(A,e){var t=new FileReader;return t.onload=function(g){g.target&&e(g.target.result)},t.readAsArrayBuffer(A),t},i.prototype.binaryStringToArrayBuffer=function(A){for(var e=new Uint8Array(A.length),t=0;t<A.length;t++)e[t]=A.charCodeAt(t)&255;return e.buffer},i.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},i.prototype.isSecure=function(){return location.protocol==="https:"},i}(),Qt=new jV,vv={};zC(vv,"Peer",()=>PN,i=>PN=i);var Wl={},zV=Object.prototype.hasOwnProperty,$g="~";function Ph(){}Object.create&&(Ph.prototype=Object.create(null),new Ph().__proto__||($g=!1));function ZV(i,A,e){this.fn=i,this.context=A,this.once=e||!1}function xv(i,A,e,t,g){if(typeof e!="function")throw new TypeError("The listener must be a function");var I=new ZV(e,t||i,g),o=$g?$g+A:A;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],I]:i._events[o].push(I):(i._events[o]=I,i._eventsCount++),i}function FD(i,A){--i._eventsCount===0?i._events=new Ph:delete i._events[A]}function Rg(){this._events=new Ph,this._eventsCount=0}Rg.prototype.eventNames=function(){var A=[],e,t;if(this._eventsCount===0)return A;for(t in e=this._events)zV.call(e,t)&&A.push($g?t.slice(1):t);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(e)):A};Rg.prototype.listeners=function(A){var e=$g?$g+A:A,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var g=0,I=t.length,o=new Array(I);g<I;g++)o[g]=t[g].fn;return o};Rg.prototype.listenerCount=function(A){var e=$g?$g+A:A,t=this._events[e];return t?t.fn?1:t.length:0};Rg.prototype.emit=function(A,e,t,g,I,o){var C=$g?$g+A:A;if(!this._events[C])return!1;var s=this._events[C],n=arguments.length,a,B;if(s.fn){switch(s.once&&this.removeListener(A,s.fn,void 0,!0),n){case 1:return s.fn.call(s.context),!0;case 2:return s.fn.call(s.context,e),!0;case 3:return s.fn.call(s.context,e,t),!0;case 4:return s.fn.call(s.context,e,t,g),!0;case 5:return s.fn.call(s.context,e,t,g,I),!0;case 6:return s.fn.call(s.context,e,t,g,I,o),!0}for(B=1,a=new Array(n-1);B<n;B++)a[B-1]=arguments[B];s.fn.apply(s.context,a)}else{var Q=s.length,E;for(B=0;B<Q;B++)switch(s[B].once&&this.removeListener(A,s[B].fn,void 0,!0),n){case 1:s[B].fn.call(s[B].context);break;case 2:s[B].fn.call(s[B].context,e);break;case 3:s[B].fn.call(s[B].context,e,t);break;case 4:s[B].fn.call(s[B].context,e,t,g);break;default:if(!a)for(E=1,a=new Array(n-1);E<n;E++)a[E-1]=arguments[E];s[B].fn.apply(s[B].context,a)}}return!0};Rg.prototype.on=function(A,e,t){return xv(this,A,e,t,!1)};Rg.prototype.once=function(A,e,t){return xv(this,A,e,t,!0)};Rg.prototype.removeListener=function(A,e,t,g){var I=$g?$g+A:A;if(!this._events[I])return this;if(!e)return FD(this,I),this;var o=this._events[I];if(o.fn)o.fn===e&&(!g||o.once)&&(!t||o.context===t)&&FD(this,I);else{for(var C=0,s=[],n=o.length;C<n;C++)(o[C].fn!==e||g&&!o[C].once||t&&o[C].context!==t)&&s.push(o[C]);s.length?this._events[I]=s.length===1?s[0]:s:FD(this,I)}return this};Rg.prototype.removeAllListeners=function(A){var e;return A?(e=$g?$g+A:A,this._events[e]&&FD(this,e)):(this._events=new Ph,this._eventsCount=0),this};Rg.prototype.off=Rg.prototype.removeListener;Rg.prototype.addListener=Rg.prototype.on;Rg.prefixed=$g;Rg.EventEmitter=Rg;Wl=Rg;var ge={};zC(ge,"LogLevel",()=>rI,i=>rI=i);zC(ge,"default",()=>qN,i=>qN=i);var $a=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),g,I=[],o;try{for(;(A===void 0||A-- >0)&&!(g=t.next()).done;)I.push(g.value)}catch(C){o={error:C}}finally{try{g&&!g.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},Ar=function(i,A,e){if(e||arguments.length===2)for(var t=0,g=A.length,I;t<g;t++)(I||!(t in A))&&(I||(I=Array.prototype.slice.call(A,0,t)),I[t]=A[t]);return i.concat(I||Array.prototype.slice.call(A))},XV="PeerJS: ",rI;(function(i){i[i.Disabled=0]="Disabled",i[i.Errors=1]="Errors",i[i.Warnings=2]="Warnings",i[i.All=3]="All"})(rI||(rI={}));var $V=function(){function i(){this._logLevel=rI.Disabled}return Object.defineProperty(i.prototype,"logLevel",{get:function(){return this._logLevel},set:function(A){this._logLevel=A},enumerable:!1,configurable:!0}),i.prototype.log=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=rI.All&&this._print.apply(this,Ar([rI.All],$a(A),!1))},i.prototype.warn=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=rI.Warnings&&this._print.apply(this,Ar([rI.Warnings],$a(A),!1))},i.prototype.error=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=rI.Errors&&this._print.apply(this,Ar([rI.Errors],$a(A),!1))},i.prototype.setLogFunction=function(A){this._print=A},i.prototype._print=function(A){for(var e=[],t=1;t<arguments.length;t++)e[t-1]=arguments[t];var g=Ar([XV],$a(e),!1);for(var I in g)g[I]instanceof Error&&(g[I]="("+g[I].name+") "+g[I].message);A>=rI.All?console.log.apply(console,Ar([],$a(g),!1)):A>=rI.Warnings?console.warn.apply(console,Ar(["WARNING"],$a(g),!1)):A>=rI.Errors&&console.error.apply(console,Ar(["ERROR"],$a(g),!1))},i}(),qN=new $V,Yv={};zC(Yv,"Socket",()=>bN,i=>bN=i);var Wo;(function(i){i.Data="data",i.Media="media"})(Wo||(Wo={}));var ai;(function(i){i.BrowserIncompatible="browser-incompatible",i.Disconnected="disconnected",i.InvalidID="invalid-id",i.InvalidKey="invalid-key",i.Network="network",i.PeerUnavailable="peer-unavailable",i.SslUnavailable="ssl-unavailable",i.ServerError="server-error",i.SocketError="socket-error",i.SocketClosed="socket-closed",i.UnavailableID="unavailable-id",i.WebRTC="webrtc"})(ai||(ai={}));var ps;(function(i){i.Binary="binary",i.BinaryUTF8="binary-utf8",i.JSON="json"})(ps||(ps={}));var vs;(function(i){i.Message="message",i.Disconnected="disconnected",i.Error="error",i.Close="close"})(vs||(vs={}));var rg;(function(i){i.Heartbeat="HEARTBEAT",i.Candidate="CANDIDATE",i.Offer="OFFER",i.Answer="ANSWER",i.Open="OPEN",i.Error="ERROR",i.IdTaken="ID-TAKEN",i.InvalidKey="INVALID-KEY",i.Leave="LEAVE",i.Expire="EXPIRE"})(rg||(rg={}));var YM={};YM=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz Stückler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","Sören Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var Aj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),ej=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),g,I=[],o;try{for(;(A===void 0||A-- >0)&&!(g=t.next()).done;)I.push(g.value)}catch(C){o={error:C}}finally{try{g&&!g.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},tj=function(i,A,e){if(e||arguments.length===2)for(var t=0,g=A.length,I;t<g;t++)(I||!(t in A))&&(I||(I=Array.prototype.slice.call(A,0,t)),I[t]=A[t]);return i.concat(I||Array.prototype.slice.call(A))},ij=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},bN=function(i){Aj(A,i);function A(e,t,g,I,o,C){C===void 0&&(C=5e3);var s=i.call(this)||this;s.pingInterval=C,s._disconnected=!0,s._messagesQueue=[];var n=e?"wss://":"ws://";return s._baseUrl=n+t+":"+g+I+"peerjs?key="+o,s}return A.prototype.start=function(e,t){var g=this;this._id=e;var I="".concat(this._baseUrl,"&id=").concat(e,"&token=").concat(t);this._socket||!this._disconnected||(this._socket=new WebSocket(I+"&version="+YM.version),this._disconnected=!1,this._socket.onmessage=function(o){var C;try{C=JSON.parse(o.data),ge.default.log("Server message received:",C)}catch{ge.default.log("Invalid server message",o.data);return}g.emit(vs.Message,C)},this._socket.onclose=function(o){g._disconnected||(ge.default.log("Socket closed.",o),g._cleanup(),g._disconnected=!0,g.emit(vs.Disconnected))},this._socket.onopen=function(){g._disconnected||(g._sendQueuedMessages(),ge.default.log("Socket open"),g._scheduleHeartbeat())})},A.prototype._scheduleHeartbeat=function(){var e=this;this._wsPingTimer=setTimeout(function(){e._sendHeartbeat()},this.pingInterval)},A.prototype._sendHeartbeat=function(){if(!this._wsOpen()){ge.default.log("Cannot send heartbeat, because socket closed");return}var e=JSON.stringify({type:rg.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()},A.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},A.prototype._sendQueuedMessages=function(){var e,t,g=tj([],ej(this._messagesQueue),!1);this._messagesQueue=[];try{for(var I=ij(g),o=I.next();!o.done;o=I.next()){var C=o.value;this.send(C)}}catch(s){e={error:s}}finally{try{o&&!o.done&&(t=I.return)&&t.call(I)}finally{if(e)throw e.error}}},A.prototype.send=function(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(vs.Error,"Invalid message");return}if(this._wsOpen()){var t=JSON.stringify(e);this._socket.send(t)}}},A.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},A.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},A}(Wl.EventEmitter),Wk={};zC(Wk,"MediaConnection",()=>xN,i=>xN=i);var TM={};zC(TM,"Negotiator",()=>LN,i=>LN=i);var Up=function(){return Up=Object.assign||function(i){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var g in A)Object.prototype.hasOwnProperty.call(A,g)&&(i[g]=A[g])}return i},Up.apply(this,arguments)},Lu=function(i,A,e,t){function g(I){return I instanceof e?I:new e(function(o){o(I)})}return new(e||(e=Promise))(function(I,o){function C(a){try{n(t.next(a))}catch(B){o(B)}}function s(a){try{n(t.throw(a))}catch(B){o(B)}}function n(a){a.done?I(a.value):g(a.value).then(C,s)}n((t=t.apply(i,A||[])).next())})},vu=function(i,A){var e={label:0,sent:function(){if(I[0]&1)throw I[1];return I[1]},trys:[],ops:[]},t,g,I,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(n){return function(a){return s([n,a])}}function s(n){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,g&&(I=n[0]&2?g.return:n[0]?g.throw||((I=g.return)&&I.call(g),0):g.next)&&!(I=I.call(g,n[1])).done)return I;switch(g=0,I&&(n=[n[0]&2,I.value]),n[0]){case 0:case 1:I=n;break;case 4:return e.label++,{value:n[1],done:!1};case 5:e.label++,g=n[1],n=[0];continue;case 7:n=e.ops.pop(),e.trys.pop();continue;default:if(I=e.trys,!(I=I.length>0&&I[I.length-1])&&(n[0]===6||n[0]===2)){e=0;continue}if(n[0]===3&&(!I||n[1]>I[0]&&n[1]<I[3])){e.label=n[1];break}if(n[0]===6&&e.label<I[1]){e.label=I[1],I=n;break}if(I&&e.label<I[2]){e.label=I[2],e.ops.push(n);break}I[2]&&e.ops.pop(),e.trys.pop();continue}n=A.call(i,e)}catch(a){n=[6,a],g=0}finally{t=I=0}if(n[0]&5)throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}},LN=function(){function i(A){this.connection=A}return i.prototype.startConnection=function(A){var e=this._startPeerConnection();if(this.connection.peerConnection=e,this.connection.type===Wo.Media&&A._stream&&this._addTracksToConnection(A._stream,e),A.originator){if(this.connection.type===Wo.Data){var t=this.connection,g={ordered:!!A.reliable},I=e.createDataChannel(t.label,g);t.initialize(I)}this._makeOffer()}else this.handleSDP("OFFER",A.sdp)},i.prototype._startPeerConnection=function(){ge.default.log("Creating RTCPeerConnection.");var A=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(A),A},i.prototype._setupListeners=function(A){var e=this,t=this.connection.peer,g=this.connection.connectionId,I=this.connection.type,o=this.connection.provider;ge.default.log("Listening for ICE candidates."),A.onicecandidate=function(C){!C.candidate||!C.candidate.candidate||(ge.default.log("Received ICE candidates for ".concat(t,":"),C.candidate),o.socket.send({type:rg.Candidate,payload:{candidate:C.candidate,type:I,connectionId:g},dst:t}))},A.oniceconnectionstatechange=function(){switch(A.iceConnectionState){case"failed":ge.default.log("iceConnectionState is failed, closing connections to "+t),e.connection.emit("error",new Error("Negotiation of connection to "+t+" failed.")),e.connection.close();break;case"closed":ge.default.log("iceConnectionState is closed, closing connections to "+t),e.connection.emit("error",new Error("Connection to "+t+" closed.")),e.connection.close();break;case"disconnected":ge.default.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":A.onicecandidate=Qt.noop;break}e.connection.emit("iceStateChanged",A.iceConnectionState)},ge.default.log("Listening for data channel"),A.ondatachannel=function(C){ge.default.log("Received data channel");var s=C.channel,n=o.getConnection(t,g);n.initialize(s)},ge.default.log("Listening for remote stream"),A.ontrack=function(C){ge.default.log("Received remote stream");var s=C.streams[0],n=o.getConnection(t,g);if(n.type===Wo.Media){var a=n;e._addStreamToMediaConnection(s,a)}}},i.prototype.cleanup=function(){ge.default.log("Cleaning up PeerConnection to "+this.connection.peer);var A=this.connection.peerConnection;if(A){this.connection.peerConnection=null,A.onicecandidate=A.oniceconnectionstatechange=A.ondatachannel=A.ontrack=function(){};var e=A.signalingState!=="closed",t=!1;if(this.connection.type===Wo.Data){var g=this.connection,I=g.dataChannel;I&&(t=!!I.readyState&&I.readyState!=="closed")}(e||t)&&A.close()}},i.prototype._makeOffer=function(){return Lu(this,void 0,Promise,function(){var A,e,t,g,I,o,C;return vu(this,function(s){switch(s.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,s.label=1;case 1:return s.trys.push([1,7,,8]),[4,A.createOffer(this.connection.options.constraints)];case 2:t=s.sent(),ge.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(t.sdp=this.connection.options.sdpTransform(t.sdp)||t.sdp),s.label=3;case 3:return s.trys.push([3,5,,6]),[4,A.setLocalDescription(t)];case 4:return s.sent(),ge.default.log("Set localDescription:",t,"for:".concat(this.connection.peer)),g={sdp:t,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:Qt.browser},this.connection.type===Wo.Data&&(I=this.connection,g=Up(Up({},g),{label:I.label,reliable:I.reliable,serialization:I.serialization})),e.socket.send({type:rg.Offer,payload:g,dst:this.connection.peer}),[3,6];case 5:return o=s.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(e.emitError(ai.WebRTC,o),ge.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return C=s.sent(),e.emitError(ai.WebRTC,C),ge.default.log("Failed to createOffer, ",C),[3,8];case 8:return[2]}})})},i.prototype._makeAnswer=function(){return Lu(this,void 0,Promise,function(){var A,e,t,g,I;return vu(this,function(o){switch(o.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,A.createAnswer()];case 2:t=o.sent(),ge.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(t.sdp=this.connection.options.sdpTransform(t.sdp)||t.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,A.setLocalDescription(t)];case 4:return o.sent(),ge.default.log("Set localDescription:",t,"for:".concat(this.connection.peer)),e.socket.send({type:rg.Answer,payload:{sdp:t,type:this.connection.type,connectionId:this.connection.connectionId,browser:Qt.browser},dst:this.connection.peer}),[3,6];case 5:return g=o.sent(),e.emitError(ai.WebRTC,g),ge.default.log("Failed to setLocalDescription, ",g),[3,6];case 6:return[3,8];case 7:return I=o.sent(),e.emitError(ai.WebRTC,I),ge.default.log("Failed to create answer, ",I),[3,8];case 8:return[2]}})})},i.prototype.handleSDP=function(A,e){return Lu(this,void 0,Promise,function(){var t,g,I,o;return vu(this,function(C){switch(C.label){case 0:e=new RTCSessionDescription(e),t=this.connection.peerConnection,g=this.connection.provider,ge.default.log("Setting remote description",e),I=this,C.label=1;case 1:return C.trys.push([1,5,,6]),[4,t.setRemoteDescription(e)];case 2:return C.sent(),ge.default.log("Set remoteDescription:".concat(A," for:").concat(this.connection.peer)),A!=="OFFER"?[3,4]:[4,I._makeAnswer()];case 3:C.sent(),C.label=4;case 4:return[3,6];case 5:return o=C.sent(),g.emitError(ai.WebRTC,o),ge.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},i.prototype.handleCandidate=function(A){return Lu(this,void 0,Promise,function(){var e,t,g,I,o,C;return vu(this,function(s){switch(s.label){case 0:ge.default.log("handleCandidate:",A),e=A.candidate,t=A.sdpMLineIndex,g=A.sdpMid,I=this.connection.peerConnection,o=this.connection.provider,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,I.addIceCandidate(new RTCIceCandidate({sdpMid:g,sdpMLineIndex:t,candidate:e}))];case 2:return s.sent(),ge.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return C=s.sent(),o.emitError(ai.WebRTC,C),ge.default.log("Failed to handleCandidate, ",C),[3,4];case 4:return[2]}})})},i.prototype._addTracksToConnection=function(A,e){if(ge.default.log("add tracks from stream ".concat(A.id," to peer connection")),!e.addTrack)return ge.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");A.getTracks().forEach(function(t){e.addTrack(t,A)})},i.prototype._addStreamToMediaConnection=function(A,e){ge.default.log("add stream ".concat(A.id," to media connection ").concat(e.connectionId)),e.addStream(A)},i}(),HM={};zC(HM,"BaseConnection",()=>vN,i=>vN=i);var gj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),vN=function(i){gj(A,i);function A(e,t,g){var I=i.call(this)||this;return I.peer=e,I.provider=t,I.options=g,I._open=!1,I.metadata=g.metadata,I}return Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),A}(Wl.EventEmitter),Ij=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),Fp=function(){return Fp=Object.assign||function(i){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var g in A)Object.prototype.hasOwnProperty.call(A,g)&&(i[g]=A[g])}return i},Fp.apply(this,arguments)},oj=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},xN=function(i){Ij(A,i);function A(e,t,g){var I=i.call(this,e,t,g)||this;return I._localStream=I.options._stream,I.connectionId=I.options.connectionId||A.ID_PREFIX+Qt.randomToken(),I._negotiator=new TM.Negotiator(I),I._localStream&&I._negotiator.startConnection({_stream:I._localStream,originator:!0}),I}return Object.defineProperty(A.prototype,"type",{get:function(){return Wo.Media},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),A.prototype.addStream=function(e){ge.default.log("Receiving stream",e),this._remoteStream=e,i.prototype.emit.call(this,"stream",e)},A.prototype.handleMessage=function(e){var t=e.type,g=e.payload;switch(e.type){case rg.Answer:this._negotiator.handleSDP(t,g.sdp),this._open=!0;break;case rg.Candidate:this._negotiator.handleCandidate(g.candidate);break;default:ge.default.warn("Unrecognized message type:".concat(t," from peer:").concat(this.peer));break}},A.prototype.answer=function(e,t){var g,I;if(t===void 0&&(t={}),this._localStream){ge.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection(Fp(Fp({},this.options._payload),{_stream:e}));var o=this.provider._getMessages(this.connectionId);try{for(var C=oj(o),s=C.next();!s.done;s=C.next()){var n=s.value;this.handleMessage(n)}}catch(a){g={error:a}}finally{try{s&&!s.done&&(I=C.return)&&I.call(C)}finally{if(g)throw g.error}}this._open=!0},A.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},A.ID_PREFIX="mc_",A}(HM.BaseConnection),Vk={};zC(Vk,"DataConnection",()=>TN,i=>TN=i);var Tv={};zC(Tv,"EncodingQueue",()=>YN,i=>YN=i);var Cj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),YN=function(i){Cj(A,i);function A(){var e=i.call(this)||this;return e.fileReader=new FileReader,e._queue=[],e._processing=!1,e.fileReader.onload=function(t){e._processing=!1,t.target&&e.emit("done",t.target.result),e.doNextTask()},e.fileReader.onerror=function(t){ge.default.error("EncodingQueue error:",t),e._processing=!1,e.destroy(),e.emit("error",t)},e}return Object.defineProperty(A.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),A.prototype.enque=function(e){this.queue.push(e),!this.processing&&this.doNextTask()},A.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},A.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},A}(Wl.EventEmitter),sj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),nj=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},TN=function(i){sj(A,i);function A(e,t,g){var I=i.call(this,e,t,g)||this;return I.stringify=JSON.stringify,I.parse=JSON.parse,I._buffer=[],I._bufferSize=0,I._buffering=!1,I._chunkedData={},I._encodingQueue=new Tv.EncodingQueue,I.connectionId=I.options.connectionId||A.ID_PREFIX+Qt.randomToken(),I.label=I.options.label||I.connectionId,I.serialization=I.options.serialization||ps.Binary,I.reliable=!!I.options.reliable,I._encodingQueue.on("done",function(o){I._bufferedSend(o)}),I._encodingQueue.on("error",function(){ge.default.error("DC#".concat(I.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),I.close()}),I._negotiator=new TM.Negotiator(I),I._negotiator.startConnection(I.options._payload||{originator:!0}),I}return Object.defineProperty(A.prototype,"type",{get:function(){return Wo.Data},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),A.prototype.initialize=function(e){this._dc=e,this._configureDataChannel()},A.prototype._configureDataChannel=function(){var e=this;(!Qt.supports.binaryBlob||Qt.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){ge.default.log("DC#".concat(e.connectionId," dc connection success")),e._open=!0,e.emit("open")},this.dataChannel.onmessage=function(t){ge.default.log("DC#".concat(e.connectionId," dc onmessage:"),t.data),e._handleDataMessage(t)},this.dataChannel.onclose=function(){ge.default.log("DC#".concat(e.connectionId," dc closed for:"),e.peer),e.close()}},A.prototype._handleDataMessage=function(e){var t=this,g=e.data,I=g.constructor,o=this.serialization===ps.Binary||this.serialization===ps.BinaryUTF8,C=g;if(o){if(I===Blob){Qt.blobToArrayBuffer(g,function(n){var a=Qt.unpack(n);t.emit("data",a)});return}else if(I===ArrayBuffer)C=Qt.unpack(g);else if(I===String){var s=Qt.binaryStringToArrayBuffer(g);C=Qt.unpack(s)}}else this.serialization===ps.JSON&&(C=this.parse(g));if(C.__peerData){this._handleChunk(C);return}i.prototype.emit.call(this,"data",C)},A.prototype._handleChunk=function(e){var t=e.__peerData,g=this._chunkedData[t]||{data:[],count:0,total:e.total};if(g.data[e.n]=e.data,g.count++,this._chunkedData[t]=g,g.total===g.count){delete this._chunkedData[t];var I=new Blob(g.data);this._handleDataMessage({data:I})}},A.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},A.prototype.send=function(e,t){if(!this.open){i.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===ps.JSON)this._bufferedSend(this.stringify(e));else if(this.serialization===ps.Binary||this.serialization===ps.BinaryUTF8){var g=Qt.pack(e);if(!t&&g.size>Qt.chunkedMTU){this._sendChunks(g);return}Qt.supports.binaryBlob?this._bufferedSend(g):this._encodingQueue.enque(g)}else this._bufferedSend(e)},A.prototype._bufferedSend=function(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)},A.prototype._trySend=function(e){var t=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>A.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){t._buffering=!1,t._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(g){return ge.default.error("DC#:".concat(this.connectionId," Error when sending:"),g),this._buffering=!0,this.close(),!1}return!0},A.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},A.prototype._sendChunks=function(e){var t,g,I=Qt.chunk(e);ge.default.log("DC#".concat(this.connectionId," Try to send ").concat(I.length," chunks..."));try{for(var o=nj(I),C=o.next();!C.done;C=o.next()){var s=C.value;this.send(s,!0)}}catch(n){t={error:n}}finally{try{C&&!C.done&&(g=o.return)&&g.call(o)}finally{if(t)throw t.error}}},A.prototype.handleMessage=function(e){var t=e.payload;switch(e.type){case rg.Answer:this._negotiator.handleSDP(e.type,t.sdp);break;case rg.Candidate:this._negotiator.handleCandidate(t.candidate);break;default:ge.default.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}},A.ID_PREFIX="dc_",A.MAX_BUFFERED_AMOUNT=8388608,A}(HM.BaseConnection),Hv={};zC(Hv,"API",()=>ON,i=>ON=i);var HN=function(i,A,e,t){function g(I){return I instanceof e?I:new e(function(o){o(I)})}return new(e||(e=Promise))(function(I,o){function C(a){try{n(t.next(a))}catch(B){o(B)}}function s(a){try{n(t.throw(a))}catch(B){o(B)}}function n(a){a.done?I(a.value):g(a.value).then(C,s)}n((t=t.apply(i,A||[])).next())})},_N=function(i,A){var e={label:0,sent:function(){if(I[0]&1)throw I[1];return I[1]},trys:[],ops:[]},t,g,I,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(n){return function(a){return s([n,a])}}function s(n){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,g&&(I=n[0]&2?g.return:n[0]?g.throw||((I=g.return)&&I.call(g),0):g.next)&&!(I=I.call(g,n[1])).done)return I;switch(g=0,I&&(n=[n[0]&2,I.value]),n[0]){case 0:case 1:I=n;break;case 4:return e.label++,{value:n[1],done:!1};case 5:e.label++,g=n[1],n=[0];continue;case 7:n=e.ops.pop(),e.trys.pop();continue;default:if(I=e.trys,!(I=I.length>0&&I[I.length-1])&&(n[0]===6||n[0]===2)){e=0;continue}if(n[0]===3&&(!I||n[1]>I[0]&&n[1]<I[3])){e.label=n[1];break}if(n[0]===6&&e.label<I[1]){e.label=I[1],I=n;break}if(I&&e.label<I[2]){e.label=I[2],e.ops.push(n);break}I[2]&&e.ops.pop(),e.trys.pop();continue}n=A.call(i,e)}catch(a){n=[6,a],g=0}finally{t=I=0}if(n[0]&5)throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}},ON=function(){function i(A){this._options=A}return i.prototype._buildRequest=function(A){var e=this._options.secure?"https":"http",t=this._options,g=t.host,I=t.port,o=t.path,C=t.key,s=new URL("".concat(e,"://").concat(g,":").concat(I).concat(o).concat(C,"/").concat(A));return s.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),s.searchParams.set("version",YM.version),fetch(s.href,{referrerPolicy:this._options.referrerPolicy})},i.prototype.retrieveId=function(){return HN(this,void 0,Promise,function(){var A,e,t;return _N(this,function(g){switch(g.label){case 0:return g.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(A=g.sent(),A.status!==200)throw new Error("Error. Status:".concat(A.status));return[2,A.text()];case 2:throw e=g.sent(),ge.default.error("Error retrieving ID",e),t="",this._options.path==="/"&&this._options.host!==Qt.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+t);case 3:return[2]}})})},i.prototype.listAllPeers=function(){return HN(this,void 0,Promise,function(){var A,e,t;return _N(this,function(g){switch(g.label){case 0:return g.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(A=g.sent(),A.status!==200)throw A.status===401?(e="",this._options.host===Qt.CLOUD_HOST?e="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":e="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+e)):new Error("Error. Status:".concat(A.status));return[2,A.json()];case 2:throw t=g.sent(),ge.default.error("Error retrieving list peers",t),new Error("Could not get list peers from the server."+t);case 3:return[2]}})})},i}(),aj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),oh=function(){return oh=Object.assign||function(i){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var g in A)Object.prototype.hasOwnProperty.call(A,g)&&(i[g]=A[g])}return i},oh.apply(this,arguments)},uc=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},rj=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),g,I=[],o;try{for(;(A===void 0||A-- >0)&&!(g=t.next()).done;)I.push(g.value)}catch(C){o={error:C}}finally{try{g&&!g.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},PN=function(i){aj(A,i);function A(e,t){var g=i.call(this)||this;g._id=null,g._lastServerId=null,g._destroyed=!1,g._disconnected=!1,g._open=!1,g._connections=new Map,g._lostMessages=new Map;var I;return e&&e.constructor==Object?t=e:e&&(I=e.toString()),t=oh({debug:0,host:Qt.CLOUD_HOST,port:Qt.CLOUD_PORT,path:"/",key:A.DEFAULT_KEY,token:Qt.randomToken(),config:Qt.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},t),g._options=t,g._options.host==="/"&&(g._options.host=window.location.hostname),g._options.path&&(g._options.path[0]!=="/"&&(g._options.path="/"+g._options.path),g._options.path[g._options.path.length-1]!=="/"&&(g._options.path+="/")),g._options.secure===void 0&&g._options.host!==Qt.CLOUD_HOST?g._options.secure=Qt.isSecure():g._options.host==Qt.CLOUD_HOST&&(g._options.secure=!0),g._options.logFunction&&ge.default.setLogFunction(g._options.logFunction),ge.default.logLevel=g._options.debug||0,g._api=new Hv.API(t),g._socket=g._createServerConnection(),!Qt.supports.audioVideo&&!Qt.supports.data?(g._delayedAbort(ai.BrowserIncompatible,"The current browser does not support WebRTC"),g):I&&!Qt.validateId(I)?(g._delayedAbort(ai.InvalidID,'ID "'.concat(I,'" is invalid')),g):(I?g._initialize(I):g._api.retrieveId().then(function(o){return g._initialize(o)}).catch(function(o){return g._abort(ai.ServerError,o)}),g)}return Object.defineProperty(A.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"connections",{get:function(){var e,t,g=Object.create(null);try{for(var I=uc(this._connections),o=I.next();!o.done;o=I.next()){var C=rj(o.value,2),s=C[0],n=C[1];g[s]=n}}catch(a){e={error:a}}finally{try{o&&!o.done&&(t=I.return)&&t.call(I)}finally{if(e)throw e.error}}return g},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),A.prototype._createServerConnection=function(){var e=this,t=new Yv.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return t.on(vs.Message,function(g){e._handleMessage(g)}),t.on(vs.Error,function(g){e._abort(ai.SocketError,g)}),t.on(vs.Disconnected,function(){e.disconnected||(e.emitError(ai.Network,"Lost connection to server."),e.disconnect())}),t.on(vs.Close,function(){e.disconnected||e._abort(ai.SocketClosed,"Underlying socket is already closed.")}),t},A.prototype._initialize=function(e){this._id=e,this.socket.start(e,this._options.token)},A.prototype._handleMessage=function(e){var t,g,I=e.type,o=e.payload,C=e.src;switch(I){case rg.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case rg.Error:this._abort(ai.ServerError,o.msg);break;case rg.IdTaken:this._abort(ai.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case rg.InvalidKey:this._abort(ai.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case rg.Leave:ge.default.log("Received leave message from ".concat(C)),this._cleanupPeer(C),this._connections.delete(C);break;case rg.Expire:this.emitError(ai.PeerUnavailable,"Could not connect to peer ".concat(C));break;case rg.Offer:var c=o.connectionId,h=this.getConnection(C,c);if(h&&(h.close(),ge.default.warn("Offer received for existing Connection ID:".concat(c))),o.type===Wo.Media){var s=new Wk.MediaConnection(C,this,{connectionId:c,_payload:o,metadata:o.metadata});h=s,this._addConnection(C,h),this.emit("call",s)}else if(o.type===Wo.Data){var n=new Vk.DataConnection(C,this,{connectionId:c,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});h=n,this._addConnection(C,h),this.emit("connection",n)}else{ge.default.warn("Received malformed connection type:".concat(o.type));return}var a=this._getMessages(c);try{for(var B=uc(a),Q=B.next();!Q.done;Q=B.next()){var E=Q.value;h.handleMessage(E)}}catch(l){t={error:l}}finally{try{Q&&!Q.done&&(g=B.return)&&g.call(B)}finally{if(t)throw t.error}}break;default:if(!o){ge.default.warn("You received a malformed message from ".concat(C," of type ").concat(I));return}var c=o.connectionId,h=this.getConnection(C,c);h&&h.peerConnection?h.handleMessage(e):c?this._storeMessage(c,e):ge.default.warn("You received an unrecognized message:",e);break}},A.prototype._storeMessage=function(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)},A.prototype._getMessages=function(e){var t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]},A.prototype.connect=function(e,t){if(t===void 0&&(t={}),this.disconnected){ge.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(ai.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var g=new Vk.DataConnection(e,this,t);return this._addConnection(e,g),g},A.prototype.call=function(e,t,g){if(g===void 0&&(g={}),this.disconnected){ge.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(ai.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!t){ge.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var I=new Wk.MediaConnection(e,this,oh(oh({},g),{_stream:t}));return this._addConnection(e,I),I},A.prototype._addConnection=function(e,t){ge.default.log("add connection ".concat(t.type,":").concat(t.connectionId," to peerId:").concat(e)),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)},A.prototype._removeConnection=function(e){var t=this._connections.get(e.peer);if(t){var g=t.indexOf(e);g!==-1&&t.splice(g,1)}this._lostMessages.delete(e.connectionId)},A.prototype.getConnection=function(e,t){var g,I,o=this._connections.get(e);if(!o)return null;try{for(var C=uc(o),s=C.next();!s.done;s=C.next()){var n=s.value;if(n.connectionId===t)return n}}catch(a){g={error:a}}finally{try{s&&!s.done&&(I=C.return)&&I.call(C)}finally{if(g)throw g.error}}return null},A.prototype._delayedAbort=function(e,t){var g=this;setTimeout(function(){g._abort(e,t)},0)},A.prototype._abort=function(e,t){ge.default.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()},A.prototype.emitError=function(e,t){ge.default.error("Error:",t);var g;typeof t=="string"?g=new Error(t):g=t,g.type=e,this.emit("error",g)},A.prototype.destroy=function(){this.destroyed||(ge.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},A.prototype._cleanup=function(){var e,t;try{for(var g=uc(this._connections.keys()),I=g.next();!I.done;I=g.next()){var o=I.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(C){e={error:C}}finally{try{I&&!I.done&&(t=g.return)&&t.call(g)}finally{if(e)throw e.error}}this.socket.removeAllListeners()},A.prototype._cleanupPeer=function(e){var t,g,I=this._connections.get(e);if(I)try{for(var o=uc(I),C=o.next();!C.done;C=o.next()){var s=C.value;s.close()}}catch(n){t={error:n}}finally{try{C&&!C.done&&(g=o.return)&&g.call(o)}finally{if(t)throw t.error}}},A.prototype.disconnect=function(){if(!this.disconnected){var e=this.id;ge.default.log("Disconnect peer with ID:".concat(e)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}},A.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)ge.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)ge.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},A.prototype.listAllPeers=function(e){var t=this;e===void 0&&(e=function(g){}),this._api.listAllPeers().then(function(g){return e(g)}).catch(function(g){return t._abort(ai.ServerError,g)})},A.DEFAULT_KEY="peerjs",A}(Wl.EventEmitter),Np=vv.Peer;class Bj{constructor(){r(this,"_host");r(this,"_client");r(this,"_clientData");this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const A="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(A)}trySetupHost(A){let e=new Np(A);e.on("error",t=>{console.error(t),this._host=void 0,this.trySetupClient(A)}),e.on("open",t=>{this._host=new Ej(e)})}trySetupClient(A){this._client=new Np,this._client.on("error",e=>{console.error("Client error",e)}),this._client.on("open",e=>{console.log("client connected",e),this._clientData=this._client.connect(A,{metadata:{id:e}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",t=>{console.log("<<",t)})})}}class Qj{constructor(A){r(this,"_peer");this._peer=A}}class Ej extends Qj{constructor(e){var t;super(e);r(this,"_connections",[]);console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(g=>{var I;return(I=g.metadata)==null?void 0:I.id}).filter(g=>g!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const g=this._peer.connections[t];if(g)if(Array.isArray(g))for(const I of g)I&&I.send(e);else console.warn(g)}}}}var EI=(i=>(i[i.OnConnection=0]="OnConnection",i[i.OnRoomJoin=1]="OnRoomJoin",i[i.Queued=2]="Queued",i[i.Immediate=3]="Immediate",i))(EI||{});const WN="https://urls.needle.tools/default-networking-backend/index";let mn="wss://needle-tiny-starter.glitch.me/socket";const vg=!!rA("debugnet"),_c=!!(vg||rA("debugowner"));var _v=(i=>(i.ConnectionInfo="connection-start-info",i))(_v||{}),gi=(i=>(i.Join="join-room",i.Leave="leave-room",i.JoinedRoom="joined-room",i.LeftRoom="left-room",i.UserJoinedRoom="user-joined-room",i.UserLeftRoom="user-left-room",i))(gi||{});class cj{constructor(){r(this,"room");r(this,"viewId");r(this,"allowEditing");r(this,"inRoom")}}class hj{constructor(){r(this,"room")}}class lj{constructor(){r(this,"userId")}}var Ov=(i=>(i.RequestHasOwner="request-has-owner",i.ResponseHasOwner="response-has-owner",i.RequestIsOwner="request-is-owner",i.ResponseIsOwner="response-is-owner",i.RequestOwnership="request-ownership",i.GainedOwnership="gained-ownership",i.RemoveOwnership="remove-ownership",i.LostOwnership="lost-ownership",i.GainedOwnershipBroadcast="gained-ownership-broadcast",i.LostOwnershipBroadcast="lost-ownership-broadcast",i))(Ov||{});class rw{constructor(A,e){r(this,"guid");r(this,"connection");r(this,"_hasOwnership",!1);r(this,"_isOwned");r(this,"_gainSubscription");r(this,"_lostSubscription");r(this,"_hasOwnerResponse");r(this,"_isWaitingForOwnershipResponseCallback",null);this.connection=A,this.guid=e,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),A.beginListen("lost-ownership",this._lostSubscription),A.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),A.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(A){A.guid===this.guid&&(this._isOwned=A.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(A){A.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=A.value,A.value||(_c&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((A,e)=>{this.requestOwnership();let t=0;const g=()=>{if(t++>10)return e("Timeout");setTimeout(()=>{this.hasOwnership?A(this):g()},100)};g()})}requestOwnership(){return _c&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(A){A.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===A.owner?(_c&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(A){A===this.guid&&(_c&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class Pv{constructor(A){r(this,"context");r(this,"_peer",null);r(this,"_usersInRoomCopy",[]);r(this,"_defaultMessagesBuffer",[]);r(this,"_defaultMessagesBufferArray",[]);r(this,"netWebSocketUrlProvider");r(this,"_listeners",{});r(this,"_listenersBinary",{});r(this,"connected",!1);r(this,"channelId");r(this,"_connectionId",null);r(this,"_ws");r(this,"_waitingForSocket",{});r(this,"_isInRoom",!1);r(this,"_currentRoomName",null);r(this,"_currentRoomViewId",null);r(this,"_currentRoomAllowEditing",!0);r(this,"_currentInRoom",[]);r(this,"_state",{});r(this,"_currentDelay",-1);r(this,"_connectingToWebsocketPromise",null);this.context=A}get peer(){return this._peer||(this._peer=new Bj),this._peer}tryGetState(A){return A==="invalid"?null:this._state[A]}get connectionId(){return this._connectionId}get isDebugEnabled(){return vg}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(A){return this._currentInRoom.indexOf(A)!==-1}usersInRoom(A=null){A||(A=this._usersInRoomCopy),A.length=0;for(const e of this._currentInRoom)A.push(e);return A}joinRoom(A,e=!1){this.connect(),vg&&console.log("join: "+A),this.send("join-room",{room:A,viewOnly:e},EI.OnConnection)}leaveRoom(A=null){if(A||(A=this.currentRoomName),!A){console.error("Can not leave unknown room");return}this.send("leave-room",{room:A})}send(A,e=null,t=EI.Queued){if(e===null&&(e={}),t===EI.Queued){this._defaultMessagesBuffer.push({key:A,value:e});return}return this.sendWithWebsocket(A,e,t)}sendDeleteRemoteState(A){this.send("delete-state",{guid:A,dontSave:!0}),delete this._state[A]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(A){var e;vg&&console.log("<< bin",A.length),(e=this._ws)==null||e.send(A)}sendBufferedMessagesNow(){var t;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const A=Object.keys(this._defaultMessagesBuffer).length;for(const g in this._defaultMessagesBuffer){const I=this._defaultMessagesBuffer[g];if(A<=1){this.sendWithWebsocket(I.key,I.value,EI.Immediate);break}const o=this.toMessage(I.key,I.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&vg&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const e=JSON.stringify(this._defaultMessagesBufferArray);(t=this._ws)==null||t.send(e)}beginListen(A,e){return this._listeners[A]||(this._listeners[A]=[]),this._listeners[A].push(e),e}stopListening(A,e){return this.stopListen(A,e)}stopListen(A,e){if(!e||!this._listeners[A])return;const t=this._listeners[A].indexOf(e);t>=0&&this._listeners[A].splice(t,1)}beginListenBinary(A,e){return this._listenersBinary[A]||(this._listenersBinary[A]=[]),this._listenersBinary[A].push(e),e}stopListenBinary(A,e){if(!this._listenersBinary[A])return;const t=this._listenersBinary[A].indexOf(e);t>=0&&this._listenersBinary[A].splice(t,1)}registerProvider(A){this.netWebSocketUrlProvider=A}async connect(){var e;if(this.connected)return Promise.resolve(!0);vg&&console.log("connecting");const A=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return A?mn=A:Yq()&&(mn="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var A;(A=this._ws)==null||A.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(A,e)=>{let t=!1;const g=o=>{t||(t=!0,A(o))};if(mn===void 0&&(console.log("Fetch default backend url: "+WN),mn=await(await fetch(WN)).text()),mn===void 0){g(!1);return}console.log(`⊡ Connecting to networking backend on
3334
3334
  `+mn);const I=new ZL.WebsocketBuilder(mn).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=I,this.connected=!0,console.log(`⊞ Connected to networking backend
3335
3335
  `+mn),g(!0),this.onSendQueued(EI.OnConnection)}).onClose(o=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,g(!1)}).onError((o,C)=>{console.error("⊠ Websocket error",o,C),g(!1)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build()})}onMessage(A,e){const t=e.data;try{if(typeof t!="string"){t.size&&this.handleIncomingBinaryMessage(t);return}const g=JSON.parse(t);if(Array.isArray(g))for(const I of g)this.handleIncomingStringMessage(I);else this.handleIncomingStringMessage(g);return}catch{vg&&t==="pong"&&console.log("<<",t)}}async handleIncomingBinaryMessage(A){const e=await A.arrayBuffer();var t=new Uint8Array(e);const g=new Oh(t),I=g.getBufferIdentifier(),o=this._listenersBinary[I],C=RV(g),s=UV(C);if(s&&typeof s=="string"&&(this._state[s]=C),!o)return;const n=C??g;for(const a of o)a(n)}handleIncomingStringMessage(A){var g,I;if(vg&&console.log("<<",A.key??A),A.key)switch(A.key){case"connection-start-info":if(A.data){const s=A.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+A.key);break;case"joined-room":if(vg&&console.log(A),A){this._isInRoom=!0;const s=A;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),vg&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(EI.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const s=A.data;this._currentInRoom.push(s.userId),vg&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const s=A.data,n=this._currentInRoom.indexOf(s.userId);n>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(n,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":vg&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const C=(g=A.data)==null?void 0:g.time;C&&(this._currentDelay=this.context.time.time-C),vg&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+((I=this._currentInRoom)==null?void 0:I.length));break}const e=this._listeners[A.key];if(e)for(const o of e)o(A.data);const t=A.data;t&&(this._state[t.guid]=t)}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,t=EI.OnRoomJoin){if(!this._ws){const I=this._waitingForSocket[t]||[];I.push(()=>this.sendWithWebsocket(A,e,t)),this._waitingForSocket[t]=I;return}const g=JSON.stringify(this.toMessage(A,e));vg&&console.log(">>",A),this._ws.send(g)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const t of e)t();e.length=0}}}function wQ(i,A){try{A?i(A):i()}catch(e){return console.error(e),!1}return!0}(0,eval)(`
3336
- if(!globalThis[""null""])
3337
- globalThis[""null""] = "0.0.0";
3336
+ if(!globalThis["NEEDLE_ENGINE_VERSION"])
3337
+ globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";
3338
3338
  if(!globalThis[""undefined""])
3339
3339
  globalThis[""undefined""] = "unknown";
3340
- `);const Wv="null",dj="undefined",Hs="needle_isActiveInHierarchy",rr="builtin_components",Ch="needle_editor_guid",uj=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Dj(i){return typeof i=="string"&&uj.test(i)}const ng=[];for(let i=0;i<256;++i)ng.push((i+256).toString(16).slice(1));function pj(i,A=0){return(ng[i[A+0]]+ng[i[A+1]]+ng[i[A+2]]+ng[i[A+3]]+"-"+ng[i[A+4]]+ng[i[A+5]]+"-"+ng[i[A+6]]+ng[i[A+7]]+"-"+ng[i[A+8]]+ng[i[A+9]]+"-"+ng[i[A+10]]+ng[i[A+11]]+ng[i[A+12]]+ng[i[A+13]]+ng[i[A+14]]+ng[i[A+15]]).toLowerCase()}function fj(i){if(!Dj(i))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(i.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(i.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(i.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(i.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(i.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function wj(i){i=unescape(encodeURIComponent(i));const A=[];for(let e=0;e<i.length;++e)A.push(i.charCodeAt(e));return A}const yj="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Sj="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function kj(i,A,e){function t(g,I,o,C){var s;if(typeof g=="string"&&(g=wj(g)),typeof I=="string"&&(I=fj(I)),((s=I)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let n=new Uint8Array(16+g.length);if(n.set(I),n.set(g,I.length),n=e(n),n[6]=n[6]&15|A,n[8]=n[8]&63|128,o){C=C||0;for(let a=0;a<16;++a)o[C+a]=n[a];return o}return pj(n)}try{t.name=i}catch{}return t.DNS=yj,t.URL=Sj,t}function Gj(i,A,e,t){switch(i){case 0:return A&e^~A&t;case 1:return A^e^t;case 2:return A&e^A&t^e&t;case 3:return A^e^t}}function JS(i,A){return i<<A|i>>>32-A}function Mj(i){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof i=="string"){const o=unescape(encodeURIComponent(i));i=[];for(let C=0;C<o.length;++C)i.push(o.charCodeAt(C))}else Array.isArray(i)||(i=Array.prototype.slice.call(i));i.push(128);const t=i.length/4+2,g=Math.ceil(t/16),I=new Array(g);for(let o=0;o<g;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=i[o*64+s*4]<<24|i[o*64+s*4+1]<<16|i[o*64+s*4+2]<<8|i[o*64+s*4+3];I[o]=C}I[g-1][14]=(i.length-1)*8/Math.pow(2,32),I[g-1][14]=Math.floor(I[g-1][14]),I[g-1][15]=(i.length-1)*8&4294967295;for(let o=0;o<g;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=I[o][E];for(let E=16;E<80;++E)C[E]=JS(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],n=e[1],a=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const c=Math.floor(E/20),h=JS(s,5)+Gj(c,n,a,B)+Q+A[c]+C[E]>>>0;Q=B,B=a,a=JS(n,30)>>>0,n=s,s=h}e[0]=e[0]+s>>>0,e[1]=e[1]+n>>>0,e[2]=e[2]+a>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const mj=kj("v5",80,Mj),VN=mj;ii.registerCallback(LI.ContextCreated,i=>{const A=i.context;Xv(A),Zv(A)});const Kp=rA("debugcomponents"),jN="eff8ba80-635d-11ec-90d6-0242ac120003";class Vg{constructor(A){r(this,"_originalSeed");r(this,"_seed");typeof A=="string"&&(A=Vg.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return VN(A,jN);const e=this._seed;return this._seed-=1,VN(e.toString(),jN)}initialize(A){typeof A=="string"?this._seed=Vg.hash(A):this._seed=A}static createFromString(A){return new Vg(this.hash(A))}static hash(A){let e=0;for(let t=0;t<A.length;t++)e=A.charCodeAt(t)+((e<<5)-e);return e}}var Vv=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(Vv||{});class jv{constructor(A){r(this,"guid");this.guid=A}}function Bw(i,A,e=!0){if(!i)return;const t=i;if(js(i,e),!A){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let g=i.guid;if(!g&&t.uuid&&(g=t.uuid),!g){console.warn("Can not send destroy: failed to find guid",i);return}const I=new jv(g);A.send("instance-destroyed",I,EI.Queued)}function zv(i,A){const e=new jv(i);A.send("instance-destroyed",e,EI.Queued)}function Zv(i){i.connection.beginListen("instance-destroyed",A=>{Kp&&console.log("[Remote] Destroyed",i.scene,A);const e=Xl(A.guid,i.scene);e&&js(e)})}class Rj{constructor(A,e,t){r(this,"filename");r(this,"hash");r(this,"size");this.filename=A,this.hash=e,this.size=t}}class Uj{constructor(A,e){r(this,"guid");r(this,"originalGuid");r(this,"seed");r(this,"visible");r(this,"hostData");r(this,"dontSave");r(this,"parent");r(this,"position");r(this,"rotation");r(this,"scale");this.originalGuid=A,this.guid=e}}function _M(i,A,e,t){var s;const g=i;if(!g.guid)return console.warn("Can not instantiate: No guid",g),null;if(A.context||(A.context=pe.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const I=A?{...A}:null,{instance:o,seed:C}=Fj(g,A);if(o){const n=o;if(n.guid){Kp&&console.log("[Local] new instance","gameobject:",o==null?void 0:o.guid);const a=new Uj(g.guid,n.guid);a.seed=C,I&&(I.position&&(a.position={x:I.position.x,y:I.position.y,z:I.position.z}),I.rotation&&(a.rotation={x:I.rotation.x,y:I.rotation.y,z:I.rotation.z,w:I.rotation.w}),I.scale&&(a.scale={x:I.scale.x,y:I.scale.y,z:I.scale.z})),a.position||(a.position={x:n.position.x,y:n.position.y,z:n.position.z}),a.rotation||(a.rotation={x:n.quaternion.x,y:n.quaternion.y,z:n.quaternion.z,w:n.quaternion.w}),a.scale||(a.scale={x:n.scale.x,y:n.scale.y,z:n.scale.z}),a.visible=g.visible,I!=null&&I.parent&&(typeof I.parent=="string"?a.parent=I.parent:a.parent=I.parent.guid),a.hostData=e,t===!1&&(a.dontSave=!0),(s=A==null?void 0:A.context)==null||s.connection.send("new-instance-created",a)}else console.warn("Missing guid, can not send new instance event",n)}return o}function Qw(){return Math.random()*9999999}function Xv(i){i.connection.beginListen("new-instance-created",async A=>{const e=await Nj(A.originalGuid,i.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const t=new TC;A.position&&(t.position=new k(A.position.x,A.position.y,A.position.z)),A.rotation&&(t.rotation=new kA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(t.scale=new k(A.scale.x,A.scale.y,A.scale.z)),t.parent=A.parent,A.seed&&(t.idProvider=new Vg(A.seed)),t.visible=A.visible,t.context=i,Kp&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const g=$l(e,t);g&&(A.parent==="scene"&&i.scene.add(g),Kp&&console.log("[Remote] new instance","gameobject:",g==null?void 0:g.guid,e))})}function Fj(i,A){const e=Qw(),t=A??new TC;t.idProvider=new Vg(e);const g=$l(i,t);return{seed:e,instance:g}}const $v={};function Ax(i,A){$v[i]=A}async function Nj(i,A){const e=$v[i];if(e!=null){const t=await e(i);if(t)return t}return ex(i,A)}function ex(i,A){if(A===null||!i)return null;if(A.guid===i)return A;if(A.children)for(const e of A.children){const t=ex(i,e);if(t)return t}return null}const tx=new Map;function Kj(i,A){if(!i)return;if(!A){console.warn("No prototype found",i,i.prototype,i.constructor);return}let e=tx.get(A);e&&e.apply(i)}function Jj(i){const A=qj(i.prototype);tx.set(i,A)}function qj(i){return new bj(i)}class bj{constructor(A){r(this,"$symbol");r(this,"extensions");r(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=Object.getOwnPropertyDescriptor(A,t);g&&this.descriptors.push(g)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=this.descriptors[e];g&&Object.defineProperty(A,t,g)}}}}var Vl=(i=>(i.Added="component-added",i.Removing="removing-component",i))(Vl||{});const zN=rA("debugcomponentevents");class jl{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let t=this.eventListeners.get(A);t||(t=[]),t.push(e),this.eventListeners.set(A,t),zN&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const t=this.eventListeners.get(A);if(!t)return;const g=t.indexOf(e);g<0||t.splice(g,1)}static dispatchComponentLifecycleEvent(A,e){const t=this.eventListeners.get(A);if(zN&&console.log("Dispatching event "+A,t),!!t)for(const g of t)g(e)}}r(jl,"eventListeners",new Map);const qS=rA("debuggetcomponent");function Lj(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function OM(i,A){if(!i||!i.userData.components)return;const e=i.userData.components.indexOf(A);e<0||(jl.dispatchComponentLifecycleEvent(Vl.Removing,A),A.gameObject=null,i.userData.components.splice(e,1))}function Ew(i,A){const e=hE(i,A);if(e)return e;const t=new A;return Xr(i,t)}const ix=new Vg("addComponentIdProvider");function Xr(i,A,e=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),hw(i),pw(A);try{e&&A.__internalAwake&&(ah(i),A.__internalAwake()),jl.dispatchComponentLifecycleEvent(Vl.Added,A)}catch(t){console.error(t)}return A}function PM(i,A){if(A.gameObject===i)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(A))return A;return i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),pw(A),A}function gx(i){if(i.gameObject&&i.gameObject.userData.components){const A=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(A,1)}i.__internalDisable&&i.__internalDisable(),i.onDestroy&&i.onDestroy(),Us(i,i.context??pe.Current),i.__internalDestroy(),i.gameObject=null}let ZN=!1;function Ix(i,A,e){var t;if(i!=null){if(!i.isObject3D){console.error("Object is not object3D");return}if(!((t=i==null?void 0:i.userData)!=null&&t.components))return null;if(typeof A=="string"&&(ZN||(ZN=!0,console.warn(`Accessing components by name is not supported.
3340
+ `);const Wv=NEEDLE_ENGINE_VERSION,dj="undefined",Hs="needle_isActiveInHierarchy",rr="builtin_components",Ch="needle_editor_guid",uj=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Dj(i){return typeof i=="string"&&uj.test(i)}const ng=[];for(let i=0;i<256;++i)ng.push((i+256).toString(16).slice(1));function pj(i,A=0){return(ng[i[A+0]]+ng[i[A+1]]+ng[i[A+2]]+ng[i[A+3]]+"-"+ng[i[A+4]]+ng[i[A+5]]+"-"+ng[i[A+6]]+ng[i[A+7]]+"-"+ng[i[A+8]]+ng[i[A+9]]+"-"+ng[i[A+10]]+ng[i[A+11]]+ng[i[A+12]]+ng[i[A+13]]+ng[i[A+14]]+ng[i[A+15]]).toLowerCase()}function fj(i){if(!Dj(i))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(i.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(i.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(i.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(i.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(i.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function wj(i){i=unescape(encodeURIComponent(i));const A=[];for(let e=0;e<i.length;++e)A.push(i.charCodeAt(e));return A}const yj="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Sj="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function kj(i,A,e){function t(g,I,o,C){var s;if(typeof g=="string"&&(g=wj(g)),typeof I=="string"&&(I=fj(I)),((s=I)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let n=new Uint8Array(16+g.length);if(n.set(I),n.set(g,I.length),n=e(n),n[6]=n[6]&15|A,n[8]=n[8]&63|128,o){C=C||0;for(let a=0;a<16;++a)o[C+a]=n[a];return o}return pj(n)}try{t.name=i}catch{}return t.DNS=yj,t.URL=Sj,t}function Gj(i,A,e,t){switch(i){case 0:return A&e^~A&t;case 1:return A^e^t;case 2:return A&e^A&t^e&t;case 3:return A^e^t}}function JS(i,A){return i<<A|i>>>32-A}function Mj(i){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof i=="string"){const o=unescape(encodeURIComponent(i));i=[];for(let C=0;C<o.length;++C)i.push(o.charCodeAt(C))}else Array.isArray(i)||(i=Array.prototype.slice.call(i));i.push(128);const t=i.length/4+2,g=Math.ceil(t/16),I=new Array(g);for(let o=0;o<g;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=i[o*64+s*4]<<24|i[o*64+s*4+1]<<16|i[o*64+s*4+2]<<8|i[o*64+s*4+3];I[o]=C}I[g-1][14]=(i.length-1)*8/Math.pow(2,32),I[g-1][14]=Math.floor(I[g-1][14]),I[g-1][15]=(i.length-1)*8&4294967295;for(let o=0;o<g;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=I[o][E];for(let E=16;E<80;++E)C[E]=JS(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],n=e[1],a=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const c=Math.floor(E/20),h=JS(s,5)+Gj(c,n,a,B)+Q+A[c]+C[E]>>>0;Q=B,B=a,a=JS(n,30)>>>0,n=s,s=h}e[0]=e[0]+s>>>0,e[1]=e[1]+n>>>0,e[2]=e[2]+a>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const mj=kj("v5",80,Mj),VN=mj;ii.registerCallback(LI.ContextCreated,i=>{const A=i.context;Xv(A),Zv(A)});const Kp=rA("debugcomponents"),jN="eff8ba80-635d-11ec-90d6-0242ac120003";class Vg{constructor(A){r(this,"_originalSeed");r(this,"_seed");typeof A=="string"&&(A=Vg.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return VN(A,jN);const e=this._seed;return this._seed-=1,VN(e.toString(),jN)}initialize(A){typeof A=="string"?this._seed=Vg.hash(A):this._seed=A}static createFromString(A){return new Vg(this.hash(A))}static hash(A){let e=0;for(let t=0;t<A.length;t++)e=A.charCodeAt(t)+((e<<5)-e);return e}}var Vv=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(Vv||{});class jv{constructor(A){r(this,"guid");this.guid=A}}function Bw(i,A,e=!0){if(!i)return;const t=i;if(js(i,e),!A){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let g=i.guid;if(!g&&t.uuid&&(g=t.uuid),!g){console.warn("Can not send destroy: failed to find guid",i);return}const I=new jv(g);A.send("instance-destroyed",I,EI.Queued)}function zv(i,A){const e=new jv(i);A.send("instance-destroyed",e,EI.Queued)}function Zv(i){i.connection.beginListen("instance-destroyed",A=>{Kp&&console.log("[Remote] Destroyed",i.scene,A);const e=Xl(A.guid,i.scene);e&&js(e)})}class Rj{constructor(A,e,t){r(this,"filename");r(this,"hash");r(this,"size");this.filename=A,this.hash=e,this.size=t}}class Uj{constructor(A,e){r(this,"guid");r(this,"originalGuid");r(this,"seed");r(this,"visible");r(this,"hostData");r(this,"dontSave");r(this,"parent");r(this,"position");r(this,"rotation");r(this,"scale");this.originalGuid=A,this.guid=e}}function _M(i,A,e,t){var s;const g=i;if(!g.guid)return console.warn("Can not instantiate: No guid",g),null;if(A.context||(A.context=pe.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const I=A?{...A}:null,{instance:o,seed:C}=Fj(g,A);if(o){const n=o;if(n.guid){Kp&&console.log("[Local] new instance","gameobject:",o==null?void 0:o.guid);const a=new Uj(g.guid,n.guid);a.seed=C,I&&(I.position&&(a.position={x:I.position.x,y:I.position.y,z:I.position.z}),I.rotation&&(a.rotation={x:I.rotation.x,y:I.rotation.y,z:I.rotation.z,w:I.rotation.w}),I.scale&&(a.scale={x:I.scale.x,y:I.scale.y,z:I.scale.z})),a.position||(a.position={x:n.position.x,y:n.position.y,z:n.position.z}),a.rotation||(a.rotation={x:n.quaternion.x,y:n.quaternion.y,z:n.quaternion.z,w:n.quaternion.w}),a.scale||(a.scale={x:n.scale.x,y:n.scale.y,z:n.scale.z}),a.visible=g.visible,I!=null&&I.parent&&(typeof I.parent=="string"?a.parent=I.parent:a.parent=I.parent.guid),a.hostData=e,t===!1&&(a.dontSave=!0),(s=A==null?void 0:A.context)==null||s.connection.send("new-instance-created",a)}else console.warn("Missing guid, can not send new instance event",n)}return o}function Qw(){return Math.random()*9999999}function Xv(i){i.connection.beginListen("new-instance-created",async A=>{const e=await Nj(A.originalGuid,i.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const t=new TC;A.position&&(t.position=new k(A.position.x,A.position.y,A.position.z)),A.rotation&&(t.rotation=new kA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(t.scale=new k(A.scale.x,A.scale.y,A.scale.z)),t.parent=A.parent,A.seed&&(t.idProvider=new Vg(A.seed)),t.visible=A.visible,t.context=i,Kp&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const g=$l(e,t);g&&(A.parent==="scene"&&i.scene.add(g),Kp&&console.log("[Remote] new instance","gameobject:",g==null?void 0:g.guid,e))})}function Fj(i,A){const e=Qw(),t=A??new TC;t.idProvider=new Vg(e);const g=$l(i,t);return{seed:e,instance:g}}const $v={};function Ax(i,A){$v[i]=A}async function Nj(i,A){const e=$v[i];if(e!=null){const t=await e(i);if(t)return t}return ex(i,A)}function ex(i,A){if(A===null||!i)return null;if(A.guid===i)return A;if(A.children)for(const e of A.children){const t=ex(i,e);if(t)return t}return null}const tx=new Map;function Kj(i,A){if(!i)return;if(!A){console.warn("No prototype found",i,i.prototype,i.constructor);return}let e=tx.get(A);e&&e.apply(i)}function Jj(i){const A=qj(i.prototype);tx.set(i,A)}function qj(i){return new bj(i)}class bj{constructor(A){r(this,"$symbol");r(this,"extensions");r(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=Object.getOwnPropertyDescriptor(A,t);g&&this.descriptors.push(g)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=this.descriptors[e];g&&Object.defineProperty(A,t,g)}}}}var Vl=(i=>(i.Added="component-added",i.Removing="removing-component",i))(Vl||{});const zN=rA("debugcomponentevents");class jl{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let t=this.eventListeners.get(A);t||(t=[]),t.push(e),this.eventListeners.set(A,t),zN&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const t=this.eventListeners.get(A);if(!t)return;const g=t.indexOf(e);g<0||t.splice(g,1)}static dispatchComponentLifecycleEvent(A,e){const t=this.eventListeners.get(A);if(zN&&console.log("Dispatching event "+A,t),!!t)for(const g of t)g(e)}}r(jl,"eventListeners",new Map);const qS=rA("debuggetcomponent");function Lj(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function OM(i,A){if(!i||!i.userData.components)return;const e=i.userData.components.indexOf(A);e<0||(jl.dispatchComponentLifecycleEvent(Vl.Removing,A),A.gameObject=null,i.userData.components.splice(e,1))}function Ew(i,A){const e=hE(i,A);if(e)return e;const t=new A;return Xr(i,t)}const ix=new Vg("addComponentIdProvider");function Xr(i,A,e=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),hw(i),pw(A);try{e&&A.__internalAwake&&(ah(i),A.__internalAwake()),jl.dispatchComponentLifecycleEvent(Vl.Added,A)}catch(t){console.error(t)}return A}function PM(i,A){if(A.gameObject===i)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(A))return A;return i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),pw(A),A}function gx(i){if(i.gameObject&&i.gameObject.userData.components){const A=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(A,1)}i.__internalDisable&&i.__internalDisable(),i.onDestroy&&i.onDestroy(),Us(i,i.context??pe.Current),i.__internalDestroy(),i.gameObject=null}let ZN=!1;function Ix(i,A,e){var t;if(i!=null){if(!i.isObject3D){console.error("Object is not object3D");return}if(!((t=i==null?void 0:i.userData)!=null&&t.components))return null;if(typeof A=="string"&&(ZN||(ZN=!0,console.warn(`Accessing components by name is not supported.
3341
3341
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
3342
3342
 
3343
3343
  You can import other modules your main module to get access to types
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/engine",
3
- "version": "3.6.0-alpha",
3
+ "version": "3.6.0-alpha.1",
4
4
  "description": "Needle Engine is a web-based runtime for 3D apps. It runs on your machine for development with great integrations into editors like Unity or Blender - and can be deployed onto any device! It is flexible, extensible and networking and XR are built-in",
5
5
  "main": "dist/needle-engine.umd.cjs",
6
6
  "type": "module",
@@ -25,8 +25,11 @@ export const needleDefines = (command, needleEngineConfig, userSettings) => {
25
25
  config(viteConfig) {
26
26
  // console.log("Update vite defines -------------------------------------------");
27
27
  if (!viteConfig.define) viteConfig.define = {};
28
- viteConfig.define.NEEDLE_ENGINE_VERSION = "\"" + tryGetNeedleEngineVersion() + "\"";
29
- viteConfig.define.NEEDLE_ENGINE_GENERATOR = "\"" + needleEngineConfig.generator + "\"";
28
+ const version = tryGetNeedleEngineVersion();
29
+ if (version)
30
+ viteConfig.define.NEEDLE_ENGINE_VERSION = "\"" + version + "\"";
31
+ if (needleEngineConfig)
32
+ viteConfig.define.NEEDLE_ENGINE_GENERATOR = "\"" + needleEngineConfig.generator + "\"";
30
33
 
31
34
  if (useRapier && userSettings?.useRapier !== true) {
32
35
  const meta = loadConfig();