@intlayer/design-system 4.0.2 → 4.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.
Files changed (240) hide show
  1. package/README.md +1 -1
  2. package/dist/.vite/manifest.json +58 -197
  3. package/dist/components/Accordion/Accordion.cjs +1 -1
  4. package/dist/components/Accordion/Accordion.cjs.map +1 -1
  5. package/dist/components/Accordion/Accordion.mjs +1 -1
  6. package/dist/components/Accordion/Accordion.mjs.map +1 -1
  7. package/dist/components/Auth/AuthModal/index.cjs +1 -1
  8. package/dist/components/Auth/AuthModal/index.mjs +1 -1
  9. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.cjs +2 -1
  10. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.cjs.map +1 -1
  11. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.mjs +2 -1
  12. package/dist/components/Auth/ExternalsLoginButtons/ExternalsLoginButtons.mjs.map +1 -1
  13. package/dist/components/Auth/useAuth/index.cjs +8 -4
  14. package/dist/components/Auth/useAuth/index.cjs.map +1 -1
  15. package/dist/components/Auth/useAuth/index.d.ts +3 -1
  16. package/dist/components/Auth/useAuth/index.d.ts.map +1 -1
  17. package/dist/components/Auth/useAuth/index.mjs +8 -4
  18. package/dist/components/Auth/useAuth/index.mjs.map +1 -1
  19. package/dist/components/Auth/useAuth/useCSRF.cjs +6 -3
  20. package/dist/components/Auth/useAuth/useCSRF.cjs.map +1 -1
  21. package/dist/components/Auth/useAuth/useCSRF.d.ts +2 -1
  22. package/dist/components/Auth/useAuth/useCSRF.d.ts.map +1 -1
  23. package/dist/components/Auth/useAuth/useCSRF.mjs +5 -2
  24. package/dist/components/Auth/useAuth/useCSRF.mjs.map +1 -1
  25. package/dist/components/Auth/useAuth/useOAuth2.cjs +6 -5
  26. package/dist/components/Auth/useAuth/useOAuth2.cjs.map +1 -1
  27. package/dist/components/Auth/useAuth/useOAuth2.d.ts +2 -1
  28. package/dist/components/Auth/useAuth/useOAuth2.d.ts.map +1 -1
  29. package/dist/components/Auth/useAuth/useOAuth2.mjs +5 -4
  30. package/dist/components/Auth/useAuth/useOAuth2.mjs.map +1 -1
  31. package/dist/components/Auth/useAuth/useSession.cjs +6 -3
  32. package/dist/components/Auth/useAuth/useSession.cjs.map +1 -1
  33. package/dist/components/Auth/useAuth/useSession.d.ts +2 -1
  34. package/dist/components/Auth/useAuth/useSession.d.ts.map +1 -1
  35. package/dist/components/Auth/useAuth/useSession.mjs +6 -3
  36. package/dist/components/Auth/useAuth/useSession.mjs.map +1 -1
  37. package/dist/components/Auth/useUser/index.cjs +1 -1
  38. package/dist/components/Auth/useUser/index.mjs +1 -1
  39. package/dist/components/Container/index.d.ts +2 -2
  40. package/dist/components/DictionaryEditor/DictionaryEditor.cjs +4 -16
  41. package/dist/components/DictionaryEditor/DictionaryEditor.cjs.map +1 -1
  42. package/dist/components/DictionaryEditor/DictionaryEditor.d.ts.map +1 -1
  43. package/dist/components/DictionaryEditor/DictionaryEditor.mjs +4 -16
  44. package/dist/components/DictionaryEditor/DictionaryEditor.mjs.map +1 -1
  45. package/dist/components/DictionaryEditor/NodeWrapper/ArrayWrapper.cjs +2 -1
  46. package/dist/components/DictionaryEditor/NodeWrapper/ArrayWrapper.cjs.map +1 -1
  47. package/dist/components/DictionaryEditor/NodeWrapper/ArrayWrapper.d.ts.map +1 -1
  48. package/dist/components/DictionaryEditor/NodeWrapper/ArrayWrapper.mjs +2 -1
  49. package/dist/components/DictionaryEditor/NodeWrapper/ArrayWrapper.mjs.map +1 -1
  50. package/dist/components/DictionaryEditor/NodeWrapper/EnumerationWrapper.cjs +1 -1
  51. package/dist/components/DictionaryEditor/NodeWrapper/EnumerationWrapper.mjs +1 -1
  52. package/dist/components/DictionaryEditor/NodeWrapper/NestedObjectWrapper.cjs +2 -1
  53. package/dist/components/DictionaryEditor/NodeWrapper/NestedObjectWrapper.cjs.map +1 -1
  54. package/dist/components/DictionaryEditor/NodeWrapper/NestedObjectWrapper.d.ts.map +1 -1
  55. package/dist/components/DictionaryEditor/NodeWrapper/NestedObjectWrapper.mjs +2 -1
  56. package/dist/components/DictionaryEditor/NodeWrapper/NestedObjectWrapper.mjs.map +1 -1
  57. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.cjs +3 -3
  58. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.cjs.map +1 -1
  59. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.d.ts.map +1 -1
  60. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.mjs +2 -2
  61. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.mjs.map +1 -1
  62. package/dist/components/DictionaryEditor/NodeWrapper/TranslationWrapper.cjs +1 -1
  63. package/dist/components/DictionaryEditor/NodeWrapper/TranslationWrapper.mjs +1 -1
  64. package/dist/components/DictionaryEditor/NodeWrapper/index.cjs +1 -1
  65. package/dist/components/DictionaryEditor/NodeWrapper/index.mjs +1 -1
  66. package/dist/components/DictionaryEditor/ValidDictionaryChangeButtons.cjs +2 -9
  67. package/dist/components/DictionaryEditor/ValidDictionaryChangeButtons.cjs.map +1 -1
  68. package/dist/components/DictionaryEditor/ValidDictionaryChangeButtons.d.ts.map +1 -1
  69. package/dist/components/DictionaryEditor/ValidDictionaryChangeButtons.mjs +2 -9
  70. package/dist/components/DictionaryEditor/ValidDictionaryChangeButtons.mjs.map +1 -1
  71. package/dist/components/DictionaryEditor/index.cjs +0 -8
  72. package/dist/components/DictionaryEditor/index.cjs.map +1 -1
  73. package/dist/components/DictionaryEditor/index.d.ts +0 -2
  74. package/dist/components/DictionaryEditor/index.d.ts.map +1 -1
  75. package/dist/components/DictionaryEditor/index.mjs +1 -9
  76. package/dist/components/DictionaryEditor/index.mjs.map +1 -1
  77. package/dist/components/DictionaryEditor/useEditedContentStore.d.ts +1 -1
  78. package/dist/components/DictionaryFieldEditor/DictionariesSelector/DictionariesSelector.cjs +3 -21
  79. package/dist/components/DictionaryFieldEditor/DictionariesSelector/DictionariesSelector.cjs.map +1 -1
  80. package/dist/components/DictionaryFieldEditor/DictionariesSelector/DictionariesSelector.d.ts.map +1 -1
  81. package/dist/components/DictionaryFieldEditor/DictionariesSelector/DictionariesSelector.mjs +3 -21
  82. package/dist/components/DictionaryFieldEditor/DictionariesSelector/DictionariesSelector.mjs.map +1 -1
  83. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.cjs +4 -2
  84. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.cjs.map +1 -1
  85. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.mjs +4 -2
  86. package/dist/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.mjs.map +1 -1
  87. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.cjs +4 -2
  88. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.cjs.map +1 -1
  89. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs +4 -2
  90. package/dist/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs.map +1 -1
  91. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.cjs +5 -31
  92. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.cjs.map +1 -1
  93. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.d.ts.map +1 -1
  94. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs +6 -32
  95. package/dist/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs.map +1 -1
  96. package/dist/components/DictionaryFieldEditor/EditorView/EditorView.cjs +8 -37
  97. package/dist/components/DictionaryFieldEditor/EditorView/EditorView.cjs.map +1 -1
  98. package/dist/components/DictionaryFieldEditor/EditorView/EditorView.d.ts.map +1 -1
  99. package/dist/components/DictionaryFieldEditor/EditorView/EditorView.mjs +6 -35
  100. package/dist/components/DictionaryFieldEditor/EditorView/EditorView.mjs.map +1 -1
  101. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.cjs +6 -24
  102. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.cjs.map +1 -1
  103. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.d.ts.map +1 -1
  104. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.mjs +5 -23
  105. package/dist/components/DictionaryFieldEditor/EditorView/TextEditor.mjs.map +1 -1
  106. package/dist/components/DictionaryFieldEditor/JSONEditor.cjs +2 -29
  107. package/dist/components/DictionaryFieldEditor/JSONEditor.cjs.map +1 -1
  108. package/dist/components/DictionaryFieldEditor/JSONEditor.d.ts.map +1 -1
  109. package/dist/components/DictionaryFieldEditor/JSONEditor.mjs +2 -29
  110. package/dist/components/DictionaryFieldEditor/JSONEditor.mjs.map +1 -1
  111. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.cjs +9 -33
  112. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.cjs.map +1 -1
  113. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.d.ts.map +1 -1
  114. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs +4 -28
  115. package/dist/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs.map +1 -1
  116. package/dist/components/DictionaryFieldEditor/NodeEditor.cjs +3 -43
  117. package/dist/components/DictionaryFieldEditor/NodeEditor.cjs.map +1 -1
  118. package/dist/components/DictionaryFieldEditor/NodeEditor.d.ts.map +1 -1
  119. package/dist/components/DictionaryFieldEditor/NodeEditor.mjs +3 -43
  120. package/dist/components/DictionaryFieldEditor/NodeEditor.mjs.map +1 -1
  121. package/dist/components/DictionaryFieldEditor/NodeTypeSelector.cjs +4 -27
  122. package/dist/components/DictionaryFieldEditor/NodeTypeSelector.cjs.map +1 -1
  123. package/dist/components/DictionaryFieldEditor/NodeTypeSelector.d.ts.map +1 -1
  124. package/dist/components/DictionaryFieldEditor/NodeTypeSelector.mjs +3 -26
  125. package/dist/components/DictionaryFieldEditor/NodeTypeSelector.mjs.map +1 -1
  126. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.cjs +9 -19
  127. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.cjs.map +1 -1
  128. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.d.ts.map +1 -1
  129. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs +9 -19
  130. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs.map +1 -1
  131. package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.cjs +2 -2
  132. package/dist/components/DictionaryFieldEditor/VersionSwitcherDropDown/VersionSwitcherContext.mjs +2 -2
  133. package/dist/components/EditableField/EditableFieldLayout.cjs +7 -3
  134. package/dist/components/EditableField/EditableFieldLayout.cjs.map +1 -1
  135. package/dist/components/EditableField/EditableFieldLayout.d.ts.map +1 -1
  136. package/dist/components/EditableField/EditableFieldLayout.mjs +7 -3
  137. package/dist/components/EditableField/EditableFieldLayout.mjs.map +1 -1
  138. package/dist/components/IDE/CodeContext.cjs +2 -2
  139. package/dist/components/IDE/CodeContext.mjs +2 -2
  140. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.cjs +2 -2
  141. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.mjs +2 -2
  142. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.cjs +2 -2
  143. package/dist/components/LocaleSwitcherContentDropDown/LocaleSwitcherContentContext.mjs +2 -2
  144. package/dist/components/Modal/Modal.cjs +12 -8
  145. package/dist/components/Modal/Modal.cjs.map +1 -1
  146. package/dist/components/Modal/Modal.d.ts.map +1 -1
  147. package/dist/components/Modal/Modal.mjs +12 -8
  148. package/dist/components/Modal/Modal.mjs.map +1 -1
  149. package/dist/components/Navbar/MobileNavbar.cjs +3 -3
  150. package/dist/components/Navbar/MobileNavbar.mjs +3 -3
  151. package/dist/components/Navbar/index.cjs +2 -2
  152. package/dist/components/Navbar/index.mjs +2 -2
  153. package/dist/components/RightDrawer/RightDrawer.cjs +34 -18
  154. package/dist/components/RightDrawer/RightDrawer.cjs.map +1 -1
  155. package/dist/components/RightDrawer/RightDrawer.d.ts.map +1 -1
  156. package/dist/components/RightDrawer/RightDrawer.mjs +33 -17
  157. package/dist/components/RightDrawer/RightDrawer.mjs.map +1 -1
  158. package/dist/components/SwitchSelector/index.cjs +2 -2
  159. package/dist/components/SwitchSelector/index.mjs +2 -2
  160. package/dist/components/TabSelector/TabSelector.cjs +2 -2
  161. package/dist/components/TabSelector/TabSelector.mjs +2 -2
  162. package/dist/components/index.cjs +0 -8
  163. package/dist/components/index.cjs.map +1 -1
  164. package/dist/components/index.mjs +0 -8
  165. package/dist/components/index.mjs.map +1 -1
  166. package/dist/hooks/index.cjs +1 -1
  167. package/dist/hooks/index.mjs +2 -2
  168. package/dist/hooks/intlayerAPIHooks.cjs +5 -1
  169. package/dist/hooks/intlayerAPIHooks.cjs.map +1 -1
  170. package/dist/hooks/intlayerAPIHooks.d.ts +49 -49
  171. package/dist/hooks/intlayerAPIHooks.d.ts.map +1 -1
  172. package/dist/hooks/intlayerAPIHooks.mjs +5 -1
  173. package/dist/hooks/intlayerAPIHooks.mjs.map +1 -1
  174. package/dist/hooks/useAsync/useAsync.cjs +14 -0
  175. package/dist/hooks/useAsync/useAsync.cjs.map +1 -1
  176. package/dist/hooks/useAsync/useAsync.d.ts.map +1 -1
  177. package/dist/hooks/useAsync/useAsync.mjs +14 -0
  178. package/dist/hooks/useAsync/useAsync.mjs.map +1 -1
  179. package/dist/hooks/useGetAllDictionaries.cjs +3 -2
  180. package/dist/hooks/useGetAllDictionaries.cjs.map +1 -1
  181. package/dist/hooks/useGetAllDictionaries.d.ts +2 -2
  182. package/dist/hooks/useGetAllDictionaries.d.ts.map +1 -1
  183. package/dist/hooks/useGetAllDictionaries.mjs +3 -2
  184. package/dist/hooks/useGetAllDictionaries.mjs.map +1 -1
  185. package/dist/hooks/useIntlayerAPI.cjs +10 -7
  186. package/dist/hooks/useIntlayerAPI.cjs.map +1 -1
  187. package/dist/hooks/useIntlayerAPI.d.ts +8 -2
  188. package/dist/hooks/useIntlayerAPI.d.ts.map +1 -1
  189. package/dist/hooks/useIntlayerAPI.mjs +10 -7
  190. package/dist/hooks/useIntlayerAPI.mjs.map +1 -1
  191. package/dist/hooks/usePersistedStore.cjs +25 -15
  192. package/dist/hooks/usePersistedStore.cjs.map +1 -1
  193. package/dist/hooks/usePersistedStore.d.ts +2 -1
  194. package/dist/hooks/usePersistedStore.d.ts.map +1 -1
  195. package/dist/hooks/usePersistedStore.mjs +26 -16
  196. package/dist/hooks/usePersistedStore.mjs.map +1 -1
  197. package/dist/hooks/useScrollBlockage/index.cjs +5 -31
  198. package/dist/hooks/useScrollBlockage/index.cjs.map +1 -1
  199. package/dist/hooks/useScrollBlockage/index.mjs +5 -31
  200. package/dist/hooks/useScrollBlockage/index.mjs.map +1 -1
  201. package/dist/hooks/useScrollDetection.cjs +1 -1
  202. package/dist/hooks/useScrollDetection.mjs +1 -1
  203. package/dist/index-B-VAyQ9R.js +673 -0
  204. package/dist/index-B-VAyQ9R.js.map +1 -0
  205. package/dist/index-B-adg6xa.js +206 -0
  206. package/dist/index-B-adg6xa.js.map +1 -0
  207. package/dist/index-BIV0x_z2.js +206 -0
  208. package/dist/index-BIV0x_z2.js.map +1 -0
  209. package/dist/index-BNH9wXVj.cjs +205 -0
  210. package/dist/index-BNH9wXVj.cjs.map +1 -0
  211. package/dist/index-Cg-S9ry9.cjs +77 -0
  212. package/dist/index-Cg-S9ry9.cjs.map +1 -0
  213. package/dist/index-D69JRZcQ.js +206 -0
  214. package/dist/index-D69JRZcQ.js.map +1 -0
  215. package/dist/index-DAsui9u9.cjs +205 -0
  216. package/dist/index-DAsui9u9.cjs.map +1 -0
  217. package/dist/index-O_7rYrbW.js +78 -0
  218. package/dist/index-O_7rYrbW.js.map +1 -0
  219. package/dist/index-SOIahRpS.cjs +205 -0
  220. package/dist/index-SOIahRpS.cjs.map +1 -0
  221. package/dist/index-T-TjVQoD.js +671 -0
  222. package/dist/index-T-TjVQoD.js.map +1 -0
  223. package/dist/index-f8_VC6c8.cjs +672 -0
  224. package/dist/index-f8_VC6c8.cjs.map +1 -0
  225. package/dist/index-llGIfxqV.cjs +670 -0
  226. package/dist/index-llGIfxqV.cjs.map +1 -0
  227. package/dist/tailwind.css +1 -1
  228. package/dist/useGetAllDictionaries-B1sqs2IB.cjs +34 -0
  229. package/dist/useGetAllDictionaries-B1sqs2IB.cjs.map +1 -0
  230. package/dist/useGetAllDictionaries-BbH8vTkY.js +35 -0
  231. package/dist/useGetAllDictionaries-BbH8vTkY.js.map +1 -0
  232. package/dist/useGetAllDictionaries-Bgkytpa2.cjs +34 -0
  233. package/dist/useGetAllDictionaries-Bgkytpa2.cjs.map +1 -0
  234. package/dist/useGetAllDictionaries-D8ma3h41.cjs +33 -0
  235. package/dist/useGetAllDictionaries-D8ma3h41.cjs.map +1 -0
  236. package/dist/useGetAllDictionaries-DHgHEbD5.js +34 -0
  237. package/dist/useGetAllDictionaries-DHgHEbD5.js.map +1 -0
  238. package/dist/useGetAllDictionaries-DUzm0rIa.js +35 -0
  239. package/dist/useGetAllDictionaries-DUzm0rIa.js.map +1 -0
  240. package/package.json +24 -16
