(function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.fetchmanager={}))})(this,function(c){"use strict";var C=Object.defineProperty;var $=(c,a,u)=>a in c?C(c,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):c[a]=u;var h=(c,a,u)=>($(c,typeof a!="symbol"?a+"":a,u),u);var a=Object.defineProperty,u=(n,e,t)=>e in n?a(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,y=(n,e,t)=>(u(n,typeof e!="symbol"?e+"":e,t),t);class g{constructor(e="cache"){y(this,"prefix"),this.prefix=e}getStorageMedium(e=!0){return typeof window>"u"||typeof window.localStorage>"u"?null:e?window.localStorage:window.sessionStorage}Has(e){return typeof this.Get(`${this.prefix}-${e}`)<"u"}Get(e){const t=this.getStorageMedium(!1),o=this.getStorageMedium(!0);let r=!1,s=null;if(t&&o){try{s=t.getItem(`${this.prefix}-${e}`),s=this.toJSONIfJSON(s),r=s!==null}catch{}if(!r)try{s=o.getItem(`${this.prefix}-${e}`),s=this.toJSONIfJSON(s),r=s!==null}catch{}}return s}toJSONIfJSON(e){return typeof e=="string"&&(e.indexOf("{")===0||e.indexOf("[")===0)&&(e=JSON.parse(e)),e}Save(e,t,o=!0){console.warn("StoreManager.Save is deprecated"),this.Set(e,t,o)}Set(e,t,o=!0){const r=this.getStorageMedium(o);let s=!1;if(r){typeof t=="object"&&(t=JSON.stringify(t));try{r.setItem(`${this.prefix}-${e}`,t),s=!0}catch(i){console.error("Unable to save object",i)}}return s}Remove(e){const t=this.getStorageMedium(!0),o=this.getStorageMedium(!1);t&&t.removeItem(`${this.prefix}-${e}`),o&&o.removeItem(`${this.prefix}-${e}`)}}var b=Object.defineProperty,w=(n,e,t)=>e in n?b(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,d=(n,e,t)=>(w(n,typeof e!="symbol"?e+"":e,t),t);class S{constructor(e="",t="",o=null){if(d(this,"storeNamespace","windowReferenceStore"),d(this,"storeName",""),d(this,"root",typeof window<"u"?window:typeof global<"u"?global:typeof document<"u"?document:{}),t?this.storeNamespace=t:console.info("It's recommended to assign a namespace for your stores"),e)this.storeName=e;else{console.error("A store name needs to be specified. Initiation aborted in WindowReferenceStore");return}o!==null&&(this.root=o),this.registerGlobalReferences()}registerGlobalReferences(){typeof this.root[this.storeNamespace]>"u"&&(this.root[this.storeNamespace]={}),typeof this.root[this.storeNamespace][this.storeName]>"u"&&(this.root[this.storeNamespace][this.storeName]={})}has(e){return e?typeof this.root[this.storeNamespace][this.storeName][e]<"u":(console.log(`Attempted to fetch an empty key. Reference store namespace: ${this.storeNamespace}. Reference store name: ${this.storeName}`),!1)}get(e){return this.has(e)?this.root[this.storeNamespace][this.storeName][e]:(console.log(`Could not find reference ${e} in store ${this.storeNamespace} ${this.storeName}`),!1)}set(e,t,o=!1){if(this.has(e)&&!o)return console.warn(`Reference '${e}' already exists in store '${this.storeName}' and override wasn't enabled`),!1;if(typeof t>"u")return console.error(`Can't register a undefined object to store ${this.storeName}`),!1;try{return this.root[this.storeNamespace][this.storeName][e]=t,!0}catch{return!1}}remove(e){return this.has(e)?delete this.root[this.storeNamespace][this.storeName][e]:!1}}const m=new g("fetchmanager"),R=new S("requests","fetchmanagerstore");class N{constructor(){h(this,"moduleName","FetchManager");h(this,"requestStore",R);h(this,"defaultOptions",{json:!0});h(this,"defaultFetchOptions",{method:"GET",mode:"cors"})}ObjToQueryString(e){return typeof e!="object"?"":new URLSearchParams(e).toString()}async Fetch(e){const t={...this.defaultOptions,...e};if(!t.url)return console.error("Need a url to do a request"),null;const o=this.getKey(t),r=this.getRequestObj(o,t);let s=this.parseFetchOptions(t);if(t.json&&!s.headers){const i=new Headers(s.headers);i.has("Content-Type")||(i.append("Content-Type","application/json"),s.headers=i)}return this.debug(r.debug,"Reqobj",r),r.active&&t.url!==r.url&&typeof window.AbortController<"u"&&r.abortcontroller&&typeof r.abortcontroller.abort=="function"&&(r.abortcontroller.abort(),r.abortcontroller=new AbortController,console.info("Previous request was cancelled",r),this.debug(r.debug,"Previous request was cancelled",r),r.active=!1),t.url!==r.url?(typeof r.abortcontroller<"u"&&r.abortcontroller&&typeof r.abortcontroller.signal<"u"&&(t.signal=r.abortcontroller.signal),r.url=this.CompileUrl(t),r.active=!0,r.promise=new Promise(async(i,v)=>{const p=typeof t.requestdelay=="number"?t.requestdelay:0;r.delaytimer!==null&&(window.clearTimeout(r.delaytimer),r.delaytimer=null),this.debug(r.debug,"Request will be delayed by "+p+"ms",r),r.delaytimer=window.setTimeout(async()=>{try{let f=!r.cache.usecache,l=null;r.cache.usecache&&(l=this.getResponseFromCache(r),this.debug(r.debug,"Response from cache ",l),l==null&&(f=!0)),f&&(l=await fetch(r.url,s),this.debug(r.debug,"Responses object from fetch",l)),r.active=!1;const O=((s.headers??"")["Content-Type"]??"").toLocaleLowerCase();this.debug(r.debug,"requestContentType ",O),this.debug(r.debug,"Returning response object",l),r.result=(l==null?void 0:l.clone())??null,r.finished=!0,r.cache.usecache&&await this.saveResponseToCache(r),i(r.result.clone())}catch(f){r.active=!1,console.error(f),v(r)}},p)}),r.promise):r.finished&&r.result!==null?new Promise(async i=>{i(r.result.clone())}):r.promise&&r.active?r.promise:null}GetScript(e){return new Promise((o,r)=>{const s=document.createElement("script");document.body.appendChild(s),s.onload=o,s.onerror=r,s.async=!0,s.src=e})}CompileUrl(e){let t=e.url;const o=typeof e.querystring=="string"?e.querystring+"":this.ObjToQueryString(e.querystring);return t+=(e.querystring&&t.indexOf("?")===-1?"?":"")+o,t}getRequestObj(e,t){if(!this.requestStore.has(e)){const o={key:e,url:"",cache:this.getRequestCacheOptions(t),options:t,active:!1,finished:!1,result:null,promise:null,abortcontroller:typeof window.AbortController=="function"?new AbortController:null,delaytimer:null,debug:(t==null?void 0:t.debug)??!1};this.requestStore.set(e,o)}return this.requestStore.get(e)}getResponseFromCache(e){const t=m.Get(e.cache.cachekey);return this.validResponse(t)?{body:function(){},bodyUsed:!1,headers:{},redirected:!1,status:200,statusText:"OK",type:"basic",url:e.url,clone:function(){return this},text:()=>new Promise(s=>{s(t)}),json:()=>new Promise(s=>{s(t)})}:null}validResponse(e){return e!=null&&(typeof e=="string"||typeof e=="object")}async saveResponseToCache(e){if(e.cache.usecache!==!0||!e.result)return!1;let t=this.validResponse(e.result);if(this.debug(e.debug,"Storing response in cache ",e.result),!t)return console.info("Result was not accepted so it is not saved to cache",e),!1;e.cache.iscached=!0;const o=await e.result.clone().text();try{return m.Set(e.cache.cachekey,o,e.cache.permanent),!0}catch{return console.error("Unable to save result",e),!1}}parseFetchOptions(e){let t=typeof e.fetchoptions<"u"?e.fetchoptions:{};return t={...this.defaultFetchOptions,...t},t}getRequestCacheOptions(e){return{permanent:typeof e.cache=="object"&&(typeof e.cache.permanent=="boolean"&&e.cache.permanent===!0||typeof e.cache.pemanent=="boolean"&&e.cache.pemanent===!0),usecache:typeof e.cache=="boolean"?e.cache:typeof e.cache=="object"&&typeof e.cache.usecache=="boolean"&&e.cache.usecache===!0,cachekey:typeof e.cache=="object"&&typeof e.cache.cachekey=="string"&&e.cache.cachekey.length!==0?e.cache.cachekey:this.getCacheKey(e),iscached:!1}}getCacheKey(e){return this.getKey(e)+this.CompileUrl(e)}getKey(e){return e.key?e.key:this.CompileUrl(e)}debug(e,...t){e&&console.debug(t)}}c.FetchManager=N,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});