@go-avro/avro-js 0.1.15 → 1.6.1-rc1

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/dist/auth/AuthManager.d.ts +32 -0
  2. package/dist/auth/AuthManager.js +138 -43
  3. package/dist/client/QueryClient.d.ts +68 -2
  4. package/dist/client/QueryClient.js +310 -96
  5. package/dist/client/cache.d.ts +24 -0
  6. package/dist/client/cache.js +51 -0
  7. package/dist/client/core/fetch.js +58 -49
  8. package/dist/client/core/policy.d.ts +17 -0
  9. package/dist/client/core/policy.js +35 -0
  10. package/dist/client/core/xhr.js +16 -14
  11. package/dist/client/hooks/bills.js +10 -14
  12. package/dist/client/hooks/catalog_items.js +18 -8
  13. package/dist/client/hooks/chats.js +2 -8
  14. package/dist/client/hooks/companies.js +11 -5
  15. package/dist/client/hooks/events.js +56 -47
  16. package/dist/client/hooks/groups.js +11 -26
  17. package/dist/client/hooks/jobs.js +3 -8
  18. package/dist/client/hooks/labels.js +11 -26
  19. package/dist/client/hooks/messages.js +21 -24
  20. package/dist/client/hooks/months.js +28 -22
  21. package/dist/client/hooks/payouts.js +3 -8
  22. package/dist/client/hooks/prepayments.js +28 -22
  23. package/dist/client/hooks/proposal.js +1 -0
  24. package/dist/client/hooks/routes.js +8 -6
  25. package/dist/client/hooks/sessions.js +21 -31
  26. package/dist/client/hooks/skills.js +6 -4
  27. package/dist/client/hooks/teams.js +6 -4
  28. package/dist/client/hooks/timecards.js +7 -7
  29. package/dist/client/hooks/waivers.js +6 -4
  30. package/dist/client/persist.js +21 -2
  31. package/dist/client/realtime.d.ts +21 -1
  32. package/dist/client/realtime.js +183 -51
  33. package/dist/types/api/Bill.js +2 -1
  34. package/dist/types/api/Company.d.ts +2 -0
  35. package/dist/types/api/Email.d.ts +3 -9
  36. package/dist/types/api/EmailNotification.d.ts +1 -1
  37. package/dist/types/api/Job.js +8 -4
  38. package/dist/types/api/LineItem.d.ts +4 -0
  39. package/dist/types/api/LineItem.js +10 -2
  40. package/dist/types/api/Prepayment.js +2 -1
  41. package/dist/types/api/Route.js +2 -1
  42. package/dist/types/api/RouteJob.js +2 -1
  43. package/dist/types/api/Session.js +2 -1
  44. package/dist/types/api/Task.d.ts +27 -2
  45. package/dist/types/api/Task.js +44 -8
  46. package/dist/types/api/_Event.js +2 -1
  47. package/dist/types/api/assignData.d.ts +9 -0
  48. package/dist/types/api/assignData.js +17 -0
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +7 -2
@@ -1,12 +1,50 @@
1
1
  import io from 'socket.io-client';
2
2
  import { useMutation, useQueryClient, } from '@tanstack/react-query';
3
3
  import { v4 as uuidv4 } from 'uuid';
4
+ import { isDefinitiveAuthFailure } from '../auth/AuthManager.js';
4
5
  import { fetchCensusFeatures } from '../census.js';
5
6
  import { LoginResponse, } from '../types/api.js';
6
7
  import { AuthState } from '../types/auth.js';
7
8
  import { StandardError } from '../types/error.js';
8
9
  import { ChangeApplier, fallbackInvalidate, patchMember, patchMemberLocation, patchTeamLocation, } from './realtime.js';
9
10
  import { QueryPersister } from './persist.js';
