"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/client/index.ts
var index_exports = {};
__export(index_exports, {
  MemoryClient: () => MemoryClient,
  default: () => index_default
});
module.exports = __toCommonJS(index_exports);

// src/client/mem0.ts
var import_axios = __toESM(require("axios"));

// src/client/telemetry.ts
var version = "2.1.36";
var MEM0_TELEMETRY = true;
var _a;
try {
  MEM0_TELEMETRY = ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) === "false" ? false : true;
} catch (error) {
}
var POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
var POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
function generateHash(input) {
  const randomStr = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  return randomStr;
}
var UnifiedTelemetry = class {
  constructor(projectApiKey, host) {
    this.apiKey = projectApiKey;
    this.host = host;
  }
  async captureEvent(distinctId, eventName, properties = {}) {
    if (!MEM0_TELEMETRY) return;
    const eventProperties = {
      client_version: version,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      ...properties,
      $process_person_profile: false,
      $lib: "posthog-node"
    };
    const payload = {
      api_key: this.apiKey,
      distinct_id: distinctId,
      event: eventName,
      properties: eventProperties
    };
    try {
      const response = await fetch(this.host, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
      });
      if (!response.ok) {
        console.error("Telemetry event capture failed:", await response.text());
      }
    } catch (error) {
      console.error("Telemetry event capture failed:", error);
    }
  }
  async shutdown() {
  }
};
var telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
async function captureClientEvent(eventName, instance, additionalData = {}) {
  if (!instance.telemetryId) {
    console.warn("No telemetry ID found for instance");
    return;
  }
  const eventData = {
    function: `${instance.constructor.name}`,
    method: eventName,
    api_host: instance.host,
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    client_version: version,
    keys: (additionalData == null ? void 0 : additionalData.keys) || [],
    ...additionalData
  };
  await telemetry.captureEvent(
    instance.telemetryId,
    `client.${eventName}`,
    eventData
  );
}

