@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.
- package/README.md +73 -4
- package/dist/adapters/GeoPlaces.d.ts +1 -1
- package/dist/auth/TokenProvider.js +3 -3
- package/dist/cjs/adapters/GeoPlaces.d.ts +64 -0
- package/dist/cjs/adapters/GeoPlaces.js +213 -0
- package/dist/cjs/auth/TokenProvider.d.ts +64 -0
- package/dist/cjs/auth/TokenProvider.js +144 -0
- package/dist/cjs/auth/tokenRefresh.d.ts +37 -0
- package/dist/cjs/auth/tokenRefresh.js +58 -0
- package/dist/cjs/client/GeoPlacesClient.d.ts +42 -0
- package/dist/cjs/client/GeoPlacesClient.js +92 -0
- package/dist/cjs/errors/LocationServiceException.d.ts +44 -0
- package/dist/cjs/errors/LocationServiceException.js +60 -0
- package/dist/cjs/index.d.ts +24 -0
- package/dist/cjs/index.js +72 -0
- package/dist/cjs/maps/Utils.d.ts +2 -0
- package/dist/cjs/maps/Utils.js +8 -0
- package/dist/cjs/maps/createTransformRequest.d.ts +12 -0
- package/dist/cjs/maps/createTransformRequest.js +87 -0
- package/dist/cjs/maps/mapEnums.d.ts +102 -0
- package/dist/cjs/maps/mapEnums.js +103 -0
- package/dist/cjs/maps/mapLanguage.d.ts +43 -0
- package/dist/cjs/maps/mapLanguage.js +75 -0
- package/dist/cjs/maps/mapPoi.d.ts +44 -0
- package/dist/cjs/maps/mapPoi.js +64 -0
- package/dist/cjs/maps/mapStyle.d.ts +77 -0
- package/dist/cjs/maps/mapStyle.js +111 -0
- package/dist/cjs/maps/staticMap.d.ts +85 -0
- package/dist/cjs/maps/staticMap.js +81 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/server/LocationServiceConnector.d.ts +104 -0
- package/dist/cjs/server/LocationServiceConnector.js +270 -0
- package/dist/cjs/server/getClientConfig.d.ts +94 -0
- package/dist/cjs/server/getClientConfig.js +174 -0
- package/dist/cjs/server/index.d.ts +6 -0
- package/dist/cjs/server/index.js +9 -0
- package/dist/cjs/transport/endpoints.d.ts +2 -0
- package/dist/cjs/transport/endpoints.js +34 -0
- package/dist/cjs/transport/errors.d.ts +32 -0
- package/dist/cjs/transport/errors.js +120 -0
- package/dist/cjs/transport/http.d.ts +24 -0
- package/dist/cjs/transport/http.js +142 -0
- package/dist/cjs/types/index.d.ts +53 -0
- package/dist/cjs/types/index.js +3 -0
- package/dist/cjs/utils/roundPosition.d.ts +66 -0
- package/dist/cjs/utils/roundPosition.js +109 -0
- package/dist/cjs/utils/tokenClaims.d.ts +55 -0
- package/dist/cjs/utils/tokenClaims.js +61 -0
- package/dist/client/GeoPlacesClient.d.ts +6 -3
- package/dist/client/GeoPlacesClient.js +35 -11
- package/dist/index.d.ts +22 -22
- package/dist/index.js +12 -12
- package/dist/maps/Utils.d.ts +1 -1
- package/dist/maps/Utils.js +1 -1
- package/dist/maps/createTransformRequest.d.ts +2 -0
- package/dist/maps/createTransformRequest.js +45 -1
- package/dist/maps/mapLanguage.d.ts +1 -1
- package/dist/maps/mapStyle.d.ts +1 -1
- package/dist/maps/mapStyle.js +2 -2
- package/dist/maps/staticMap.d.ts +1 -1
- package/dist/maps/staticMap.js +1 -1
- package/dist/server/LocationServiceConnector.d.ts +58 -9
- package/dist/server/LocationServiceConnector.js +217 -38
- package/dist/server/getClientConfig.d.ts +58 -4
- package/dist/server/getClientConfig.js +108 -66
- package/dist/server/index.d.ts +6 -6
- package/dist/server/index.js +3 -3
- package/dist/transport/endpoints.d.ts +1 -1
- package/dist/transport/endpoints.js +1 -1
- package/dist/transport/errors.d.ts +14 -1
- package/dist/transport/errors.js +16 -1
- package/dist/transport/http.js +2 -2
- package/dist/types/index.d.ts +19 -0
- package/package.json +33 -11
|
@@ -1,15 +1,35 @@
|
|
|
1
|
-
import type { RequestOptions } from '../transport/http';
|
|
2
|
-
import type { AppConfigClaims } from '../utils/tokenClaims';
|
|
1
|
+
import type { RequestOptions } from '../transport/http.js';
|
|
2
|
+
import type { AppConfigClaims } from '../utils/tokenClaims.js';
|
|
3
3
|
export interface ConnectorConfig {
|
|
4
|
+
/** Falls back to `LOCATION_API_URL` / `LOCATION_SERVICE_API_URL`. */
|
|
4
5
|
apiUrl?: string;
|
|
6
|
+
/**
|
|
7
|
+
* A fixed token. Nothing can refresh it, so it dies at its own `exp` — pass
|
|
8
|
+
* `getToken` instead, or nothing at all, for a connector that keeps working.
|
|
9
|
+
*/
|
|
5
10
|
token?: string;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Where a token comes from. Called for every request, so this is what makes
|
|
13
|
+
* a long-lived connector survive expiry.
|
|
14
|
+
*
|
|
15
|
+
* `forceRefresh` is passed as `true` when the API has just rejected the token
|
|
16
|
+
* this returned — the signature is `TokenProvider.getToken`'s exactly, so
|
|
17
|
+
* `getToken: (f) => provider.getToken(f)` is a complete implementation.
|
|
18
|
+
*/
|
|
19
|
+
getToken?: (forceRefresh?: boolean) => Promise<string | {
|
|
20
|
+
token?: string;
|
|
21
|
+
} | undefined>;
|
|
22
|
+
/** Falls back to `LOCATION_CLIENT_ID` / `LOCATION_SERVICE_CLIENT_ID`. */
|
|
23
|
+
clientId?: string;
|
|
24
|
+
/** Falls back to `LOCATION_CLIENT_SECRET` / `LOCATION_SERVICE_CLIENT_SECRET`. */
|
|
25
|
+
clientSecret?: string;
|
|
9
26
|
/**
|
|
10
27
|
* Sent as the `Origin` header on every request. The API requires an Origin it
|
|
11
28
|
* recognises on every data request and answers 403 without one, so every
|
|
12
29
|
* caller was setting it by hand on each `send`; this does it once.
|
|
30
|
+
*
|
|
31
|
+
* Falls back to `LOCATION_ORIGIN` / `LOCATION_SERVICE_ORIGIN`, so the
|
|
32
|
+
* zero-argument connector can be made to work from the environment alone.
|
|
13
33
|
*/
|
|
14
34
|
origin?: string;
|
|
15
35
|
}
|
|
@@ -23,19 +43,38 @@ export interface SendOptions extends RequestOptions {
|
|
|
23
43
|
* token management, and the same transport (timeout, cancellation, retry) as the
|
|
24
44
|
* browser client.
|
|
25
45
|
*
|
|
46
|
+
* Configuration is COMPLETED from the environment rather than replaced by it.
|
|
47
|
+
* The constructor used to be all-or-nothing — any argument at all took the
|
|
48
|
+
* "caller supplies everything" branch — so `new LocationServiceConnector()` had
|
|
49
|
+
* credentials but could never send an Origin (403 on every data request) and
|
|
50
|
+
* `new LocationServiceConnector({ origin })` had an Origin but no credentials
|
|
51
|
+
* (#45). Now an explicit `token`/`getToken` still wins outright, and anything
|
|
52
|
+
* short of that is filled in from `LOCATION_API_URL` / `LOCATION_CLIENT_ID` /
|
|
53
|
+
* `LOCATION_CLIENT_SECRET` / `LOCATION_ORIGIN`.
|
|
54
|
+
*
|
|
26
55
|
* @example
|
|
27
56
|
* ```typescript
|
|
57
|
+
* // Credentials and apiUrl from the environment, Origin supplied here
|
|
28
58
|
* const connector = new LocationServiceConnector({ origin: 'https://app.example.com' })
|
|
29
59
|
* const result = await connector.send(new SearchTextCommand({ QueryText: 'Space Needle' }))
|
|
30
60
|
* ```
|
|
31
61
|
*/
|
|
32
62
|
export declare class LocationServiceConnector {
|
|
33
|
-
private
|
|
34
|
-
private
|
|
63
|
+
private readonly config;
|
|
64
|
+
private tokenSource?;
|
|
65
|
+
private readonly origin?;
|
|
35
66
|
readonly serviceId: string;
|
|
36
67
|
constructor(config?: ConnectorConfig);
|
|
37
|
-
/**
|
|
38
|
-
|
|
68
|
+
/**
|
|
69
|
+
* One place that knows how a token is obtained, so nothing can drift.
|
|
70
|
+
*
|
|
71
|
+
* Built on first use rather than in the constructor: resolving the
|
|
72
|
+
* environment path used to start a `/auth/token` round trip from `new`, whose
|
|
73
|
+
* rejection nothing was awaiting yet — an unhandled rejection for a
|
|
74
|
+
* misconfigured process, before it had made a single request.
|
|
75
|
+
*/
|
|
76
|
+
private source;
|
|
77
|
+
private buildSource;
|
|
39
78
|
/**
|
|
40
79
|
* This application's own configuration, as carried on the access token
|
|
41
80
|
* (api#65) — bias precision, and the countries it is scoped to.
|
|
@@ -51,5 +90,15 @@ export declare class LocationServiceConnector {
|
|
|
51
90
|
* case until one is configured in the portal.
|
|
52
91
|
*/
|
|
53
92
|
getAppConfig(): Promise<AppConfigClaims>;
|
|
93
|
+
/**
|
|
94
|
+
* The Origin this request will actually carry.
|
|
95
|
+
*
|
|
96
|
+
* ONE definition, for the two readers that must never disagree about it: the
|
|
97
|
+
* header merge in `dispatch`, and the 403 explanation in `send`. A per-call
|
|
98
|
+
* header beats the connector default, whatever the caller capitalised.
|
|
99
|
+
*/
|
|
100
|
+
private effectiveOrigin;
|
|
54
101
|
send<TInput, TOutput>(command: TInput, options?: SendOptions): Promise<TOutput>;
|
|
102
|
+
private dispatchWithRetry;
|
|
103
|
+
private dispatch;
|
|
55
104
|
}
|
|
@@ -1,11 +1,68 @@
|
|
|
1
1
|
import debug from 'debug';
|
|
2
|
-
import { LocationServiceException } from '../errors/LocationServiceException';
|
|
3
|
-
import { resolveEndpoint } from '../transport/endpoints';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
2
|
+
import { LocationServiceException } from '../errors/LocationServiceException.js';
|
|
3
|
+
import { resolveEndpoint } from '../transport/endpoints.js';
|
|
4
|
+
import { isTokenRejected } from '../transport/errors.js';
|
|
5
|
+
import { requestJson } from '../transport/http.js';
|
|
6
|
+
import { roundPositionFields } from '../utils/roundPosition.js';
|
|
7
|
+
import { readAppConfigClaims } from '../utils/tokenClaims.js';
|
|
8
|
+
import { resolveApiUrl, serverTokenSource } from './getClientConfig.js';
|
|
8
9
|
const log = debug('location-client:connector');
|
|
10
|
+
/** Header lookup that does not care how the caller capitalised the name. */
|
|
11
|
+
function headerValue(headers, name) {
|
|
12
|
+
if (!headers)
|
|
13
|
+
return undefined;
|
|
14
|
+
const wanted = name.toLowerCase();
|
|
15
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
16
|
+
if (key.toLowerCase() === wanted)
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The headers `dispatch` sets itself, and which a caller therefore cannot
|
|
23
|
+
* supply. Lower-case, because that is how they are compared.
|
|
24
|
+
*
|
|
25
|
+
* Kept beside `withoutHeaders` so the list and the record in `dispatch` cannot
|
|
26
|
+
* drift apart: a header added there must be added here too, or the caller's own
|
|
27
|
+
* spelling of it survives the merge.
|
|
28
|
+
*/
|
|
29
|
+
const SYSTEM_HEADERS = ['origin', 'content-type', 'authorization'];
|
|
30
|
+
/** The caller's headers minus `names`, however they capitalised them. */
|
|
31
|
+
function withoutHeaders(headers, names) {
|
|
32
|
+
if (!headers)
|
|
33
|
+
return {};
|
|
34
|
+
const wanted = new Set(names);
|
|
35
|
+
return Object.fromEntries(Object.entries(headers).filter(([key]) => !wanted.has(key.toLowerCase())));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Say why the 403 happened, when we know.
|
|
39
|
+
*
|
|
40
|
+
* `Origin not allowed` with no Origin sent is not an ambiguous failure — it is
|
|
41
|
+
* the documented backend path missing one piece of configuration (#45), and the
|
|
42
|
+
* API's own message cannot say so because from its side the header is simply
|
|
43
|
+
* absent. A new integrator following the README hit a bare "Origin not allowed"
|
|
44
|
+
* that named neither the cause nor the fix.
|
|
45
|
+
*/
|
|
46
|
+
function explainMissingOrigin(err, sentOrigin) {
|
|
47
|
+
if (sentOrigin)
|
|
48
|
+
return err;
|
|
49
|
+
if (!(err instanceof LocationServiceException))
|
|
50
|
+
return err;
|
|
51
|
+
if (err.code !== 'OriginNotAllowedException')
|
|
52
|
+
return err;
|
|
53
|
+
return new LocationServiceException({
|
|
54
|
+
code: err.code,
|
|
55
|
+
message: `${err.message} — this request carried no Origin header, and the API requires ` +
|
|
56
|
+
`one it recognises on every data request. Set \`origin\` on the ` +
|
|
57
|
+
`LocationServiceConnector, set LOCATION_ORIGIN, or pass an Origin in the ` +
|
|
58
|
+
`per-call headers; if the application has no allowed domain configured in ` +
|
|
59
|
+
`the developer portal yet, set that first.`,
|
|
60
|
+
statusCode: err.statusCode,
|
|
61
|
+
requestId: err.requestId,
|
|
62
|
+
details: err.details,
|
|
63
|
+
cause: err,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
9
66
|
/**
|
|
10
67
|
* LocationServiceConnector — server-side connector for the Location Service API.
|
|
11
68
|
*
|
|
@@ -13,28 +70,79 @@ const log = debug('location-client:connector');
|
|
|
13
70
|
* token management, and the same transport (timeout, cancellation, retry) as the
|
|
14
71
|
* browser client.
|
|
15
72
|
*
|
|
73
|
+
* Configuration is COMPLETED from the environment rather than replaced by it.
|
|
74
|
+
* The constructor used to be all-or-nothing — any argument at all took the
|
|
75
|
+
* "caller supplies everything" branch — so `new LocationServiceConnector()` had
|
|
76
|
+
* credentials but could never send an Origin (403 on every data request) and
|
|
77
|
+
* `new LocationServiceConnector({ origin })` had an Origin but no credentials
|
|
78
|
+
* (#45). Now an explicit `token`/`getToken` still wins outright, and anything
|
|
79
|
+
* short of that is filled in from `LOCATION_API_URL` / `LOCATION_CLIENT_ID` /
|
|
80
|
+
* `LOCATION_CLIENT_SECRET` / `LOCATION_ORIGIN`.
|
|
81
|
+
*
|
|
16
82
|
* @example
|
|
17
83
|
* ```typescript
|
|
84
|
+
* // Credentials and apiUrl from the environment, Origin supplied here
|
|
18
85
|
* const connector = new LocationServiceConnector({ origin: 'https://app.example.com' })
|
|
19
86
|
* const result = await connector.send(new SearchTextCommand({ QueryText: 'Space Needle' }))
|
|
20
87
|
* ```
|
|
21
88
|
*/
|
|
22
89
|
export class LocationServiceConnector {
|
|
23
|
-
constructor(config) {
|
|
90
|
+
constructor(config = {}) {
|
|
24
91
|
this.serviceId = 'Geo Places';
|
|
25
|
-
this.
|
|
26
|
-
|
|
92
|
+
this.config = config;
|
|
93
|
+
// `||`, not `??`, to match the other four env-completed fields: an empty
|
|
94
|
+
// string is not a choice to send no Origin, it is a missing value, and the
|
|
95
|
+
// asymmetry meant `origin: ''` suppressed the environment and then produced
|
|
96
|
+
// an error telling the caller to set a variable they may already have set.
|
|
97
|
+
this.origin =
|
|
98
|
+
config.origin ||
|
|
99
|
+
process.env.LOCATION_ORIGIN ||
|
|
100
|
+
process.env.LOCATION_SERVICE_ORIGIN;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* One place that knows how a token is obtained, so nothing can drift.
|
|
104
|
+
*
|
|
105
|
+
* Built on first use rather than in the constructor: resolving the
|
|
106
|
+
* environment path used to start a `/auth/token` round trip from `new`, whose
|
|
107
|
+
* rejection nothing was awaiting yet — an unhandled rejection for a
|
|
108
|
+
* misconfigured process, before it had made a single request.
|
|
109
|
+
*/
|
|
110
|
+
source() {
|
|
111
|
+
return (this.tokenSource ?? (this.tokenSource = this.buildSource()));
|
|
27
112
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
113
|
+
buildSource() {
|
|
114
|
+
const { apiUrl, token, getToken, clientId, clientSecret } = this.config;
|
|
115
|
+
// An explicit token source wins outright. A caller that supplied one is
|
|
116
|
+
// managing credentials itself, and quietly reading the environment
|
|
117
|
+
// underneath it could send another application's token.
|
|
118
|
+
if (getToken) {
|
|
119
|
+
return {
|
|
120
|
+
apiUrl: () => requireApiUrl(apiUrl),
|
|
121
|
+
get: async (forceRefresh) => {
|
|
122
|
+
const result = await getToken(forceRefresh);
|
|
123
|
+
if (!result)
|
|
124
|
+
return undefined;
|
|
125
|
+
return typeof result === 'string' ? result : result.token;
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
if (token) {
|
|
130
|
+
return {
|
|
131
|
+
apiUrl: () => requireApiUrl(apiUrl),
|
|
132
|
+
// A fixed string. Asking again returns the same one, which is how the
|
|
133
|
+
// retry guard knows there is nothing to retry with.
|
|
134
|
+
get: async () => token,
|
|
135
|
+
};
|
|
36
136
|
}
|
|
37
|
-
|
|
137
|
+
// Nothing but (at most) an apiUrl and an origin — complete it from the
|
|
138
|
+
// environment. This is the branch every sample and doc actually takes.
|
|
139
|
+
const env = serverTokenSource({ apiUrl, clientId, clientSecret });
|
|
140
|
+
return {
|
|
141
|
+
// Already validated by serverTokenSource, which cannot resolve
|
|
142
|
+
// credentials without it.
|
|
143
|
+
apiUrl: () => env.apiUrl,
|
|
144
|
+
get: async (forceRefresh) => (await env.getToken(forceRefresh)).token,
|
|
145
|
+
};
|
|
38
146
|
}
|
|
39
147
|
/**
|
|
40
148
|
* This application's own configuration, as carried on the access token
|
|
@@ -51,34 +159,105 @@ export class LocationServiceConnector {
|
|
|
51
159
|
* case until one is configured in the portal.
|
|
52
160
|
*/
|
|
53
161
|
async getAppConfig() {
|
|
54
|
-
return readAppConfigClaims(await this.
|
|
162
|
+
return readAppConfigClaims(await this.source().get());
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The Origin this request will actually carry.
|
|
166
|
+
*
|
|
167
|
+
* ONE definition, for the two readers that must never disagree about it: the
|
|
168
|
+
* header merge in `dispatch`, and the 403 explanation in `send`. A per-call
|
|
169
|
+
* header beats the connector default, whatever the caller capitalised.
|
|
170
|
+
*/
|
|
171
|
+
effectiveOrigin(options) {
|
|
172
|
+
// `||` for the same reason as the constructor: an empty per-call header is
|
|
173
|
+
// a missing value, not a decision to send no Origin.
|
|
174
|
+
return headerValue(options?.headers, 'origin') || this.origin;
|
|
55
175
|
}
|
|
56
176
|
async send(command, options) {
|
|
57
|
-
const
|
|
58
|
-
if (!token) {
|
|
59
|
-
throw new LocationServiceException({
|
|
60
|
-
code: 'InvalidCredentialsException',
|
|
61
|
-
message: 'No token available — check clientId/clientSecret configuration',
|
|
62
|
-
details: { source: 'client' },
|
|
63
|
-
});
|
|
64
|
-
}
|
|
177
|
+
const source = this.source();
|
|
65
178
|
const cmd = command;
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
179
|
+
const url = `${source.apiUrl()}${resolveEndpoint(cmd)}`;
|
|
180
|
+
try {
|
|
181
|
+
return await this.dispatchWithRetry(source, url, cmd, options);
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
throw explainMissingOrigin(err, this.effectiveOrigin(options));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async dispatchWithRetry(source, url, cmd, options) {
|
|
188
|
+
const token = await source.get();
|
|
189
|
+
if (!token)
|
|
190
|
+
throw noTokenAvailable();
|
|
191
|
+
try {
|
|
192
|
+
return await this.dispatch(url, token, cmd, options);
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
if (!isTokenRejected(err))
|
|
196
|
+
throw err;
|
|
197
|
+
// One retry, and only when the replacement is genuinely a different
|
|
198
|
+
// token. That single comparison covers every source: a fixed `token`
|
|
199
|
+
// string, a caller `getToken` that ignores `forceRefresh`, and a cached
|
|
200
|
+
// token the API has revoked before its `exp` all hand back what we
|
|
201
|
+
// already sent — and re-sending it would be a second doomed request, and
|
|
202
|
+
// a second billed one.
|
|
203
|
+
const fresh = await source.get(true);
|
|
204
|
+
if (!fresh || fresh === token)
|
|
205
|
+
throw err;
|
|
206
|
+
log('401 on a token the API no longer accepts — retrying once, refreshed');
|
|
207
|
+
return await this.dispatch(url, fresh, cmd, options);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
dispatch(url, token, cmd, options) {
|
|
211
|
+
// The token is resolved before the request is shaped, so the precision this
|
|
212
|
+
// application is entitled to is available (api#65). Absent claim -> the
|
|
213
|
+
// 3 dp floor, which is what every application gets until one is configured
|
|
214
|
+
// otherwise. Recomputed per attempt because a refreshed token may carry
|
|
215
|
+
// different claims.
|
|
71
216
|
const { biasDecimals } = readAppConfigClaims(token);
|
|
72
217
|
const input = roundPositionFields(cmd.input, biasDecimals);
|
|
73
|
-
//
|
|
74
|
-
//
|
|
218
|
+
// Every system header is set exactly ONCE, and the caller's own spelling of
|
|
219
|
+
// each is dropped first.
|
|
220
|
+
//
|
|
221
|
+
// Spreading them over the caller's record is not enough, because fetch's
|
|
222
|
+
// Headers fill APPENDS rather than replaces: a caller's lowercase key
|
|
223
|
+
// survives beside the canonical one and both go on the wire. For Origin
|
|
224
|
+
// that produced `Origin: default, per-call`, which the API's exact-match
|
|
225
|
+
// domain check rejects (observed: 403 OriginNotAllowedException) — and two
|
|
226
|
+
// keys with the SAME value fared no better, `Origin: x, x`. For
|
|
227
|
+
// Authorization it is worse than a failed override: `{ authorization:
|
|
228
|
+
// 'Bearer not-yours' }` went out as `Bearer not-yours, Bearer <real>`,
|
|
229
|
+
// corrupting the token rather than being ignored by it.
|
|
230
|
+
//
|
|
231
|
+
// Origin's value comes from `effectiveOrigin`, so a per-call header still
|
|
232
|
+
// beats the connector default — it is the DUPLICATE that is removed, not
|
|
233
|
+
// the caller's intent.
|
|
234
|
+
const origin = this.effectiveOrigin(options);
|
|
75
235
|
const headers = {
|
|
76
|
-
...(
|
|
77
|
-
...(
|
|
236
|
+
...withoutHeaders(options?.headers, SYSTEM_HEADERS),
|
|
237
|
+
...(origin ? { Origin: origin } : {}),
|
|
78
238
|
'Content-Type': 'application/json',
|
|
79
239
|
Authorization: `Bearer ${token}`,
|
|
80
240
|
};
|
|
81
|
-
log('Sending %s request to %s', cmd.constructor?.name,
|
|
82
|
-
return requestJson(
|
|
241
|
+
log('Sending %s request to %s', cmd.constructor?.name, url);
|
|
242
|
+
return requestJson(url, { method: 'POST', headers, body: JSON.stringify(input) }, options);
|
|
83
243
|
}
|
|
84
244
|
}
|
|
245
|
+
function requireApiUrl(explicit) {
|
|
246
|
+
const apiUrl = resolveApiUrl(explicit);
|
|
247
|
+
if (!apiUrl) {
|
|
248
|
+
throw new LocationServiceException({
|
|
249
|
+
code: 'ValidationException',
|
|
250
|
+
message: 'No API URL. Pass `apiUrl` to the LocationServiceConnector constructor ' +
|
|
251
|
+
'or set LOCATION_API_URL.',
|
|
252
|
+
details: { source: 'client' },
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return apiUrl;
|
|
256
|
+
}
|
|
257
|
+
function noTokenAvailable() {
|
|
258
|
+
return new LocationServiceException({
|
|
259
|
+
code: 'InvalidCredentialsException',
|
|
260
|
+
message: 'No token available — check clientId/clientSecret configuration',
|
|
261
|
+
details: { source: 'client' },
|
|
262
|
+
});
|
|
263
|
+
}
|
|
@@ -1,12 +1,52 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { TokenResponse } from '../auth/TokenProvider.js';
|
|
2
|
+
import type { ClientConfig } from '../types/index.js';
|
|
2
3
|
export interface ServerAuthConfig {
|
|
3
4
|
apiUrl?: string;
|
|
4
5
|
clientId?: string;
|
|
5
6
|
clientSecret?: string;
|
|
7
|
+
/**
|
|
8
|
+
* Mint a new token instead of returning the cached one.
|
|
9
|
+
*
|
|
10
|
+
* For the case the cache cannot see: a token the API has stopped accepting
|
|
11
|
+
* before its `exp` — revoked in the portal, or issued against a secret that
|
|
12
|
+
* has since been rotated. `TokenProvider` judges freshness from `exp` alone,
|
|
13
|
+
* so without this a caller holding a dead token waits out its whole lifetime.
|
|
14
|
+
*/
|
|
15
|
+
forceRefresh?: boolean;
|
|
6
16
|
}
|
|
7
17
|
export interface ServerClientConfig extends ClientConfig {
|
|
8
18
|
expiresAt?: number;
|
|
9
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Where the API lives, from the argument or the environment.
|
|
22
|
+
*
|
|
23
|
+
* Separate from the credentials because the two are independently overridable:
|
|
24
|
+
* a caller can hand `LocationServiceConnector` its own `token` and still expect
|
|
25
|
+
* `LOCATION_API_URL` to say where to send it.
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveApiUrl(explicit?: string): string | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* A LIVE token source: resolved credentials plus a `getToken` that re-mints
|
|
30
|
+
* when the cached token is spent.
|
|
31
|
+
*
|
|
32
|
+
* This is the seam `getClientConfig` and `LocationServiceConnector` share, and
|
|
33
|
+
* it exists because the two need different SHAPES of the same thing.
|
|
34
|
+
* `getClientConfig` has to return plain data — see the warning on its return
|
|
35
|
+
* value — so it can only ever hand back a snapshot. The connector is long-lived
|
|
36
|
+
* and needs the source itself, or it dies at the first `exp` (#36).
|
|
37
|
+
*
|
|
38
|
+
* Deliberately not exported from `./server`: it hands out a callable bound to
|
|
39
|
+
* the process-wide provider, and the public surface stays the two functions
|
|
40
|
+
* that were already there.
|
|
41
|
+
*/
|
|
42
|
+
export interface ServerTokenSource {
|
|
43
|
+
apiUrl: string;
|
|
44
|
+
/** Resolves with a token or rejects; it never resolves tokenless. */
|
|
45
|
+
getToken(forceRefresh?: boolean): Promise<TokenResponse & {
|
|
46
|
+
token: string;
|
|
47
|
+
}>;
|
|
48
|
+
}
|
|
49
|
+
export declare function serverTokenSource(config?: ServerAuthConfig): ServerTokenSource;
|
|
10
50
|
/**
|
|
11
51
|
* Get client configuration with OAuth2 authentication.
|
|
12
52
|
*
|
|
@@ -26,6 +66,21 @@ export interface ServerClientConfig extends ClientConfig {
|
|
|
26
66
|
* NEVER call from browser/client code as it exposes credentials.
|
|
27
67
|
* For SPA projects, create your own backend endpoint that calls this.
|
|
28
68
|
*
|
|
69
|
+
* ## The return value is PLAIN DATA, and has to stay that way
|
|
70
|
+
*
|
|
71
|
+
* `{ apiUrl, token, expiresAt }` — no methods, no closures. The reason is not
|
|
72
|
+
* style: the shape every sample uses is a Next.js Server Action that returns
|
|
73
|
+
* this straight to a Client Component (every `src/lib/actions/location.ts`
|
|
74
|
+
* under `location-service-samples/web`), and the RSC boundary
|
|
75
|
+
* serialises it. A function on this object is not serialisable and throws at
|
|
76
|
+
* the boundary, so "make getClientConfig return getToken" — which #36 proposed
|
|
77
|
+
* and this JSDoc used to promise two lines below — would break every Next.js
|
|
78
|
+
* consumer of the library.
|
|
79
|
+
*
|
|
80
|
+
* A caller that needs a token which REFRESHES wants one of:
|
|
81
|
+
* - `LocationServiceConnector`, which holds a live source internally (#36), or
|
|
82
|
+
* - `TokenProvider` directly, if it is managing its own lifecycle.
|
|
83
|
+
*
|
|
29
84
|
* @example
|
|
30
85
|
* // Auto-detect from environment
|
|
31
86
|
* const config = await getClientConfig()
|
|
@@ -33,8 +88,7 @@ export interface ServerClientConfig extends ClientConfig {
|
|
|
33
88
|
* // Or override specific values
|
|
34
89
|
* const config = await getClientConfig({ apiUrl: 'https://custom.api.com' })
|
|
35
90
|
*
|
|
36
|
-
* //
|
|
37
|
-
* const
|
|
38
|
-
* const connector = new LocationServiceConnector({ apiUrl: config.apiUrl, token })
|
|
91
|
+
* // The API rejected the token before its exp — revoked, or secret rotated
|
|
92
|
+
* const fresh = await getClientConfig({ forceRefresh: true })
|
|
39
93
|
*/
|
|
40
94
|
export declare function getClientConfig(config?: ServerAuthConfig): Promise<ServerClientConfig>;
|