/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { LocalActorContext } from "#behavior/context/server/LocalActorContext.js";
import { asJson } from "#general";
import { DataModelPath } from "#model";
import { StatusResponse, TlvOfModel } from "#types";
class Envelope {
  #supervisor;
  #js;
  #json;
  #tlv;
  constructor({ supervisor, js, json, tlv }) {
    this.#supervisor = supervisor;
    this.#js = js;
    this.#json = json;
    this.#tlv = tlv;
  }
  /**
   * Validate against the schema.  Casts to appropriate types if necessary.
   */
  validate(path) {
    if (!path) {
      path = DataModelPath(this.#supervisor.schema.path);
    }
    this.#js = this.#supervisor.cast(this.#js);
    this.#supervisor.validate?.(this.js, LocalActorContext.ReadOnly, { path });
  }
  /**
   * Convert a {@link js} value to {@link JSON}.
   *
   * This acts as a deep copy and optimizes JSON access.  If TLV becomes a priority then we can make this conversion
   * configurable.
   */
  convertToJson() {
    if (this.#js !== void 0) {
      void this.json;
    }
    this.#js = void 0;
  }
  /**
   * Native JS format.
   */
  get js() {
    if (this.#js === void 0) {
      if (this.#json) {
        try {
          this.#js = JSON.parse(this.#json);
        } catch (e) {
          if (e instanceof SyntaxError) {
            throw new StatusResponse.FailureError(`Unparseable JSON: ${e.message}`);
          }
          throw e;
        }
      } else if (this.#tlv) {
        this.#js = TlvOfModel(this.#supervisor.schema).decode(this.#tlv);
      } else {
        this.#js = null;
      }
    }
    return this.#js;
  }
  /**
   * JSON format.
   */
  get json() {
    if (this.#json === void 0) {
      this.#json = asJson(this.js);
    }
    return this.#json;
  }
  /**
   * Serialized TLV format.
   */
  get tlv() {
    if (this.#tlv === void 0) {
      this.#tlv = TlvOfModel(this.#supervisor.schema).encode(this.#js);
    }
    return this.#tlv;
  }
}
export {
  Envelope
};
//# sourceMappingURL=Envelope.js.map
