@chaosity/location-client 0.12.0 → 0.13.1

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 (62) hide show
  1. package/README.md +125 -36
  2. package/dist/adapters/GeoPlaces.d.ts +7 -1
  3. package/dist/adapters/GeoPlaces.js +11 -5
  4. package/dist/auth/TokenProvider.d.ts +22 -1
  5. package/dist/auth/TokenProvider.js +42 -2
  6. package/dist/auth/tokenHold.d.ts +14 -5
  7. package/dist/auth/tokenHold.js +70 -5
  8. package/dist/aws.d.ts +4 -0
  9. package/dist/aws.js +2 -0
  10. package/dist/cjs/adapters/GeoPlaces.d.ts +7 -1
  11. package/dist/cjs/adapters/GeoPlaces.js +10 -4
  12. package/dist/cjs/auth/TokenProvider.d.ts +22 -1
  13. package/dist/cjs/auth/TokenProvider.js +42 -2
  14. package/dist/cjs/auth/tokenHold.d.ts +14 -5
  15. package/dist/cjs/auth/tokenHold.js +71 -5
  16. package/dist/cjs/aws.d.ts +4 -0
  17. package/dist/cjs/aws.js +155 -0
  18. package/dist/cjs/client/GeoPlacesClient.d.ts +17 -1
  19. package/dist/cjs/client/GeoPlacesClient.js +18 -62
  20. package/dist/cjs/index.d.ts +4 -3
  21. package/dist/cjs/index.js +13 -8
  22. package/dist/cjs/maps/createTransformRequest.d.ts +25 -0
  23. package/dist/cjs/maps/createTransformRequest.js +1 -0
  24. package/dist/cjs/maps/mapPoi.d.ts +10 -5
  25. package/dist/cjs/maps/mapPoi.js +14 -5
  26. package/dist/cjs/maps/mapStyle.d.ts +9 -2
  27. package/dist/cjs/maps/mapStyle.js +16 -12
  28. package/dist/cjs/maps/mapToken.d.ts +87 -0
  29. package/dist/cjs/maps/mapToken.js +181 -0
  30. package/dist/cjs/maps/staticMap.d.ts +7 -3
  31. package/dist/cjs/maps/staticMap.js +13 -12
  32. package/dist/cjs/server/LocationServiceConnector.d.ts +18 -3
  33. package/dist/cjs/server/LocationServiceConnector.js +17 -58
  34. package/dist/cjs/server/getClientConfig.d.ts +7 -3
  35. package/dist/cjs/server/getClientConfig.js +9 -12
  36. package/dist/cjs/server/index.d.ts +1 -1
  37. package/dist/cjs/transport/http.d.ts +18 -0
  38. package/dist/cjs/transport/http.js +39 -1
  39. package/dist/cjs/types/index.d.ts +26 -0
  40. package/dist/client/GeoPlacesClient.d.ts +17 -1
  41. package/dist/client/GeoPlacesClient.js +21 -65
  42. package/dist/index.d.ts +4 -3
  43. package/dist/index.js +11 -7
  44. package/dist/maps/createTransformRequest.d.ts +25 -0
  45. package/dist/maps/createTransformRequest.js +1 -1
  46. package/dist/maps/mapPoi.d.ts +10 -5
  47. package/dist/maps/mapPoi.js +14 -5
  48. package/dist/maps/mapStyle.d.ts +9 -2
  49. package/dist/maps/mapStyle.js +17 -13
  50. package/dist/maps/mapToken.d.ts +87 -0
  51. package/dist/maps/mapToken.js +177 -0
  52. package/dist/maps/staticMap.d.ts +7 -3
  53. package/dist/maps/staticMap.js +14 -13
  54. package/dist/server/LocationServiceConnector.d.ts +18 -3
  55. package/dist/server/LocationServiceConnector.js +20 -61
  56. package/dist/server/getClientConfig.d.ts +7 -3
  57. package/dist/server/getClientConfig.js +9 -12
  58. package/dist/server/index.d.ts +1 -1
  59. package/dist/transport/http.d.ts +18 -0
  60. package/dist/transport/http.js +37 -1
  61. package/dist/types/index.d.ts +26 -0
  62. package/package.json +3 -3
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendWithTokenRefresh = sendWithTokenRefresh;
4
+ exports.refreshTokenOnUnauthorized = refreshTokenOnUnauthorized;
5
+ const tokenHold_js_1 = require("../auth/tokenHold.js");
6
+ const LocationServiceException_js_1 = require("../errors/LocationServiceException.js");
7
+ const errors_js_1 = require("../transport/errors.js");
8
+ const http_js_1 = require("../transport/http.js");
9
+ const createTransformRequest_js_1 = require("./createTransformRequest.js");
10
+ /**
11
+ * One hold per `MapTokens` object, so the helpers handed the same one share
12
+ * what the API and `refreshToken` said (#38): a refusal one of them met is not
13
+ * asked again by the next. A bare `getToken` never asks again, and needs none.
14
+ */
15
+ const holds = new WeakMap();
16
+ function holdOf(tokens) {
17
+ let hold = holds.get(tokens);
18
+ if (!hold)
19
+ holds.set(tokens, (hold = new tokenHold_js_1.TokenHold()));
20
+ return hold;
21
+ }
22
+ /**
23
+ * The token each `MapTokens` object's refresh last brought, and until when a
24
+ * 401 while it is in hand is not news (#72). One per object, beside its hold:
25
+ * a note per helper had each of two helpers handed one object take the
26
+ * other's token as news, and ask again for every refusal.
27
+ */
28
+ const broughtBy = new WeakMap();
29
+ /**
30
+ * Send with the token in hand, and after a 401 once more with a different one
31
+ * from `refreshToken`, all within the call's signal and deadline (#62). A 403
32
+ * is never retried, and neither is the token the API refused.
33
+ */
34
+ async function sendWithTokenRefresh(source, noTokenAdvice, call, send) {
35
+ const tokens = typeof source === 'function' ? { getToken: source } : source;
36
+ const token = tokens.getToken();
37
+ if (!token)
38
+ throw (0, errors_js_1.noTokenAvailable)(noTokenAdvice);
39
+ const { refreshToken } = tokens;
40
+ if (!refreshToken)
41
+ return send(token);
42
+ return (0, tokenHold_js_1.sendRetryingOnce)(holdOf(tokens), token, send, async () => (await (0, http_js_1.withinCall)(refreshToken(), call)) ?? tokens.getToken());
43
+ }
44
+ /**
45
+ * Recover the tiles MapLibre fetches itself when the API refuses the token
46
+ * (#72).
47
+ *
48
+ * `createTransformRequest` builds each request synchronously and never sees
49
+ * the answer, so a refused tile used to leave a hole until the page reloaded.
50
+ * This listens for MapLibre's `error` events. On a 401 from a URL of our API it
51
+ * asks `refreshToken` once for the whole burst. When `getToken` then returns a
52
+ * different token, it reloads each refused tile with `map.refreshTiles`, whose
53
+ * requests carry that token. So `refreshToken` must make `getToken` return
54
+ * what it obtained: the tiles have no other way to receive it. A refused
55
+ * request that is not a tile (a glyph, a sprite) has the token replaced for
56
+ * the next one, and nothing reloaded.
57
+ *
58
+ * Tiles are reloaded by id, never a whole source: MapLibre 6 reloads a source's
59
+ * errored tiles as still loading, and they wait for a load that never comes.
60
+ *
61
+ * What it learns is held as the fetch helpers hold it, and shared with them
62
+ * when they are handed the same `tokens` object (#38): a token `refreshToken`
63
+ * could not replace, a token it brought that the API refused on a tile
64
+ * reloaded with it, and a failure that says when to ask again, are not asked
65
+ * about again until they lapse or the token in hand changes. While the token
66
+ * a refresh brought is in hand, any other refused tile is reloaded once with
67
+ * it, without asking.
68
+ *
69
+ * Returns a function that stops listening.
70
+ *
71
+ * @example
72
+ * const tokens = { getToken, refreshToken }
73
+ * const map = new Map({
74
+ * container: 'map',
75
+ * style: await fetchMapStyle(API_URL, 'Standard', tokens),
76
+ * transformRequest: createTransformRequest(API_URL, getToken),
77
+ * })
78
+ * refreshTokenOnUnauthorized(map, API_URL, tokens)
79
+ */
80
+ function refreshTokenOnUnauthorized(map, apiUrl, tokens) {
81
+ const hold = holdOf(tokens);
82
+ // Each source's refused tiles, keyed `z/x/y` so a tile refused twice is
83
+ // reloaded once. Tiles refused while a hold stands are kept, so the next ask
84
+ // reloads them; MapLibre ignores ids no longer in view.
85
+ const refused = new Map();
86
+ // The token each tile was reloaded with here, keyed `source:z/x/y`.
87
+ const reloadedWith = new Map();
88
+ let asking = false;
89
+ const reload = (sourceId, tiles, token) => {
90
+ for (const { x, y, z } of tiles)
91
+ reloadedWith.set(`${sourceId}:${z}/${x}/${y}`, token);
92
+ map.refreshTiles(sourceId, tiles);
93
+ };
94
+ const onError = ({ error, sourceId, tile }) => {
95
+ if (error?.status !== 401 || !error.url || !(0, createTransformRequest_js_1.isOurApi)(error.url, apiUrl))
96
+ return;
97
+ let refusedTile;
98
+ if (sourceId && tile) {
99
+ const { x, y, z } = tile.tileID.canonical;
100
+ const tiles = refused.get(sourceId) ?? new Map();
101
+ refused.set(sourceId, tiles.set(`${z}/${x}/${y}`, { x, y, z }));
102
+ refusedTile = [sourceId, { x, y, z }];
103
+ }
104
+ if (asking)
105
+ return;
106
+ const inHand = tokens.getToken();
107
+ const held = hold.check(inHand);
108
+ if (held && !held.askAgain)
109
+ return;
110
+ // A 401 while the token a refresh brought is in hand. The event does not
111
+ // say which token the refused request carried, and a tile requested with
112
+ // the token before, answered late, looks like the new token refused. So
113
+ // only a tile reloaded here with the token in hand is that token refused:
114
+ // the API refuses every token, as it does a map pointed at an API its
115
+ // tokens are not for, and asking again minted a token and reloaded the
116
+ // tiles several times a second. That is remembered, as a send path
117
+ // remembers its retry refused, and the next ask is after the hold. Any
118
+ // other tile is reloaded once with the token in hand; anything else (a
119
+ // glyph, a sprite) asks nothing.
120
+ const brought = broughtBy.get(tokens);
121
+ if (inHand && inHand === brought?.token && Date.now() < brought.until) {
122
+ if (!refusedTile)
123
+ return;
124
+ const [id, coordinates] = refusedTile;
125
+ const key = `${coordinates.z}/${coordinates.x}/${coordinates.y}`;
126
+ if (reloadedWith.get(`${id}:${key}`) !== inHand) {
127
+ refused.get(id)?.delete(key);
128
+ reload(id, [coordinates], inHand);
129
+ return;
130
+ }
131
+ // Kept in `refused`, as every tile refused during the hold is.
132
+ broughtBy.delete(tokens);
133
+ hold.remember(unauthorized('The API refused a tile reloaded with the token refreshToken brought.'), inHand);
134
+ return;
135
+ }
136
+ asking = true;
137
+ // Asked inside an executor, so a `refreshToken` that throws instead of
138
+ // rejecting lands in the catch below rather than in MapLibre's emitter.
139
+ new Promise((resolve) => resolve(tokens.refreshToken()))
140
+ .then(() => {
141
+ // A reloaded tile takes its token from `getToken`, as every tile does,
142
+ // so that is the token that must have changed. Reloading on what
143
+ // `refreshToken` returned alone would send the refused one again, and
144
+ // its 401 would ask again: a loop of refreshes and reloads.
145
+ const now = tokens.getToken();
146
+ if (!now || now === inHand) {
147
+ // MapLibre's error carries none of the API's fields, so the refusal
148
+ // is remembered as the 401 it was.
149
+ hold.remember(unauthorized('The API refused the token, and getToken has no other since refreshToken settled.'), inHand);
150
+ return;
151
+ }
152
+ broughtBy.set(tokens, {
153
+ token: now,
154
+ until: Date.now() + tokenHold_js_1.TOKEN_REFUSAL_HOLD_MS,
155
+ });
156
+ // What was reloaded with an earlier token can no longer match.
157
+ reloadedWith.clear();
158
+ for (const [id, tiles] of refused)
159
+ if (tiles.size)
160
+ reload(id, [...tiles.values()], now);
161
+ })
162
+ .catch((refusal) => {
163
+ // Only a failure that says when to ask again is remembered; any other
164
+ // leaves the next refused tile to ask, as the send paths do.
165
+ if ((0, tokenHold_js_1.holdFor)(refusal) > 0)
166
+ hold.remember(refusal, inHand);
167
+ })
168
+ .finally(() => {
169
+ refused.clear();
170
+ asking = false;
171
+ });
172
+ };
173
+ map.on('error', onError);
174
+ return () => map.off('error', onError);
175
+ }
176
+ /** A refusal MapLibre reported, remembered as the 401 it was. */
177
+ const unauthorized = (message) => new LocationServiceException_js_1.LocationServiceException({
178
+ code: 'UnauthorizedException',
179
+ message,
180
+ statusCode: 401,
181
+ });
@@ -1,5 +1,6 @@
1
1
  import type { RequestOptions } from '../transport/http.js';
