@go-avro/avro-js 0.1.15 → 1.6.0

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 (38) hide show
  1. package/dist/auth/AuthManager.d.ts +28 -0
  2. package/dist/auth/AuthManager.js +119 -43
  3. package/dist/client/QueryClient.d.ts +56 -1
  4. package/dist/client/QueryClient.js +260 -79
  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 +36 -30
  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 +3 -8
  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 +11 -27
  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 +12 -0
  32. package/dist/client/realtime.js +160 -46
  33. package/dist/types/api/Company.d.ts +2 -0
  34. package/dist/types/api/LineItem.d.ts +4 -0
  35. package/dist/types/api/LineItem.js +8 -1
  36. package/dist/version.d.ts +1 -1
  37. package/dist/version.js +1 -1
  38. 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;
@@ -23,6 +61,11 @@ export class AvroQueryClient {
23
61
  this._restored = null;
24
62
  this._emailTracking = new Map();
25
63
  this._emailListenersInit = false;
64
+ this._authCheck = null;
65
+ this._authRecheckTimer = null;
66
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
67
+ this._socketAuthRetried = false;
68
+ this._socketRetryTimer = null;
26
69
  this.config = {
27
70
  baseUrl: config.baseUrl,
28
71
  authManager: config.authManager,
@@ -39,27 +82,8 @@ export class AvroQueryClient {
39
82
  transports: ['websocket'],
40
83
  });
41
84
  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
85
  this.socket.on('connect', () => {
86
+ this._socketAuthRetried = false;
63
87
  this.setAuthState(AuthState.AUTHENTICATED);
64
88
  console.log(`Socket connected with ID: ${this.socket?.id}`);
65
89
  });
@@ -67,7 +91,8 @@ export class AvroQueryClient {
67
91
  console.log(`Socket disconnected: ${reason}`);
68
92
  });
69
93
  this.socket.on('connect_error', (err) => {
70
- console.error(`Socket connection error: ${err.message}`);
94
+ console.error(`Socket connection error: ${err?.message}`);
95
+ this.handleSocketConnectError();
71
96
  });
