npm-pkg-hook 1.3.5 → 1.3.7

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/package.json CHANGED
@@ -43,5 +43,5 @@
43
43
  "rm": "rm -rf node_modules package-lock.json && npm i",
44
44
  "test": "echo \"Error: no test specified\" && exit 1"
45
45
  },
46
- "version": "1.3.5"
46
+ "version": "1.3.7"
47
47
  }
@@ -0,0 +1,10 @@
1
+ export async function handleLogin(body) {
2
+ const response = await fetch(`${process.env.URL_BASE}/api/auth/login`, {
3
+ method: 'POST',
4
+ headers: { 'Content-Type': 'application/json' },
5
+ body: JSON.stringify(body),
6
+ credentials: 'include'
7
+ })
8
+
9
+ return response.json()
10
+ }
@@ -74,3 +74,4 @@ export * from './useUser'
74
74
  export * from './useCart'
75
75
  export * from './useGetStoreCookie'
76
76
  export * from './getGlobalSession'
77
+ export * from './handleLogin'
@@ -0,0 +1,32 @@
1
+ function BroadcastChannel(name = "nextauth.message") {
2
+ return {
3
+ receive: function (onReceive) {
4
+ const handler = function (event) {
5
+ if (event.key !== name) return;
6
+ const message = JSON.parse(event.newValue ?? "{}");
7
+ if (message?.event !== "session" || !message?.data) return;
8
+ onReceive(message);
9
+ };
10
+ window.addEventListener("storage", handler);
11
+ return function () {
12
+ window.removeEventListener("storage", handler);
13
+ };
14
+ },
15
+ post: function (message) {
16
+ if (typeof window === "undefined") return;
17
+ try {
18
+ localStorage.setItem(
19
+ name,
20
+ JSON.stringify({ ...message, timestamp: now() })
21
+ );
22
+ } catch {
23
+ // The localStorage API isn't always available.
24
+ // It won't work in private mode prior to Safari 11 for example.
25
+ // Notifications are simply dropped if an error is encountered.
26
+ }
27
+ },
28
+ };
29
+ }
30
+
31
+ export { BroadcastChannel };
32
+
@@ -0,0 +1,8 @@
1
+ export function apiBaseUrl(__NEXTAUTH) {
2
+ if (typeof window === "undefined") {
3
+ // Return absolute path when called server side
4
+ return `${__NEXTAUTH.baseUrlServer}${__NEXTAUTH.basePathServer}`
5
+ }
6
+ // Return relative path when called client side
7
+ return __NEXTAUTH.basePath
8
+ }
@@ -0,0 +1,29 @@
1
+ import { apiBaseUrl } from "./apiBaseUrl";
2
+
3
+ async function fetchData(path, __NEXTAUTH, logger, { ctx, req } = {}) {
4
+ const url = `${apiBaseUrl(__NEXTAUTH)}/${path}`;
5
+ try {
6
+ const options = {
7
+ headers: {
8
+ "Content-Type": "application/json",
9
+ ...(req?.headers?.cookie ? { cookie: req.headers.cookie } : {}),
10
+ },
11
+ };
12
+
13
+ if (req?.body) {
14
+ options.body = JSON.stringify(req.body);
15
+ options.method = "POST";
16
+ }
17
+
18
+ const res = await fetch(url, options);
19
+ const data = await res.json();
20
+ if (!res.ok) throw data;
21
+ return Object.keys(data).length > 0 ? data : null; // Return null if data is empty
22
+ } catch (error) {
23
+ logger.error("CLIENT_FETCH_ERROR", { error, url });
24
+ return null;
25
+ }
26
+ }
27
+
28
+ export { fetchData };
29
+
@@ -0,0 +1,30 @@
1
+ import { fetchData } from "./fetchData"
2
+ import _logger, { proxyLogger } from "./logger"
3
+ import { parseUrl } from "./parseUrl";
4
+
5
+ const __NEXTAUTH = {
6
+ baseUrl: parseUrl(process.env.NEXTAUTH_URL || process.env.VERCEL_URL).origin,
7
+ basePath: parseUrl(process.env.NEXTAUTH_URL).path,
8
+ baseUrlServer: parseUrl(
9
+ process.env.NEXTAUTH_URL_INTERNAL ||
10
+ process.env.NEXTAUTH_URL ||
11
+ process.env.VERCEL_URL
12
+ ).origin,
13
+ basePathServer: parseUrl(
14
+ process.env.NEXTAUTH_URL_INTERNAL || process.env.NEXTAUTH_URL
15
+ ).path,
16
+ _lastSync: 0,
17
+ _session: undefined,
18
+ _getSession: () => {},
19
+ };
20
+ const logger = proxyLogger(_logger, __NEXTAUTH.basePath)
21
+
22
+ export async function getCsrfToken(params) {
23
+ const response = await fetchData(
24
+ "csrf",
25
+ __NEXTAUTH,
26
+ logger,
27
+ params
28
+ )
29
+ return response?.csrfToken
30
+ }
@@ -0,0 +1,54 @@
1
+ import { apiBaseUrl } from "./apiBaseUrl";
2
+ import { getCsrfToken } from "./getCsrfToken";
3
+ import { parseUrl } from "./parseUrl";
4
+ import { BroadcastChannel } from "./BroadcastChannel";
5
+
6
+ const broadcast = BroadcastChannel()
7
+
8
+ export const __NEXTAUTH = {
9
+ baseUrl: parseUrl(process.env.NEXTAUTH_URL || process.env.VERCEL_URL).origin,
10
+ basePath: parseUrl(process.env.NEXTAUTH_URL).path,
11
+ baseUrlServer: parseUrl(
12
+ process.env.NEXTAUTH_URL_INTERNAL ||
13
+ process.env.NEXTAUTH_URL ||
14
+ process.env.VERCEL_URL
15
+ ).origin,
16
+ basePathServer: parseUrl(
17
+ process.env.NEXTAUTH_URL_INTERNAL || process.env.NEXTAUTH_URL
18
+ ).path,
19
+ _lastSync: 0,
20
+ _session: undefined,
21
+ _getSession: () => {},
22
+ };
23
+
24
+ export async function signOutAuth(options) {
25
+ const { callbackUrl = window.location.href } = options ?? {}
26
+ const baseUrl = apiBaseUrl(__NEXTAUTH)
27
+ const fetchOptions = {
28
+ method: "post",
29
+ headers: {
30
+ "Content-Type": "application/x-www-form-urlencoded",
31
+ },
32
+ // @ts-expect-error
33
+ body: new URLSearchParams({
34
+ csrfToken: await getCsrfToken(),
35
+ callbackUrl,
36
+ json: true,
37
+ }),
38
+ }
39
+ const res = await fetch(`${baseUrl}/signout`, fetchOptions)
40
+ const data = await res.json()
41
+
42
+ broadcast.post({ event: "session", data: { trigger: "signout" } })
43
+
44
+ if (options?.redirect ?? true) {
45
+ const url = data.url ?? callbackUrl
46
+ window.location.href = url
47
+ // If url contains a hash, the browser does not reload the page. We reload manually
48
+ if (url.includes("#")) window.location.reload()
49
+ // @ts-expect-error
50
+ return
51
+ }
52
+ await __NEXTAUTH._getSession({ event: "storage" })
53
+ return data
54
+ }
@@ -0,0 +1,72 @@
1
+ function formatError(o) {
2
+ if (hasErrorProperty(o)) {
3
+ o.error = formatError(o.error);
4
+ o.message = o.message ?? o.error.message;
5
+ }
6
+ return o;
7
+ }
8
+
9
+ function hasErrorProperty(x) {
10
+ return !!(x?.error);
11
+ }
12
+
13
+ const _logger = {
14
+ error(code, metadata) {
15
+ metadata = formatError(metadata);
16
+ console.error(
17
+ `[next-auth][error][${code}]`,
18
+ `\nhttps://next-auth.js.org/errors#${code.toLowerCase()}`,
19
+ metadata.message,
20
+ metadata
21
+ );
22
+ },
23
+ warn(code) {
24
+ console.warn(
25
+ `[next-auth][warn][${code}]`,
26
+ `\nhttps://next-auth.js.org/warnings#${code.toLowerCase()}`
27
+ );
28
+ },
29
+ debug(code, metadata) {
30
+ console.log(`[next-auth][debug][${code}]`, metadata);
31
+ },
32
+ };
33
+
34
+
35
+ export function setLogger(newLogger = {}, debug) {
36
+ if (!debug) _logger.debug = () => {};
37
+
38
+ if (newLogger.error) _logger.error = newLogger.error;
39
+ if (newLogger.warn) _logger.warn = newLogger.warn;
40
+ if (newLogger.debug) _logger.debug = newLogger.debug;
41
+ }
42
+
43
+ export function proxyLogger(logger = _logger, basePath) {
44
+ try {
45
+ if (typeof window === "undefined") {
46
+ return logger;
47
+ }
48
+
49
+ const clientLogger = {};
50
+ for (const level in logger) {
51
+ clientLogger[level] = (code, metadata) => {
52
+ _logger[level](code, metadata);
53
+
54
+ if (level === "error") {
55
+ metadata = formatError(metadata);
56
+ }
57
+ metadata.client = true;
58
+ const url = `${basePath}/_log`;
59
+ const body = new URLSearchParams({ level, code, ...metadata });
60
+ if (navigator.sendBeacon) {
61
+ return navigator.sendBeacon(url, body);
62
+ }
63
+ return fetch(url, { method: "POST", body, keepalive: true });
64
+ };
65
+ }
66
+ return clientLogger;
67
+ } catch {
68
+ return _logger;
69
+ }
70
+ }
71
+ export { _logger as default };
72
+
@@ -0,0 +1,36 @@
1
+ /** Interface for the internal URL structure */
2
+ const InternalUrl = {
3
+ origin: 'http://localhost:3000',
4
+ host: 'localhost:3000',
5
+ path: '/api/auth',
6
+ base: 'http://localhost:3000/api/auth',
7
+ toString: function() {
8
+ return this.base;
9
+ },
10
+ };
11
+
12
+ /** Function to parse a URL-like object for server-side requests/redirects */
13
+ function parseUrl(url) {
14
+ const defaultUrl = new URL('http://localhost:3000/api/auth');
15
+
16
+ if (url && !url.startsWith('http')) {
17
+ url = `https://${url}`;
18
+ }
19
+
20
+ const _url = new URL(url || defaultUrl);
21
+ const path = (_url.pathname === '/' ? defaultUrl.pathname : _url.pathname).replace(/\/$/, '');
22
+
23
+ const base = `${_url.origin}${path}`;
24
+
25
+ return {
26
+ origin: _url.origin,
27
+ host: _url.host,
28
+ path,
29
+ base,
30
+ toString: function() {
31
+ return base;
32
+ },
33
+ };
34
+ }
35
+
36
+ export { InternalUrl, parseUrl };
@@ -1,12 +1,12 @@
1
1
  import { useApolloClient } from '@apollo/client'
