asma-helpers 0.2.33 → 0.2.35

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.
Files changed (97) hide show
  1. package/.prettierrc +15 -15
  2. package/.vscode/settings.json +39 -39
  3. package/README.md +0 -0
  4. package/lib/clients/srvAuth.d.ts +1 -1
  5. package/lib/clients/srvAuth.js +6 -6
  6. package/lib/global.d.ts +40 -39
  7. package/lib/global.d.ts.map +1 -1
  8. package/lib/global.js +4 -4
  9. package/lib/global.js.map +1 -1
  10. package/lib/helpers/CapitalizeFistLetter.d.ts +2 -2
  11. package/lib/helpers/CapitalizeFistLetter.js +6 -6
  12. package/lib/helpers/Config.d.ts +5 -5
  13. package/lib/helpers/Config.js +44 -44
  14. package/lib/helpers/EnvironmentToOperateTypes.d.ts +7 -7
  15. package/lib/helpers/EnvironmentToOperateTypes.js +8 -8
  16. package/lib/helpers/EnvironmentsUrls.d.ts +93 -93
  17. package/lib/helpers/EnvironmentsUrls.js +89 -89
  18. package/lib/helpers/FormatNumberConstants.d.ts +24 -24
  19. package/lib/helpers/FormatNumberConstants.js +40 -40
  20. package/lib/helpers/InitializeIDBListenersOnMstSnapshots.d.ts +1 -1
  21. package/lib/helpers/InitializeIDBListenersOnMstSnapshots.js +49 -49
  22. package/lib/helpers/InitializeIDBListenersOnMstSnapshotsThenCatch.d.ts +8 -8
  23. package/lib/helpers/InitializeIDBListenersOnMstSnapshotsThenCatch.js +68 -68
  24. package/lib/helpers/IsAdcuris.d.ts +2 -2
  25. package/lib/helpers/IsAdcuris.js +4 -4
  26. package/lib/helpers/IsNotEmpty.d.ts +1 -1
  27. package/lib/helpers/IsNotEmpty.js +3 -3
  28. package/lib/helpers/NorwegianPostalCodes.d.ts +8 -8
  29. package/lib/helpers/NorwegianPostalCodes.js +3 -3
  30. package/lib/helpers/ProcessServerError.d.ts +2 -2
  31. package/lib/helpers/ProcessServerError.js +100 -100
  32. package/lib/helpers/attachUserJournalCredentials.d.ts +1 -1
  33. package/lib/helpers/attachUserJournalCredentials.js +16 -16
  34. package/lib/helpers/base64ToFile.d.ts +1 -1
  35. package/lib/helpers/base64ToFile.js +8 -8
  36. package/lib/helpers/clearCacheData.d.ts +1 -1
  37. package/lib/helpers/clearCacheData.js +12 -12
  38. package/lib/helpers/generateEnvConfigsBindings.d.ts +30 -30
  39. package/lib/helpers/generateEnvConfigsBindings.js +48 -48
  40. package/lib/helpers/generateGenqlClient.d.ts +16 -16
  41. package/lib/helpers/generateGenqlClient.d.ts.map +1 -1
  42. package/lib/helpers/generateGenqlClient.js +77 -75
  43. package/lib/helpers/generateGenqlClient.js.map +1 -1
  44. package/lib/helpers/generateSrvAuthBindings.d.ts +36 -36
  45. package/lib/helpers/generateSrvAuthBindings.d.ts.map +1 -1
  46. package/lib/helpers/generateSrvAuthBindings.js +163 -153
  47. package/lib/helpers/generateSrvAuthBindings.js.map +1 -1
  48. package/lib/helpers/getGqlOperationName.d.ts +1 -1
  49. package/lib/helpers/getGqlOperationName.js +15 -15
  50. package/lib/helpers/getSubdomain.d.ts +12 -12
  51. package/lib/helpers/getSubdomain.js +39 -39
  52. package/lib/helpers/isValidUrl.d.ts +1 -1
  53. package/lib/helpers/isValidUrl.js +9 -9
  54. package/lib/helpers/parseJwt.d.ts +1 -1
  55. package/lib/helpers/parseJwt.js +7 -7
  56. package/lib/helpers/userTypingSignal.d.ts +4 -4
  57. package/lib/helpers/userTypingSignal.js +32 -32
  58. package/lib/index.d.ts +28 -28
  59. package/lib/index.js +26 -26
  60. package/lib/interfaces/api/advoca/ISaveToDataBase.d.ts +16 -16
  61. package/lib/interfaces/api/advoca/ISaveToDataBase.js +1 -1
  62. package/lib/interfaces/api/advoca/IUploadedDocument.d.ts +26 -26
  63. package/lib/interfaces/api/advoca/IUploadedDocument.js +1 -1
  64. package/lib/interfaces/enums.d.ts +50 -50
  65. package/lib/interfaces/enums.js +59 -59
  66. package/lib/utility/fetch.d.ts +1 -1
  67. package/lib/utility/fetch.js +5 -5
  68. package/package.json +29 -29
  69. package/src/clients/srvAuth.ts +6 -6
  70. package/src/global.ts +46 -45
  71. package/src/helpers/CapitalizeFistLetter.ts +7 -7
  72. package/src/helpers/Config.ts +58 -58
  73. package/src/helpers/EnvironmentToOperateTypes.ts +6 -6
  74. package/src/helpers/EnvironmentsUrls.ts +102 -102
  75. package/src/helpers/FormatNumberConstants.ts +41 -41
  76. package/src/helpers/InitializeIDBListenersOnMstSnapshots.ts +62 -62
  77. package/src/helpers/InitializeIDBListenersOnMstSnapshotsThenCatch.ts +82 -82
  78. package/src/helpers/IsAdcuris.ts +4 -4
  79. package/src/helpers/IsNotEmpty.ts +2 -2
  80. package/src/helpers/NorwegianPostalCodes.ts +6 -6
  81. package/src/helpers/ProcessServerError.ts +92 -92
  82. package/src/helpers/attachUserJournalCredentials.ts +23 -23
  83. package/src/helpers/base64ToFile.ts +9 -9
  84. package/src/helpers/clearCacheData.ts +15 -15
  85. package/src/helpers/generateEnvConfigsBindings.ts +82 -82
  86. package/src/helpers/generateGenqlClient.ts +110 -108
  87. package/src/helpers/generateSrvAuthBindings.ts +217 -204
  88. package/src/helpers/getGqlOperationName.ts +20 -20
  89. package/src/helpers/getSubdomain.ts +50 -50
  90. package/src/helpers/isValidUrl.ts +12 -12
  91. package/src/helpers/parseJwt.ts +10 -10
  92. package/src/index.ts +34 -34
  93. package/src/interfaces/api/advoca/ISaveToDataBase.ts +17 -17
  94. package/src/interfaces/api/advoca/IUploadedDocument.ts +23 -23
  95. package/src/interfaces/enums.ts +56 -56
  96. package/src/utility/fetch.ts +9 -9
  97. package/tsconfig.json +84 -84
