@itwin/map-layers-auth 3.4.6 → 3.4.7

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 (38) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/lib/cjs/ArcGis/ArcGisAccessClient.d.ts +67 -67
  3. package/lib/cjs/ArcGis/ArcGisAccessClient.js +309 -309
  4. package/lib/cjs/ArcGis/ArcGisAccessClient.js.map +1 -1
  5. package/lib/cjs/ArcGis/ArcGisOAuth2Endpoint.d.ts +22 -22
  6. package/lib/cjs/ArcGis/ArcGisOAuth2Endpoint.js +46 -46
  7. package/lib/cjs/ArcGis/ArcGisOAuth2Endpoint.js.map +1 -1
  8. package/lib/cjs/ArcGis/ArcGisTokenGenerator.d.ts +41 -41
  9. package/lib/cjs/ArcGis/ArcGisTokenGenerator.js +110 -110
  10. package/lib/cjs/ArcGis/ArcGisTokenGenerator.js.map +1 -1
  11. package/lib/cjs/ArcGis/ArcGisTokenManager.d.ts +20 -20
  12. package/lib/cjs/ArcGis/ArcGisTokenManager.js +109 -109
  13. package/lib/cjs/ArcGis/ArcGisTokenManager.js.map +1 -1
  14. package/lib/cjs/ArcGis/ArcGisUrl.d.ts +6 -6
  15. package/lib/cjs/ArcGis/ArcGisUrl.js +49 -49
  16. package/lib/cjs/ArcGis/ArcGisUrl.js.map +1 -1
  17. package/lib/cjs/map-layers-auth.d.ts +5 -5
  18. package/lib/cjs/map-layers-auth.js +21 -21
  19. package/lib/cjs/map-layers-auth.js.map +1 -1
  20. package/lib/esm/ArcGis/ArcGisAccessClient.d.ts +67 -67
  21. package/lib/esm/ArcGis/ArcGisAccessClient.js +305 -305
  22. package/lib/esm/ArcGis/ArcGisAccessClient.js.map +1 -1
  23. package/lib/esm/ArcGis/ArcGisOAuth2Endpoint.d.ts +22 -22
  24. package/lib/esm/ArcGis/ArcGisOAuth2Endpoint.js +42 -42
  25. package/lib/esm/ArcGis/ArcGisOAuth2Endpoint.js.map +1 -1
  26. package/lib/esm/ArcGis/ArcGisTokenGenerator.d.ts +41 -41
  27. package/lib/esm/ArcGis/ArcGisTokenGenerator.js +106 -106
  28. package/lib/esm/ArcGis/ArcGisTokenGenerator.js.map +1 -1
  29. package/lib/esm/ArcGis/ArcGisTokenManager.d.ts +20 -20
  30. package/lib/esm/ArcGis/ArcGisTokenManager.js +105 -105
  31. package/lib/esm/ArcGis/ArcGisTokenManager.js.map +1 -1
  32. package/lib/esm/ArcGis/ArcGisUrl.d.ts +6 -6
  33. package/lib/esm/ArcGis/ArcGisUrl.js +45 -45
  34. package/lib/esm/ArcGis/ArcGisUrl.js.map +1 -1
  35. package/lib/esm/map-layers-auth.d.ts +5 -5
  36. package/lib/esm/map-layers-auth.js +9 -9
  37. package/lib/esm/map-layers-auth.js.map +1 -1
  38. package/package.json +7 -7
