import zlib from 'zlib';
import { buffer as stream_to_buffer, text as stream_to_text } from 'stream/consumers';
import { isReadable } from 'stream';
import { t } from "./i18n/instance.js";
import { rethrow } from "./prototype.js";
import { message_symbol, pack, parse } from "./io.js";
import { inspect, assert, genid, delay, Lock, pipe_with_error, map_values, unique, timeout, check, colored } from "./utils.js";
export const WebSocketConnecting = 0;
export const WebSocketOpen = 1;
export const WebSocketClosing = 2;
export const WebSocketClosed = 3;
export const websocket_states = ['connecting', 'open', 'closing', 'closed'];
export var MyProxy;
(function (MyProxy) {
    MyProxy["socks5"] = "http://127.0.0.1:10080";
    MyProxy["whistle"] = "http://localhost:8899";
    MyProxy["work"] = "http://localhost:10090";
})(MyProxy || (MyProxy = {}));
// ------------------------------------ fetch, request
export const cookies = {
    store: null,
    jar: null,
    async init() {
        if (this.jar)
            return;
        const { MemoryCookieStore, CookieJar } = await import('tough-cookie');
        this.jar = new CookieJar(this.store = new MemoryCookieStore());
    },
};
/** 对于 request() 函数来说无意义的 headers，会自动过滤掉 */
const drop_request_headers = new Set([
    // : 开头的 key
    // sec-*
    'accept-charset',
    'connection',
    'content-length',
    'keep-alive',
    'trailer',
    'transfer-encoding',
    'upgrade',
]);
let agents = {};
async function request_retry(url, options, _timeout, retries = 0, count = 0, print) {
    let { default: undici, request: undici_request } = await import('undici');
    undici_request ??= undici.request;
    try {
        if (_timeout > 0) {
            // 设置给 undici 设置 timeout, signal 不一定管用，还是得自己兜底
            options.signal = AbortSignal.timeout(_timeout);
            return await timeout(_timeout + 300, // 为 undici 兜底
            undici.request(url, options), undefined, print.timeout && count >= retries // 只打印最后一次超时的错误，避免太多冗余输出
            );
        }
        else
            return await undici.request(url, options);
    }
    catch (error) {
        if (error.name === 'TimeoutError')
            if (count < retries) {
                const duration = 2 ** count;
                if (print.retry)
                    console.log(`${`等待 ${duration} 秒后重试请求 (已尝试 ${count + 1} 次) ··`.yellow}  ${url.toString().blue.underline}`);
                await delay(1000 * duration);
                return request_retry(url, options, _timeout, retries, count + 1, print);
            }
            else {
                const seconds = _timeout / 1000;
                throw Object.assign(new Error(`请求超过 ${seconds.toFixed(seconds < 1 ? 1 : 0)} 秒等待时间: ${url.toString()}`), { name: 'TimeoutError' });
            }
        else
            throw error;
    }
}
export class StatusCodeError extends Error {
    name = 'StatusCodeError';
    constructor(status, url) {
        super(`状态码 ${status}: ${url}`);
        Object.defineProperties(this, {
            status: { value: status }
        });
    }
}
export async function request(url, options = {}) {
    let { default: undici, ProxyAgent: UndiciProxyAgent, FormData } = await import('undici');
    UndiciProxyAgent ??= undici.ProxyAgent;
    FormData ??= undici.FormData;
    const { Cookie } = await import('tough-cookie');
    await cookies.init();
    const { queries, headers: _headers, body, type = 'application/json', timeout = 5 * 1000, auth, cookies: _cookies, raw = false, full = false, redirect = 'follow', decode = true, print = {
        timeout: true,
        retry: true
    } } = options;
    let { method, retries, encoding, proxy, } = options;
    url = new URL(url);
    if (queries)
        for (const key in queries) {
            let value = queries[key];
            if (typeof value === 'boolean')
                value = value ? '1' : '0';
            url.searchParams.append(key, value);
        }
    const urlstr = url.toString();
    if (body !== undefined && !method)
        method = 'POST';
    if (retries === true)
        retries = 2;
    // --- headers, http/2 开始都用小写的 headers
    let headers = {
        'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja-JP;q=0.6,ja;q=0.5',
        'accept-encoding': 'gzip, deflate, br',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
        'sec-ch-ua-platform': '"Windows"',
        'sec-ch-ua-platform-version': '"15.0.0"',
    };
    if (body !== undefined)
        headers['content-type'] = type;
    if (auth)
        headers.authorization = auth.type === 'basic' ?
            `Basic ${`${auth.username}:${auth.password}`.to_base64()}`
            :
                `Bearer ${auth.token}`;
    const request_cookies = unique([
        ...cookies.jar.getCookiesSync(urlstr),
        ..._cookies ?
            Object.entries(_cookies).map(([key, value]) => new Cookie({ key, value }))
            :
                []
    ], 'key');
    if (request_cookies.length)
        headers.cookie = request_cookies.map(cookie => cookie.cookieString())
            .join('; ');
    if (_headers) {
        check(Object.getPrototypeOf(_headers)?.constructor.name !== 'Headers');
        for (const key in _headers)
            // 可能在 http/2 的 response 中会有这样开头的保留 headers, 在透传时忽略比较好
            if (!key.startsWith(':') && !key.startsWith('sec-') && !drop_request_headers.has(key)) {
                check(key === key.toLowerCase(), `传入 request 的 headers 参数中 key 应该都是小写的，实际为 ${key}`);
                headers[key] = _headers[key];
            }
    }
    let undici_options = {
        ...method ? { method } : {},
        dispatcher: await (async () => {
            const { default: { 
            // @ts-ignore
            ProxyAgent, Agent, interceptors } } = await import('undici');
            if (proxy === true)
                proxy = MyProxy.socks5;
            return agents[`${proxy || 'direct'}.${redirect}`] ??= (() => {
                let dispatcher = proxy ? new ProxyAgent({ uri: proxy }) : new Agent();
                if (redirect === 'follow')
                    dispatcher = dispatcher.compose(
                    // todo: 强制手动处理重定向，来正确处理 cookie ?
                    interceptors.redirect({ maxRedirections: 5 }));
                return dispatcher;
            })();
        })(),
        // 下面这些 timeout 都不是总的时间
        headersTimeout: timeout,
        // 从收完 headers 开始算
        bodyTimeout: timeout,
        // @ts-ignore 没有类型声明，实际可用
        connectTimeout: timeout,
        headers,
        // --- body
        body: (() => {
            if (body === undefined)
                return;
            if (typeof body?.read === 'function' && isReadable(body))
                return body;
            switch (type) {
                case 'application/json': // 可能的类型 string | Record<string, any> | Uint8Array
                    if (typeof body === 'string')
                        return body;
                    if (body instanceof Uint8Array)
                        return body;
                    assert(!(body instanceof ArrayBuffer || ArrayBuffer.isView(body)));
                    return JSON.stringify(body);
                case 'application/x-www-form-urlencoded':
                    return (body instanceof URLSearchParams ? body : new URLSearchParams(body)).toString();
                case 'multipart/form-data':
                    if (body instanceof FormData)
                        return body;
                    else {
                        let form = new FormData();
                        for (const key in body) {
                            let value = body[key];
                            form.set(key, value);
                        }
                        return form;
                    }
            }
        })(),
    };
    let response;
    try {
        const { statusCode: status, headers: _headers, body: _body } = await request_retry(url, undici_options, timeout, retries, 0, print);
        // 处理 cookie，自动保存到 cookie jar
        let _cookies = _headers['set-cookie'] || [];
        if (typeof _cookies === 'string')
            _cookies = [_cookies];
        _cookies.map(cookie => cookies.jar.setCookieSync(cookie, urlstr, { ignoreError: true }));
        const headers = map_values(_headers, value => Array.isArray(value) ? value.join(', ') : (value || ''));
        // UndiciResponse.body 没有自动根据 content-encoding 来解码，这里手动处理并替换 body 为解码后的 stream
        let body = _body;
        const content_encoding = headers['content-encoding']?.trim().toLowerCase();
        if (decode && content_encoding) {
            assert(!content_encoding.includes(','));
            switch (content_encoding) {
                case 'gzip':
                case 'x-gzip':
                    body = pipe_with_error(_body, zlib.createGunzip({
                        // Be less strict when decoding compressed responses, since sometimes
                        // servers send slightly invalid responses that are still accepted
                        // by common browsers.
                        // Always using Z_SYNC_FLUSH is what cURL does.
                        flush: zlib.constants.Z_SYNC_FLUSH,
                        finishFlush: zlib.constants.Z_SYNC_FLUSH
                    }));
                    break;
                case 'deflate':
                    body = pipe_with_error(_body, zlib.createInflate());
                    break;
                case 'br':
                    body = pipe_with_error(_body, zlib.createBrotliDecompress());
                    break;
                default:
                    throw new Error(`不支持 content-encoding: ${content_encoding.quote()} 的 http 请求`);
            }
        }
        response = {
            status,
            headers,
            body
        };
        if (!((200 <= status && status <= 299) || status === 304 || (redirect === 'manual' && 300 <= status && status < 400)))
            throw new StatusCodeError(status, url.toString());
    }
    catch (error) {
        response ??= error.response;
        throw Object.defineProperties(error, {
            url: { value: url },
            options: { value: options },
            ...response ? {
                response: {
                    value: {
                        status: response.status,
                        headers: response.headers,
                        body: decode
                            ? await stream_to_text(response.body)
                            : await stream_to_buffer(response.body),
                    }
                }
            } : {},
            [inspect.custom]: {
                value(depth, options, inspect) {
                    const { colors } = options;
                    const c = (str, color) => colored(str, color, colors);
                    let s = '\n' +
                        `${c(method || 'GET', 'red')} ${c(c(urlstr, 'blue'), 'underline')}\n`;
                    if (queries && Object.keys(queries).length)
                        s += c('请求参数:\n', 'yellow') +
                            inspect(queries, options).ensure_end();
                    if (body !== undefined)
                        s += c('请求体:\n', 'yellow') +
                            inspect(body, options).ensure_end();
                    if (response) {
                        s += c('响应头:\n', 'yellow');
                        for (const key in response.headers) {
                            const value = response.headers[key];
                            s += `${key}: ${value}\n`;
                        }
                        if (error.response.body)
                            s += c('响应体:\n', 'yellow') +
                                error.response.body.toString().ensure_end();
                    }
                    s += inspect(error, { ...options, customInspect: false });
                    return s;
                }
            }
        });
    }
    if (raw)
        return response;
    const body_ = await (async () => {
        if (!response.body)
            return encoding === 'binary' ? Buffer.from([]) : '';
        if (encoding === 'binary')
            return stream_to_buffer(response.body);
        encoding ||= /charset=(.*)/.exec(response.headers['content-type'])?.[1] || 'utf-8';
        if (/utf-?8/i.test(encoding))
            return stream_to_text(response.body);
        return new TextDecoder(encoding)
            .decode(await stream_to_buffer(response.body));
    })();
    return full ? {
        status: response.status,
        headers: response.headers,
        body: body_
    }
        :
            body_;
}
/** 发起 http 请求并将响应体作为 json 解析 */
export async function request_json(url, options) {
    const body = await request(url, options);
    if (!body)
        return;
    try {
        return JSON.parse(body);
    }
    catch (error) {
        console.error(body);
        throw error;
    }
}
export class WebSocketConnectionError extends Error {
    name = 'WebSocketConnectionError';
    // 这里不保留 websocket 引用，防止循环引用导致 JSON 序列化失败
    url;
    protocols;
    event;
    type;
    address;
    errno;
    port;
    syscall;
    /** close 事件时为 close code, error 事件为 error code */
    code;
    reason;
    constructor(url, protocols, event, message = '') {
        super(`${url}${protocols ? ' ' + protocols.join(', ').bracket() : ''} ${t('连接出错了')}. ${message}`);
        this.url = url;
        this.protocols = protocols;
        this.event = event;
        this.type = event.type;
        if (this.type === 'error') {
            const { error } = event;
            this.address = error.address;
            this.code = error.code;
            this.errno = error.errno;
            this.port = error.port;
            this.syscall = error.syscall;
            this.reason = error.reason;
            this.stack = `${this.name}: ${this.message}\n` +
                error.stack.slice(error.stack.indexOf('\n') + 1) + '\n';
        }
        else {
            this.code = event.code;
            this.reason = event.reason;
        }
    }
}
let websocket_proxy_agents = {};
/** 连接 websocket url, 设置各种事件监听器。在 open 事件后 resolve, 返回 websocket
    遇到 error 时会创建 WebSocketConnectionError:
        - reject 掉返回的 promise (若此时未 settle)
        - 作为参数调用 on_error (已 settle 且有 on_error 回调)
    可以用 WebSocket.bufferedAmount 来显示大消息的发送进度
    https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/bufferedAmount
    - url
    - options:
        - protocols?
        - max_payload?: `8 GB`
        - on_message: 根据 websocket frame 的 opcode 不同 (text frame 或 binary frame)，event 中的 data 对应为 ArrayBuffer 或者 string
          https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
        - on_error?: 在 websocket 出错和非正常关闭 (close, error 事件) 时都调用，可以根据 error.type 来区分，error 的类型是 WebSocketConnectionError，
            type 为 'close' 时有 code 和 reason 属性
        - on_close?: 和 websocket 的 'close' 事件不相同，只在正常关闭 (close code 为 1000) 时才调用，否则都会调用 on_error
            https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
        - print?: 是否打印连接、关闭信息 */
