"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 ClientSubscription_exports = {};
__export(ClientSubscription_exports, {
  ClientSubscription: () => ClientSubscription
});
module.exports = __toCommonJS(ClientSubscription_exports);
var import_general = require("@matter/general");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_general.Logger.get("ClientSubscription");
class ClientSubscription {
  request;
  peer;
  /**
   * If the subscription has an async worker, this is the promise associated with the worker.
   */
  done;
  #lifetime;
  #closed;
  #abort;
  #isClosed = false;
  #id = -1;
  constructor({ request, peer, closed, abort, lifetime }) {
    this.#lifetime = lifetime.join(this.kind);
    this.request = request;
    this.peer = peer;
    this.#closed = closed;
    this.#abort = new import_general.Abort({
      abort,
      handler: this.close.bind(this)
    });
  }
  get kind() {
    return (0, import_general.decamelize)(this.constructor.name.replace(/Subscription$/, ""), " ");
  }
  get subscriptionId() {
    return this.#id;
  }
  set subscriptionId(id) {
    this.#id = id;
    this.#lifetime.name = [this.kind, import_general.Diagnostic.strong(id)];
  }
  close() {
    if (this.#isClosed) {
      return;
    }
    const closing = this.#lifetime.closing();
    this.#isClosed = true;
    this.#abort();
    this.#closed();
    const unhandledError = (e) => {
      this.logger.error("Unhandled error in subscription to", import_general.Diagnostic.strong(this.peer.toString()), e);
    };
    if (this.done) {
      this.done.finally(() => {
        this.request.closed?.();
        closing[Symbol.dispose]();
      }).catch(unhandledError);
    } else {
      try {
        this.request.closed?.();
      } catch (e) {
        unhandledError(e);
      } finally {
        closing[Symbol.dispose]();
      }
    }
  }
  get abort() {
    return this.#abort;
  }
  get logger() {
    return logger;
  }
}
((ClientSubscription2) => {
  ClientSubscription2.NO_SUBSCRIPTION = -1;
})(ClientSubscription || (ClientSubscription = {}));
//# sourceMappingURL=ClientSubscription.js.map
