update api.js

This commit is contained in:
Mohamadzadeh 2026-06-13 14:00:57 +03:30
parent f2654dbab1
commit f2f8ef17fe
4 changed files with 388 additions and 313 deletions

595
dist/index.js vendored
View File

@ -1,55 +1,55 @@
import { jsxs as I, jsx as u } from "react/jsx-runtime"; import { jsxs as I, jsx as a } from "react/jsx-runtime";
import { useState as B, useRef as T, useEffect as A, useCallback as D, createContext as U, useMemo as F, useContext as H } from "react"; import { useState as B, useRef as z, useEffect as C, useCallback as E, createContext as G, useMemo as R, useContext as Z } from "react";
import { HStack as S, IconButton as K, Button as j, Input as L, Text as k } from "@chakra-ui/react"; import { HStack as k, IconButton as D, Button as V, Input as W, Text as S } from "@chakra-ui/react";
import { IoChevronForwardOutline as V, IoChevronBackOutline as W } from "react-icons/io5"; import { IoChevronForwardOutline as O, IoChevronBackOutline as q } from "react-icons/io5";
import X from "keycloak-js"; import P from "keycloak-js";
import { useQuery as Z } from "@tanstack/react-query"; import { useQuery as ee } from "@tanstack/react-query";
import P from "axios"; import te from "axios";
const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => String(e).replace(/\d/g, (t) => "۰۱۲۳۴۵۶۷۸۹"[Number(t)]), E = (e) => String(e).replace(/[۰-۹]/g, (o) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(o))), ye = ({ const Be = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), p = (e) => String(e).replace(/\d/g, (t) => "۰۱۲۳۴۵۶۷۸۹"[Number(t)]), K = (e) => String(e).replace(/[۰-۹]/g, (r) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(r))), Ce = ({
currentPage: e, currentPage: e,
totalPages: t, totalPages: t,
totalCount: o, totalCount: r,
onPageChange: l onPageChange: l
}) => { }) => {
const [d, i] = B(f(e)), [w, r] = B(!1), [s, c] = B(null), m = T(null), y = [.../* @__PURE__ */ new Set([1, e, t])].filter( const [c, i] = B(p(e)), [u, o] = B(!1), [f, s] = B(null), w = z(null), y = [.../* @__PURE__ */ new Set([1, e, t])].filter(
(n) => n >= 1 && n <= t (n) => n >= 1 && n <= t
); );
A(() => { C(() => {
if (s !== null) { if (f !== null) {
e === s && (c(null), r(!1), i(f(e))); e === f && (s(null), o(!1), i(p(e)));
return; return;
} }
w || i(f(e)); u || i(p(e));
}, [e, w, s]), A(() => { }, [e, u, f]), C(() => {
if (!w || !d || s !== null) return; if (!u || !c || f !== null) return;
const n = parseInt(E(d), 10); const n = parseInt(K(c), 10);
if (isNaN(n)) return; if (isNaN(n)) return;
const p = setTimeout(() => { const h = setTimeout(() => {
var b; var b;
const h = Math.min(Math.max(n, 1), t); const m = Math.min(Math.max(n, 1), t);
h !== e ? (c(h), i(f(h)), l(h)) : (r(!1), i(f(e))), (b = m.current) == null || b.blur(); m !== e ? (s(m), i(p(m)), l(m)) : (o(!1), i(p(e))), (b = w.current) == null || b.blur();
}, 1e3); }, 1e3);
return () => clearTimeout(p); return () => clearTimeout(h);
}, [ }, [
d, c,
w, u,
s, f,
t, t,
e, e,
l l
]); ]);
const v = () => { const v = () => {
var h, b; var m, b;
const n = parseInt(E(d), 10); const n = parseInt(K(c), 10);
if (isNaN(n)) { if (isNaN(n)) {
i(f(e)), r(!1), c(null), (h = m.current) == null || h.blur(); i(p(e)), o(!1), s(null), (m = w.current) == null || m.blur();
return; return;
} }
const p = Math.min(Math.max(n, 1), t); const h = Math.min(Math.max(n, 1), t);
p !== e ? (c(p), i(f(p)), l(p)) : (i(f(e)), r(!1), c(null)), (b = m.current) == null || b.blur(); h !== e ? (s(h), i(p(h)), l(h)) : (i(p(e)), o(!1), s(null)), (b = w.current) == null || b.blur();
}; };
return t === 0 || !o ? null : /* @__PURE__ */ I( return t === 0 || !r ? null : /* @__PURE__ */ I(
S, k,
{ {
justifyContent: "space-around", justifyContent: "space-around",
backgroundColor: "white", backgroundColor: "white",
@ -60,9 +60,9 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
borderColor: "blue.200", borderColor: "blue.200",
w: "100%", w: "100%",
children: [ children: [
/* @__PURE__ */ I(S, { spacing: 2, alignItems: "center", justifyContent: "center", children: [ /* @__PURE__ */ I(k, { spacing: 2, alignItems: "center", justifyContent: "center", children: [
/* @__PURE__ */ u( /* @__PURE__ */ a(
K, D,
{ {
size: "md", size: "md",
bg: "#e6e6f1", bg: "#e6e6f1",
@ -70,12 +70,12 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: "#cbcbe8" }, _hover: { bg: "#cbcbe8" },
onClick: () => l(e - 1), onClick: () => l(e - 1),
isDisabled: e === 1, isDisabled: e === 1,
icon: /* @__PURE__ */ u(V, {}), icon: /* @__PURE__ */ a(O, {}),
"aria-label": "صفحه قبلی" "aria-label": "صفحه قبلی"
} }
), ),
y.map((n) => /* @__PURE__ */ u( y.map((n) => /* @__PURE__ */ a(
j, V,
{ {
size: "md", size: "md",
px: 2, px: 2,
@ -84,12 +84,12 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: e === n ? "#4B49AC" : "#cbcbe8" }, _hover: { bg: e === n ? "#4B49AC" : "#cbcbe8" },
onClick: () => l(n), onClick: () => l(n),
variant: "soft", variant: "soft",
children: f(n) children: p(n)
}, },
n n
)), )),
/* @__PURE__ */ u( /* @__PURE__ */ a(
K, D,
{ {
size: "md", size: "md",
bg: "#e6e6f1", bg: "#e6e6f1",
@ -97,28 +97,28 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: "#cbcbe8" }, _hover: { bg: "#cbcbe8" },
onClick: () => l(e + 1), onClick: () => l(e + 1),
isDisabled: e === t, isDisabled: e === t,
icon: /* @__PURE__ */ u(W, {}), icon: /* @__PURE__ */ a(q, {}),
"aria-label": "صفحه بعدی" "aria-label": "صفحه بعدی"
} }
), ),
/* @__PURE__ */ u( /* @__PURE__ */ a(
L, W,
{ {
ref: m, ref: w,
type: "text", type: "text",
inputMode: "numeric", inputMode: "numeric",
placeholder: "صفحه", placeholder: "صفحه",
w: "56px", w: "56px",
value: d, value: c,
onFocus: () => { onFocus: () => {
r(!0), c(null), i(""); o(!0), s(null), i("");
}, },
onChange: (n) => { onChange: (n) => {
const p = n.target.value, h = E(p).replace(/\D/g, ""); const h = n.target.value, m = K(h).replace(/\D/g, "");
i(f(h)); i(p(m));
}, },
onBlur: () => { onBlur: () => {
d || (i(f(e)), r(!1), c(null)); c || (i(p(e)), o(!1), s(null));
}, },
onKeyDown: (n) => { onKeyDown: (n) => {
n.key === "Enter" && v(); n.key === "Enter" && v();
@ -131,58 +131,58 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
} }
) )
] }), ] }),
/* @__PURE__ */ I(S, { spacing: 2, children: [ /* @__PURE__ */ I(k, { spacing: 2, children: [
/* @__PURE__ */ u(k, { w: "auto", fontWeight: "bold", whiteSpace: "nowrap", children: "تعداد کل:" }), /* @__PURE__ */ a(S, { w: "auto", fontWeight: "bold", whiteSpace: "nowrap", children: "تعداد کل:" }),
/* @__PURE__ */ u(k, { children: f(o) }) /* @__PURE__ */ a(S, { children: p(r) })
] }) ] })
] ]
} }
); );
}, xe = ({ }, ke = ({
currentPage: e, currentPage: e,
totalPages: t, totalPages: t,
totalCount: o, totalCount: r,
onPageChange: l onPageChange: l
}) => { }) => {
const [d, i] = B(f(e)), [w, r] = B(!1), [s, c] = B(null), m = T(null), y = Array.from( const [c, i] = B(p(e)), [u, o] = B(!1), [f, s] = B(null), w = z(null), y = Array.from(
/* @__PURE__ */ new Set([1, e, e + 1, t]) /* @__PURE__ */ new Set([1, e, e + 1, t])
).filter((n) => n >= 1 && n <= t).sort((n, p) => n - p); ).filter((n) => n >= 1 && n <= t).sort((n, h) => n - h);
A(() => { C(() => {
if (s !== null) { if (f !== null) {
e === s && (c(null), r(!1), i(f(e))); e === f && (s(null), o(!1), i(p(e)));
return; return;
} }
w || i(f(e)); u || i(p(e));
}, [e, w, s]), A(() => { }, [e, u, f]), C(() => {
if (!w || !d || s !== null) return; if (!u || !c || f !== null) return;
const n = parseInt(E(d), 10); const n = parseInt(K(c), 10);
if (isNaN(n)) return; if (isNaN(n)) return;
const p = setTimeout(() => { const h = setTimeout(() => {
var b; var b;
const h = Math.min(Math.max(n, 1), t); const m = Math.min(Math.max(n, 1), t);
h !== e ? (c(h), i(f(h)), l(h)) : (r(!1), i(f(e))), (b = m.current) == null || b.blur(); m !== e ? (s(m), i(p(m)), l(m)) : (o(!1), i(p(e))), (b = w.current) == null || b.blur();
}, 1e3); }, 1e3);
return () => clearTimeout(p); return () => clearTimeout(h);
}, [ }, [
d, c,
w, u,
s, f,
t, t,
e, e,
l l
]); ]);
const v = () => { const v = () => {
var h, b; var m, b;
const n = parseInt(E(d), 10); const n = parseInt(K(c), 10);
if (isNaN(n)) { if (isNaN(n)) {
i(f(e)), r(!1), c(null), (h = m.current) == null || h.blur(); i(p(e)), o(!1), s(null), (m = w.current) == null || m.blur();
return; return;
} }
const p = Math.min(Math.max(n, 1), t); const h = Math.min(Math.max(n, 1), t);
p !== e ? (c(p), i(f(p)), l(p)) : (i(f(e)), r(!1), c(null)), (b = m.current) == null || b.blur(); h !== e ? (s(h), i(p(h)), l(h)) : (i(p(e)), o(!1), s(null)), (b = w.current) == null || b.blur();
}; };
return t === 0 || !o ? null : /* @__PURE__ */ I( return t === 0 || !r ? null : /* @__PURE__ */ I(
S, k,
{ {
justifyContent: "space-around", justifyContent: "space-around",
backgroundColor: "white", backgroundColor: "white",
@ -193,15 +193,15 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
borderColor: "blue.200", borderColor: "blue.200",
w: "100%", w: "100%",
children: [ children: [
/* @__PURE__ */ I(S, { spacing: 2, whiteSpace: "nowrap", children: [ /* @__PURE__ */ I(k, { spacing: 2, whiteSpace: "nowrap", children: [
/* @__PURE__ */ u(k, { fontWeight: "bold", children: "صفحه" }), /* @__PURE__ */ a(S, { fontWeight: "bold", children: "صفحه" }),
/* @__PURE__ */ u(k, { children: f(e) }), /* @__PURE__ */ a(S, { children: p(e) }),
/* @__PURE__ */ u(k, { fontWeight: "bold", children: "از" }), /* @__PURE__ */ a(S, { fontWeight: "bold", children: "از" }),
/* @__PURE__ */ u(k, { children: f(t) }) /* @__PURE__ */ a(S, { children: p(t) })
] }), ] }),
/* @__PURE__ */ I(S, { spacing: 2, alignItems: "center", justifyContent: "center", children: [ /* @__PURE__ */ I(k, { spacing: 2, alignItems: "center", justifyContent: "center", children: [
/* @__PURE__ */ u( /* @__PURE__ */ a(
K, D,
{ {
size: "md", size: "md",
bg: "#e6e6f1", bg: "#e6e6f1",
@ -209,12 +209,12 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: "#cbcbe8" }, _hover: { bg: "#cbcbe8" },
onClick: () => l(e - 1), onClick: () => l(e - 1),
isDisabled: e === 1, isDisabled: e === 1,
icon: /* @__PURE__ */ u(V, {}), icon: /* @__PURE__ */ a(O, {}),
"aria-label": "صفحه قبلی" "aria-label": "صفحه قبلی"
} }
), ),
y.map((n) => /* @__PURE__ */ u( y.map((n) => /* @__PURE__ */ a(
j, V,
{ {
size: "md", size: "md",
bg: e === n ? "#4B49AC" : "#e6e6f1", bg: e === n ? "#4B49AC" : "#e6e6f1",
@ -222,12 +222,12 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: e === n ? "#4B49AC" : "#cbcbe8" }, _hover: { bg: e === n ? "#4B49AC" : "#cbcbe8" },
onClick: () => l(n), onClick: () => l(n),
variant: "soft", variant: "soft",
children: f(n) children: p(n)
}, },
n n
)), )),
/* @__PURE__ */ u( /* @__PURE__ */ a(
K, D,
{ {
size: "md", size: "md",
bg: "#e6e6f1", bg: "#e6e6f1",
@ -235,28 +235,28 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: "#cbcbe8" }, _hover: { bg: "#cbcbe8" },
onClick: () => l(e + 1), onClick: () => l(e + 1),
isDisabled: e === t, isDisabled: e === t,
icon: /* @__PURE__ */ u(W, {}), icon: /* @__PURE__ */ a(q, {}),
"aria-label": "صفحه بعدی" "aria-label": "صفحه بعدی"
} }
), ),
/* @__PURE__ */ u( /* @__PURE__ */ a(
L, W,
{ {
ref: m, ref: w,
type: "text", type: "text",
inputMode: "numeric", inputMode: "numeric",
placeholder: "صفحه", placeholder: "صفحه",
w: "100px", w: "100px",
value: d, value: c,
onFocus: () => { onFocus: () => {
r(!0), c(null), i(""); o(!0), s(null), i("");
}, },
onChange: (n) => { onChange: (n) => {
const p = n.target.value, h = E(p).replace(/\D/g, ""); const h = n.target.value, m = K(h).replace(/\D/g, "");
i(f(h)); i(p(m));
}, },
onBlur: () => { onBlur: () => {
d || (i(f(e)), r(!1), c(null)); c || (i(p(e)), o(!1), s(null));
}, },
onKeyDown: (n) => { onKeyDown: (n) => {
n.key === "Enter" && v(); n.key === "Enter" && v();
@ -269,69 +269,69 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
} }
) )
] }), ] }),
/* @__PURE__ */ I(S, { spacing: 2, whiteSpace: "nowrap", children: [ /* @__PURE__ */ I(k, { spacing: 2, whiteSpace: "nowrap", children: [
/* @__PURE__ */ u(k, { fontWeight: "bold", children: "تعداد کل:" }), /* @__PURE__ */ a(S, { fontWeight: "bold", children: "تعداد کل:" }),
/* @__PURE__ */ u(k, { children: f(o) }) /* @__PURE__ */ a(S, { children: p(r) })
] }) ] })
] ]
} }
); );
}, ve = ({ }, Se = ({
currentPage: e, currentPage: e,
totalPages: t, totalPages: t,
totalCount: o, totalCount: r,
onPageChange: l onPageChange: l
}) => { }) => {
const [d, i] = B(""), [w, r] = B(!1), [s, c] = B(null), m = T(null), y = s ?? e, v = D( const [c, i] = B(""), [u, o] = B(!1), [f, s] = B(null), w = z(null), y = f ?? e, v = E(
(x) => { (x) => {
const C = Math.min(Math.max(x, 1), t); const A = Math.min(Math.max(x, 1), t);
r(!1), i(""), c(null), C !== e && l(C); o(!1), i(""), s(null), A !== e && l(A);
}, },
[e, t, l] [e, t, l]
), n = D(() => { ), n = E(() => {
if (!d) { if (!c) {
r(!1), i(""), c(null); o(!1), i(""), s(null);
return; return;
} }
const x = parseInt(E(d), 10); const x = parseInt(K(c), 10);
if (isNaN(x)) { if (isNaN(x)) {
r(!1), i(""), c(null); o(!1), i(""), s(null);
return; return;
} }
const C = Math.min(Math.max(x, 1), t); const A = Math.min(Math.max(x, 1), t);
r(!1), i(""), C !== e ? (c(C), l(C)) : c(null); o(!1), i(""), A !== e ? (s(A), l(A)) : s(null);
}, [d, e, t, l]); }, [c, e, t, l]);
A(() => { C(() => {
var x; var x;
w && ((x = m.current) == null || x.focus()); u && ((x = w.current) == null || x.focus());
}, [w]), A(() => { }, [u]), C(() => {
s !== null && e === s && c(null); f !== null && e === f && s(null);
}, [e, s]), A(() => { }, [e, f]), C(() => {
if (!w || !d) return; if (!u || !c) return;
const x = setTimeout(() => { const x = setTimeout(() => {
n(); n();
}, 1e3); }, 1e3);
return () => clearTimeout(x); return () => clearTimeout(x);
}, [d, w, n]); }, [c, u, n]);
const p = () => { const h = () => {
c(null), i(""), r(!0); s(null), i(""), o(!0);
}, h = (x, C = !1) => /* @__PURE__ */ u( }, m = (x, A = !1) => /* @__PURE__ */ a(
j, V,
{ {
size: "md", size: "md",
bg: C ? "#4B49AC" : "#e6e6f1", bg: A ? "#4B49AC" : "#e6e6f1",
color: C ? "#e6e6f1" : "#4B49AC", color: A ? "#e6e6f1" : "#4B49AC",
_hover: { bg: C ? "#4B49AC" : "#cbcbe8" }, _hover: { bg: A ? "#4B49AC" : "#cbcbe8" },
onClick: C ? p : () => v(x), onClick: A ? h : () => v(x),
variant: "soft", variant: "soft",
children: f(x) children: p(x)
}, },
x x
); );
if (t === 0 || !o) return null; if (t === 0 || !r) return null;
const b = t > 1 && y !== 1, M = t > 1 && y !== t; const b = t > 1 && y !== 1, _ = t > 1 && y !== t;
return /* @__PURE__ */ u( return /* @__PURE__ */ a(
S, k,
{ {
justifyContent: "center", justifyContent: "center",
backgroundColor: "white", backgroundColor: "white",
@ -341,9 +341,9 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
border: "1px", border: "1px",
borderColor: "blue.200", borderColor: "blue.200",
w: "100%", w: "100%",
children: /* @__PURE__ */ I(S, { spacing: 2, alignItems: "center", justifyContent: "center", children: [ children: /* @__PURE__ */ I(k, { spacing: 2, alignItems: "center", justifyContent: "center", children: [
/* @__PURE__ */ u( /* @__PURE__ */ a(
K, D,
{ {
size: "md", size: "md",
bg: "#e6e6f1", bg: "#e6e6f1",
@ -351,29 +351,29 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: "#cbcbe8" }, _hover: { bg: "#cbcbe8" },
onClick: () => v(y - 1), onClick: () => v(y - 1),
isDisabled: y === 1, isDisabled: y === 1,
icon: /* @__PURE__ */ u(V, {}), icon: /* @__PURE__ */ a(O, {}),
"aria-label": "صفحه قبلی" "aria-label": "صفحه قبلی"
} }
), ),
b && h(1), b && m(1),
w ? /* @__PURE__ */ u( u ? /* @__PURE__ */ a(
L, W,
{ {
ref: m, ref: w,
type: "text", type: "text",
inputMode: "numeric", inputMode: "numeric",
placeholder: "صفحه", placeholder: "صفحه",
w: "48px", w: "48px",
value: d, value: c,
onChange: (x) => { onChange: (x) => {
const C = x.target.value, g = E(C).replace(/\D/g, ""); const A = x.target.value, X = K(A).replace(/\D/g, "");
i(f(g)); i(p(X));
}, },
onBlur: () => { onBlur: () => {
d ? n() : (i(""), r(!1), c(null)); c ? n() : (i(""), o(!1), s(null));
}, },
onKeyDown: (x) => { onKeyDown: (x) => {
x.key === "Enter" && n(), x.key === "Escape" && (i(""), r(!1), c(null)); x.key === "Enter" && n(), x.key === "Escape" && (i(""), o(!1), s(null));
}, },
textAlign: "center", textAlign: "center",
color: "#1D2939", color: "#1D2939",
@ -381,10 +381,10 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
minW: 0, minW: 0,
dir: "ltr" dir: "ltr"
} }
) : h(y, !0), ) : m(y, !0),
M && h(t), _ && m(t),
/* @__PURE__ */ u( /* @__PURE__ */ a(
K, D,
{ {
size: "md", size: "md",
bg: "#e6e6f1", bg: "#e6e6f1",
@ -392,7 +392,7 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
_hover: { bg: "#cbcbe8" }, _hover: { bg: "#cbcbe8" },
onClick: () => v(y + 1), onClick: () => v(y + 1),
isDisabled: y === t, isDisabled: y === t,
icon: /* @__PURE__ */ u(W, {}), icon: /* @__PURE__ */ a(q, {}),
"aria-label": "صفحه بعدی" "aria-label": "صفحه بعدی"
} }
) )
@ -400,88 +400,92 @@ const we = (e) => new Intl.NumberFormat("fa-IR").format(Number(e)), f = (e) => S
} }
); );
}; };
let a = null, _ = null, R = !1; let j = null, d = null, F = null, L = !1;
const ee = U(null), te = ({ url: e, realm: t, clientId: o }) => (a || (a = new X({ const ne = G(null), re = ({ url: e, realm: t, clientId: r }) => (d || (d = new P({
url: e, url: e,
realm: t, realm: t,
clientId: o clientId: r
})), a), G = ({ config: e, initOptions: t = {} }) => { })), d), ie = (e) => (j = e, j), oe = () => L, $ = () => !!(d != null && d.authenticated), N = () => (d == null ? void 0 : d.token) ?? null, U = async (e = 30) => d ? d.updateToken(e) : !1, J = (e) => d == null ? void 0 : d.logout(e), Ie = (e) => d == null ? void 0 : d.login(e), Q = ({ config: e, initOptions: t = {} } = {}) => {
const o = te(e); const r = e ?? j;
return _ || (_ = o.init({ if (!(r != null && r.url) || !(r != null && r.realm) || !(r != null && r.clientId))
throw new Error("Keycloak config is required.");
ie(r);
const l = re(r);
return F || (F = l.init({
onLoad: "login-required", onLoad: "login-required",
checkLoginIframe: !1, checkLoginIframe: !1,
flow: "implicit", flow: "implicit",
...t ...t
}).then((l) => (R = !0, l)).catch((l) => { }).then((c) => (L = !0, c)).catch((c) => {
throw R = !0, l; throw L = !0, c;
})), _; })), F;
}, ne = () => R, $ = () => !!(a != null && a.authenticated), N = () => (a == null ? void 0 : a.token) ?? null, q = async (e = 30) => a ? a.updateToken(e) : !1, J = (e) => a == null ? void 0 : a.logout(e), Ce = (e) => a == null ? void 0 : a.login(e), Be = ({ }, Ee = ({
children: e, children: e,
config: t, config: t,
initOptions: o, initOptions: r,
loading: l = null loading: l = null
}) => { }) => {
const [d, i] = B(!1), [w, r] = B(!1), [s, c] = B(null), m = T(!1), y = D(() => { const [c, i] = B(!1), [u, o] = B(!1), [f, s] = B(null), w = z(!1), y = E(() => {
a && (r(!!a.authenticated), c(a.token ?? null)); d && (o(!!d.authenticated), s(d.token ?? null));
}, []); }, []);
A(() => (m.current = !0, G({ config: t, initOptions: o }).then((b) => { C(() => (w.current = !0, Q({ config: t, initOptions: r }).then((b) => {
m.current && (r(!!b), c((a == null ? void 0 : a.token) ?? null), i(!0)); w.current && (o(!!b), s((d == null ? void 0 : d.token) ?? null), i(!0));
}).catch(() => { }).catch(() => {
m.current && (r(!1), c(null), i(!0)); w.current && (o(!1), s(null), i(!0));
}), () => { }), () => {
m.current = !1; w.current = !1;
}), [t, o]); }), [t, r]);
const v = D(() => a == null ? void 0 : a.login(), []), n = D((b) => a == null ? void 0 : a.logout(b), []), p = D( const v = E(() => d == null ? void 0 : d.login(), []), n = E((b) => d == null ? void 0 : d.logout(b), []), h = E(
async (b = 30) => { async (b = 30) => {
if (!a) return !1; if (!d) return !1;
const M = await a.updateToken(b); const _ = await d.updateToken(b);
return y(), M; return y(), _;
}, },
[y] [y]
), h = F( ), m = R(
() => ({ () => ({
initialized: d, initialized: c,
authenticated: w, authenticated: u,
token: s, token: f,
login: v, login: v,
logout: n, logout: n,
updateToken: p updateToken: h
}), }),
[d, w, s, v, n, p] [c, u, f, v, n, h]
); );
return d ? /* @__PURE__ */ u(ee.Provider, { value: h, children: e }) : l; return c ? /* @__PURE__ */ a(ne.Provider, { value: m, children: e }) : l;
}, Q = U(null), z = "permissions", ie = (e) => (e == null ? void 0 : e.storageKey) || z, Ae = ({ }, Y = G(null), M = "permissions", se = (e) => (e == null ? void 0 : e.storageKey) || M, Ke = ({
user: e = null, user: e = null,
children: t, children: t,
config: o, config: r,
loading: l = /* @__PURE__ */ u("div", { children: "Loading permissions..." }), loading: l = /* @__PURE__ */ a("div", { children: "Loading permissions..." }),
errorFallback: d = /* @__PURE__ */ u("div", { children: "Error loading permissions" }) errorFallback: c = /* @__PURE__ */ a("div", { children: "Error loading permissions" })
}) => { }) => {
const i = ie(o), [w, r] = B( const i = se(r), [u, o] = B(
() => re(i) () => le(i)
), { data: s, isLoading: c, error: m } = ue(o), y = s ?? w; ), { data: f, isLoading: s, error: w } = fe(r), y = f ?? u;
A(() => { C(() => {
s && (oe(i, s), r(s)); f && (ce(i, f), o(f));
}, [s, i]); }, [f, i]);
const v = F( const v = R(
() => se(y), () => ue(y),
[y] [y]
), n = D( ), n = E(
(b = "") => le(v, b), (b = "") => ae(v, b),
[v] [v]
), p = D((b = "") => !n(b), [n]), h = F( ), h = E((b = "") => !n(b), [n]), m = R(
() => ({ () => ({
user: e, user: e,
can: n, can: n,
cannot: p, cannot: h,
permissions: y, permissions: y,
isLoading: c, isLoading: s,
error: m error: w
}), }),
[e, n, p, y, c, m] [e, n, h, y, s, w]
); );
return m && !y ? d : c && !y ? l : /* @__PURE__ */ u(Q.Provider, { value: h, children: t }); return w && !y ? c : s && !y ? l : /* @__PURE__ */ a(Y.Provider, { value: m, children: t });
}, re = (e = z) => { }, le = (e = M) => {
if (!(typeof window > "u")) if (!(typeof window > "u"))
try { try {
const t = localStorage.getItem(e); const t = localStorage.getItem(e);
@ -489,34 +493,34 @@ const ee = U(null), te = ({ url: e, realm: t, clientId: o }) => (a || (a = new X
} catch { } catch {
return; return;
} }
}, oe = (e = z, t) => { }, ce = (e = M, t) => {
if (!(typeof window > "u")) if (!(typeof window > "u"))
try { try {
localStorage.setItem(e, JSON.stringify(t)); localStorage.setItem(e, JSON.stringify(t));
} catch { } catch {
} }
}, Se = (e = z) => { }, De = (e = M) => {
if (!(typeof window > "u")) if (!(typeof window > "u"))
try { try {
localStorage.removeItem(e); localStorage.removeItem(e);
} catch { } catch {
} }
}, se = (e) => e ? new Set(e.map((t) => t.name)) : /* @__PURE__ */ new Set(), le = (e, t = "") => { }, ue = (e) => e ? new Set(e.map((t) => t.name)) : /* @__PURE__ */ new Set(), ae = (e, t = "") => {
if (!t) return !1; if (!t) return !1;
if (e.has(t) || [...e].some((l) => l.startsWith(t))) return !0; if (e.has(t) || [...e].some((l) => l.startsWith(t))) return !0;
let o = t; let r = t;
for (; o.includes(":"); ) for (; r.includes(":"); )
if (o = o.slice(0, o.lastIndexOf(":")), e.has(`${o}:*`)) return !0; if (r = r.slice(0, r.lastIndexOf(":")), e.has(`${r}:*`)) return !0;
return !1; return !1;
}, Y = { }, H = {
all: ["permissions"], all: ["permissions"],
list: (e) => [...Y.all, e] list: (e) => [...H.all, e]
}, ce = async (e) => { }, de = async (e) => {
if (!(e != null && e.url) || !(e != null && e.clientId)) if (!(e != null && e.url) || !(e != null && e.clientId))
throw new Error("Permission config requires url and clientId."); throw new Error("Permission config requires url and clientId.");
const t = N(), o = new URL(e.url); const t = N(), r = new URL(e.url);
o.searchParams.set("client_id", e.clientId); r.searchParams.set("client_id", e.clientId);
const l = await fetch(o.toString(), { const l = await fetch(r.toString(), {
method: "GET", method: "GET",
headers: { headers: {
...t ? { Authorization: `Bearer ${t}` } : {} ...t ? { Authorization: `Bearer ${t}` } : {}
@ -525,101 +529,120 @@ const ee = U(null), te = ({ url: e, realm: t, clientId: o }) => (a || (a = new X
if (!l.ok) if (!l.ok)
throw new Error("Failed to load permissions"); throw new Error("Failed to load permissions");
return l.json(); return l.json();
}, O = () => { }, g = () => {
const e = H(Q); const e = Z(Y);
if (!e) if (!e)
throw new Error("usePermission must be used within PermissionProvider"); throw new Error("usePermission must be used within PermissionProvider");
return e; return e;
}, ue = (e) => Z({ }, fe = (e) => ee({
queryKey: Y.list(e == null ? void 0 : e.clientId), queryKey: H.list(e == null ? void 0 : e.clientId),
queryFn: () => ce(e), queryFn: () => de(e),
enabled: !!(e != null && e.url) && !!(e != null && e.clientId) && $(), enabled: !!(e != null && e.url) && !!(e != null && e.clientId) && $(),
staleTime: 1 / 0, staleTime: 1 / 0,
refetchOnWindowFocus: !1, refetchOnWindowFocus: !1,
refetchOnReconnect: !1 refetchOnReconnect: !1
}), ke = ({ }), Ne = ({
perm: e, perm: e,
children: t, children: t,
fallback: o = /* @__PURE__ */ u("div", { children: "You are not allowed to do this" }) fallback: r = /* @__PURE__ */ a("div", { children: "You are not allowed to do this" })
}) => { }) => {
const { can: l } = O(); const { can: l } = g();
return l(e) ? t : o; return l(e) ? t : r;
}, Ie = ({ children: e }) => { }, Te = ({ children: e }) => {
const { can: t, permissions: o } = O(); const { can: t, permissions: r } = g();
return o && t("admin") ? e : null; return r && t("admin") ? e : null;
}, De = ({ children: e }) => { }, ze = ({ children: e }) => {
const { can: t, isLoading: o } = O(); const { can: t, isLoading: r } = g();
return A(() => { return C(() => {
o || t("panel_access") || J(); r || t("panel_access") || J();
}, [o, t]), e; }, [r, t]), e;
}, Ee = (e) => { };
const { api: t, keycloak: o } = e, l = P.create({ let T = null;
const pe = (e) => {
const { api: t } = e, r = te.create({
baseURL: t.baseUrl baseURL: t.baseUrl
}), d = async () => { }), l = async () => {
(!ne() || !$()) && await G({ config: o }); (!oe() || !$()) && await Q();
}, i = async (r) => { }, c = async (u) => {
await d(); await l();
let s = N(); let o = N();
if (s) { if (o) {
try { try {
await q(5), s = N(); await U(5), o = N();
} catch { } catch {
} }
r.headers = { u.headers = {
...r.headers, ...u.headers,
Authorization: `Bearer ${s}` Authorization: `Bearer ${o}`
}; };
} }
return r; return u;
}, w = async (r) => { }, i = async (u) => {
var c; var f;
const s = r.config; const o = u.config;
if (((c = r == null ? void 0 : r.response) == null ? void 0 : c.status) === 401 && !(s != null && s._retry)) { if (((f = u == null ? void 0 : u.response) == null ? void 0 : f.status) === 401 && !(o != null && o._retry)) {
s._retry = !0; o._retry = !0;
try { try {
await q(30); await U(30);
const m = N(); const s = N();
return s.headers = { return o.headers = {
...s.headers, ...o.headers,
Authorization: `Bearer ${m}` Authorization: `Bearer ${s}`
}, l(s); }, r(o);
} catch { } catch {
J({ redirectUri: window.location.origin }); J({ redirectUri: window.location.origin });
} }
} }
return Promise.reject(r); return Promise.reject(u);
}; };
return t.interceptors.request.use(i), t.interceptors.response.use((r) => r, w), { return r.interceptors.request.use(c), r.interceptors.response.use(
api: l (u) => u,
i
), {
api: r
}; };
}; }, Me = (e) => (T = pe(e), T), he = () => {
if (!T)
throw new Error("api is not configured. Call configureApi(config) first.");
return T.api;
}, _e = new Proxy(
{},
{
get(e, t) {
return he()[t];
}
}
);
export { export {
Ie as AdminGuard, Te as AdminGuard,
ke as Can, Ne as Can,
Be as KeycloakProvider, Ee as KeycloakProvider,
ye as LightPagination, Ce as LightPagination,
xe as Pagination, ke as Pagination,
De as PanelAccessGuard, ze as PanelAccessGuard,
Ae as PermissionProvider, Ke as PermissionProvider,
ve as SimplePagination, Se as SimplePagination,
le as checkPermission, _e as api,
Se as clearCachedPermissions, ae as checkPermission,
Ee as createApi, De as clearCachedPermissions,
se as createPermissionSet, Me as configureApi,
re as getCachedPermissions, pe as createApi,
ue as createPermissionSet,
he as getApi,
le as getCachedPermissions,
N as getKeycloakToken, N as getKeycloakToken,
ce as getPermissions, de as getPermissions,
G as initKeycloak, Q as initKeycloak,
$ as isKeycloakAuthenticated, $ as isKeycloakAuthenticated,
ne as isKeycloakInitialized, oe as isKeycloakInitialized,
Ce as loginKeycloak, Ie as loginKeycloak,
J as logoutKeycloak, J as logoutKeycloak,
Y as permissionKeys, H as permissionKeys,
oe as setCachedPermissions, ce as setCachedPermissions,
E as toEnDigits, K as toEnDigits,
f as toFaDigits, p as toFaDigits,
we as toFaNumber, Be as toFaNumber,
q as updateKeycloakToken, U as updateKeycloakToken,
O as usePermission, g as usePermission,
ue as usePermissionsQuery fe as usePermissionsQuery
}; };

View File

@ -8,8 +8,10 @@ import {
updateKeycloakToken, updateKeycloakToken,
} from "./keycloak.jsx"; } from "./keycloak.jsx";
let configuredApi = null;
export const createApi = (config) => { export const createApi = (config) => {
const { api, keycloak } = config; const { api } = config;
// instances // instances
@ -21,7 +23,7 @@ export const createApi = (config) => {
const waitForKeycloak = async () => { const waitForKeycloak = async () => {
if (!isKeycloakInitialized() || !isKeycloakAuthenticated()) { if (!isKeycloakInitialized() || !isKeycloakAuthenticated()) {
await initKeycloak({ config: keycloak }); await initKeycloak();
} }
}; };
@ -29,17 +31,21 @@ export const createApi = (config) => {
const handleAuthRequestInterceptor = async (config) => { const handleAuthRequestInterceptor = async (config) => {
await waitForKeycloak(); await waitForKeycloak();
let token = getKeycloakToken(); let token = getKeycloakToken();
if (token) { if (token) {
try { try {
await updateKeycloakToken(5); await updateKeycloakToken(5);
token = getKeycloakToken(); token = getKeycloakToken();
} catch {} } catch {}
config.headers = { config.headers = {
...config.headers, ...config.headers,
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}; };
} }
return config; return config;
}; };
@ -47,29 +53,60 @@ export const createApi = (config) => {
const handleAuthResponseInterceptor = async (error) => { const handleAuthResponseInterceptor = async (error) => {
const originalRequest = error.config; const originalRequest = error.config;
if (error?.response?.status === 401 && !originalRequest?._retry) { if (error?.response?.status === 401 && !originalRequest?._retry) {
originalRequest._retry = true; originalRequest._retry = true;
try { try {
await updateKeycloakToken(30); await updateKeycloakToken(30);
const token = getKeycloakToken(); const token = getKeycloakToken();
originalRequest.headers = { originalRequest.headers = {
...originalRequest.headers, ...originalRequest.headers,
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}; };
return axiosInstance(originalRequest); return axiosInstance(originalRequest);
} catch (err) { } catch (err) {
logoutKeycloak({ redirectUri: window.location.origin }); logoutKeycloak({ redirectUri: window.location.origin });
} }
} }
return Promise.reject(error); return Promise.reject(error);
}; };
// add interceptors // add interceptors
api.interceptors.request.use(handleAuthRequestInterceptor); axiosInstance.interceptors.request.use(handleAuthRequestInterceptor);
api.interceptors.response.use((res) => res, handleAuthResponseInterceptor); axiosInstance.interceptors.response.use(
(res) => res,
handleAuthResponseInterceptor,
);
return { return {
api: axiosInstance, api: axiosInstance,
}; };
}; };
export const configureApi = (config) => {
configuredApi = createApi(config);
return configuredApi;
};
export const getApi = () => {
if (!configuredApi) {
throw new Error("api is not configured. Call configureApi(config) first.");
}
return configuredApi.api;
};
export const api = new Proxy(
{},
{
get(_, prop) {
return getApi()[prop];
},
},
);

View File

@ -10,6 +10,7 @@ import {
// variables // variables
let keycloakConfig = null;
let keycloakInstance = null; let keycloakInstance = null;
let initPromise = null; let initPromise = null;
let initializedValue = false; let initializedValue = false;
@ -29,31 +30,16 @@ const createKeycloak = ({ url, realm, clientId }) => {
return keycloakInstance; return keycloakInstance;
}; };
// initializations // exports
export const initKeycloak = ({ config, initOptions = {} }) => { export const setKeycloakConfig = (config) => {
const keycloak = createKeycloak(config); keycloakConfig = config;
if (!initPromise) { return keycloakConfig;
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;
}; };
// exports export const getKeycloakConfig = () => {
return keycloakConfig;
};
export const isKeycloakInitialized = () => { export const isKeycloakInitialized = () => {
return initializedValue; return initializedValue;
@ -81,6 +67,35 @@ export const loginKeycloak = (options) => {
return keycloakInstance?.login(options); return keycloakInstance?.login(options);
}; };
// initializations
export const initKeycloak = ({ config, initOptions = {} } = {}) => {
const finalConfig = config ?? keycloakConfig;
if (!finalConfig?.url || !finalConfig?.realm || !finalConfig?.clientId) {
throw new Error("Keycloak config is required.");
}
setKeycloakConfig(finalConfig);
const keycloak = createKeycloak(finalConfig);
if (!initPromise) {
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;
};
// providers // providers
export const KeycloakProvider = ({ export const KeycloakProvider = ({

View File

@ -31,4 +31,4 @@ export {
getPermissions, getPermissions,
} from "./core/permission.jsx"; } from "./core/permission.jsx";
export { createApi } from "./core/api.js"; export { createApi, configureApi, getApi, api } from "./core/api.js";