@arex95/vue-core 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ export interface CallbacksConfig {
2
+ onRefreshFailed?: () => void;
3
+ onLogout?: () => void;
4
+ }
5
+ /**
6
+ * Configures the lifecycle callbacks for auth events.
7
+ * @param {CallbacksConfig} config - Callbacks to invoke on refresh failure or logout.
8
+ */
9
+ export declare const configCallbacks: (config: CallbacksConfig) => void;
10
+ /**
11
+ * Returns the configured lifecycle callbacks.
12
+ * @returns {CallbacksConfig}
13
+ */
14
+ export declare const getCallbacksConfig: () => CallbacksConfig;
@@ -3,3 +3,4 @@ export * from './endpointsConfig';
3
3
  export * from './sessionConfig';
4
4
  export * from './keyConfig';
5
5
  export * from './tokenPathsConfig';
6
+ export * from './callbacksConfig';
package/dist/index.mjs CHANGED
@@ -1246,6 +1246,20 @@ function getRefreshTokenPathsConfig() {
1246
1246
  return refreshTokenPathsConfig;
1247
1247
  }
1248
1248
 
1249
+ let callbacksConfig = {};
1250
+ /**
1251
+ * Configures the lifecycle callbacks for auth events.
1252
+ * @param {CallbacksConfig} config - Callbacks to invoke on refresh failure or logout.
1253
+ */
1254
+ const configCallbacks = (config) => {
1255
+ callbacksConfig = { ...config };
1256
+ };
1257
+ /**
1258
+ * Returns the configured lifecycle callbacks.
1259
+ * @returns {CallbacksConfig}
1260
+ */
1261
+ const getCallbacksConfig = () => callbacksConfig;
1262
+
1249
1263
  /**
1250
1264
  * Removes all stored authentication credentials (access and refresh tokens) from the specified storage locations.
1251
1265
  *
@@ -1340,7 +1354,7 @@ const verifyAuth = async () => {
1340
1354
  };
1341
1355
  const token = await getAuthToken(getAppKey(), sessionPersistence);
1342
1356
  if (!token) {
1343
- return handleAuthError("TOKEN_MISSING: No valid token found");
1357
+ return handleAuthError("TOKEN_MISSING: No valid token found", false);
1344
1358
  }
1345
1359
  try {
1346
1360
  const decoded = jwtDecode(token);
@@ -1349,7 +1363,7 @@ const verifyAuth = async () => {
1349
1363
  return handleAuthError("TOKEN_INVALID: Invalid expiration format");
1350
1364
  }
1351
1365
  if (decoded.exp <= currentTime) {
1352
- return handleAuthError("TOKEN_EXPIRED: Token is expired");
1366
+ return handleAuthError("TOKEN_EXPIRED: Token is expired", false);
1353
1367
  }
1354
1368
  return true;
1355
1369
  }
@@ -1775,7 +1789,11 @@ const refreshTokens = async (fetcher) => {
1775
1789
  catch (error) {
1776
1790
  handleError(error);
1777
1791
  await cleanCredentials(persistence);
1778
- if (typeof window !== 'undefined') {
1792
+ const { onRefreshFailed } = getCallbacksConfig();
1793
+ if (onRefreshFailed) {
1794
+ onRefreshFailed();
1795
+ }
1796
+ else if (typeof window !== 'undefined') {
1779
1797
  window.location.reload();
1780
1798
  }
1781
1799
  throw error;
@@ -1853,7 +1871,9 @@ class AxiosService {
1853
1871
  },
1854
1872
  withCredentials: options.withCredentials ?? false,
1855
1873
  });
1856
- this.initializeInterceptors();
1874
+ if (options.setupAuthInterceptors !== false) {
1875
+ this.initializeInterceptors();
1876
+ }
1857
1877
  }
1858
1878
  processQueue(error, token = null) {
1859
1879
  this.failedQueue.forEach((prom) => {
@@ -1889,6 +1909,9 @@ class AxiosService {
1889
1909
  return response;
1890
1910
  }, async (error) => {
1891
1911
  this.activeRequests--;
1912
+ if (typeof window === 'undefined') {
1913
+ return Promise.reject(error);
1914
+ }
1892
1915
  const originalRequest = error.config;
1893
1916
  const isAuthError = axios.isAxiosError(error) && error.response?.status === 401;
1894
1917
  const isRefreshCall = originalRequest?.url === this.refreshTokenUrl;
@@ -4279,7 +4302,11 @@ function useAuth(fetcher) {
4279
4302
  }
4280
4303
  finally {
4281
4304
  await cleanCredentials(await getSessionPersistence());
4282
- if (typeof window !== 'undefined') {
4305
+ const { onLogout } = getCallbacksConfig();
4306
+ if (onLogout) {
4307
+ onLogout();
4308
+ }
4309
+ else if (typeof window !== 'undefined') {
4283
4310
  window.location.reload();
4284
4311
  }
4285
4312
  }
@@ -4406,9 +4433,14 @@ const ArexVueCore = {
4406
4433
  baseURL: options.axios.baseURL,
4407
4434
  headers: options.axios.headers,
4408
4435
  timeout: options.axios.timeout,
4409
- withCredentials: options.axios.withCredentials
4436
+ withCredentials: options.axios.withCredentials,
4437
+ setupAuthInterceptors: options.axios.setupAuthInterceptors,
4438
+ });
4439
+ configCallbacks({
4440
+ onRefreshFailed: options.onRefreshFailed,
4441
+ onLogout: options.onLogout,
4410
4442
  });
4411
4443
  },
4412
4444
  };
4413
4445
 
4414
- export { AppTypes, ArchiveTypes, ArexVueCore, AudioTypes, AuthError, AxiosService, BaseError, ContentTypeEnum, DocumentTypes, ERROR_MESSAGES, ERROR_STYLES, ErrorEnum, ErrorMessages, ErrorStyles, ExceptionEnum, FontTypes, ImageTypes, KeyCodeEnum, NetworkError, OtherTypes, RestStd, ScreenBreakpoint, ScreenSize, ServerError, StorageKeyEnum, StorageTypeEnum, TextTypes, ValidationError, VideoTypes, ab2hex, addCustomKeyboardShortcut, addDays, addDoubleClickListener, addKeyListener, ageAtDate, axiosFetch, blobToFormData, bufferToBlob, calculateAge, cleanCredentials, clickOutside, compareObject, configAppKey, configAuthFetcher, configAxios, configEndpoints, configRefreshTokenPaths, configSession, configTokenKeys, configTokenPaths, copyToClipboard, countWords, createAxiosFetcher, createKeyMap, createOfetchFetcher, customShortcut, daysBetween, daysToNextBirthday, debounce, debounceAsync, debounceAsyncValidator, debounceAsyncWithImmediate, debounceLeading, debounceLeadingTrailing, debounceTrailing, decrypt, deepClone, deepEqual, deepMerge, detectKeyHold, disableCopy, disableF12Key, disableMouseButtons, disableRightClick, disableSpecificKeys, downloadBlob, enableMouseButtons, enableRightClick, enableSpecificKeys, encrypt, exportToCSV, exportToExcel, exportToJSON, exportToText, exportToXML, extractAndValidateTokens, filterObjectByKeys, flattenObject, formDataToObject, formatDate, generateRandomString, getAppKey, getAuthRefreshToken, getAuthToken, getConfiguredAxiosInstance, getCookieStorage, getDecryptedItem, getDefaultAuthFetcher, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getPreferredStorage, getQueryParam, getRefreshTokenPathsConfig, getSessionConfig, getSessionId, getSessionPersistence, getSessionStorage, getStartOfMonth, getStorage, getTokenConfig, getTokenPathsConfig, handleError, hasNestedProperties, hex2ab, importKey, isClient, isEmptyObject, isLeapYear, isServer, isStrongPassword, isValidAge, isValidCreditCard, isValidDate, isValidEmail, isValidExpiryDate, isValidHexColor, isValidHexColorAlpha, isValidHexNumber, isValidIP, isValidPhoneNumber, isValidSSN, isValidTime, isValidURL, isValidUsername, isValidZIP, lowerFirst, objectToFormData, objectToFormDataEnhanced, objectToQueryString, openWindow, parseDate, proxyToPlainObject, readFileAsDataURL, readFileAsText, refreshTokens, registerKeyboardShortcuts, removeAccent, removeClickOutside, removeCustomKeyboardShortcut, removeCustomShortcuts, removeDoubleClickListener, removeEmptyProperties, removeKeyListeners, replaceAll, retryWithBackoff, reverseString, safeGet, screenMap, scrollToTop, setDefaultAuthFetcherFactory, simulateKeyPress, stopDetectingKeyHold, storeAuthRefreshToken, storeAuthToken, storeEncryptedItem, storeTokens, stringToBlob, subtractDays, throttle, toCamelCase, toKebabCase, toggleTabNavigation, truncateString, unregisterKeyboardShortcuts, upperFirst, useAuth, useBreakpoint, useFetch, useFilter, usePagination, useSorter, validateAlphanumeric, validateLetters, validateNumbers, verifyAuth };
4446
+ export { AppTypes, ArchiveTypes, ArexVueCore, AudioTypes, AuthError, AxiosService, BaseError, ContentTypeEnum, DocumentTypes, ERROR_MESSAGES, ERROR_STYLES, ErrorEnum, ErrorMessages, ErrorStyles, ExceptionEnum, FontTypes, ImageTypes, KeyCodeEnum, NetworkError, OtherTypes, RestStd, ScreenBreakpoint, ScreenSize, ServerError, StorageKeyEnum, StorageTypeEnum, TextTypes, ValidationError, VideoTypes, ab2hex, addCustomKeyboardShortcut, addDays, addDoubleClickListener, addKeyListener, ageAtDate, axiosFetch, blobToFormData, bufferToBlob, calculateAge, cleanCredentials, clickOutside, compareObject, configAppKey, configAuthFetcher, configAxios, configCallbacks, configEndpoints, configRefreshTokenPaths, configSession, configTokenKeys, configTokenPaths, copyToClipboard, countWords, createAxiosFetcher, createKeyMap, createOfetchFetcher, customShortcut, daysBetween, daysToNextBirthday, debounce, debounceAsync, debounceAsyncValidator, debounceAsyncWithImmediate, debounceLeading, debounceLeadingTrailing, debounceTrailing, decrypt, deepClone, deepEqual, deepMerge, detectKeyHold, disableCopy, disableF12Key, disableMouseButtons, disableRightClick, disableSpecificKeys, downloadBlob, enableMouseButtons, enableRightClick, enableSpecificKeys, encrypt, exportToCSV, exportToExcel, exportToJSON, exportToText, exportToXML, extractAndValidateTokens, filterObjectByKeys, flattenObject, formDataToObject, formatDate, generateRandomString, getAppKey, getAuthRefreshToken, getAuthToken, getCallbacksConfig, getConfiguredAxiosInstance, getCookieStorage, getDecryptedItem, getDefaultAuthFetcher, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getPreferredStorage, getQueryParam, getRefreshTokenPathsConfig, getSessionConfig, getSessionId, getSessionPersistence, getSessionStorage, getStartOfMonth, getStorage, getTokenConfig, getTokenPathsConfig, handleError, hasNestedProperties, hex2ab, importKey, isClient, isEmptyObject, isLeapYear, isServer, isStrongPassword, isValidAge, isValidCreditCard, isValidDate, isValidEmail, isValidExpiryDate, isValidHexColor, isValidHexColorAlpha, isValidHexNumber, isValidIP, isValidPhoneNumber, isValidSSN, isValidTime, isValidURL, isValidUsername, isValidZIP, lowerFirst, objectToFormData, objectToFormDataEnhanced, objectToQueryString, openWindow, parseDate, proxyToPlainObject, readFileAsDataURL, readFileAsText, refreshTokens, registerKeyboardShortcuts, removeAccent, removeClickOutside, removeCustomKeyboardShortcut, removeCustomShortcuts, removeDoubleClickListener, removeEmptyProperties, removeKeyListeners, replaceAll, retryWithBackoff, reverseString, safeGet, screenMap, scrollToTop, setDefaultAuthFetcherFactory, simulateKeyPress, stopDetectingKeyHold, storeAuthRefreshToken, storeAuthToken, storeEncryptedItem, storeTokens, stringToBlob, subtractDays, throttle, toCamelCase, toKebabCase, toggleTabNavigation, truncateString, unregisterKeyboardShortcuts, upperFirst, useAuth, useBreakpoint, useFetch, useFilter, usePagination, useSorter, validateAlphanumeric, validateLetters, validateNumbers, verifyAuth };
@@ -39,4 +39,14 @@ export interface ArexVueCoreOptions {
39
39
  };
40
40
  /** The configuration options for the underlying Axios instance. */
41
41
  axios: AxiosServiceOptions;
42
+ /**
43
+ * Called when a token refresh attempt fails (e.g., to redirect to login via Vue Router).
44
+ * Falls back to `window.location.reload()` if not provided.
45
+ */
46
+ onRefreshFailed?: () => void;
47
+ /**
48
+ * Called after a successful logout (e.g., to redirect to login via Vue Router).
49
+ * Falls back to `window.location.reload()` if not provided.
50
+ */
51
+ onLogout?: () => void;
42
52
  }
@@ -12,4 +12,10 @@ export interface AxiosServiceOptions {
12
12
  timeout?: number;
13
13
  /** A boolean indicating whether cross-site Access-Control requests should be made using credentials. */
14
14
  withCredentials?: boolean;
15
+ /**
16
+ * Whether to mount the authentication interceptors (token attachment + 401 refresh).
17
+ * Set to `false` in SSR environments where browser storage is unavailable.
18
+ * Defaults to `true`.
19
+ */
20
+ setupAuthInterceptors?: boolean;
15
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arex95/vue-core",
3
- "version": "3.1.0",
3
+ "version": "3.3.0",
4
4
  "description": "Opinionated Vue Core",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",