@@ -1 +1 @@
1
- {"version":3,"file":"intlayerAPIHooks.mjs","sources":["../../__vite-browser-external","../../src/hooks/intlayerAPIHooks.ts"],"sourcesContent":["export default {}","/* eslint-disable @typescript-eslint/no-explicit-any */\n'use client';\n\nimport process from 'process';\nimport { intlayerAPI } from '@intlayer/api';\nimport { useAuth } from '../components/Auth/useAuth/index';\nimport { useToast } from '../components/Toaster';\nimport { useAsync, UseAsyncOptions } from './useAsync/useAsync';\nimport { useIntlayerAuth } from './useIntlayerAPI';\n\n/**\n * Hook to handle error logging and toast notifications\n */\nconst useErrorHandling = <T extends UseAsyncOptions<any>>(options: T): T => {\n const { toast } = useToast();\n\n return {\n ...options,\n onError: (errorMessage) => {\n let error;\n\n // If json is valid, parse it\n try {\n error = JSON.parse(errorMessage);\n } catch (e) {\n console.error(e);\n // If json is not valid, set error to the original errorMessage\n\n error = errorMessage;\n }\n\n // render toast for each error if there is more than one\n // otherwise render the toast with the error message\n [error]\n .flatMap((error) => error)\n .forEach((error) =>\n toast({\n title:\n (process.env.NODE_ENV === 'production'\n ? error.title\n : error.code) ?? 'Error',\n description: error.message ?? errorMessage ?? 'An error occurred',\n variant: 'error',\n })\n );\n options.onError?.(errorMessage);\n },\n onSuccess: (data) => {\n if (data.message)\n toast({\n title: data.message,\n description: data.description,\n variant: 'success',\n });\n options.onSuccess?.(data);\n },\n };\n};\n\ntype AuthEnableOptions = {\n requireUser?: boolean;\n requireProject?: boolean;\n requireOrganization?: boolean;\n};\n\n/**\n * Hook to enable authentication\n */\nconst useAuthEnable = <T extends UseAsyncOptions<any>>(\n options: T,\n { requireUser, requireProject, requireOrganization }: AuthEnableOptions = {}\n): T => {\n const { csrfToken, oAuth2AccessToken, session } = useAuth();\n\n const isEnabledOption = options?.enable ?? true;\n const user = session ? session.user : oAuth2AccessToken?.user;\n\n const organization = session\n ? session.organization\n : oAuth2AccessToken?.organization;\n\n const project = session ? session.project : oAuth2AccessToken?.project;\n\n const isUserEnabled = requireUser ? Boolean(user) : true;\n\n const isProjectEnabled = requireProject ? Boolean(project) : true;\n\n const isOrganizationEnabled = requireOrganization\n ? Boolean(organization)\n : true;\n\n const isCSRFEnabled =\n Boolean(csrfToken) ||\n // If auth using session, csrf token is not required\n (!session && Boolean(oAuth2AccessToken));\n\n const isEnabled =\n isEnabledOption &&\n isUserEnabled &&\n isProjectEnabled &&\n isOrganizationEnabled &&\n isCSRFEnabled;\n\n return {\n ...options,\n enable: isEnabled,\n };\n};\n\nconst useAppAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>,\n authOptions?: AuthEnableOptions\n) => {\n // Enhance options using custom hooks\n const optionsWithAuth = useAuthEnable(options ?? {}, authOptions);\n\n const optionsWithErrorHandling = useErrorHandling(optionsWithAuth);\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\n/**\n * Auth\n */\n\nexport const useLogin = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.login>\n) =>\n useAppAsync('login', useIntlayerAuth().auth.login, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useRegister = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.register>\n) =>\n useAppAsync('register', useIntlayerAuth().auth.register, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useLogout = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.logout>\n) =>\n useAppAsync('logout', useIntlayerAuth().auth.logout, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useChangePassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.changePassword>\n) => useAppAsync('changePassword', useIntlayerAuth().auth.changePassword, args);\nexport const useAskResetPassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.askResetPassword>\n) =>\n useAppAsync(\n 'askResetPassword',\n useIntlayerAuth().auth.askResetPassword,\n args\n );\nexport const useResetPassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.resetPassword>\n) => useAppAsync('resetPassword', useIntlayerAuth().auth.resetPassword, args);\nexport const useCheckIfUserHasPassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.checkIfUserHasPassword>\n) =>\n useAppAsync(\n 'checkIfUserHasPassword',\n useIntlayerAuth().auth.checkIfUserHasPassword,\n args,\n {\n requireUser: true,\n }\n );\nexport const useVerifyEmail = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.verifyEmail>\n) => useAppAsync('verifyEmail', useIntlayerAuth().auth.verifyEmail, args);\n\nexport const useGetUserByAccount = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.getUserByAccount>\n) =>\n useAppAsync(\n 'getUserByAccount',\n useIntlayerAuth().user.getUserByAccount,\n args\n );\n\n/**\n * User\n */\n\nexport const useGetUsers = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.getUsers>\n) =>\n useAppAsync(\n 'getUsers',\n useIntlayerAuth().user.getUsers,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\nexport const useCreateUser = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.createUser>\n) =>\n useAppAsync('createUser', useIntlayerAuth().user.createUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\nexport const useUpdateUser = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.updateUser>\n) =>\n useAppAsync('updateUser', useIntlayerAuth().user.updateUser, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useDeleteUser = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.deleteUser>\n) =>\n useAppAsync('deleteUser', useIntlayerAuth().user.deleteUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\n/**\n * Organization\n */\n\nexport const useGetOrganizations = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.getOrganizations>\n) =>\n useAppAsync(\n 'getOrganizations',\n useIntlayerAuth().organization.getOrganizations,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useAddOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.addOrganization>\n) =>\n useAppAsync(\n 'addOrganization',\n useIntlayerAuth().organization.addOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useUpdateOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.updateOrganization>\n) =>\n useAppAsync(\n 'updateOrganization',\n useIntlayerAuth().organization.updateOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\nexport const useUpdateOrganizationMembers = (\n args?: UseAsyncOptions<\n typeof intlayerAPI.organization.updateOrganizationMembers\n >\n) =>\n useAppAsync(\n 'updateOrganizationMembers',\n useIntlayerAuth().organization.updateOrganizationMembers,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useAddOrganizationMember = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.addOrganizationMember>\n) =>\n useAppAsync(\n 'addOrganizationMember',\n useIntlayerAuth().organization.addOrganizationMember,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useDeleteOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.deleteOrganization>\n) =>\n useAppAsync(\n 'deleteOrganization',\n useIntlayerAuth().organization.deleteOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useSelectOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.selectOrganization>\n) =>\n useAppAsync(\n 'selectOrganization',\n useIntlayerAuth().organization.selectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\nexport const useUnselectOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.unselectOrganization>\n) =>\n useAppAsync(\n 'unselectOrganization',\n useIntlayerAuth().organization.unselectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\n/**\n * Project\n */\n\nexport const useGetProjects = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.getProjects>\n) =>\n useAppAsync(\n 'getProjects',\n useIntlayerAuth().project.getProjects,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\nexport const useAddProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.addProject>\n) =>\n useAppAsync('addProject', useIntlayerAuth().project.addProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\nexport const useUpdateProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.updateProject>\n) =>\n useAppAsync('updateProject', useIntlayerAuth().project.updateProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useUpdateProjectMembers = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.updateProjectMembers>\n) =>\n useAppAsync(\n 'updateProjectMembers',\n useIntlayerAuth().project.updateProjectMembers,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\nexport const useDeleteProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.deleteProject>\n) =>\n useAppAsync('deleteProject', useIntlayerAuth().project.deleteProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\nexport const useSelectProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.selectProject>\n) =>\n useAppAsync('selectProject', useIntlayerAuth().project.selectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useUnselectProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.unselectProject>\n) =>\n useAppAsync('unselectProject', useIntlayerAuth().project.unselectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useAddNewAccessKey = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.addNewAccessKey>\n) =>\n useAppAsync('addNewAccessKey', useIntlayerAuth().project.addNewAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useDeleteAccessKey = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.deleteAccessKey>\n) =>\n useAppAsync('deleteAccessKey', useIntlayerAuth().project.deleteAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useRefreshAccessKey = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.refreshAccessKey>\n) =>\n useAppAsync('refreshAccessKey', useIntlayerAuth().project.refreshAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\n/**\n * Dictionary\n */\n\nexport const useGetDictionaries = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.getDictionaries>\n) =>\n useAppAsync(\n 'getDictionaries',\n useIntlayerAuth().dictionary.getDictionaries,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionariesKeys = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.getDictionariesKeys>\n) =>\n useAppAsync(\n 'getDictionariesKeys',\n useIntlayerAuth().dictionary.getDictionariesKeys,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.getDictionary>\n) =>\n useAppAsync(\n 'getDictionary',\n useIntlayerAuth().dictionary.getDictionary,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\nexport const useAddDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.addDictionary>\n) =>\n useAppAsync('addDictionary', useIntlayerAuth().dictionary.addDictionary, {\n invalidateQueries: ['getDictionaries', 'getDictionariesKeys'],\n ...args,\n });\n\nexport const usePushDictionaries = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.pushDictionaries>\n) =>\n useAppAsync(\n 'pushDictionaries',\n useIntlayerAuth().dictionary.pushDictionaries,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\nexport const useUpdateDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.updateDictionary>\n) =>\n useAppAsync(\n 'updateDictionary',\n useIntlayerAuth().dictionary.updateDictionary,\n {\n invalidateQueries: ['getDictionaries', 'getDictionary'],\n ...args,\n }\n );\nexport const useDeleteDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.deleteDictionary>\n) =>\n useAppAsync(\n 'deleteDictionary',\n useIntlayerAuth().dictionary.deleteDictionary,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\n/**\n * Tag\n */\n\nexport const useGetTags = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.getTags>\n) =>\n useAppAsync(\n 'getTags',\n useIntlayerAuth().tag.getTags,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\nexport const useAddTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.addTag>\n) =>\n useAppAsync('addTag', useIntlayerAuth().tag.addTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\nexport const useUpdateTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.updateTag>\n) =>\n useAppAsync('updateTag', useIntlayerAuth().tag.updateTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\nexport const useDeleteTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.deleteTag>\n) =>\n useAppAsync('deleteTag', useIntlayerAuth().tag.deleteTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\n/**\n * Stripe\n */\n\nexport const useGetSubscription = (\n args?: UseAsyncOptions<typeof intlayerAPI.stripe.getSubscription>\n) =>\n useAppAsync(\n 'getSubscription',\n useIntlayerAuth().stripe.getSubscription,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useCancelSubscription = (\n args?: UseAsyncOptions<typeof intlayerAPI.stripe.cancelSubscription>\n) =>\n useAppAsync(\n 'cancelSubscription',\n useIntlayerAuth().stripe.cancelSubscription,\n { invalidateQueries: ['getSession'], ...args },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\n/**\n * AI\n */\n\nexport const useAuditContentDeclaration = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditContentDeclaration>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerAuth().ai.auditContentDeclaration,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationMetadata = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditContentDeclarationMetadata>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerAuth().ai.auditContentDeclarationMetadata,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationField = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditContentDeclarationField>\n) =>\n useAppAsync(\n 'auditContentDeclarationField',\n useIntlayerAuth().ai.auditContentDeclarationField,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditTag>\n) =>\n useAppAsync('auditTag', useIntlayerAuth().ai.auditTag, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAskDocQuestion = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.askDocQuestion>\n) => useAppAsync('askDocQuestion', useIntlayerAuth().ai.askDocQuestion, args);\n"],"names":["error"],"mappings":";;;;;;;AAAA,MAAe,UAAA,CAAA;ACaf,MAAM,mBAAmB,CAAiC,YAAkB;AACpE,QAAA,EAAE,MAAM,IAAI,SAAS;AAEpB,SAAA;AAAA,IACL,GAAG;AAAA,IACH,SAAS,CAAC,iBAAiB;AACrB,UAAA;AAGA,UAAA;AACM,gBAAA,KAAK,MAAM,YAAY;AAAA,eACxB,GAAG;AACV,gBAAQ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AAA,IACE,aAAa;AAAA,IACb,qBAAqB;AAAA,IACrB,gBAAgB;AAAA,EAAA;AAEpB;AAEW,MAAA,qCAAqC,CAChD,SAEA;AAAA,EACE;AAAA,EACA,gBAAA,EAAkB,GAAG;AAAA,EACrB;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,qBAAqB;AAAA,IACrB,gBAAgB;AAAA,EAAA;AAEpB;AAEW,MAAA,kCAAkC,CAC7C,SAEA;AAAA,EACE;AAAA,EACA,gBAAA,EAAkB,GAAG;AAAA,EACrB;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,qBAAqB;AAAA,IACrB,gBAAgB;AAAA,EAAA;AAEpB;AAEW,MAAA,cAAc,CACzB,SAEA,YAAY,YAAY,kBAAkB,GAAG,UAAU,MAAM;AAAA,EAC3D,aAAa;AAAA,EACb,qBAAqB;AAAA,EACrB,gBAAgB;AAClB,CAAC;AAEU,MAAA,oBAAoB,CAC/B,SACG,YAAY,kBAAkB,kBAAkB,GAAG,gBAAgB,IAAI;"}
1
+ {"version":3,"file":"intlayerAPIHooks.mjs","sources":["../../__vite-browser-external","../../src/hooks/intlayerAPIHooks.ts"],"sourcesContent":["export default {}","/* eslint-disable @typescript-eslint/no-explicit-any */\n'use client';\n\nimport process from 'process';\nimport { intlayerAPI } from '@intlayer/api';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport { useAuth } from '../components/Auth/useAuth/index';\nimport { useToast } from '../components/Toaster';\nimport { useAsync, UseAsyncOptions } from './useAsync/useAsync';\nimport { useIntlayerAuth } from './useIntlayerAPI';\n\n/**\n * Hook to handle error logging and toast notifications\n */\nconst useErrorHandling = <T extends UseAsyncOptions<any>>(options: T): T => {\n const { toast } = useToast();\n\n return {\n ...options,\n onError: (errorMessage) => {\n let error;\n\n // If json is valid, parse it\n try {\n error = JSON.parse(errorMessage);\n } catch (e) {\n console.error(e);\n // If json is not valid, set error to the original errorMessage\n\n error = errorMessage;\n }\n\n // render toast for each error if there is more than one\n // otherwise render the toast with the error message\n [error]\n .flatMap((error) => error)\n .forEach((error) =>\n toast({\n title:\n (process.env.NODE_ENV === 'production'\n ? error.title\n : error.code) ?? 'Error',\n description: error.message ?? errorMessage ?? 'An error occurred',\n variant: 'error',\n })\n );\n options.onError?.(errorMessage);\n },\n onSuccess: (data) => {\n if (data.message)\n toast({\n title: data.message,\n description: data.description,\n variant: 'success',\n });\n options.onSuccess?.(data);\n },\n };\n};\n\ntype AuthEnableOptions = {\n requireUser?: boolean;\n requireProject?: boolean;\n requireOrganization?: boolean;\n};\n\n/**\n * Hook to enable authentication\n */\nconst useAuthEnable = <T extends UseAsyncOptions<any>>(\n options: T,\n { requireUser, requireProject, requireOrganization }: AuthEnableOptions = {}\n): T => {\n const { configuration } = useConfiguration();\n const { csrfToken, oAuth2AccessToken, session } = useAuth({\n intlayerConfiguration: configuration,\n });\n\n const isEnabledOption = options?.enable ?? true;\n const user = session ? session.user : oAuth2AccessToken?.user;\n\n const organization = session\n ? session.organization\n : oAuth2AccessToken?.organization;\n\n const project = session ? session.project : oAuth2AccessToken?.project;\n\n const isUserEnabled = requireUser ? Boolean(user) : true;\n\n const isProjectEnabled = requireProject ? Boolean(project) : true;\n\n const isOrganizationEnabled = requireOrganization\n ? Boolean(organization)\n : true;\n\n const isCSRFEnabled =\n Boolean(csrfToken) ||\n // If auth using session, csrf token is not required\n (!session && Boolean(oAuth2AccessToken));\n\n const isEnabled =\n isEnabledOption &&\n isUserEnabled &&\n isProjectEnabled &&\n isOrganizationEnabled &&\n isCSRFEnabled;\n\n return {\n ...options,\n enable: isEnabled,\n };\n};\n\nconst useAppAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>,\n authOptions?: AuthEnableOptions\n) => {\n // Enhance options using custom hooks\n const optionsWithAuth = useAuthEnable(options ?? {}, authOptions);\n\n const optionsWithErrorHandling = useErrorHandling(optionsWithAuth);\n\n // Call the main useAsync hook with enhanced options\n return useAsync(key, asyncFunction, optionsWithErrorHandling);\n};\n\n/**\n * Auth\n */\n\nexport const useLogin = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.login>\n) =>\n useAppAsync('login', useIntlayerAuth().auth.login, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useRegister = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.register>\n) =>\n useAppAsync('register', useIntlayerAuth().auth.register, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useLogout = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.logout>\n) =>\n useAppAsync('logout', useIntlayerAuth().auth.logout, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useChangePassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.changePassword>\n) => useAppAsync('changePassword', useIntlayerAuth().auth.changePassword, args);\nexport const useAskResetPassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.askResetPassword>\n) =>\n useAppAsync(\n 'askResetPassword',\n useIntlayerAuth().auth.askResetPassword,\n args\n );\nexport const useResetPassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.resetPassword>\n) => useAppAsync('resetPassword', useIntlayerAuth().auth.resetPassword, args);\nexport const useCheckIfUserHasPassword = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.checkIfUserHasPassword>\n) =>\n useAppAsync(\n 'checkIfUserHasPassword',\n useIntlayerAuth().auth.checkIfUserHasPassword,\n args,\n {\n requireUser: true,\n }\n );\nexport const useVerifyEmail = (\n args?: UseAsyncOptions<typeof intlayerAPI.auth.verifyEmail>\n) => useAppAsync('verifyEmail', useIntlayerAuth().auth.verifyEmail, args);\n\nexport const useGetUserByAccount = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.getUserByAccount>\n) =>\n useAppAsync(\n 'getUserByAccount',\n useIntlayerAuth().user.getUserByAccount,\n args\n );\n\n/**\n * User\n */\n\nexport const useGetUsers = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.getUsers>\n) =>\n useAppAsync(\n 'getUsers',\n useIntlayerAuth().user.getUsers,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\nexport const useCreateUser = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.createUser>\n) =>\n useAppAsync('createUser', useIntlayerAuth().user.createUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\nexport const useUpdateUser = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.updateUser>\n) =>\n useAppAsync('updateUser', useIntlayerAuth().user.updateUser, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useDeleteUser = (\n args?: UseAsyncOptions<typeof intlayerAPI.user.deleteUser>\n) =>\n useAppAsync('deleteUser', useIntlayerAuth().user.deleteUser, {\n invalidateQueries: ['getUsers'],\n ...args,\n });\n\n/**\n * Organization\n */\n\nexport const useGetOrganizations = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.getOrganizations>\n) =>\n useAppAsync(\n 'getOrganizations',\n useIntlayerAuth().organization.getOrganizations,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n }\n );\n\nexport const useAddOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.addOrganization>\n) =>\n useAppAsync(\n 'addOrganization',\n useIntlayerAuth().organization.addOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useUpdateOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.updateOrganization>\n) =>\n useAppAsync(\n 'updateOrganization',\n useIntlayerAuth().organization.updateOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\nexport const useUpdateOrganizationMembers = (\n args?: UseAsyncOptions<\n typeof intlayerAPI.organization.updateOrganizationMembers\n >\n) =>\n useAppAsync(\n 'updateOrganizationMembers',\n useIntlayerAuth().organization.updateOrganizationMembers,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useAddOrganizationMember = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.addOrganizationMember>\n) =>\n useAppAsync(\n 'addOrganizationMember',\n useIntlayerAuth().organization.addOrganizationMember,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useDeleteOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.deleteOrganization>\n) =>\n useAppAsync(\n 'deleteOrganization',\n useIntlayerAuth().organization.deleteOrganization,\n {\n invalidateQueries: ['getOrganizations'],\n ...args,\n }\n );\nexport const useSelectOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.selectOrganization>\n) =>\n useAppAsync(\n 'selectOrganization',\n useIntlayerAuth().organization.selectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\nexport const useUnselectOrganization = (\n args?: UseAsyncOptions<typeof intlayerAPI.organization.unselectOrganization>\n) =>\n useAppAsync(\n 'unselectOrganization',\n useIntlayerAuth().organization.unselectOrganization,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\n\n/**\n * Project\n */\n\nexport const useGetProjects = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.getProjects>\n) =>\n useAppAsync(\n 'getProjects',\n useIntlayerAuth().project.getProjects,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\nexport const useAddProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.addProject>\n) =>\n useAppAsync('addProject', useIntlayerAuth().project.addProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\nexport const useUpdateProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.updateProject>\n) =>\n useAppAsync('updateProject', useIntlayerAuth().project.updateProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useUpdateProjectMembers = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.updateProjectMembers>\n) =>\n useAppAsync(\n 'updateProjectMembers',\n useIntlayerAuth().project.updateProjectMembers,\n {\n invalidateQueries: ['getSession'],\n ...args,\n }\n );\nexport const useDeleteProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.deleteProject>\n) =>\n useAppAsync('deleteProject', useIntlayerAuth().project.deleteProject, {\n invalidateQueries: ['getProjects'],\n ...args,\n });\nexport const useSelectProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.selectProject>\n) =>\n useAppAsync('selectProject', useIntlayerAuth().project.selectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useUnselectProject = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.unselectProject>\n) =>\n useAppAsync('unselectProject', useIntlayerAuth().project.unselectProject, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useAddNewAccessKey = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.addNewAccessKey>\n) =>\n useAppAsync('addNewAccessKey', useIntlayerAuth().project.addNewAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useDeleteAccessKey = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.deleteAccessKey>\n) =>\n useAppAsync('deleteAccessKey', useIntlayerAuth().project.deleteAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\nexport const useRefreshAccessKey = (\n args?: UseAsyncOptions<typeof intlayerAPI.project.refreshAccessKey>\n) =>\n useAppAsync('refreshAccessKey', useIntlayerAuth().project.refreshAccessKey, {\n invalidateQueries: ['getSession'],\n ...args,\n });\n\n/**\n * Dictionary\n */\n\nexport const useGetDictionaries = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.getDictionaries>\n) =>\n useAppAsync(\n 'getDictionaries',\n useIntlayerAuth().dictionary.getDictionaries,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionariesKeys = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.getDictionariesKeys>\n) =>\n useAppAsync(\n 'getDictionariesKeys',\n useIntlayerAuth().dictionary.getDictionariesKeys,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useGetDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.getDictionary>\n) =>\n useAppAsync(\n 'getDictionary',\n useIntlayerAuth().dictionary.getDictionary,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\nexport const useAddDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.addDictionary>\n) =>\n useAppAsync('addDictionary', useIntlayerAuth().dictionary.addDictionary, {\n invalidateQueries: ['getDictionaries', 'getDictionariesKeys'],\n ...args,\n });\n\nexport const usePushDictionaries = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.pushDictionaries>\n) =>\n useAppAsync(\n 'pushDictionaries',\n useIntlayerAuth().dictionary.pushDictionaries,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\nexport const useUpdateDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.updateDictionary>\n) =>\n useAppAsync(\n 'updateDictionary',\n useIntlayerAuth().dictionary.updateDictionary,\n {\n invalidateQueries: ['getDictionaries', 'getDictionary'],\n ...args,\n }\n );\nexport const useDeleteDictionary = (\n args?: UseAsyncOptions<typeof intlayerAPI.dictionary.deleteDictionary>\n) =>\n useAppAsync(\n 'deleteDictionary',\n useIntlayerAuth().dictionary.deleteDictionary,\n {\n invalidateQueries: [\n 'getDictionaries',\n 'getDictionary',\n 'getDictionariesKeys',\n ],\n ...args,\n }\n );\n\n/**\n * Tag\n */\n\nexport const useGetTags = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.getTags>\n) =>\n useAppAsync(\n 'getTags',\n useIntlayerAuth().tag.getTags,\n {\n cache: true,\n store: true,\n retryLimit: 3,\n autoFetch: true,\n revalidation: true,\n revalidateTime: 5 * 60 * 1000, // 5 minutes\n ...args,\n },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\nexport const useAddTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.addTag>\n) =>\n useAppAsync('addTag', useIntlayerAuth().tag.addTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\nexport const useUpdateTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.updateTag>\n) =>\n useAppAsync('updateTag', useIntlayerAuth().tag.updateTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\nexport const useDeleteTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.tag.deleteTag>\n) =>\n useAppAsync('deleteTag', useIntlayerAuth().tag.deleteTag, {\n invalidateQueries: ['getTags'],\n ...args,\n });\n\n/**\n * Stripe\n */\n\nexport const useGetSubscription = (\n args?: UseAsyncOptions<typeof intlayerAPI.stripe.getSubscription>\n) =>\n useAppAsync(\n 'getSubscription',\n useIntlayerAuth().stripe.getSubscription,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\nexport const useCancelSubscription = (\n args?: UseAsyncOptions<typeof intlayerAPI.stripe.cancelSubscription>\n) =>\n useAppAsync(\n 'cancelSubscription',\n useIntlayerAuth().stripe.cancelSubscription,\n { invalidateQueries: ['getSession'], ...args },\n {\n requireUser: true,\n requireOrganization: true,\n }\n );\n\n/**\n * AI\n */\n\nexport const useAuditContentDeclaration = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditContentDeclaration>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerAuth().ai.auditContentDeclaration,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationMetadata = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditContentDeclarationMetadata>\n) =>\n useAppAsync(\n 'auditContentDeclaration',\n useIntlayerAuth().ai.auditContentDeclarationMetadata,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditContentDeclarationField = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditContentDeclarationField>\n) =>\n useAppAsync(\n 'auditContentDeclarationField',\n useIntlayerAuth().ai.auditContentDeclarationField,\n args,\n {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n }\n );\n\nexport const useAuditTag = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.auditTag>\n) =>\n useAppAsync('auditTag', useIntlayerAuth().ai.auditTag, args, {\n requireUser: true,\n requireOrganization: true,\n requireProject: true,\n });\n\nexport const useAskDocQuestion = (\n args?: UseAsyncOptions<typeof intlayerAPI.ai.askDocQuestion>\n) => useAppAsync('askDocQuestion', useIntlayerAuth().ai.askDocQuestion, args);\n"],"names":["error"],"mappings":";;;;;;;;AAAA,MAAe,UAAA,CAAA;ACcf,MAAM,mBAAmB,CAAiC,YAAkB;AACpE,QAAA,EAAE,MAAM,IAAI,SAAS;AAEpB,SAAA;AAAA,IACL,GAAG;AAAA,IACH,SAAS,CAAC,iBAAiB;AACrB,UAAA;AAGA,UAAA;AACM,gBAAA,KAAK,MAAM,YAAY;AAAA,eACxB,GAAG;AACV,gBAAQ,MAAM,CAAC;AAGP,gBAAA;AAAA,MAAA;AAKV,OAAC,KAAK,EACH,QAAQ,CAACA,WAAUA,MAAK,EACxB;AAAA,QAAQ,CAACA,WACR,MAAM;AAAA,UACJ,QACG,QAAQ,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B;AAEW,MAAA,qCAAqC,CAChD,SAEA;AAAA,EACE;AAAA,EACA,gBAAA,EAAkB,GAAG;AAAA,EACrB;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,qBAAqB;AAAA,IACrB,gBAAgB;AAAA,EAAA;AAEpB;AAEW,MAAA,kCAAkC,CAC7C,SAEA;AAAA,EACE;AAAA,EACA,gBAAA,EAAkB,GAAG;AAAA,EACrB;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,qBAAqB;AAAA,IACrB,gBAAgB;AAAA,EAAA;AAEpB;AAEW,MAAA,cAAc,CACzB,SAEA,YAAY,YAAY,kBAAkB,GAAG,UAAU,MAAM;AAAA,EAC3D,aAAa;AAAA,EACb,qBAAqB;AAAA,EACrB,gBAAgB;AAClB,CAAC;AAEU,MAAA,oBAAoB,CAC/B,SACG,YAAY,kBAAkB,kBAAkB,GAAG,gBAAgB,IAAI;"}
@@ -30,6 +30,7 @@ const useAsync = (key, asyncFunction, options) => {
30
30
  const args = getArgs(options?.args ?? []);
31
31
  const { getStates, setQueryState, setQueriesState, makeQueryInError } = hooks_useAsync_useAsyncStateStore.useAsyncState();
32
32
  const storedArgsRef = require$$0.useRef(args);
33
+ const controllerRef = require$$0.useRef(null);
33
34
  const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);
