alex-evo-sh-auth 0.0.17 → 0.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,29 @@
1
- import ue, { createContext as fe, useState as I, useCallback as j, useEffect as N, useContext as B, useRef as de } from "react";
2
- import { Outlet as H } from "react-router-dom";
3
- async function me(r) {
4
- const t = await fetch(`${r.authServer}/refresh`, {
1
+ import le, { createContext as ue, useState as I, useCallback as j, useEffect as C, useContext as G, useRef as fe } from "react";
2
+ import { Outlet as K } from "react-router-dom";
3
+ async function de(t) {
4
+ const r = await fetch(`${t.authServer}/refresh`, {
5
5
  method: "POST",
6
+ credentials: "include",
6
7
  headers: {
7
8
  "Content-Type": "application/json"
8
9
  },
9
10
  body: JSON.stringify({
10
11
  grant_type: "refresh_token",
11
- client_id: r.clientId
12
+ client_id: t.clientId
12
13
  })
13
14
  });
14
- if (t.status === 401)
15
- return localStorage.removeItem(r.baseKey + "_access"), null;
16
- const o = await t.json();
17
- return localStorage.setItem(r.baseKey + "_access", o.access), o.access;
15
+ if (r.status === 401)
16
+ return localStorage.removeItem(t.baseKey + "_access"), null;
17
+ if (!r.ok)
18
+ throw new Error(`Token refresh failed: ${r.status} ${await r.text()}`);
19
+ const n = await r.json();
20
+ if (typeof n.access != "string" || !n.access)
21
+ throw new Error("Token refresh response did not contain an access token");
22
+ return localStorage.setItem(t.baseKey + "_access", n.access), n.access;
18
23
  }
19
- class Se {
20
- constructor(t, o) {
21
- this.onAuthFail = o, this.config = t;
24
+ class ye {
25
+ constructor(r, n) {
26
+ this.onAuthFail = n, this.config = r;
22
27
  }
23
28
  onAuthFail;
24
29
  refreshPromise = null;
@@ -26,170 +31,173 @@ class Se {
26
31
  getToken() {
27
32
  return localStorage.getItem(this.config.baseKey + "_access");
28
33
  }
29
- setToken(t) {
30
- t ? localStorage.setItem(this.config.baseKey + "_access", t) : localStorage.removeItem(this.config.baseKey + "_access");
34
+ setToken(r) {
35
+ r ? localStorage.setItem(this.config.baseKey + "_access", r) : localStorage.removeItem(this.config.baseKey + "_access");
31
36
  }
32
37
  async getValidToken() {
33
- let t = this.getToken();
34
- return t || (this.refreshPromise || (this.refreshPromise = me(this.config).then((o) => (this.setToken(o), o)).finally(() => {
38
+ let r = this.getToken();
39
+ return r || (this.refreshPromise || (this.refreshPromise = de(this.config).then((n) => (this.setToken(n), n)).finally(() => {
35
40
  this.refreshPromise = null;
36
- })), t = await this.refreshPromise, !t && this.onAuthFail && this.onAuthFail(), t);
41
+ })), r = await this.refreshPromise, !r && this.onAuthFail && this.onAuthFail(), r);
37
42
  }
38
43
  }
39
- class ke {
44
+ class Re {
40
45
  authServer;
41
46
  clientId;
42
47
  redirectUri;
43
48
  homePage;
44
49
  baseKey;
45
- constructor(t, o, s, a, i) {
46
- this.authServer = t, this.clientId = o, this.redirectUri = s, this.homePage = a, this.baseKey = i;
50
+ constructor(r, n, s, a, c) {
51
+ this.authServer = r, this.clientId = n, this.redirectUri = s, this.homePage = a, this.baseKey = c;
47
52
  }
48
53
  }
49
- async function X(r, t, o = {}, s) {
50
- let a = r.getToken();
51
- const i = (d) => fetch(t, {
52
- ...o,
54
+ async function H(t, r, n = {}, s) {
55
+ let a = t.getToken();
56
+ const c = (d) => fetch(r, {
57
+ ...n,
58
+ credentials: n.credentials ?? "include",
53
59
  headers: {
54
- ...o.headers,
60
+ ...n.headers,
55
61
  Authorization: d ? `Bearer ${d}` : ""
56
62
  }
57
- });
58
- let l = await i(a);
59
- return l.status !== 401 ? l : (r.setToken(null), a = await r.getValidToken(), a ? i(a) : (s?.(), l));
63
+ }), l = await c(a);
64
+ return l.status !== 401 ? l : (t.setToken(null), a = await t.getValidToken(), a ? c(a) : (s?.(), l));
60
65
  }
61
- async function he(r) {
62
- const t = new URLSearchParams(window.location.search), o = t.get("code"), s = t.get("state");
63
- if (!o)
66
+ async function me(t) {
67
+ const r = new URLSearchParams(window.location.search), n = r.get("code"), s = r.get("state");
68
+ if (!n)
64
69
  throw new Error("Missing OAuth code");
65
70
  const a = sessionStorage.getItem("oauth_state");
66
71
  if (!s || s !== a)
67
72
  throw new Error("Invalid OAuth state");
68
- const i = sessionStorage.getItem("pkce_verifier");
69
- if (!i)
73
+ const c = sessionStorage.getItem("pkce_verifier");
74
+ if (!c)
70
75
  throw new Error("Missing PKCE verifier");
71
76
  const l = await fetch(
72
- `${r.config.authServer}/token`,
77
+ `${t.config.authServer}/token`,
73
78
  {
74
79
  method: "POST",
80
+ credentials: "include",
75
81
  headers: {
76
82
  "Content-Type": "application/json"
77
83
  },
78
84
  body: JSON.stringify({
79
- client_id: r.config.clientId,
80
- code: o,
81
- code_verifier: i
85
+ client_id: t.config.clientId,
86
+ code: n,
87
+ code_verifier: c
82
88
  })
83
89
  }
84
90
  );
85
91
  if (!l.ok) {
86
- const _ = await l.text();
92
+ const p = await l.text();
87
93
  throw new Error(
88
- `Token exchange failed: ${l.status} ${_}`
94
+ `Token exchange failed: ${l.status} ${p}`
89
95
  );
90
96
  }
91
97
  const d = await l.json();
92
- r.setToken(d.access), sessionStorage.removeItem("oauth_state"), sessionStorage.removeItem("pkce_verifier");
98
+ if (typeof d.access != "string" || !d.access)
99
+ throw new Error("Token response did not contain an access token");
100
+ t.setToken(d.access), sessionStorage.removeItem("oauth_state"), sessionStorage.removeItem("pkce_verifier");
93
101
  }
94
- function ge(r = 64) {
95
- const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
96
- let o = "";
97
- const s = new Uint8Array(r);
102
+ function he(t = 64) {
103
+ const r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
104
+ let n = "";
105
+ const s = new Uint8Array(t);
98
106
  crypto.getRandomValues(s);
99
107
  for (let a = 0; a < s.length; a++)
100
- o += t[s[a] % t.length];
101
- return o;
108
+ n += r[s[a] % r.length];
109
+ return n;
102
110
  }
103
- async function _e(r) {
104
- const o = new TextEncoder().encode(r), s = await crypto.subtle.digest("SHA-256", o);
111
+ async function ge(t) {
112
+ const n = new TextEncoder().encode(t), s = await crypto.subtle.digest("SHA-256", n);
105
113
  return new Uint8Array(s);
106
114
  }
107
- function pe(r) {
108
- return btoa(String.fromCharCode(...Array.from(r))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
115
+ function _e(t) {
116
+ return btoa(String.fromCharCode(...Array.from(t))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
109
117
  }
110
- async function C(r) {
111
- const t = ge(64), o = pe(await _e(t));
112
- sessionStorage.setItem("pkce_verifier", t);
118
+ async function X(t) {
119
+ const r = he(64), n = _e(await ge(r));
120
+ sessionStorage.setItem("pkce_verifier", r);
113
121
  const s = crypto.randomUUID();
114
122
  sessionStorage.setItem("oauth_state", s);
115
123
  const a = new URLSearchParams({
116
124
  response_type: "code",
117
- client_id: r.config.clientId,
118
- redirect_uri: r.config.redirectUri,
119
- code_challenge: o,
125
+ client_id: t.config.clientId,
126
+ redirect_uri: t.config.redirectUri,
127
+ code_challenge: n,
120
128
  code_challenge_method: "S256",
121
129
  state: s
122
130
  });
123
- window.location.href = `${r.config.authServer}/authorize?${a}`;
131
+ window.location.href = `${t.config.authServer}/authorize?${a}`;
124
132
  }
125
- async function z(r) {
133
+ async function pe(t) {
126
134
  try {
127
- await X(r, `${r.config.authServer}/logout`, {
135
+ await H(t, `${t.config.authServer}/logout`, {
128
136
  method: "POST",
129
137
  headers: {
130
138
  "Content-Type": "application/json"
131
139
  },
132
140
  body: JSON.stringify({
133
- client_id: r.config.clientId
141
+ client_id: t.config.clientId
134
142
  })
135
- }), localStorage.removeItem(r.config.baseKey + "_access"), await C(r);
136
- } catch (t) {
137
- console.error(t);
143
+ }), localStorage.removeItem(t.config.baseKey + "_access"), await X(t);
144
+ } catch (r) {
145
+ console.error(r);
138
146
  }
139
147
  }
140
- const $ = fe({
148
+ const N = ue({
141
149
  login: () => {
142
150
  },
143
151
  logout: () => {
144
152
  },
145
- loadMe: () => {
153
+ loadMe: async () => {
146
154
  },
147
155
  authManager: null,
148
156
  user: null,
149
157
  loading: !1
150
158
  });
151
- var S = { exports: {} }, v = {};
152
- var q;
159
+ var y = { exports: {} }, v = {};
160
+ var W;
153
161
  function ve() {
154
- if (q) return v;
155
- q = 1;
156
- var r = /* @__PURE__ */ Symbol.for("react.transitional.element"), t = /* @__PURE__ */ Symbol.for("react.fragment");
157
- function o(s, a, i) {
162
+ if (W) return v;
163
+ W = 1;
164
+ var t = /* @__PURE__ */ Symbol.for("react.transitional.element"), r = /* @__PURE__ */ Symbol.for("react.fragment");
165
+ function n(s, a, c) {
158
166
  var l = null;
159
- if (i !== void 0 && (l = "" + i), a.key !== void 0 && (l = "" + a.key), "key" in a) {
160
- i = {};
167
+ if (c !== void 0 && (l = "" + c), a.key !== void 0 && (l = "" + a.key), "key" in a) {
168
+ c = {};
161
169
  for (var d in a)
162
- d !== "key" && (i[d] = a[d]);
163
- } else i = a;
164
- return a = i.ref, {
165
- $$typeof: r,
170
+ d !== "key" && (c[d] = a[d]);
171
+ } else c = a;
172
+ return a = c.ref, {
173
+ $$typeof: t,
166
174
  type: s,
167
175
  key: l,
168
176
  ref: a !== void 0 ? a : null,
169
- props: i
177
+ props: c
170
178
  };
171
179
  }
172
- return v.Fragment = t, v.jsx = o, v.jsxs = o, v;
180
+ return v.Fragment = r, v.jsx = n, v.jsxs = n, v;
173
181
  }
174
182
  var E = {};
175
- var G;
183
+ var z;
176
184
  function Ee() {
177
- return G || (G = 1, process.env.NODE_ENV !== "production" && (function() {
178
- function r(e) {
185
+ return z || (z = 1, process.env.NODE_ENV !== "production" && (function() {
186
+ function t(e) {
179
187
  if (e == null) return null;
180
188
  if (typeof e == "function")
181
- return e.$$typeof === ie ? null : e.displayName || e.name || null;
189
+ return e.$$typeof === ae ? null : e.displayName || e.name || null;
182
190
  if (typeof e == "string") return e;
183
191
  switch (e) {
184
- case k:
192
+ case R:
185
193
  return "Fragment";
186
- case Q:
194
+ case M:
187
195
  return "Profiler";
188
196
  case Z:
189
197
  return "StrictMode";
190
- case ne:
198
+ case te:
191
199
  return "Suspense";
192
- case oe:
200
+ case ne:
193
201
  return "SuspenseList";
194
202
  case se:
195
203
  return "Activity";
@@ -198,53 +206,53 @@ function Ee() {
198
206
  switch (typeof e.tag == "number" && console.error(
199
207
  "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
200
208
  ), e.$$typeof) {
201
- case M:
209
+ case B:
202
210
  return "Portal";
203
- case re:
204
- return e.displayName || "Context";
205
211
  case ee:
212
+ return e.displayName || "Context";
213
+ case Q:
206
214
  return (e._context.displayName || "Context") + ".Consumer";
207
- case te:
208
- var n = e.render;
209
- return e = e.displayName, e || (e = n.displayName || n.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
210
- case ae:
211
- return n = e.displayName || null, n !== null ? n : r(e.type) || "Memo";
212
- case R:
213
- n = e._payload, e = e._init;
215
+ case re:
216
+ var o = e.render;
217
+ return e = e.displayName, e || (e = o.displayName || o.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
218
+ case oe:
219
+ return o = e.displayName || null, o !== null ? o : t(e.type) || "Memo";
220
+ case S:
221
+ o = e._payload, e = e._init;
214
222
  try {
215
- return r(e(n));
223
+ return t(e(o));
216
224
  } catch {
217
225
  }
218
226
  }
219
227
  return null;
220
228
  }
221
- function t(e) {
229
+ function r(e) {
222
230
  return "" + e;
223
231
  }
224
- function o(e) {
232
+ function n(e) {
225
233
  try {
226
- t(e);
227
- var n = !1;
234
+ r(e);
235
+ var o = !1;
228
236
  } catch {
229
- n = !0;
237
+ o = !0;
230
238
  }
231
- if (n) {
232
- n = console;
233
- var c = n.error, u = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
234
- return c.call(
235
- n,
239
+ if (o) {
240
+ o = console;
241
+ var i = o.error, u = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
242
+ return i.call(
243
+ o,
236
244
  "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
237
245
  u
238
- ), t(e);
246
+ ), r(e);
239
247
  }
240
248
  }
241
249
  function s(e) {
242
- if (e === k) return "<>";
243
- if (typeof e == "object" && e !== null && e.$$typeof === R)
250
+ if (e === R) return "<>";
251
+ if (typeof e == "object" && e !== null && e.$$typeof === S)
244
252
  return "<...>";
245
253
  try {
246
- var n = r(e);
247
- return n ? "<" + n + ">" : "<...>";
254
+ var o = t(e);
255
+ return o ? "<" + o + ">" : "<...>";
248
256
  } catch {
249
257
  return "<...>";
250
258
  }
@@ -253,45 +261,45 @@ function Ee() {
253
261
  var e = P.A;
254
262
  return e === null ? null : e.getOwner();
255
263
  }
256
- function i() {
264
+ function c() {
257
265
  return Error("react-stack-top-frame");
258
266
  }
259
267
  function l(e) {
260
- if (Y.call(e, "key")) {
261
- var n = Object.getOwnPropertyDescriptor(e, "key").get;
262
- if (n && n.isReactWarning) return !1;
268
+ if (U.call(e, "key")) {
269
+ var o = Object.getOwnPropertyDescriptor(e, "key").get;
270
+ if (o && o.isReactWarning) return !1;
263
271
  }
264
272
  return e.key !== void 0;
265
273
  }
266
- function d(e, n) {
267
- function c() {
268
- L || (L = !0, console.error(
274
+ function d(e, o) {
275
+ function i() {
276
+ Y || (Y = !0, console.error(
269
277
  "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
270
- n
278
+ o
271
279
  ));
272
280
  }
273
- c.isReactWarning = !0, Object.defineProperty(e, "key", {
274
- get: c,
281
+ i.isReactWarning = !0, Object.defineProperty(e, "key", {
282
+ get: i,
275
283
  configurable: !0
276
284
  });
277
285
  }
278
- function _() {
279
- var e = r(this.type);
280
- return D[e] || (D[e] = !0, console.error(
286
+ function p() {
287
+ var e = t(this.type);
288
+ return L[e] || (L[e] = !0, console.error(
281
289
  "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
282
290
  )), e = this.props.ref, e !== void 0 ? e : null;
283
291
  }
284
- function b(e, n, c, u, T, O) {
285
- var f = c.ref;
292
+ function b(e, o, i, u, T, x) {
293
+ var f = i.ref;
286
294
  return e = {
287
- $$typeof: U,
295
+ $$typeof: F,
288
296
  type: e,
289
- key: n,
290
- props: c,
297
+ key: o,
298
+ props: i,
291
299
  _owner: u
292
300
  }, (f !== void 0 ? f : null) !== null ? Object.defineProperty(e, "ref", {
293
301
  enumerable: !1,
294
- get: _
302
+ get: p
295
303
  }) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
296
304
  configurable: !1,
297
305
  enumerable: !1,
@@ -311,28 +319,28 @@ function Ee() {
311
319
  configurable: !1,
312
320
  enumerable: !1,
313
321
  writable: !0,
314
- value: O
322
+ value: x
315
323
  }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
316
324
  }
317
- function p(e, n, c, u, T, O) {
318
- var f = n.children;
325
+ function h(e, o, i, u, T, x) {
326
+ var f = o.children;
319
327
  if (f !== void 0)
320
328
  if (u)
321
- if (ce(f)) {
329
+ if (ie(f)) {
322
330
  for (u = 0; u < f.length; u++)
323
- m(f[u]);
331
+ g(f[u]);
324
332
  Object.freeze && Object.freeze(f);
325
333
  } else
326
334
  console.error(
327
335
  "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
328
336
  );
329
- else m(f);
330
- if (Y.call(n, "key")) {
331
- f = r(e);
332
- var h = Object.keys(n).filter(function(le) {
333
- return le !== "key";
337
+ else g(f);
338
+ if (U.call(o, "key")) {
339
+ f = t(e);
340
+ var _ = Object.keys(o).filter(function(ce) {
341
+ return ce !== "key";
334
342
  });
335
- u = 0 < h.length ? "{key: someKey, " + h.join(": ..., ") + ": ...}" : "{key: someKey}", W[f + u] || (h = 0 < h.length ? "{" + h.join(": ..., ") + ": ...}" : "{}", console.error(
343
+ u = 0 < _.length ? "{key: someKey, " + _.join(": ..., ") + ": ...}" : "{key: someKey}", J[f + u] || (_ = 0 < _.length ? "{" + _.join(": ..., ") + ": ...}" : "{}", console.error(
336
344
  `A props object containing a "key" prop is being spread into JSX:
337
345
  let props = %s;
338
346
  <%s {...props} />
@@ -341,158 +349,159 @@ React keys must be passed directly to JSX without using spread:
341
349
  <%s key={someKey} {...props} />`,
342
350
  u,
343
351
  f,
344
- h,
352
+ _,
345
353
  f
346
- ), W[f + u] = !0);
354
+ ), J[f + u] = !0);
347
355
  }
348
- if (f = null, c !== void 0 && (o(c), f = "" + c), l(n) && (o(n.key), f = "" + n.key), "key" in n) {
349
- c = {};
350
- for (var x in n)
351
- x !== "key" && (c[x] = n[x]);
352
- } else c = n;
356
+ if (f = null, i !== void 0 && (n(i), f = "" + i), l(o) && (n(o.key), f = "" + o.key), "key" in o) {
357
+ i = {};
358
+ for (var O in o)
359
+ O !== "key" && (i[O] = o[O]);
360
+ } else i = o;
353
361
  return f && d(
354
- c,
362
+ i,
355
363
  typeof e == "function" ? e.displayName || e.name || "Unknown" : e
356
364
  ), b(
357
365
  e,
358
366
  f,
359
- c,
367
+ i,
360
368
  a(),
361
369
  T,
362
- O
370
+ x
363
371
  );
364
372
  }
365
- function m(e) {
366
- w(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === R && (e._payload.status === "fulfilled" ? w(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
373
+ function g(e) {
374
+ k(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === S && (e._payload.status === "fulfilled" ? k(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
367
375
  }
368
- function w(e) {
369
- return typeof e == "object" && e !== null && e.$$typeof === U;
376
+ function k(e) {
377
+ return typeof e == "object" && e !== null && e.$$typeof === F;
370
378
  }
371
- var y = ue, U = /* @__PURE__ */ Symbol.for("react.transitional.element"), M = /* @__PURE__ */ Symbol.for("react.portal"), k = /* @__PURE__ */ Symbol.for("react.fragment"), Z = /* @__PURE__ */ Symbol.for("react.strict_mode"), Q = /* @__PURE__ */ Symbol.for("react.profiler"), ee = /* @__PURE__ */ Symbol.for("react.consumer"), re = /* @__PURE__ */ Symbol.for("react.context"), te = /* @__PURE__ */ Symbol.for("react.forward_ref"), ne = /* @__PURE__ */ Symbol.for("react.suspense"), oe = /* @__PURE__ */ Symbol.for("react.suspense_list"), ae = /* @__PURE__ */ Symbol.for("react.memo"), R = /* @__PURE__ */ Symbol.for("react.lazy"), se = /* @__PURE__ */ Symbol.for("react.activity"), ie = /* @__PURE__ */ Symbol.for("react.client.reference"), P = y.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Y = Object.prototype.hasOwnProperty, ce = Array.isArray, A = console.createTask ? console.createTask : function() {
379
+ var w = le, F = /* @__PURE__ */ Symbol.for("react.transitional.element"), B = /* @__PURE__ */ Symbol.for("react.portal"), R = /* @__PURE__ */ Symbol.for("react.fragment"), Z = /* @__PURE__ */ Symbol.for("react.strict_mode"), M = /* @__PURE__ */ Symbol.for("react.profiler"), Q = /* @__PURE__ */ Symbol.for("react.consumer"), ee = /* @__PURE__ */ Symbol.for("react.context"), re = /* @__PURE__ */ Symbol.for("react.forward_ref"), te = /* @__PURE__ */ Symbol.for("react.suspense"), ne = /* @__PURE__ */ Symbol.for("react.suspense_list"), oe = /* @__PURE__ */ Symbol.for("react.memo"), S = /* @__PURE__ */ Symbol.for("react.lazy"), se = /* @__PURE__ */ Symbol.for("react.activity"), ae = /* @__PURE__ */ Symbol.for("react.client.reference"), P = w.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, U = Object.prototype.hasOwnProperty, ie = Array.isArray, A = console.createTask ? console.createTask : function() {
372
380
  return null;
373
381
  };
374
- y = {
382
+ w = {
375
383
  react_stack_bottom_frame: function(e) {
376
384
  return e();
377
385
  }
378
386
  };
379
- var L, D = {}, J = y.react_stack_bottom_frame.bind(
380
- y,
381
- i
382
- )(), V = A(s(i)), W = {};
383
- E.Fragment = k, E.jsx = function(e, n, c) {
387
+ var Y, L = {}, D = w.react_stack_bottom_frame.bind(
388
+ w,
389
+ c
390
+ )(), V = A(s(c)), J = {};
391
+ E.Fragment = R, E.jsx = function(e, o, i) {
384
392
  var u = 1e4 > P.recentlyCreatedOwnerStacks++;
385
- return p(
393
+ return h(
386
394
  e,
387
- n,
388
- c,
395
+ o,
396
+ i,
389
397
  !1,
390
- u ? Error("react-stack-top-frame") : J,
398
+ u ? Error("react-stack-top-frame") : D,
391
399
  u ? A(s(e)) : V
392
400
  );
393
- }, E.jsxs = function(e, n, c) {
401
+ }, E.jsxs = function(e, o, i) {
394
402
  var u = 1e4 > P.recentlyCreatedOwnerStacks++;
395
- return p(
403
+ return h(
396
404
  e,
397
- n,
398
- c,
405
+ o,
406
+ i,
399
407
  !0,
400
- u ? Error("react-stack-top-frame") : J,
408
+ u ? Error("react-stack-top-frame") : D,
401
409
  u ? A(s(e)) : V
402
410
  );
403
411
  };
404
412
  })()), E;
405
413
  }
406
- var K;
414
+ var q;
407
415
  function be() {
408
- return K || (K = 1, process.env.NODE_ENV === "production" ? S.exports = ve() : S.exports = Ee()), S.exports;
416
+ return q || (q = 1, process.env.NODE_ENV === "production" ? y.exports = ve() : y.exports = Ee()), y.exports;
409
417
  }
410
- var g = be();
411
- const Re = ({ children: r, authManager: t }) => {
412
- const [o, s] = I(null), [a, i] = I(!0), l = j(async () => {
413
- i(!0);
414
- const b = localStorage.getItem(t.config.baseKey + "_access");
415
- if (!b) {
416
- s(null), i(!1);
417
- return;
418
- }
418
+ var m = be();
419
+ const Se = ({ children: t, authManager: r }) => {
420
+ const [n, s] = I(null), [a, c] = I(!0), l = j(async () => {
419
421
  try {
420
- const p = await X(t, `${t.config.authServer}/me`, {
421
- headers: {
422
- Authorization: `Bearer ${b}`
423
- }
424
- });
425
- if (!p.ok) throw new Error("not found");
426
- const m = await p.json();
422
+ if (!await r.getValidToken()) {
423
+ s(null);
424
+ return;
425
+ }
426
+ const h = await H(r, `${r.config.authServer}/me`);
427
+ if (h.status === 401) {
428
+ r.setToken(null), s(null);
429
+ return;
430
+ }
431
+ if (!h.ok)
432
+ throw new Error(`Failed to load current user: ${h.status}`);
433
+ const g = await h.json();
427
434
  s({
428
- role: m.role.role_name,
429
- userId: m.user_id,
430
- userName: m.user_name,
431
- privileges: m.role.privileges.map((w) => w.privilege.trim())
435
+ role: g.role.role_name,
436
+ userId: g.user_id,
437
+ userName: g.user_name,
438
+ privileges: g.role.privileges.map((k) => k.privilege.trim())
432
439
  });
433
- } catch {
434
- s(null);
440
+ } catch (b) {
441
+ console.error("Failed to load current user:", b), s(null);
442
+ } finally {
443
+ c(!1);
435
444
  }
436
- i(!1);
437
- }, []);
438
- N(() => {
439
- l();
445
+ }, [r]);
446
+ C(() => {
447
+ Promise.resolve().then(l);
440
448
  }, [l]);
441
449
  const d = j(() => {
442
- C(t);
443
- }, [C, t]), _ = j(() => {
444
- z(t), s(null);
445
- }, [z, t]);
446
- return /* @__PURE__ */ g.jsx($.Provider, { value: { loadMe: l, loading: a, user: o, login: d, authManager: t, logout: _ }, children: r });
450
+ X(r);
451
+ }, [r]), p = j(() => {
452
+ pe(r), s(null);
453
+ }, [r]);
454
+ return /* @__PURE__ */ m.jsx(N.Provider, { value: { loadMe: l, loading: a, user: n, login: d, authManager: r, logout: p }, children: t });
447
455
  }, Pe = () => {
448
- const { authManager: r, loadMe: t } = B($), o = de(!1);
449
- return N(() => {
450
- if (!r || o.current)
456
+ const { authManager: t, login: r } = G(N), n = fe(!1), [s, a] = I(null);
457
+ return C(() => {
458
+ if (!t || n.current)
451
459
  return;
452
- o.current = !0, (async () => {
460
+ n.current = !0, (async () => {
453
461
  try {
454
- await he(r), await t(), window.location.replace(
455
- r.config.homePage
456
- );
457
- } catch (a) {
458
- console.error("Authentication callback failed:", a), window.location.replace(
459
- r.config.homePage
460
- );
462
+ await me(t), window.location.replace(t.config.homePage);
463
+ } catch (l) {
464
+ console.error("Authentication callback failed:", l), a("Не удалось завершить вход. Попробуйте снова.");
461
465
  }
462
466
  })();
463
- }, [r, t]), /* @__PURE__ */ g.jsx("div", { children: "Авторизация..." });
464
- }, F = () => {
465
- const r = B($);
466
- if (!r || !r.authManager) throw new Error("AuthContext not found");
467
- return r;
468
- }, we = (r) => {
469
- const { user: t } = F();
470
- return !!t?.privileges?.includes(r);
467
+ }, [t]), s ? /* @__PURE__ */ m.jsxs("div", { role: "alert", children: [
468
+ /* @__PURE__ */ m.jsxs("p", { children: [
469
+ "Не удалось завершить вход: ",
470
+ s
471
+ ] }),
472
+ /* @__PURE__ */ m.jsx("button", { type: "button", onClick: r, children: "Повторить вход" })
473
+ ] }) : /* @__PURE__ */ m.jsx("div", { children: "Авторизация..." });
474
+ }, $ = () => {
475
+ const t = G(N);
476
+ if (!t || !t.authManager) throw new Error("AuthContext not found");
477
+ return t;
478
+ }, ke = (t) => {
479
+ const { user: r } = $();
480
+ return !!r?.privileges?.includes(t);
471
481
  };
472
- function Ae({ privilege: r, invalidPage: t, loadingPage: o }) {
473
- const { loading: s } = F(), a = we(r);
474
- return s ? o : a ? /* @__PURE__ */ g.jsx(H, {}) : t;
482
+ function Ae({ privilege: t, invalidPage: r, loadingPage: n }) {
483
+ const { loading: s } = $(), a = ke(t);
484
+ return s ? n : a ? /* @__PURE__ */ m.jsx(K, {}) : r;
475
485
  }
476
- function Oe({ loadingPage: r }) {
477
- const { authManager: t, login: o, user: s } = F(), [a, i] = I(!0);
478
- return N(() => {
479
- if (!t) return;
480
- t.getToken() ? i(!1) : o();
481
- }, [t, s]), t ? a ? r ?? /* @__PURE__ */ g.jsx("div", { children: "Loading..." }) : /* @__PURE__ */ g.jsx(H, {}) : /* @__PURE__ */ g.jsx("p", { children: "invalud config" });
486
+ function xe({ loadingPage: t }) {
487
+ const { authManager: r, login: n, loading: s } = $(), a = r?.getToken() ?? null;
488
+ return C(() => {
489
+ r && !s && !a && n();
490
+ }, [r, s, n, a]), s || !a ? t ?? /* @__PURE__ */ m.jsx("div", { children: "Loading..." }) : /* @__PURE__ */ m.jsx(K, {});
482
491
  }
483
492
  export {
484
- $ as AuthContext,
485
- Se as AuthManager,
486
- Re as AuthProvider,
493
+ N as AuthContext,
494
+ ye as AuthManager,
495
+ Se as AuthProvider,
487
496
  Pe as CallbackPage,
488
- ke as Config,
497
+ Re as Config,
489
498
  Ae as PrivilegeGate,
490
- Oe as ProtectGate,
491
- X as apiFetch,
492
- he as handleCallback,
493
- C as login,
494
- z as logout,
495
- me as refreshToken,
496
- F as useAuth,
497
- we as usePrivilege
499
+ xe as ProtectGate,
500
+ H as apiFetch,
501
+ me as handleCallback,
502
+ X as login,
503
+ pe as logout,
504
+ de as refreshToken,
505
+ $ as useAuth,
506
+ ke as usePrivilege
498
507
  };
@@ -1,6 +1,6 @@
1
- (function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("react"),require("react-router-dom")):typeof define=="function"&&define.amd?define(["exports","react","react-router-dom"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l["alex-evo-sh-auth"]={},l.React,l.ReactRouterDOM))})(this,(function(l,h,L){"use strict";async function D(t){const r=await fetch(`${t.authServer}/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t.clientId})});if(r.status===401)return localStorage.removeItem(t.baseKey+"_access"),null;const o=await r.json();return localStorage.setItem(t.baseKey+"_access",o.access),o.access}class ${constructor(r,o){this.onAuthFail=o,this.config=r}onAuthFail;refreshPromise=null;config;getToken(){return localStorage.getItem(this.config.baseKey+"_access")}setToken(r){r?localStorage.setItem(this.config.baseKey+"_access",r):localStorage.removeItem(this.config.baseKey+"_access")}async getValidToken(){let r=this.getToken();return r||(this.refreshPromise||(this.refreshPromise=D(this.config).then(o=>(this.setToken(o),o)).finally(()=>{this.refreshPromise=null})),r=await this.refreshPromise,!r&&this.onAuthFail&&this.onAuthFail(),r)}}class q{authServer;clientId;redirectUri;homePage;baseKey;constructor(r,o,s,a,c){this.authServer=r,this.clientId=o,this.redirectUri=s,this.homePage=a,this.baseKey=c}}async function j(t,r,o={},s){let a=t.getToken();const c=m=>fetch(r,{...o,headers:{...o.headers,Authorization:m?`Bearer ${m}`:""}});let u=await c(a);return u.status!==401?u:(t.setToken(null),a=await t.getValidToken(),a?c(a):(s?.(),u))}async function J(t){const r=new URLSearchParams(window.location.search),o=r.get("code"),s=r.get("state");if(!o)throw new Error("Missing OAuth code");const a=sessionStorage.getItem("oauth_state");if(!s||s!==a)throw new Error("Invalid OAuth state");const c=sessionStorage.getItem("pkce_verifier");if(!c)throw new Error("Missing PKCE verifier");const u=await fetch(`${t.config.authServer}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId,code:o,code_verifier:c})});if(!u.ok){const E=await u.text();throw new Error(`Token exchange failed: ${u.status} ${E}`)}const m=await u.json();t.setToken(m.access),sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("pkce_verifier")}function ee(t=64){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let o="";const s=new Uint8Array(t);crypto.getRandomValues(s);for(let a=0;a<s.length;a++)o+=r[s[a]%r.length];return o}async function te(t){const o=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",o);return new Uint8Array(s)}function re(t){return btoa(String.fromCharCode(...Array.from(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function T(t){const r=ee(64),o=re(await te(r));sessionStorage.setItem("pkce_verifier",r);const s=crypto.randomUUID();sessionStorage.setItem("oauth_state",s);const a=new URLSearchParams({response_type:"code",client_id:t.config.clientId,redirect_uri:t.config.redirectUri,code_challenge:o,code_challenge_method:"S256",state:s});window.location.href=`${t.config.authServer}/authorize?${a}`}async function x(t){try{await j(t,`${t.config.authServer}/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId})}),localStorage.removeItem(t.config.baseKey+"_access"),await T(t)}catch(r){console.error(r)}}const k=h.createContext({login:()=>{},logout:()=>{},loadMe:()=>{},authManager:null,user:null,loading:!1});var w={exports:{}},p={};var V;function ne(){if(V)return p;V=1;var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function o(s,a,c){var u=null;if(c!==void 0&&(u=""+c),a.key!==void 0&&(u=""+a.key),"key"in a){c={};for(var m in a)m!=="key"&&(c[m]=a[m])}else c=a;return a=c.ref,{$$typeof:t,type:s,key:u,ref:a!==void 0?a:null,props:c}}return p.Fragment=r,p.jsx=o,p.jsxs=o,p}var b={};var W;function oe(){return W||(W=1,process.env.NODE_ENV!=="production"&&(function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Ee?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case C:return"Fragment";case de:return"Profiler";case fe:return"StrictMode";case _e:return"Suspense";case ve:return"SuspenseList";case be:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case ue:return"Portal";case me:return e.displayName||"Context";case he:return(e._context.displayName||"Context")+".Consumer";case ge:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case pe:return n=e.displayName||null,n!==null?n:t(e.type)||"Memo";case I:n=e._payload,e=e._init;try{return t(e(n))}catch{}}return null}function r(e){return""+e}function o(e){try{r(e);var n=!1}catch{n=!0}if(n){n=console;var i=n.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),r(e)}}function s(e){if(e===C)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===I)return"<...>";try{var n=t(e);return n?"<"+n+">":"<...>"}catch{return"<...>"}}function a(){var e=N.A;return e===null?null:e.getOwner()}function c(){return Error("react-stack-top-frame")}function u(e){if(M.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function m(e,n){function i(){B||(B=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",n))}i.isReactWarning=!0,Object.defineProperty(e,"key",{get:i,configurable:!0})}function E(){var e=t(this.type);return H[e]||(H[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function R(e,n,i,f,O,U){var d=i.ref;return e={$$typeof:K,type:e,key:n,props:i,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:E}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:O}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function y(e,n,i,f,O,U){var d=n.children;if(d!==void 0)if(f)if(ye(d)){for(f=0;f<d.length;f++)g(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else g(d);if(M.call(n,"key")){d=t(e);var v=Object.keys(n).filter(function(Te){return Te!=="key"});f=0<v.length?"{key: someKey, "+v.join(": ..., ")+": ...}":"{key: someKey}",Q[d+f]||(v=0<v.length?"{"+v.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
1
+ (function(i,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("react"),require("react-router-dom")):typeof define=="function"&&define.amd?define(["exports","react","react-router-dom"],h):(i=typeof globalThis<"u"?globalThis:i||self,h(i["alex-evo-sh-auth"]={},i.React,i.ReactRouterDOM))})(this,(function(i,h,Y){"use strict";async function L(r){const t=await fetch(`${r.authServer}/refresh`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:r.clientId})});if(t.status===401)return localStorage.removeItem(r.baseKey+"_access"),null;if(!t.ok)throw new Error(`Token refresh failed: ${t.status} ${await t.text()}`);const n=await t.json();if(typeof n.access!="string"||!n.access)throw new Error("Token refresh response did not contain an access token");return localStorage.setItem(r.baseKey+"_access",n.access),n.access}class ${constructor(t,n){this.onAuthFail=n,this.config=t}onAuthFail;refreshPromise=null;config;getToken(){return localStorage.getItem(this.config.baseKey+"_access")}setToken(t){t?localStorage.setItem(this.config.baseKey+"_access",t):localStorage.removeItem(this.config.baseKey+"_access")}async getValidToken(){let t=this.getToken();return t||(this.refreshPromise||(this.refreshPromise=L(this.config).then(n=>(this.setToken(n),n)).finally(()=>{this.refreshPromise=null})),t=await this.refreshPromise,!t&&this.onAuthFail&&this.onAuthFail(),t)}}class q{authServer;clientId;redirectUri;homePage;baseKey;constructor(t,n,s,a,l){this.authServer=t,this.clientId=n,this.redirectUri=s,this.homePage=a,this.baseKey=l}}async function O(r,t,n={},s){let a=r.getToken();const l=m=>fetch(t,{...n,credentials:n.credentials??"include",headers:{...n.headers,Authorization:m?`Bearer ${m}`:""}}),u=await l(a);return u.status!==401?u:(r.setToken(null),a=await r.getValidToken(),a?l(a):(s?.(),u))}async function D(r){const t=new URLSearchParams(window.location.search),n=t.get("code"),s=t.get("state");if(!n)throw new Error("Missing OAuth code");const a=sessionStorage.getItem("oauth_state");if(!s||s!==a)throw new Error("Invalid OAuth state");const l=sessionStorage.getItem("pkce_verifier");if(!l)throw new Error("Missing PKCE verifier");const u=await fetch(`${r.config.authServer}/token`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r.config.clientId,code:n,code_verifier:l})});if(!u.ok){const k=await u.text();throw new Error(`Token exchange failed: ${u.status} ${k}`)}const m=await u.json();if(typeof m.access!="string"||!m.access)throw new Error("Token response did not contain an access token");r.setToken(m.access),sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("pkce_verifier")}function ee(r=64){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";const s=new Uint8Array(r);crypto.getRandomValues(s);for(let a=0;a<s.length;a++)n+=t[s[a]%t.length];return n}async function te(r){const n=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",n);return new Uint8Array(s)}function re(r){return btoa(String.fromCharCode(...Array.from(r))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function j(r){const t=ee(64),n=re(await te(t));sessionStorage.setItem("pkce_verifier",t);const s=crypto.randomUUID();sessionStorage.setItem("oauth_state",s);const a=new URLSearchParams({response_type:"code",client_id:r.config.clientId,redirect_uri:r.config.redirectUri,code_challenge:n,code_challenge_method:"S256",state:s});window.location.href=`${r.config.authServer}/authorize?${a}`}async function V(r){try{await O(r,`${r.config.authServer}/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r.config.clientId})}),localStorage.removeItem(r.config.baseKey+"_access"),await j(r)}catch(t){console.error(t)}}const T=h.createContext({login:()=>{},logout:()=>{},loadMe:async()=>{},authManager:null,user:null,loading:!1});var y={exports:{}},E={};var J;function ne(){if(J)return E;J=1;var r=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(s,a,l){var u=null;if(l!==void 0&&(u=""+l),a.key!==void 0&&(u=""+a.key),"key"in a){l={};for(var m in a)m!=="key"&&(l[m]=a[m])}else l=a;return a=l.ref,{$$typeof:r,type:s,key:u,ref:a!==void 0?a:null,props:l}}return E.Fragment=t,E.jsx=n,E.jsxs=n,E}var b={};var W;function oe(){return W||(W=1,process.env.NODE_ENV!=="production"&&(function(){function r(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===be?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case x:return"Fragment";case de:return"Profiler";case fe:return"StrictMode";case ve:return"Suspense";case _e:return"SuspenseList";case Ee:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case ue:return"Portal";case me:return e.displayName||"Context";case he:return(e._context.displayName||"Context")+".Consumer";case ge:var o=e.render;return e=e.displayName,e||(e=o.displayName||o.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case pe:return o=e.displayName||null,o!==null?o:r(e.type)||"Memo";case C:o=e._payload,e=e._init;try{return r(e(o))}catch{}}return null}function t(e){return""+e}function n(e){try{t(e);var o=!1}catch{o=!0}if(o){o=console;var c=o.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return c.call(o,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),t(e)}}function s(e){if(e===x)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===C)return"<...>";try{var o=r(e);return o?"<"+o+">":"<...>"}catch{return"<...>"}}function a(){var e=I.A;return e===null?null:e.getOwner()}function l(){return Error("react-stack-top-frame")}function u(e){if(H.call(e,"key")){var o=Object.getOwnPropertyDescriptor(e,"key").get;if(o&&o.isReactWarning)return!1}return e.key!==void 0}function m(e,o){function c(){X||(X=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",o))}c.isReactWarning=!0,Object.defineProperty(e,"key",{get:c,configurable:!0})}function k(){var e=r(this.type);return B[e]||(B[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function S(e,o,c,f,A,F){var d=c.ref;return e={$$typeof:K,type:e,key:o,props:c,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:k}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:A}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:F}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function v(e,o,c,f,A,F){var d=o.children;if(d!==void 0)if(f)if(ke(d)){for(f=0;f<d.length;f++)_(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else _(d);if(H.call(o,"key")){d=r(e);var p=Object.keys(o).filter(function(Te){return Te!=="key"});f=0<p.length?"{key: someKey, "+p.join(": ..., ")+": ...}":"{key: someKey}",Q[d+f]||(p=0<p.length?"{"+p.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
2
  let props = %s;
3
3
  <%s {...props} />
4
4
  React keys must be passed directly to JSX without using spread:
5
5
  let props = %s;
6
- <%s key={someKey} {...props} />`,f,d,v,d),Q[d+f]=!0)}if(d=null,i!==void 0&&(o(i),d=""+i),u(n)&&(o(n.key),d=""+n.key),"key"in n){i={};for(var Y in n)Y!=="key"&&(i[Y]=n[Y])}else i=n;return d&&m(i,typeof e=="function"?e.displayName||e.name||"Unknown":e),R(e,d,i,a(),O,U)}function g(e){P(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===I&&(e._payload.status==="fulfilled"?P(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function P(e){return typeof e=="object"&&e!==null&&e.$$typeof===K}var A=h,K=Symbol.for("react.transitional.element"),ue=Symbol.for("react.portal"),C=Symbol.for("react.fragment"),fe=Symbol.for("react.strict_mode"),de=Symbol.for("react.profiler"),he=Symbol.for("react.consumer"),me=Symbol.for("react.context"),ge=Symbol.for("react.forward_ref"),_e=Symbol.for("react.suspense"),ve=Symbol.for("react.suspense_list"),pe=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),be=Symbol.for("react.activity"),Ee=Symbol.for("react.client.reference"),N=A.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,M=Object.prototype.hasOwnProperty,ye=Array.isArray,F=console.createTask?console.createTask:function(){return null};A={react_stack_bottom_frame:function(e){return e()}};var B,H={},X=A.react_stack_bottom_frame.bind(A,c)(),Z=F(s(c)),Q={};b.Fragment=C,b.jsx=function(e,n,i){var f=1e4>N.recentlyCreatedOwnerStacks++;return y(e,n,i,!1,f?Error("react-stack-top-frame"):X,f?F(s(e)):Z)},b.jsxs=function(e,n,i){var f=1e4>N.recentlyCreatedOwnerStacks++;return y(e,n,i,!0,f?Error("react-stack-top-frame"):X,f?F(s(e)):Z)}})()),b}var z;function ae(){return z||(z=1,process.env.NODE_ENV==="production"?w.exports=ne():w.exports=oe()),w.exports}var _=ae();const se=({children:t,authManager:r})=>{const[o,s]=h.useState(null),[a,c]=h.useState(!0),u=h.useCallback(async()=>{c(!0);const R=localStorage.getItem(r.config.baseKey+"_access");if(!R){s(null),c(!1);return}try{const y=await j(r,`${r.config.authServer}/me`,{headers:{Authorization:`Bearer ${R}`}});if(!y.ok)throw new Error("not found");const g=await y.json();s({role:g.role.role_name,userId:g.user_id,userName:g.user_name,privileges:g.role.privileges.map(P=>P.privilege.trim())})}catch{s(null)}c(!1)},[]);h.useEffect(()=>{u()},[u]);const m=h.useCallback(()=>{T(r)},[T,r]),E=h.useCallback(()=>{x(r),s(null)},[x,r]);return _.jsx(k.Provider,{value:{loadMe:u,loading:a,user:o,login:m,authManager:r,logout:E},children:t})},ce=()=>{const{authManager:t,loadMe:r}=h.useContext(k),o=h.useRef(!1);return h.useEffect(()=>{if(!t||o.current)return;o.current=!0,(async()=>{try{await J(t),await r(),window.location.replace(t.config.homePage)}catch(a){console.error("Authentication callback failed:",a),window.location.replace(t.config.homePage)}})()},[t,r]),_.jsx("div",{children:"Авторизация..."})},S=()=>{const t=h.useContext(k);if(!t||!t.authManager)throw new Error("AuthContext not found");return t},G=t=>{const{user:r}=S();return!!r?.privileges?.includes(t)};function ie({privilege:t,invalidPage:r,loadingPage:o}){const{loading:s}=S(),a=G(t);return s?o:a?_.jsx(L.Outlet,{}):r}function le({loadingPage:t}){const{authManager:r,login:o,user:s}=S(),[a,c]=h.useState(!0);return h.useEffect(()=>{if(!r)return;r.getToken()?c(!1):o()},[r,s]),r?a?t??_.jsx("div",{children:"Loading..."}):_.jsx(L.Outlet,{}):_.jsx("p",{children:"invalud config"})}l.AuthContext=k,l.AuthManager=$,l.AuthProvider=se,l.CallbackPage=ce,l.Config=q,l.PrivilegeGate=ie,l.ProtectGate=le,l.apiFetch=j,l.handleCallback=J,l.login=T,l.logout=x,l.refreshToken=D,l.useAuth=S,l.usePrivilege=G,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
6
+ <%s key={someKey} {...props} />`,f,d,p,d),Q[d+f]=!0)}if(d=null,c!==void 0&&(n(c),d=""+c),u(o)&&(n(o.key),d=""+o.key),"key"in o){c={};for(var U in o)U!=="key"&&(c[U]=o[U])}else c=o;return d&&m(c,typeof e=="function"?e.displayName||e.name||"Unknown":e),S(e,d,c,a(),A,F)}function _(e){R(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===C&&(e._payload.status==="fulfilled"?R(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function R(e){return typeof e=="object"&&e!==null&&e.$$typeof===K}var P=h,K=Symbol.for("react.transitional.element"),ue=Symbol.for("react.portal"),x=Symbol.for("react.fragment"),fe=Symbol.for("react.strict_mode"),de=Symbol.for("react.profiler"),he=Symbol.for("react.consumer"),me=Symbol.for("react.context"),ge=Symbol.for("react.forward_ref"),ve=Symbol.for("react.suspense"),_e=Symbol.for("react.suspense_list"),pe=Symbol.for("react.memo"),C=Symbol.for("react.lazy"),Ee=Symbol.for("react.activity"),be=Symbol.for("react.client.reference"),I=P.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,H=Object.prototype.hasOwnProperty,ke=Array.isArray,N=console.createTask?console.createTask:function(){return null};P={react_stack_bottom_frame:function(e){return e()}};var X,B={},M=P.react_stack_bottom_frame.bind(P,l)(),Z=N(s(l)),Q={};b.Fragment=x,b.jsx=function(e,o,c){var f=1e4>I.recentlyCreatedOwnerStacks++;return v(e,o,c,!1,f?Error("react-stack-top-frame"):M,f?N(s(e)):Z)},b.jsxs=function(e,o,c){var f=1e4>I.recentlyCreatedOwnerStacks++;return v(e,o,c,!0,f?Error("react-stack-top-frame"):M,f?N(s(e)):Z)}})()),b}var G;function se(){return G||(G=1,process.env.NODE_ENV==="production"?y.exports=ne():y.exports=oe()),y.exports}var g=se();const ae=({children:r,authManager:t})=>{const[n,s]=h.useState(null),[a,l]=h.useState(!0),u=h.useCallback(async()=>{try{if(!await t.getValidToken()){s(null);return}const v=await O(t,`${t.config.authServer}/me`);if(v.status===401){t.setToken(null),s(null);return}if(!v.ok)throw new Error(`Failed to load current user: ${v.status}`);const _=await v.json();s({role:_.role.role_name,userId:_.user_id,userName:_.user_name,privileges:_.role.privileges.map(R=>R.privilege.trim())})}catch(S){console.error("Failed to load current user:",S),s(null)}finally{l(!1)}},[t]);h.useEffect(()=>{Promise.resolve().then(u)},[u]);const m=h.useCallback(()=>{j(t)},[t]),k=h.useCallback(()=>{V(t),s(null)},[t]);return g.jsx(T.Provider,{value:{loadMe:u,loading:a,user:n,login:m,authManager:t,logout:k},children:r})},ce=()=>{const{authManager:r,login:t}=h.useContext(T),n=h.useRef(!1),[s,a]=h.useState(null);return h.useEffect(()=>{if(!r||n.current)return;n.current=!0,(async()=>{try{await D(r),window.location.replace(r.config.homePage)}catch(u){console.error("Authentication callback failed:",u),a("Не удалось завершить вход. Попробуйте снова.")}})()},[r]),s?g.jsxs("div",{role:"alert",children:[g.jsxs("p",{children:["Не удалось завершить вход: ",s]}),g.jsx("button",{type:"button",onClick:t,children:"Повторить вход"})]}):g.jsx("div",{children:"Авторизация..."})},w=()=>{const r=h.useContext(T);if(!r||!r.authManager)throw new Error("AuthContext not found");return r},z=r=>{const{user:t}=w();return!!t?.privileges?.includes(r)};function ie({privilege:r,invalidPage:t,loadingPage:n}){const{loading:s}=w(),a=z(r);return s?n:a?g.jsx(Y.Outlet,{}):t}function le({loadingPage:r}){const{authManager:t,login:n,loading:s}=w(),a=t?.getToken()??null;return h.useEffect(()=>{t&&!s&&!a&&n()},[t,s,n,a]),s||!a?r??g.jsx("div",{children:"Loading..."}):g.jsx(Y.Outlet,{})}i.AuthContext=T,i.AuthManager=$,i.AuthProvider=ae,i.CallbackPage=ce,i.Config=q,i.PrivilegeGate=ie,i.ProtectGate=le,i.apiFetch=O,i.handleCallback=D,i.login=j,i.logout=V,i.refreshToken=L,i.useAuth=w,i.usePrivilege=z,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));
@@ -1,2 +1,2 @@
1
1
  import { Config } from './config';
2
- export declare function refreshToken(authConfig: Config): Promise<any>;
2
+ export declare function refreshToken(authConfig: Config): Promise<string | null>;
@@ -3,7 +3,7 @@ import { AuthData } from '../types';
3
3
  type IAuthContext = {
4
4
  login: () => void;
5
5
  logout: () => void;
6
- loadMe: () => void;
6
+ loadMe: () => Promise<void>;
7
7
  authManager: AuthManager | null;
8
8
  user: AuthData | null;
9
9
  loading: boolean;
@@ -1,6 +1,5 @@
1
- import { default as React } from 'react';
2
1
  export declare function PrivilegeGate({ privilege, invalidPage, loadingPage }: {
3
2
  privilege: string;
4
3
  invalidPage: React.ReactNode;
5
4
  loadingPage: React.ReactNode;
6
- }): string | number | bigint | boolean | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | React.JSX.Element | null | undefined;
5
+ }): string | number | bigint | boolean | Iterable<import('react').ReactNode> | Promise<string | number | bigint | boolean | import('react').ReactPortal | import('react').ReactElement<unknown, string | import('react').JSXElementConstructor<any>> | Iterable<import('react').ReactNode> | null | undefined> | import("react").JSX.Element | null | undefined;
@@ -1,7 +1,7 @@
1
1
  export declare const useAuth: () => {
2
2
  login: () => void;
3
3
  logout: () => void;
4
- loadMe: () => void;
4
+ loadMe: () => Promise<void>;
5
5
  authManager: import('../..').AuthManager | null;
6
6
  user: import('../types').AuthData | null;
7
7
  loading: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alex-evo-sh-auth",
3
- "version": "0.0.17",
3
+ "version": "0.0.21",
4
4
  "type": "module",
5
5
  "main": "./dist/alex-evo-sh-auth.umd.js",
6
6
  "module": "./dist/alex-evo-sh-auth.es.js",