"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 DatasourceCache_exports = {};
__export(DatasourceCache_exports, {
  DatasourceCache: () => DatasourceCache
});
module.exports = __toCommonJS(DatasourceCache_exports);
var import_Datasource = require("#behavior/state/managed/Datasource.js");
var import_general = require("#general");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
function DatasourceCache(store, behaviorId, initialValues) {
  let version = initialValues?.[DatasourceCache.VERSION_KEY];
  if (typeof version !== "number") {
    version = import_Datasource.Datasource.UNKNOWN_VERSION;
  }
  return {
    initialValues,
    async set(transaction, values) {
      const participant = store.participantFor(transaction);
      participant.set(store.number, behaviorId, values);
    },
    async externalSet(values) {
      if (typeof values[DatasourceCache.VERSION_KEY] === "number") {
        version = values[DatasourceCache.VERSION_KEY];
      }
      await store.set({ [behaviorId]: values });
      if (this.externalChangeListener) {
        await this.externalChangeListener(values);
      } else {
        if (!this.initialValues) {
          this.initialValues = {};
        }
        Object.assign(this.initialValues, values);
      }
    },
    externalChangeListener: void 0,
    releaseValues: void 0,
    reclaimValues() {
      if (this.releaseValues) {
        this.initialValues = this.releaseValues();
        this.releaseValues = void 0;
      }
    },
    get version() {
      return version;
    },
    set version(_version) {
      throw new import_general.InternalError("Datasource version must be set via externalSet");
    },
    async erase() {
      await store.eraseStoreForBehavior(behaviorId);
    }
  };
}
((DatasourceCache2) => {
  DatasourceCache2.VERSION_KEY = "__version__";
})(DatasourceCache || (DatasourceCache = {}));
//# sourceMappingURL=DatasourceCache.js.map
