@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,37 @@
1
+ /**
2
+ * How long before expiry a token is treated as needing replacement.
3
+ *
4
+ * ONE number, used by both sides: the server-side `TokenProvider` deciding
5
+ * whether its cached token is still good, and the React provider deciding
6
+ * whether to ask for a new one. Both apply it to the same `exp` claim, so they
7
+ * cannot reach different answers about the same token.
8
+ *
9
+ * It used to be two separate `60`s — a private literal in `isExpired()` and a
10
+ * public `refreshBuffer` prop default — with nothing tying them together. On
11
+ * 2026-08-23 a consumer passed `refreshBuffer={800}` against a 900 s token: the
12
+ * client judged it stale after 100 s, the server still considered it fresh for
13
+ * another 840 s and returned the same one, and the client asked again
14
+ * immediately — roughly 110 requests per second from an idle page.
15
+ *
16
+ * Not configurable per consumer, deliberately. A settable client-side buffer is
17
+ * precisely what allowed that disagreement, and no amount of capping or backing
18
+ * off fixes it as cleanly as the two sides simply sharing the number.
19
+ */
20
+ export declare const TOKEN_REFRESH_BUFFER_SECONDS = 60;
21
+ /**
22
+ * Read the `exp` claim out of a JWT, in milliseconds.
23
+ *
24
+ * The expiry is IN THE TOKEN, so neither side needs to be told it. Both used to
25
+ * take it on trust from elsewhere — the server from the response body's
26
+ * `expires_at`, the React provider from whatever `getConfig` returned, falling
27
+ * back to inventing `Date.now() + 900_000` when that was absent. An invented
28
+ * expiry is how the two ended up disagreeing about the same token.
29
+ *
30
+ * Deliberately NOT verified. This is only used to decide *when to refresh*;
31
+ * nothing is authorised on the strength of it, and the API verifies the
32
+ * signature on every request regardless. Trusting `exp` for scheduling is safe
33
+ * in a way that trusting it for access would not be.
34
+ *
35
+ * Returns undefined for anything unparseable, so callers keep their fallback.
36
+ */
37
+ export declare function readTokenExpiry(token: string | undefined): number | undefined;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TOKEN_REFRESH_BUFFER_SECONDS = void 0;
4
+ exports.readTokenExpiry = readTokenExpiry;
5
+ /**
6
+ * How long before expiry a token is treated as needing replacement.
7
+ *
8
+ * ONE number, used by both sides: the server-side `TokenProvider` deciding
9
+ * whether its cached token is still good, and the React provider deciding
10
+ * whether to ask for a new one. Both apply it to the same `exp` claim, so they
11
+ * cannot reach different answers about the same token.
12
+ *
13
+ * It used to be two separate `60`s — a private literal in `isExpired()` and a
14
+ * public `refreshBuffer` prop default — with nothing tying them together. On
15
+ * 2026-08-23 a consumer passed `refreshBuffer={800}` against a 900 s token: the
16
+ * client judged it stale after 100 s, the server still considered it fresh for
17
+ * another 840 s and returned the same one, and the client asked again
18
+ * immediately — roughly 110 requests per second from an idle page.
19
+ *
20
+ * Not configurable per consumer, deliberately. A settable client-side buffer is
21
+ * precisely what allowed that disagreement, and no amount of capping or backing
22
+ * off fixes it as cleanly as the two sides simply sharing the number.
23
+ */
24
+ exports.TOKEN_REFRESH_BUFFER_SECONDS = 60;
25
+ /**
26
+ * Read the `exp` claim out of a JWT, in milliseconds.
27
+ *
28
+ * The expiry is IN THE TOKEN, so neither side needs to be told it. Both used to
29
+ * take it on trust from elsewhere — the server from the response body's
30
+ * `expires_at`, the React provider from whatever `getConfig` returned, falling
31
+ * back to inventing `Date.now() + 900_000` when that was absent. An invented
32
+ * expiry is how the two ended up disagreeing about the same token.
33
+ *
34
+ * Deliberately NOT verified. This is only used to decide *when to refresh*;
35
+ * nothing is authorised on the strength of it, and the API verifies the
36
+ * signature on every request regardless. Trusting `exp` for scheduling is safe
37
+ * in a way that trusting it for access would not be.
38
+ *
39
+ * Returns undefined for anything unparseable, so callers keep their fallback.
40
+ */
41
+ function readTokenExpiry(token) {
42
+ if (!token)
43
+ return undefined;
44
+ const payload = token.split('.')[1];
45
+ if (!payload)
46
+ return undefined;
47
+ try {
48
+ const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
49
+ const json = typeof atob === 'function'
50
+ ? atob(base64)
51
+ : Buffer.from(base64, 'base64').toString('utf8');
52
+ const exp = JSON.parse(json)?.exp;
53
+ return typeof exp === 'number' ? exp * 1000 : undefined;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
@@ -0,0 +1,42 @@
1
+ import type { RequestOptions } from '../transport/http.js';
2
+ import type { ClientConfig } from '../types/index.js';
3
+ import type { AppConfigClaims } from '../utils/tokenClaims.js';
4
+ export type SendOptions = RequestOptions;
5
+ /**
6
+ * GeoPlacesClient — AWS Location Service compatible client with custom auth.
7
+ *
8
+ * Uses AWS SDK command classes but replaces SigV4 with a Bearer token. All
9
+ * request and response types are identical to AWS Location Service.
10
+ *
11
+ * Pass `getToken` in config for live refresh without recreating the client.
12
+ */
13
+ export declare class GeoPlacesClient {
14
+ private clientConfig;
15
+ readonly config: {
16
+ serviceId: string;
17
+ };
18
+ constructor(config: ClientConfig);
19
+ /**
20
+ * This application's own configuration, as carried on the access token
21
+ * (api#65) — bias precision, and the countries it is scoped to.
22
+ *
23
+ * Provided so an application can SHOW its own settings: populate a country
24
+ * selector with the markets it actually serves, label a settings screen,
25
+ * and so on. Being a few minutes stale is cosmetic for that.
26
+ *
27
+ * It is not an entitlement check. See AppConfigClaims for why acting on
28
+ * `countries` client-side makes requests fail that would otherwise succeed.
29
+ *
30
+ * Returns `{}` when the token carries no application config, which is the
31
+ * case until one is configured in the portal.
32
+ */
33
+ getAppConfig(): AppConfigClaims;
34
+ /** Prefer the getToken callback (live ref) over a static token string. */
35
+ private currentToken;
36
+ /**
37
+ * @param options `signal` to cancel, `timeoutMs` per attempt, `retry: false`
38
+ * to disable the retry loop. Every failure throws LocationServiceException.
39
+ */
40
+ send<TInput, TOutput>(command: TInput, options?: SendOptions): Promise<TOutput>;
41
+ private dispatch;
42
+ }
@@ -0,0 +1,92 @@
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.GeoPlacesClient = void 0;
7
+ const debug_1 = __importDefault(require("debug"));
8
+ const endpoints_js_1 = require("../transport/endpoints.js");
9
+ const errors_js_1 = require("../transport/errors.js");
10
+ const http_js_1 = require("../transport/http.js");
11
+ const roundPosition_js_1 = require("../utils/roundPosition.js");
12
+ const tokenClaims_js_1 = require("../utils/tokenClaims.js");
13
+ const log = (0, debug_1.default)('location-client:api');
14
+ /**
15
+ * GeoPlacesClient — AWS Location Service compatible client with custom auth.
16
+ *
17
+ * Uses AWS SDK command classes but replaces SigV4 with a Bearer token. All
18
+ * request and response types are identical to AWS Location Service.
19
+ *
20
+ * Pass `getToken` in config for live refresh without recreating the client.
21
+ */
22
+ class GeoPlacesClient {
23
+ constructor(config) {
24
+ this.clientConfig = config;
25
+ this.config = { serviceId: 'Geo Places' };
26
+ }
27
+ /**
28
+ * This application's own configuration, as carried on the access token
29
+ * (api#65) — bias precision, and the countries it is scoped to.
30
+ *
31
+ * Provided so an application can SHOW its own settings: populate a country
32
+ * selector with the markets it actually serves, label a settings screen,
33
+ * and so on. Being a few minutes stale is cosmetic for that.
34
+ *
35
+ * It is not an entitlement check. See AppConfigClaims for why acting on
36
+ * `countries` client-side makes requests fail that would otherwise succeed.
37
+ *
38
+ * Returns `{}` when the token carries no application config, which is the
39
+ * case until one is configured in the portal.
40
+ */
41
+ getAppConfig() {
42
+ return (0, tokenClaims_js_1.readAppConfigClaims)(this.currentToken());
43
+ }
44
+ /** Prefer the getToken callback (live ref) over a static token string. */
45
+ currentToken() {
46
+ return this.clientConfig.getToken?.() ?? this.clientConfig.token;
47
+ }
48
+ /**
49
+ * @param options `signal` to cancel, `timeoutMs` per attempt, `retry: false`
50
+ * to disable the retry loop. Every failure throws LocationServiceException.
51
+ */
52
+ async send(command, options) {
53
+ const cmd = command;
54
+ const url = `${this.clientConfig.apiUrl}${(0, endpoints_js_1.resolveEndpoint)(cmd)}`;
55
+ const token = this.currentToken();
56
+ try {
57
+ return await this.dispatch(url, token, cmd, options);
58
+ }
59
+ catch (err) {
60
+ if (!(0, errors_js_1.isTokenRejected)(err))
61
+ throw err;
62
+ // One shot. `refreshToken` is the only way to actually obtain a new
63
+ // token here — `getToken` is synchronous and returns the one already in
64
+ // hand — but it is re-read as a fallback because a provider that
65
+ // refreshes in the background may have landed a new one while this
66
+ // request was in flight.
67
+ const fresh = (await this.clientConfig.refreshToken?.()) ?? this.currentToken();
68
+ // Nothing new to send. Repeating the request would fail identically, and
69
+ // be billed identically.
70
+ if (!fresh || fresh === token)
71
+ throw err;
72
+ log('401 — retrying %s once with a refreshed token', cmd.constructor?.name);
73
+ return await this.dispatch(url, fresh, cmd, options);
74
+ }
75
+ }
76
+ dispatch(url, token, cmd, options) {
77
+ // Resolve the token BEFORE rounding: the precision this application is
78
+ // entitled to is a claim on it (api#65). Absent claim -> the 3 dp floor.
79
+ const { biasDecimals } = (0, tokenClaims_js_1.readAppConfigClaims)(token);
80
+ const input = (0, roundPosition_js_1.roundPositionFields)(cmd.input, biasDecimals);
81
+ log('Sending %s to %s', cmd.constructor?.name, url);
82
+ return (0, http_js_1.requestJson)(url, {
83
+ method: 'POST',
84
+ headers: {
85
+ 'Content-Type': 'application/json',
86
+ Authorization: `Bearer ${token}`,
87
+ },
88
+ body: JSON.stringify(input),
89
+ }, options);
90
+ }
91
+ }
92
+ exports.GeoPlacesClient = GeoPlacesClient;
@@ -0,0 +1,44 @@
1
+ export interface LocationServiceExceptionOptions {
2
+ message: string;
3
+ code: string;
4
+ /** Absent for failures that never reached the server: network, timeout, abort. */
5
+ statusCode?: number;
6
+ requestId?: string;
7
+ /** Structured extras — `source: 'client'` marks a locally-raised failure. */
8
+ details?: Record<string, unknown>;
9
+ cause?: unknown;
10
+ /** Parsed from the `Retry-After` header, in milliseconds. */
11
+ retryAfterMs?: number;
12
+ }
13
+ /**
14
+ * The single error type this package throws.
15
+ *
16
+ * Every failure — an API error envelope, a network fault, a timeout, an abort —
17
+ * arrives as one of these, so a caller writes one `catch` and asks the getters
18
+ * rather than sniffing at `TypeError` vs `DOMException` vs a bare `Error`.
19
+ */
20
+ export declare class LocationServiceException extends Error {
21
+ readonly code: string;
22
+ readonly statusCode?: number;
23
+ readonly requestId?: string;
24
+ readonly details?: Record<string, unknown>;
25
+ readonly retryAfterMs?: number;
26
+ constructor(options: LocationServiceExceptionOptions);
27
+ /**
28
+ * Worth another attempt.
29
+ *
30
+ * Deliberately a explicit list rather than `statusCode >= 500`: a 500 or 501
31
+ * means the server broke on this request and will break again, while 502/503/
32
+ * 504 mean it never got there or gave up waiting. Retrying the first kind just
33
+ * multiplies the damage. Network failures and timeouts are retryable because
34
+ * nothing was necessarily processed.
35
+ */
36
+ get isRetryable(): boolean;
37
+ get isThrottling(): boolean;
38
+ get isValidation(): boolean;
39
+ /** Credentials or entitlements — the caller must act, retrying will not help. */
40
+ get isAuth(): boolean;
41
+ get isAborted(): boolean;
42
+ get isTimeout(): boolean;
43
+ toString(): string;
44
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LocationServiceException = void 0;
4
+ /**
5
+ * The single error type this package throws.
6
+ *
7
+ * Every failure — an API error envelope, a network fault, a timeout, an abort —
8
+ * arrives as one of these, so a caller writes one `catch` and asks the getters
9
+ * rather than sniffing at `TypeError` vs `DOMException` vs a bare `Error`.
10
+ */
11
+ class LocationServiceException extends Error {
12
+ constructor(options) {
13
+ super(options.message, { cause: options.cause });
14
+ this.name = 'LocationServiceException';
15
+ this.code = options.code;
16
+ this.statusCode = options.statusCode;
17
+ this.requestId = options.requestId;
18
+ this.details = options.details;
19
+ this.retryAfterMs = options.retryAfterMs;
20
+ }
21
+ /**
22
+ * Worth another attempt.
23
+ *
24
+ * Deliberately a explicit list rather than `statusCode >= 500`: a 500 or 501
25
+ * means the server broke on this request and will break again, while 502/503/
26
+ * 504 mean it never got there or gave up waiting. Retrying the first kind just
27
+ * multiplies the damage. Network failures and timeouts are retryable because
28
+ * nothing was necessarily processed.
29
+ */
30
+ get isRetryable() {
31
+ if (this.code === 'AbortedException')
32
+ return false;
33
+ if (this.code === 'NetworkException' || this.code === 'TimeoutException')
34
+ return true;
35
+ return (this.statusCode === 429 || [502, 503, 504].includes(this.statusCode ?? 0));
36
+ }
37
+ get isThrottling() {
38
+ return this.code === 'ThrottlingException' || this.statusCode === 429;
39
+ }
40
+ get isValidation() {
41
+ return this.code === 'ValidationException' || this.statusCode === 400;
42
+ }
43
+ /** Credentials or entitlements — the caller must act, retrying will not help. */
44
+ get isAuth() {
45
+ return this.statusCode === 401 || this.statusCode === 403;
46
+ }
47
+ get isAborted() {
48
+ return this.code === 'AbortedException';
49
+ }
50
+ get isTimeout() {
51
+ return this.code === 'TimeoutException';
52
+ }
53
+ toString() {
54
+ const parts = [`LocationServiceException: [${this.code}] ${this.message}`];
55
+ if (this.requestId)
56
+ parts.push(`(requestId: ${this.requestId})`);
57
+ return parts.join(' ');
58
+ }
59
+ }
60
+ exports.LocationServiceException = LocationServiceException;
@@ -0,0 +1,24 @@
1
+ export { GeoPlacesClient } from './client/GeoPlacesClient.js';
2
+ export type { SendOptions } from './client/GeoPlacesClient.js';
3
+ export { DEFAULT_MAX_ATTEMPTS, DEFAULT_TIMEOUT_MS } from './transport/http.js';
4
+ export type { RequestOptions } from './transport/http.js';
5
+ export { TOKEN_REFRESH_BUFFER_SECONDS, readTokenExpiry, } from './auth/tokenRefresh.js';
6
+ export { LocationServiceException } from './errors/LocationServiceException.js';
7
+ export type { LocationServiceExceptionOptions } from './errors/LocationServiceException.js';
8
+ export * from '@aws-sdk/client-geo-places';
9
+ export * from '@aws/amazon-location-utilities-datatypes';
10
+ export { GeoPlaces } from './adapters/GeoPlaces.js';
11
+ export type { GeoPlacesDetailOptions, GeoPlacesOptions, } from './adapters/GeoPlaces.js';
12
+ export { createTransformRequest } from './maps/createTransformRequest.js';
13
+ export { applyMapLanguage } from './maps/mapLanguage.js';
14
+ export { POI_CATEGORIES, setAllPoiVisibility, setPoiVisibility, } from './maps/mapPoi.js';
15
+ export type { PoiCategory } from './maps/mapPoi.js';
16
+ export { buildMapStyleUrl, fetchMapStyle } from './maps/mapStyle.js';
17
+ export type { MapStyleOptions } from './maps/mapStyle.js';
18
+ export { buildStaticMapUrl, fetchStaticMap, staticMapAccept, } from './maps/staticMap.js';
19
+ export type { StaticMapFileName, StaticMapOptions } from './maps/staticMap.js';
20
+ export { BUILDINGS, COLOR_SCHEMES, CONTOUR_DENSITIES, LABEL_SIZES, MAP_FEATURE_MODES, MAP_STYLES, SCALE_BAR_UNITS, SPRITE_VARIANTS, STATIC_MAP_STYLES, TERRAINS, TRAFFIC_MODES, TRAVEL_MODES, } from './maps/mapEnums.js';
21
+ export type { Buildings, ColorScheme, ContourDensity, LabelSize, MapFeatureMode, MapStyle, ScaleBarUnit, SpriteVariant, StaticMapStyle, Terrain, TrafficMode, TravelMode, } from './maps/mapEnums.js';
22
+ export { transformRequest } from './maps/Utils.js';
23
+ export type { ClientConfig, GeoPlacesCommand, MapLike } from './types/index.js';
24
+ export type { AppConfigClaims } from './utils/tokenClaims.js';
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.transformRequest = exports.TRAVEL_MODES = exports.TRAFFIC_MODES = exports.TERRAINS = exports.STATIC_MAP_STYLES = exports.SPRITE_VARIANTS = exports.SCALE_BAR_UNITS = exports.MAP_STYLES = exports.MAP_FEATURE_MODES = exports.LABEL_SIZES = exports.CONTOUR_DENSITIES = exports.COLOR_SCHEMES = exports.BUILDINGS = exports.staticMapAccept = exports.fetchStaticMap = exports.buildStaticMapUrl = exports.fetchMapStyle = exports.buildMapStyleUrl = exports.setPoiVisibility = exports.setAllPoiVisibility = exports.POI_CATEGORIES = exports.applyMapLanguage = exports.createTransformRequest = exports.GeoPlaces = exports.LocationServiceException = exports.readTokenExpiry = exports.TOKEN_REFRESH_BUFFER_SECONDS = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_MAX_ATTEMPTS = exports.GeoPlacesClient = void 0;
18
+ // Client (Custom - uses our auth instead of AWS SigV4)
19
+ var GeoPlacesClient_js_1 = require("./client/GeoPlacesClient.js");
20
+ Object.defineProperty(exports, "GeoPlacesClient", { enumerable: true, get: function () { return GeoPlacesClient_js_1.GeoPlacesClient; } });
21
+ // Transport options — cancellation, per-attempt timeout, retry policy
22
+ var http_js_1 = require("./transport/http.js");
23
+ Object.defineProperty(exports, "DEFAULT_MAX_ATTEMPTS", { enumerable: true, get: function () { return http_js_1.DEFAULT_MAX_ATTEMPTS; } });
24
+ Object.defineProperty(exports, "DEFAULT_TIMEOUT_MS", { enumerable: true, get: function () { return http_js_1.DEFAULT_TIMEOUT_MS; } });
25
+ // Token refresh policy — shared by the server provider and the React provider
26
+ var tokenRefresh_js_1 = require("./auth/tokenRefresh.js");
27
+ Object.defineProperty(exports, "TOKEN_REFRESH_BUFFER_SECONDS", { enumerable: true, get: function () { return tokenRefresh_js_1.TOKEN_REFRESH_BUFFER_SECONDS; } });
28
+ Object.defineProperty(exports, "readTokenExpiry", { enumerable: true, get: function () { return tokenRefresh_js_1.readTokenExpiry; } });
29
+ // Errors
30
+ var LocationServiceException_js_1 = require("./errors/LocationServiceException.js");
31
+ Object.defineProperty(exports, "LocationServiceException", { enumerable: true, get: function () { return LocationServiceException_js_1.LocationServiceException; } });
32
+ // Re-export AWS SDK commands and types
33
+ __exportStar(require("@aws-sdk/client-geo-places"), exports);
34
+ // Re-export AWS Location Utilities (data type conversions)
35
+ __exportStar(require("@aws/amazon-location-utilities-datatypes"), exports);
36
+ // Adapters (Custom - for MapLibre integration)
37
+ var GeoPlaces_js_1 = require("./adapters/GeoPlaces.js");
38
+ Object.defineProperty(exports, "GeoPlaces", { enumerable: true, get: function () { return GeoPlaces_js_1.GeoPlaces; } });
39
+ // Maps utilities
40
+ var createTransformRequest_js_1 = require("./maps/createTransformRequest.js");
41
+ Object.defineProperty(exports, "createTransformRequest", { enumerable: true, get: function () { return createTransformRequest_js_1.createTransformRequest; } });
42
+ var mapLanguage_js_1 = require("./maps/mapLanguage.js");
43
+ Object.defineProperty(exports, "applyMapLanguage", { enumerable: true, get: function () { return mapLanguage_js_1.applyMapLanguage; } });
44
+ var mapPoi_js_1 = require("./maps/mapPoi.js");
45
+ Object.defineProperty(exports, "POI_CATEGORIES", { enumerable: true, get: function () { return mapPoi_js_1.POI_CATEGORIES; } });
46
+ Object.defineProperty(exports, "setAllPoiVisibility", { enumerable: true, get: function () { return mapPoi_js_1.setAllPoiVisibility; } });
47
+ Object.defineProperty(exports, "setPoiVisibility", { enumerable: true, get: function () { return mapPoi_js_1.setPoiVisibility; } });
48
+ var mapStyle_js_1 = require("./maps/mapStyle.js");
49
+ Object.defineProperty(exports, "buildMapStyleUrl", { enumerable: true, get: function () { return mapStyle_js_1.buildMapStyleUrl; } });
50
+ Object.defineProperty(exports, "fetchMapStyle", { enumerable: true, get: function () { return mapStyle_js_1.fetchMapStyle; } });
51
+ var staticMap_js_1 = require("./maps/staticMap.js");
52
+ Object.defineProperty(exports, "buildStaticMapUrl", { enumerable: true, get: function () { return staticMap_js_1.buildStaticMapUrl; } });
53
+ Object.defineProperty(exports, "fetchStaticMap", { enumerable: true, get: function () { return staticMap_js_1.fetchStaticMap; } });
54
+ Object.defineProperty(exports, "staticMapAccept", { enumerable: true, get: function () { return staticMap_js_1.staticMapAccept; } });
55
+ // Accepted values for every map parameter, as VALUES so a picker can be built
56
+ // from them, plus the matching types. Case sensitive — see mapEnums.ts.
57
+ var mapEnums_js_1 = require("./maps/mapEnums.js");
58
+ Object.defineProperty(exports, "BUILDINGS", { enumerable: true, get: function () { return mapEnums_js_1.BUILDINGS; } });
59
+ Object.defineProperty(exports, "COLOR_SCHEMES", { enumerable: true, get: function () { return mapEnums_js_1.COLOR_SCHEMES; } });
60
+ Object.defineProperty(exports, "CONTOUR_DENSITIES", { enumerable: true, get: function () { return mapEnums_js_1.CONTOUR_DENSITIES; } });
61
+ Object.defineProperty(exports, "LABEL_SIZES", { enumerable: true, get: function () { return mapEnums_js_1.LABEL_SIZES; } });
62
+ Object.defineProperty(exports, "MAP_FEATURE_MODES", { enumerable: true, get: function () { return mapEnums_js_1.MAP_FEATURE_MODES; } });
63
+ Object.defineProperty(exports, "MAP_STYLES", { enumerable: true, get: function () { return mapEnums_js_1.MAP_STYLES; } });
64
+ Object.defineProperty(exports, "SCALE_BAR_UNITS", { enumerable: true, get: function () { return mapEnums_js_1.SCALE_BAR_UNITS; } });
65
+ Object.defineProperty(exports, "SPRITE_VARIANTS", { enumerable: true, get: function () { return mapEnums_js_1.SPRITE_VARIANTS; } });
66
+ Object.defineProperty(exports, "STATIC_MAP_STYLES", { enumerable: true, get: function () { return mapEnums_js_1.STATIC_MAP_STYLES; } });
67
+ Object.defineProperty(exports, "TERRAINS", { enumerable: true, get: function () { return mapEnums_js_1.TERRAINS; } });
68
+ Object.defineProperty(exports, "TRAFFIC_MODES", { enumerable: true, get: function () { return mapEnums_js_1.TRAFFIC_MODES; } });
69
+ Object.defineProperty(exports, "TRAVEL_MODES", { enumerable: true, get: function () { return mapEnums_js_1.TRAVEL_MODES; } });
70
+ var Utils_js_1 = require("./maps/Utils.js");
71
+ Object.defineProperty(exports, "transformRequest", { enumerable: true, get: function () { return Utils_js_1.transformRequest; } });
72
+ // Server-only utilities are available via '@chaosity/location-client/server'
@@ -0,0 +1,2 @@
1
+ import type { ClientConfig } from '../types/index.js';
2
+ export declare function transformRequest(url: string, config: ClientConfig): import("maplibre-gl").RequestParameters | Promise<import("maplibre-gl").RequestParameters> | undefined;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transformRequest = transformRequest;
4
+ const createTransformRequest_js_1 = require("./createTransformRequest.js");
5
+ function transformRequest(url, config) {
6
+ const token = config.getToken?.() ?? config.token;
7
+ return (0, createTransformRequest_js_1.createTransformRequest)(config.apiUrl, () => token)(url);
8
+ }
@@ -0,0 +1,12 @@
1
+ import type { RequestTransformFunction } from 'maplibre-gl';
2
+ /**
3
+ * Creates a transformRequest function for MapLibre that adds authentication
4
+ * and proper Accept headers for AWS Location Service API requests.
5
+ *
6
+ * The token is attached to our own API and nowhere else — see isOurApi.
7
+ *
8
+ * @param apiUrl - Base URL of the Location Service API
9
+ * @param getToken - Callback function that returns the current auth token
10
+ * @returns MapLibre transformRequest function
11
+ */
12
+ export declare function createTransformRequest(apiUrl: string, getToken: () => string | undefined): RequestTransformFunction;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTransformRequest = createTransformRequest;
4
+ /**
5
+ * Does this URL belong to our API?
6
+ *
7
+ * This decides who receives the customer's bearer token, and it used to be
8
+ * `url.startsWith(apiUrl)` — a string test standing in for a URL test. For
9
+ * `apiUrl = "https://api.example.com"`, the host `api.example.com.evil.test`
10
+ * is a prefix match, so a style referencing
11
+ * `https://api.example.com.evil.test/tiles/1/2/3` was handed
12
+ * `Authorization: Bearer <token>` and the token left the building (#34).
13
+ *
14
+ * That is reachable because a style descriptor is DATA: its `sprite`, `glyphs`
15
+ * and `sources` entries are URLs the style author chose, and MapLibre asks
16
+ * transformRequest about every one of them. Any style not wholly ours — a
17
+ * customer's own, or one edited through a tool — can name a host it likes.
18
+ *
19
+ * Compared as URLs instead, which also gets host case-folding, default ports
20
+ * (`https://api.test:443` === `https://api.test`) and userinfo right for free,
21
+ * and adds a path check so a shared host serving another tenant under a
22
+ * different base path is not "ours" either.
23
+ *
24
+ * Fails CLOSED: anything that will not parse gets no token. The only way to
25
+ * reach that is a relative `apiUrl` in a runtime with no `location` to resolve
26
+ * it against — i.e. not a browser, which is the only place MapLibre runs.
27
+ */
28
+ function isOurApi(url, apiUrl) {
29
+ const base = typeof location === 'undefined' ? undefined : location.href;
30
+ let ours;
31
+ let theirs;
32
+ try {
33
+ ours = new URL(apiUrl, base);
34
+ theirs = new URL(url, base);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ if (theirs.origin !== ours.origin)
40
+ return false;
41
+ // Trailing slashes normalised so `/v1` and `/v1/` behave the same; the `/`
42
+ // boundary is what stops `/v1` from matching `/v1-internal`.
43
+ const basePath = ours.pathname.replace(/\/+$/, '');
44
+ return (theirs.pathname === basePath || theirs.pathname.startsWith(`${basePath}/`));
45
+ }
46
+ /**
47
+ * Creates a transformRequest function for MapLibre that adds authentication
48
+ * and proper Accept headers for AWS Location Service API requests.
49
+ *
50
+ * The token is attached to our own API and nowhere else — see isOurApi.
51
+ *
52
+ * @param apiUrl - Base URL of the Location Service API
53
+ * @param getToken - Callback function that returns the current auth token
54
+ * @returns MapLibre transformRequest function
55
+ */
56
+ function createTransformRequest(apiUrl, getToken) {
57
+ return (url, _resourceType) => {
58
+ if (isOurApi(url, apiUrl)) {
59
+ const token = getToken();
60
+ if (!token) {
61
+ console.warn('[createTransformRequest] No token available');
62
+ return { url };
63
+ }
64
+ const headers = {
65
+ Authorization: `Bearer ${token}`,
66
+ };
67
+ // Set appropriate Accept headers based on resource type
68
+ if (url.includes('/tiles/')) {
69
+ headers['Accept'] = 'application/x-protobuf';
70
+ }
71
+ else if (url.includes('/glyphs/')) {
72
+ headers['Accept'] = 'application/x-protobuf';
73
+ }
74
+ else if (url.includes('/sprites/') && url.endsWith('.png')) {
75
+ headers['Accept'] = 'image/png';
76
+ }
77
+ else if (url.includes('/sprites/') && url.endsWith('.json')) {
78
+ headers['Accept'] = 'application/json';
79
+ }
80
+ else if (url.includes('/descriptor')) {
81
+ headers['Accept'] = 'application/json';
82
+ }
83
+ return { url, headers };
84
+ }
85
+ return { url };
86
+ };
87
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The values Amazon Location accepts for each map parameter.
3
+ *
4
+ * WHY THESE ARE EXPORTED AS VALUES, NOT JUST TYPES
5
+ *
6
+ * A type union gives you compile-time safety and nothing to iterate. Every
7
+ * consumer that renders a style picker then re-types the same list by hand into
8
+ * a `<select>`, and those copies drift the moment AWS adds a style. Exporting
9
+ * the arrays means a dropdown is `MAP_STYLES.map(...)` and cannot disagree with
10
+ * the type beside it.
11
+ *
12
+ * THESE ARE CASE SENSITIVE
13
+ *
14
+ * AWS documents them so, and since location-service-api#89 the API enforces it
15
+ * rather than forwarding a wrong-cased value for Amazon to reject with an
16
+ * unhelpful 404. `'light'` is not `'Light'`:
17
+ *
18
+ * GET /maps/Standard/descriptor?colorScheme=light
19
+ * 400 "'colorScheme' is case sensitive — use 'Light', not 'light'"
20
+ *
21
+ * So take the values from here rather than typing them, and the case is right
22
+ * by construction.
23
+ *
24
+ * MEMBERSHIP IS NOT THE WHOLE STORY
25
+ *
26
+ * A value being in one of these lists does not mean it is legal in every
27
+ * COMBINATION. `Traffic: 'All'` is valid, and `Style: 'Satellite'` is valid,
28
+ * but together they are not:
29
+ *
30
+ * 400 "Traffic is not supported for style."
31
+ *
32
+ * Amazon owns those rules and answers them per request; the API forwards that
33
+ * message verbatim. Do not try to encode combination rules here — they change
34
+ * without an SDK release.
35
+ *
36
+ * KEEPING THESE HONEST
37
+ *
38
+ * The API derives its copy from the AWS SDK's own `enums.d.ts` via
39
+ * `npm run generate:maps-enums`, so that side cannot drift. This file is the
40
+ * client-side mirror and every value below was additionally confirmed against
41
+ * the live geo-maps API on 2026-08-26. If the API starts rejecting something
42
+ * listed here, its generated list is the authority.
43
+ */
44
+ /** Map styles for the style descriptor. */
45
+ export declare const MAP_STYLES: readonly ["Hybrid", "Monochrome", "Satellite", "Standard"];
46
+ export type MapStyle = (typeof MAP_STYLES)[number];
47
+ /**
48
+ * Styles the STATIC map accepts — deliberately narrower than `MAP_STYLES`.
49
+ *
50
+ * `/maps/static/*` takes only Satellite and Standard. Passing Hybrid or
51
+ * Monochrome there is a 400, so the two lists are not interchangeable.
52
+ */
53
+ export declare const STATIC_MAP_STYLES: readonly ["Satellite", "Standard"];
54
+ export type StaticMapStyle = (typeof STATIC_MAP_STYLES)[number];
55
+ /** Light or dark cartography. Not applicable to the raster styles. */
56
+ export declare const COLOR_SCHEMES: readonly ["Dark", "Light"];
57
+ export type ColorScheme = (typeof COLOR_SCHEMES)[number];
58
+ /** Terrain overlay. `Hillshade` is shaded relief; `Terrain3D` is elevation. */
59
+ export declare const TERRAINS: readonly ["Hillshade", "Terrain3D"];
60
+ export type Terrain = (typeof TERRAINS)[number];
61
+ /** 3D building extrusions. One value today, kept a list for when that changes. */
62
+ export declare const BUILDINGS: readonly ["Buildings3D"];
63
+ export type Buildings = (typeof BUILDINGS)[number];
64
+ /**
65
+ * Elevation contour line density.
66
+ *
67
+ * All three work. An earlier version of this library documented `Medium` as
68
+ * "the only value currently supported by the AWS SDK", which was wrong — `High`
69
+ * and `Low` were both confirmed against the live API on 2026-08-26.
70
+ */
71
+ export declare const CONTOUR_DENSITIES: readonly ["High", "Low", "Medium"];
72
+ export type ContourDensity = (typeof CONTOUR_DENSITIES)[number];
73
+ /**
74
+ * Traffic overlay.
75
+ *
76
+ * `Congestion` was previously missing from this library's types, so it could
77
+ * not be requested from TypeScript even though the API accepts it.
78
+ */
79
+ export declare const TRAFFIC_MODES: readonly ["All", "Congestion"];
80
+ export type TrafficMode = (typeof TRAFFIC_MODES)[number];
81
+ /** Routing overlays. Sent as a comma-separated list; each entry is checked. */
82
+ export declare const TRAVEL_MODES: readonly ["Transit", "Truck"];
83
+ export type TravelMode = (typeof TRAVEL_MODES)[number];
84
+ /** Sprite sheet variant. One value today. */
85
+ export declare const SPRITE_VARIANTS: readonly ["Default"];
86
+ export type SpriteVariant = (typeof SPRITE_VARIANTS)[number];
87
+ /** Static map label size. */
88
+ export declare const LABEL_SIZES: readonly ["Large", "Small"];
89
+ export type LabelSize = (typeof LABEL_SIZES)[number];
90
+ /** Static map scale bar units. */
91
+ export declare const SCALE_BAR_UNITS: readonly ["Kilometers", "KilometersMiles", "Miles", "MilesKilometers"];
92
+ export type ScaleBarUnit = (typeof SCALE_BAR_UNITS)[number];
93
+ /**
94
+ * Static map points-of-interest rendering.
95
+ *
96
+ * A MODE, not a list of categories — an easy one to get wrong, and the reason
97
+ * the static map route returned a confusing error before
98
+ * location-service-api#35. To filter POIs on an interactive map, use
99
+ * `setPoiVisibility` instead.
100
+ */
101
+ export declare const MAP_FEATURE_MODES: readonly ["Disabled", "Enabled"];
102
+ export type MapFeatureMode = (typeof MAP_FEATURE_MODES)[number];