/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import s from"../config.js";import e from"../request.js";import{getOrigin as t}from"../core/urlUtils.js";const r=/^https?:\/\/(i?basemaps|basemapstyles)-api\.arcgis\.com\//i,n="https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/sessions/start",a=new Set(["elevation3d.arcgis.com","js.arcgis.com","jsdev.arcgis.com","jsqa.arcgis.com","static.arcgis.com"]),i=new Map;let o=null;function c(e){if(!p(e))return null;const t=s=>s instanceof RegExp?s.test(e):"string"==typeof s&&e.startsWith(s),n=s.apiKeys;if(Array.isArray(n.scopes))for(const s of n.scopes)if(Array.isArray(s.urls)){if(s.urls.some(t))return s.token}else if(t(s.urls))return s.token;return n.basemapStyles&&r.test(e)?n.basemapStyles:s.apiKey&&/^https?:\/\/.+\.arcgis\.com(\/|$)/i.test(e)?s.apiKey:null}async function l(t){if(!s.sessions?.basemap?.enabled||!r.test(t))return null;const a=c(t);if(!a)return null;o&&await o;const{styleFamily:l="arcgis",autoRefresh:u,duration:m=43200}=s.sessions.basemap,p=`${a}:${l}`,y=i.get(p);if(y&&(!u||y.endTime>Date.now()))return y.sessionToken;let f;o=e(n,{cacheBust:!0,query:{durationSeconds:m,styleFamily:l,token:a}});try{f=(await o).data,f.endTime-=5e3,i.set(p,f)}finally{o=null}return f.sessionToken}function u(){return null!=s.apiKey||null!=s.apiKeys.basemapStyles}function m(s,e){return e?p(s):null!=c(s)}function p(s){const e=t(s,!0);return!!e&&(!a.has(e)&&!s.endsWith("/sharing/rest/generateToken"))}export{c as getApiKey,l as getSessionToken,u as hasBasemapStylesApiKey,m as isApiKeyApplicable,p as supportsApiKey};
