|
| 1 | +import type {} from '@vitejs/devtools' |
| 2 | +import type { DevToolsRpcClient } from '@vitejs/devtools-kit/client' |
| 3 | +import type {} from '../../node/rpc' |
| 4 | +import { useRuntimeConfig } from '#app/nuxt' |
| 5 | +import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client' |
| 6 | +import { reactive, shallowRef } from 'vue' |
| 7 | + |
| 8 | +export const rpcConnectionState = reactive<{ |
| 9 | + connected: boolean |
| 10 | + error: Error | null |
| 11 | +}>({ |
| 12 | + connected: false, |
| 13 | + error: null, |
| 14 | +}) |
| 15 | + |
| 16 | +const rpc = shallowRef<DevToolsRpcClient>(undefined!) |
| 17 | + |
| 18 | +export async function connect() { |
| 19 | + const runtimeConfig = useRuntimeConfig() |
| 20 | + try { |
| 21 | + rpc.value = await getDevToolsRpcClient({ |
| 22 | + baseURL: [ |
| 23 | + '/.devtools/', |
| 24 | + runtimeConfig.app.baseURL, |
| 25 | + ], |
| 26 | + connectionMeta: runtimeConfig.app.connection, |
| 27 | + wsOptions: { |
| 28 | + onConnected: () => { |
| 29 | + rpcConnectionState.connected = true |
| 30 | + }, |
| 31 | + onError: (e) => { |
| 32 | + rpcConnectionState.error = e |
| 33 | + }, |
| 34 | + onDisconnected: () => { |
| 35 | + rpcConnectionState.connected = false |
| 36 | + }, |
| 37 | + }, |
| 38 | + rpcOptions: { |
| 39 | + onGeneralError: (e, name) => { |
| 40 | + rpcConnectionState.error = e |
| 41 | + console.error(`[vite-devtools] RPC error on executing "${name}":`) |
| 42 | + }, |
| 43 | + onFunctionError: (e, name) => { |
| 44 | + rpcConnectionState.error = e |
| 45 | + console.error(`[vite-devtools] RPC error on executing "${name}":`) |
| 46 | + }, |
| 47 | + }, |
| 48 | + }) |
| 49 | + |
| 50 | + rpcConnectionState.connected = true |
| 51 | + } |
| 52 | + catch (e) { |
| 53 | + rpcConnectionState.error = e as Error |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +export function useRpc() { |
| 58 | + return rpc |
| 59 | +} |
0 commit comments