'use strict';

var fs = require('fs');
var path = require('path');

// src/chat/storage.ts

// src/errors.ts
var AgentSDKError = class extends Error {
  /** @internal Marker for cross-bundle identity checks */
  _agentSDKError = true;
  /** Machine-readable error code. Prefer values from the ErrorCode enum. */
  code;
  /** Whether this error is safe to retry */
  retryable;
  /** HTTP status code hint for error classification */
  httpStatus;
  constructor(message, options) {
    super(message, options);
    this.name = "AgentSDKError";
    this.code = options?.code;
    this.retryable = options?.retryable ?? false;
    this.httpStatus = options?.httpStatus;
  }
  /** Check if an error is an AgentSDKError (works across bundled copies) */
  static is(error) {
    return error instanceof Error && "_agentSDKError" in error && error._agentSDKError === true;
  }
};

// src/chat/storage.ts
var StorageError = class extends AgentSDKError {
  /** Machine-readable error code from the unified ErrorCode enum */
  code;
  constructor(message, code) {
    super(message);
    this.name = "StorageError";
    this.code = code;
  }
};
var InMemoryStorage = class {
  data = /* @__PURE__ */ new Map();
  /** @inheritdoc */
  async get(key) {
    const item = this.data.get(key);
    return item !== void 0 ? structuredClone(item) : null;
  }
  /** @inheritdoc */
  async list(options) {
    let items = Array.from(this.data.values()).map((item) => structuredClone(item));
    if (options?.filter) {
      items = items.filter(options.filter);
    }
    if (options?.sort) {
      items.sort(options.sort);
    }
    if (options?.offset !== void 0) {
      items = items.slice(options.offset);
    }
    if (options?.limit !== void 0) {
      items = items.slice(0, options.limit);
    }
    return items;
  }
  /** @inheritdoc */
  async create(key, item) {
    if (this.data.has(key)) {
      throw new StorageError(
        `Item with key "${key}" already exists`,
        "STORAGE_DUPLICATE_KEY" /* STORAGE_DUPLICATE_KEY */
      );
    }
    this.data.set(key, structuredClone(item));
  }
  /** @inheritdoc */
  async update(key, item) {
    if (!this.data.has(key)) {
      throw new StorageError(
        `Item with key "${key}" not found`,
        "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
      );
    }
    this.data.set(key, structuredClone(item));
  }
  /** @inheritdoc */
  async delete(key) {
    if (!this.data.has(key)) {
      throw new StorageError(
        `Item with key "${key}" not found`,
        "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
      );
    }
    this.data.delete(key);
  }
  /** @inheritdoc */
  async has(key) {
    return this.data.has(key);
  }
  /** @inheritdoc */
  async count() {
    return this.data.size;
  }
  /** @inheritdoc */
  async clear() {
    this.data.clear();
  }
};
var FileStorage = class {
  directory;
  extension;
  constructor(options) {
    this.directory = options.directory;
    this.extension = options.extension ?? ".json";
    this.ensureDirectory();
  }
  /** @inheritdoc */
  async get(key) {
    const filePath = this.keyToPath(key);
    if (!fs.existsSync(filePath)) {
      return null;
    }
    return this.readFile(filePath);
  }
  /** @inheritdoc */
  async list(options) {
    this.ensureDirectory();
    const files = fs.readdirSync(this.directory).filter(
      (f) => f.endsWith(this.extension)
    );
    let items = [];
    for (const file of files) {
      const item = this.readFile(path.join(this.directory, file));
      items.push(item);
    }
    if (options?.filter) {
      items = items.filter(options.filter);
    }
    if (options?.sort) {
      items.sort(options.sort);
    }
    if (options?.offset !== void 0) {
      items = items.slice(options.offset);
    }
    if (options?.limit !== void 0) {
      items = items.slice(0, options.limit);
    }
    return items;
  }
  /** @inheritdoc */
  async create(key, item) {
    const filePath = this.keyToPath(key);
    if (fs.existsSync(filePath)) {
      throw new StorageError(
        `Item with key "${key}" already exists`,
        "STORAGE_DUPLICATE_KEY" /* STORAGE_DUPLICATE_KEY */
      );
    }
    this.writeFile(filePath, item);
  }
  /** @inheritdoc */
  async update(key, item) {
    const filePath = this.keyToPath(key);
    if (!fs.existsSync(filePath)) {
      throw new StorageError(
        `Item with key "${key}" not found`,
        "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
      );
    }
    this.writeFile(filePath, item);
  }
  /** @inheritdoc */
  async delete(key) {
    const filePath = this.keyToPath(key);
    if (!fs.existsSync(filePath)) {
      throw new StorageError(
        `Item with key "${key}" not found`,
        "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
      );
    }
    fs.unlinkSync(filePath);
  }
  /** @inheritdoc */
  async has(key) {
    return fs.existsSync(this.keyToPath(key));
  }
  /** @inheritdoc */
  async count() {
    this.ensureDirectory();
    return fs.readdirSync(this.directory).filter(
      (f) => f.endsWith(this.extension)
    ).length;
  }
  /** @inheritdoc */
  async clear() {
    this.ensureDirectory();
    const files = fs.readdirSync(this.directory).filter(
      (f) => f.endsWith(this.extension)
    );
    for (const file of files) {
      fs.unlinkSync(path.join(this.directory, file));
    }
  }
  keyToPath(key) {
    const safeKey = key.replace(
      /[^a-zA-Z0-9_-]/g,
      (c) => "%" + c.charCodeAt(0).toString(16).padStart(2, "0")
    );
    return path.join(this.directory, `${safeKey}${this.extension}`);
  }
  ensureDirectory() {
    if (!fs.existsSync(this.directory)) {
      fs.mkdirSync(this.directory, { recursive: true });
    }
  }
  readFile(filePath) {
    try {
      const content = fs.readFileSync(filePath, "utf-8");
      return JSON.parse(content);
    } catch (error) {
      if (error instanceof SyntaxError) {
        throw new StorageError(
          `Failed to parse file: ${filePath}`,
          "STORAGE_SERIALIZATION_ERROR" /* STORAGE_SERIALIZATION_ERROR */
        );
      }
      throw new StorageError(
        `Failed to read file: ${filePath}`,
        "STORAGE_IO_ERROR" /* STORAGE_IO_ERROR */
      );
    }
  }
  writeFile(filePath, item) {
    try {
      const content = JSON.stringify(item, null, 2);
      fs.writeFileSync(filePath, content, "utf-8");
    } catch {
      throw new StorageError(
        `Failed to write file: ${filePath}`,
        "STORAGE_IO_ERROR" /* STORAGE_IO_ERROR */
      );
    }
  }
};

exports.FileStorage = FileStorage;
exports.InMemoryStorage = InMemoryStorage;
exports.StorageError = StorageError;
//# sourceMappingURL=storage.cjs.map
//# sourceMappingURL=storage.cjs.map