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