@@ -1,306 +1,306 @@
1
- /*---------------------------------------------------------------------------------------------
2
- * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
3
- * See LICENSE.md in the project root for license terms and full copyright notice.
4
- *--------------------------------------------------------------------------------------------*/
5
- /** @packageDocumentation
6
- * @module Tiles
7
- */
8
- import { assert, BeEvent } from "@itwin/core-bentley";
9
- import { ArcGisTokenClientType } from "./ArcGisTokenGenerator";
10
- import { ArcGisOAuth2Endpoint, ArcGisOAuth2EndpointType } from "./ArcGisOAuth2Endpoint";
11
- import { ArcGisTokenManager } from "./ArcGisTokenManager";
12
- import { ArcGisUrl } from "./ArcGisUrl";
13
- /** @beta */
14
- export class ArcGisAccessClient {
15
- constructor() {
16
- this.onOAuthProcessEnd = new BeEvent();
17
- // Derive the Oauth URL from a typical MapLayerURL
18
- // i.e. https://hostname/server/rest/services/NewYork/NewYork3857/MapServer
19
- // => https://hostname/portal/sharing/oauth2/authorize
20
- this._oauthAuthorizeEndPointsCache = new Map();
21
- this._oauthTokenEndPointsCache = new Map();
22
- }
23
- initialize(oAuthConfig) {
24
- if (oAuthConfig) {
25
- this._redirectUri = oAuthConfig.redirectUri;
26
- this._expiration = oAuthConfig.tokenExpiration;
27
- this._clientIds = oAuthConfig.clientIds;
28
- this.initOauthCallbackFunction();
29
- }
30
- return true;
31
- }
32
- initOauthCallbackFunction() {
33
- window.arcGisOAuth2Callback = (redirectLocation) => {
34
- var _a, _b, _c, _d;
35
- let eventSuccess = false;
36
- let stateData;
37
- if (redirectLocation && redirectLocation.hash.length > 0) {
38
- const locationHash = redirectLocation.hash;
39
- const hashParams = new URLSearchParams(locationHash.substring(1));
40
- const token = (_a = hashParams.get("access_token")) !== null && _a !== void 0 ? _a : undefined;
41
- const expiresInStr = (_b = hashParams.get("expires_in")) !== null && _b !== void 0 ? _b : undefined;
42
- const userName = (_c = hashParams.get("username")) !== null && _c !== void 0 ? _c : undefined;
43
- const ssl = hashParams.get("ssl") === "true";
44
- const stateStr = (_d = hashParams.get("state")) !== null && _d !== void 0 ? _d : undefined;
45
- const persist = hashParams.get("persist") === "true";
46
- if (token !== undefined && expiresInStr !== undefined && userName !== undefined && ssl !== undefined && stateStr !== undefined) {
47
- let endpointOrigin;
48
- try {
49
- const state = JSON.parse(stateStr);
50
- stateData = state === null || state === void 0 ? void 0 : state.customData;
51
- endpointOrigin = state === null || state === void 0 ? void 0 : state.endpointOrigin;
52
- }
53
- catch {
54
- }
55
- const expiresIn = Number(expiresInStr);
56
- const expiresAt = (expiresIn * 1000) + (+new Date()); // Converts the token expiration delay (seconds) into a timestamp (UNIX time)
57
- if (endpointOrigin !== undefined) {
58
- ArcGisTokenManager.setOAuth2Token(endpointOrigin, { token, expiresAt, ssl, userName, persist });
59
- eventSuccess = true;
60
- }
61
- }
62
- }
63
- this.onOAuthProcessEnd.raiseEvent(eventSuccess, stateData);
64
- };
65
- }
66
- unInitialize() {
67
- this._redirectUri = undefined;
68
- this._expiration = undefined;
69
- window.arcGisOAuth2Callback = undefined;
70
- }
71
- async getAccessToken(params) {
72
- // First lookup Oauth2 tokens, otherwise check try "legacy tokens" if credentials were provided
73
- try {
74
- const oauth2Token = await this.getOAuthTokenForMapLayerUrl(params.mapLayerUrl.toString());
75
- if (oauth2Token)
76
- return oauth2Token;
77
- if (params.userName && params.password) {
78
- return await ArcGisTokenManager.getToken(params.mapLayerUrl.toString(), params.userName, params.password, { client: ArcGisTokenClientType.referer });
79
- }
80
- }
81
- catch {
82
- }
83
- return undefined;
84
- }
85
- async getTokenServiceEndPoint(mapLayerUrl) {
86
- let tokenEndpoint;
87
- try {
88
- tokenEndpoint = await this.getOAuth2Endpoint(mapLayerUrl, ArcGisOAuth2EndpointType.Authorize);
89
- if (tokenEndpoint) {
90
- }
91
- }
92
- catch { }
93
- return tokenEndpoint;
94
- }
95
- invalidateToken(token) {
96
- let found = ArcGisTokenManager.invalidateToken(token);
97
- if (!found) {
98
- found = ArcGisTokenManager.invalidateOAuth2Token(token);
99
- }
100
- return found;
101
- }
102
- get redirectUri() {
103
- return this._redirectUri;
104
- }
105
- getMatchingEnterpriseClientId(url) {
106
- const clientIds = this.arcGisEnterpriseClientIds;
107
- if (!clientIds) {
108
- return undefined;
109
- }
110
- let clientId;
111
- let defaultClientId;
112
- for (const entry of clientIds) {
113
- if (entry.serviceBaseUrl === "") {
114
- defaultClientId = entry.clientId;
115
- }
116
- else {
117
- if (url.toLowerCase().startsWith(entry.serviceBaseUrl)) {
118
- clientId = entry.clientId;
119
- }
120
- }
121
- }
122
- // If we could not find a match with serviceBaseUrl, and a default clientId
123
- // was specified (i.e empty url), then use default clientId
124
- if (clientId === undefined && defaultClientId !== undefined) {
125
- clientId = defaultClientId;
126
- }
127
- return clientId;
128
- }
129
- get expiration() {
130
- return this._expiration;
131
- }
132
- get arcGisOnlineClientId() {
133
- var _a;
134
- return (_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.arcgisOnlineClientId;
135
- }
136
- set arcGisOnlineClientId(clientId) {
137
- if (this._clientIds === undefined) {
138
- this._clientIds = { arcgisOnlineClientId: clientId };
139
- }
140
- this._clientIds.arcgisOnlineClientId = clientId;
141
- }
142
- get arcGisEnterpriseClientIds() {
143
- var _a;
144
- return (_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.enterpriseClientIds;
145
- }
146
- setEnterpriseClientId(serviceBaseUrl, clientId) {
147
- var _a;
148
- if ((_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.enterpriseClientIds) {
149
- const foundIdx = this._clientIds.enterpriseClientIds.findIndex((entry) => entry.serviceBaseUrl === serviceBaseUrl);
150
- if (foundIdx !== -1) {
151
- this._clientIds.enterpriseClientIds[foundIdx].clientId = clientId;
152
- }
153
- else {
154
- this._clientIds.enterpriseClientIds.push({ serviceBaseUrl, clientId });
155
- }
156
- }
157
- else {
158
- if (this._clientIds === undefined) {
159
- this._clientIds = {};
160
- }
161
- this._clientIds.enterpriseClientIds = [{ serviceBaseUrl, clientId }];
162
- }
163
- }
164
- removeEnterpriseClientId(clientId) {
165
- var _a, _b, _c;
166
- if ((_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.enterpriseClientIds) {
167
- this._clientIds.enterpriseClientIds = (_c = (_b = this._clientIds) === null || _b === void 0 ? void 0 : _b.enterpriseClientIds) === null || _c === void 0 ? void 0 : _c.filter((item) => item.serviceBaseUrl !== clientId.serviceBaseUrl);
168
- }
169
- }
170
- /// //////////
171
- /** @internal */
172
- async getOAuthTokenForMapLayerUrl(mapLayerUrl) {
173
- try {
174
- const oauthEndpoint = await this.getOAuth2Endpoint(mapLayerUrl, ArcGisOAuth2EndpointType.Authorize);
175
- if (oauthEndpoint !== undefined) {
176
- const oauthEndpointUrl = new URL(oauthEndpoint.getUrl());
177
- return ArcGisTokenManager.getOAuth2Token(oauthEndpointUrl.origin);
178
- }
179
- }
180
- catch { }
181
- return undefined;
182
- }
183
- /**
184
- * Test if Oauth2 endpoint is accessible and has an associated appId
185
- * @return true/false if validation succeeded, undefined if validation could not be performed (i.e CORS/network error)
186
- * @internal
187
- */
188
- async validateOAuth2Endpoint(endpointUrl) {
189
- // Check if we got a matching appId for that endpoint, otherwise its not worth going further
190
- if (undefined === this.getMatchingEnterpriseClientId(endpointUrl)) {
191
- return false;
192
- }
193
- let status;
194
- try {
195
- const data = await fetch(endpointUrl, { method: "GET" });
196
- status = data.status;
197
- }
198
- catch (error) {
199
- // fetch() throws when there is a CORS error, so in that case
200
- // we cannot confirm if the oauth2 endpoint is valid or not, we return undefined
201
- return undefined;
202
- }
203
- return status === 400; // Oauth2 API returns 400 (Bad Request) when there are missing parameters
204
- }
205
- /**
206
- * Get OAuth2 endpoint that must be cause to get the Oauth2 token
207
- * @internal
208
- */
209
- async getOAuth2Endpoint(url, endpoint) {
210
- // Return from cache if available
211
- const cachedEndpoint = (endpoint === ArcGisOAuth2EndpointType.Authorize ? this._oauthAuthorizeEndPointsCache.get(url) : this._oauthTokenEndPointsCache.get(url));
212
- if (cachedEndpoint !== undefined) {
213
- return cachedEndpoint;
214
- }
215
- const cacheResult = (obj) => {
216
- if (endpoint === ArcGisOAuth2EndpointType.Authorize) {
217
- this._oauthAuthorizeEndPointsCache.set(url, obj);
218
- }
219
- else {
220
- this._oauthTokenEndPointsCache.set(url, obj);
221
- }
222
- };
223
- const endpointStr = (endpoint === ArcGisOAuth2EndpointType.Authorize ? "authorize" : "token");
224
- const urlObj = new URL(url);
225
- if (urlObj.hostname.toLowerCase().endsWith("arcgis.com")) {
226
- // ArcGIS Online (fixed)
227
- // Doc: https://developers.arcgis.com/documentation/mapping-apis-and-services/security/oauth-2.0/
228
- if (this.arcGisOnlineClientId === undefined) {
229
- return undefined;
230
- }
231
- const oauth2Url = `https://www.arcgis.com/sharing/rest/oauth2/${endpointStr}`;
232
- return new ArcGisOAuth2Endpoint(url, this.constructLoginUrl(oauth2Url, true), true);
233
- }
234
- else {
235
- // First attempt: derive the Oauth2 token URL from the 'tokenServicesUrl', exposed by the 'info request'
236
- let restUrlFromTokenService;
237
- try {
238
- restUrlFromTokenService = await ArcGisUrl.getRestUrlFromGenerateTokenUrl(urlObj);
239
- }
240
- catch { }
241
- if (restUrlFromTokenService !== undefined) {
242
- // Validate the URL we just composed
243
- try {
244
- const oauth2Url = `${restUrlFromTokenService.toString()}oauth2/${endpointStr}`;
245
- const valid = await this.validateOAuth2Endpoint(oauth2Url);
246
- // We assume undefined means CORS error, that shouldn't prevent popup from displaying the login page.
247
- if (valid === undefined || valid) {
248
- const oauthEndpoint = new ArcGisOAuth2Endpoint(oauth2Url, this.constructLoginUrl(oauth2Url, false), false);
249
- cacheResult(oauthEndpoint);
250
- return oauthEndpoint;
251
- }
252
- }
253
- catch { }
254
- }
255
- // If reach this point, that means we could not derive the token endpoint from 'tokenServicesUrl', lets try something else.
256
- // ArcGIS Enterprise Format https://<host>:<port>/<subdirectory>/sharing/rest/oauth2/authorize
257
- const regExMatch = url.match(new RegExp(/([^&\/]+)\/rest\/services\/.*/, "i"));
258
- if (regExMatch !== null && regExMatch.length >= 2) {
259
- const subdirectory = regExMatch[1];
260
- const port = (urlObj.port !== "80" && urlObj.port !== "443") ? `:${urlObj.port}` : "";
261
- const newUrlObj = new URL(`${urlObj.protocol}//${urlObj.hostname}${port}/${subdirectory}/sharing/rest/oauth2/${endpointStr}`);
262
- // Check again the URL we just composed
263
- try {
264
- const newUrl = newUrlObj.toString();
265
- if (await this.validateOAuth2Endpoint(newUrl)) {
266
- const oauthEndpoint = new ArcGisOAuth2Endpoint(newUrl, this.constructLoginUrl(newUrl, false), false);
267
- cacheResult(oauthEndpoint);
268
- return oauthEndpoint;
269
- }
270
- }
271
- catch { }
272
- }
273
- }
274
- return undefined; // we could not find any valid oauth2 endpoint
275
- }
276
- /**
277
- * Construct the complete Authorize url to starts the Oauth process
278
- * @internal
279
- */
280
- constructLoginUrl(url, isArcgisOnline) {
281
- const urlObj = new URL(url);
282
- // Set the client id
283
- if (isArcgisOnline) {
284
- const clientId = this.arcGisOnlineClientId;
285
- assert(clientId !== undefined);
286
- if (clientId !== undefined) {
287
- urlObj.searchParams.set("client_id", clientId);
288
- }
289
- }
290
- else {
291
- const clientId = this.getMatchingEnterpriseClientId(url);
292
- assert(clientId !== undefined);
293
- if (undefined !== clientId) {
294
- urlObj.searchParams.set("client_id", clientId);
295
- }
296
- }
297
- urlObj.searchParams.set("response_type", "token");
298
- if (this.expiration !== undefined) {
299
- urlObj.searchParams.set("expiration", `${this.expiration}`);
300
- }
301
- if (this.redirectUri)
302
- urlObj.searchParams.set("redirect_uri", this.redirectUri);
303
- return urlObj.toString();
304
- }
305
- }
1
+ /*---------------------------------------------------------------------------------------------
2
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
3
+ * See LICENSE.md in the project root for license terms and full copyright notice.
4
+ *--------------------------------------------------------------------------------------------*/
5
+ /** @packageDocumentation
6
+ * @module Tiles
7
+ */
8
+ import { assert, BeEvent } from "@itwin/core-bentley";
9
+ import { ArcGisTokenClientType } from "./ArcGisTokenGenerator";
10
+ import { ArcGisOAuth2Endpoint, ArcGisOAuth2EndpointType } from "./ArcGisOAuth2Endpoint";
11
+ import { ArcGisTokenManager } from "./ArcGisTokenManager";
12
+ import { ArcGisUrl } from "./ArcGisUrl";
13
+ /** @beta */
14
+ export class ArcGisAccessClient {
15
+ constructor() {
16
+ this.onOAuthProcessEnd = new BeEvent();
17
+ // Derive the Oauth URL from a typical MapLayerURL
18
+ // i.e. https://hostname/server/rest/services/NewYork/NewYork3857/MapServer
19
+ // => https://hostname/portal/sharing/oauth2/authorize
20
+ this._oauthAuthorizeEndPointsCache = new Map();
21
+ this._oauthTokenEndPointsCache = new Map();
22
+ }
23
+ initialize(oAuthConfig) {
24
+ if (oAuthConfig) {
25
+ this._redirectUri = oAuthConfig.redirectUri;
26
+ this._expiration = oAuthConfig.tokenExpiration;
27
+ this._clientIds = oAuthConfig.clientIds;
28
+ this.initOauthCallbackFunction();
29
+ }
30
+ return true;
31
+ }
32
+ initOauthCallbackFunction() {
33
+ window.arcGisOAuth2Callback = (redirectLocation) => {
34
+ var _a, _b, _c, _d;
35
+ let eventSuccess = false;
36
+ let stateData;
37
+ if (redirectLocation && redirectLocation.hash.length > 0) {
38
+ const locationHash = redirectLocation.hash;
39
+ const hashParams = new URLSearchParams(locationHash.substring(1));
40
+ const token = (_a = hashParams.get("access_token")) !== null && _a !== void 0 ? _a : undefined;
41
+ const expiresInStr = (_b = hashParams.get("expires_in")) !== null && _b !== void 0 ? _b : undefined;
42
+ const userName = (_c = hashParams.get("username")) !== null && _c !== void 0 ? _c : undefined;
43
+ const ssl = hashParams.get("ssl") === "true";
44
+ const stateStr = (_d = hashParams.get("state")) !== null && _d !== void 0 ? _d : undefined;
45
+ const persist = hashParams.get("persist") === "true";
46
+ if (token !== undefined && expiresInStr !== undefined && userName !== undefined && ssl !== undefined && stateStr !== undefined) {
47
+ let endpointOrigin;
48
+ try {
49
+ const state = JSON.parse(stateStr);
50
+ stateData = state === null || state === void 0 ? void 0 : state.customData;
51
+ endpointOrigin = state === null || state === void 0 ? void 0 : state.endpointOrigin;
52
+ }
53
+ catch {
54
+ }
55
+ const expiresIn = Number(expiresInStr);
56
+ const expiresAt = (expiresIn * 1000) + (+new Date()); // Converts the token expiration delay (seconds) into a timestamp (UNIX time)
57
+ if (endpointOrigin !== undefined) {
58
+ ArcGisTokenManager.setOAuth2Token(endpointOrigin, { token, expiresAt, ssl, userName, persist });
59
+ eventSuccess = true;
60
+ }
61
+ }
62
+ }
63
+ this.onOAuthProcessEnd.raiseEvent(eventSuccess, stateData);
64
+ };
65
+ }
66
+ unInitialize() {
67
+ this._redirectUri = undefined;
68
+ this._expiration = undefined;
69
+ window.arcGisOAuth2Callback = undefined;
70
+ }
71
+ async getAccessToken(params) {
72
+ // First lookup Oauth2 tokens, otherwise check try "legacy tokens" if credentials were provided
73
+ try {
74
+ const oauth2Token = await this.getOAuthTokenForMapLayerUrl(params.mapLayerUrl.toString());
75
+ if (oauth2Token)
76
+ return oauth2Token;
77
+ if (params.userName && params.password) {
78
+ return await ArcGisTokenManager.getToken(params.mapLayerUrl.toString(), params.userName, params.password, { client: ArcGisTokenClientType.referer });
79
+ }
80
+ }
81
+ catch {
82
+ }
83
+ return undefined;
84
+ }
85
+ async getTokenServiceEndPoint(mapLayerUrl) {
86
+ let tokenEndpoint;
87
+ try {
88
+ tokenEndpoint = await this.getOAuth2Endpoint(mapLayerUrl, ArcGisOAuth2EndpointType.Authorize);
89
+ if (tokenEndpoint) {
90
+ }
91
+ }
92
+ catch { }
93
+ return tokenEndpoint;
94
+ }
95
+ invalidateToken(token) {
96
+ let found = ArcGisTokenManager.invalidateToken(token);
97
+ if (!found) {
98
+ found = ArcGisTokenManager.invalidateOAuth2Token(token);
99
+ }
100
+ return found;
101
+ }
102
+ get redirectUri() {
103
+ return this._redirectUri;
104
+ }
105
+ getMatchingEnterpriseClientId(url) {
106
+ const clientIds = this.arcGisEnterpriseClientIds;
107
+ if (!clientIds) {
108
+ return undefined;
109
+ }
110
+ let clientId;
111
+ let defaultClientId;
112
+ for (const entry of clientIds) {
113
+ if (entry.serviceBaseUrl === "") {
114
+ defaultClientId = entry.clientId;
115
+ }
116
+ else {
117
+ if (url.toLowerCase().startsWith(entry.serviceBaseUrl)) {
118
+ clientId = entry.clientId;
119
+ }
120
+ }
121
+ }
122
+ // If we could not find a match with serviceBaseUrl, and a default clientId
123
+ // was specified (i.e empty url), then use default clientId
124
+ if (clientId === undefined && defaultClientId !== undefined) {
125
+ clientId = defaultClientId;
126
+ }
127
+ return clientId;
128
+ }
129
+ get expiration() {
130
+ return this._expiration;
131
+ }
132
+ get arcGisOnlineClientId() {
133
+ var _a;
134
+ return (_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.arcgisOnlineClientId;
135
+ }
136
+ set arcGisOnlineClientId(clientId) {
137
+ if (this._clientIds === undefined) {
138
+ this._clientIds = { arcgisOnlineClientId: clientId };
139
+ }
140
+ this._clientIds.arcgisOnlineClientId = clientId;
141
+ }
142
+ get arcGisEnterpriseClientIds() {
143
+ var _a;
144
+ return (_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.enterpriseClientIds;
145
+ }
146
+ setEnterpriseClientId(serviceBaseUrl, clientId) {
147
+ var _a;
148
+ if ((_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.enterpriseClientIds) {
149
+ const foundIdx = this._clientIds.enterpriseClientIds.findIndex((entry) => entry.serviceBaseUrl === serviceBaseUrl);
150
+ if (foundIdx !== -1) {
151
+ this._clientIds.enterpriseClientIds[foundIdx].clientId = clientId;
152
+ }
153
+ else {
154
+ this._clientIds.enterpriseClientIds.push({ serviceBaseUrl, clientId });
155
+ }
156
+ }
157
+ else {
158
+ if (this._clientIds === undefined) {
159
+ this._clientIds = {};
160
+ }
161
+ this._clientIds.enterpriseClientIds = [{ serviceBaseUrl, clientId }];
162
+ }
163
+ }
164
+ removeEnterpriseClientId(clientId) {
165
+ var _a, _b, _c;
166
+ if ((_a = this._clientIds) === null || _a === void 0 ? void 0 : _a.enterpriseClientIds) {
167
+ this._clientIds.enterpriseClientIds = (_c = (_b = this._clientIds) === null || _b === void 0 ? void 0 : _b.enterpriseClientIds) === null || _c === void 0 ? void 0 : _c.filter((item) => item.serviceBaseUrl !== clientId.serviceBaseUrl);
168
+ }
169
+ }
170
+ /// //////////
171
+ /** @internal */
172
+ async getOAuthTokenForMapLayerUrl(mapLayerUrl) {
173
+ try {
174
+ const oauthEndpoint = await this.getOAuth2Endpoint(mapLayerUrl, ArcGisOAuth2EndpointType.Authorize);
175
+ if (oauthEndpoint !== undefined) {
176
+ const oauthEndpointUrl = new URL(oauthEndpoint.getUrl());
177
+ return ArcGisTokenManager.getOAuth2Token(oauthEndpointUrl.origin);
178
+ }
179
+ }
180
+ catch { }
181
+ return undefined;
182
+ }
183
+ /**
184
+ * Test if Oauth2 endpoint is accessible and has an associated appId
185
+ * @return true/false if validation succeeded, undefined if validation could not be performed (i.e CORS/network error)
186
+ * @internal
187
+ */
188
+ async validateOAuth2Endpoint(endpointUrl) {
189
+ // Check if we got a matching appId for that endpoint, otherwise its not worth going further
190
+ if (undefined === this.getMatchingEnterpriseClientId(endpointUrl)) {
191
+ return false;
192
+ }
193
+ let status;
194
+ try {
195
+ const data = await fetch(endpointUrl, { method: "GET" });
196
+ status = data.status;
197
+ }
198
+ catch (error) {
199
+ // fetch() throws when there is a CORS error, so in that case
200
+ // we cannot confirm if the oauth2 endpoint is valid or not, we return undefined
201
+ return undefined;
202
+ }
203
+ return status === 400; // Oauth2 API returns 400 (Bad Request) when there are missing parameters
204
+ }
205
+ /**
206
+ * Get OAuth2 endpoint that must be cause to get the Oauth2 token
207
+ * @internal
208
+ */
209
+ async getOAuth2Endpoint(url, endpoint) {
210
+ // Return from cache if available
211
+ const cachedEndpoint = (endpoint === ArcGisOAuth2EndpointType.Authorize ? this._oauthAuthorizeEndPointsCache.get(url) : this._oauthTokenEndPointsCache.get(url));
212
+ if (cachedEndpoint !== undefined) {
213
+ return cachedEndpoint;
214
+ }
215
+ const cacheResult = (obj) => {
216
+ if (endpoint === ArcGisOAuth2EndpointType.Authorize) {
217
+ this._oauthAuthorizeEndPointsCache.set(url, obj);
218
+ }
219
+ else {
220
+ this._oauthTokenEndPointsCache.set(url, obj);
221
+ }
222
+ };
223
+ const endpointStr = (endpoint === ArcGisOAuth2EndpointType.Authorize ? "authorize" : "token");
224
+ const urlObj = new URL(url);
225
+ if (urlObj.hostname.toLowerCase().endsWith("arcgis.com")) {
226
+ // ArcGIS Online (fixed)
227
+ // Doc: https://developers.arcgis.com/documentation/mapping-apis-and-services/security/oauth-2.0/
228
+ if (this.arcGisOnlineClientId === undefined) {
229
+ return undefined;
230
+ }
231
+ const oauth2Url = `https://www.arcgis.com/sharing/rest/oauth2/${endpointStr}`;
232
+ return new ArcGisOAuth2Endpoint(url, this.constructLoginUrl(oauth2Url, true), true);
233
+ }
234
+ else {
235
+ // First attempt: derive the Oauth2 token URL from the 'tokenServicesUrl', exposed by the 'info request'
236
+ let restUrlFromTokenService;
237
+ try {
238
+ restUrlFromTokenService = await ArcGisUrl.getRestUrlFromGenerateTokenUrl(urlObj);
239
+ }
240
+ catch { }
241
+ if (restUrlFromTokenService !== undefined) {
242
+ // Validate the URL we just composed
243
+ try {
244
+ const oauth2Url = `${restUrlFromTokenService.toString()}oauth2/${endpointStr}`;
245
+ const valid = await this.validateOAuth2Endpoint(oauth2Url);
246
+ // We assume undefined means CORS error, that shouldn't prevent popup from displaying the login page.
247
+ if (valid === undefined || valid) {
248
+ const oauthEndpoint = new ArcGisOAuth2Endpoint(oauth2Url, this.constructLoginUrl(oauth2Url, false), false);
249
+ cacheResult(oauthEndpoint);
250
+ return oauthEndpoint;
251
+ }
252
+ }
253
+ catch { }
254
+ }
255
+ // If reach this point, that means we could not derive the token endpoint from 'tokenServicesUrl', lets try something else.
256
+ // ArcGIS Enterprise Format https://<host>:<port>/<subdirectory>/sharing/rest/oauth2/authorize
257
+ const regExMatch = url.match(new RegExp(/([^&\/]+)\/rest\/services\/.*/, "i"));
258
+ if (regExMatch !== null && regExMatch.length >= 2) {
259
+ const subdirectory = regExMatch[1];
260
+ const port = (urlObj.port !== "80" && urlObj.port !== "443") ? `:${urlObj.port}` : "";
261
+ const newUrlObj = new URL(`${urlObj.protocol}//${urlObj.hostname}${port}/${subdirectory}/sharing/rest/oauth2/${endpointStr}`);
262
+ // Check again the URL we just composed
263
+ try {
264
+ const newUrl = newUrlObj.toString();
265
+ if (await this.validateOAuth2Endpoint(newUrl)) {
266
+ const oauthEndpoint = new ArcGisOAuth2Endpoint(newUrl, this.constructLoginUrl(newUrl, false), false);
267
+ cacheResult(oauthEndpoint);
268
+ return oauthEndpoint;
269
+ }
270
+ }
271
+ catch { }
272
+ }
273
+ }
274
+ return undefined; // we could not find any valid oauth2 endpoint
275
+ }
276
+ /**
277
+ * Construct the complete Authorize url to starts the Oauth process
278
+ * @internal
279
+ */
280
+ constructLoginUrl(url, isArcgisOnline) {
281
+ const urlObj = new URL(url);
282
+ // Set the client id
283
+ if (isArcgisOnline) {
284
+ const clientId = this.arcGisOnlineClientId;
285
+ assert(clientId !== undefined);
286
+ if (clientId !== undefined) {
287
+ urlObj.searchParams.set("client_id", clientId);
288
+ }
289
+ }
290
+ else {
291
+ const clientId = this.getMatchingEnterpriseClientId(url);
292
+ assert(clientId !== undefined);
293
+ if (undefined !== clientId) {
294
+ urlObj.searchParams.set("client_id", clientId);
295
+ }
296
+ }
297
+ urlObj.searchParams.set("response_type", "token");
298
+ if (this.expiration !== undefined) {
299
+ urlObj.searchParams.set("expiration", `${this.expiration}`);
300
+ }
301
+ if (this.redirectUri)
302
+ urlObj.searchParams.set("redirect_uri", this.redirectUri);
303
+ return urlObj.toString();
304
+ }
305
+ }
306
306
  //# sourceMappingURL=ArcGisAccessClient.js.map