/**
 * @license
 * Copyright 2022-2025 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { LocalActorContext } from "#behavior/context/server/LocalActorContext.js";
import { NotImplementedError } from "#general";
function Commands(endpoint) {
  const commands = {};
  return new Proxy(commands, {
    get(target, property, receiver) {
      if (Object.hasOwn(commands, property)) {
        return commands[property];
      }
      const behavior = endpoint.behaviors.supported[property];
      if (typeof behavior === "function" && "schema" in behavior) {
        return commands[property] = BehaviorCommands(endpoint, behavior);
      }
      return Reflect.get(target, property, receiver);
    }
  });
}
function BehaviorCommands(endpoint, type) {
  return new Proxy(
    {},
    {
      get(target, property, receiver) {
        if (typeof property !== "string" || property in Object.prototype) {
          return Reflect.get(target, property, receiver);
        }
        return Implementation(endpoint, type, property);
      }
    }
  );
}
function Implementation(endpoint, type, name) {
  return {
    [name](input, context) {
      if (context) {
        return Promise.resolve(invokerFor(context)(input, context));
      }
      const context2 = LocalActorContext.open(`invoke-${name}`, { lifetime: endpoint.construction });
      try {
        return Promise.resolve(context2.resolve(invokerFor(context2)(input, context)));
      } catch (e) {
        return Promise.resolve(context2.reject(e));
      }
      function invokerFor(context3) {
        const agent = endpoint.agentFor(context3);
        const behavior = agent.get(type);
        const method = behavior[name];
        if (typeof method !== "function") {
          throw new NotImplementedError(`Command ${name} is not implemented`);
        }
        return method.bind(behavior);
      }
    }
  }[name];
}
export {
  Commands
};
//# sourceMappingURL=Commands.js.map
