Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@esri/arcgis-rest-request

Package Overview
Dependencies
Maintainers
6
Versions
130
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@esri/arcgis-rest-request - npm Package Compare versions

Comparing version 4.1.4 to 4.2.0

6

dist/bundled/request.esm.min.js
/* @preserve
* @esri/arcgis-rest-request - v4.1.3 - Apache-2.0
* @esri/arcgis-rest-request - v4.1.4 - Apache-2.0
* Copyright (c) 2017-2023 Esri, Inc.
* Fri Apr 28 2023 01:37:08 GMT+0000 (Coordinated Universal Time)
* Thu May 04 2023 19:06:50 GMT+0000 (Coordinated Universal Time)
*/
function e(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function t(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let i=e[r];if(i&&i.toParam&&(i=i.toParam()),!i&&0!==i&&"boolean"!=typeof i&&"string"!=typeof i)return;let o;switch(i.constructor.name){case"Array":const e=null===(n=null===(s=i[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;o="Array"===e?i:"Object"===e?JSON.stringify(i):i.join(",");break;case"Object":o=JSON.stringify(i);break;case"Date":o=i.valueOf();break;case"Function":o=null;break;case"Boolean":o=i+"";break;default:o=i}(o||0===o||"string"==typeof o||Array.isArray(o))&&(t[r]=o)})),t}function r(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>r(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function s(e){const s=t(e);return Object.keys(s).map((e=>r(e,s[e]))).join("&")}const n=globalThis.FormData,i=globalThis.File,o=globalThis.Blob;function a(r,i){const o=e(r)||i,a=t(r);if(o){const e=new n;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return s(r)}class c extends Error{constructor(e,t,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function h(e){console&&console.warn&&console.warn.apply(console,[e])}function l(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const u="@esri/arcgis-rest-js";function d(e,t){e.authentication&&!t&&h("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e}function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends c{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const i=new.target.prototype;Object.setPrototypeOf(this,i)}retry(e,t=1){let r=0;const s=(n,i)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return m(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,i):e.name===this.name&&e.message===this.message&&r>=t?i(this):i(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function f(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new c(r,n,e,t,s)}if(e.error){const{message:r,code:i,messageCode:o}=e.error,a=o||i||"UNKNOWN_ERROR_CODE";if(498===i||499===i)throw n||new g(r,a,e,t,s);throw new c(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new c(r,n,e,t,s)}return e}function m(t,r){const n=p(),i=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},n),r),{params:Object.assign(Object.assign({},n.params),r.params),headers:Object.assign(Object.assign({},n.headers),r.headers)}),{httpMethod:o,rawResponse:d}=i,g=Object.assign({f:"json"},i.params);let m=null;const E={method:o,signal:i.signal,credentials:i.credentials||"same-origin"};let w;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&t.indexOf("/oauth2/platformSelf")>-1&&(E.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;w={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(h("Using an oAuth 2.0 access token directly in the token option is discouraged. Consider using ArcGISIdentityManager or Application session. See https://esriurl.com/arcgis-rest-js-direct-token-warning for more information."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else w=i.authentication;const k=t;return(w?w.getToken(t).catch((e=>(e.url=t,e.options=i,m=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),w&&w.getDomainCredentials&&(E.credentials=w.getDomainCredentials(t));const n={};if("GET"===E.method){g.token&&i.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${g.token}`,delete g.token);const e=""===s(g)?t:t+"?"+s(g);i.maxUrlLength&&e.length>i.maxUrlLength||g.token&&i.hideToken?(E.method="POST",r.length&&i.hideToken&&(g.token=r,delete n["X-Esri-Authorization"])):t=e}const o=new RegExp("/items/.+/updateResources").test(t);return"POST"===E.method&&(E.body=a(g,o)),E.headers=Object.assign(Object.assign({},n),i.headers),("undefined"==typeof window||window&&void 0===window.document)&&!E.headers.referer&&(E.headers.referer=u),e(g)||o||(E.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,E):l().then((({fetch:e})=>e(t,E)))})).then((e=>{if(!e.ok){const{status:r,statusText:s}=e;throw new c(s,`HTTP ${r}`,e,t,i)}if(d)return e;switch(g.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==g.f&&"geojson"!==g.f||d)return e;{const r=f(e,k,0,i,m);if(m){const e=t.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[e]={token:[],expires:new Date(Date.now()+864e5)},m=null}return r}}))}function E(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}function w(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})}var k,_;!function(e){e.TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",e.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",e.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",e.NOT_FEDERATED="NOT_FEDERATED",e.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE"}(k||(k={}));class T extends Error{constructor(e="UNKNOWN_ERROR",t=k.UNKNOWN_ERROR_CODE,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),this.name="ArcGISTokenRequestError",this.message=`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}class R extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}class O extends Error{constructor(e="Unknown error",t){super(e);const r=new.target.prototype;Object.setPrototypeOf(this,r),this.name="ArcGISJobError",this.message=`${t.status}: ${e}`,this.status=t.status,this.id=t.id,this.jobInfo=t}}function b(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function S(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function I(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=S(t);return e[r]=s,e}),{})}!function(e){e.ArcGISRequestError="ArcGISRequestError",e.ArcGISAuthError="ArcGISAuthError",e.ArcGISAccessDeniedError="ArcGISAccessDeniedError",e.ArcGISTokenRequestError="ArcGISTokenRequestError"}(_||(_={}));const A=3e5;function v(e,t){const r=t;return r.rawResponse=!1,E(e,r).then((e=>{if("token"in e&&"expires"in e)return{token:e.token,username:t.params.username,expires:new Date(e.expires)};const r={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-A),ssl:!0===e.ssl};return e.refresh_token&&(r.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(r.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-A)),r}))}class x{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new x(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(e){const t=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},e);return v(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function y(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new x(e)}class U{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new U({key:e})}getToken(e){return Promise.resolve(this.key)}}function j(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new U(e)}const D=/^https?:\/\/(\S+)\.arcgis\.com.+/;function C(e){return D.test(e)}function N(e){if(!D.test(e))return e;switch(P(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function P(e){if(!D.test(e))return null;const t=e.match(D)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function M(e,t){const r=b(N(t)).replace(/https?:\/\//,""),s=b(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function F(e,t){const r=C(e),s=C(t),n=P(e),i=P(t);return!(!r||!s||n!==i)}function $(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function G(e){const t=`${b(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return E(t,n).then((e=>{if(!e.success)throw new c("Unable to revoke token",500,e,t,n);return e}))}function J(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(e){!e&&window&&(e=window);return J(e.crypto.getRandomValues(new Uint8Array(32)))}class H{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?b(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.referer=e.referer,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:i,expiration:o,redirectUri:a,popup:c,popupWindowFeatures:h,locale:l,params:u,style:d,pkce:p,state:f}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),m=f||q(t),E=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(E,m);let w=`${b(r)}/oauth2/authorize`;const k={client_id:i,response_type:p?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:d};let _;if("arcgis"!==n&&(w=`${b(r)}/oauth2/social/authorize`,k.socialLoginProviderName=n,k.autoAccountCreateForSocial=!0),p){const e=q(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),_=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>J(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){k.code_challenge_method=t?"S256":"plain",k.code_challenge=t||e}))}else _=Promise.resolve();return _.then((()=>(w=`${w}?${s(k)}`,u&&(w=`${w}&${s(u)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new R;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new H({clientId:i,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(w,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=w))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i,redirectUri:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,c=t.localStorage.getItem(a),h=I(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),l=h&&h.state?JSON.parse(h.state):void 0;function u(e,r,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(i&&t.history.replaceState(t.history.state,"",i),"access_denied"===r?Promise.reject(new R):Promise.reject(new g(e,r)))}function d(e,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",i),new H({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:o||location.href.replace(location.search,"")}))}if(!c||!l)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(l.id!==c)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return u(h.error_description||"Unknown error",e,l.originalUrl)}if(i&&h.code){const e=b(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),v(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:o||location.href.replace(location.search,""),code:h.code}}).then((e=>d(Object.assign(Object.assign({},e),l),l.originalUrl))).catch((e=>u(e.originalMessage,e.code,l.originalUrl)))}return!i&&h.access_token?Promise.resolve(d(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},l),l.originalUrl)):u("Unknown error","oauth-error",l.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(H.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:n,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),c={client_id:n,expiration:i,response_type:"code",redirect_uri:o};a&&(c.state=a);const h=`${r}/oauth2/authorize?${s(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},e);return v(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new H({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}static deserialize(e){const t=JSON.parse(e);return new H({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new H({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new H({portal:b(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new H(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return G({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new H(e);return t.getUser().then((()=>t))}static signIn(e){const t=new H(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=E(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=E(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return F(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>$(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(e){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(e):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new T("Unable to refresh token. No refresh token or password present.",k.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=b(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[i,...o]=n.split("/");return`${s}${i.toLowerCase()}/${o.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return H.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(e,t){const r=this.getServerRootUrl(e),s=this.federatedServers[r];return s&&s.expires&&s.expires.getTime()>Date.now()?Promise.resolve(s.token):(this._pendingTokenRequests[r]||(this._pendingTokenRequests[r]=this.fetchAuthorizedDomains().then((()=>E(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(M(s.owningSystemUrl,this.portal))return E(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new T(`${e} is not federated with ${this.portal}.`,k.NOT_FEDERATED)}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new T(`${e} is not federated with any portal and is not explicitly trusted.`,k.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))).then((e=>(this.federatedServers[r]=e,delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}generateTokenForServer(e,t){return E(e,{params:{token:this.token,serverUrl:t,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((e=>{throw new T(e.message,k.GENERATE_TOKEN_FOR_SERVER_FAILED,e.response,e.url,e.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:this.referer?this.referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:u};return(this.server?E(`${this.getServerRootUrl(this.server)}/rest/info`).then((r=>E(r.authInfo.tokenServicesUrl,Object.assign({params:t},e)))):E(`${this.portal}/generateToken`,Object.assign({params:t},e))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshWithRefreshToken(e){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(e);const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return v(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(e){const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return v(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function z(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new H(e)}function K(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))}function W(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})}var L;z.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),H.beginOAuth2(...e)},z.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),H.completeOAuth2(...e)},z.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),H.fromParent(...e)},z.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),H.authorize(...e)},z.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),H.exchangeAuthorizationCode(...e)},z.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),H.fromCredential(...e)},z.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),H.deserialize(...e)},function(e){e.Success="Succeeded",e.Failed="Failed",e.Waiting="Waiting",e.Cancelled="Cancelled",e.Cancelling="Cancelling",e.New="New",e.Executing="Executing",e.Submitted="Submitted",e.Failure="Failure",e.TimedOut="TimedOut",e.Error="Error",e.Status="Etatus",e.Unknown="Unknown"}(L||(L={}));const X={pollingRate:2e3,startMonitoring:!1};class B{constructor(e){this.executePoll=async()=>{let e;try{e=await this.getJobInfo()}catch(e){return void this.emitter.emit(L.Error,e)}this.emitter.emit(L.Status,e),this.emitter.emit(e.status,e)};const{url:t,id:r,pollingRate:s,authentication:n}=Object.assign(Object.assign({},X),e);var i;this.url=t,this.id=r,this.authentication=n,this._pollingRate=s,this.emitter={all:i=i||new Map,on:function(e,t){var r=i.get(e);r?r.push(t):i.set(e,[t])},off:function(e,t){var r=i.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):i.set(e,[]))},emit:function(e,t){var r=i.get(e);r&&r.slice().map((function(e){e(t)})),(r=i.get("*"))&&r.slice().map((function(r){r(e,t)}))}},e.startMonitoring&&this.startEventMonitoring(s)}static deserialize(e,t){const r=Object.assign(Object.assign(Object.assign({},X),JSON.parse(e)),t);return E(`${r.url}/jobs/${r.id}`,{authentication:r.authentication}).then((()=>new B(r)))}static fromExistingJob(e){const t=Object.assign(Object.assign({},X),e);return E(`${b(t.url.replace(/\/submitJob\/?/,""))}/jobs/${t.id}`,{authentication:t.authentication}).then((()=>new B(t)))}static submitJob(e){const{url:t,params:r,authentication:s,pollingRate:n,startMonitoring:i}=Object.assign(Object.assign({},X),e),o=function(e){return Object.keys(e).reduce(((t,r)=>{const s=e[r],n=s.constructor.name;return t[r]="Array"===n?JSON.stringify(s):s,t}),{})}(r),a=b(t.replace(/\/submitJob\/?/,""));return E(a+"/submitJob",{params:o,authentication:s}).then((e=>new B({url:a,authentication:s,id:e.jobId,startMonitoring:i,pollingRate:n})))}get jobUrl(){return`${this.url}/jobs/${this.id}`}get isMonitoring(){return!!this.setIntervalHandler}get pollingRate(){return this._pollingRate}set pollingRate(e){this.stopEventMonitoring(),this.startEventMonitoring(e)}getJobInfo(){return E(this.jobUrl,{authentication:this.authentication}).then((e=>{const t=Object.assign({id:e.jobId,status:void 0},e);switch(delete t.jobId,delete t.jobStatus,e.jobStatus){case"esriJobCancelled":t.status=L.Cancelled;break;case"esriJobCancelling":t.status=L.Cancelling;break;case"esriJobNew":t.status=L.New;break;case"esriJobWaiting":t.status=L.Waiting;break;case"esriJobExecuting":t.status=L.Executing;break;case"esriJobSubmitted":t.status=L.Submitted;break;case"esriJobTimedOut":t.status=L.TimedOut;break;case"esriJobFailed":t.status=L.Failed;break;case"expectedFailure":t.status=L.Failure;break;case"esriJobSucceeded":t.status=L.Success}return t}))}on(e,t){this.emitter.on(e,t)}once(e,t){const r=s=>{this.emitter.off(e,r),t(s)};this.emitter.on(e,r),t.__arcgis_job_once_original_function__=r}off(e,t){t.__arcgis_job_once_original_function__?this.emitter.off(e,t.__arcgis_job_once_original_function__):this.emitter.off(e,t)}async getResult(e){return this.waitForCompletion().then((t=>E(this.jobUrl+"/"+t.results[e].paramUrl,{authentication:this.authentication})))}toJSON(){return{id:this.id,url:this.url,startMonitoring:this.isMonitoring,pollingRate:this.pollingRate}}serialize(){return JSON.stringify(this)}async waitForCompletion(){const e=await this.getJobInfo();return e.status===L.Success?Promise.resolve(e):e.status===L.Cancelling||e.status===L.Cancelled||e.status===L.Failed||e.status===L.Failure||e.status===L.TimedOut?(this.stopInternalEventMonitoring(),Promise.reject(new O("Job cancelled or failed.",e))):new Promise(((e,t)=>{this.startInternalEventMonitoring(),this.once(L.Cancelled,(e=>{this.stopInternalEventMonitoring(),t(new O("Job cancelled.",e))})),this.once(L.TimedOut,(e=>{this.stopInternalEventMonitoring(),t(new O("Job timed out.",e))})),this.once(L.Failed,(e=>{this.stopInternalEventMonitoring(),t(new O("Job failed.",e))})),this.once(L.Success,(t=>{this.stopInternalEventMonitoring(),e(t)}))}))}async getAllResults(){return this.waitForCompletion().then((e=>{const t=Object.keys(e.results),r=t.map((t=>E(this.jobUrl+"/"+e.results[t].paramUrl,{authentication:this.authentication}).then((e=>e))));return Promise.all(r).then((e=>t.reduce(((r,s,n)=>(r[t[n]]=e[n],r)),{})))}))}cancelJob(){return E(this.jobUrl+"/cancel",{authentication:this.authentication,params:{id:this.id,returnMessages:!1}}).then((e=>(this.emitter.emit("cancelled",e),e)))}startInternalEventMonitoring(e=X.pollingRate){this._pollingRate=e,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopInternalEventMonitoring(){this.isMonitoring&&!this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}startEventMonitoring(e=X.pollingRate){this._pollingRate=e,this.didUserEnableMonitoring=!0,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopEventMonitoring(){this.isMonitoring&&this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}}function V(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}}export{j as ApiKey,U as ApiKeyManager,x as ApplicationCredentialsManager,y as ApplicationSession,R as ArcGISAccessDeniedError,g as ArcGISAuthError,H as ArcGISIdentityManager,O as ArcGISJobError,c as ArcGISRequestError,T as ArcGISTokenRequestError,k as ArcGISTokenRequestErrorCodes,o as Blob,_ as ErrorTypes,i as File,n as FormData,L as JOB_STATUSES,B as Job,u as NODEJS_DEFAULT_REFERER_HEADER,z as UserSession,w as appendCustomParams,F as canUseOnlineToken,f as checkForErrors,b as cleanUrl,S as decodeParam,I as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,K as exchangeToken,v as fetchToken,p as getDefaultRequestOptions,l as getFetch,P as getOnlineEnvironment,m as internalRequest,M as isFederated,C as isOnline,N as normalizeOnlinePortalUrl,W as platformSelf,t as processParams,E as request,e as requiresFormData,G as revokeToken,d as setDefaultRequestOptions,$ as validateAppAccess,h as warn,V as withOptions};
function e(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function t(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let i=e[r];if(i&&i.toParam&&(i=i.toParam()),!i&&0!==i&&"boolean"!=typeof i&&"string"!=typeof i)return;let o;switch(i.constructor.name){case"Array":const e=null===(n=null===(s=i[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;o="Array"===e?i:"Object"===e?JSON.stringify(i):i.join(",");break;case"Object":o=JSON.stringify(i);break;case"Date":o=i.valueOf();break;case"Function":o=null;break;case"Boolean":o=i+"";break;default:o=i}(o||0===o||"string"==typeof o||Array.isArray(o))&&(t[r]=o)})),t}function r(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>r(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function s(e){const s=t(e);return Object.keys(s).map((e=>r(e,s[e]))).join("&")}const n=globalThis.FormData,i=globalThis.File,o=globalThis.Blob;function a(r,i){const o=e(r)||i,a=t(r);if(o){const e=new n;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return s(r)}class c extends Error{constructor(e,t,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function h(e){console&&console.warn&&console.warn.apply(console,[e])}function l(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const u="@esri/arcgis-rest-js";function d(e,t){e.authentication&&!t&&h("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e}function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends c{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const i=new.target.prototype;Object.setPrototypeOf(this,i)}retry(e,t=1){let r=0;const s=(n,i)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return m(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,i):e.name===this.name&&e.message===this.message&&r>=t?i(this):i(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function f(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new c(r,n,e,t,s)}if(e.error){const{message:r,code:i,messageCode:o}=e.error,a=o||i||"UNKNOWN_ERROR_CODE";if(498===i||499===i)throw n||new g(r,a,e,t,s);throw new c(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new c(r,n,e,t,s)}return e}function m(t,r){const n=p(),i=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},n),r),{params:Object.assign(Object.assign({},n.params),r.params),headers:Object.assign(Object.assign({},n.headers),r.headers)}),{httpMethod:o,rawResponse:d}=i,g=Object.assign({f:"json"},i.params);let m=null;const E={method:o,signal:i.signal,credentials:i.credentials||"same-origin"};let w;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&t.indexOf("/oauth2/platformSelf")>-1&&(E.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;w={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(h("Using an oAuth 2.0 access token directly in the token option is discouraged. Consider using ArcGISIdentityManager or Application session. See https://esriurl.com/arcgis-rest-js-direct-token-warning for more information."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else w=i.authentication;const k=t;return(w?w.getToken(t).catch((e=>(e.url=t,e.options=i,m=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),w&&w.getDomainCredentials&&(E.credentials=w.getDomainCredentials(t));const n={};if("GET"===E.method){g.token&&i.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${g.token}`,delete g.token);const e=""===s(g)?t:t+"?"+s(g);i.maxUrlLength&&e.length>i.maxUrlLength||g.token&&i.hideToken?(E.method="POST",r.length&&i.hideToken&&(g.token=r,delete n["X-Esri-Authorization"])):t=e}const o=new RegExp("/items/.+/updateResources").test(t);return"POST"===E.method&&(E.body=a(g,o)),E.headers=Object.assign(Object.assign({},n),i.headers),("undefined"==typeof window||window&&void 0===window.document)&&!E.headers.referer&&(E.headers.referer=u),e(g)||o||(E.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,E):l().then((({fetch:e})=>e(t,E)))})).then((e=>{if(!e.ok)return e.json().then((r=>{const{status:s,statusText:n}=e,{message:o,details:a}=r.error,h=`${o}. ${a?a.join(" "):""}`.trim();throw new c(h,`HTTP ${s} ${n}`,r,t,i)})).catch((r=>{if("ArcGISRequestError"===r.name)throw r;const{status:s,statusText:n}=e;throw new c(n,`HTTP ${s}`,e,t,i)}));if(d)return e;switch(g.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==g.f&&"geojson"!==g.f||d)return e;{const r=f(e,k,0,i,m);if(m){const e=t.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[e]={token:[],expires:new Date(Date.now()+864e5)},m=null}return r}}))}function E(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}function w(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})}var k,_;!function(e){e.TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",e.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",e.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",e.NOT_FEDERATED="NOT_FEDERATED",e.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE"}(k||(k={}));class T extends Error{constructor(e="UNKNOWN_ERROR",t=k.UNKNOWN_ERROR_CODE,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),this.name="ArcGISTokenRequestError",this.message=`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}class R extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}class O extends Error{constructor(e="Unknown error",t){super(e);const r=new.target.prototype;Object.setPrototypeOf(this,r),this.name="ArcGISJobError",this.message=`${t.status}: ${e}`,this.status=t.status,this.id=t.id,this.jobInfo=t}}function b(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function S(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function I(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=S(t);return e[r]=s,e}),{})}!function(e){e.ArcGISRequestError="ArcGISRequestError",e.ArcGISAuthError="ArcGISAuthError",e.ArcGISAccessDeniedError="ArcGISAccessDeniedError",e.ArcGISTokenRequestError="ArcGISTokenRequestError"}(_||(_={}));const A=3e5;function v(e,t){const r=t;return r.rawResponse=!1,E(e,r).then((e=>{if("token"in e&&"expires"in e)return{token:e.token,username:t.params.username,expires:new Date(e.expires)};const r={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-A),ssl:!0===e.ssl};return e.refresh_token&&(r.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(r.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-A)),r}))}class x{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new x(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(e){const t=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},e);return v(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function y(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new x(e)}class U{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new U({key:e})}getToken(e){return Promise.resolve(this.key)}}function j(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new U(e)}const D=/^https?:\/\/(\S+)\.arcgis\.com.+/;function C(e){return D.test(e)}function N(e){if(!D.test(e))return e;switch(P(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function P(e){if(!D.test(e))return null;const t=e.match(D)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function M(e,t){const r=b(N(t)).replace(/https?:\/\//,""),s=b(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function F(e,t){const r=C(e),s=C(t),n=P(e),i=P(t);return!(!r||!s||n!==i)}function $(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function G(e){const t=`${b(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return E(t,n).then((e=>{if(!e.success)throw new c("Unable to revoke token",500,e,t,n);return e}))}function J(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(e){!e&&window&&(e=window);return J(e.crypto.getRandomValues(new Uint8Array(32)))}class H{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?b(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.referer=e.referer,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:i,expiration:o,redirectUri:a,popup:c,popupWindowFeatures:h,locale:l,params:u,style:d,pkce:p,state:f}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),m=f||q(t),E=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(E,m);let w=`${b(r)}/oauth2/authorize`;const k={client_id:i,response_type:p?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:d};let _;if("arcgis"!==n&&(w=`${b(r)}/oauth2/social/authorize`,k.socialLoginProviderName=n,k.autoAccountCreateForSocial=!0),p){const e=q(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),_=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>J(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){k.code_challenge_method=t?"S256":"plain",k.code_challenge=t||e}))}else _=Promise.resolve();return _.then((()=>(w=`${w}?${s(k)}`,u&&(w=`${w}&${s(u)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new R;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new H({clientId:i,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(w,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=w))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i,redirectUri:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,c=t.localStorage.getItem(a),h=I(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),l=h&&h.state?JSON.parse(h.state):void 0;function u(e,r,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(i&&t.history.replaceState(t.history.state,"",i),"access_denied"===r?Promise.reject(new R):Promise.reject(new g(e,r)))}function d(e,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",i),new H({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:o||location.href.replace(location.search,"")}))}if(!c||!l)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(l.id!==c)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return u(h.error_description||"Unknown error",e,l.originalUrl)}if(i&&h.code){const e=b(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),v(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:o||location.href.replace(location.search,""),code:h.code}}).then((e=>d(Object.assign(Object.assign({},e),l),l.originalUrl))).catch((e=>u(e.originalMessage,e.code,l.originalUrl)))}return!i&&h.access_token?Promise.resolve(d(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},l),l.originalUrl)):u("Unknown error","oauth-error",l.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(H.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:n,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),c={client_id:n,expiration:i,response_type:"code",redirect_uri:o};a&&(c.state=a);const h=`${r}/oauth2/authorize?${s(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},e);return v(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new H({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}static deserialize(e){const t=JSON.parse(e);return new H({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new H({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new H({portal:b(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new H(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return G({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new H(e);return t.getUser().then((()=>t))}static signIn(e){const t=new H(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=E(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=E(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return F(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>$(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(e){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(e):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new T("Unable to refresh token. No refresh token or password present.",k.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=b(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[i,...o]=n.split("/");return`${s}${i.toLowerCase()}/${o.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return H.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(e,t){const r=this.getServerRootUrl(e),s=this.federatedServers[r];return s&&s.expires&&s.expires.getTime()>Date.now()?Promise.resolve(s.token):(this._pendingTokenRequests[r]||(this._pendingTokenRequests[r]=this.fetchAuthorizedDomains().then((()=>E(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(M(s.owningSystemUrl,this.portal))return E(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new T(`${e} is not federated with ${this.portal}.`,k.NOT_FEDERATED)}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new T(`${e} is not federated with any portal and is not explicitly trusted.`,k.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))).then((e=>(this.federatedServers[r]=e,delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}generateTokenForServer(e,t){return E(e,{params:{token:this.token,serverUrl:t,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((e=>{throw new T(e.message,k.GENERATE_TOKEN_FOR_SERVER_FAILED,e.response,e.url,e.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:this.referer?this.referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:u};return(this.server?E(`${this.getServerRootUrl(this.server)}/rest/info`).then((r=>E(r.authInfo.tokenServicesUrl,Object.assign({params:t},e)))):E(`${this.portal}/generateToken`,Object.assign({params:t},e))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshWithRefreshToken(e){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(e);const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return v(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(e){const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return v(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function z(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new H(e)}function K(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))}function W(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})}var L;z.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),H.beginOAuth2(...e)},z.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),H.completeOAuth2(...e)},z.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),H.fromParent(...e)},z.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),H.authorize(...e)},z.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),H.exchangeAuthorizationCode(...e)},z.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),H.fromCredential(...e)},z.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),H.deserialize(...e)},function(e){e.Success="Succeeded",e.Failed="Failed",e.Waiting="Waiting",e.Cancelled="Cancelled",e.Cancelling="Cancelling",e.New="New",e.Executing="Executing",e.Submitted="Submitted",e.Failure="Failure",e.TimedOut="TimedOut",e.Error="Error",e.Status="Etatus",e.Unknown="Unknown"}(L||(L={}));const X={pollingRate:2e3,startMonitoring:!1};class B{constructor(e){this.executePoll=async()=>{let e;try{e=await this.getJobInfo()}catch(e){return void this.emitter.emit(L.Error,e)}this.emitter.emit(L.Status,e),this.emitter.emit(e.status,e)};const{url:t,id:r,pollingRate:s,authentication:n}=Object.assign(Object.assign({},X),e);var i;this.url=t,this.id=r,this.authentication=n,this._pollingRate=s,this.emitter={all:i=i||new Map,on:function(e,t){var r=i.get(e);r?r.push(t):i.set(e,[t])},off:function(e,t){var r=i.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):i.set(e,[]))},emit:function(e,t){var r=i.get(e);r&&r.slice().map((function(e){e(t)})),(r=i.get("*"))&&r.slice().map((function(r){r(e,t)}))}},e.startMonitoring&&this.startEventMonitoring(s)}static deserialize(e,t){const r=Object.assign(Object.assign(Object.assign({},X),JSON.parse(e)),t);return E(`${r.url}/jobs/${r.id}`,{authentication:r.authentication}).then((()=>new B(r)))}static fromExistingJob(e){const t=Object.assign(Object.assign({},X),e);return E(`${b(t.url.replace(/\/submitJob\/?/,""))}/jobs/${t.id}`,{authentication:t.authentication}).then((()=>new B(t)))}static submitJob(e){const{url:t,params:r,authentication:s,pollingRate:n,startMonitoring:i}=Object.assign(Object.assign({},X),e),o=function(e){return Object.keys(e).reduce(((t,r)=>{const s=e[r],n=s.constructor.name;return t[r]="Array"===n?JSON.stringify(s):s,t}),{})}(r),a=b(t.replace(/\/submitJob\/?/,""));return E(a+"/submitJob",{params:o,authentication:s}).then((e=>new B({url:a,authentication:s,id:e.jobId,startMonitoring:i,pollingRate:n})))}get jobUrl(){return`${this.url}/jobs/${this.id}`}get isMonitoring(){return!!this.setIntervalHandler}get pollingRate(){return this._pollingRate}set pollingRate(e){this.stopEventMonitoring(),this.startEventMonitoring(e)}getJobInfo(){return E(this.jobUrl,{authentication:this.authentication}).then((e=>{const t=Object.assign({id:e.jobId,status:void 0},e);switch(delete t.jobId,delete t.jobStatus,e.jobStatus){case"esriJobCancelled":t.status=L.Cancelled;break;case"esriJobCancelling":t.status=L.Cancelling;break;case"esriJobNew":t.status=L.New;break;case"esriJobWaiting":t.status=L.Waiting;break;case"esriJobExecuting":t.status=L.Executing;break;case"esriJobSubmitted":t.status=L.Submitted;break;case"esriJobTimedOut":t.status=L.TimedOut;break;case"esriJobFailed":t.status=L.Failed;break;case"expectedFailure":t.status=L.Failure;break;case"esriJobSucceeded":t.status=L.Success}return t}))}on(e,t){this.emitter.on(e,t)}once(e,t){const r=s=>{this.emitter.off(e,r),t(s)};this.emitter.on(e,r),t.__arcgis_job_once_original_function__=r}off(e,t){t.__arcgis_job_once_original_function__?this.emitter.off(e,t.__arcgis_job_once_original_function__):this.emitter.off(e,t)}async getResult(e){return this.waitForCompletion().then((t=>E(this.jobUrl+"/"+t.results[e].paramUrl,{authentication:this.authentication})))}toJSON(){return{id:this.id,url:this.url,startMonitoring:this.isMonitoring,pollingRate:this.pollingRate}}serialize(){return JSON.stringify(this)}async waitForCompletion(){const e=await this.getJobInfo();return e.status===L.Success?Promise.resolve(e):e.status===L.Cancelling||e.status===L.Cancelled||e.status===L.Failed||e.status===L.Failure||e.status===L.TimedOut?(this.stopInternalEventMonitoring(),Promise.reject(new O("Job cancelled or failed.",e))):new Promise(((e,t)=>{this.startInternalEventMonitoring(),this.once(L.Cancelled,(e=>{this.stopInternalEventMonitoring(),t(new O("Job cancelled.",e))})),this.once(L.TimedOut,(e=>{this.stopInternalEventMonitoring(),t(new O("Job timed out.",e))})),this.once(L.Failed,(e=>{this.stopInternalEventMonitoring(),t(new O("Job failed.",e))})),this.once(L.Success,(t=>{this.stopInternalEventMonitoring(),e(t)}))}))}async getAllResults(){return this.waitForCompletion().then((e=>{const t=Object.keys(e.results),r=t.map((t=>E(this.jobUrl+"/"+e.results[t].paramUrl,{authentication:this.authentication}).then((e=>e))));return Promise.all(r).then((e=>t.reduce(((r,s,n)=>(r[t[n]]=e[n],r)),{})))}))}cancelJob(){return E(this.jobUrl+"/cancel",{authentication:this.authentication,params:{id:this.id,returnMessages:!1}}).then((e=>(this.emitter.emit("cancelled",e),e)))}startInternalEventMonitoring(e=X.pollingRate){this._pollingRate=e,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopInternalEventMonitoring(){this.isMonitoring&&!this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}startEventMonitoring(e=X.pollingRate){this._pollingRate=e,this.didUserEnableMonitoring=!0,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopEventMonitoring(){this.isMonitoring&&this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}}function V(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}}export{j as ApiKey,U as ApiKeyManager,x as ApplicationCredentialsManager,y as ApplicationSession,R as ArcGISAccessDeniedError,g as ArcGISAuthError,H as ArcGISIdentityManager,O as ArcGISJobError,c as ArcGISRequestError,T as ArcGISTokenRequestError,k as ArcGISTokenRequestErrorCodes,o as Blob,_ as ErrorTypes,i as File,n as FormData,L as JOB_STATUSES,B as Job,u as NODEJS_DEFAULT_REFERER_HEADER,z as UserSession,w as appendCustomParams,F as canUseOnlineToken,f as checkForErrors,b as cleanUrl,S as decodeParam,I as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,K as exchangeToken,v as fetchToken,p as getDefaultRequestOptions,l as getFetch,P as getOnlineEnvironment,m as internalRequest,M as isFederated,C as isOnline,N as normalizeOnlinePortalUrl,W as platformSelf,t as processParams,E as request,e as requiresFormData,G as revokeToken,d as setDefaultRequestOptions,$ as validateAppAccess,h as warn,V as withOptions};
//# sourceMappingURL=request.esm.min.js.map
/* @preserve
* @esri/arcgis-rest-request - v4.1.3 - Apache-2.0
* @esri/arcgis-rest-request - v4.1.4 - Apache-2.0
* Copyright (c) 2017-2023 Esri, Inc.
* Fri Apr 28 2023 01:37:08 GMT+0000 (Coordinated Universal Time)
* Thu May 04 2023 19:06:50 GMT+0000 (Coordinated Universal Time)
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).arcgisRest=e.arcgisRest||{})}(this,(function(e){"use strict";function t(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function r(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let i=e[r];if(i&&i.toParam&&(i=i.toParam()),!i&&0!==i&&"boolean"!=typeof i&&"string"!=typeof i)return;let o;switch(i.constructor.name){case"Array":const e=null===(n=null===(s=i[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;o="Array"===e?i:"Object"===e?JSON.stringify(i):i.join(",");break;case"Object":o=JSON.stringify(i);break;case"Date":o=i.valueOf();break;case"Function":o=null;break;case"Boolean":o=i+"";break;default:o=i}(o||0===o||"string"==typeof o||Array.isArray(o))&&(t[r]=o)})),t}function s(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>s(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function n(e){const t=r(e);return Object.keys(t).map((e=>s(e,t[e]))).join("&")}const i=globalThis.FormData,o=globalThis.File,a=globalThis.Blob;function c(e,s){const o=t(e)||s,a=r(e);if(o){const e=new i;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return n(e)}class h extends Error{constructor(e,t,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function l(e){console&&console.warn&&console.warn.apply(console,[e])}function u(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const d="@esri/arcgis-rest-js";function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends h{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const i=new.target.prototype;Object.setPrototypeOf(this,i)}retry(e,t=1){let r=0;const s=(n,i)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return f(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,i):e.name===this.name&&e.message===this.message&&r>=t?i(this):i(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function E(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new h(r,n,e,t,s)}if(e.error){const{message:r,code:i,messageCode:o}=e.error,a=o||i||"UNKNOWN_ERROR_CODE";if(498===i||499===i)throw n||new g(r,a,e,t,s);throw new h(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new h(r,n,e,t,s)}return e}function f(e,r){const s=p(),i=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},s),r),{params:Object.assign(Object.assign({},s.params),r.params),headers:Object.assign(Object.assign({},s.headers),r.headers)}),{httpMethod:o,rawResponse:a}=i,g=Object.assign({f:"json"},i.params);let f=null;const m={method:o,signal:i.signal,credentials:i.credentials||"same-origin"};let k;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;k={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(l("Using an oAuth 2.0 access token directly in the token option is discouraged. Consider using ArcGISIdentityManager or Application session. See https://esriurl.com/arcgis-rest-js-direct-token-warning for more information."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else k=i.authentication;const T=e;return(k?k.getToken(e).catch((t=>(t.url=e,t.options=i,f=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),k&&k.getDomainCredentials&&(m.credentials=k.getDomainCredentials(e));const s={};if("GET"===m.method){g.token&&i.hideToken&&"undefined"==typeof window&&(s["X-Esri-Authorization"]=`Bearer ${g.token}`,delete g.token);const t=""===n(g)?e:e+"?"+n(g);i.maxUrlLength&&t.length>i.maxUrlLength||g.token&&i.hideToken?(m.method="POST",r.length&&i.hideToken&&(g.token=r,delete s["X-Esri-Authorization"])):e=t}const o=new RegExp("/items/.+/updateResources").test(e);return"POST"===m.method&&(m.body=c(g,o)),m.headers=Object.assign(Object.assign({},s),i.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer=d),t(g)||o||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,m):u().then((({fetch:t})=>t(e,m)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new h(s,`HTTP ${r}`,t,e,i)}if(a)return t;switch(g.f){case"json":case"geojson":return t.json();case"html":case"text":return t.text();default:return t.blob()}})).then((t=>{if("json"!==g.f&&"geojson"!==g.f||a)return t;{const r=E(t,T,0,i,f);if(f){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},f=null}return r}}))}function m(e,t={params:{f:"json"}}){return f(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}var k,T;e.ArcGISTokenRequestErrorCodes=void 0,(k=e.ArcGISTokenRequestErrorCodes||(e.ArcGISTokenRequestErrorCodes={})).TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",k.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",k.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",k.NOT_FEDERATED="NOT_FEDERATED",k.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE";class w extends Error{constructor(t="UNKNOWN_ERROR",r=e.ArcGISTokenRequestErrorCodes.UNKNOWN_ERROR_CODE,s,n,i){super(t);const o=new.target.prototype;Object.setPrototypeOf(this,o),this.name="ArcGISTokenRequestError",this.message=`${r}: ${t}`,this.originalMessage=t,this.code=r,this.response=s,this.url=n,this.options=i}}class S extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}class _ extends Error{constructor(e="Unknown error",t){super(e);const r=new.target.prototype;Object.setPrototypeOf(this,r),this.name="ArcGISJobError",this.message=`${t.status}: ${e}`,this.status=t.status,this.id=t.id,this.jobInfo=t}}function O(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function R(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function A(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=R(t);return e[r]=s,e}),{})}e.ErrorTypes=void 0,(T=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",T.ArcGISAuthError="ArcGISAuthError",T.ArcGISAccessDeniedError="ArcGISAccessDeniedError",T.ArcGISTokenRequestError="ArcGISTokenRequestError";const b=3e5;function I(e,t){const r=t;return r.rawResponse=!1,m(e,r).then((e=>{if("token"in e&&"expires"in e)return{token:e.token,username:t.params.username,expires:new Date(e.expires)};const r={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-b),ssl:!0===e.ssl};return e.refresh_token&&(r.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(r.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-b)),r}))}class v{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new v(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(t){const r=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},t);return I(`${this.portal}/oauth2/token/`,r).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class U{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new U({key:e})}getToken(e){return Promise.resolve(this.key)}}const y=/^https?:\/\/(\S+)\.arcgis\.com.+/;function x(e){return y.test(e)}function D(e){if(!y.test(e))return e;switch(C(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function C(e){if(!y.test(e))return null;const t=e.match(y)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function j(e,t){const r=O(D(t)).replace(/https?:\/\//,""),s=O(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function N(e,t){const r=x(e),s=x(t),n=C(e),i=C(t);return!(!r||!s||n!==i)}function P(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function J(e){const t=`${O(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return m(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function F(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function M(e){!e&&window&&(e=window);return F(e.crypto.getRandomValues(new Uint8Array(32)))}class G{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?O(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.referer=e.referer,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:i,expiration:o,redirectUri:a,popup:c,popupWindowFeatures:h,locale:l,params:u,style:d,pkce:p,state:E}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),f=E||M(t),m=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(m,f);let k=`${O(r)}/oauth2/authorize`;const T={client_id:i,response_type:p?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:f,originalUrl:t.location.href}),locale:l,style:d};let w;if("arcgis"!==s&&(k=`${O(r)}/oauth2/social/authorize`,T.socialLoginProviderName=s,T.autoAccountCreateForSocial=!0),p){const e=M(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),w=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>F(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){T.code_challenge_method=t?"S256":"plain",T.code_challenge=t||e}))}else w=Promise.resolve();return w.then((()=>(k=`${k}?${n(T)}`,u&&(k=`${k}&${n(u)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new S;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new G({clientId:i,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(k,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=k))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i,redirectUri:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,c=t.localStorage.getItem(a),h=A(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),l=h&&h.state?JSON.parse(h.state):void 0;function u(e,r,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(i&&t.history.replaceState(t.history.state,"",i),"access_denied"===r?Promise.reject(new S):Promise.reject(new g(e,r)))}function d(e,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",i),new G({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:o||location.href.replace(location.search,"")}))}if(!c||!l)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(l.id!==c)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return u(h.error_description||"Unknown error",e,l.originalUrl)}if(i&&h.code){const e=O(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),I(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:o||location.href.replace(location.search,""),code:h.code}}).then((e=>d(Object.assign(Object.assign({},e),l),l.originalUrl))).catch((e=>u(e.originalMessage,e.code,l.originalUrl)))}return!i&&h.access_token?Promise.resolve(d(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},l),l.originalUrl)):u("Unknown error","oauth-error",l.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(G.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:s,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),c={client_id:s,expiration:i,response_type:"code",redirect_uri:o};a&&(c.state=a);const h=`${r}/oauth2/authorize?${n(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(t,r){const{portal:s,clientId:n,redirectUri:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},t);return I(`${s}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:n,redirect_uri:i,code:r}}).then((e=>new G({clientId:n,portal:s,ssl:e.ssl,redirectUri:i,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}static deserialize(e){const t=JSON.parse(e);return new G({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new G({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new G({portal:O(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new G(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return J({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new G(e);return t.getUser().then((()=>t))}static signIn(e){const t=new G(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=m(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=m(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return N(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>P(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(t){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(t):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new w("Unable to refresh token. No refresh token or password present.",e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=O(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[i,...o]=n.split("/");return`${s}${i.toLowerCase()}/${o.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return G.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(t,r){const s=this.getServerRootUrl(t),n=this.federatedServers[s];return n&&n.expires&&n.expires.getTime()>Date.now()?Promise.resolve(n.token):(this._pendingTokenRequests[s]||(this._pendingTokenRequests[s]=this.fetchAuthorizedDomains().then((()=>m(`${s}/rest/info`,{credentials:this.getDomainCredentials(t)}).then((n=>{if(n.owningSystemUrl){if(j(n.owningSystemUrl,this.portal))return m(`${n.owningSystemUrl}/sharing/rest/info`,r);throw new w(`${t} is not federated with ${this.portal}.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)}if(n.authInfo&&void 0!==this.federatedServers[s])return Promise.resolve({authInfo:n.authInfo});throw new w(`${t} is not federated with any portal and is not explicitly trusted.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))).then((e=>(this.federatedServers[s]=e,delete this._pendingTokenRequests[s],e.token)))))),this._pendingTokenRequests[s])}generateTokenForServer(t,r){return m(t,{params:{token:this.token,serverUrl:r,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.GENERATE_TOKEN_FOR_SERVER_FAILED,t.response,t.url,t.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(t){const r={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:this.referer?this.referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:d};return(this.server?m(`${this.getServerRootUrl(this.server)}/rest/info`).then((e=>m(e.authInfo.tokenServicesUrl,Object.assign({params:r},t)))):m(`${this.portal}/generateToken`,Object.assign({params:r},t))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshWithRefreshToken(t){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(t);const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>this.updateToken(e.token,e.expires))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(t){const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function q(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new G(e)}var $;q.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),G.beginOAuth2(...e)},q.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),G.completeOAuth2(...e)},q.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),G.fromParent(...e)},q.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),G.authorize(...e)},q.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),G.exchangeAuthorizationCode(...e)},q.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),G.fromCredential(...e)},q.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),G.deserialize(...e)},e.JOB_STATUSES=void 0,($=e.JOB_STATUSES||(e.JOB_STATUSES={})).Success="Succeeded",$.Failed="Failed",$.Waiting="Waiting",$.Cancelled="Cancelled",$.Cancelling="Cancelling",$.New="New",$.Executing="Executing",$.Submitted="Submitted",$.Failure="Failure",$.TimedOut="TimedOut",$.Error="Error",$.Status="Etatus",$.Unknown="Unknown";const H={pollingRate:2e3,startMonitoring:!1};class z{constructor(t){this.executePoll=async()=>{let t;try{t=await this.getJobInfo()}catch(t){return void this.emitter.emit(e.JOB_STATUSES.Error,t)}this.emitter.emit(e.JOB_STATUSES.Status,t),this.emitter.emit(t.status,t)};const{url:r,id:s,pollingRate:n,authentication:i}=Object.assign(Object.assign({},H),t);var o;this.url=r,this.id=s,this.authentication=i,this._pollingRate=n,this.emitter={all:o=o||new Map,on:function(e,t){var r=o.get(e);r?r.push(t):o.set(e,[t])},off:function(e,t){var r=o.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):o.set(e,[]))},emit:function(e,t){var r=o.get(e);r&&r.slice().map((function(e){e(t)})),(r=o.get("*"))&&r.slice().map((function(r){r(e,t)}))}},t.startMonitoring&&this.startEventMonitoring(n)}static deserialize(e,t){const r=Object.assign(Object.assign(Object.assign({},H),JSON.parse(e)),t);return m(`${r.url}/jobs/${r.id}`,{authentication:r.authentication}).then((()=>new z(r)))}static fromExistingJob(e){const t=Object.assign(Object.assign({},H),e);return m(`${O(t.url.replace(/\/submitJob\/?/,""))}/jobs/${t.id}`,{authentication:t.authentication}).then((()=>new z(t)))}static submitJob(e){const{url:t,params:r,authentication:s,pollingRate:n,startMonitoring:i}=Object.assign(Object.assign({},H),e),o=function(e){return Object.keys(e).reduce(((t,r)=>{const s=e[r],n=s.constructor.name;return t[r]="Array"===n?JSON.stringify(s):s,t}),{})}(r),a=O(t.replace(/\/submitJob\/?/,""));return m(a+"/submitJob",{params:o,authentication:s}).then((e=>new z({url:a,authentication:s,id:e.jobId,startMonitoring:i,pollingRate:n})))}get jobUrl(){return`${this.url}/jobs/${this.id}`}get isMonitoring(){return!!this.setIntervalHandler}get pollingRate(){return this._pollingRate}set pollingRate(e){this.stopEventMonitoring(),this.startEventMonitoring(e)}getJobInfo(){return m(this.jobUrl,{authentication:this.authentication}).then((t=>{const r=Object.assign({id:t.jobId,status:void 0},t);switch(delete r.jobId,delete r.jobStatus,t.jobStatus){case"esriJobCancelled":r.status=e.JOB_STATUSES.Cancelled;break;case"esriJobCancelling":r.status=e.JOB_STATUSES.Cancelling;break;case"esriJobNew":r.status=e.JOB_STATUSES.New;break;case"esriJobWaiting":r.status=e.JOB_STATUSES.Waiting;break;case"esriJobExecuting":r.status=e.JOB_STATUSES.Executing;break;case"esriJobSubmitted":r.status=e.JOB_STATUSES.Submitted;break;case"esriJobTimedOut":r.status=e.JOB_STATUSES.TimedOut;break;case"esriJobFailed":r.status=e.JOB_STATUSES.Failed;break;case"expectedFailure":r.status=e.JOB_STATUSES.Failure;break;case"esriJobSucceeded":r.status=e.JOB_STATUSES.Success}return r}))}on(e,t){this.emitter.on(e,t)}once(e,t){const r=s=>{this.emitter.off(e,r),t(s)};this.emitter.on(e,r),t.__arcgis_job_once_original_function__=r}off(e,t){t.__arcgis_job_once_original_function__?this.emitter.off(e,t.__arcgis_job_once_original_function__):this.emitter.off(e,t)}async getResult(e){return this.waitForCompletion().then((t=>m(this.jobUrl+"/"+t.results[e].paramUrl,{authentication:this.authentication})))}toJSON(){return{id:this.id,url:this.url,startMonitoring:this.isMonitoring,pollingRate:this.pollingRate}}serialize(){return JSON.stringify(this)}async waitForCompletion(){const t=await this.getJobInfo();return t.status===e.JOB_STATUSES.Success?Promise.resolve(t):t.status===e.JOB_STATUSES.Cancelling||t.status===e.JOB_STATUSES.Cancelled||t.status===e.JOB_STATUSES.Failed||t.status===e.JOB_STATUSES.Failure||t.status===e.JOB_STATUSES.TimedOut?(this.stopInternalEventMonitoring(),Promise.reject(new _("Job cancelled or failed.",t))):new Promise(((t,r)=>{this.startInternalEventMonitoring(),this.once(e.JOB_STATUSES.Cancelled,(e=>{this.stopInternalEventMonitoring(),r(new _("Job cancelled.",e))})),this.once(e.JOB_STATUSES.TimedOut,(e=>{this.stopInternalEventMonitoring(),r(new _("Job timed out.",e))})),this.once(e.JOB_STATUSES.Failed,(e=>{this.stopInternalEventMonitoring(),r(new _("Job failed.",e))})),this.once(e.JOB_STATUSES.Success,(e=>{this.stopInternalEventMonitoring(),t(e)}))}))}async getAllResults(){return this.waitForCompletion().then((e=>{const t=Object.keys(e.results),r=t.map((t=>m(this.jobUrl+"/"+e.results[t].paramUrl,{authentication:this.authentication}).then((e=>e))));return Promise.all(r).then((e=>t.reduce(((r,s,n)=>(r[t[n]]=e[n],r)),{})))}))}cancelJob(){return m(this.jobUrl+"/cancel",{authentication:this.authentication,params:{id:this.id,returnMessages:!1}}).then((e=>(this.emitter.emit("cancelled",e),e)))}startInternalEventMonitoring(e=H.pollingRate){this._pollingRate=e,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopInternalEventMonitoring(){this.isMonitoring&&!this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}startEventMonitoring(e=H.pollingRate){this._pollingRate=e,this.didUserEnableMonitoring=!0,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopEventMonitoring(){this.isMonitoring&&this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}}e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new U(e)},e.ApiKeyManager=U,e.ApplicationCredentialsManager=v,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)},e.ArcGISAccessDeniedError=S,e.ArcGISAuthError=g,e.ArcGISIdentityManager=G,e.ArcGISJobError=_,e.ArcGISRequestError=h,e.ArcGISTokenRequestError=w,e.Blob=a,e.File=o,e.FormData=i,e.Job=z,e.NODEJS_DEFAULT_REFERER_HEADER=d,e.UserSession=q,e.appendCustomParams=function(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})},e.canUseOnlineToken=N,e.checkForErrors=E,e.cleanUrl=O,e.decodeParam=R,e.decodeQueryString=A,e.encodeFormData=c,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=I,e.getDefaultRequestOptions=p,e.getFetch=u,e.getOnlineEnvironment=C,e.internalRequest=f,e.isFederated=j,e.isOnline=x,e.normalizeOnlinePortalUrl=D,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})},e.processParams=r,e.request=m,e.requiresFormData=t,e.revokeToken=J,e.setDefaultRequestOptions=function(e,t){e.authentication&&!t&&l("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e},e.validateAppAccess=P,e.warn=l,e.withOptions=function(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}},Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).arcgisRest=e.arcgisRest||{})}(this,(function(e){"use strict";function t(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function r(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let i=e[r];if(i&&i.toParam&&(i=i.toParam()),!i&&0!==i&&"boolean"!=typeof i&&"string"!=typeof i)return;let o;switch(i.constructor.name){case"Array":const e=null===(n=null===(s=i[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;o="Array"===e?i:"Object"===e?JSON.stringify(i):i.join(",");break;case"Object":o=JSON.stringify(i);break;case"Date":o=i.valueOf();break;case"Function":o=null;break;case"Boolean":o=i+"";break;default:o=i}(o||0===o||"string"==typeof o||Array.isArray(o))&&(t[r]=o)})),t}function s(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>s(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function n(e){const t=r(e);return Object.keys(t).map((e=>s(e,t[e]))).join("&")}const i=globalThis.FormData,o=globalThis.File,a=globalThis.Blob;function c(e,s){const o=t(e)||s,a=r(e);if(o){const e=new i;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return n(e)}class h extends Error{constructor(e,t,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function l(e){console&&console.warn&&console.warn.apply(console,[e])}function u(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const d="@esri/arcgis-rest-js";function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends h{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const i=new.target.prototype;Object.setPrototypeOf(this,i)}retry(e,t=1){let r=0;const s=(n,i)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return f(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,i):e.name===this.name&&e.message===this.message&&r>=t?i(this):i(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function E(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new h(r,n,e,t,s)}if(e.error){const{message:r,code:i,messageCode:o}=e.error,a=o||i||"UNKNOWN_ERROR_CODE";if(498===i||499===i)throw n||new g(r,a,e,t,s);throw new h(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new h(r,n,e,t,s)}return e}function f(e,r){const s=p(),i=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},s),r),{params:Object.assign(Object.assign({},s.params),r.params),headers:Object.assign(Object.assign({},s.headers),r.headers)}),{httpMethod:o,rawResponse:a}=i,g=Object.assign({f:"json"},i.params);let f=null;const m={method:o,signal:i.signal,credentials:i.credentials||"same-origin"};let T;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;T={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(l("Using an oAuth 2.0 access token directly in the token option is discouraged. Consider using ArcGISIdentityManager or Application session. See https://esriurl.com/arcgis-rest-js-direct-token-warning for more information."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else T=i.authentication;const k=e;return(T?T.getToken(e).catch((t=>(t.url=e,t.options=i,f=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),T&&T.getDomainCredentials&&(m.credentials=T.getDomainCredentials(e));const s={};if("GET"===m.method){g.token&&i.hideToken&&"undefined"==typeof window&&(s["X-Esri-Authorization"]=`Bearer ${g.token}`,delete g.token);const t=""===n(g)?e:e+"?"+n(g);i.maxUrlLength&&t.length>i.maxUrlLength||g.token&&i.hideToken?(m.method="POST",r.length&&i.hideToken&&(g.token=r,delete s["X-Esri-Authorization"])):e=t}const o=new RegExp("/items/.+/updateResources").test(e);return"POST"===m.method&&(m.body=c(g,o)),m.headers=Object.assign(Object.assign({},s),i.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer=d),t(g)||o||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,m):u().then((({fetch:t})=>t(e,m)))})).then((t=>{if(!t.ok)return t.json().then((r=>{const{status:s,statusText:n}=t,{message:o,details:a}=r.error,c=`${o}. ${a?a.join(" "):""}`.trim();throw new h(c,`HTTP ${s} ${n}`,r,e,i)})).catch((r=>{if("ArcGISRequestError"===r.name)throw r;const{status:s,statusText:n}=t;throw new h(n,`HTTP ${s}`,t,e,i)}));if(a)return t;switch(g.f){case"json":case"geojson":return t.json();case"html":case"text":return t.text();default:return t.blob()}})).then((t=>{if("json"!==g.f&&"geojson"!==g.f||a)return t;{const r=E(t,k,0,i,f);if(f){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},f=null}return r}}))}function m(e,t={params:{f:"json"}}){return f(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}var T,k;e.ArcGISTokenRequestErrorCodes=void 0,(T=e.ArcGISTokenRequestErrorCodes||(e.ArcGISTokenRequestErrorCodes={})).TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",T.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",T.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",T.NOT_FEDERATED="NOT_FEDERATED",T.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE";class w extends Error{constructor(t="UNKNOWN_ERROR",r=e.ArcGISTokenRequestErrorCodes.UNKNOWN_ERROR_CODE,s,n,i){super(t);const o=new.target.prototype;Object.setPrototypeOf(this,o),this.name="ArcGISTokenRequestError",this.message=`${r}: ${t}`,this.originalMessage=t,this.code=r,this.response=s,this.url=n,this.options=i}}class S extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}class _ extends Error{constructor(e="Unknown error",t){super(e);const r=new.target.prototype;Object.setPrototypeOf(this,r),this.name="ArcGISJobError",this.message=`${t.status}: ${e}`,this.status=t.status,this.id=t.id,this.jobInfo=t}}function R(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function O(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function A(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=O(t);return e[r]=s,e}),{})}e.ErrorTypes=void 0,(k=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",k.ArcGISAuthError="ArcGISAuthError",k.ArcGISAccessDeniedError="ArcGISAccessDeniedError",k.ArcGISTokenRequestError="ArcGISTokenRequestError";const b=3e5;function I(e,t){const r=t;return r.rawResponse=!1,m(e,r).then((e=>{if("token"in e&&"expires"in e)return{token:e.token,username:t.params.username,expires:new Date(e.expires)};const r={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-b),ssl:!0===e.ssl};return e.refresh_token&&(r.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(r.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-b)),r}))}class v{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new v(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(t){const r=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},t);return I(`${this.portal}/oauth2/token/`,r).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class U{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new U({key:e})}getToken(e){return Promise.resolve(this.key)}}const y=/^https?:\/\/(\S+)\.arcgis\.com.+/;function x(e){return y.test(e)}function D(e){if(!y.test(e))return e;switch(C(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function C(e){if(!y.test(e))return null;const t=e.match(y)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function j(e,t){const r=R(D(t)).replace(/https?:\/\//,""),s=R(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function N(e,t){const r=x(e),s=x(t),n=C(e),i=C(t);return!(!r||!s||n!==i)}function P(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function J(e){const t=`${R(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return m(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function F(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function M(e){!e&&window&&(e=window);return F(e.crypto.getRandomValues(new Uint8Array(32)))}class G{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?R(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.referer=e.referer,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:i,expiration:o,redirectUri:a,popup:c,popupWindowFeatures:h,locale:l,params:u,style:d,pkce:p,state:E}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),f=E||M(t),m=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(m,f);let T=`${R(r)}/oauth2/authorize`;const k={client_id:i,response_type:p?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:f,originalUrl:t.location.href}),locale:l,style:d};let w;if("arcgis"!==s&&(T=`${R(r)}/oauth2/social/authorize`,k.socialLoginProviderName=s,k.autoAccountCreateForSocial=!0),p){const e=M(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),w=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>F(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){k.code_challenge_method=t?"S256":"plain",k.code_challenge=t||e}))}else w=Promise.resolve();return w.then((()=>(T=`${T}?${n(k)}`,u&&(T=`${T}&${n(u)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new S;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new G({clientId:i,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(T,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=T))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i,redirectUri:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,c=t.localStorage.getItem(a),h=A(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),l=h&&h.state?JSON.parse(h.state):void 0;function u(e,r,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(i&&t.history.replaceState(t.history.state,"",i),"access_denied"===r?Promise.reject(new S):Promise.reject(new g(e,r)))}function d(e,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",i),new G({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:o||location.href.replace(location.search,"")}))}if(!c||!l)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(l.id!==c)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return u(h.error_description||"Unknown error",e,l.originalUrl)}if(i&&h.code){const e=R(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),I(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:o||location.href.replace(location.search,""),code:h.code}}).then((e=>d(Object.assign(Object.assign({},e),l),l.originalUrl))).catch((e=>u(e.originalMessage,e.code,l.originalUrl)))}return!i&&h.access_token?Promise.resolve(d(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},l),l.originalUrl)):u("Unknown error","oauth-error",l.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(G.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:s,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),c={client_id:s,expiration:i,response_type:"code",redirect_uri:o};a&&(c.state=a);const h=`${r}/oauth2/authorize?${n(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(t,r){const{portal:s,clientId:n,redirectUri:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},t);return I(`${s}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:n,redirect_uri:i,code:r}}).then((e=>new G({clientId:n,portal:s,ssl:e.ssl,redirectUri:i,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}static deserialize(e){const t=JSON.parse(e);return new G({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new G({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new G({portal:R(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new G(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return J({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new G(e);return t.getUser().then((()=>t))}static signIn(e){const t=new G(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=m(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=m(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return N(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>P(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(t){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(t):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new w("Unable to refresh token. No refresh token or password present.",e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=R(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[i,...o]=n.split("/");return`${s}${i.toLowerCase()}/${o.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return G.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(t,r){const s=this.getServerRootUrl(t),n=this.federatedServers[s];return n&&n.expires&&n.expires.getTime()>Date.now()?Promise.resolve(n.token):(this._pendingTokenRequests[s]||(this._pendingTokenRequests[s]=this.fetchAuthorizedDomains().then((()=>m(`${s}/rest/info`,{credentials:this.getDomainCredentials(t)}).then((n=>{if(n.owningSystemUrl){if(j(n.owningSystemUrl,this.portal))return m(`${n.owningSystemUrl}/sharing/rest/info`,r);throw new w(`${t} is not federated with ${this.portal}.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)}if(n.authInfo&&void 0!==this.federatedServers[s])return Promise.resolve({authInfo:n.authInfo});throw new w(`${t} is not federated with any portal and is not explicitly trusted.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))).then((e=>(this.federatedServers[s]=e,delete this._pendingTokenRequests[s],e.token)))))),this._pendingTokenRequests[s])}generateTokenForServer(t,r){return m(t,{params:{token:this.token,serverUrl:r,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.GENERATE_TOKEN_FOR_SERVER_FAILED,t.response,t.url,t.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(t){const r={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:this.referer?this.referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:d};return(this.server?m(`${this.getServerRootUrl(this.server)}/rest/info`).then((e=>m(e.authInfo.tokenServicesUrl,Object.assign({params:r},t)))):m(`${this.portal}/generateToken`,Object.assign({params:r},t))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshWithRefreshToken(t){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(t);const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>this.updateToken(e.token,e.expires))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(t){const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function q(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new G(e)}var $;q.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),G.beginOAuth2(...e)},q.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),G.completeOAuth2(...e)},q.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),G.fromParent(...e)},q.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),G.authorize(...e)},q.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),G.exchangeAuthorizationCode(...e)},q.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),G.fromCredential(...e)},q.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),G.deserialize(...e)},e.JOB_STATUSES=void 0,($=e.JOB_STATUSES||(e.JOB_STATUSES={})).Success="Succeeded",$.Failed="Failed",$.Waiting="Waiting",$.Cancelled="Cancelled",$.Cancelling="Cancelling",$.New="New",$.Executing="Executing",$.Submitted="Submitted",$.Failure="Failure",$.TimedOut="TimedOut",$.Error="Error",$.Status="Etatus",$.Unknown="Unknown";const H={pollingRate:2e3,startMonitoring:!1};class z{constructor(t){this.executePoll=async()=>{let t;try{t=await this.getJobInfo()}catch(t){return void this.emitter.emit(e.JOB_STATUSES.Error,t)}this.emitter.emit(e.JOB_STATUSES.Status,t),this.emitter.emit(t.status,t)};const{url:r,id:s,pollingRate:n,authentication:i}=Object.assign(Object.assign({},H),t);var o;this.url=r,this.id=s,this.authentication=i,this._pollingRate=n,this.emitter={all:o=o||new Map,on:function(e,t){var r=o.get(e);r?r.push(t):o.set(e,[t])},off:function(e,t){var r=o.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):o.set(e,[]))},emit:function(e,t){var r=o.get(e);r&&r.slice().map((function(e){e(t)})),(r=o.get("*"))&&r.slice().map((function(r){r(e,t)}))}},t.startMonitoring&&this.startEventMonitoring(n)}static deserialize(e,t){const r=Object.assign(Object.assign(Object.assign({},H),JSON.parse(e)),t);return m(`${r.url}/jobs/${r.id}`,{authentication:r.authentication}).then((()=>new z(r)))}static fromExistingJob(e){const t=Object.assign(Object.assign({},H),e);return m(`${R(t.url.replace(/\/submitJob\/?/,""))}/jobs/${t.id}`,{authentication:t.authentication}).then((()=>new z(t)))}static submitJob(e){const{url:t,params:r,authentication:s,pollingRate:n,startMonitoring:i}=Object.assign(Object.assign({},H),e),o=function(e){return Object.keys(e).reduce(((t,r)=>{const s=e[r],n=s.constructor.name;return t[r]="Array"===n?JSON.stringify(s):s,t}),{})}(r),a=R(t.replace(/\/submitJob\/?/,""));return m(a+"/submitJob",{params:o,authentication:s}).then((e=>new z({url:a,authentication:s,id:e.jobId,startMonitoring:i,pollingRate:n})))}get jobUrl(){return`${this.url}/jobs/${this.id}`}get isMonitoring(){return!!this.setIntervalHandler}get pollingRate(){return this._pollingRate}set pollingRate(e){this.stopEventMonitoring(),this.startEventMonitoring(e)}getJobInfo(){return m(this.jobUrl,{authentication:this.authentication}).then((t=>{const r=Object.assign({id:t.jobId,status:void 0},t);switch(delete r.jobId,delete r.jobStatus,t.jobStatus){case"esriJobCancelled":r.status=e.JOB_STATUSES.Cancelled;break;case"esriJobCancelling":r.status=e.JOB_STATUSES.Cancelling;break;case"esriJobNew":r.status=e.JOB_STATUSES.New;break;case"esriJobWaiting":r.status=e.JOB_STATUSES.Waiting;break;case"esriJobExecuting":r.status=e.JOB_STATUSES.Executing;break;case"esriJobSubmitted":r.status=e.JOB_STATUSES.Submitted;break;case"esriJobTimedOut":r.status=e.JOB_STATUSES.TimedOut;break;case"esriJobFailed":r.status=e.JOB_STATUSES.Failed;break;case"expectedFailure":r.status=e.JOB_STATUSES.Failure;break;case"esriJobSucceeded":r.status=e.JOB_STATUSES.Success}return r}))}on(e,t){this.emitter.on(e,t)}once(e,t){const r=s=>{this.emitter.off(e,r),t(s)};this.emitter.on(e,r),t.__arcgis_job_once_original_function__=r}off(e,t){t.__arcgis_job_once_original_function__?this.emitter.off(e,t.__arcgis_job_once_original_function__):this.emitter.off(e,t)}async getResult(e){return this.waitForCompletion().then((t=>m(this.jobUrl+"/"+t.results[e].paramUrl,{authentication:this.authentication})))}toJSON(){return{id:this.id,url:this.url,startMonitoring:this.isMonitoring,pollingRate:this.pollingRate}}serialize(){return JSON.stringify(this)}async waitForCompletion(){const t=await this.getJobInfo();return t.status===e.JOB_STATUSES.Success?Promise.resolve(t):t.status===e.JOB_STATUSES.Cancelling||t.status===e.JOB_STATUSES.Cancelled||t.status===e.JOB_STATUSES.Failed||t.status===e.JOB_STATUSES.Failure||t.status===e.JOB_STATUSES.TimedOut?(this.stopInternalEventMonitoring(),Promise.reject(new _("Job cancelled or failed.",t))):new Promise(((t,r)=>{this.startInternalEventMonitoring(),this.once(e.JOB_STATUSES.Cancelled,(e=>{this.stopInternalEventMonitoring(),r(new _("Job cancelled.",e))})),this.once(e.JOB_STATUSES.TimedOut,(e=>{this.stopInternalEventMonitoring(),r(new _("Job timed out.",e))})),this.once(e.JOB_STATUSES.Failed,(e=>{this.stopInternalEventMonitoring(),r(new _("Job failed.",e))})),this.once(e.JOB_STATUSES.Success,(e=>{this.stopInternalEventMonitoring(),t(e)}))}))}async getAllResults(){return this.waitForCompletion().then((e=>{const t=Object.keys(e.results),r=t.map((t=>m(this.jobUrl+"/"+e.results[t].paramUrl,{authentication:this.authentication}).then((e=>e))));return Promise.all(r).then((e=>t.reduce(((r,s,n)=>(r[t[n]]=e[n],r)),{})))}))}cancelJob(){return m(this.jobUrl+"/cancel",{authentication:this.authentication,params:{id:this.id,returnMessages:!1}}).then((e=>(this.emitter.emit("cancelled",e),e)))}startInternalEventMonitoring(e=H.pollingRate){this._pollingRate=e,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopInternalEventMonitoring(){this.isMonitoring&&!this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}startEventMonitoring(e=H.pollingRate){this._pollingRate=e,this.didUserEnableMonitoring=!0,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopEventMonitoring(){this.isMonitoring&&this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}}e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new U(e)},e.ApiKeyManager=U,e.ApplicationCredentialsManager=v,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)},e.ArcGISAccessDeniedError=S,e.ArcGISAuthError=g,e.ArcGISIdentityManager=G,e.ArcGISJobError=_,e.ArcGISRequestError=h,e.ArcGISTokenRequestError=w,e.Blob=a,e.File=o,e.FormData=i,e.Job=z,e.NODEJS_DEFAULT_REFERER_HEADER=d,e.UserSession=q,e.appendCustomParams=function(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})},e.canUseOnlineToken=N,e.checkForErrors=E,e.cleanUrl=R,e.decodeParam=O,e.decodeQueryString=A,e.encodeFormData=c,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=I,e.getDefaultRequestOptions=p,e.getFetch=u,e.getOnlineEnvironment=C,e.internalRequest=f,e.isFederated=j,e.isOnline=x,e.normalizeOnlinePortalUrl=D,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})},e.processParams=r,e.request=m,e.requiresFormData=t,e.revokeToken=J,e.setDefaultRequestOptions=function(e,t){e.authentication&&!t&&l("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e},e.validateAppAccess=P,e.warn=l,e.withOptions=function(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}},Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=request.umd.min.js.map

@@ -321,6 +321,24 @@ "use strict";

.then((response) => {
// the request got back an error status code (4xx, 5xx)
if (!response.ok) {
// server responded w/ an actual error (404, 500, etc)
const { status, statusText } = response;
throw new ArcGISRequestError_js_1.ArcGISRequestError(statusText, `HTTP ${status}`, response, url, options);
// we need to determine if the server returned a JSON body with more details.
// this is the format used by newer services such as the Places and Style service.
return response
.json()
.then((jsonError) => {
// The body can be parsed as JSON
const { status, statusText } = response;
const { message, details } = jsonError.error;
const formattedMessage = `${message}. ${details ? details.join(" ") : ""}`.trim();
throw new ArcGISRequestError_js_1.ArcGISRequestError(formattedMessage, `HTTP ${status} ${statusText}`, jsonError, url, options);
})
.catch((e) => {
// if we already were about to format this as an ArcGISRequestError throw that error
if (e.name === "ArcGISRequestError") {
throw e;
}
// server responded w/ an actual error (404, 500, etc) but we could not parse it as JSON
const { status, statusText } = response;
throw new ArcGISRequestError_js_1.ArcGISRequestError(statusText, `HTTP ${status}`, response, url, options);
});
}

@@ -345,2 +363,4 @@ if (rawResponse) {

.then((data) => {
// Check for an error in the JSON body of a successful response.
// Most ArcGIS Server services will return a successful status code but include an error in the response body.
if ((params.f === "json" || params.f === "geojson") && !rawResponse) {

@@ -347,0 +367,0 @@ const response = checkForErrors(data, originalUrl, params, options, originalAuthError);

@@ -314,6 +314,24 @@ /* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.

.then((response) => {
// the request got back an error status code (4xx, 5xx)
if (!response.ok) {
// server responded w/ an actual error (404, 500, etc)
const { status, statusText } = response;
throw new ArcGISRequestError(statusText, `HTTP ${status}`, response, url, options);
// we need to determine if the server returned a JSON body with more details.
// this is the format used by newer services such as the Places and Style service.
return response
.json()
.then((jsonError) => {
// The body can be parsed as JSON
const { status, statusText } = response;
const { message, details } = jsonError.error;
const formattedMessage = `${message}. ${details ? details.join(" ") : ""}`.trim();
throw new ArcGISRequestError(formattedMessage, `HTTP ${status} ${statusText}`, jsonError, url, options);
})
.catch((e) => {
// if we already were about to format this as an ArcGISRequestError throw that error
if (e.name === "ArcGISRequestError") {
throw e;
}
// server responded w/ an actual error (404, 500, etc) but we could not parse it as JSON
const { status, statusText } = response;
throw new ArcGISRequestError(statusText, `HTTP ${status}`, response, url, options);
});
}

@@ -338,2 +356,4 @@ if (rawResponse) {

.then((data) => {
// Check for an error in the JSON body of a successful response.
// Most ArcGIS Server services will return a successful status code but include an error in the response body.
if ((params.f === "json" || params.f === "geojson") && !rawResponse) {

@@ -340,0 +360,0 @@ const response = checkForErrors(data, originalUrl, params, options, originalAuthError);

{
"name": "@esri/arcgis-rest-request",
"version": "4.1.4",
"version": "4.2.0",
"description": "Common methods and utilities for @esri/arcgis-rest-js packages.",

@@ -52,2 +52,5 @@ "license": "Apache-2.0",

},
"devDependencies": {
"@types/serialize-javascript": "^5.0.2"
},
"contributors": [

@@ -75,6 +78,3 @@ "Patrick Arlt <parlt@esri.com> (http://patrickarlt.com/)"

]
},
"devDependencies": {
"@types/serialize-javascript": "^5.0.2"
}
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc