"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ISocketWithClientAuth = void 0;
exports.connectSingleUseISocket = connectSingleUseISocket;
const socket_js_1 = require("./socket.js");
const tracedSocket_js_1 = require("./tracedSocket.js");
const util_js_1 = require("./util.js");
// a subclass of ISocket that sends an auth token on the first request
// this is useful for client-side sockets that need to authenticate
class ISocketWithClientAuth extends tracedSocket_js_1.TracedSocket {
    authorization;
    authorizationVersion = 0;
    hasSentAuth = false;
    constructor(ws, authorization, requestHandlers, globalMiddlewares, tracer, options) {
        super(ws, requestHandlers, globalMiddlewares, tracer, options);
        this.authorization = authorization;
    }
    // override `request` from the base class to send `authorization` when appropriate
    async request(method, params) {
        // only send `authorization` on the first request
        const authorizationVersion = this.authorizationVersion;
        const authorization = this.hasSentAuth ? undefined : this.authorization;
        const result = await super.request(method, params, authorization);
        if (this.authorizationVersion === authorizationVersion) {
            this.hasSentAuth = true;
        }
        return result;
    }
    /**
     * Updates the authorization token for this socket.
     * This is useful for long-lived connections where the token may expire and need to be refreshed.
     *
     * @param newAuthorization - The new authorization token (e.g., "Bearer <token>") or undefined to clear it
     */
    setAuthorization(newAuthorization) {
        this.authorization = newAuthorization;
        this.authorizationVersion++;
        this.hasSentAuth = false;
    }
}
exports.ISocketWithClientAuth = ISocketWithClientAuth;
/**
 * Creates a new socket for a set of operations, without any retry behavior
 * If the requests fail, the promise will reject.
 */
async function connectSingleUseISocket(wsUrl, authorization, requestHandlers, globalMiddlewares, tracer, options) {
    const ws = await (0, util_js_1.connectWebSocket)(wsUrl);
    const isocket = new ISocketWithClientAuth(ws, authorization, requestHandlers, globalMiddlewares, tracer, options);
    return (0, socket_js_1.createISocketClient)(isocket);
}
//# sourceMappingURL=socketWithClientAuth.js.map