@chaosity/location-client 0.7.0 → 0.9.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 (44) hide show
  1. package/README.md +73 -12
  2. package/dist/cjs/client/GeoPlacesClient.d.ts +11 -3
  3. package/dist/cjs/client/GeoPlacesClient.js +38 -12
  4. package/dist/cjs/index.d.ts +1 -1
  5. package/dist/cjs/index.js +3 -2
  6. package/dist/cjs/maps/mapStyle.d.ts +3 -1
  7. package/dist/cjs/maps/mapStyle.js +24 -19
  8. package/dist/cjs/maps/staticMap.d.ts +3 -1
  9. package/dist/cjs/maps/staticMap.js +18 -12
  10. package/dist/cjs/server/LocationServiceConnector.d.ts +1 -1
  11. package/dist/cjs/server/LocationServiceConnector.js +17 -20
  12. package/dist/cjs/server/getClientConfig.d.ts +19 -0
  13. package/dist/cjs/server/getClientConfig.js +44 -10
  14. package/dist/cjs/transport/errors.d.ts +18 -1
  15. package/dist/cjs/transport/errors.js +25 -1
  16. package/dist/cjs/transport/http.d.ts +36 -0
  17. package/dist/cjs/transport/http.js +118 -15
  18. package/dist/cjs/types/index.d.ts +19 -2
  19. package/dist/cjs/utils/tokenClaims.d.ts +11 -13
  20. package/dist/cjs/utils/tokenClaims.js +11 -14
  21. package/dist/client/GeoPlacesClient.d.ts +11 -3
  22. package/dist/client/GeoPlacesClient.js +39 -13
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/maps/mapStyle.d.ts +3 -1
  26. package/dist/maps/mapStyle.js +25 -20
  27. package/dist/maps/staticMap.d.ts +3 -1
  28. package/dist/maps/staticMap.js +19 -13
  29. package/dist/server/LocationServiceConnector.d.ts +1 -1
  30. package/dist/server/LocationServiceConnector.js +18 -21
  31. package/dist/server/getClientConfig.d.ts +19 -0
  32. package/dist/server/getClientConfig.js +43 -10
  33. package/dist/transport/errors.d.ts +18 -1
  34. package/dist/transport/errors.js +24 -1
  35. package/dist/transport/http.d.ts +36 -0
  36. package/dist/transport/http.js +116 -14
  37. package/dist/types/index.d.ts +19 -2
  38. package/dist/utils/tokenClaims.d.ts +11 -13
  39. package/dist/utils/tokenClaims.js +11 -14
  40. package/package.json +1 -1
  41. package/dist/cjs/utils/roundPosition.d.ts +0 -66
  42. package/dist/cjs/utils/roundPosition.js +0 -109
  43. package/dist/utils/roundPosition.d.ts +0 -66
  44. package/dist/utils/roundPosition.js +0 -104
@@ -1,4 +1,5 @@
1
- import { parseErrorResponse } from '../transport/errors.js';
1
+ import { noTokenAvailable } from '../transport/errors.js';
2
+ import { requestJson } from '../transport/http.js';
2
3
  import { labelsByName, languageExpression } from './mapLanguage.js';
3
4
  /**
4
5
  * Build a map style descriptor URL for the Location Service API.
@@ -46,38 +47,42 @@ export function buildMapStyleUrl(apiUrl, mapStyle, options = {}) {
46
47
  * @param mapStyle - Map style name (e.g. 'Standard', 'Monochrome', 'Satellite', 'Hybrid')
47
48
  * @param getToken - Callback returning the current auth token
48
49
  * @param options - Style options; `language` is applied to the descriptor, all others become URL params
50
+ * @param request - Transport options: `signal` to cancel, `timeoutMs`, `overallTimeoutMs`, `retry`
49
51
  * @returns Modified MapLibre StyleSpecification object
50
52
  *
51
53
  * @example
52
54
  * const style = await fetchMapStyle(API_URL, 'Standard', getToken, { colorScheme: 'Dark', language: 'fr' })
53
55
  * const map = new maplibregl.Map({ style, transformRequest: createTransformRequest(API_URL, getToken) })
54
56
  */