2
2
  import type { ColorScheme, LabelSize, MapFeatureMode, ScaleBarUnit, StaticMapStyle } from './mapEnums.js';
3
+ import type { MapTokenSource } from './mapToken.js';
3
4
  /**
4
5
  * Static maps: build the URL, send the right headers, get a Blob.
5
6
  *
@@ -110,11 +111,14 @@ export declare function buildStaticMapUrl(apiUrl: string, options: StaticMapOpti
110
111
  *
111
112
  * A refused plan feature — a Satellite `style`, the default when none is
112
113
  * given, or a `politicalView` — rejects with a `LocationServiceException`
113
- * whose `isFeatureNotEntitled` is true, as `fetchMapStyle` does.
114
+ * whose `isFeatureNotEntitled` is true, as `fetchMapStyle` does. Given
115
+ * `{ getToken, refreshToken }`, a refused token is replaced once, as
116
+ * `fetchMapStyle` does it (#72).
114
117
  *
115
118
  * @param apiUrl Base URL of the Location Service API
116
119
  * @param options Render options; exactly one of center / boundingBox / boundedPositions
117
- * @param getToken Callback returning the current auth token
120
+ * @param tokens Callback returning the current auth token, or
121
+ * `{ getToken, refreshToken }` to recover from a refused one
118
122
  * @param request Transport options: `signal` to cancel, `timeoutMs`, `overallTimeoutMs`, `retry`
119
123
  *
120
124
  * @example
@@ -124,4 +128,4 @@ export declare function buildStaticMapUrl(apiUrl: string, options: StaticMapOpti
124
128
  * }, getToken)
125
129
  * const url = URL.createObjectURL(blob) // remember to revokeObjectURL
126
130
  */
