@esri/arcgis-rest-request
Advanced tools
Comparing version 4.0.0-beta.5 to 4.0.0-beta.6
/* @preserve | ||
* @esri/arcgis-rest-request - v4.0.0-beta.4 - Apache-2.0 | ||
* @esri/arcgis-rest-request - v4.0.0-beta.5 - Apache-2.0 | ||
* Copyright (c) 2017-2022 Esri, Inc. | ||
* Wed Mar 16 2022 17:43:24 GMT+0000 (Coordinated Universal Time) | ||
* Tue Mar 22 2022 19:12:08 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 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 c(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 p(e,t){e.authentication&&!t&&c("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 d(){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}`}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 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||"GWM_0003"===o||400===i&&"Unable to generate token."===r)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 m(t,r){const n=d(),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:u}=i,p=Object.assign({f:"json"},i.params);let g=null;const m={method:o,credentials:i.credentials||"same-origin"};let k;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&t.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||(c("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 w=t;return(k?k.getToken(t).catch((e=>(e.url=t,e.options=i,g=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(p.token=r),k&&k.getDomainCredentials&&(m.credentials=k.getDomainCredentials(t));const n={};if("GET"===m.method){p.token&&i.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${p.token}`,delete p.token);const e=""===s(p)?t:t+"?"+s(p);i.maxUrlLength&&e.length>i.maxUrlLength||p.token&&i.hideToken?(m.method="POST",r.length&&i.hideToken&&(p.token=r,delete n["X-Esri-Authorization"])):t=e}const o=new RegExp("/items/.+/updateResources").test(t);return"POST"===m.method&&(m.body=a(p,o)),m.headers=Object.assign(Object.assign({},n),i.headers),"undefined"!=typeof window||m.headers.referer||(m.headers.referer="@esri/arcgis-rest-js"),e(p)||o||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,m):l().then((({fetch:e})=>e(t,m)))})).then((e=>{if(!e.ok){const{status:r,statusText:s}=e;throw new h(s,`HTTP ${r}`,e,t,i)}if(u)return e;switch(p.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==p.f&&"geojson"!==p.f||u)return e;{const r=f(e,w,0,i,g);if(g){const e=t.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[e]={token:[],expires:new Date(Date.now()+864e5)},g=null}return r}}))}function k(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&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])&&(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)),{})}class T extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function _(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function E(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function R(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=E(t);return e[r]=s,e}),{})}var x;!function(e){e.ArcGISRequestError="ArcGISRequestError",e.ArcGISAuthError="ArcGISAuthError",e.ArcGISAccessDeniedError="ArcGISAccessDeniedError"}(x||(x={}));function O(e,t){const r=t;return r.rawResponse=!1,k(e,r).then((e=>{const t={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-3e5),ssl:!0===e.ssl};return e.refresh_token&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-3e5)),t}))}class S{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 S(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 O(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token)))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function v(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new S(e)}class y{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new y({key:e})}getToken(e){return Promise.resolve(this.key)}}function A(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)}function I(e,t){const r=t;return"undefined"!=typeof window&&window.location&&window.location.host?r.params.referer=window.location.host:r.params.referer="@esri/arcgis-rest-js",k(e,r)}const b=/^https?:\/\/(\S+)\.arcgis\.com.+/;function U(e){return b.test(e)}function D(e){if(!b.test(e))return e;switch(j(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 j(e){if(!b.test(e))return null;const t=e.match(b)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function P(e,t){const r=_(D(t)).replace(/https?:\/\//,""),s=_(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function C(e,t){const r=U(e),s=U(t),n=j(e),i=j(t);return!(!r||!s||n!==i)}function N(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function $(e){const t=`${_(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 k(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function q(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 q(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?_(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.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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:i,expiration:o,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:p,pkce:d,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||M(t),k=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(k,m);let w=`${_(r)}/oauth2/authorize`;const E={client_id:i,response_type:d?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:p};let R;if("arcgis"!==n&&(w=`${_(r)}/oauth2/social/authorize`,E.socialLoginProviderName=n,E.autoAccountCreateForSocial=!0),d){const e=M(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),R=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=>q(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){E.code_challenge_method=t?"S256":"plain",E.code_challenge=t||e}))}else R=Promise.resolve();return R.then((()=>(w=`${w}?${s(E)}`,u&&(w=`${w}&${s(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new T;return s(e),e}if(t.detail.error){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}))}),{once:!0}),t.open(w,"oauth-window",c),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}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),o=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(o),h=R(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,i){return t.localStorage.removeItem(o),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 T):Promise.reject(new g(e,r)))}function u(e,i){return t.localStorage.removeItem(o),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}))}if(!a||!c)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)return l("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return l(h.error_description||"Unknown error",e,c.originalUrl)}if(i&&h.code){const e=_(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),O(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>u(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>l(e.message,e.error,c.originalUrl)))}return!i&&h.access_token?Promise.resolve(u(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):l("Unknown error","oauth-error",c.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:n,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),h={client_id:n,expiration:i,response_type:"code",redirect_uri:o};a&&(h.state=a);const c=`${r}/oauth2/authorize?${s(h)}`;t.writeHead(301,{Location:c}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},e);return O(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new G({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username})))}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){const t=void 0===e.ssl||e.ssl,r=e.expires||Date.now()+72e5;return new G({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:t,token:e.token,username:e.userId,tokenExpires:new Date(r)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return G.fromCredential(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 $({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.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=k(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=k(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 C(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=>N(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 g("Unable to refresh token."))}getServerRootUrl(e){const[t]=_(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){const t=this.toCredential();t.server=t.server.replace("/sharing/rest",""),e={type:"arcgis:auth:credential",credential:t}}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((()=>k(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(P(s.owningSystemUrl,this.portal))return k(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new g(`${e} is not federated with ${this.portal}.`,"NOT_FEDERATED")}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new g(`${e} is not federated with any portal and is not explicitly trusted.`,"NOT_FEDERATED")})).then((e=>e.authInfo.tokenServicesUrl)).then((t=>this.token&&this.tokenExpires.getTime()>Date.now()?I(t,{params:{token:this.token,serverUrl:e,expiration:this.tokenDuration,client:"referer"}}):I(t,{params:{username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer"}}).then((e=>(this.updateToken(e.token,new Date(e.expires)),e))))).then((e=>(this.federatedServers[r]={expires:new Date(e.expires),token:e.token},delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}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((e=>(this._pendingTokenRequests[this.portal]=null,e.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t=Object.assign({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return I(`${this.portal}/generateToken`,t).then((e=>(this.updateToken(e.token,new Date(e.expires)),this)))}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 O(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires)))}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 O(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this)))}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 W(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new G(e)}function z(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))}function F(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})}export{A as ApiKey,y as ApiKeyManager,S as ApplicationCredentialsManager,v as ApplicationSession,T as ArcGISAccessDeniedError,g as ArcGISAuthError,G as ArcGISIdentityManager,h as ArcGISRequestError,o as Blob,x as ErrorTypes,i as File,n as FormData,u as NODEJS_DEFAULT_REFERER_HEADER,W as UserSession,w as appendCustomParams,C as canUseOnlineToken,f as checkForErrors,_ as cleanUrl,E as decodeParam,R as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,z as exchangeToken,O as fetchToken,I as generateToken,d as getDefaultRequestOptions,l as getFetch,j as getOnlineEnvironment,m as internalRequest,P as isFederated,U as isOnline,D as normalizeOnlinePortalUrl,F as platformSelf,t as processParams,k as request,e as requiresFormData,$ as revokeToken,p as setDefaultRequestOptions,N as validateAppAccess,c as warn}; | ||
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 o=e[r];if(o&&o.toParam&&(o=o.toParam()),!o&&0!==o&&"boolean"!=typeof o&&"string"!=typeof o)return;let i;switch(o.constructor.name){case"Array":const e=null===(n=null===(s=o[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;i="Array"===e?o:"Object"===e?JSON.stringify(o):o.join(",");break;case"Object":i=JSON.stringify(o);break;case"Date":i=o.valueOf();break;case"Function":i=null;break;case"Boolean":i=o+"";break;default:i=o}(i||0===i||"string"==typeof i||Array.isArray(i))&&(t[r]=i)})),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,o=globalThis.File,i=globalThis.Blob;function a(r,o){const i=e(r)||o,a=t(r);if(i){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 h extends Error{constructor(e,t,r,s,n){super(e);const o=new.target.prototype;Object.setPrototypeOf(this,o),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 c(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 p(e,t){e.authentication&&!t&&c("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 d(){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 o=new.target.prototype;Object.setPrototypeOf(this,o)}retry(e,t=1){let r=0;const s=(n,o)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return k(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,o):e.name===this.name&&e.message===this.message&&r>=t?o(this):o(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 h(r,n,e,t,s)}if(e.error){const{message:r,code:o,messageCode:i}=e.error,a=i||o||"UNKNOWN_ERROR_CODE";if(498===o||499===o||"GWM_0003"===i||400===o&&"Unable to generate token."===r)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 k(t,r){const n=d(),o=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:i,rawResponse:u}=o,p=Object.assign({f:"json"},o.params);let g=null;const k={method:i,credentials:o.credentials||"same-origin"};let m;if(o.headers&&o.headers["X-Esri-Auth-Client-Id"]&&t.indexOf("/oauth2/platformSelf")>-1&&(k.credentials="include"),"string"==typeof o.authentication){const e=o.authentication;m={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},o.authentication.startsWith("AAPK")||o.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(c("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 m=o.authentication;const w=t;return(m?m.getToken(t).catch((e=>(e.url=t,e.options=o,g=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(p.token=r),m&&m.getDomainCredentials&&(k.credentials=m.getDomainCredentials(t));const n={};if("GET"===k.method){p.token&&o.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${p.token}`,delete p.token);const e=""===s(p)?t:t+"?"+s(p);o.maxUrlLength&&e.length>o.maxUrlLength||p.token&&o.hideToken?(k.method="POST",r.length&&o.hideToken&&(p.token=r,delete n["X-Esri-Authorization"])):t=e}const i=new RegExp("/items/.+/updateResources").test(t);return"POST"===k.method&&(k.body=a(p,i)),k.headers=Object.assign(Object.assign({},n),o.headers),("undefined"==typeof window||window&&void 0===window.document)&&!k.headers.referer&&(k.headers.referer="@esri/arcgis-rest-js"),e(p)||i||(k.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,k):l().then((({fetch:e})=>e(t,k)))})).then((e=>{if(!e.ok){const{status:r,statusText:s}=e;throw new h(s,`HTTP ${r}`,e,t,o)}if(u)return e;switch(p.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==p.f&&"geojson"!==p.f||u)return e;{const r=f(e,w,0,o,g);if(g){const e=t.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];o.authentication.federatedServers[e]={token:[],expires:new Date(Date.now()+864e5)},g=null}return r}}))}function m(e,t={params:{f:"json"}}){return k(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&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])&&(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 E,_;!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"}(E||(E={}));class T extends Error{constructor(e="UNKNOWN_ERROR",t=E.UNKNOWN_ERROR_CODE,r,s,n){super(e);const o=new.target.prototype;Object.setPrototypeOf(this,o),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"}}function O(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 v(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"}(_||(_={}));function A(e,t){const r=t;return r.rawResponse=!1,m(e,r).then((e=>{const t={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-3e5),ssl:!0===e.ssl};return e.refresh_token&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-3e5)),t}))}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 A(`${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,E.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function I(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new x(e)}class y{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new y({key:e})}getToken(e){return Promise.resolve(this.key)}}function D(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)}const b=/^https?:\/\/(\S+)\.arcgis\.com.+/;function U(e){return b.test(e)}function N(e){if(!b.test(e))return e;switch(j(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 j(e){if(!b.test(e))return null;const t=e.match(b)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function C(e,t){const r=O(N(t)).replace(/https?:\/\//,""),s=O(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function P(e,t){const r=U(e),s=U(t),n=j(e),o=j(t);return!(!r||!s||n!==o)}function F(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 $(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 q(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function G(e){!e&&window&&(e=window);return q(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?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.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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:o,expiration:i,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:p,pkce:d,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),k=f||G(t),m=`ARCGIS_REST_JS_AUTH_STATE_${o}`;t.localStorage.setItem(m,k);let w=`${O(r)}/oauth2/authorize`;const E={client_id:o,response_type:d?"code":"token",expiration:i,redirect_uri:a,state:JSON.stringify({id:k,originalUrl:t.location.href}),locale:l,style:p};let _;if("arcgis"!==n&&(w=`${O(r)}/oauth2/social/authorize`,E.socialLoginProviderName=n,E.autoAccountCreateForSocial=!0),d){const e=G(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${o}`;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=>q(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){E.code_challenge_method=t?"S256":"plain",E.code_challenge=t||e}))}else _=Promise.resolve();return _.then((()=>(w=`${w}?${s(E)}`,u&&(w=`${w}&${s(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${o}`,(t=>{if("access_denied"===t.detail.error){const e=new R;return s(e),e}if(t.detail.error){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new H({clientId:o,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}))}),{once:!0}),t.open(w,"oauth-window",c),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:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),i=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(i),h=v(o?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,o){return t.localStorage.removeItem(i),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(o&&t.history.replaceState(t.history.state,"",o),"access_denied"===r?Promise.reject(new R):Promise.reject(new g(e,r)))}function u(e,o){return t.localStorage.removeItem(i),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,"",o),new H({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires}))}if(!a||!c)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)return l("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return l(h.error_description||"Unknown error",e,c.originalUrl)}if(o&&h.code){const e=O(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,o=t.localStorage.getItem(n);return t.localStorage.removeItem(n),A(e,{httpMethod:"POST",params:{client_id:s,code_verifier:o,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>u(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>l(e.message,e.error,c.originalUrl)))}return!o&&h.access_token?Promise.resolve(u(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):l("Unknown error","oauth-error",c.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:o,redirectUri:i,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),h={client_id:n,expiration:o,response_type:"code",redirect_uri:i};a&&(h.state=a);const c=`${r}/oauth2/authorize?${s(h)}`;t.writeHead(301,{Location:c}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},e);return A(`${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,E.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: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 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 $({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=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 P(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=>F(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.",E.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=O(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[o,...i]=n.split("/");return`${s}${o.toLowerCase()}/${i.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((()=>m(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(C(s.owningSystemUrl,this.portal))return m(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new T(`${e} is not federated with ${this.portal}.`,E.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.`,E.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 m(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,E.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:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:"@esri/arcgis-rest-js"};return(this.server?m(`${this.getServerRootUrl(this.server)}/rest/info`).then((r=>m(r.authInfo.tokenServicesUrl,Object.assign({params:t},e)))):m(`${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,E.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 A(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires))).catch((e=>{throw new T(e.message,E.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 A(`${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,E.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 M(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new H(e)}function K(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))}function L(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"}})}export{D as ApiKey,y as ApiKeyManager,x as ApplicationCredentialsManager,I as ApplicationSession,R as ArcGISAccessDeniedError,g as ArcGISAuthError,H as ArcGISIdentityManager,h as ArcGISRequestError,T as ArcGISTokenRequestError,E as ArcGISTokenRequestErrorCodes,i as Blob,_ as ErrorTypes,o as File,n as FormData,u as NODEJS_DEFAULT_REFERER_HEADER,M as UserSession,w as appendCustomParams,P as canUseOnlineToken,f as checkForErrors,O as cleanUrl,S as decodeParam,v as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,K as exchangeToken,A as fetchToken,d as getDefaultRequestOptions,l as getFetch,j as getOnlineEnvironment,k as internalRequest,C as isFederated,U as isOnline,N as normalizeOnlinePortalUrl,L as platformSelf,t as processParams,m as request,e as requiresFormData,$ as revokeToken,p as setDefaultRequestOptions,F as validateAppAccess,c as warn}; | ||
//# sourceMappingURL=request.esm.min.js.map |
/* @preserve | ||
* @esri/arcgis-rest-request - v4.0.0-beta.4 - Apache-2.0 | ||
* @esri/arcgis-rest-request - v4.0.0-beta.5 - Apache-2.0 | ||
* Copyright (c) 2017-2022 Esri, Inc. | ||
* Wed Mar 16 2022 17:43:24 GMT+0000 (Coordinated Universal Time) | ||
* Tue Mar 22 2022 19:12:08 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 h(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 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 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 p="@esri/arcgis-rest-js";function d(){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}`}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||"GWM_0003"===o||400===i&&"Unable to generate token."===r)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(e,r){const s=d(),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 m=null;const k={method:o,credentials:i.credentials||"same-origin"};let w;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(k.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||(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 w=i.authentication;const T=e;return(w?w.getToken(e).catch((t=>(t.url=e,t.options=i,m=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),w&&w.getDomainCredentials&&(k.credentials=w.getDomainCredentials(e));const s={};if("GET"===k.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?(k.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"===k.method&&(k.body=h(g,o)),k.headers=Object.assign(Object.assign({},s),i.headers),"undefined"!=typeof window||k.headers.referer||(k.headers.referer=p),t(g)||o||(k.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,k):u().then((({fetch:t})=>t(e,k)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new c(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=f(t,T,0,i,m);if(m){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},m=null}return r}}))}function k(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}class w extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function T(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function _(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function E(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=_(t);return e[r]=s,e}),{})}var R;e.ErrorTypes=void 0,(R=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",R.ArcGISAuthError="ArcGISAuthError",R.ArcGISAccessDeniedError="ArcGISAccessDeniedError";const O=3e5;function S(e,t){const r=t;return r.rawResponse=!1,k(e,r).then((e=>{const t={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-O),ssl:!0===e.ssl};return e.refresh_token&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-O)),t}))}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 S(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token)))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class v{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new v({key:e})}getToken(e){return Promise.resolve(this.key)}}function y(e,t){const r=t;return"undefined"!=typeof window&&window.location&&window.location.host?r.params.referer=window.location.host:r.params.referer=p,k(e,r)}const A=/^https?:\/\/(\S+)\.arcgis\.com.+/;function I(e){return A.test(e)}function b(e){if(!A.test(e))return e;switch(D(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 D(e){if(!A.test(e))return null;const t=e.match(A)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function U(e,t){const r=T(b(t)).replace(/https?:\/\//,""),s=T(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function P(e,t){const r=I(e),s=I(t),n=D(e),i=D(t);return!(!r||!s||n!==i)}function j(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function C(e){const t=`${T(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 k(t,n).then((e=>{if(!e.success)throw new c("Unable to revoke token",500,e,t,n);return e}))}function N(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(e){!e&&window&&(e=window);return N(e.crypto.getRandomValues(new Uint8Array(32)))}class q{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?T(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.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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:i,expiration:o,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:p,pkce:d,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||$(t),k=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(k,m);let _=`${T(r)}/oauth2/authorize`;const E={client_id:i,response_type:d?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:p};let R;if("arcgis"!==s&&(_=`${T(r)}/oauth2/social/authorize`,E.socialLoginProviderName=s,E.autoAccountCreateForSocial=!0),d){const e=$(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),R=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=>N(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){E.code_challenge_method=t?"S256":"plain",E.code_challenge=t||e}))}else R=Promise.resolve();return R.then((()=>(_=`${_}?${n(E)}`,u&&(_=`${_}&${n(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new w;return s(e),e}if(t.detail.error){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new q({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}))}),{once:!0}),t.open(_,"oauth-window",c),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=_))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),o=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(o),h=E(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,i){return t.localStorage.removeItem(o),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 w):Promise.reject(new g(e,r)))}function u(e,i){return t.localStorage.removeItem(o),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 q({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires}))}if(!a||!c)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)return l("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return l(h.error_description||"Unknown error",e,c.originalUrl)}if(i&&h.code){const e=T(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),S(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>u(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>l(e.message,e.error,c.originalUrl)))}return!i&&h.access_token?Promise.resolve(u(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):l("Unknown error","oauth-error",c.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(q.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),h={client_id:s,expiration:i,response_type:"code",redirect_uri:o};a&&(h.state=a);const c=`${r}/oauth2/authorize?${n(h)}`;t.writeHead(301,{Location:c}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},e);return S(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new q({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username})))}static deserialize(e){const t=JSON.parse(e);return new q({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){const t=void 0===e.ssl||e.ssl,r=e.expires||Date.now()+72e5;return new q({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:t,token:e.token,username:e.userId,tokenExpires:new Date(r)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return q.fromCredential(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 C({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new q(e);return t.getUser().then((()=>t))}static signIn(e){const t=new q(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),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=k(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=k(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 P(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=>j(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 g("Unable to refresh token."))}getServerRootUrl(e){const[t]=T(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 q.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){const t=this.toCredential();t.server=t.server.replace("/sharing/rest",""),e={type:"arcgis:auth:credential",credential:t}}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((()=>k(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(U(s.owningSystemUrl,this.portal))return k(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new g(`${e} is not federated with ${this.portal}.`,"NOT_FEDERATED")}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new g(`${e} is not federated with any portal and is not explicitly trusted.`,"NOT_FEDERATED")})).then((e=>e.authInfo.tokenServicesUrl)).then((t=>this.token&&this.tokenExpires.getTime()>Date.now()?y(t,{params:{token:this.token,serverUrl:e,expiration:this.tokenDuration,client:"referer"}}):y(t,{params:{username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer"}}).then((e=>(this.updateToken(e.token,new Date(e.expires)),e))))).then((e=>(this.federatedServers[r]={expires:new Date(e.expires),token:e.token},delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}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((e=>(this._pendingTokenRequests[this.portal]=null,e.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t=Object.assign({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return y(`${this.portal}/generateToken`,t).then((e=>(this.updateToken(e.token,new Date(e.expires)),this)))}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 S(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires)))}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 S(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this)))}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)))}}e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new v(e)},e.ApiKeyManager=v,e.ApplicationCredentialsManager=x,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new x(e)},e.ArcGISAccessDeniedError=w,e.ArcGISAuthError=g,e.ArcGISIdentityManager=q,e.ArcGISRequestError=c,e.Blob=a,e.File=o,e.FormData=i,e.NODEJS_DEFAULT_REFERER_HEADER=p,e.UserSession=function(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new q(e)},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])&&(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=P,e.checkForErrors=f,e.cleanUrl=T,e.decodeParam=_,e.decodeQueryString=E,e.encodeFormData=h,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=S,e.generateToken=y,e.getDefaultRequestOptions=d,e.getFetch=u,e.getOnlineEnvironment=D,e.internalRequest=m,e.isFederated=U,e.isOnline=I,e.normalizeOnlinePortalUrl=b,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${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=k,e.requiresFormData=t,e.revokeToken=C,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=j,e.warn=l,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 o=e[r];if(o&&o.toParam&&(o=o.toParam()),!o&&0!==o&&"boolean"!=typeof o&&"string"!=typeof o)return;let i;switch(o.constructor.name){case"Array":const e=null===(n=null===(s=o[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;i="Array"===e?o:"Object"===e?JSON.stringify(o):o.join(",");break;case"Object":i=JSON.stringify(o);break;case"Date":i=o.valueOf();break;case"Function":i=null;break;case"Boolean":i=o+"";break;default:i=o}(i||0===i||"string"==typeof i||Array.isArray(i))&&(t[r]=i)})),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 o=globalThis.FormData,i=globalThis.File,a=globalThis.Blob;function h(e,s){const i=t(e)||s,a=r(e);if(i){const e=new o;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 c extends Error{constructor(e,t,r,s,n){super(e);const o=new.target.prototype;Object.setPrototypeOf(this,o),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 u(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 p="@esri/arcgis-rest-js";function d(){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 o=new.target.prototype;Object.setPrototypeOf(this,o)}retry(e,t=1){let r=0;const s=(n,o)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return k(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,o):e.name===this.name&&e.message===this.message&&r>=t?o(this):o(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:o,messageCode:i}=e.error,a=i||o||"UNKNOWN_ERROR_CODE";if(498===o||499===o||"GWM_0003"===i||400===o&&"Unable to generate token."===r)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 k(e,r){const s=d(),o=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:i,rawResponse:a}=o,g=Object.assign({f:"json"},o.params);let k=null;const E={method:i,credentials:o.credentials||"same-origin"};let m;if(o.headers&&o.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(E.credentials="include"),"string"==typeof o.authentication){const e=o.authentication;m={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},o.authentication.startsWith("AAPK")||o.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(u("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 m=o.authentication;const w=e;return(m?m.getToken(e).catch((t=>(t.url=e,t.options=o,k=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),m&&m.getDomainCredentials&&(E.credentials=m.getDomainCredentials(e));const s={};if("GET"===E.method){g.token&&o.hideToken&&"undefined"==typeof window&&(s["X-Esri-Authorization"]=`Bearer ${g.token}`,delete g.token);const t=""===n(g)?e:e+"?"+n(g);o.maxUrlLength&&t.length>o.maxUrlLength||g.token&&o.hideToken?(E.method="POST",r.length&&o.hideToken&&(g.token=r,delete s["X-Esri-Authorization"])):e=t}const i=new RegExp("/items/.+/updateResources").test(e);return"POST"===E.method&&(E.body=h(g,i)),E.headers=Object.assign(Object.assign({},s),o.headers),("undefined"==typeof window||window&&void 0===window.document)&&!E.headers.referer&&(E.headers.referer=p),t(g)||i||(E.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,E):l().then((({fetch:t})=>t(e,E)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new c(s,`HTTP ${r}`,t,e,o)}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=f(t,w,0,o,k);if(k){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];o.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},k=null}return r}}))}function E(e,t={params:{f:"json"}}){return k(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}var m,w;e.ArcGISTokenRequestErrorCodes=void 0,(m=e.ArcGISTokenRequestErrorCodes||(e.ArcGISTokenRequestErrorCodes={})).TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",m.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",m.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",m.NOT_FEDERATED="NOT_FEDERATED",m.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE";class _ extends Error{constructor(t="UNKNOWN_ERROR",r=e.ArcGISTokenRequestErrorCodes.UNKNOWN_ERROR_CODE,s,n,o){super(t);const i=new.target.prototype;Object.setPrototypeOf(this,i),this.name="ArcGISTokenRequestError",this.message=`${r}: ${t}`,this.originalMessage=t,this.code=r,this.response=s,this.url=n,this.options=o}}class T extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function R(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 O(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}),{})}e.ErrorTypes=void 0,(w=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",w.ArcGISAuthError="ArcGISAuthError",w.ArcGISAccessDeniedError="ArcGISAccessDeniedError",w.ArcGISTokenRequestError="ArcGISTokenRequestError";const A=3e5;function I(e,t){const r=t;return r.rawResponse=!1,E(e,r).then((e=>{const t={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&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-A)),t}))}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 _(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class x{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new x({key:e})}getToken(e){return Promise.resolve(this.key)}}const y=/^https?:\/\/(\S+)\.arcgis\.com.+/;function D(e){return y.test(e)}function b(e){if(!y.test(e))return e;switch(U(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 U(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 C(e,t){const r=R(b(t)).replace(/https?:\/\//,""),s=R(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function N(e,t){const r=D(e),s=D(t),n=U(e),o=U(t);return!(!r||!s||n!==o)}function j(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 P(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 E(t,n).then((e=>{if(!e.success)throw new c("Unable to revoke token",500,e,t,n);return e}))}function q(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function F(e){!e&&window&&(e=window);return q(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.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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:o,expiration:i,redirectUri:a,popup:h,popupWindowFeatures:c,locale:u,params:l,style:p,pkce:d,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),k=f||F(t),E=`ARCGIS_REST_JS_AUTH_STATE_${o}`;t.localStorage.setItem(E,k);let m=`${R(r)}/oauth2/authorize`;const w={client_id:o,response_type:d?"code":"token",expiration:i,redirect_uri:a,state:JSON.stringify({id:k,originalUrl:t.location.href}),locale:u,style:p};let _;if("arcgis"!==s&&(m=`${R(r)}/oauth2/social/authorize`,w.socialLoginProviderName=s,w.autoAccountCreateForSocial=!0),d){const e=F(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${o}`;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=>q(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){w.code_challenge_method=t?"S256":"plain",w.code_challenge=t||e}))}else _=Promise.resolve();return _.then((()=>(m=`${m}?${n(w)}`,l&&(m=`${m}&${n(l)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${o}`,(t=>{if("access_denied"===t.detail.error){const e=new T;return s(e),e}if(t.detail.error){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new G({clientId:o,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}))}),{once:!0}),t.open(m,"oauth-window",c),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=m))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),i=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(i),h=O(o?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function u(e,r,o){return t.localStorage.removeItem(i),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(o&&t.history.replaceState(t.history.state,"",o),"access_denied"===r?Promise.reject(new T):Promise.reject(new g(e,r)))}function l(e,o){return t.localStorage.removeItem(i),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,"",o),new G({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires}))}if(!a||!c)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)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,c.originalUrl)}if(o&&h.code){const e=R(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,o=t.localStorage.getItem(n);return t.localStorage.removeItem(n),I(e,{httpMethod:"POST",params:{client_id:s,code_verifier:o,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>l(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>u(e.message,e.error,c.originalUrl)))}return!o&&h.access_token?Promise.resolve(l(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):u("Unknown error","oauth-error",c.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:o,redirectUri:i,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),h={client_id:s,expiration:o,response_type:"code",redirect_uri:i};a&&(h.state=a);const c=`${r}/oauth2/authorize?${n(h)}`;t.writeHead(301,{Location:c}),t.end()}static exchangeAuthorizationCode(t,r){const{portal:s,clientId:n,redirectUri:o}=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:o,code:r}}).then((e=>new G({clientId:n,portal:s,ssl:e.ssl,redirectUri:o,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((t=>{throw new _(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 P({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=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 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=>j(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 _("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?:\/\/)(.+)/),[o,...i]=n.split("/");return`${s}${o.toLowerCase()}/${i.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((()=>E(`${s}/rest/info`,{credentials:this.getDomainCredentials(t)}).then((n=>{if(n.owningSystemUrl){if(C(n.owningSystemUrl,this.portal))return E(`${n.owningSystemUrl}/sharing/rest/info`,r);throw new _(`${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 _(`${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 E(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 _(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:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:p};return(this.server?E(`${this.getServerRootUrl(this.server)}/rest/info`).then((e=>E(e.authInfo.tokenServicesUrl,Object.assign({params:r},t)))):E(`${this.portal}/generateToken`,Object.assign({params:r},t))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((t=>{throw new _(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 _(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 _(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)))}}e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new x(e)},e.ApiKeyManager=x,e.ApplicationCredentialsManager=v,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)},e.ArcGISAccessDeniedError=T,e.ArcGISAuthError=g,e.ArcGISIdentityManager=G,e.ArcGISRequestError=c,e.ArcGISTokenRequestError=_,e.Blob=a,e.File=i,e.FormData=o,e.NODEJS_DEFAULT_REFERER_HEADER=p,e.UserSession=function(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new G(e)},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])&&(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=f,e.cleanUrl=R,e.decodeParam=S,e.decodeQueryString=O,e.encodeFormData=h,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(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))},e.fetchToken=I,e.getDefaultRequestOptions=d,e.getFetch=l,e.getOnlineEnvironment=U,e.internalRequest=k,e.isFederated=C,e.isOnline=D,e.normalizeOnlinePortalUrl=b,e.platformSelf=function(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"}})},e.processParams=r,e.request=E,e.requiresFormData=t,e.revokeToken=P,e.setDefaultRequestOptions=function(e,t){e.authentication&&!t&&u("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=j,e.warn=u,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=request.umd.min.js.map |
@@ -7,2 +7,3 @@ "use strict"; | ||
const fetch_token_js_1 = require("./fetch-token.js"); | ||
const ArcGISTokenRequestError_js_1 = require("./utils/ArcGISTokenRequestError.js"); | ||
/** | ||
@@ -52,3 +53,4 @@ * Used to authenticate methods in ArcGIS REST JS with oAuth 2.0 application credentials. The instance of `ApplicationCredentialsManager` can be passed to {@linkcode IRequestOptions.authentication} to authenticate requests. | ||
} }, requestOptions); | ||
return (0, fetch_token_js_1.fetchToken)(`${this.portal}/oauth2/token/`, options).then((response) => { | ||
return (0, fetch_token_js_1.fetchToken)(`${this.portal}/oauth2/token/`, options) | ||
.then((response) => { | ||
this._pendingTokenRequest = null; | ||
@@ -58,2 +60,5 @@ this.token = response.token; | ||
return response.token; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(e.message, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -60,0 +65,0 @@ } |
@@ -9,3 +9,2 @@ "use strict"; | ||
const encode_query_string_js_1 = require("./utils/encode-query-string.js"); | ||
const generate_token_js_1 = require("./generate-token.js"); | ||
const fetch_token_js_1 = require("./fetch-token.js"); | ||
@@ -19,2 +18,4 @@ const federation_utils_js_1 = require("./federation-utils.js"); | ||
const ArcGISAccessDeniedError_js_1 = require("./utils/ArcGISAccessDeniedError.js"); | ||
const ArcGISTokenRequestError_js_1 = require("./utils/ArcGISTokenRequestError.js"); | ||
const index_js_1 = require("./index.js"); | ||
/** | ||
@@ -441,3 +442,4 @@ * Used to authenticate both ArcGIS Online and ArcGIS Enterprise users. `ArcGISIdentityManager` includes helper methods for [OAuth 2.0](/arcgis-rest-js/guides/browser-authentication/) in both browser and server applications. | ||
} | ||
}).then((response) => { | ||
}) | ||
.then((response) => { | ||
return new ArcGISIdentityManager({ | ||
@@ -454,2 +456,5 @@ clientId, | ||
}); | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(e.message, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -479,8 +484,14 @@ } | ||
/** | ||
* Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* Translates authentication from the format used in the [`IdentityManager` class in the ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-Credential.html). | ||
* | ||
* You will need to call both [`IdentityManger.findCredential`](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#findCredential) and [`IdentityManger.findServerInfo`](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#findServerInfo) to obtain both parameters for this method. | ||
* | ||
* This method can be used with {@linkcode ArcGISIdentityManager.toCredential} to interop with the ArcGIS API for JavaScript. | ||
* | ||
* ```js | ||
* ArcGISIdentityManager.fromCredential({ | ||
* userId: "jsmith", | ||
* token: "secret" | ||
* require(["esri/id"], (esriId) => { | ||
* const credential = esriId.findCredential("https://www.arcgis.com/sharing/rest"); | ||
* const serverInfo = esriId.findServerInfo("https://www.arcgis.com/sharing/rest"); | ||
* | ||
* const manager = ArcGISIdentityManager.fromCredential(credential, serverInfo); | ||
* }); | ||
@@ -491,3 +502,3 @@ * ``` | ||
*/ | ||
static fromCredential(credential) { | ||
static fromCredential(credential, serverInfo) { | ||
// At ArcGIS Online 9.1, credentials no longer include the ssl and expires properties | ||
@@ -497,6 +508,15 @@ // Here, we provide default values for them to cover this condition | ||
const expires = credential.expires || Date.now() + 7200000; /* 2 hours */ | ||
if (serverInfo.hasServer) { | ||
return new ArcGISIdentityManager({ | ||
server: credential.server, | ||
ssl, | ||
token: credential.token, | ||
username: credential.userId, | ||
tokenExpires: new Date(expires) | ||
}); | ||
} | ||
return new ArcGISIdentityManager({ | ||
portal: credential.server.includes("sharing/rest") | ||
portal: (0, clean_url_js_1.cleanUrl)(credential.server.includes("sharing/rest") | ||
? credential.server | ||
: credential.server + `/sharing/rest`, | ||
: credential.server + `/sharing/rest`), | ||
ssl, | ||
@@ -514,3 +534,3 @@ token: credential.token, | ||
if (event.data.type === "arcgis:auth:credential") { | ||
return ArcGISIdentityManager.fromCredential(event.data.credential); | ||
return new ArcGISIdentityManager(event.data.credential); | ||
} | ||
@@ -557,6 +577,11 @@ if (event.data.type === "arcgis:auth:error") { | ||
/** | ||
* Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* Returns authentication in a format useable in the [`IdentityManager.registerToken()` method in the ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#registerToken). | ||
* | ||
* This method can be used with {@linkcode ArcGISIdentityManager.fromCredential} to interop with the ArcGIS API for JavaScript. | ||
* | ||
* ```js | ||
* esriId.registerToken(manager.toCredential()); | ||
* require(["esri/id"], (esriId) => { | ||
* esriId.registerToken(manager.toCredential()); | ||
* }) | ||
* ``` | ||
@@ -569,3 +594,3 @@ * | ||
expires: this.tokenExpires.getTime(), | ||
server: this.portal, | ||
server: this.server || this.portal, | ||
ssl: this.ssl, | ||
@@ -747,3 +772,3 @@ token: this.token, | ||
} | ||
return Promise.reject(new request_js_1.ArcGISAuthError("Unable to refresh token.")); | ||
return Promise.reject(new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError("Unable to refresh token. No refresh token or password present.", ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED)); | ||
} | ||
@@ -813,6 +838,3 @@ /** | ||
if (isTokenValid) { | ||
const credential = this.toCredential(); | ||
// the following line allows us to conform to our spec without changing other depended-on functionality | ||
// https://github.com/Esri/arcgis-rest-js/blob/master/packages/arcgis-rest-request/post-message-auth-spec.md#arcgisauthcredential | ||
credential.server = credential.server.replace("/sharing/rest", ""); | ||
const credential = this.toJSON(); | ||
msg = { | ||
@@ -857,4 +879,4 @@ type: "arcgis:auth:credential", | ||
}) | ||
.then((response) => { | ||
if (response.owningSystemUrl) { | ||
.then((serverInfo) => { | ||
if (serverInfo.owningSystemUrl) { | ||
/** | ||
@@ -865,4 +887,4 @@ * if this server is not owned by this portal | ||
*/ | ||
if (!(0, federation_utils_js_1.isFederated)(response.owningSystemUrl, this.portal)) { | ||
throw new request_js_1.ArcGISAuthError(`${url} is not federated with ${this.portal}.`, "NOT_FEDERATED"); | ||
if (!(0, federation_utils_js_1.isFederated)(serverInfo.owningSystemUrl, this.portal)) { | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(`${url} is not federated with ${this.portal}.`, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.NOT_FEDERATED); | ||
} | ||
@@ -873,6 +895,6 @@ else { | ||
*/ | ||
return (0, request_js_1.request)(`${response.owningSystemUrl}/sharing/rest/info`, requestOptions); | ||
return (0, request_js_1.request)(`${serverInfo.owningSystemUrl}/sharing/rest/info`, requestOptions); | ||
} | ||
} | ||
else if (response.authInfo && | ||
else if (serverInfo.authInfo && | ||
this.federatedServers[root] !== undefined) { | ||
@@ -884,44 +906,32 @@ /** | ||
return Promise.resolve({ | ||
authInfo: response.authInfo | ||
authInfo: serverInfo.authInfo | ||
}); | ||
} | ||
else { | ||
throw new request_js_1.ArcGISAuthError(`${url} is not federated with any portal and is not explicitly trusted.`, "NOT_FEDERATED"); | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(`${url} is not federated with any portal and is not explicitly trusted.`, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.NOT_FEDERATED); | ||
} | ||
}) | ||
.then((response) => { | ||
return response.authInfo.tokenServicesUrl; | ||
}) | ||
.then((tokenServicesUrl) => { | ||
// an expired token cant be used to generate a new token | ||
if (this.token && this.tokenExpires.getTime() > Date.now()) { | ||
return (0, generate_token_js_1.generateToken)(tokenServicesUrl, { | ||
params: { | ||
token: this.token, | ||
serverUrl: url, | ||
expiration: this.tokenDuration, | ||
client: "referer" | ||
} | ||
.then((serverInfo) => { | ||
// an expired token cant be used to generate a new token so refresh our credentials before trying to generate a server token | ||
if (this.token && this.tokenExpires.getTime() < Date.now()) { | ||
// If we are authenticated to a single server just refresh with username and password and use the new credentials as the credentials for this server. | ||
if (this.server) { | ||
return this.refreshCredentials().then(() => { | ||
return { | ||
token: this.token, | ||
expires: this.tokenExpires | ||
}; | ||
}); | ||
} | ||
// Otherwise refresh the credentials for the portal and generate a URL for the specific server. | ||
return this.refreshCredentials().then(() => { | ||
return this.generateTokenForServer(serverInfo.authInfo.tokenServicesUrl, root); | ||
}); | ||
// generate an entirely fresh token if necessary | ||
} | ||
else { | ||
return (0, generate_token_js_1.generateToken)(tokenServicesUrl, { | ||
params: { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration, | ||
client: "referer" | ||
} | ||
}).then((response) => { | ||
this.updateToken(response.token, new Date(response.expires)); | ||
return response; | ||
}); | ||
return this.generateTokenForServer(serverInfo.authInfo.tokenServicesUrl, root); | ||
} | ||
}) | ||
.then((response) => { | ||
this.federatedServers[root] = { | ||
expires: new Date(response.expires), | ||
token: response.token | ||
}; | ||
this.federatedServers[root] = response; | ||
delete this._pendingTokenRequests[root]; | ||
@@ -934,2 +944,23 @@ return response.token; | ||
/** | ||
* Generates a token for a given `serverUrl` using a given `tokenServicesUrl`. | ||
*/ | ||
generateTokenForServer(tokenServicesUrl, serverUrl) { | ||
return (0, request_js_1.request)(tokenServicesUrl, { | ||
params: { | ||
token: this.token, | ||
serverUrl, | ||
expiration: this.tokenDuration | ||
} | ||
}) | ||
.then((response) => { | ||
return { | ||
token: response.token, | ||
expires: new Date(response.expires - 1000 * 60 * 5) | ||
}; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(e.message, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.GENERATE_TOKEN_FOR_SERVER_FAILED, e.response, e.url, e.options); | ||
}); | ||
} | ||
/** | ||
* Returns an unexpired token for the current `portal`. | ||
@@ -947,5 +978,5 @@ */ | ||
if (!this._pendingTokenRequests[this.portal]) { | ||
this._pendingTokenRequests[this.portal] = this.refreshCredentials(requestOptions).then((manager) => { | ||
this._pendingTokenRequests[this.portal] = this.refreshCredentials(requestOptions).then(() => { | ||
this._pendingTokenRequests[this.portal] = null; | ||
return manager.token; | ||
return this.token; | ||
}); | ||
@@ -960,10 +991,26 @@ } | ||
refreshWithUsernameAndPassword(requestOptions) { | ||
const options = Object.assign({ params: { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration | ||
} }, requestOptions); | ||
return (0, generate_token_js_1.generateToken)(`${this.portal}/generateToken`, options).then((response) => { | ||
const params = { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration, | ||
client: "referer", | ||
referer: typeof window !== "undefined" && | ||
typeof window.document !== "undefined" && | ||
window.location && | ||
window.location.origin | ||
? window.location.origin | ||
: /* istanbul ignore next */ | ||
index_js_1.NODEJS_DEFAULT_REFERER_HEADER | ||
}; | ||
return (this.server | ||
? (0, request_js_1.request)(`${this.getServerRootUrl(this.server)}/rest/info`).then((response) => { | ||
return (0, request_js_1.request)(response.authInfo.tokenServicesUrl, Object.assign({ params }, requestOptions)); | ||
}) | ||
: (0, request_js_1.request)(`${this.portal}/generateToken`, Object.assign({ params }, requestOptions))) | ||
.then((response) => { | ||
this.updateToken(response.token, new Date(response.expires)); | ||
return this; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(e.message, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -987,4 +1034,8 @@ } | ||
} }, requestOptions); | ||
return (0, fetch_token_js_1.fetchToken)(`${this.portal}/oauth2/token`, options).then((response) => { | ||
return (0, fetch_token_js_1.fetchToken)(`${this.portal}/oauth2/token`, options) | ||
.then((response) => { | ||
return this.updateToken(response.token, response.expires); | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(e.message, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -1016,3 +1067,4 @@ } | ||
} }, requestOptions); | ||
return (0, fetch_token_js_1.fetchToken)(`${this.portal}/oauth2/token`, options).then((response) => { | ||
return (0, fetch_token_js_1.fetchToken)(`${this.portal}/oauth2/token`, options) | ||
.then((response) => { | ||
this._token = response.token; | ||
@@ -1023,2 +1075,5 @@ this._tokenExpires = response.expires; | ||
return this; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError_js_1.ArcGISTokenRequestError(e.message, ArcGISTokenRequestError_js_1.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -1025,0 +1080,0 @@ } |
@@ -9,2 +9,3 @@ "use strict"; | ||
(0, tslib_1.__exportStar)(require("./utils/ArcGISRequestError.js"), exports); | ||
(0, tslib_1.__exportStar)(require("./utils/ArcGISTokenRequestError.js"), exports); | ||
(0, tslib_1.__exportStar)(require("./utils/ArcGISAccessDeniedError.js"), exports); | ||
@@ -34,3 +35,2 @@ (0, tslib_1.__exportStar)(require("./utils/clean-url.js"), exports); | ||
(0, tslib_1.__exportStar)(require("./fetch-token.js"), exports); | ||
(0, tslib_1.__exportStar)(require("./generate-token.js"), exports); | ||
(0, tslib_1.__exportStar)(require("./authenticated-request-options.js"), exports); | ||
@@ -37,0 +37,0 @@ (0, tslib_1.__exportStar)(require("./app-tokens.js"), exports); |
@@ -44,2 +44,24 @@ "use strict"; | ||
exports.getDefaultRequestOptions = getDefaultRequestOptions; | ||
/** | ||
* This error is thrown when a request encounters an invalid token error. Requests that use {@linkcode ArcGISIdentityManager} or | ||
* {@linkcode ApplicationCredentialsManager} in the `authentication` option the authentication manager will automatically try to generate | ||
* a fresh token using either {@linkcode ArcGISIdentityManager.refreshCredentials} or | ||
* {@linkcode ApplicationCredentialsManager.refreshCredentials}. If the request with the new token fails you will receive an `ArcGISAuthError` | ||
* if refreshing the token fails you will receive an instance of {@linkcode ArcGISTokenRequestError}. | ||
* | ||
* ```js | ||
* request(someUrl, { | ||
* authentication: identityManager, | ||
* // some additional options... | ||
* }).catch(e => { | ||
* if(e.name === "ArcGISAuthError") { | ||
* console.log("Request with a new token failed you might want to have the user authorize again.") | ||
* } | ||
* | ||
* if(e.name === "ArcGISTokenRequestError") { | ||
* console.log("There was an error refreshing the token you might want to have the user authorize again.") | ||
* } | ||
* }) | ||
* ``` | ||
*/ | ||
class ArcGISAuthError extends ArcGISRequestError_js_1.ArcGISRequestError { | ||
@@ -60,2 +82,8 @@ /** | ||
code === "AUTHENTICATION_ERROR_CODE" ? message : `${code}: ${message}`; | ||
// restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class | ||
// we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now. | ||
// Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types | ||
const actualProto = new.target.prototype; | ||
Object.setPrototypeOf(this, actualProto); | ||
} | ||
@@ -271,4 +299,8 @@ retry(getSession, retryLimit = 1) { | ||
fetchOptions.headers = Object.assign(Object.assign({}, requestHeaders), options.headers); | ||
// This should have the same conditional for Node JS as ArcGISIdentityManager.refreshWithUsernameAndPassword() | ||
// to ensure that generated tokens have the same referer when used in Node with a username and password. | ||
/* istanbul ignore next - karma reports coverage on browser tests only */ | ||
if (typeof window === "undefined" && !fetchOptions.headers.referer) { | ||
if ((typeof window === "undefined" || | ||
(window && typeof window.document === "undefined")) && | ||
!fetchOptions.headers.referer) { | ||
fetchOptions.headers.referer = exports.NODEJS_DEFAULT_REFERER_HEADER; | ||
@@ -275,0 +307,0 @@ } |
@@ -6,6 +6,28 @@ "use strict"; | ||
exports.ArcGISAccessDeniedError = void 0; | ||
// TypeScript 2.1 no longer allows you to extend built in types. See https://github.com/Microsoft/TypeScript/issues/12790#issuecomment-265981442 | ||
// and https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// | ||
// This code is from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types. | ||
/** | ||
* This error code will be thrown by the following methods when the user cancels or denies an authorization request on the OAuth 2.0 | ||
* authorization screen. | ||
* | ||
* * {@linkcode ArcGISIdentityManager.beginOAuth2} when the `popup` option is `true` | ||
* * {@linkcode ArcGISIdentityManager.completeOAuth2} when the `popup` option is `false` | ||
* | ||
* ```js | ||
* import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; | ||
* | ||
* ArcGISIdentityManager.beginOAuth2({ | ||
* clientId: "***" | ||
* redirectUri: "***", | ||
* popup: true | ||
* }).then(authenticationManager => { | ||
* console.log("OAuth 2.0 Successful"); | ||
* }).catch(e => { | ||
* if(e.name === "ArcGISAccessDeniedError") { | ||
* console.log("The user did not authorize your app.") | ||
* } else { | ||
* console.log("Something else went wrong. Error:", e); | ||
* } | ||
* }) | ||
* | ||
* ``` | ||
*/ | ||
class ArcGISAccessDeniedError extends Error { | ||
@@ -19,3 +41,5 @@ /** | ||
// restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class | ||
// we don't need to check for Object.setPrototypeOf as in the answers becasue we are ES2017 now | ||
// we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now. | ||
// Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types | ||
const actualProto = new.target.prototype; | ||
@@ -22,0 +46,0 @@ Object.setPrototypeOf(this, actualProto); |
@@ -6,6 +6,15 @@ "use strict"; | ||
exports.ArcGISRequestError = void 0; | ||
// TypeScript 2.1 no longer allows you to extend built in types. See https://github.com/Microsoft/TypeScript/issues/12790#issuecomment-265981442 | ||
// and https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// | ||
// This code is from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types. | ||
/** | ||
* This represents a generic error from an ArcGIS endpoint. There will be details about the error in the {@linkcode ArcGISRequestError.message}, {@linkcode ArcGISRequestError.originalMessage} properties on the error. You | ||
* can also access the original server response at {@linkcode ArcGISRequestError.response} which may have additional details. | ||
* | ||
* ```js | ||
* request(someUrl, someOptions).catch(e => { | ||
* if(e.name === "ArcGISRequestError") { | ||
* console.log("Something went wrong with the request:", e); | ||
* console.log("Full server response", e.response); | ||
* } | ||
* }) | ||
* ``` | ||
*/ | ||
class ArcGISRequestError extends Error { | ||
@@ -25,3 +34,5 @@ /** | ||
// restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class | ||
// we don't need to check for Object.setPrototypeOf as in the answers becasue we are ES2017 now | ||
// we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now. | ||
// Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types | ||
const actualProto = new.target.prototype; | ||
@@ -28,0 +39,0 @@ Object.setPrototypeOf(this, actualProto); |
@@ -37,3 +37,4 @@ "use strict"; | ||
ErrorTypes["ArcGISAccessDeniedError"] = "ArcGISAccessDeniedError"; | ||
ErrorTypes["ArcGISTokenRequestError"] = "ArcGISTokenRequestError"; | ||
})(ErrorTypes = exports.ErrorTypes || (exports.ErrorTypes = {})); | ||
//# sourceMappingURL=ErrorTypes.js.map |
/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
import { fetchToken } from "./fetch-token.js"; | ||
import { ArcGISTokenRequestError, ArcGISTokenRequestErrorCodes } from "./utils/ArcGISTokenRequestError.js"; | ||
/** | ||
@@ -48,3 +49,4 @@ * Used to authenticate methods in ArcGIS REST JS with oAuth 2.0 application credentials. The instance of `ApplicationCredentialsManager` can be passed to {@linkcode IRequestOptions.authentication} to authenticate requests. | ||
} }, requestOptions); | ||
return fetchToken(`${this.portal}/oauth2/token/`, options).then((response) => { | ||
return fetchToken(`${this.portal}/oauth2/token/`, options) | ||
.then((response) => { | ||
this._pendingTokenRequest = null; | ||
@@ -54,2 +56,5 @@ this.token = response.token; | ||
return response.token; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError(e.message, ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -56,0 +61,0 @@ } |
@@ -15,2 +15,4 @@ /// <reference types="node" /> | ||
portal?: string; | ||
server?: string; | ||
username?: string; | ||
} | ||
@@ -38,2 +40,12 @@ /** | ||
/** | ||
* Represents the [`ServerInfo`](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-ServerInfo.html) class | ||
* in the ArcGIS API for JavaScript. | ||
*/ | ||
export interface IServerInfo { | ||
server: string; | ||
hasPortal: boolean; | ||
hasServer: boolean; | ||
owningSystemUrl: string | null; | ||
} | ||
/** | ||
* Options for static OAuth 2.0 helper methods on `ArcGISIdentityManager`. | ||
@@ -264,8 +276,14 @@ */ | ||
/** | ||
* Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* Translates authentication from the format used in the [`IdentityManager` class in the ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-Credential.html). | ||
* | ||
* You will need to call both [`IdentityManger.findCredential`](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#findCredential) and [`IdentityManger.findServerInfo`](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#findServerInfo) to obtain both parameters for this method. | ||
* | ||
* This method can be used with {@linkcode ArcGISIdentityManager.toCredential} to interop with the ArcGIS API for JavaScript. | ||
* | ||
* ```js | ||
* ArcGISIdentityManager.fromCredential({ | ||
* userId: "jsmith", | ||
* token: "secret" | ||
* require(["esri/id"], (esriId) => { | ||
* const credential = esriId.findCredential("https://www.arcgis.com/sharing/rest"); | ||
* const serverInfo = esriId.findServerInfo("https://www.arcgis.com/sharing/rest"); | ||
* | ||
* const manager = ArcGISIdentityManager.fromCredential(credential, serverInfo); | ||
* }); | ||
@@ -276,3 +294,3 @@ * ``` | ||
*/ | ||
static fromCredential(credential: ICredential): ArcGISIdentityManager; | ||
static fromCredential(credential: ICredential, serverInfo: IServerInfo): ArcGISIdentityManager; | ||
/** | ||
@@ -369,6 +387,11 @@ * Handle the response from the parent | ||
/** | ||
* Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* Returns authentication in a format useable in the [`IdentityManager.registerToken()` method in the ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#registerToken). | ||
* | ||
* This method can be used with {@linkcode ArcGISIdentityManager.fromCredential} to interop with the ArcGIS API for JavaScript. | ||
* | ||
* ```js | ||
* esriId.registerToken(manager.toCredential()); | ||
* require(["esri/id"], (esriId) => { | ||
* esriId.registerToken(manager.toCredential()); | ||
* }) | ||
* ``` | ||
@@ -487,2 +510,6 @@ * | ||
/** | ||
* Generates a token for a given `serverUrl` using a given `tokenServicesUrl`. | ||
*/ | ||
private generateTokenForServer; | ||
/** | ||
* Returns an unexpired token for the current `portal`. | ||
@@ -489,0 +516,0 @@ */ |
@@ -6,3 +6,2 @@ /* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc. | ||
import { encodeQueryString } from "./utils/encode-query-string.js"; | ||
import { generateToken } from "./generate-token.js"; | ||
import { fetchToken } from "./fetch-token.js"; | ||
@@ -16,2 +15,4 @@ import { canUseOnlineToken, isFederated } from "./federation-utils.js"; | ||
import { ArcGISAccessDeniedError } from "./utils/ArcGISAccessDeniedError.js"; | ||
import { ArcGISTokenRequestError, ArcGISTokenRequestErrorCodes } from "./utils/ArcGISTokenRequestError.js"; | ||
import { NODEJS_DEFAULT_REFERER_HEADER } from "./index.js"; | ||
/** | ||
@@ -438,3 +439,4 @@ * Used to authenticate both ArcGIS Online and ArcGIS Enterprise users. `ArcGISIdentityManager` includes helper methods for [OAuth 2.0](/arcgis-rest-js/guides/browser-authentication/) in both browser and server applications. | ||
} | ||
}).then((response) => { | ||
}) | ||
.then((response) => { | ||
return new ArcGISIdentityManager({ | ||
@@ -451,2 +453,5 @@ clientId, | ||
}); | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError(e.message, ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -476,8 +481,14 @@ } | ||
/** | ||
* Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* Translates authentication from the format used in the [`IdentityManager` class in the ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-Credential.html). | ||
* | ||
* You will need to call both [`IdentityManger.findCredential`](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#findCredential) and [`IdentityManger.findServerInfo`](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#findServerInfo) to obtain both parameters for this method. | ||
* | ||
* This method can be used with {@linkcode ArcGISIdentityManager.toCredential} to interop with the ArcGIS API for JavaScript. | ||
* | ||
* ```js | ||
* ArcGISIdentityManager.fromCredential({ | ||
* userId: "jsmith", | ||
* token: "secret" | ||
* require(["esri/id"], (esriId) => { | ||
* const credential = esriId.findCredential("https://www.arcgis.com/sharing/rest"); | ||
* const serverInfo = esriId.findServerInfo("https://www.arcgis.com/sharing/rest"); | ||
* | ||
* const manager = ArcGISIdentityManager.fromCredential(credential, serverInfo); | ||
* }); | ||
@@ -488,3 +499,3 @@ * ``` | ||
*/ | ||
static fromCredential(credential) { | ||
static fromCredential(credential, serverInfo) { | ||
// At ArcGIS Online 9.1, credentials no longer include the ssl and expires properties | ||
@@ -494,6 +505,15 @@ // Here, we provide default values for them to cover this condition | ||
const expires = credential.expires || Date.now() + 7200000; /* 2 hours */ | ||
if (serverInfo.hasServer) { | ||
return new ArcGISIdentityManager({ | ||
server: credential.server, | ||
ssl, | ||
token: credential.token, | ||
username: credential.userId, | ||
tokenExpires: new Date(expires) | ||
}); | ||
} | ||
return new ArcGISIdentityManager({ | ||
portal: credential.server.includes("sharing/rest") | ||
portal: cleanUrl(credential.server.includes("sharing/rest") | ||
? credential.server | ||
: credential.server + `/sharing/rest`, | ||
: credential.server + `/sharing/rest`), | ||
ssl, | ||
@@ -511,3 +531,3 @@ token: credential.token, | ||
if (event.data.type === "arcgis:auth:credential") { | ||
return ArcGISIdentityManager.fromCredential(event.data.credential); | ||
return new ArcGISIdentityManager(event.data.credential); | ||
} | ||
@@ -554,6 +574,11 @@ if (event.data.type === "arcgis:auth:error") { | ||
/** | ||
* Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* Returns authentication in a format useable in the [`IdentityManager.registerToken()` method in the ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-IdentityManager.html#registerToken). | ||
* | ||
* This method can be used with {@linkcode ArcGISIdentityManager.fromCredential} to interop with the ArcGIS API for JavaScript. | ||
* | ||
* ```js | ||
* esriId.registerToken(manager.toCredential()); | ||
* require(["esri/id"], (esriId) => { | ||
* esriId.registerToken(manager.toCredential()); | ||
* }) | ||
* ``` | ||
@@ -566,3 +591,3 @@ * | ||
expires: this.tokenExpires.getTime(), | ||
server: this.portal, | ||
server: this.server || this.portal, | ||
ssl: this.ssl, | ||
@@ -744,3 +769,3 @@ token: this.token, | ||
} | ||
return Promise.reject(new ArcGISAuthError("Unable to refresh token.")); | ||
return Promise.reject(new ArcGISTokenRequestError("Unable to refresh token. No refresh token or password present.", ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED)); | ||
} | ||
@@ -810,6 +835,3 @@ /** | ||
if (isTokenValid) { | ||
const credential = this.toCredential(); | ||
// the following line allows us to conform to our spec without changing other depended-on functionality | ||
// https://github.com/Esri/arcgis-rest-js/blob/master/packages/arcgis-rest-request/post-message-auth-spec.md#arcgisauthcredential | ||
credential.server = credential.server.replace("/sharing/rest", ""); | ||
const credential = this.toJSON(); | ||
msg = { | ||
@@ -854,4 +876,4 @@ type: "arcgis:auth:credential", | ||
}) | ||
.then((response) => { | ||
if (response.owningSystemUrl) { | ||
.then((serverInfo) => { | ||
if (serverInfo.owningSystemUrl) { | ||
/** | ||
@@ -862,4 +884,4 @@ * if this server is not owned by this portal | ||
*/ | ||
if (!isFederated(response.owningSystemUrl, this.portal)) { | ||
throw new ArcGISAuthError(`${url} is not federated with ${this.portal}.`, "NOT_FEDERATED"); | ||
if (!isFederated(serverInfo.owningSystemUrl, this.portal)) { | ||
throw new ArcGISTokenRequestError(`${url} is not federated with ${this.portal}.`, ArcGISTokenRequestErrorCodes.NOT_FEDERATED); | ||
} | ||
@@ -870,6 +892,6 @@ else { | ||
*/ | ||
return request(`${response.owningSystemUrl}/sharing/rest/info`, requestOptions); | ||
return request(`${serverInfo.owningSystemUrl}/sharing/rest/info`, requestOptions); | ||
} | ||
} | ||
else if (response.authInfo && | ||
else if (serverInfo.authInfo && | ||
this.federatedServers[root] !== undefined) { | ||
@@ -881,44 +903,32 @@ /** | ||
return Promise.resolve({ | ||
authInfo: response.authInfo | ||
authInfo: serverInfo.authInfo | ||
}); | ||
} | ||
else { | ||
throw new ArcGISAuthError(`${url} is not federated with any portal and is not explicitly trusted.`, "NOT_FEDERATED"); | ||
throw new ArcGISTokenRequestError(`${url} is not federated with any portal and is not explicitly trusted.`, ArcGISTokenRequestErrorCodes.NOT_FEDERATED); | ||
} | ||
}) | ||
.then((response) => { | ||
return response.authInfo.tokenServicesUrl; | ||
}) | ||
.then((tokenServicesUrl) => { | ||
// an expired token cant be used to generate a new token | ||
if (this.token && this.tokenExpires.getTime() > Date.now()) { | ||
return generateToken(tokenServicesUrl, { | ||
params: { | ||
token: this.token, | ||
serverUrl: url, | ||
expiration: this.tokenDuration, | ||
client: "referer" | ||
} | ||
.then((serverInfo) => { | ||
// an expired token cant be used to generate a new token so refresh our credentials before trying to generate a server token | ||
if (this.token && this.tokenExpires.getTime() < Date.now()) { | ||
// If we are authenticated to a single server just refresh with username and password and use the new credentials as the credentials for this server. | ||
if (this.server) { | ||
return this.refreshCredentials().then(() => { | ||
return { | ||
token: this.token, | ||
expires: this.tokenExpires | ||
}; | ||
}); | ||
} | ||
// Otherwise refresh the credentials for the portal and generate a URL for the specific server. | ||
return this.refreshCredentials().then(() => { | ||
return this.generateTokenForServer(serverInfo.authInfo.tokenServicesUrl, root); | ||
}); | ||
// generate an entirely fresh token if necessary | ||
} | ||
else { | ||
return generateToken(tokenServicesUrl, { | ||
params: { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration, | ||
client: "referer" | ||
} | ||
}).then((response) => { | ||
this.updateToken(response.token, new Date(response.expires)); | ||
return response; | ||
}); | ||
return this.generateTokenForServer(serverInfo.authInfo.tokenServicesUrl, root); | ||
} | ||
}) | ||
.then((response) => { | ||
this.federatedServers[root] = { | ||
expires: new Date(response.expires), | ||
token: response.token | ||
}; | ||
this.federatedServers[root] = response; | ||
delete this._pendingTokenRequests[root]; | ||
@@ -931,2 +941,23 @@ return response.token; | ||
/** | ||
* Generates a token for a given `serverUrl` using a given `tokenServicesUrl`. | ||
*/ | ||
generateTokenForServer(tokenServicesUrl, serverUrl) { | ||
return request(tokenServicesUrl, { | ||
params: { | ||
token: this.token, | ||
serverUrl, | ||
expiration: this.tokenDuration | ||
} | ||
}) | ||
.then((response) => { | ||
return { | ||
token: response.token, | ||
expires: new Date(response.expires - 1000 * 60 * 5) | ||
}; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError(e.message, ArcGISTokenRequestErrorCodes.GENERATE_TOKEN_FOR_SERVER_FAILED, e.response, e.url, e.options); | ||
}); | ||
} | ||
/** | ||
* Returns an unexpired token for the current `portal`. | ||
@@ -944,5 +975,5 @@ */ | ||
if (!this._pendingTokenRequests[this.portal]) { | ||
this._pendingTokenRequests[this.portal] = this.refreshCredentials(requestOptions).then((manager) => { | ||
this._pendingTokenRequests[this.portal] = this.refreshCredentials(requestOptions).then(() => { | ||
this._pendingTokenRequests[this.portal] = null; | ||
return manager.token; | ||
return this.token; | ||
}); | ||
@@ -957,10 +988,26 @@ } | ||
refreshWithUsernameAndPassword(requestOptions) { | ||
const options = Object.assign({ params: { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration | ||
} }, requestOptions); | ||
return generateToken(`${this.portal}/generateToken`, options).then((response) => { | ||
const params = { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration, | ||
client: "referer", | ||
referer: typeof window !== "undefined" && | ||
typeof window.document !== "undefined" && | ||
window.location && | ||
window.location.origin | ||
? window.location.origin | ||
: /* istanbul ignore next */ | ||
NODEJS_DEFAULT_REFERER_HEADER | ||
}; | ||
return (this.server | ||
? request(`${this.getServerRootUrl(this.server)}/rest/info`).then((response) => { | ||
return request(response.authInfo.tokenServicesUrl, Object.assign({ params }, requestOptions)); | ||
}) | ||
: request(`${this.portal}/generateToken`, Object.assign({ params }, requestOptions))) | ||
.then((response) => { | ||
this.updateToken(response.token, new Date(response.expires)); | ||
return this; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError(e.message, ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -984,4 +1031,8 @@ } | ||
} }, requestOptions); | ||
return fetchToken(`${this.portal}/oauth2/token`, options).then((response) => { | ||
return fetchToken(`${this.portal}/oauth2/token`, options) | ||
.then((response) => { | ||
return this.updateToken(response.token, response.expires); | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError(e.message, ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -1013,3 +1064,4 @@ } | ||
} }, requestOptions); | ||
return fetchToken(`${this.portal}/oauth2/token`, options).then((response) => { | ||
return fetchToken(`${this.portal}/oauth2/token`, options) | ||
.then((response) => { | ||
this._token = response.token; | ||
@@ -1020,2 +1072,5 @@ this._tokenExpires = response.expires; | ||
return this; | ||
}) | ||
.catch((e) => { | ||
throw new ArcGISTokenRequestError(e.message, ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED, e.response, e.url, e.options); | ||
}); | ||
@@ -1022,0 +1077,0 @@ } |
export * from "./request.js"; | ||
export * from "./utils/append-custom-params.js"; | ||
export * from "./utils/ArcGISRequestError.js"; | ||
export * from "./utils/ArcGISTokenRequestError.js"; | ||
export * from "./utils/ArcGISAccessDeniedError.js"; | ||
@@ -28,3 +29,2 @@ export * from "./utils/clean-url.js"; | ||
export * from "./fetch-token.js"; | ||
export * from "./generate-token.js"; | ||
export * from "./authenticated-request-options.js"; | ||
@@ -31,0 +31,0 @@ export * from "./app-tokens.js"; |
@@ -6,2 +6,3 @@ /* Copyright (c) 2018-2019 Environmental Systems Research Institute, Inc. | ||
export * from "./utils/ArcGISRequestError.js"; | ||
export * from "./utils/ArcGISTokenRequestError.js"; | ||
export * from "./utils/ArcGISAccessDeniedError.js"; | ||
@@ -31,3 +32,2 @@ export * from "./utils/clean-url.js"; | ||
export * from "./fetch-token.js"; | ||
export * from "./generate-token.js"; | ||
export * from "./authenticated-request-options.js"; | ||
@@ -34,0 +34,0 @@ export * from "./app-tokens.js"; |
@@ -23,2 +23,24 @@ import { ArcGISRequestError } from "./utils/ArcGISRequestError.js"; | ||
export declare function getDefaultRequestOptions(): any; | ||
/** | ||
* This error is thrown when a request encounters an invalid token error. Requests that use {@linkcode ArcGISIdentityManager} or | ||
* {@linkcode ApplicationCredentialsManager} in the `authentication` option the authentication manager will automatically try to generate | ||
* a fresh token using either {@linkcode ArcGISIdentityManager.refreshCredentials} or | ||
* {@linkcode ApplicationCredentialsManager.refreshCredentials}. If the request with the new token fails you will receive an `ArcGISAuthError` | ||
* if refreshing the token fails you will receive an instance of {@linkcode ArcGISTokenRequestError}. | ||
* | ||
* ```js | ||
* request(someUrl, { | ||
* authentication: identityManager, | ||
* // some additional options... | ||
* }).catch(e => { | ||
* if(e.name === "ArcGISAuthError") { | ||
* console.log("Request with a new token failed you might want to have the user authorize again.") | ||
* } | ||
* | ||
* if(e.name === "ArcGISTokenRequestError") { | ||
* console.log("There was an error refreshing the token you might want to have the user authorize again.") | ||
* } | ||
* }) | ||
* ``` | ||
*/ | ||
export declare class ArcGISAuthError extends ArcGISRequestError { | ||
@@ -25,0 +47,0 @@ /** |
@@ -39,2 +39,24 @@ /* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc. | ||
} | ||
/** | ||
* This error is thrown when a request encounters an invalid token error. Requests that use {@linkcode ArcGISIdentityManager} or | ||
* {@linkcode ApplicationCredentialsManager} in the `authentication` option the authentication manager will automatically try to generate | ||
* a fresh token using either {@linkcode ArcGISIdentityManager.refreshCredentials} or | ||
* {@linkcode ApplicationCredentialsManager.refreshCredentials}. If the request with the new token fails you will receive an `ArcGISAuthError` | ||
* if refreshing the token fails you will receive an instance of {@linkcode ArcGISTokenRequestError}. | ||
* | ||
* ```js | ||
* request(someUrl, { | ||
* authentication: identityManager, | ||
* // some additional options... | ||
* }).catch(e => { | ||
* if(e.name === "ArcGISAuthError") { | ||
* console.log("Request with a new token failed you might want to have the user authorize again.") | ||
* } | ||
* | ||
* if(e.name === "ArcGISTokenRequestError") { | ||
* console.log("There was an error refreshing the token you might want to have the user authorize again.") | ||
* } | ||
* }) | ||
* ``` | ||
*/ | ||
export class ArcGISAuthError extends ArcGISRequestError { | ||
@@ -55,2 +77,8 @@ /** | ||
code === "AUTHENTICATION_ERROR_CODE" ? message : `${code}: ${message}`; | ||
// restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class | ||
// we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now. | ||
// Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types | ||
const actualProto = new.target.prototype; | ||
Object.setPrototypeOf(this, actualProto); | ||
} | ||
@@ -264,4 +292,8 @@ retry(getSession, retryLimit = 1) { | ||
fetchOptions.headers = Object.assign(Object.assign({}, requestHeaders), options.headers); | ||
// This should have the same conditional for Node JS as ArcGISIdentityManager.refreshWithUsernameAndPassword() | ||
// to ensure that generated tokens have the same referer when used in Node with a username and password. | ||
/* istanbul ignore next - karma reports coverage on browser tests only */ | ||
if (typeof window === "undefined" && !fetchOptions.headers.referer) { | ||
if ((typeof window === "undefined" || | ||
(window && typeof window.document === "undefined")) && | ||
!fetchOptions.headers.referer) { | ||
fetchOptions.headers.referer = NODEJS_DEFAULT_REFERER_HEADER; | ||
@@ -268,0 +300,0 @@ } |
@@ -0,1 +1,27 @@ | ||
/** | ||
* This error code will be thrown by the following methods when the user cancels or denies an authorization request on the OAuth 2.0 | ||
* authorization screen. | ||
* | ||
* * {@linkcode ArcGISIdentityManager.beginOAuth2} when the `popup` option is `true` | ||
* * {@linkcode ArcGISIdentityManager.completeOAuth2} when the `popup` option is `false` | ||
* | ||
* ```js | ||
* import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; | ||
* | ||
* ArcGISIdentityManager.beginOAuth2({ | ||
* clientId: "***" | ||
* redirectUri: "***", | ||
* popup: true | ||
* }).then(authenticationManager => { | ||
* console.log("OAuth 2.0 Successful"); | ||
* }).catch(e => { | ||
* if(e.name === "ArcGISAccessDeniedError") { | ||
* console.log("The user did not authorize your app.") | ||
* } else { | ||
* console.log("Something else went wrong. Error:", e); | ||
* } | ||
* }) | ||
* | ||
* ``` | ||
*/ | ||
export declare class ArcGISAccessDeniedError extends Error { | ||
@@ -2,0 +28,0 @@ /** |
/* Copyright (c) 2022 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
// TypeScript 2.1 no longer allows you to extend built in types. See https://github.com/Microsoft/TypeScript/issues/12790#issuecomment-265981442 | ||
// and https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// | ||
// This code is from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types. | ||
/** | ||
* This error code will be thrown by the following methods when the user cancels or denies an authorization request on the OAuth 2.0 | ||
* authorization screen. | ||
* | ||
* * {@linkcode ArcGISIdentityManager.beginOAuth2} when the `popup` option is `true` | ||
* * {@linkcode ArcGISIdentityManager.completeOAuth2} when the `popup` option is `false` | ||
* | ||
* ```js | ||
* import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; | ||
* | ||
* ArcGISIdentityManager.beginOAuth2({ | ||
* clientId: "***" | ||
* redirectUri: "***", | ||
* popup: true | ||
* }).then(authenticationManager => { | ||
* console.log("OAuth 2.0 Successful"); | ||
* }).catch(e => { | ||
* if(e.name === "ArcGISAccessDeniedError") { | ||
* console.log("The user did not authorize your app.") | ||
* } else { | ||
* console.log("Something else went wrong. Error:", e); | ||
* } | ||
* }) | ||
* | ||
* ``` | ||
*/ | ||
export class ArcGISAccessDeniedError extends Error { | ||
@@ -15,3 +37,5 @@ /** | ||
// restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class | ||
// we don't need to check for Object.setPrototypeOf as in the answers becasue we are ES2017 now | ||
// we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now. | ||
// Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types | ||
const actualProto = new.target.prototype; | ||
@@ -18,0 +42,0 @@ Object.setPrototypeOf(this, actualProto); |
import { IRequestOptions } from "./IRequestOptions.js"; | ||
/** | ||
* This represents a generic error from an ArcGIS endpoint. There will be details about the error in the {@linkcode ArcGISRequestError.message}, {@linkcode ArcGISRequestError.originalMessage} properties on the error. You | ||
* can also access the original server response at {@linkcode ArcGISRequestError.response} which may have additional details. | ||
* | ||
* ```js | ||
* request(someUrl, someOptions).catch(e => { | ||
* if(e.name === "ArcGISRequestError") { | ||
* console.log("Something went wrong with the request:", e); | ||
* console.log("Full server response", e.response); | ||
* } | ||
* }) | ||
* ``` | ||
*/ | ||
export declare class ArcGISRequestError extends Error { | ||
@@ -3,0 +16,0 @@ /** |
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
// TypeScript 2.1 no longer allows you to extend built in types. See https://github.com/Microsoft/TypeScript/issues/12790#issuecomment-265981442 | ||
// and https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// | ||
// This code is from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types. | ||
/** | ||
* This represents a generic error from an ArcGIS endpoint. There will be details about the error in the {@linkcode ArcGISRequestError.message}, {@linkcode ArcGISRequestError.originalMessage} properties on the error. You | ||
* can also access the original server response at {@linkcode ArcGISRequestError.response} which may have additional details. | ||
* | ||
* ```js | ||
* request(someUrl, someOptions).catch(e => { | ||
* if(e.name === "ArcGISRequestError") { | ||
* console.log("Something went wrong with the request:", e); | ||
* console.log("Full server response", e.response); | ||
* } | ||
* }) | ||
* ``` | ||
*/ | ||
export class ArcGISRequestError extends Error { | ||
@@ -21,3 +30,5 @@ /** | ||
// restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class | ||
// we don't need to check for Object.setPrototypeOf as in the answers becasue we are ES2017 now | ||
// we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now. | ||
// Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
// and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types | ||
const actualProto = new.target.prototype; | ||
@@ -24,0 +35,0 @@ Object.setPrototypeOf(this, actualProto); |
@@ -30,3 +30,4 @@ /** | ||
ArcGISAuthError = "ArcGISAuthError", | ||
ArcGISAccessDeniedError = "ArcGISAccessDeniedError" | ||
ArcGISAccessDeniedError = "ArcGISAccessDeniedError", | ||
ArcGISTokenRequestError = "ArcGISTokenRequestError" | ||
} |
@@ -34,3 +34,4 @@ /* Copyright (c) 2017 Environmental Systems Research Institute, Inc. | ||
ErrorTypes["ArcGISAccessDeniedError"] = "ArcGISAccessDeniedError"; | ||
ErrorTypes["ArcGISTokenRequestError"] = "ArcGISTokenRequestError"; | ||
})(ErrorTypes || (ErrorTypes = {})); | ||
//# sourceMappingURL=ErrorTypes.js.map |
{ | ||
"name": "@esri/arcgis-rest-request", | ||
"version": "4.0.0-beta.5", | ||
"version": "4.0.0-beta.6", | ||
"description": "Common methods and utilities for @esri/arcgis-rest-js packages.", | ||
@@ -5,0 +5,0 @@ "license": "Apache-2.0", |
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
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
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
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1613598
11901