55
- export async function fetchMapStyle(apiUrl, mapStyle, getToken, options = {}) {
57
+ export async function fetchMapStyle(apiUrl, mapStyle, getToken, options = {}, request = {}) {
56
58
  const { language, ...styleOptions } = options;
57
59
  const url = buildMapStyleUrl(apiUrl, mapStyle, styleOptions);
58
60
  const token = getToken();
59
- const response = await fetch(url, {
61
+ // `Bearer undefined` used to go out here, and came back as a 401 the caller
62
+ // had to work backwards from — a whole round trip for a request that was
63
+ // never going to succeed (#37).
64
+ if (!token) {
65
+ throw noTokenAvailable('getToken() returned nothing, so no style request was sent. Check the token provider has finished initialising.');
66
+ }
67
+ // Through the shared transport, not a bare fetch: this gets the same
68
+ // per-attempt timeout, overall budget, cancellation and retry as every other
69
+ // call in the package, and the same error type on the way out. It also keeps
70
+ // the API's own message, which is the whole point of reading the body — for
71
+ // a style request that sentence is Amazon's, forwarded verbatim by
72
+ // location-service-api#89:
73
+ //
74
+ // 400 "Traffic is not supported for style."
75
+ // 400 "light is not a supported color scheme for style Standard."
76
+ //
77
+ // This used to throw `Failed to fetch map style: 400`, discarding all of it
78
+ // two lines before anyone could read it — the same defect #89 fixed in the
79
+ // API, one layer up.
80
+ const style = await requestJson(url, {
60
81
  headers: {
61
82
  Authorization: `Bearer ${token}`,
62
83
  Accept: 'application/json',
63
84
  },
64
- });
65
- if (!response.ok) {
66
- // Read the body. The API sends `{message, code, requestId}` and the message
67
- // is the whole point of it — for a style request it is Amazon's own
68
- // sentence, forwarded verbatim by location-service-api#89:
69
- //
70
- // 400 "Traffic is not supported for style."
71
- // 400 "light is not a supported color scheme for style Standard."
72
- //
73
- // This used to throw `Failed to fetch map style: 400`, discarding all of it
74
- // two lines before anyone could read it — the same defect #89 fixed in the
75
- // API, one layer up. Reuses parseErrorResponse so a style failure arrives as
76
- // the same LocationServiceException as every other call in this package,
77
- // with `code`, `statusCode` and `requestId` intact.
78
- throw parseErrorResponse(response.status, response.statusText, await response.text(), response.headers);
79
- }
80
- const style = (await response.json());
85
+ }, request);
81
86
  if (language) {
82
87
  applyLanguageToDescriptor(style, language);
83
88
  }
@@ -1,3 +1,4 @@
1
+ import type { RequestOptions } from '../transport/http.js';
1
2
  import type { ColorScheme, LabelSize, MapFeatureMode, ScaleBarUnit, StaticMapStyle } from './mapEnums.js';
2
3
  /**
3
4
  * Static maps: build the URL, send the right headers, get a Blob.
@@ -74,6 +75,7 @@ export declare function buildStaticMapUrl(apiUrl: string, options: StaticMapOpti
74
75
  * @param apiUrl Base URL of the Location Service API
75
76
  * @param options Render options; exactly one of center / boundingBox / boundedPositions
76
77
  * @param getToken Callback returning the current auth token
78
+ * @param request Transport options: `signal` to cancel, `timeoutMs`, `overallTimeoutMs`, `retry`
77
79
  *
78
80
  * @example
79
81
  * const blob = await fetchStaticMap(API_URL, {
@@ -82,4 +84,4 @@ export declare function buildStaticMapUrl(apiUrl: string, options: StaticMapOpti
82
84
  * }, getToken)
83
85
  * const url = URL.createObjectURL(blob) // remember to revokeObjectURL
84
86
  */
85
- export declare function fetchStaticMap(apiUrl: string, options: StaticMapOptions, getToken: () => string | undefined): Promise<Blob>;
87
+ export declare function fetchStaticMap(apiUrl: string, options: StaticMapOptions, getToken: () => string | undefined, request?: RequestOptions): Promise<Blob>;
@@ -1,4 +1,5 @@
1
- import { parseErrorResponse } from '../transport/errors.js';
1
+ import { noTokenAvailable } from '../transport/errors.js';
2
+ import { requestBlob } from '../transport/http.js';
2
3
  /**
3
4
  * The Accept header this request must send.
4
5
  *
@@ -50,6 +51,7 @@ export function buildStaticMapUrl(apiUrl, options) {
50
51
  * @param apiUrl Base URL of the Location Service API
51
52
  * @param options Render options; exactly one of center / boundingBox / boundedPositions
52
53
  * @param getToken Callback returning the current auth token
54
+ * @param request Transport options: `signal` to cancel, `timeoutMs`, `overallTimeoutMs`, `retry`
53
55
  *
54
56
  * @example
55
57
  * const blob = await fetchStaticMap(API_URL, {
@@ -58,19 +60,23 @@ export function buildStaticMapUrl(apiUrl, options) {
58
60
  * }, getToken)
59
61
  * const url = URL.createObjectURL(blob) // remember to revokeObjectURL
60
62
  */
61
- export async function fetchStaticMap(apiUrl, options, getToken) {
62
- const response = await fetch(buildStaticMapUrl(apiUrl, options), {
63
+ export async function fetchStaticMap(apiUrl, options, getToken, request = {}) {
64
+ const token = getToken();
65
+ // The same guard as fetchMapStyle and the server connector: a render is not
66
+ // worth requesting without a token to send (#37).
67
+ if (!token) {
68
+ throw noTokenAvailable('getToken() returned nothing, so no static map was requested. Check the token provider has finished initialising.');
69
+ }
70
+ // Through the shared transport, so a static map gets the timeout, budget,
71
+ // cancellation and retry every other call has -- and its failures arrive as
72
+ // LocationServiceException rather than as a raw TypeError. The API's own
73
+ // {message, code, requestId} survives, which matters here: the messages are
74
+ // specific and actionable -- "'width' and 'height' are required", "Only one
75
+ // of center, bounding-box or bounded-positions may be set".
76
+ return requestBlob(buildStaticMapUrl(apiUrl, options), {
63
77
  headers: {
64
- Authorization: `Bearer ${getToken()}`,
78
+ Authorization: `Bearer ${token}`,
65
79
  Accept: staticMapAccept(options.style),
66
80
  },
67
- });
68
- if (!response.ok) {
69
- // Same treatment as fetchMapStyle: the API's {message, code, requestId} is
70
- // the useful part, and a bare "failed: 400" throws it away. The messages
71
- // here are specific and actionable -- "'width' and 'height' are required",
72
- // "Only one of center, bounding-box or bounded-positions may be set".
73
- throw parseErrorResponse(response.status, response.statusText, await response.text());
74
- }
75
- return response.blob();
81
+ }, request);
76
82
  }
@@ -77,7 +77,7 @@ export declare class LocationServiceConnector {
77
77
  private buildSource;
78
78
  /**
79
79
  * This application's own configuration, as carried on the access token
80
- * (api#65) — bias precision, and the countries it is scoped to.
80
+ * (api#65) — today, the countries it is scoped to.
81
81
  *
82
82
  * Provided so an application can SHOW its own settings: populate a country
83
83
  * selector with the markets it actually serves, label a settings screen, and
@@ -1,9 +1,8 @@
1
1
  import debug from 'debug';
2
2
  import { LocationServiceException } from '../errors/LocationServiceException.js';
3
3
  import { resolveEndpoint } from '../transport/endpoints.js';
4
- import { isTokenRejected } from '../transport/errors.js';
4
+ import { isTokenRejected, noTokenAvailable } from '../transport/errors.js';
5
5
  import { requestJson } from '../transport/http.js';
6
- import { roundPositionFields } from '../utils/roundPosition.js';
7
6
  import { readAppConfigClaims } from '../utils/tokenClaims.js';
8
7
  import { resolveApiUrl, serverTokenSource } from './getClientConfig.js';
9
8
  const log = debug('location-client:connector');
@@ -27,6 +26,12 @@ function headerValue(headers, name) {
27
26
  * spelling of it survives the merge.
28
27
  */
29
28
  const SYSTEM_HEADERS = ['origin', 'content-type', 'authorization'];
29
+ /**
30
+ * What to check when the token source comes up empty. The guard itself is
31
+ * shared with the map fetches (`noTokenAvailable`); only the advice differs,
32
+ * and on this path the answer is always the credentials.
33
+ */
34
+ const NO_TOKEN_ADVICE = 'check clientId/clientSecret configuration';
30
35
  /** The caller's headers minus `names`, however they capitalised them. */
31
36
  function withoutHeaders(headers, names) {
32
37
  if (!headers)
@@ -146,7 +151,7 @@ export class LocationServiceConnector {
146
151
  }
147
152
  /**
148
153
  * This application's own configuration, as carried on the access token
149
- * (api#65) — bias precision, and the countries it is scoped to.
154
+ * (api#65) — today, the countries it is scoped to.
150
155
  *
151
156
  * Provided so an application can SHOW its own settings: populate a country
152
157
  * selector with the markets it actually serves, label a settings screen, and
@@ -187,7 +192,7 @@ export class LocationServiceConnector {
187
192
  async dispatchWithRetry(source, url, cmd, options) {
188
193
  const token = await source.get();
189
194
  if (!token)
190
- throw noTokenAvailable();
195
+ throw noTokenAvailable(NO_TOKEN_ADVICE);
191
196
  try {
192
197
  return await this.dispatch(url, token, cmd, options);
193
198
  }
@@ -198,8 +203,8 @@ export class LocationServiceConnector {
198
203
  // token. That single comparison covers every source: a fixed `token`
199
204
  // string, a caller `getToken` that ignores `forceRefresh`, and a cached
200
205
  // token the API has revoked before its `exp` all hand back what we
201
- // already sent — and re-sending it would be a second doomed request, and
202
- // a second billed one.
206
+ // already sent — and re-sending it would be a second doomed request for
207
+ // the same answer.
203
208
  const fresh = await source.get(true);
204
209
  if (!fresh || fresh === token)
205
210
  throw err;
@@ -208,13 +213,12 @@ export class LocationServiceConnector {
208
213
  }
209
214
  }
210
215
  dispatch(url, token, cmd, options) {
211
- // The token is resolved before the request is shaped, so the precision this
212
- // application is entitled to is available (api#65). Absent claim -> the
213
- // 3 dp floor, which is what every application gets until one is configured
214
- // otherwise. Recomputed per attempt because a refreshed token may carry
215
- // different claims.
216
- const { biasDecimals } = readAppConfigClaims(token);
217
- const input = roundPositionFields(cmd.input, biasDecimals);
216
+ // The caller's input goes out as the caller wrote it — nothing in the body
217
+ // is derived from the token any more. `BiasPosition` used to be rounded
218
+ // here to a grid sized by a token claim, so nearby callers shared a server
219
+ // cache entry; with no cache the rounding only lowered the precision the
220
+ // upstream geocoder had to work with, which moves the results rather than
221
+ // coarsening them (#51).
218
222
  // Every system header is set exactly ONCE, and the caller's own spelling of
219
223
  // each is dropped first.
220
224
  //
@@ -239,7 +243,7 @@ export class LocationServiceConnector {
239
243
  Authorization: `Bearer ${token}`,
240
244
  };
241
245
  log('Sending %s request to %s', cmd.constructor?.name, url);
242
- return requestJson(url, { method: 'POST', headers, body: JSON.stringify(input) }, options);
246
+ return requestJson(url, { method: 'POST', headers, body: JSON.stringify(cmd.input) }, options);
243
247
  }
244
248
  }
245
249
  function requireApiUrl(explicit) {
@@ -254,10 +258,3 @@ function requireApiUrl(explicit) {
254
258
  }
255
259
  return apiUrl;
256
260
  }
257
- function noTokenAvailable() {
258
- return new LocationServiceException({
259
- code: 'InvalidCredentialsException',
260
- message: 'No token available — check clientId/clientSecret configuration',
261
- details: { source: 'client' },
262
- });
263
- }
@@ -14,7 +14,26 @@ export interface ServerAuthConfig {
14
14
  */
15
15
  forceRefresh?: boolean;
16
16
  }
17
+ /**
18
+ * How many applications one process keeps token providers for.
19
+ *
20
+ * A provider holds a URL, a client id, a secret and one cached JWT, so the
21
+ * ceiling is about memory containment rather than a tuned working set — 64 is
22
+ * far above what a single-tenant service needs and far below anything worth
23
+ * worrying about. An agency past it pays a re-mint for the least recently used
24
+ * application, which is exactly the behaviour this replaced, but only for the
25
+ * coldest one instead of for every alternation.
26
+ */
27
+ export declare const MAX_CACHED_PROVIDERS = 64;
17
28
  export interface ServerClientConfig extends ClientConfig {
29
+ /**
30
+ * Narrowed back to required. `ClientConfig.token` is optional because a
31
+ * client can be driven by `getToken`/`refreshToken` alone, but this type is
32
+ * what `getClientConfig` RESOLVES — it either has a token or it threw — and
33
+ * widening it would push a needless `string | undefined` onto every consumer
34
+ * that reads `config.token`.
35
+ */
36
+ token: string;
18
37
  expiresAt?: number;
19
38
  }
20
39
  /**
@@ -3,9 +3,32 @@ import { createHash } from 'node:crypto';
3
3
  import { TokenProvider } from '../auth/TokenProvider.js';
4
4
  import { LocationServiceException } from '../errors/LocationServiceException.js';
5
5
  const log = debug('location-client:clientConfig');
6
- // Singleton instance to prevent race conditions
7
- let tokenProviderInstance = null;
8
- let currentConfig = null;
6
+ /**
7
+ * How many applications one process keeps token providers for.
8
+ *
9
+ * A provider holds a URL, a client id, a secret and one cached JWT, so the
10
+ * ceiling is about memory containment rather than a tuned working set — 64 is
11
+ * far above what a single-tenant service needs and far below anything worth
12
+ * worrying about. An agency past it pays a re-mint for the least recently used
13
+ * application, which is exactly the behaviour this replaced, but only for the
14
+ * coldest one instead of for every alternation.
15
+ */
16
+ export const MAX_CACHED_PROVIDERS = 64;
17
+ /**
18
+ * One provider per configuration, most-recently-used last.
19
+ *
20
+ * This used to be TWO module-level variables holding a single provider, and a
21
+ * process serving more than one application therefore evicted the cache on
22
+ * every alternation: A→B→A→B took a full `/auth/token` round trip per call,
23
+ * each writing a jti row, all against the one shared token-endpoint throttle.
24
+ * The hit rate under alternating load was 0% (#39). Nothing leaked between
25
+ * tenants — each caller closes over the provider it asked for — so what this
26
+ * fixes is availability and cost, not confidentiality.
27
+ *
28
+ * A `Map` iterates in insertion order, so re-inserting on a hit makes the first
29
+ * key the least recently used, and an LRU needs no other bookkeeping.
30
+ */
31
+ const tokenProviders = new Map();
9
32
  function getTokenProvider(apiUrl, clientId, clientSecret) {
10
33
  // The SECRET is part of the key. Without it, rotating a client secret while
11
34
  // keeping the same clientId left this process reusing a provider built on the
@@ -13,16 +36,26 @@ function getTokenProvider(apiUrl, clientId, clientSecret) {
13
36
  // rather than concatenated so the key is never a secret in its own right, and
14
37
  // never ends up in a log line (#5).
15
38
  const configKey = `${apiUrl}:${clientId}:${createHash('sha256').update(clientSecret).digest('hex').slice(0, 16)}`;
16
- // Reuse existing instance if config matches
17
- if (tokenProviderInstance && currentConfig === configKey) {
39
+ const cached = tokenProviders.get(configKey);
40
+ if (cached) {
18
41
  log('[getTokenProvider] Reusing existing TokenProvider instance');
19
- return tokenProviderInstance;
42
+ // Re-insert to mark it most recently used.
43
+ tokenProviders.delete(configKey);
44
+ tokenProviders.set(configKey, cached);
45
+ return cached;
20
46
  }
21
- // Create new instance if config changed
22
47
  log('[getTokenProvider] Creating new TokenProvider instance');
23
- tokenProviderInstance = new TokenProvider({ apiUrl, clientId, clientSecret });
24
- currentConfig = configKey;
25
- return tokenProviderInstance;
48
+ const provider = new TokenProvider({ apiUrl, clientId, clientSecret });
49
+ tokenProviders.set(configKey, provider);
50
+ if (tokenProviders.size > MAX_CACHED_PROVIDERS) {
51
+ const leastRecentlyUsed = tokenProviders.keys().next().value;
52
+ /* c8 ignore next — size > 0 here, so the iterator always yields */
53
+ if (leastRecentlyUsed !== undefined) {
54
+ log('[getTokenProvider] Evicting the least recently used TokenProvider');
55
+ tokenProviders.delete(leastRecentlyUsed);
56
+ }
57
+ }
58
+ return provider;
26
59
  }
27
60
  /**
28
61
  * Where the API lives, from the argument or the environment.
@@ -19,7 +19,9 @@ export declare function parseErrorResponse(status: number, statusText: string, b
19
19
  * expired, and API Gateway turns that into a 401. Its other refusals — no
20
20
  * domain configured for the application, an Origin the application does not
21
21
  * allow — are a Deny policy or a service 403, and a fresh token changes
22
- * neither. Retrying those would send, and bill, the same doomed request twice.
22
+ * neither. Retrying those sends the same doomed request twice, for the same
23
+ * answer — which is the whole cost, since the service meters successful
24
+ * requests and no error response is billed whatever its status.
23
25
  *
24
26
  * Shared by both send paths so the browser client and the server connector
25
27
  * cannot come to different conclusions about the same response.
@@ -30,3 +32,18 @@ export declare function isTokenRejected(err: unknown): boolean;
30
32
  * API sends the first; a date is handled so a proxy or gateway cannot surprise us.
31
33
  */
32
34
  export declare function parseRetryAfter(value: string | null | undefined): number | undefined;
35
+ /**
36
+ * No token to send, so nothing is sent.
37
+ *
38
+ * Every send path resolves a token before it builds a request, and every one of
39
+ * them can come up empty — a provider that has not initialised, a server action
40
+ * that returned nothing, credentials that are not configured. Sending anyway
41
+ * puts the literal string `Bearer undefined` on the wire, which the API answers
42
+ * with a 401 the caller then has to work backwards from — a whole round trip,
43
+ * paid for out of the caller's own deadline, to be told what it already knew.
44
+ * The map fetches did exactly that until #37.
45
+ *
46
+ * `advice` says what to check, because that differs by path: a server connector
47
+ * wants its client credentials looked at, a browser map wants its token source.
48
+ */
49
+ export declare function noTokenAvailable(advice: string): LocationServiceException;
@@ -90,7 +90,9 @@ function statusCode(status) {
90
90
  * expired, and API Gateway turns that into a 401. Its other refusals — no
91
91
  * domain configured for the application, an Origin the application does not
92
92
  * allow — are a Deny policy or a service 403, and a fresh token changes
93
- * neither. Retrying those would send, and bill, the same doomed request twice.
93
+ * neither. Retrying those sends the same doomed request twice, for the same
94
+ * answer — which is the whole cost, since the service meters successful
95
+ * requests and no error response is billed whatever its status.
94
96
  *
95
97
  * Shared by both send paths so the browser client and the server connector
96
98
  * cannot come to different conclusions about the same response.
@@ -113,3 +115,24 @@ export function parseRetryAfter(value) {
113
115
  return Math.max(0, date - Date.now());
114
116
  return undefined;
115
117
  }
118
+ /**
119
+ * No token to send, so nothing is sent.
120
+ *
121
+ * Every send path resolves a token before it builds a request, and every one of
122
+ * them can come up empty — a provider that has not initialised, a server action
123
+ * that returned nothing, credentials that are not configured. Sending anyway
124
+ * puts the literal string `Bearer undefined` on the wire, which the API answers
125
+ * with a 401 the caller then has to work backwards from — a whole round trip,
126
+ * paid for out of the caller's own deadline, to be told what it already knew.
127
+ * The map fetches did exactly that until #37.
128
+ *
129
+ * `advice` says what to check, because that differs by path: a server connector
130
+ * wants its client credentials looked at, a browser map wants its token source.
131
+ */
132
+ export function noTokenAvailable(advice) {
133
+ return new LocationServiceException({
134
+ code: 'InvalidCredentialsException',
135
+ message: `No token available — ${advice}`,
136
+ details: { source: 'client' },
137
+ });
138
+ }
@@ -1,11 +1,38 @@
1
1
  /** Per-attempt timeout. Sits well under the API's own 25 s Lambda ceiling. */
2
2
  export declare const DEFAULT_TIMEOUT_MS = 10000;
3
+ /**
4
+ * Ceiling for the WHOLE call — every attempt plus every wait between them.
5
+ *
6
+ * `timeoutMs` bounds an attempt, not a call, and the gap between those two is
7
+ * where the caller's own deadline disappears. The API answers a spent quota
8
+ * with `Retry-After: 60`, which the retry loop honoured literally: two waits of
9
+ * a minute each, so one call could sit for ~120 s — past any Lambda budget,
10
+ * past any HTTP gateway, and until now uncancellable (#37).
11
+ *
12
+ * 30 s is picked to sit just under the old worst case: three default attempts
13
+ * that all time out, plus their backoff, came to ~30.75 s. The overlap is not
14
+ * quite nothing — when both earlier attempts burn their full 10 s, the third is
15
+ * clamped to the ~9.25 s that remain, so a response arriving in its final
16
+ * ~0.75 s used to succeed and now times out. That window is why this ships in a
17
+ * MINOR rather than a patch. What it buys is that no call can be made to sit
18
+ * out a retry hint longer than the caller has.
19
+ */
20
+ export declare const DEFAULT_OVERALL_TIMEOUT_MS = 30000;
3
21
  export declare const DEFAULT_MAX_ATTEMPTS = 3;
4
22
  export interface RequestOptions {
5
23
  /** Caller cancellation. Aborting rejects with code `AbortedException`. */
6
24
  signal?: AbortSignal;
7
25
  /** Per ATTEMPT, not for the whole call. Default 10 s. */
8
26
  timeoutMs?: number;
27
+ /**
28
+ * The whole call — attempts and the waits between them. Default 30 s.
29
+ *
30
+ * No attempt is given more than what is left of it, and a retry that would
31
+ * have to wait longer than what is left is not made at all: the API's own
32
+ * error comes back instead, `retryAfterMs` intact, so the caller can decide
33
+ * whether to queue the work or drop it.
34
+ */
35
+ overallTimeoutMs?: number;
9
36
  /** `false` disables retries entirely. Default 3 attempts = 2 retries. */
10
37
  retry?: false | {
11
38
  maxAttempts?: number;
@@ -22,3 +49,12 @@ export declare function backoffMs(attempt: number, random?: () => number): numbe
22
49
  * `details.source = 'client'` so it is distinguishable from the API's own 504.
23
50
  */
24
51
  export declare function requestJson<T>(url: string, init: RequestInit, options?: RequestOptions): Promise<T>;
52
+ /**
53
+ * One request answered as a Blob — the static map path.
54
+ *
55
+ * Exists so the two map fetches are not the only calls in the package without
56
+ * a timeout, a retry or a signal: they used their own bare `fetch`, so a
57
+ * network fault there escaped as a raw `TypeError` while the identical fault on
58
+ * any other call arrived as `NetworkException` (#37).
59
+ */
60
+ export declare function requestBlob(url: string, init: RequestInit, options?: RequestOptions): Promise<Blob>;
@@ -4,6 +4,24 @@ import { parseErrorResponse, parseRetryAfter } from './errors.js';
4
4
  const log = debug('location-client:transport');
5
5
  /** Per-attempt timeout. Sits well under the API's own 25 s Lambda ceiling. */
6
6
  export const DEFAULT_TIMEOUT_MS = 10000;
7
+ /**
8
+ * Ceiling for the WHOLE call — every attempt plus every wait between them.
9
+ *
10
+ * `timeoutMs` bounds an attempt, not a call, and the gap between those two is
11
+ * where the caller's own deadline disappears. The API answers a spent quota
12
+ * with `Retry-After: 60`, which the retry loop honoured literally: two waits of
13
+ * a minute each, so one call could sit for ~120 s — past any Lambda budget,
14
+ * past any HTTP gateway, and until now uncancellable (#37).
15
+ *
16
+ * 30 s is picked to sit just under the old worst case: three default attempts
17
+ * that all time out, plus their backoff, came to ~30.75 s. The overlap is not
18
+ * quite nothing — when both earlier attempts burn their full 10 s, the third is
19
+ * clamped to the ~9.25 s that remain, so a response arriving in its final
20
+ * ~0.75 s used to succeed and now times out. That window is why this ships in a
21
+ * MINOR rather than a patch. What it buys is that no call can be made to sit
22
+ * out a retry hint longer than the caller has.
23
+ */
24
+ export const DEFAULT_OVERALL_TIMEOUT_MS = 30000;
7
25
  export const DEFAULT_MAX_ATTEMPTS = 3;
8
26
  const BACKOFF_BASE_MS = 250;
9
27
  const BACKOFF_CAP_MS = 4000;
@@ -40,38 +58,86 @@ export function backoffMs(attempt, random = Math.random) {
40
58
  const ceiling = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
41
59
  return Math.floor(random() * ceiling);
42
60
  }
43
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
44
61
  /**
45
- * One JSON request, with timeout, cancellation and retry.
62
+ * Sleep, unless the caller aborts first.
46
63
  *
47
- * Every failure leaves as a LocationServiceException — a fetch rejection
48
- * becomes `NetworkException` with the original as `cause`, an abort becomes
49
- * `AbortedException`, a timeout becomes `TimeoutException` with
50
- * `details.source = 'client'` so it is distinguishable from the API's own 504.
64
+ * The timer used to be uncancellable, so an `abort()` during backoff was
65
+ * ignored until it elapsed — up to a whole `Retry-After` — and the loop only
66
+ * noticed at the top of the next attempt (#37). Resolving early is all that is
67
+ * needed: the loop's own pre-attempt check is what raises `AbortedException`,
68
+ * so exactly one place decides what an abort means.
51
69
  */
52
- export async function requestJson(url, init, options = {}) {
70
+ function sleep(ms, signal) {
71
+ if (ms <= 0 || signal?.aborted)
72
+ return Promise.resolve();
73
+ return new Promise((resolve) => {
74
+ const done = () => {
75
+ clearTimeout(timer);
76
+ signal?.removeEventListener('abort', done);
77
+ resolve();
78
+ };
79
+ const timer = setTimeout(done, ms);
80
+ signal?.addEventListener('abort', done, { once: true });
81
+ });
82
+ }
83
+ /**
84
+ * One request, with timeout, cancellation and retry.
85
+ *
86
+ * The body is read INSIDE the attempt loop deliberately: a truncated or
87
+ * malformed body is a failed attempt like any other and earns the same
88
+ * wrapping and the same retry as a dropped socket. Handing the `Response` back
89
+ * for the caller to read would move that outside the loop, where a bare
90
+ * `SyntaxError` escapes as itself.
91
+ */
92
+ async function request(url, init, options, read) {
53
93
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
94
+ const overallTimeoutMs = options.overallTimeoutMs ?? DEFAULT_OVERALL_TIMEOUT_MS;
54
95
  const maxAttempts = options.retry === false
55
96
  ? 1
56
97
  : (options.retry?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
98
+ // A request budget of zero attempts is a caller mistake, not a policy. It
99
+ // used to fall straight through the loop and raise `InternalException` for a
100
+ // request that was never made — an error about our own internals, for their
101
+ // typo (#37).
102
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
103
+ throw new LocationServiceException({
104
+ code: 'ValidationException',
105
+ message: `retry.maxAttempts must be a whole number of at least 1; received ${maxAttempts}`,
106
+ details: { source: 'client' },
107
+ });
108
+ }
109
+ const deadline = Date.now() + overallTimeoutMs;
57
110
  let lastError;
58
111
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
59
112
  // Checked before every attempt: a signal aborted during backoff must not fire one more.
60
113
  if (options.signal?.aborted)
61
114
  throw abortedException(options.signal);
62
- const { signal, cleanup } = attemptSignal(options.signal, timeoutMs);
115
+ const budget = deadline - Date.now();
116
+ if (budget <= 0)
117
+ throw lastError ?? overallTimeoutException(overallTimeoutMs);
118
+ // Never longer than what is left of the call, so the per-attempt timeout
119
+ // cannot overrun the budget it sits inside.
120
+ const { signal, cleanup } = attemptSignal(options.signal, Math.min(timeoutMs, budget));
63
121
  try {
64
122
  const response = await fetch(url, { ...init, signal });
65
123
  if (response.ok)
66
- return (await response.json());
124
+ return await read(response);
67
125
  const error = parseErrorResponse(response.status, response.statusText, await response.text(), response.headers);
68
126
  lastError = error;
69
127
  if (!error.isRetryable || attempt === maxAttempts - 1)
70
128
  throw error;
71
- log('attempt %d failed (%s), retrying', attempt + 1, error.code);
72
- await sleep(error.retryAfterMs ??
129
+ const wait = error.retryAfterMs ??
73
130
  parseRetryAfter(response.headers.get('retry-after')) ??
74
- backoffMs(attempt));
131
+ backoffMs(attempt);
132
+ // Sitting out a 60 s `Retry-After` inside a 30 s budget only delivers the
133
+ // same failure after the caller has already given up. Stop now and hand
134
+ // back what the API said, `retryAfterMs` and all.
135
+ if (wait >= deadline - Date.now()) {
136
+ log('not retrying: a %d ms wait outlasts the remaining budget', wait);
137
+ break;
138
+ }
139
+ log('attempt %d failed (%s), retrying', attempt + 1, error.code);
140
+ await sleep(wait, options.signal);
75
141
  }
76
142
  catch (err) {
77
143
  if (err instanceof LocationServiceException) {
@@ -85,20 +151,48 @@ export async function requestJson(url, init, options = {}) {
85
151
  lastError = wrapped;
86
152
  if (!wrapped.isRetryable || attempt === maxAttempts - 1)
87
153
  throw wrapped;
154
+ const wait = backoffMs(attempt);
155
+ if (wait >= deadline - Date.now()) {
156
+ log('not retrying: a %d ms wait outlasts the remaining budget', wait);
157
+ break;
158
+ }
88
159
  log('attempt %d failed (%s), retrying', attempt + 1, wrapped.code);
89
- await sleep(backoffMs(attempt));
160
+ await sleep(wait, options.signal);
90
161
  }
91
162
  finally {
92
163
  cleanup();
93
164
  }
94
165
  }
95
- /* c8 ignore next */
166
+ // Reached when the budget ran out before another attempt could be made, so
167
+ // `lastError` is the API's own answer and is the useful thing to throw.
96
168
  throw (lastError ??
97
169
  new LocationServiceException({
98
170
  code: 'InternalException',
99
171
  message: 'Request failed',
100
172
  }));
101
173
  }
174
+ /**
175
+ * One JSON request, with timeout, cancellation and retry.
176
+ *
177
+ * Every failure leaves as a LocationServiceException — a fetch rejection
178
+ * becomes `NetworkException` with the original as `cause`, an abort becomes
179
+ * `AbortedException`, a timeout becomes `TimeoutException` with
180
+ * `details.source = 'client'` so it is distinguishable from the API's own 504.
181
+ */
182
+ export function requestJson(url, init, options = {}) {
183
+ return request(url, init, options, (response) => response.json());
184
+ }
185
+ /**
186
+ * One request answered as a Blob — the static map path.
187
+ *
188
+ * Exists so the two map fetches are not the only calls in the package without
189
+ * a timeout, a retry or a signal: they used their own bare `fetch`, so a
190
+ * network fault there escaped as a raw `TypeError` while the identical fault on
191
+ * any other call arrived as `NetworkException` (#37).
192
+ */
193
+ export function requestBlob(url, init, options = {}) {
194
+ return request(url, init, options, (response) => response.blob());
195
+ }
102
196
  function abortedException(signal) {
103
197
  return new LocationServiceException({
104
198
  code: 'AbortedException',
@@ -107,6 +201,14 @@ function abortedException(signal) {
107
201
  cause: signal?.reason,
108
202
  });
109
203
  }
204
+ /** The call's own budget elapsed, rather than one attempt's timeout. */
205
+ function overallTimeoutException(overallTimeoutMs) {
206
+ return new LocationServiceException({
207
+ code: 'TimeoutException',
208
+ message: `Request exceeded its overall timeout of ${overallTimeoutMs} ms`,
209
+ details: { source: 'client' },
210
+ });
211
+ }
110
212
  /**
111
213
  * fetch rejects with a raw `TypeError` for a network fault and a `DOMException`
112
214
  * named AbortError for both cancellation and timeout — indistinguishable from