127
- export declare function fetchStaticMap(apiUrl: string, options: StaticMapOptions, getToken: () => string | undefined, request?: RequestOptions): Promise<Blob>;
131
+ export declare function fetchStaticMap(apiUrl: string, options: StaticMapOptions, tokens: MapTokenSource, request?: RequestOptions): Promise<Blob>;
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.staticMapAccept = staticMapAccept;
4
4
  exports.buildStaticMapUrl = buildStaticMapUrl;
5
5
  exports.fetchStaticMap = fetchStaticMap;
6
- const errors_js_1 = require("../transport/errors.js");
7
6
  const http_js_1 = require("../transport/http.js");
7
+ const mapToken_js_1 = require("./mapToken.js");
8
8
  /**
9
9
  * The Accept header this request must send.
10
10
  *
@@ -55,11 +55,14 @@ function buildStaticMapUrl(apiUrl, options) {
55
55
  *
56
56
  * A refused plan feature — a Satellite `style`, the default when none is
57
57
  * given, or a `politicalView` — rejects with a `LocationServiceException`
58
- * whose `isFeatureNotEntitled` is true, as `fetchMapStyle` does.
58
+ * whose `isFeatureNotEntitled` is true, as `fetchMapStyle` does. Given
59
+ * `{ getToken, refreshToken }`, a refused token is replaced once, as
60
+ * `fetchMapStyle` does it (#72).
59
61
  *
60
62
  * @param apiUrl Base URL of the Location Service API
61
63
  * @param options Render options; exactly one of center / boundingBox / boundedPositions
62
- * @param getToken Callback returning the current auth token
64
+ * @param tokens Callback returning the current auth token, or
65
+ * `{ getToken, refreshToken }` to recover from a refused one
63
66
  * @param request Transport options: `signal` to cancel, `timeoutMs`, `overallTimeoutMs`, `retry`
64
67
  *
65
68
  * @example
@@ -69,23 +72,21 @@ function buildStaticMapUrl(apiUrl, options) {
69
72
  * }, getToken)
70
73
  * const url = URL.createObjectURL(blob) // remember to revokeObjectURL
71
74
  */
