@go-avro/avro-js 0.0.2-beta.12 → 0.0.2-beta.120

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 (51) hide show
  1. package/README.md +1 -0
  2. package/dist/auth/AuthManager.d.ts +12 -3
  3. package/dist/auth/AuthManager.js +56 -12
  4. package/dist/auth/storage.d.ts +8 -8
  5. package/dist/auth/storage.js +12 -10
  6. package/dist/client/QueryClient.d.ts +385 -15
  7. package/dist/client/QueryClient.js +323 -203
  8. package/dist/client/core/fetch.d.ts +1 -0
  9. package/dist/client/core/fetch.js +62 -0
  10. package/dist/client/core/utils.d.ts +1 -0
  11. package/dist/client/core/utils.js +14 -0
  12. package/dist/client/core/xhr.d.ts +1 -0
  13. package/dist/client/core/xhr.js +84 -0
  14. package/dist/client/hooks/analytics.d.ts +1 -0
  15. package/dist/client/hooks/analytics.js +26 -0
  16. package/dist/client/hooks/avro.d.ts +1 -0
  17. package/dist/client/hooks/avro.js +9 -0
  18. package/dist/client/hooks/bills.d.ts +1 -0
  19. package/dist/client/hooks/bills.js +164 -0
  20. package/dist/client/hooks/chats.d.ts +1 -0
  21. package/dist/client/hooks/chats.js +37 -0
  22. package/dist/client/hooks/companies.d.ts +1 -0
  23. package/dist/client/hooks/companies.js +138 -0
  24. package/dist/client/hooks/events.d.ts +1 -0
  25. package/dist/client/hooks/events.js +307 -0
  26. package/dist/client/hooks/jobs.d.ts +1 -0
  27. package/dist/client/hooks/jobs.js +219 -0
  28. package/dist/client/hooks/messages.d.ts +1 -0
  29. package/dist/client/hooks/messages.js +30 -0
  30. package/dist/client/hooks/months.d.ts +1 -0
  31. package/dist/client/hooks/months.js +92 -0
  32. package/dist/client/hooks/plans.d.ts +1 -0
  33. package/dist/client/hooks/plans.js +8 -0
  34. package/dist/client/hooks/root.d.ts +1 -0
  35. package/dist/client/hooks/root.js +8 -0
  36. package/dist/client/hooks/routes.d.ts +1 -0
  37. package/dist/client/hooks/routes.js +167 -0
  38. package/dist/client/hooks/sessions.d.ts +1 -0
  39. package/dist/client/hooks/sessions.js +175 -0
  40. package/dist/client/hooks/teams.d.ts +1 -0
  41. package/dist/client/hooks/teams.js +127 -0
  42. package/dist/client/hooks/users.d.ts +1 -0
  43. package/dist/client/hooks/users.js +104 -0
  44. package/dist/index.d.ts +21 -1
  45. package/dist/index.js +21 -1
  46. package/dist/types/api.d.ts +123 -32
  47. package/dist/types/api.js +10 -1
  48. package/dist/types/auth.d.ts +0 -5
  49. package/dist/types/cache.d.ts +9 -0
  50. package/dist/types/cache.js +1 -0
  51. package/package.json +6 -4
@@ -1,241 +1,280 @@
1
+ import io from 'socket.io-client';
2
+ import { useMutation } from '@tanstack/react-query';
3
+ import { LoginResponse } from '../types/api';
1
4
  import { StandardError } from '../types/error';