@@ -1,108 +1,110 @@
1
- import type { AxiosRequestConfig } from 'axios'
2
- import type { ClientOptions, createClient } from '@genql/runtime'
3
- import { httpToWs } from './Config'
4
- //import { parseJwt } from '../helpers/parseJwt'
5
-
6
- interface CliOptions extends Omit<ClientOptions, 'url'> {
7
- anonymous?: boolean
8
- }
9
-
10
- export function generateGenqlClient<T extends ReturnType<typeof createClient>>({
11
- setReqConfig,
12
- createClient,
13
- serviceUrl,
14
- path = '/v1/graphql',
15
- }: {
16
- // jwt_exp: number
17
- setReqConfig: () => Promise<AxiosRequestConfig<any>>
18
- createClient: (options?: ClientOptions | undefined) => T
19
- serviceUrl: () => string
20
- path?: string
21
- }) {
22
- // let jwt_exp = 0
23
-
24
- let client: T | null = null
25
-
26
- let wsClient: T | null = null
27
-
28
- //function accessTokenHasExpired() {
29
- // const nowTime = Math.floor(new Date().getTime() / 1000)
30
- //
31
- // //set exp time -20sec for token to be refreshed early
32
- // return jwt_exp - 10 <= nowTime
33
- //}
34
-
35
- async function getGenqlClient() {
36
- if (/* accessTokenHasExpired() || */ client === null) {
37
- client = await genqlClient()
38
-
39
- return client
40
- }
41
-
42
- return client
43
- }
44
-
45
- //function resetGenqlClient() {
46
- // client = null
47
- //}
48
-
49
- // function setJwtExp(token?: string) {
50
- // if (!token) return
51
- //
52
- // const parsed_jwt = parseJwt<{ exp: number }>(token)?.exp
53
- //
54
- // jwt_exp = parsed_jwt || 0
55
- // }
56
-
57
- /**
58
- *
59
- * This is used for anonymous requests as well as authenticated requests
60
- *
61
- */
62
- async function genqlClient(options: CliOptions = {}): Promise<T> {
63
- //let req_headers: Record<string, string> = {}
64
-
65
- const { anonymous, headers, ...rest } = options
66
-
67
- if (!serviceUrl()) {
68
- console.warn('requred param srv_url is undefined, please check EnvConfig object!')
69
- }
70
- //if (!anonymous) {
71
- //req_headers = ((await setReqConfig()).headers ?? {}) as Record<string, string>
72
- // setJwtExp(req_headers['Authorization'])
73
- // }
74
-
75
- return createClient({
76
- url: `${serviceUrl()}${path}`,
77
- headers: async () => ({
78
- ...(options.anonymous ? {} : (((await setReqConfig()).headers ?? {}) as Record<string, string>)),
79
- ...headers,
80
- }),
81
- batch: { batchInterval: 50, maxBatchSize: 100 },
82
- ...rest,
83
- })
84
- }
85
-
86
- async function genqlClientWs() {
87
- if (/* accessTokenHasExpired() || */ !wsClient) {
88
- //const req_headers = ((await setReqConfig()).headers ?? {}) as Record<string, string>
89
-
90
- //setJwtExp(req_headers['Authorization'])
91
-
92
- wsClient = createClient({
93
- url: `${httpToWs(serviceUrl())}${path}`,
94
- cache: 'reload',
95
- batch: { batchInterval: 50, maxBatchSize: 100 },
96
- subscription: {
97
- reconnect: true,
98
- reconnectionAttempts: 5,
99
- headers: async () => ((await setReqConfig()).headers ?? {}) as Record<string, string>,
100
- },
101
- })
102
- }
103
-
104
- return wsClient
105
- }
106
-
107
- return { getGenqlClient, /* resetGenqlClient, */ genqlClient, genqlClientWs }
108
- }
1
+ import type { AxiosRequestConfig } from 'axios'
2
+ import type { ClientOptions, createClient } from '@genql/runtime'
3
+ import { httpToWs } from './Config'
4
+ //import { parseJwt } from '../helpers/parseJwt'
5
+
6
+ interface CliOptions extends Omit<ClientOptions, 'url'> {
7
+ anonymous?: boolean
8
+ }
9
+
10
+ export function generateGenqlClient<T extends ReturnType<typeof createClient>>({
11
+ setReqConfig,
12
+ createClient,
13
+ serviceUrl,
14
+ path = '/v1/graphql',
15
+ }: {
16
+ // jwt_exp: number
17
+ setReqConfig: () => Promise<AxiosRequestConfig<any>>
18
+ createClient: (options?: ClientOptions | undefined) => T | null
19
+ serviceUrl: () => string
20
+ path?: string
21
+ }) {
22
+ // let jwt_exp = 0
23
+
24
+ let client: T | null = null
25
+
26
+ let wsClient: T | null = null
27
+
28
+ //function accessTokenHasExpired() {
29
+ // const nowTime = Math.floor(new Date().getTime() / 1000)
30
+ //
31
+ // //set exp time -20sec for token to be refreshed early
32
+ // return jwt_exp - 10 <= nowTime
33
+ //}
34
+
35
+ async function getGenqlClient() {
36
+ if (/* accessTokenHasExpired() || */ !client) {
37
+ client = await genqlClient()
38
+
39
+ return client
40
+ }
41
+
42
+ return client
43
+ }
44
+
45
+ //function resetGenqlClient() {
46
+ // client = null
47
+ //}
48
+
49
+ // function setJwtExp(token?: string) {
50
+ // if (!token) return
51
+ //
52
+ // const parsed_jwt = parseJwt<{ exp: number }>(token)?.exp
53
+ //
54
+ // jwt_exp = parsed_jwt || 0
55
+ // }
56
+
57
+ /**
58
+ *
59
+ * This is used for anonymous requests as well as authenticated requests
60
+ *
61
+ */
62
+ async function genqlClient(options: CliOptions = {}): Promise<T | null> {
63
+ let req_headers: Record<string, string> = {}
64
+
65
+ const { anonymous, headers, ...rest } = options
66
+
67
+ if (!serviceUrl()) {
68
+ console.warn('requred param srv_url is undefined, please check EnvConfig object!')
69
+ }
70
+ if (!anonymous) {
71
+ req_headers = ((await setReqConfig()).headers ?? {}) as Record<string, string>
72
+ if (!req_headers['Authorization']) return null
73
+ }
74
+
75
+ return createClient({
76
+ url: `${serviceUrl()}${path}`,
77
+ headers: async () => ({
78
+ ...req_headers,
79
+ ...headers,
80
+ }),
81
+ batch: { batchInterval: 50, maxBatchSize: 100 },
82
+ ...rest,
83
+ })
84
+ }
85
+
86
+ async function genqlClientWs() {
87
+ if (/* accessTokenHasExpired() || */ !wsClient) {
88
+ const req_headers = ((await setReqConfig()).headers ?? {}) as Record<string, string>
89
+
90
+ if (!req_headers['Authorization']) return null
91
+
92
+ //setJwtExp(req_headers['Authorization'])
93
+
94
+ wsClient = createClient({
95
+ url: `${httpToWs(serviceUrl())}${path}`,
96
+ cache: 'reload',
97
+ batch: { batchInterval: 50, maxBatchSize: 100 },
98
+ subscription: {
99
+ reconnect: true,
100
+ reconnectionAttempts: 5,
101
+ headers: async () => req_headers,
102
+ },
103
+ })
104
+ }
105
+
106
+ return wsClient
107
+ }
108
+
109
+ return { getGenqlClient, /* resetGenqlClient, */ genqlClient, genqlClientWs }
110
+ }
@@ -1,204 +1,217 @@
1
- import axios, { AxiosResponse, ResponseType } from 'axios'
2
- import { EnvironmentEnums, parseJwt } from '..'
3
-
4
- export function generateSrvAuthBindings<FeatureEnums = never>(
5
- SRV_AUTH: () => string,
6
- DEVELOPMENT: () => boolean,
7
- EnvironmentToOperateFn: () => string,
8
- logout?: () => void,
9
- ) {
10
- if (window.__ASMA__SHELL__?.auth_bindings) {
11
- return window.__ASMA__SHELL__.auth_bindings as typeof auth_bindings
12
- }
13
- let jwtToken = ''
14
-
15
- let features: Set<FeatureEnums> | undefined
16
-
17
- let parsed_jwt: any | undefined
18
-
19
- let fetchJwtPromise: Promise<{
20
- data: { message: string; token?: string; features?: FeatureEnums[]; errors: { message: string }[] }
21
- }> | null = null
22
-
23
- const isJwtInvalid = () => (jwtToken && accessTokenHasExpired()) || !jwtToken
24
-
25
- const isJwtValid = () => !isJwtInvalid()
26
-
27
- async function srvAuthGet<R>(url: string, headers?: Record<string, string>) {
28
- if (DEVELOPMENT() && EnvironmentToOperateFn()) {
29
- if (EnvironmentToOperateFn() in EnvironmentEnums) {
30
- url = `${url}&env=${EnvironmentToOperateFn()}`
31
-
32
- url = url.includes('&') && !url.includes('?') ? url.replace('&', '?') : url
33
- } else {
34
- console.warn(
35
- 'EnvironmentToOperateFn() is not a valid EnvironmentEnums',
36
- 'shall be one of:',
37
- EnvironmentEnums,
38
- 'actual value:',
39
- EnvironmentToOperateFn(),
40
- )
41
- }
42
- }
43
-
44
- return axios.get<unknown, AxiosResponse<R>>(`${SRV_AUTH()}${url}`, {
45
- headers: {
46
- ...headers,
47
- 'asma-origin': window.location.origin,
48
- },
49
- withCredentials: true,
50
- })
51
- }
52
-
53
- function accessTokenHasExpired(): boolean {
54
- const tokenObj = getParsedJwt()
55
-
56
- const accessTokenExpDate = tokenObj?.exp || 0
57
-
58
- const nowTime = Math.floor(new Date().getTime() / 1000)
59
-
60
- //set exp time -20sec for token to be refreshed early
61
- return accessTokenExpDate - 10 <= nowTime
62
- }
63
-
64
- async function signin(url: string, headers?: Record<string, string>) {
65
- const { data } = await srvAuthGet<{ token: string; features: FeatureEnums[] }>(url, headers)
66
-
67
- setAuthData(data)
68
-
69
- return data
70
- }
71
-
72
- async function signoutAuth() {
73
- setAuthData({ token: '' })
74
- await srvAuthGet('/signout')
75
- }
76
- function getUserId(): string {
77
- return getParsedJwt()?.['user_id'] || '-1'
78
- }
79
-
80
- function setAuthData(data: { token: string; features?: FeatureEnums[] }) {
81
- jwtToken = data.token
82
- features = new Set(data.features)
83
- parsed_jwt = undefined
84
- }
85
-
86
- function getJwtToken() {
87
- return jwtToken
88
- }
89
-
90
- async function getJwtTokenAsync() {
91
- if (isJwtInvalid()) {
92
- const new_jwt = await getNewJwtToken()
93
-
94
- return new_jwt
95
- } else {
96
- return jwtToken
97
- }
98
- }
99
-
100
- async function setReqConfig<T = unknown>(data?: T, responseType?: ResponseType) {
101
- const token = await getJwtTokenAsync()
102
-
103
- const res = {
104
- data: data,
105
- responseType: responseType,
106
- headers: {} as Record<string, string>,
107
- }
108
-
109
- if (token) {
110
- res.headers['Authorization'] = `Bearer ${token}`
111
- }
112
-
113
- return res
114
- }
115
-
116
- async function getNewJwtToken() {
117
- try {
118
- if (!fetchJwtPromise) {
119
- fetchJwtPromise = srvAuthGet('/token')
120
- }
121
-
122
- const { data } = await fetchJwtPromise
123
-
124
- if (!data || data.errors || data.message != 'Success') {
125
- logout?.() || signoutAuth()
126
- }
127
- if (!data.token) {
128
- throw new Error('Token is not present in the result')
129
- }
130
- setAuthData({ token: data.token || '', features: data.features || [] })
131
-
132
- fetchJwtPromise = null
133
-
134
- return jwtToken
135
- } catch (error) {
136
- logout?.() || signoutAuth()
137
- //signoutAuth()
138
-
139
- fetchJwtPromise = null
140
-
141
- console.error(error)
142
-
143
- return jwtToken
144
- }
145
- }
146
-
147
- function getParsedJwt<R = { user_id: string; exp: number }>(): R | undefined {
148
- if (!parsed_jwt) {
149
- parsed_jwt = parseJwt<R>(jwtToken)
150
- }
151
- return parsed_jwt
152
- }
153
- function getFeatures() {
154
- return features
155
- }
156
- /**
157
- *
158
- * @param featureName feature_name_enums add this: generateSrvAuthBindings<feature_name_enums.>(...)
159
- * @returns boolean
160
- */
161
- function hasFeature(featureName: FeatureEnums) {
162
- return !!features?.has(featureName)
163
- }
164
-
165
- const auth_bindings = {
166
- hasFeature,
167
- getFeatures,
168
- isJwtValid,
169
- signin,
170
- srvAuthGet,
171
- signoutAuth,
172
- setReqConfig,
173
- getJwtTokenAsync,
174
- getNewJwtToken,
175
- getUserId,
176
- getParsedJwt,
177
- getJwtToken,
178
- accessTokenHasExpired,
179
- }
180
- window.__ASMA__SHELL__ = window.__ASMA__SHELL__ || {}
181
-
182
- window.__ASMA__SHELL__.auth_bindings = auth_bindings
183
-
184
- return auth_bindings
185
- }
186
- /**
187
- * @deprecated use generateSrvAuthBindings
188
- * @param SRV_AUTH
189
- * @param DEVELOPMENT
190
- * @param ENVIRONMENT_TO_OPERATE
191
- * @param logout
192
- * @returns
193
- */
194
- export function generateSrvAuthBindingsMicroApp(
195
- SRV_AUTH: () => string,
196
- DEVELOPMENT: () => boolean,
197
- ENVIRONMENT_TO_OPERATE: () => EnvironmentEnums,
198
- logout?: () => void,
199
- ) {
200
- return (
201
- window.__ASMA__SHELL__?.auth_bindings ||
202
- generateSrvAuthBindings(SRV_AUTH, DEVELOPMENT, ENVIRONMENT_TO_OPERATE, logout)
203
- )
204
- }
1
+ import axios, {type AxiosResponse, type ResponseType } from 'axios'
2
+ import { EnvironmentEnums, parseJwt } from '..'
3
+
4
+ let logoutsuccesfull = false
5
+
6
+ export function generateSrvAuthBindings<FeatureEnums = never>(
7
+ SRV_AUTH: () => string,
8
+ DEVELOPMENT: () => boolean,
9
+ EnvironmentToOperateFn: () => string,
10
+ logout?: () => void,
11
+ ) {
12
+ let logoutMfes: (() => void)[] = []
13
+
14
+ if (logout && window.__ASMA__SHELL__?.auth_bindings) {
15
+ logoutMfes.push(logout)
16
+ }
17
+
18
+ if (window.__ASMA__SHELL__?.auth_bindings) {
19
+ window.__ASMA__SHELL__.logoutMfes = logoutMfes
20
+ return window.__ASMA__SHELL__.auth_bindings as typeof auth_bindings
21
+ }
22
+
23
+ let jwtToken = ''
24
+
25
+ let features: Set<FeatureEnums> | undefined
26
+
27
+ let parsed_jwt: any | undefined
28
+
29
+ let fetchJwtPromise: Promise<{
30
+ data: { message: string; token?: string; features?: FeatureEnums[]; errors: { message: string }[] }
31
+ }> | null = null
32
+
33
+ const isJwtInvalid = () => (jwtToken && accessTokenHasExpired()) || !jwtToken
34
+
35
+ const isJwtValid = () => !isJwtInvalid()
36
+
37
+ async function srvAuthGet<R>(url: string, headers?: Record<string, string>) {
38
+ if (DEVELOPMENT() && EnvironmentToOperateFn()) {
39
+ if (EnvironmentToOperateFn() in EnvironmentEnums) {
40
+ url = `${url}&env=${EnvironmentToOperateFn()}`
41
+
42
+ url = url.includes('&') && !url.includes('?') ? url.replace('&', '?') : url
43
+ } else {
44
+ console.warn(
45
+ 'EnvironmentToOperateFn() is not a valid EnvironmentEnums',
46
+ 'shall be one of:',
47
+ EnvironmentEnums,
48
+ 'actual value:',
49
+ EnvironmentToOperateFn(),
50
+ )
51
+ }
52
+ }
53
+
54
+ return axios.get<unknown, AxiosResponse<R>>(`${SRV_AUTH()}${url}`, {
55
+ headers: {
56
+ ...headers,
57
+ 'asma-origin': window.location.origin,
58
+ },
59
+ withCredentials: true,
60
+ })
61
+ }
62
+
63
+ function accessTokenHasExpired(): boolean {
64
+ const tokenObj = getParsedJwt()
65
+
66
+ const accessTokenExpDate = tokenObj?.exp || 0
67
+
68
+ const nowTime = Math.floor(new Date().getTime() / 1000)
69
+
70
+ //set exp time -20sec for token to be refreshed early
71
+ return accessTokenExpDate - 10 <= nowTime
72
+ }
73
+
74
+ async function signin(url: string, headers?: Record<string, string>) {
75
+ const { data } = await srvAuthGet<{ token: string; features: FeatureEnums[] }>(url, headers)
76
+
77
+ setAuthData(data)
78
+
79
+ logoutsuccesfull = false
80
+
81
+ return data
82
+ }
83
+
84
+ async function signoutAuth() {
85
+ setAuthData({ token: '' })
86
+ await srvAuthGet('/signout')
87
+ }
88
+ function getUserId(): string {
89
+ return getParsedJwt()?.['user_id'] || '-1'
90
+ }
91
+
92
+ function setAuthData(data: { token: string; features?: FeatureEnums[] }) {
93
+ jwtToken = data.token
94
+ features = new Set(data.features)
95
+ parsed_jwt = undefined
96
+ }
97
+
98
+ function getJwtToken() {
99
+ return jwtToken
100
+ }
101
+
102
+ async function getJwtTokenAsync() {
103
+ if (isJwtInvalid()) {
104
+ const new_jwt = await getNewJwtToken()
105
+
106
+ return new_jwt
107
+ } else {
108
+ return jwtToken
109
+ }
110
+ }
111
+
112
+ async function setReqConfig<T = unknown>(data?: T, responseType?: ResponseType) {
113
+ const token = await getJwtTokenAsync()
114
+
115
+ const res = {
116
+ data: data,
117
+ responseType: responseType,
118
+ headers: {} as Record<string, string>,
119
+ }
120
+
121
+ if (token) {
122
+ res.headers['Authorization'] = `Bearer ${token}`
123
+ }
124
+
125
+ return res
126
+ }
127
+
128
+ async function getNewJwtToken() {
129
+ if(logoutsuccesfull) return
130
+ try {
131
+ if (!fetchJwtPromise) {
132
+ fetchJwtPromise = srvAuthGet('/token')
133
+ }
134
+
135
+ const { data } = await fetchJwtPromise
136
+
137
+ if (!data || data.errors || data.message != 'Success' || !data.token) {
138
+ logout?.()
139
+ logoutsuccesfull = true
140
+
141
+ //signoutAuth()
142
+ }
143
+
144
+ setAuthData({ token: data.token || '', features: data.features || [] })
145
+ } catch (error) {
146
+ logout?.()
147
+ logoutsuccesfull = true
148
+ //signoutAuth()
149
+
150
+ setAuthData({ token: '', features: [] })
151
+
152
+ console.error(error)
153
+ } finally {
154
+ fetchJwtPromise = null
155
+
156
+ return jwtToken
157
+ }
158
+ }
159
+
160
+ function getParsedJwt<R = { user_id: string; exp: number }>(): R | undefined {
161
+ if (!parsed_jwt) {
162
+ parsed_jwt = parseJwt<R>(jwtToken)
163
+ }
164
+ return parsed_jwt
165
+ }
166
+ function getFeatures() {
167
+ return features
168
+ }
169
+ /**
170
+ *
171
+ * @param featureName feature_name_enums add this: generateSrvAuthBindings<feature_name_enums.>(...)
172
+ * @returns boolean
173
+ */
174
+ function hasFeature(featureName: FeatureEnums) {
175
+ return !!features?.has(featureName)
176
+ }
177
+
178
+ const auth_bindings = {
179
+ hasFeature,
180
+ getFeatures,
181
+ isJwtValid,
182
+ signin,
183
+ srvAuthGet,
184
+ signoutAuth,
185
+ setReqConfig,
186
+ getJwtTokenAsync,
187
+ getNewJwtToken,
188
+ getUserId,
189
+ getParsedJwt,
190
+ getJwtToken,
191
+ accessTokenHasExpired,
192
+ }
193
+ window.__ASMA__SHELL__ = window.__ASMA__SHELL__ || {}
194
+
195
+ window.__ASMA__SHELL__.auth_bindings = auth_bindings
196
+
197
+ return auth_bindings
198
+ }
199
+ /**
200
+ * @deprecated use generateSrvAuthBindings
201
+ * @param SRV_AUTH
202
+ * @param DEVELOPMENT
203
+ * @param ENVIRONMENT_TO_OPERATE
204
+ * @param logout
205
+ * @returns
206
+ */
207
+ export function generateSrvAuthBindingsMicroApp(
208
+ SRV_AUTH: () => string,
209
+ DEVELOPMENT: () => boolean,
210
+ ENVIRONMENT_TO_OPERATE: () => EnvironmentEnums,
211
+ logout?: () => void,
212
+ ) {
213
+ return (
214
+ window.__ASMA__SHELL__?.auth_bindings ||
215
+ generateSrvAuthBindings(SRV_AUTH, DEVELOPMENT, ENVIRONMENT_TO_OPERATE, logout)
216
+ )
217
+ }