Files
Handwerksfreund_Frontend/node_modules/@supabase/phoenix/priv/static/phoenix.min.js
T
MarcWieland 8b613ec0bc Init
2026-07-26 23:57:23 +02:00

3 lines
26 KiB
JavaScript

"use strict";var Phoenix=(()=>{var H=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var z=(a,e)=>{for(var t in e)H(a,t,{get:e[t],enumerable:!0})},J=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of F(e))!I.call(a,s)&&s!==t&&H(a,s,{get:()=>e[s],enumerable:!(i=U(e,s))||i.enumerable});return a};var W=a=>J(H({},"__esModule",{value:!0}),a);var O=(a,e,t)=>new Promise((i,s)=>{var r=h=>{try{n(t.next(h))}catch(l){s(l)}},o=h=>{try{n(t.throw(h))}catch(l){s(l)}},n=h=>h.done?i(h.value):Promise.resolve(h.value).then(r,o);n((t=t.apply(a,e)).next())});var K={};z(K,{Channel:()=>j,LongPoll:()=>b,Presence:()=>_,Push:()=>E,Serializer:()=>L,Socket:()=>x,Timer:()=>y});var R=a=>typeof a=="function"?a:function(){return a};var X=typeof self!="undefined"?self:null,v=typeof window!="undefined"?window:null,p=X||v||globalThis,P="2.0.0",B=1e4,$=1e3,M=100,g={connecting:0,open:1,closing:2,closed:3},u={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},m={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},A={longpoll:"longpoll",websocket:"websocket"},D={complete:4},w="base64url.bearer.phx.";var E=class{constructor(e,t,i,s){this.channel=e,this.event=t,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:i}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}};var y=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var j=class{constructor(e,t,i){this.state=u.closed,this.topic=e,this.params=R(t||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new E(this,m.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new y(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=u.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=u.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=u.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=u.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new E(this,m.leave,R({}),this.timeout).send(),this.state=u.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(m.reply,(s,r)=>{this.trigger(this.replyEventName(r),s)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=u.closed,this.bindings=[]}onClose(e){this.on(m.close,e)}onError(e){return this.on(m.error,t=>e(t))}on(e,t){let i=this.bindingRef++;return this.bindings.push({event:e,ref:i,callback:t}),i}off(e,t){this.bindings=this.bindings.filter(i=>!(i.event===e&&(typeof t=="undefined"||t===i.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,i=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new E(this,e,function(){return t},i);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=u.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(m.close,"leave")},i=new E(this,m.leave,R({}),e);return i.receive("ok",()=>t()).receive("timeout",()=>t()),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(e,t,i){return t}filterBindings(e,t,i){return!0}isMember(e,t,i,s){return this.topic!==e?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:i,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=u.joining,this.joinPush.resend(e))}trigger(e,t,i,s){let r=this.onMessage(e,t,i,s);if(t&&!r)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let o=this.bindings.filter(n=>n.event===e&&this.filterBindings(n,t,i));for(let n=0;n<o.length;n++)o[n].callback(r,i,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===u.closed}isErrored(){return this.state===u.errored}isJoined(){return this.state===u.joined}isJoining(){return this.state===u.joining}isLeaving(){return this.state===u.leaving}};var C=class{static request(e,t,i,s,r,o,n){if(p.XDomainRequest){let h=new p.XDomainRequest;return this.xdomainRequest(h,e,t,s,r,o,n)}else if(p.XMLHttpRequest){let h=new p.XMLHttpRequest;return this.xhrRequest(h,e,t,i,s,r,o,n)}else{if(p.fetch&&p.AbortController)return this.fetchRequest(e,t,i,s,r,o,n);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(e,t,i,s,r,o,n){let h={method:e,headers:i,body:s},l=null;if(r){l=new AbortController;let c=setTimeout(()=>l.abort(),r);h.signal=l.signal}return p.fetch(t,h).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>n&&n(c)).catch(c=>{c.name==="AbortError"&&o?o():n&&n(null)}),l}static xdomainRequest(e,t,i,s,r,o,n){return e.timeout=r,e.open(t,i),e.onload=()=>{let h=this.parseJSON(e.responseText);n&&n(h)},o&&(e.ontimeout=o),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,i,s,r,o,n,h){e.open(t,i,!0),e.timeout=o;for(let[l,c]of Object.entries(s))e.setRequestHeader(l,c);return e.onerror=()=>h&&h(null),e.onreadystatechange=()=>{if(e.readyState===D.complete&&h){let l=this.parseJSON(e.responseText);h(l)}},n&&(e.ontimeout=n),e.send(r),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch(t){return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let i=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let r=t?`${t}[${s}]`:s,o=e[s];typeof o=="object"?i.push(this.serialize(o,r)):i.push(encodeURIComponent(r)+"="+encodeURIComponent(o))}return i.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let i=e.match(/\?/)?"&":"?";return`${e}${i}${this.serialize(t)}`}};var G=a=>{let e="",t=new Uint8Array(a),i=t.byteLength;for(let s=0;s<i;s++)e+=String.fromCharCode(t[s]);return btoa(e)},b=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(w)&&(this.authToken=atob(t[1].slice(w.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=g.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+A.websocket),"$1/"+A.longpoll)}endpointURL(){return C.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,i){this.close(e,t,i),this.readyState=g.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===g.open||this.readyState===g.connecting}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),t=>{if(t){var{status:i,token:s,messages:r}=t;if(i===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else i=0;switch(i){case 200:r.forEach(o=>{setTimeout(()=>this.onmessage({data:o}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=g.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${i}`)}})}send(e){typeof e!="string"&&(e=G(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;let i=t+M,s=e.slice(t,i);this.ajax("POST",{"Content-Type":"application/x-ndjson"},s.join(`
`),()=>this.onerror("timeout"),r=>{!r||r.status!==200?(this.awaitingBatchAck=!1,this.onerror(r&&r.status),this.closeAndRetry(1011,"internal server error",!1)):i<e.length?this.batchSend(e,i):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(e,t,i){for(let r of this.reqs)r.abort();this.readyState=g.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:i});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent!="undefined"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,i,s,r){let o,n=()=>{this.reqs.delete(o),s()};o=C.request(e,this.endpointURL(),t,i,this.timeout,n,h=>{this.reqs.delete(o),this.isActive()&&r(h)}),this.reqs.add(o)}};var _=class a{constructor(e,t={}){let i=t.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(i.state,s=>{let{onJoin:r,onLeave:o,onSync:n}=this.caller;this.joinRef=this.channel.joinRef(),this.state=a.syncState(this.state,s,r,o),this.pendingDiffs.forEach(h=>{this.state=a.syncDiff(this.state,h,r,o)}),this.pendingDiffs=[],n()}),this.channel.on(i.diff,s=>{let{onJoin:r,onLeave:o,onSync:n}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=a.syncDiff(this.state,s,r,o),n())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return a.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,i,s){let r=this.toNullProtoObj(this.clone(e));t=this.toNullProtoObj(t);let o=Object.create(null),n=Object.create(null);return this.map(r,(h,l)=>{t[h]||(n[h]=l)}),this.map(t,(h,l)=>{let c=r[h];if(c){let T=l.metas.map(f=>f.phx_ref),d=c.metas.map(f=>f.phx_ref),S=l.metas.filter(f=>d.indexOf(f.phx_ref)<0),k=c.metas.filter(f=>T.indexOf(f.phx_ref)<0);S.length>0&&(o[h]=l,o[h].metas=S),k.length>0&&(n[h]=this.clone(c),n[h].metas=k)}else o[h]=l}),this.syncDiff(r,{joins:o,leaves:n},i,s)}static syncDiff(e,t,i,s){e=this.toNullProtoObj(e);let{joins:r,leaves:o}=this.clone(t);return i||(i=function(){}),s||(s=function(){}),this.map(r,(n,h)=>{let l=e[n];if(e[n]=this.clone(h),l){let c=e[n].metas.map(d=>d.phx_ref),T=l.metas.filter(d=>c.indexOf(d.phx_ref)<0);e[n].metas.unshift(...T)}i(n,l,h)}),this.map(o,(n,h)=>{let l=e[n];if(!l)return;let c=h.metas.map(T=>T.phx_ref);l.metas=l.metas.filter(T=>c.indexOf(T.phx_ref)<0),s(n,l,h),l.metas.length===0&&delete e[n]}),e}static list(e,t){return t||(t=function(i,s){return s}),this.map(e,(i,s)=>t(i,s))}static map(e,t){return Object.getOwnPropertyNames(e).map(i=>t(i,e[i]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(i=>{t[i]=e[i]}),t}static clone(e){return JSON.parse(JSON.stringify(e))}};var L={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(a,e){if(a.payload.constructor===ArrayBuffer)return e(this.binaryEncode(a));{let t=[a.join_ref,a.ref,a.topic,a.event,a.payload];return e(JSON.stringify(t))}},decode(a,e){if(a.constructor===ArrayBuffer)return e(this.binaryDecode(a));{let[t,i,s,r,o]=JSON.parse(a);return e({join_ref:t,ref:i,topic:s,event:r,payload:o})}},binaryEncode(a){let{join_ref:e,ref:t,event:i,topic:s,payload:r}=a,o=new TextEncoder,n=o.encode(e),h=o.encode(t),l=o.encode(s),c=o.encode(i);this.assertFieldSize(n.byteLength,"join_ref"),this.assertFieldSize(h.byteLength,"ref"),this.assertFieldSize(l.byteLength,"topic"),this.assertFieldSize(c.byteLength,"event");let T=this.META_LENGTH+n.byteLength+h.byteLength+l.byteLength+c.byteLength,d=new ArrayBuffer(this.HEADER_LENGTH+T),S=new Uint8Array(d),k=new DataView(d),f=0;k.setUint8(f++,this.KINDS.push),k.setUint8(f++,n.byteLength),k.setUint8(f++,h.byteLength),k.setUint8(f++,l.byteLength),k.setUint8(f++,c.byteLength),S.set(n,f),f+=n.byteLength,S.set(h,f),f+=h.byteLength,S.set(l,f),f+=l.byteLength,S.set(c,f),f+=c.byteLength;var N=new Uint8Array(d.byteLength+r.byteLength);return N.set(S,0),N.set(new Uint8Array(r),d.byteLength),N.buffer},assertFieldSize(a,e){if(a>255)throw new Error(`unable to convert ${e} to binary: must be less than or equal to 255 bytes, but is ${a} bytes`)},binaryDecode(a){let e=new DataView(a),t=e.getUint8(0),i=new TextDecoder;switch(t){case this.KINDS.push:return this.decodePush(a,e,i);case this.KINDS.reply:return this.decodeReply(a,e,i);case this.KINDS.broadcast:return this.decodeBroadcast(a,e,i)}},decodePush(a,e,t){let i=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,n=t.decode(a.slice(o,o+i));o=o+i;let h=t.decode(a.slice(o,o+s));o=o+s;let l=t.decode(a.slice(o,o+r));o=o+r;let c=a.slice(o,a.byteLength);return{join_ref:n,ref:null,topic:h,event:l,payload:c}},decodeReply(a,e,t){let i=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=e.getUint8(4),n=this.HEADER_LENGTH+this.META_LENGTH,h=t.decode(a.slice(n,n+i));n=n+i;let l=t.decode(a.slice(n,n+s));n=n+s;let c=t.decode(a.slice(n,n+r));n=n+r;let T=t.decode(a.slice(n,n+o));n=n+o;let d=a.slice(n,a.byteLength),S={status:T,response:d};return{join_ref:h,ref:l,topic:c,event:m.reply,payload:S}},decodeBroadcast(a,e,t){let i=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,o=t.decode(a.slice(r,r+i));r=r+i;let n=t.decode(a.slice(r,r+s));r=r+s;let h=a.slice(r,a.byteLength);return{join_ref:null,ref:null,topic:o,event:n,payload:h}}};var x=class{constructor(e,t={}){var r,o;this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||B,this.transport=t.transport||p.WebSocket||b,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let i=null;try{i=p&&p.sessionStorage}catch(n){}this.sessionStore=t.sessionStorage||i,this.establishedConnections=0,this.defaultEncoder=L.encode.bind(L),this.defaultDecoder=L.decode.bind(L),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==b?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;v&&v.addEventListener&&(v.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),v.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())}),v.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=(r=t.autoSendHeartbeat)!=null?r:!0,this.heartbeatCallback=(o=t.heartbeatCallback)!=null?o:()=>{},this.rejoinAfterMs=n=>t.rejoinAfterMs?t.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>t.reconnectAfterMs?t.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(n,h,l)=>{console.log(`${n}: ${h}`,l)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=R(t.params||{}),this.endPoint=`${e}/${A.websocket}`,this.vsn=t.vsn||P,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new y(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(()=>O(this,null,function*(){t.beforeReconnect&&(yield t.beforeReconnect()),this.connect()}))},this.reconnectAfterMs),this.authToken=t.authToken&&R(t.authToken)}getLongPollTransport(){return b}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=C.appendParams(C.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,i){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,i)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=R(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==b?this.connectWithFallback(b,this.longPollFallbackMs):this.transportConnect())}log(e,t,i){this.logger&&this.logger(e,t,i)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(r=>{r.ref===t&&(this.off([s]),e(Date.now()-i))});return!0}transportName(e){switch(e){case b:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["phoenix",`${w}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let i=!1,s=!0,r,o,n=this.transportName(e),h=l=>{this.log("transport",`falling back to ${n}...`,l),this.off([r,o]),s=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${n}`))return h("memorized");this.fallbackTimer=setTimeout(h,t),o=this.onError(l=>{this.log("transport","error",l),s&&!i&&(clearTimeout(this.fallbackTimer),h(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!s){let l=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(h,t),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),$,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,i){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,i||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,i=1){if(i===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,i+1)},150*i)}waitForSocketClosed(e,t,i=1){if(i===5||e.readyState===g.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,i+1)},150*i)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,i=this.establishedConnections;this.triggerStateCallbacks("error",e,t,i),(t===this.transport||i>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(m.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case g.connecting:return"connecting";case g.open:return"open";case g.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([i])=>e.indexOf(i)===-1)}channel(e,t={}){let i=new j(e,t,this);return this.channels.push(i),i}push(e){if(this.hasLogger()){let{topic:t,event:i,payload:s,ref:r,join_ref:o}=e;this.log("push",`${t} ${i} (${o}, ${r})`,s)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:i,event:s,payload:r,ref:o,join_ref:n}=t;if(o&&o===this.pendingHeartbeatRef){let h=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(r.status==="ok"?"ok":"error",h)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${r.status||""} ${i} ${s} ${o&&"("+o+")"||""}`.trim(),r);for(let h=0;h<this.channels.length;h++){let l=this.channels[h];l.isMember(i,s,r,n)&&l.trigger(s,r,o,n)}this.triggerStateCallbacks("message",t)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([i,s])=>{try{s(...t)}catch(r){this.log("error",`error in ${e} callback`,r)}})}catch(i){this.log("error",`error triggering ${e} callbacks`,i)}}leaveOpenTopic(e){let t=this.channels.find(i=>i.topic===e&&(i.isJoined()||i.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};return W(K);})();