/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { WebSocketServer as wsServer } from 'ws';
import { computeAllowedHosts, hostnameFromHostHeader } from './httpServer';
import { createHttpServer } from './network';
import { debugLogger } from './debugLogger';
let lastConnectionId = 0;
const kConnectionSymbol = Symbol('kConnection');
export const perMessageDeflate = {
    serverNoContextTakeover: true,
    zlibDeflateOptions: {
        level: 3,
    },
    zlibInflateOptions: {
        chunkSize: 10 * 1024
    },
    threshold: 10 * 1024,
};
export class WSServer {
    _wsServer;
    server;
    _delegate;
    // Allowed Host headers for HTTP requests. null disables the check (server bound to a public address).
    _allowedHosts = null;
    constructor(delegate) {
        this._delegate = delegate;
    }
    async listen(port = 0, hostname, path) {
        debugLogger.log('server', `Server started at ${new Date()}`);
        // Default to loopback so the WebSocket RPC is not exposed to the network unless
        // the caller explicitly opts in by passing a host (e.g. '0.0.0.0').
        hostname ??= 'localhost';
        const server = createHttpServer((request, response) => this._onRequest(request, response));
        server.on('error', error => debugLogger.log('server', String(error)));
        this.server = server;
        const wsEndpoint = await new Promise((resolve, reject) => {
            server.listen(port, hostname, () => {
                const address = server.address();
                if (!address) {
                    reject(new Error('Could not bind server socket'));
                    return;
                }
                const urlHost = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;
                const wsEndpoint = typeof address === 'string' ? `${address}${path}` : `ws://${urlHost}:${address.port}${path}`;
                if (typeof address !== 'string')
                    this._allowedHosts = computeAllowedHosts(hostname, address.address);
                resolve(wsEndpoint);
            }).on('error', reject);
        });
        debugLogger.log('server', 'Listening at ' + wsEndpoint);
        this._wsServer = new wsServer({
            noServer: true,
            perMessageDeflate,
        });
        this._wsServer.on('headers', headers => this._delegate.onHeaders(headers));
        server.on('upgrade', (request, socket, head) => {
            const pathname = new URL('http://localhost' + request.url).pathname;
            if (pathname !== path) {
                socket.write(`HTTP/${request.httpVersion} 400 Bad Request\r\n\r\n`);
                socket.destroy();
                return;
            }
            if (this._allowedHosts && !this._isAllowedOrigin(request.headers.origin)) {
                socket.write(`HTTP/${request.httpVersion} 403 Forbidden\r\n\r\n`);
                socket.destroy();
                return;
            }
            const upgradeResult = this._delegate.onUpgrade(request, socket);
            if (upgradeResult) {
                socket.write(upgradeResult.error);
                socket.destroy();
                return;
            }
            this._wsServer.handleUpgrade(request, socket, head, ws => this._wsServer.emit('connection', ws, request));
        });
        this._wsServer.on('connection', (ws, request) => {
            debugLogger.log('server', 'Connected client ws.extension=' + ws.extensions);
            const url = new URL('http://localhost' + (request.url || ''));
            const id = String(++lastConnectionId);
            debugLogger.log('server', `[${id}] serving connection: ${request.url}`);
            const connection = this._delegate.onConnection(request, url, ws, id);
            ws[kConnectionSymbol] = connection;
        });
        return wsEndpoint;
    }
    _onRequest(request, response) {
        if (this._allowedHosts) {
            const host = request.headers.host?.toLowerCase();
            const hostname = host ? hostnameFromHostHeader(host) : undefined;
            if (!hostname || !this._allowedHosts.has(hostname)) {
                response.statusCode = 403;
                response.end();
                return;
            }
        }
        this._delegate.onRequest(request, response);
    }
    _isAllowedOrigin(origin) {
        if (!origin)
            return true;
        try {
            const hostname = new URL(origin).hostname.toLowerCase();
            const bracketed = hostname.includes(':') ? `[${hostname}]` : hostname;
            return this._allowedHosts.has(hostname) || this._allowedHosts.has(bracketed);
        }
        catch {
            return false;
        }
    }
    async close() {
        const server = this._wsServer;
        if (!server)
            return;
        debugLogger.log('server', 'closing websocket server');
        const waitForClose = new Promise(f => server.close(f));
        // First disconnect all remaining clients.
        await Promise.all(Array.from(server.clients).map(async (ws) => {
            const connection = ws[kConnectionSymbol];
            if (connection)
                await connection.close();
            try {
                ws.terminate();
            }
            catch (e) {
            }
        }));
        await waitForClose;
        debugLogger.log('server', 'closing http server');
        if (this.server)
            await new Promise(f => this.server.close(f));
        this._wsServer = undefined;
        this.server = undefined;
        debugLogger.log('server', 'closed server');
    }
}
//# sourceMappingURL=wsServer.js.map