@gofreego/tsutils 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1175,7 +1175,7 @@ var HttpClient = class {
1175
1175
  try {
1176
1176
  error.data = await response.json();
1177
1177
  } catch {
1178
- error.data = await response.text();
1178
+ error.data = { code: response.status, message: await response.text() };
1179
1179
  }
1180
1180
  throw error;
1181
1181
  }
@@ -1194,6 +1194,15 @@ var HttpClient = class {
1194
1194
  throw error;
1195
1195
  }
1196
1196
  }
1197
+ setDefaultHeader(key, value) {
1198
+ this.defaultHeaders[key] = value;
1199
+ }
1200
+ removeDefaultHeader(key) {
1201
+ delete this.defaultHeaders[key];
1202
+ }
1203
+ getDefaultHeaders() {
1204
+ return { ...this.defaultHeaders };
1205
+ }
1197
1206
  get(url, config) {
1198
1207
  return this.request(url, { ...config, method: "GET" });
1199
1208
  }
@@ -1210,6 +1219,16 @@ var HttpClient = class {
1210
1219
  return this.request(url, { ...config, method: "DELETE" });
1211
1220
  }
1212
1221
  };
1222
+ function extractErrorMessage(error) {
1223
+ if (error instanceof Error) {
1224
+ const httpError = error;
1225
+ if (httpError.data) {
1226
+ return httpError.data.message;
1227
+ }
1228
+ return error.message;
1229
+ }
1230
+ return "An unexpected error occurred";
1231
+ }
1213
1232
 
1214
1233
  // src/utils/cn.ts
