UNPKG

@mux/upchunk

Version:

Dead simple chunked file uploads using Fetch

5 lines (4 loc) 26 kB
var Me=Object.create;var L=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),je=(t,e)=>{for(var n in e)L(t,n,{get:e[n],enumerable:!0})},K=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of De(e))!He.call(t,i)&&i!==n&&L(t,i,{get:()=>e[i],enumerable:!(r=Ne(e,i))||r.enumerable});return t};var We=(t,e,n)=>(n=t!=null?Me(Xe(t)):{},K(e||!t||!t.__esModule?L(n,"default",{value:t,enumerable:!0}):n,t)),$e=t=>K(L({},"__esModule",{value:!0}),t);var Ee=_((It,Se)=>{var P;typeof window!="undefined"?P=window:typeof global!="undefined"?P=global:typeof self!="undefined"?P=self:P={};Se.exports=P});var we=_((Lt,ve)=>{ve.exports=dt;var ht=Object.prototype.toString;function dt(t){if(!t)return!1;var e=ht.call(t);return e==="[object Function]"||typeof t=="function"&&e!=="[object RegExp]"||typeof window!="undefined"&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)}});var ze=_((Bt,Re)=>{var $=function(t){return t.replace(/^\s+|\s+$/g,"")},ft=function(t){return Object.prototype.toString.call(t)==="[object Array]"};Re.exports=function(t){if(!t)return{};for(var e={},n=$(t).split(` `),r=0;r<n.length;r++){var i=n[r],a=i.indexOf(":"),o=$(i.slice(0,a)).toLowerCase(),s=$(i.slice(a+1));typeof e[o]=="undefined"?e[o]=s:ft(e[o])?e[o].push(s):e[o]=[e[o],s]}return e}});var _e=_((xt,Te)=>{Te.exports=mt;var pt=Object.prototype.hasOwnProperty;function mt(){for(var t={},e=0;e<arguments.length;e++){var n=arguments[e];for(var r in n)pt.call(n,r)&&(t[r]=n[r])}return t}});var Ie=_((Ft,V)=>{"use strict";var Pe=Ee(),gt=we(),bt=ze(),yt=_e();V.exports=k;V.exports.default=k;k.XMLHttpRequest=Pe.XMLHttpRequest||Et;k.XDomainRequest="withCredentials"in new k.XMLHttpRequest?k.XMLHttpRequest:Pe.XDomainRequest;kt(["get","put","post","patch","head","delete"],function(t){k[t==="delete"?"del":t]=function(e,n,r){return n=Oe(e,n,r),n.method=t.toUpperCase(),Ae(n)}});function kt(t,e){for(var n=0;n<t.length;n++)e(t[n])}function Ct(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function Oe(t,e,n){var r=t;return gt(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=yt(e,{uri:t}),r.callback=n,r}function k(t,e,n){return e=Oe(t,e,n),Ae(e)}function Ae(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(S,I,Ue){e||(e=!0,t.callback(S,I,Ue))};function r(){s.readyState===4&&setTimeout(o,0)}function i(){var l=void 0;if(s.response?l=s.response:l=s.responseText||St(s),G)try{l=JSON.parse(l)}catch{}return l}function a(l){return clearTimeout(M),l instanceof Error||(l=new Error(""+(l||"Unknown XMLHttpRequest Error"))),l.statusCode=0,n(l,Y)}function o(){if(!h){var l;clearTimeout(M),t.useXDR&&s.status===void 0?l=200:l=s.status===1223?204:s.status;var S=Y,I=null;return l!==0?(S={body:i(),statusCode:l,method:d,headers:{},url:f,rawRequest:s},s.getAllResponseHeaders&&(S.headers=bt(s.getAllResponseHeaders()))):I=new Error("Internal XMLHttpRequest Error"),n(I,S,S.body)}}var s=t.xhr||null;s||(t.cors||t.useXDR?s=new k.XDomainRequest:s=new k.XMLHttpRequest);var u,h,f=s.url=t.uri||t.url,d=s.method=t.method||"GET",y=t.body||t.data,p=s.headers=t.headers||{},U=!!t.sync,G=!1,M,Y={body:void 0,headers:{},statusCode:0,method:d,url:f,rawRequest:s};if("json"in t&&t.json!==!1&&(G=!0,p.accept||p.Accept||(p.Accept="application/json"),d!=="GET"&&d!=="HEAD"&&(p["content-type"]||p["Content-Type"]||(p["Content-Type"]="application/json"),y=JSON.stringify(t.json===!0?y:t.json))),s.onreadystatechange=r,s.onload=o,s.onerror=a,s.onprogress=function(){},s.onabort=function(){h=!0},s.ontimeout=a,s.open(d,f,!U,t.username,t.password),U||(s.withCredentials=!!t.withCredentials),!U&&t.timeout>0&&(M=setTimeout(function(){if(!h){h=!0,s.abort("timeout");var l=new Error("XMLHttpRequest timeout");l.code="ETIMEDOUT",a(l)}},t.timeout)),s.setRequestHeader)for(u in p)p.hasOwnProperty(u)&&s.setRequestHeader(u,p[u]);else if(t.headers&&!Ct(t.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in t&&(s.responseType=t.responseType),"beforeSend"in t&&typeof t.beforeSend=="function"&&t.beforeSend(s),s.send(y||null),s}function St(t){try{if(t.responseType==="document")return t.responseXML;var e=t.responseXML&&t.responseXML.documentElement.nodeName==="parsererror";if(t.responseType===""&&!e)return t.responseXML}catch{}return null}function Et(){}});var _t={};je(_t,{ChunkedFileIterable:()=>F,ChunkedStreamIterable:()=>x,UpChunk:()=>T,createUpload:()=>Tt,getChunkSizeError:()=>z,isIncompleteChunkUploadNeedingRetry:()=>Fe,isValidChunkSize:()=>R});module.exports=$e(_t);function W(t,e,...n){if(!t)throw new TypeError(oe(e,n))}function oe(t,e){let n=0;return t.replace(/%[os]/gu,()=>ue(e[n++]))}function ue(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var Z;function Ve(t){try{let e=t instanceof Error?t:new Error(ue(t));if(Z){Z(e);return}if(typeof dispatchEvent=="function"&&typeof ErrorEvent=="function")dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}));else if(typeof process!="undefined"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)}catch{}}var m=typeof window!="undefined"?window:typeof self!="undefined"?self:typeof global!="undefined"?global:typeof globalThis!="undefined"?globalThis:void 0,J;var g=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if(J){J({...this,args:e});return}let r=((n=new Error().stack)!==null&&n!==void 0?n:"").replace(/^(?:.+?\n){2}/gu,` `);console.warn(this.message,...e,r)}catch{}}},qe=new g("W01","Unable to initialize event under dispatching."),Ge=new g("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),Ye=new g("W03","Assigning any truthy value to 'returnValue' property has no effect."),Ke=new g("W04","Unable to preventDefault on non-cancelable events."),Ze=new g("W05","Unable to preventDefault inside passive event listener invocation."),Je=new g("W06","An event listener wasn't added because it has been added already: %o, %o"),N=new g("W07","The %o option value was abandoned because the event listener wasn't added as duplicated."),Q=new g("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),Ot=new g("W09","Event attribute handler must be a function: %o"),b=class{static get NONE(){return ee}static get CAPTURING_PHASE(){return te}static get AT_TARGET(){return ne}static get BUBBLING_PHASE(){return re}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};j.set(this,{type:String(e),bubbles:Boolean(r.bubbles),cancelable:Boolean(r.cancelable),composed:Boolean(r.composed),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1,inPassiveListenerFlag:!1,dispatchFlag:!1,timeStamp:Date.now()})}get type(){return c(this).type}get target(){return c(this).target}get srcElement(){return c(this).target}get currentTarget(){return c(this).currentTarget}composedPath(){let e=c(this).currentTarget;return e?[e]:[]}get NONE(){return ee}get CAPTURING_PHASE(){return te}get AT_TARGET(){return ne}get BUBBLING_PHASE(){return re}get eventPhase(){return c(this).dispatchFlag?2:0}stopPropagation(){c(this).stopPropagationFlag=!0}get cancelBubble(){return c(this).stopPropagationFlag}set cancelBubble(e){e?c(this).stopPropagationFlag=!0:Ge.warn()}stopImmediatePropagation(){let e=c(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return c(this).bubbles}get cancelable(){return c(this).cancelable}get returnValue(){return!c(this).canceledFlag}set returnValue(e){e?Ye.warn():ie(c(this))}preventDefault(){ie(c(this))}get defaultPrevented(){return c(this).canceledFlag}get composed(){return c(this).composed}get isTrusted(){return!1}get timeStamp(){return c(this).timeStamp}initEvent(e,n=!1,r=!1){let i=c(this);if(i.dispatchFlag){qe.warn();return}j.set(this,{...i,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},ee=0,te=1,ne=2,re=3,j=new WeakMap;function c(t,e="this"){let n=j.get(t);return W(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function ie(t){if(t.inPassiveListenerFlag){Ze.warn();return}if(!t.cancelable){Ke.warn();return}t.canceledFlag=!0}Object.defineProperty(b,"NONE",{enumerable:!0});Object.defineProperty(b,"CAPTURING_PHASE",{enumerable:!0});Object.defineProperty(b,"AT_TARGET",{enumerable:!0});Object.defineProperty(b,"BUBBLING_PHASE",{enumerable:!0});var D=Object.getOwnPropertyNames(b.prototype);for(let t=0;t<D.length;++t)D[t]!=="constructor"&&Object.defineProperty(b.prototype,D[t],{enumerable:!0});typeof m!="undefined"&&typeof m.Event!="undefined"&&Object.setPrototypeOf(b.prototype,m.Event.prototype);function Qe(t){return m.DOMException?new m.DOMException(t,"InvalidStateError"):(v==null&&(v=class le extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,le)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(v.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),ae(v),ae(v.prototype)),new v(t))}var v,se={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25};function ae(t){let e=Object.keys(se);for(let n=0;n<e.length;++n){let r=e[n],i=se[r];Object.defineProperty(t,r,{get(){return i},configurable:!0,enumerable:!0})}}var w=class extends b{static wrap(e){return new(he(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),ce.set(this,{original:e});let n=Object.keys(e);for(let r=0;r<n.length;++r){let i=n[r];i in this||Object.defineProperty(this,i,de(e,i))}}stopPropagation(){super.stopPropagation();let{original:e}=C(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=C(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=C(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=C(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=C(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=C(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},ce=new WeakMap;function C(t){let e=ce.get(t);return W(e!=null,"'this' is expected an Event object, but got",t),e}var B=new WeakMap;B.set(Object.prototype,w);typeof m!="undefined"&&typeof m.Event!="undefined"&&B.set(m.Event.prototype,w);function he(t){let e=Object.getPrototypeOf(t);if(e==null)return w;let n=B.get(e);return n==null&&(n=et(he(e),e),B.set(e,n)),n}function et(t,e){class n extends t{}let r=Object.keys(e);for(let i=0;i<r.length;++i)Object.defineProperty(n.prototype,r[i],de(e,r[i]));return n}function de(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=C(this).original,i=r[e];return typeof i=="function"?i.bind(r):i},set(r){let i=C(this).original;i[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function tt(t,e,n,r,i,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:i,signalListener:a}}function nt(t){t.flags|=8}function fe(t){return(t.flags&1)===1}function pe(t){return(t.flags&2)===2}function me(t){return(t.flags&4)===4}function rt(t){return(t.flags&8)===8}function it({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){Ve(r)}}function ge({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&fe(t[r])===n)return r;return-1}function st(t,e,n,r,i,a){let o;a&&(o=be.bind(null,t,e,n),a.addEventListener("abort",o));let s=tt(e,n,r,i,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,s]):t.listeners.push(s),s}function be(t,e,n){let r=ge(t,e,n);return r!==-1?ye(t,r):!1}function ye(t,e,n=!1){let r=t.listeners[e];return nt(r),r.signal&&r.signal.removeEventListener("abort",r.signalListener),t.cow&&!n?(t.cow=!1,t.listeners=t.listeners.filter((i,a)=>a!==e),!1):(t.listeners.splice(e,1),!0)}function at(){return Object.create(null)}function ot(t,e){var n;return(n=t[e])!==null&&n!==void 0?n:t[e]={attrCallback:void 0,attrListener:void 0,cow:!1,listeners:[]}}var E=class{constructor(){ke.set(this,at())}addEventListener(e,n,r){let i=X(this),{callback:a,capture:o,once:s,passive:u,signal:h,type:f}=ut(e,n,r);if(a==null||(h==null?void 0:h.aborted))return;let d=ot(i,f),y=ge(d,a,o);if(y!==-1){ct(d.listeners[y],u,s,h);return}st(d,a,o,u,s,h)}removeEventListener(e,n,r){let i=X(this),{callback:a,capture:o,type:s}=lt(e,n,r),u=i[s];a!=null&&u&&be(u,a,o)}dispatchEvent(e){let n=X(this)[String(e.type)];if(n==null)return!0;let r=e instanceof b?e:w.wrap(e),i=c(r,"event");if(i.dispatchFlag)throw Qe("This event has been in dispatching.");if(i.dispatchFlag=!0,i.target=i.currentTarget=this,!i.stopPropagationFlag){let{cow:a,listeners:o}=n;n.cow=!0;for(let s=0;s<o.length;++s){let u=o[s];if(!rt(u)&&(me(u)&&ye(n,s,!a)&&(s-=1),i.inPassiveListenerFlag=pe(u),it(u,this,r),i.inPassiveListenerFlag=!1,i.stopImmediatePropagationFlag))break}a||(n.cow=!1)}return i.target=null,i.currentTarget=null,i.stopImmediatePropagationFlag=!1,i.stopPropagationFlag=!1,i.dispatchFlag=!1,!i.canceledFlag}},ke=new WeakMap;function X(t,e="this"){let n=ke.get(t);return W(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function ut(t,e,n){var r;return Ce(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture),passive:Boolean(n.passive),once:Boolean(n.once),signal:(r=n.signal)!==null&&r!==void 0?r:void 0}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n),passive:!1,once:!1,signal:void 0}}function lt(t,e,n){return Ce(e),typeof n=="object"&&n!==null?{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n.capture)}:{type:String(t),callback:e!=null?e:void 0,capture:Boolean(n)}}function Ce(t){if(!(typeof t=="function"||typeof t=="object"&&t!==null&&typeof t.handleEvent=="function")){if(t==null||typeof t=="object"){Q.warn(t);return}throw new TypeError(oe(Q.message,[t]))}}function ct(t,e,n,r){Je.warn(fe(t)?"capture":"bubble",t.callback),pe(t)!==e&&N.warn("passive"),me(t)!==n&&N.warn("once"),t.signal!==r&&N.warn("signal")}var H=Object.getOwnPropertyNames(E.prototype);for(let t=0;t<H.length;++t)H[t]!=="constructor"&&Object.defineProperty(E.prototype,H[t],{enumerable:!0});typeof m!="undefined"&&typeof m.EventTarget!="undefined"&&Object.setPrototypeOf(E.prototype,m.EventTarget.prototype);var Le=We(Ie()),q=30720,O=512e3,A=256,R=(t,{minChunkSize:e=A,maxChunkSize:n=O}={})=>t==null||typeof t=="number"&&t>=256&&t%256===0&&t>=e&&t<=n,z=(t,{minChunkSize:e=A,maxChunkSize:n=O}={})=>new TypeError(`chunkSize ${t} must be a positive number in multiples of 256, between ${e} and ${n}`),x=class{constructor(e,n={}){this.readableStream=e;var r,i,a;if(!R(n.defaultChunkSize,n))throw z(n.defaultChunkSize,n);this.defaultChunkSize=(r=n.defaultChunkSize)!=null?r:q,this.minChunkSize=(i=n.minChunkSize)!=null?i:A,this.maxChunkSize=(a=n.maxChunkSize)!=null?a:O}get chunkSize(){var e;return(e=this._chunkSize)!=null?e:this.defaultChunkSize}set chunkSize(e){if(!R(e,this))throw z(e,this);this._chunkSize=e}get chunkByteSize(){return this.chunkSize*1024}get error(){return this._error}async*[Symbol.asyncIterator](){let e,n=this.readableStream.getReader();try{for(;;){let{done:r,value:i}=await n.read();if(r){if(e){let o=e;e=void 0,yield o}break}let a=i instanceof Uint8Array?new Blob([i],{type:"application/octet-stream"}):i;for(e=e?new Blob([e,a]):a;e;)if(e.size===this.chunkByteSize){let o=e;e=void 0,yield o;break}else{if(e.size<this.chunkByteSize)break;{let o=e.slice(0,this.chunkByteSize);e=e.slice(this.chunkByteSize),yield o}}}}catch(r){this._error=r}finally{if(e){let r=e;e=void 0,yield r}n.releaseLock();return}}},F=class{constructor(e,n={}){this.file=e;var r,i,a;if(!R(n.defaultChunkSize,n))throw z(n.defaultChunkSize,n);this.defaultChunkSize=(r=n.defaultChunkSize)!=null?r:q,this.minChunkSize=(i=n.minChunkSize)!=null?i:A,this.maxChunkSize=(a=n.maxChunkSize)!=null?a:O}get chunkSize(){var e;return(e=this._chunkSize)!=null?e:this.defaultChunkSize}set chunkSize(e){if(!R(e,this))throw z(e,this);this._chunkSize=e}get chunkByteSize(){return this.chunkSize*1024}get error(){return this._error}async*[Symbol.asyncIterator](){let e=new FileReader,n=0,r=()=>new Promise(i=>{if(n>=this.file.size){i(void 0);return}let a=Math.min(this.chunkByteSize,this.file.size-n);e.onload=()=>{e.result!==null?i(new Blob([e.result],{type:"application/octet-stream"})):i(void 0)},e.readAsArrayBuffer(this.file.slice(n,n+a))});try{for(;;){let i=await r();if(i)n+=i.size,yield i;else break}}catch(i){this._error=i}}},vt=[200,201,202,204,308],Be=[408,502,503,504],wt=[308],xe=(t,e)=>!!t&&vt.includes(t.statusCode),Rt=(t,{retryCodes:e=Be})=>!t||e.includes(t.statusCode),zt=(t,e)=>e.attemptCount>=e.attempts||!(xe(t)||Rt(t,e)),Fe=(t,e)=>{var i;if(!t||!wt.includes(t.statusCode)||!((i=t.headers)!=null&&i.range))return!1;let n=t.headers.range.match(/bytes=(\d+)-(\d+)/);return n?parseInt(n[2],10)<e.currentChunkEndByte:!1},T=class{static createUpload(e){return new T(e)}constructor(e){if(this.eventTarget=new E,this.endpoint=e.endpoint,this.file=e.file,this.headers=e.headers||{},this.method=e.method||"PUT",this.attempts=e.attempts||5,this.delayBeforeAttempt=e.delayBeforeAttempt||1,this.retryCodes=e.retryCodes||Be,this.dynamicChunkSize=e.dynamicChunkSize||!1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.attemptCount=0,this._offline=typeof window!="undefined"&&!window.navigator.onLine,this._paused=!1,this.success=!1,this.nextChunkRangeStart=0,e.useLargeFileWorkaround){let n=r=>{this.chunkedIterable.error&&(console.warn(`Unable to read file of size ${this.file.size} bytes via a ReadableStream. Falling back to in-memory FileReader!`),r.stopImmediatePropagation(),this.chunkedIterable=new F(this.file,{...e,defaultChunkSize:e.chunkSize}),this.chunkedIterator=this.chunkedIterable[Symbol.asyncIterator](),this.getEndpoint().then(()=>{this.sendChunks()}).catch(i=>{let a=i!=null&&i.message?`: ${i.message}`:"";this.dispatch("error",{message:`Failed to get endpoint${a}`})}),this.off("error",n))};this.on("error",n)}this.chunkedIterable=new x(this.file.stream(),{...e,defaultChunkSize:e.chunkSize}),this.chunkedIterator=this.chunkedIterable[Symbol.asyncIterator](),this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()).catch(n=>{let r=n!=null&&n.message?`: ${n.message}`:"";this.dispatch("error",{message:`Failed to get endpoint${r}`})}),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this._offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline||(this._offline=!0,this.dispatch("offline"))}))}get maxChunkSize(){var e,n;return(n=(e=this.chunkedIterable)==null?void 0:e.maxChunkSize)!=null?n:O}get minChunkSize(){var e,n;return(n=(e=this.chunkedIterable)==null?void 0:e.minChunkSize)!=null?n:A}get chunkSize(){var e,n;return(n=(e=this.chunkedIterable)==null?void 0:e.chunkSize)!=null?n:q}set chunkSize(e){this.chunkedIterable.chunkSize=e}get chunkByteSize(){return this.chunkedIterable.chunkByteSize}get totalChunkSize(){return Math.ceil(this.file.size/this.chunkByteSize)}on(e,n){this.eventTarget.addEventListener(e,n)}once(e,n){this.eventTarget.addEventListener(e,n,{once:!0})}off(e,n){this.eventTarget.removeEventListener(e,n)}get offline(){return this._offline}get paused(){return this._paused}abort(){var e;this.pause(),(e=this.currentXhr)==null||e.abort()}pause(){this._paused=!0}resume(){this._paused&&(this._paused=!1,this.sendChunks())}get successfulPercentage(){return this.nextChunkRangeStart/this.file.size}dispatch(e,n){let r=new CustomEvent(e,{detail:n});this.eventTarget.dispatchEvent(r)}validateOptions(){if(!this.endpoint||typeof this.endpoint!="function"&&typeof this.endpoint!="string")throw new TypeError("endpoint must be defined as a string or a function that returns a promise");if(!(this.file instanceof File))throw new TypeError("file must be a File object");if(this.headers&&typeof this.headers!="function"&&typeof this.headers!="object")throw new TypeError("headers must be null, an object, or a function that returns an object or a promise");if(!R(this.chunkSize,{maxChunkSize:this.maxChunkSize,minChunkSize:this.minChunkSize}))throw z(this.chunkSize,{maxChunkSize:this.maxChunkSize,minChunkSize:this.minChunkSize});if(this.maxChunkSize&&(typeof this.maxChunkSize!="number"||this.maxChunkSize<256||this.maxChunkSize%256!==0||this.maxChunkSize<this.chunkSize||this.maxChunkSize<this.minChunkSize))throw new TypeError(`maxChunkSize must be a positive number in multiples of 256, and larger than or equal to both ${this.minChunkSize} and ${this.chunkSize}`);if(this.minChunkSize&&(typeof this.minChunkSize!="number"||this.minChunkSize<256||this.minChunkSize%256!==0||this.minChunkSize>this.chunkSize||this.minChunkSize>this.maxChunkSize))throw new TypeError(`minChunkSize must be a positive number in multiples of 256, and smaller than ${this.chunkSize} and ${this.maxChunkSize}`);if(this.maxFileBytes>0&&this.maxFileBytes<this.file.size)throw new Error(`file size exceeds maximum (${this.file.size} > ${this.maxFileBytes})`);if(this.attempts&&(typeof this.attempts!="number"||this.attempts<=0))throw new TypeError("retries must be a positive number");if(this.delayBeforeAttempt&&(typeof this.delayBeforeAttempt!="number"||this.delayBeforeAttempt<0))throw new TypeError("delayBeforeAttempt must be a positive number")}getEndpoint(){return typeof this.endpoint=="string"?(this.endpointValue=this.endpoint,Promise.resolve(this.endpoint)):this.endpoint(this.file).then(e=>{if(this.endpointValue=e,typeof e!="string")throw new TypeError("endpoint must return a string");return this.endpointValue})}xhrPromise(e){let n=r=>{r.upload.onprogress=i=>{var h;let a=this.totalChunks-this.chunkCount,o=(this.file.size-this.nextChunkRangeStart)/this.file.size/a,u=i.loaded/((h=i.total)!=null?h:this.chunkByteSize)*o;this.dispatch("progress",Math.min((this.successfulPercentage+u)*100,100))}};return new Promise((r,i)=>{this.currentXhr=(0,Le.default)({...e,beforeSend:n},(a,o)=>(this.currentXhr=void 0,a?i(a):r(o)))})}async sendChunk(e){let n=this.nextChunkRangeStart,r=n+e.size-1,a={...await(typeof this.headers=="function"?this.headers():this.headers),"Content-Type":this.file.type,"Content-Range":`bytes ${n}-${r}/${this.file.size}`};return this.dispatch("attempt",{chunkNumber:this.chunkCount,totalChunks:this.totalChunks,chunkSize:this.chunkSize}),this.xhrPromise({headers:a,url:this.endpointValue,method:this.method,body:e})}async sendChunkWithRetries(e){let n=async(s,u)=>{var d;let f=(new Date().getTime()-this.lastChunkStart.getTime())/1e3;if(this.dispatch("chunkSuccess",{chunk:this.chunkCount,chunkSize:this.chunkSize,attempts:this.attemptCount,timeInterval:f,response:s}),this.attemptCount=0,this.chunkCount=((d=this.chunkCount)!=null?d:0)+1,this.nextChunkRangeStart=this.nextChunkRangeStart+this.chunkByteSize,this.dynamicChunkSize){let y=this.chunkSize;f<10?y=Math.min(this.chunkSize*2,this.maxChunkSize):f>30&&(y=Math.max(this.chunkSize/2,this.minChunkSize)),this.chunkSize=Math.ceil(y/256)*256;let p=(this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;this.totalChunks=Math.ceil(this.chunkCount+p)}return!0},r=async(s,u)=>(this.dispatch("progress",Math.min(this.successfulPercentage*100,100)),this.dispatch("error",{message:`Server responded with ${s.statusCode}. Stopping upload.`,chunk:this.chunkCount,attempts:this.attemptCount,response:s}),!1),i=async(s,u)=>(this.dispatch("attemptFailure",{message:`An error occured uploading chunk ${this.chunkCount}. ${this.attempts-this.attemptCount} retries left.`,chunkNumber:this.chunkCount,attemptsLeft:this.attempts-this.attemptCount,response:s}),new Promise(h=>{setTimeout(async()=>{if(this._paused||this.offline){this.pendingChunk=e,h(!1);return}let f=await this.sendChunkWithRetries(e);h(f)},this.delayBeforeAttempt*1e3)})),a;try{this.attemptCount=this.attemptCount+1,this.lastChunkStart=new Date,a=await this.sendChunk(e)}catch(s){typeof(s==null?void 0:s.statusCode)=="number"&&(a=s)}let o={retryCodes:this.retryCodes,attemptCount:this.attemptCount,attempts:this.attempts,currentChunkEndByte:this.nextChunkRangeStart+e.size-1};return Fe(a,o)?i(a,e):xe(a,o)?n(a,e):zt(a,o)?r(a,e):i(a,e)}async sendChunks(){if(this.pendingChunk&&!(this._paused||this.offline)){let e=this.pendingChunk;this.pendingChunk=void 0;let n=await this.sendChunkWithRetries(e);this.success&&n&&this.dispatch("success")}for(;!(this.success||this._paused||this.offline);){let{value:e,done:n}=await this.chunkedIterator.next(),r=!e&&n;if(e&&(r=await this.sendChunkWithRetries(e)),this.chunkedIterable.error){r=!1,this.dispatch("error",{message:`Unable to read file of size ${this.file.size} bytes. Try loading from another browser.`});return}if(this.success=!!n,this.success&&r&&this.dispatch("success"),!r)return}}};function Tt(t){return T.createUpload(t)} //# sourceMappingURL=upchunk.cjs.js.map