12345 |
- /*
- All material copyright ESRI, All Rights Reserved, unless otherwise specified.
- See https://js.arcgis.com/4.24/esri/copyright.txt for details.
- */
- import e from"./config.js";import{id as r}from"./kernel.js";import t from"./core/Error.js";import s from"./core/has.js";import{clone as o}from"./core/lang.js";import{unwrap as n}from"./core/maybe.js";import{onAbort as a,isAbortError as i,createAbortError as l,isAborted as u}from"./core/promiseUtils.js";import{isDataProtocol as c,isBlobProtocol as d,normalize as p,getInterceptor as h,isTrustedServer as m,getOrigin as f,toHTTPS as y,addQueryParameter as w,objectToQuery as g,getProxyRule as b,getProxyUrl as q,addQueryParameters as T,hasSameOrigin as k,getAppUrl as O,addProxyRule as S}from"./core/urlUtils.js";import{supportsApiKey as C}from"./support/apiKeyUtils.js";import{registerNoCorsDomains as x,isNoCorsRequestRequired as v,sendNoCorsRequest as E,loadImageAsync as L}from"./support/requestUtils.js";async function U(e,r){const t=c(e),o=d(e);o||t||(e=p(e));const i={url:e,requestOptions:{...n(r)}};let l=h(e);if(l){const e=await G(l,i);if(null!=e)return{data:e,getHeader:M,requestOptions:i.requestOptions,url:i.url};l.after||l.error||(l=null)}if(e=i.url,"image"===(r=i.requestOptions).responseType){if(s("host-webworker")||s("host-node"))throw N("request:invalid-parameters",new Error("responseType 'image' is not supported in Web Workers or Node environment"),i)}else if(t)throw N("request:invalid-parameters",new Error("Data URLs are not supported for responseType = "+r.responseType),i);if("head"===r.method){if(r.body)throw N("request:invalid-parameters",new Error("body parameter cannot be set when method is 'head'"),i);if(t||o)throw N("request:invalid-parameters",new Error("data and blob URLs are not supported for method 'head'"),i)}if(await B(),j)return j.execute(e,r);const u=new AbortController;a(r,(()=>u.abort()));const m={controller:u,credential:null,credentialToken:null,fetchOptions:null,hasToken:!1,interceptor:l,params:i,redoRequest:!1,useIdentity:P.useIdentity,useProxy:!1,useSSL:!1,withCredentials:!1},f=await Q(m);return l?.after?.(f),f}let j;const P=e.request,D="FormData"in globalThis,_=[499,498,403,401],F=["COM_0056","COM_0057","SB_0008"],I=[/\/arcgis\/tokens/i,/\/sharing(\/rest)?\/generatetoken/i,/\/rest\/info/i],M=()=>null,R=Symbol();function H(e){const r=f(e);r&&!U._corsServers.includes(r)&&U._corsServers.push(r)}function A(e){const r=f(e);return!r||r.endsWith(".arcgis.com")||U._corsServers.includes(r)||m(r)}function N(e,r,s,n){let a="Error";const u={url:s.url,requestOptions:s.requestOptions,getHeader:M,ssl:!1};if(r instanceof t)return r.details?(r.details=o(r.details),r.details.url=s.url,r.details.requestOptions=s.requestOptions):r.details=u,r;if(r){const e=n&&(e=>n.headers.get(e)),t=n&&n.status,s=r.message;s&&(a=s),e&&(u.getHeader=e),u.httpStatus=(null!=r.httpCode?r.httpCode:r.code)||t||0,u.subCode=r.subcode,u.messageCode=r.messageCode,"string"==typeof r.details?u.messages=[r.details]:u.messages=r.details,u.raw=R in r?r[R]:r}return i(r)?l():new t(e,a,u)}async function B(){s("host-webworker")?j||(j=await import("./core/workers/request.js")):U._abortableFetch||(U._abortableFetch=globalThis.fetch.bind(globalThis))}async function $(){r||await import("./identity/IdentityManager.js")}async function z(t){const s=t.params.url,o=t.params.requestOptions,n=t.controller.signal,a=o.body;let i=null,l=null;if(D&&"HTMLFormElement"in globalThis&&(a instanceof FormData?i=a:a instanceof HTMLFormElement&&(i=new FormData(a))),"string"==typeof a&&(l=a),t.fetchOptions={cache:o.cacheBust&&!U._abortableFetch.polyfill?"no-cache":"default",credentials:"same-origin",headers:o.headers||{},method:"head"===o.method?"HEAD":"GET",mode:"cors",priority:P.priority,redirect:"follow",signal:n},(i||l)&&(t.fetchOptions.body=i||l),"anonymous"===o.authMode&&(t.useIdentity=!1),t.hasToken=!!(/token=/i.test(s)||o.query?.token||i?.get("token")),!t.hasToken&&e.apiKey&&C(s)&&(o.query||(o.query={}),o.query.token=e.apiKey,t.hasToken=!0),t.useIdentity&&!t.hasToken&&!t.credentialToken&&!K(s)&&!u(n)){let e;"immediate"===o.authMode?(await $(),e=await r.getCredential(s,{signal:n}),t.credential=e):"no-prompt"===o.authMode?(await $(),e=await r.getCredential(s,{prompt:!1,signal:n}).catch((()=>{})),t.credential=e):r&&(e=r.findCredential(s)),e&&(t.credentialToken=e.token,t.useSSL=!!e.ssl)}}function K(e){return I.some((r=>r.test(e)))}async function W(e){let t=e.params.url;const o=e.params.requestOptions,n=e.fetchOptions,a=d(t)||c(t),i=o.responseType||"json",u=a?0:null!=o.timeout?o.timeout:P.timeout;let p=!1;if(!a){e.useSSL&&(t=y(t)),o.cacheBust&&"default"===n.cache&&(t=w(t,"request.preventCache",Date.now()));let a={...o.query};e.credentialToken&&(a.token=e.credentialToken);let i=g(a);s("esri-url-encodes-apostrophe")&&(i=i.replace(/'/g,"%27"));const l=t.length+1+i.length;let u;p="delete"===o.method||"post"===o.method||"put"===o.method||!!o.body||l>P.maxUrlLength;const c=o.useProxy||!!b(t);if(c){const e=q(t);u=e.path,!p&&u.length+1+l>P.maxUrlLength&&(p=!0),e.query&&(a={...e.query,...a})}if("HEAD"===n.method&&(p||c)){if(p){if(l>P.maxUrlLength)throw N("request:invalid-parameters",new Error("URL exceeds maximum length"),e.params);throw N("request:invalid-parameters",new Error("cannot use POST request when method is 'head'"),e.params)}if(c)throw N("request:invalid-parameters",new Error("cannot use proxy when method is 'head'"),e.params)}if(p?(n.method="delete"===o.method?"DELETE":"put"===o.method?"PUT":"POST",o.body?t=T(t,a):(n.body=g(a),n.headers["Content-Type"]="application/x-www-form-urlencoded")):t=T(t,a),c&&(e.useProxy=!0,t=`${u}?${t}`),a.token&&D&&n.body instanceof FormData&&!/\/(sharing|usrsvcs)\/(appservices|servers)\//i.test(t)&&n.body.set("token",a.token),o.hasOwnProperty("withCredentials"))e.withCredentials=o.withCredentials;else if(!k(t,O()))if(m(t))e.withCredentials=!0;else if(r){const s=r.findServerInfo(t);s&&s.webTierAuth&&(e.withCredentials=!0)}e.withCredentials&&(n.credentials="include",v(t)&&await E(p?T(t,a):t))}let h,C,x=0,L=!1;u>0&&(x=setTimeout((()=>{L=!0,e.controller.abort()}),u));try{if("native-request-init"===o.responseType)C=n,C.url=t;else if("image"!==o.responseType||"default"!==n.cache||"GET"!==n.method||p||J(o.headers)||!a&&!e.useProxy&&P.proxyUrl&&!A(t)){if(h=await U._abortableFetch(t,n),e.useProxy||H(t),"native"===o.responseType)C=h;else if("HEAD"!==n.method)if(h.ok){switch(i){case"array-buffer":C=await h.arrayBuffer();break;case"blob":case"image":C=await h.blob();break;default:C=await h.text()}if(x&&(clearTimeout(x),x=0),"json"===i||"xml"===i||"document"===i)if(C)switch(i){case"json":C=JSON.parse(C);break;case"xml":C=X(C,"application/xml");break;case"document":C=X(C,"text/html")}else C=null;if(C){if("array-buffer"===i||"blob"===i){const e=h.headers.get("Content-Type");if(/application\/json|text\/plain/i.test(e)&&C["blob"===i?"size":"byteLength"]<=750)try{const e=await new Response(C).json();e.error&&(C=e)}catch{}}"image"===i&&C instanceof Blob&&(C=await Y(URL.createObjectURL(C),e,!0))}}else C=await h.text()}else C=await Y(t,e)}catch(j){if("AbortError"===j.name){if(L)throw new Error("Timeout exceeded");throw l("Request canceled")}if(!(!h&&j instanceof TypeError&&P.proxyUrl)||o.body||"delete"===o.method||"head"===o.method||"post"===o.method||"put"===o.method||e.useProxy||A(t))throw j;e.redoRequest=!0,S({proxyUrl:P.proxyUrl,urlPrefix:f(t)})}finally{x&&clearTimeout(x)}return[h,C]}async function G(e,r){if(null!=e.responseData)return e.responseData;if(e.headers&&(r.requestOptions.headers={...r.requestOptions.headers,...e.headers}),e.query&&(r.requestOptions.query={...r.requestOptions.query,...e.query}),e.before){let o,n;try{n=await e.before(r)}catch(s){o=N("request:interceptor",s,r)}if((n instanceof Error||n instanceof t)&&(o=N("request:interceptor",n,r)),o)throw e.error&&e.error(o),o;return n}}function J(e){if(e)for(const r of Object.getOwnPropertyNames(e))if(e[r])return!0;return!1}function X(e,r){let t;try{t=(new DOMParser).parseFromString(e,r)}catch{}if(!t||t.getElementsByTagName("parsererror").length)throw new SyntaxError("XML Parse error");return t}async function Q(e){let t,s;await z(e);try{do{[t,s]=await W(e)}while(!await V(e,t,s))}catch(a){const r=N("request:server",a,e.params,t);throw r.details.ssl=e.useSSL,e.interceptor&&e.interceptor.error&&e.interceptor.error(r),r}const o=e.params.url;if(s&&/\/sharing\/rest\/(accounts|portals)\/self/i.test(o)){if(!e.hasToken&&!e.credentialToken&&s.user?.username&&!m(o)){const e=f(o,!0);e&&P.trustedServers.push(e)}Array.isArray(s.authorizedCrossOriginNoCorsDomains)&&x(s.authorizedCrossOriginNoCorsDomains)}const n=e.credential;if(n&&r){const e=r.findServerInfo(n.server);let t=e&&e.owningSystemUrl;if(t){t=t.replace(/\/?$/,"/sharing");const e=r.findCredential(t,n.userId);e&&-1===r._getIdenticalSvcIdx(t,e)&&e.resources.unshift(t)}}return{data:s,getHeader:t?e=>t.headers.get(e):M,requestOptions:e.params.requestOptions,ssl:e.useSSL,url:e.params.url}}async function V(e,t,s){if(e.redoRequest)return e.redoRequest=!1,!1;const o=e.params.requestOptions;if(!t||"native"===o.responseType||"native-request-init"===o.responseType)return!0;let n,a,i,l;if(!t.ok)throw n=new Error(`Unable to load ${t.url} status: ${t.status}`),n[R]=s,n;s?.error&&(n=s.error),n&&(a=Number(n.code),i=n.hasOwnProperty("subcode")?Number(n.subcode):null,l=n.messageCode,l=l&&l.toUpperCase());const u=o.authMode;if(403===a&&(4===i||n.message&&n.message.toLowerCase().includes("ssl")&&!n.message.toLowerCase().includes("permission"))){if(!e.useSSL)return e.useSSL=!0,!1}else if(!e.hasToken&&e.useIdentity&&("no-prompt"!==u||498===a)&&_.includes(a)&&!K(e.params.url)&&(403!==a||!F.includes(l)&&(null==i||2===i&&e.credentialToken))){await $();try{const t=await r.getCredential(e.params.url,{error:N("request:server",n,e.params),prompt:"no-prompt"!==u,signal:e.controller.signal,token:e.credentialToken});return e.credential=t,e.credentialToken=t.token,e.useSSL=e.useSSL||t.ssl,!1}catch(c){if("no-prompt"===u)return e.credential=null,e.credentialToken=null,!1;n=c}}if(n)throw n;return!0}function Y(e,r,t=!1){const s=r.controller.signal,o=new Image;return r.withCredentials?o.crossOrigin="use-credentials":o.crossOrigin="anonymous",o.alt="",o.fetchPriority=P.priority,o.src=e,L(o,e,t,s)}U._abortableFetch=null,U._corsServers=["https://server.arcgisonline.com","https://services.arcgisonline.com"];export{U as default};
|