"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 ServiceBundle_exports = {};
__export(ServiceBundle_exports, {
  ServiceBundle: () => ServiceBundle
});
module.exports = __toCommonJS(ServiceBundle_exports);
var import_Logger = require("#log/Logger.js");
var import_Set = require("#util/Set.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = new import_Logger.Logger("ServiceBundle");
class ServiceBundle extends import_Set.BasicSet {
  static #default = new ServiceBundle();
  #environments = /* @__PURE__ */ new Set();
  constructor() {
    super();
    this.added.on((factory) => {
      let toRemove;
      for (const ref of this.#environments) {
        const env = ref.deref();
        if (env) {
          this.#deployFactory(factory, env);
        }
        if (env === void 0) {
          if (toRemove === void 0) {
            toRemove = /* @__PURE__ */ new Set();
          }
          toRemove.add(ref);
        }
      }
      if (toRemove) {
        for (const expiredRef of toRemove) {
          this.#environments.delete(expiredRef);
        }
      }
    });
  }
  /**
   * A default bundle for services that should generally deploy in all environments.
   */
  static get default() {
    return this.#default;
  }
  /**
   * Install the bundle into an {@link Environment}.
   *
   * This installs any services that currently comprise the bundle and will install any services added in the future
   * as well.
   */
  deploy(env) {
    for (const factory of this) {
      this.#deployFactory(factory, env);
    }
    this.#environments.add(new WeakRef(env));
  }
  #deployFactory(factory, env) {
    try {
      factory(env);
    } catch (e) {
      let name = "factory";
      if (factory.name) {
        name = `${name} ${factory.name}`;
      }
      logger.error(`Error deploying services for ${name}:`, e);
    }
  }
}
//# sourceMappingURL=ServiceBundle.js.map
