@go-avro/avro-js 0.0.108 → 0.0.110

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.
@@ -7,9 +7,10 @@ export interface AvroQueryClientProviderProps {
7
7
  authManager: AuthManager;
8
8
  queryClient: QueryClient;
9
9
  configOverrides?: Partial<AvroQueryClientConfig>;
10
+ client?: AvroQueryClient;
10
11
  children: ReactNode;
11
12
  }
12
- export declare const AvroQueryClientProvider: ({ baseUrl, authManager, queryClient, configOverrides, children, }: AvroQueryClientProviderProps) => React.JSX.Element;
13
+ export declare const AvroQueryClientProvider: ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, children, }: AvroQueryClientProviderProps) => React.JSX.Element;
13
14
  export declare const useAvroQueryClient: () => AvroQueryClient;
14
15
  export declare const useSocketEvent: (eventName: string, callback: (data: Record<string, unknown>) => void) => void;
15
16
  export default AvroQueryClientProvider;
@@ -1,15 +1,17 @@
1
1
  import React, { createContext, useContext, useMemo, useEffect, useRef, useCallback, } from 'react';
2
2
  import { AvroQueryClient } from './QueryClient';
3
3
  const AvroQueryClientContext = createContext(null);
4
- export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, configOverrides, children, }) => {
4
+ export const AvroQueryClientProvider = ({ baseUrl, authManager, queryClient, configOverrides, client: providedClient, children, }) => {
5
5
  const client = useMemo(() => {
6
+ if (providedClient)
7
+ return providedClient;
6
8
  const cfg = {
7
9
  baseUrl,
8
10
  authManager,
9
11
  ...(configOverrides || {}),
10
12
  };
11
13
  return new AvroQueryClient(cfg);
12
- }, [baseUrl, authManager, configOverrides]);
14
+ }, [providedClient, baseUrl, authManager, configOverrides]);
13
15
  useEffect(() => {
14
16
  if (queryClient) {
15
17
  client.setupSocketInvalidation(queryClient);
@@ -678,6 +678,9 @@ export declare class AvroQueryClient {
678
678
  /** The install identity sent with sockets and location pings, if any. */
679
679
  get device(): DeviceInfo | undefined;
680
680
  setDevice(device: DeviceInfo | undefined): void;
681
+ private ensureSocketConnected;
682
+ /** Tell the server which install this live socket belongs to. */
683
+ private registerDevice;
681
684
  emit(eventName: string, data: unknown): void;
682
685
  on<T>(eventName: string, callback: (data: T) => void): void;
683
686
  off(eventName: string, callback?: Function): void;
@@ -400,17 +400,15 @@ export class AvroQueryClient {
400
400
  autoConnect: false,
401
401
  transports: ['websocket'],
402
402
  });
403
+ this.socket.on('connect', () => this.registerDevice());
403
404
  config.authManager.isAuthenticated().then((isAuth) => {
404
405
  this.setAuthState(isAuth);
405
406
  if (!this.socket.connected && isAuth === AuthState.AUTHENTICATED) {
406
- // Resolve both companyId and access token before connecting so
407
- // the 'connect' handler in setupSocketInvalidation can immediately
408
- // join the company room.
409
407
  Promise.all([this.getCompanyId(), this.config.authManager.accessToken()])
410
408
  .then(([id, token]) => {
411
409
  this.companyId = id;
412
410
  this.socket.auth = this.socketAuth(token);
413
- this.socket.connect();
411
+ this.ensureSocketConnected();
414
412
  })
415
413
  .catch((err) => {
416
414
  console.error('Not logged in:', err);
@@ -437,7 +435,7 @@ export class AvroQueryClient {
437
435
  if (this.socket && newAccessToken) {
438
436
  this.setAuthState(AuthState.AUTHENTICATED);
439
437
  this.socket.auth = this.socketAuth(newAccessToken);
440
- this.socket.disconnect().connect();
438
+ this.ensureSocketConnected();
441
439
  }
442
440
  });
443
441
  config.authManager.onTokenRefreshFailed(() => {
@@ -455,11 +453,22 @@ export class AvroQueryClient {
455
453
  setDevice(device) {
456
454
  this.config.device = device;
457
455
  const auth = this.socket.auth;
458
- if (!auth?.token)
459
- return;
460
- this.socket.auth = this.socketAuth(auth.token);
461
- if (this.socket.connected || this.socket.active) {
462
- this.socket.disconnect().connect();
456
+ if (auth?.token)
457
+ this.socket.auth = this.socketAuth(auth.token);
458
+ // Don't reconnect: a restart mid-handshake leaks the original
459
+ // connection. Declare the device on whatever socket is live now;
460
+ // the 'connect' handler repeats it on every (re)connect.
461
+ this.registerDevice();
462
+ }
463
+ ensureSocketConnected() {
464
+ if (!this.socket.connected && !this.socket.active) {
465
+ this.socket.connect();
466
+ }
467
+ }
468
+ /** Tell the server which install this live socket belongs to. */
469
+ registerDevice() {
470
+ if (this.config.device && this.socket.connected) {
471
+ this.socket.emit('register_device', this.config.device);
463
472
  }
464
473
  }
465
474
  emit(eventName, data) {
@@ -501,7 +510,37 @@ export class AvroQueryClient {
501
510
  predicate: (q) => matchesEntityKey(q, entityKey),
502
511
  });
503
512
  };
513
+ const patchMemberLocation = (data) => {
514
+ const userId = data?.user_id;
515
+ if (!userId || typeof userId !== 'string' || typeof data?.latitude !== 'number') {
516
+ queryClient.invalidateQueries({ queryKey: ['companies'] });
517
+ return;
518
+ }
519
+ queryClient.setQueriesData({ queryKey: ['companies'] }, (old) => {
520
+ if (!old || !Array.isArray(old.users))
521
+ return old;
522
+ let changed = false;
523
+ const users = old.users.map((u) => {
524
+ if (u?.user?.id !== userId)
525
+ return u;
526
+ changed = true;
527
+ return { ...u, last_location: data };
528
+ });
529
+ return changed ? { ...old, users } : old;
530
+ });
531
+ };
504
532
  for (const [event, config] of Object.entries(SOCKET_EVENT_CONFIG)) {
533
+ if (event === 'location_update' && isBulkEvent(config)) {
534
+ const handler = (data) => {
535
+ patchMemberLocation(data);
536
+ for (const key of config.invalidateKeys) {
537
+ queryClient.invalidateQueries({ queryKey: key });
538
+ }
539
+ };
540
+ this.socket.on(event, handler);
541
+ handlers.push({ event, handler });
542
+ continue;
543
+ }
505
544
  if (isBulkEvent(config)) {
506
545
  // ── Bulk: invalidate all specified keys ──────────────
507
546
  const handler = () => {
@@ -618,9 +657,9 @@ export class AvroQueryClient {
618
657
  }
619
658
  loginSuccess(tokens) {
620
659
  this.setAuthState(AuthState.AUTHENTICATED);
621
- this.socket.auth = { token: tokens.access_token };
660
+ this.socket.auth = this.socketAuth(tokens.access_token);
622
661
  if (!this.socket.connected) {
623
- this.socket.connect();
662
+ this.ensureSocketConnected();
624
663
  }
625
664
  return this.config.authManager.setTokens(tokens);
626
665
  }
@@ -706,9 +745,9 @@ export class AvroQueryClient {
706
745
  throw new StandardError(401, 'Invalid Google login response');
707
746
  }
708
747
  this.setAuthState(AuthState.AUTHENTICATED);
709
- this.socket.auth = { token: resp.access_token };
748
+ this.socket.auth = this.socketAuth(resp.access_token);
710
749
  if (!this.socket.connected) {
711
- this.socket.connect();
750
+ this.ensureSocketConnected();
712
751
  }
713
752
  await this.config.authManager.setTokens({
714
753
  access_token: resp.access_token,
@@ -737,9 +776,9 @@ export class AvroQueryClient {
737
776
  throw new StandardError(401, 'Invalid Apple login response');
738
777
  }
739
778
  this.setAuthState(AuthState.AUTHENTICATED);
740
- this.socket.auth = { token: resp.access_token };
779
+ this.socket.auth = this.socketAuth(resp.access_token);
741
780
  if (!this.socket.connected) {
742
- this.socket.connect();
781
+ this.ensureSocketConnected();
743
782
  }
744
783
  await this.config.authManager.setTokens({
745
784
  access_token: resp.access_token,
package/dist/index.d.ts CHANGED
@@ -40,7 +40,7 @@ import './client/hooks/email';
40
40
  export { defaultPassOnFeeMethod } from './billing/fees';
41
41
  export { reverseGeocode } from './geocode';
42
42
  export { fetchCensusFeatures } from './census';
43
- export { LOCATION_STALE_MINUTES, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, } from './presence';
43
+ export { LOCATION_STALE_MINUTES, LOCATION_RECENT_HOURS, isLocationRecent, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, } from './presence';
44
44
  export type { ReverseGeocodeResult } from './geocode';
45
45
  export * from './types/api';
46
46
  export * from './types/auth';
package/dist/index.js CHANGED
@@ -38,7 +38,7 @@ import './client/hooks/email';
38
38
  export { defaultPassOnFeeMethod } from './billing/fees';
39
39
  export { reverseGeocode } from './geocode';
40
40
  export { fetchCensusFeatures } from './census';
41
- export { LOCATION_STALE_MINUTES, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, } from './presence';
41
+ export { LOCATION_STALE_MINUTES, LOCATION_RECENT_HOURS, isLocationRecent, REPORTING_STATUSES, locationAgeMinutes, isLocationStale, isReportingStatus, isMobileDevice, mobileDevices, } from './presence';
42
42
  export * from './types/api';
43
43
  export * from './types/auth';
44
44
  export * from './types/cache';
@@ -16,8 +16,12 @@ export declare const mobileDevices: (devices: Device[] | null | undefined) => De
16
16
  * stationary phone in the background on iOS). Distinct from
17
17
  * `location_status`, which reports permissions / app liveness.
18
18
  */
19
- export declare const LOCATION_STALE_MINUTES = 15;
19
+ export declare const LOCATION_STALE_MINUTES = 5;
20
20
  /** Age of a location fix in whole minutes, or null when there is none. */
21
21
  export declare const locationAgeMinutes: (location: Pick<Location, "time_collected"> | null | undefined, nowMs?: number) => number | null;
22
22
  /** True when the fix is missing or older than `staleMinutes`. */
23
23
  export declare const isLocationStale: (location: Pick<Location, "time_collected"> | null | undefined, staleMinutes?: number, nowMs?: number) => boolean;
24
+ /** Members with a fix newer than this still appear on the map. */
25
+ export declare const LOCATION_RECENT_HOURS = 24;
26
+ /** True when the fix exists and is newer than `hours` old. */
27
+ export declare const isLocationRecent: (location: Pick<Location, "time_collected"> | null | undefined, hours?: number, nowMs?: number) => boolean;
package/dist/presence.js CHANGED
@@ -19,7 +19,7 @@ export const mobileDevices = (devices) => (devices ?? []).filter(isMobileDevice)
19
19
  * stationary phone in the background on iOS). Distinct from
20
20
  * `location_status`, which reports permissions / app liveness.
21
21
  */
22
- export const LOCATION_STALE_MINUTES = 15;
22
+ export const LOCATION_STALE_MINUTES = 5;
23
23
  /** Age of a location fix in whole minutes, or null when there is none. */
24
24
  export const locationAgeMinutes = (location, nowMs = Date.now()) => {
25
25
  if (!location?.time_collected)
@@ -31,3 +31,10 @@ export const isLocationStale = (location, staleMinutes = LOCATION_STALE_MINUTES,
31
31
  const age = locationAgeMinutes(location, nowMs);
32
32
  return age === null || age >= staleMinutes;
33
33
  };
34
+ /** Members with a fix newer than this still appear on the map. */
35
+ export const LOCATION_RECENT_HOURS = 24;
36
+ /** True when the fix exists and is newer than `hours` old. */
37
+ export const isLocationRecent = (location, hours = LOCATION_RECENT_HOURS, nowMs = Date.now()) => {
38
+ const age = locationAgeMinutes(location, nowMs);
39
+ return age !== null && age < hours * 60;
40
+ };
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AVRO_JS_VERSION = "0.0.108";
1
+ export declare const AVRO_JS_VERSION = "0.0.110";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // AUTO-GENERATED by scripts/gen-version.js — do not edit by hand.
2
2
  // Regenerated from package.json by the `prebuild` npm hook.
3
- export const AVRO_JS_VERSION = '0.0.108';
3
+ export const AVRO_JS_VERSION = '0.0.110';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@go-avro/avro-js",
3
- "version": "0.0.108",
3
+ "version": "0.0.110",
4
4
  "description": "JS client for Avro backend integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",