'use client'
"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);

// src/storage/client.ts
var client_exports = {};
__export(client_exports, {
  M2M_AUTH_TOKEN_KEY: () => M2M_AUTH_TOKEN_KEY,
  m2mAuthTokenApi: () => m2mAuthTokenApi,
  m2mStorageClient: () => m2mStorageClient
});
module.exports = __toCommonJS(client_exports);

// src/storage/lib/client.ts
var generateUUID = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
    return v.toString(16);
  });
};
var StorageClient = class {
  constructor(url, opts) {
    opts = opts || {};
    this.id = generateUUID();
    this.frameId = opts.frameId || "CrossStorageClient-" + this.id;
    this.origin = new URL(url).origin;
    this.requests = {};
    this.connected = false;
    this.closed = false;
    this.count = 0;
    this.timeout = opts.timeout || 5e3;
    window.addEventListener("message", this.listener.bind(this), false);
    const frame = this.createFrame(url);
    this.hub = frame.contentWindow;
  }
  onConnect() {
    if (this.connected) {
      return Promise.resolve();
    } else if (this.closed) {
      return Promise.reject(new Error("StorageClient has closed."));
    }
    if (!this.requests.connect) {
      this.requests.connect = [];
    }
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(function() {
        reject(new Error("StorageClient could not connect."));
      }, this.timeout);
      this.requests.connect.push((err) => {
        clearTimeout(timeout);
        if (err)
          return reject(err);
        resolve(void 0);
      });
    });
  }
  set(key, value) {
    return this.request("set", {
      key,
      value
    });
  }
  get(...keys) {
    return this.request("get", { keys });
  }
  del(...keys) {
    return this.request("del", { keys });
  }
  clear() {
    return this.request("clear");
  }
  getKeys() {
    this.request("getKeys");
  }
  close() {
    const frame = document.getElementById(this.frameId);
    if (frame && frame.parentNode) {
      frame.parentNode.removeChild(frame);
    }
    window.removeEventListener("message", this.listener, false);
    this.connected = false;
    this.closed = true;
  }
  listener(message) {
    let i, error, response;
    if (this.closed || !message.data || typeof message.data !== "string") {
      return;
    }
    const origin = message.origin;
    if (origin !== this.origin)
      return;
    if (message.data === "cross-storage:unavailable") {
      if (!this.closed)
        this.close();
      if (!this.requests.connect)
        return;
      error = new Error(
        "Closing StorageClient. Could not access localStorage in StorageHub."
      );
      for (i = 0; i < this.requests.connect.length; i++) {
        this.requests.connect[i](error);
      }
      return;
    }
    if (message.data.indexOf("cross-storage:") !== -1 && !this.connected) {
      this.connected = true;
      if (!this.requests.connect)
        return;
      for (i = 0; i < this.requests.connect.length; i++) {
        this.requests.connect[i](error);
      }
      delete this.requests.connect;
    }
    if (message.data === "cross-storage:ready")
      return;
    try {
      response = JSON.parse(message.data);
    } catch (e) {
      return;
    }
    if (!response.id)
      return;
    if (this.requests[response.id]) {
      this.requests[response.id](response.error, response.result);
    }
  }
  createFrame(url) {
    const frame = window.document.createElement("iframe");
    frame.id = this.frameId;
    frame.style.display = "none";
    frame.style.position = "absolute";
    frame.style.top = "-999px";
    frame.style.left = "-999px";
    window.document.body.appendChild(frame);
    frame.src = url;
    return frame;
  }
  // eslint-disable-next-line @typescript-eslint/ban-types
  request(method, params) {
    if (this.closed) {
      return Promise.reject(new Error("StorageClient has closed."));
    }
    this.count++;
    const req = {
      id: this.id + ":" + this.count,
      method: "cross-storage:" + method,
      params
    };
    return new Promise((resolve, reject) => {
      const timeout = window.setTimeout(() => {
        if (!this.requests[req.id])
          return;
        delete this.requests[req.id];
        reject(
          new Error("Timeout: StorageClient could not perform " + req.method)
        );
      }, this.timeout);
      this.requests[req.id] = (err, result) => {
        clearTimeout(timeout);
        delete this.requests[req.id];
        if (err)
          return reject(new Error(err));
        resolve(result);
      };
      if (this.hub) {
        this.hub.postMessage(JSON.stringify(req), this.origin);
      } else {
        reject(new Error("Not found StorageHub."));
      }
    });
  }
};

// src/storage/client.ts
var M2mStorageClient = class extends StorageClient {
};
var context = {};
var getStorage = async (timeout = 5e3) => {
  const storage = await new Promise((resolve, reject) => {
    const rejectTimer = window.setTimeout(function() {
      reject(
        new Error(
          "Timeout: M2mStorageClient could not connect. Please call m2mStorageClient.init() before using m2mStorageClient."
        )
      );
    }, timeout);
    const storage2 = context.storage;
    if (storage2) {
      window.clearTimeout(rejectTimer);
      resolve(storage2);
    }
    const timer = window.setInterval(() => {
      const storage3 = context.storage;
      if (storage3) {
        window.clearTimeout(rejectTimer);
        window.clearInterval(timer);
        resolve(storage3);
      }
    }, 200);
  });
  await storage.onConnect();
  return storage;
};
var M2M_STORAGE_HUB_URL = "https://hub.m2msystems.cloud/";
var M2M_STORAGE_HUB_URL_DEV = "https://m2m-components-storage-hub-dev.netlify.app/";
var initStorageClient = (options) => {
  if (context.storage) {
    throw new Error(
      "M2mStorageClient already initialized. Do not call m2mStorageClient.init multiple times."
    );
  }
  const storage = new M2mStorageClient(
    (options == null ? void 0 : options.env) === "production" ? M2M_STORAGE_HUB_URL : M2M_STORAGE_HUB_URL_DEV
  );
  context.storage = storage;
};
var m2mStorageClient = {
  init: initStorageClient,
  getStorage
};
var M2M_AUTH_TOKEN_KEY = "M2M_APP_AUTH_TOKEN";
var getAuthTokenCache = () => {
  return window.localStorage.getItem(M2M_AUTH_TOKEN_KEY);
};
var getAuthToken = async () => {
  try {
    const storage = await getStorage();
    const autuToken = await storage.get(M2M_AUTH_TOKEN_KEY);
    return autuToken || getAuthTokenCache();
  } catch (error) {
    console.warn(error);
    return getAuthTokenCache();
  }
};
var setAuthToken = async (token) => {
  window.localStorage.setItem(M2M_AUTH_TOKEN_KEY, token);
  try {
    const storage = await getStorage();
    await storage.set(M2M_AUTH_TOKEN_KEY, token);
  } catch (error) {
    console.warn(error);
  }
};
var clearAuthToken = async () => {
  window.localStorage.removeItem(M2M_AUTH_TOKEN_KEY);
  try {
    const storage = await getStorage();
    await storage.del(M2M_AUTH_TOKEN_KEY);
  } catch (error) {
    console.warn(error);
  }
};
var m2mAuthTokenApi = {
  get: getAuthToken,
  getCache: getAuthTokenCache,
  set: setAuthToken,
  clear: clearAuthToken
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  M2M_AUTH_TOKEN_KEY,
  m2mAuthTokenApi,
  m2mStorageClient
});
//# sourceMappingURL=client.js.map