34
35
  const {
35
36
  isFetched,
@@ -45,6 +46,11 @@ const useAsync = (key, asyncFunction, options) => {
45
46
  const fetch = require$$0.useCallback(
46
47
  async (...args2) => {
47
48
  const keyWithArgs2 = getKeyWithArgs(key, args2);
49
+ if (controllerRef.current) {
50
+ controllerRef.current.abort();
51
+ }
52
+ const controller = new AbortController();
53
+ controllerRef.current = controller;
48
54
  if (pendingPromises.has(keyWithArgs2)) {
49
55
  return pendingPromises.get(keyWithArgs2);
50
56
  }
@@ -256,6 +262,14 @@ const useAsync = (key, asyncFunction, options) => {
256
262
  setDataMemo
257
263
  ]
258
264
  );
265
+ require$$0.useEffect(
266
+ () => () => {
267
+ if (controllerRef.current) {
268
+ controllerRef.current.abort();
269
+ }
270
+ },
271
+ []
272
+ );
259
273
  return memoResult;
260
274
  };
261
275
  exports.useAsync = useAsync;
@@ -1 +1 @@
1
- {"version":3,"file":"useAsync.cjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n isWaitingData: boolean;\n isRevalidating: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n errorCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function\n store?: boolean; // Store the result of the function in local storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n *\n * ```tsx\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n * ```\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n errorCount,\n } = getStates(keyWithArgs);\n\n /**\n * FETCH FUNCTION\n *\n * Manage parallel fetching across multiple instances of the hook\n * Manage state updates on success and error\n * Manage eventual invalidation of other queries\n */\n const fetch: T = useCallback<T>(\n (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n errorCount: 0,\n isLoading: false,\n isFetched: true,\n fetchedDateTime: new Date(),\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in local storage\n if (storeEnabled) {\n localStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T,\n [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]\n );\n\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n\n if (args) {\n // Revalidation arguments can be different from the initial fetch arguments\n // If arguments are provided, store/update them for future periodic revalidation\n\n storedArgsRef.current = getArgs(args);\n }\n\n return await fetch(...storedArgsRef.current);\n }) as T,\n [isEnabled, enabled, storedArgsRef, fetch]\n );\n\n /**\n * EXECUTION FUNCTION\n *\n * Wrap revalidation function\n * If data is valid return it directly to avoid fetching again\n */\n const execute: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n\n const shouldReturnData =\n !isInvalidated && // If data are invalidated, we should refetch to revalidate the data\n isSuccess &&\n cacheEnabled &&\n data;\n\n if (shouldReturnData) return data; // Data are already fetched and should be returned directly. Avoid fetching again.\n\n return await revalidate(...args);\n }) as T,\n [\n isEnabled,\n enabled,\n isInvalidated,\n cacheEnabled,\n isSuccess,\n data,\n isLoading,\n revalidate,\n ]\n );\n\n /**\n * HANDLE SYNCHRONIZATION HOOKS DISACTIVATION\n *\n * If one instance of the hook is disabled, the other instances should be disabled too.\n * This is to prevent inconsistencies in the state of the hook.\n */\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n /**\n * HANDLE LOCAL STORAGE LOADING\n *\n * If store is enabled, load data from local storage\n */\n useEffect(() => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!storeEnabled) return; // Hook should not use local storage\n if (isInvalidated || isFetched || data) return; // Hook have been already mounted and fetched or invalidated\n\n const storedData = localStorage.getItem(keyWithArgs);\n\n // Wrap parsing in a try-catch block to handle invalid JSON data\n try {\n if (storedData) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n } catch (error) {\n console.error(error);\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n /**\n * HANDLE AUTO-FETCH ON HOOK MOUNT\n *\n * If autoFetch is enabled, fetch the data when the hook is mounted\n */\n useEffect(() => {\n if (!autoFetch) return; // Auto-fetch is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isFetched && !isInvalidated) return; // Hook have already fetched or invalidated\n if (isLoading) return; // Fetch is already in progress\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isEnabled,\n enabled,\n isFetched,\n isInvalidated,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE RETRY\n *\n * If fetching fails, retry the fetch after a certain time\n */\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount > retryLimit;\n\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!isRetryEnabled) return; // Retry is disabled\n if (isRetryLimitReached) return; // Retry limit has been reached\n if (!(cacheEnabled || storeEnabled)) return; // Useless to retry if caching is disabled\n if (isLoading) return; // Fetch is already in progress\n if (isSuccess) return; // Hook has already fetched successfully\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeout);\n }, [\n isEnabled,\n errorCount,\n retryLimit,\n enabled,\n retryTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE PERIODIC REVALIDATION\n *\n * If revalidation is enabled, revalidate the data periodically\n */\n useEffect(() => {\n if (!revalidationEnabled || revalidateTime <= 0) return; // Revalidation is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n if (!isSuccess || !fetchedDateTime) return; // Should retry either of revalidate\n if (!(cacheEnabled || storeEnabled)) return; // Useless to revalidate if caching is disabled\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n fetch,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = useCallback(\n (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n },\n [keyWithArgs]\n );\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = useMemo(\n () => ({\n isFetched,\n isInvalidated,\n error,\n data,\n errorCount,\n isSuccess,\n isEnabled,\n isDisabled: !isEnabled,\n isLoading,\n isWaitingData: isLoading && !isFetched && !data, // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage\n isRevalidating: isLoading && isFetched, // Check if the data is valid and is being revalidated\n [key]: execute, // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)\n revalidate,\n setData: setDataMemo,\n }),\n [\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n errorCount,\n isEnabled,\n key,\n execute,\n revalidate,\n setDataMemo,\n ]\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n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IAClB,CAACK,UAAwC;AACvC,oBAAc,aAAa;AAAA,QACzB,MAAAA;AAAAA,MAAA,CACD;AAAA,IACH;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAGA,QAAM,aAAaC,WAAA;AAAA,IACjB,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,YAAY,CAAC;AAAA,MACb;AAAA,MACA,eAAe,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,MAC3C,gBAAgB,aAAa;AAAA;AAAA,MAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,MACP;AAAA,MACA,SAAS;AAAA,IAAA;AAAA,IAEX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAGO,SAAA;AACT;;"}
1
+ {"version":3,"file":"useAsync.cjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n isWaitingData: boolean;\n isRevalidating: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n errorCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function\n store?: boolean; // Store the result of the function in local storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n *\n * ```tsx\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n * ```\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n const controllerRef = useRef<AbortController | null>(null);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n errorCount,\n } = getStates(keyWithArgs);\n\n /**\n * FETCH FUNCTION\n *\n * Manage parallel fetching across multiple instances of the hook\n * Manage state updates on success and error\n * Manage eventual invalidation of other queries\n */\n const fetch: T = useCallback<T>(\n (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\n */\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n errorCount: 0,\n isLoading: false,\n isFetched: true,\n fetchedDateTime: new Date(),\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in local storage\n if (storeEnabled) {\n localStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T,\n [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]\n );\n\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n\n if (args) {\n // Revalidation arguments can be different from the initial fetch arguments\n // If arguments are provided, store/update them for future periodic revalidation\n\n storedArgsRef.current = getArgs(args);\n }\n\n return await fetch(...storedArgsRef.current);\n }) as T,\n [isEnabled, enabled, storedArgsRef, fetch]\n );\n\n /**\n * EXECUTION FUNCTION\n *\n * Wrap revalidation function\n * If data is valid return it directly to avoid fetching again\n */\n const execute: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n\n const shouldReturnData =\n !isInvalidated && // If data are invalidated, we should refetch to revalidate the data\n isSuccess &&\n cacheEnabled &&\n data;\n\n if (shouldReturnData) return data; // Data are already fetched and should be returned directly. Avoid fetching again.\n\n return await revalidate(...args);\n }) as T,\n [\n isEnabled,\n enabled,\n isInvalidated,\n cacheEnabled,\n isSuccess,\n data,\n isLoading,\n revalidate,\n ]\n );\n\n /**\n * HANDLE SYNCHRONIZATION HOOKS DISACTIVATION\n *\n * If one instance of the hook is disabled, the other instances should be disabled too.\n * This is to prevent inconsistencies in the state of the hook.\n */\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n /**\n * HANDLE LOCAL STORAGE LOADING\n *\n * If store is enabled, load data from local storage\n */\n useEffect(() => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!storeEnabled) return; // Hook should not use local storage\n if (isInvalidated || isFetched || data) return; // Hook have been already mounted and fetched or invalidated\n\n const storedData = localStorage.getItem(keyWithArgs);\n\n // Wrap parsing in a try-catch block to handle invalid JSON data\n try {\n if (storedData) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n } catch (error) {\n console.error(error);\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n /**\n * HANDLE AUTO-FETCH ON HOOK MOUNT\n *\n * If autoFetch is enabled, fetch the data when the hook is mounted\n */\n useEffect(() => {\n if (!autoFetch) return; // Auto-fetch is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isFetched && !isInvalidated) return; // Hook have already fetched or invalidated\n if (isLoading) return; // Fetch is already in progress\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isEnabled,\n enabled,\n isFetched,\n isInvalidated,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE RETRY\n *\n * If fetching fails, retry the fetch after a certain time\n */\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount > retryLimit;\n\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!isRetryEnabled) return; // Retry is disabled\n if (isRetryLimitReached) return; // Retry limit has been reached\n if (!(cacheEnabled || storeEnabled)) return; // Useless to retry if caching is disabled\n if (isLoading) return; // Fetch is already in progress\n if (isSuccess) return; // Hook has already fetched successfully\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeout);\n }, [\n isEnabled,\n errorCount,\n retryLimit,\n enabled,\n retryTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE PERIODIC REVALIDATION\n *\n * If revalidation is enabled, revalidate the data periodically\n */\n useEffect(() => {\n if (!revalidationEnabled || revalidateTime <= 0) return; // Revalidation is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n if (!isSuccess || !fetchedDateTime) return; // Should retry either of revalidate\n if (!(cacheEnabled || storeEnabled)) return; // Useless to revalidate if caching is disabled\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n fetch,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = useCallback(\n (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n },\n [keyWithArgs]\n );\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = useMemo(\n () => ({\n isFetched,\n isInvalidated,\n error,\n data,\n errorCount,\n isSuccess,\n isEnabled,\n isDisabled: !isEnabled,\n isLoading,\n isWaitingData: isLoading && !isFetched && !data, // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage\n isRevalidating: isLoading && isFetched, // Check if the data is valid and is being revalidated\n [key]: execute, // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)\n revalidate,\n setData: setDataMemo,\n }),\n [\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n errorCount,\n isEnabled,\n key,\n execute,\n revalidate,\n setDataMemo,\n ]\n );\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\n []\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n"],"names":["useAsyncState","useRef","useCallback","args","keyWithArgs","error","useEffect","data","useMemo"],"mappings":";;;;;AAQA,MAAM,sCAAsB,IAAI;AAoChC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,+BAA+B;AACrC,MAAM,0BAA0B,IAAI,KAAK;AACzC,MAAM,qBAAqB,IAAI,KAAK;AAQpC,MAAM,UAAU,CAAC,SACf,OAAQ,MAAM,QAAQ,IAAI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AC,EAAE,MAAM,EAAE,CAAC;IACzB,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;IACnD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,IAAI,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC;CACtB,CAAC;AAaF,MAAM,MAAM,cAAc,CACxB,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,IACxC,kBAAkB,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAQzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,eAAO,MAAM,QAAQ,GACnB,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,OAErC,CAAC,iBACS,CAAC,YACN,eAAe,CAAC,CAAC,CAAC,KAC3B,cAAc,CAAC,CAAC,EAAE,CAAC,CAiYrB,CAAC"}
@@ -28,6 +28,7 @@ const useAsync = (key, asyncFunction, options) => {
28
28
  const args = getArgs(options?.args ?? []);
29
29
  const { getStates, setQueryState, setQueriesState, makeQueryInError } = useAsyncState();
30
30
  const storedArgsRef = useRef(args);
31
+ const controllerRef = useRef(null);
31
32
  const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);
32
33
  const {
33
34
  isFetched,
@@ -43,6 +44,11 @@ const useAsync = (key, asyncFunction, options) => {
43
44
  const fetch = useCallback(
44
45
  async (...args2) => {
45
46
  const keyWithArgs2 = getKeyWithArgs(key, args2);
47
+ if (controllerRef.current) {
48
+ controllerRef.current.abort();
49
+ }
50
+ const controller = new AbortController();
51
+ controllerRef.current = controller;
46
52
  if (pendingPromises.has(keyWithArgs2)) {
47
53
  return pendingPromises.get(keyWithArgs2);
48
54
  }
@@ -254,6 +260,14 @@ const useAsync = (key, asyncFunction, options) => {
254
260
  setDataMemo
255
261
  ]
256
262
  );
263
+ useEffect(
264
+ () => () => {
265
+ if (controllerRef.current) {
266
+ controllerRef.current.abort();
267
+ }
268
+ },
269
+ []
270
+ );
257
271
  return memoResult;
258
272
  };
259
273
  export {
@@ -1 +1 @@
1
- {"version":3,"file":"useAsync.mjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n isWaitingData: boolean;\n isRevalidating: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n errorCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function\n store?: boolean; // Store the result of the function in local storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n *\n * ```tsx\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n * ```\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n errorCount,\n } = getStates(keyWithArgs);\n\n /**\n * FETCH FUNCTION\n *\n * Manage parallel fetching across multiple instances of the hook\n * Manage state updates on success and error\n * Manage eventual invalidation of other queries\n */\n const fetch: T = useCallback<T>(\n (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n errorCount: 0,\n isLoading: false,\n isFetched: true,\n fetchedDateTime: new Date(),\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in local storage\n if (storeEnabled) {\n localStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T,\n [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]\n );\n\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n\n if (args) {\n // Revalidation arguments can be different from the initial fetch arguments\n // If arguments are provided, store/update them for future periodic revalidation\n\n storedArgsRef.current = getArgs(args);\n }\n\n return await fetch(...storedArgsRef.current);\n }) as T,\n [isEnabled, enabled, storedArgsRef, fetch]\n );\n\n /**\n * EXECUTION FUNCTION\n *\n * Wrap revalidation function\n * If data is valid return it directly to avoid fetching again\n */\n const execute: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n\n const shouldReturnData =\n !isInvalidated && // If data are invalidated, we should refetch to revalidate the data\n isSuccess &&\n cacheEnabled &&\n data;\n\n if (shouldReturnData) return data; // Data are already fetched and should be returned directly. Avoid fetching again.\n\n return await revalidate(...args);\n }) as T,\n [\n isEnabled,\n enabled,\n isInvalidated,\n cacheEnabled,\n isSuccess,\n data,\n isLoading,\n revalidate,\n ]\n );\n\n /**\n * HANDLE SYNCHRONIZATION HOOKS DISACTIVATION\n *\n * If one instance of the hook is disabled, the other instances should be disabled too.\n * This is to prevent inconsistencies in the state of the hook.\n */\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n /**\n * HANDLE LOCAL STORAGE LOADING\n *\n * If store is enabled, load data from local storage\n */\n useEffect(() => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!storeEnabled) return; // Hook should not use local storage\n if (isInvalidated || isFetched || data) return; // Hook have been already mounted and fetched or invalidated\n\n const storedData = localStorage.getItem(keyWithArgs);\n\n // Wrap parsing in a try-catch block to handle invalid JSON data\n try {\n if (storedData) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n } catch (error) {\n console.error(error);\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n /**\n * HANDLE AUTO-FETCH ON HOOK MOUNT\n *\n * If autoFetch is enabled, fetch the data when the hook is mounted\n */\n useEffect(() => {\n if (!autoFetch) return; // Auto-fetch is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isFetched && !isInvalidated) return; // Hook have already fetched or invalidated\n if (isLoading) return; // Fetch is already in progress\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isEnabled,\n enabled,\n isFetched,\n isInvalidated,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE RETRY\n *\n * If fetching fails, retry the fetch after a certain time\n */\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount > retryLimit;\n\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!isRetryEnabled) return; // Retry is disabled\n if (isRetryLimitReached) return; // Retry limit has been reached\n if (!(cacheEnabled || storeEnabled)) return; // Useless to retry if caching is disabled\n if (isLoading) return; // Fetch is already in progress\n if (isSuccess) return; // Hook has already fetched successfully\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeout);\n }, [\n isEnabled,\n errorCount,\n retryLimit,\n enabled,\n retryTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE PERIODIC REVALIDATION\n *\n * If revalidation is enabled, revalidate the data periodically\n */\n useEffect(() => {\n if (!revalidationEnabled || revalidateTime <= 0) return; // Revalidation is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n if (!isSuccess || !fetchedDateTime) return; // Should retry either of revalidate\n if (!(cacheEnabled || storeEnabled)) return; // Useless to revalidate if caching is disabled\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n fetch,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = useCallback(\n (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n },\n [keyWithArgs]\n );\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = useMemo(\n () => ({\n isFetched,\n isInvalidated,\n error,\n data,\n errorCount,\n isSuccess,\n isEnabled,\n isDisabled: !isEnabled,\n isLoading,\n isWaitingData: isLoading && !isFetched && !data, // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage\n isRevalidating: isLoading && isFetched, // Check if the data is valid and is being revalidated\n [key]: execute, // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)\n revalidate,\n setData: setDataMemo,\n }),\n [\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n errorCount,\n isEnabled,\n key,\n execute,\n revalidate,\n setDataMemo,\n ]\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n"],"names":["args","keyWithArgs","error","data"],"mappings":";;;AAQA,MAAM,sCAAsB,IAAI;AAoChC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,+BAA+B;AACrC,MAAM,0BAA0B,IAAI,KAAK;AACzC,MAAM,qBAAqB,IAAI,KAAK;AAQpC,MAAM,UAAU,CAAC,SACf,OAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,IAAK,CAAC;AAElD,MAAM,iBAAiB,CAAC,KAAa,SACnC,QAAQ,IAAI,EAAE,SAAS,IAAI,GAAG,GAAG,IAAI,KAAK,UAAU,IAAI,CAAC,KAAK;AAwCzD,MAAM,WAAW,CAItB,KACA,eACA,YACyB;AAEnB,QAAA,aAAa,SAAS,cAAc;AACpC,QAAA,YAAY,SAAS,aAAa;AAClC,QAAA,YAAY,SAAS,aAAa;AAClC,QAAA,eAAe,SAAS,SAAS;AACjC,QAAA,eAAe,SAAS,SAAS;AACjC,QAAA,UAAU,SAAS,UAAU;AAC7B,QAAA,sBACJ,SAAS,gBAAgB;AACrB,QAAA,iBAAiB,SAAS,kBAAkB;AAC5C,QAAA,gBAAgB,SAAS,iBAAiB,CAAC;AAC3C,QAAA,oBAAoB,SAAS,qBAAqB,CAAC;AACzD,QAAM,YAAY,SAAS;AAC3B,QAAM,UAAU,SAAS;AACzB,QAAM,OAAO,QAAQ,SAAS,QAAQ,CAAA,CAAE;AAGxC,QAAM,EAAE,WAAW,eAAe,iBAAiB,iBAAA,IACjD,cAAc;AAGV,QAAA,gBAAgB,OAAc,IAAI;AAGxC,QAAM,cAAc,eAAe,KAAK,cAAc,OAAO;AAGvD,QAA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,CACD;AAGD,QAAM,cAAc;AAAA,IAClB,CAACC,UAAwC;AACvC,oBAAc,aAAa;AAAA,QACzB,MAAAA;AAAAA,MAAA,CACD;AAAA,IACH;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAGA,QAAM,aAAa;AAAA,IACjB,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,YAAY,CAAC;AAAA,MACb;AAAA,MACA,eAAe,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,MAC3C,gBAAgB,aAAa;AAAA;AAAA,MAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,MACP;AAAA,MACA,SAAS;AAAA,IAAA;AAAA,IAEX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAGO,SAAA;AACT;"}
1
+ {"version":3,"file":"useAsync.mjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n isWaitingData: boolean;\n isRevalidating: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n errorCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function\n store?: boolean; // Store the result of the function in local storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n *\n * ```tsx\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n * ```\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n const controllerRef = useRef<AbortController | null>(null);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n errorCount,\n } = getStates(keyWithArgs);\n\n /**\n * FETCH FUNCTION\n *\n * Manage parallel fetching across multiple instances of the hook\n * Manage state updates on success and error\n * Manage eventual invalidation of other queries\n */\n const fetch: T = useCallback<T>(\n (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\n */\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n errorCount: 0,\n isLoading: false,\n isFetched: true,\n fetchedDateTime: new Date(),\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in local storage\n if (storeEnabled) {\n localStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T,\n [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]\n );\n\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n\n if (args) {\n // Revalidation arguments can be different from the initial fetch arguments\n // If arguments are provided, store/update them for future periodic revalidation\n\n storedArgsRef.current = getArgs(args);\n }\n\n return await fetch(...storedArgsRef.current);\n }) as T,\n [isEnabled, enabled, storedArgsRef, fetch]\n );\n\n /**\n * EXECUTION FUNCTION\n *\n * Wrap revalidation function\n * If data is valid return it directly to avoid fetching again\n */\n const execute: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n\n const shouldReturnData =\n !isInvalidated && // If data are invalidated, we should refetch to revalidate the data\n isSuccess &&\n cacheEnabled &&\n data;\n\n if (shouldReturnData) return data; // Data are already fetched and should be returned directly. Avoid fetching again.\n\n return await revalidate(...args);\n }) as T,\n [\n isEnabled,\n enabled,\n isInvalidated,\n cacheEnabled,\n isSuccess,\n data,\n isLoading,\n revalidate,\n ]\n );\n\n /**\n * HANDLE SYNCHRONIZATION HOOKS DISACTIVATION\n *\n * If one instance of the hook is disabled, the other instances should be disabled too.\n * This is to prevent inconsistencies in the state of the hook.\n */\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n /**\n * HANDLE LOCAL STORAGE LOADING\n *\n * If store is enabled, load data from local storage\n */\n useEffect(() => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!storeEnabled) return; // Hook should not use local storage\n if (isInvalidated || isFetched || data) return; // Hook have been already mounted and fetched or invalidated\n\n const storedData = localStorage.getItem(keyWithArgs);\n\n // Wrap parsing in a try-catch block to handle invalid JSON data\n try {\n if (storedData) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n } catch (error) {\n console.error(error);\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n /**\n * HANDLE AUTO-FETCH ON HOOK MOUNT\n *\n * If autoFetch is enabled, fetch the data when the hook is mounted\n */\n useEffect(() => {\n if (!autoFetch) return; // Auto-fetch is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isFetched && !isInvalidated) return; // Hook have already fetched or invalidated\n if (isLoading) return; // Fetch is already in progress\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isEnabled,\n enabled,\n isFetched,\n isInvalidated,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE RETRY\n *\n * If fetching fails, retry the fetch after a certain time\n */\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount > retryLimit;\n\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!isRetryEnabled) return; // Retry is disabled\n if (isRetryLimitReached) return; // Retry limit has been reached\n if (!(cacheEnabled || storeEnabled)) return; // Useless to retry if caching is disabled\n if (isLoading) return; // Fetch is already in progress\n if (isSuccess) return; // Hook has already fetched successfully\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeout);\n }, [\n isEnabled,\n errorCount,\n retryLimit,\n enabled,\n retryTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE PERIODIC REVALIDATION\n *\n * If revalidation is enabled, revalidate the data periodically\n */\n useEffect(() => {\n if (!revalidationEnabled || revalidateTime <= 0) return; // Revalidation is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n if (!isSuccess || !fetchedDateTime) return; // Should retry either of revalidate\n if (!(cacheEnabled || storeEnabled)) return; // Useless to revalidate if caching is disabled\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n fetch,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = useCallback(\n (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n },\n [keyWithArgs]\n );\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = useMemo(\n () => ({\n isFetched,\n isInvalidated,\n error,\n data,\n errorCount,\n isSuccess,\n isEnabled,\n isDisabled: !isEnabled,\n isLoading,\n isWaitingData: isLoading && !isFetched && !data, // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage\n isRevalidating: isLoading && isFetched, // Check if the data is valid and is being revalidated\n [key]: execute, // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)\n revalidate,\n setData: setDataMemo,\n }),\n [\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n errorCount,\n isEnabled,\n key,\n execute,\n revalidate,\n setDataMemo,\n ]\n );\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\n []\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n"],"names":["args","keyWithArgs","error","data"],"mappings":";;;AAQA,MAAM,sCAAsB,IAAI;AAoChC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,+BAA+B;AACrC,MAAM,0BAA0B,IAAI,KAAK;AACzC,MAAM,qBAAqB,IAAI,KAAK;AAQpC,MAAM,UAAU,CAAC,SACf,OAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO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,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,MAC3C,gBAAgB,aAAa;AAAA;AAAA,MAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,MACP;AAAA,MACA,SAAS;AAAA,IAAA;AAAA,IAEX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEA;AAAA,IACE,MAAM,MAAM;AAEV,UAAI,cAAc,SAAS;AACzB,sBAAc,QAAQ,MAAM;AAAA,MAAA;AAAA,IAEhC;AAAA,IACA,CAAA;AAAA,EACF;AAGO,SAAA;AACT;"}
@@ -1,11 +1,12 @@
1
1
  "use client";
2
2
  "use strict";
3
3
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
4
- const localeDictionaries = require("@intlayer/dictionaries-entry");
4
+ const editorReact = require("@intlayer/editor-react");
5
5
  const merge = require("deepmerge");
6
6
  const require$$0 = require("react");
7
7
  const hooks_intlayerAPIHooks = require("./intlayerAPIHooks.cjs");
8
8
  const useGetAllDictionaries = (...props) => {
9
+ const { localeDictionaries } = editorReact.useDictionariesRecord();
9
10
  const { data: onlineDictionariesAPI, isWaitingData } = hooks_intlayerAPIHooks.useGetDictionaries(
10
11
  ...props
11
12
  );
@@ -21,7 +22,7 @@ const useGetAllDictionaries = (...props) => {
21
22
  );
22
23
  const allDictionaries = require$$0.useMemo(
23
24
  () => merge(onlineDictionaries ?? {}, localeDictionaries),
24
- [onlineDictionaries]
25
+ [onlineDictionaries, localeDictionaries]
25
26
  );
26
27
  return {
27
28
  online: onlineDictionaries,
@@ -1 +1 @@
1
- {"version":3,"file":"useGetAllDictionaries.cjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport localeDictionaries from '@intlayer/dictionaries-entry';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading: isWaitingData,\n };\n};\n"],"names":["useGetDictionaries","useMemo"],"mappings":";;;;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACvD,QAAM,EAAE,MAAM,uBAAuB,cAAkB,IAAAA,uBAAA;AAAA,IACrD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiDC,WAAA;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8CA,WAAA;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,kBAAkB;AAAA,EACrB;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF;;"}
1
+ {"version":3,"file":"useGetAllDictionaries.cjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport { useDictionariesRecord } from '@intlayer/editor-react';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { localeDictionaries } = useDictionariesRecord();\n const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries, localeDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading: isWaitingData,\n };\n};\n"],"names":["useDictionariesRecord","useGetDictionaries","useMemo"],"mappings":";;;;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACjD,QAAA,EAAE,mBAAmB,IAAIA,kCAAsB;AACrD,QAAM,EAAE,MAAM,uBAAuB,cAAkB,IAAAC,uBAAA;AAAA,IACrD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiDC,WAAA;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8CA,WAAA;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,oBAAoB,kBAAkB;AAAA,EACzC;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF;;"}
@@ -1,9 +1,9 @@
1
1
  import { Dictionary } from '@intlayer/core';
2
2
  import { useGetDictionaries } from './intlayerAPIHooks';
3
3
  type Args = Parameters<typeof useGetDictionaries>;
4
- export declare const useGetAllDictionaries: (args?: import('./useAsync').UseAsyncOptions<(filters?: import('@intlayer/backend').GetDictionariesParams, otherOptions?: import('node_modules/@intlayer/api/dist/types/fetcher').FetcherOptions) => Promise<import('@intlayer/backend').GetDictionariesResult>> | undefined) => {
4
+ export declare const useGetAllDictionaries: (args?: import('./useAsync').UseAsyncOptions<(filters?: import('@intlayer/backend').GetDictionariesParams, otherOptions?: import('@intlayer/api').FetcherOptions) => Promise<import('@intlayer/backend').GetDictionariesResult>> | undefined) => {
5
5
  online: Record<string, Dictionary>;
6
- locale: Record<string, Dictionary>;
6
+ locale: import('@intlayer/editor-react').DictionaryContent;
7
7
  all: Record<string, Dictionary>;
8
8
  isLoading: boolean;
9
9
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useGetAllDictionaries.d.ts","sourceRoot":"","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAI5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExD,KAAK,IAAI,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAElD,eAAO,MAAM,qBAAqB,iEA6Bsuf,mBAAmB,kIAA0E,mBAAmB;;;;;CADv3f,CAAC"}
1
+ {"version":3,"file":"useGetAllDictionaries.d.ts","sourceRoot":"","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAI5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExD,KAAK,IAAI,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAElD,eAAO,MAAM,qBAAqB,iEA8Bwpf,mBAAmB,kGAA0E,mBAAmB;;;;;CADzyf,CAAC"}
@@ -1,9 +1,10 @@
1
1
  "use client";
2
- import localeDictionaries from "@intlayer/dictionaries-entry";
2
+ import { useDictionariesRecord } from "@intlayer/editor-react";
3
3
  import merge from "deepmerge";
4
4
  import { useMemo } from "react";
5
5
  import { useGetDictionaries } from "./intlayerAPIHooks.mjs";
6
6
  const useGetAllDictionaries = (...props) => {
7
+ const { localeDictionaries } = useDictionariesRecord();
7
8
  const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(
8
9
  ...props
9
10
  );
@@ -19,7 +20,7 @@ const useGetAllDictionaries = (...props) => {
19
20
  );
20
21
  const allDictionaries = useMemo(
21
22
  () => merge(onlineDictionaries ?? {}, localeDictionaries),
22
- [onlineDictionaries]
23
+ [onlineDictionaries, localeDictionaries]
23
24
  );
24
25
  return {
25
26
  online: onlineDictionaries,
@@ -1 +1 @@
1
- {"version":3,"file":"useGetAllDictionaries.mjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport localeDictionaries from '@intlayer/dictionaries-entry';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading: isWaitingData,\n };\n};\n"],"names":[],"mappings":";;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACvD,QAAM,EAAE,MAAM,uBAAuB,cAAkB,IAAA;AAAA,IACrD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiD;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8C;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,kBAAkB;AAAA,EACrB;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF;"}
1
+ {"version":3,"file":"useGetAllDictionaries.mjs","sources":["../../src/hooks/useGetAllDictionaries.tsx"],"sourcesContent":["'use client';\n\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport { Dictionary } from '@intlayer/core';\nimport { useDictionariesRecord } from '@intlayer/editor-react';\nimport merge from 'deepmerge';\nimport { useMemo } from 'react';\nimport { useGetDictionaries } from './intlayerAPIHooks';\n\ntype Args = Parameters<typeof useGetDictionaries>;\n\nexport const useGetAllDictionaries = (...props: Args) => {\n const { localeDictionaries } = useDictionariesRecord();\n const { data: onlineDictionariesAPI, isWaitingData } = useGetDictionaries(\n ...props\n );\n\n const onlineDictionaries: Record<string, Dictionary> = useMemo(\n () =>\n (onlineDictionariesAPI?.data ?? []).reduce(\n (acc, dictionary) => {\n acc[dictionary.key] = dictionary;\n return acc;\n },\n {} as Record<string, Dictionary>\n ),\n [onlineDictionariesAPI]\n );\n\n const allDictionaries: Record<string, Dictionary> = useMemo(\n () => merge(onlineDictionaries ?? {}, localeDictionaries),\n [onlineDictionaries, localeDictionaries]\n );\n\n return {\n online: onlineDictionaries,\n locale: localeDictionaries,\n all: allDictionaries,\n isLoading: isWaitingData,\n };\n};\n"],"names":[],"mappings":";;;;;AAea,MAAA,wBAAwB,IAAI,UAAgB;AACjD,QAAA,EAAE,mBAAmB,IAAI,sBAAsB;AACrD,QAAM,EAAE,MAAM,uBAAuB,cAAkB,IAAA;AAAA,IACrD,GAAG;AAAA,EACL;AAEA,QAAM,qBAAiD;AAAA,IACrD,OACG,uBAAuB,QAAQ,CAAA,GAAI;AAAA,MAClC,CAAC,KAAK,eAAe;AACf,YAAA,WAAW,GAAG,IAAI;AACf,eAAA;AAAA,MACT;AAAA,MACA,CAAA;AAAA,IACF;AAAA,IACF,CAAC,qBAAqB;AAAA,EACxB;AAEA,QAAM,kBAA8C;AAAA,IAClD,MAAM,MAAM,sBAAsB,IAAI,kBAAkB;AAAA,IACxD,CAAC,oBAAoB,kBAAkB;AAAA,EACzC;AAEO,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,WAAW;AAAA,EACb;AACF;"}
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const api = require("@intlayer/api");
3
4
  const require$$0 = require("react");
4
- const index = require("../index-DFc7og1d.cjs");
5
5
  const components_Auth_useAuth_index = require("../components/Auth/useAuth/index.cjs");
6
- const useIntlayerAuth = (options) => {
6
+ const useIntlayerAuth = (props) => {
7
7
  const { csrfToken, oAuth2AccessToken } = components_Auth_useAuth_index.useAuth();
8
8
  const headers = require$$0.useMemo(
9
9
  () => oAuth2AccessToken?.accessToken ? {
@@ -16,11 +16,14 @@ const useIntlayerAuth = (options) => {
16
16
  [csrfToken]
17
17
  );
18
18
  return require$$0.useMemo(
19
- () => index.getIntlayerAPI({
20
- headers,
21
- body,
22
- ...options
23
- }),
19
+ () => api.getIntlayerAPI(
20
+ {
21
+ headers,
22
+ body,
23
+ ...props?.options ?? {}
24
+ },
25
+ props?.intlayerConfiguration
26
+ ),
24
27
  [body, headers]
25
28
  );
26
29
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.cjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { getIntlayerAPI } from '../../../api/src';\nimport { FetcherOptions } from '../../../api/src/fetcher';\nimport { useAuth } from '../components/Auth/useAuth';\n\nexport const useIntlayerAuth = (options?: FetcherOptions) => {\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = useMemo(\n () =>\n oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined,\n [oAuth2AccessToken?.accessToken]\n );\n\n const body = useMemo(\n () => (csrfToken ? { csrf_token: csrfToken } : undefined),\n [csrfToken]\n );\n\n return useMemo(\n () =>\n getIntlayerAPI({\n headers,\n body,\n ...options,\n }),\n [body, headers]\n );\n};\n"],"names":["useAuth","useMemo","getIntlayerAPI"],"mappings":";;;;;AAKa,MAAA,kBAAkB,CAAC,YAA6B;AAC3D,QAAM,EAAE,WAAW,kBAAkB,IAAIA,sCAAQ;AAEjD,QAAM,UAAUC,WAAA;AAAA,IACd,MACE,mBAAmB,cACf;AAAA,MACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,IAAA,IAExD;AAAA,IACN,CAAC,mBAAmB,WAAW;AAAA,EACjC;AAEA,QAAM,OAAOA,WAAA;AAAA,IACX,MAAO,YAAY,EAAE,YAAY,UAAc,IAAA;AAAA,IAC/C,CAAC,SAAS;AAAA,EACZ;AAEO,SAAAA,WAAA;AAAA,IACL,MACEC,qBAAe;AAAA,MACb;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA,CACJ;AAAA,IACH,CAAC,MAAM,OAAO;AAAA,EAChB;AACF;;"}
1
+ {"version":3,"file":"useIntlayerAPI.cjs","sources":["../../src/hooks/useIntlayerAPI.ts"],"sourcesContent":["import { getIntlayerAPI, type FetcherOptions } from '@intlayer/api';\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport { useMemo } from 'react';\nimport { useAuth } from '../components/Auth/useAuth';\n\ntype UseIntlayerAuthProps = {\n options?: FetcherOptions;\n intlayerConfiguration?: IntlayerConfig;\n};\n\nexport const useIntlayerAuth = (props?: UseIntlayerAuthProps) => {\n const { csrfToken, oAuth2AccessToken } = useAuth();\n\n const headers = useMemo(\n () =>\n oAuth2AccessToken?.accessToken\n ? {\n Authorization: `Bearer ${oAuth2AccessToken.accessToken}`,\n }\n : undefined,\n [oAuth2AccessToken?.accessToken]\n );\n\n const body = useMemo(\n () => (csrfToken ? { csrf_token: csrfToken } : undefined),\n [csrfToken]\n );\n\n return useMemo(\n () =>\n getIntlayerAPI(\n {\n headers,\n body,\n ...(props?.options ?? {}),\n },\n props?.intlayerConfiguration\n ),\n [body, headers]\n );\n};\n"],"names":["useAuth","useMemo","getIntlayerAPI"],"mappings":";;;;;AAUa,MAAA,kBAAkB,CAAC,UAAiC;AAC/D,QAAM,EAAE,WAAW,kBAAkB,IAAIA,sCAAQ;AAEjD,QAAM,UAAUC,WAAA;AAAA,IACd,MACE,mBAAmB,cACf;AAAA,MACE,eAAe,UAAU,kBAAkB,WAAW;AAAA,IAAA,IAExD;AAAA,IACN,CAAC,mBAAmB,WAAW;AAAA,EACjC;AAEA,QAAM,OAAOA,WAAA;AAAA,IACX,MAAO,YAAY,EAAE,YAAY,UAAc,IAAA;AAAA,IAC/C,CAAC,SAAS;AAAA,EACZ;AAEO,SAAAA,WAAA;AAAA,IACL,MACEC,IAAA;AAAA,MACE;AAAA,QACE;AAAA,QACA;AAAA,QACA,GAAI,OAAO,WAAW,CAAA;AAAA,MACxB;AAAA,MACA,OAAO;AAAA,IACT;AAAA,IACF,CAAC,MAAM,OAAO;AAAA,EAChB;AACF;;"}
@@ -1,5 +1,10 @@
1
- import { FetcherOptions } from '../../../api/src/fetcher';
2
- export declare const useIntlayerAuth: (options?: FetcherOptions) => {
1
+ import { FetcherOptions } from '@intlayer/api';
2
+ import { IntlayerConfig } from '@intlayer/config/client';
3
+ type UseIntlayerAuthProps = {
4
+ options?: FetcherOptions;
5
+ intlayerConfiguration?: IntlayerConfig;
6
+ };
7
+ export declare const useIntlayerAuth: (props?: UseIntlayerAuthProps) => {
3
8
  organization: {
4
9
  getOrganizations: (filters?: import('@intlayer/backend').GetOrganizationsParams, otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOrganizationsResult>;
5
10
  getOrganization: (organizationId: import('@intlayer/backend').GetOrganizationParam["organizationId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').GetOrganizationResult>;
@@ -76,4 +81,5 @@ export declare const useIntlayerAuth: (options?: FetcherOptions) => {
76
81
  deleteTag: (tagId: import('@intlayer/backend').DeleteTagParams["tagId"], otherOptions?: FetcherOptions) => Promise<import('@intlayer/backend').DeleteTagResult>;
77
82
  };
78
83
  };
84
+ export {};
79
85
  //# sourceMappingURL=useIntlayerAPI.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useIntlayerAPI.d.ts","sourceRoot":"","sources":["../../src/hooks/useIntlayerAPI.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG1D,eAAO,MAAM,eAAe,aAA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