@laravel/echo-vue
Version:
Vue hooks for seamless integration with Laravel Echo.
3 lines (2 loc) • 13.5 kB
JavaScript
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("vue"),L=require("pusher-js");class k{listenForWhisper(e,t){return this.listen(".client-"+e,t)}notification(e){return this.listen(".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated",e)}stopListeningForWhisper(e,t){return this.stopListening(".client-"+e,t)}}class S{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 $(s){try{new s}catch(e){if(e instanceof Error&&e.message.includes("is not a constructor"))return!1}return!0}class I extends k{constructor(e,t,n){super(),this.name=t,this.pusher=e,this.options=n,this.eventFormatter=new S(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,n)=>{if(t.startsWith("pusher:"))return;let r=String(this.options.namespace??"").replace(/\./g,"\\"),i=t.startsWith(r)?t.substring(r.length+1):"."+t;e(i,n)}),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 I{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class q extends I{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class H extends C{here(e){return this.on("pusher:subscription_succeeded",t=>{e(Object.keys(t.members).map(n=>t.members[n]))}),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 R extends k{constructor(e,t,n){super(),this.events={},this.listeners={},this.name=t,this.socket=e,this.options=n,this.eventFormatter=new S(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]=(n,r)=>{this.name===n&&this.listeners[e]&&this.listeners[e].forEach(i=>i(r))},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(n=>n!==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 A extends R{whisper(e,t){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:t}),this}}class B extends A{here(e){return this.on("presence:subscribed",t=>{e(t.map(n=>n.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 m extends k{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 V extends m{whisper(e,t){return this}}class F extends m{whisper(e,t){return this}}class U extends V{here(e){return this}joining(e){return this}whisper(e,t){return this}leaving(e){return this}}const x=class O{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...O._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(){var e,t;return typeof window<"u"&&(e=window.Laravel)!=null&&e.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?((t=document.querySelector('meta[name="csrf-token"]'))==null?void 0:t.getAttribute("content"))??null:null}};x._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let T=x;class g extends T{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,n){return this.channel(e).listen(t,n)}channel(e){return this.channels[e]||(this.channels[e]=new I(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 q(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new H(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}disconnect(){this.pusher.disconnect()}}class K extends T{constructor(){super(...arguments),this.channels={}}connect(){let 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,n){return this.channel(e).listen(t,n)}channel(e){return this.channels[e]||(this.channels[e]=new R(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new A(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new B(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}disconnect(){this.socket.disconnect()}}class P extends T{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,t,n){return new m}channel(e){return new m}privateChannel(e){return new V}encryptedPrivateChannel(e){return new F}presenceChannel(e){return new U}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}disconnect(){}}class M{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 g({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new g(this.options);else if(this.options.broadcaster==="ably")this.connector=new g({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new K(this.options);else if(this.options.broadcaster==="null")this.connector=new P(this.options);else if(typeof this.options.broadcaster=="function"&&$(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,n){return this.connector.listen(e,t,n)}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 g||e instanceof P}socketId(){return this.connector.socketId()}registerInterceptors(){typeof Vue<"u"&&Vue!=null&&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,n)=>{this.socketId()&&n.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}let p=null,l=null;const X=()=>{if(p)return p;if(!l)throw new Error("Echo has not been configured. Please call `configureEcho()` with your configuration options before using Echo.");return l.Pusher??(l.Pusher=L),p=new M(l),p},N=()=>l!==null,Q=s=>{l={...{reverb:{broadcaster:"reverb",key:(void 0).VITE_REVERB_APP_KEY,wsHost:(void 0).VITE_REVERB_HOST,wsPort:(void 0).VITE_REVERB_PORT,wssPort:(void 0).VITE_REVERB_PORT,forceTLS:((void 0).VITE_REVERB_SCHEME??"https")==="https",enabledTransports:["ws","wss"]},pusher:{broadcaster:"pusher",key:(void 0).VITE_PUSHER_APP_KEY,cluster:(void 0).VITE_PUSHER_APP_CLUSTER,forceTLS:!0,wsHost:(void 0).VITE_PUSHER_HOST,wsPort:(void 0).VITE_PUSHER_PORT,wssPort:(void 0).VITE_PUSHER_PORT,enabledTransports:["ws","wss"]},"socket.io":{broadcaster:"socket.io",host:(void 0).VITE_SOCKET_IO_HOST},null:{broadcaster:"null"},ably:{broadcaster:"pusher",key:(void 0).VITE_ABLY_PUBLIC_KEY,wsHost:"realtime-pusher.ably.io",wsPort:443,disableStats:!0,encrypted:!0}}[s.broadcaster],...s},p&&(p=null)},y=()=>X(),j=s=>Array.isArray(s)?s:[s],a={},W=s=>{if(a[s.id])return a[s.id].count+=1,a[s.id].connection;const e=Y(s);return a[s.id]={count:1,connection:e},e},Y=s=>{const e=y();return s.visibility==="presence"?e.join(s.name):s.visibility==="private"?e.private(s.name):e.channel(s.name)},z=(s,e=!1)=>{a[s.id]&&(a[s.id].count-=1,!(a[s.id].count>0)&&(delete a[s.id],e?y().leave(s.name):y().leaveChannel(s.id)))},v=(s,e=[],t=()=>{},n=[],r="private")=>{const i=h.ref(t),c=h.ref(!1);h.watch(()=>t,u=>{i.value=u});const d={name:s,id:["private","presence"].includes(r)?`${r}-${s}`:s,visibility:r},f=W(d),b=Array.isArray(e)?e:[e],w=()=>{o()},o=()=>{c.value||(b.forEach(u=>{f.listen(u,i.value)}),c.value=!0)},_=()=>{c.value&&(b.forEach(u=>{f.stopListening(u,i.value)}),c.value=!1)},E=(u=!1)=>{_(),z(d,u)};return h.onMounted(()=>{w()}),h.onUnmounted(()=>{E()}),n.length>0&&h.watch(()=>n,()=>{E(),w()},{deep:!0}),{leaveChannel:E,leave:()=>E(!0),stopListening:_,listen:o,channel:()=>f}},D=(s,e=()=>{},t=[],n=[])=>{const r=v(s,[],e,n,"private"),i=j(t).map(o=>o.includes(".")?[o,o.replace(/\./g,"\\")]:[o,o.replace(/\\/g,".")]).flat(),c=h.ref(!1),d=h.ref(!1),f=o=>{c.value&&(i.length===0||i.includes(o.type))&&e(o)},b=()=>{c.value||(d.value||r.channel().notification(f),c.value=!0,d.value=!0)},w=()=>{c.value&&(c.value=!1)};return h.onMounted(()=>{b()}),{...r,stopListening:w,listen:b}},G=(s,e=[],t=()=>{},n=[])=>v(s,e,t,n,"presence"),J=(s,e=[],t=()=>{},n=[])=>v(s,e,t,n,"public"),Z=(s,e,t=[],n=()=>{},r=[])=>v(`${s}.${e}`,j(t).map(i=>i.startsWith(".")?i:`.${i}`),n,r,"private");exports.configureEcho=Q;exports.echo=y;exports.echoIsConfigured=N;exports.useEcho=v;exports.useEchoModel=Z;exports.useEchoNotification=D;exports.useEchoPresence=G;exports.useEchoPublic=J;
//# sourceMappingURL=index.common.js.map