72
- async function fetchStaticMap(apiUrl, options, getToken, request = {}) {
73
- const token = getToken();
74
- // The same guard as fetchMapStyle and the server connector: a render is not
75
- // worth requesting without a token to send (#37).
76
- if (!token) {
77
- throw (0, errors_js_1.noTokenAvailable)('getToken() returned nothing, so no static map was requested. Check the token provider has finished initialising.');
78
- }
75
+ async function fetchStaticMap(apiUrl, options, tokens, request = {}) {
76
+ const call = (0, http_js_1.startCall)(request);
79
77
  // Through the shared transport, so a static map gets the timeout, budget,
80
78
  // cancellation and retry every other call has -- and its failures arrive as
81
79
  // LocationServiceException rather than as a raw TypeError. The API's own
82
80
  // {message, code, requestId} survives, which matters here: the messages are
83
81
  // specific and actionable -- "'width' and 'height' are required", "Only one
84
82
  // of center, bounding-box or bounded-positions may be set".
85
- return (0, http_js_1.requestBlob)(buildStaticMapUrl(apiUrl, options), {
83
+ //
84
+ // The same guard as fetchMapStyle and the server connector: a render is not
85
+ // worth requesting without a token to send (#37).
86
+ return (0, mapToken_js_1.sendWithTokenRefresh)(tokens, 'getToken() returned nothing, so no static map was requested. Check the token provider has finished initialising.', call, (token) => (0, http_js_1.requestBlob)(buildStaticMapUrl(apiUrl, options), {
86
87
  headers: {
87
88
  Authorization: `Bearer ${token}`,
88
89
  Accept: staticMapAccept(options.style),
89
90
  },
90
- }, request);
91
+ }, call));
91
92
  }
@@ -1,5 +1,7 @@
1
+ import type { GetTokenOptions } from '../auth/TokenProvider.js';
1
2
  import type { VerifyAddressResponse } from '../client/commands.js';
2
3
  import type { RequestOptions } from '../transport/http.js';
4
+ import type { CommandOutput, CommandWithOutput } from '../types/index.js';
3
5
  import type { AppConfigClaims } from '../utils/tokenClaims.js';
4
6
  export interface ConnectorConfig {
5
7
  /** Falls back to `LOCATION_API_URL` / `LOCATION_SERVICE_API_URL`. */
@@ -14,10 +16,13 @@ export interface ConnectorConfig {
14
16
  * a long-lived connector survive expiry.
15
17
  *
16
18
  * `forceRefresh` is passed as `true` when the API has just rejected the token
17
- * this returned — the signature is `TokenProvider.getToken`'s exactly, so
18
- * `getToken: (f) => provider.getToken(f)` is a complete implementation.
19
+ * this returned, and `options` always asks for `cachedUntilExpiry` (#63): a
20
+ * source that can keep sending its cached token through a throttled refresh
21
+ * should, since a connector's token never reaches a browser. The signature
22
+ * is `TokenProvider.getToken`'s, so
23
+ * `getToken: (f, o) => provider.getToken(f, o)` is a complete implementation.
19
24
  */
20
- getToken?: (forceRefresh?: boolean) => Promise<string | {
25
+ getToken?: (forceRefresh?: boolean, options?: GetTokenOptions) => Promise<string | {
21
26
  token?: string;
22
27
  } | undefined>;
23
28
  /** Falls back to `LOCATION_CLIENT_ID` / `LOCATION_SERVICE_CLIENT_ID`. */
@@ -109,6 +114,16 @@ export declare class LocationServiceConnector {
109
114
  * header beats the connector default, whatever the caller capitalised.
110
115
  */
111
116
  private effectiveOrigin;
117
+ /**
118
+ * Send a command, and resolve with its output:
119
+ * `await connector.send(new SearchTextCommand(…))` is a
120
+ * `SearchTextCommandOutput`, with nothing to annotate (#68).
121
+ */
122
+ send<C extends CommandWithOutput>(command: C, options?: SendOptions): Promise<CommandOutput<C>>;
123
+ /**
124
+ * The signature `send` had before it inferred its output (#68), kept for
125
+ * calls naming both type arguments, as `GeoPlacesClient.send` keeps it.
126
+ */
112
127
  send<TInput, TOutput>(command: TInput, options?: SendOptions): Promise<TOutput>;
113
128
  /**
114
129
  * Verify a PlaceId: `send(new VerifyAddressCommand({ PlaceId }))`, typed
@@ -140,7 +140,10 @@ class LocationServiceConnector {
140
140
  return {
141
141
  apiUrl: () => requireApiUrl(apiUrl),
142
142
  get: async (forceRefresh) => {
143
- const result = await getToken(forceRefresh);
143
+ // As the environment source below asks its provider (#63).
144
+ const result = await getToken(forceRefresh, {
145
+ cachedUntilExpiry: true,
146
+ });
144
147
  if (!result)
145
148
  return undefined;
146
149
  return typeof result === 'string' ? result : result.token;
@@ -162,7 +165,9 @@ class LocationServiceConnector {
162
165
  // Already validated by serverTokenSource, which cannot resolve
163
166
  // credentials without it.
164
167
  apiUrl: () => env.apiUrl,
165
- get: async (forceRefresh) => (await env.getToken(forceRefresh)).token,
168
+ // A throttled refresh keeps the cached token in use until its own exp
169
+ // (#63): this is a server dispatch, never a token handed to a browser.
170
+ get: async (forceRefresh) => (await env.getToken(forceRefresh, { cachedUntilExpiry: true })).token,
166
171
  };
167
172
  }
168
173
  /**
@@ -200,8 +205,11 @@ class LocationServiceConnector {
200
205
  const source = this.source();
201
206
  const cmd = command;
202
207
  const url = `${source.apiUrl()}${(0, endpoints_js_1.resolveEndpoint)(cmd)}`;
208
+ // The call's deadline starts here, before the token is waited for, so the
209
+ // caller's `overallTimeoutMs` and `signal` bound the whole call (#62).
210
+ const call = (0, http_js_1.startCall)(options);
203
211
  try {
204
- return await this.dispatchWithRetry(source, url, cmd, options);
212
+ return await this.dispatchWithRetry(source, url, cmd, call);
205
213
  }
206
214
  catch (err) {
207
215
  throw explainMissingOrigin(err, this.effectiveOrigin(options));
@@ -219,63 +227,14 @@ class LocationServiceConnector {
219
227
  return this.send(new commands_js_1.VerifyAddressCommand({ PlaceId: placeId }), options);
220
228
  }
221
229
  async dispatchWithRetry(source, url, cmd, options) {
222
- const token = await source.get();
230
+ // Raced against the caller's signal and deadline, not given them: the
231
+ // token fetch may be shared with other calls (#62).
232
+ const token = await (0, http_js_1.withinCall)(source.get(), options);
223
233
  if (!token)
224
234
  throw (0, errors_js_1.noTokenAvailable)(NO_TOKEN_ADVICE);
225
- // This token was refused a moment ago and nothing has replaced it: answer
226
- // with that refusal rather than send it, and force the source, again (#38).
227
- // A different token from the source ends the hold. When the refresh that
228
- // followed said nothing about when to ask again, it is asked now — but the
229
- // refused token is still not sent.
230
- const held = this.refused.check(token);
231
- if (held && !held.askAgain)
232
- throw held.error;
233
- let rejected = held?.error;
234
- if (!held) {
235
- try {
236
- return await this.dispatch(url, token, cmd, options);
237
- }
238
- catch (err) {
239
- if (!(0, errors_js_1.isTokenRejected)(err))
240
- throw err;
241
- rejected = err;
242
- }
243
- }
244
- // One retry, and only when the replacement is genuinely a different token.
245
- // That single comparison covers every source: a fixed `token` string, a
246
- // caller `getToken` that ignores `forceRefresh`, and a cached token the API
247
- // has revoked before its `exp` all hand back what we already sent — and
248
- // re-sending it would be a second doomed request for the same answer.
249
- let fresh;
250
- try {
251
- fresh = await source.get(true);
252
- }
253
- catch (refusal) {
254
- // A suspended application's /auth/token refuses it as its data routes
255
- // refuse its token. Without this, every send asked for another. A
256
- // refusal that says nothing — a network fault — leaves the source to be
257
- // asked again, but not the token sent.
258
- if ((0, tokenHold_js_1.holdFor)(refusal) > 0)
259
- this.refused.remember(refusal, token);
260
- // Only when no hold stands: one already standing keeps its own end, so
261
- // the refused token is tried again once per hold rather than never.
262
- else if (!held)
263
- this.refused.remember(rejected, token, { askAgain: true });
264
- throw refusal;
265
- }
266
- if (!fresh || fresh === token) {
267
- this.refused.remember(rejected, token);
268
- throw rejected;
269
- }
270
- log('401 on a token the API no longer accepts — retrying once, refreshed');
271
- try {
272
- return await this.dispatch(url, fresh, cmd, options);
273
- }
274
- catch (again) {
275
- if ((0, errors_js_1.isTokenRejected)(again))
276
- this.refused.remember(again, fresh);
277
- throw again;
278
- }
235
+ // Through `sendRetryingOnce`, like every 401 retry here (#38). The forced
236
+ // refresh is raced against the caller as the first ask was (#62).
237
+ return (0, tokenHold_js_1.sendRetryingOnce)(this.refused, token, (t) => this.dispatch(url, t, cmd, options), () => (0, http_js_1.withinCall)(source.get(true), options), () => log('401 on a token the API no longer accepts — retrying once, refreshed'));
279
238
  }
280
239
  dispatch(url, token, cmd, options) {
281
240
  // The caller's input goes out as the caller wrote it — nothing in the body
@@ -1,4 +1,4 @@
1
- import type { TokenResponse } from '../auth/TokenProvider.js';
1
+ import type { GetTokenOptions, TokenResponse } from '../auth/TokenProvider.js';
2
2
  import type { ClientConfig } from '../types/index.js';
3
3
  export interface ServerAuthConfig {
4
4
  apiUrl?: string;
@@ -60,8 +60,12 @@ export declare function resolveApiUrl(explicit?: string): string | undefined;
60
60
  */
61
61
  export interface ServerTokenSource {
62
62
  apiUrl: string;
63
- /** Resolves with a token or rejects; it never resolves tokenless. */
64
- getToken(forceRefresh?: boolean): Promise<TokenResponse & {
63
+ /**
64
+ * Resolves with a token or rejects; it never resolves tokenless. The options
65
+ * are `TokenProvider.getToken`'s: the connector asks for `cachedUntilExpiry`
66
+ * (#63), and `getClientConfig` never does.
67
+ */
68
+ getToken(forceRefresh?: boolean, options?: GetTokenOptions): Promise<TokenResponse & {
65
69
  token: string;
66
70
  }>;
67
71
  }
@@ -84,10 +84,10 @@ function resolveApiUrl(explicit) {
84
84
  *
85
85
  * Two answers qualify. `/auth/token`'s own `Invalid credentials` is a secret
86
86
  * that matched nothing. The gateway's 401 (`UnauthorizedException`) is the
87
- * authorizer refusing the Basic pair before `/auth/token` runs, and it gives
88
- * the same answer for a wrong secret and for an application that is not
89
- * active, so the advice for it names both. `Application is not active`, and
90
- * every 403, is left as the API wrote it.
87
+ * authorizer refusing the Basic pair before `/auth/token` runs. An application
88
+ * that is not active is a 403 (`ApplicationNotActiveException`) on either
89
+ * path, whose sentence names its cause, and it is left as the API wrote it,
90
+ * like every 403.
91
91
  */
92
92
  function isCredentialsRefusal(error) {
93
93
  if (!(error instanceof LocationServiceException_js_1.LocationServiceException))
@@ -99,11 +99,8 @@ function isCredentialsRefusal(error) {
99
99
  }
100
100
  /** The API's words as a sentence, so the advice can follow them. */
101
101
  const sentence = (text) => (/[.!?]$/.test(text) ? text : `${text}.`);
102
- function credentialsAdvice(clientId, error) {
103
- const check = `Check that LOCATION_CLIENT_ID ("${clientId}") and LOCATION_CLIENT_SECRET match your application in the developer portal`;
104
- return error.code === 'UnauthorizedException'
105
- ? `${check}, and that the application is active there.`
106
- : `${check}.`;
102
+ function credentialsAdvice(clientId) {
103
+ return `Check that LOCATION_CLIENT_ID ("${clientId}") and LOCATION_CLIENT_SECRET match your application in the developer portal.`;
107
104
  }
108
105
  function serverTokenSource(config = {}) {
109
106
  log('[serverTokenSource] Starting with config:', {
@@ -139,11 +136,11 @@ function serverTokenSource(config = {}) {
139
136
  const provider = getTokenProvider(apiUrl, clientId, clientSecret);
140
137
  return {
141
138
  apiUrl,
142
- async getToken(forceRefresh = false) {
139
+ async getToken(forceRefresh = false, options) {
143
140
  log('[serverTokenSource] Fetching token (forceRefresh=%s)', forceRefresh);
144
141
  let result;
145
142
  try {
146
- result = await provider.getToken(forceRefresh);
143
+ result = await provider.getToken(forceRefresh, options);
147
144
  }
148
145
  catch (error) {
149
146
  // The API's code and sentence, passed through (#38). Every 401 and 403
@@ -153,7 +150,7 @@ function serverTokenSource(config = {}) {
153
150
  if (isCredentialsRefusal(error)) {
154
151
  throw new LocationServiceException_js_1.LocationServiceException({
155
152
  code: error.code,
156
- message: `${sentence(error.message)} ${credentialsAdvice(clientId, error)}`,
153
+ message: `${sentence(error.message)} ${credentialsAdvice(clientId)}`,
157
154
  statusCode: error.statusCode,
158
155
  requestId: error.requestId,
159
156
  details: error.details,
@@ -1,5 +1,5 @@
1
1
  export { TokenProvider } from '../auth/TokenProvider.js';
2
- export type { TokenProviderConfig, TokenResponse, } from '../auth/TokenProvider.js';
2
+ export type { GetTokenOptions, TokenProviderConfig, TokenResponse, } from '../auth/TokenProvider.js';
3
3
  export { getClientConfig } from './getClientConfig.js';
4
4
  export type { ServerAuthConfig, ServerClientConfig } from './getClientConfig.js';
5
5
  export { LocationServiceConnector } from './LocationServiceConnector.js';
@@ -38,6 +38,24 @@ export interface RequestOptions {
38
38
  maxAttempts?: number;
39
39
  };
40
40
  }
41
+ /**
42
+ * A call's options once it has begun: `deadline` is when `overallTimeoutMs`
43
+ * runs out, fixed at the call's entry, so that a wait before the request — a
44
+ * token — spends the same budget the request then gets the rest of (#62).
45
+ */
46
+ export interface CallOptions extends RequestOptions {
47
+ deadline: number;
48
+ }
49
+ /** Fix a call's deadline at its entry (#62). */
50
+ export declare function startCall<T extends RequestOptions>(options?: T): T & CallOptions;
51
+ /**
52
+ * Wait for `work` within the call: reject with `AbortedException` when the
53
+ * caller's signal aborts, and with `TimeoutException` when its deadline
54
+ * passes, whichever comes first (#62). `work` itself is left running, because
55
+ * it may be shared: one caller's abort must not fail another waiting on the
56
+ * same token fetch.
57
+ */
58
+ export declare function withinCall<T>(work: Promise<T>, call: CallOptions): Promise<T>;
41
59
  /** Exponential backoff with FULL jitter, so retries never march in lockstep. */
42
60
  export declare function backoffMs(attempt: number, random?: () => number): number;
43
61
  /**
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DEFAULT_MAX_ATTEMPTS = exports.DEFAULT_OVERALL_TIMEOUT_MS = exports.DEFAULT_TIMEOUT_MS = void 0;
7
+ exports.startCall = startCall;
8
+ exports.withinCall = withinCall;
7
9
  exports.backoffMs = backoffMs;
8
10
  exports.requestJson = requestJson;
9
11
  exports.requestBlob = requestBlob;
@@ -34,6 +36,40 @@ exports.DEFAULT_OVERALL_TIMEOUT_MS = 30000;
34
36
  exports.DEFAULT_MAX_ATTEMPTS = 3;
35
37
  const BACKOFF_BASE_MS = 250;
36
38
  const BACKOFF_CAP_MS = 4000;
39
+ /** Fix a call's deadline at its entry (#62). */
40
+ function startCall(options = {}) {
41
+ return {
42
+ ...options,
43
+ deadline: Date.now() + (options.overallTimeoutMs ?? exports.DEFAULT_OVERALL_TIMEOUT_MS),
44
+ };
45
+ }
46
+ /**
47
+ * Wait for `work` within the call: reject with `AbortedException` when the
48
+ * caller's signal aborts, and with `TimeoutException` when its deadline
49
+ * passes, whichever comes first (#62). `work` itself is left running, because
50
+ * it may be shared: one caller's abort must not fail another waiting on the
51
+ * same token fetch.
52
+ */
53
+ function withinCall(work, call) {
54
+ const { signal, deadline } = call;
55
+ const overallTimeoutMs = call.overallTimeoutMs ?? exports.DEFAULT_OVERALL_TIMEOUT_MS;
56
+ if (signal?.aborted)
57
+ return Promise.reject(abortedException(signal));
58
+ const left = deadline - Date.now();
59
+ if (left <= 0)
60
+ return Promise.reject(overallTimeoutException(overallTimeoutMs));
61
+ return new Promise((resolve, reject) => {
62
+ const timer = setTimeout(() => finish(() => reject(overallTimeoutException(overallTimeoutMs))), left);
63
+ const onAbort = () => finish(() => reject(abortedException(signal)));
64
+ signal?.addEventListener('abort', onAbort, { once: true });
65
+ function finish(settle) {
66
+ clearTimeout(timer);
67
+ signal?.removeEventListener('abort', onAbort);
68
+ settle();
69
+ }
70
+ work.then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
71
+ });
72
+ }
37
73
  /**
38
74
  * Combine the caller's signal with a per-attempt timeout.
39
75
  *
@@ -115,7 +151,9 @@ async function request(url, init, options, read) {
115
151
  details: { source: 'client' },
116
152
  });
117
153
  }
118
- const deadline = Date.now() + overallTimeoutMs;
154
+ // A call that began before this request (#62) brings its own deadline, so
155
+ // the request has only what the wait before it left.
156
+ const deadline = options.deadline ?? Date.now() + overallTimeoutMs;
119
157
  let lastError;
120
158
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
121
159
  // Checked before every attempt: a signal aborted during backoff must not fire one more.
@@ -1,3 +1,4 @@
1
+ import type { VerifyAddressCommand, VerifyAddressResponse } from '../client/commands.js';
1
2
  /**
2
3
  * At least one of `token`, `getToken` or `refreshToken` must supply a token, or
3
4
  * `send` refuses locally with `InvalidCredentialsException` rather than putting
@@ -52,6 +53,30 @@ export interface ClientConfig {
52
53
  export interface GeoPlacesCommand {
53
54
  readonly input: object;
54
55
  }
56
+ /**
57
+ * The part of an AWS SDK command that carries its output type: the request
58
+ * handler its `resolveMiddleware` builds resolves with `{ output }`. The SDK's
59
+ * own `send` reads the output from the command the same way.
60
+ */
61
+ interface SdkCommandOutputs<O extends object = object> {
62
+ resolveMiddleware(...args: never[]): (...args: never[]) => Promise<{
63
+ output: O;
64
+ }>;
65
+ }
66
+ /**
67
+ * A command whose output `send` can name (#68): every SDK command, this
68
+ * package's narrowed Places commands among them, and `VerifyAddressCommand`.
69
+ */
70
+ export type CommandWithOutput = SdkCommandOutputs | VerifyAddressCommand;
71
+ /**
72
+ * What `send` resolves with for a command (#68): an SDK command's own
73
+ * `…CommandOutput`, and `VerifyAddressResponse` for `VerifyAddressCommand`,
74
+ * which is this package's and has no handler.
75
+ *
76
+ * @example
77
+ * type Out = CommandOutput<AutocompleteCommand> // AutocompleteCommandOutput
78
+ */
79
+ export type CommandOutput<C extends CommandWithOutput> = C extends SdkCommandOutputs<infer O> ? O : VerifyAddressResponse;
55
80
  /**
56
81
  * Minimal interface for a MapLibre Map instance.
57
82
  * Using a structural type avoids hard coupling to a specific maplibre-gl version.
@@ -69,3 +94,4 @@ export interface MapLike {
69
94
  getLayoutProperty(layerId: string, name: string): unknown;
70
95
  setLayoutProperty(layerId: string, name: string, value: unknown): void;
71
96
  }
97
+ export {};