"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var HttpSharedEndpoint_exports = {};
__export(HttpSharedEndpoint_exports, {
  HttpSharedEndpoint: () => HttpSharedEndpoint
});
module.exports = __toCommonJS(HttpSharedEndpoint_exports);
var import_Logger = require("#log/Logger.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_Logger.Logger.get("HttpSharedEntpoint");
class HttpSharedEndpoint {
  #create;
  #target;
  #instances = /* @__PURE__ */ new Set();
  #isTls;
  constructor(isTls, create) {
    this.#isTls = isTls;
    this.#create = create;
  }
  get isTls() {
    return this.#isTls;
  }
  async use() {
    if (this.#target === void 0) {
      this.#target = this.#createTarget();
    }
    await this.#target;
    const instance = {
      http: void 0,
      ws: void 0,
      close: async () => {
        this.#instances.delete(instance);
        if (!this.#instances.size) {
          try {
            await (await this.#target)?.close();
          } catch (e) {
            logger.error("Error closing HTTP endpoint", e);
          } finally {
            this.#target = void 0;
          }
        }
      }
    };
    this.#instances.add(instance);
    return instance;
  }
  async #createTarget() {
    const target = await this.#create();
    target.http = async (request) => {
      for (const instance of this.#instances) {
        const response = await instance.http?.(request);
        if (response) {
          return response;
        }
      }
    };
    target.ws = async (request, connect) => {
      let connected = false;
      for (const instance of this.#instances) {
        await instance.ws?.(request, async () => {
          connected = true;
          return connect();
        });
        if (connected) {
          break;
        }
      }
    };
    return target;
  }
}
//# sourceMappingURL=HttpSharedEndpoint.js.map
