text: import"./p-476cf7c4.js";import{N as t,D as e,E as i,K as s,P as n,L as r,Q as o,M as h,R as a,S as l,T as u,V as c,W as d,m as f,X as p,$ as v,Y as m,Z as w,_ as g,a0 as y,a1 as b,a2 as k,A as S,a3 as I,a4 as _,U as A,a5 as T,a6 as U,a7 as O,a8 as x,a9 as j}from"./p-ab028778.js";import{o as D,e as N,H as R,r as C,u as E,a as P}from"./p-ddbd9c9c.js";import"./p-73b795c3.js";import"./p-e07a8dfe.js";function F(e,i,s={}){let n=t(s.expires);if("number"==typeof n){const t=new Date;t.setTime(t.getTime()+24*n*60*60*1e3),n=s.expires=t}"string"!=typeof n&&(s.expires=n.toUTCString());let r=e+"="+encodeURIComponent(i);for(const t in s){r+="; "+t;const e=s[t];!0!==e&&(r+="="+e)}document.cookie=r}const q="esri-identity-form__group",$="esri-identity-form__label",B="esri-input",M="esri-button";let z=class extends R{constructor(t,e){super(t,e),this._usernameInputNode=null,this._passwordInputNode=null,this.messages=null,this.signingIn=!1,this.server=null,this.resource=null,this.error=null,this.oAuthPrompt=!1}render(){const{error:t,server:e,resource:i,signingIn:s,oAuthPrompt:r,messages:o}=this,h=C("div",{class:q},n(r?o.oAuthInfo:o.info,{server:/\.arcgis\.com/i.test(e)?"ArcGIS Online":e,resource:`(${i||o.lblItem})`})),a=r?null:C("div",{class:q},C("label",{class:$},o.lblUser,C("input",{value:"",required:!0,autocomplete:"off",spellcheck:!1,type:"text",bind:this,afterCreate:E,"data-node-ref":"_usernameInputNode",class:B}))),l=r?null:C("div",{class:q},C("label",{class:$},o.lblPwd,C("input",{value:"",required:!0,type:"password",bind:this,afterCreate:E,"data-node-ref":"_passwordInputNode",class:B}))),u=C("div",{class:this.classes(q,"esri-identity-form__footer")},C("input",{type:"submit",disabled:!!s,value:s?o.lblSigning:o.lblOk,class:M}),C("input",{type:"button",value:o.lblCancel,bind:this,onclick:this._cancel,class:this.classes(M,"esri-button--secondary")})),c=t?C("div",null,t.details&&t.details.httpStatus?o.invalidUser:o.noAuthService):null;return C("form",{class:"esri-identity-form",bind:this,onsubmit:this._submit},h,c,a,l,u)}_cancel(){this._set("signingIn",!1),this._usernameInputNode&&(this._usernameInputNode.value=""),this._passwordInputNode&&(this._passwordInputNode.value=""),this.emit("cancel")}_submit(t){t.preventDefault(),this._set("signingIn",!0),this.emit("submit",this.oAuthPrompt?{}:{username:this._usernameInputNode&&this._usernameInputNode.value,password:this._passwordInputNode&&this._passwordInputNode.value})}};e([i(),D(),N("esri/identity/t9n/identity")],z.prototype,"messages",void 0),e([i(),D()],z.prototype,"signingIn",void 0),e([i(),D()],z.prototype,"server",void 0),e([i(),D()],z.prototype,"resource",void 0),e([i(),D()],z.prototype,"error",void 0),e([i(),D()],z.prototype,"oAuthPrompt",void 0),z=e([s("esri.identity.IdentityForm")],z);var J,L=z,H=["input","select","textarea","a[href]","button","[tabindex]","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable="false"])',"details>summary:first-of-type","details"],V=H.join(","),G="undefined"==typeof Element?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Y=function(t){var e=parseInt(t.getAttribute("tabindex"),10);return isNaN(e)?function(t){return"true"===t.contentEditable}(t)?0:"AUDIO"!==t.nodeName&&"VIDEO"!==t.nodeName&&"DETAILS"!==t.nodeName||null!==t.getAttribute("tabindex")?t.tabIndex:0:e},W=function(t,e){return t.tabIndex===e.tabIndex?t.documentOrder-e.documentOrder:t.tabIndex-e.tabIndex},X=function(t){return"INPUT"===t.tagName},K=function(t){return!(t.disabled||function(t){return X(t)&&"hidden"===t.type}(t)||function(t){if("hidden"===getComputedStyle(t).visibility)return!0;var e=G.call(t,"details>summary:first-of-type");if(G.call(e?t.parentElement:t,"details:not([open]) *"))return!0;for(;t;){if("none"===getComputedStyle(t).display)return!0;t=t.parentElement}return!1}(t)||function(t){return"DETAILS"===t.tagName&&Array.prototype.slice.apply(t.children).some((function(t){return"SUMMARY"===t.tagName}))}(t))},Q=function(t){return!(!K(t)||function(t){return function(t){return X(t)&&"radio"===t.type}(t)&&!function(t){if(!t.name)return!0;var e,i=t.form||t.ownerDocument,s=function(t){return i.querySelectorAll('input[type="radio"][name="'+t+'"]')};if("undefined"!=typeof window&&void 0!==window.CSS&&"function"==typeof window.CSS.escape)e=s(window.CSS.escape(t.name));else try{e=s(t.name)}catch(t){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",t.message),!1}var n=function(t,e){for(var i=0;i<t.length;i++)if(t[i].checked&&t[i].form===e)return t[i]}(e,t.form);return!n||n===t}(t)}(t)||Y(t)<0)},Z=H.concat("iframe").join(","),tt=function(t){if(!t)throw new Error("No node provided");return!1!==G.call(t,Z)&&K(t)};
  /*!
  * tabbable 5.1.5
  * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
  */
  /*!
  * focus-trap 6.2.3
  * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
  */
  function et(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function it(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,s)}return i}var st,nt=(st=[],{activateTrap:function(t){if(st.length>0){var e=st[st.length-1];e!==t&&e.pause()}var i=st.indexOf(t);-1===i||st.splice(i,1),st.push(t)},deactivateTrap:function(t){var e=st.indexOf(t);-1!==e&&st.splice(e,1),st.length>0&&st[st.length-1].unpause()}}),rt=function(t){return setTimeout(t,0)},ot=function(t,e){var i=-1;return t.every((function(t,s){return!e(t)||(i=s,!1)})),i},ht=function(t,e){var i,s=document,n=function(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?it(Object(i),!0).forEach((function(e){et(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):it(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0},e),r={containers:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1},o=function(t){return r.containers.some((function(e){return e.contains(t)}))},h=function(t){var e=n[t];if(!e)return null;var i=e;if("string"==typeof e&&!(i=s.querySelector(e)))throw new Error("`".concat(t,"` refers to no known node"));if("function"==typeof e&&!(i=e()))throw new Error("`".concat(t,"` did not return a node"));return i},a=function(){var t;if(null!==h("initialFocus"))t=h("initialFocus");else if(o(s.activeElement))t=s.activeElement;else{var e=r.tabbableGroups[0];t=e&&e.firstTabbableNode||h("fallbackFocus")}if(!t)throw new Error("Your focus-trap needs to have at least one focusable element");return t},l=function(){if(r.tabbableGroups=r.containers.map((function(t){var e,i,s,n=(i=[],s=[],function(t,e,i){var s=Array.prototype.slice.apply(t.querySelectorAll(V));return e&&G.call(t,V)&&s.unshift(t),s.filter(i)}(t,(e=e||{}).includeContainer,Q).forEach((function(t,e){var n=Y(t);0===n?i.push(t):s.push({documentOrder:e,tabIndex:n,node:t})})),s.sort(W).map((function(t){return t.node})).concat(i));if(n.length>0)return{firstTabbableNode:n[0],lastTabbableNode:n[n.length-1]}})).filter((function(t){return!!t})),r.tabbableGroups.length<=0&&!h("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times")},u=function t(e){e!==s.activeElement&&(e&&e.focus?(e.focus({preventScroll:!!n.preventScroll}),r.mostRecentlyFocusedNode=e,function(t){return t.tagName&&"input"===t.tagName.toLowerCase()&&"function"==typeof t.select}(e)&&e.select()):t(a()))},c=function(t){o(t.target)||(n.clickOutsideDeactivates?i.deactivate({returnFocus:n.returnFocusOnDeactivate&&!tt(t.target)}):n.allowOutsideClick&&("boolean"==typeof n.allowOutsideClick?n.allowOutsideClick:n.allowOutsideClick(t))||t.preventDefault())},d=function(t){var e=o(t.target);e||t.target instanceof Document?e&&(r.mostRecentlyFocusedNode=t.target):(t.stopImmediatePropagation(),u(r.mostRecentlyFocusedNode||a()))},f=function(t){if(!1!==n.escapeDeactivates&&function(t){return"Escape"===t.key||"Esc"===t.key||27===t.keyCode}(t))return t.preventDefault(),void i.deactivate();(function(t){return"Tab"===t.key||9===t.keyCode})(t)&&function(t){l();var e=null;if(r.tabbableGroups.length>0)if(t.shiftKey){var i=ot(r.tabbableGroups,(function(e){return t.target===e.firstTabbableNode}));i>=0&&(e=r.tabbableGroups[0===i?r.tabbableGroups.length-1:i-1].lastTabbableNode)}else{var s=ot(r.tabbableGroups,(function(e){return t.target===e.lastTabbableNode}));s>=0&&(e=r.tabbableGroups[s===r.tabbableGroups.length-1?0:s+1].firstTabbableNode)}else e=h("fallbackFocus");e&&(t.preventDefault(),u(e))}(t)},p=function(t){n.clickOutsideDeactivates||o(t.target)||n.allowOutsideClick&&("boolean"==typeof n.allowOutsideClick?n.allowOutsideClick:n.allowOutsideClick(t))||(t.preventDefault(),t.stopImmediatePropagation())},v=function(){if(r.active)return nt.activateTrap(i),J=n.delayInitialFocus?rt((function(){u(a())})):u(a()),s.addEventListener("focusin",d,!0),s.addEventListener("mousedown",c,{capture:!0,passive:!1}),s.addEventListener("touchstart",c,{capture:!0,passive:!1}),s.addEventListener("click",p,{capture:!0,passive:!1}),s.addEventListener("keydown",f,{capture:!0,passive:!1}),i},m=function(){if(r.active)return s.removeEventListener("focusin",d,!0),s.removeEventListener("mousedown",c,!0),s.removeEventListener("touchstart",c,!0),s.removeEventListener("click",p,!0),s.removeEventListener("keydown",f,!0),i};return(i={activate:function(t){if(r.active)return this;l(),r.active=!0,r.paused=!1,r.nodeFocusedBeforeActivation=s.activeElement;var e=t&&t.onActivate?t.onActivate:n.onActivate;return e&&e(),v(),this},deactivate:function(t){if(!r.active)return this;clearTimeout(J),m(),r.active=!1,r.paused=!1,nt.deactivateTrap(i);var e=t&&void 0!==t.onDeactivate?t.onDeactivate:n.onDeactivate;return e&&e(),(t&&void 0!==t.returnFocus?t.returnFocus:n.returnFocusOnDeactivate)&&rt((function(){var t;u((t=r.nodeFocusedBeforeActivation,h("setReturnFocus")||t))})),this},pause:function(){return r.paused||!r.active||(r.paused=!0,m()),this},unpause:function(){return r.paused&&r.active?(r.paused=!1,l(),v(),this):this},updateContainerElements:function(t){var e=[].concat(t).filter(Boolean);return r.containers=e.map((function(t){return"string"==typeof t?s.querySelector(t):t})),r.active&&l(),this}}).updateContainerElements(t),i};const at="esri-identity-modal__content";let lt=class extends R{constructor(t,e){super(t,e),this.container=document.createElement("div"),this.content=null,this.open=!1,this._close=()=>{this.open=!1},document.body.appendChild(this.container),this.own(this.watch("open",(()=>this._toggleFocusTrap())))}destroy(){this._destroyFocusTrap()}render(){const t=this.id,{open:e,content:i,title:s,messages:n}=this,r=e&&!!i,o={"esri-identity-modal--open":r,"esri-identity-modal--closed":!r},h=C("button",{class:"esri-identity-modal__close-button","aria-label":n.close,title:n.close,bind:this,onclick:this._close},C("span",{"aria-hidden":"true",class:"esri-icon-close"})),a=`${t}_title`,l=`${t}_content`,u=s?C("h1",{id:a,class:"esri-identity-modal__title"},s):null,c=r?C("div",{bind:this,class:"esri-identity-modal__dialog",role:"dialog","aria-labelledby":a,"aria-describedby":l,afterCreate:this._createFocusTrap},h,u,this._renderContent(l)):null;return C("div",{tabIndex:-1,class:this.classes("esri-identity-modal",o)},c)}_destroyFocusTrap(){var t;null==(t=this._focusTrap)||t.deactivate({onDeactivate:null}),this._focusTrap=null}_toggleFocusTrap(){const{_focusTrap:t,open:e}=this;t&&(e?t.activate():t.deactivate())}_createFocusTrap(t){this._destroyFocusTrap(),requestAnimationFrame((()=>{this._focusTrap=ht(t,{initialFocus:"input",onDeactivate:this._close}),this._toggleFocusTrap()}))}_renderContent(t){const e=this.content;return"string"==typeof e?C("div",{class:at,id:t,innerHTML:e}):P(e)?C("div",{class:at,id:t},e.render()):e instanceof HTMLElement?C("div",{class:at,id:t,bind:e,afterCreate:this._attachToNode}):null}_attachToNode(t){t.appendChild(this)}};e([i({readOnly:!0})],lt.prototype,"container",void 0),e([i(),D()],lt.prototype,"content",void 0),e([i(),D()],lt.prototype,"open",void 0),e([i(),D(),N("esri/t9n/common")],lt.prototype,"messages",void 0),e([i({aliasOf:"messages.auth.signIn"}),D()],lt.prototype,"title",void 0),lt=e([s("esri.identity.IdentityModal")],lt);var ut,ct=lt;class dt{constructor(t,e){this.oAuthInfo=null,this.storage=null,this.appId=null,this.expires=null,this.ssl=null,this.token=null,this.userId=null,this.oAuthInfo=t,this.storage=e,this._init()}isValid(){let t=!1;if(this.oAuthInfo&&this.token&&this.userId){const e=Date.now();this.expires>e&&(this.expires-e)/1e3>60*this.oAuthInfo.minTimeUntilExpiration&&(t=!0)}return t}save(){if(!this.storage)return;const t=this._load(),e=this.oAuthInfo;if(e&&e.authNamespace&&e.portalUrl){let i=t[e.authNamespace];i||(i=t[e.authNamespace]={}),i[e.portalUrl]={appId:this.appId=e.appId,expires:this.expires,ssl:this.ssl,token:this.token,userId:this.userId};try{this.storage.setItem("esriJSAPIOAuth",JSON.stringify(t))}catch(t){console.log(t)}}}destroy(){const t=this._load(),e=this.oAuthInfo;if(e&&e.appId&&e.portalUrl&&this.token&&this.expires>Date.now()){const t=e.portalUrl.replace(/^http:/i,"https:")+"/sharing/rest/oauth2/revokeToken",i=new FormData;if(i.append("f","json"),i.append("auth_token",this.token),i.append("client_id",e.appId),i.append("token_type_hint","access_token"),"function"==typeof navigator.sendBeacon)navigator.sendBeacon(t,i);else{const e=new XMLHttpRequest;e.open("POST",t),e.send(i)}}if(e&&e.authNamespace&&e.portalUrl&&this.storage){const i=t[e.authNamespace];if(i){delete i[e.portalUrl];try{this.storage.setItem("esriJSAPIOAuth",JSON.stringify(t))}catch(t){console.log(t)}}}e&&(e._oAuthCred=null,this.oAuthInfo=null)}_init(){const t=this._load(),e=this.oAuthInfo;if(e&&e.authNamespace&&e.portalUrl){let i=t[e.authNamespace];i&&(i=i[e.portalUrl],i&&(this.appId=i.appId,this.expires=i.expires,this.ssl=i.ssl,this.token=i.token,this.userId=i.userId))}}_load(){let t={};if(this.storage){const e=this.storage.getItem("esriJSAPIOAuth");if(e)try{t=JSON.parse(e)}catch(t){console.log(t)}}return t}}dt.prototype.declaredClass="esri.identity.OAuthCredential";let ft=ut=class extends r{constructor(t){super(t),this._oAuthCred=null,this.appId=null,this.authNamespace="/",this.expiration=20160,this.forceLogin=!1,this.forceUserId=!1,this.locale=null,this.minTimeUntilExpiration=30,this.popup=!1,this.popupCallbackUrl="oauth-callback.html",this.popupWindowFeatures="height=490,width=800,resizable,scrollbars,status",this.portalUrl="https://www.arcgis.com",this.preserveUrlHash=!1,this.userId=null}clone(){return ut.fromJSON(this.toJSON())}};e([i({json:{write:!0}})],ft.prototype,"appId",void 0),e([i({json:{write:!0}})],ft.prototype,"authNamespace",void 0),e([i({json:{write:!0}})],ft.prototype,"expiration",void 0),e([i({json:{write:!0}})],ft.prototype,"forceLogin",void 0),e([i({json:{write:!0}})],ft.prototype,"forceUserId",void 0),e([i({json:{write:!0}})],ft.prototype,"locale",void 0),e([i({json:{write:!0}})],ft.prototype,"minTimeUntilExpiration",void 0),e([i({json:{write:!0}})],ft.prototype,"popup",void 0),e([i({json:{write:!0}})],ft.prototype,"popupCallbackUrl",void 0),e([i({json:{write:!0}})],ft.prototype,"popupWindowFeatures",void 0),e([i({json:{write:!0}})],ft.prototype,"portalUrl",void 0),e([i({json:{write:!0}})],ft.prototype,"preserveUrlHash",void 0),e([i({json:{write:!0}})],ft.prototype,"userId",void 0),ft=ut=e([s("esri.identity.OAuthInfo")],ft);var pt=ft;let vt=class extends r{constructor(t){super(t),this.adminTokenServiceUrl=null,this.currentVersion=null,this.hasPortal=null,this.hasServer=null,this.owningSystemUrl=null,this.owningTenant=null,this.server=null,this.shortLivedTokenValidity=null,this.tokenServiceUrl=null,this.webTierAuth=null}};e([i({json:{write:!0}})],vt.prototype,"adminTokenServiceUrl",void 0),e([i({json:{write:!0}})],vt.prototype,"currentVersion",void 0),e([i({json:{write:!0}})],vt.prototype,"hasPortal",void 0),e([i({json:{write:!0}})],vt.prototype,"hasServer",void 0),e([i({json:{write:!0}})],vt.prototype,"owningSystemUrl",void 0),e([i({json:{write:!0}})],vt.prototype,"owningTenant",void 0),e([i({json:{write:!0}})],vt.prototype,"server",void 0),e([i({json:{write:!0}})],vt.prototype,"shortLivedTokenValidity",void 0),e([i({json:{write:!0}})],vt.prototype,"tokenServiceUrl",void 0),e([i({json:{write:!0}})],vt.prototype,"webTierAuth",void 0),vt=e([s("esri.identity.ServerInfo")],vt);var mt=vt;const wt={},gt=t=>{const e=new v(t.owningSystemUrl).host,i=new v(t.server).host,s=/.+\.arcgis\.com$/i;return s.test(e)&&s.test(i)},yt=(t,e)=>!!(gt(t)&&e&&e.some((e=>e.test(t.server))));let bt=class extends o{constructor(){super(),this._portalConfig=h.esriGeowConfig,this.serverInfos=[],this.oAuthInfos=[],this.credentials=[],this._soReqs=[],this._xoReqs=[],this._portals=[],this.defaultOAuthInfo=null,this.defaultTokenValidity=60,this.dialog=null,this.formConstructor=L,this.tokenValidity=null,this.signInPage=null,this.useSignInPage=!0,this.normalizeWebTierAuth=!1,this._busy=null,this._rejectOnPersistedPageShow=!1,this._oAuthHash=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|MapServer|MobileServer|NAServer|NetworkDiagramServer|ParcelFabricServer|RelationalCatalogServer|SceneServer|StreamServer|UtilityNetworkServer|ValidationServer|VectorTileServer|VersionManagementServer)).*/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._getOAuthHash(),window.addEventListener("pageshow",(t=>{this._pageShowHandler(t)}))}registerServers(t){const e=this.serverInfos;e?(t=t.filter((t=>!this.findServerInfo(t.server))),this.serverInfos=e.concat(t)):this.serverInfos=t,t.forEach((t=>{t.owningSystemUrl&&this._portals.push(t.owningSystemUrl),t.hasPortal&&this._portals.push(t.server)}))}registerOAuthInfos(t){const e=this.oAuthInfos;e?(t=t.filter((t=>!this.findOAuthInfo(t.portalUrl))),this.oAuthInfos=e.concat(t)):this.oAuthInfos=t}registerToken(t){t={...t};const e=this._sanitizeUrl(t.server),i=this._isServerRsrc(e);let s,n=this.findServerInfo(e),r=!0;n||(n=new mt,n.server=this._getServerInstanceRoot(e),i?n.hasServer=!0:(n.tokenServiceUrl=this._getTokenSvcUrl(e),n.hasPortal=!0),this.registerServers([n])),s=this._findCredential(e),s?(delete t.server,a(s,t),r=!1):(s=new kt({userId:t.userId,server:n.server,token:t.token,expires:t.expires,ssl:t.ssl,scope:i?"server":"portal"}),s.resources=[e],this.credentials.push(s)),s.emitTokenChange(!1),r||s.refreshServerTokens()}toJSON(){return l({serverInfos:this.serverInfos.map((t=>t.toJSON())),oAuthInfos:this.oAuthInfos.map((t=>t.toJSON())),credentials:this.credentials.map((t=>t.toJSON()))})}initialize(t){if(!t)return;"string"==typeof t&&(t=JSON.parse(t));const e=t.serverInfos,i=t.oAuthInfos,s=t.credentials;if(e){const t=[];e.forEach((e=>{e.server&&e.tokenServiceUrl&&t.push(e.declaredClass?e:new mt(e))})),t.length&&this.registerServers(t)}if(i){const t=[];i.forEach((e=>{e.appId&&t.push(e.declaredClass?e:new pt(e))})),t.length&&this.registerOAuthInfos(t)}s&&s.forEach((t=>{t.server&&t.token&&t.expires&&t.expires>Date.now()&&((t=t.declaredClass?t:new kt(t)).emitTokenChange(),this.credentials.push(t))}))}findServerInfo(t){let e;t=this._sanitizeUrl(t);for(const i of this.serverInfos)if(this._hasSameServerInstance(i.server,t)){e=i;break}return e}findOAuthInfo(t){let e;t=this._sanitizeUrl(t);for(const i of this.oAuthInfos)if(this._hasSameServerInstance(i.portalUrl,t)){e=i;break}return e}findCredential(t,e){let i,s;if(t=this._sanitizeUrl(t),s=this._isServerRsrc(t)?"server":"portal",e){for(const n of this.credentials)if(this._hasSameServerInstance(n.server,t)&&e===n.userId&&n.scope===s){i=n;break}}else for(const e of this.credentials)if(this._hasSameServerInstance(e.server,t)&&-1!==this._getIdenticalSvcIdx(t,e)&&e.scope===s){i=e;break}return i}getCredential(t,e){let i,s,n=!0;e&&(i=!!e.token,s=e.error,n=!1!==e.prompt),e={...e},t=this._sanitizeUrl(t);const r=u(),o=c();if(e.signal&&d(e.signal,(()=>{r.abort()})),d(r,(()=>{o.reject(new f("identity-manager:user-aborted","ABORTED"))})),p(r))return o.promise;e.signal=r.signal;const h=this._isAdminResource(t),a=i&&this._doPortalSignIn(t)?this._getEsriAuthCookie():null,l=i?this.findCredential(t):null;let v;if(l&&s&&s.details&&498===s.details.httpStatus)l.destroy(),a&&a.token===e.token&&(F("esri_auth",null,{expires:-1,path:"/",domain:document.domain}),window.location.hostname.endsWith(".arcgis.com")&&F("esri_auth",null,{expires:-1,path:"/",domain:"arcgis.com"}));else if(a||l)return v=new f("identity-manager:not-authorized","You are currently signed in as: '"+(a&&a.email||l&&l.userId)+"'. You do not have access to this resource: "+t,{error:s}),o.reject(v),o.promise;const m=this._findCredential(t,e);if(m)return o.resolve(m),o.promise;let w=this.findServerInfo(t);if(w)!w.hasServer&&this._isServerRsrc(t)&&(w._restInfoPms=this._getTokenSvcUrl(t),w.hasServer=!0);else{const e=this._getTokenSvcUrl(t);if(!e)return v=new f("identity-manager:unknown-resource","Unknown resource - could not find token service endpoint."),o.reject(v),o.promise;w=new mt,w.server=this._getServerInstanceRoot(t),"string"==typeof e?(w.tokenServiceUrl=e,w.hasPortal=!0):(w._restInfoPms=e,w.hasServer=!0),this.registerServers([w])}return n&&w.hasPortal&&void 0===w._selfReq&&!this._findOAuthInfo(t)&&(w._selfReq={owningTenant:e&&e.owningTenant,selfDfd:this._getPortalSelf(w.tokenServiceUrl.replace(this._rePortalTokenSvc,"/sharing/rest/portals/self"),t)}),this._enqueue(t,w,e,o,h)}getResourceName(t){return this._isRESTService(t)?t.replace(this._regexSDirUrl,"").replace(this._regexServerType,"")||"":this._gwUser.test(t)&&t.replace(this._gwUser,"$1")||this._gwItem.test(t)&&t.replace(this._gwItem,"$1")||this._gwGroup.test(t)&&t.replace(this._gwGroup,"$1")||""}generateToken(t,e,i){const s=this._rePortalTokenSvc.test(t.tokenServiceUrl),n=new v(window.location.href.toLowerCase()),r=this._getEsriAuthCookie(),o=t.shortLivedTokenValidity;let h,l,u,c,d,p,g,y,b,k;return e&&(k=this.tokenValidity||o||this.defaultTokenValidity,k>o&&o>0&&(k=o)),i&&(l=i.isAdmin,u=i.serverUrl,c=i.token,g=i.signal,y=i.ssl,t.customParameters=i.customParameters),l?d=t.adminTokenServiceUrl:(d=t.tokenServiceUrl,p=new v(d.toLowerCase()),r&&(h=r.auth_tier,h=h&&h.toLowerCase()),("web"===h||t.webTierAuth)&&i&&i.serverUrl&&!y&&"http"===n.scheme&&(m(n.uri,d,!0)||"https"===p.scheme&&n.host===p.host&&"7080"===n.port&&"7443"===p.port)&&(d=d.replace(/^https:/i,"http:").replace(/:7443/i,":7080"))),b=a({query:a({request:"getToken",username:e&&e.username,password:e&&e.password,serverUrl:u,token:c,expiration:k,referer:l||s?window.location.host:null,client:l?"referer":null,f:"json"},t.customParameters),method:"post",authMode:"anonymous",useProxy:this._useProxy(t,i),signal:g},i&&i.ioArgs),s||(b.withCredentials=!1),w(d,b).then((i=>{const s=i.data;if(!s||!s.token)return new f("identity-manager:authentication-failed","Unable to generate token");const n=t.server;return wt[n]||(wt[n]={}),e&&(wt[n][e.username]=e.password),s.validity=k,s}))}isBusy(){return!!this._busy}checkSignInStatus(t){return this.checkAppAccess(t,"").then((t=>t.credential))}checkAppAccess(t,e,i){let s=!1;return this.getCredential(t,{prompt:!1}).then((n=>{let r;const o={f:"json"};if("portal"===n.scope)if(e&&(this._doPortalSignIn(t,!0)||i&&i.force))r=n.server+"/sharing/rest/oauth2/validateAppAccess",o.client_id=e;else{if(!n.token)return{credential:n};r=n.server+"/sharing/rest"}else{if(!n.token)return{credential:n};r=n.server+"/rest/services"}return n.token&&(o.token=n.token),w(r,{query:o,authMode:"anonymous"}).then((t=>{if(!1===t.data.valid)throw new f("identity-manager:not-authorized",`You are currently signed in as: '${n.userId}'.`,t.data);return s=!!t.data.viewOnlyUserTypeApp,{credential:n}})).catch((t=>{if("identity-manager:not-authorized"===t.name)throw t;const e=t.details&&t.details.httpStatus;if(498===e)throw n.destroy(),new f("identity-manager:not-authenticated","User is not signed in.");if(400===e)throw new f("identity-manager:invalid-request");return{credential:n}}))})).then((t=>({credential:t.credential,viewOnly:s})))}setOAuthResponseHash(t){var e;const i=this._oAuthDfd;if(this._oAuthDfd=null,!i||!t)return;clearInterval(this._oAuthIntervalId),null==(e=this._oAuthOnHashHandle)||e.remove(),"#"===t.charAt(0)&&(t=t.substring(1));const s=g(t);if(s.error){const t="access_denied"===s.error,e=new f(t?"identity-manager:user-aborted":"identity-manager:authentication-failed",t?"ABORTED":"OAuth: "+s.error+" - "+s.error_description);i.reject(e)}else{const t=i.oinfo_,e=t._oAuthCred,n=new kt({userId:s.username,server:i.sinfo_.server,token:s.access_token,expires:Date.now()+1e3*Number(s.expires_in),ssl:"true"===s.ssl,_oAuthCred:e});t.userId=n.userId,e.storage=s.persist?window.localStorage:window.sessionStorage,e.token=n.token,e.expires=n.expires,e.userId=n.userId,e.ssl=n.ssl,e.save(),i.resolve(n)}}setRedirectionHandler(t){this._redirectFunc=t}setOAuthRedirectionHandler(t){this._oAuthRedirectFunc=t}setProtocolErrorHandler(t){this._protocolFunc=t}signIn(t,e,i={}){const s=c(),n=()=>{var t,e,i,s,n;null==(t=h)||t.remove(),null==(e=a)||e.remove(),null==(i=l)||i.remove(),null==(s=o)||s.destroy(),null==(n=this.dialog)||n.destroy(),this.dialog=o=h=a=l=null},r=()=>{n(),this._oAuthDfd=null,s.reject(new f("identity-manager:user-aborted","ABORTED"))};i.signal&&d(i.signal,(()=>{r()}));let o=new this.formConstructor;o.resource=this.getResourceName(t),o.server=e.server,this.dialog=new ct,this.dialog.content=o,this.dialog.open=!0,this.emit("dialog-create");let h=o.on("cancel",r),a=this.dialog.watch("open",r),l=o.on("submit",(t=>{this.generateToken(e,t,{isAdmin:i.isAdmin,signal:i.signal}).then((r=>{n();const o=new kt({userId:t.username,server:e.server,token:r.token,expires:null!=r.expires?Number(r.expires):null,ssl:!!r.ssl,isAdmin:i.isAdmin,validity:r.validity});s.resolve(o)})).catch((t=>{o.error=t,o.signingIn=!1}))}));return s.promise}oAuthSignIn(t,e,i,s){this._oAuthDfd=c();const n=this._oAuthDfd;if(null!=s&&s.signal&&d(s.signal,(()=>{const t=this._oAuthDfd&&this._oAuthDfd.oAuthWin_;t&&!t.closed?t.close():this.dialog&&o()})),n.resUrl_=t,n.sinfo_=e,n.oinfo_=i,!i.popup||s&&!1===s.oAuthPopupConfirmation)return this._doOAuthSignIn(t,e,i),n.promise;const r=new this.formConstructor;r.oAuthPrompt=!0,r.server=e.server,this.dialog=new ct,this.dialog.content=r,this.dialog.open=!0,this.emit("dialog-create");const o=()=>{u(),this._oAuthDfd=null,n.reject(new f("identity-manager:user-aborted","ABORTED"))},h=r.on("cancel",o),a=this.dialog.watch("open",o),l=r.on("submit",(()=>{u(),this._doOAuthSignIn(t,e,i)})),u=()=>{h.remove(),a.remove(),l.remove(),r.destroy(),this.dialog.destroy(),this.dialog=null};return n.promise}destroyCredentials(){this.credentials&&this.credentials.slice().forEach((t=>{t.destroy()})),this.emit("credentials-destroy")}_getOAuthHash(){let t=window.location.hash;if(t){"#"===t.charAt(0)&&(t=t.substring(1));const e=g(t);let i=!1;e.access_token&&e.expires_in&&e.state&&e.hasOwnProperty("username")?(e.state=JSON.parse(e.state),this._oAuthHash=e,i=!0):e.error&&e.error_description&&(console.log("IdentityManager OAuth Error: ",e.error," - ",e.error_description),"access_denied"===e.error&&(i=!0)),i&&(window.location.hash="object"==typeof e.state&&e.state.hash||"")}}_pageShowHandler(t){if(t.persisted&&this.isBusy()&&this._rejectOnPersistedPageShow){const t=new f("identity-manager:user-aborted","ABORTED");this._errbackFunc(t)}}_findCredential(t,e){let i,s,n,r,o=-1;const h=e&&e.token,a=e&&e.resource,l=this._isServerRsrc(t)?"server":"portal",u=this.credentials.filter((e=>this._hasSameServerInstance(e.server,t)&&e.scope===l));if(t=a||t,u.length)if(1===u.length){if(i=u[0],r=this.findServerInfo(i.server),s=r&&r.owningSystemUrl,n=s&&this.findCredential(s,i.userId),o=this._getIdenticalSvcIdx(t,i),!h)return-1===o&&i.resources.push(t),this._addResource(t,n),i;-1!==o&&(i.resources.splice(o,1),this._removeResource(t,n))}else{let e,i;if(u.some((h=>(i=this._getIdenticalSvcIdx(t,h),-1!==i&&(e=h,r=this.findServerInfo(e.server),s=r&&r.owningSystemUrl,n=s&&this.findCredential(s,e.userId),o=i,!0)))),h)e&&(e.resources.splice(o,1),this._removeResource(t,n));else if(e)return this._addResource(t,n),e}}_findOAuthInfo(t){let e=this.findOAuthInfo(t);if(!e)for(const i of this.oAuthInfos)if(this._isIdProvider(i.portalUrl,t)){e=i;break}return e}_addResource(t,e){e&&-1===this._getIdenticalSvcIdx(t,e)&&e.resources.push(t)}_removeResource(t,e){let i=-1;e&&(i=this._getIdenticalSvcIdx(t,e),i>-1&&e.resources.splice(i,1))}_useProxy(t,e){return e&&e.isAdmin&&!m(t.adminTokenServiceUrl,window.location.href)||!this._isPortalDomain(t.tokenServiceUrl)&&"10.1"===String(t.currentVersion)&&!m(t.tokenServiceUrl,window.location.href)}_getOrigin(t){const e=new v(t);return e.scheme+"://"+e.host+(null!=e.port?":"+e.port:"")}_getServerInstanceRoot(t){const e=t.toLowerCase();let i=e.indexOf(this._agsRest);return-1===i&&this._isAdminResource(t)&&(i=this._agsAdmin.test(t)?t.replace(this._agsAdmin,"$1").length:t.search(this._adminSvcs)),-1===i&&(i=e.indexOf("/sharing")),-1===i&&"/"===e.substr(-1)&&(i=e.length-1),i>-1?t.substring(0,i):t}_hasSameServerInstance(t,e){return"/"===t.substr(-1)&&(t=t.slice(0,-1)),t=t.toLowerCase(),e=this._getServerInstanceRoot(e).toLowerCase(),t=this._normalizeAGOLorgDomain(t),e=this._normalizeAGOLorgDomain(e),(t=t.substr(t.indexOf(":")))===e.substr(e.indexOf(":"))}_normalizeAGOLorgDomain(t){const e=/^https?:\/\/(?:cdn|[a-z\d-]+\.maps)\.arcgis\.com/i,i=/^https?:\/\/(?:cdndev|[a-z\d-]+\.mapsdevext)\.arcgis\.com/i,s=/^https?:\/\/(?:cdnqa|[a-z\d-]+\.mapsqa)\.arcgis\.com/i;return e.test(t)?t=t.replace(e,"https://www.arcgis.com"):i.test(t)?t=t.replace(i,"https://devext.arcgis.com"):s.test(t)&&(t=t.replace(s,"https://qaext.arcgis.com")),t}_sanitizeUrl(t){const e=(y.request.proxyUrl||"").toLowerCase(),i=e?t.toLowerCase().indexOf(e+"?"):-1;return-1!==i&&(t=t.substring(i+e.length+1)),t=b(t),k(t).path}_isRESTService(t){return t.indexOf(this._agsRest)>-1}_isAdminResource(t){return this._agsAdmin.test(t)||this._adminSvcs.test(t)}_isServerRsrc(t){return this._isRESTService(t)||this._isAdminResource(t)}_isIdenticalService(t,e){let i;if(this._isRESTService(t)&&this._isRESTService(e)){const s=this._getSuffix(t).toLowerCase(),n=this._getSuffix(e).toLowerCase();if(i=s===n,!i){const t=/(.*)\/(MapServer|FeatureServer).*/gi;i=s.replace(t,"$1")===n.replace(t,"$1")}}else this._isAdminResource(t)&&this._isAdminResource(e)?i=!0:this._isServerRsrc(t)||this._isServerRsrc(e)||!this._isPortalDomain(t)||(i=!0);return i}_isPortalDomain(t){const e=new v(t.toLowerCase()),i=this._portalConfig;let s=this._gwDomains.some((t=>t.regex.test(e.uri)));return!s&&i&&(s=this._hasSameServerInstance(this._getServerInstanceRoot(i.restBaseUrl),e.uri)),s||y.portalUrl&&(s=m(e,y.portalUrl,!0)),s||(s=this._portals.some((t=>this._hasSameServerInstance(t,e.uri)))),s=s||this._agsPortal.test(e.path),s}_isIdProvider(t,e){let i=-1,s=-1;this._gwDomains.forEach(((n,r)=>{-1===i&&n.regex.test(t)&&(i=r),-1===s&&n.regex.test(e)&&(s=r)}));let n=!1;if(i>-1&&s>-1&&(0===i||4===i?0!==s&&4!==s||(n=!0):1===i?1!==s&&2!==s||(n=!0):2===i?2===s&&(n=!0):3===i&&3===s&&(n=!0)),!n){const i=this.findServerInfo(e),s=i&&i.owningSystemUrl;s&&gt(i)&&this._isPortalDomain(s)&&this._isIdProvider(t,s)&&(n=!0)}return n}_getIdenticalSvcIdx(t,e){let i=-1;for(let s=0;s<e.resources.length;s++)if(this._isIdenticalService(t,e.resources[s])){i=s;break}return i}_getSuffix(t){return t.replace(this._regexSDirUrl,"").replace(this._regexServerType,"$1")}_getTokenSvcUrl(t){let e,i,s;if(this._isRESTService(t)||this._isAdminResource(t)){const s=this._getServerInstanceRoot(t);return e=s+"/admin/generateToken",i=w(t=s+"/rest/info",{query:{f:"json"}}).then((t=>t.data)),{adminUrl:e,promise:i}}if(this._isPortalDomain(t)){let e="";if(this._gwDomains.some((i=>(i.regex.test(t)&&(e=i.tokenServiceUrl),!!e))),e||this._portals.some((i=>(this._hasSameServerInstance(i,t)&&(e=i+this._gwTokenUrl),!!e))),e||(s=t.toLowerCase().indexOf("/sharing"),-1!==s&&(e=t.substring(0,s)+this._gwTokenUrl)),e||(e=this._getOrigin(t)+this._gwTokenUrl),e){const i=new v(t).port;/^http:\/\//i.test(t)&&"7080"===i&&(e=e.replace(/:7080/i,":7443")),e=e.replace(/http:/i,"https:")}return e}if(-1!==t.toLowerCase().indexOf("premium.arcgisonline.com"))return"https://premium.arcgisonline.com/server/tokens"}_exchangeToken(t,e,i){return w(`${t}/sharing/rest/oauth2/exchangeToken`,{authMode:"anonymous",method:"post",query:{f:"json",client_id:e,token:i}}).then((t=>t.data.token))}_getPortalSelf(t,e){let i;return this._gwDomains.some((e=>(e.regex.test(t)&&(i=e.customBaseUrl),!!i))),i?A({allSSL:!0,currentVersion:"4.4",customBaseUrl:i,portalMode:"multitenant",supportsOAuth:!0}):("https:"===window.location.protocol?t=t.replace(/^http:/i,"https:").replace(/:7080/i,":7443"):/^http:/i.test(e)&&(t=t.replace(/^https:/i,"http:").replace(/:7443/i,":7080")),w(t,{query:{f:"json"},authMode:"anonymous",withCredentials:!0}).then((t=>t.data)))}_hasPortalSession(){return!!this._getEsriAuthCookie()}_getEsriAuthCookie(){let t=null;if(navigator.cookieEnabled){const e=this._getAllCookies("esri_auth");let i;for(let s=0;s<e.length;s++){const n=JSON.parse(e[s]);if(n.portalApp){t=n;break}i?i.push(n):i=[n]}if(!t&&i)for(const e of i)if(e.urlKey&&window.location.hostname===`${e.urlKey.toLowerCase()}.${e.customBaseUrl}`){t=e;break}}if(t){let e=null;t.expires&&("number"==typeof t.expires?e=t.expires:"string"==typeof t.expires&&(e=Date.parse(t.expires)),isNaN(e)&&(e=null),t.expires=e),e&&e<Date.now()&&(t=null)}return t}_getAllCookies(t){const e=[],i=document.cookie.match(new RegExp("(?:^|; )"+S(t)+"=([^;]*)","g"));if(i)for(let t=0;t<i.length;t++){let s=i[t];const n=s.indexOf("=");n>-1&&(s=s.substring(n+1),e.push(decodeURIComponent(s)))}return e}_doPortalSignIn(t,e){if(navigator.cookieEnabled){const i=this._getEsriAuthCookie(),s=this._portalConfig,n=window.location.href,r=this.findServerInfo(t);if((e||this.useSignInPage)&&(s||this._isPortalDomain(n)||i)&&(r?r.hasPortal||r.owningSystemUrl&&this._isPortalDomain(r.owningSystemUrl):this._isPortalDomain(t))&&(this._isIdProvider(n,t)||s&&(this._hasSameServerInstance(this._getServerInstanceRoot(s.restBaseUrl),t)||this._isIdProvider(s.restBaseUrl,t))||m(n,t,!0)))return!0}return!1}_canUsePortalSignInWorkflow(t){return this._doPortalSignIn(t)&&(window===window.top||this._hasPortalSession())}_checkProtocol(t,e,i,s){let n=!0;const r=s?e.adminTokenServiceUrl:e.tokenServiceUrl;return 0===r.trim().toLowerCase().indexOf("https:")&&0!==window.location.href.toLowerCase().indexOf("https:")&&I(r)&&(n=!!this._protocolFunc&&!!this._protocolFunc({resourceUrl:t,serverInfo:e}),!n)&&i(new f("identity-manager:aborted","Aborted the Sign-In process to avoid sending password over insecure connection.")),n}_enqueue(t,e,i,s,n,r){return s||(s=c()),s.resUrl_=t,s.sinfo_=e,s.options_=i,s.admin_=n,s.refresh_=r,this._busy?this._hasSameServerInstance(this._getServerInstanceRoot(t),this._busy.resUrl_)?(this._oAuthDfd&&this._oAuthDfd.oAuthWin_&&this._oAuthDfd.oAuthWin_.focus(),this._soReqs.push(s)):this._xoReqs.push(s):this._doSignIn(s),s.promise}_doSignIn(t){this._busy=t,this._rejectOnPersistedPageShow=!1;const e=e=>{const i=t.options_&&t.options_.resource,s=t.resUrl_,n=t.refresh_;let r=!1;-1===this.credentials.indexOf(e)&&(n&&-1!==this.credentials.indexOf(n)?(n.userId=e.userId,n.token=e.token,n.expires=e.expires,n.validity=e.validity,n.ssl=e.ssl,n.creationTime=e.creationTime,r=!0,e=n):this.credentials.push(e)),e.resources||(e.resources=[]),e.resources.push(i||s),e.scope=this._isServerRsrc(s)?"server":"portal",e.emitTokenChange();const o=this._soReqs,h={};this._soReqs=[],o.forEach((t=>{if(!this._isIdenticalService(s,t.resUrl_)){const i=this._getSuffix(t.resUrl_);h[i]||(h[i]=!0,e.resources.push(t.resUrl_))}})),t.resolve(e),o.forEach((t=>{this._hasSameServerInstance(this._getServerInstanceRoot(s),t.resUrl_)?t.resolve(e):this._soReqs.push(t)})),this._busy=t.resUrl_=t.sinfo_=t.refresh_=null,r||this.emit("credential-create",{credential:e}),this._soReqs.length?this._doSignIn(this._soReqs.shift()):this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},i=e=>{t.reject(e),this._busy=t.resUrl_=t.sinfo_=t.refresh_=null,this._soReqs.length?this._doSignIn(this._soReqs.shift()):this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},s=(s,n,r,o)=>{const h=t.sinfo_,a=!t.options_||!1!==t.options_.prompt,l=h.hasPortal&&this._findOAuthInfo(t.resUrl_);let u,c;if(this._canUsePortalSignInWorkflow(t.resUrl_)){const s=this._getEsriAuthCookie(),n=this._portalConfig;if(s)return h.webTierAuth||"web"===(s.auth_tier&&s.auth_tier.toLowerCase())&&(h.webTierAuth=!0),u=new kt({userId:s.email,server:h.server,token:h.webTierAuth?null:s.token,expires:s.expires}),void(u.token?t._pendingDfd=this._exchangeToken(u.server,l?l.appId:"arcgisonline",u.token).then((t=>{u.token=t,e(u)})).catch((()=>{e(u)})):e(u));if(a){let e="";const s=window.location.href;return e=this.signInPage?this.signInPage:n?n.baseUrl+n.signin:this._isIdProvider(s,t.resUrl_)?this._getOrigin(s)+"/home/signin.html":h.tokenServiceUrl.replace(this._rePortalTokenSvc,"")+"/home/signin.html",e=e.replace(/http:/i,"https:"),n&&!1===n.useSSL&&(e=e.replace(/https:/i,"http:")),void(0===s.toLowerCase().replace("https","http").indexOf(e.toLowerCase().replace("https","http"))?(c=new f("identity-manager:unexpected-error","Cannot redirect to Sign-In page from within Sign-In page. URL of the resource that triggered this workflow: "+t.resUrl_),i(c)):(this._rejectOnPersistedPageShow=!0,this._redirectFunc?this._redirectFunc({signInPage:e,returnUrlParamName:"returnUrl",returnUrl:s,resourceUrl:t.resUrl_,serverInfo:h}):window.location.href=e+"?returnUrl="+encodeURIComponent(s)))}c=new f("identity-manager:not-authenticated","User is not signed in."),i(c)}else if(s)e(new kt({userId:s,server:h.server,token:r,expires:null!=o?Number(o):null,ssl:!!n}));else if(l){let s=l._oAuthCred;if(!s){const t=new dt(l,window.localStorage),e=new dt(l,window.sessionStorage);t.isValid()&&e.isValid()?t.expires>e.expires?(s=t,e.destroy()):(s=e,t.destroy()):s=t.isValid()?t:e,l._oAuthCred=s}if(s.isValid())u=new kt({userId:s.userId,server:h.server,token:s.token,expires:s.expires,ssl:s.ssl,_oAuthCred:s}),l.appId!==s.appId&&this._doPortalSignIn(t.resUrl_,!0)?t._pendingDfd=this._exchangeToken(u.server,l.appId,u.token).then((t=>{u.token=t,s.token=t,s.save(),e(u)})).catch((()=>{e(u)})):e(u);else if(this._oAuthHash&&this._oAuthHash.state.portalUrl===l.portalUrl){const t=this._oAuthHash;u=new kt({userId:t.username,server:h.server,token:t.access_token,expires:Date.now()+1e3*Number(t.expires_in),ssl:"true"===t.ssl,oAuthState:t.state,_oAuthCred:s}),l.userId=u.userId,s.storage=t.persist?window.localStorage:window.sessionStorage,s.token=u.token,s.expires=u.expires,s.userId=u.userId,s.ssl=u.ssl,s.save(),this._oAuthHash=null,e(u)}else a?t._pendingDfd=this.oAuthSignIn(t.resUrl_,h,l,t.options_).then(e,i):(c=new f("identity-manager:not-authenticated","User is not signed in."),i(c))}else if(a){if(this._checkProtocol(t.resUrl_,h,i,t.admin_)){let s=t.options_;t.admin_&&(s=s||{},s.isAdmin=!0),t._pendingDfd=this.signIn(t.resUrl_,h,s).then(e,i)}}else c=new f("identity-manager:not-authenticated","User is not signed in."),i(c)},n=()=>{const s=t.sinfo_,n=s.owningSystemUrl,r=t.options_;let o,h,a,l;if(r&&(o=r.token,h=r.error,a=r.prompt),l=this._findCredential(n,{token:o,resource:t.resUrl_}),!l)for(const t of this.credentials)if(this._isIdProvider(n,t.server)){l=t;break}if(l){const n=this.findCredential(t.resUrl_,l.userId);if(n)e(n);else if(yt(s,this._legacyFed)){const t=l.toJSON();t.server=s.server,t.resources=null,e(new kt(t))}else(t._pendingDfd=this.generateToken(this.findServerInfo(l.server),null,{serverUrl:t.resUrl_,token:l.token,signal:t.options_.signal,ssl:l.ssl})).then((i=>{e(new kt({userId:l.userId,server:s.server,token:i.token,expires:null!=i.expires?Number(i.expires):null,ssl:!!i.ssl,isAdmin:t.admin_,validity:i.validity}))}),i)}else this._busy=null,o&&(t.options_.token=null),(t._pendingDfd=this.getCredential(n.replace(/\/?$/,"/sharing"),{resource:t.resUrl_,owningTenant:s.owningTenant,signal:t.options_.signal,token:o,error:h,prompt:a})).then((()=>{this._enqueue(t.resUrl_,t.sinfo_,t.options_,t,t.admin_)}),(t=>{i(t)}))};this._errbackFunc=i;const r=t.sinfo_.owningSystemUrl,o=this._isServerRsrc(t.resUrl_),h=t.sinfo_._restInfoPms;h?h.promise.then((e=>{const i=t.sinfo_;if(i._restInfoPms){i.adminTokenServiceUrl=i._restInfoPms.adminUrl,i._restInfoPms=null,i.tokenServiceUrl=_("authInfo.tokenServicesUrl",e)||_("authInfo.tokenServiceUrl",e)||_("tokenServiceUrl",e),i.shortLivedTokenValidity=_("authInfo.shortLivedTokenValidity",e),i.currentVersion=e.currentVersion,i.owningTenant=e.owningTenant;const t=i.owningSystemUrl=e.owningSystemUrl;t&&this._portals.push(t)}o&&i.owningSystemUrl?n():s()}),(()=>{t.sinfo_._restInfoPms=null;const e=new f("identity-manager:server-identification-failed","Unknown resource - could not find token service endpoint.");i(e)})):o&&r?n():t.sinfo_._selfReq?t.sinfo_._selfReq.selfDfd.then((e=>{const i={};let s,n,r,o;return e&&(s=e.user&&e.user.username,i.username=s,i.allSSL=e.allSSL,n=e.supportsOAuth,r=e.currentVersion,"multitenant"===e.portalMode&&(o=e.customBaseUrl)),t.sinfo_.webTierAuth=!!s,s&&this.normalizeWebTierAuth?this.generateToken(t.sinfo_,null,{ssl:i.allSSL}).catch((()=>null)).then((t=>(i.portalToken=t&&t.token,i.tokenExpiration=t&&t.expires,i))):!s&&n&&parseFloat(r)>=4.4&&!this._canUsePortalSignInWorkflow(t.resUrl_)?this._generateOAuthInfo({portalUrl:t.sinfo_.server,customBaseUrl:o,owningTenant:t.sinfo_._selfReq.owningTenant}).catch((()=>null)).then((()=>i)):i})).catch((()=>null)).then((e=>{t.sinfo_._selfReq=null,e?s(e.username,e.allSSL,e.portalToken,e.tokenExpiration):s()})):s()}_generateOAuthInfo(t){let e,i,s=t.portalUrl;const n=t.customBaseUrl,r=t.owningTenant,o=!this.defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal;if(o){i=window.location.href;let t=i.indexOf("?");t>-1&&(i=i.slice(0,t)),t=i.search(/\/(apps|home)\//),i=t>-1?i.slice(0,t):null}return o&&i?(this._hasTestedIfAppIsOnPortal=!0,e=w(i+"/sharing/rest",{query:{f:"json"}}).then((()=>{this.defaultOAuthInfo=new pt({appId:"arcgisonline",popup:!0,popupCallbackUrl:i+"/home/oauth-callback.html"})}))):e=A(),e.then((()=>{if(this.defaultOAuthInfo)return s=s.replace(/^http:/i,"https:"),w(s+"/sharing/rest/oauth2/validateRedirectUri",{query:{accountId:r,client_id:this.defaultOAuthInfo.appId,redirect_uri:T(this.defaultOAuthInfo.popupCallbackUrl),f:"json"}}).then((t=>{if(t.data.valid){const e=this.defaultOAuthInfo.clone();e.portalUrl=t.data.urlKey&&n?"https://"+t.data.urlKey.toLowerCase()+"."+n:s,this.oAuthInfos.push(e)}}))}))}_doOAuthSignIn(t,e,i){const s={portalUrl:i.portalUrl};!i.popup&&i.preserveUrlHash&&window.location.hash&&(s.hash=window.location.hash);const n={client_id:i.appId,response_type:"token",state:JSON.stringify(s),expiration:i.expiration,locale:i.locale,redirect_uri:i.popup?T(i.popupCallbackUrl):window.location.href.replace(/#.*$/,"")};i.forceLogin&&(n.force_login=!0),i.forceUserId&&i.userId&&(n.prepopulatedusername=i.userId);const r=i.portalUrl.replace(/^http:/i,"https:")+"/sharing/oauth2/authorize",o=r+"?"+U(n);if(i.popup){const t=window.open(o,"esriJSAPIOAuth",i.popupWindowFeatures);if(t)t.focus(),this._oAuthDfd.oAuthWin_=t,this._oAuthIntervalId=setInterval((()=>{if(t.closed){clearInterval(this._oAuthIntervalId),this._oAuthOnHashHandle.remove();const t=this._oAuthDfd;if(t){const e=new f("identity-manager:user-aborted","ABORTED");t.reject(e)}}}),500),this._oAuthOnHashHandle=O(h,"arcgis:auth:hash",(t=>{this.setOAuthResponseHash(t.detail)}));else{const t=new f("identity-manager:popup-blocked","ABORTED");this._oAuthDfd.reject(t)}}else this._rejectOnPersistedPageShow=!0,this._oAuthRedirectFunc?this._oAuthRedirectFunc({authorizeParams:n,authorizeUrl:r,resourceUrl:t,serverInfo:e,oAuthInfo:i}):window.location.href=o}};bt=e([s("esri.identity.IdentityManagerBase")],bt);let kt=class extends o.EventedAccessor{constructor(t){super(t),this._oAuthCred=null,this.tokenRefreshBuffer=2,t&&t._oAuthCred&&(this._oAuthCred=t._oAuthCred)}initialize(){this.resources=this.resources||[],null==this.creationTime&&(this.creationTime=Date.now())}refreshToken(){const t=x.findServerInfo(this.server),e=t&&t.owningSystemUrl,i=!!e&&"server"===this.scope,s=i&&yt(t,x._legacyFed),n=t.webTierAuth,r=n&&x.normalizeWebTierAuth,o=wt[this.server],h=o&&o[this.userId];let a,l,u=this.resources&&this.resources[0],c=i&&x.findServerInfo(e),d={username:this.userId,password:h};if((!n||r)&&(i&&!c&&x.serverInfos.some((t=>(x._isIdProvider(e,t.server)&&(c=t),!!c))),a=c&&x.findCredential(c.server,this.userId),!i||a)){if(!s){if(i)l={serverUrl:u,token:a&&a.token,ssl:a&&a.ssl};else if(r)d=null,l={ssl:this.ssl};else{if(!h){let e;return u&&(u=x._sanitizeUrl(u),this._enqueued=1,e=x._enqueue(u,t,null,null,this.isAdmin,this),e.then((()=>{this._enqueued=0,this.refreshServerTokens()})).catch((()=>{this._enqueued=0}))),e}this.isAdmin&&(l={isAdmin:!0})}return x.generateToken(i?c:t,i?null:d,l).then((t=>{this.token=t.token,this.expires=null!=t.expires?Number(t.expires):null,this.creationTime=Date.now(),this.validity=t.validity,this.emitTokenChange(),this.refreshServerTokens()})).catch((()=>{}))}a.refreshToken()}}refreshServerTokens(){"portal"===this.scope&&x.credentials.forEach((t=>{const e=x.findServerInfo(t.server),i=e&&e.owningSystemUrl;t!==this&&t.userId===this.userId&&i&&"server"===t.scope&&(x._hasSameServerInstance(this.server,i)||x._isIdProvider(i,this.server))&&(yt(e,x._legacyFed)?(t.token=this.token,t.expires=this.expires,t.creationTime=this.creationTime,t.validity=this.validity,t.emitTokenChange()):t.refreshToken())}))}emitTokenChange(t){clearTimeout(this._refreshTimer);const e=this.server&&x.findServerInfo(this.server),i=e&&e.owningSystemUrl,s=i&&x.findServerInfo(i);!1===t||i&&"portal"!==this.scope&&(!s||!s.webTierAuth||x.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 t=x.credentials.indexOf(this);t>-1&&x.credentials.splice(t,1),this.emitTokenChange(),this.emit("destroy")}toJSON(){const t=l({userId:this.userId,server:this.server,token:this.token,expires:this.expires,validity:this.validity,ssl:this.ssl,isAdmin:this.isAdmin,creationTime:this.creationTime,scope:this.scope}),e=this.resources;return e&&e.length>0&&(t.resources=e.slice()),t}_startRefreshTimer(){clearTimeout(this._refreshTimer);const t=6e4*this.tokenRefreshBuffer;let e=(this.validity?this.creationTime+6e4*this.validity:this.expires)-Date.now();e<0&&(e=0),this._refreshTimer=setTimeout(this.refreshToken.bind(this),e>t?e-t:e)}};e([i()],kt.prototype,"creationTime",void 0),e([i()],kt.prototype,"expires",void 0),e([i()],kt.prototype,"isAdmin",void 0),e([i()],kt.prototype,"oAuthState",void 0),e([i()],kt.prototype,"resources",void 0),e([i()],kt.prototype,"scope",void 0),e([i()],kt.prototype,"server",void 0),e([i()],kt.prototype,"ssl",void 0),e([i()],kt.prototype,"token",void 0),e([i()],kt.prototype,"tokenRefreshBuffer",void 0),e([i()],kt.prototype,"userId",void 0),e([i()],kt.prototype,"validity",void 0),kt=e([s("esri.identity.Credential")],kt);let St=class extends bt{};St=e([s("esri.identity.IdentityManager")],St);const It=new St;j(It);export default It;