@gofreego/tsutils 0.1.13 → 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
@@ -1269,162 +1269,162 @@ function formatDate(date, options = {
1269
1269
  const dateObj = typeof date === "string" || typeof date === "number" ? new Date(date) : date;
1270
1270
  return new Intl.DateTimeFormat("en-US", options).format(dateObj);
1271
1271
  }
1272
- function getCookie(name) {
1273
- if (typeof document === "undefined") return null;
1274
- const value = `; ${document.cookie}`;
1275
- const parts = value.split(`; ${name}=`);
1276
- if (parts.length === 2) return parts.pop()?.split(";").shift() || null;
1277
- return null;
1278
- }
1279
- function decodeJWT(token) {
1280
- try {
1281
- const base64Url = token.split(".")[1];
1282
- if (!base64Url) return null;
1283
- const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
1284
- const jsonPayload = decodeURIComponent(
1285
- window.atob(base64).split("").map(function(c) {
1286
- return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
1287
- }).join("")
1288
- );
1289
- return JSON.parse(jsonPayload);
1290
- } catch (e) {
1291
- 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;
1292
1280
  }
1293
- }
1294
- var AuthContext = createContext({
1295
- isAuthenticated: false,
1296
- isLoading: true
1297
- });
1298
- var AuthProvider = ({
1299
- cookieName = "authorization",
1300
- redirectUrl,
1301
- children,
1302
- onAuthFail,
1303
- onAuthSuccess,
1304
- loadingElement = null
1305
- }) => {
1306
- const [authState, setAuthState] = useState({
1307
- isAuthenticated: false,
1308
- isLoading: true
1309
- // starts loading until cookie check completes
1310
- });
1311
- const [authFailed, setAuthFailed] = useState(false);
1312
- useEffect(() => {
1313
- const verifyAuth = () => {
1314
- const token = getCookie(cookieName);
1315
- if (!token) {
1316
- handleFail();
1317
- return;
1318
- }
1319
- const decoded = decodeJWT(token);
1320
- if (!decoded) {
1321
- handleFail();
1322
- return;
1323
- }
1324
- if (decoded.exp) {
1325
- const expirationDate = new Date(decoded.exp * 1e3);
1326
- if (expirationDate < /* @__PURE__ */ new Date()) {
1327
- handleFail();
1328
- return;
1329
- }
1330
- }
1331
- setAuthState({
1332
- isAuthenticated: true,
1333
- isLoading: false
1334
- });
1335
- if (onAuthSuccess) {
1336
- onAuthSuccess();
1337
- }
1338
- };
1339
- verifyAuth();
1340
- }, [cookieName]);
1341
- const handleFail = () => {
1342
- setAuthState({
1343
- isAuthenticated: false,
1344
- isLoading: false
1345
- });
1346
- setAuthFailed(true);
1347
- if (onAuthFail) {
1348
- onAuthFail();
1349
- } else if (redirectUrl && typeof window !== "undefined") {
1350
- window.location.href = redirectUrl;
1281
+ static getInstance(client) {
1282
+ if (!_SessionManager.instance) {
1283
+ _SessionManager.instance = new _SessionManager(client);
1351
1284
  }
1352
- };
1353
- if (authState.isLoading || authFailed && !onAuthFail) {
1354
- return /* @__PURE__ */ jsx(Fragment, { children: loadingElement });
1285
+ return _SessionManager.instance;
1355
1286
  }
1356
- if (authFailed && onAuthFail) {
1357
- 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");
1358
1339
  }
1359
- return /* @__PURE__ */ jsx(AuthContext.Provider, { value: authState, children });
1360
- };
1361
- var useAuth = () => {
1362
- return useContext(AuthContext);
1363
1340
  };
1364
1341
 
1365
- // src/auth/PermissionManager.ts
1366
- var PERMISSIONS_STORAGE_KEY = "auth_permissions";
1367
- var PermissionManager = class {
1368
- /**
1369
- * Saves an array of permission strings to local storage.
1370
- * @param permissions Array of permission strings.
1371
- */
1372
- static setPermissions(permissions) {
1373
- this.cachedPermissions = new Set(permissions);
1374
- if (typeof window === "undefined") return;
1375
- try {
1376
- localStorage.setItem(PERMISSIONS_STORAGE_KEY, JSON.stringify(permissions));
1377
- } catch (error) {
1378
- 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);
1379
1352
  }
1353
+ return _AuthService.instance;
1380
1354
  }
1381
- /**
1382
- * Retrieves the currently stored permissions from local storage or memory cache.
1383
- * @returns Array of permission strings, or an empty array if none exist.
1384
- */
1385
- static getPermissions() {
1386
- if (this.cachedPermissions !== null) {
1387
- 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
+ });
1388
1379
  }
1389
- if (typeof window === "undefined") return [];
1380
+ return response.data;
1381
+ }
1382
+ async logout(request) {
1390
1383
  try {
1391
- const stored = localStorage.getItem(PERMISSIONS_STORAGE_KEY);
1392
- if (!stored) {
1393
- this.cachedPermissions = /* @__PURE__ */ new Set();
1394
- return [];
1395
- }
1396
- const parsed = JSON.parse(stored);
1397
- const permissionsArray = Array.isArray(parsed) ? parsed : [];
1398
- this.cachedPermissions = new Set(permissionsArray);
1399
- return permissionsArray;
1400
- } catch (error) {
1401
- console.error("Failed to parse permissions from localStorage", error);
1402
- this.cachedPermissions = /* @__PURE__ */ new Set();
1403
- 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();
1404
1392
  }
1405
1393
  }
1406
- /**
1407
- * Clears all stored permissions from memory and local storage.
1408
- */
1409
- static clearPermissions() {
1410
- this.cachedPermissions = null;
1411
- if (typeof window === "undefined") return;
1412
- 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;
1413
1400
  }
1414
- /**
1415
- * Checks whether the given permission string exists in the currently stored permissions.
1416
- * @param permission The permission string to check for.
1417
- * @returns True if the permission exists, false otherwise.
1418
- */
1419
- static hasPermission(permission) {
1420
- if (this.cachedPermissions === null) {
1421
- 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);
1422
1408
  }
1423
- 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();
1424
1425
  }
1425
1426
  };
1426
- PermissionManager.cachedPermissions = null;
1427
1427
 
1428
- export { AuthProvider, ConfirmDialog, HttpClient, LocalStorage, NotificationProvider, PermissionManager, ReadmeViewer_default as ReadmeViewer, SidebarLayout, ThemeProvider, ThemeToggle, borderRadius, cn, darkTheme, debounce, elevation, extractErrorMessage, 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 };
1429
1429
  //# sourceMappingURL=index.mjs.map
1430
1430
  //# sourceMappingURL=index.mjs.map