@uploadcare/file-uploader
Version:
Building blocks for Uploadcare products integration
29 lines • 283 kB
JavaScript
/**
* @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 an=Object.defineProperty;var ln=Object.getPrototypeOf;var cn=Reflect.get;var un=(s,i,e)=>i in s?an(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e;var u=(s,i,e)=>un(s,typeof i!="symbol"?i+"":i,e);var X=(s,i,e)=>cn(ln(s),e,i);var dn=Object.defineProperty,hn=(s,i,e)=>i in s?dn(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,Zi=(s,i,e)=>(hn(s,typeof i!="symbol"?i+"":i,e),e);function pn(s){let i=e=>{var t;for(let r in e)((t=e[r])==null?void 0:t.constructor)===Object&&(e[r]=i(e[r]));return{...e}};return i(s)}var A=class{constructor(s){s.constructor===Object?this.store=pn(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}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,i,e=!1){!e&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){A.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,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(i),e&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let e=A.globalStore.get(i);return e?console.warn('State: context UID "'+i+'" already in use'):(e=new A(s),A.globalStore.set(i,e)),e}static deleteCtx(s){A.globalStore.delete(s)}static getCtx(s,i=!0){return A.globalStore.get(s)||(i&&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"}),tr="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",fn=tr.length-1,ze=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let e=0;e<s.length;e++)i+=s[e]==="-"?s[e]:tr.charAt(Math.random()*fn);return i}};function ir(s,i,e){let t=!0,r,o=i.split(".");return o.forEach((n,a)=>{a<o.length-1?s=s[n]:r=n}),s?s[r]=e:t=!1,t}function mn(s){return s.split("-").map((i,e)=>i&&e?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,e)=>i&&e?i.toUpperCase():i).join("")}function gn(s,i){[...s.querySelectorAll(`[${E.REPEAT_ATTR}]`)].forEach(e=>{let t=e.getAttribute(E.REPEAT_ITEM_TAG_ATTR),r;if(t&&(r=window.customElements.get(t)),!r){r=class extends i.BaseComponent{constructor(){super(),t||(this.style.display="contents")}};let n=e.innerHTML;r.template=n,r.reg(t)}for(;e.firstChild;)e.firstChild.remove();let o=e.getAttribute(E.REPEAT_ATTR);i.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 Qs="__default__";function bn(s,i){if(i.shadowRoot)return;let e=[...s.querySelectorAll("slot")];if(!e.length)return;let t={};e.forEach(r=>{let o=r.getAttribute("name")||Qs;t[o]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var o;let n=Qs;r instanceof Element&&r.hasAttribute("slot")&&(n=r.getAttribute("slot"),r.removeAttribute("slot")),(o=t[n])==null||o.fr.appendChild(r)}),Object.values(t).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 _n(s,i){[...s.querySelectorAll(`[${E.EL_REF_ATTR}]`)].forEach(e=>{let t=e.getAttribute(E.EL_REF_ATTR);i.ref[t]=e,e.removeAttribute(E.EL_REF_ATTR)})}function vn(s,i){[...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=mn(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("!","")),i.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):ir(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 Ft="{{",nt="}}",yn="skip-text";function wn(s){let i,e=[],t=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var o;return!((o=r.parentElement)!=null&&o.hasAttribute(yn))&&r.textContent.includes(Ft)&&r.textContent.includes(nt)&&1}});for(;i=t.nextNode();)e.push(i);return e}var Cn=function(s,i){wn(s).forEach(t=>{let r=[],o;for(;t.textContent.includes(nt);)t.textContent.startsWith(Ft)?(o=t.textContent.indexOf(nt)+nt.length,t.splitText(o),r.push(t)):(o=t.textContent.indexOf(Ft),t.splitText(o)),t=t.nextSibling;r.forEach(n=>{let a=n.textContent.replace(Ft,"").replace(nt,"");n.textContent="",i.sub(a,l=>{n.textContent=l})})})},xn=[gn,bn,_n,vn,Cn],Nt="'",Be='"',En=/\\([0-9a-fA-F]{1,6} ?)/g;function An(s){return(s[0]===Be||s[0]===Nt)&&(s[s.length-1]===Be||s[s.length-1]===Nt)}function Tn(s){return(s[0]===Be||s[0]===Nt)&&(s=s.slice(1)),(s[s.length-1]===Be||s[s.length-1]===Nt)&&(s=s.slice(0,-1)),s}function Sn(s){let i="",e="";for(var t=0;t<s.length;t++){let r=s[t+1];s[t]==="\\"&&r==='"'?(i+='\\"',t++):s[t]==='"'&&e!=="\\"?i+='\\"':i+=s[t],e=s[t]}return i}function In(s){let i=s;An(s)&&(i=Tn(i),i=i.replace(En,(e,t)=>String.fromCodePoint(parseInt(t.trim(),16))),i=i.replaceAll(`\\
`,"\\n"),i=Sn(i),i=Be+i+Be);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var er=0,Ve=null,fe=null,xe=class extends HTMLElement{constructor(){super(),Zi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let e=this.getCssData(this.__extractCssName(i),!0);e!==null&&this.$[i]!==e&&(this.$[i]=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 xe}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let e;if((i||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 t=()=>{e&&(i&&this.shadowRoot.appendChild(e)||this.appendChild(e)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=t,this.shadowRoot.prepend(r)}else t()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ze.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 i=((s=this.getAttribute(E.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}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,i){let e,t;if(s.startsWith(E.EXT_DATA_CTX_PRFX))e=i.nodeCtx,t=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]),t=r[1]}else e=i.localCtx,t=s;return{ctx:e,name:t}}sub(s,i,e=!0){let t=o=>{this.isConnected&&i(o)},r=xe.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,t,e)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,t,e))})}notify(s){let i=xe.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=xe.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,e=!1){let t=xe.__parseProp(s,this);t.ctx.add(t.name,i,e)}add$(s,i=!1){for(let e in s)this.add(e,s[e],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,e,t)=>{let r=xe.__parseProp(e,this);return r.ctx.pub(r.name,t),!0},get:(i,e)=>{let t=xe.__parseProp(e,this);return t.ctx.read(t.name)}})}return this.__stateProxy}set$(s,i=!1){for(let e in s){let t=s[e];i||![String,Number,Boolean].includes(t==null?void 0:t.constructor)?this.$[e]=t:this.$[e]!==t&&(this.$[e]=t)}}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 i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(E.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(E.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(E.NAMED_DATA_CTX_SPLTR)){let e=i.split(E.NAMED_DATA_CTX_SPLTR),t=e[0].trim(),r=e[1].trim();if(t&&r){let o=A.getCtx(t,!1);o||(o=A.registerCtx({},t)),o.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(E.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(E.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[E.SET_LATER_KEY]){for(let e in this[E.SET_LATER_KEY])ir(this,e,this[E.SET_LATER_KEY][e]);delete this[E.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let e of xn)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);fe==null||fe.delete(this.updateCssData),fe!=null&&fe.size||(Ve==null||Ve.disconnect(),Ve=null,fe=null)},100)))}static reg(s,i=!1){s||(er++,s=`${E.AUTO_TAG_PRFX}-${er}`),this.__tag=s;let e=window.customElements.get(s);if(e){!i&&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,i?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,i,e){var t;if(i===e)return;let r=(t=this.constructor.__attrDesc)==null?void 0:t[s];r?this.__dataCtxInitialized?this.$[r]=e:this.init$[r]=e:this[s]=e}getCssData(s,i=!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]=In(e)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,e)=>e===0?"":i).join("--")}__initStyleAttrObserver(){fe||(fe=new Set),fe.add(this.updateCssData),Ve||(Ve=new MutationObserver(s=>{s[0].type==="attributes"&&fe.forEach(i=>{i()})}),Ve.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let e=this.getCssData(this.__extractCssName(s),!0);e===null&&(e=i),this.add(s,e),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,e){let t="__"+s;this[t]=this[s],Object.defineProperty(this,s,{set:r=>{this[t]=r,e?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[t]}),this[s]=this[t]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),e=URL.createObjectURL(i),t=document.createElement("link");t.href=e,t.rel="stylesheet",this.__rootStylesLink=t}}},Ee=xe;Zi(Ee,"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 i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}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 t=e.split("=");s.options[t[0]]=decodeURI(t[1])}else s.options[e]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let e=new CustomEvent(Ki.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(e)}static reflect(s,i={}){let e=this.appMap[s];if(!e){this._print("Wrong route: "+s);return}let t="?"+s;for(let o in i)i[o]===!0?t+=this.separator+o:t+=this.separator+o+`=${i[o]}`;let r=e.title||this.defaultTitle||"";window.history.pushState(null,r,t),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let e=A.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,t=>{var r;e.multiPub({route:t.detail.route,options:t.detail.options,title:((r=t.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,i){for(let e in i)e.includes("-")?s.style.setProperty(e,i[e]):s.style[e]=i[e]}function On(s,i){for(let e in i)i[e].constructor===Boolean?i[e]?s.setAttribute(e,""):s.removeAttribute(e):s.setAttribute(e,i[e])}function Yi(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&On(i,s.attributes),s.styles&&at(i,s.styles),s.properties)for(let e in s.properties)i[e]=s.properties[e];return s.processors&&s.processors.forEach(e=>{e(i)}),s.children&&s.children.forEach(e=>{let t=Yi(e);i.appendChild(t)}),i}var sr="idb-store-ready",kn="symbiote-db",$n="symbiote-idb-update_",Mn=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(sr,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return $n+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,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=t=>{this._notifyWhenReady(t)}},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((t,r)=>{e.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?t(o.target.result._value):(t(null),console.warn(`IDB: cannot read "${s}"`))},e.onerror=o=>{r(o)}})}write(s,i,e=!1){let t={_key:s,_value:i},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(t);return new Promise((n,a)=>{o.onsuccess=l=>{e||this._notifySubscribers(s),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(s,i=!1){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,o)=>{t.onsuccess=n=>{i||this._notifySubscribers(s),r(n)},t.onerror=n=>{o(n)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((e,t)=>{i.onsuccess=r=>{let o=r.target.result;e(o.map(n=>n._value))},i.onerror=r=>{t(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let e=this._subscriptionsMap[s];return e.add(i),{remove:()=>{e.delete(i),e.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,rr.clear(this.name)}},rr=class{static get readyEventName(){return sr}static open(s=kn,i="store"){let e=s+"/"+i;return this._reg[e]||(this._reg[e]=new Mn(s,i)),this._reg[e]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Zi(rr,"_reg",Object.create(null));var or=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Vt=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>or(i)).join("/-/"),B=(...s)=>{let i=Vt(...s);return i?`-/${i}/`:""};function Bt(s){let i=new URL(s),e=i.pathname+i.search+i.hash,t=e.lastIndexOf("http"),r=e.lastIndexOf("/"),o="";return t>=0?o=e.slice(t):r>=0&&(o=e.slice(r+1)),o}function zt(s){let i=new URL(s),{pathname:e}=i,t=e.indexOf("/"),r=e.indexOf("/",t+1);return e.substring(t+1,r)}function Ji(s){let i=ar(s),e=new URL(i),t=e.pathname.indexOf("/-/");return t===-1?"":e.pathname.substring(t).slice(1)}function nr(s){return Ji(s).split("/-/").filter(Boolean).map(e=>or(e))}function ar(s){let i=new URL(s),e=Bt(s),t=lr(e)?cr(e).pathname:e;return i.pathname=i.pathname.replace(t,""),i.search="",i.hash="",i.toString()}function lr(s){return s.startsWith("http")}function cr(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var R=(s,i,e)=>{let t=new URL(ar(s));if(e=e||Bt(s),t.pathname.startsWith("//")&&(t.pathname=t.pathname.replace("//","/")),lr(e)){let r=cr(e);t.pathname=t.pathname+(i||"")+(r.pathname||""),t.search=r.search,t.hash=r.hash}else t.pathname=t.pathname+(i||"")+(e||"");return t.toString()},Ae=(s,i)=>{let e=new URL(s);return e.pathname=i+"/",e.toString()};var N=(s,i=",")=>s.trim().split(i).map(e=>e.trim()).filter(e=>e.length>0);var Y=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}),dr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function Ln(s,i){if(typeof i=="number"){let e=i;return Y[s]!==e?`${s}/${e}`:""}if(typeof i=="boolean"){let e=i;return Y[s]!==e?`${s}`:""}if(s==="filter"&&i){let{name:e,amount:t}=i;return Y.filter===t?"":`${s}/${e}/${t}`}if(s==="crop"&&i){let{dimensions:e,coords:t}=i;return`${s}/${e.join("x")}/${t.join(",")}`}return""}function Te(s){return Vt(...dr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let e=s[i];return Ln(i,e)}).filter(i=>!!i))}var Ht=Vt("format/auto","progressive/yes"),me=([s])=>typeof s!="undefined"?Number(s):void 0,ur=()=>!0,Un=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Pn=([s,i])=>{if(!/\d+x\d+/.test(s)||!/\d+,\d+/.test(i))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}},Rn=Object.freeze({enhance:me,brightness:me,exposure:me,gamma:me,contrast:me,saturation:me,vibrance:me,warmth:me,filter:Un,mirror:ur,flip:ur,rotate:me,crop:Pn});function hr(s){let i={};for(let e of s){let[t,...r]=e.split("/");if(!dr.includes(t))continue;let o=t,n=Rn[o];try{let a=n(r);i[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 i}var M=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),q=[M.CROP,M.TUNING,M.FILTERS],pr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],fr=["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"],mr=["rotate","mirror","flip"],ne=Object.freeze({brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}});var K=s=>s?s.split(",").map(i=>i.trim()).filter(Boolean):[],ge=s=>s?s.join(","):"";var Dn="https://ucarecdn.com",Fn="https://upload.uploadcare.com",Nn="https://social.uploadcare.com",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",cloudImageEditorTabs:ge(q),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Dn,baseUrl:Fn,socialBaseUrl:Nn,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:10,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};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"}),jt=class{constructor(i){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);u(this,"_debugPrint",null);this._debugPrint=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,e){var t;for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:e}));(t=this._debugPrint)==null||t.call(this,()=>{let r=e&&typeof e=="object"?{...e}:e;return[`event "${i}"`,r]})}emit(i,e,{debounce:t}={}){if(typeof t!="number"&&!t){this._dispatch(i,typeof e=="function"?e():e);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof t=="number"?t:20,o=window.setTimeout(()=>{this._dispatch(i,typeof e=="function"?e():e),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,o)}};function $(s,i){let e,t=(...r)=>{clearTimeout(e),e=setTimeout(()=>s(...r),i)};return t.cancel=()=>{clearTimeout(e)},t}var gr="--uploadcare-blocks-window-height",Le=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(gr)}};u(Le,"clientsRegistry",new Set),u(Le,"flush",$(()=>{document.documentElement.style.setProperty(gr,`${window.innerHeight}px`)},100));var br=s=>{var t;let i=new Intl.Locale(s),e="ltr";return typeof i.getTextInfo=="function"&&i.getTextInfo().direction?e=i.getTextInfo().direction:"textInfo"in i&&((t=i.textInfo)!=null&&t.direction)&&(e=i.textInfo.direction),e};var Gt=(s,i)=>new Intl.PluralRules(s).select(i);var Vn=s=>s,Qi="{{",vr="}}",_r="plural:";function lt(s,i,e={}){var n;let{openToken:t=Qi,closeToken:r=vr,transform:o=Vn}=e;for(let a in i){let l=(n=i[a])==null?void 0:n.toString();s=s.replaceAll(t+a+r,typeof l=="string"?o(l):l)}return s}function yr(s){let i=[],e=s.indexOf(Qi);for(;e!==-1;){let t=s.indexOf(vr,e),r=s.substring(e+2,t);if(r.startsWith(_r)){let o=s.substring(e+2,t).replace(_r,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:r,pluralKey:n,countVariable:a})}e=s.indexOf(Qi,t)}return i}var wr=({element:s,attribute:i,onSuccess:e,onTimeout:t,timeout:r=300})=>{let o=s.getAttribute(i);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:[i]});let a=setTimeout(()=>{n.disconnect(),t()},r),l=c=>{let h=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&h!==null&&(clearTimeout(a),n.disconnect(),e(h))}};function Cr(s){return Object.prototype.toString.call(s)==="[object Object]"}var Bn=/\W|_/g;function zn(s){return s.split(Bn).map((i,e)=>i.charAt(0)[e>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function xr(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(e=>ve(e,{ignoreKeys:i})):s}function ve(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return xr(s,{ignoreKeys:i});if(!Cr(s))return s;let e={};for(let t of Object.keys(s)){let r=s[t];if(i.includes(t)){e[t]=r;continue}Cr(r)?r=ve(r,{ignoreKeys:i}):Array.isArray(r)&&(r=xr(r,{ignoreKeys:i})),e[zn(t)]=r}return e}var Hn=s=>new Promise(i=>setTimeout(i,s));function ns({libraryName:s,libraryVersion:i,userAgent:e,publicKey:t="",integration:r=""}){let o="JavaScript";if(typeof e=="string")return e;if(typeof e=="function")return e({publicKey:t,libraryName:s,libraryVersion:i,languageName:o,integration:r});let n=[s,i,t].filter(Boolean).join("/"),a=[o,r].filter(Boolean).join("; ");return`${n} (${a})`}var jn={factor:2,time:100};function Gn(s,i=jn){let e=0;function t(r){let o=Math.round(i.time*i.factor**e);return r({attempt:e,retry:a=>Hn(a!=null?a:o).then(()=>(e+=1,t(r)))})}return t(s)}var Ue=class extends Error{},He=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}},Xt=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Se=class s extends Ue{constructor(e="Request canceled"){super(e);u(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,s.prototype)}},Wn=500,Ar=({check:s,interval:i=Wn,timeout:e,signal:t})=>new Promise((r,o)=>{let n,a;Xt(t,()=>{n&&clearTimeout(n),o(new Se("Poll cancelled"))}),e&&(a=setTimeout(()=>{n&&clearTimeout(n),o(new Se("Timed out"))},e));let l=()=>{try{Promise.resolve(s(t)).then(c=>{c?(a&&clearTimeout(a),r(c)):n=setTimeout(l,i)}).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"},qt="application/octet-stream",Tr="original",Ie=({method:s,url:i,data:e,headers:t={},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,i,!0),t&&Object.entries(t).forEach(d=>{let[p,f]=d;typeof f!="undefined"&&!Array.isArray(f)&&l.setRequestHeader(p,f)}),l.responseType="text",Xt(r,()=>{h=!0,l.abort(),a(new Se)}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let d={method:c,url:i,data:e,headers:t||void 0,signal:r,onProgress:o},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),f={};p.forEach(function(C){let w=C.split(": "),v=w.shift(),y=w.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 He(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 Xn(s,...i){return s}var qn=({name:s})=>s?[s]:[],Kn=Xn,Zn=()=>new FormData,Sr=s=>!1,Kt=s=>typeof Blob!="undefined"&&s instanceof Blob,Zt=s=>typeof File!="undefined"&&s instanceof File,Yt=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",je=s=>Kt(s)||Zt(s)||Sr()||Yt(s),Yn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",Jn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),Qn=s=>!!s&&typeof s=="object"&&"data"in s&&je(s.data);function Ir(s,i,e){if(Array.isArray(e))for(let t of e)Ir(s,`${i}[]`,t);else if(Qn(e)){let{name:t,contentType:r}=e,o=Kn(e.data,t,r!=null?r:qt),n=qn({name:t,contentType:r});s.push([i,o,...n])}else if(Jn(e))for(let[t,r]of Object.entries(e))typeof r!="undefined"&&s.push([`${i}[${t}]`,String(r)]);else Yn(e)&&e&&s.push([i,e.toString()])}function ea(s){let i=[];for(let[e,t]of Object.entries(s))Ir(i,e,t);return i}function Jt(s){let i=Zn(),e=ea(s);for(let t of e){let[r,o,...n]=t;i.append(r,o,...n)}return i}var z=class s extends Ue{constructor(e,t,r,o,n){super();u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadError",this.message=e,this.code=t,this.request=r,this.response=o,this.headers=n,Object.setPrototypeOf(this,s.prototype)}},ta=s=>{let i=new URLSearchParams;for(let[e,t]of Object.entries(s))t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).filter(r=>{var o;return(o=r[1])!=null?o:!1}).forEach(r=>i.set(`${e}[${r[0]}]`,String(r[1]))):Array.isArray(t)?t.forEach(r=>{i.append(`${e}[]`,r)}):typeof t=="string"&&t?i.set(e,t):typeof t=="number"&&i.set(e,t.toString());return i.toString()},be=(s,i,e)=>{let t=new URL(s);return t.pathname=(t.pathname+i).replace("//","/"),e&&(t.search=ta(e)),t.toString()},ia="6.14.1",sa="UploadcareUploadClient",ra=ia;function Pe(s){return ns({libraryName:sa,libraryVersion:ra,...s})}var oa="RequestThrottledError",Er=15e3,na=1e3;function aa(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Er;let e=parseInt(i["retry-after"],10);return Number.isFinite(e)?e*1e3:Er}function Oe(s,i){let{retryThrottledRequestMaxTimes:e,retryNetworkErrorMaxTimes:t}=i;return Gn(({attempt:r,retry:o})=>s().catch(n=>{if("response"in n&&(n==null?void 0:n.code)===oa&&r<e)return o(aa(n));if(n instanceof He&&r<t)return o((r+1)*na);throw n}))}var Or=s=>{let i="";return(Kt(s)||Zt(s)||Yt(s))&&(i=s.type),i||qt},kr=s=>{let i="";return Zt(s)&&s.name?i=s.name:Kt(s)||Sr()?i="":Yt(s)&&s.name&&(i=s.name),i||Tr};function as(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function la(s,{publicKey:i,fileName:e,contentType:t,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 Oe(()=>Ie({method:"POST",url:be(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Pe({publicKey:i,integration:d,userAgent:p})},data:Jt({file:{data:s,name:e||kr(s),contentType:t||Or(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:as(a),signature:o,expire:n,source:h,metadata:b}),signal:l,onProgress:c}).then(({data:C,headers:w,request:v})=>{let y=ve(JSON.parse(C));if("error"in y)throw new z(y.error.content,y.error.errorCode,v,y,w);return y}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var is;(function(s){s.Token="token",s.FileInfo="file_info"})(is||(is={}));function ca(s,{publicKey:i,baseURL:e=S.baseURL,store:t,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 Oe(()=>Ie({method:"POST",headers:{"X-UC-User-Agent":Pe({publicKey:i,integration:d,userAgent:p})},url:be(e,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:as(t),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:C,headers:w,request:v})=>{let y=ve(JSON.parse(C));if("error"in y)throw new z(y.error.content,y.error.errorCode,v,y,w);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 ua=s=>"status"in s&&s.status===Z.Error;function da(s,{publicKey:i,baseURL:e=S.baseURL,signal:t,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=S.retryNetworkErrorMaxTimes}={}){return Oe(()=>Ie({method:"GET",headers:i?{"X-UC-User-Agent":Pe({publicKey:i,integration:r,userAgent:o})}:void 0,url:be(e,"/from_url/status/",{jsonerrors:1,token:s}),signal:t}).then(({data:l,headers:c,request:h})=>{let d=ve(JSON.parse(l));if("error"in d&&!ua(d))throw new z(d.error.content,d.error.errorCode,h,d,c);return d}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:n})}function ha(s,{publicKey:i,baseURL:e=S.baseURL,jsonpCallback:t,secureSignature:r,secureExpire:o,signal:n,source:a,integration:l,userAgent:c,retryThrottledRequestMaxTimes:h=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=S.retryNetworkErrorMaxTimes}){return Oe(()=>Ie({method:"POST",headers:{"X-UC-User-Agent":Pe({publicKey:i,integration:l,userAgent:c})},url:be(e,"/group/",{jsonerrors:1}),data:Jt({files:s,callback:t,pub_key:i,signature:r,expire:o,source:a}),signal:n}).then(({data:p,headers:f,request:m})=>{let b=ve(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 $r(s,{publicKey:i,baseURL:e=S.baseURL,signal:t,source:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}){return Oe(()=>Ie({method:"GET",headers:{"X-UC-User-Agent":Pe({publicKey:i,integration:o,userAgent:n})},url:be(e,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:t}).then(({data:c,headers:h,request:d})=>{let p=ve(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 pa(s,{publicKey:i,contentType:e,fileName:t,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 Oe(()=>Ie({method:"POST",url:be(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Pe({publicKey:i,integration:d,userAgent:p})},data:Jt({filename:t||Tr,size:s,content_type:e||qt,part_size:r,UPLOADCARE_STORE:as(l),UPLOADCARE_PUB_KEY:i,signature:n,expire:a,source:h,metadata:b}),signal:c}).then(({data:C,headers:w,request:v})=>{let y=ve(JSON.parse(C));if("error"in y)throw new z(y.error.content,y.error.errorCode,v,y,w);return y.parts=Object.keys(y.parts).map(P=>y.parts[Number(P)]),y}),{retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})}function fa(s,i,{contentType:e,signal:t,onProgress:r,retryThrottledRequestMaxTimes:o=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=S.retryNetworkErrorMaxTimes}){return Oe(()=>Ie({method:"PUT",url:i,data:s,onProgress:r,signal:t,headers:{"Content-Type":e||qt}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n})}function ma(s,{publicKey:i,baseURL:e=S.baseURL,source:t="local",signal:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}){return Oe(()=>Ie({method:"POST",url:be(e,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Pe({publicKey:i,integration:o,userAgent:n})},data:Jt({uuid:s,UPLOADCARE_PUB_KEY:i,source:t}),signal:r}).then(({data:c,headers:h,request:d})=>{let p=ve(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 ls(s,{publicKey:i,baseURL:e,source:t,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a,signal:l,onProgress:c}){return Ar({check:h=>$r(s,{publicKey:i,baseURL:e,signal:h,source:t,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:l})}function ga(s){return"defaultEffects"in s}var _e=class{constructor(i,{baseCDN:e=S.baseCDN,fileName:t}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);u(this,"defaultEffects",null);let{uuid:r,s3Bucket:o}=i,n=be(e,`${r}/`),a=o?be(`https://${o}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=t||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=n,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=o||null,this.s3Url=a,ga(i)&&(this.defaultEffects=i.defaultEffects)}},ba=(s,{publicKey:i,fileName:e,baseURL:t,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:C})=>la(s,{publicKey:i,fileName:e,contentType:a,baseURL:t,secureSignature:r,secureExpire:o,store:n,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:C}).then(({file:w})=>ls(w,{publicKey:i,baseURL:t,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:c,signal:l})).then(w=>new _e(w,{baseCDN:b})),_a=(s,{publicKey:i,fileName:e,baseURL:t,signal:r,onProgress:o,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>$r(s,{publicKey:i,baseURL:t,signal:r,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(p=>new _e(p,{baseCDN:d,fileName:e})).then(p=>(o&&o({isComputable:!0,value:1}),p)),va=(s,{signal:i}={})=>{let e=null,t=null,r=s.map(()=>new AbortController),o=n=>()=>{t=n,r.forEach((a,l)=>l!==n&&a.abort())};return Xt(i,()=>{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(t===null)throw e;return n[t]})},ya=window.WebSocket,ss=class{constructor(){u(this,"events",Object.create({}))}emit(i,e){var t;(t=this.events[i])==null||t.forEach(r=>r(e))}on(i,e){this.events[i]=this.events[i]||[],this.events[i].push(e)}off(i,e){e?this.events[i]=this.events[i].filter(t=>t!==e):this.events[i]=[]}},wa=(s,i)=>s==="success"?{status:Z.Success,...i}:s==="progress"?{status:Z.Progress,...i}:{status:Z.Error,...i},rs=class{constructor(i,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 ss);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=e}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new ya(i),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 t=JSON.parse(e.data.toString());switch(t.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(t.channel,wa(t.event,JSON.parse(t.data)))}})}}disconnect(){let i=()=>{var e;(e=this.ws)==null||e.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,e){var r;let t=JSON.stringify({event:i,data:e});(r=this.ws)==null||r.send(t)}subscribe(i,e){this.subscribers+=1,this.connect();let t=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:t}};this.emmitter.on(t,e),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let e=`task-status-${i}`,t={event:"pusher:unsubscribe",data:{channel:e}};this.emmitter.off(e),this.isConnected?this.send(t.event,t.data):this.queue=this.queue.filter(r=>r.data.channel!==e),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},es=null,cs=s=>{if(!es){let i=typeof window=="undefined"?0:3e4;es=new rs(s,i)}return es},Ca=s=>{cs(s).connect()};function xa({token:s,publicKey:i,baseURL:e,integration:t,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,onProgress:a,signal:l}){return Ar({check:c=>da(s,{publicKey:i,baseURL:e,integration:t,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 Ea=({token:s,pusherKey:i,signal:e,onProgress:t})=>new Promise((r,o)=>{let n=cs(i),a=n.onError(o),l=()=>{a(),n.unsubscribe(s)};Xt(e,()=>{l(),o(new Se("pusher cancelled"))}),n.subscribe(s,c=>{switch(c.status){case Z.Progress:{t&&(c.total==="unknown"?t({isComputable:!1}):t({isComputable:!0,value:c.done/c.total}));break}case Z.Success:{l(),t&&t({isComputable:!0,value:c.done/c.total}),r(c);break}case Z.Error:l(),o(new z(c.msg,c.error_code))}})}),Aa=(s,{publicKey:i,fileName:e,baseURL:t,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:C=S.pusherKey,metadata:w})=>Promise.resolve(Ca(C)).then(()=>ca(s,{publicKey:i,fileName:e,baseURL:t,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:c,signal:h,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:w})).catch(v=>{let y=cs(C);return y==null||y.disconnect(),Promise.reject(v)}).then(v=>v.type===is.FileInfo?v:va([({signal:y})=>xa({token:v.token,publicKey:i,baseURL:t,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:y}),({signal:y})=>Ea({token:v.token,pusherKey:C,signal:y,onProgress:d})],{signal:h})).then(v=>{if(v instanceof z)throw v;return v}).then(v=>ls(v.uuid,{publicKey:i,baseURL:t,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:h})).then(v=>new _e(