diff --git a/dist/index.js b/dist/index.js index 7d624e5..f43db52 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,15 +1,15 @@ -var ze = Object.defineProperty; -var ve = (r) => { +var Pe = Object.defineProperty; +var Se = (r) => { throw TypeError(r); }; -var je = (r, e, t) => e in r ? ze(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; -var f = (r, e, t) => je(r, typeof e != "symbol" ? e + "" : e, t), oe = (r, e, t) => e.has(r) || ve("Cannot " + t); -var h = (r, e, t) => (oe(r, e, "read from private field"), t ? t.call(r) : e.get(r)), A = (r, e, t) => e.has(r) ? ve("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), B = (r, e, t, i) => (oe(r, e, "write to private field"), i ? i.call(r, t) : e.set(r, t), t), d = (r, e, t) => (oe(r, e, "access private method"), t); +var je = (r, e, t) => e in r ? Pe(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; +var f = (r, e, t) => je(r, typeof e != "symbol" ? e + "" : e, t), oe = (r, e, t) => e.has(r) || Se("Cannot " + t); +var h = (r, e, t) => (oe(r, e, "read from private field"), t ? t.call(r) : e.get(r)), A = (r, e, t) => e.has(r) ? Se("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), B = (r, e, t, i) => (oe(r, e, "write to private field"), i ? i.call(r, t) : e.set(r, t), t), d = (r, e, t) => (oe(r, e, "access private method"), t); import { jsxs as O, jsx as S } from "react/jsx-runtime"; -import { useState as I, useRef as ie, useEffect as W, useCallback as H, createContext as Oe, useMemo as We, useContext as Fe } from "react"; -import { HStack as N, IconButton as G, Button as ge, Input as ke, Text as j } from "@chakra-ui/react"; -import { IoChevronForwardOutline as be, IoChevronBackOutline as ye } from "react-icons/io5"; -const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => String(r).replace(/\d/g, (e) => "۰۱۲۳۴۵۶۷۸۹"[Number(e)]), F = (r) => String(r).replace(/[۰-۹]/g, (t) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(t))), vt = ({ +import { useState as I, useRef as ie, useEffect as W, useCallback as H, createContext as Oe, useMemo as We } from "react"; +import { HStack as N, IconButton as G, Button as ke, Input as be, Text as j } from "@chakra-ui/react"; +import { IoChevronForwardOutline as ye, IoChevronBackOutline as ve } from "react-icons/io5"; +const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => String(r).replace(/\d/g, (e) => "۰۱۲۳۴۵۶۷۸۹"[Number(e)]), V = (r) => String(r).replace(/[۰-۹]/g, (t) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(t))), vt = ({ currentPage: r, totalPages: e, totalCount: t, @@ -26,7 +26,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S c || o(v(r)); }, [r, c, l]), W(() => { if (!c || !n || l !== null) return; - const p = parseInt(F(n), 10); + const p = parseInt(V(n), 10); if (isNaN(p)) return; const k = setTimeout(() => { var C; @@ -44,7 +44,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S ]); const T = () => { var g, C; - const p = parseInt(F(n), 10); + const p = parseInt(V(n), 10); if (isNaN(p)) { o(v(r)), a(!1), u(null), (g = w.current) == null || g.blur(); return; @@ -74,12 +74,12 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S _hover: { bg: "#cbcbe8" }, onClick: () => i(r - 1), isDisabled: r === 1, - icon: /* @__PURE__ */ S(be, {}), + icon: /* @__PURE__ */ S(ye, {}), "aria-label": "صفحه قبلی" } ), m.map((p) => /* @__PURE__ */ S( - ge, + ke, { size: "md", px: 2, @@ -101,12 +101,12 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S _hover: { bg: "#cbcbe8" }, onClick: () => i(r + 1), isDisabled: r === e, - icon: /* @__PURE__ */ S(ye, {}), + icon: /* @__PURE__ */ S(ve, {}), "aria-label": "صفحه بعدی" } ), /* @__PURE__ */ S( - ke, + be, { ref: w, type: "text", @@ -118,7 +118,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S a(!0), u(null), o(""); }, onChange: (p) => { - const k = p.target.value, g = F(k).replace(/\D/g, ""); + const k = p.target.value, g = V(k).replace(/\D/g, ""); o(v(g)); }, onBlur: () => { @@ -159,7 +159,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S c || o(v(r)); }, [r, c, l]), W(() => { if (!c || !n || l !== null) return; - const p = parseInt(F(n), 10); + const p = parseInt(V(n), 10); if (isNaN(p)) return; const k = setTimeout(() => { var C; @@ -177,7 +177,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S ]); const T = () => { var g, C; - const p = parseInt(F(n), 10); + const p = parseInt(V(n), 10); if (isNaN(p)) { o(v(r)), a(!1), u(null), (g = w.current) == null || g.blur(); return; @@ -213,12 +213,12 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S _hover: { bg: "#cbcbe8" }, onClick: () => i(r - 1), isDisabled: r === 1, - icon: /* @__PURE__ */ S(be, {}), + icon: /* @__PURE__ */ S(ye, {}), "aria-label": "صفحه قبلی" } ), m.map((p) => /* @__PURE__ */ S( - ge, + ke, { size: "md", bg: r === p ? "#4B49AC" : "#e6e6f1", @@ -239,12 +239,12 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S _hover: { bg: "#cbcbe8" }, onClick: () => i(r + 1), isDisabled: r === e, - icon: /* @__PURE__ */ S(ye, {}), + icon: /* @__PURE__ */ S(ve, {}), "aria-label": "صفحه بعدی" } ), /* @__PURE__ */ S( - ke, + be, { ref: w, type: "text", @@ -256,7 +256,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S a(!0), u(null), o(""); }, onChange: (p) => { - const k = p.target.value, g = F(k).replace(/\D/g, ""); + const k = p.target.value, g = V(k).replace(/\D/g, ""); o(v(g)); }, onBlur: () => { @@ -297,7 +297,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S a(!1), o(""), u(null); return; } - const U = parseInt(F(n), 10); + const U = parseInt(V(n), 10); if (isNaN(U)) { a(!1), o(""), u(null); return; @@ -320,7 +320,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S const k = () => { u(null), o(""), a(!0); }, g = (U, E = !1) => /* @__PURE__ */ S( - ge, + ke, { size: "md", bg: E ? "#4B49AC" : "#e6e6f1", @@ -333,7 +333,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S U ); if (e === 0 || !t) return null; - const C = e > 1 && m !== 1, V = e > 1 && m !== e; + const C = e > 1 && m !== 1, F = e > 1 && m !== e; return /* @__PURE__ */ S( N, { @@ -355,13 +355,13 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S _hover: { bg: "#cbcbe8" }, onClick: () => T(m - 1), isDisabled: m === 1, - icon: /* @__PURE__ */ S(be, {}), + icon: /* @__PURE__ */ S(ye, {}), "aria-label": "صفحه قبلی" } ), C && g(1), c ? /* @__PURE__ */ S( - ke, + be, { ref: w, type: "text", @@ -370,8 +370,8 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S w: "48px", value: n, onChange: (U) => { - const E = U.target.value, Pe = F(E).replace(/\D/g, ""); - o(v(Pe)); + const E = U.target.value, ze = V(E).replace(/\D/g, ""); + o(v(ze)); }, onBlur: () => { n ? p() : (o(""), a(!1), u(null)); @@ -386,7 +386,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S dir: "ltr" } ) : g(m, !0), - V && g(e), + F && g(e), /* @__PURE__ */ S( G, { @@ -396,7 +396,7 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S _hover: { bg: "#cbcbe8" }, onClick: () => T(m + 1), isDisabled: m === e, - icon: /* @__PURE__ */ S(ye, {}), + icon: /* @__PURE__ */ S(ve, {}), "aria-label": "صفحه بعدی" } ) @@ -404,8 +404,8 @@ const yt = (r) => new Intl.NumberFormat("fa-IR").format(Number(r)), v = (r) => S } ); }, Ve = "application/json"; -var K, _, $, J, M, q, y, L, s, ee, Ue, _e, Ee, Ae, ae, Ie, ce, xe, Le, te, X, le, P, Re, de, z, re, Z, R, ue; -class He { +var K, _, $, J, M, q, y, L, s, ee, _e, Ee, Ae, Ie, ae, xe, ce, Le, Re, te, X, le, z, Me, de, P, re, Z, R, ue; +class Fe { /** * @param {KeycloakConfig} config */ @@ -512,7 +512,7 @@ class He { var i; if (this.didInitialize) throw new Error("A 'Keycloak' instance can only be initialized once."); - this.didInitialize = !0, B(this, J, Xe()); + this.didInitialize = !0, B(this, J, Qe()); const t = ["default", "cordova", "cordova-native"]; if (typeof e.adapter == "string" && t.includes(e.adapter) ? B(this, _, d(this, s, ee).call(this, e.adapter)) : typeof e.adapter == "object" ? B(this, _, e.adapter) : "Cordova" in window || "cordova" in window ? B(this, _, d(this, s, ee).call(this, "cordova")) : B(this, _, d(this, s, ee).call(this, "default")), typeof e.useNonce < "u" && B(this, $, e.useNonce), typeof e.checkLoginIframe < "u" && (h(this, y).enable = e.checkLoginIframe), e.checkLoginIframeInterval && (h(this, y).interval = e.checkLoginIframeInterval), e.onLoad === "login-required" && (this.loginRequired = !0), e.responseMode) if (e.responseMode === "query" || e.responseMode === "fragment") @@ -540,7 +540,7 @@ class He { throw new TypeError(`Invalid value for pkceMethod', expected 'S256' or false but got ${e.pkceMethod}.`); this.pkceMethod = e.pkceMethod; } - return typeof e.enableLogging == "boolean" && (this.enableLogging = e.enableLogging), e.logoutMethod === "POST" && (this.logoutMethod = "POST"), typeof e.scope == "string" && (this.scope = e.scope), typeof e.messageReceiveTimeout == "number" && e.messageReceiveTimeout > 0 && (this.messageReceiveTimeout = e.messageReceiveTimeout), await d(this, s, Ae).call(this), await d(this, s, xe).call(this), await d(this, s, Le).call(this, e), (i = this.onReady) == null || i.call(this, this.authenticated), this.authenticated; + return typeof e.enableLogging == "boolean" && (this.enableLogging = e.enableLogging), e.logoutMethod === "POST" && (this.logoutMethod = "POST"), typeof e.scope == "string" && (this.scope = e.scope), typeof e.messageReceiveTimeout == "number" && e.messageReceiveTimeout > 0 && (this.messageReceiveTimeout = e.messageReceiveTimeout), await d(this, s, Ie).call(this), await d(this, s, Le).call(this), await d(this, s, Re).call(this, e), (i = this.onReady) == null || i.call(this, this.authenticated), this.authenticated; }); /** * @param {KeycloakLoginOptions} [options] @@ -552,7 +552,7 @@ class He { * @returns {Promise} */ f(this, "createLoginUrl", async (e) => { - const t = Se(), i = Se(), n = h(this, _).redirectUri(e), o = { + const t = Ce(), i = Ce(), n = h(this, _).redirectUri(e), o = { state: t, nonce: i, redirectUri: n, @@ -575,9 +575,9 @@ class He { ["response_type", this.responseType], ["scope", a] ]); - if (h(this, $) && u.append("nonce", i), e != null && e.prompt && u.append("prompt", e.prompt), typeof (e == null ? void 0 : e.maxAge) == "number" && u.append("max_age", e.maxAge.toString()), e != null && e.loginHint && u.append("login_hint", e.loginHint), e != null && e.idpHint && u.append("kc_idp_hint", e.idpHint), e != null && e.action && e.action !== "register" && u.append("kc_action", e.action), e != null && e.locale && u.append("ui_locales", e.locale), e != null && e.acr && u.append("claims", Ye(e.acr)), e != null && e.acrValues && u.append("acr_values", e.acrValues), this.pkceMethod) + if (h(this, $) && u.append("nonce", i), e != null && e.prompt && u.append("prompt", e.prompt), typeof (e == null ? void 0 : e.maxAge) == "number" && u.append("max_age", e.maxAge.toString()), e != null && e.loginHint && u.append("login_hint", e.loginHint), e != null && e.idpHint && u.append("kc_idp_hint", e.idpHint), e != null && e.action && e.action !== "register" && u.append("kc_action", e.action), e != null && e.locale && u.append("ui_locales", e.locale), e != null && e.acr && u.append("claims", He(e.acr)), e != null && e.acrValues && u.append("acr_values", e.acrValues), this.pkceMethod) try { - const w = $e(96), m = await Je(this.pkceMethod, w); + const w = Ye(96), m = await $e(this.pkceMethod, w); o.pkceCodeVerifier = w, u.append("code_challenge", m), u.append("code_challenge_method", this.pkceMethod); } catch (w) { throw new Error("Failed to generate PKCE challenge.", { cause: w }); @@ -667,7 +667,7 @@ class He { if (!e) throw new Error("Unable to load user profile, make sure the adapter is not configured using a generic OIDC provider."); const t = `${e}/account`, i = await Q(t, { - headers: [Ce(this.token)] + headers: [Te(this.token)] }); return this.profile = i; }); @@ -676,7 +676,7 @@ class He { */ f(this, "loadUserInfo", async () => { const e = this.endpoints.userinfo(), t = await Q(e, { - headers: [Ce(this.token)] + headers: [Te(this.token)] }); return this.userInfo = t; }); @@ -716,7 +716,7 @@ class He { const l = this.endpoints.token(); let u = (/* @__PURE__ */ new Date()).getTime(); try { - const w = await ct( + const w = await at( l, this.refreshToken, /** @type {string} */ @@ -726,7 +726,7 @@ class He { for (let m = h(this, K).pop(); m != null; m = h(this, K).pop()) m.resolve(!0); } catch (w) { - h(this, q).call(this, "[KEYCLOAK] Failed to refresh token"), w instanceof Ne && w.response.status === 400 && this.clearToken(), (a = this.onAuthRefreshError) == null || a.call(this); + h(this, q).call(this, "[KEYCLOAK] Failed to refresh token"), w instanceof Be && w.response.status === 400 && this.clearToken(), (a = this.onAuthRefreshError) == null || a.call(this); for (let m = h(this, K).pop(); m != null; m = h(this, K).pop()) m.reject(w); } @@ -757,16 +757,16 @@ K = new WeakMap(), _ = new WeakMap(), $ = new WeakMap(), J = new WeakMap(), M = */ ee = function(e) { if (e === "default") - return d(this, s, Ue).call(this); + return d(this, s, _e).call(this); if (e === "cordova") - return h(this, y).enable = !1, d(this, s, _e).call(this); - if (e === "cordova-native") return h(this, y).enable = !1, d(this, s, Ee).call(this); + if (e === "cordova-native") + return h(this, y).enable = !1, d(this, s, Ae).call(this); throw new Error("invalid adapter type: " + e); }, /** * @returns {KeycloakAdapter} */ -Ue = function() { +_e = function() { const e = (t) => (t == null ? void 0 : t.redirectUri) || this.redirectUri || globalThis.location.href; return { login: async (t) => (window.location.assign(await this.createLoginUrl(t)), await new Promise(() => { @@ -809,7 +809,7 @@ Ue = function() { }, /** * @returns {KeycloakAdapter} */ -_e = function() { +Ee = function() { const e = (c, a, l) => window.cordova && window.cordova.InAppBrowser ? window.cordova.InAppBrowser.open(c, a, l) : window.open(c, a, l), t = (c) => c && c.cordovaOptions ? Object.keys(c.cordovaOptions).reduce((a, l) => (a[l] = c.cordovaOptions[l], a), {}) : {}, i = (c) => Object.keys(c).reduce((a, l) => (a.push(l + "=" + c[l]), a), []).join(","), n = (c) => { const a = t(c); return a.location = "no", c && c.prompt === "none" && (a.hidden = "yes"), i(a); @@ -824,23 +824,23 @@ _e = function() { return await new Promise((p, k) => { u.addEventListener("loadstart", async (g) => { if (g.url.indexOf(o()) === 0) { - const C = d(this, s, P).call(this, g.url); + const C = d(this, s, z).call(this, g.url); w = !0, T(); try { - await d(this, s, z).call(this, C), p(); - } catch (V) { - k(V); + await d(this, s, P).call(this, C), p(); + } catch (F) { + k(F); } } }), u.addEventListener("loaderror", async (g) => { if (!w) if (g.url.indexOf(o()) === 0) { - const C = d(this, s, P).call(this, g.url); + const C = d(this, s, z).call(this, g.url); w = !0, T(); try { - await d(this, s, z).call(this, C), p(); - } catch (V) { - k(V); + await d(this, s, P).call(this, C), p(); + } catch (F) { + k(F); } } else k(new Error("Unable to process login.")), T(); @@ -868,9 +868,9 @@ _e = function() { u.addEventListener("loadstart", async (p) => { if (p.url.indexOf(o()) === 0) { u.close(); - const k = d(this, s, P).call(this, p.url); + const k = d(this, s, z).call(this, p.url); try { - await d(this, s, z).call(this, k), m(); + await d(this, s, P).call(this, k), m(); } catch (g) { T(g); } @@ -893,16 +893,16 @@ _e = function() { }, /** * @returns {KeycloakAdapter} */ -Ee = function() { +Ae = function() { return { login: async (e) => { const t = await this.createLoginUrl(e); await new Promise((i, n) => { universalLinks.subscribe("keycloak", async (o) => { universalLinks.unsubscribe("keycloak"), window.cordova.plugins.browsertab.close(); - const c = d(this, s, P).call(this, o.url); + const c = d(this, s, z).call(this, o.url); try { - await d(this, s, z).call(this, c), i(); + await d(this, s, P).call(this, c), i(); } catch (a) { n(a); } @@ -922,9 +922,9 @@ Ee = function() { await new Promise((i, n) => { universalLinks.subscribe("keycloak", async (o) => { universalLinks.unsubscribe("keycloak"), window.cordova.plugins.browsertab.close(); - const c = d(this, s, P).call(this, o.url); + const c = d(this, s, z).call(this, o.url); try { - await d(this, s, z).call(this, c), i(); + await d(this, s, P).call(this, c), i(); } catch (a) { n(a); } @@ -940,12 +940,12 @@ Ee = function() { }, redirectUri: (e) => e && e.redirectUri ? e.redirectUri : this.redirectUri ? this.redirectUri : "http://localhost" }; -}, Ae = async function() { +}, Ie = async function() { if (typeof h(this, L) == "string") { - const e = await nt(h(this, L)); + const e = await ot(h(this, L)); this.authServerUrl = e["auth-server-url"], this.realm = e.realm, this.clientId = e.resource, d(this, s, ae).call(this); } else - this.clientId = h(this, L).clientId, "oidcProvider" in h(this, L) ? await d(this, s, Ie).call(this, h(this, L).oidcProvider) : (this.authServerUrl = h(this, L).url, this.realm = h(this, L).realm, d(this, s, ae).call(this)); + this.clientId = h(this, L).clientId, "oidcProvider" in h(this, L) ? await d(this, s, xe).call(this, h(this, L).oidcProvider) : (this.authServerUrl = h(this, L).url, this.realm = h(this, L).realm, d(this, s, ae).call(this)); }, /** * @returns {void} */ @@ -959,9 +959,9 @@ ae = function() { register: () => d(this, s, R).call(this) + "/protocol/openid-connect/registrations", userinfo: () => d(this, s, R).call(this) + "/protocol/openid-connect/userinfo" }; -}, Ie = async function(e) { +}, xe = async function(e) { if (typeof e == "string") { - const t = `${Te(e)}/.well-known/openid-configuration`, i = await st(t); + const t = `${Ue(e)}/.well-known/openid-configuration`, i = await nt(t); d(this, s, ce).call(this, i); } else d(this, s, ce).call(this, e); @@ -996,7 +996,7 @@ ce = function(e) { return e.userinfo_endpoint; } }; -}, xe = async function() { +}, Le = async function() { if (!h(this, y).enable && !this.silentCheckSsoRedirectUri || typeof this.endpoints.thirdPartyCookiesIframe != "function") return; const e = document.createElement("iframe"); @@ -1012,12 +1012,12 @@ For more information see: https://www.keycloak.org/securing-apps/javascript-adap }; window.addEventListener("message", n, !1); }); - return await Qe(t, this.messageReceiveTimeout, "Timeout when waiting for 3rd party check iframe message."); -}, Le = async function(e) { + return await Ge(t, this.messageReceiveTimeout, "Timeout when waiting for 3rd party check iframe message."); +}, Re = async function(e) { var o, c, a; - const t = d(this, s, P).call(this, window.location.href); + const t = d(this, s, z).call(this, window.location.href); if (t != null && t.newUrl && window.history.replaceState(window.history.state, "", t.newUrl), t && t.valid) { - await d(this, s, te).call(this), await d(this, s, z).call(this, t); + await d(this, s, te).call(this), await d(this, s, P).call(this, t); return; } const i = async (l) => { @@ -1087,9 +1087,9 @@ For more information see: https://www.keycloak.org/securing-apps/javascript-adap const o = async (c) => { if (c.origin !== window.location.origin || e.contentWindow !== c.source) return; - const a = d(this, s, P).call(this, c.data); + const a = d(this, s, z).call(this, c.data); try { - await d(this, s, z).call(this, a), i(); + await d(this, s, P).call(this, a), i(); } catch (l) { n(l); } @@ -1100,8 +1100,8 @@ For more information see: https://www.keycloak.org/securing-apps/javascript-adap }, /** * @param {string} url */ -P = function(e) { - const t = d(this, s, Re).call(this, e); +z = function(e) { + const t = d(this, s, Me).call(this, e); if (!t) return; const i = h(this, J).get(t.state); @@ -1109,7 +1109,7 @@ P = function(e) { }, /** * @param {string} urlString */ -Re = function(e) { +Me = function(e) { let t = []; switch (this.flow) { case "standard": @@ -1158,7 +1158,7 @@ de = function(e, t) { paramsString: o, oauthParams: n }; -}, z = async function(e) { +}, P = async function(e) { var a, l, u, w; const { code: t, error: i, prompt: n } = e; let o = (/* @__PURE__ */ new Date()).getTime(); @@ -1178,7 +1178,7 @@ de = function(e, t) { } else this.flow !== "standard" && (e.access_token || e.id_token) && (c(e.access_token, void 0, e.id_token), (l = this.onAuthSuccess) == null || l.call(this)); if (this.flow !== "implicit" && t) try { - const m = await at( + const m = await st( this.endpoints.token(), t, /** @type {string} */ @@ -1191,7 +1191,7 @@ de = function(e, t) { throw (w = this.onAuthError) == null || w.call(this), m; } }, re = async function() { - h(this, y).enable && this.token && (await dt(h(this, y).interval * 1e3), await d(this, s, X).call(this) && await d(this, s, re).call(this)); + h(this, y).enable && this.token && (await lt(h(this, y).interval * 1e3), await d(this, s, X).call(this) && await d(this, s, re).call(this)); }, /** * @param {string} [token] * @param {string} [refreshToken] @@ -1211,7 +1211,7 @@ Z = function(e, t, i, n) { */ R = function() { if (!(typeof this.authServerUrl > "u")) - return `${Te(this.authServerUrl)}/realms/${encodeURIComponent( + return `${Ue(this.authServerUrl)}/realms/${encodeURIComponent( /** @type {string} */ this.realm )}`; @@ -1224,39 +1224,39 @@ ue = function(e) { this.enableLogging && e.call(console, t); }; }; -function Se() { +function Ce() { if (typeof crypto > "u" || typeof crypto.randomUUID > "u") throw new Error("Web Crypto API is not available."); return crypto.randomUUID(); } -function Ye(r) { +function He(r) { return JSON.stringify({ id_token: { acr: r } }); } -function $e(r) { - return qe(r, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); +function Ye(r) { + return Je(r, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); } -async function Je(r, e) { +async function $e(r, e) { if (r !== "S256") throw new TypeError(`Invalid value for 'pkceMethod', expected 'S256' but got '${r}'.`); - const t = new Uint8Array(await rt(e)); - return tt(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + const t = new Uint8Array(await tt(e)); + return et(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } -function qe(r, e) { - const t = Ge(r), i = new Array(r); +function Je(r, e) { + const t = qe(r), i = new Array(r); for (let n = 0; n < r; n++) i[n] = e.charCodeAt(t[n] % e.length); return String.fromCharCode.apply(null, i); } -function Ge(r) { +function qe(r) { if (typeof crypto > "u" || typeof crypto.getRandomValues > "u") throw new Error("Web Crypto API is not available."); return crypto.getRandomValues(new Uint8Array(r)); } -function Qe(r, e, t) { +function Ge(r, e, t) { let i; const n = new Promise(function(o, c) { i = window.setTimeout(function() { @@ -1267,16 +1267,16 @@ function Qe(r, e, t) { clearTimeout(i); }); } -function Xe() { +function Qe() { try { - return new Ze(); + return new Xe(); } catch { - return new et(); + return new Ze(); } } const Y = "kc-callback-"; -var x, he, Me, fe, De; -class Ze { +var x, he, De, fe, Ke; +class Xe { constructor() { A(this, x); globalThis.localStorage.setItem("kc-test", "test"), globalThis.localStorage.removeItem("kc-test"); @@ -1305,7 +1305,7 @@ class Ze { try { globalThis.localStorage.setItem(t, i); } catch { - d(this, x, Me).call(this), globalThis.localStorage.setItem(t, i); + d(this, x, De).call(this), globalThis.localStorage.setItem(t, i); } } } @@ -1315,13 +1315,13 @@ x = new WeakSet(), /** he = function() { const e = Date.now(); for (const [t, i] of d(this, x, fe).call(this)) { - const n = d(this, x, De).call(this, i); + const n = d(this, x, Ke).call(this, i); (n === null || n < e) && globalThis.localStorage.removeItem(t); } }, /** * Clears all known values from local storage. */ -Me = function() { +De = function() { for (const [e] of d(this, x, fe).call(this)) globalThis.localStorage.removeItem(e); }, /** @@ -1335,7 +1335,7 @@ fe = function() { * @param {string} value * @returns {number | null} The expiry time in milliseconds, or `null` if the value is malformed. */ -De = function(e) { +Ke = function(e) { let t; try { t = JSON.parse(e); @@ -1344,8 +1344,8 @@ De = function(e) { } return me(t) && "expires" in t && typeof t.expires == "number" ? t.expires : null; }; -var D, Ke, pe, we; -class et { +var D, Ne, pe, we; +class Ze { constructor() { A(this, D); } @@ -1356,7 +1356,7 @@ class et { get(e) { if (!e) return null; - const t = d(this, D, Ke).call(this, Y + e); + const t = d(this, D, Ne).call(this, Y + e); return d(this, D, pe).call(this, Y + e, "", d(this, D, we).call(this, -100)), t ? JSON.parse(t) : null; } /** @@ -1370,7 +1370,7 @@ D = new WeakSet(), /** * @param {string} key * @returns */ -Ke = function(e) { +Ne = function(e) { const t = e + "=", i = document.cookie.split(";"); for (let n = 0; n < i.length; n++) { let o = i[n]; @@ -1396,11 +1396,11 @@ we = function(e) { const t = /* @__PURE__ */ new Date(); return t.setTime(t.getTime() + e * 60 * 1e3), t; }; -function tt(r) { +function et(r) { const e = String.fromCodePoint(...r); return btoa(e); } -async function rt(r) { +async function tt(r) { const t = new TextEncoder().encode(r); if (typeof crypto > "u" || typeof crypto.subtle > "u") throw new Error("Web Crypto API is not available."); @@ -1412,7 +1412,7 @@ function ne(r) { throw new Error("Unable to decode token, payload not found."); let t; try { - t = it(e); + t = rt(e); } catch (i) { throw new Error("Unable to decode token, payload is not a valid Base64URL value.", { cause: i }); } @@ -1422,7 +1422,7 @@ function ne(r) { throw new Error("Unable to decode token, payload is not a valid JSON value.", { cause: i }); } } -function it(r) { +function rt(r) { let e = r.replaceAll("-", "+").replaceAll("_", "/"); switch (e.length % 4) { case 0: @@ -1437,12 +1437,12 @@ function it(r) { throw new Error("Input is not of the correct length."); } try { - return ot(e); + return it(e); } catch { return atob(e); } } -function ot(r) { +function it(r) { return decodeURIComponent(atob(r).replace(/(.)/g, (e, t) => { let i = t.charCodeAt(0).toString(16).toUpperCase(); return i.length < 2 && (i = "0" + i), "%" + i; @@ -1451,13 +1451,13 @@ function ot(r) { function me(r) { return typeof r == "object" && r !== null; } +async function ot(r) { + return await Q(r); +} async function nt(r) { return await Q(r); } -async function st(r) { - return await Q(r); -} -async function at(r, e, t, i, n) { +async function st(r, e, t, i, n) { const o = new URLSearchParams([ ["code", e], ["grant_type", "authorization_code"], @@ -1470,7 +1470,7 @@ async function at(r, e, t, i, n) { body: o }); } -async function ct(r, e, t) { +async function at(r, e, t) { const i = new URLSearchParams([ ["grant_type", "refresh_token"], ["refresh_token", e], @@ -1484,26 +1484,26 @@ async function ct(r, e, t) { } async function Q(r, e = {}) { const t = new Headers(e.headers); - return t.set("Accept", Ve), await (await lt(r, { + return t.set("Accept", Ve), await (await ct(r, { ...e, headers: t })).json(); } -async function lt(r, e) { +async function ct(r, e) { const t = await fetch(r, e); if (!t.ok) - throw new Ne("Server responded with an invalid status.", { response: t }); + throw new Be("Server responded with an invalid status.", { response: t }); return t; } -function Ce(r) { +function Te(r) { if (!r) throw new Error("Unable to build authorization header, token is not set, make sure the user is authenticated."); return ["Authorization", `bearer ${r}`]; } -function Te(r) { +function Ue(r) { return r.endsWith("/") ? r.slice(0, -1) : r; } -class Ne extends Error { +class Be extends Error { /** * @param {string} message * @param {NetworkErrorOptions} options @@ -1515,11 +1515,11 @@ class Ne extends Error { this.response = i.response; } } -const dt = (r) => new Promise((e) => setTimeout(e, r)), ut = "https://auth.ibagher.ir", ht = "bi"; -let b = null, se = null; -const Be = Oe(null), ft = (r) => (b || (b = new He({ - url: ut, - realm: ht, +const lt = (r) => new Promise((e) => setTimeout(e, r)), dt = "https://auth.ibagher.ir", ut = "bi"; +let b = null, se = null, ge = !1; +const ht = Oe(null), ft = (r) => (b || (b = new Fe({ + url: dt, + realm: ut, clientId: r })), b), pt = ({ clientId: r, initOptions: e = {} }) => { const t = ft(r); @@ -1528,8 +1528,10 @@ const Be = Oe(null), ft = (r) => (b || (b = new He({ checkLoginIframe: !1, flow: "implicit", ...e + }).then((i) => (ge = !0, i)).catch((i) => { + throw ge = !0, i; })), se; -}, Tt = () => !!(b != null && b.authenticated), Ut = () => (b == null ? void 0 : b.token) ?? null, _t = async (r = 30) => b ? b.updateToken(r) : !1, Et = (r) => b == null ? void 0 : b.logout(r), At = (r) => b == null ? void 0 : b.login(r), It = ({ +}, Tt = () => ge, Ut = () => !!(b != null && b.authenticated), _t = () => (b == null ? void 0 : b.token) ?? null, Et = async (r = 30) => b ? b.updateToken(r) : !1, At = (r) => b == null ? void 0 : b.logout(r), It = (r) => b == null ? void 0 : b.login(r), xt = ({ children: r, clientId: e, initOptions: t, @@ -1548,8 +1550,8 @@ const Be = Oe(null), ft = (r) => (b || (b = new He({ const T = H(() => b == null ? void 0 : b.login(), []), p = H((C) => b == null ? void 0 : b.logout(C), []), k = H( async (C = 30) => { if (!b) return !1; - const V = await b.updateToken(C); - return m(), V; + const F = await b.updateToken(C); + return m(), F; }, [m] ), g = We( @@ -1563,26 +1565,21 @@ const Be = Oe(null), ft = (r) => (b || (b = new He({ }), [n, c, l, T, p, k] ); - return n ? /* @__PURE__ */ S(Be.Provider, { value: g, children: r }) : i; -}, xt = () => { - const r = Fe(Be); - if (!r) - throw new Error("useKeycloak must be used inside KeycloakProvider"); - return r; + return n ? /* @__PURE__ */ S(ht.Provider, { value: g, children: r }) : i; }; export { - It as KeycloakProvider, + xt as KeycloakProvider, vt as LightPagination, St as Pagination, Ct as SimplePagination, - Ut as getKeycloakToken, + _t as getKeycloakToken, pt as initKeycloak, - Tt as isKeycloakAuthenticated, - At as loginKeycloak, - Et as logoutKeycloak, - F as toEnDigits, + Ut as isKeycloakAuthenticated, + Tt as isKeycloakInitialized, + It as loginKeycloak, + At as logoutKeycloak, + V as toEnDigits, v as toFaDigits, yt as toFaNumber, - _t as updateKeycloakToken, - xt as useKeycloak + Et as updateKeycloakToken }; diff --git a/src/core/keycloak.jsx b/src/core/keycloak.jsx index 650543c..bacf56c 100644 --- a/src/core/keycloak.jsx +++ b/src/core/keycloak.jsx @@ -14,6 +14,7 @@ const KEYCLOAK_REALM = "bi"; let keycloakInstance = null; let initPromise = null; +let initializedValue = false; const KeycloakContext = createContext(null); @@ -25,25 +26,35 @@ const createKeycloak = (clientId) => { clientId, }); } - return keycloakInstance; }; export const initKeycloak = ({ clientId, initOptions = {} }) => { const keycloak = createKeycloak(clientId); - if (!initPromise) { - initPromise = keycloak.init({ - onLoad: "login-required", - checkLoginIframe: false, - flow: "implicit", - ...initOptions, - }); + initPromise = keycloak + .init({ + onLoad: "login-required", + checkLoginIframe: false, + flow: "implicit", + ...initOptions, + }) + .then((auth) => { + initializedValue = true; + return auth; + }) + .catch((error) => { + initializedValue = true; + throw error; + }); } - return initPromise; }; +export const isKeycloakInitialized = () => { + return initializedValue; +}; + export const isKeycloakAuthenticated = () => { return Boolean(keycloakInstance?.authenticated); }; @@ -79,30 +90,25 @@ export const KeycloakProvider = ({ const syncState = useCallback(() => { if (!keycloakInstance) return; - setAuthenticated(Boolean(keycloakInstance.authenticated)); setToken(keycloakInstance.token ?? null); }, []); useEffect(() => { mountedRef.current = true; - initKeycloak({ clientId, initOptions }) .then((auth) => { if (!mountedRef.current) return; - setAuthenticated(Boolean(auth)); setToken(keycloakInstance?.token ?? null); setInitialized(true); }) .catch(() => { if (!mountedRef.current) return; - setAuthenticated(false); setToken(null); setInitialized(true); }); - return () => { mountedRef.current = false; }; @@ -119,11 +125,8 @@ export const KeycloakProvider = ({ const updateToken = useCallback( async (minValidity = 30) => { if (!keycloakInstance) return false; - const refreshed = await keycloakInstance.updateToken(minValidity); - syncState(); - return refreshed; }, [syncState], @@ -150,12 +153,12 @@ export const KeycloakProvider = ({ ); }; -export const useKeycloak = () => { - const context = useContext(KeycloakContext); +// const useKeycloak = () => { +// const context = useContext(KeycloakContext); - if (!context) { - throw new Error("useKeycloak must be used inside KeycloakProvider"); - } +// if (!context) { +// throw new Error("useKeycloak must be used inside KeycloakProvider"); +// } - return context; -}; +// return context; +// }; diff --git a/src/index.js b/src/index.js index d3fa8dc..28cb1ae 100644 --- a/src/index.js +++ b/src/index.js @@ -6,8 +6,8 @@ export { SimplePagination } from "./components/pagination/SimplePagination.jsx"; export { KeycloakProvider, - useKeycloak, initKeycloak, + isKeycloakInitialized, isKeycloakAuthenticated, getKeycloakToken, updateKeycloakToken,