export async function connect_websocket(url, { protocols, max_payload = 2 ** 33, // 8 GB
on_message, on_error, on_close, proxy, print = true, }) {
    const { WebSocket } = await import('ws');
    const { HttpsProxyAgent } = await import('https-proxy-agent');
    let websocket = new WebSocket(url, protocols, {
        maxPayload: max_payload,
        skipUTF8Validation: true,
        allowSynchronousEvents: true,
        ...proxy ? {
            agent: websocket_proxy_agents[proxy] ??= new HttpsProxyAgent(proxy)
        } : {}
    });
    // https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob/39951543
    websocket.binaryType = 'arraybuffer';
    return new Promise((resolve, reject) => {
        let settled = false;
        websocket.addEventListener('open', event => {
            if (print)
                console.log(websocket.url +
                    (websocket.protocol ? ' ' + websocket.protocol.bracket() : '') +
                    t(' 已连接'));
            settled = true;
            resolve(websocket);
        });
        websocket.addEventListener('close', event => {
            // https://blog.insiderattack.net/promises-next-ticks-and-immediates-nodejs-event-loop-part-3-9226cbe7a6aa
            // error 事件会先发生，然后 reject(error) 被执行，此时还未轮到外层的 await connect_websocket 执行（在微任务队列中），
            // 接着马上 close 事件也被调用，此时 settled，马上调用了 on_error 函数，弄乱了顺序
            // error 的错误信息比较多，而且通过 await 得到的栈也比较清晰，这里延后调用 on_close 和 on_error，放到微任务队列之后的 timers 队列中
            setTimeout(() => {
                if (event.code === 1000) { // 正常关闭
                    if (on_close)
                        on_close(event, websocket);
                    else if (print)
                        console.log(`${websocket.url} ${t('已正常关闭')}`);
                }
                else { // 异常关闭，认为发生了错误，进行错误处理
                    // websocket close 事件时已经 settled
                    const error = new WebSocketConnectionError(websocket.url, protocols, event, `${t('连接被关闭')}, code: ${event.code}${event.reason ? `, ${t('原因')}: ${event.reason}` : ''}`);
                    if (on_error)
                        on_error(error, websocket);
                    else // 既然用户不传 on_error, 就当 unhandled error 抛出来
                        throw error;
                }
            });
        });
        websocket.addEventListener('error', event => {
            const error = new WebSocketConnectionError(websocket.url, protocols, event, event.error?.message);
            if (settled)
                if (on_error)
                    on_error(error, websocket);
                else // 既然用户不传 on_error, 就当 unhandled error 抛出来
                    throw error;
            else {
                settled = true;
                reject(error);
            }
        });
        websocket.addEventListener('message', event => {
            on_message(event.data, websocket);
        });
    });
}
/** 通过创建 remote 对象对 websocket rpc 进行抽象
    创建 remote 对象时传入 funcs 注册处理函数，使得对端能通过 (rpc message).func 调用
    使用 remote.handle 方法处理对端发来的 websocket message，对于 websocket 连接接收方需要手动绑定 websocket message 事件到 remote.handle
    使用 remote.call 进行一元 rpc
    使用 remote.send 结合 message.id 进行复杂 rpc
    创建后等到首个 remote.call 或 remote.send 时自动建立实际 websocket 连接
    rpc 状态与底层连接的状态无关，如果是传入 url 创建的 remote 实例，remote.send 时检测到断线会自动建立新的 websocket 连接
    
    @example
    // Zero 继承自 Remote 并通过 call 实现了一些方法
    let zero = new Zero({ local: true })
    
    // 一元 rpc
    await zero.repl_ts('1234')
    
    // 订阅流
    const id = genid()
    
    zero.handlers.set(id, ({ data: [chunk] }: Message<[Uint8Array]>) => {
        term.write(chunk)
    })
    
    zero.send({ id, func: 'subscribe_stdio' }) */
