@flexbe/sdk 0.1.2 → 0.1.3

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.
@@ -1,9 +1,14 @@
1
1
  const TOKEN_STORAGE_KEY = 'flexbe_jwt_token';
2
2
  const REFRESH_THRESHOLD = 0.8; // Refresh when 80% of token lifetime has passed
3
+ const REFRESH_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds
4
+ const MAX_REFRESH_DELAY = 10000; // Maximum random delay of 10 seconds
3
5
  export class TokenManager {
4
6
  constructor() {
5
7
  this.token = null;
6
8
  this.refreshInterval = null;
9
+ this.refreshTimeout = null;
10
+ this.tokenPromise = null;
11
+ this.debug = false;
7
12
  this.initializeFromStorage();
8
13
  this.setupStorageListener();
9
14
  }
@@ -14,59 +19,61 @@ export class TokenManager {
14
19
  return TokenManager.instance;
15
20
  }
16
21
  initializeFromStorage() {
17
- if (typeof window !== 'undefined') {
18
- const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
19
- if (storedToken) {
20
- try {
21
- this.token = JSON.parse(storedToken);
22
- if (this.token.expiresAt > Date.now()) {
23
- console.log('Reusing stored token:', {
24
- expiresIn: `${Math.round((this.token.expiresAt - Date.now()) / 1000)} seconds`,
25
- expiresAt: new Date(this.token.expiresAt).toISOString(),
26
- });
27
- this.startRefreshInterval();
28
- }
29
- else {
30
- this.clearToken();
31
- }
32
- }
33
- catch (error) {
34
- console.error('Failed to parse stored token:', error);
35
- this.clearToken();
36
- }
22
+ if (typeof window === 'undefined')
23
+ return;
24
+ const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
25
+ if (!storedToken)
26
+ return;
27
+ try {
28
+ this.token = JSON.parse(storedToken);
29
+ if (this.token.expiresAt > Date.now()) {
30
+ this.logTokenStatus('Token loaded from storage');
31
+ this.startRefreshInterval();
32
+ }
33
+ else {
34
+ this.clearToken();
37
35
  }
38
36
  }
37
+ catch (error) {
38
+ console.error('Failed to parse stored token:', error);
39
+ this.clearToken();
40
+ }
39
41
  }
40
42
  setupStorageListener() {
41
- if (typeof window !== 'undefined') {
42
- window.addEventListener('storage', (event) => {
43
- if (event.key === TOKEN_STORAGE_KEY) {
44
- if (event.newValue) {
45
- try {
46
- const newToken = JSON.parse(event.newValue);
47
- if (newToken.expiresAt > Date.now()) {
48
- this.token = newToken;
49
- console.log('Token updated from storage:', {
50
- expiresIn: `${Math.round((newToken.expiresAt - Date.now()) / 1000)} seconds`,
51
- expiresAt: new Date(newToken.expiresAt).toISOString(),
52
- });
53
- this.startRefreshInterval();
54
- }
55
- else {
56
- this.clearToken();
57
- }
58
- }
59
- catch (error) {
60
- console.error('Failed to parse token from storage event:', error);
61
- this.clearToken();
62
- }
63
- }
64
- else {
65
- this.clearToken();
66
- }
43
+ if (typeof window === 'undefined')
44
+ return;
45
+ window.addEventListener('storage', (event) => {
46
+ if (event.key !== TOKEN_STORAGE_KEY)
47
+ return;
48
+ if (!event.newValue) {
49
+ this.clearToken();
50
+ void this.retrieveToken();
51
+ return;
52
+ }
53
+ try {
54
+ const newToken = JSON.parse(event.newValue);
55
+ // Skip if the new token is exactly the same as current token
56
+ if (this.token &&
57
+ this.token.accessToken === newToken.accessToken &&
58
+ this.token.expiresAt === newToken.expiresAt) {
59
+ return;
67
60
  }
68
- });
69
- }
61
+ if (newToken.expiresAt > Date.now()) {
62
+ this.token = newToken;
63
+ this.logTokenStatus('Token updated from storage');
64
+ this.startRefreshInterval();
65
+ }
66
+ else {
67
+ this.clearToken();
68
+ void this.retrieveToken();
69
+ }
70
+ }
71
+ catch (error) {
72
+ console.error('Failed to parse token from storage event:', error);
73
+ this.clearToken();
74
+ void this.retrieveToken();
75
+ }
76
+ });
70
77
  }
71
78
  getExpirationFromToken(token) {
72
79
  try {
@@ -79,32 +86,125 @@ export class TokenManager {
79
86
  return Date.now() + (4 * 60 * 1000); // Default to 4 minutes if parsing fails
80
87
  }
81
88
  }
89
+ async getToken() {
90
+ const token = this.token;
91
+ if (token && token.expiresAt && token.expiresAt > Date.now()) {
92
+ return token.accessToken;
93
+ }
94
+ await this.retrieveToken();
95
+ return this.token?.accessToken ?? null;
96
+ }
97
+ async retrieveToken() {
98
+ if (this.tokenPromise) {
99
+ await this.tokenPromise;
100
+ return;
101
+ }
102
+ this.tokenPromise = this.doRetrieveToken();
103
+ try {
104
+ await this.tokenPromise;
105
+ }
106
+ finally {
107
+ this.tokenPromise = null;
108
+ }
109
+ }
110
+ async doRetrieveToken() {
111
+ const controller = new AbortController();
112
+ const timeoutId = setTimeout(() => controller.abort(), 30000);
113
+ try {
114
+ const response = await fetch('/oauth/token', {
115
+ method: 'POST',
116
+ headers: { 'Content-Type': 'application/json' },
117
+ body: JSON.stringify({ grant_type: 'client_credentials' }),
118
+ credentials: 'include',
119
+ signal: controller.signal,
120
+ });
121
+ clearTimeout(timeoutId);
122
+ if (!response.ok) {
123
+ const errorData = await response.json().catch(() => ({ message: response.statusText }));
124
+ throw new Error(errorData.message || response.statusText);
125
+ }
126
+ const data = await response.json();
127
+ this.setToken(data);
128
+ }
129
+ catch (error) {
130
+ console.error('Failed to retrieve token:', error);
131
+ this.clearToken();
132
+ throw error;
133
+ }
134
+ }
82
135
  startRefreshInterval() {
136
+ this.clearRefreshTimers();
137
+ if (!this.token)
138
+ return;
139
+ const tokenLifetime = this.token.expiresAt - Date.now();
140
+ const refreshThreshold = Math.round(tokenLifetime * REFRESH_THRESHOLD);
141
+ const timeUntilRefresh = refreshThreshold - (Math.random() * MAX_REFRESH_DELAY);
142
+ this.logTokenStatus('Starting refresh interval', {
143
+ tokenLifetime: `${Math.round(tokenLifetime / 1000)} seconds`,
144
+ refreshThreshold: `${Math.round(refreshThreshold / 1000)} seconds`,
145
+ timeUntilRefresh: `${Math.round(timeUntilRefresh / 1000)} seconds`,
146
+ });
147
+ this.scheduleRefresh(timeUntilRefresh);
148
+ this.refreshInterval = window.setInterval(() => {
149
+ if (!this.token)
150
+ return;
151
+ const timeUntilExpiry = this.token.expiresAt - Date.now();
152
+ if (timeUntilExpiry <= 0) {
153
+ this.logTokenStatus('Token expired');
154
+ this.clearToken();
155
+ void this.retrieveToken();
156
+ return;
157
+ }
158
+ const refreshThreshold = Math.round(timeUntilExpiry * REFRESH_THRESHOLD);
159
+ if (timeUntilExpiry <= refreshThreshold) {
160
+ this.logTokenStatus('Refreshing token', {
161
+ timeUntilExpiry: `${Math.round(timeUntilExpiry / 1000)} seconds`,
162
+ refreshThreshold: `${Math.round(refreshThreshold / 1000)} seconds`,
163
+ });
164
+ this.scheduleRefresh(refreshThreshold - (Math.random() * MAX_REFRESH_DELAY));
165
+ }
166
+ }, REFRESH_CHECK_INTERVAL);
167
+ }
168
+ scheduleRefresh(delay) {
169
+ if (this.refreshTimeout) {
170
+ window.clearTimeout(this.refreshTimeout);
171
+ }
172
+ this.refreshTimeout = window.setTimeout(() => {
173
+ const token = this.token;
174
+ if (token && token.expiresAt - Date.now() <= token.expiresAt * REFRESH_THRESHOLD) {
175
+ void this.retrieveToken();
176
+ }
177
+ }, delay);
178
+ }
179
+ clearRefreshTimers() {
83
180
  if (this.refreshInterval) {
84
181
  clearInterval(this.refreshInterval);
182
+ this.refreshInterval = null;
85
183
  }
86
- if (this.token) {
87
- const tokenLifetime = this.token.expiresAt - (this.token.expiresAt - 4 * 60 * 1000); // 4 minutes in milliseconds
88
- const refreshTime = Math.round(tokenLifetime * REFRESH_THRESHOLD);
89
- console.log('Setting up token refresh:', {
90
- tokenLifetime: `${Math.round(tokenLifetime / 1000)} seconds`,
91
- refreshIn: `${Math.round(refreshTime / 1000)} seconds`,
92
- refreshAt: new Date(Date.now() + refreshTime).toISOString(),
93
- });
94
- this.refreshInterval = window.setInterval(() => {
95
- this.clearToken();
96
- }, refreshTime);
184
+ if (this.refreshTimeout) {
185
+ window.clearTimeout(this.refreshTimeout);
186
+ this.refreshTimeout = null;
97
187
  }
98
188
  }
189
+ logTokenStatus(message, additionalInfo = {}) {
190
+ if (!this.debug)
191
+ return;
192
+ const token = this.token;
193
+ if (!token)
194
+ return;
195
+ console.log(message, {
196
+ expiresIn: `${Math.round((token.expiresAt - Date.now()) / 1000)} seconds`,
197
+ expiresAt: new Date(token.expiresAt).toISOString(),
198
+ ...additionalInfo,
199
+ });
200
+ }
99
201
  setToken(tokenResponse) {
100
202
  const expiresAt = this.getExpirationFromToken(tokenResponse.accessToken);
101
203
  this.token = {
102
204
  accessToken: tokenResponse.accessToken,
103
205
  expiresAt,
104
206
  };
105
- const expiresIn = Math.round((expiresAt - Date.now()) / 1000);
106
- console.log('New access token obtained:', {
107
- expiresIn: `${expiresIn} seconds`,
207
+ this.logTokenStatus('Token set', {
108
208
  expiresAt: new Date(expiresAt).toISOString(),
109
209
  });
110
210
  if (typeof window !== 'undefined') {
@@ -112,19 +212,9 @@ export class TokenManager {
112
212
  }
113
213
  this.startRefreshInterval();
114
214
  }
115
- getToken() {
116
- if (this.token && this.token.expiresAt > Date.now()) {
117
- return this.token.accessToken;
118
- }
119
- this.clearToken();
120
- return null;
121
- }
122
215
  clearToken() {
123
216
  this.token = null;
124
- if (this.refreshInterval) {
125
- clearInterval(this.refreshInterval);
126
- this.refreshInterval = null;
127
- }
217
+ this.clearRefreshTimers();
128
218
  if (typeof window !== 'undefined') {
129
219
  localStorage.removeItem(TOKEN_STORAGE_KEY);
130
220
  }
@@ -1 +1,5 @@
1
- export {};
1
+ export var FlexbeAuthType;
2
+ (function (FlexbeAuthType) {
3
+ FlexbeAuthType["API_KEY"] = "apiKey";
4
+ FlexbeAuthType["BEARER"] = "bearer";
5
+ })(FlexbeAuthType || (FlexbeAuthType = {}));
@@ -3,10 +3,9 @@ export declare class FlexbeAuth {
3
3
  private readonly config;
4
4
  private readonly tokenManager;
5
5
  private initialized;
6
- private initializing;
6
+ private initializationPromise;
7
7
  constructor(config: FlexbeConfig);
8
- private initializeBearerAuth;
8
+ private initialize;
9
9
  ensureInitialized(): Promise<void>;
10
10
  getAuthHeaders(): Promise<Record<string, string>>;
11
- isInitialized(): boolean;
12
11
  }
@@ -3,13 +3,21 @@ export declare class TokenManager {
3
3
  private static instance;
4
4
  private token;
5
5
  private refreshInterval;
6
+ private refreshTimeout;
7
+ private tokenPromise;
8
+ private debug;
6
9
  private constructor();
7
10
  static getInstance(): TokenManager;
8
11
  private initializeFromStorage;
9
12
  private setupStorageListener;
10
13
  private getExpirationFromToken;
14
+ getToken(): Promise<string | null>;
15
+ private retrieveToken;
16
+ private doRetrieveToken;
11
17
  private startRefreshInterval;
18
+ private scheduleRefresh;
19
+ private clearRefreshTimers;
20
+ private logTokenStatus;
12
21
  setToken(tokenResponse: TokenResponse): void;
13
- getToken(): string | null;
14
22
  clearToken(): void;
15
23
  }
@@ -1,3 +1,7 @@
1
+ export declare enum FlexbeAuthType {
2
+ API_KEY = "apiKey",
3
+ BEARER = "bearer"
4
+ }
1
5
  export interface FlexbeConfig {
2
6
  apiKey?: string;
3
7
  baseUrl?: string;
@@ -21,7 +25,6 @@ export interface FlexbeError {
21
25
  status?: number;
22
26
  details?: unknown;
23
27
  }
24
- export type FlexbeAuthType = 'apiKey' | 'bearer';
25
28
  export interface JwtToken {
26
29
  accessToken: string;
27
30
  expiresAt: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flexbe/sdk",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "TypeScript SDK for Flexbe API",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",