@esri/arcgis-rest-request
Advanced tools
Comparing version 4.0.0-beta.9 to 4.0.0-beta.10
/* @preserve | ||
* @esri/arcgis-rest-request - v4.0.0-beta.8 - Apache-2.0 | ||
* @esri/arcgis-rest-request - v4.0.0-beta.9 - Apache-2.0 | ||
* Copyright (c) 2017-2022 Esri, Inc. | ||
* Mon May 09 2022 20:16:07 GMT+0000 (Coordinated Universal Time) | ||
* Tue May 10 2022 02:53:20 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 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 u(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const l="@esri/arcgis-rest-js";function d(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 p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends h{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const 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 m(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)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=p(),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:l}=o,d=Object.assign({f:"json"},o.params);let g=null;const m={method:i,signal:o.signal,credentials:o.credentials||"same-origin"};let E;if(o.headers&&o.headers["X-Esri-Auth-Client-Id"]&&t.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof o.authentication){const e=o.authentication;E={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 E=o.authentication;const w=t;return(E?E.getToken(t).catch((e=>(e.url=t,e.options=o,g=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(d.token=r),E&&E.getDomainCredentials&&(m.credentials=E.getDomainCredentials(t));const n={};if("GET"===m.method){d.token&&o.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${d.token}`,delete d.token);const e=""===s(d)?t:t+"?"+s(d);o.maxUrlLength&&e.length>o.maxUrlLength||d.token&&o.hideToken?(m.method="POST",r.length&&o.hideToken&&(d.token=r,delete n["X-Esri-Authorization"])):t=e}const i=new RegExp("/items/.+/updateResources").test(t);return"POST"===m.method&&(m.body=a(d,i)),m.headers=Object.assign(Object.assign({},n),o.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer="@esri/arcgis-rest-js"),e(d)||i||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,m):u().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,o)}if(l)return e;switch(d.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==d.f&&"geojson"!==d.f||l)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 E(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}function w(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})}var k,_;!function(e){e.TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",e.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",e.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",e.NOT_FEDERATED="NOT_FEDERATED",e.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE"}(k||(k={}));class T extends Error{constructor(e="UNKNOWN_ERROR",t=k.UNKNOWN_ERROR_CODE,r,s,n){super(e);const 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 A(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 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-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 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(e){const t=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},e);return I(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function x(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(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 U=/^https?:\/\/(\S+)\.arcgis\.com.+/;function b(e){return U.test(e)}function C(e){if(!U.test(e))return e;switch(N(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 N(e){if(!U.test(e))return null;const t=e.match(U)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function P(e,t){const r=O(C(t)).replace(/https?:\/\//,""),s=O(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function j(e,t){const r=b(e),s=b(t),n=N(e),o=N(t);return!(!r||!s||n!==o)}function F(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 $(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 E(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function G(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(e){!e&&window&&(e=window);return G(e.crypto.getRandomValues(new Uint8Array(32)))}class M{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:u,params:l,style:d,pkce:p,state:f}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),m=f||q(t),E=`ARCGIS_REST_JS_AUTH_STATE_${o}`;t.localStorage.setItem(E,m);let w=`${O(r)}/oauth2/authorize`;const k={client_id:o,response_type:p?"code":"token",expiration:i,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:u,style:d};let _;if("arcgis"!==n&&(w=`${O(r)}/oauth2/social/authorize`,k.socialLoginProviderName=n,k.autoAccountCreateForSocial=!0),p){const e=q(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=>G(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){k.code_challenge_method=t?"S256":"plain",k.code_challenge=t||e}))}else _=Promise.resolve();return _.then((()=>(w=`${w}?${s(k)}`,l&&(w=`${w}&${s(l)}`),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 M({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=A(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 R):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 M({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=O(`${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(M.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 I(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new M({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}static deserialize(e){const t=JSON.parse(e);return new M({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 M({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new M({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 M(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 M(e);return t.getUser().then((()=>t))}static signIn(e){const t=new M(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 j(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.",k.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 M.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(e,t){const r=this.getServerRootUrl(e),s=this.federatedServers[r];return s&&s.expires&&s.expires.getTime()>Date.now()?Promise.resolve(s.token):(this._pendingTokenRequests[r]||(this._pendingTokenRequests[r]=this.fetchAuthorizedDomains().then((()=>E(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(P(s.owningSystemUrl,this.portal))return E(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new T(`${e} is not federated with ${this.portal}.`,k.NOT_FEDERATED)}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new T(`${e} is not federated with any portal and is not explicitly trusted.`,k.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))).then((e=>(this.federatedServers[r]=e,delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}generateTokenForServer(e,t){return E(e,{params:{token:this.token,serverUrl:t,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((e=>{throw new T(e.message,k.GENERATE_TOKEN_FOR_SERVER_FAILED,e.response,e.url,e.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:"@esri/arcgis-rest-js"};return(this.server?E(`${this.getServerRootUrl(this.server)}/rest/info`).then((r=>E(r.authInfo.tokenServicesUrl,Object.assign({params:t},e)))):E(`${this.portal}/generateToken`,Object.assign({params:t},e))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshWithRefreshToken(e){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(e);const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return I(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(e){const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return I(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function H(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new M(e)}function z(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))}function K(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"}})}H.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),M.beginOAuth2(...e)},H.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),M.completeOAuth2(...e)},H.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),M.fromParent(...e)},H.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),M.authorize(...e)},H.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),M.exchangeAuthorizationCode(...e)},H.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),M.fromCredential(...e)},H.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),M.deserialize(...e)};export{D as ApiKey,y as ApiKeyManager,v as ApplicationCredentialsManager,x as ApplicationSession,R as ArcGISAccessDeniedError,g as ArcGISAuthError,M as ArcGISIdentityManager,h as ArcGISRequestError,T as ArcGISTokenRequestError,k as ArcGISTokenRequestErrorCodes,i as Blob,_ as ErrorTypes,o as File,n as FormData,l as NODEJS_DEFAULT_REFERER_HEADER,H as UserSession,w as appendCustomParams,j as canUseOnlineToken,f as checkForErrors,O as cleanUrl,S as decodeParam,A as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,z as exchangeToken,I as fetchToken,p as getDefaultRequestOptions,u as getFetch,N as getOnlineEnvironment,m as internalRequest,P as isFederated,b as isOnline,C as normalizeOnlinePortalUrl,K as platformSelf,t as processParams,E as request,e as requiresFormData,$ as revokeToken,d as setDefaultRequestOptions,F as validateAppAccess,c as warn}; | ||
//# sourceMappingURL=request.esm.min.js.map |
/* @preserve | ||
* @esri/arcgis-rest-request - v4.0.0-beta.8 - Apache-2.0 | ||
* @esri/arcgis-rest-request - v4.0.0-beta.9 - Apache-2.0 | ||
* Copyright (c) 2017-2022 Esri, Inc. | ||
* Mon May 09 2022 20:16:07 GMT+0000 (Coordinated Universal Time) | ||
* Tue May 10 2022 02:53:20 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 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 c(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 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 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 d="@esri/arcgis-rest-js";function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends h{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const 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 E(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)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 E(e,r){const s=p(),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 E=null;const m={method:i,signal:o.signal,credentials:o.credentials||"same-origin"};let k;if(o.headers&&o.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof o.authentication){const e=o.authentication;k={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 k=o.authentication;const w=e;return(k?k.getToken(e).catch((t=>(t.url=e,t.options=o,E=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),k&&k.getDomainCredentials&&(m.credentials=k.getDomainCredentials(e));const s={};if("GET"===m.method){g.token&&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?(m.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"===m.method&&(m.body=c(g,i)),m.headers=Object.assign(Object.assign({},s),o.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer=d),t(g)||i||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,m):l().then((({fetch:t})=>t(e,m)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new h(s,`HTTP ${r}`,t,e,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,E);if(E){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];o.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},E=null}return r}}))}function m(e,t={params:{f:"json"}}){return E(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}var k,w;e.ArcGISTokenRequestErrorCodes=void 0,(k=e.ArcGISTokenRequestErrorCodes||(e.ArcGISTokenRequestErrorCodes={})).TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",k.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",k.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",k.NOT_FEDERATED="NOT_FEDERATED",k.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE";class T 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 _ 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 A(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function S(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=A(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 O=3e5;function I(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-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 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(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}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)}}const x=/^https?:\/\/(\S+)\.arcgis\.com.+/;function D(e){return x.test(e)}function U(e){if(!x.test(e))return e;switch(C(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function C(e){if(!x.test(e))return null;const t=e.match(x)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function b(e,t){const r=R(U(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=C(e),o=C(t);return!(!r||!s||n!==o)}function P(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function j(e){const t=`${R(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return m(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function G(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(e){!e&&window&&(e=window);return G(e.crypto.getRandomValues(new Uint8Array(32)))}class F{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:c,popupWindowFeatures:h,locale:u,params:l,style:d,pkce:p,state:f}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),E=f||q(t),m=`ARCGIS_REST_JS_AUTH_STATE_${o}`;t.localStorage.setItem(m,E);let k=`${R(r)}/oauth2/authorize`;const w={client_id:o,response_type:p?"code":"token",expiration:i,redirect_uri:a,state:JSON.stringify({id:E,originalUrl:t.location.href}),locale:u,style:d};let T;if("arcgis"!==s&&(k=`${R(r)}/oauth2/social/authorize`,w.socialLoginProviderName=s,w.autoAccountCreateForSocial=!0),p){const e=q(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${o}`;t.localStorage.setItem(r,e),T=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=>G(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 T=Promise.resolve();return T.then((()=>(k=`${k}?${n(w)}`,l&&(k=`${k}&${n(l)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${o}`,(t=>{if("access_denied"===t.detail.error){const e=new _;return s(e),e}if(t.detail.error){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new F({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(k,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=k))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce: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),c=S(o?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),h=c&&c.state?JSON.parse(c.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 _):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 F({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires}))}if(!a||!h)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(h.id!==a)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(c.error){const e=c.error;return u(c.error_description||"Unknown error",e,h.originalUrl)}if(o&&c.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:c.code}}).then((e=>l(Object.assign(Object.assign({},e),h),h.originalUrl))).catch((e=>u(e.message,e.error,h.originalUrl)))}return!o&&c.access_token?Promise.resolve(l(Object.assign({token:c.access_token,expires:new Date(Date.now()+1e3*parseInt(c.expires_in,10)),ssl:"true"===c.ssl,username:c.username},h),h.originalUrl)):u("Unknown error","oauth-error",h.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(F.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),c={client_id:s,expiration:o,response_type:"code",redirect_uri:i};a&&(c.state=a);const h=`${r}/oauth2/authorize?${n(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(t,r){const{portal:s,clientId:n,redirectUri: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 F({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(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}static deserialize(e){const t=JSON.parse(e);return new F({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 F({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new F({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 F(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return j({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new F(e);return t.getUser().then((()=>t))}static signIn(e){const t=new F(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=m(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=m(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return N(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>P(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(t){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(t):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new T("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 F.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(t,r){const s=this.getServerRootUrl(t),n=this.federatedServers[s];return n&&n.expires&&n.expires.getTime()>Date.now()?Promise.resolve(n.token):(this._pendingTokenRequests[s]||(this._pendingTokenRequests[s]=this.fetchAuthorizedDomains().then((()=>m(`${s}/rest/info`,{credentials:this.getDomainCredentials(t)}).then((n=>{if(n.owningSystemUrl){if(b(n.owningSystemUrl,this.portal))return m(`${n.owningSystemUrl}/sharing/rest/info`,r);throw new T(`${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(`${t} is not federated with any portal and is not explicitly trusted.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))).then((e=>(this.federatedServers[s]=e,delete this._pendingTokenRequests[s],e.token)))))),this._pendingTokenRequests[s])}generateTokenForServer(t,r){return m(t,{params:{token:this.token,serverUrl:r,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((t=>{throw new T(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:d};return(this.server?m(`${this.getServerRootUrl(this.server)}/rest/info`).then((e=>m(e.authInfo.tokenServicesUrl,Object.assign({params:r},t)))):m(`${this.portal}/generateToken`,Object.assign({params:r},t))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((t=>{throw new T(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(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(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function $(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new F(e)}$.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),F.beginOAuth2(...e)},$.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),F.completeOAuth2(...e)},$.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),F.fromParent(...e)},$.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),F.authorize(...e)},$.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),F.exchangeAuthorizationCode(...e)},$.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),F.fromCredential(...e)},$.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),F.deserialize(...e)},e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)},e.ApiKeyManager=y,e.ApplicationCredentialsManager=v,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)},e.ArcGISAccessDeniedError=_,e.ArcGISAuthError=g,e.ArcGISIdentityManager=F,e.ArcGISRequestError=h,e.ArcGISTokenRequestError=T,e.Blob=a,e.File=i,e.FormData=o,e.NODEJS_DEFAULT_REFERER_HEADER=d,e.UserSession=$,e.appendCustomParams=function(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})},e.canUseOnlineToken=N,e.checkForErrors=f,e.cleanUrl=R,e.decodeParam=A,e.decodeQueryString=S,e.encodeFormData=c,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=I,e.getDefaultRequestOptions=p,e.getFetch=l,e.getOnlineEnvironment=C,e.internalRequest=E,e.isFederated=b,e.isOnline=D,e.normalizeOnlinePortalUrl=U,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})},e.processParams=r,e.request=m,e.requiresFormData=t,e.revokeToken=j,e.setDefaultRequestOptions=function(e,t){e.authentication&&!t&&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=P,e.warn=u,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=request.umd.min.js.map |
{ | ||
"name": "@esri/arcgis-rest-request", | ||
"version": "4.0.0-beta.9", | ||
"version": "4.0.0-beta.10", | ||
"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
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
1663610