const isBrowser = (typeof process === 'undefined') || 
  (typeof window !== 'undefined' && typeof window.document !== 'undefined') || 
  (typeof process !== 'undefined' && process?.env?.BROWSER === 'true');
const chantHttpToWs = (url: string) => {
  if (url.startsWith('http://')) {
    return url.replace('http://', 'ws://');
  }
  if (url.startsWith('https://')) {
    return url.replace('https://', 'wss://');
  }
  return url;
};
type WebSocketOptions = {
  /**
   * 是否拒绝不安全的证书, in node only
   */
  rejectUnauthorized?: boolean;
  headers?: Record<string, string>;
  [key: string]: any;
};
export const initWs = async (url: string, options?: WebSocketOptions) => {
  let ws: WebSocket;
  url = chantHttpToWs(url);
  if (isBrowser) {
    ws = new WebSocket(url);
  } else {
    const WebSocket = await import('ws').then((module) => module.default);
    const { rejectUnauthorized, headers, ...rest } = options || {};
    ws = new WebSocket(url, {
      rejectUnauthorized: rejectUnauthorized ?? true,
      headers: headers,
      ...rest,
    }) as any;
  }
  return ws;
};
export interface EventEmitterOptions {
  /**
   * Enables automatic capturing of promise rejection.
   */
  captureRejections?: boolean | undefined;
}
