@riligar/auth-react 1.0.4

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.
@@ -0,0 +1,828 @@
1
+ import require$$0, { useEffect, createContext } from 'react';
2
+ import { Navigate, Outlet } from 'react-router-dom';
3
+
4
+ // Ajuste se o back-end estiver em outro domínio/porta
5
+ const API_BASE = typeof window !== 'undefined' && window?.location ? import.meta?.env?.VITE_API_BASE ?? "http://localhost:3000" : "http://localhost:3000";
6
+
7
+ // helper fetch pré-configurado
8
+ async function api(route, opts = {}) {
9
+ const token = getStoredToken();
10
+ const headers = {
11
+ "Content-Type": "application/json",
12
+ ...opts.headers
13
+ };
14
+
15
+ // Adiciona Authorization header se tiver token
16
+ if (token) {
17
+ headers.Authorization = `Bearer ${token}`;
18
+ }
19
+ const res = await fetch(`${API_BASE}${route}`, {
20
+ headers,
21
+ ...opts
22
+ });
23
+
24
+ // Converte JSON automaticamente e lança erro legível
25
+ const data = res.status !== 204 ? await res.json().catch(() => ({})) : null;
26
+ if (!res.ok) throw Object.assign(new Error(data?.error ?? res.statusText), {
27
+ res,
28
+ data
29
+ });
30
+ return data;
31
+ }
32
+
33
+ // Gerenciamento de token no localStorage
34
+ function getStoredToken() {
35
+ if (typeof window === 'undefined') return null;
36
+ return window.localStorage.getItem('auth:token');
37
+ }
38
+ function setStoredToken(token) {
39
+ if (typeof window === 'undefined') return;
40
+ if (token) {
41
+ window.localStorage.setItem('auth:token', token);
42
+ } else {
43
+ window.localStorage.removeItem('auth:token');
44
+ }
45
+ }
46
+
47
+ // Decodifica JWT (apenas payload, sem verificação de assinatura)
48
+ function decodeJWT(token) {
49
+ try {
50
+ const parts = token.split('.');
51
+ if (parts.length !== 3) return null;
52
+ const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
53
+ return payload;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ // Verifica se o token está expirado
60
+ function isTokenExpired(token) {
61
+ const payload = decodeJWT(token);
62
+ if (!payload || !payload.exp) return true;
63
+ return Date.now() >= payload.exp * 1000;
64
+ }
65
+
66
+ // Verifica se o usuário está autenticado
67
+ function isAuthenticated() {
68
+ const token = getStoredToken();
69
+ return token && !isTokenExpired(token);
70
+ }
71
+
72
+ // Obtém dados do usuário do token
73
+ function getCurrentUser() {
74
+ const token = getStoredToken();
75
+ if (!token || isTokenExpired(token)) return null;
76
+ const payload = decodeJWT(token);
77
+ return payload ? {
78
+ id: payload.sub,
79
+ email: payload.email,
80
+ name: payload.name,
81
+ ...payload
82
+ } : null;
83
+ }
84
+
85
+ /*--- métodos de autenticação-------------------*/
86
+ const signUp = async (email, password) => {
87
+ const result = await api("/auth/sign-up", {
88
+ method: "POST",
89
+ body: JSON.stringify({
90
+ email,
91
+ password
92
+ })
93
+ });
94
+ if (result.token) {
95
+ setStoredToken(result.token);
96
+ }
97
+ return result;
98
+ };
99
+ const signIn = async (email, password) => {
100
+ const result = await api("/auth/sign-in", {
101
+ method: "POST",
102
+ body: JSON.stringify({
103
+ email,
104
+ password
105
+ })
106
+ });
107
+ if (result.token) {
108
+ setStoredToken(result.token);
109
+ }
110
+ return result;
111
+ };
112
+ const signOut = async () => {
113
+ try {
114
+ await api("/auth/sign-out", {
115
+ method: "POST"
116
+ });
117
+ } catch {
118
+ // Ignora erros de logout no servidor
119
+ } finally {
120
+ setStoredToken(null);
121
+ }
122
+ };
123
+ const refreshToken = async () => {
124
+ try {
125
+ const result = await api("/auth/refresh", {
126
+ method: "POST"
127
+ });
128
+ if (result.token) {
129
+ setStoredToken(result.token);
130
+ return result;
131
+ }
132
+ } catch (error) {
133
+ setStoredToken(null);
134
+ throw error;
135
+ }
136
+ };
137
+
138
+ /* Social login redirect (ex.: Google) ---------*/
139
+ function socialRedirect(provider, redirectTo = typeof window !== 'undefined' ? window.location.href : '/') {
140
+ if (typeof window === 'undefined') return;
141
+ // Melhor pegar a URL de redirect dada pelo back-end, mas isso já funciona:
142
+ window.location = `${API_BASE}/auth/sign-in/${provider}?redirect=${encodeURIComponent(redirectTo)}`;
143
+ }
144
+
145
+ const createStoreImpl = (createState) => {
146
+ let state;
147
+ const listeners = /* @__PURE__ */ new Set();
148
+ const setState = (partial, replace) => {
149
+ const nextState = typeof partial === "function" ? partial(state) : partial;
150
+ if (!Object.is(nextState, state)) {
151
+ const previousState = state;
152
+ state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
153
+ listeners.forEach((listener) => listener(state, previousState));
154
+ }
155
+ };
156
+ const getState = () => state;
157
+ const getInitialState = () => initialState;
158
+ const subscribe = (listener) => {
159
+ listeners.add(listener);
160
+ return () => listeners.delete(listener);
161
+ };
162
+ const destroy = () => {
163
+ if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
164
+ console.warn(
165
+ "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."
166
+ );
167
+ }
168
+ listeners.clear();
169
+ };
170
+ const api = { setState, getState, getInitialState, subscribe, destroy };
171
+ const initialState = state = createState(setState, getState, api);
172
+ return api;
173
+ };
174
+ const createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
175
+
176
+ function getDefaultExportFromCjs (x) {
177
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
178
+ }
179
+
180
+ var withSelector = {exports: {}};
181
+
182
+ var withSelector_production = {};
183
+
184
+ var shim = {exports: {}};
185
+
186
+ var useSyncExternalStoreShim_production = {};
187
+
188
+ /**
189
+ * @license React
190
+ * use-sync-external-store-shim.production.js
191
+ *
192
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
193
+ *
194
+ * This source code is licensed under the MIT license found in the
195
+ * LICENSE file in the root directory of this source tree.
196
+ */
197
+
198
+ var hasRequiredUseSyncExternalStoreShim_production;
199
+
200
+ function requireUseSyncExternalStoreShim_production () {
201
+ if (hasRequiredUseSyncExternalStoreShim_production) return useSyncExternalStoreShim_production;
202
+ hasRequiredUseSyncExternalStoreShim_production = 1;
203
+ var React = require$$0;
204
+ function is(x, y) {
205
+ return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
206
+ }
207
+ var objectIs = "function" === typeof Object.is ? Object.is : is,
208
+ useState = React.useState,
209
+ useEffect = React.useEffect,
210
+ useLayoutEffect = React.useLayoutEffect,
211
+ useDebugValue = React.useDebugValue;
212
+ function useSyncExternalStore$2(subscribe, getSnapshot) {
213
+ var value = getSnapshot(),
214
+ _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),
215
+ inst = _useState[0].inst,
216
+ forceUpdate = _useState[1];
217
+ useLayoutEffect(
218
+ function () {
219
+ inst.value = value;
220
+ inst.getSnapshot = getSnapshot;
221
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
222
+ },
223
+ [subscribe, value, getSnapshot]
224
+ );
225
+ useEffect(
226
+ function () {
227
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
228
+ return subscribe(function () {
229
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
230
+ });
231
+ },
232
+ [subscribe]
233
+ );
234
+ useDebugValue(value);
235
+ return value;
236
+ }
237
+ function checkIfSnapshotChanged(inst) {
238
+ var latestGetSnapshot = inst.getSnapshot;
239
+ inst = inst.value;
240
+ try {
241
+ var nextValue = latestGetSnapshot();
242
+ return !objectIs(inst, nextValue);
243
+ } catch (error) {
244
+ return true;
245
+ }
246
+ }
247
+ function useSyncExternalStore$1(subscribe, getSnapshot) {
248
+ return getSnapshot();
249
+ }
250
+ var shim =
251
+ "undefined" === typeof window ||
252
+ "undefined" === typeof window.document ||
253
+ "undefined" === typeof window.document.createElement
254
+ ? useSyncExternalStore$1
255
+ : useSyncExternalStore$2;
256
+ useSyncExternalStoreShim_production.useSyncExternalStore =
257
+ void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
258
+ return useSyncExternalStoreShim_production;
259
+ }
260
+
261
+ var useSyncExternalStoreShim_development = {};
262
+
263
+ /**
264
+ * @license React
265
+ * use-sync-external-store-shim.development.js
266
+ *
267
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
268
+ *
269
+ * This source code is licensed under the MIT license found in the
270
+ * LICENSE file in the root directory of this source tree.
271
+ */
272
+
273
+ var hasRequiredUseSyncExternalStoreShim_development;
274
+
275
+ function requireUseSyncExternalStoreShim_development () {
276
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
277
+ hasRequiredUseSyncExternalStoreShim_development = 1;
278
+ "production" !== process.env.NODE_ENV &&
279
+ (function () {
280
+ function is(x, y) {
281
+ return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
282
+ }
283
+ function useSyncExternalStore$2(subscribe, getSnapshot) {
284
+ didWarnOld18Alpha ||
285
+ void 0 === React.startTransition ||
286
+ ((didWarnOld18Alpha = true),
287
+ console.error(
288
+ "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
289
+ ));
290
+ var value = getSnapshot();
291
+ if (!didWarnUncachedGetSnapshot) {
292
+ var cachedValue = getSnapshot();
293
+ objectIs(value, cachedValue) ||
294
+ (console.error(
295
+ "The result of getSnapshot should be cached to avoid an infinite loop"
296
+ ),
297
+ (didWarnUncachedGetSnapshot = true));
298
+ }
299
+ cachedValue = useState({
300
+ inst: { value: value, getSnapshot: getSnapshot }
301
+ });
302
+ var inst = cachedValue[0].inst,
303
+ forceUpdate = cachedValue[1];
304
+ useLayoutEffect(
305
+ function () {
306
+ inst.value = value;
307
+ inst.getSnapshot = getSnapshot;
308
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
309
+ },
310
+ [subscribe, value, getSnapshot]
311
+ );
312
+ useEffect(
313
+ function () {
314
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
315
+ return subscribe(function () {
316
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
317
+ });
318
+ },
319
+ [subscribe]
320
+ );
321
+ useDebugValue(value);
322
+ return value;
323
+ }
324
+ function checkIfSnapshotChanged(inst) {
325
+ var latestGetSnapshot = inst.getSnapshot;
326
+ inst = inst.value;
327
+ try {
328
+ var nextValue = latestGetSnapshot();
329
+ return !objectIs(inst, nextValue);
330
+ } catch (error) {
331
+ return true;
332
+ }
333
+ }
334
+ function useSyncExternalStore$1(subscribe, getSnapshot) {
335
+ return getSnapshot();
336
+ }
337
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
338
+ "function" ===
339
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
340
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
341
+ var React = require$$0,
342
+ objectIs = "function" === typeof Object.is ? Object.is : is,
343
+ useState = React.useState,
344
+ useEffect = React.useEffect,
345
+ useLayoutEffect = React.useLayoutEffect,
346
+ useDebugValue = React.useDebugValue,
347
+ didWarnOld18Alpha = false,
348
+ didWarnUncachedGetSnapshot = false,
349
+ shim =
350
+ "undefined" === typeof window ||
351
+ "undefined" === typeof window.document ||
352
+ "undefined" === typeof window.document.createElement
353
+ ? useSyncExternalStore$1
354
+ : useSyncExternalStore$2;
355
+ useSyncExternalStoreShim_development.useSyncExternalStore =
356
+ void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
357
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
358
+ "function" ===
359
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
360
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
361
+ })();
362
+ return useSyncExternalStoreShim_development;
363
+ }
364
+
365
+ var hasRequiredShim;
366
+
367
+ function requireShim () {
368
+ if (hasRequiredShim) return shim.exports;
369
+ hasRequiredShim = 1;
370
+
371
+ if (process.env.NODE_ENV === 'production') {
372
+ shim.exports = requireUseSyncExternalStoreShim_production();
373
+ } else {
374
+ shim.exports = requireUseSyncExternalStoreShim_development();
375
+ }
376
+ return shim.exports;
377
+ }
378
+
379
+ /**
380
+ * @license React
381
+ * use-sync-external-store-shim/with-selector.production.js
382
+ *
383
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
384
+ *
385
+ * This source code is licensed under the MIT license found in the
386
+ * LICENSE file in the root directory of this source tree.
387
+ */
388
+
389
+ var hasRequiredWithSelector_production;
390
+
391
+ function requireWithSelector_production () {
392
+ if (hasRequiredWithSelector_production) return withSelector_production;
393
+ hasRequiredWithSelector_production = 1;
394
+ var React = require$$0,
395
+ shim = requireShim();
396
+ function is(x, y) {
397
+ return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
398
+ }
399
+ var objectIs = "function" === typeof Object.is ? Object.is : is,
400
+ useSyncExternalStore = shim.useSyncExternalStore,
401
+ useRef = React.useRef,
402
+ useEffect = React.useEffect,
403
+ useMemo = React.useMemo,
404
+ useDebugValue = React.useDebugValue;
405
+ withSelector_production.useSyncExternalStoreWithSelector = function (
406
+ subscribe,
407
+ getSnapshot,
408
+ getServerSnapshot,
409
+ selector,
410
+ isEqual
411
+ ) {
412
+ var instRef = useRef(null);
413
+ if (null === instRef.current) {
414
+ var inst = { hasValue: false, value: null };
415
+ instRef.current = inst;
416
+ } else inst = instRef.current;
417
+ instRef = useMemo(
418
+ function () {
419
+ function memoizedSelector(nextSnapshot) {
420
+ if (!hasMemo) {
421
+ hasMemo = true;
422
+ memoizedSnapshot = nextSnapshot;
423
+ nextSnapshot = selector(nextSnapshot);
424
+ if (void 0 !== isEqual && inst.hasValue) {
425
+ var currentSelection = inst.value;
426
+ if (isEqual(currentSelection, nextSnapshot))
427
+ return (memoizedSelection = currentSelection);
428
+ }
429
+ return (memoizedSelection = nextSnapshot);
430
+ }
431
+ currentSelection = memoizedSelection;
432
+ if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
433
+ var nextSelection = selector(nextSnapshot);
434
+ if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
435
+ return (memoizedSnapshot = nextSnapshot), currentSelection;
436
+ memoizedSnapshot = nextSnapshot;
437
+ return (memoizedSelection = nextSelection);
438
+ }
439
+ var hasMemo = false,
440
+ memoizedSnapshot,
441
+ memoizedSelection,
442
+ maybeGetServerSnapshot =
443
+ void 0 === getServerSnapshot ? null : getServerSnapshot;
444
+ return [
445
+ function () {
446
+ return memoizedSelector(getSnapshot());
447
+ },
448
+ null === maybeGetServerSnapshot
449
+ ? void 0
450
+ : function () {
451
+ return memoizedSelector(maybeGetServerSnapshot());
452
+ }
453
+ ];
454
+ },
455
+ [getSnapshot, getServerSnapshot, selector, isEqual]
456
+ );
457
+ var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
458
+ useEffect(
459
+ function () {
460
+ inst.hasValue = true;
461
+ inst.value = value;
462
+ },
463
+ [value]
464
+ );
465
+ useDebugValue(value);
466
+ return value;
467
+ };
468
+ return withSelector_production;
469
+ }
470
+
471
+ var withSelector_development = {};
472
+
473
+ /**
474
+ * @license React
475
+ * use-sync-external-store-shim/with-selector.development.js
476
+ *
477
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
478
+ *
479
+ * This source code is licensed under the MIT license found in the
480
+ * LICENSE file in the root directory of this source tree.
481
+ */
482
+
483
+ var hasRequiredWithSelector_development;
484
+
485
+ function requireWithSelector_development () {
486
+ if (hasRequiredWithSelector_development) return withSelector_development;
487
+ hasRequiredWithSelector_development = 1;
488
+ "production" !== process.env.NODE_ENV &&
489
+ (function () {
490
+ function is(x, y) {
491
+ return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
492
+ }
493
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
494
+ "function" ===
495
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
496
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
497
+ var React = require$$0,
498
+ shim = requireShim(),
499
+ objectIs = "function" === typeof Object.is ? Object.is : is,
500
+ useSyncExternalStore = shim.useSyncExternalStore,
501
+ useRef = React.useRef,
502
+ useEffect = React.useEffect,
503
+ useMemo = React.useMemo,
504
+ useDebugValue = React.useDebugValue;
505
+ withSelector_development.useSyncExternalStoreWithSelector = function (
506
+ subscribe,
507
+ getSnapshot,
508
+ getServerSnapshot,
509
+ selector,
510
+ isEqual
511
+ ) {
512
+ var instRef = useRef(null);
513
+ if (null === instRef.current) {
514
+ var inst = { hasValue: false, value: null };
515
+ instRef.current = inst;
516
+ } else inst = instRef.current;
517
+ instRef = useMemo(
518
+ function () {
519
+ function memoizedSelector(nextSnapshot) {
520
+ if (!hasMemo) {
521
+ hasMemo = true;
522
+ memoizedSnapshot = nextSnapshot;
523
+ nextSnapshot = selector(nextSnapshot);
524
+ if (void 0 !== isEqual && inst.hasValue) {
525
+ var currentSelection = inst.value;
526
+ if (isEqual(currentSelection, nextSnapshot))
527
+ return (memoizedSelection = currentSelection);
528
+ }
529
+ return (memoizedSelection = nextSnapshot);
530
+ }
531
+ currentSelection = memoizedSelection;
532
+ if (objectIs(memoizedSnapshot, nextSnapshot))
533
+ return currentSelection;
534
+ var nextSelection = selector(nextSnapshot);
535
+ if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
536
+ return (memoizedSnapshot = nextSnapshot), currentSelection;
537
+ memoizedSnapshot = nextSnapshot;
538
+ return (memoizedSelection = nextSelection);
539
+ }
540
+ var hasMemo = false,
541
+ memoizedSnapshot,
542
+ memoizedSelection,
543
+ maybeGetServerSnapshot =
544
+ void 0 === getServerSnapshot ? null : getServerSnapshot;
545
+ return [
546
+ function () {
547
+ return memoizedSelector(getSnapshot());
548
+ },
549
+ null === maybeGetServerSnapshot
550
+ ? void 0
551
+ : function () {
552
+ return memoizedSelector(maybeGetServerSnapshot());
553
+ }
554
+ ];
555
+ },
556
+ [getSnapshot, getServerSnapshot, selector, isEqual]
557
+ );
558
+ var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
559
+ useEffect(
560
+ function () {
561
+ inst.hasValue = true;
562
+ inst.value = value;
563
+ },
564
+ [value]
565
+ );
566
+ useDebugValue(value);
567
+ return value;
568
+ };
569
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
570
+ "function" ===
571
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
572
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
573
+ })();
574
+ return withSelector_development;
575
+ }
576
+
577
+ if (process.env.NODE_ENV === 'production') {
578
+ withSelector.exports = requireWithSelector_production();
579
+ } else {
580
+ withSelector.exports = requireWithSelector_development();
581
+ }
582
+
583
+ var withSelectorExports = withSelector.exports;
584
+ var useSyncExternalStoreExports = /*@__PURE__*/getDefaultExportFromCjs(withSelectorExports);
585
+
586
+ const { useDebugValue } = require$$0;
587
+ const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;
588
+ let didWarnAboutEqualityFn = false;
589
+ const identity = (arg) => arg;
590
+ function useStore(api, selector = identity, equalityFn) {
591
+ if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && equalityFn && !didWarnAboutEqualityFn) {
592
+ console.warn(
593
+ "[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"
594
+ );
595
+ didWarnAboutEqualityFn = true;
596
+ }
597
+ const slice = useSyncExternalStoreWithSelector(
598
+ api.subscribe,
599
+ api.getState,
600
+ api.getServerState || api.getInitialState,
601
+ selector,
602
+ equalityFn
603
+ );
604
+ useDebugValue(slice);
605
+ return slice;
606
+ }
607
+ const createImpl = (createState) => {
608
+ if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && typeof createState !== "function") {
609
+ console.warn(
610
+ "[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`."
611
+ );
612
+ }
613
+ const api = typeof createState === "function" ? createStore(createState) : createState;
614
+ const useBoundStore = (selector, equalityFn) => useStore(api, selector, equalityFn);
615
+ Object.assign(useBoundStore, api);
616
+ return useBoundStore;
617
+ };
618
+ const create = (createState) => createState ? createImpl(createState) : createImpl;
619
+
620
+ // Estado: { user, loading, error }
621
+ const useAuthStore = create((set, get) => ({
622
+ user: null,
623
+ loading: true,
624
+ error: null,
625
+ /* Init ao montar o Provider */
626
+ init: async () => {
627
+ try {
628
+ // Verifica se há um token válido e obtém dados do usuário
629
+ if (isAuthenticated()) {
630
+ const user = getCurrentUser();
631
+ set({
632
+ user,
633
+ loading: false
634
+ });
635
+ } else {
636
+ set({
637
+ user: null,
638
+ loading: false
639
+ });
640
+ }
641
+ } catch (error) {
642
+ console.error('Erro na inicialização:', error);
643
+ set({
644
+ user: null,
645
+ loading: false
646
+ });
647
+ }
648
+ },
649
+ /* Ações */
650
+ signUp: async (email, password) => {
651
+ set({
652
+ loading: true,
653
+ error: null
654
+ });
655
+ try {
656
+ const result = await signUp(email, password);
657
+ const user = getCurrentUser();
658
+ set({
659
+ user,
660
+ loading: false
661
+ });
662
+ return result;
663
+ } catch (err) {
664
+ set({
665
+ error: err,
666
+ loading: false
667
+ });
668
+ throw err;
669
+ }
670
+ },
671
+ signIn: async (email, password) => {
672
+ set({
673
+ loading: true,
674
+ error: null
675
+ });
676
+ try {
677
+ const result = await signIn(email, password);
678
+ const user = getCurrentUser();
679
+ set({
680
+ user,
681
+ loading: false
682
+ });
683
+ return result;
684
+ } catch (err) {
685
+ set({
686
+ error: err,
687
+ loading: false
688
+ });
689
+ throw err;
690
+ }
691
+ },
692
+ signOut: async () => {
693
+ await signOut();
694
+ set({
695
+ user: null
696
+ });
697
+ // Sincronizar logout entre abas
698
+ if (typeof window !== 'undefined') {
699
+ window.localStorage.setItem("auth:logout", Date.now());
700
+ }
701
+ },
702
+ /* Refresh do token em background */
703
+ startRefresh: () => {
704
+ if (typeof window === 'undefined') return;
705
+ const refreshInterval = setInterval(async () => {
706
+ try {
707
+ // Se o usuário está autenticado mas o token está próximo do vencimento
708
+ if (isAuthenticated()) {
709
+ const token = window.localStorage.getItem('auth:token');
710
+ if (token) {
711
+ // Decodifica o token para verificar tempo de expiração
712
+ const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
713
+ const now = Date.now() / 1000;
714
+ const timeUntilExpiry = payload.exp - now;
715
+
716
+ // Se o token expira em menos de 5 minutos, faz refresh
717
+ if (timeUntilExpiry < 300) {
718
+ // 5 minutos
719
+ await refreshToken();
720
+ const user = getCurrentUser();
721
+ set({
722
+ user
723
+ });
724
+ }
725
+ }
726
+ }
727
+ } catch (error) {
728
+ console.error('Erro no refresh automático:', error);
729
+ // Em caso de erro, faz logout
730
+ set({
731
+ user: null
732
+ });
733
+ window.localStorage.removeItem('auth:token');
734
+ }
735
+ }, 4 * 60 * 1000); // Verifica a cada 4 minutos
736
+
737
+ // Limpa o intervalo quando necessário
738
+ if (typeof window !== 'undefined') {
739
+ window.addEventListener('beforeunload', () => {
740
+ clearInterval(refreshInterval);
741
+ });
742
+ }
743
+ },
744
+ /* Verifica se o token ainda é válido */
745
+ checkTokenValidity: () => {
746
+ if (!isAuthenticated()) {
747
+ set({
748
+ user: null
749
+ });
750
+ return false;
751
+ }
752
+ return true;
753
+ }
754
+ }));
755
+
756
+ const AuthContext = /*#__PURE__*/createContext(); // só para ter o Provider em JSX
757
+
758
+ function AuthProvider({
759
+ children
760
+ }) {
761
+ const init = useAuthStore(s => s.init);
762
+ const startRefresh = useAuthStore(s => s.startRefresh);
763
+ const checkTokenValidity = useAuthStore(s => s.checkTokenValidity);
764
+ useEffect(() => {
765
+ init();
766
+ startRefresh();
767
+ }, [init, startRefresh]);
768
+
769
+ // Sincronização entre abas - escuta logout e mudanças no token
770
+ useEffect(() => {
771
+ if (typeof window === 'undefined') return;
772
+ const handleStorageChange = event => {
773
+ if (event.key === "auth:logout") {
774
+ window.location.reload();
775
+ }
776
+ // Se o token mudou em outra aba, recarrega
777
+ if (event.key === "auth:token") {
778
+ checkTokenValidity();
779
+ }
780
+ };
781
+ window.addEventListener("storage", handleStorageChange);
782
+ return () => window.removeEventListener("storage", handleStorageChange);
783
+ }, [checkTokenValidity]);
784
+
785
+ // Verifica validade do token periodicamente
786
+ useEffect(() => {
787
+ if (typeof window === 'undefined') return;
788
+ const interval = setInterval(() => {
789
+ checkTokenValidity();
790
+ }, 30 * 1000); // Verifica a cada 30 segundos
791
+
792
+ return () => clearInterval(interval);
793
+ }, [checkTokenValidity]);
794
+ return /*#__PURE__*/React.createElement(AuthContext.Provider, {
795
+ value: null /* valor irrelevante */
796
+ }, children);
797
+ }
798
+
799
+ /* Hooks "facade" que a app vai usar */
800
+ const useAuth = () => useAuthStore(s => ({
801
+ user: s.user,
802
+ loading: s.loading,
803
+ error: s.error,
804
+ isAuthenticated: s.user !== null
805
+ }));
806
+ const useSignIn = () => useAuthStore(s => s.signIn);
807
+ const useSignUp = () => useAuthStore(s => s.signUp);
808
+ const useSignOut = () => useAuthStore(s => s.signOut);
809
+ const useCheckToken = () => useAuthStore(s => s.checkTokenValidity);
810
+
811
+ function ProtectedRoute({
812
+ fallback = /*#__PURE__*/React.createElement("p", null, "\u231B Carregando..."),
813
+ redirectTo = "/login"
814
+ }) {
815
+ const {
816
+ user,
817
+ loading
818
+ } = useAuth();
819
+ if (loading) return fallback;
820
+ if (!user) return /*#__PURE__*/React.createElement(Navigate, {
821
+ to: redirectTo,
822
+ replace: true
823
+ });
824
+ return /*#__PURE__*/React.createElement(Outlet, null);
825
+ }
826
+
827
+ export { AuthProvider, ProtectedRoute, getCurrentUser, isAuthenticated, refreshToken, signIn, signOut, signUp, socialRedirect, useAuth, useAuthStore, useCheckToken, useSignIn, useSignOut, useSignUp };
828
+ //# sourceMappingURL=index.esm.js.map