// src/client/mem0.ts
var APIError = class extends Error {
  constructor(message) {
    super(message);
    this.name = "APIError";
  }
};
var MemoryClient = class {
  _validateApiKey() {
    if (!this.apiKey) {
      throw new Error("Mem0 API key is required");
    }
    if (typeof this.apiKey !== "string") {
      throw new Error("Mem0 API key must be a string");
    }
    if (this.apiKey.trim() === "") {
      throw new Error("Mem0 API key cannot be empty");
    }
  }
  _validateOrgProject() {
    if (this.organizationName === null && this.projectName !== null || this.organizationName !== null && this.projectName === null) {
      console.warn(
        "Warning: Both organizationName and projectName must be provided together when using either. This will be removed from version 1.0.40. Note that organizationName/projectName are being deprecated in favor of organizationId/projectId."
      );
    }
    if (this.organizationId === null && this.projectId !== null || this.organizationId !== null && this.projectId === null) {
      console.warn(
        "Warning: Both organizationId and projectId must be provided together when using either. This will be removed from version 1.0.40."
      );
    }
  }
  constructor(options) {
    this.apiKey = options.apiKey;
    this.host = options.host || "https://api.mem0.ai";
    this.organizationName = options.organizationName || null;
    this.projectName = options.projectName || null;
    this.organizationId = options.organizationId || null;
    this.projectId = options.projectId || null;
    this.headers = {
      Authorization: `Token ${this.apiKey}`,
      "Content-Type": "application/json"
    };
    this.client = import_axios.default.create({
      baseURL: this.host,
      headers: { Authorization: `Token ${this.apiKey}` },
      timeout: 6e4
    });
    this._validateApiKey();
    this.telemetryId = "";
    this._initializeClient();
  }
  async _initializeClient() {
    try {
      await this.ping();
      if (!this.telemetryId) {
        this.telemetryId = generateHash(this.apiKey);
      }
      this._validateOrgProject();
      captureClientEvent("init", this, {
        api_version: "v1",
        client_type: "MemoryClient"
      }).catch((error) => {
        console.error("Failed to capture event:", error);
      });
    } catch (error) {
      console.error("Failed to initialize client:", error);
      await captureClientEvent("init_error", this, {
        error: (error == null ? void 0 : error.message) || "Unknown error",
        stack: (error == null ? void 0 : error.stack) || "No stack trace"
      });
    }
  }
  _captureEvent(methodName, args) {
    captureClientEvent(methodName, this, {
      success: true,
      args_count: args.length,
      keys: args.length > 0 ? args[0] : []
    }).catch((error) => {
      console.error("Failed to capture event:", error);
    });
  }
  async _fetchWithErrorHandling(url, options) {
    const response = await fetch(url, {
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Token ${this.apiKey}`,
        "Mem0-User-ID": this.telemetryId
      }
    });
    if (!response.ok) {
      const errorData = await response.text();
      throw new APIError(`API request failed: ${errorData}`);
    }
    const jsonResponse = await response.json();
    return jsonResponse;
  }
  _preparePayload(messages, options) {
    const payload = {};
    payload.messages = messages;
    return { ...payload, ...options };
  }
  _prepareParams(options) {
    return Object.fromEntries(
      Object.entries(options).filter(([_, v]) => v != null)
    );
  }
  async ping() {
    try {
      const response = await this._fetchWithErrorHandling(
        `${this.host}/v1/ping/`,
        {
          method: "GET",
          headers: {
            Authorization: `Token ${this.apiKey}`
          }
        }
      );
      if (!response || typeof response !== "object") {
        throw new APIError("Invalid response format from ping endpoint");
      }
      if (response.status !== "ok") {
        throw new APIError(response.message || "API Key is invalid");
      }
      const { org_id, project_id, user_email } = response;
      if (org_id && !this.organizationId) this.organizationId = org_id;
      if (project_id && !this.projectId) this.projectId = project_id;
      if (user_email) this.telemetryId = user_email;
    } catch (error) {
      if (error instanceof APIError) {
        throw error;
      } else {
        throw new APIError(
          `Failed to ping server: ${error.message || "Unknown error"}`
        );
      }
    }
  }
  async add(messages, options = {}) {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    if (this.organizationName != null && this.projectName != null) {
      options.org_name = this.organizationName;
      options.project_name = this.projectName;
    }
    if (this.organizationId != null && this.projectId != null) {
      options.org_id = this.organizationId;
      options.project_id = this.projectId;
      if (options.org_name) delete options.org_name;
      if (options.project_name) delete options.project_name;
    }
    if (options.api_version) {
      options.version = options.api_version.toString() || "v2";
    }
    const payload = this._preparePayload(messages, options);
    const payloadKeys = Object.keys(payload);
    this._captureEvent("add", [payloadKeys]);
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/memories/`,
      {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(payload)
      }
    );
    return response;
  }
  async update(memoryId, {
    text,
    metadata,
    timestamp
  }) {
    if (text === void 0 && metadata === void 0 && timestamp === void 0) {
      throw new Error(
        "At least one of text, metadata, or timestamp must be provided for update."
      );
    }
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    const payload = {};
    if (text !== void 0) payload.text = text;
    if (metadata !== void 0) payload.metadata = metadata;
    if (timestamp !== void 0) payload.timestamp = timestamp;
    const payloadKeys = Object.keys(payload);
    this._captureEvent("update", [payloadKeys]);
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/memories/${memoryId}/`,
      {
        method: "PUT",
        headers: this.headers,
        body: JSON.stringify(payload)
      }
    );
    return response;
  }
  async get(memoryId) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("get", []);
    return this._fetchWithErrorHandling(
      `${this.host}/v1/memories/${memoryId}/`,
      {
        headers: this.headers
      }
    );
  }
  async getAll(options) {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    const payloadKeys = Object.keys(options || {});
    this._captureEvent("get_all", [payloadKeys]);
    const { api_version, page, page_size, ...otherOptions } = options;
    if (this.organizationName != null && this.projectName != null) {
      otherOptions.org_name = this.organizationName;
      otherOptions.project_name = this.projectName;
    }
    let appendedParams = "";
    let paginated_response = false;
    if (page && page_size) {
      appendedParams += `page=${page}&page_size=${page_size}`;
      paginated_response = true;
    }
    if (this.organizationId != null && this.projectId != null) {
      otherOptions.org_id = this.organizationId;
      otherOptions.project_id = this.projectId;
      if (otherOptions.org_name) delete otherOptions.org_name;
      if (otherOptions.project_name) delete otherOptions.project_name;
    }
    if (api_version === "v2") {
      let url = paginated_response ? `${this.host}/v2/memories/?${appendedParams}` : `${this.host}/v2/memories/`;
      return this._fetchWithErrorHandling(url, {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(otherOptions)
      });
    } else {
      const params = new URLSearchParams(this._prepareParams(otherOptions));
      const url = paginated_response ? `${this.host}/v1/memories/?${params}&${appendedParams}` : `${this.host}/v1/memories/?${params}`;
      return this._fetchWithErrorHandling(url, {
        headers: this.headers
      });
    }
  }
  async search(query, options) {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    const payloadKeys = Object.keys(options || {});
    this._captureEvent("search", [payloadKeys]);
    const { api_version, ...otherOptions } = options;
    const payload = { query, ...otherOptions };
    if (this.organizationName != null && this.projectName != null) {
      payload.org_name = this.organizationName;
      payload.project_name = this.projectName;
    }
    if (this.organizationId != null && this.projectId != null) {
      payload.org_id = this.organizationId;
      payload.project_id = this.projectId;
      if (payload.org_name) delete payload.org_name;
      if (payload.project_name) delete payload.project_name;
    }
    const endpoint = api_version === "v2" ? "/v2/memories/search/" : "/v1/memories/search/";
    const response = await this._fetchWithErrorHandling(
      `${this.host}${endpoint}`,
      {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(payload)
      }
    );
    return response;
  }
  async delete(memoryId) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("delete", []);
    return this._fetchWithErrorHandling(
      `${this.host}/v1/memories/${memoryId}/`,
      {
        method: "DELETE",
        headers: this.headers
      }
    );
  }
  async deleteAll(options = {}) {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    const payloadKeys = Object.keys(options || {});
    this._captureEvent("delete_all", [payloadKeys]);
    if (this.organizationName != null && this.projectName != null) {
      options.org_name = this.organizationName;
      options.project_name = this.projectName;
    }
    if (this.organizationId != null && this.projectId != null) {
      options.org_id = this.organizationId;
      options.project_id = this.projectId;
      if (options.org_name) delete options.org_name;
      if (options.project_name) delete options.project_name;
    }
    const params = new URLSearchParams(this._prepareParams(options));
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/memories/?${params}`,
      {
        method: "DELETE",
        headers: this.headers
      }
    );
    return response;
  }
  async history(memoryId) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("history", []);
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/memories/${memoryId}/history/`,
      {
        headers: this.headers
      }
    );
    return response;
  }
  async users() {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    this._captureEvent("users", []);
    const options = {};
    if (this.organizationName != null && this.projectName != null) {
      options.org_name = this.organizationName;
      options.project_name = this.projectName;
    }
    if (this.organizationId != null && this.projectId != null) {
      options.org_id = this.organizationId;
      options.project_id = this.projectId;
      if (options.org_name) delete options.org_name;
      if (options.project_name) delete options.project_name;
    }
    const params = new URLSearchParams(options);
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/entities/?${params}`,
      {
        headers: this.headers
      }
    );
    return response;
  }
  /**
   * @deprecated The method should not be used, use `deleteUsers` instead. This will be removed in version 2.2.0.
   */
  async deleteUser(data) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("delete_user", []);
    if (!data.entity_type) {
      data.entity_type = "user";
    }
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/entities/${data.entity_type}/${data.entity_id}/`,
      {
        method: "DELETE",
        headers: this.headers
      }
    );
    return response;
  }
  async deleteUsers(params = {}) {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    let to_delete = [];
    const { user_id, agent_id, app_id, run_id } = params;
    if (user_id) {
      to_delete = [{ type: "user", name: user_id }];
    } else if (agent_id) {
      to_delete = [{ type: "agent", name: agent_id }];
    } else if (app_id) {
      to_delete = [{ type: "app", name: app_id }];
    } else if (run_id) {
      to_delete = [{ type: "run", name: run_id }];
    } else {
      const entities = await this.users();
      to_delete = entities.results.map((entity) => ({
        type: entity.type,
        name: entity.name
      }));
    }
    if (to_delete.length === 0) {
      throw new Error("No entities to delete");
    }
    const requestOptions = {};
    if (this.organizationName != null && this.projectName != null) {
      requestOptions.org_name = this.organizationName;
      requestOptions.project_name = this.projectName;
    }
    if (this.organizationId != null && this.projectId != null) {
      requestOptions.org_id = this.organizationId;
      requestOptions.project_id = this.projectId;
      if (requestOptions.org_name) delete requestOptions.org_name;
      if (requestOptions.project_name) delete requestOptions.project_name;
    }
    for (const entity of to_delete) {
      try {
        await this.client.delete(
          `/v2/entities/${entity.type}/${entity.name}/`,
          {
            params: requestOptions
          }
        );
      } catch (error) {
        throw new APIError(
          `Failed to delete ${entity.type} ${entity.name}: ${error.message}`
        );
      }
    }
    this._captureEvent("delete_users", [
      {
        user_id,
        agent_id,
        app_id,
        run_id,
        sync_type: "sync"
      }
    ]);
    return {
      message: user_id || agent_id || app_id || run_id ? "Entity deleted successfully." : "All users, agents, apps and runs deleted."
    };
  }
  async batchUpdate(memories) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("batch_update", []);
    const memoriesBody = memories.map((memory) => ({
      memory_id: memory.memoryId,
      text: memory.text
    }));
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/batch/`,
      {
        method: "PUT",
        headers: this.headers,
        body: JSON.stringify({ memories: memoriesBody })
      }
    );
    return response;
  }
  async batchDelete(memories) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("batch_delete", []);
    const memoriesBody = memories.map((memory) => ({
      memory_id: memory
    }));
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/batch/`,
      {
        method: "DELETE",
        headers: this.headers,
        body: JSON.stringify({ memories: memoriesBody })
      }
    );
    return response;
  }
  async getProject(options) {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    const payloadKeys = Object.keys(options || {});
    this._captureEvent("get_project", [payloadKeys]);
    const { fields } = options;
    if (!(this.organizationId && this.projectId)) {
      throw new Error(
        "organizationId and projectId must be set to access instructions or categories"
      );
    }
    const params = new URLSearchParams();
    fields == null ? void 0 : fields.forEach((field) => params.append("fields", field));
    const response = await this._fetchWithErrorHandling(
      `${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/?${params.toString()}`,
      {
        headers: this.headers
      }
    );
    return response;
  }
  async updateProject(prompts) {
    if (this.telemetryId === "") await this.ping();
    this._validateOrgProject();
    this._captureEvent("update_project", []);
    if (!(this.organizationId && this.projectId)) {
      throw new Error(
        "organizationId and projectId must be set to update instructions or categories"
      );
    }
    const response = await this._fetchWithErrorHandling(
      `${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/`,
      {
        method: "PATCH",
        headers: this.headers,
        body: JSON.stringify(prompts)
      }
    );
    return response;
  }
  // WebHooks
  async getWebhooks(data) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("get_webhooks", []);
    const project_id = (data == null ? void 0 : data.projectId) || this.projectId;
    const response = await this._fetchWithErrorHandling(
      `${this.host}/api/v1/webhooks/projects/${project_id}/`,
      {
        headers: this.headers
      }
    );
    return response;
  }
  async createWebhook(webhook) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("create_webhook", []);
    const response = await this._fetchWithErrorHandling(
      `${this.host}/api/v1/webhooks/projects/${this.projectId}/`,
      {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(webhook)
      }
    );
    return response;
  }
  async updateWebhook(webhook) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("update_webhook", []);
    const project_id = webhook.projectId || this.projectId;
    const response = await this._fetchWithErrorHandling(
      `${this.host}/api/v1/webhooks/${webhook.webhookId}/`,
      {
        method: "PUT",
        headers: this.headers,
        body: JSON.stringify({
          ...webhook,
          projectId: project_id
        })
      }
    );
    return response;
  }
  async deleteWebhook(data) {
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("delete_webhook", []);
    const webhook_id = data.webhookId || data;
    const response = await this._fetchWithErrorHandling(
      `${this.host}/api/v1/webhooks/${webhook_id}/`,
      {
        method: "DELETE",
        headers: this.headers
      }
    );
    return response;
  }
  async feedback(data) {
    if (this.telemetryId === "") await this.ping();
    const payloadKeys = Object.keys(data || {});
    this._captureEvent("feedback", [payloadKeys]);
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/feedback/`,
      {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(data)
      }
    );
    return response;
  }
  async createMemoryExport(data) {
    var _a2, _b;
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("create_memory_export", []);
    if (!data.filters || !data.schema) {
      throw new Error("Missing filters or schema");
    }
    data.org_id = ((_a2 = this.organizationId) == null ? void 0 : _a2.toString()) || null;
    data.project_id = ((_b = this.projectId) == null ? void 0 : _b.toString()) || null;
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/exports/`,
      {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(data)
      }
    );
    return response;
  }
  async getMemoryExport(data) {
    var _a2, _b;
    if (this.telemetryId === "") await this.ping();
    this._captureEvent("get_memory_export", []);
    if (!data.memory_export_id && !data.filters) {
      throw new Error("Missing memory_export_id or filters");
    }
    data.org_id = ((_a2 = this.organizationId) == null ? void 0 : _a2.toString()) || "";
    data.project_id = ((_b = this.projectId) == null ? void 0 : _b.toString()) || "";
    const response = await this._fetchWithErrorHandling(
      `${this.host}/v1/exports/get/`,
      {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(data)
      }
    );
    return response;
  }
};

// src/client/index.ts
var index_default = MemoryClient;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MemoryClient
});
//# sourceMappingURL=index.js.map