@chaosity/location-client-react 0.1.18 → 0.2.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.
package/README.md CHANGED
@@ -50,14 +50,17 @@ export default function RootLayout({
50
50
 
51
51
  ```tsx
52
52
  import { useLocationClient } from '@chaosity/location-client-react'
53
- import { SuggestCommand } from '@chaosity/location-client'
53
+ import {
54
+ SuggestCommand,
55
+ type SuggestCommandOutput,
56
+ } from '@chaosity/location-client'
54
57
 
55
58
  function SearchComponent() {
56
59
  const { client, loading, error } = useLocationClient()
57
60
 
58
61
  const searchPlaces = async (query: string) => {
59
62
  if (!client) return
60
- const response = await client.send(
63
+ const response: SuggestCommandOutput = await client.send(
61
64
  new SuggestCommand({ QueryText: query, MaxResults: 5 }),
62
65
  )
63
66
  return response.ResultItems
@@ -87,9 +90,7 @@ function MapComponent() {
87
90
  useMapLanguage(mapInstance, language)
88
91
 
89
92
  useEffect(() => {
90
- const map = new maplibregl.Map({
91
- /* ... */
92
- })
93
+ const map = new maplibregl.Map({/* ... */})
93
94
  map.once('load', () => setMapInstance(map))
94
95
  return () => map.remove()
95
96
  }, [])
@@ -261,6 +262,7 @@ All AWS Location Service commands are available through the client:
261
262
  ```tsx
262
263
  import {
263
264
  SuggestCommand,
265
+ type SuggestCommandOutput,
264
266
  GeocodeCommand,
265
267
  ReverseGeocodeCommand,
266
268
  GetPlaceCommand,
@@ -272,7 +274,7 @@ function MyComponent() {
272
274
  const { client } = useLocationClient()
273
275
 
274
276
  const search = async () => {
275
- const response = await client!.send(
277
+ const response: SuggestCommandOutput = await client!.send(
276
278
  new SuggestCommand({ QueryText: 'Vancouver', MaxResults: 5 }),
277
279
  )
278
280
  return response.ResultItems
@@ -293,7 +295,10 @@ DEBUG=location-client-react:* npm run dev
293
295
  Full TypeScript support with types from AWS SDK:
294
296
 
295
297
  ```tsx
296
- import type { SuggestCommandOutput } from '@aws-sdk/client-geo-places'
298
+ import {
299
+ SuggestCommand,
300
+ type SuggestCommandOutput,
301
+ } from '@chaosity/location-client'
297
302
 
298
303
  const { client } = useLocationClient()
299
304
  const response: SuggestCommandOutput = await client!.send(
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { LocationClientProvider, useLocationClient, } from './provider/LocationClientProvider';
2
- export type { LocationClientProviderProps } from './provider/LocationClientProvider';
2
+ export type { LocationClient, LocationClientProviderProps, SendOptions, } from './provider/LocationClientProvider';
3
3
  export { useMapLanguage } from './hooks/useMapLanguage';
@@ -1,8 +1,34 @@
1
1
  import type { ClientConfig } from '@chaosity/location-client';
2
- import { GeoPlacesClient } from '@chaosity/location-client';
3
2
  import type { ReactNode } from 'react';
3
+ /**
4
+ * Per-request transport options.
5
+ *
6
+ * Declared structurally rather than imported so this package builds against the
7
+ * currently published client; it matches `SendOptions` there exactly.
8
+ */
9
+ export interface SendOptions {
10
+ signal?: AbortSignal;
11
+ timeoutMs?: number;
12
+ retry?: false | {
13
+ maxAttempts?: number;
14
+ };
15
+ }
16
+ /**
17
+ * What the provider hands out.
18
+ *
19
+ * An interface rather than `GeoPlacesClient` because the provider wraps the
20
+ * real client to refresh tokens first, and a class with private fields is not
21
+ * structurally assignable — which is why this used to be an `Object.create`
22
+ * prototype hack.
23
+ */
24
+ export interface LocationClient {
25
+ readonly config: {
26
+ serviceId: string;
27
+ };
28
+ send<TInput, TOutput>(command: TInput, options?: SendOptions): Promise<TOutput>;
29
+ }
4
30
  interface LocationClientContextValue {
5
- client: GeoPlacesClient | null;
31
+ client: LocationClient | null;
6
32
  getToken: () => string | undefined;
7
33
  loading: boolean;
8
34
  error: string | null;
@@ -15,6 +41,6 @@ export interface LocationClientProviderProps {
15
41
  /** Seconds before expiry to proactively refresh (default: 60) */
16
42
  refreshBuffer?: number;
17
43
  }
18
- export declare function LocationClientProvider({ children, getConfig, refreshBuffer, }: LocationClientProviderProps): import("react/jsx-runtime").JSX.Element;
44
+ export declare function LocationClientProvider({ children, getConfig, refreshBuffer, }: LocationClientProviderProps): import("react").JSX.Element;
19
45
  export declare function useLocationClient(): LocationClientContextValue;
20
46
  export {};
@@ -5,102 +5,177 @@ import debug from 'debug';
5
5
  import { createContext, useCallback, useContext, useEffect, useRef, useState, } from 'react';
6
6
  const log = debug('location-client-react:provider');
7
7
  const LocationClientContext = createContext(undefined);
8
+ const DEFAULT_LIFETIME_MS = 900000;
8
9
  export function LocationClientProvider({ children, getConfig, refreshBuffer = 60, }) {
9
10
  const [client, setClient] = useState(null);
10
11
  const [loading, setLoading] = useState(true);
11
12
  const [error, setError] = useState(null);
12
- // Refs hold live values without triggering re-renders
13
13
  const tokenRef = useRef(undefined);
14
14
  const expiresAtRef = useRef(null);
15
15
  const getConfigRef = useRef(getConfig);
16
16
  const refreshPromiseRef = useRef(null);
17
- const ensureValidTokenRef = useRef(async () => { });
18
- // Keep getConfig ref current without recreating callbacks
17
+ const timerRef = useRef(null);
18
+ const mountedRef = useRef(true);
19
19
  useEffect(() => {
20
20
  getConfigRef.current = getConfig;
21
21
  }, [getConfig]);
22
- // Stable token getter — passed into GeoPlacesClient so it always reads the live ref
23
- const getToken = useCallback(() => tokenRef.current, []);
24
- // Returns true when the token is expired or within the refresh buffer window.
25
- // Treats unknown expiry as expired so we always refresh on first use.
26
22
  const isTokenExpired = useCallback(() => {
27
23
  if (!expiresAtRef.current)
28
24
  return true;
29
25
  return Date.now() >= expiresAtRef.current - refreshBuffer * 1000;
30
26
  }, [refreshBuffer]);
31
- // Refreshes the token exactly once even when called concurrently.
32
- // All concurrent callers await the same in-flight promise — same pattern as
33
- // server-side TokenProvider.tokenPromise deduplication.
34
- const ensureValidToken = useCallback(async () => {
35
- if (!isTokenExpired())
36
- return;
37
- // Deduplicate: if a refresh is already in flight, wait for it instead of firing another
38
- if (refreshPromiseRef.current) {
39
- log('Token refresh already in progress, waiting...');
27
+ /**
28
+ * Refresh once, however many callers ask at the same moment.
29
+ *
30
+ * REJECTS on failure. It used to swallow the error into state and resolve,
31
+ * so `send` carried on with the token it already had — guaranteeing a 401 on
32
+ * the very next call and reporting it as an API error rather than a refresh
33
+ * failure.
34
+ */
35
+ const refreshToken = useCallback(async () => {
36
+ if (refreshPromiseRef.current)
40
37
  return refreshPromiseRef.current;
41
- }
42
- const timeUntilExpiry = expiresAtRef.current
43
- ? Math.floor((expiresAtRef.current - Date.now()) / 1000)
44
- : 0;
45
- log('Token expired or expiring soon (in %ds), refreshing...', timeUntilExpiry);
46
38
  refreshPromiseRef.current = (async () => {
47
39
  const cfg = await getConfigRef.current();
48
40
  tokenRef.current = cfg.token;
49
- expiresAtRef.current = cfg.expiresAt ?? Date.now() + 900000;
50
- const newExpiry = Math.floor((expiresAtRef.current - Date.now()) / 1000);
51
- log('Token refreshed (expires in %ds)', newExpiry);
41
+ expiresAtRef.current = cfg.expiresAt ?? Date.now() + DEFAULT_LIFETIME_MS;
42
+ log('Token refreshed (expires in %ds)', Math.floor((expiresAtRef.current - Date.now()) / 1000));
43
+ if (mountedRef.current)
44
+ setError(null);
52
45
  })();
53
46
  try {
54
47
  await refreshPromiseRef.current;
48
+ scheduleRefreshRef.current();
55
49
  }
56
50
  catch (err) {
57
- log('Token refresh failed: %s', err instanceof Error ? err.message : 'Unknown error');
58
- setError(err instanceof Error ? err.message : 'Failed to refresh token');
51
+ const message = err instanceof Error ? err.message : 'Failed to refresh token';
52
+ log('Token refresh failed: %s', message);
53
+ if (mountedRef.current)
54
+ setError(message);
55
+ throw err;
59
56
  }
60
57
  finally {
61
58
  refreshPromiseRef.current = null;
62
59
  }
63
- }, [isTokenExpired]);
64
- // Keep ensureValidToken ref current so the send wrapper always uses the latest version
60
+ }, []);
61
+ /**
62
+ * Refresh AHEAD of expiry, on a timer.
63
+ *
64
+ * This is the whole fix for the map path. MapLibre's `transformRequest` is
65
+ * synchronous by contract, so `getToken` cannot await anything — the token it
66
+ * reads has to be valid already. Refresh used to happen only inside the `send`
67
+ * wrapper, which the map never calls: it requests tiles, glyphs and sprites
68
+ * directly. So after 15 minutes every map request failed, for as long as the
69
+ * page stayed open, and no amount of panning recovered it.
70
+ */
71
+ const scheduleRefresh = useCallback(() => {
72
+ if (timerRef.current)
73
+ clearTimeout(timerRef.current);
74
+ if (!expiresAtRef.current)
75
+ return;
76
+ const delay = Math.max(0, expiresAtRef.current - refreshBuffer * 1000 - Date.now());
77
+ log('Next refresh in %ds', Math.floor(delay / 1000));
78
+ timerRef.current = setTimeout(() => {
79
+ // Errors are already surfaced onto state by refreshToken; swallow here so
80
+ // a failed background refresh cannot become an unhandled rejection.
81
+ void refreshToken().catch(() => { });
82
+ }, delay);
83
+ }, [refreshBuffer, refreshToken]);
84
+ // refreshToken and scheduleRefresh reference each other; a ref breaks the cycle
85
+ // without recreating either callback on every render.
86
+ const scheduleRefreshRef = useRef(() => { });
87
+ useEffect(() => {
88
+ scheduleRefreshRef.current = scheduleRefresh;
89
+ }, [scheduleRefresh]);
90
+ /**
91
+ * Synchronous read for the map path.
92
+ *
93
+ * If the token is already stale — a timer that never fired because the tab was
94
+ * backgrounded and throttled — this kicks off a refresh but cannot wait for it.
95
+ * The current read still returns the stale value; the point is that the NEXT
96
+ * one will not.
97
+ */
98
+ const getToken = useCallback(() => {
99
+ // `tokenRef.current` guards the pre-initialisation window: until the first
100
+ // config load lands there is no expiry to judge, and firing here would race
101
+ // the initial fetch and request a second token nobody asked for.
102
+ if (tokenRef.current && isTokenExpired() && !refreshPromiseRef.current) {
103
+ log('Stale token read — refreshing in the background');
104
+ void refreshToken().catch(() => { });
105
+ }
106
+ return tokenRef.current;
107
+ }, [isTokenExpired, refreshToken]);
108
+ const ensureValidToken = useCallback(async () => {
109
+ if (!isTokenExpired())
110
+ return;
111
+ await refreshToken();
112
+ }, [isTokenExpired, refreshToken]);
113
+ const ensureValidTokenRef = useRef(ensureValidToken);
65
114
  useEffect(() => {
66
115
  ensureValidTokenRef.current = ensureValidToken;
67
116
  }, [ensureValidToken]);
68
- // Initial load — create the client once.
69
- // getToken is passed as a callback so the client always reads the live token ref.
70
- // ensureValidToken is called before each send so expiring tokens are refreshed
71
- // transparently without recreating the client or causing re-renders.
117
+ /**
118
+ * A backgrounded tab has its timers throttled, so the scheduled refresh can be
119
+ * arbitrarily late. Refresh on the way back in, before the user touches the map.
120
+ */
121
+ useEffect(() => {
122
+ if (typeof document === 'undefined')
123
+ return;
124
+ const onVisible = () => {
125
+ if (document.visibilityState === 'visible' &&
126
+ tokenRef.current &&
127
+ isTokenExpired()) {
128
+ log('Tab visible again with a stale token — refreshing');
129
+ void refreshToken().catch(() => { });
130
+ }
131
+ };
132
+ document.addEventListener('visibilitychange', onVisible);
133
+ return () => document.removeEventListener('visibilitychange', onVisible);
134
+ }, [isTokenExpired, refreshToken]);
72
135
  useEffect(() => {
136
+ mountedRef.current = true;
73
137
  log('Initializing LocationClientProvider');
74
138
  getConfigRef
75
139
  .current()
76
140
  .then((cfg) => {
141
+ if (!mountedRef.current)
142
+ return;
77
143
  tokenRef.current = cfg.token;
78
- expiresAtRef.current = cfg.expiresAt ?? Date.now() + 900000;
79
- // GeoPlacesClient.send() calls getToken() synchronously for the token value,
80
- // but token refresh is async. We create a thin send wrapper that:
81
- // 1. awaits ensureValidToken (via ref — always latest, race-safe)
82
- // 2. delegates to baseClient which reads the now-fresh token from getToken()
83
- // The client instance is created once and never recreated on token refresh.
144
+ expiresAtRef.current = cfg.expiresAt ?? Date.now() + DEFAULT_LIFETIME_MS;
84
145
  const baseClient = new GeoPlacesClient({
85
146
  apiUrl: cfg.apiUrl,
86
147
  token: cfg.token,
87
148
  getToken,
88
149
  });
89
- const wrappingClient = Object.create(baseClient);
90
- wrappingClient.send = async (command) => {
91
- await ensureValidTokenRef.current();
92
- return baseClient.send(command);
150
+ // A plain object, not Object.create(baseClient): the prototype hack was
151
+ // opaque, and its `send` dropped the second argument entirely — so once
152
+ // the client gained `signal`/`timeoutMs`, every option passed through
153
+ // this provider would have been silently discarded.
154
+ const refreshing = {
155
+ config: baseClient.config,
156
+ async send(command, options) {
157
+ await ensureValidTokenRef.current();
158
+ return baseClient.send(command, options);
159
+ },
93
160
  };
94
- setClient(wrappingClient);
95
- const expiry = Math.floor((expiresAtRef.current - Date.now()) / 1000);
96
- log('Client initialized (token expires in %ds)', expiry);
161
+ setClient(refreshing);
162
+ scheduleRefreshRef.current();
163
+ log('Client initialized (token expires in %ds)', Math.floor((expiresAtRef.current - Date.now()) / 1000));
97
164
  setLoading(false);
98
165
  })
99
166
  .catch((err) => {
100
- log('Initialization failed: %s', err instanceof Error ? err.message : 'Unknown error');
101
- setError(err instanceof Error ? err.message : 'Failed to initialize client');
167
+ if (!mountedRef.current)
168
+ return;
169
+ const message = err instanceof Error ? err.message : 'Failed to initialize client';
170
+ log('Initialization failed: %s', message);
171
+ setError(message);
102
172
  setLoading(false);
103
173
  });
174
+ return () => {
175
+ mountedRef.current = false;
176
+ if (timerRef.current)
177
+ clearTimeout(timerRef.current);
178
+ };
104
179
  }, [getToken]);
105
180
  return (_jsx(LocationClientContext.Provider, { value: { client, getToken, loading, error }, children: children }));
106
181
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaosity/location-client-react",
3
- "version": "0.1.18",
3
+ "version": "0.2.0",
4
4
  "description": "React bindings for Chaosity Location Service client",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -11,7 +11,7 @@
11
11
  "lint": "eslint . && prettier --check .",
12
12
  "lint:fix": "eslint --fix . && prettier --write .",
13
13
  "format": "prettier --write .",
14
- "test": "vitest run --passWithNoTests",
14
+ "test": "vitest run",
15
15
  "test:watch": "vitest",
16
16
  "prepublishOnly": "npm run build",
17
17
  "prepare": "husky"
@@ -34,7 +34,7 @@
34
34
  "url": "https://github.com/chaosity-io/location-service-client-react/issues"
35
35
  },
36
36
  "dependencies": {
37
- "@chaosity/location-client": "^0.1.0",
37
+ "@chaosity/location-client": "^0.2.0",
38
38
  "debug": "^4.4.3"
39
39
  },
40
40
  "peerDependencies": {