"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 StorageBackendMemory_exports = {};
__export(StorageBackendMemory_exports, {
  StorageBackendMemory: () => StorageBackendMemory
});
module.exports = __toCommonJS(StorageBackendMemory_exports);
var import_Bytes = require("#util/Bytes.js");
var import_DeepCopy = require("#util/DeepCopy.js");
var import_Storage = require("./Storage.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
class StorageBackendMemory extends import_Storage.Storage {
  constructor(store = {}) {
    super();
    this.store = store;
  }
  isInitialized = false;
  get initialized() {
    return this.isInitialized;
  }
  static async create(store = {}) {
    const storage = new StorageBackendMemory(store);
    storage.initialize();
    return storage;
  }
  createContextKey(contexts) {
    const key = contexts.join(".");
    if (!key.length || key.includes("..") || key.startsWith(".") || key.endsWith("."))
      throw new import_Storage.StorageError("Context must not be an empty string.");
    return key;
  }
  initialize() {
    if (this.initialized) throw new import_Storage.StorageError("Storage already initialized!");
    this.isInitialized = true;
  }
  clone() {
    const clone = new StorageBackendMemory((0, import_DeepCopy.deepCopy)(this.store));
    clone.initialize();
    return clone;
  }
  async close() {
    this.isInitialized = false;
  }
  clear() {
    this.store = {};
  }
  get data() {
    return this.store;
  }
  get(contexts, key) {
    this.#assertInitialized();
    if (!contexts.length || !key.length) throw new import_Storage.StorageError("Context and key must not be empty.");
    return this.store[this.createContextKey(contexts)]?.[key];
  }
  openBlob(contexts, key) {
    const value = this.get(contexts, key);
    if (value === void 0) {
      return new Blob([]);
    }
    if (!import_Bytes.Bytes.isBytes(value)) {
      throw new import_Storage.StorageError("Value must be Bytes to read as blob stream.");
    }
    return new Blob([import_Bytes.Bytes.exclusive(value)]);
  }
  async writeBlobFromStream(contexts, key, stream) {
    this.#assertInitialized();
    const reader = stream.getReader();
    const chunks = [];
    try {
      let length = 0;
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        const data = import_Bytes.Bytes.of(value);
        chunks.push(data);
        length += data.length;
      }
      const combined = new Uint8Array(length);
      let offset = 0;
      for (const chunk of chunks) {
        combined.set(chunk, offset);
        offset += chunk.length;
      }
      this.#setKey(contexts, key, combined);
    } catch (error) {
      throw new import_Storage.StorageError(`Error reading stream: ${error.message}`);
    } finally {
      if (stream.locked) {
        reader.releaseLock();
      }
      await stream.cancel();
    }
  }
  #setKey(contexts, key, value) {
    if (!contexts.length || !key.length) throw new import_Storage.StorageError("Context and key must not be empty.");
    const contextKey = this.createContextKey(contexts);
    if (this.store[contextKey] === void 0) {
      this.store[contextKey] = {};
    }
    this.store[contextKey][key] = value;
  }
  set(contexts, keyOrValues, value) {
    this.#assertInitialized();
    if (typeof keyOrValues === "string") {
      this.#setKey(contexts, keyOrValues, value);
    } else {
      Object.entries(keyOrValues).forEach(([key, value2]) => {
        this.#setKey(contexts, key, value2);
      });
    }
  }
  delete(contexts, key) {
    this.#assertInitialized();
    if (!contexts.length || !key.length) throw new import_Storage.StorageError("Context and key must not be empty.");
    delete this.store[this.createContextKey(contexts)]?.[key];
  }
  keys(contexts) {
    this.#assertInitialized();
    if (!contexts.length) throw new import_Storage.StorageError("Context must not be empty!");
    return Object.keys(this.store[this.createContextKey(contexts)] ?? {});
  }
  values(contexts) {
    const values = {};
    for (const key of this.keys(contexts)) {
      values[key] = this.get(contexts, key);
    }
    return values;
  }
  contexts(contexts) {
    this.#assertInitialized();
    const contextKey = contexts.length ? this.createContextKey(contexts) : "";
    const startContextKey = contextKey.length ? `${contextKey}.` : "";
    const foundContexts = new Array();
    Object.keys(this.store).forEach((key) => {
      if (key.startsWith(startContextKey)) {
        const subKeys = key.substring(startContextKey.length).split(".");
        if (subKeys.length < 1) return;
        const context = subKeys[0];
        if (!foundContexts.includes(context)) {
          foundContexts.push(context);
        }
      }
    });
    return foundContexts;
  }
  clearAll(contexts) {
    this.#assertInitialized();
    const contextKey = this.createContextKey(contexts);
    if (contextKey.length) {
      delete this.store[contextKey];
    }
    const startContextKey = contextKey.length ? `${contextKey}.` : "";
    Object.keys(this.store).forEach((key) => {
      if (key.startsWith(startContextKey)) {
        delete this.store[key];
      }
    });
  }
  #assertInitialized() {
    if (this.initialized) {
      return;
    }
    throw new import_Storage.StorageError("Storage is not initialized");
  }
}
//# sourceMappingURL=StorageBackendMemory.js.map
