@itwin/map-layers-auth 4.0.0-dev.7 → 4.0.0-dev.72

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