// All material copyright Esri, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.30/esri/copyright.txt for details. //>>built define("exports ../chunks/tslib.es6 ../config ../kernel ../request ../core/Error ../core/Evented ../core/events ../core/lang ../core/object ../core/promiseUtils ../core/urlUtils ../core/accessorSupport/decorators/property ../core/has ../core/Logger ../core/accessorSupport/decorators/subclass ./IdentityModal ./OAuthCredential ./OAuthInfo ./ServerInfo ../portal/support/urlUtils".split(" "),function(t,A,K,E,D,w,P,L,Q,F,C,r,B,Y,Z,W,R,S,T,M,N){const G={},U=a=>{const b=(new r.Url(a.owningSystemUrl)).host; a=(new r.Url(a.server)).host;const c=/.+\.arcgis\.com$/i;return c.test(b)&&c.test(a)},O=(a,b)=>!!(U(a)&&b&&b.some(c=>c.test(a.server)));let H=null,I=null;try{H=window.localStorage,I=window.sessionStorage}catch{}class V extends P{constructor(){super();this._portalConfig=globalThis.esriGeowConfig;this.serverInfos=[];this.oAuthInfos=[];this.credentials=[];this._soReqs=[];this._xoReqs=[];this._portals=[];this._defaultOAuthInfo=null;this._defaultTokenValidity=60;this.tokenValidity=this.dialog=null;this.normalizeWebTierAuth= !1;this._appOrigin="null"!==window.origin?window.origin:window.location.origin;this._appUrlObj=r.urlToObject(window.location.href);this._busy=null;this._rejectOnPersistedPageShow=!1;this._oAuthLocationParams=null;this._gwTokenUrl="/sharing/rest/generateToken";this._agsRest="/rest/services";this._agsPortal=/\/sharing(\/|$)/i;this._agsAdmin=/(https?:\/\/[^/]+\/[^/]+)\/admin\/?(\/.*)?$/i;this._adminSvcs=/\/rest\/admin\/services(\/|$)/i;this._gwDomains=[{regex:/^https?:\/\/www\.arcgis\.com/i,customBaseUrl:"maps.arcgis.com", tokenServiceUrl:"https://www.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/(?:dev|[a-z\d-]+\.mapsdev)\.arcgis\.com/i,customBaseUrl:"mapsdev.arcgis.com",tokenServiceUrl:"https://dev.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/(?:devext|[a-z\d-]+\.mapsdevext)\.arcgis\.com/i,customBaseUrl:"mapsdevext.arcgis.com",tokenServiceUrl:"https://devext.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/(?:qaext|[a-z\d-]+\.mapsqa)\.arcgis\.com/i,customBaseUrl:"mapsqa.arcgis.com", tokenServiceUrl:"https://qaext.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/[a-z\d-]+\.maps\.arcgis\.com/i,customBaseUrl:"maps.arcgis.com",tokenServiceUrl:"https://www.arcgis.com/sharing/rest/generateToken"}];this._legacyFed=[];this._regexSDirUrl=/http.+\/rest\/services\/?/gi;this._regexServerType=/(\/(FeatureServer|GPServer|GeoDataServer|GeocodeServer|GeoenrichmentServer|GeometryServer|GlobeServer|ImageServer|KnowledgeGraphServer|MapServer|MissionServer|MobileServer|NAServer|NetworkDiagramServer|OGCFeatureServer|ParcelFabricServer|RelationalCatalogServer|SceneServer|StreamServer|UtilityNetworkServer|ValidationServer|VectorTileServer|VersionManagementServer|VideoServer)).*/gi; this._gwUser=/http.+\/users\/([^/]+).*/i;this._gwItem=/http.+\/items\/([^/]+).*/i;this._gwGroup=/http.+\/groups\/([^/]+).*/i;this._rePortalTokenSvc=/\/sharing(\/rest)?\/generatetoken/i;this._createDefaultOAuthInfo=!0;this._hasTestedIfAppIsOnPortal=!1;this._getPlatformSelfError=null;this._getOAuthLocationParams();window.addEventListener("pageshow",a=>{this._pageShowHandler(a)})}registerServers(a){const b=this.serverInfos;b?(a=a.filter(c=>!this.findServerInfo(c.server)),this.serverInfos=b.concat(a)): this.serverInfos=a;a.forEach(c=>{c.owningSystemUrl&&this._portals.push(c.owningSystemUrl);c.hasPortal&&this._portals.push(c.server)})}registerOAuthInfos(a){const b=this.oAuthInfos;if(b){for(const c of a){const d=this.findOAuthInfo(c.portalUrl);d&&b.splice(b.indexOf(d),1)}this.oAuthInfos=b.concat(a)}else this.oAuthInfos=a}registerToken(a){a={...a};const b=this._sanitizeUrl(a.server),c=this._isServerRsrc(b);let d=this.findServerInfo(b),e=!0,g;d||(d=new M,d.server=this._getServerInstanceRoot(b),c?d.hasServer= !0:(d.tokenServiceUrl=this._getTokenSvcUrl(b),d.hasPortal=!0),this.registerServers([d]));(g=this._findCredential(b))?(delete a.server,Object.assign(g,a),e=!1):(g=new t.Credential({userId:a.userId,server:d.server??void 0,token:a.token,expires:a.expires,ssl:a.ssl,scope:c?"server":"portal"}),g.resources=[b],this.credentials.push(g));g.emitTokenChange(!1);e||g.refreshServerTokens()}toJSON(){return Q.fixJson({serverInfos:this.serverInfos.map(a=>a.toJSON()),oAuthInfos:this.oAuthInfos.map(a=>a.toJSON()), credentials:this.credentials.map(a=>a.toJSON())})}initialize(a){if(a){"string"===typeof a&&(a=JSON.parse(a));var b=a.serverInfos,c=a.oAuthInfos;a=a.credentials;if(b){const d=[];b.forEach(e=>{e.server&&e.tokenServiceUrl&&d.push(e.declaredClass?e:new M(e))});d.length&&this.registerServers(d)}if(c){const d=[];c.forEach(e=>{e.appId&&d.push(e.declaredClass?e:new T(e))});d.length&&this.registerOAuthInfos(d)}a&&a.forEach(d=>{d.server&&d.token&&d.expires&&d.expires>Date.now()&&(d=d.declaredClass?d:new t.Credential(d), d.emitTokenChange(),this.credentials.push(d))})}}findServerInfo(a){let b;a=this._sanitizeUrl(a);for(const c of this.serverInfos)if(this._hasSameServerInstance(c.server,a)){b=c;break}return b}findOAuthInfo(a){let b;a=this._sanitizeUrl(a);for(const c of this.oAuthInfos)if(this._hasSameServerInstance(c.portalUrl,a)){b=c;break}return b}findCredential(a,b){if(a){a=this._sanitizeUrl(a);var c=this._isServerRsrc(a)?"server":"portal";if(b)for(const e of this.credentials){if(this._hasSameServerInstance(e.server, a)&&b===e.userId&&e.scope===c){var d=e;break}}else for(const e of this.credentials)if(this._hasSameServerInstance(e.server,a)&&-1!==this._getIdenticalSvcIdx(a,e)&&e.scope===c){d=e;break}return d}}getCredential(a,b){let c=!0;if(b){var d=!!b.token;var e=b.error;c=!1!==b.prompt}b={...b};a=this._sanitizeUrl(a);const g=new AbortController,k=C.createResolver();if(b.signal)C.onAbort(b.signal,()=>{g.abort()});C.onAbort(g,()=>{k.reject(new w("identity-manager:user-aborted","ABORTED"))});if(C.isAborted(g))return k.promise; b.signal=g.signal;const p=this._isAdminResource(a);if((d=d?this.findCredential(a):null)&&e&&e.details&&498===e.details.httpStatus)d.destroy();else if(d)return a=new w("identity-manager:not-authorized","You are currently signed in as: '"+d.userId+"'. You do not have access to this resource: "+a,{error:e}),k.reject(a),k.promise;if(e=this._findCredential(a,b))return k.resolve(e),k.promise;let f=this.findServerInfo(a);if(f)!f.hasPortal&&f.server&&f.owningSystemUrl&&this._hasSameServerInstance(f.server, f.owningSystemUrl)&&(f.hasPortal=!0),!f.hasServer&&this._isServerRsrc(a)&&(f._restInfoPms=this._getTokenSvcUrl(a),f.hasServer=!0);else{e=this._getTokenSvcUrl(a);if(!e)return a=new w("identity-manager:unknown-resource","Unknown resource - could not find token service endpoint."),k.reject(a),k.promise;f=new M;f.server=this._getServerInstanceRoot(a);"string"===typeof e?(f.tokenServiceUrl=e,f.hasPortal=!0):(f._restInfoPms=e,f.hasServer=!0);this.registerServers([f])}f.hasPortal&&void 0===f._selfReq&&(c|| r.hasSameOrigin(f.tokenServiceUrl,this._appOrigin)||this._gwDomains.some(h=>h.tokenServiceUrl===f.tokenServiceUrl))&&(f._selfReq={owningTenant:b?.owningTenant,selfDfd:this._getPortalSelf(f.tokenServiceUrl.replace(this._rePortalTokenSvc,"/sharing/rest/portals/self"),a)});return this._enqueue(a,f,b,k,p)}getResourceName(a){return this._isRESTService(a)?a.replace(this._regexSDirUrl,"").replace(this._regexServerType,"")||"":this._gwUser.test(a)&&a.replace(this._gwUser,"$1")||this._gwItem.test(a)&&a.replace(this._gwItem, "$1")||this._gwGroup.test(a)&&a.replace(this._gwGroup,"$1")||""}generateToken(a,b,c){const d=this._rePortalTokenSvc.test(a.tokenServiceUrl),e=new r.Url(this._appOrigin);var g=a.shortLivedTokenValidity;let k,p,f,h,n,l,m;b&&(m=this.tokenValidity||g||this._defaultTokenValidity,m>g&&0 {x=x.data;if(!x?.token)return new w("identity-manager:authentication-failed","Unable to generate token");const q=a.server;G[q]||(G[q]={});b&&(G[q][b.username]=b.password);x.validity=m;return x})}isBusy(){return!!this._busy}async checkSignInStatus(a){return(await this.checkAppAccess(a,"")).credential}checkAppAccess(a,b,c){let d=!1;return this.getCredential(a,{prompt:!1}).then(e=>{let g;const k={f:"json"};if("portal"===e.scope)if(b&&(this._doPortalSignIn(a)||c?.force))g=e.server+"/sharing/rest/oauth2/validateAppAccess", k.client_id=b;else if(e.token)g=e.server+"/sharing/rest";else return{credential:e};else if(e.token)g=e.server+"/rest/services";else return{credential:e};e.token&&(k.token=e.token);return D(g,{query:k,authMode:"anonymous"}).then(p=>{if(!1===p.data.valid)throw new w("identity-manager:not-authorized",`You are currently signed in as: '${e.userId}'.`,p.data);d=!!p.data.viewOnlyUserTypeApp;return{credential:e}}).catch(p=>{if("identity-manager:not-authorized"===p.name)throw p;p=p.details?.httpStatus;if(498=== p)throw e.destroy(),new w("identity-manager:not-authenticated","User is not signed in.");if(400===p)throw new w("identity-manager:invalid-request");return{credential:e}})}).then(e=>({credential:e.credential,viewOnly:d}))}setOAuthResponseHash(a){a&&("#"===a.charAt(0)&&(a=a.substring(1)),this._processOAuthPopupParams(r.queryToObject(a)))}setOAuthRedirectionHandler(a){this._oAuthRedirectFunc=a}setProtocolErrorHandler(a){this._protocolFunc=a}signIn(a,b,c={}){const d=C.createResolver(),e=()=>{p?.remove(); f?.remove();this.dialog?.destroy();this.dialog=p=f=null},g=()=>{e();this._oAuthDfd=null;d.reject(new w("identity-manager:user-aborted","ABORTED"))};if(c.signal)C.onAbort(c.signal,()=>{g()});const k=new R({open:!0,resource:this.getResourceName(a),server:b.server});this.dialog=k;this.emit("dialog-create");let p=k.on("cancel",g),f=k.on("submit",h=>{this.generateToken(b,h,{isAdmin:c.isAdmin,signal:c.signal}).then(n=>{e();n=new t.Credential({userId:h.username,server:b.server??void 0,token:n.token,expires:null!= n.expires?Number(n.expires):null,ssl:!!n.ssl,isAdmin:c.isAdmin,validity:n.validity});d.resolve(n)}).catch(n=>{k.error=n;k.signingIn=!1})});return d.promise}oAuthSignIn(a,b,c,d){const e=this._oAuthDfd=C.createResolver();if(d?.signal)C.onAbort(d.signal,()=>{const l=this._oAuthDfd&&this._oAuthDfd.oAuthWin_;l&&!l.closed?l.close():this.dialog&&h()});e.resUrl_=a;e.sinfo_=b;e.oinfo_=c;let g;const k=c._oAuthCred;if(k.storage&&("authorization-code"===c.flowType||"auto"===c.flowType&&8.4<=b.currentVersion)){let l= crypto.getRandomValues(new Uint8Array(32));g=r.base64UrlEncode(l);k.codeVerifier=g;l=crypto.getRandomValues(new Uint8Array(32));k.stateUID=r.base64UrlEncode(l);k.save()||(k.codeVerifier=g=null)}else k.codeVerifier=null;this._getCodeChallenge(g).then(l=>{var m=!d||!1!==d.oAuthPopupConfirmation;c.popup&&m?(this.dialog=m=new R({oAuthPrompt:!0,server:b.server,open:!0}),this.emit("dialog-create"),p=m.on("cancel",h),f=m.on("submit",()=>{n();this._doOAuthSignIn(a,b,c,l)})):this._doOAuthSignIn(a,b,c,l)}); let p,f;const h=()=>{n();this._oAuthDfd=null;e.reject(new w("identity-manager:user-aborted","ABORTED"))},n=()=>{p?.remove();f?.remove();this.dialog?.destroy();this.dialog=null};return e.promise}destroyCredentials(){this.credentials&&this.credentials.slice().forEach(a=>{a.destroy()});this.emit("credentials-destroy")}enablePostMessageAuth(a="https://www.arcgis.com/sharing/rest"){this._postMessageAuthHandle&&this._postMessageAuthHandle.remove();this._postMessageAuthHandle=L.on(window,"message",b=>{if((b.origin=== this._appOrigin||b.origin.endsWith(".arcgis.com"))&&"arcgis:auth:requestCredential"===b.data?.type){const c=b.source;this.getCredential(a).then(d=>{c.postMessage({type:"arcgis:auth:credential",credential:{expires:d.expires,server:d.server,ssl:d.ssl,token:d.token,userId:d.userId}},b.origin)}).catch(d=>{c.postMessage({type:"arcgis:auth:error",error:{name:d.name,message:d.message}},b.origin)})}})}disablePostMessageAuth(){this._postMessageAuthHandle&&(this._postMessageAuthHandle.remove(),this._postMessageAuthHandle= null)}_getOAuthLocationParams(){var a=window.location.hash;if(a){"#"===a.charAt(0)&&(a=a.substring(1));a=r.queryToObject(a);var b=!1;if(a.access_token&&a.expires_in&&a.state&&a.hasOwnProperty("username"))try{a.state=JSON.parse(a.state),a.state.portalUrl&&(this._oAuthLocationParams=a,b=!0)}catch{}else if(a.error&&a.error_description&&(console.log("IdentityManager OAuth Error: ",a.error," - ",a.error_description),"access_denied"===a.error&&(b=!0,a.state)))try{a.state=JSON.parse(a.state)}catch{}b&&(window.location.hash= a.state?.hash||"")}if(a=window.location.search){"?"===a.charAt(0)&&(a=a.substring(1));a=r.queryToObject(a);b=!1;if(a.code&&a.state)try{a.state=JSON.parse(a.state),a.state.portalUrl&&a.state.uid&&(this._oAuthLocationParams=a,b=!0)}catch{}else if(a.error&&a.error_description&&(console.log("IdentityManager OAuth Error: ",a.error," - ",a.error_description),"access_denied"===a.error&&(b=!0,a.state)))try{a.state=JSON.parse(a.state)}catch{}if(b){const c={...a};"code error error_description message_code persist state".split(" ").forEach(d=> {delete c[d]});b=r.objectToQuery(c);window.history.replaceState(window.history.state,"",window.location.pathname+(b?`?${b}`:"")+(a.state?.hash||""))}}}_getOAuthToken(a,b,c,d,e){a=a.replace(/^http:/i,"https:");return D(`${a}/sharing/rest/oauth2/token`,{authMode:"anonymous",method:"post",query:d&&e?{grant_type:"authorization_code",code:b,redirect_uri:d,client_id:c,code_verifier:e}:{grant_type:"refresh_token",refresh_token:b,client_id:c}}).then(g=>g.data)}async _getCodeChallenge(a){return a&&globalThis.isSecureContext? (a=(new TextEncoder).encode(a),a=await crypto.subtle.digest("SHA-256",a),r.base64UrlEncode(new Uint8Array(a))):null}_pageShowHandler(a){a.persisted&&this.isBusy()&&this._rejectOnPersistedPageShow&&(a=new w("identity-manager:user-aborted","ABORTED"),this._errbackFunc(a))}_findCredential(a,b){let c=-1,d,e,g;const k=b?.token;b=b?.resource;const p=this._isServerRsrc(a)?"server":"portal",f=this.credentials.filter(h=>this._hasSameServerInstance(h.server,a)&&h.scope===p);a=b||a;if(f.length)if(1===f.length)if(b= f[0],e=this.findServerInfo(b.server),g=(d=e?.owningSystemUrl)?this.findCredential(d,b.userId):void 0,c=this._getIdenticalSvcIdx(a,b),k)-1!==c&&(b.resources.splice(c,1),this._removeResource(a,g));else return-1===c&&b.resources.push(a),this._addResource(a,g),b;else{let h,n;f.some(l=>{n=this._getIdenticalSvcIdx(a,l);return-1!==n?(h=l,e=this.findServerInfo(h.server),g=(d=e?.owningSystemUrl)?this.findCredential(d,h.userId):void 0,c=n,!0):!1});if(k)h&&(h.resources.splice(c,1),this._removeResource(a,g)); else if(h)return this._addResource(a,g),h}}_findOAuthInfo(a){let b=this.findOAuthInfo(a);if(!b)for(const c of this.oAuthInfos)if(this._isIdProvider(c.portalUrl,a)){b=c;break}return b}_addResource(a,b){b&&-1===this._getIdenticalSvcIdx(a,b)&&b.resources.push(a)}_removeResource(a,b){let c=-1;b&&(c=this._getIdenticalSvcIdx(a,b),-1d.regex.test(b.uri));!c&&a&&(c=this._hasSameServerInstance(this._getServerInstanceRoot(a.restBaseUrl),b.uri));c||K.portalUrl&&(c=r.hasSameOrigin(b,K.portalUrl,!0));c||=this._portals.some(d=>this._hasSameServerInstance(d,b.uri));return c=c||this._agsPortal.test(b.path)}_isIdProvider(a,b){let c=-1,d=-1;this._gwDomains.forEach((g,k)=>{-1===c&&g.regex.test(a)&&(c=k);-1===d&&g.regex.test(b)&& (d=k)});let e=!1;if(-1d.data);return{adminUrl:c,promise:b}}if(this._isPortalDomain(a)){let d="";this._gwDomains.some(e=>{e.regex.test(a)&&(d=e.tokenServiceUrl);return!!d});d||this._portals.some(e=>{this._hasSameServerInstance(e,a)&&(d=e+this._gwTokenUrl);return!!d});d||(c=a.toLowerCase().indexOf("/sharing"),-1!==c&&(d=a.substring(0, c)+this._gwTokenUrl));d||=this._getOrigin(a)+this._gwTokenUrl;d&&(c=(new r.Url(a)).port,/^http:\/\//i.test(a)&&"7080"===c&&(d=d.replace(/:7080/i,":7443")),d=d.replace(/http:/i,"https:"));return d}}_processOAuthResponseParams(a,b,c){const d=b._oAuthCred;if(a.code){var e=d.codeVerifier;d.codeVerifier=null;d.stateUID=null;d.save();return this._getOAuthToken(c.server,a.code,b.appId,this._getRedirectURI(b,!0),e).then(g=>{const k=new t.Credential({userId:g.username,server:c.server??void 0,token:g.access_token, expires:Date.now()+1E3*g.expires_in,ssl:g.ssl,oAuthState:a.state,_oAuthCred:d});b.userId=k.userId;d.storage=g.persist?H:I;d.refreshToken=g.refresh_token;d.token=null;d.expires=g.refresh_token_expires_in?Date.now()+1E3*g.refresh_token_expires_in:null;d.userId=k.userId;d.ssl=k.ssl;d.save();return k})}e=new t.Credential({userId:a.username,server:c.server??void 0,token:a.access_token,expires:Date.now()+1E3*Number(a.expires_in),ssl:"true"===a.ssl,oAuthState:a.state,_oAuthCred:d});b.userId=e.userId;d.storage= a.persist?H:I;d.refreshToken=null;d.token=e.token;d.expires=e.expires;d.userId=e.userId;d.ssl=e.ssl;d.save();return Promise.resolve(e)}_processOAuthPopupParams(a){const b=this._oAuthDfd;this._oAuthDfd=null;if(b)if(clearInterval(this._oAuthIntervalId),this._oAuthOnPopupHandle?.remove(),a.error){const c="access_denied"===a.error;a=new w(c?"identity-manager:user-aborted":"identity-manager:authentication-failed",c?"ABORTED":"OAuth: "+a.error+" - "+a.error_description);b.reject(a)}else this._processOAuthResponseParams(a, b.oinfo_,b.sinfo_).then(c=>{b.resolve(c)}).catch(c=>{b.reject(c)})}_setOAuthResponseQueryString(a){a&&("?"===a.charAt(0)&&(a=a.substring(1)),this._processOAuthPopupParams(r.queryToObject(a)))}async _exchangeToken(a,b,c){return(await D(`${a}/sharing/rest/oauth2/exchangeToken`,{authMode:"anonymous",method:"post",query:{f:"json",client_id:b,token:c}})).data.token}async _getPlatformSelf(a,b){if(this._getPlatformSelfError&&1E3>Date.now()-this._getPlatformSelfError[1])throw this._getPlatformSelfError[0]; a=a.replace(/^http:/i,"https:");try{const c=await D(`${a}/sharing/rest/oauth2/platformSelf`,{authMode:"anonymous",headers:{"X-Esri-Auth-Client-Id":b,"X-Esri-Auth-Redirect-Uri":window.location.href.replace(/#.*$/,"")},method:"post",query:{f:"json",expiration:30},withCredentials:!0});this._getPlatformSelfError=null;return c.data}catch(c){throw"OAUTH_0066"===c.details?.messageCode&&(this._getPlatformSelfError=[c,Date.now()]),c;}}_getPortalSelf(a,b){let c;this._gwDomains.some(d=>{d.regex.test(a)&&(c= d.customBaseUrl);return!!c});if(c)return Promise.resolve({allSSL:!0,currentVersion:"8.4",customBaseUrl:c,portalMode:"multitenant",supportsOAuth:!0});this._appOrigin.startsWith("https:")?a=a.replace(/^http:/i,"https:").replace(/:7080/i,":7443"):/^http:/i.test(b)&&(a=a.replace(/^https:/i,"http:").replace(/:7443/i,":7080"));return D(a,{query:{f:"json"},authMode:"anonymous",withCredentials:!0}).then(d=>d.data)}_doPortalSignIn(a){const b=this._portalConfig,c=window.location.href,d=this.findServerInfo(a); return(b||this._isPortalDomain(c))&&(d?d.hasPortal||d.owningSystemUrl&&this._isPortalDomain(d.owningSystemUrl):this._isPortalDomain(a))&&(this._isIdProvider(c,a)||b&&(this._hasSameServerInstance(this._getServerInstanceRoot(b.restBaseUrl),a)||this._isIdProvider(b.restBaseUrl,a))||r.hasSameOrigin(c,a,!0))?!0:!1}_checkProtocol(a,b,c,d){let e=!0;d=d?b.adminTokenServiceUrl:b.tokenServiceUrl;d.trim().toLowerCase().startsWith("https:")&&!this._appOrigin.startsWith("https:")&&r.getProxyRule(d)&&(e=this._protocolFunc? !!this._protocolFunc({resourceUrl:a,serverInfo:b}):!1,e||(a=new w("identity-manager:aborted","Aborted the Sign-In process to avoid sending password over insecure connection."),c(a)));return e}_enqueue(a,b,c,d,e,g){d||=C.createResolver();d.resUrl_=a;d.sinfo_=b;d.options_=c;d.admin_=e;d.refresh_=g;this._busy?this._hasSameServerInstance(this._getServerInstanceRoot(a),this._busy.resUrl_)?(this._oAuthDfd&&this._oAuthDfd.oAuthWin_&&this._oAuthDfd.oAuthWin_.focus(),this._soReqs.push(d)):this._xoReqs.push(d): this._doSignIn(d);return d.promise}_doSignIn(a){this._busy=a;this._rejectOnPersistedPageShow=!1;const b=f=>{var h=a.options_?.resource;const n=a.resUrl_,l=a.refresh_;let m=!1;this.credentials.includes(f)||(l&&this.credentials.includes(l)?(l.userId=f.userId,l.token=f.token,l.expires=f.expires,l.validity=f.validity,l.ssl=f.ssl,l.creationTime=f.creationTime,m=!0,f=l):this.credentials.push(f));f.resources||(f.resources=[]);f.resources.includes(h||n)||f.resources.push(h||n);f.scope=this._isServerRsrc(n)? "server":"portal";f.emitTokenChange();h=this._soReqs;const x={};this._soReqs=[];h.forEach(q=>{if(!this._isIdenticalService(n,q.resUrl_)){const v=this._getSuffix(q.resUrl_);x[v]||(x[v]=!0,f.resources.push(q.resUrl_))}});a.resolve(f);h.forEach(q=>{this._hasSameServerInstance(this._getServerInstanceRoot(n),q.resUrl_)?q.resolve(f):this._soReqs.push(q)});this._busy=a.resUrl_=a.sinfo_=a.refresh_=null;m||this.emit("credential-create",{credential:f});this._soReqs.length?this._doSignIn(this._soReqs.shift()): this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},c=f=>{a.reject(f);this._busy=a.resUrl_=a.sinfo_=a.refresh_=null;this._soReqs.length?this._doSignIn(this._soReqs.shift()):this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},d=(f,h,n,l)=>{const m=a.sinfo_,x=!a.options_||!1!==a.options_.prompt,q=m.hasPortal&&this._findOAuthInfo(a.resUrl_);let v,J;if(f)b(new t.Credential({userId:f,server:m.server??void 0,token:n??void 0,expires:null!=l?Number(l):null,ssl:!!h}));else if(window!==window.parent&& this._appUrlObj.query?.["arcgis-auth-origin"]&&this._appUrlObj.query?.["arcgis-auth-portal"]&&this._hasSameServerInstance(this._getServerInstanceRoot(this._appUrlObj.query["arcgis-auth-portal"]),a.resUrl_)){window.parent.postMessage({type:"arcgis:auth:requestCredential"},this._appUrlObj.query["arcgis-auth-origin"]);const u=L.on(window,"message",y=>{y.source===window.parent&&y.data&&("arcgis:auth:credential"===y.data.type?(u.remove(),y.data.credential.expires{u.remove()})}else if(q){let u=q._oAuthCred;u||(f=new S(q,H),h=new S(q,I),f.isValid()&&h.isValid()?f.expires>h.expires?(u=f,h.destroy()):(u=h,f.destroy()):u=f.isValid()? f:h,q._oAuthCred=u);if(u.isValid()){v=new t.Credential({userId:u.userId??void 0,server:m.server??void 0,token:u.token??void 0,expires:u.expires,ssl:u.ssl??void 0,_oAuthCred:u});const y=q.appId!==u.appId&&this._doPortalSignIn(a.resUrl_);y||u.refreshToken?(a._pendingDfd=u.refreshToken?this._getOAuthToken(m.server,u.refreshToken,u.appId).then(z=>{v.expires=Date.now()+1E3*z.expires_in;v.token=z.access_token;return v}):Promise.resolve(v),a._pendingDfd.then(z=>y?this._exchangeToken(z.server,q.appId,z.token).then(X=> {z.token=X;return z}).catch(()=>z):z).then(z=>{b(z)}).catch(()=>{u?.destroy();d()})):b(v)}else if(this._oAuthLocationParams&&this._hasSameServerInstance(q.portalUrl,this._oAuthLocationParams.state.portalUrl)&&(this._oAuthLocationParams.access_token||this._oAuthLocationParams.code&&this._oAuthLocationParams.state.uid===u.stateUID&&u.codeVerifier))f=this._oAuthLocationParams,this._oAuthLocationParams=null,a._pendingDfd=this._processOAuthResponseParams(f,q,m).then(y=>{b(y)}).catch(c);else{const y=()=> {x?a._pendingDfd=this.oAuthSignIn(a.resUrl_,m,q,a.options_).then(b,c):(J=new w("identity-manager:not-authenticated","User is not signed in."),c(J))};this._doPortalSignIn(a.resUrl_)?a._pendingDfd=this._getPlatformSelf(m.server,q.appId).then(z=>{r.hasSameOrigin(z.portalUrl,this._appOrigin,!0)?(v=new t.Credential({userId:z.username,server:m.server??void 0,expires:Date.now()+1E3*z.expires_in,token:z.token}),b(v)):y()}).catch(y):y()}}else x?this._checkProtocol(a.resUrl_,m,c,a.admin_)&&(f=a.options_,a.admin_&& (f=f||{},f.isAdmin=!0),a._pendingDfd=this.signIn(a.resUrl_,m,f).then(b,c)):(J=new w("identity-manager:not-authenticated","User is not signed in."),c(J))},e=()=>{const f=a.sinfo_;var h=f.owningSystemUrl;const n=a.options_;let l,m,x,q;n&&(l=n.token,m=n.error,x=n.prompt);q=this._findCredential(h,{token:l,resource:a.resUrl_});if(!q)for(const v of this.credentials)if(this._isIdProvider(h,v.server)){q=v;break}q?(h=this.findCredential(a.resUrl_,q.userId))?b(h):O(f,this._legacyFed)?(h=q.toJSON(),h.server= f.server,h.resources=null,b(new t.Credential(h))):(a._pendingDfd=this.generateToken(this.findServerInfo(q.server),null,{serverUrl:a.resUrl_,token:q.token,signal:a.options_.signal,ssl:q.ssl})).then(v=>{b(new t.Credential({userId:q?.userId,server:f.server??void 0,token:v.token,expires:null!=v.expires?Number(v.expires):null,ssl:!!v.ssl,isAdmin:a.admin_,validity:v.validity}))},c):(this._busy=null,l&&(a.options_.token=null),(a._pendingDfd=this.getCredential(h.replace(/\/?$/,"/sharing"),{resource:a.resUrl_, owningTenant:f.owningTenant,signal:a.options_.signal,token:l,error:m,prompt:x})).then(()=>{this._enqueue(a.resUrl_,a.sinfo_,a.options_,a,a.admin_)},v=>{a.resUrl_=a.sinfo_=a.refresh_=null;a.reject(v)}))};this._errbackFunc=c;const g=a.sinfo_.owningSystemUrl,k=this._isServerRsrc(a.resUrl_),p=a.sinfo_._restInfoPms;p?p.promise.then(f=>{const h=a.sinfo_;h._restInfoPms&&(h.adminTokenServiceUrl=h._restInfoPms.adminUrl,h._restInfoPms=null,h.tokenServiceUrl=(F.getDeepValue("authInfo.tokenServicesUrl",f)||F.getDeepValue("authInfo.tokenServiceUrl", f)||F.getDeepValue("tokenServiceUrl",f))??null,h.shortLivedTokenValidity=F.getDeepValue("authInfo.shortLivedTokenValidity",f)??null,h.currentVersion=f.currentVersion,h.owningTenant=f.owningTenant,(f=h.owningSystemUrl=f.owningSystemUrl)&&this._portals.push(f));k&&h.owningSystemUrl?e():d()},()=>{a.sinfo_._restInfoPms=null;const f=new w("identity-manager:server-identification-failed","Unknown resource - could not find token service endpoint.");c(f)}):k&&g?e():a.sinfo_._selfReq?a.sinfo_._selfReq.selfDfd.then(f=> {const h={};let n,l,m,x;f&&(n=f.user?.username,h.username=n,h.allSSL=f.allSSL,l=f.supportsOAuth,x=parseFloat(f.currentVersion),"multitenant"===f.portalMode&&(m=f.customBaseUrl),a.sinfo_.currentVersion=x);a.sinfo_.webTierAuth=!!n;return n&&this.normalizeWebTierAuth?this.generateToken(a.sinfo_,null,{ssl:h.allSSL}).catch(()=>null).then(q=>{h.portalToken=q?.token;h.tokenExpiration=q?.expires;return h}):!n&&l&&4.4<=x&&!this._findOAuthInfo(a.resUrl_)?this._generateOAuthInfo({portalUrl:a.sinfo_.server,customBaseUrl:m, owningTenant:a.sinfo_._selfReq.owningTenant}).catch(()=>null).then(()=>h):h}).catch(()=>null).then(f=>{a.sinfo_._selfReq=null;f?d(f.username,f.allSSL,f.portalToken,f.tokenExpiration):d()}):d()}_generateOAuthInfo(a){let b=null,c=a.portalUrl;const d=a.customBaseUrl,e=a.owningTenant;if(a=!this._defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal){b=window.location.href;let g=b.indexOf("?");-1{this._defaultOAuthInfo=new T({appId:"arcgisonline",popupCallbackUrl:b+"/home/oauth-callback.html"})})):a=Promise.resolve();return a.then(()=>{if(this._defaultOAuthInfo)return c=c.replace(/^http:/i,"https:"),D(c+"/sharing/rest/oauth2/validateRedirectUri",{query:{accountId:e,client_id:this._defaultOAuthInfo.appId,redirect_uri:r.makeAbsolute(this._defaultOAuthInfo.popupCallbackUrl),f:"json"}}).then(g=>{if(g.data.valid){const k= this._defaultOAuthInfo.clone();k.portalUrl=g.data.urlKey&&d?"https://"+g.data.urlKey.toLowerCase()+"."+d:c;k.popup=window!==window.top||!(r.hasSameOrigin(c,this._appOrigin)||this._gwDomains.some(p=>p.regex.test(c)&&p.regex.test(this._appOrigin)));this.oAuthInfos.push(k)}})})}_doOAuthSignIn(a,b,c,d){var e=c._oAuthCred,g={portalUrl:c.portalUrl};!c.popup&&c.preserveUrlHash&&window.location.hash&&(g.hash=window.location.hash);e.stateUID&&(g.uid=e.stateUID);g={client_id:c.appId,response_type:e.codeVerifier? "code":"token",state:JSON.stringify(g),expiration:c.expiration,locale:c.locale,redirect_uri:this._getRedirectURI(c,!!e.codeVerifier)};c.forceLogin&&(g.force_login=!0);c.forceUserId&&c.userId&&(g.prepopulatedusername=c.userId);!c.popup&&this._doPortalSignIn(a)&&(g.redirectToUserOrgUrl=!0);e.codeVerifier&&(g.code_challenge=d||e.codeVerifier,g.code_challenge_method=d?"S256":"plain");d=c.portalUrl.replace(/^http:/i,"https:")+"/sharing/oauth2/authorize";e=d+"?"+r.objectToQuery(g);if(c.popup){const k=window.open(e, "esriJSAPIOAuth",c.popupWindowFeatures);k?(k.focus(),this._oAuthDfd.oAuthWin_=k,this._oAuthIntervalId=setInterval(()=>{if(k.closed){clearInterval(this._oAuthIntervalId);this._oAuthOnPopupHandle.remove();const p=this._oAuthDfd;if(p){const f=new w("identity-manager:user-aborted","ABORTED");p.reject(f)}}},500),this._oAuthOnPopupHandle=L.on(window,["arcgis:auth:hash","arcgis:auth:location:search"],p=>{"arcgis:auth:hash"===p.type?this.setOAuthResponseHash(p.detail):this._setOAuthResponseQueryString(p.detail)})): (a=new w("identity-manager:popup-blocked","ABORTED"),this._oAuthDfd.reject(a))}else this._rejectOnPersistedPageShow=!0,this._oAuthRedirectFunc?this._oAuthRedirectFunc({authorizeParams:g,authorizeUrl:d,resourceUrl:a,serverInfo:b,oAuthInfo:c}):window.location.href=e}_getRedirectURI(a,b){const c=window.location.href.replace(/#.*$/,"");if(a.popup)return r.makeAbsolute(a.popupCallbackUrl);if(b){const d=r.urlToObject(c);d.query&&"code error error_description message_code persist state".split(" ").forEach(e=> {delete d.query[e]});return r.addQueryParameters(d.path,d.query)}return c}}V.prototype.declaredClass="esri.identity.IdentityManagerBase";t.Credential=class extends P.EventedAccessor{constructor(a){super(a);this._oAuthCred=null;this.tokenRefreshBuffer=2;a?._oAuthCred&&(this._oAuthCred=a._oAuthCred)}initialize(){this.resources=this.resources||[];null==this.creationTime&&(this.creationTime=Date.now())}refreshToken(){const a=E.id,b=a.findServerInfo(this.server),c=b?.owningSystemUrl,d=!!c&&"server"=== this.scope,e=d&&O(b,a._legacyFed);var g=b.webTierAuth;const k=g&&a.normalizeWebTierAuth,p=G[this.server]?.[this.userId];let f=this.resources&&this.resources[0],h=d?a.findServerInfo(c):null,n={username:this.userId,password:p},l;if(!g||k)if(d&&!h&&a.serverInfos.some(m=>{a._isIdProvider(c,m.server)&&(h=m);return!!h}),g=h?a.findCredential(h.server,this.userId):null,!d||g)if(e)g?.refreshToken();else{if(d)l={serverUrl:f,token:g?.token,ssl:g?.ssl};else if(k)n=null,l={ssl:this.ssl};else if(p)this.isAdmin&& (l={isAdmin:!0});else{let m;f&&(f=a._sanitizeUrl(f),this._enqueued=1,m=a._enqueue(f,b,null,null,this.isAdmin,this),m.then(()=>{this._enqueued=0;this.refreshServerTokens()}).catch(()=>{this._enqueued=0}));return m}return a.generateToken(d?h:b,d?null:n,l).then(m=>{this.token=m.token;this.expires=null!=m.expires?Number(m.expires):null;this.creationTime=Date.now();this.validity=m.validity;this.emitTokenChange();this.refreshServerTokens()}).catch(()=>{})}}refreshServerTokens(){if("portal"===this.scope){const a= E.id;a.credentials.forEach(b=>{const c=a.findServerInfo(b.server),d=c?.owningSystemUrl;b!==this&&b.userId===this.userId&&d&&"server"===b.scope&&(a._hasSameServerInstance(this.server,d)||a._isIdProvider(d,this.server))&&(O(c,a._legacyFed)?(b.token=this.token,b.expires=this.expires,b.creationTime=this.creationTime,b.validity=this.validity,b.emitTokenChange()):b.refreshToken())})}}emitTokenChange(a){clearTimeout(this._refreshTimer);const b=E.id,c=(this.server?b.findServerInfo(this.server):null)?.owningSystemUrl, d=c?b.findServerInfo(c):null;!1===a||c&&"portal"!==this.scope&&(!d?.webTierAuth||b.normalizeWebTierAuth)||null==this.expires&&null==this.validity||this._startRefreshTimer();this.emit("token-change")}destroy(){this.userId=this.server=this.token=this.expires=this.validity=this.resources=this.creationTime=null;this._oAuthCred&&(this._oAuthCred.destroy(),this._oAuthCred=null);const a=E.id,b=a.credentials.indexOf(this);-1c?c=0:c>b&&(c=b);this._refreshTimer=setTimeout(this.refreshToken.bind(this), c>a?c-a:c)}};A.__decorate([B.property()],t.Credential.prototype,"creationTime",void 0);A.__decorate([B.property()],t.Credential.prototype,"expires",void 0);A.__decorate([B.property()],t.Credential.prototype,"isAdmin",void 0);A.__decorate([B.property()],t.Credential.prototype,"oAuthState",void 0);A.__decorate([B.property()],t.Credential.prototype,"resources",void 0);A.__decorate([B.property()],t.Credential.prototype,"scope",void 0);A.__decorate([B.property()],t.Credential.prototype,"server",void 0); A.__decorate([B.property()],t.Credential.prototype,"ssl",void 0);A.__decorate([B.property()],t.Credential.prototype,"token",void 0);A.__decorate([B.property()],t.Credential.prototype,"tokenRefreshBuffer",void 0);A.__decorate([B.property()],t.Credential.prototype,"userId",void 0);A.__decorate([B.property()],t.Credential.prototype,"validity",void 0);t.Credential=A.__decorate([W.subclass("esri.identity.Credential")],t.Credential);t.IdentityManagerBase=V;Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});