'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/useM2mAuth.tsx
var useM2mAuth_exports = {};
__export(useM2mAuth_exports, {
  M2mAuthenticationProvider: () => M2mAuthenticationProvider,
  useAuth: () => useAuth
});
module.exports = __toCommonJS(useM2mAuth_exports);
var import_matsuri_hooks = require("matsuri-hooks");

// src/storage/client.ts
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_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
};

// src/endpoints/m2m-users.v1.ts
var root = () => {
  let __root = "";
  if (globalThis.M2M_COMPONENTS_ENV === "local") {
    __root = "http://localhost:8080";
  }
  if (globalThis.M2M_COMPONENTS_ENV === "localDev") {
    __root = "https://api-users.dev.m2msystems.cloud";
  }
  if (globalThis.M2M_COMPONENTS_ENV === "development") {
    __root = "https://api-users.dev.m2msystems.cloud";
  }
  if (globalThis.M2M_COMPONENTS_ENV === "production") {
    __root = "https://api.m2msystems.cloud";
  }
  return __root;
};
var login = () => {
  const __root = root();
  const __queries = Object.entries({}).filter(([_, value]) => {
    return value !== void 0;
  }).map(([key, value]) => {
    return `${key}=${value}`;
  }).join("&");
  const __path = `${__root}/${`login`}`;
  return __queries ? `${__path}?${__queries}` : __path;
};

// src/storage/useM2mAuth.tsx
var import_react = require("react");
var import_jsx_runtime = require("react/jsx-runtime");
var AuthenticationContext = (0, import_react.createContext)(
  void 0
);
var checkJwtExpiration = (jwt) => {
  const splitted = jwt.split(".");
  if (splitted.length !== 3)
    return false;
  const [, payload] = splitted;
  const parsedPayload = JSON.parse(atob(payload));
  return /* @__PURE__ */ new Date() < new Date(parsedPayload.exp * 1e3);
};
var M2mAuthenticationProvider = ({
  children
}) => {
  var _a;
  const [token, setToken] = (0, import_react.useState)((_a = m2mAuthTokenApi.getCache()) != null ? _a : "");
  const authenticated = (0, import_react.useMemo)(() => !!token, [token]);
  const tryCheckAuth = (0, import_react.useCallback)(async () => {
    const authToken = await m2mAuthTokenApi.get();
    if (!(authToken && checkJwtExpiration(authToken))) {
      void m2mAuthTokenApi.clear();
      setToken("");
    } else {
      void m2mAuthTokenApi.set(authToken);
      setToken(authToken);
    }
  }, []);
  (0, import_react.useEffect)(() => {
    void tryCheckAuth();
  }, [tryCheckAuth]);
  const login2 = (0, import_react.useCallback)(async (input) => {
    const { data, error } = await (0, import_matsuri_hooks.fetcher)(login(), {
      method: "POST",
      body: JSON.stringify(input)
    });
    if (data) {
      const authToken = data.accessToken;
      void m2mAuthTokenApi.set(authToken);
      setToken(authToken);
    }
    return {
      error,
      token: data ? data.accessToken : void 0
    };
  }, []);
  const logout = (0, import_react.useCallback)(() => {
    void m2mAuthTokenApi.clear();
    window.location.reload();
  }, []);
  const updateToken = (0, import_react.useCallback)(async (token2) => {
    if (checkJwtExpiration(token2)) {
      return {
        error: new Error("M2MAuthToken is expired")
      };
    }
    await m2mAuthTokenApi.set(token2);
    setToken(token2);
    return { error: void 0 };
  }, []);
  const state = (0, import_react.useMemo)(() => {
    return {
      login: login2,
      logout,
      token,
      authenticated,
      updateToken
    };
  }, [authenticated, login2, logout, token, updateToken]);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthenticationContext.Provider, { value: state, children });
};
var useAuth = () => {
  const ctx = (0, import_react.useContext)(AuthenticationContext);
  if (!ctx) {
    throw new Error("AuthenticationProvider is not found");
  }
  return ctx;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  M2mAuthenticationProvider,
  useAuth
});
//# sourceMappingURL=useM2mAuth.js.map