94 lines
2.4 KiB
JavaScript
94 lines
2.4 KiB
JavaScript
import axios from 'axios'
|
|
import Echo from 'laravel-echo'
|
|
import Pusher from 'pusher-js'
|
|
import React from 'react'
|
|
import { createRoot, hydrateRoot } from 'react-dom/client'
|
|
|
|
const browserWindow = typeof window !== 'undefined' ? window : null
|
|
const csrfToken = typeof document !== 'undefined'
|
|
? document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
|
|
: null
|
|
|
|
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
|
|
|
|
if (csrfToken) {
|
|
axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken
|
|
}
|
|
|
|
if (browserWindow) {
|
|
browserWindow.axios = axios
|
|
browserWindow.Pusher = Pusher
|
|
}
|
|
|
|
let echoInstance = null
|
|
|
|
function isLoopbackHost(host) {
|
|
return ['127.0.0.1', '0.0.0.0', 'localhost', '::1'].includes(String(host || '').toLowerCase())
|
|
}
|
|
|
|
export function getEcho() {
|
|
if (echoInstance !== null) {
|
|
return echoInstance || null
|
|
}
|
|
|
|
if (!browserWindow) {
|
|
echoInstance = false
|
|
return null
|
|
}
|
|
|
|
const key = import.meta.env.VITE_REVERB_APP_KEY
|
|
if (!key) {
|
|
echoInstance = false
|
|
return null
|
|
}
|
|
|
|
const scheme = import.meta.env.VITE_REVERB_SCHEME || browserWindow.location.protocol.replace(':', '') || 'https'
|
|
const forceTLS = scheme === 'https'
|
|
const configuredHost = import.meta.env.VITE_REVERB_HOST || browserWindow.location.hostname
|
|
const publicHostname = browserWindow.location.hostname
|
|
const useWindowHost = !isLoopbackHost(publicHostname) && isLoopbackHost(configuredHost)
|
|
const resolvedHost = useWindowHost ? publicHostname : configuredHost
|
|
const resolvedPort = useWindowHost
|
|
? Number(forceTLS ? 443 : 80)
|
|
: Number(import.meta.env.VITE_REVERB_PORT || (forceTLS ? 443 : 80))
|
|
const resolvedSecurePort = useWindowHost
|
|
? Number(forceTLS ? 443 : 80)
|
|
: Number(import.meta.env.VITE_REVERB_PORT || 443)
|
|
|
|
echoInstance = new Echo({
|
|
broadcaster: 'reverb',
|
|
key,
|
|
wsHost: resolvedHost,
|
|
wsPort: resolvedPort,
|
|
wssPort: resolvedSecurePort,
|
|
forceTLS,
|
|
enabledTransports: ['ws', 'wss'],
|
|
authEndpoint: '/broadcasting/auth',
|
|
auth: {
|
|
headers: {
|
|
'X-CSRF-TOKEN': csrfToken || '',
|
|
Accept: 'application/json',
|
|
},
|
|
},
|
|
})
|
|
|
|
browserWindow.Echo = echoInstance
|
|
|
|
return echoInstance
|
|
}
|
|
|
|
export function mountInertiaRoot(el, App, props) {
|
|
if (!el) {
|
|
return null
|
|
}
|
|
|
|
const node = React.createElement(App, props)
|
|
const hasServerMarkup = el.childNodes.length > 0 && el.innerHTML.trim() !== ''
|
|
|
|
if (hasServerMarkup) {
|
|
return hydrateRoot(el, node)
|
|
}
|
|
|
|
return createRoot(el).render(node)
|
|
}
|