UNPKG

@uploadcare/file-uploader

Version:

Building blocks for Uploadcare products integration

29 lines 286 kB
/** * @license * MIT License * * Copyright (c) 2022 Uploadcare (hello@uploadcare.com). All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ var mn=Object.defineProperty;var gn=Object.getPrototypeOf;var bn=Reflect.get;var _n=(s,t,e)=>t in s?mn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var u=(s,t,e)=>_n(s,typeof t!="symbol"?t+"":t,e);var X=(s,t,e)=>bn(gn(s),e,t);var vn=Object.defineProperty,yn=(s,t,e)=>t in s?vn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,Zi=(s,t,e)=>(yn(s,typeof t!="symbol"?t+"":t,e),e);function wn(s){let t=e=>{var i;for(let r in e)((i=e[r])==null?void 0:i.constructor)===Object&&(e[r]=t(e[r]));return{...e}};return t(s)}var A=class{constructor(s){s.constructor===Object?this.store=wn(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,t){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+t)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,t,e=!1){!e&&Object.keys(this.store).includes(s)||(this.store[s]=t,this.notify(s))}pub(s,t){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){A.warn("publish",s);return}this.store[s]=t,this.notify(s)}multiPub(s){for(let t in s)this.pub(t,s[t])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(t=>{t(this.store[s])})}sub(s,t,e=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(t),e&&t(this.store[s]),{remove:()=>{this.callbackMap[s].delete(t),this.callbackMap[s].size||delete this.callbackMap[s]},callback:t})}static registerCtx(s,t=Symbol()){let e=A.globalStore.get(t);return e?console.warn('State: context UID "'+t+'" already in use'):(e=new A(s),A.globalStore.set(t,e)),e}static deleteCtx(s){A.globalStore.delete(s)}static getCtx(s,t=!0){return A.globalStore.get(s)||(t&&console.warn('State: wrong context UID - "'+s+'"'),null)}};A.globalStore=new Map;var E=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),rr="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Cn=rr.length-1,He=class{static generate(s="XXXXXXXXX-XXX"){let t="";for(let e=0;e<s.length;e++)t+=s[e]==="-"?s[e]:rr.charAt(Math.random()*Cn);return t}};function or(s,t,e){let i=!0,r,o=t.split(".");return o.forEach((n,a)=>{a<o.length-1?s=s[n]:r=n}),s?s[r]=e:i=!1,i}function xn(s){return s.split("-").map((t,e)=>t&&e?t[0].toUpperCase()+t.slice(1):t).join("").split("_").map((t,e)=>t&&e?t.toUpperCase():t).join("")}function En(s,t){[...s.querySelectorAll(`[${E.REPEAT_ATTR}]`)].forEach(e=>{let i=e.getAttribute(E.REPEAT_ITEM_TAG_ATTR),r;if(i&&(r=window.customElements.get(i)),!r){r=class extends t.BaseComponent{constructor(){super(),i||(this.style.display="contents")}};let n=e.innerHTML;r.template=n,r.reg(i)}for(;e.firstChild;)e.firstChild.remove();let o=e.getAttribute(E.REPEAT_ATTR);t.sub(o,n=>{if(!n){for(;e.firstChild;)e.firstChild.remove();return}let a=[...e.children],l,c=h=>{h.forEach((p,f)=>{if(a[f])if(a[f].set$)setTimeout(()=>{a[f].set$(p)});else for(let m in p)a[f][m]=p[m];else{l||(l=new DocumentFragment);let m=new r;Object.assign(m.init$,p),l.appendChild(m)}}),l&&e.appendChild(l);let d=a.slice(h.length,a.length);for(let p of d)p.remove()};if(n.constructor===Array)c(n);else if(n.constructor===Object){let h=[];for(let d in n){let p=n[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),h.push(p)}c(h)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),e.removeAttribute(E.REPEAT_ATTR),e.removeAttribute(E.REPEAT_ITEM_TAG_ATTR)})}var ir="__default__";function An(s,t){if(t.shadowRoot)return;let e=[...s.querySelectorAll("slot")];if(!e.length)return;let i={};e.forEach(r=>{let o=r.getAttribute("name")||ir;i[o]={slot:r,fr:document.createDocumentFragment()}}),t.initChildren.forEach(r=>{var o;let n=ir;r instanceof Element&&r.hasAttribute("slot")&&(n=r.getAttribute("slot"),r.removeAttribute("slot")),(o=i[n])==null||o.fr.appendChild(r)}),Object.values(i).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(o,r.slot)}else r.slot.remove()})}function Tn(s,t){[...s.querySelectorAll(`[${E.EL_REF_ATTR}]`)].forEach(e=>{let i=e.getAttribute(E.EL_REF_ATTR);t.ref[i]=e,e.removeAttribute(E.EL_REF_ATTR)})}function Sn(s,t){[...s.querySelectorAll(`[${E.BIND_ATTR}]`)].forEach(e=>{let r=e.getAttribute(E.BIND_ATTR).split(";");[...e.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=xn(o.name.replace("-",""));r.push(n+":"+o.value),e.removeAttribute(o.name)}}),r.forEach(o=>{if(!o)return;let n=o.split(":").map(h=>h.trim()),a=n[0],l;a.indexOf(E.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(E.ATTR_BIND_PRFX,""));let c=n[1].split(",").map(h=>h.trim());for(let h of c){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),t.sub(h,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),l?(p==null?void 0:p.constructor)===Boolean?p?e.setAttribute(a,""):e.removeAttribute(a):e.setAttribute(a,p):or(e,a,p)||(e[E.SET_LATER_KEY]||(e[E.SET_LATER_KEY]=Object.create(null)),e[E.SET_LATER_KEY][a]=p)})}}),e.removeAttribute(E.BIND_ATTR)})}var Nt="{{",nt="}}",In="skip-text";function On(s){let t,e=[],i=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var o;return!((o=r.parentElement)!=null&&o.hasAttribute(In))&&r.textContent.includes(Nt)&&r.textContent.includes(nt)&&1}});for(;t=i.nextNode();)e.push(t);return e}var kn=function(s,t){On(s).forEach(i=>{let r=[],o;for(;i.textContent.includes(nt);)i.textContent.startsWith(Nt)?(o=i.textContent.indexOf(nt)+nt.length,i.splitText(o),r.push(i)):(o=i.textContent.indexOf(Nt),i.splitText(o)),i=i.nextSibling;r.forEach(n=>{let a=n.textContent.replace(Nt,"").replace(nt,"");n.textContent="",t.sub(a,l=>{n.textContent=l})})})},$n=[En,An,Tn,Sn,kn],Vt="'",ze='"',Mn=/\\([0-9a-fA-F]{1,6} ?)/g;function Ln(s){return(s[0]===ze||s[0]===Vt)&&(s[s.length-1]===ze||s[s.length-1]===Vt)}function Pn(s){return(s[0]===ze||s[0]===Vt)&&(s=s.slice(1)),(s[s.length-1]===ze||s[s.length-1]===Vt)&&(s=s.slice(0,-1)),s}function Un(s){let t="",e="";for(var i=0;i<s.length;i++){let r=s[i+1];s[i]==="\\"&&r==='"'?(t+='\\"',i++):s[i]==='"'&&e!=="\\"?t+='\\"':t+=s[i],e=s[i]}return t}function Rn(s){let t=s;Ln(s)&&(t=Pn(t),t=t.replace(Mn,(e,i)=>String.fromCodePoint(parseInt(i.trim(),16))),t=t.replaceAll(`\\ `,"\\n"),t=Un(t),t=ze+t+ze);try{return JSON.parse(t)}catch{throw new Error(`Failed to parse CSS property value: ${t}. Original input: ${s}`)}}var sr=0,Be=null,ge=null,Ee=class extends HTMLElement{constructor(){super(),Zi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(t=>{let e=this.getCssData(this.__extractCssName(t),!0);e!==null&&this.$[t]!==e&&(this.$[t]=e)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return Ee}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,t=this.renderShadow){let e;if((t||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(E.USE_TPL);if(r){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(r))||document.querySelector(r);n?s=n.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)e=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,e=r.content.cloneNode(!0)}else this.constructor.__tpl&&(e=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(e,this)}let i=()=>{e&&(t&&this.shadowRoot.appendChild(e)||this.appendChild(e)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){t=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=i,this.shadowRoot.prepend(r)}else i()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=He.generate(),this.style.setProperty(E.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(E.CSS_CTX_PROP,!0)}get ctxName(){var s;let t=((s=this.getAttribute(E.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=t,t}get localCtx(){return this.__localCtx||(this.__localCtx=A.registerCtx({},this)),this.__localCtx}get nodeCtx(){return A.getCtx(this.ctxName,!1)||A.registerCtx({},this.ctxName)}static __parseProp(s,t){let e,i;if(s.startsWith(E.EXT_DATA_CTX_PRFX))e=t.nodeCtx,i=s.replace(E.EXT_DATA_CTX_PRFX,"");else if(s.includes(E.NAMED_DATA_CTX_SPLTR)){let r=s.split(E.NAMED_DATA_CTX_SPLTR);e=A.getCtx(r[0]),i=r[1]}else e=t.localCtx,i=s;return{ctx:e,name:i}}sub(s,t,e=!0){let i=o=>{this.isConnected&&t(o)},r=Ee.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,i,e)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,i,e))})}notify(s){let t=Ee.__parseProp(s,this);t.ctx.notify(t.name)}has(s){let t=Ee.__parseProp(s,this);return t.ctx.has(t.name)}add(s,t,e=!1){let i=Ee.__parseProp(s,this);i.ctx.add(i.name,t,e)}add$(s,t=!1){for(let e in s)this.add(e,s[e],t)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(t,e,i)=>{let r=Ee.__parseProp(e,this);return r.ctx.pub(r.name,i),!0},get:(t,e)=>{let i=Ee.__parseProp(e,this);return i.ctx.read(i.name)}})}return this.__stateProxy}set$(s,t=!1){for(let e in s){let i=s[e];t||![String,Number,Boolean].includes(i==null?void 0:i.constructor)?this.$[e]=i:this.$[e]!==i&&(this.$[e]=i)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(E.CTX_OWNER_ATTR)&&this.getAttribute(E.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let t of Object.values(s))Object.keys(this.init$).includes(t)||(this.init$[t]="");for(let t in this.init$)if(t.startsWith(E.EXT_DATA_CTX_PRFX))this.nodeCtx.add(t.replace(E.EXT_DATA_CTX_PRFX,""),this.init$[t],this.__ctxOwner);else if(t.includes(E.NAMED_DATA_CTX_SPLTR)){let e=t.split(E.NAMED_DATA_CTX_SPLTR),i=e[0].trim(),r=e[1].trim();if(i&&r){let o=A.getCtx(i,!1);o||(o=A.registerCtx({},i)),o.add(r,this.init$[t])}}else this.localCtx.add(t,this.init$[t]);for(let t in this.cssInit$)this.bindCssData(t,this.cssInit$[t]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let t=(s=this.getAttribute(E.CTX_NAME_ATTR))==null?void 0:s.trim();if(t&&this.style.setProperty(E.CSS_CTX_PROP,`'${t}'`),this.__initDataCtx(),this[E.SET_LATER_KEY]){for(let e in this[E.SET_LATER_KEY])or(this,e,this[E.SET_LATER_KEY][e]);delete this[E.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let e of $n)this.addTemplateProcessor(e);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let e=this.getRootNode();if(!e)return;if(e==null?void 0:e.querySelector(`link[${E.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(E.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},e.nodeType===Node.DOCUMENT_NODE?e.head.appendChild(r):e.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ge==null||ge.delete(this.updateCssData),ge!=null&&ge.size||(Be==null||Be.disconnect(),Be=null,ge=null)},100)))}static reg(s,t=!1){s||(sr++,s=`${E.AUTO_TAG_PRFX}-${sr}`),this.__tag=s;let e=window.customElements.get(s);if(e){!t&&e!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,t?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,t,e){var i;if(t===e)return;let r=(i=this.constructor.__attrDesc)==null?void 0:i[s];r?this.__dataCtxInitialized?this.$[r]=e:this.init$[r]=e:this[s]=e}getCssData(s,t=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let e=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Rn(e)}catch{!t&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((t,e)=>e===0?"":t).join("--")}__initStyleAttrObserver(){ge||(ge=new Set),ge.add(this.updateCssData),Be||(Be=new MutationObserver(s=>{s[0].type==="attributes"&&ge.forEach(t=>{t()})}),Be.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,t=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let e=this.getCssData(this.__extractCssName(s),!0);e===null&&(e=t),this.add(s,e),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,t,e){let i="__"+s;this[i]=this[s],Object.defineProperty(this,s,{set:r=>{this[i]=r,e?window.setTimeout(()=>{t==null||t(r)}):t==null||t(r)},get:()=>this[i]}),this[s]=this[i]}static set shadowStyles(s){let t=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(t)}static set rootStyles(s){if(!this.__rootStylesLink){let t=new Blob([s],{type:"text/css"}),e=URL.createObjectURL(t),i=document.createElement("link");i.href=e,i.rel="stylesheet",this.__rootStylesLink=i}}},Ae=Ee;Zi(Ae,"template");var Ki=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let t in this.appMap)!this.defaultRoute&&this.appMap[t].default===!0?this.defaultRoute=t:!this.errorRoute&&this.appMap[t].error===!0&&(this.errorRoute=t)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(e=>{if(e.includes("?"))s.route=e.replace("?","");else if(e.includes("=")){let i=e.split("=");s.options[i[0]]=decodeURI(i[1])}else s.options[e]=!0}),s}static notify(){let s=this.readAddressBar(),t=this.appMap[s.route];if(t&&t.title&&(document.title=t.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!t&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!t&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!t){this._print(`Route "${s.route}" not found...`);return}let e=new CustomEvent(Ki.routingEventName,{detail:{route:s.route,options:Object.assign(t||{},s.options)}});window.dispatchEvent(e)}static reflect(s,t={}){let e=this.appMap[s];if(!e){this._print("Wrong route: "+s);return}let i="?"+s;for(let o in t)t[o]===!0?i+=this.separator+o:i+=this.separator+o+`=${t[o]}`;let r=e.title||this.defaultTitle||"";window.history.pushState(null,r,i),document.title=r}static applyRoute(s,t={}){this.reflect(s,t),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,t){this.setRoutingMap(t);let e=A.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,i=>{var r;e.multiPub({route:i.detail.route,options:i.detail.options,title:((r=i.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ki.notify(),this.initPopstateListener(),e}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ki.appMap=Object.create(null);function at(s,t){for(let e in t)e.includes("-")?s.style.setProperty(e,t[e]):s.style[e]=t[e]}function Dn(s,t){for(let e in t)t[e].constructor===Boolean?t[e]?s.setAttribute(e,""):s.removeAttribute(e):s.setAttribute(e,t[e])}function Yi(s={tag:"div"}){let t=document.createElement(s.tag);if(s.attributes&&Dn(t,s.attributes),s.styles&&at(t,s.styles),s.properties)for(let e in s.properties)t[e]=s.properties[e];return s.processors&&s.processors.forEach(e=>{e(t)}),s.children&&s.children.forEach(e=>{let i=Yi(e);t.appendChild(i)}),t}var nr="idb-store-ready",Fn="symbiote-db",Nn="symbiote-idb-update_",Vn=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(nr,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return Nn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,t){this.name=s,this.storeName=t,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=e=>{this.db=e.target.result,this.objStore=this.db.createObjectStore(t,{keyPath:"_key"}),this.objStore.transaction.oncomplete=i=>{this._notifyWhenReady(i)}},this.request.onsuccess=e=>{this.db=e.target.result,this._notifyWhenReady(e)},this.request.onerror=e=>{console.error(e)},this._subscriptionsMap={},this._updateHandler=e=>{e.key===this.name&&this._subscriptionsMap[e.newValue]&&this._subscriptionsMap[e.newValue].forEach(async r=>{r(await this.read(e.newValue))})},this._localUpdateHandler=e=>{this._updateHandler(e.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((i,r)=>{e.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?i(o.target.result._value):(i(null),console.warn(`IDB: cannot read "${s}"`))},e.onerror=o=>{r(o)}})}write(s,t,e=!1){let i={_key:s,_value:t},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(i);return new Promise((n,a)=>{o.onsuccess=l=>{e||this._notifySubscribers(s),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(s,t=!1){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,o)=>{i.onsuccess=n=>{t||this._notifySubscribers(s),r(n)},i.onerror=n=>{o(n)}})}getAll(){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((e,i)=>{t.onsuccess=r=>{let o=r.target.result;e(o.map(n=>n._value))},t.onerror=r=>{i(r)}})}subscribe(s,t){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let e=this._subscriptionsMap[s];return e.add(t),{remove:()=>{e.delete(t),e.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,ar.clear(this.name)}},ar=class{static get readyEventName(){return nr}static open(s=Fn,t="store"){let e=s+"/"+t;return this._reg[e]||(this._reg[e]=new Vn(s,t)),this._reg[e]}static clear(s){window.indexedDB.deleteDatabase(s);for(let t in this._reg)t.split("/")[0]===s&&delete this._reg[t]}};Zi(ar,"_reg",Object.create(null));var lr=s=>{if(typeof s!="string"||!s)return"";let t=s.trim();return t.startsWith("-/")?t=t.slice(2):t.startsWith("/")&&(t=t.slice(1)),t.endsWith("/")&&(t=t.slice(0,t.length-1)),t},Bt=(...s)=>s.filter(t=>typeof t=="string"&&t).map(t=>lr(t)).join("/-/"),B=(...s)=>{let t=Bt(...s);return t?`-/${t}/`:""};function zt(s){let t=new URL(s),e=t.pathname+t.search+t.hash,i=e.lastIndexOf("http"),r=e.lastIndexOf("/"),o="";return i>=0?o=e.slice(i):r>=0&&(o=e.slice(r+1)),o}function Ht(s){let t=new URL(s),{pathname:e}=t,i=e.indexOf("/"),r=e.indexOf("/",i+1);return e.substring(i+1,r)}function Ji(s){let t=ur(s),e=new URL(t),i=e.pathname.indexOf("/-/");return i===-1?"":e.pathname.substring(i).slice(1)}function cr(s){return Ji(s).split("/-/").filter(Boolean).map(e=>lr(e))}function ur(s){let t=new URL(s),e=zt(s),i=dr(e)?hr(e).pathname:e;return t.pathname=t.pathname.replace(i,""),t.search="",t.hash="",t.toString()}function dr(s){return s.startsWith("http")}function hr(s){let t=new URL(s);return{pathname:t.origin+t.pathname||"",search:t.search||"",hash:t.hash||""}}var R=(s,t,e)=>{let i=new URL(ur(s));if(e=e||zt(s),i.pathname.startsWith("//")&&(i.pathname=i.pathname.replace("//","/")),dr(e)){let r=hr(e);i.pathname=i.pathname+(t||"")+(r.pathname||""),i.search=r.search,i.hash=r.hash}else i.pathname=i.pathname+(t||"")+(e||"");return i.toString()},Te=(s,t)=>{let e=new URL(s);return e.pathname=t+"/",e.toString()};var N=(s,t=",")=>s.trim().split(t).map(e=>e.trim()).filter(e=>e.length>0);var J=Object.freeze({brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0,mirror:!1,flip:!1,crop:void 0}),fr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function Bn(s,t){if(typeof t=="number"){let e=t;return J[s]!==e?`${s}/${e}`:""}if(typeof t=="boolean"){let e=t;return J[s]!==e?`${s}`:""}if(s==="filter"&&t){let{name:e,amount:i}=t;return J.filter===i?"":`${s}/${e}/${i}`}if(s==="crop"&&t){let{dimensions:e,coords:i}=t;return`${s}/${e.join("x")}/${i.join(",")}`}return""}function Se(s){return Bt(...fr.filter(t=>typeof s[t]!="undefined"&&s[t]!==null).map(t=>{let e=s[t];return Bn(t,e)}).filter(t=>!!t))}var jt=Bt("format/auto","progressive/yes"),be=([s])=>typeof s!="undefined"?Number(s):void 0,pr=()=>!0,zn=([s,t])=>({name:s,amount:typeof t!="undefined"?Number(t):100}),Hn=([s,t])=>{if(!/\d+x\d+/.test(s)||!/\d+,\d+/.test(t))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:N(s,"x").map(Number),coords:N(t).map(Number)}},jn=Object.freeze({enhance:be,brightness:be,exposure:be,gamma:be,contrast:be,saturation:be,vibrance:be,warmth:be,filter:zn,mirror:pr,flip:pr,rotate:be,crop:Hn});function mr(s){let t={};for(let e of s){let[i,...r]=e.split("/");if(!fr.includes(i))continue;let o=i,n=jn[o];try{let a=n(r);t[o]=a}catch(a){console.warn([`Failed to parse URL operation "${e}". It will be ignored.`,a instanceof Error?`Error message: "${a.message}"`:a,"If you need this functionality, please feel free to open an issue at https://github.com/uploadcare/blocks/issues/new"].join(` `))}}return t}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),q=[L.CROP,L.TUNING,L.FILTERS],gr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],br=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],_r=["rotate","mirror","flip"],ae=Object.freeze({brightness:{zero:J.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:J.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:J.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:J.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:J.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:J.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:J.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:J.enhance,range:[0,100],keypointsNumber:1},filter:{zero:J.filter,range:[0,100],keypointsNumber:1}});var K=s=>s?s.split(",").map(t=>t.trim()).filter(Boolean):[],_e=s=>s?s.join(","):"";var Qi="https://ucarecdn.com",Gn="https://upload.uploadcare.com",Wn="https://social.uploadcare.com",Xn="https://ucarecd.net",se={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",externalSourcesEmbedCss:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",topLevelOrigin:"",cloudImageEditorTabs:_e(q),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Qi,cdnCnamePrefixed:Xn,baseUrl:Gn,socialBaseUrl:Wn,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:10,retryNetworkErrorMaxTimes:3,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",debug:!1,metadata:null,localeName:"en",localeDefinitionOverride:null,secureUploadsExpireThreshold:10*60*1e3,secureUploadsSignatureResolver:null,secureDeliveryProxyUrlResolver:null,iconHrefResolver:null,fileValidators:[],collectionValidators:[],cameraModes:"photo, video",defaultCameraMode:null,enableAudioRecording:!0,enableVideoRecording:null,maxVideoRecordingDuration:null,mediaRecorderOptions:null,filesViewMode:"list",gridShowFileNames:!1,cloudImageEditorAutoOpen:!1,cloudImageEditorMaskHref:null,testMode:!1};var O=Object.freeze({FILE_ADDED:"file-added",FILE_REMOVED:"file-removed",FILE_UPLOAD_START:"file-upload-start",FILE_UPLOAD_PROGRESS:"file-upload-progress",FILE_UPLOAD_SUCCESS:"file-upload-success",FILE_UPLOAD_FAILED:"file-upload-failed",FILE_URL_CHANGED:"file-url-changed",MODAL_OPEN:"modal-open",MODAL_CLOSE:"modal-close",DONE_CLICK:"done-click",UPLOAD_CLICK:"upload-click",ACTIVITY_CHANGE:"activity-change",COMMON_UPLOAD_START:"common-upload-start",COMMON_UPLOAD_PROGRESS:"common-upload-progress",COMMON_UPLOAD_SUCCESS:"common-upload-success",COMMON_UPLOAD_FAILED:"common-upload-failed",CHANGE:"change",GROUP_CREATED:"group-created"}),Gt=class{constructor(t){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);u(this,"_debugPrint",null);this._debugPrint=t}bindTarget(t){this._targets.add(t)}unbindTarget(t){this._targets.delete(t)}_dispatch(t,e){var i;for(let r of this._targets)r.dispatchEvent(new CustomEvent(t,{detail:e}));(i=this._debugPrint)==null||i.call(this,()=>{let r=e&&typeof e=="object"?{...e}:e;return[`event "${t}"`,r]})}emit(t,e,{debounce:i}={}){if(typeof i!="number"&&!i){this._dispatch(t,typeof e=="function"?e():e);return}this._timeoutStore.has(t)&&window.clearTimeout(this._timeoutStore.get(t));let r=typeof i=="number"?i:20,o=window.setTimeout(()=>{this._dispatch(t,typeof e=="function"?e():e),this._timeoutStore.delete(t)},r);this._timeoutStore.set(t,o)}};function $(s,t){let e,i=(...r)=>{clearTimeout(e),e=setTimeout(()=>s(...r),t)};return i.cancel=()=>{clearTimeout(e)},i}var vr="--uploadcare-blocks-window-height",Pe=class{static registerClient(t){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(t)}static unregisterClient(t){this.clientsRegistry.delete(t),this.clientsRegistry.size===0&&this.detachTracker()}static attachTracker(){window.addEventListener("resize",this.flush,{passive:!0,capture:!0}),this.flush()}static detachTracker(){window.removeEventListener("resize",this.flush,{capture:!0}),document.documentElement.style.removeProperty(vr)}};u(Pe,"clientsRegistry",new Set),u(Pe,"flush",$(()=>{document.documentElement.style.setProperty(vr,`${window.innerHeight}px`)},100));var yr=s=>{var i;let t=new Intl.Locale(s),e="ltr";return typeof t.getTextInfo=="function"&&t.getTextInfo().direction?e=t.getTextInfo().direction:"textInfo"in t&&((i=t.textInfo)!=null&&i.direction)&&(e=t.textInfo.direction),e};var Wt=(s,t)=>new Intl.PluralRules(s).select(t);var qn=s=>s,es="{{",Cr="}}",wr="plural:";function lt(s,t,e={}){var n;let{openToken:i=es,closeToken:r=Cr,transform:o=qn}=e;for(let a in t){let l=(n=t[a])==null?void 0:n.toString();s=s.replaceAll(i+a+r,typeof l=="string"?o(l):l)}return s}function xr(s){let t=[],e=s.indexOf(es);for(;e!==-1;){let i=s.indexOf(Cr,e),r=s.substring(e+2,i);if(r.startsWith(wr)){let o=s.substring(e+2,i).replace(wr,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));t.push({variable:r,pluralKey:n,countVariable:a})}e=s.indexOf(es,i)}return t}var Er=({element:s,attribute:t,onSuccess:e,onTimeout:i,timeout:r=300})=>{let o=s.getAttribute(t);if(o!==null){e(o);return}let n=new MutationObserver(c=>{let h=c[c.length-1];l(h)});n.observe(s,{attributes:!0,attributeFilter:[t]});let a=setTimeout(()=>{n.disconnect(),i()},r),l=c=>{let h=s.getAttribute(t);c.type==="attributes"&&c.attributeName===t&&h!==null&&(clearTimeout(a),n.disconnect(),e(h))}};function Ar(s){return Object.prototype.toString.call(s)==="[object Object]"}var Kn=/\W|_/g;function Zn(s){return s.split(Kn).map((t,e)=>t.charAt(0)[e>0?"toUpperCase":"toLowerCase"]()+t.slice(1)).join("")}function Tr(s,{ignoreKeys:t}={ignoreKeys:[]}){return Array.isArray(s)?s.map(e=>we(e,{ignoreKeys:t})):s}function we(s,{ignoreKeys:t}={ignoreKeys:[]}){if(Array.isArray(s))return Tr(s,{ignoreKeys:t});if(!Ar(s))return s;let e={};for(let i of Object.keys(s)){let r=s[i];if(t.includes(i)){e[i]=r;continue}Ar(r)?r=we(r,{ignoreKeys:t}):Array.isArray(r)&&(r=Tr(r,{ignoreKeys:t})),e[Zn(i)]=r}return e}var Yn=s=>new Promise(t=>setTimeout(t,s));function as({libraryName:s,libraryVersion:t,userAgent:e,publicKey:i="",integration:r=""}){let o="JavaScript";if(typeof e=="string")return e;if(typeof e=="function")return e({publicKey:i,libraryName:s,libraryVersion:t,languageName:o,integration:r});let n=[s,t,i].filter(Boolean).join("/"),a=[o,r].filter(Boolean).join("; ");return`${n} (${a})`}var Jn={factor:2,time:100};function Qn(s,t=Jn){let e=0;function i(r){let o=Math.round(t.time*t.factor**e);return r({attempt:e,retry:a=>Yn(a!=null?a:o).then(()=>(e+=1,i(r)))})}return i(s)}var Ue=class extends Error{},je=class s extends Ue{constructor(e){super();u(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,s.prototype),this.originalProgressEvent=e}},qt=(s,t)=>{s&&(s.aborted?Promise.resolve().then(t):s.addEventListener("abort",()=>t(),{once:!0}))},Ie=class s extends Ue{constructor(e="Request canceled"){super(e);u(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,s.prototype)}},ea=500,Ir=({check:s,interval:t=ea,timeout:e,signal:i})=>new Promise((r,o)=>{let n,a;qt(i,()=>{n&&clearTimeout(n),o(new Ie("Poll cancelled"))}),e&&(a=setTimeout(()=>{n&&clearTimeout(n),o(new Ie("Timed out"))},e));let l=()=>{try{Promise.resolve(s(i)).then(c=>{c?(a&&clearTimeout(a),r(c)):n=setTimeout(l,t)}).catch(c=>{a&&clearTimeout(a),o(c)})}catch(c){a&&clearTimeout(a),o(c)}};n=setTimeout(l,0)}),S={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Kt="application/octet-stream",Or="original",Oe=({method:s,url:t,data:e,headers:i={},signal:r,onProgress:o})=>new Promise((n,a)=>{let l=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",h=!1;l.open(c,t,!0),i&&Object.entries(i).forEach(d=>{let[p,f]=d;typeof f!="undefined"&&!Array.isArray(f)&&l.setRequestHeader(p,f)}),l.responseType="text",qt(r,()=>{h=!0,l.abort(),a(new Ie)}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let d={method:c,url:t,data:e,headers:i||void 0,signal:r,onProgress:o},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),f={};p.forEach(function(w){let C=w.split(": "),v=C.shift(),y=C.join(": ");v&&typeof v!="undefined"&&(f[v]=y)});let m=l.response,b=l.status;n({request:d,data:m,headers:f,status:b})}},l.onerror=d=>{h||a(new je(d))},o&&typeof o=="function"&&(l.upload.onprogress=d=>{d.lengthComputable?o({isComputable:!0,value:d.loaded/d.total}):o({isComputable:!1})}),e?l.send(e):l.send()});function ta(s,...t){return s}var ia=({name:s})=>s?[s]:[],sa=ta,ra=()=>new FormData,kr=s=>!1,Zt=s=>typeof Blob!="undefined"&&s instanceof Blob,Yt=s=>typeof File!="undefined"&&s instanceof File,Jt=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Ge=s=>Zt(s)||Yt(s)||kr()||Jt(s),oa=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",na=s=>!!s&&typeof s=="object"&&!Array.isArray(s),aa=s=>!!s&&typeof s=="object"&&"data"in s&&Ge(s.data);function $r(s,t,e){if(Array.isArray(e))for(let i of e)$r(s,`${t}[]`,i);else if(aa(e)){let{name:i,contentType:r}=e,o=sa(e.data,i,r!=null?r:Kt),n=ia({name:i,contentType:r});s.push([t,o,...n])}else if(na(e))for(let[i,r]of Object.entries(e))typeof r!="undefined"&&s.push([`${t}[${i}]`,String(r)]);else oa(e)&&e&&s.push([t,e.toString()])}function la(s){let t=[];for(let[e,i]of Object.entries(s))$r(t,e,i);return t}function Qt(s){let t=ra(),e=la(s);for(let i of e){let[r,o,...n]=i;t.append(r,o,...n)}return t}var z=class s extends Ue{constructor(e,i,r,o,n){super();u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadError",this.message=e,this.code=i,this.request=r,this.response=o,this.headers=n,Object.setPrototypeOf(this,s.prototype)}},ca=s=>{let t=new URLSearchParams;for(let[e,i]of Object.entries(s))i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).filter(r=>{var o;return(o=r[1])!=null?o:!1}).forEach(r=>t.set(`${e}[${r[0]}]`,String(r[1]))):Array.isArray(i)?i.forEach(r=>{t.append(`${e}[]`,r)}):typeof i=="string"&&i?t.set(e,i):typeof i=="number"&&t.set(e,i.toString());return t.toString()},ve=(s,t,e)=>{let i=new URL(s);return i.pathname=(i.pathname+t).replace("//","/"),e&&(i.search=ca(e)),i.toString()},ua="6.17.0",da="UploadcareUploadClient",ha=ua;function Re(s){return as({libraryName:da,libraryVersion:ha,...s})}var pa="RequestThrottledError",Sr=15e3,fa=1e3;function ma(s){let{headers:t}=s||{};if(!t||typeof t["retry-after"]!="string")return Sr;let e=parseInt(t["retry-after"],10);return Number.isFinite(e)?e*1e3:Sr}function ke(s,t){let{retryThrottledRequestMaxTimes:e,retryNetworkErrorMaxTimes:i}=t;return Qn(({attempt:r,retry:o})=>s().catch(n=>{if("response"in n&&(n==null?void 0:n.code)===pa&&r<e)return o(ma(n));if(n instanceof je&&r<i)return o((r+1)*fa);throw n}))}var Mr=s=>{let t="";return(Zt(s)||Yt(s)||Jt(s))&&(t=s.type),t||Kt},Lr=s=>{let t="";return Yt(s)&&s.name?t=s.name:Zt(s)||kr()?t="":Jt(s)&&s.name&&(t=s.name),t||Or};function ls(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function ga(s,{publicKey:t,fileName:e,contentType:i,baseURL:r=S.baseURL,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:c,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=S.retryNetworkErrorMaxTimes,metadata:b}){return ke(()=>Oe({method:"POST",url:ve(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Re({publicKey:t,integration:d,userAgent:p})},data:Qt({file:{data:s,name:e||Lr(s),contentType:i||Mr(s)},UPLOADCARE_PUB_KEY:t,UPLOADCARE_STORE:ls(a),signature:o,expire:n,source:h,metadata:b}),signal:l,onProgress:c}).then(({data:w,headers:C,request:v})=>{let y=we(JSON.parse(w));if("error"in y)throw new z(y.error.content,y.error.errorCode,v,y,C);return y}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var ss;(function(s){s.Token="token",s.FileInfo="file_info"})(ss||(ss={}));function ba(s,{publicKey:t,baseURL:e=S.baseURL,store:i,fileName:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,source:c="url",signal:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=S.retryNetworkErrorMaxTimes,metadata:b}){return ke(()=>Oe({method:"POST",headers:{"X-UC-User-Agent":Re({publicKey:t,integration:d,userAgent:p})},url:ve(e,"/from_url/",{jsonerrors:1,pub_key:t,source_url:s,store:ls(i),filename:r,check_URL_duplicates:o?1:void 0,save_URL_duplicates:n?1:void 0,signature:a,expire:l,source:c,metadata:b}),signal:h}).then(({data:w,headers:C,request:v})=>{let y=we(JSON.parse(w));if("error"in y)throw new z(y.error.content,y.error.errorCode,v,y,C);return y}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var Z;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(Z||(Z={}));var _a=s=>"status"in s&&s.status===Z.Error;function va(s,{publicKey:t,baseURL:e=S.baseURL,signal:i,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=S.retryNetworkErrorMaxTimes}={}){return ke(()=>Oe({method:"GET",headers:t?{"X-UC-User-Agent":Re({publicKey:t,integration:r,userAgent:o})}:void 0,url:ve(e,"/from_url/status/",{jsonerrors:1,token:s}),signal:i}).then(({data:l,headers:c,request:h})=>{let d=we(JSON.parse(l));if("error"in d&&!_a(d))throw new z(d.error.content,d.error.errorCode,h,d,c);return d}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:n})}function ya(s,{publicKey:t,baseURL:e=S.baseURL,jsonpCallback:i,secureSignature:r,secureExpire:o,signal:n,source:a,integration:l,userAgent:c,retryThrottledRequestMaxTimes:h=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=S.retryNetworkErrorMaxTimes}){return ke(()=>Oe({method:"POST",headers:{"X-UC-User-Agent":Re({publicKey:t,integration:l,userAgent:c})},url:ve(e,"/group/",{jsonerrors:1}),data:Qt({files:s,callback:i,pub_key:t,signature:r,expire:o,source:a}),signal:n}).then(({data:p,headers:f,request:m})=>{let b=we(JSON.parse(p));if("error"in b)throw new z(b.error.content,b.error.errorCode,m,b,f);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function Pr(s,{publicKey:t,baseURL:e=S.baseURL,signal:i,source:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}){return ke(()=>Oe({method:"GET",headers:{"X-UC-User-Agent":Re({publicKey:t,integration:o,userAgent:n})},url:ve(e,"/info/",{jsonerrors:1,pub_key:t,file_id:s,source:r}),signal:i}).then(({data:c,headers:h,request:d})=>{let p=we(JSON.parse(c));if("error"in p)throw new z(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function wa(s,{publicKey:t,contentType:e,fileName:i,multipartChunkSize:r=S.multipartChunkSize,baseURL:o="",secureSignature:n,secureExpire:a,store:l,signal:c,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=S.retryNetworkErrorMaxTimes,metadata:b}){return ke(()=>Oe({method:"POST",url:ve(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Re({publicKey:t,integration:d,userAgent:p})},data:Qt({filename:i||Or,size:s,content_type:e||Kt,part_size:r,UPLOADCARE_STORE:ls(l),UPLOADCARE_PUB_KEY:t,signature:n,expire:a,source:h,metadata:b}),signal:c}).then(({data:w,headers:C,request:v})=>{let y=we(JSON.parse(w));if("error"in y)throw new z(y.error.content,y.error.errorCode,v,y,C);return y.parts=Object.keys(y.parts).map(U=>y.parts[Number(U)]),y}),{retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})}function Ca(s,t,{contentType:e,signal:i,onProgress:r,retryThrottledRequestMaxTimes:o=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=S.retryNetworkErrorMaxTimes}){return ke(()=>Oe({method:"PUT",url:t,data:s,onProgress:r,signal:i,headers:{"Content-Type":e||Kt}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n})}function xa(s,{publicKey:t,baseURL:e=S.baseURL,source:i="local",signal:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}){return ke(()=>Oe({method:"POST",url:ve(e,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Re({publicKey:t,integration:o,userAgent:n})},data:Qt({uuid:s,UPLOADCARE_PUB_KEY:t,source:i}),signal:r}).then(({data:c,headers:h,request:d})=>{let p=we(JSON.parse(c));if("error"in p)throw new z(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function cs(s,{publicKey:t,baseURL:e,source:i,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a,signal:l,onProgress:c}){return Ir({check:h=>Pr(s,{publicKey:t,baseURL:e,signal:h,source:i,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:l})}function Ea(s){return"defaultEffects"in s}var ye=class{constructor(t,{baseCDN:e=S.baseCDN,fileName:i}={}){u(this,"uuid");u(this,"name");u(this,"size");u(this,"isStored");u(this,"isImage");u(this,"mimeType");u(this,"cdnUrl");u(this,"s3Url");u(this,"originalFilename");u(this,"imageInfo");u(this,"videoInfo");u(this,"contentInfo");u(this,"metadata");u(this,"s3Bucket");u(this,"defaultEffects",null);let{uuid:r,s3Bucket:o}=t,n=ve(e,`${r}/`),a=o?ve(`https://${o}.s3.amazonaws.com/`,`${r}/${t.filename}`):null;this.uuid=r,this.name=i||t.filename,this.size=t.size,this.isStored=t.isStored,this.isImage=t.isImage,this.mimeType=t.mimeType,this.cdnUrl=n,this.originalFilename=t.originalFilename,this.imageInfo=t.imageInfo,this.videoInfo=t.videoInfo,this.contentInfo=t.contentInfo,this.metadata=t.metadata||null,this.s3Bucket=o||null,this.s3Url=a,Ea(t)&&(this.defaultEffects=t.defaultEffects)}},Aa=(s,{publicKey:t,fileName:e,baseURL:i,secureSignature:r,secureExpire:o,store:n,contentType:a,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:w})=>ga(s,{publicKey:t,fileName:e,contentType:a,baseURL:i,secureSignature:r,secureExpire:o,store:n,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:w}).then(({file:C})=>cs(C,{publicKey:t,baseURL:i,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:c,signal:l})).then(C=>new ye(C,{baseCDN:b})),Ta=(s,{publicKey:t,fileName:e,baseURL:i,signal:r,onProgress:o,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>Pr(s,{publicKey:t,baseURL:i,signal:r,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(p=>new ye(p,{baseCDN:d,fileName:e})).then(p=>(o&&o({isComputable:!0,value:1}),p)),Sa=(s,{signal:t}={})=>{let e=null,i=null,r=s.map(()=>new AbortController),o=n=>()=>{i=n,r.forEach((a,l)=>l!==n&&a.abort())};return qt(t,()=>{r.forEach(n=>n.abort())}),Promise.all(s.map((n,a)=>{let l=o(a);return Promise.resolve().then(()=>n({stopRace:l,signal:r[a].signal})).then(c=>(l(),c)).catch(c=>(e=c,null))})).then(n=>{if(i===null)throw e;return n[i]})},Ia=window.WebSocket,rs=class{constructor(){u(this,"events",Object.create({}))}emit(t,e){var i;(i=this.events[t])==null||i.forEach(r=>r(e))}on(t,e){this.events[t]=this.events[t]||[],this.events[t].push(e)}off(t,e){e?this.events[t]=this.events[t].filter(i=>i!==e):this.events[t]=[]}},Oa=(s,t)=>s==="success"?{status:Z.Success,...t}:s==="progress"?{status:Z.Progress,...t}:{status:Z.Error,...t},os=class{constructor(t,e=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new rs);u(this,"disconnectTimeoutId",null);this.key=t,this.disconnectTime=e}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let t=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Ia(t),this.ws.addEventListener("error",e=>{this.emmitter.emit("error",new Error(e.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(e=>this.send(e.event,e.data)),this.queue=[]}),this.ws.addEventListener("message",e=>{let i=JSON.parse(e.data.toString());switch(i.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(i.channel,Oa(i.event,JSON.parse(i.data)))}})}}disconnect(){let t=()=>{var e;(e=this.ws)==null||e.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{t()},this.disconnectTime):t()}send(t,e){var r;let i=JSON.stringify({event:t,data:e});(r=this.ws)==null||r.send(i)}subscribe(t,e){this.subscribers+=1,this.connect();let i=`task-status-${t}`,r={event:"pusher:subscribe",data:{channel:i}};this.emmitter.on(i,e),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(t){this.subscribers-=1;let e=`task-status-${t}`,i={event:"pusher:unsubscribe",data:{channel:e}};this.emmitter.off(e),this.isConnected?this.send(i.event,i.data):this.queue=this.queue.filter(r=>r.data.channel!==e),this.subscribers===0&&this.disconnect()}onError(t){return this.emmitter.on("error",t),()=>this.emmitter.off("error",t)}},ts=null,us=s=>{if(!ts){let t=typeof window=="undefined"?0:3e4;ts=new os(s,t)}return ts},ka=s=>{us(s).connect()};function $a({token:s,publicKey:t,baseURL:e,integration:i,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,onProgress:a,signal:l}){return Ir({check:c=>va(s,{publicKey:t,baseURL:e,integration:i,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,signal:c}).then(h=>{switch(h.status){case Z.Error:return new z(h.error,h.errorCode);case Z.Waiting:return!1;case Z.Unknown:return new z(`Token "${s}" was not found.`);case Z.Progress:return a&&(h.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:h.done/h.total})),!1;case Z.Success:return a&&a({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:l})}var Ma=({token:s,pusherKey:t,signal:e,onProgress:i})=>new Promise((r,o)=>{let n=us(t),a=n.onError(o),l=()=>{a(),n.unsubscribe(s)};qt(e,()=>{l(),o(new Ie("pusher cancelled"))}),n.subscribe(s,c=>{switch(c.status){case Z.Progress:{i&&(c.total==="unknown"?i({isComputable:!1}):i({isComputable:!0,value:c.done/c.total}));break}case Z.Success:{l(),i&&i({isComputable:!0,value:c.done/c.total}),r(c);break}case Z.Error:l(),o(new z(c.msg,c.error_code))}})}),La=(s,{publicKey:t,fileName:e,baseURL:i,baseCDN:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:c,signal:h,onProgress:d,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:w=S.pusherKey,metadata:C})=>Promise.resolve(ka(w)).then(()=>ba(s,{publicKey:t,fileName:e,baseURL:i,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:c,signal:h,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:C})).catch(v=>{let y=us(w);return y==null||y.disconnect(),Promise.reject(v)}).then(v=>v.type===ss.FileInfo?v:Sa([({signal:y})=>$a({token:v.token,publicKey:t,baseURL:i,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:y}),({signal:y})=>Ma({token:v.token,pusherKey:w,signal:y,onProgress:d})],{signal:h})).then(v=>{if(v instanceof z)throw v;return v}).then(v=>cs(v.uuid,{publicKey:t,baseURL:i,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,on