2
2
  import { useState } from 'react'
3
- import { useRouter } from 'next/router'
4
3
  import { Cookies } from '../../cookies'
4
+ import { signOutAuth } from './helpers'
5
+ export { signOutAuth } from './helpers'
5
6
 
6
7
  export const useLogout = ({ setAlertBox = () => { } } = {}) => {
7
8
  const [loading, setLoading] = useState(false)
8
9
  const [error, setError] = useState(false)
9
- const router = useRouter()
10
10
  const client = useApolloClient()
11
11
 
12
12
  const onClickLogout = async () => {
@@ -15,23 +15,18 @@ export const useLogout = ({ setAlertBox = () => { } } = {}) => {
15
15
  .fetch(`${process.env.URL_BASE}/api/auth/logout/`, {})
16
16
  .then(res => {
17
17
  if (res) {
18
- localStorage.removeItem('session')
19
- localStorage.removeItem('usuario')
20
- localStorage.removeItem('location')
21
- localStorage.removeItem('sessionGoogle')
22
- localStorage.removeItem('namefood')
23
- localStorage.removeItem('longitude')
24
- localStorage.removeItem('latitude')
25
- localStorage.removeItem('userlogin')
26
- localStorage.removeItem('restaurant')
27
18
  Cookies.remove(process.env.SESSION_NAME)
28
- Cookies.remove('app.cart.sales')
19
+ Cookies.remove(process.env.LOCAL_SALES_STORE)
29
20
  Cookies.remove('restaurant')
21
+ Cookies.remove('usuario')
22
+ Cookies.remove('session')
30
23
  client?.clearStore()
31
- router.replace('/entrar')
32
24
  setLoading(false)
25
+ console.log('Borrado todo')
26
+
33
27
  }
34
28
  })
29
+ signOutAuth({ redirect: true, callbackUrl: '/' })
35
30
  .catch(() => {
36
31
  setError(true)
37
32
  setAlertBox({ message: 'Ocurrió un error al cerrar session' })
@@ -82,9 +82,11 @@ export const useSales = ({
82
82
  const [_, setFilteredList] = useState([])
83
83
  const [delivery, setDelivery] = useState(false)
84
84
  const [print, setPrint] = useState(false)
85
+ const [errors, setErrors] = useState({})
85
86
  const [values, setValues] = useState({
86
87
  comment: '',
87
88
  change: '',
89
+ cliId: '',
88
90
  valueDelivery: ''
89
91
  })
90
92
  const [dataStore] = useStore()
@@ -185,8 +187,13 @@ export const useSales = ({
185
187
  const handleChangeFilter = (e) => {
186
188
  return setSearch(e.target.value)
187
189
  }
188
- const handleChange = (e) => {
189
- return setValues({ ...values, [e.target.name]: e.target.value })
190
+ const handleChange = (e, error) => {
191
+ const { name, value } = e.target;
192
+ setErrors({ ...errors, [e.target.name]: error })
193
+ setValues((prevValues) => ({
194
+ ...prevValues,
195
+ [name]: value,
196
+ }));
190
197
  }
191
198
  const onChangeInput = (e) => {
192
199
  return setValuesDates({ ...valuesDates, [e.target.name]: e.target.value })
@@ -816,29 +823,35 @@ export const useSales = ({
816
823
  const client = useApolloClient()
817
824
  const { getOnePedidoStore } = useGetSale()
818
825
  const handleSubmit = () => {
819
- if (!values?.cliId) {
826
+
827
+ if (errors?.change || errors?.valueDelivery) {
820
828
  return sendNotification({
821
- title: 'Error',
822
- backgroundColor: 'error',
823
- description: 'Elije primero un cliente'
829
+ title: 'error',
830
+ backgroundColor: 'warning',
831
+ description: 'Completa los campos requeridos'
824
832
  })
825
833
  }
826
834
  setLoadingSale(true)
827
835
  const code = RandomCode(10)
828
836
  setCode(code)
829
- const changeValue = values.change ? convertToIntegerOrFloat(values.change) : null;
830
-
837
+ function convertirAEntero(cadena) {
838
+ if (typeof cadena === 'string') {
839
+ const numeroEntero = parseInt(cadena?.replace('.', ''));
840
+ return numeroEntero
841
+ }
842
+ return cadena || 0
843
+ }
831
844
  return registerSalesStore({
832
845
  variables: {
833
846
  input: finalArrayProduct || [],
834
847
  id: values?.cliId,
835
848
  pCodeRef: code,
836
- change: changeValue,
837
- valueDelivery: convertToIntegerOrFloat(values.valueDelivery),
849
+ change: convertirAEntero(values.change),
850
+ valueDelivery: convertirAEntero(values.valueDelivery),
838
851
  payMethodPState: data.payMethodPState,
839
852
  pickUp: 1,
840
853
  discount: discount.discount || 0,
841
- totalProductsPrice: convertToIntegerOrFloat(totalProductsPrice) || 0
854
+ totalProductsPrice: convertirAEntero(totalProductsPrice) || 0
842
855
  }
843
856
  })
844
857
  .then((responseRegisterR) => {
@@ -1056,6 +1069,7 @@ export const useSales = ({
1056
1069
  disabledItems,
1057
1070
  setCheckedItems,
1058
1071
  handleChangeCheck,
1072
+ errors,
1059
1073
  handleUpdateAllExtra,
1060
1074
  dispatch,
1061
1075
  handleComment,
@@ -1064,6 +1078,7 @@ export const useSales = ({
1064
1078
  handleProduct,
1065
1079
  handleChange,
1066
1080
  setOpenCurrentSale,
1081
+ setErrors,
1067
1082
  onChangeInput,
1068
1083
  handleRemoveValue,
1069
1084
  applyDiscount,