import type { HttpClient } from './index.js'; import type { HttpClientConfig } from './options.js'; /** 规格化 URL */ function normalizeUrl(url: string, config: HttpClientConfig): string { if (!url) url = config.apiUrl; if (url.startsWith('ws://') || url.startsWith('wss://')) { return url; } if (url.startsWith('http://') || url.startsWith('https://')) { return url.replace(/^http/, 'ws'); } if (url.startsWith('/')) { return `${config.apiUrl}${url}`.replace(/^http/, 'ws'); } throw new Error(`Url must starts with '/', 'ws://', 'wss://', 'http://' or 'https://'`); } /** 获取构造函数 */ function getConstructor(config: HttpClientConfig): typeof WebSocket { return config.webSocket ?? WebSocket; } /** 建立 WebSocket */ export type Ws = (url: string, protocols?: string | string[]) => WebSocket; /** 建立 WebSocket */ export function createWs(client: HttpClient): Ws { return (url, protocols) => { const { config } = client; const wsUrl = normalizeUrl(url, config); const ws = new (getConstructor(config))(wsUrl, protocols); return ws; }; }