72
97
  this.config.authManager.onTokenRefreshed((newAccessToken) => {
73
98
  if (this.socket && newAccessToken) {
@@ -79,6 +104,133 @@ export class AvroQueryClient {
79
104
  config.authManager.onTokenRefreshFailed(() => {
80
105
  void this.forceLogout();
81
106
  });
107
+ // Cache the stored companyId even before auth resolves.
108
+ this.getCompanyId().then((id) => {
109
+ this.companyId ?? (this.companyId = id);
110
+ });
111
+ void this.recheckAuth();
112
+ // Browsers: re-check as soon as the network comes back.
113
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
114
+ window.addEventListener('online', () => {
115
+ if (this._authState === AuthState.UNKNOWN)
116
+ void this.recheckAuth();
117
+ });
118
+ }
119
+ }
120
+ /**
121
+ * Re-validate the stored session (deduplicated). Call it when the app
122
+ * returns to the foreground or regains connectivity; the SDK also calls
123
+ * it on a backoff timer and after the next successful request while the
124
+ * state is UNKNOWN (e.g. after an offline cold start). A network error
125
+ * or 5xx never downgrades the state to UNAUTHENTICATED: only a
126
+ * definitive auth failure does.
127
+ */
128
+ recheckAuth() {
129
+ if (this._authCheck)
130
+ return this._authCheck;
131
+ if (this._authRecheckTimer) {
132
+ clearTimeout(this._authRecheckTimer);
133
+ this._authRecheckTimer = null;
134
+ }
135
+ const check = this.config.authManager
136
+ .isAuthenticated()
137
+ .catch((err) => {
138
+ console.error('Auth check failed:', err);
139
+ return AuthState.UNKNOWN;
140
+ })
141
+ .then(async (state) => {
142
+ if (state === AuthState.AUTHENTICATED) {
143
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
144
+ this.setAuthState(state);
145
+ if (!this.socket.connected) {
146
+ try {
147
+ const [id, token] = await Promise.all([
148
+ this.getCompanyId(),
149
+ this.config.authManager.accessToken(),
150
+ ]);
151
+ this.companyId = id;
152
+ this.socket.auth = this.socketAuth(token);
153
+ this.ensureSocketConnected();
154
+ }
155
+ catch (err) {
156
+ console.error('Not logged in:', err);
157
+ }
158
+ }
159
+ }
160
+ else if (state === AuthState.UNAUTHENTICATED) {
161
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
162
+ this.setAuthState(state);
163
+ }
164
+ else {
165
+ // Couldn't reach the server. Keep a known state (an
166
+ // AUTHENTICATED session stays usable offline) and retry.
167
+ if (this._authState === AuthState.UNKNOWN)
168
+ this.setAuthState(state);
169
+ this.scheduleAuthRecheck();
170
+ }
171
+ return state;
172
+ })
173
+ .finally(() => {
174
+ this._authCheck = null;
175
+ });
176
+ this._authCheck = check;
177
+ return check;
178
+ }
179
+ scheduleAuthRecheck() {
180
+ if (this._authRecheckTimer)
181
+ return;
182
+ const delay = this._authRecheckDelay;
183
+ this._authRecheckDelay = Math.min(delay * 2, AUTH_RECHECK_MAX_MS);
184
+ this._authRecheckTimer = setTimeout(() => {
185
+ this._authRecheckTimer = null;
186
+ if (this._authState === AuthState.UNKNOWN)
187
+ void this.recheckAuth();
188
+ }, delay);
189
+ }
190
+ /** Called by the transports after any 2xx: the server is reachable again. */
191
+ _noteRequestSucceeded() {
192
+ if (this._authState === AuthState.UNKNOWN && !this._authCheck) {
193
+ void this.recheckAuth();
194
+ }
195
+ }
196
+ /**
197
+ * The server refuses the socket handshake when the access token has
198
+ * expired; socket.io then stops reconnecting (`active` is false).
199
+ * Refresh the token once (shared with any in-flight refresh) and
200
+ * reconnect with it. A definitive refresh failure logs out via
201
+ * onTokenRefreshFailed; a transient one retries after a delay.
202
+ */
203
+ handleSocketConnectError() {
204
+ if (this.socket.active)
205
+ return; // transport error: socket.io retries itself
206
+ if (this._authState !== AuthState.AUTHENTICATED)
207
+ return;
208
+ if (this._socketAuthRetried)
209
+ return; // refreshed already and still refused
210
+ this._socketAuthRetried = true;
211
+ this.config.authManager
212
+ .refreshTokens()
213
+ .then((tokens) => {
214
+ // onTokenRefreshed already reconnects; make sure regardless.
215
+ if (tokens?.access_token) {
216
+ this.socket.auth = this.socketAuth(tokens.access_token);
217
+ this.ensureSocketConnected();
218
+ }
219
+ })
220
+ .catch((err) => {
221
+ if (isDefinitiveAuthFailure(err))
222
+ return; // forceLogout runs
223
+ console.error('Socket token refresh failed; retrying later:', err);
224
+ if (this._socketRetryTimer)
225
+ return;
226
+ this._socketRetryTimer = setTimeout(() => {
227
+ this._socketRetryTimer = null;
228
+ this._socketAuthRetried = false;
229
+ if (this._authState === AuthState.AUTHENTICATED) {
230
+ this.ensureSocketConnected();
231
+ }
232
+ }, SOCKET_AUTH_RETRY_MS);
233
+ });
82
234
  }
83
235
  /** Handshake payload: the token plus, when known, this install's identity. */
84
236
  socketAuth(token) {
@@ -177,6 +329,7 @@ export class AvroQueryClient {
177
329
  path: `/company/${this.companyId}/users`,
178
330
  data: JSON.stringify({ user_ids: userIds }),
179
331
  headers: { 'Content-Type': 'application/json' },
332
+ idempotent: true,
180
333
  })
181
334
  .then((members) => {
182
335
  if (!Array.isArray(members)) {
@@ -287,8 +440,8 @@ export class AvroQueryClient {
287
440
  // Reporting must never become a second failure.
288
441
  }
289
442
  }
290
- post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, }) {
291
- return this._xhr('POST', path, data, cancelToken, headers, false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
443
+ post({ path, data, cancelToken, headers, progressUpdateCallback, maxRetries, idempotent, }) {
444
+ return this._xhr('POST', path, data, cancelToken, headers, idempotent ?? false, maxRetries ?? this.config.maxRetries, progressUpdateCallback);
292
445
  }
293
446
  put({ path, data, cancelToken, headers, progressUpdateCallback, }) {
294
447
  return this._xhr('PUT', path, data, cancelToken, headers, true, this.config.maxRetries, progressUpdateCallback);
@@ -296,13 +449,20 @@ export class AvroQueryClient {
296
449
  delete({ path, cancelToken, headers, progressUpdateCallback, }) {
297
450
  return this._xhr('DELETE', path, null, cancelToken, headers, false, this.config.maxRetries, progressUpdateCallback);
298
451
  }
299
- loginSuccess(tokens) {
452
+ /**
453
+ * Persist freshly issued tokens, then flip to AUTHENTICATED and connect
454
+ * the socket. Tokens are stored first so that anything reacting to the
455
+ * auth-state change (queries enabled on AUTHENTICATED) finds them.
456
+ */
457
+ async loginSuccess(tokens) {
458
+ await this.config.authManager.setTokens(tokens);
459
+ this._socketAuthRetried = false;
460
+ this._authRecheckDelay = AUTH_RECHECK_MIN_MS;
300
461
  this.setAuthState(AuthState.AUTHENTICATED);
301
462
  this.socket.auth = this.socketAuth(tokens.access_token);
302
463
  if (!this.socket.connected) {
303
464
  this.ensureSocketConnected();
304
465
  }
305
- return this.config.authManager.setTokens(tokens);
306
466
  }
307
467
  useLogin() {
308
468
  const queryClient = this.getQueryClient();
@@ -554,12 +714,25 @@ export class AvroQueryClient {
554
714
  * server that no longer recognizes our identity.
555
715
  */
556
716
  async forceLogout() {
717
+ // Stop the socket first, including one that is mid-reconnect
718
+ // (`active` but not `connected`), so it can't come back with the
719
+ // old token.
720
+ if (this.socket && (this.socket.connected || this.socket.active)) {
721
+ this.socket.disconnect();
722
+ }
723
+ this.socket.auth = {};
724
+ if (this._socketRetryTimer) {
725
+ clearTimeout(this._socketRetryTimer);
726
+ this._socketRetryTimer = null;
727
+ }
728
+ if (this._authRecheckTimer) {
729
+ clearTimeout(this._authRecheckTimer);
730
+ this._authRecheckTimer = null;
731
+ }
732
+ this._socketAuthRetried = false;
557
733
  await this.clearCache();
558
734
  await this._persister?.clear();
559
735
  this.setAuthState(AuthState.UNAUTHENTICATED);
560
- if (this.socket && this.socket.connected) {
561
- this.socket.disconnect();
562
- }
563
736
  this.peekQueryClient()?.removeQueries();
564
737
  }
565
738
  useLogout() {
@@ -593,7 +766,7 @@ export class AvroQueryClient {
593
766
  return this._fetch('POST', `/company/${companyIdToUse}/jobs`, JSON.stringify(body), cancelToken, {
594
767
  ...headers,
595
768
  'Content-Type': 'application/json',
596
- })
769
+ }, true)
597
770
  .then((response) => {
598
771
  if (!response || !Array.isArray(response)) {
599
772
  throw new StandardError(400, 'Invalid jobs response');
@@ -602,7 +775,7 @@ export class AvroQueryClient {
602
775
  })
603
776
  .catch((err) => {
604
777
  console.error('Failed to fetch jobs:', err);
605
- throw new StandardError(500, `Failed to fetch jobs: ${err.message ?? err}`);
778
+ throw fetchError(err, 'Failed to fetch jobs');
606
779
  });
607
780
  }
608
781
  async autocompleteAddress({ address, size = 10, include_census = true, }, cancelToken, headers = {}) {
@@ -660,23 +833,25 @@ export class AvroQueryClient {
660
833
  maxRetries: 0,
661
834
  });
662
835
  }
836
+ /**
837
+ * The caller's chats. The backend only exposes `GET /chat` (every chat
838
+ * the user belongs to, unpaged), so the id/query/paging filters are
839
+ * applied client-side.
840
+ */
663
841
  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
- })
842
+ return this._fetch('GET', '/chat', null, cancelToken, headers, true)
671
843
  .then((response) => {
672
844
  if (!response || !Array.isArray(response)) {
673
845
  throw new StandardError(400, 'Invalid chats response');
674
846
  }
675
- return response;
847
+ const scoped = this.companyId
848
+ ? response.filter((c) => !c?.company_id || c.company_id === this.companyId)
849
+ : response;
850
+ return filterLocally(scoped, body, (c) => [c?.name]);
676
851
  })
677
852
  .catch((err) => {
678
853
  console.error('Failed to fetch chats:', err);
679
- throw new StandardError(500, 'Failed to fetch chats');
854
+ throw fetchError(err, 'Failed to fetch chats');
680
855
  });
681
856
  }
682
857
  fetchMessages(chatId, body = {}, cancelToken, headers = {}) {
@@ -686,7 +861,7 @@ export class AvroQueryClient {
686
861
  return this._fetch('POST', `/chat/${chatId}/messages`, JSON.stringify(body), cancelToken, {
687
862
  ...headers,
688
863
  'Content-Type': 'application/json',
689
- })
864
+ }, true)
690
865
  .then((response) => {
691
866
  if (!response || !Array.isArray(response)) {
692
867
  throw new StandardError(400, 'Invalid messages response');
@@ -695,17 +870,17 @@ export class AvroQueryClient {
695
870
  })
696
871
  .catch((err) => {
697
872
  console.error('Failed to fetch messages:', err);
698
- throw new StandardError(500, 'Failed to fetch messages');
873
+ throw fetchError(err, 'Failed to fetch messages');
699
874
  });
700
875
  }
701
876
  async fetchPrepayments(body = {}, cancelToken, headers = {}) {
702
877
  if (!this.companyId || this.companyId.trim() === '') {
703
878
  throw new StandardError(400, 'Company ID is required');
704
879
  }
705
- return this._fetch('POST', `/company/${this.companyId}/prepayments`, JSON.stringify(body), cancelToken, {
880
+ return this._fetch('POST', `/company/${this.companyId}/prepayments`, JSON.stringify(withWireParent(body, 'taskId', 'task_id')), cancelToken, {
706
881
  ...headers,
707
882
  'Content-Type': 'application/json',
708
- })
883
+ }, true)
709
884
  .then((response) => {
710
885
  if (!response || !Array.isArray(response)) {
711
886
  throw new StandardError(400, 'Invalid prepayments response');
@@ -714,7 +889,7 @@ export class AvroQueryClient {
714
889
  })
715
890
  .catch((err) => {
716
891
  console.error('Failed to fetch prepayments:', err);
717
- throw new StandardError(500, 'Failed to fetch prepayments');
892
+ throw fetchError(err, 'Failed to fetch prepayments');
718
893
  });
719
894
  }
720
895
  async fetchWaivers(body = {}, cancelToken, headers = {}) {
@@ -724,7 +899,7 @@ export class AvroQueryClient {
724
899
  return this._fetch('POST', `/company/${this.companyId}/waivers`, JSON.stringify(body), cancelToken, {
725
900
  ...headers,
726
901
  'Content-Type': 'application/json',
727
- })
902
+ }, true)
728
903
  .then((response) => {
729
904
  if (!response || !Array.isArray(response)) {
730
905
  throw new StandardError(400, 'Invalid waivers response');
@@ -733,7 +908,7 @@ export class AvroQueryClient {
733
908
  })
734
909
  .catch((err) => {
735
910
  console.error('Failed to fetch waivers:', err);
736
- throw new StandardError(500, 'Failed to fetch waivers');
911
+ throw fetchError(err, 'Failed to fetch waivers');
737
912
  });
738
913
  }
739
914
  async fetchEvents(body = {}, cancelToken, headers = {}) {
@@ -743,7 +918,7 @@ export class AvroQueryClient {
743
918
  return this._fetch('POST', `/company/${this.companyId}/events`, JSON.stringify(body), cancelToken, {
744
919
  ...headers,
745
920
  'Content-Type': 'application/json',
746
- })
921
+ }, true)
747
922
  .then((response) => {
748
923
  if (!response || !Array.isArray(response)) {
749
924
  throw new StandardError(400, 'Invalid events response');
@@ -752,17 +927,17 @@ export class AvroQueryClient {
752
927
  })
753
928
  .catch((err) => {
754
929
  console.error('Failed to fetch events:', err);
755
- throw new StandardError(500, 'Failed to fetch events');
930
+ throw fetchError(err, 'Failed to fetch events');
756
931
  });
757
932
  }
758
933
  fetchMonths(body = {}, cancelToken, headers = {}) {
759
934
  if (!this.companyId || this.companyId.trim() === '') {
760
935
  throw new StandardError(400, 'Company ID is required');
761
936
  }
762
- return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(body), cancelToken, {
937
+ return this._fetch('POST', `/company/${this.companyId}/months`, JSON.stringify(withWireParent(body, 'jobId', 'job_id')), cancelToken, {
763
938
  ...headers,
764
939
  'Content-Type': 'application/json',
765
- })
940
+ }, true)
766
941
  .then((response) => {
767
942
  if (!response || !Array.isArray(response)) {
768
943
  throw new StandardError(400, 'Invalid months response');
@@ -771,7 +946,7 @@ export class AvroQueryClient {
771
946
  })
772
947
  .catch((err) => {
773
948
  console.error('Failed to fetch months:', err);
774
- throw new StandardError(500, 'Failed to fetch months');
949
+ throw fetchError(err, 'Failed to fetch months');
775
950
  });
776
951
  }
777
952
  fetchBills(body = {}, cancelToken, headers = {}) {
@@ -781,7 +956,7 @@ export class AvroQueryClient {
781
956
  return this._fetch('POST', `/company/${this.companyId}/bills`, JSON.stringify(body), cancelToken, {
782
957
  ...headers,
783
958
  'Content-Type': 'application/json',
784
- })
959
+ }, true)
785
960
  .then((response) => {
786
961
  if (!response || !Array.isArray(response)) {
787
962
  throw new StandardError(400, 'Invalid bills response');
@@ -790,7 +965,7 @@ export class AvroQueryClient {
790
965
  })
791
966
  .catch((err) => {
792
967
  console.error('Failed to fetch bills:', err);
793
- throw new StandardError(500, 'Failed to fetch bills');
968
+ throw fetchError(err, 'Failed to fetch bills');
794
969
  });
795
970
  }
796
971
  fetchPayouts(body = {}, cancelToken, headers = {}) {
@@ -800,7 +975,7 @@ export class AvroQueryClient {
800
975
  return this._fetch('POST', `/company/${this.companyId}/payouts`, JSON.stringify(body), cancelToken, {
801
976
  ...headers,
802
977
  'Content-Type': 'application/json',
803
- })
978
+ }, true)
804
979
  .then((response) => {
805
980
  if (!response || !Array.isArray(response)) {
806
981
  throw new StandardError(400, 'Invalid payouts response');
@@ -809,7 +984,7 @@ export class AvroQueryClient {
809
984
  })
810
985
  .catch((err) => {
811
986
  console.error('Failed to fetch payouts:', err);
812
- throw new StandardError(500, 'Failed to fetch payouts');
987
+ throw fetchError(err, 'Failed to fetch payouts');
813
988
  });
814
989
  }
815
990
  fetchRoutes(body = {}, cancelToken, headers = {}) {
@@ -819,7 +994,7 @@ export class AvroQueryClient {
819
994
  return this._fetch('POST', `/company/${this.companyId}/routes`, JSON.stringify(body), cancelToken, {
820
995
  ...headers,
821
996
  'Content-Type': 'application/json',
822
- })
997
+ }, true)
823
998
  .then((response) => {
824
999
  if (!response || !Array.isArray(response)) {
825
1000
  throw new StandardError(400, 'Invalid routes response');
@@ -828,7 +1003,7 @@ export class AvroQueryClient {
828
1003
  })
829
1004
  .catch((err) => {
830
1005
  console.error('Failed to fetch routes:', err);
831
- throw new StandardError(500, 'Failed to fetch routes');
1006
+ throw fetchError(err, 'Failed to fetch routes');
832
1007
  });
833
1008
  }
834
1009
  fetchTeams(body = {}, cancelToken, headers = {}) {
@@ -838,7 +1013,7 @@ export class AvroQueryClient {
838
1013
  return this._fetch('POST', `/company/${this.companyId}/teams`, JSON.stringify(body), cancelToken, {
839
1014
  ...headers,
840
1015
  'Content-Type': 'application/json',
841
- })
1016
+ }, true)
842
1017
  .then((response) => {
843
1018
  if (!response || !Array.isArray(response)) {
844
1019
  throw new StandardError(400, 'Invalid teams response');
@@ -847,45 +1022,51 @@ export class AvroQueryClient {
847
1022
  })
848
1023
  .catch((err) => {
849
1024
  console.error('Failed to fetch teams:', err);
850
- throw new StandardError(500, 'Failed to fetch teams');
1025
+ throw fetchError(err, 'Failed to fetch teams');
851
1026
  });
852
1027
  }
1028
+ /**
1029
+ * Company labels. There is no list endpoint for them: they are embedded
1030
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1031
+ * client-side.
1032
+ */
853
1033
  fetchLabels(body = {}, cancelToken, headers = {}) {
854
1034
  if (!this.companyId || this.companyId.trim() === '') {
855
1035
  throw new StandardError(400, 'Company ID is required');
856
1036
  }
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)) {
1037
+ return this._fetch('GET', `/company/${this.companyId}`, null, cancelToken, headers, true)
1038
+ .then((company) => {
1039
+ const items = company?.labels;
1040
+ if (!Array.isArray(items)) {
863
1041
  throw new StandardError(400, 'Invalid labels response');
864
1042
  }
865
- return response;
1043
+ return filterLocally(items, body, (x) => [x?.name]);
866
1044
  })
867
1045
  .catch((err) => {
868
1046
  console.error('Failed to fetch labels:', err);
869
- throw new StandardError(500, 'Failed to fetch labels');
1047
+ throw fetchError(err, 'Failed to fetch labels');
870
1048
  });
871
1049
  }
1050
+ /**
1051
+ * Company groups. There is no list endpoint for them: they are embedded
1052
+ * in `GET /company/<id>`, so the id/query/paging filters are applied
1053
+ * client-side.
1054
+ */
872
1055
  fetchGroups(body = {}, cancelToken, headers = {}) {
873
1056
  if (!this.companyId || this.companyId.trim() === '') {
874
1057
  throw new StandardError(400, 'Company ID is required');
875
1058
  }
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)) {
1059
+ return this._fetch('GET', `/company/${this.companyId}`, null, cancelToken, headers, true)
1060
+ .then((company) => {
1061
+ const items = company?.groups;
1062
+ if (!Array.isArray(items)) {
882
1063
  throw new StandardError(400, 'Invalid groups response');
883
1064
  }
884
- return response;
1065
+ return filterLocally(items, body, (x) => [x?.name]);
885
1066
  })
886
1067
  .catch((err) => {
887
1068
  console.error('Failed to fetch groups:', err);
888
- throw new StandardError(500, 'Failed to fetch groups');
1069
+ throw fetchError(err, 'Failed to fetch groups');
889
1070
  });
890
1071
  }
891
1072
  fetchSkills(body = {}, cancelToken, headers = {}) {
@@ -895,7 +1076,7 @@ export class AvroQueryClient {
895
1076
  return this._fetch('POST', `/company/${this.companyId}/skills`, JSON.stringify(body), cancelToken, {
896
1077
  ...headers,
897
1078
  'Content-Type': 'application/json',
898
- })
1079
+ }, true)
899
1080
  .then((response) => {
900
1081
  if (!response || !Array.isArray(response)) {
901
1082
  throw new StandardError(400, 'Invalid skills response');
@@ -904,7 +1085,7 @@ export class AvroQueryClient {
904
1085
  })
905
1086
  .catch((err) => {
906
1087
  console.error('Failed to fetch skills:', err);
907
- throw new StandardError(500, 'Failed to fetch skills');
1088
+ throw fetchError(err, 'Failed to fetch skills');
908
1089
  });
909
1090
  }
910
1091
  fetchSessions(body = {}, cancelToken, headers = {}) {
@@ -915,7 +1096,7 @@ export class AvroQueryClient {
915
1096
  return this._fetch('POST', `/company/${this.companyId}/sessions?amount=${amount}`, JSON.stringify({ ...body, amt: amount }), cancelToken, {
916
1097
  ...headers,
917
1098
  'Content-Type': 'application/json',
918
- })
1099
+ }, true)
919
1100
  .then((response) => {
920
1101
  if (!response || !Array.isArray(response)) {
921
1102
  throw new StandardError(400, 'Invalid sessions response');
@@ -924,7 +1105,7 @@ export class AvroQueryClient {
924
1105
  })
925
1106
  .catch((err) => {
926
1107
  console.error('Failed to fetch sessions:', err);
927
- throw new StandardError(500, 'Failed to fetch sessions');
1108
+ throw fetchError(err, 'Failed to fetch sessions');
928
1109
  });
929
1110
  }
930
1111
  _initEmailListeners() {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Small cache helpers shared by the hooks: namespace snapshots for
3
+ * optimistic-update rollback, detail seeding from list fetches, and
4
+ * optimistic-row cleanup.
5
+ */
6
+ import { QueryClient, QueryKey } from '@tanstack/react-query';
7
+ export type NsSnapshot = Array<[QueryKey, unknown]>;
8
+ /**
9
+ * Snapshot every cached query under `ns` (lists and details). A plain
10
+ * `getQueryData([ns])` only reads the exact key `[ns]`, which no hook
11
+ * uses, so rollbacks built on it were no-ops.
12
+ */
13
+ export declare function snapshotNs(qc: QueryClient, ns: string): NsSnapshot;
14
+ /** Restore a snapshot taken with `snapshotNs`. */
15
+ export declare function restoreNs(qc: QueryClient, snapshot: NsSnapshot | undefined): void;
16
+ /**
17
+ * Seed `[ns, id]` detail entries from a fetched list. Call from inside a
18
+ * `queryFn` (never during render).
19
+ */
20
+ export declare function seedDetails<T extends {
21
+ id?: string;
22
+ }>(qc: QueryClient | null, ns: string, items: T[]): T[];
23
+ /** Remove an optimistic row (by its temporary id) from every list in `ns`. */
24
+ export declare function removeOptimisticRow(qc: QueryClient, ns: string, tempId: string): void;