1215
1234
  function cn(...classes) {
@@ -1250,162 +1269,162 @@ function formatDate(date, options = {
1250
1269
  const dateObj = typeof date === "string" || typeof date === "number" ? new Date(date) : date;
1251
1270
  return new Intl.DateTimeFormat("en-US", options).format(dateObj);
1252
1271
  }
1253
- function getCookie(name) {
1254
- if (typeof document === "undefined") return null;
1255
- const value = `; ${document.cookie}`;
1256
- const parts = value.split(`; ${name}=`);
1257
- if (parts.length === 2) return parts.pop()?.split(";").shift() || null;
1258
- return null;
1259
- }
1260
- function decodeJWT(token) {
1261
- try {
1262
- const base64Url = token.split(".")[1];
1263
- if (!base64Url) return null;
1264
- const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
1265
- const jsonPayload = decodeURIComponent(
1266
- window.atob(base64).split("").map(function(c) {
1267
- return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
1268
- }).join("")
1269
- );
1270
- return JSON.parse(jsonPayload);
1271
- } catch (e) {
1272
- return null;
1272
+
1273
+ // src/auth/sessionManager.ts
1274
+ var SESSION_KEY = "session_details";
1275
+ var SessionManager = class _SessionManager {
1276
+ constructor(client, key = SESSION_KEY) {
1277
+ this.cache = null;
1278
+ this.client = client;
1279
+ this.key = key;
1273
1280
  }
1274
- }
1275
- var AuthContext = createContext({
1276
- isAuthenticated: false,
1277
- isLoading: true
1278
- });
1279
- var AuthProvider = ({
1280
- cookieName = "authorization",
1281
- redirectUrl,
1282
- children,
1283
- onAuthFail,
1284
- onAuthSuccess,
1285
- loadingElement = null
1286
- }) => {
1287
- const [authState, setAuthState] = useState({
1288
- isAuthenticated: false,
1289
- isLoading: true
1290
- // starts loading until cookie check completes
1291
- });
1292
- const [authFailed, setAuthFailed] = useState(false);
1293
- useEffect(() => {
1294
- const verifyAuth = () => {
1295
- const token = getCookie(cookieName);
1296
- if (!token) {
1297
- handleFail();
1298
- return;
1299
- }
1300
- const decoded = decodeJWT(token);
1301
- if (!decoded) {
1302
- handleFail();
1303
- return;
1304
- }
1305
- if (decoded.exp) {
1306
- const expirationDate = new Date(decoded.exp * 1e3);
1307
- if (expirationDate < /* @__PURE__ */ new Date()) {
1308
- handleFail();
1309
- return;
1310
- }
1311
- }
1312
- setAuthState({
1313
- isAuthenticated: true,
1314
- isLoading: false
1315
- });
1316
- if (onAuthSuccess) {
1317
- onAuthSuccess();
1318
- }
1319
- };
1320
- verifyAuth();
1321
- }, [cookieName]);
1322
- const handleFail = () => {
1323
- setAuthState({
1324
- isAuthenticated: false,
1325
- isLoading: false
1326
- });
1327
- setAuthFailed(true);
1328
- if (onAuthFail) {
1329
- onAuthFail();
1330
- } else if (redirectUrl && typeof window !== "undefined") {
1331
- window.location.href = redirectUrl;
1281
+ static getInstance(client) {
1282
+ if (!_SessionManager.instance) {
1283
+ _SessionManager.instance = new _SessionManager(client);
1332
1284
  }
1333
- };
1334
- if (authState.isLoading || authFailed && !onAuthFail) {
1335
- return /* @__PURE__ */ jsx(Fragment, { children: loadingElement });
1285
+ return _SessionManager.instance;
1336
1286
  }
1337
- if (authFailed && onAuthFail) {
1338
- return /* @__PURE__ */ jsx(Fragment, { children });
1287
+ save(session) {
1288
+ this.cache = session;
1289
+ LocalStorage.setItem(this.key, session);
1290
+ this.setAuthToken(session.accessToken);
1291
+ }
1292
+ patch(updates) {
1293
+ const current = this.get();
1294
+ if (!current) return;
1295
+ const updated = { ...current, ...updates };
1296
+ this.cache = updated;
1297
+ LocalStorage.setItem(this.key, updated);
1298
+ if (updates.accessToken) {
1299
+ this.setAuthToken(updates.accessToken);
1300
+ }
1301
+ }
1302
+ clear() {
1303
+ this.cache = null;
1304
+ LocalStorage.removeItem(this.key);
1305
+ this.clearAuthToken();
1306
+ }
1307
+ get() {
1308
+ if (this.cache !== null) return this.cache;
1309
+ this.cache = LocalStorage.getItem(this.key);
1310
+ return this.cache;
1311
+ }
1312
+ getAccessToken() {
1313
+ return this.get()?.accessToken || void 0;
1314
+ }
1315
+ getRefreshToken() {
1316
+ return this.get()?.refreshToken || void 0;
1317
+ }
1318
+ getSessionId() {
1319
+ return this.get()?.sessionId || void 0;
1320
+ }
1321
+ isAuthenticated() {
1322
+ const session = this.get();
1323
+ if (!session?.accessToken) return false;
1324
+ return Number(session.expiresAt) > Date.now() / 1e3;
1325
+ }
1326
+ initialize() {
1327
+ const session = this.get();
1328
+ if (session?.accessToken && Number(session.expiresAt) > Date.now() / 1e3) {
1329
+ this.setAuthToken(session.accessToken);
1330
+ } else {
1331
+ this.clear();
1332
+ }
1333
+ }
1334
+ setAuthToken(token) {
1335
+ this.client.setDefaultHeader("Authorization", `Bearer ${token}`);
1336
+ }
1337
+ clearAuthToken() {
1338
+ this.client.removeDefaultHeader("Authorization");
1339
1339
  }
1340
- return /* @__PURE__ */ jsx(AuthContext.Provider, { value: authState, children });
1341
- };
1342
- var useAuth = () => {
1343
- return useContext(AuthContext);
1344
1340
  };
1345
1341
 
1346
- // src/auth/PermissionManager.ts
1347
- var PERMISSIONS_STORAGE_KEY = "auth_permissions";
1348
- var PermissionManager = class {
1349
- /**
1350
- * Saves an array of permission strings to local storage.
1351
- * @param permissions Array of permission strings.
1352
- */
1353
- static setPermissions(permissions) {
1354
- this.cachedPermissions = new Set(permissions);
1355
- if (typeof window === "undefined") return;
1356
- try {
1357
- localStorage.setItem(PERMISSIONS_STORAGE_KEY, JSON.stringify(permissions));
1358
- } catch (error) {
1359
- console.error("Failed to save permissions to localStorage", error);
1342
+ // src/auth/AuthService.ts
1343
+ var BASE_URL = "/openauth/v1";
1344
+ var AuthService = class _AuthService {
1345
+ constructor(client) {
1346
+ this.client = client;
1347
+ this.sessionManager = SessionManager.getInstance(client);
1348
+ }
1349
+ static getInstance(client) {
1350
+ if (!_AuthService.instance) {
1351
+ _AuthService.instance = new _AuthService(client);
1360
1352
  }
1353
+ return _AuthService.instance;
1361
1354
  }
1362
- /**
1363
- * Retrieves the currently stored permissions from local storage or memory cache.
1364
- * @returns Array of permission strings, or an empty array if none exist.
1365
- */
1366
- static getPermissions() {
1367
- if (this.cachedPermissions !== null) {
1368
- return Array.from(this.cachedPermissions);
1355
+ async signIn(request) {
1356
+ const response = await this.client.post(
1357
+ `${BASE_URL}/auth/signin`,
1358
+ request
1359
+ );
1360
+ if (response.data.accessToken) {
1361
+ this.sessionManager.save(response.data);
1362
+ }
1363
+ return response.data;
1364
+ }
1365
+ async refreshToken(request) {
1366
+ const refreshToken = this.sessionManager.getRefreshToken();
1367
+ if (!refreshToken) {
1368
+ throw new Error("No refresh token available");
1369
+ }
1370
+ const response = await this.client.post(
1371
+ `${BASE_URL}/auth/refresh`,
1372
+ { refreshToken, ...request }
1373
+ );
1374
+ if (response.data.accessToken) {
1375
+ this.sessionManager.patch({
1376
+ accessToken: response.data.accessToken,
1377
+ refreshToken: response.data.refreshToken
1378
+ });
1369
1379
  }
1370
- if (typeof window === "undefined") return [];
1380
+ return response.data;
1381
+ }
1382
+ async logout(request) {
1371
1383
  try {
1372
- const stored = localStorage.getItem(PERMISSIONS_STORAGE_KEY);
1373
- if (!stored) {
1374
- this.cachedPermissions = /* @__PURE__ */ new Set();
1375
- return [];
1376
- }
1377
- const parsed = JSON.parse(stored);
1378
- const permissionsArray = Array.isArray(parsed) ? parsed : [];
1379
- this.cachedPermissions = new Set(permissionsArray);
1380
- return permissionsArray;
1381
- } catch (error) {
1382
- console.error("Failed to parse permissions from localStorage", error);
1383
- this.cachedPermissions = /* @__PURE__ */ new Set();
1384
- return [];
1384
+ request.sessionId = this.sessionManager.getSessionId();
1385
+ const response = await this.client.post(
1386
+ `${BASE_URL}/auth/logout`,
1387
+ request || {}
1388
+ );
1389
+ return response.data;
1390
+ } finally {
1391
+ this.sessionManager.clear();
1385
1392
  }
1386
1393
  }
1387
- /**
1388
- * Clears all stored permissions from memory and local storage.
1389
- */
1390
- static clearPermissions() {
1391
- this.cachedPermissions = null;
1392
- if (typeof window === "undefined") return;
1393
- localStorage.removeItem(PERMISSIONS_STORAGE_KEY);
1394
+ async generateLoginToken(request) {
1395
+ const response = await this.client.put(
1396
+ `${BASE_URL}/auth/login-token`,
1397
+ request ?? {}
1398
+ );
1399
+ return response.data;
1394
1400
  }
1395
- /**
1396
- * Checks whether the given permission string exists in the currently stored permissions.
1397
- * @param permission The permission string to check for.
1398
- * @returns True if the permission exists, false otherwise.
1399
- */
1400
- static hasPermission(permission) {
1401
- if (this.cachedPermissions === null) {
1402
- this.getPermissions();
1401
+ async signInWithLoginToken(request) {
1402
+ const response = await this.client.post(
1403
+ `${BASE_URL}/auth/signin-with-token`,
1404
+ request
1405
+ );
1406
+ if (response.data.accessToken) {
1407
+ this.sessionManager.save(response.data);
1403
1408
  }
1404
- return this.cachedPermissions.has(permission);
1409
+ return response.data;
1410
+ }
1411
+ isAuthenticated() {
1412
+ return this.sessionManager.isAuthenticated();
1413
+ }
1414
+ getAccessToken() {
1415
+ return this.sessionManager.getAccessToken();
1416
+ }
1417
+ getSessionDetails() {
1418
+ return this.sessionManager.get();
1419
+ }
1420
+ getSessionId() {
1421
+ return this.sessionManager.getSessionId();
1422
+ }
1423
+ initializeAuth() {
1424
+ this.sessionManager.initialize();
1405
1425
  }
1406
1426
  };
1407
- PermissionManager.cachedPermissions = null;
1408
1427
 
1409
- export { AuthProvider, ConfirmDialog, HttpClient, LocalStorage, NotificationProvider, PermissionManager, ReadmeViewer_default as ReadmeViewer, SidebarLayout, ThemeProvider, ThemeToggle, borderRadius, cn, darkTheme, debounce, elevation, fontSize, fontWeight, formatDate, getHighlighter, lightTheme, lineHeight, spacing, throttle, tokens_exports as tokens, transition, useAuth, useNotification, useTheme, zIndex };
1428
+ export { AuthService, ConfirmDialog, HttpClient, LocalStorage, NotificationProvider, ReadmeViewer_default as ReadmeViewer, SessionManager, SidebarLayout, ThemeProvider, ThemeToggle, borderRadius, cn, darkTheme, debounce, elevation, extractErrorMessage, fontSize, fontWeight, formatDate, getHighlighter, lightTheme, lineHeight, spacing, throttle, tokens_exports as tokens, transition, useNotification, useTheme, zIndex };
1410
1429
  //# sourceMappingURL=index.mjs.map
1411
1430
  //# sourceMappingURL=index.mjs.map