@chaosity/location-client 0.5.1 → 0.7.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 (74) hide show
  1. package/README.md +73 -4
  2. package/dist/adapters/GeoPlaces.d.ts +1 -1
  3. package/dist/auth/TokenProvider.js +3 -3
  4. package/dist/cjs/adapters/GeoPlaces.d.ts +64 -0
  5. package/dist/cjs/adapters/GeoPlaces.js +213 -0
  6. package/dist/cjs/auth/TokenProvider.d.ts +64 -0
  7. package/dist/cjs/auth/TokenProvider.js +144 -0
  8. package/dist/cjs/auth/tokenRefresh.d.ts +37 -0
  9. package/dist/cjs/auth/tokenRefresh.js +58 -0
  10. package/dist/cjs/client/GeoPlacesClient.d.ts +42 -0
  11. package/dist/cjs/client/GeoPlacesClient.js +92 -0
  12. package/dist/cjs/errors/LocationServiceException.d.ts +44 -0
  13. package/dist/cjs/errors/LocationServiceException.js +60 -0
  14. package/dist/cjs/index.d.ts +24 -0
  15. package/dist/cjs/index.js +72 -0
  16. package/dist/cjs/maps/Utils.d.ts +2 -0
  17. package/dist/cjs/maps/Utils.js +8 -0
  18. package/dist/cjs/maps/createTransformRequest.d.ts +12 -0
  19. package/dist/cjs/maps/createTransformRequest.js +87 -0
  20. package/dist/cjs/maps/mapEnums.d.ts +102 -0
  21. package/dist/cjs/maps/mapEnums.js +103 -0
  22. package/dist/cjs/maps/mapLanguage.d.ts +43 -0
  23. package/dist/cjs/maps/mapLanguage.js +75 -0
  24. package/dist/cjs/maps/mapPoi.d.ts +44 -0
  25. package/dist/cjs/maps/mapPoi.js +64 -0
  26. package/dist/cjs/maps/mapStyle.d.ts +77 -0
  27. package/dist/cjs/maps/mapStyle.js +111 -0
  28. package/dist/cjs/maps/staticMap.d.ts +85 -0
  29. package/dist/cjs/maps/staticMap.js +81 -0
  30. package/dist/cjs/package.json +3 -0
  31. package/dist/cjs/server/LocationServiceConnector.d.ts +104 -0
  32. package/dist/cjs/server/LocationServiceConnector.js +270 -0
  33. package/dist/cjs/server/getClientConfig.d.ts +94 -0
  34. package/dist/cjs/server/getClientConfig.js +174 -0
  35. package/dist/cjs/server/index.d.ts +6 -0
  36. package/dist/cjs/server/index.js +9 -0
  37. package/dist/cjs/transport/endpoints.d.ts +2 -0
  38. package/dist/cjs/transport/endpoints.js +34 -0
  39. package/dist/cjs/transport/errors.d.ts +32 -0
  40. package/dist/cjs/transport/errors.js +120 -0
  41. package/dist/cjs/transport/http.d.ts +24 -0
  42. package/dist/cjs/transport/http.js +142 -0
  43. package/dist/cjs/types/index.d.ts +53 -0
  44. package/dist/cjs/types/index.js +3 -0
  45. package/dist/cjs/utils/roundPosition.d.ts +66 -0
  46. package/dist/cjs/utils/roundPosition.js +109 -0
  47. package/dist/cjs/utils/tokenClaims.d.ts +55 -0
  48. package/dist/cjs/utils/tokenClaims.js +61 -0
  49. package/dist/client/GeoPlacesClient.d.ts +6 -3
  50. package/dist/client/GeoPlacesClient.js +35 -11
  51. package/dist/index.d.ts +22 -22
  52. package/dist/index.js +12 -12
  53. package/dist/maps/Utils.d.ts +1 -1
  54. package/dist/maps/Utils.js +1 -1
  55. package/dist/maps/createTransformRequest.d.ts +2 -0
  56. package/dist/maps/createTransformRequest.js +45 -1
  57. package/dist/maps/mapLanguage.d.ts +1 -1
  58. package/dist/maps/mapStyle.d.ts +1 -1
  59. package/dist/maps/mapStyle.js +2 -2
  60. package/dist/maps/staticMap.d.ts +1 -1
  61. package/dist/maps/staticMap.js +1 -1
  62. package/dist/server/LocationServiceConnector.d.ts +58 -9
  63. package/dist/server/LocationServiceConnector.js +217 -38
  64. package/dist/server/getClientConfig.d.ts +58 -4
  65. package/dist/server/getClientConfig.js +108 -66
  66. package/dist/server/index.d.ts +6 -6
  67. package/dist/server/index.js +3 -3
  68. package/dist/transport/endpoints.d.ts +1 -1
  69. package/dist/transport/endpoints.js +1 -1
  70. package/dist/transport/errors.d.ts +14 -1
  71. package/dist/transport/errors.js +16 -1
  72. package/dist/transport/http.js +2 -2
  73. package/dist/types/index.d.ts +19 -0
  74. package/package.json +33 -11
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolveApiUrl = resolveApiUrl;
7
+ exports.serverTokenSource = serverTokenSource;
8
+ exports.getClientConfig = getClientConfig;
9
+ const debug_1 = __importDefault(require("debug"));
10
+ const node_crypto_1 = require("node:crypto");
11
+ const TokenProvider_js_1 = require("../auth/TokenProvider.js");
12
+ const LocationServiceException_js_1 = require("../errors/LocationServiceException.js");
13
+ const log = (0, debug_1.default)('location-client:clientConfig');
14
+ // Singleton instance to prevent race conditions
15
+ let tokenProviderInstance = null;
16
+ let currentConfig = null;
17
+ function getTokenProvider(apiUrl, clientId, clientSecret) {
18
+ // The SECRET is part of the key. Without it, rotating a client secret while
19
+ // keeping the same clientId left this process reusing a provider built on the
20
+ // old secret — so the rotation appeared to do nothing until a restart. Hashed
21
+ // rather than concatenated so the key is never a secret in its own right, and
22
+ // never ends up in a log line (#5).
23
+ const configKey = `${apiUrl}:${clientId}:${(0, node_crypto_1.createHash)('sha256').update(clientSecret).digest('hex').slice(0, 16)}`;
24
+ // Reuse existing instance if config matches
25
+ if (tokenProviderInstance && currentConfig === configKey) {
26
+ log('[getTokenProvider] Reusing existing TokenProvider instance');
27
+ return tokenProviderInstance;
28
+ }
29
+ // Create new instance if config changed
30
+ log('[getTokenProvider] Creating new TokenProvider instance');
31
+ tokenProviderInstance = new TokenProvider_js_1.TokenProvider({ apiUrl, clientId, clientSecret });
32
+ currentConfig = configKey;
33
+ return tokenProviderInstance;
34
+ }
35
+ /**
36
+ * Where the API lives, from the argument or the environment.
37
+ *
38
+ * Separate from the credentials because the two are independently overridable:
39
+ * a caller can hand `LocationServiceConnector` its own `token` and still expect
40
+ * `LOCATION_API_URL` to say where to send it.
41
+ */
42
+ function resolveApiUrl(explicit) {
43
+ return (explicit ||
44
+ process.env.LOCATION_API_URL ||
45
+ process.env.LOCATION_SERVICE_API_URL);
46
+ }
47
+ function serverTokenSource(config = {}) {
48
+ log('[serverTokenSource] Starting with config:', {
49
+ hasApiUrl: !!config.apiUrl,
50
+ hasClientId: !!config.clientId,
51
+ });
52
+ // Auto-detect from environment with fallbacks
53
+ const apiUrl = resolveApiUrl(config.apiUrl);
54
+ const clientId = config.clientId ||
55
+ process.env.LOCATION_CLIENT_ID ||
56
+ process.env.LOCATION_SERVICE_CLIENT_ID;
57
+ const clientSecret = config.clientSecret ||
58
+ process.env.LOCATION_CLIENT_SECRET ||
59
+ process.env.LOCATION_SERVICE_CLIENT_SECRET;
60
+ log('[serverTokenSource] Resolved config:', {
61
+ apiUrl,
62
+ clientId: clientId?.substring(0, 10) + '...',
63
+ });
64
+ // Validate required values. A LocationServiceException like everything else
65
+ // this package throws — it used to be a bare `Error`, which was survivable
66
+ // while only `getClientConfig` could raise it and is not now that the
67
+ // connector reaches this path too.
68
+ if (!apiUrl || !clientId || !clientSecret) {
69
+ console.error('[location-client] Missing required configuration');
70
+ throw new LocationServiceException_js_1.LocationServiceException({
71
+ code: 'ValidationException',
72
+ message: 'Missing required configuration. Set environment variables: ' +
73
+ 'LOCATION_API_URL, LOCATION_CLIENT_ID, LOCATION_CLIENT_SECRET',
74
+ details: { source: 'client' },
75
+ });
76
+ }
77
+ log('[serverTokenSource] Getting TokenProvider instance');
78
+ const provider = getTokenProvider(apiUrl, clientId, clientSecret);
79
+ return {
80
+ apiUrl,
81
+ async getToken(forceRefresh = false) {
82
+ log('[serverTokenSource] Fetching token (forceRefresh=%s)', forceRefresh);
83
+ let result;
84
+ try {
85
+ result = await provider.getToken(forceRefresh);
86
+ }
87
+ catch (error) {
88
+ // The provider now rejects rather than resolving with success:false, and
89
+ // the rejection is typed — so a store outage (503) can be reported as a
90
+ // store outage instead of as bad credentials.
91
+ if (error instanceof LocationServiceException_js_1.LocationServiceException) {
92
+ if (error.isAuth) {
93
+ throw new LocationServiceException_js_1.LocationServiceException({
94
+ code: 'InvalidCredentialsException',
95
+ message: `Authentication failed for client ID "${clientId}". ` +
96
+ `Verify LOCATION_CLIENT_ID and LOCATION_CLIENT_SECRET match your application in the developer portal.`,
97
+ statusCode: error.statusCode,
98
+ requestId: error.requestId,
99
+ cause: error,
100
+ });
101
+ }
102
+ throw error;
103
+ }
104
+ throw error;
105
+ }
106
+ // TokenProvider rejects rather than returning a tokenless success, so this
107
+ // is unreachable in practice — it is here to keep the contract explicit at
108
+ // the type level rather than asserting non-null.
109
+ const token = result.token;
110
+ if (!token) {
111
+ throw new LocationServiceException_js_1.LocationServiceException({
112
+ code: 'InvalidCredentialsException',
113
+ message: 'Token provider returned no token',
114
+ details: { source: 'client' },
115
+ });
116
+ }
117
+ return { ...result, token };
118
+ },
119
+ };
120
+ }
121
+ /**
122
+ * Get client configuration with OAuth2 authentication.
123
+ *
124
+ * Automatically reads from environment variables:
125
+ * - LOCATION_API_URL or LOCATION_SERVICE_API_URL
126
+ * - LOCATION_CLIENT_ID or LOCATION_SERVICE_CLIENT_ID
127
+ * - LOCATION_CLIENT_SECRET or LOCATION_SERVICE_CLIENT_SECRET
128
+ *
129
+ * You can override any value by passing it explicitly.
130
+ *
131
+ * WARNING: This function uses client credentials (clientId/clientSecret).
132
+ * Only call this from:
133
+ * - Next.js Server Components/Actions
134
+ * - Node.js backend servers
135
+ * - API routes
136
+ *
137
+ * NEVER call from browser/client code as it exposes credentials.
138
+ * For SPA projects, create your own backend endpoint that calls this.
139
+ *
140
+ * ## The return value is PLAIN DATA, and has to stay that way
141
+ *
142
+ * `{ apiUrl, token, expiresAt }` — no methods, no closures. The reason is not
143
+ * style: the shape every sample uses is a Next.js Server Action that returns
144
+ * this straight to a Client Component (every `src/lib/actions/location.ts`
145
+ * under `location-service-samples/web`), and the RSC boundary
146
+ * serialises it. A function on this object is not serialisable and throws at
147
+ * the boundary, so "make getClientConfig return getToken" — which #36 proposed
148
+ * and this JSDoc used to promise two lines below — would break every Next.js
149
+ * consumer of the library.
150
+ *
151
+ * A caller that needs a token which REFRESHES wants one of:
152
+ * - `LocationServiceConnector`, which holds a live source internally (#36), or
153
+ * - `TokenProvider` directly, if it is managing its own lifecycle.
154
+ *
155
+ * @example
156
+ * // Auto-detect from environment
157
+ * const config = await getClientConfig()
158
+ *
159
+ * // Or override specific values
160
+ * const config = await getClientConfig({ apiUrl: 'https://custom.api.com' })
161
+ *
162
+ * // The API rejected the token before its exp — revoked, or secret rotated
163
+ * const fresh = await getClientConfig({ forceRefresh: true })
164
+ */
165
+ async function getClientConfig(config = {}) {
166
+ const source = serverTokenSource(config);
167
+ const result = await source.getToken(config.forceRefresh);
168
+ log('[getClientConfig] Token fetched successfully, length:', result.token.length);
169
+ return {
170
+ apiUrl: source.apiUrl,
171
+ token: result.token,
172
+ expiresAt: result.expiresAt,
173
+ };
174
+ }
@@ -0,0 +1,6 @@
1
+ export { TokenProvider } from '../auth/TokenProvider.js';
2
+ export type { TokenProviderConfig, TokenResponse, } from '../auth/TokenProvider.js';
3
+ export { getClientConfig } from './getClientConfig.js';
4
+ export type { ServerAuthConfig, ServerClientConfig } from './getClientConfig.js';
5
+ export { LocationServiceConnector } from './LocationServiceConnector.js';
6
+ export type { ConnectorConfig, SendOptions, } from './LocationServiceConnector.js';
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LocationServiceConnector = exports.getClientConfig = exports.TokenProvider = void 0;
4
+ var TokenProvider_js_1 = require("../auth/TokenProvider.js");
5
+ Object.defineProperty(exports, "TokenProvider", { enumerable: true, get: function () { return TokenProvider_js_1.TokenProvider; } });
6
+ var getClientConfig_js_1 = require("./getClientConfig.js");
7
+ Object.defineProperty(exports, "getClientConfig", { enumerable: true, get: function () { return getClientConfig_js_1.getClientConfig; } });
8
+ var LocationServiceConnector_js_1 = require("./LocationServiceConnector.js");
9
+ Object.defineProperty(exports, "LocationServiceConnector", { enumerable: true, get: function () { return LocationServiceConnector_js_1.LocationServiceConnector; } });
@@ -0,0 +1,2 @@
1
+ import type { GeoPlacesCommand } from '../types/index.js';
2
+ export declare function resolveEndpoint(command: GeoPlacesCommand): string;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveEndpoint = resolveEndpoint;
4
+ const client_geo_places_1 = require("@aws-sdk/client-geo-places");
5
+ const LocationServiceException_js_1 = require("../errors/LocationServiceException.js");
6
+ /**
7
+ * Command class -> API path.
8
+ *
9
+ * Keyed on constructor IDENTITY, never on `constructor.name`: a minifier
10
+ * rewrites class names and a string-keyed map silently stops matching in a
11
+ * production bundle while working perfectly in dev. The server connector used
12
+ * to carry its own `if (cmd instanceof X)` chain saying the same thing in a
13
+ * different order — one of them was always going to drift.
14
+ */
15
+ const ENDPOINTS = new Map([
16
+ [client_geo_places_1.AutocompleteCommand, '/address/autocomplete'],
17
+ [client_geo_places_1.GeocodeCommand, '/address/geocode'],
18
+ [client_geo_places_1.GetPlaceCommand, '/address/place'],
19
+ [client_geo_places_1.ReverseGeocodeCommand, '/address/search/reverse-geocode'],
20
+ [client_geo_places_1.SearchNearbyCommand, '/address/search/nearby'],
21
+ [client_geo_places_1.SearchTextCommand, '/address/search/text'],
22
+ [client_geo_places_1.SuggestCommand, '/address/suggestion'],
23
+ ]);
24
+ function resolveEndpoint(command) {
25
+ for (const [CommandClass, endpoint] of ENDPOINTS) {
26
+ if (command instanceof CommandClass)
27
+ return endpoint;
28
+ }
29
+ throw new LocationServiceException_js_1.LocationServiceException({
30
+ code: 'UnknownCommandException',
31
+ message: `Unknown command type: ${command?.constructor?.name ?? typeof command}`,
32
+ details: { source: 'client' },
33
+ });
34
+ }
@@ -0,0 +1,32 @@
1
+ import { LocationServiceException } from '../errors/LocationServiceException.js';
2
+ /**
3
+ * Turn a non-2xx response into a LocationServiceException.
4
+ *
5
+ * The API does not yet speak one error shape — that is api#29 (T23) — so this
6
+ * tolerates the three it currently emits and synthesises a `code` for each.
7
+ * RFC-0002 calls this legacy tolerance, and it is what lets the client ship
8
+ * before the API contract lands. Delete the fallbacks once T23 is deployed.
9
+ *
10
+ * { message, code, requestId } service Lambdas — already correct
11
+ * { error, error_description } /auth/token, OAuth shape
12
+ * { message: "Unauthorized" } API Gateway's own responses
13
+ */
14
+ export declare function parseErrorResponse(status: number, statusText: string, body: string, headers?: Headers): LocationServiceException;
15
+ /**
16
+ * The API has rejected this token: a 401, and only a 401.
17
+ *
18
+ * The authorizer throws `Unauthorized` for a token it cannot verify or that has
19
+ * expired, and API Gateway turns that into a 401. Its other refusals — no
20
+ * domain configured for the application, an Origin the application does not
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.
23
+ *
24
+ * Shared by both send paths so the browser client and the server connector
25
+ * cannot come to different conclusions about the same response.
26
+ */
27
+ export declare function isTokenRejected(err: unknown): boolean;
28
+ /**
29
+ * `Retry-After` is either delta-seconds or an HTTP date. Both are legal and the
30
+ * API sends the first; a date is handled so a proxy or gateway cannot surprise us.
31
+ */
32
+ export declare function parseRetryAfter(value: string | null | undefined): number | undefined;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseErrorResponse = parseErrorResponse;
4
+ exports.isTokenRejected = isTokenRejected;
5
+ exports.parseRetryAfter = parseRetryAfter;
6
+ const LocationServiceException_js_1 = require("../errors/LocationServiceException.js");
7
+ /**
8
+ * Turn a non-2xx response into a LocationServiceException.
9
+ *
10
+ * The API does not yet speak one error shape — that is api#29 (T23) — so this
11
+ * tolerates the three it currently emits and synthesises a `code` for each.
12
+ * RFC-0002 calls this legacy tolerance, and it is what lets the client ship
13
+ * before the API contract lands. Delete the fallbacks once T23 is deployed.
14
+ *
15
+ * { message, code, requestId } service Lambdas — already correct
16
+ * { error, error_description } /auth/token, OAuth shape
17
+ * { message: "Unauthorized" } API Gateway's own responses
18
+ */
19
+ function parseErrorResponse(status, statusText, body, headers) {
20
+ let message = `Request failed: ${statusText || status}`;
21
+ let code;
22
+ let requestId;
23
+ let details;
24
+ try {
25
+ const data = JSON.parse(body);
26
+ if (typeof data.message === 'string')
27
+ message = data.message;
28
+ if (typeof data.code === 'string')
29
+ code = data.code;
30
+ if (typeof data.requestId === 'string')
31
+ requestId = data.requestId;
32
+ // OAuth envelope from /auth/token
33
+ if (!code && typeof data.error === 'string') {
34
+ message = data.error_description ?? data.error;
35
+ code = oauthCode(data.error, status);
36
+ details = { oauthError: data.error };
37
+ }
38
+ }
39
+ catch {
40
+ if (body)
41
+ message = body;
42
+ }
43
+ return new LocationServiceException_js_1.LocationServiceException({
44
+ message,
45
+ code: code ?? statusCode(status),
46
+ statusCode: status,
47
+ requestId,
48
+ details,
49
+ retryAfterMs: parseRetryAfter(headers?.get('retry-after')),
50
+ });
51
+ }
52
+ /** OAuth `error` values the token endpoint emits, mapped to our codes. */
53
+ function oauthCode(error, status) {
54
+ switch (error) {
55
+ case 'temporarily_unavailable':
56
+ return 'ServiceUnavailableException';
57
+ case 'invalid_client':
58
+ case 'unauthorized':
59
+ return 'InvalidCredentialsException';
60
+ case 'invalid_request':
61
+ return 'ValidationException';
62
+ case 'unsupported_grant_type':
63
+ return 'ValidationException';
64
+ default:
65
+ return statusCode(status);
66
+ }
67
+ }
68
+ /** Last resort when the body carried no code at all (bare gateway responses). */
69
+ function statusCode(status) {
70
+ switch (status) {
71
+ case 400:
72
+ return 'ValidationException';
73
+ case 401:
74
+ return 'UnauthorizedException';
75
+ case 403:
76
+ return 'ForbiddenException';
77
+ case 404:
78
+ return 'NotFoundException';
79
+ case 429:
80
+ return 'ThrottlingException';
81
+ case 502:
82
+ return 'UpstreamException';
83
+ case 503:
84
+ return 'ServiceUnavailableException';
85
+ case 504:
86
+ return 'TimeoutException';
87
+ default:
88
+ return status >= 500 ? 'InternalException' : 'ServiceException';
89
+ }
90
+ }
91
+ /**
92
+ * The API has rejected this token: a 401, and only a 401.
93
+ *
94
+ * The authorizer throws `Unauthorized` for a token it cannot verify or that has
95
+ * expired, and API Gateway turns that into a 401. Its other refusals — no
96
+ * domain configured for the application, an Origin the application does not
97
+ * allow — are a Deny policy or a service 403, and a fresh token changes
98
+ * neither. Retrying those would send, and bill, the same doomed request twice.
99
+ *
100
+ * Shared by both send paths so the browser client and the server connector
101
+ * cannot come to different conclusions about the same response.
102
+ */
103
+ function isTokenRejected(err) {
104
+ return err instanceof LocationServiceException_js_1.LocationServiceException && err.statusCode === 401;
105
+ }
106
+ /**
107
+ * `Retry-After` is either delta-seconds or an HTTP date. Both are legal and the
108
+ * API sends the first; a date is handled so a proxy or gateway cannot surprise us.
109
+ */
110
+ function parseRetryAfter(value) {
111
+ if (!value)
112
+ return undefined;
113
+ const seconds = Number(value);
114
+ if (Number.isFinite(seconds) && seconds >= 0)
115
+ return seconds * 1000;
116
+ const date = Date.parse(value);
117
+ if (!Number.isNaN(date))
118
+ return Math.max(0, date - Date.now());
119
+ return undefined;
120
+ }
@@ -0,0 +1,24 @@
1
+ /** Per-attempt timeout. Sits well under the API's own 25 s Lambda ceiling. */
2
+ export declare const DEFAULT_TIMEOUT_MS = 10000;
3
+ export declare const DEFAULT_MAX_ATTEMPTS = 3;
4
+ export interface RequestOptions {
5
+ /** Caller cancellation. Aborting rejects with code `AbortedException`. */
6
+ signal?: AbortSignal;
7
+ /** Per ATTEMPT, not for the whole call. Default 10 s. */
8
+ timeoutMs?: number;
9
+ /** `false` disables retries entirely. Default 3 attempts = 2 retries. */
10
+ retry?: false | {
11
+ maxAttempts?: number;
12
+ };
13
+ }
14
+ /** Exponential backoff with FULL jitter, so retries never march in lockstep. */
15
+ export declare function backoffMs(attempt: number, random?: () => number): number;
16
+ /**
17
+ * One JSON request, with timeout, cancellation and retry.
18
+ *
19
+ * Every failure leaves as a LocationServiceException — a fetch rejection
20
+ * becomes `NetworkException` with the original as `cause`, an abort becomes
21
+ * `AbortedException`, a timeout becomes `TimeoutException` with
22
+ * `details.source = 'client'` so it is distinguishable from the API's own 504.
23
+ */
24
+ export declare function requestJson<T>(url: string, init: RequestInit, options?: RequestOptions): Promise<T>;
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DEFAULT_MAX_ATTEMPTS = exports.DEFAULT_TIMEOUT_MS = void 0;
7
+ exports.backoffMs = backoffMs;
8
+ exports.requestJson = requestJson;
9
+ const debug_1 = __importDefault(require("debug"));
10
+ const LocationServiceException_js_1 = require("../errors/LocationServiceException.js");
11
+ const errors_js_1 = require("./errors.js");
12
+ const log = (0, debug_1.default)('location-client:transport');
13
+ /** Per-attempt timeout. Sits well under the API's own 25 s Lambda ceiling. */
14
+ exports.DEFAULT_TIMEOUT_MS = 10000;
15
+ exports.DEFAULT_MAX_ATTEMPTS = 3;
16
+ const BACKOFF_BASE_MS = 250;
17
+ const BACKOFF_CAP_MS = 4000;
18
+ /**
19
+ * Combine the caller's signal with a per-attempt timeout.
20
+ *
21
+ * `AbortSignal.any` is the clean way and exists in Node 20+ and current
22
+ * browsers; the manual fan-in keeps older runtimes working rather than
23
+ * throwing at import time.
24
+ */
25
+ function attemptSignal(caller, timeoutMs) {
26
+ const timeout = AbortSignal.timeout(timeoutMs);
27
+ if (!caller)
28
+ return { signal: timeout, cleanup: () => { } };
29
+ if (typeof AbortSignal.any === 'function') {
30
+ return { signal: AbortSignal.any([caller, timeout]), cleanup: () => { } };
31
+ }
32
+ const controller = new AbortController();
33
+ const abort = () => controller.abort();
34
+ if (caller.aborted || timeout.aborted)
35
+ controller.abort();
36
+ caller.addEventListener('abort', abort);
37
+ timeout.addEventListener('abort', abort);
38
+ return {
39
+ signal: controller.signal,
40
+ cleanup: () => {
41
+ caller.removeEventListener('abort', abort);
42
+ timeout.removeEventListener('abort', abort);
43
+ },
44
+ };
45
+ }
46
+ /** Exponential backoff with FULL jitter, so retries never march in lockstep. */
47
+ function backoffMs(attempt, random = Math.random) {
48
+ const ceiling = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
49
+ return Math.floor(random() * ceiling);
50
+ }
51
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
52
+ /**
53
+ * One JSON request, with timeout, cancellation and retry.
54
+ *
55
+ * Every failure leaves as a LocationServiceException — a fetch rejection
56
+ * becomes `NetworkException` with the original as `cause`, an abort becomes
57
+ * `AbortedException`, a timeout becomes `TimeoutException` with
58
+ * `details.source = 'client'` so it is distinguishable from the API's own 504.
59
+ */
60
+ async function requestJson(url, init, options = {}) {
61
+ const timeoutMs = options.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS;
62
+ const maxAttempts = options.retry === false
63
+ ? 1
64
+ : (options.retry?.maxAttempts ?? exports.DEFAULT_MAX_ATTEMPTS);
65
+ let lastError;
66
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
67
+ // Checked before every attempt: a signal aborted during backoff must not fire one more.
68
+ if (options.signal?.aborted)
69
+ throw abortedException(options.signal);
70
+ const { signal, cleanup } = attemptSignal(options.signal, timeoutMs);
71
+ try {
72
+ const response = await fetch(url, { ...init, signal });
73
+ if (response.ok)
74
+ return (await response.json());
75
+ const error = (0, errors_js_1.parseErrorResponse)(response.status, response.statusText, await response.text(), response.headers);
76
+ lastError = error;
77
+ if (!error.isRetryable || attempt === maxAttempts - 1)
78
+ throw error;
79
+ log('attempt %d failed (%s), retrying', attempt + 1, error.code);
80
+ await sleep(error.retryAfterMs ??
81
+ (0, errors_js_1.parseRetryAfter)(response.headers.get('retry-after')) ??
82
+ backoffMs(attempt));
83
+ }
84
+ catch (err) {
85
+ if (err instanceof LocationServiceException_js_1.LocationServiceException) {
86
+ // Already classified above, or thrown on the final attempt.
87
+ if (!err.isRetryable || attempt === maxAttempts - 1)
88
+ throw err;
89
+ lastError = err;
90
+ continue;
91
+ }
92
+ const wrapped = wrapFetchError(err, options.signal);
93
+ lastError = wrapped;
94
+ if (!wrapped.isRetryable || attempt === maxAttempts - 1)
95
+ throw wrapped;
96
+ log('attempt %d failed (%s), retrying', attempt + 1, wrapped.code);
97
+ await sleep(backoffMs(attempt));
98
+ }
99
+ finally {
100
+ cleanup();
101
+ }
102
+ }
103
+ /* c8 ignore next */
104
+ throw (lastError ??
105
+ new LocationServiceException_js_1.LocationServiceException({
106
+ code: 'InternalException',
107
+ message: 'Request failed',
108
+ }));
109
+ }
110
+ function abortedException(signal) {
111
+ return new LocationServiceException_js_1.LocationServiceException({
112
+ code: 'AbortedException',
113
+ message: 'Request was aborted by the caller',
114
+ details: { source: 'client' },
115
+ cause: signal?.reason,
116
+ });
117
+ }
118
+ /**
119
+ * fetch rejects with a raw `TypeError` for a network fault and a `DOMException`
120
+ * named AbortError for both cancellation and timeout — indistinguishable from
121
+ * each other unless the caller's own signal is checked, which is why that is
122
+ * checked first.
123
+ */
124
+ function wrapFetchError(err, callerSignal) {
125
+ const name = err?.name;
126
+ if (callerSignal?.aborted)
127
+ return abortedException(callerSignal);
128
+ if (name === 'TimeoutError' || name === 'AbortError') {
129
+ return new LocationServiceException_js_1.LocationServiceException({
130
+ code: 'TimeoutException',
131
+ message: 'Request timed out',
132
+ details: { source: 'client' },
133
+ cause: err,
134
+ });
135
+ }
136
+ return new LocationServiceException_js_1.LocationServiceException({
137
+ code: 'NetworkException',
138
+ message: err instanceof Error ? err.message : 'Network request failed',
139
+ details: { source: 'client' },
140
+ cause: err,
141
+ });
142
+ }
@@ -0,0 +1,53 @@
1
+ export interface ClientConfig {
2
+ apiUrl: string;
3
+ token: string;
4
+ /** Optional callback to get the current token dynamically. When provided,
5
+ * called on every request so token updates are reflected without recreating the client. */
6
+ getToken?: () => string | undefined;
7
+ /**
8
+ * Asked for a replacement AFTER the API has rejected the current token with a
9
+ * 401, so the request can be retried once instead of failing.
10
+ *
11
+ * Separate from `getToken` because that one is synchronous by contract — it
12
+ * is read while a request is being built and cannot await anything, so it can
13
+ * only ever return the token already in hand. Nothing in this library could
14
+ * therefore recover from a token revoked, or a secret rotated, before its
15
+ * `exp`: every request failed until the refresh buffer elapsed on its own
16
+ * (#36).
17
+ *
18
+ * Returning `undefined` is not "no replacement": the client then re-reads
19
+ * `getToken`, because a provider refreshing in the background may have landed
20
+ * a new token while the failed request was in flight. What actually decides
21
+ * is the token that comes out of those two — if it is the one just rejected,
22
+ * or there is none, the retry is skipped rather than repeating a request that
23
+ * is going to fail again.
24
+ */
25
+ refreshToken?: () => Promise<string | undefined>;
26
+ }
27
+ /**
28
+ * Minimal interface for AWS SDK command objects.
29
+ * All AWS SDK commands (AutocompleteCommand, SearchTextCommand, etc.) extend
30
+ * Smithy's Command base class which has an `input` property containing the
31
+ * request parameters. This interface captures what we actually need from
32
+ * commands without coupling to Smithy internals.
33
+ */
34
+ export interface GeoPlacesCommand {
35
+ readonly input: object;
36
+ }
37
+ /**
38
+ * Minimal interface for a MapLibre Map instance.
39
+ * Using a structural type avoids hard coupling to a specific maplibre-gl version.
40
+ */
41
+ export interface MapLike {
42
+ isStyleLoaded(): boolean | void;
43
+ on(event: string, listener: (...args: unknown[]) => void): void;
44
+ off(event: string, listener: (...args: unknown[]) => void): void;
45
+ getStyle(): {
46
+ layers: Array<{
47
+ id: string;
48
+ type: string;
49
+ }>;
50
+ };
51
+ getLayoutProperty(layerId: string, name: string): unknown;
52
+ setLayoutProperty(layerId: string, name: string, value: unknown): void;
53
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ // Custom types not provided by AWS SDK
3
+ Object.defineProperty(exports, "__esModule", { value: true });