11
+ /** Keep the original status (401/403/404/0…) when surfacing a list-fetch failure. */
12
+ function fetchError(err, context) {
13
+ if (err instanceof StandardError)
14
+ return err;
15
+ const message = err instanceof Error ? err.message : String(err);
16
+ return new StandardError(0, `${context}: ${message}`);
17
+ }
18
+ /**
19
+ * Apply the list-endpoint filter contract client-side: non-empty
20
+ * `unknown_ids` = only these; else `known_ids` = exclude these; `query`
21
+ * substring-matches the given fields; then `offset`/`amt` paging.
22
+ */
23
+ function filterLocally(items, body, fields) {
24
+ let out = items;
25
+ if (body.unknown_ids && body.unknown_ids.length > 0) {
26
+ const wanted = new Set(body.unknown_ids);
27
+ out = out.filter((x) => x?.id && wanted.has(x.id));
28
+ }
29
+ else if (body.known_ids && body.known_ids.length > 0) {
30
+ const known = new Set(body.known_ids);
31
+ out = out.filter((x) => !(x?.id && known.has(x.id)));
32
+ }
33
+ const q = body.query?.trim().toLowerCase();
34
+ if (q) {
35
+ out = out.filter((x) => fields(x).some((f) => typeof f === 'string' && f.toLowerCase().includes(q)));
36
+ }
37
+ const offset = body.offset ?? 0;
38
+ return body.amt !== undefined ? out.slice(offset, offset + body.amt) : out.slice(offset);
39
+ }
40
+ /** Translate a legacy camelCase parent filter to the snake_case the backend reads. */
41
+ function withWireParent(body, legacy, wire) {
42
+ const { [legacy]: legacyValue, ...rest } = body;
43
+ return { ...rest, [wire]: rest[wire] ?? legacyValue ?? undefined };
44
+ }
45
+ const AUTH_RECHECK_MIN_MS = 2000;
46
+ const AUTH_RECHECK_MAX_MS = 60000;
47
+ const SOCKET_AUTH_RETRY_MS = 10000;
10
48
  export class AvroQueryClient {
11
49
  constructor(config) {
12
50
  this._authState = AuthState.UNKNOWN;
@@ -20,9 +58,16 @@ export class AvroQueryClient {
20
58
  this._persister = null;
21
59
  this._presencePending = new Set();
22
60
  this._presenceTimer = null;
61
+ /** Chat rooms to (re)join on every connect; socket rooms don't survive reconnects. */
62
+ this._joinedChats = new Set();
23
63
  this._restored = null;
24
64
  this._emailTracking = new Map();
25
65
  this._emailListenersInit = false;
66
+ this._authCheck = null;
67
+ this._authRecheckTimer = null;
68
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
69
+ this._socketAuthRetried = false;
70
+ this._socketRetryTimer = null;
26
71
  this.config = {
27
72
  baseUrl: config.baseUrl,
28
73
  authManager: config.authManager,
@@ -39,27 +84,8 @@ export class AvroQueryClient {
39
84
  transports: ['websocket'],
40
85
  });
41
86
  this.socket.on('connect', () => this.registerDevice());
42
- config.authManager.isAuthenticated().then((isAuth) => {
43
- this.setAuthState(isAuth);
44
- if (!this.socket.connected && isAuth === AuthState.AUTHENTICATED) {
45
- Promise.all([this.getCompanyId(), this.config.authManager.accessToken()])
46
- .then(([id, token]) => {
47
- this.companyId = id;
48
- this.socket.auth = this.socketAuth(token);
49
- this.ensureSocketConnected();
50
- })
51
- .catch((err) => {
52
- console.error('Not logged in:', err);
53
- });
54
- }
55
- else {
56
- // Not authenticated – still cache the companyId for later.
57
- this.getCompanyId().then((id) => {
58
- this.companyId = id;
59
- });
60
- }
61
- });
62
87
  this.socket.on('connect', () => {
88
+ this._socketAuthRetried = false;
63
89
  this.setAuthState(AuthState.AUTHENTICATED);
64
90
  console.log(`Socket connected with ID: ${this.socket?.id}`);
65
91
  });
@@ -67,7 +93,8 @@ export class AvroQueryClient {
67
93
  console.log(`Socket disconnected: ${reason}`);
68
94
  });
69
95
  this.socket.on('connect_error', (err) => {
70
- console.error(`Socket connection error: ${err.message}`);
96
+ console.error(`Socket connection error: ${err?.message}`);
97
+ this.handleSocketConnectError();
71
98
  });
72
99
  this.config.authManager.onTokenRefreshed((newAccessToken) => {
73
100
  if (this.socket && newAccessToken) {
@@ -79,6 +106,133 @@ export class AvroQueryClient {
79
106
  config.authManager.onTokenRefreshFailed(() => {
80
107
  void this.forceLogout();
81
108
  });
109
+ // Cache the stored companyId even before auth resolves.
110
+ this.getCompanyId().then((id) => {
111
+ this.companyId ?? (this.companyId = id);
112
+ });
113
+ void this.recheckAuth();
114
+ // Browsers: re-check as soon as the network comes back.
115
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
116
+ window.addEventListener('online', () => {
117
+ if (this._authState === AuthState.UNKNOWN)
118
+ void this.recheckAuth();
119
+ });
120
+ }
121
+ }
122
+ /**
123
+ * Re-validate the stored session (deduplicated). Call it when the app
124
+ * returns to the foreground or regains connectivity; the SDK also calls
125
+ * it on a backoff timer and after the next successful request while the
126
+ * state is UNKNOWN (e.g. after an offline cold start). A network error
127
+ * or 5xx never downgrades the state to UNAUTHENTICATED: only a
128
+ * definitive auth failure does.
129
+ */
130
+ recheckAuth() {
131
+ if (this._authCheck)
132
+ return this._authCheck;
133
+ if (this._authRecheckTimer) {
134
+ clearTimeout(this._authRecheckTimer);
135
+ this._authRecheckTimer = null;
136
+ }
137
+ const check = this.config.authManager
138
+ .isAuthenticated()
139
+ .catch((err) => {
140
+ console.error('Auth check failed:', err);
141
+ return AuthState.UNKNOWN;
142
+ })
143
+ .then(async (state) => {
144
+ if (state === AuthState.AUTHENTICATED) {
145
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
146
+ this.setAuthState(state);
147
+ if (!this.socket.connected) {
148
+ try {
149
+ const [id, token] = await Promise.all([
150
+ this.getCompanyId(),
151
+ this.config.authManager.accessToken(),
152
+ ]);
153
+ this.companyId = id;
154
+ this.socket.auth = this.socketAuth(token);
155
+ this.ensureSocketConnected();
156
+ }
157
+ catch (err) {
158
+ console.error('Not logged in:', err);
159
+ }
160
+ }
161
+ }
162
+ else if (state === AuthState.UNAUTHENTICATED) {
163
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
164
+ this.setAuthState(state);
165
+ }
166
+ else {
167
+ // Couldn't reach the server. Keep a known state (an
168
+ // AUTHENTICATED session stays usable offline) and retry.
169
+ if (this._authState === AuthState.UNKNOWN)
170
+ this.setAuthState(state);
171
+ this.scheduleAuthRecheck();
172
+ }
173
+ return state;
174
+ })
175
+ .finally(() => {
176
+ this._authCheck = null;
177
+ });
178
+ this._authCheck = check;
179
+ return check;
180
+ }
181
+ scheduleAuthRecheck() {
182
+ if (this._authRecheckTimer)
183
+ return;
184
+ const delay = this._authRecheckDelay;
185
+ this._authRecheckDelay = Math.min(delay * 2, AUTH_RECHECK_MAX_MS);
186
+ this._authRecheckTimer = setTimeout(() => {
187
+ this._authRecheckTimer = null;
188
+ if (this._authState === AuthState.UNKNOWN)
189
+ void this.recheckAuth();
190
+ }, delay);
191
+ }
192
+ /** Called by the transports after any 2xx: the server is reachable again. */
193
+ _noteRequestSucceeded() {
194
+ if (this._authState === AuthState.UNKNOWN && !this._authCheck) {
195
+ void this.recheckAuth();
196
+ }
197
+ }
198
+ /**
199
+ * The server refuses the socket handshake when the access token has
200
+ * expired; socket.io then stops reconnecting (`active` is false).
201
+ * Refresh the token once (shared with any in-flight refresh) and
202
+ * reconnect with it. A definitive refresh failure logs out via
203
+ * onTokenRefreshFailed; a transient one retries after a delay.
204
+ */
205
+ handleSocketConnectError() {
206
+ if (this.socket.active)
207
+ return; // transport error: socket.io retries itself
208
+ if (this._authState !== AuthState.AUTHENTICATED)
209
+ return;
210
+ if (this._socketAuthRetried)
211
+ return; // refreshed already and still refused
212
+ this._socketAuthRetried = true;
213
+ this.config.authManager
214
+ .refreshTokens()
215
+ .then((tokens) => {
216
+ // onTokenRefreshed already reconnects; make sure regardless.
217
+ if (tokens?.access_token) {
218
+ this.socket.auth = this.socketAuth(tokens.access_token);
219
+ this.ensureSocketConnected();
220
+ }
221
+ })
222
+ .catch((err) => {
223
+ if (isDefinitiveAuthFailure(err))
224
+ return; // forceLogout runs
225
+ console.error('Socket token refresh failed; retrying later:', err);
226
+ if (this._socketRetryTimer)
227
+ return;
228
+ this._socketRetryTimer = setTimeout(() => {
229
+ this._socketRetryTimer = null;
230
+ this._socketAuthRetried = false;
231
+ if (this._authState === AuthState.AUTHENTICATED) {
232
+ this.ensureSocketConnected();
233
+ }
234
+ }, SOCKET_AUTH_RETRY_MS);
235
+ });
82
236
  }
83
237
  /** Handshake payload: the token plus, when known, this install's identity. */
84
238
  socketAuth(token) {
@@ -116,6 +270,25 @@ export class AvroQueryClient {
116
270
  }
117
271
  this.socket.emit(eventName, data);
118
272
  }
273
+ /**
274
+ * Join a chat's socket room so `new_message` and presence events for it
275
+ * arrive. The room is rejoined after reconnects until `leaveChat`.
276
+ */
277
+ joinChat(chatId) {
278
+ if (!chatId)
279
+ return;
280
+ this._joinedChats.add(chatId);
281
+ if (this.socket?.connected)
282
+ this.socket.emit('join_chat', { chat_id: chatId });
283
+ }
284
+ /** Leave a chat's socket room joined with `joinChat`. */
285
+ leaveChat(chatId) {
286
+ if (!chatId)
287
+ return;
288
+ this._joinedChats.delete(chatId);
289
+ if (this.socket?.connected)
290
+ this.socket.emit('leave_chat', { chat_id: chatId });
291
+ }
119
292
  on(eventName, callback) {
120
293
  this.socket?.on(eventName, callback);
121
294
  }
@@ -145,6 +318,13 @@ export class AvroQueryClient {
145
318
  if (data?.company_id && data.company_id === this.companyId)
146
319
  this.joinCompanyRoom();
147
320
  });
321
+ // Sent before a chat room is closed after a membership change;
322
+ // the server re-checks membership, so removed members stay out.
323
+ on('rejoin_chat', (data) => {
324
+ if (data?.chat_id && this._joinedChats.has(data.chat_id)) {
325
+ this.socket?.emit('join_chat', { chat_id: data.chat_id });
326
+ }
327
+ });
148
328
  // Presence names the member that changed; coalesce a burst of
149
329
  // flips (mobile sockets cycle constantly) into one bulk fetch
150
330
  // and patch those members instead of re-downloading every
@@ -177,6 +357,7 @@ export class AvroQueryClient {
177
357
  path: `/company/${this.companyId}/users`,
178
358
  data: JSON.stringify({ user_ids: userIds }),
179
359
  headers: { 'Content-Type': 'application/json' },
360
+ idempotent: true,
180
361
  })
181
362
  .then((members) => {
182
363
  if (!Array.isArray(members)) {
@@ -217,7 +398,12 @@ export class AvroQueryClient {
217
398
  queryClient.invalidateQueries({ queryKey: ['chats'] });
218
399
  queryClient.invalidateQueries({ queryKey: ['messages'] });
219
400
  });
220
- on('connect', () => this.joinCompanyRoom());
401
+ on('connect', () => {
402
+ this.joinCompanyRoom();
403
+ for (const chatId of this._joinedChats) {
404
+ this.socket.emit('join_chat', { chat_id: chatId });
405
+ }
406
+ });
221
407
  if (this.socket.connected && this.companyId)
222
408
  this.joinCompanyRoom();
223
409
  this._socketInvalidationCleanup = () => {
@@ -247,7 +433,17 @@ export class AvroQueryClient {
247
433
  const known = this._companyVersions.get(companyId);
248
434
  this._companyVersions.set(companyId, ack.version);
249
435
  this._persister?.setCompanyVersion(companyId, ack.version);
250
- if (known !== undefined && known !== ack.version) {
436
+ if (known === undefined) {
437
+ // First join: nothing to compare with, and changes made
438
+ // between the initial REST loads and joining the room
439
+ // were never delivered. Refresh what loaded before now
440
+ // once; later joins compare versions instead.
441
+ const joinedAt = Date.now();
442
+ this._queryClient?.invalidateQueries({
443
+ predicate: (q) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < joinedAt,
444
+ });
445
+ }
446
+ else if (known !== ack.version) {
251
447
  this._queryClient?.invalidateQueries();
252
448
  }
253
449
  });
@@ -287,8 +483,8 @@ export class AvroQueryClient {
287
483
  // Reporting must never become a second failure.
288
484
  }
289
485
  }
290
- post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, }) {
291
- return this._xhr('POST', path, data, cancelToken, headers, false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
486
+ post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }) {
487
+ return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
292
488
  }
293
489
  put({ path, data, cancelToken, headers, progressUpdateCallback, }) {
294
490
  return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
@@ -296,13 +492,20 @@ export class AvroQueryClient {
296
492
  delete({ path, cancelToken, headers, progressUpdateCallback, }) {
297
493
  return this._xhr('DELETE', path, null, cancelToken, headers, false, this.config.maxRetries, progressUpdateCallback);
298
494
  }
299
- loginSuccess(tokens) {
495
+ /**
496
+ * Persist freshly issued tokens, then flip to AUTHENTICATED and connect
497
+ * the socket. Tokens are stored first so that anything reacting to the
498
+ * auth-state change (queries enabled on AUTHENTICATED) finds them.
499
+ */
500
+ async loginSuccess(tokens) {
501
+ await this.config.authManager.setTokens(tokens);
502
+ this._socketAuthRetried = false;
503
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
300
504
  this.setAuthState(AuthState.AUTHENTICATED);
301
505
  this.socket.auth = this.socketAuth(tokens.access_token);
302
506
  if (!this.socket.connected) {
303
507
  this.ensureSocketConnected();
304
508
  }
305
- return this.config.authManager.setTokens(tokens);
306
509
  }
307
510
  useLogin() {
308
511
  const queryClient = this.getQueryClient();
@@ -385,12 +588,7 @@ export class AvroQueryClient {
385
588
  }
386
589
  throw new StandardError(401, 'Invalid Google login response');
387
590
  }
388
- this.setAuthState(AuthState.AUTHENTICATED);
389
- this.socket.auth = this.socketAuth(resp.access_token);
390
- if (!this.socket.connected) {
391
- this.ensureSocketConnected();
392
- }
393
- await this.config.authManager.setTokens({
591
+ await this.loginSuccess({
394
592
  access_token: resp.access_token,
395
593
  refresh_token: resp.refresh_token,
396
594
  });
@@ -416,12 +614,7 @@ export class AvroQueryClient {
416
614
  }
417
615
  throw new StandardError(401, 'Invalid Apple login response');
418
616
  }
419
- this.setAuthState(AuthState.AUTHENTICATED);
420
- this.socket.auth = this.socketAuth(resp.access_token);
421
- if (!this.socket.connected) {
422
- this.ensureSocketConnected();
423
- }
424
- await this.config.authManager.setTokens({
617
+ await this.loginSuccess({
425
618
  access_token: resp.access_token,
426
619
  refresh_token: resp.refresh_token,
427
620
  });
@@ -554,12 +747,25 @@ export class AvroQueryClient {
554
747
  * server that no longer recognizes our identity.
555
748
  */
556
749
  async forceLogout() {
750
+ // Stop the socket first, including one that is mid-reconnect
751
+ // (`active` but not `connected`), so it can't come back with the
752
+ // old token.
753
+ if (this.socket && (this.socket.connected || this.socket.active)) {
754
+ this.socket.disconnect();
755
+ }
756
+ this.socket.auth = {};
757
+ if (this._socketRetryTimer) {
758
+ clearTimeout(this._socketRetryTimer);
759
+ this._socketRetryTimer = null;
760
+ }
761
+ if (this._authRecheckTimer) {
762
+ clearTimeout(this._authRecheckTimer);
763
+ this._authRecheckTimer = null;
764
+ }
765
+ this._socketAuthRetried = false;
557
766
  await this.clearCache();
558
767
  await this._persister?.clear();
559
768
  this.setAuthState(AuthState.UNAUTHENTICATED);
560
- if (this.socket && this.socket.connected) {
561
- this.socket.disconnect();
562
- }
563
769
  this.peekQueryClient()?.removeQueries();
564
770
  }
565
771
  useLogout() {
@@ -593,7 +799,7 @@ export class AvroQueryClient {
593
799
  return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(body), cancelToken, {
594
800
  ...headers,
595
801
  'Content-Type': 'application/json',
596
- })
802
+ }, true)
597
803
  .then((response) => {
598
804
  if (!response || !Array.isArray(response)) {
599
805
  throw new StandardError(400, 'Invalid jobs response');
@@ -602,7 +808,7 @@ export class AvroQueryClient {
602
808
  })
603
809
  .catch((err) => {
604
810
  console.error('Failed to fetch jobs:', err);
605
- throw new StandardError(500, `Failed to fetch jobs: ${err.message ?? err}`);
811
+ throw fetchError(err, 'Failed to fetch jobs');
606
812
  });
607
813
  }
608
814
  async autocompleteAddress({ address, size = 10, include_census = true, }, cancelToken, headers = {}) {
@@ -660,23 +866,25 @@ export class AvroQueryClient {
660
866
  maxRetries: 0,
661
867
  });
662
868
  }
869
+ /**
870
+ * The caller's chats. The backend only exposes `GET /chat` (every chat
871
+ * the user belongs to, unpaged), so the id/query/paging filters are
872
+ * applied client-side.
873
+ */
663
874
  fetchChats(body = {}, cancelToken, headers = {}) {
664
- if (!this.companyId || this.companyId.trim() === '') {
665
- throw new StandardError(400, 'Company ID is required');
666
- }
667
- return this._fetch('POST', `/company/${this.companyId}/chats`, JSON.stringify(body), cancelToken, {
668
- ...headers,
669
- 'Content-Type': 'application/json',
670
- })
875
+ return this._fetch('GET', '/chat', null, cancelToken, headers, true)
671
876
  .then((response) => {
672
877
  if (!response || !Array.isArray(response)) {
673
878
  throw new StandardError(400, 'Invalid chats response');
674
879
  }
675
- return response;
880
+ const scoped = this.companyId
881
+ ? response.filter((c) => !c?.company_id || c.company_id === this.companyId)
882
+ : response;
883
+ return filterLocally(scoped, body, (c) => [c?.name]);
676
884
  })
677
885
  .catch((err) => {
678
886
  console.error('Failed to fetch chats:', err);
679
- throw new StandardError(500, 'Failed to fetch chats');
887
+ throw fetchError(err, 'Failed to fetch chats');
680
888
  });
681
889
  }
682
890
  fetchMessages(chatId, body = {}, cancelToken, headers = {}) {
@@ -686,7 +894,7 @@ export class AvroQueryClient {
686
894
  return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(body), cancelToken, {
687
895
  ...headers,
688
896
  'Content-Type': 'application/json',
689
- })
897
+ }, true)
690
898
  .then((response) => {
691
899
  if (!response || !Array.isArray(response)) {
692
900
  throw new StandardError(400, 'Invalid messages response');
@@ -695,17 +903,17 @@ export class AvroQueryClient {
695
903
  })
696
904
  .catch((err) => {
697
905
  console.error('Failed to fetch messages:', err);
698
- throw new StandardError(500, 'Failed to fetch messages');
906
+ throw fetchError(err, 'Failed to fetch messages');
699
907
  });
700
908
  }
701
909
  async fetchPrepayments(body = {}, cancelToken, headers = {}) {
702
910
  if (!this.companyId || this.companyId.trim() === '') {
703
911
  throw new StandardError(400, 'Company ID is required');
704
912
  }
705
- return this._fetch('POST', `/company/${this.companyId}/prepayments`, JSON.stringify(body), cancelToken, {
913
+ return this._fetch('POST', `/company/${this.companyId}/prepayments`, JSON.stringify(withWireParent(body, 'taskId', 'task_id')), cancelToken, {
706
914
  ...headers,
707
915
  'Content-Type': 'application/json',
708
- })
916
+ }, true)
709
917
  .then((response) => {
710
918
  if (!response || !Array.isArray(response)) {
711
919
  throw new StandardError(400, 'Invalid prepayments response');
@@ -714,7 +922,7 @@ export class AvroQueryClient {
714
922
  })
715
923
  .catch((err) => {
716
924
  console.error('Failed to fetch prepayments:', err);
717
- throw new StandardError(500, 'Failed to fetch prepayments');
925
+ throw fetchError(err, 'Failed to fetch prepayments');
718
926
  });
719
927
  }
720
928
  async fetchWaivers(body = {}, cancelToken, headers = {}) {
@@ -724,7 +932,7 @@ export class AvroQueryClient {
724
932
  return this._fetch('POST', `/company/${this.companyId}/waivers`, JSON.stringify(body), cancelToken, {
725
933
  ...headers,
726
934
  'Content-Type': 'application/json',
727
- })
935
+ }, true)
728
936
  .then((response) => {
729
937
  if (!response || !Array.isArray(response)) {
730
938
  throw new StandardError(400, 'Invalid waivers response');
@@ -733,7 +941,7 @@ export class AvroQueryClient {
733
941
  })
734
942
  .catch((err) => {
735
943
  console.error('Failed to fetch waivers:', err);
736
- throw new StandardError(500, 'Failed to fetch waivers');
944
+ throw fetchError(err, 'Failed to fetch waivers');
737
945
  });
738
946
  }
739
947
  async fetchEvents(body = {}, cancelToken, headers = {}) {
@@ -743,7 +951,7 @@ export class AvroQueryClient {
743
951
  return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(body), cancelToken, {
744
952
  ...headers,
745
953
  'Content-Type': 'application/json',
746
- })
954
+ }, true)
747
955
  .then((response) => {
748
956
  if (!response || !Array.isArray(response)) {
749
957
  throw new StandardError(400, 'Invalid events response');
@@ -752,17 +960,17 @@ export class AvroQueryClient {
752
960
  })
753
961
  .catch((err) => {
754
962
  console.error('Failed to fetch events:', err);
755
- throw new StandardError(500, 'Failed to fetch events');
963
+ throw fetchError(err, 'Failed to fetch events');
756
964
  });
757
965
  }
758
966
  fetchMonths(body = {}, cancelToken, headers = {}) {
759
967
  if (!this.companyId || this.companyId.trim() === '') {
760
968
  throw new StandardError(400, 'Company ID is required');
761
969
  }
762
- return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(body), cancelToken, {
970
+ return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(withWireParent(body, 'jobId', 'job_id')), cancelToken, {
763
971
  ...headers,
764
972
  'Content-Type': 'application/json',
765
- })
973
+ }, true)
766
974
  .then((response) => {
767
975
  if (!response || !Array.isArray(response)) {
768
976
  throw new StandardError(400, 'Invalid months response');
@@ -771,7 +979,7 @@ export class AvroQueryClient {
771
979
  })
772
980
  .catch((err) => {
773
981
  console.error('Failed to fetch months:', err);
774
- throw new StandardError(500, 'Failed to fetch months');
982
+ throw fetchError(err, 'Failed to fetch months');
775
983
  });
776
984
  }
777
985
  fetchBills(body = {}, cancelToken, headers = {}) {
@@ -781,7 +989,7 @@ export class AvroQueryClient {
781
989
  return this._fetch('POST', `/company/${this.companyId}/bills`, JSON.stringify(body), cancelToken, {
782
990
  ...headers,
783
991
  'Content-Type': 'application/json',
784
- })
992
+ }, true)
785
993
  .then((response) => {
786
994
  if (!response || !Array.isArray(response)) {
787
995
  throw new StandardError(400, 'Invalid bills response');
@@ -790,7 +998,7 @@ export class AvroQueryClient {
790
998
  })
791
999
  .catch((err) => {
792
1000
  console.error('Failed to fetch bills:', err);
793
- throw new StandardError(500, 'Failed to fetch bills');
1001
+ throw fetchError(err, 'Failed to fetch bills');
794
1002
  });
795
1003
  }
796
1004
  fetchPayouts(body = {}, cancelToken, headers = {}) {
@@ -800,7 +1008,7 @@ export class AvroQueryClient {
800
1008
  return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(body), cancelToken, {
801
1009
  ...headers,
802
1010
  'Content-Type': 'application/json',
803
- })
1011
+ }, true)
804
1012
  .then((response) => {
805
1013
  if (!response || !Array.isArray(response)) {
806
1014
  throw new StandardError(400, 'Invalid payouts response');
@@ -809,7 +1017,7 @@ export class AvroQueryClient {
809
1017
  })
810
1018
  .catch((err) => {
811
1019
  console.error('Failed to fetch payouts:', err);
812
- throw new StandardError(500, 'Failed to fetch payouts');
1020
+ throw fetchError(err, 'Failed to fetch payouts');
813
1021
  });
814
1022
  }
815
1023
  fetchRoutes(body = {}, cancelToken, headers = {}) {
@@ -819,7 +1027,7 @@ export class AvroQueryClient {
819
1027
  return this._fetch('POST', `/company/${this.companyId}/routes`, JSON.stringify(body), cancelToken, {
820
1028
  ...headers,
821
1029
  'Content-Type': 'application/json',
822
- })
1030
+ }, true)
823
1031
  .then((response) => {
824
1032
  if (!response || !Array.isArray(response)) {
825
1033
  throw new StandardError(400, 'Invalid routes response');
@@ -828,7 +1036,7 @@ export class AvroQueryClient {
828
1036
  })
829
1037
  .catch((err) => {
830
1038
  console.error('Failed to fetch routes:', err);
831
- throw new StandardError(500, 'Failed to fetch routes');
1039
+ throw fetchError(err, 'Failed to fetch routes');
832
1040
  });
833
1041
  }
834
1042
  fetchTeams(body = {}, cancelToken, headers = {}) {
@@ -838,7 +1046,7 @@ export class AvroQueryClient {
838
1046
  return this._fetch('POST', `/company/${this.companyId}/teams`, JSON.stringify(body), cancelToken, {
839
1047
  ...headers,
840
1048
  'Content-Type': 'application/json',
841
- })
1049
+ }, true)
842
1050
  .then((response) => {
843
1051
  if (!response || !Array.isArray(response)) {
844
1052
  throw new StandardError(400, 'Invalid teams response');
@@ -847,45 +1055,51 @@ export class AvroQueryClient {
847
1055
  })
848
1056
  .catch((err) => {
849
1057
  console.error('Failed to fetch teams:', err);
850
- throw new StandardError(500, 'Failed to fetch teams');
1058
+ throw fetchError(err, 'Failed to fetch teams');
851
1059
  });
852
1060
  }
1061
+ /**
1062
+ * Company labels. There is no list endpoint for them: they are embedded
1063
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1064
+ * client-side.
1065
+ */
853
1066
  fetchLabels(body = {}, cancelToken, headers = {}) {
854
1067
  if (!this.companyId || this.companyId.trim() === '') {
855
1068
  throw new StandardError(400, 'Company ID is required');
856
1069
  }
857
- return this._fetch('POST', `/company/${this.companyId}/labels`, JSON.stringify(body), cancelToken, {
858
- ...headers,
859
- 'Content-Type': 'application/json',
860
- })
861
- .then((response) => {
862
- if (!response || !Array.isArray(response)) {
1070
+ return this._fetch('GET', `/company/${this.companyId}`, null, cancelToken, headers, true)
1071
+ .then((company) => {
1072
+ const items = company?.labels;
1073
+ if (!Array.isArray(items)) {
863
1074
  throw new StandardError(400, 'Invalid labels response');
864
1075
  }
865
- return response;
1076
+ return filterLocally(items, body, (x) => [x?.name]);
866
1077
  })
867
1078
  .catch((err) => {
868
1079
  console.error('Failed to fetch labels:', err);
869
- throw new StandardError(500, 'Failed to fetch labels');
1080
+ throw fetchError(err, 'Failed to fetch labels');
870
1081
  });
871
1082
  }
1083
+ /**
1084
+ * Company groups. There is no list endpoint for them: they are embedded
1085
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1086
+ * client-side.
1087
+ */
872
1088
  fetchGroups(body = {}, cancelToken, headers = {}) {
873
1089
  if (!this.companyId || this.companyId.trim() === '') {
874
1090
  throw new StandardError(400, 'Company ID is required');
875
1091
  }
876
- return this._fetch('POST', `/company/${this.companyId}/groups`, JSON.stringify(body), cancelToken, {
877
- ...headers,
878
- 'Content-Type': 'application/json',
879
- })
880
- .then((response) => {
881
- if (!response || !Array.isArray(response)) {
1092
+ return this._fetch('GET', `/company/${this.companyId}`, null, cancelToken, headers, true)
1093
+ .then((company) => {
1094
+ const items = company?.groups;
1095
+ if (!Array.isArray(items)) {
882
1096
  throw new StandardError(400, 'Invalid groups response');
883
1097
  }
884
- return response;
1098
+ return filterLocally(items, body, (x) => [x?.name]);
885
1099
  })
886
1100
  .catch((err) => {
887
1101
  console.error('Failed to fetch groups:', err);
888
- throw new StandardError(500, 'Failed to fetch groups');
1102
+ throw fetchError(err, 'Failed to fetch groups');
889
1103
  });
890
1104
  }
891
1105
  fetchSkills(body = {}, cancelToken, headers = {}) {
@@ -895,7 +1109,7 @@ export class AvroQueryClient {
895
1109
  return this._fetch('POST', `/company/${this.companyId}/skills`, JSON.stringify(body), cancelToken, {
896
1110
  ...headers,
897
1111
  'Content-Type': 'application/json',
898
- })
1112
+ }, true)
899
1113
  .then((response) => {
900
1114
  if (!response || !Array.isArray(response)) {
901
1115
  throw new StandardError(400, 'Invalid skills response');
@@ -904,18 +1118,18 @@ export class AvroQueryClient {
904
1118
  })
905
1119
  .catch((err) => {
906
1120
  console.error('Failed to fetch skills:', err);
907
- throw new StandardError(500, 'Failed to fetch skills');
1121
+ throw fetchError(err, 'Failed to fetch skills');
908
1122
  });
909
1123
  }
910
- fetchSessions(body = {}, cancelToken, headers = {}) {
911
- if (!this.companyId || this.companyId.trim() === '') {
1124
+ fetchSessions(body = {}, cancelToken, headers = {}, companyId = this.companyId) {
1125
+ if (!companyId || companyId.trim() === '') {
912
1126
  throw new StandardError(400, 'Company ID is required');
913
1127
  }
914
1128
  const amount = body.amt ?? Math.max(body.unknown_ids?.length ?? 0, 50);
915
- return this._fetch('POST', `/company/${this.companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
1129
+ return this._fetch('POST', `/company/${companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
916
1130
  ...headers,
917
1131
  'Content-Type': 'application/json',
918
- })
1132
+ }, true)
919
1133
  .then((response) => {
920
1134
  if (!response || !Array.isArray(response)) {
921
1135
  throw new StandardError(400, 'Invalid sessions response');
@@ -924,7 +1138,7 @@ export class AvroQueryClient {
924
1138
  })
925
1139
  .catch((err) => {
926
1140
  console.error('Failed to fetch sessions:', err);
927
- throw new StandardError(500, 'Failed to fetch sessions');
1141
+ throw fetchError(err, 'Failed to fetch sessions');
928
1142
  });
929
1143
  }
930
1144
  _initEmailListeners() {