"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
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 __using = (stack, value, async) => {
  if (value != null) {
    if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
    var dispose, inner;
    if (async) dispose = value[__knownSymbol("asyncDispose")];
    if (dispose === void 0) {
      dispose = value[__knownSymbol("dispose")];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") __typeError("Object not disposable");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    stack.push([async, dispose, value]);
  } else if (async) {
    stack.push([async]);
  }
  return value;
};
var __callDispose = (stack, error, hasError) => {
  var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
    return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
  };
  var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
  var next = (it) => {
    while (it = stack.pop()) {
      try {
        var result = it[1] && it[1].call(it[2]);
        if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
      } catch (e) {
        fail(e);
      }
    }
    if (hasError) throw error;
  };
  return next();
};
var WebSocketInterface_exports = {};
__export(WebSocketInterface_exports, {
  WebSocketInterface: () => WebSocketInterface
});
module.exports = __toCommonJS(WebSocketInterface_exports);
var import_general = require("#general");
var import_types = require("#types");
var import_Api = require("../remote/api/Api.js");
var import_ApiPath = require("../remote/api/ApiPath.js");
var import_RemoteRequest = require("../remote/api/RemoteRequest.js");
var import_RemoteResponse = require("../remote/api/RemoteResponse.js");
var import_RemoteInterface = require("../remote/RemoteInterface.js");
/**
 * @license
 * Copyright 2022-2025 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const LOG_FACILITY = "WebSocket";
class WebSocketInterface extends import_RemoteInterface.RemoteInterface {
  static protocol = "ws";
  #http;
  #mutex = new import_general.Mutex(this);
  async start() {
    this.#http = await this.env.get(import_general.HttpService).create(this.address);
    this.#http.ws = this.#handleConnection.bind(this);
  }
  async stop() {
    await super.stop();
    await this.#http?.close();
  }
  /**
   * Handle HTTP connections.
   *
   * Checks path, upgrades to a WebSocket if the path applies, then processes input messages
   */
  async #handleConnection(request, upgrade) {
    var _stack = [];
    try {
      const address = new import_general.AppAddress(request.url);
      const path = new import_ApiPath.ApiPath(address).toString();
      if (path !== this.root.toString()) {
        return;
      }
      const ws = await import_general.Abort.race(this.abort, await upgrade());
      if (!ws) {
        return;
      }
      const subtask = __using(_stack, import_general.Abort.subtask(this.abort));
      const send = async (local) => {
        await this.#mutex.produce(async () => {
          const message = (0, import_RemoteResponse.RemoteResponse)(local);
          import_Api.Api.logResponse(LOG_FACILITY, message);
          const writer = ws.writable.getWriter();
          try {
            await writer.write((0, import_general.asJson)(message));
          } finally {
            writer.releaseLock();
          }
        });
      };
      for await (let message of import_general.Stream.iterable(ws.readable)) {
        let requestId;
        try {
          message = import_general.Bytes.toString(message);
          let parsed;
          try {
            parsed = JSON.parse(message);
          } catch (e) {
            if (e instanceof SyntaxError) {
              throw new import_types.StatusResponse.InvalidCommandError(`Request parse error: ${e.message}`);
            }
            throw e;
          }
          requestId = parsed?.id;
          const request2 = (0, import_RemoteRequest.RemoteRequest)(parsed);
          await this.#handleRequest(request2, subtask, send);
        } catch (error) {
          import_types.StatusResponseError.accept(error);
          await send({
            kind: "error",
            id: requestId,
            error
          });
        }
      }
      subtask.abort();
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async #handleRequest(request, abort, send) {
    const response = await this.#mutex.produce(() => import_Api.Api.execute(LOG_FACILITY, this.node, request, abort));
    if (response.kind !== "subscription") {
      await send(response);
      return;
    }
    await send({ id: request.id, kind: "ok" });
    this.addWorker(this.#handleSubscription(response.stream, send), "ws subscription handler");
  }
  async #handleSubscription(stream, send) {
    for await (const update of stream) {
      await send(update.js);
    }
  }
}
//# sourceMappingURL=WebSocketInterface.js.map