2
5
  export class AvroQueryClient {
3
6
  constructor(config) {
7
+ this._isAuthenticated = false;
8
+ this.companyId = null;
4
9
  this.config = {
5
10
  baseUrl: config.baseUrl,
6
11
  authManager: config.authManager,
12
+ queryClient: config.queryClient,
7
13
  maxRetries: config.maxRetries ?? 3,
8
14
  retryStrategy: config.retryStrategy ?? 'fixed',
9
15
  timeout: config.timeout ?? 0,
10
16
  };
11
- }
12
- getDelay(strategy, attempt) {
13
- if (typeof strategy === 'function') {
14
- return strategy(attempt);
15
- }
16
- else if (strategy === 'fixed') {
17
- return 1000;
17
+ config.authManager.isAuthenticated().then(isAuth => {
18
+ this._isAuthenticated = isAuth;
19
+ });
20
+ config.authManager.getCompanyId().then(companyId => {
21
+ this.companyId = companyId;
22
+ });
23
+ this.socket = io(config.baseUrl, { autoConnect: false, transports: ["websocket"], });
24
+ if (!this.socket.connected) {
25
+ this.config.authManager.accessToken().then(token => {
26
+ console.log('Initializing socket connection with token...');
27
+ this.socket.auth = { token: token };
28
+ this.socket.connect();
29
+ });
18
30
  }
19
- else if (strategy === 'exponential') {
20
- return Math.pow(2, attempt) * 100;
31
+ this.socket.on('connect', () => {
32
+ this._isAuthenticated = true;
33
+ console.log(`Socket connected with ID: ${this.socket?.id}`);
34
+ });
35
+ this.socket.on('disconnect', (reason) => {
36
+ console.log(`Socket disconnected: ${reason}`);
37
+ });
38
+ this.socket.on('connect_error', (err) => {
39
+ console.error(`Socket connection error: ${err.message}`);
40
+ });
41
+ this.config.authManager.onTokenRefreshed((newAccessToken) => {
42
+ if (this.socket && newAccessToken) {
43
+ this._isAuthenticated = true;
44
+ console.log('Access token refreshed, updating socket auth...');
45
+ this.socket.auth = { token: newAccessToken };
46
+ this.socket.disconnect().connect();
47
+ }
48
+ });
49
+ config.authManager.onTokenRefreshFailed(() => {
50
+ this._isAuthenticated = false;
51
+ if (this.socket && this.socket.connected) {
52
+ this.socket.disconnect();
53
+ }
54
+ });
55
+ }
56
+ emit(eventName, data) {
57
+ if (!this.socket?.connected) {
58
+ console.error('Socket is not connected. Cannot emit event.');
59
+ return;
21
60
  }
22
- throw new Error(`Invalid retry strategy: ${strategy}`);
61
+ this.socket.emit(eventName, data);
23
62
  }
24
- _xhr(method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
25
- const checkCancelled = () => {
26
- if (cancelToken?.isCancelled()) {
27
- return new StandardError(0, 'Request cancelled');
28
- }
29
- return null;
30
- };
31
- return this.config.authManager.accessToken().then(token => {
32
- return new Promise((resolve, reject) => {
33
- const cancelErr = checkCancelled();
34
- if (cancelErr)
35
- return reject(cancelErr);
36
- const xhr = new XMLHttpRequest();
37
- const url = this.config.baseUrl + path;
38
- xhr.open(method, url, true);
39
- if (token) {
40
- xhr.setRequestHeader('Authorization', `Bearer ${token}`);
41
- }
42
- Object.entries(headers).forEach(([key, value]) => {
43
- xhr.setRequestHeader(key, value);
44
- });
45
- xhr.onload = () => {
46
- const cancelErr = checkCancelled();
47
- if (cancelErr)
48
- return reject(cancelErr);
49
- if (xhr.status === 401 && this.config.authManager.refreshTokens && retryCount === 0) {
50
- this.config.authManager
51
- .refreshTokens()
52
- .then(() => {
53
- this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
54
- })
55
- .catch(() => {
56
- reject(new StandardError(401, 'Unauthorized (refresh failed)'));
57
- });
58
- return;
59
- }
60
- if (xhr.status >= 200 && xhr.status < 300) {
61
- try {
62
- resolve(JSON.parse(xhr.responseText));
63
- }
64
- catch {
65
- resolve(xhr.responseText);
66
- }
67
- }
68
- else {
69
- if (retryCount < this.config.maxRetries) {
70
- const delay = this.getDelay(this.config.retryStrategy, retryCount);
71
- setTimeout(() => {
72
- this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
73
- }, delay);
74
- }
75
- else {
76
- let msg = xhr.statusText;
77
- try {
78
- const parsed = JSON.parse(xhr.responseText);
79
- msg = parsed.message || msg;
80
- }
81
- catch {
82
- console.warn('Failed to parse error response:', xhr.responseText);
83
- }
84
- reject(new StandardError(xhr.status, msg));
85
- }
86
- }
87
- };
88
- xhr.onerror = () => {
89
- if (retryCount < this.config.maxRetries) {
90
- const delay = this.getDelay(this.config.retryStrategy, retryCount);
91
- setTimeout(() => {
92
- this._xhr(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1).then(resolve, reject);
93
- }, delay);
94
- }
95
- else {
96
- reject(new StandardError(0, 'Network Error'));
63
+ on(eventName, callback) {
64
+ this.socket?.on(eventName, callback);
65
+ }
66
+ off(eventName, callback) {
67
+ this.socket?.off(eventName, callback);
68
+ }
69
+ get(path, cancelToken, headers = {}, progressUpdateCallback) {
70
+ return this._xhr('GET', path, null, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
71
+ }
72
+ post(path, data, cancelToken, headers = {}, progressUpdateCallback) {
73
+ return this._xhr('POST', path, data, cancelToken, headers, false, this.config.maxRetries, progressUpdateCallback);
74
+ }
75
+ put(path, data, cancelToken, headers = {}, progressUpdateCallback) {
76
+ return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
77
+ }
78
+ delete(path, cancelToken, headers = {}, progressUpdateCallback) {
79
+ return this._xhr('DELETE', path, null, cancelToken, headers, false, this.config.maxRetries, progressUpdateCallback);
80
+ }
81
+ useLogin() {
82
+ const queryClient = this.getQueryClient();
83
+ return useMutation({
84
+ mutationFn: async ({ username, password, code, cancelToken }) => {
85
+ const resp = await this.post('/login', JSON.stringify({ username, password, code }), cancelToken, { 'Content-Type': 'application/json' });
86
+ if (!resp || !('access_token' in resp)) {
87
+ if (resp.msg === "TOTP required") {
88
+ return LoginResponse.NEEDS_TOTP;
97
89
  }
98
- };
99
- if (this.config.timeout) {
100
- xhr.timeout = this.config.timeout;
101
- xhr.ontimeout = () => reject(new StandardError(0, 'Request timed out'));
90
+ throw new StandardError(401, 'Invalid login response');
102
91
  }
103
- xhr.send(body);
104
- });
105
- });
106
- }
107
- _fetch(method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
108
- const checkCancelled = () => {
109
- try {
110
- if (cancelToken?.isCancelled()) {
111
- return new StandardError(0, 'Request cancelled');
92
+ this._isAuthenticated = true;
93
+ this.socket.auth = { token: resp.access_token };
94
+ if (!this.socket.connected) {
95
+ this.socket.connect();
112
96
  }
97
+ await this.config.authManager.setTokens({ access_token: resp.access_token, refresh_token: resp.refresh_token });
98
+ return LoginResponse.SUCCESS;
99
+ },
100
+ onSettled: () => {
101
+ queryClient.invalidateQueries();
102
+ },
103
+ onError: (err) => {
104
+ this.config.authManager.clearCache();
105
+ throw new StandardError(401, err.message || 'Login failed');
113
106
  }
114
- catch (error) {
115
- throw new StandardError(0, `Error checking cancellation (${typeof cancelToken}): ${error}`);
107
+ });
108
+ }
109
+ useRequestCode() {
110
+ const queryClient = this.getQueryClient();
111
+ return useMutation({
112
+ mutationFn: async ({ username, email, cancelToken }) => {
113
+ const resp = await this.post('/code', JSON.stringify({ username, email }), cancelToken, { 'Content-Type': 'application/json' });
114
+ return resp;
115
+ },
116
+ onSettled: () => {
117
+ queryClient.invalidateQueries();
118
+ },
119
+ onError: (err) => {
120
+ throw new StandardError(err.status, err.message || 'Request code failed');
116
121
  }
117
- return null;
118
- };
119
- return this.config.authManager.accessToken().then(token => {
120
- const cancelErr = checkCancelled();
121
- if (cancelErr)
122
- return Promise.reject(cancelErr);
123
- const url = this.config.baseUrl + path;
124
- const requestHeaders = {
125
- 'Content-Type': 'application/json',
126
- ...headers,
127
- };
128
- if (token) {
129
- requestHeaders['Authorization'] = `Bearer ${token}`;
122
+ });
123
+ }
124
+ useUpdatePassword() {
125
+ const queryClient = this.getQueryClient();
126
+ return useMutation({
127
+ mutationFn: async ({ username, email, code, newPassword, cancelToken }) => {
128
+ await this.post(`/user/${username ?? email}/password`, JSON.stringify({ code, password: newPassword }), cancelToken, { 'Content-Type': 'application/json' });
129
+ },
130
+ onSettled: () => {
131
+ queryClient.invalidateQueries();
132
+ },
133
+ onError: (err) => {
134
+ throw new StandardError(err.status, err.message || 'Update password failed');
130
135
  }
131
- const options = {
132
- method,
133
- headers: requestHeaders,
134
- body: body ? JSON.stringify(body) : null,
135
- };
136
- return fetch(url, options).then(response => {
137
- if (response.status === 401 && this.config.authManager.refreshTokens && retryCount === 0) {
138
- return this.config.authManager
139
- .refreshTokens()
140
- .then(() => this._fetch(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1))
141
- .catch(() => Promise.reject(new StandardError(401, 'Unauthorized (refresh failed)')));
142
- }
143
- if (!response.ok) {
144
- if (retryCount < this.config.maxRetries) {
145
- const delay = this.getDelay(this.config.retryStrategy, retryCount);
146
- return new Promise((resolve, reject) => {
147
- setTimeout(() => {
148
- this._fetch(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1)
149
- .then(resolve)
150
- .catch(reject);
151
- }, delay);
152
- });
153
- }
154
- else {
155
- return response.text().then(text => {
156
- let msg = response.statusText;
157
- try {
158
- const parsed = JSON.parse(text);
159
- msg = parsed.message || msg;
160
- }
161
- catch {
162
- console.warn('Failed to parse error response:', text);
163
- }
164
- throw new StandardError(response.status, msg);
165
- });
136
+ });
137
+ }
138
+ useGoogleLogin() {
139
+ const queryClient = this.getQueryClient();
140
+ return useMutation({
141
+ mutationFn: async ({ token, cancelToken }) => {
142
+ const resp = await this._xhr('POST', `/google/authorize?token=${token}`, {}, cancelToken, { 'Content-Type': 'application/json' });
143
+ if (!resp || !('access_token' in resp)) {
144
+ if (resp.msg === "TOTP required") {
145
+ return LoginResponse.NEEDS_TOTP;
166
146
  }
147
+ throw new StandardError(401, 'Invalid Google login response');
167
148
  }
168
- return response.json();
169
- });
149
+ this._isAuthenticated = true;
150
+ this.socket.auth = { token: resp.access_token };
151
+ if (!this.socket.connected) {
152
+ this.socket.connect();
153
+ }
154
+ await this.config.authManager.setTokens({ access_token: resp.access_token, refresh_token: resp.refresh_token });
155
+ return LoginResponse.SUCCESS;
156
+ },
157
+ onSettled: () => {
158
+ queryClient.invalidateQueries();
159
+ },
160
+ onError: (err) => {
161
+ this.config.authManager.clearCache();
162
+ throw new StandardError(err.status, err.message || 'Google Login failed');
163
+ }
170
164
  });
171
165
  }
172
- get(path, cancelToken, headers = {}) {
173
- return this._xhr('GET', path, null, cancelToken, headers, true);
166
+ setTokens(tokens) {
167
+ return this.config.authManager.setTokens(tokens);
168
+ }
169
+ setCache(data) {
170
+ return this.config.authManager.setCache(data);
171
+ }
172
+ getCache(key) {
173
+ return this.config.authManager.getCache(key);
174
174
  }
175
- post(path, data, cancelToken, headers = {}) {
176
- return this._xhr('POST', path, data, cancelToken, headers, false);
175
+ setCompanyId(companyId) {
176
+ this.companyId = companyId;
177
+ return this.config.authManager.setCompanyId(companyId);
177
178
  }
178
- put(path, data, cancelToken, headers = {}) {
179
- return this._xhr('PUT', path, data, cancelToken, headers, true);
179
+ clearCache() {
180
+ return this.config.authManager.clearCache();
180
181
  }
181
- delete(path, cancelToken, headers = {}) {
182
- return this._xhr('DELETE', path, null, cancelToken, headers, false);
182
+ isAuthenticated() {
183
+ return this._isAuthenticated;
183
184
  }
184
- login(data, cancelToken) {
185
- return this._fetch('POST', '/login', data, cancelToken)
186
- .then(tokens => {
187
- if (!tokens || !tokens.access_token || !tokens.refresh_token) {
188
- throw new StandardError(401, 'Invalid login response');
185
+ isAuthenticatedAsync() {
186
+ return this.config.authManager.isAuthenticated();
187
+ }
188
+ getQueryClient() {
189
+ return this.config.queryClient;
190
+ }
191
+ useLogout() {
192
+ const queryClient = this.getQueryClient();
193
+ return useMutation({
194
+ mutationFn: async (cancelToken) => {
195
+ await this.post('/logout', null, cancelToken);
196
+ await this.config.authManager.clearCache();
197
+ if (this.socket && this.socket.connected) {
198
+ this.socket.disconnect();
199
+ }
200
+ },
201
+ onSettled: () => {
202
+ this._isAuthenticated = false;
203
+ this.clearCache();
204
+ queryClient.invalidateQueries();
205
+ },
206
+ onError: (err) => {
207
+ this.clearCache();
208
+ console.error('Logout failed:', err);
209
+ throw new StandardError(500, 'Logout failed');
210
+ }
211
+ });
212
+ }
213
+ fetchJobs(body = {}, cancelToken, headers = {}) {
214
+ if (!this.companyId || this.companyId.trim() === '') {
215
+ throw new StandardError(400, 'Company ID is required');
216
+ }
217
+ return this._fetch('POST', `/company/${this.companyId}/jobs`, JSON.stringify(body), cancelToken, {
218
+ ...headers,
219
+ 'Content-Type': 'application/json',
220
+ })
221
+ .then(response => {
222
+ if (!response || !Array.isArray(response)) {
223
+ throw new StandardError(400, 'Invalid jobs response');
189
224
  }
190
- return this.config.authManager.setTokens(tokens).then(() => true);
225
+ return response;
191
226
  })
192
227
  .catch(err => {
193
- console.error('Login failed:', err);
194
- throw new StandardError(401, 'Login failed');
228
+ console.error('Failed to fetch jobs:', err);
229
+ throw new StandardError(500, `Failed to fetch jobs: ${err.message ?? err}`);
195
230
  });
196
231
  }
197
- logout(cancelToken) {
198
- return this._fetch('POST', '/logout', null, cancelToken)
199
- .then(() => this.config.authManager.clearTokens())
232
+ fetchChats(body = {}, cancelToken, headers = {}) {
233
+ if (!this.companyId || this.companyId.trim() === '') {
234
+ throw new StandardError(400, 'Company ID is required');
235
+ }
236
+ return this._fetch('POST', `/company/${this.companyId}/chats`, JSON.stringify(body), cancelToken, {
237
+ ...headers,
238
+ 'Content-Type': 'application/json',
239
+ })
240
+ .then(response => {
241
+ if (!response || !Array.isArray(response)) {
242
+ throw new StandardError(400, 'Invalid chats response');
243
+ }
244
+ return response;
245
+ })
200
246
  .catch(err => {
201
- console.error('Logout failed:', err);
202
- throw new StandardError(500, 'Logout failed');
247
+ console.error('Failed to fetch chats:', err);
248
+ throw new StandardError(500, 'Failed to fetch chats');
203
249
  });
204
250
  }
205
- fetchJobs(companyGuid, amt = 50, knownIds = [], unknownIds = [], keyword = '', offset = 0, cancelToken, headers = {}) {
206
- const body = {
207
- amt,
208
- known_ids: knownIds,
209
- unknown_ids: unknownIds,
210
- query: keyword,
211
- };
212
- if (!companyGuid) {
213
- return Promise.reject(new StandardError(400, 'Company GUID is required'));
251
+ fetchMessages(chatId, body = {}, cancelToken, headers = {}) {
252
+ if (!chatId || chatId.trim() === '') {
253
+ throw new StandardError(400, 'Chat ID is required');
214
254
  }
215
- return this._fetch('POST', `/company/${companyGuid}/jobs?amt=${amt}&offset=${offset}`, body, cancelToken, headers)
255
+ return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(body), cancelToken, {
256
+ ...headers,
257
+ 'Content-Type': 'application/json',
258
+ })
216
259
  .then(response => {
217
260
  if (!response || !Array.isArray(response)) {
218
- throw new StandardError(400, 'Invalid jobs response');
261
+ throw new StandardError(400, 'Invalid messages response');
219
262
  }
220
263
  return response;
221
264
  })
222
265
  .catch(err => {
223
- console.error('Failed to fetch jobs:', err);
224
- throw new StandardError(500, 'Failed to fetch jobs');
266
+ console.error('Failed to fetch messages:', err);
267
+ throw new StandardError(500, 'Failed to fetch messages');
225
268
  });
226
269
  }
227
- fetchEvents(companyGuid, amt = 50, known_ids = [], unknown_ids = [], keyword = '', offset = 0, unbilled = true, billed = true, paid = true, job_id = null, cancelToken, headers = {}) {
228
- const body = {
229
- amt,
230
- known_ids,
231
- unknown_ids,
232
- query: keyword,
233
- job_id,
234
- };
235
- if (!companyGuid) {
236
- return Promise.reject(new StandardError(400, 'Company GUID is required'));
270
+ async fetchEvents(body = {}, cancelToken, headers = {}) {
271
+ if (!this.companyId || this.companyId.trim() === '') {
272
+ throw new StandardError(400, 'Company ID is required');
237
273
  }
238
- return this._fetch('POST', `/company/${companyGuid}/events?amt=${amt}&offset=${offset}&unbilled=${unbilled}&billed=${billed}&paid=${paid}`, body, cancelToken, headers)
274
+ return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(body), cancelToken, {
275
+ ...headers,
276
+ 'Content-Type': 'application/json',
277
+ })
239
278
  .then(response => {
240
279
  if (!response || !Array.isArray(response)) {
241
280
  throw new StandardError(400, 'Invalid events response');
@@ -247,17 +286,33 @@ export class AvroQueryClient {
247
286
  throw new StandardError(500, 'Failed to fetch events');
248
287
  });
249
288
  }
250
- fetchBills(companyGuid, amt = 50, known_ids = [], unknown_ids = [], keyword = '', offset = 0, cancelToken, headers = {}) {
251
- const body = {
252
- amt,
253
- known_ids,
254
- unknown_ids,
255
- query: keyword,
256
- };
257
- if (!companyGuid) {
258
- return Promise.reject(new StandardError(400, 'Company GUID is required'));
289
+ fetchMonths(body = {}, cancelToken, headers = {}) {
290
+ if (!this.companyId || this.companyId.trim() === '') {
291
+ throw new StandardError(400, 'Company ID is required');
259
292
  }
260
- return this._fetch('POST', `/company/${companyGuid}/bills?amt=${amt}&offset=${offset}`, body, cancelToken, headers)
293
+ return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(body), cancelToken, {
294
+ ...headers,
295
+ 'Content-Type': 'application/json',
296
+ })
297
+ .then(response => {
298
+ if (!response || !Array.isArray(response)) {
299
+ throw new StandardError(400, 'Invalid months response');
300
+ }
301
+ return response;
302
+ })
303
+ .catch(err => {
304
+ console.error('Failed to fetch months:', err);
305
+ throw new StandardError(500, 'Failed to fetch months');
306
+ });
307
+ }
308
+ fetchBills(body = {}, cancelToken, headers = {}) {
309
+ if (!this.companyId || this.companyId.trim() === '') {
310
+ throw new StandardError(400, 'Company ID is required');
311
+ }
312
+ return this._fetch('POST', `/company/${this.companyId}/bills`, JSON.stringify(body), cancelToken, {
313
+ ...headers,
314
+ 'Content-Type': 'application/json',
315
+ })
261
316
  .then(response => {
262
317
  if (!response || !Array.isArray(response)) {
263
318
  throw new StandardError(400, 'Invalid bills response');
@@ -269,4 +324,69 @@ export class AvroQueryClient {
269
324
  throw new StandardError(500, 'Failed to fetch bills');
270
325
  });
271
326
  }
327
+ fetchRoutes(body = {}, cancelToken, headers = {}) {
328
+ if (!this.companyId || this.companyId.trim() === '') {
329
+ throw new StandardError(400, 'Company ID is required');
330
+ }
331
+ return this._fetch('POST', `/company/${this.companyId}/routes`, JSON.stringify(body), cancelToken, {
332
+ ...headers,
333
+ 'Content-Type': 'application/json',
334
+ })
335
+ .then(response => {
336
+ if (!response || !Array.isArray(response)) {
337
+ throw new StandardError(400, 'Invalid routes response');
338
+ }
339
+ return response;
340
+ })
341
+ .catch(err => {
342
+ console.error('Failed to fetch routes:', err);
343
+ throw new StandardError(500, 'Failed to fetch routes');
344
+ });
345
+ }
346
+ fetchTeams(body = {}, cancelToken, headers = {}) {
347
+ if (!this.companyId || this.companyId.trim() === '') {
348
+ throw new StandardError(400, 'Company ID is required');
349
+ }
350
+ return this._fetch('POST', `/company/${this.companyId}/teams`, JSON.stringify(body), cancelToken, {
351
+ ...headers,
352
+ 'Content-Type': 'application/json',
353
+ })
354
+ .then(response => {
355
+ if (!response || !Array.isArray(response)) {
356
+ throw new StandardError(400, 'Invalid teams response');
357
+ }
358
+ return response;
359
+ })
360
+ .catch(err => {
361
+ console.error('Failed to fetch teams:', err);
362
+ throw new StandardError(500, 'Failed to fetch teams');
363
+ });
364
+ }
365
+ fetchSessions(body = {}, cancelToken, headers = {}) {
366
+ if (!this.companyId || this.companyId.trim() === '') {
367
+ throw new StandardError(400, 'Company ID is required');
368
+ }
369
+ return this._fetch('POST', `/company/${this.companyId}/sessions`, JSON.stringify(body), cancelToken, {
370
+ ...headers,
371
+ 'Content-Type': 'application/json',
372
+ })
373
+ .then(response => {
374
+ if (!response || !Array.isArray(response)) {
375
+ throw new StandardError(400, 'Invalid sessions response');
376
+ }
377
+ return response;
378
+ })
379
+ .catch(err => {
380
+ console.error('Failed to fetch sessions:', err);
381
+ throw new StandardError(500, 'Failed to fetch sessions');
382
+ });
383
+ }
384
+ sendEmail(emailId, formData, progressUpdateCallback) {
385
+ try {
386
+ return this.post(`/email/${emailId}`, formData, undefined, {}, progressUpdateCallback);
387
+ }
388
+ catch (error) {
389
+ throw new StandardError(500, `Failed to send email: ${error}`);
390
+ }
391
+ }
272
392
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,62 @@
1
+ import { AvroQueryClient } from '../../client/QueryClient';
2
+ import { StandardError } from '../../types/error';
3
+ AvroQueryClient.prototype._fetch = async function (method, path, body, cancelToken, headers = {}, isIdempotent = false, retryCount = 0) {
4
+ const checkCancelled = () => {
5
+ try {
6
+ if (cancelToken?.isCancelled()) {
7
+ throw new StandardError(0, 'Request cancelled');
8
+ }
9
+ }
10
+ catch (error) {
11
+ throw new StandardError(0, `Error checking cancellation: ${error.message}`);
12
+ }
13
+ };
14
+ try {
15
+ checkCancelled();
16
+ const token = await this.config.authManager.accessToken();
17
+ checkCancelled();
18
+ const url = this.config.baseUrl + path;
19
+ const requestHeaders = {
20
+ Authorization: `Bearer ${token}`,
21
+ ...headers,
22
+ };
23
+ const options = {
24
+ method,
25
+ headers: requestHeaders,
26
+ body,
27
+ };
28
+ const response = await fetch(url, options);
29
+ if (response.ok) {
30
+ const text = await response.text();
31
+ if (!text) {
32
+ return undefined;
33
+ }
34
+ return JSON.parse(text);
35
+ }
36
+ if (response.status === 401 && this.config.authManager.refreshTokens && retryCount === 0) {
37
+ await this.config.authManager.refreshTokens();
38
+ return this._fetch(method, path, body, cancelToken, headers, isIdempotent, 1);
39
+ }
40
+ if (retryCount < this.config.maxRetries) {
41
+ const delay = this.getDelay(this.config.retryStrategy, retryCount);
42
+ await this.sleep(delay);
43
+ return this._fetch(method, path, body, cancelToken, headers, isIdempotent, retryCount + 1);
44
+ }
45
+ let errorMessage = response.statusText;
46
+ try {
47
+ const parsedError = await response.json();
48
+ errorMessage = parsedError.message ?? parsedError.msg ?? errorMessage;
49
+ }
50
+ catch (e) {
51
+ console.error('Ignoring:', e);
52
+ }
53
+ throw new StandardError(response.status, errorMessage);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof StandardError) {
57
+ throw error;
58
+ }
59
+ const message = error instanceof Error ? error.message : String(error);
60
+ throw new StandardError(0, `Request failed: ${message}`);
61
+ }
62
+ };
@@ -0,0 +1 @@
1
+ export {};