export class Remote {
    /** 在构造 Remote 时, this.initiator = Boolean(url || websocket)
        - true:  作为 websocket 连接发起方
        - false: 作为 websocket 连接接收方 */
    initiator;
    /** 作为 websocket 连接发起方，对端的 url 地址 */
    url;
    /** 作为 websocket 连接发起方有 websocket lock */
    lwebsocket;
    /** websocket 连接发起方，接收方，都能被对端通过 (rpc message).func 调用的 rpc 函数 */
    funcs;
    /** map<id, message handler>: 通过 (rpc message).id 找到对应的 handler
        一元 rpc 接收方不需要设置 handlers, 发送方需要 */
    handlers = new Map();
    keeper;
    /** `true` 是否打印连接信息、错误信息 */
    print = true;
    /** `false` 打印所有交互的 rpc messages */
    verbose = false;
    first_error = true;
    keeping = false;
    reconnecting = false;
    disconnected = false;
    /** 作为 websocket 连接发起方，传入 url 或 websocket，定义远程 Remote
        作为 websocket 连接接收方，不传 url 和 websocket，定义本地 Remote */
    constructor({ url, funcs, print, verbose, websocket, keeper, on_error, } = {}) {
        check(!(url && websocket), '构建 Remote 时 url 和 websocket 最多只能传一个');
        this.initiator = Boolean(url || websocket);
        if (url)
            this.url = url;
        check(!funcs?.echo);
        this.funcs = {
            ...funcs,
            echo({ data }) {
                return data;
            }
        };
        if (print !== undefined)
            this.print = print;
        if (verbose !== undefined)
            this.verbose = verbose;
        if (on_error)
            this.on_error = on_error;
        if (this.initiator)
            this.lwebsocket = new Lock(websocket || null);
        if (keeper) {
            check(this.initiator && url);
            this.keeper = {
                reconnect_interval: 5000,
                heartbeat_interval: 1000 * 60,
                error_delay: 2000,
                ...keeper
            };
        }
    }
    /** 统一处理首次连接和连接后的 websocket 错误 */
    _on_error = (error, websocket) => {
        if (this.keeper && !this.reconnecting && !this.disconnected) // 在一段时间后调度错误重连
            (async () => {
                this.reconnecting = true;
                const { error_delay, reconnect_interval } = this.keeper;
                if (this.first_error) {
                    this.first_error = false;
                    await delay(error_delay);
                }
                else
                    await delay(reconnect_interval);
                this.reconnecting = false;
                if (!this.disconnected)
                    try {
                        await timeout(3000, this.connect(), undefined, this.print);
                        this.first_error = true;
                    }
                    catch (error) {
                        // 重连失败的错误这里需要简单打印下，_on_error 不会打印，这里也不继续往上抛了
                        if (this.print)
                            console.log(error.message);
                        // 重连由 this.connect 里面调用 this._on_error 处理
                    }
            })();
        this.on_error(error, websocket);
    };
    _on_message = (data, websocket) => {
        this.handle(new Uint8Array(data), websocket);
    };
    /** 使用者自定义的在 websocket 连接出错时，或者 handlers 出错时的处理 */
    on_error(error, websocket) {
        // 使用者未定义 Remote 如何处理 error 时，一般来说直接忽略即可，因为 handlers 中报错了也会返回给对端
        if (this.print)
            console.log(error && error instanceof WebSocketConnectionError ? error.message : error);
        // 这里继续往上层抛没有太大意义，上面一般都是 websocket on_message 这些
    }
    /** 幂等，保证 websocket 已连接，否则抛出异常
        一般情况不需要手动调用，在其它方法中会自动调用这个方法，除非需要手动建立 websocket 连接并确保成功
        连接断开后，通过传入 url 参数构造的 remote 实例会自动创建新的 websocket 连接，而通过传入 websocket 参数构造的实例只会检查连接状态，在断开时抛出异常
        作为 websocket 连接发起方，不需要传入 websocket
        作为 websocket 连接接收方，需要传入使用的 websocket 连接，确保这个这个连接的状态 */
    async connect(websocket) {
        if (this.initiator)
            if (this.lwebsocket.resource?.readyState === WebSocketOpen)
                return;
            else if (!this.url)
                throw new Error('创建 Remote 时传入的 websocket 连接已断开');
            else {
                let reconnected = false;
                // 假设有多个请求想要并发连接 websocket, 且此时 websocket 是断开的状态
                // 应该排队依次连接，而不是后续的连接直接使用第一次连接的 promise，后续调用还是应该尝试重连（不止连接一次）
                await this.lwebsocket.request(async (websocket) => {
                    // 保存的 rpc 状态在 this.handlers, 与 websocket 无关，因此即使断开重连也不影响 rpc 的运行，即
                    // 底层连接断开后自动重连对上层应该是无感知的，除非再次连接时失败
                    if (websocket?.readyState === WebSocketOpen)
                        return;
                    // 重连
                    try {
                        this.lwebsocket.resource = await connect_websocket(this.url, {
                            on_message: this._on_message,
                            on_error: this._on_error,
                            print: this.print
                        });
                        reconnected = true;
                    }
                    catch (error) {
                        this._on_error(error);
                        throw error;
                    }
                });
                if (this.keeper) {
                    const { heartbeat_interval, func, args } = this.keeper;
                    // 首次连接成功时，开始心跳保活
                    if (!this.keeping) {
                        this.keeping = true;
                        (async () => {
                            for (;;) {
                                await delay(heartbeat_interval);
                                if (this.disconnected)
                                    break;
                                if (!this.reconnecting)
                                    try {
                                        await timeout(1000 * 2, this.call('echo'), undefined, this.print);
                                    }
                                    catch (error) {
                                        if (this.print)
                                            console.log(error.message);
                                        this._on_error(error);
                                    }
                            }
                        })();
                    }
                    if (reconnected && func)
                        await this.call(func, args);
                }
            }
        else if (websocket.readyState !== WebSocketOpen)
            throw new Error('传入的 websocket 连接已断开');
    }
    /** 作为 websocket 连接发起方手动关闭到对端的 websocket 连接 */
    disconnect() {
        this.disconnected = true;
        this.lwebsocket.resource?.close(1000);
    }
    /** 发送 message 到对端 remote
        作为 websocket 连接发起方，不需要传入 websocket
        作为 websocket 连接接收方，必传 websocket 参数
        发送或连接出错时自动清理 message.id 对应的 handler */
    async send(message, websocket) {
        if (this.verbose)
            console.log('remote.send:', message);
        try {
            await this.connect(websocket);
            message[message_symbol] = true;
            (websocket || this.lwebsocket.resource).send(pack(message));
        }
        catch (error) {
            if (message.id)
                this.handlers.delete(message.id);
            throw error;
        }
    }
    /** 处理接收到的 websocket message 并解析, 根据 message.id 或 message.func 分发到对应的 handler 进行处理，
        handler 处理完成后:
        - 传了 func: 调用函数的情况下 (通常是一元 rpc)，总是将返回值包装为 message 回传
        - 未传 func: 通过 id 调用，如果 handler 返回非 undefined 的值，也包装为 message 回传
        
        如果 message.done == true 则对端指示当前 remote 可以清理 handler
        使用 Uint8Array 作为参数更灵活 https://stackoverflow.com/a/74505197/7609214
        这个方法一般不会抛出错误，也不需要 await，一般在 websocket on_message 时使用 */
    async handle(data, websocket) {
        let message;
        try {
            check(data[0] === 0xcc, 'message 格式错误');
            message = parse(data);
        }
        catch (error) {
            this.on_error(error);
            return;
        }
        const { id, func, done } = message;
        if (this.verbose)
            console.log('remote.handle:', message);
        let handler;
        if (func) {
            handler = this.funcs[func];
            // 传了 func 调用函数的情况下，如果 message.data 为 undefined, 默认为 [ ]
            if (message.data === undefined)
                message.data = [];
        }
        else {
            handler = this.handlers.get(id);
            if (done && handler)
                this.handlers.delete(id);
        }
        try {
            if (handler) {
                const data = await handler(message, websocket);
                if (func || data !== undefined)
                    await this.send({ id, data }, websocket);
            }
            else
                throw message.error || new Error(`找不到 rpc handler: ${func ? `func: ${func.quote()}` : `id: ${id}`}`);
        }
        catch (error) {
            // handler 出错并不意味着 rpc 一定会结束，可能 error 是运行中的正常数据，所以不能清理 handler
            if (websocket.readyState === WebSocketOpen &&
                !message.error // 防止无限循环往对方发送 error, 只有在对方无错误时才可以发送
            )
                await this.send({ id, error, /* 不能设置 done 清理对面 handler, 理由同上 */ }, websocket);
            // 这里继续往上层抛没有太大意义，上面一般都是 websocket on_message 这些，交给自定义或默认的 on_error 处理
            this.on_error(error);
        }
    }
    /** 调用对端 remote 中的 func, 只适用于最简单的一元 rpc (请求, 响应)
        作为 websocket 连接发起方，不需要传入 websocket
        作为 websocket 连接接收方，必传 websocket 参数  */
    async call(func, args, websocket) {
        return new Promise(async (resolve, reject) => {
            const id = genid();
            this.handlers.set(id, ({ error, data }) => {
                if (error)
                    reject(error);
                else
                    resolve(data);
                this.handlers.delete(id);
            });
            try {
                await this.send({ id, func, data: args }, websocket); // 不需要 done: true, 因为对面的 remote.handlers 中不会有这个 id 的 handler
            }
            catch (error) {
                reject(error);
            }
        });
    }
    /** 调用对端 remote 中的 func, 开始订阅并接收连续的消息 (订阅流)
        - func: 订阅处理函数
        - on_data: 接收开始订阅后的数据
        - options?:
            - on_error?: 处理开始订阅后的错误
            - websocket?: 作为 websocket 连接接收方，必传 websocket 参数 */
    async subscribe(func, on_data, { on_error = rethrow, websocket } = {}) {
        const id = genid();
        let psubscribed = new Promise((resolve, reject) => {
            let first = true;
            this.handlers.set(id, ({ error, data }) => {
                if (error) {
                    if (first) {
                        first = false;
                        this.handlers.delete(id);
                        reject(error);
                    }
                    else
                        on_error(error);
                    return;
                }
                if (first) {
                    first = false;
                    resolve({ id, data: data });
                    return;
                }
                on_data(data);
            });
        });
        try {
            await this.send({ id, func }, websocket);
        }
        catch (error) {
            this.handlers.delete(id);
            throw error;
        }
        return psubscribed;
    }
}
/** 为连接到 server 的 client 创建 RemoteClient，以便后续调用 client 中方法 */
export class RemoteClient {
    remote;
    websocket;
    constructor(remote, websocket) {
        this.remote = remote;
        this.websocket = websocket;
    }
    /** 调用 client 中的 func, 只适用于最简单的一元 rpc (请求, 响应) */
    async call(func, args) {
        return this.remote.call(func, args, this.websocket);
    }
    /** 发送 message 到 client
        发送或连接出错时自动清理 message.id 对应的 handler */
    async send(message) {
        return this.remote.send(message, this.websocket);
    }
    [inspect.custom]() {
        const { [inspect.custom]: _inspect, websocket, remote, ...others } = this;
        return {
            remote: '<Remote(receiver)>',
            websocket: `<WebSocket(${websocket_states[websocket.readyState]})>`,
            ...others
        };
    }
}
//# sourceMappingURL=net.js.map