UNPKG

@laravel/echo-vue

Version:

Vue hooks for seamless integration with Laravel Echo.

3 lines (2 loc) 13.8 kB
var EchoVue=(function(o,a,$){"use strict";class m{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,t){return this.listen(".client-"+e,t)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,t){return this.stopListening(".client-"+e,t)}}class E{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function O(n){try{return Reflect.construct(String,[],n),!0}catch{return!1}}class k extends m{constructor(e,t,s){super(),this.name=t,this.pusher=e,this.options=s,this.eventFormatter=new E(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,t){return this.on(this.eventFormatter.format(e),t),this}listenToAll(e){return this.subscription.bind_global((t,s)=>{if(t.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),r=t.startsWith(i)?t.substring(i.length+1):"."+t;e(r,s)}),this}stopListening(e,t){return t?this.subscription.unbind(this.eventFormatter.format(e),t):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",t=>{e(t)}),this}on(e,t){return this.subscription.bind(e,t),this}}class C extends k{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class F extends k{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class q extends C{here(e){return this.on("pusher:subscription_succeeded",t=>{e(Object.keys(t.members).map(s=>t.members[s]))}),this}joining(e){return this.on("pusher:member_added",t=>{e(t.info)}),this}whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}leaving(e){return this.on("pusher:member_removed",t=>{e(t.info)}),this}}class S extends m{constructor(e,t,s){super(),this.events={},this.listeners={},this.name=t,this.socket=e,this.options=s,this.eventFormatter=new E(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,t){return this.on(this.eventFormatter.format(e),t),this}stopListening(e,t){return this.unbindEvent(this.eventFormatter.format(e),t),this}subscribed(e){return this.on("connect",t=>{e(t)}),this}error(e){return this}on(e,t){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(s,i)=>{this.name===s&&this.listeners[e]&&this.listeners[e].forEach(r=>r(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(t),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,t){this.listeners[e]=this.listeners[e]||[],t&&(this.listeners[e]=this.listeners[e].filter(s=>s!==t)),(!t||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class I extends S{whisper(e,t){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:t}),this}}class R extends I{here(e){return this.on("presence:subscribed",t=>{e(t.map(s=>s.user_info))}),this}joining(e){return this.on("presence:joining",t=>e(t.user_info)),this}whisper(e,t){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:t}),this}leaving(e){return this.on("presence:leaving",t=>e(t.user_info)),this}}class p extends m{subscribe(){}unsubscribe(){}listen(e,t){return this}listenToAll(e){return this}stopListening(e,t){return this}subscribed(e){return this}error(e){return this}on(e,t){return this}}class P extends p{whisper(e,t){return this}}class V extends p{whisper(e,t){return this}}class X extends P{here(e){return this}joining(e){return this}whisper(e,t){return this}leaving(e){return this}}class l{static{this._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"}}constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...l._defaultOptions,...e,broadcaster:e.broadcaster};let t=this.csrfToken();t&&(this.options.auth.headers["X-CSRF-TOKEN"]=t,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=t),t=this.options.bearerToken,t&&(this.options.auth.headers.Authorization="Bearer "+t,this.options.userAuthentication.headers.Authorization="Bearer "+t)}csrfToken(){return typeof window<"u"&&window.Laravel?.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?document.querySelector('meta[name="csrf-token"]')?.getAttribute("content")??null:null}}class d extends l{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,t,s){return this.channel(e).listen(t,s)}channel(e){return this.channels[e]||(this.channels[e]=new k(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new C(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new F(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new q(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(t=>{this.leaveChannel(t)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}connectionStatus(){const e=this.pusher.connection.state;switch(e){case"connected":case"connecting":return e;case"failed":case"unavailable":return"failed";default:return"disconnected"}}onConnectionChange(e){const t=()=>{e(this.connectionStatus())},s=["state_change","connected","disconnected"];return s.forEach(i=>{this.pusher.connection.bind(i,t)}),()=>{s.forEach(i=>{this.pusher.connection.unbind(i,t)})}}disconnect(){this.pusher.disconnect()}}class B extends l{constructor(){super(...arguments),this.channels={}}connect(){const e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(t=>{t.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,t,s){return this.channel(e).listen(t,s)}channel(e){return this.channels[e]||(this.channels[e]=new S(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new I(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new R(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(t=>{this.leaveChannel(t)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}connectionStatus(){return this.socket.connected?"connected":this.socket.io._reconnecting?"reconnecting":this.socket.id!==void 0?"disconnected":"connecting"}onConnectionChange(e){const t=()=>{e(this.connectionStatus())},s=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return s.forEach(i=>{this.socket.on(i,t)}),()=>{s.forEach(i=>{this.socket.off(i,t)})}}disconnect(){this.socket.disconnect()}}class T extends l{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,t,s){return new p}channel(e){return new p}privateChannel(e){return new P}encryptedPrivateChannel(e){return new V}presenceChannel(e){return new X}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class Q{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new d({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new d(this.options);else if(this.options.broadcaster==="ably")this.connector=new d({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new B(this.options);else if(this.options.broadcaster==="null")this.connector=new T(this.options);else if(typeof this.options.broadcaster=="function"&&O(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,t,s){return this.connector.listen(e,t,s)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof d||e instanceof T}socketId(){return this.connector.socketId()}connectionStatus(){return this.connector.connectionStatus()}registerInterceptors(){typeof Vue<"u"&&Vue?.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,t)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),t()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,t,s)=>{this.socketId()&&s.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}let u=null,f=null;const W=()=>{if(u)return u;if(!f)throw new Error("Echo has not been configured. Please call `configureEcho()` with your configuration options before using Echo.");return f.Pusher??=$,u=new Q(f),u},H=n=>{f={...{reverb:{broadcaster:"reverb",key:void 0,wsHost:void 0,wsPort:void 0,wssPort:void 0,forceTLS:!0,enabledTransports:["ws","wss"]},pusher:{broadcaster:"pusher",key:void 0,cluster:void 0,forceTLS:!0,wsHost:void 0,wsPort:void 0,wssPort:void 0,enabledTransports:["ws","wss"]},"socket.io":{broadcaster:"socket.io",host:void 0},null:{broadcaster:"null"},ably:{broadcaster:"pusher",key:void 0,wsHost:"realtime-pusher.ably.io",wsPort:443,disableStats:!0,encrypted:!0}}[n.broadcaster],...n},u&&(u=null)},b=()=>W(),M=n=>Array.isArray(n)?n:[n],c={},N=n=>{if(c[n.id])return c[n.id].count+=1,c[n.id].connection;const e=z(n);return c[n.id]={count:1,connection:e},e},z=n=>{const e=b();return n.visibility==="presence"?e.join(n.name):n.visibility==="private"?e.private(n.name):e.channel(n.name)},D=(n,e=!1)=>{c[n.id]&&(c[n.id].count-=1,!(c[n.id].count>0)&&(delete c[n.id],e?b().leave(n.name):b().leaveChannel(n.id)))};function v(n,e=[],t=()=>{},s=[],i="private"){const r=a.ref(t),g=a.ref(!1);a.watch(()=>t,h=>{r.value=h});const A={name:n,id:["private","presence"].includes(i)?`${i}-${n}`:n,visibility:i},y=N(A),j=Array.isArray(e)?e:[e],_=()=>{L()},L=()=>{g.value||(j.forEach(h=>{y.listen(h,r.value)}),g.value=!0)},x=()=>{g.value&&(j.forEach(h=>{y.stopListening(h,r.value)}),g.value=!1)},w=(h=!1)=>{x(),D(A,h)};return a.onMounted(()=>{_()}),a.onUnmounted(()=>{w()}),s.length>0&&a.watch(()=>s,()=>{w(),_()},{deep:!0}),{leaveChannel:w,leave:()=>w(!0),stopListening:x,listen:L,channel:()=>y}}const K=(n,e=[],t=()=>{},s=[])=>v(n,e,t,s,"presence"),U=(n,e=[],t=()=>{},s=[])=>v(n,e,t,s,"public"),G=(n,e,t=[],s=()=>{},i=[])=>v(`${n}.${e}`,M(t).map(r=>r.startsWith(".")?r:`.${r}`),s,i,"private");return o.configureEcho=H,o.echo=b,o.useEcho=v,o.useEchoModel=G,o.useEchoPresence=K,o.useEchoPublic=U,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o})({},Vue,Pusher); //# sourceMappingURL=echo-vue.iife.js.map