UNPKG

@uploadcare/file-uploader

Version:

Building blocks for Uploadcare products integration

29 lines 263 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 Uo=Object.defineProperty;var Mo=Object.getPrototypeOf;var Po=Reflect.get;var Ro=(r,e,t)=>e in r?Uo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var u=(r,e,t)=>(Ro(r,typeof e!="symbol"?e+"":e,t),t);var j=(r,e,t)=>Po(Mo(r),t,e);var Fo=Object.defineProperty,Do=(r,e,t)=>e in r?Fo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pi=(r,e,t)=>(Do(r,typeof e!="symbol"?e+"":e,t),t);function No(r){let e=t=>{var i;for(let s in t)((i=t[s])==null?void 0:i.constructor)===Object&&(t[s]=e(t[s]));return{...t}};return e(r)}var E=class{constructor(r){r.constructor===Object?this.store=No(r):(this._storeIsProxy=!0,this.store=r),this.callbackMap=Object.create(null)}static warn(r,e){console.warn(`Symbiote Data: cannot ${r}. Prop name: `+e)}read(r){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(E.warn("read",r),null):this.store[r]}has(r){return this._storeIsProxy?this.store[r]!==void 0:this.store.hasOwnProperty(r)}add(r,e,t=!1){!t&&Object.keys(this.store).includes(r)||(this.store[r]=e,this.notify(r))}pub(r,e){if(!this._storeIsProxy&&!this.store.hasOwnProperty(r)){E.warn("publish",r);return}this.store[r]=e,this.notify(r)}multiPub(r){for(let e in r)this.pub(e,r[e])}notify(r){this.callbackMap[r]&&this.callbackMap[r].forEach(e=>{e(this.store[r])})}sub(r,e,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(E.warn("subscribe",r),null):(this.callbackMap[r]||(this.callbackMap[r]=new Set),this.callbackMap[r].add(e),t&&e(this.store[r]),{remove:()=>{this.callbackMap[r].delete(e),this.callbackMap[r].size||delete this.callbackMap[r]},callback:e})}static registerCtx(r,e=Symbol()){let t=E.globalStore.get(e);return t?console.warn('State: context UID "'+e+'" already in use'):(t=new E(r),E.globalStore.set(e,t)),t}static deleteCtx(r){E.globalStore.delete(r)}static getCtx(r,e=!0){return E.globalStore.get(r)||(e&&console.warn('State: wrong context UID - "'+r+'"'),null)}};E.globalStore=new Map;var A=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"}),Pr="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Bo=Pr.length-1,Mt=class{static generate(r="XXXXXXXXX-XXX"){let e="";for(let t=0;t<r.length;t++)e+=r[t]==="-"?r[t]:Pr.charAt(Math.random()*Bo);return e}};function Rr(r,e,t){let i=!0,s,o=e.split(".");return o.forEach((n,l)=>{l<o.length-1?r=r[n]:s=n}),r?r[s]=t:i=!1,i}function zo(r){return r.split("-").map((e,t)=>e&&t?e[0].toUpperCase()+e.slice(1):e).join("").split("_").map((e,t)=>e&&t?e.toUpperCase():e).join("")}function Vo(r,e){[...r.querySelectorAll(`[${A.REPEAT_ATTR}]`)].forEach(t=>{let i=t.getAttribute(A.REPEAT_ITEM_TAG_ATTR),s;if(i&&(s=window.customElements.get(i)),!s){s=class extends e.BaseComponent{constructor(){super(),i||(this.style.display="contents")}};let n=t.innerHTML;s.template=n,s.reg(i)}for(;t.firstChild;)t.firstChild.remove();let o=t.getAttribute(A.REPEAT_ATTR);e.sub(o,n=>{if(!n){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=h=>{h.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new s;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(h.length,l.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)}),t.removeAttribute(A.REPEAT_ATTR),t.removeAttribute(A.REPEAT_ITEM_TAG_ATTR)})}var Ur="__default__";function jo(r,e){if(e.shadowRoot)return;let t=[...r.querySelectorAll("slot")];if(!t.length)return;let i={};t.forEach(s=>{let o=s.getAttribute("name")||Ur;i[o]={slot:s,fr:document.createDocumentFragment()}}),e.initChildren.forEach(s=>{var o;let n=Ur;s instanceof Element&&s.hasAttribute("slot")&&(n=s.getAttribute("slot"),s.removeAttribute("slot")),(o=i[n])==null||o.fr.appendChild(s)}),Object.values(i).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(o,s.slot)}else s.slot.remove()})}function Ho(r,e){[...r.querySelectorAll(`[${A.EL_REF_ATTR}]`)].forEach(t=>{let i=t.getAttribute(A.EL_REF_ATTR);e.ref[i]=t,t.removeAttribute(A.EL_REF_ATTR)})}function Go(r,e){[...r.querySelectorAll(`[${A.BIND_ATTR}]`)].forEach(t=>{let s=t.getAttribute(A.BIND_ATTR).split(";");[...t.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=zo(o.name.replace("-",""));s.push(n+":"+o.value),t.removeAttribute(o.name)}}),s.forEach(o=>{if(!o)return;let n=o.split(":").map(h=>h.trim()),l=n[0],a;l.indexOf(A.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(A.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("!","")),e.sub(h,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):Rr(t,l,p)||(t[A.SET_LATER_KEY]||(t[A.SET_LATER_KEY]=Object.create(null)),t[A.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(A.BIND_ATTR)})}var Ie="{{",Jt="}}",Wo="skip-text";function Xo(r){let e,t=[],i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var o;return!((o=s.parentElement)!=null&&o.hasAttribute(Wo))&&s.textContent.includes(Ie)&&s.textContent.includes(Jt)&&1}});for(;e=i.nextNode();)t.push(e);return t}var qo=function(r,e){Xo(r).forEach(i=>{let s=[],o;for(;i.textContent.includes(Jt);)i.textContent.startsWith(Ie)?(o=i.textContent.indexOf(Jt)+Jt.length,i.splitText(o),s.push(i)):(o=i.textContent.indexOf(Ie),i.splitText(o)),i=i.nextSibling;s.forEach(n=>{let l=n.textContent.replace(Ie,"").replace(Jt,"");n.textContent="",e.sub(l,a=>{n.textContent=a})})})},Ko=[Vo,jo,Ho,Go,qo],Oe="'",Ut='"',Zo=/\\([0-9a-fA-F]{1,6} ?)/g;function Yo(r){return(r[0]===Ut||r[0]===Oe)&&(r[r.length-1]===Ut||r[r.length-1]===Oe)}function Jo(r){return(r[0]===Ut||r[0]===Oe)&&(r=r.slice(1)),(r[r.length-1]===Ut||r[r.length-1]===Oe)&&(r=r.slice(0,-1)),r}function Qo(r){let e="",t="";for(var i=0;i<r.length;i++){let s=r[i+1];r[i]==="\\"&&s==='"'?(e+='\\"',i++):r[i]==='"'&&t!=="\\"?e+='\\"':e+=r[i],t=r[i]}return e}function tn(r){let e=r;Yo(r)&&(e=Jo(e),e=e.replace(Zo,(t,i)=>String.fromCodePoint(parseInt(i.trim(),16))),e=e.replaceAll(`\\ `,"\\n"),e=Qo(e),e=Ut+e+Ut);try{return JSON.parse(e)}catch{throw new Error(`Failed to parse CSS property value: ${e}. Original input: ${r}`)}}var Mr=0,Lt=null,ut=null,_t=class extends HTMLElement{constructor(){super(),Pi(this,"updateCssData",()=>{var r;this.dropCssDataCache(),(r=this.__boundCssProps)==null||r.forEach(e=>{let t=this.getCssData(this.__extractCssName(e),!0);t!==null&&this.$[e]!==t&&(this.$[e]=t)})}),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 _t}initCallback(){}__initCallback(){var r;this.__initialized||(this.__initialized=!0,(r=this.initCallback)==null||r.call(this))}render(r,e=this.renderShadow){let t;if((e||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(A.USE_TPL);if(s){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(s))||document.querySelector(s);n?r=n.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(this,this);if(r||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(r==null?void 0:r.constructor)===DocumentFragment)t=r;else if((r==null?void 0:r.constructor)===String){let s=document.createElement("template");s.innerHTML=r,t=s.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(t,this)}let i=()=>{t&&(e&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){e=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=i,this.shadowRoot.prepend(s)}else i()}addTemplateProcessor(r){this.tplProcessors.add(r)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Mt.generate(),this.style.setProperty(A.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(A.CSS_CTX_PROP,!0)}get ctxName(){var r;let e=((r=this.getAttribute(A.CTX_NAME_ATTR))==null?void 0:r.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=e,e}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(r,e){let t,i;if(r.startsWith(A.EXT_DATA_CTX_PRFX))t=e.nodeCtx,i=r.replace(A.EXT_DATA_CTX_PRFX,"");else if(r.includes(A.NAMED_DATA_CTX_SPLTR)){let s=r.split(A.NAMED_DATA_CTX_SPLTR);t=E.getCtx(s[0]),i=s[1]}else t=e.localCtx,i=r;return{ctx:t,name:i}}sub(r,e,t=!0){let i=o=>{this.isConnected&&e(o)},s=_t.__parseProp(r,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,i,t)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,i,t))})}notify(r){let e=_t.__parseProp(r,this);e.ctx.notify(e.name)}has(r){let e=_t.__parseProp(r,this);return e.ctx.has(e.name)}add(r,e,t=!1){let i=_t.__parseProp(r,this);i.ctx.add(i.name,e,t)}add$(r,e=!1){for(let t in r)this.add(t,r[t],e)}get $(){if(!this.__stateProxy){let r=Object.create(null);this.__stateProxy=new Proxy(r,{set:(e,t,i)=>{let s=_t.__parseProp(t,this);return s.ctx.pub(s.name,i),!0},get:(e,t)=>{let i=_t.__parseProp(t,this);return i.ctx.read(i.name)}})}return this.__stateProxy}set$(r,e=!1){for(let t in r){let i=r[t];e||![String,Number,Boolean].includes(i==null?void 0:i.constructor)?this.$[t]=i:this.$[t]!==i&&(this.$[t]=i)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(A.CTX_OWNER_ATTR)&&this.getAttribute(A.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let r=this.constructor.__attrDesc;if(r)for(let e of Object.values(r))Object.keys(this.init$).includes(e)||(this.init$[e]="");for(let e in this.init$)if(e.startsWith(A.EXT_DATA_CTX_PRFX))this.nodeCtx.add(e.replace(A.EXT_DATA_CTX_PRFX,""),this.init$[e],this.__ctxOwner);else if(e.includes(A.NAMED_DATA_CTX_SPLTR)){let t=e.split(A.NAMED_DATA_CTX_SPLTR),i=t[0].trim(),s=t[1].trim();if(i&&s){let o=E.getCtx(i,!1);o||(o=E.registerCtx({},i)),o.add(s,this.init$[e])}}else this.localCtx.add(e,this.init$[e]);for(let e in this.cssInit$)this.bindCssData(e,this.cssInit$[e]);this.__dataCtxInitialized=!0}connectedCallback(){var r;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let e=(r=this.getAttribute(A.CTX_NAME_ATTR))==null?void 0:r.trim();if(e&&this.style.setProperty(A.CSS_CTX_PROP,`'${e}'`),this.__initDataCtx(),this[A.SET_LATER_KEY]){for(let t in this[A.SET_LATER_KEY])Rr(this,t,this[A.SET_LATER_KEY][t]);delete this[A.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Ko)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${A.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(A.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(s):t.prepend(s)}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 r of this.allSubs)r.remove(),this.allSubs.delete(r);for(let r of this.tplProcessors)this.tplProcessors.delete(r);ut==null||ut.delete(this.updateCssData),ut!=null&&ut.size||(Lt==null||Lt.disconnect(),Lt=null,ut=null)},100)))}static reg(r,e=!1){r||(Mr++,r=`${A.AUTO_TAG_PRFX}-${Mr}`),this.__tag=r;let t=window.customElements.get(r);if(t){!e&&t!==this&&console.warn([`Element with tag name "${r}" 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(r,e?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(r){this.observedAttributes=Object.keys(r),this.__attrDesc=r}attributeChangedCallback(r,e,t){var i;if(e===t)return;let s=(i=this.constructor.__attrDesc)==null?void 0:i[r];s?this.__dataCtxInitialized?this.$[s]=t:this.init$[s]=t:this[r]=t}getCssData(r,e=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(r)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(r).trim();try{this.__cssDataCache[r]=tn(t)}catch{!e&&console.warn(`CSS Data error: ${r}`),this.__cssDataCache[r]=null}}return this.__cssDataCache[r]}__extractCssName(r){return r.split("--").map((e,t)=>t===0?"":e).join("--")}__initStyleAttrObserver(){ut||(ut=new Set),ut.add(this.updateCssData),Lt||(Lt=new MutationObserver(r=>{r[0].type==="attributes"&&ut.forEach(e=>{e()})}),Lt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(r,e=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(r);let t=this.getCssData(this.__extractCssName(r),!0);t===null&&(t=e),this.add(r,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(r,e,t){let i="__"+r;this[i]=this[r],Object.defineProperty(this,r,{set:s=>{this[i]=s,t?window.setTimeout(()=>{e==null||e(s)}):e==null||e(s)},get:()=>this[i]}),this[r]=this[i]}static set shadowStyles(r){let e=new Blob([r],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(e)}static set rootStyles(r){if(!this.__rootStylesLink){let e=new Blob([r],{type:"text/css"}),t=URL.createObjectURL(e),i=document.createElement("link");i.href=t,i.rel="stylesheet",this.__rootStylesLink=i}}},Pt=_t;Pi(Pt,"template");var Mi=class{static _print(r){console.warn(r)}static setDefaultTitle(r){this.defaultTitle=r}static setRoutingMap(r){Object.assign(this.appMap,r);for(let e in this.appMap)!this.defaultRoute&&this.appMap[e].default===!0?this.defaultRoute=e:!this.errorRoute&&this.appMap[e].error===!0&&(this.errorRoute=e)}static set routingEventName(r){this.__routingEventName=r}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let r={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))r.route=t.replace("?","");else if(t.includes("=")){let i=t.split("=");r.options[i[0]]=decodeURI(i[1])}else r.options[t]=!0}),r}static notify(){let r=this.readAddressBar(),e=this.appMap[r.route];if(e&&e.title&&(document.title=e.title),r.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!e&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e){this._print(`Route "${r.route}" not found...`);return}let t=new CustomEvent(Mi.routingEventName,{detail:{route:r.route,options:Object.assign(e||{},r.options)}});window.dispatchEvent(t)}static reflect(r,e={}){let t=this.appMap[r];if(!t){this._print("Wrong route: "+r);return}let i="?"+r;for(let o in e)e[o]===!0?i+=this.separator+o:i+=this.separator+o+`=${e[o]}`;let s=t.title||this.defaultTitle||"";window.history.pushState(null,s,i),document.title=s}static applyRoute(r,e={}){this.reflect(r,e),this.notify()}static setSeparator(r){this._separator=r}static get separator(){return this._separator||"&"}static createRouterData(r,e){this.setRoutingMap(e);let t=E.registerCtx({route:null,options:null,title:null},r);return window.addEventListener(this.routingEventName,i=>{var s;t.multiPub({route:i.detail.route,options:i.detail.options,title:((s=i.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),Mi.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Mi.appMap=Object.create(null);function Qt(r,e){for(let t in e)t.includes("-")?r.style.setProperty(t,e[t]):r.style[t]=e[t]}function en(r,e){for(let t in e)e[t].constructor===Boolean?e[t]?r.setAttribute(t,""):r.removeAttribute(t):r.setAttribute(t,e[t])}function Ri(r={tag:"div"}){let e=document.createElement(r.tag);if(r.attributes&&en(e,r.attributes),r.styles&&Qt(e,r.styles),r.properties)for(let t in r.properties)e[t]=r.properties[t];return r.processors&&r.processors.forEach(t=>{t(e)}),r.children&&r.children.forEach(t=>{let i=Ri(t);e.appendChild(i)}),e}var Fr="idb-store-ready",rn="symbiote-db",sn="symbiote-idb-update_",on=class{_notifyWhenReady(r=null){window.dispatchEvent(new CustomEvent(Fr,{detail:{dbName:this.name,storeName:this.storeName,event:r}}))}get _updEventName(){return sn+this.name}_getUpdateEvent(r){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:r}})}_notifySubscribers(r){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,r),window.dispatchEvent(this._getUpdateEvent(r))}constructor(r,e){this.name=r,this.storeName=e,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(e,{keyPath:"_key"}),this.objStore.transaction.oncomplete=i=>{this._notifyWhenReady(i)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async s=>{s(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(r){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(r);return new Promise((i,s)=>{t.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?i(o.target.result._value):(i(null),console.warn(`IDB: cannot read "${r}"`))},t.onerror=o=>{s(o)}})}write(r,e,t=!1){let i={_key:r,_value:e},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(i);return new Promise((n,l)=>{o.onsuccess=a=>{t||this._notifySubscribers(r),n(a.target.result)},o.onerror=a=>{l(a)}})}delete(r,e=!1){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(r);return new Promise((s,o)=>{i.onsuccess=n=>{e||this._notifySubscribers(r),s(n)},i.onerror=n=>{o(n)}})}getAll(){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,i)=>{e.onsuccess=s=>{let o=s.target.result;t(o.map(n=>n._value))},e.onerror=s=>{i(s)}})}subscribe(r,e){this._subscriptionsMap[r]||(this._subscriptionsMap[r]=new Set);let t=this._subscriptionsMap[r];return t.add(e),{remove:()=>{t.delete(e),t.size||delete this._subscriptionsMap[r]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Dr.clear(this.name)}},Dr=class{static get readyEventName(){return Fr}static open(r=rn,e="store"){let t=r+"/"+e;return this._reg[t]||(this._reg[t]=new on(r,e)),this._reg[t]}static clear(r){window.indexedDB.deleteDatabase(r);for(let e in this._reg)e.split("/")[0]===r&&delete this._reg[e]}};Pi(Dr,"_reg",Object.create(null));var Nr=r=>{if(typeof r!="string"||!r)return"";let e=r.trim();return e.startsWith("-/")?e=e.slice(2):e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,e.length-1)),e},Le=(...r)=>r.filter(e=>typeof e=="string"&&e).map(e=>Nr(e)).join("/-/"),D=(...r)=>{let e=Le(...r);return e?`-/${e}/`:""};function Ue(r){let e=new URL(r),t=e.pathname+e.search+e.hash,i=t.lastIndexOf("http"),s=t.lastIndexOf("/"),o="";return i>=0?o=t.slice(i):s>=0&&(o=t.slice(s+1)),o}function Me(r){let e=new URL(r),{pathname:t}=e,i=t.indexOf("/"),s=t.indexOf("/",i+1);return t.substring(i+1,s)}function Fi(r){let e=zr(r),t=new URL(e),i=t.pathname.indexOf("/-/");return i===-1?"":t.pathname.substring(i).slice(1)}function Br(r){return Fi(r).split("/-/").filter(Boolean).map(t=>Nr(t))}function zr(r){let e=new URL(r),t=Ue(r),i=Vr(t)?jr(t).pathname:t;return e.pathname=e.pathname.replace(i,""),e.search="",e.hash="",e.toString()}function Vr(r){return r.startsWith("http")}function jr(r){let e=new URL(r);return{pathname:e.origin+e.pathname||"",search:e.search||"",hash:e.hash||""}}var U=(r,e,t)=>{let i=new URL(zr(r));if(t=t||Ue(r),i.pathname.startsWith("//")&&(i.pathname=i.pathname.replace("//","/")),Vr(t)){let s=jr(t);i.pathname=i.pathname+(e||"")+(s.pathname||""),i.search=s.search,i.hash=s.hash}else i.pathname=i.pathname+(e||"")+(t||"");return i.toString()},yt=(r,e)=>{let t=new URL(r);return t.pathname=e+"/",t.toString()};var N=(r,e=",")=>r.trim().split(e).map(t=>t.trim()).filter(t=>t.length>0);var X=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}),Gr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function nn(r,e){if(typeof e=="number"){let t=e;return X[r]!==t?`${r}/${t}`:""}if(typeof e=="boolean"){let t=e;return X[r]!==t?`${r}`:""}if(r==="filter"&&e){let{name:t,amount:i}=e;return X.filter===i?"":`${r}/${t}/${i}`}if(r==="crop"&&e){let{dimensions:t,coords:i}=e;return`${r}/${t.join("x")}/${i.join(",")}`}return""}function vt(r){return Le(...Gr.filter(e=>typeof r[e]!="undefined"&&r[e]!==null).map(e=>{let t=r[e];return nn(e,t)}).filter(e=>!!e))}var Pe=Le("format/auto","progressive/yes"),ht=([r])=>typeof r!="undefined"?Number(r):void 0,Hr=()=>!0,ln=([r,e])=>({name:r,amount:typeof e!="undefined"?Number(e):100}),an=([r,e])=>{if(!/\d+x\d+/.test(r)||!/\d+,\d+/.test(e))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:N(r,"x").map(Number),coords:N(e).map(Number)}},cn=Object.freeze({enhance:ht,brightness:ht,exposure:ht,gamma:ht,contrast:ht,saturation:ht,vibrance:ht,warmth:ht,filter:ln,mirror:Hr,flip:Hr,rotate:ht,crop:an});function Wr(r){let e={};for(let t of r){let[i,...s]=t.split("/");if(!Gr.includes(i))continue;let o=i,n=cn[o];try{let l=n(s);e[o]=l}catch(l){console.warn([`Failed to parse URL operation "${t}". It will be ignored.`,l instanceof Error?`Error message: "${l.message}"`:l,"If you need this functionality, please feel free to open an issue at https://github.com/uploadcare/blocks/issues/new"].join(` `))}}return e}var I=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),H=[I.CROP,I.TUNING,I.FILTERS],Xr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],qr=["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"],Kr=["rotate","mirror","flip"],it=Object.freeze({brightness:{zero:X.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:X.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:X.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:X.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:X.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:X.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:X.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:X.enhance,range:[0,100],keypointsNumber:1},filter:{zero:X.filter,range:[0,100],keypointsNumber:1}});var Zr=r=>r?r.split(",").map(e=>e.trim()):[],Rt=r=>r?r.join(","):"";var un="https://ucarecdn.com",hn="https://upload.uploadcare.com",dn="https://social.uploadcare.com",J={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Rt(H),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:un,baseUrl:hn,socialBaseUrl:dn,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,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:[]};var k=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"}),Re=class{constructor(e){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);u(this,"_debugPrint",null);this._debugPrint=e}bindTarget(e){this._targets.add(e)}unbindTarget(e){this._targets.delete(e)}_dispatch(e,t){var i;for(let s of this._targets)s.dispatchEvent(new CustomEvent(e,{detail:t}));(i=this._debugPrint)==null||i.call(this,()=>{let s=t&&typeof t=="object"?{...t}:t;return[`event "${e}"`,s]})}emit(e,t,{debounce:i}={}){if(typeof i!="number"&&!i){this._dispatch(e,typeof t=="function"?t():t);return}this._timeoutStore.has(e)&&window.clearTimeout(this._timeoutStore.get(e));let s=typeof i=="number"?i:20,o=window.setTimeout(()=>{this._dispatch(e,typeof t=="function"?t():t),this._timeoutStore.delete(e)},s);this._timeoutStore.set(e,o)}};function O(r,e){let t,i=(...s)=>{clearTimeout(t),t=setTimeout(()=>r(...s),e)};return i.cancel=()=>{clearTimeout(t)},i}var Yr="--uploadcare-blocks-window-height",St=class{static registerClient(e){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(e)}static unregisterClient(e){this.clientsRegistry.delete(e),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(Yr)}};u(St,"clientsRegistry",new Set),u(St,"flush",O(()=>{document.documentElement.style.setProperty(Yr,`${window.innerHeight}px`)},100));var Jr=r=>{var i;let e=new Intl.Locale(r),t="ltr";return typeof e.getTextInfo=="function"&&e.getTextInfo().direction?t=e.getTextInfo().direction:"textInfo"in e&&((i=e.textInfo)!=null&&i.direction)&&(t=e.textInfo.direction),t};var Fe=(r,e)=>new Intl.PluralRules(r).select(e);var pn=r=>r,Di="{{",ts="}}",Qr="plural:";function te(r,e,t={}){var n;let{openToken:i=Di,closeToken:s=ts,transform:o=pn}=t;for(let l in e){let a=(n=e[l])==null?void 0:n.toString();r=r.replaceAll(i+l+s,typeof a=="string"?o(a):a)}return r}function es(r){let e=[],t=r.indexOf(Di);for(;t!==-1;){let i=r.indexOf(ts,t),s=r.substring(t+2,i);if(s.startsWith(Qr)){let o=r.substring(t+2,i).replace(Qr,""),n=o.substring(0,o.indexOf("(")),l=o.substring(o.indexOf("(")+1,o.indexOf(")"));e.push({variable:s,pluralKey:n,countVariable:l})}t=r.indexOf(Di,i)}return e}var is=({element:r,attribute:e,onSuccess:t,onTimeout:i,timeout:s=300})=>{let o=r.getAttribute(e);if(o!==null){t(o);return}let n=new MutationObserver(c=>{let h=c[c.length-1];a(h)});n.observe(r,{attributes:!0,attributeFilter:[e]});let l=setTimeout(()=>{n.disconnect(),i()},s),a=c=>{let h=r.getAttribute(e);c.type==="attributes"&&c.attributeName===e&&h!==null&&(clearTimeout(l),n.disconnect(),t(h))}};function rs(r){return Object.prototype.toString.call(r)==="[object Object]"}var fn=/\W|_/g;function mn(r){return r.split(fn).map((e,t)=>e.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+e.slice(1)).join("")}function ss(r,{ignoreKeys:e}={ignoreKeys:[]}){return Array.isArray(r)?r.map(t=>ft(t,{ignoreKeys:e})):r}function ft(r,{ignoreKeys:e}={ignoreKeys:[]}){if(Array.isArray(r))return ss(r,{ignoreKeys:e});if(!rs(r))return r;let t={};for(let i of Object.keys(r)){let s=r[i];if(e.includes(i)){t[i]=s;continue}rs(s)?s=ft(s,{ignoreKeys:e}):Array.isArray(s)&&(s=ss(s,{ignoreKeys:e})),t[mn(i)]=s}return t}var gn=r=>new Promise(e=>setTimeout(e,r));function Gi({libraryName:r,libraryVersion:e,userAgent:t,publicKey:i="",integration:s=""}){let o="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:i,libraryName:r,libraryVersion:e,languageName:o,integration:s});let n=[r,e,i].filter(Boolean).join("/"),l=[o,s].filter(Boolean).join("; ");return`${n} (${l})`}var bn={factor:2,time:100};function _n(r,e=bn){let t=0;function i(s){let o=Math.round(e.time*e.factor**t);return s({attempt:t,retry:l=>gn(l!=null?l:o).then(()=>(t+=1,i(s)))})}return i(r)}var ee=class extends Error{},Ft=class r extends ee{constructor(t){super();u(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,r.prototype),this.originalProgressEvent=t}},Ne=(r,e)=>{r&&(r.aborted?Promise.resolve().then(e):r.addEventListener("abort",()=>e(),{once:!0}))},wt=class r extends ee{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,r.prototype)}},yn=500,ns=({check:r,interval:e=yn,timeout:t,signal:i})=>new Promise((s,o)=>{let n,l;Ne(i,()=>{n&&clearTimeout(n),o(new wt("Poll cancelled"))}),t&&(l=setTimeout(()=>{n&&clearTimeout(n),o(new wt("Timed out"))},t));let a=()=>{try{Promise.resolve(r(i)).then(c=>{c?(l&&clearTimeout(l),s(c)):n=setTimeout(a,e)}).catch(c=>{l&&clearTimeout(l),o(c)})}catch(c){l&&clearTimeout(l),o(c)}};n=setTimeout(a,0)}),T={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"},Be="application/octet-stream",ls="original",Ct=({method:r,url:e,data:t,headers:i={},signal:s,onProgress:o})=>new Promise((n,l)=>{let a=new XMLHttpRequest,c=(r==null?void 0:r.toUpperCase())||"GET",h=!1;a.open(c,e,!0),i&&Object.entries(i).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ne(s,()=>{h=!0,a.abort(),l(new wt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:e,data:t,headers:i||void 0,signal:s,onProgress:o},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function(v){let w=v.split(": "),y=w.shift(),C=w.join(": ");y&&typeof y!="undefined"&&(m[y]=C)});let f=a.response,g=a.status;n({request:d,data:f,headers:m,status:g})}},a.onerror=d=>{h||l(new Ft(d))},o&&typeof o=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?o({isComputable:!0,value:d.loaded/d.total}):o({isComputable:!1})}),t?a.send(t):a.send()});function vn(r,...e){return r}var wn=({name:r})=>r?[r]:[],Cn=vn,xn=()=>new FormData,as=r=>!1,ze=r=>typeof Blob!="undefined"&&r instanceof Blob,Ve=r=>typeof File!="undefined"&&r instanceof File,je=r=>!!r&&typeof r=="object"&&!Array.isArray(r)&&"uri"in r&&typeof r.uri=="string",Dt=r=>ze(r)||Ve(r)||as()||je(r),An=r=>typeof r=="string"||typeof r=="number"||typeof r=="undefined",En=r=>!!r&&typeof r=="object"&&!Array.isArray(r),Tn=r=>!!r&&typeof r=="object"&&"data"in r&&Dt(r.data);function cs(r,e,t){if(Array.isArray(t))for(let i of t)cs(r,`${e}[]`,i);else if(Tn(t)){let{name:i,contentType:s}=t,o=Cn(t.data,i,s!=null?s:Be),n=wn({name:i,contentType:s});r.push([e,o,...n])}else if(En(t))for(let[i,s]of Object.entries(t))typeof s!="undefined"&&r.push([`${e}[${i}]`,String(s)]);else An(t)&&t&&r.push([e,t.toString()])}function Sn(r){let e=[];for(let[t,i]of Object.entries(r))cs(e,t,i);return e}function He(r){let e=xn(),t=Sn(r);for(let i of t){let[s,o,...n]=i;e.append(s,o,...n)}return e}var B=class r extends ee{constructor(t,i,s,o,n){super();u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadError",this.message=t,this.code=i,this.request=s,this.response=o,this.headers=n,Object.setPrototypeOf(this,r.prototype)}},kn=r=>{let e=new URLSearchParams;for(let[t,i]of Object.entries(r))i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).filter(s=>{var o;return(o=s[1])!=null?o:!1}).forEach(s=>e.set(`${t}[${s[0]}]`,String(s[1]))):Array.isArray(i)?i.forEach(s=>{e.append(`${t}[]`,s)}):typeof i=="string"&&i?e.set(t,i):typeof i=="number"&&e.set(t,i.toString());return e.toString()},dt=(r,e,t)=>{let i=new URL(r);return i.pathname=(i.pathname+e).replace("//","/"),t&&(i.search=kn(t)),i.toString()},$n="6.14.1",In="UploadcareUploadClient",On=$n;function kt(r){return Gi({libraryName:In,libraryVersion:On,...r})}var Ln="RequestThrottledError",os=15e3,Un=1e3;function Mn(r){let{headers:e}=r||{};if(!e||typeof e["retry-after"]!="string")return os;let t=parseInt(e["retry-after"],10);return Number.isFinite(t)?t*1e3:os}function xt(r,e){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:i}=e;return _n(({attempt:s,retry:o})=>r().catch(n=>{if("response"in n&&(n==null?void 0:n.code)===Ln&&s<t)return o(Mn(n));if(n instanceof Ft&&s<i)return o((s+1)*Un);throw n}))}var us=r=>{let e="";return(ze(r)||Ve(r)||je(r))&&(e=r.type),e||Be},hs=r=>{let e="";return Ve(r)&&r.name?e=r.name:ze(r)||as()?e="":je(r)&&r.name&&(e=r.name),e||ls};function Wi(r){return typeof r=="undefined"||r==="auto"?"auto":r?"1":"0"}function Pn(r,{publicKey:e,fileName:t,contentType:i,baseURL:s=T.baseURL,secureSignature:o,secureExpire:n,store:l,signal:a,onProgress:c,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:g}){return xt(()=>Ct({method:"POST",url:dt(s,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:e,integration:d,userAgent:p})},data:He({file:{data:r,name:t||hs(r),contentType:i||us(r)},UPLOADCARE_PUB_KEY:e,UPLOADCARE_STORE:Wi(l),signature:o,expire:n,source:h,metadata:g}),signal:a,onProgress:c}).then(({data:v,headers:w,request:y})=>{let C=ft(JSON.parse(v));if("error"in C)throw new B(C.error.content,C.error.errorCode,y,C,w);return C}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var zi;(function(r){r.Token="token",r.FileInfo="file_info"})(zi||(zi={}));function Rn(r,{publicKey:e,baseURL:t=T.baseURL,store:i,fileName:s,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:l,secureExpire:a,source:c="url",signal:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:g}){return xt(()=>Ct({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:e,integration:d,userAgent:p})},url:dt(t,"/from_url/",{jsonerrors:1,pub_key:e,source_url:r,store:Wi(i),filename:s,check_URL_duplicates:o?1:void 0,save_URL_duplicates:n?1:void 0,signature:l,expire:a,source:c,metadata:g}),signal:h}).then(({data:v,headers:w,request:y})=>{let C=ft(JSON.parse(v));if("error"in C)throw new B(C.error.content,C.error.errorCode,y,C,w);return C}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var G;(function(r){r.Unknown="unknown",r.Waiting="waiting",r.Progress="progress",r.Error="error",r.Success="success"})(G||(G={}));var Fn=r=>"status"in r&&r.status===G.Error;function Dn(r,{publicKey:e,baseURL:t=T.baseURL,signal:i,integration:s,userAgent:o,retryThrottledRequestMaxTimes:n=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}={}){return xt(()=>Ct({method:"GET",headers:e?{"X-UC-User-Agent":kt({publicKey:e,integration:s,userAgent:o})}:void 0,url:dt(t,"/from_url/status/",{jsonerrors:1,token:r}),signal:i}).then(({data:a,headers:c,request:h})=>{let d=ft(JSON.parse(a));if("error"in d&&!Fn(d))throw new B(d.error.content,d.error.errorCode,h,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:n})}function Nn(r,{publicKey:e,baseURL:t=T.baseURL,jsonpCallback:i,secureSignature:s,secureExpire:o,signal:n,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=T.retryNetworkErrorMaxTimes}){return xt(()=>Ct({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:e,integration:a,userAgent:c})},url:dt(t,"/group/",{jsonerrors:1}),data:He({files:r,callback:i,pub_key:e,signature:s,expire:o,source:l}),signal:n}).then(({data:p,headers:m,request:f})=>{let g=ft(JSON.parse(p));if("error"in g)throw new B(g.error.content,g.error.errorCode,f,g,m);return g}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function ds(r,{publicKey:e,baseURL:t=T.baseURL,signal:i,source:s,integration:o,userAgent:n,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return xt(()=>Ct({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:e,integration:o,userAgent:n})},url:dt(t,"/info/",{jsonerrors:1,pub_key:e,file_id:r,source:s}),signal:i}).then(({data:c,headers:h,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new B(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bn(r,{publicKey:e,contentType:t,fileName:i,multipartChunkSize:s=T.multipartChunkSize,baseURL:o="",secureSignature:n,secureExpire:l,store:a,signal:c,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:g}){return xt(()=>Ct({method:"POST",url:dt(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:e,integration:d,userAgent:p})},data:He({filename:i||ls,size:r,content_type:t||Be,part_size:s,UPLOADCARE_STORE:Wi(a),UPLOADCARE_PUB_KEY:e,signature:n,expire:l,source:h,metadata:g}),signal:c}).then(({data:v,headers:w,request:y})=>{let C=ft(JSON.parse(v));if("error"in C)throw new B(C.error.content,C.error.errorCode,y,C,w);return C.parts=Object.keys(C.parts).map(M=>C.parts[Number(M)]),C}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function zn(r,e,{contentType:t,signal:i,onProgress:s,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=T.retryNetworkErrorMaxTimes}){return xt(()=>Ct({method:"PUT",url:e,data:r,onProgress:s,signal:i,headers:{"Content-Type":t||Be}}).then(l=>(s&&s({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n})}function Vn(r,{publicKey:e,baseURL:t=T.baseURL,source:i="local",signal:s,integration:o,userAgent:n,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return xt(()=>Ct({method:"POST",url:dt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:e,integration:o,userAgent:n})},data:He({uuid:r,UPLOADCARE_PUB_KEY:e,source:i}),signal:s}).then(({data:c,headers:h,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new B(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Xi(r,{publicKey:e,baseURL:t,source:i,integration:s,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ns({check:h=>ds(r,{publicKey:e,baseURL:t,signal:h,source:i,integration:s,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function jn(r){return"defaultEffects"in r}var pt=class{constructor(e,{baseCDN:t=T.baseCDN,fileName:i}={}){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:s,s3Bucket:o}=e,n=dt(t,`${s}/`),l=o?dt(`https://${o}.s3.amazonaws.com/`,`${s}/${e.filename}`):null;this.uuid=s,this.name=i||e.filename,this.size=e.size,this.isStored=e.isStored,this.isImage=e.isImage,this.mimeType=e.mimeType,this.cdnUrl=n,this.originalFilename=e.originalFilename,this.imageInfo=e.imageInfo,this.videoInfo=e.videoInfo,this.contentInfo=e.contentInfo,this.metadata=e.metadata||null,this.s3Bucket=o||null,this.s3Url=l,jn(e)&&(this.defaultEffects=e.defaultEffects)}},Hn=(r,{publicKey:e,fileName:t,baseURL:i,secureSignature:s,secureExpire:o,store:n,contentType:l,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:g,metadata:v})=>Pn(r,{publicKey:e,fileName:t,contentType:l,baseURL:i,secureSignature:s,secureExpire:o,store:n,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:v}).then(({file:w})=>Xi(w,{publicKey:e,baseURL:i,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(w=>new pt(w,{baseCDN:g})),Gn=(r,{publicKey:e,fileName:t,baseURL:i,signal:s,onProgress:o,source:n,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>ds(r,{publicKey:e,baseURL:i,signal:s,source:n,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(p=>new pt(p,{baseCDN:d,fileName:t})).then(p=>(o&&o({isComputable:!0,value:1}),p)),Wn=(r,{signal:e}={})=>{let t=null,i=null,s=r.map(()=>new AbortController),o=n=>()=>{i=n,s.forEach((l,a)=>a!==n&&l.abort())};return Ne(e,()=>{s.forEach(n=>n.abort())}),Promise.all(r.map((n,l)=>{let a=o(l);return Promise.resolve().then(()=>n({stopRace:a,signal:s[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(n=>{if(i===null)throw t;return n[i]})},Xn=window.WebSocket,Vi=class{constructor(){u(this,"events",Object.create({}))}emit(e,t){var i;(i=this.events[e])==null||i.forEach(s=>s(t))}on(e,t){this.events[e]=this.events[e]||[],this.events[e].push(t)}off(e,t){t?this.events[e]=this.events[e].filter(i=>i!==t):this.events[e]=[]}},qn=(r,e)=>r==="success"?{status:G.Success,...e}:r==="progress"?{status:G.Progress,...e}:{status:G.Error,...e},ji=class{constructor(e,t=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 Vi);u(this,"disconnectTimeoutId",null);this.key=e,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let e=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Xn(e),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let i=JSON.parse(t.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,qn(i.event,JSON.parse(i.data)))}})}}disconnect(){let e=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{e()},this.disconnectTime):e()}send(e,t){var s;let i=JSON.stringify({event:e,data:t});(s=this.ws)==null||s.send(i)}subscribe(e,t){this.subscribers+=1,this.connect();let i=`task-status-${e}`,s={event:"pusher:subscribe",data:{channel:i}};this.emmitter.on(i,t),this.isConnected?this.send(s.event,s.data):this.queue.push(s)}unsubscribe(e){this.subscribers-=1;let t=`task-status-${e}`,i={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(i.event,i.data):this.queue=this.queue.filter(s=>s.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(e){return this.emmitter.on("error",e),()=>this.emmitter.off("error",e)}},Ni=null,qi=r=>{if(!Ni){let e=typeof window=="undefined"?0:3e4;Ni=new ji(r,e)}return Ni},Kn=r=>{qi(r).connect()};function Zn({token:r,publicKey:e,baseURL:t,integration:i,userAgent:s,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,onProgress:l,signal:a}){return ns({check:c=>Dn(r,{publicKey:e,baseURL:t,integration:i,userAgent:s,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,signal:c}).then(h=>{switch(h.status){case G.Error:return new B(h.error,h.errorCode);case G.Waiting:return!1;case G.Unknown:return new B(`Token "${r}" was not found.`);case G.Progress:return l&&(h.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:h.done/h.total})),!1;case G.Success:return l&&l({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:a})}var Yn=({token:r,pusherKey:e,signal:t,onProgress:i})=>new Promise((s,o)=>{let n=qi(e),l=n.onError(o),a=()=>{l(),n.unsubscribe(r)};Ne(t,()=>{a(),o(new wt("pusher cancelled"))}),n.subscribe(r,c=>{switch(c.status){case G.Progress:{i&&(c.total==="unknown"?i({isComputable:!1}):i({isComputable:!0,value:c.done/c.total}));break}case G.Success:{a(),i&&i({isComputable:!0,value:c.done/c.total}),s(c);break}case G.Error:a(),o(new B(c.msg,c.error_code))}})}),Jn=(r,{publicKey:e,fileName:t,baseURL:i,baseCDN:s,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:l,secureExpire:a,store:c,signal:h,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:g,pusherKey:v=T.pusherKey,metadata:w})=>Promise.resolve(Kn(v)).then(()=>Rn(r,{publicKey:e,fileName:t,baseURL:i,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:l,secureExpire:a,store:c,signal:h,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:g,metadata:w})).catch(y=>{let C=qi(v);return C==null||C.disconnect(),Promise.reject(y)}).then(y=>y.type===zi.FileInfo?y:Wn([({signal:C})=>Zn({token:y.token,publicKey:e,baseURL:i,integration:m,userAgent:f,retryThrottledRequestMaxTimes:g,onProgress:d,signal:C}),({signal:C})=>Yn({token:y.token,pusherKey:v,signal:C,onProgress:d})],{signal:h})).then(y=>{if(y instanceof B)throw y;return y}).then(y=>Xi(y.uuid,{publicKey:e,baseURL:i,integration:m,userAgent:f,retryThrottledRequestMaxTimes:g,onProgress:d,signal:h})).then(y=>new pt(y,{baseCDN:s})),Bi=new WeakMap,Qn=async r=>{if(Bi.has(r))return Bi.get(r);let e=await fetch(r.uri).then(t=>t.blob());return Bi.set(r,e),e},ps=async r=>{if(Ve(r)||ze(r))return r.size;if(je(r))return(await Qn(r)).size;throw new Error("Unknown file type. Cannot determine file size.")},tl=(r,e=T.mult