@mux/upchunk
Advanced tools
Comparing version 2.6.0 to 3.0.0
@@ -1,4 +0,4 @@ | ||
var Ae=Object.create;var A=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Be=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},X=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ze(e))!Le.call(t,i)&&i!==n&&A(t,i,{get:()=>e[i],enumerable:!(r=Oe(e,i))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?Ae(_e(t)):{},X(e||!t||!t.__esModule?A(n,"default",{value:t,enumerable:!0}):n,t)),Ie=t=>X(A({},"__esModule",{value:!0}),t);var me=R((vt,de)=>{var T;typeof window!="undefined"?T=window:typeof global!="undefined"?T=global:typeof self!="undefined"?T=self:T={};de.exports=T});var be=R((Ct,ge)=>{ge.exports=nt;var tt=Object.prototype.toString;function nt(t){if(!t)return!1;var e=tt.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 Ee=R((St,ye)=>{var M=function(t){return t.replace(/^\s+|\s+$/g,"")},rt=function(t){return Object.prototype.toString.call(t)==="[object Array]"};ye.exports=function(t){if(!t)return{};for(var e={},n=M(t).split(` | ||
`),r=0;r<n.length;r++){var i=n[r],a=i.indexOf(":"),o=M(i.slice(0,a)).toLowerCase(),s=M(i.slice(a+1));typeof e[o]=="undefined"?e[o]=s:rt(e[o])?e[o].push(s):e[o]=[e[o],s]}return e}});var Ce=R((kt,ve)=>{ve.exports=st;var it=Object.prototype.hasOwnProperty;function st(){for(var t={},e=0;e<arguments.length;e++){var n=arguments[e];for(var r in n)it.call(n,r)&&(t[r]=n[r])}return t}});var Re=R((wt,j)=>{"use strict";var Se=me(),at=be(),ot=Ee(),ut=Ce();j.exports=b;j.exports.default=b;b.XMLHttpRequest=Se.XMLHttpRequest||ft;b.XDomainRequest="withCredentials"in new b.XMLHttpRequest?b.XMLHttpRequest:Se.XDomainRequest;lt(["get","put","post","patch","head","delete"],function(t){b[t==="delete"?"del":t]=function(e,n,r){return n=ke(e,n,r),n.method=t.toUpperCase(),we(n)}});function lt(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 ke(t,e,n){var r=t;return at(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=ut(e,{uri:t}),r.callback=n,r}function b(t,e,n){return e=ke(t,e,n),we(e)}function we(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(v,P,Pe){e||(e=!0,t.callback(v,P,Pe))};function r(){s.readyState===4&&setTimeout(o,0)}function i(){var u=void 0;if(s.response?u=s.response:u=s.responseText||ht(s),H)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(L),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,U)}function o(){if(!h){var u;clearTimeout(L),t.useXDR&&s.status===void 0?u=200:u=s.status===1223?204:s.status;var v=U,P=null;return u!==0?(v={body:i(),statusCode:u,method:m,headers:{},url:y,rawRequest:s},s.getAllResponseHeaders&&(v.headers=ot(s.getAllResponseHeaders()))):P=new Error("Internal XMLHttpRequest Error"),n(P,v,v.body)}}var s=t.xhr||null;s||(t.cors||t.useXDR?s=new b.XDomainRequest:s=new b.XMLHttpRequest);var c,h,y=s.url=t.uri||t.url,m=s.method=t.method||"GET",S=t.body||t.data,g=s.headers=t.headers||{},_=!!t.sync,H=!1,L,U={body:void 0,headers:{},statusCode:0,method:m,url:y,rawRequest:s};if("json"in t&&t.json!==!1&&(H=!0,g.accept||g.Accept||(g.Accept="application/json"),m!=="GET"&&m!=="HEAD"&&(g["content-type"]||g["Content-Type"]||(g["Content-Type"]="application/json"),S=JSON.stringify(t.json===!0?S:t.json))),s.onreadystatechange=r,s.onload=o,s.onerror=a,s.onprogress=function(){},s.onabort=function(){h=!0},s.ontimeout=a,s.open(m,y,!_,t.username,t.password),_||(s.withCredentials=!!t.withCredentials),!_&&t.timeout>0&&(L=setTimeout(function(){if(!h){h=!0,s.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),s.setRequestHeader)for(c in g)g.hasOwnProperty(c)&&s.setRequestHeader(c,g[c]);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(S||null),s}function ht(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 ft(){}});var gt={};Be(gt,{UpChunk:()=>z,createUpload:()=>mt});module.exports=Ie(gt);function D(t,e,...n){if(!t)throw new TypeError(ee(e,n))}function ee(t,e){let n=0;return t.replace(/%[os]/gu,()=>te(e[n++]))}function te(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var W;function Fe(t){try{let e=t instanceof Error?t:new Error(te(t));if(W){W(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 f=typeof window!="undefined"?window:typeof self!="undefined"?self:typeof global!="undefined"?global:typeof globalThis!="undefined"?globalThis:void 0,$;var p=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if($){$({...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{}}},Ne=new p("W01","Unable to initialize event under dispatching."),De=new p("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),Me=new p("W03","Assigning any truthy value to 'returnValue' property has no effect."),je=new p("W04","Unable to preventDefault on non-cancelable events."),He=new p("W05","Unable to preventDefault inside passive event listener invocation."),Ue=new p("W06","An event listener wasn't added because it has been added already: %o, %o"),B=new p("W07","The %o option value was abandoned because the event listener wasn't added as duplicated."),q=new p("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),yt=new p("W09","Event attribute handler must be a function: %o"),d=class{static get NONE(){return V}static get CAPTURING_PHASE(){return G}static get AT_TARGET(){return Y}static get BUBBLING_PHASE(){return J}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};N.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 l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return V}get CAPTURING_PHASE(){return G}get AT_TARGET(){return Y}get BUBBLING_PHASE(){return J}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:De.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?Me.warn():K(l(this))}preventDefault(){K(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let i=l(this);if(i.dispatchFlag){Ne.warn();return}N.set(this,{...i,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},V=0,G=1,Y=2,J=3,N=new WeakMap;function l(t,e="this"){let n=N.get(t);return D(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function K(t){if(t.inPassiveListenerFlag){He.warn();return}if(!t.cancelable){je.warn();return}t.canceledFlag=!0}Object.defineProperty(d,"NONE",{enumerable:!0});Object.defineProperty(d,"CAPTURING_PHASE",{enumerable:!0});Object.defineProperty(d,"AT_TARGET",{enumerable:!0});Object.defineProperty(d,"BUBBLING_PHASE",{enumerable:!0});var x=Object.getOwnPropertyNames(d.prototype);for(let t=0;t<x.length;++t)x[t]!=="constructor"&&Object.defineProperty(d.prototype,x[t],{enumerable:!0});typeof f!="undefined"&&typeof f.Event!="undefined"&&Object.setPrototypeOf(d.prototype,f.Event.prototype);function Xe(t){return f.DOMException?new f.DOMException(t,"InvalidStateError"):(k==null&&(k=class ne extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,ne)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(k.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),Z(k),Z(k.prototype)),new k(t))}var k,Q={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 Z(t){let e=Object.keys(Q);for(let n=0;n<e.length;++n){let r=e[n],i=Q[r];Object.defineProperty(t,r,{get(){return i},configurable:!0,enumerable:!0})}}var w=class extends d{static wrap(e){return new(ie(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),re.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,se(e,i))}}stopPropagation(){super.stopPropagation();let{original:e}=E(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=E(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=E(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=E(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=E(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=E(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},re=new WeakMap;function E(t){let e=re.get(t);return D(e!=null,"'this' is expected an Event object, but got",t),e}var O=new WeakMap;O.set(Object.prototype,w);typeof f!="undefined"&&typeof f.Event!="undefined"&&O.set(f.Event.prototype,w);function ie(t){let e=Object.getPrototypeOf(t);if(e==null)return w;let n=O.get(e);return n==null&&(n=We(ie(e),e),O.set(e,n)),n}function We(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],se(e,r[i]));return n}function se(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=E(this).original,i=r[e];return typeof i=="function"?i.bind(r):i},set(r){let i=E(this).original;i[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function $e(t,e,n,r,i,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:i,signalListener:a}}function qe(t){t.flags|=8}function ae(t){return(t.flags&1)===1}function oe(t){return(t.flags&2)===2}function ue(t){return(t.flags&4)===4}function Ve(t){return(t.flags&8)===8}function Ge({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){Fe(r)}}function le({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&ae(t[r])===n)return r;return-1}function Ye(t,e,n,r,i,a){let o;a&&(o=ce.bind(null,t,e,n),a.addEventListener("abort",o));let s=$e(e,n,r,i,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,s]):t.listeners.push(s),s}function ce(t,e,n){let r=le(t,e,n);return r!==-1?he(t,r):!1}function he(t,e,n=!1){let r=t.listeners[e];return qe(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 Je(){return Object.create(null)}function Ke(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 C=class{constructor(){fe.set(this,Je())}addEventListener(e,n,r){let i=I(this),{callback:a,capture:o,once:s,passive:c,signal:h,type:y}=Qe(e,n,r);if(a==null||(h==null?void 0:h.aborted))return;let m=Ke(i,y),S=le(m,a,o);if(S!==-1){et(m.listeners[S],c,s,h);return}Ye(m,a,o,c,s,h)}removeEventListener(e,n,r){let i=I(this),{callback:a,capture:o,type:s}=Ze(e,n,r),c=i[s];a!=null&&c&&ce(c,a,o)}dispatchEvent(e){let n=I(this)[String(e.type)];if(n==null)return!0;let r=e instanceof d?e:w.wrap(e),i=l(r,"event");if(i.dispatchFlag)throw Xe("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 c=o[s];if(!Ve(c)&&(ue(c)&&he(n,s,!a)&&(s-=1),i.inPassiveListenerFlag=oe(c),Ge(c,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}},fe=new WeakMap;function I(t,e="this"){let n=fe.get(t);return D(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function Qe(t,e,n){var r;return pe(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 Ze(t,e,n){return pe(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 pe(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(ee(q.message,[t]))}}function et(t,e,n,r){Ue.warn(ae(t)?"capture":"bubble",t.callback),oe(t)!==e&&B.warn("passive"),ue(t)!==n&&B.warn("once"),t.signal!==r&&B.warn("signal")}var F=Object.getOwnPropertyNames(C.prototype);for(let t=0;t<F.length;++t)F[t]!=="constructor"&&Object.defineProperty(C.prototype,F[t],{enumerable:!0});typeof f!="undefined"&&typeof f.EventTarget!="undefined"&&Object.setPrototypeOf(C.prototype,f.EventTarget.prototype);var Te=xe(Re()),pt=[200,201,202,204,308],dt=[408,502,503,504],z=class{constructor(e){this.endpoint=e.endpoint,this.file=e.file,this.headers=e.headers||{},this.method=e.method||"PUT",this.chunkSize=e.chunkSize||30720,this.attempts=e.attempts||5,this.delayBeforeAttempt=e.delayBeforeAttempt||1,this.retryCodes=e.retryCodes||dt,this.dynamicChunkSize=e.dynamicChunkSize||!1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.chunkByteSize=this.chunkSize*1024,this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.attemptCount=0,this.offline=!1,this.paused=!1,this.success=!1,this.nextChunkRangeStart=0,this.maxChunkSize=e.maxChunkSize||512e3,this.minChunkSize=e.minChunkSize||256,this.reader=new FileReader,this.eventTarget=new C,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}on(e,n){this.eventTarget.addEventListener(e,n)}abort(){var e;this.pause(),(e=this.currentXhr)==null||e.abort()}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.sendChunks())}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!="object")throw new TypeError("headers must be null or an object");if(this.chunkSize&&(typeof this.chunkSize!="number"||this.chunkSize<256||this.chunkSize%256!==0||this.chunkSize<this.minChunkSize||this.chunkSize>this.maxChunkSize))throw new TypeError(`chunkSize must be a positive number in multiples of 256, between ${this.minChunkSize} and ${this.maxChunkSize}`);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=>(this.endpointValue=e,this.endpointValue))}getChunk(){return new Promise(e=>{let n=this.totalChunks===1?this.file.size:this.chunkByteSize;this.reader.onload=()=>{this.reader.result!==null&&(this.chunk=new Blob([this.reader.result],{type:"application/octet-stream"})),e()},this.reader.readAsArrayBuffer(this.file.slice(this.nextChunkRangeStart,this.nextChunkRangeStart+n))})}xhrPromise(e){let n=r=>{r.upload.onprogress=i=>{var y;let a=this.totalChunks-this.chunkCount,o=(this.file.size-this.nextChunkRangeStart)/this.file.size/a,s=this.nextChunkRangeStart/this.file.size,h=i.loaded/((y=i.total)!=null?y:this.chunkByteSize)*o;this.dispatch("progress",Math.min((s+h)*100,100))}};return new Promise((r,i)=>{this.currentXhr=(0,Te.default)({...e,beforeSend:n},(a,o)=>(this.currentXhr=void 0,a?i(a):r(o)))})}async sendChunk(){let e=this.nextChunkRangeStart,n=e+this.chunk.size-1,r={...this.headers,"Content-Type":this.file.type,"Content-Range":`bytes ${e}-${n}/${this.file.size}`};return this.dispatch("attempt",{chunkNumber:this.chunkCount,totalChunks:this.totalChunks,chunkSize:this.chunkSize}),this.xhrPromise({headers:r,url:this.endpointValue,method:this.method,body:this.chunk})}manageRetries(){if(this.attemptCount<this.attempts){setTimeout(()=>this.sendChunks(),this.delayBeforeAttempt*1e3),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});return}this.dispatch("error",{message:`An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`,chunk:this.chunkCount,attempts:this.attemptCount})}sendChunks(){this.paused||this.offline||this.success||this.getChunk().then(()=>(this.attemptCount=this.attemptCount+1,this.lastChunkStart=new Date,this.sendChunk())).then(e=>{if(pt.includes(e.statusCode)){let r=(new Date().getTime()-this.lastChunkStart.getTime())/1e3;if(this.dispatch("chunkSuccess",{chunk:this.chunkCount,chunkSize:this.chunkSize,attempts:this.attemptCount,timeInterval:r,response:e}),this.attemptCount=0,this.chunkCount=this.chunkCount+1,this.nextChunkRangeStart=this.nextChunkRangeStart+this.chunkByteSize,this.chunkCount<this.totalChunks){if(this.dynamicChunkSize){r<10?this.chunkSize=Math.min(this.chunkSize*2,this.maxChunkSize):r>30&&(this.chunkSize=Math.max(this.chunkSize/2,this.minChunkSize)),this.chunkSize=Math.ceil(this.chunkSize/256)*256,this.chunkByteSize=this.chunkSize*1024;let i=(this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;this.totalChunks=Math.ceil(this.chunkCount+i)}this.sendChunks()}else this.success=!0,this.dispatch("success")}else if(this.retryCodes.includes(e.statusCode)){if(this.paused||this.offline)return;this.manageRetries()}else{if(this.paused||this.offline)return;this.dispatch("error",{message:`Server responded with ${e.statusCode}. Stopping upload.`,chunkNumber:this.chunkCount,attempts:this.attemptCount})}}).catch(e=>{this.paused||this.offline||this.manageRetries()})}},mt=t=>new z(t); | ||
var Ue=Object.create;var _=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),je=(t,e)=>{for(var n in e)_(t,n,{get:e[n],enumerable:!0})},G=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ne(e))!Me.call(t,i)&&i!==n&&_(t,i,{get:()=>e[i],enumerable:!(r=Fe(e,i))||r.enumerable});return t};var Xe=(t,e,n)=>(n=t!=null?Ue(De(t)):{},G(e||!t||!t.__esModule?_(n,"default",{value:t,enumerable:!0}):n,t)),He=t=>G(_({},"__esModule",{value:!0}),t);var Ee=R((Pt,Ce)=>{var T;typeof window!="undefined"?T=window:typeof global!="undefined"?T=global:typeof self!="undefined"?T=self:T={};Ce.exports=T});var ke=R((At,Se)=>{Se.exports=ct;var lt=Object.prototype.toString;function ct(t){if(!t)return!1;var e=lt.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 we=R((Ot,ve)=>{var W=function(t){return t.replace(/^\s+|\s+$/g,"")},ht=function(t){return Object.prototype.toString.call(t)==="[object Array]"};ve.exports=function(t){if(!t)return{};for(var e={},n=W(t).split(` | ||
`),r=0;r<n.length;r++){var i=n[r],a=i.indexOf(":"),o=W(i.slice(0,a)).toLowerCase(),s=W(i.slice(a+1));typeof e[o]=="undefined"?e[o]=s:ht(e[o])?e[o].push(s):e[o]=[e[o],s]}return e}});var Te=R((It,Re)=>{Re.exports=dt;var pt=Object.prototype.hasOwnProperty;function dt(){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 Ae=R((Lt,$)=>{"use strict";var ze=Ee(),ft=ke(),mt=we(),gt=Te();$.exports=C;$.exports.default=C;C.XMLHttpRequest=ze.XMLHttpRequest||Et;C.XDomainRequest="withCredentials"in new C.XMLHttpRequest?C.XMLHttpRequest:ze.XDomainRequest;bt(["get","put","post","patch","head","delete"],function(t){C[t==="delete"?"del":t]=function(e,n,r){return n=_e(e,n,r),n.method=t.toUpperCase(),Pe(n)}});function bt(t,e){for(var n=0;n<t.length;n++)e(t[n])}function yt(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function _e(t,e,n){var r=t;return ft(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=gt(e,{uri:t}),r.callback=n,r}function C(t,e,n){return e=_e(t,e,n),Pe(e)}function Pe(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(S,z,xe){e||(e=!0,t.callback(S,z,xe))};function r(){s.readyState===4&&setTimeout(o,0)}function i(){var u=void 0;if(s.response?u=s.response:u=s.responseText||Ct(s),V)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(F),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,q)}function o(){if(!h){var u;clearTimeout(F),t.useXDR&&s.status===void 0?u=200:u=s.status===1223?204:s.status;var S=q,z=null;return u!==0?(S={body:i(),statusCode:u,method:d,headers:{},url:p,rawRequest:s},s.getAllResponseHeaders&&(S.headers=mt(s.getAllResponseHeaders()))):z=new Error("Internal XMLHttpRequest Error"),n(z,S,S.body)}}var s=t.xhr||null;s||(t.cors||t.useXDR?s=new C.XDomainRequest:s=new C.XMLHttpRequest);var c,h,p=s.url=t.uri||t.url,d=s.method=t.method||"GET",y=t.body||t.data,f=s.headers=t.headers||{},U=!!t.sync,V=!1,F,q={body:void 0,headers:{},statusCode:0,method:d,url:p,rawRequest:s};if("json"in t&&t.json!==!1&&(V=!0,f.accept||f.Accept||(f.Accept="application/json"),d!=="GET"&&d!=="HEAD"&&(f["content-type"]||f["Content-Type"]||(f["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,p,!U,t.username,t.password),U||(s.withCredentials=!!t.withCredentials),!U&&t.timeout>0&&(F=setTimeout(function(){if(!h){h=!0,s.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),s.setRequestHeader)for(c in f)f.hasOwnProperty(c)&&s.setRequestHeader(c,f[c]);else if(t.headers&&!yt(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 Ct(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 Rt={};je(Rt,{ChunkedStreamIterable:()=>I,UpChunk:()=>L,createUpload:()=>wt,getChunkSizeError:()=>O,isValidChunkSize:()=>A});module.exports=He(Rt);function H(t,e,...n){if(!t)throw new TypeError(se(e,n))}function se(t,e){let n=0;return t.replace(/%[os]/gu,()=>ae(e[n++]))}function ae(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var Y;function We(t){try{let e=t instanceof Error?t:new Error(ae(t));if(Y){Y(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,K;var g=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if(K){K({...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{}}},$e=new g("W01","Unable to initialize event under dispatching."),Ve=new g("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),qe=new g("W03","Assigning any truthy value to 'returnValue' property has no effect."),Ge=new g("W04","Unable to preventDefault on non-cancelable events."),Ye=new g("W05","Unable to preventDefault inside passive event listener invocation."),Ke=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."),Z=new g("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),zt=new g("W09","Event attribute handler must be a function: %o"),b=class{static get NONE(){return J}static get CAPTURING_PHASE(){return Q}static get AT_TARGET(){return ee}static get BUBBLING_PHASE(){return te}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};X.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 l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return J}get CAPTURING_PHASE(){return Q}get AT_TARGET(){return ee}get BUBBLING_PHASE(){return te}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:Ve.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?qe.warn():ne(l(this))}preventDefault(){ne(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let i=l(this);if(i.dispatchFlag){$e.warn();return}X.set(this,{...i,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},J=0,Q=1,ee=2,te=3,X=new WeakMap;function l(t,e="this"){let n=X.get(t);return H(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function ne(t){if(t.inPassiveListenerFlag){Ye.warn();return}if(!t.cancelable){Ge.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 Ze(t){return m.DOMException?new m.DOMException(t,"InvalidStateError"):(v==null&&(v=class oe extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,oe)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(v.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),ie(v),ie(v.prototype)),new v(t))}var v,re={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 ie(t){let e=Object.keys(re);for(let n=0;n<e.length;++n){let r=e[n],i=re[r];Object.defineProperty(t,r,{get(){return i},configurable:!0,enumerable:!0})}}var w=class extends b{static wrap(e){return new(le(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),ue.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,ce(e,i))}}stopPropagation(){super.stopPropagation();let{original:e}=E(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=E(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=E(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=E(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=E(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=E(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},ue=new WeakMap;function E(t){let e=ue.get(t);return H(e!=null,"'this' is expected an Event object, but got",t),e}var P=new WeakMap;P.set(Object.prototype,w);typeof m!="undefined"&&typeof m.Event!="undefined"&&P.set(m.Event.prototype,w);function le(t){let e=Object.getPrototypeOf(t);if(e==null)return w;let n=P.get(e);return n==null&&(n=Je(le(e),e),P.set(e,n)),n}function Je(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],ce(e,r[i]));return n}function ce(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=E(this).original,i=r[e];return typeof i=="function"?i.bind(r):i},set(r){let i=E(this).original;i[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function Qe(t,e,n,r,i,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:i,signalListener:a}}function et(t){t.flags|=8}function he(t){return(t.flags&1)===1}function pe(t){return(t.flags&2)===2}function de(t){return(t.flags&4)===4}function tt(t){return(t.flags&8)===8}function nt({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){We(r)}}function fe({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&he(t[r])===n)return r;return-1}function rt(t,e,n,r,i,a){let o;a&&(o=me.bind(null,t,e,n),a.addEventListener("abort",o));let s=Qe(e,n,r,i,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,s]):t.listeners.push(s),s}function me(t,e,n){let r=fe(t,e,n);return r!==-1?ge(t,r):!1}function ge(t,e,n=!1){let r=t.listeners[e];return et(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 it(){return Object.create(null)}function st(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 k=class{constructor(){be.set(this,it())}addEventListener(e,n,r){let i=M(this),{callback:a,capture:o,once:s,passive:c,signal:h,type:p}=at(e,n,r);if(a==null||(h==null?void 0:h.aborted))return;let d=st(i,p),y=fe(d,a,o);if(y!==-1){ut(d.listeners[y],c,s,h);return}rt(d,a,o,c,s,h)}removeEventListener(e,n,r){let i=M(this),{callback:a,capture:o,type:s}=ot(e,n,r),c=i[s];a!=null&&c&&me(c,a,o)}dispatchEvent(e){let n=M(this)[String(e.type)];if(n==null)return!0;let r=e instanceof b?e:w.wrap(e),i=l(r,"event");if(i.dispatchFlag)throw Ze("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 c=o[s];if(!tt(c)&&(de(c)&&ge(n,s,!a)&&(s-=1),i.inPassiveListenerFlag=pe(c),nt(c,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}},be=new WeakMap;function M(t,e="this"){let n=be.get(t);return H(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function at(t,e,n){var r;return ye(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 ot(t,e,n){return ye(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 ye(t){if(!(typeof t=="function"||typeof t=="object"&&t!==null&&typeof t.handleEvent=="function")){if(t==null||typeof t=="object"){Z.warn(t);return}throw new TypeError(se(Z.message,[t]))}}function ut(t,e,n,r){Ke.warn(he(t)?"capture":"bubble",t.callback),pe(t)!==e&&N.warn("passive"),de(t)!==n&&N.warn("once"),t.signal!==r&&N.warn("signal")}var j=Object.getOwnPropertyNames(k.prototype);for(let t=0;t<j.length;++t)j[t]!=="constructor"&&Object.defineProperty(k.prototype,j[t],{enumerable:!0});typeof m!="undefined"&&typeof m.EventTarget!="undefined"&&Object.setPrototypeOf(k.prototype,m.EventTarget.prototype);var Oe=Xe(Ae()),Ie=30720,B=512e3,x=256,A=(t,{minChunkSize:e=x,maxChunkSize:n=B}={})=>t==null||typeof t=="number"&&t>=256&&t%256===0&&t>=e&&t<=n,O=(t,{minChunkSize:e=x,maxChunkSize:n=B}={})=>new TypeError(`chunkSize ${t} must be a positive number in multiples of 256, between ${e} and ${n}`),I=class{constructor(e,n={}){this.readableStream=e;var r,i,a;if(!A(n.defaultChunkSize,n))throw O(n.defaultChunkSize,n);this.defaultChunkSize=(r=n.defaultChunkSize)!=null?r:Ie,this.minChunkSize=(i=n.minChunkSize)!=null?i:x,this.maxChunkSize=(a=n.maxChunkSize)!=null?a:B}get chunkSize(){var e;return(e=this._chunkSize)!=null?e:this.defaultChunkSize}set chunkSize(e){if(!A(e,this))throw O(e,this);this._chunkSize=e}get chunkByteSize(){return this.chunkSize*1024}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}}}}finally{if(e){let r=e;e=void 0,yield r}n.releaseLock();return}}},St=[200,201,202,204,308],Le=[408,502,503,504],Be=(t,e)=>!!t&&St.includes(t.statusCode),kt=(t,{retryCodes:e=Le})=>!t||e.includes(t.statusCode),vt=(t,e)=>e.attemptCount>=e.attempts||!(Be(t)||kt(t,e)),L=class{constructor(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||Le,this.dynamicChunkSize=e.dynamicChunkSize||!1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.attemptCount=0,this.offline=!1,this._paused=!1,this.success=!1,this.nextChunkRangeStart=0,this.chunkedStreamIterable=new I(this.file.stream(),{...e,defaultChunkSize:e.chunkSize}),this.chunkedStreamIterator=this.chunkedStreamIterable[Symbol.asyncIterator](),this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.eventTarget=new k,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}get maxChunkSize(){var e,n;return(n=(e=this.chunkedStreamIterable)==null?void 0:e.chunkSize)!=null?n:B}get minChunkSize(){var e,n;return(n=(e=this.chunkedStreamIterable)==null?void 0:e.chunkSize)!=null?n:x}get chunkSize(){var e,n;return(n=(e=this.chunkedStreamIterable)==null?void 0:e.chunkSize)!=null?n:Ie}set chunkSize(e){this.chunkedStreamIterable.chunkSize=e}get chunkByteSize(){return this.chunkedStreamIterable.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 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())}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!="object")throw new TypeError("headers must be null or an object");if(!A(this.chunkSize,{maxChunkSize:this.maxChunkSize,minChunkSize:this.minChunkSize}))throw O(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=>(this.endpointValue=e,this.endpointValue))}xhrPromise(e){let n=r=>{r.upload.onprogress=i=>{var p;let a=this.totalChunks-this.chunkCount,o=(this.file.size-this.nextChunkRangeStart)/this.file.size/a,s=this.nextChunkRangeStart/this.file.size,h=i.loaded/((p=i.total)!=null?p:this.chunkByteSize)*o;this.dispatch("progress",Math.min((s+h)*100,100))}};return new Promise((r,i)=>{this.currentXhr=(0,Oe.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,i={...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:i,url:this.endpointValue,method:this.method,body:e})}async sendChunkWithRetries(e){let n=async(s,c)=>{var d;let p=(new Date().getTime()-this.lastChunkStart.getTime())/1e3;if(this.dispatch("chunkSuccess",{chunk:this.chunkCount,chunkSize:this.chunkSize,attempts:this.attemptCount,timeInterval:p,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;p<10?y=Math.min(this.chunkSize*2,this.maxChunkSize):p>30&&(y=Math.max(this.chunkSize/2,this.minChunkSize)),this.chunkSize=Math.ceil(y/256)*256;let f=(this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;this.totalChunks=Math.ceil(this.chunkCount+f)}return!0},r=async(s,c)=>(this.dispatch("error",{message:`Server responded with ${s.statusCode}. Stopping upload.`,chunk:this.chunkCount,attempts:this.attemptCount}),!1),i=async(s,c)=>(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}),new Promise(h=>{setTimeout(async()=>{if(this._paused||this.offline){this.pendingChunk=e,h(!1);return}let p=await this.sendChunkWithRetries(e);h(p)},this.delayBeforeAttempt*1e3)})),a;try{this.attemptCount=this.attemptCount+1,this.lastChunkStart=new Date,a=await this.sendChunk(e)}catch{}let o={retryCodes:this.retryCodes,attemptCount:this.attemptCount,attempts:this.attempts};return Be(a,o)?n(a,e):vt(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.chunkedStreamIterator.next(),r=!e&&n;if(e&&(r=await this.sendChunkWithRetries(e)),this.success=!!n,this.success&&r&&this.dispatch("success"),!r)return}}},wt=t=>new L(t); | ||
//# sourceMappingURL=upchunk.cjs.js.map |
@@ -1,2 +0,27 @@ | ||
import { XhrHeaders, XhrResponse } from 'xhr'; | ||
import { type XhrHeaders, type XhrResponse } from 'xhr'; | ||
export declare const isValidChunkSize: (chunkSize: any, { minChunkSize, maxChunkSize, }?: { | ||
minChunkSize?: number | undefined; | ||
maxChunkSize?: number | undefined; | ||
}) => chunkSize is number | null | undefined; | ||
export declare const getChunkSizeError: (chunkSize: any, { minChunkSize, maxChunkSize, }?: { | ||
minChunkSize?: number | undefined; | ||
maxChunkSize?: number | undefined; | ||
}) => TypeError; | ||
export declare type ChunkedStreamIterableOptions = { | ||
defaultChunkSize?: number; | ||
minChunkSize?: number; | ||
maxChunkSize?: number; | ||
}; | ||
export declare class ChunkedStreamIterable implements AsyncIterable<Blob> { | ||
protected readableStream: ReadableStream<Uint8Array | Blob>; | ||
protected _chunkSize: number | undefined; | ||
protected defaultChunkSize: number; | ||
readonly minChunkSize: number; | ||
readonly maxChunkSize: number; | ||
constructor(readableStream: ReadableStream<Uint8Array | Blob>, options?: ChunkedStreamIterableOptions); | ||
get chunkSize(): number; | ||
set chunkSize(value: number); | ||
get chunkByteSize(): number; | ||
[Symbol.asyncIterator](): AsyncIterator<Blob>; | ||
} | ||
declare type EventName = 'attempt' | 'attemptFailure' | 'chunkSuccess' | 'error' | 'offline' | 'online' | 'progress' | 'success'; | ||
@@ -23,3 +48,2 @@ declare type AllowedMethods = 'PUT' | 'POST' | 'PATCH'; | ||
method: AllowedMethods; | ||
chunkSize: number; | ||
attempts: number; | ||
@@ -29,5 +53,6 @@ delayBeforeAttempt: number; | ||
dynamicChunkSize: boolean; | ||
private chunk; | ||
protected chunkedStreamIterable: ChunkedStreamIterable; | ||
protected chunkedStreamIterator: AsyncIterator<Blob, any, undefined>; | ||
protected pendingChunk?: Blob; | ||
private chunkCount; | ||
private chunkByteSize; | ||
private maxFileBytes; | ||
@@ -38,3 +63,3 @@ private endpointValue; | ||
private offline; | ||
private paused; | ||
private _paused; | ||
private success; | ||
@@ -44,7 +69,10 @@ private currentXhr?; | ||
private nextChunkRangeStart; | ||
private maxChunkSize; | ||
private minChunkSize; | ||
private reader; | ||
private eventTarget; | ||
constructor(options: UpChunkOptions); | ||
protected get maxChunkSize(): number; | ||
protected get minChunkSize(): number; | ||
get chunkSize(): number; | ||
set chunkSize(value: number); | ||
get chunkByteSize(): number; | ||
get totalChunkSize(): number; | ||
/** | ||
@@ -54,2 +82,11 @@ * Subscribe to an event | ||
on(eventName: EventName, fn: (event: CustomEvent) => void): void; | ||
/** | ||
* Subscribe to an event once | ||
*/ | ||
once(eventName: EventName, fn: (event: CustomEvent) => void): void; | ||
/** | ||
* Unsubscribe to an event | ||
*/ | ||
off(eventName: EventName, fn: (event: CustomEvent) => void): void; | ||
get paused(): boolean; | ||
abort(): void; | ||
@@ -70,6 +107,2 @@ pause(): void; | ||
private getEndpoint; | ||
/** | ||
* Get portion of the file of x bytes corresponding to chunkSize | ||
*/ | ||
private getChunk; | ||
private xhrPromise; | ||
@@ -79,8 +112,5 @@ /** | ||
*/ | ||
protected sendChunk(): Promise<XhrResponse>; | ||
protected sendChunk(chunk: Blob): Promise<XhrResponse>; | ||
protected sendChunkWithRetries(chunk: Blob): Promise<boolean>; | ||
/** | ||
* Called on net failure. If retry counter !== 0, retry after delayBeforeAttempt | ||
*/ | ||
private manageRetries; | ||
/** | ||
* Manage the whole upload by calling getChunk & sendChunk | ||
@@ -87,0 +117,0 @@ * handle errors & retries and dispatch events |
@@ -1,4 +0,4 @@ | ||
var UpChunk=(()=>{var Ae=Object.create;var A=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Be=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},X=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ze(e))!Le.call(t,i)&&i!==n&&A(t,i,{get:()=>e[i],enumerable:!(r=Oe(e,i))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?Ae(_e(t)):{},X(e||!t||!t.__esModule?A(n,"default",{value:t,enumerable:!0}):n,t)),Ie=t=>X(A({},"__esModule",{value:!0}),t);var me=R((vt,de)=>{var T;typeof window!="undefined"?T=window:typeof global!="undefined"?T=global:typeof self!="undefined"?T=self:T={};de.exports=T});var be=R((Ct,ge)=>{ge.exports=nt;var tt=Object.prototype.toString;function nt(t){if(!t)return!1;var e=tt.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 Ee=R((St,ye)=>{var M=function(t){return t.replace(/^\s+|\s+$/g,"")},rt=function(t){return Object.prototype.toString.call(t)==="[object Array]"};ye.exports=function(t){if(!t)return{};for(var e={},n=M(t).split(` | ||
`),r=0;r<n.length;r++){var i=n[r],a=i.indexOf(":"),o=M(i.slice(0,a)).toLowerCase(),s=M(i.slice(a+1));typeof e[o]=="undefined"?e[o]=s:rt(e[o])?e[o].push(s):e[o]=[e[o],s]}return e}});var Ce=R((kt,ve)=>{ve.exports=st;var it=Object.prototype.hasOwnProperty;function st(){for(var t={},e=0;e<arguments.length;e++){var n=arguments[e];for(var r in n)it.call(n,r)&&(t[r]=n[r])}return t}});var Re=R((wt,j)=>{"use strict";var Se=me(),at=be(),ot=Ee(),ut=Ce();j.exports=b;j.exports.default=b;b.XMLHttpRequest=Se.XMLHttpRequest||ft;b.XDomainRequest="withCredentials"in new b.XMLHttpRequest?b.XMLHttpRequest:Se.XDomainRequest;lt(["get","put","post","patch","head","delete"],function(t){b[t==="delete"?"del":t]=function(e,n,r){return n=ke(e,n,r),n.method=t.toUpperCase(),we(n)}});function lt(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 ke(t,e,n){var r=t;return at(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=ut(e,{uri:t}),r.callback=n,r}function b(t,e,n){return e=ke(t,e,n),we(e)}function we(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(v,P,Pe){e||(e=!0,t.callback(v,P,Pe))};function r(){s.readyState===4&&setTimeout(o,0)}function i(){var u=void 0;if(s.response?u=s.response:u=s.responseText||ht(s),H)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(L),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,U)}function o(){if(!h){var u;clearTimeout(L),t.useXDR&&s.status===void 0?u=200:u=s.status===1223?204:s.status;var v=U,P=null;return u!==0?(v={body:i(),statusCode:u,method:m,headers:{},url:y,rawRequest:s},s.getAllResponseHeaders&&(v.headers=ot(s.getAllResponseHeaders()))):P=new Error("Internal XMLHttpRequest Error"),n(P,v,v.body)}}var s=t.xhr||null;s||(t.cors||t.useXDR?s=new b.XDomainRequest:s=new b.XMLHttpRequest);var c,h,y=s.url=t.uri||t.url,m=s.method=t.method||"GET",S=t.body||t.data,g=s.headers=t.headers||{},_=!!t.sync,H=!1,L,U={body:void 0,headers:{},statusCode:0,method:m,url:y,rawRequest:s};if("json"in t&&t.json!==!1&&(H=!0,g.accept||g.Accept||(g.Accept="application/json"),m!=="GET"&&m!=="HEAD"&&(g["content-type"]||g["Content-Type"]||(g["Content-Type"]="application/json"),S=JSON.stringify(t.json===!0?S:t.json))),s.onreadystatechange=r,s.onload=o,s.onerror=a,s.onprogress=function(){},s.onabort=function(){h=!0},s.ontimeout=a,s.open(m,y,!_,t.username,t.password),_||(s.withCredentials=!!t.withCredentials),!_&&t.timeout>0&&(L=setTimeout(function(){if(!h){h=!0,s.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),s.setRequestHeader)for(c in g)g.hasOwnProperty(c)&&s.setRequestHeader(c,g[c]);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(S||null),s}function ht(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 ft(){}});var gt={};Be(gt,{UpChunk:()=>z,createUpload:()=>mt});function D(t,e,...n){if(!t)throw new TypeError(ee(e,n))}function ee(t,e){let n=0;return t.replace(/%[os]/gu,()=>te(e[n++]))}function te(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var W;function Fe(t){try{let e=t instanceof Error?t:new Error(te(t));if(W){W(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 f=typeof window!="undefined"?window:typeof self!="undefined"?self:typeof global!="undefined"?global:typeof globalThis!="undefined"?globalThis:void 0,$;var p=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if($){$({...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{}}},Ne=new p("W01","Unable to initialize event under dispatching."),De=new p("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),Me=new p("W03","Assigning any truthy value to 'returnValue' property has no effect."),je=new p("W04","Unable to preventDefault on non-cancelable events."),He=new p("W05","Unable to preventDefault inside passive event listener invocation."),Ue=new p("W06","An event listener wasn't added because it has been added already: %o, %o"),B=new p("W07","The %o option value was abandoned because the event listener wasn't added as duplicated."),q=new p("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),yt=new p("W09","Event attribute handler must be a function: %o"),d=class{static get NONE(){return V}static get CAPTURING_PHASE(){return G}static get AT_TARGET(){return Y}static get BUBBLING_PHASE(){return J}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};N.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 l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return V}get CAPTURING_PHASE(){return G}get AT_TARGET(){return Y}get BUBBLING_PHASE(){return J}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:De.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?Me.warn():K(l(this))}preventDefault(){K(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let i=l(this);if(i.dispatchFlag){Ne.warn();return}N.set(this,{...i,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},V=0,G=1,Y=2,J=3,N=new WeakMap;function l(t,e="this"){let n=N.get(t);return D(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function K(t){if(t.inPassiveListenerFlag){He.warn();return}if(!t.cancelable){je.warn();return}t.canceledFlag=!0}Object.defineProperty(d,"NONE",{enumerable:!0});Object.defineProperty(d,"CAPTURING_PHASE",{enumerable:!0});Object.defineProperty(d,"AT_TARGET",{enumerable:!0});Object.defineProperty(d,"BUBBLING_PHASE",{enumerable:!0});var x=Object.getOwnPropertyNames(d.prototype);for(let t=0;t<x.length;++t)x[t]!=="constructor"&&Object.defineProperty(d.prototype,x[t],{enumerable:!0});typeof f!="undefined"&&typeof f.Event!="undefined"&&Object.setPrototypeOf(d.prototype,f.Event.prototype);function Xe(t){return f.DOMException?new f.DOMException(t,"InvalidStateError"):(k==null&&(k=class ne extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,ne)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(k.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),Z(k),Z(k.prototype)),new k(t))}var k,Q={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 Z(t){let e=Object.keys(Q);for(let n=0;n<e.length;++n){let r=e[n],i=Q[r];Object.defineProperty(t,r,{get(){return i},configurable:!0,enumerable:!0})}}var w=class extends d{static wrap(e){return new(ie(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),re.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,se(e,i))}}stopPropagation(){super.stopPropagation();let{original:e}=E(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=E(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=E(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=E(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=E(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=E(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},re=new WeakMap;function E(t){let e=re.get(t);return D(e!=null,"'this' is expected an Event object, but got",t),e}var O=new WeakMap;O.set(Object.prototype,w);typeof f!="undefined"&&typeof f.Event!="undefined"&&O.set(f.Event.prototype,w);function ie(t){let e=Object.getPrototypeOf(t);if(e==null)return w;let n=O.get(e);return n==null&&(n=We(ie(e),e),O.set(e,n)),n}function We(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],se(e,r[i]));return n}function se(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=E(this).original,i=r[e];return typeof i=="function"?i.bind(r):i},set(r){let i=E(this).original;i[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function $e(t,e,n,r,i,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:i,signalListener:a}}function qe(t){t.flags|=8}function ae(t){return(t.flags&1)===1}function oe(t){return(t.flags&2)===2}function ue(t){return(t.flags&4)===4}function Ve(t){return(t.flags&8)===8}function Ge({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){Fe(r)}}function le({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&ae(t[r])===n)return r;return-1}function Ye(t,e,n,r,i,a){let o;a&&(o=ce.bind(null,t,e,n),a.addEventListener("abort",o));let s=$e(e,n,r,i,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,s]):t.listeners.push(s),s}function ce(t,e,n){let r=le(t,e,n);return r!==-1?he(t,r):!1}function he(t,e,n=!1){let r=t.listeners[e];return qe(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 Je(){return Object.create(null)}function Ke(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 C=class{constructor(){fe.set(this,Je())}addEventListener(e,n,r){let i=I(this),{callback:a,capture:o,once:s,passive:c,signal:h,type:y}=Qe(e,n,r);if(a==null||(h==null?void 0:h.aborted))return;let m=Ke(i,y),S=le(m,a,o);if(S!==-1){et(m.listeners[S],c,s,h);return}Ye(m,a,o,c,s,h)}removeEventListener(e,n,r){let i=I(this),{callback:a,capture:o,type:s}=Ze(e,n,r),c=i[s];a!=null&&c&&ce(c,a,o)}dispatchEvent(e){let n=I(this)[String(e.type)];if(n==null)return!0;let r=e instanceof d?e:w.wrap(e),i=l(r,"event");if(i.dispatchFlag)throw Xe("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 c=o[s];if(!Ve(c)&&(ue(c)&&he(n,s,!a)&&(s-=1),i.inPassiveListenerFlag=oe(c),Ge(c,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}},fe=new WeakMap;function I(t,e="this"){let n=fe.get(t);return D(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function Qe(t,e,n){var r;return pe(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 Ze(t,e,n){return pe(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 pe(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(ee(q.message,[t]))}}function et(t,e,n,r){Ue.warn(ae(t)?"capture":"bubble",t.callback),oe(t)!==e&&B.warn("passive"),ue(t)!==n&&B.warn("once"),t.signal!==r&&B.warn("signal")}var F=Object.getOwnPropertyNames(C.prototype);for(let t=0;t<F.length;++t)F[t]!=="constructor"&&Object.defineProperty(C.prototype,F[t],{enumerable:!0});typeof f!="undefined"&&typeof f.EventTarget!="undefined"&&Object.setPrototypeOf(C.prototype,f.EventTarget.prototype);var Te=xe(Re()),pt=[200,201,202,204,308],dt=[408,502,503,504],z=class{constructor(e){this.endpoint=e.endpoint,this.file=e.file,this.headers=e.headers||{},this.method=e.method||"PUT",this.chunkSize=e.chunkSize||30720,this.attempts=e.attempts||5,this.delayBeforeAttempt=e.delayBeforeAttempt||1,this.retryCodes=e.retryCodes||dt,this.dynamicChunkSize=e.dynamicChunkSize||!1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.chunkByteSize=this.chunkSize*1024,this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.attemptCount=0,this.offline=!1,this.paused=!1,this.success=!1,this.nextChunkRangeStart=0,this.maxChunkSize=e.maxChunkSize||512e3,this.minChunkSize=e.minChunkSize||256,this.reader=new FileReader,this.eventTarget=new C,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}on(e,n){this.eventTarget.addEventListener(e,n)}abort(){var e;this.pause(),(e=this.currentXhr)==null||e.abort()}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.sendChunks())}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!="object")throw new TypeError("headers must be null or an object");if(this.chunkSize&&(typeof this.chunkSize!="number"||this.chunkSize<256||this.chunkSize%256!==0||this.chunkSize<this.minChunkSize||this.chunkSize>this.maxChunkSize))throw new TypeError(`chunkSize must be a positive number in multiples of 256, between ${this.minChunkSize} and ${this.maxChunkSize}`);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=>(this.endpointValue=e,this.endpointValue))}getChunk(){return new Promise(e=>{let n=this.totalChunks===1?this.file.size:this.chunkByteSize;this.reader.onload=()=>{this.reader.result!==null&&(this.chunk=new Blob([this.reader.result],{type:"application/octet-stream"})),e()},this.reader.readAsArrayBuffer(this.file.slice(this.nextChunkRangeStart,this.nextChunkRangeStart+n))})}xhrPromise(e){let n=r=>{r.upload.onprogress=i=>{var y;let a=this.totalChunks-this.chunkCount,o=(this.file.size-this.nextChunkRangeStart)/this.file.size/a,s=this.nextChunkRangeStart/this.file.size,h=i.loaded/((y=i.total)!=null?y:this.chunkByteSize)*o;this.dispatch("progress",Math.min((s+h)*100,100))}};return new Promise((r,i)=>{this.currentXhr=(0,Te.default)({...e,beforeSend:n},(a,o)=>(this.currentXhr=void 0,a?i(a):r(o)))})}async sendChunk(){let e=this.nextChunkRangeStart,n=e+this.chunk.size-1,r={...this.headers,"Content-Type":this.file.type,"Content-Range":`bytes ${e}-${n}/${this.file.size}`};return this.dispatch("attempt",{chunkNumber:this.chunkCount,totalChunks:this.totalChunks,chunkSize:this.chunkSize}),this.xhrPromise({headers:r,url:this.endpointValue,method:this.method,body:this.chunk})}manageRetries(){if(this.attemptCount<this.attempts){setTimeout(()=>this.sendChunks(),this.delayBeforeAttempt*1e3),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});return}this.dispatch("error",{message:`An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`,chunk:this.chunkCount,attempts:this.attemptCount})}sendChunks(){this.paused||this.offline||this.success||this.getChunk().then(()=>(this.attemptCount=this.attemptCount+1,this.lastChunkStart=new Date,this.sendChunk())).then(e=>{if(pt.includes(e.statusCode)){let r=(new Date().getTime()-this.lastChunkStart.getTime())/1e3;if(this.dispatch("chunkSuccess",{chunk:this.chunkCount,chunkSize:this.chunkSize,attempts:this.attemptCount,timeInterval:r,response:e}),this.attemptCount=0,this.chunkCount=this.chunkCount+1,this.nextChunkRangeStart=this.nextChunkRangeStart+this.chunkByteSize,this.chunkCount<this.totalChunks){if(this.dynamicChunkSize){r<10?this.chunkSize=Math.min(this.chunkSize*2,this.maxChunkSize):r>30&&(this.chunkSize=Math.max(this.chunkSize/2,this.minChunkSize)),this.chunkSize=Math.ceil(this.chunkSize/256)*256,this.chunkByteSize=this.chunkSize*1024;let i=(this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;this.totalChunks=Math.ceil(this.chunkCount+i)}this.sendChunks()}else this.success=!0,this.dispatch("success")}else if(this.retryCodes.includes(e.statusCode)){if(this.paused||this.offline)return;this.manageRetries()}else{if(this.paused||this.offline)return;this.dispatch("error",{message:`Server responded with ${e.statusCode}. Stopping upload.`,chunkNumber:this.chunkCount,attempts:this.attemptCount})}}).catch(e=>{this.paused||this.offline||this.manageRetries()})}},mt=t=>new z(t);return Ie(gt);})(); | ||
var UpChunk=(()=>{var Ue=Object.create;var _=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),je=(t,e)=>{for(var n in e)_(t,n,{get:e[n],enumerable:!0})},G=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ne(e))!Me.call(t,i)&&i!==n&&_(t,i,{get:()=>e[i],enumerable:!(r=Fe(e,i))||r.enumerable});return t};var Xe=(t,e,n)=>(n=t!=null?Ue(De(t)):{},G(e||!t||!t.__esModule?_(n,"default",{value:t,enumerable:!0}):n,t)),He=t=>G(_({},"__esModule",{value:!0}),t);var Ee=R((Pt,Ce)=>{var T;typeof window!="undefined"?T=window:typeof global!="undefined"?T=global:typeof self!="undefined"?T=self:T={};Ce.exports=T});var ke=R((At,Se)=>{Se.exports=ct;var lt=Object.prototype.toString;function ct(t){if(!t)return!1;var e=lt.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 we=R((Ot,ve)=>{var W=function(t){return t.replace(/^\s+|\s+$/g,"")},ht=function(t){return Object.prototype.toString.call(t)==="[object Array]"};ve.exports=function(t){if(!t)return{};for(var e={},n=W(t).split(` | ||
`),r=0;r<n.length;r++){var i=n[r],a=i.indexOf(":"),o=W(i.slice(0,a)).toLowerCase(),s=W(i.slice(a+1));typeof e[o]=="undefined"?e[o]=s:ht(e[o])?e[o].push(s):e[o]=[e[o],s]}return e}});var Te=R((It,Re)=>{Re.exports=dt;var pt=Object.prototype.hasOwnProperty;function dt(){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 Ae=R((Lt,$)=>{"use strict";var ze=Ee(),ft=ke(),mt=we(),gt=Te();$.exports=C;$.exports.default=C;C.XMLHttpRequest=ze.XMLHttpRequest||Et;C.XDomainRequest="withCredentials"in new C.XMLHttpRequest?C.XMLHttpRequest:ze.XDomainRequest;bt(["get","put","post","patch","head","delete"],function(t){C[t==="delete"?"del":t]=function(e,n,r){return n=_e(e,n,r),n.method=t.toUpperCase(),Pe(n)}});function bt(t,e){for(var n=0;n<t.length;n++)e(t[n])}function yt(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function _e(t,e,n){var r=t;return ft(e)?(n=e,typeof t=="string"&&(r={uri:t})):r=gt(e,{uri:t}),r.callback=n,r}function C(t,e,n){return e=_e(t,e,n),Pe(e)}function Pe(t){if(typeof t.callback=="undefined")throw new Error("callback argument missing");var e=!1,n=function(S,z,xe){e||(e=!0,t.callback(S,z,xe))};function r(){s.readyState===4&&setTimeout(o,0)}function i(){var u=void 0;if(s.response?u=s.response:u=s.responseText||Ct(s),V)try{u=JSON.parse(u)}catch{}return u}function a(u){return clearTimeout(F),u instanceof Error||(u=new Error(""+(u||"Unknown XMLHttpRequest Error"))),u.statusCode=0,n(u,q)}function o(){if(!h){var u;clearTimeout(F),t.useXDR&&s.status===void 0?u=200:u=s.status===1223?204:s.status;var S=q,z=null;return u!==0?(S={body:i(),statusCode:u,method:d,headers:{},url:p,rawRequest:s},s.getAllResponseHeaders&&(S.headers=mt(s.getAllResponseHeaders()))):z=new Error("Internal XMLHttpRequest Error"),n(z,S,S.body)}}var s=t.xhr||null;s||(t.cors||t.useXDR?s=new C.XDomainRequest:s=new C.XMLHttpRequest);var c,h,p=s.url=t.uri||t.url,d=s.method=t.method||"GET",y=t.body||t.data,f=s.headers=t.headers||{},U=!!t.sync,V=!1,F,q={body:void 0,headers:{},statusCode:0,method:d,url:p,rawRequest:s};if("json"in t&&t.json!==!1&&(V=!0,f.accept||f.Accept||(f.Accept="application/json"),d!=="GET"&&d!=="HEAD"&&(f["content-type"]||f["Content-Type"]||(f["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,p,!U,t.username,t.password),U||(s.withCredentials=!!t.withCredentials),!U&&t.timeout>0&&(F=setTimeout(function(){if(!h){h=!0,s.abort("timeout");var u=new Error("XMLHttpRequest timeout");u.code="ETIMEDOUT",a(u)}},t.timeout)),s.setRequestHeader)for(c in f)f.hasOwnProperty(c)&&s.setRequestHeader(c,f[c]);else if(t.headers&&!yt(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 Ct(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 Rt={};je(Rt,{ChunkedStreamIterable:()=>I,UpChunk:()=>L,createUpload:()=>wt,getChunkSizeError:()=>O,isValidChunkSize:()=>A});function H(t,e,...n){if(!t)throw new TypeError(se(e,n))}function se(t,e){let n=0;return t.replace(/%[os]/gu,()=>ae(e[n++]))}function ae(t){return typeof t!="object"||t===null?String(t):Object.prototype.toString.call(t)}var Y;function We(t){try{let e=t instanceof Error?t:new Error(ae(t));if(Y){Y(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,K;var g=class{constructor(e,n){this.code=e,this.message=n}warn(...e){var n;try{if(K){K({...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{}}},$e=new g("W01","Unable to initialize event under dispatching."),Ve=new g("W02","Assigning any falsy value to 'cancelBubble' property has no effect."),qe=new g("W03","Assigning any truthy value to 'returnValue' property has no effect."),Ge=new g("W04","Unable to preventDefault on non-cancelable events."),Ye=new g("W05","Unable to preventDefault inside passive event listener invocation."),Ke=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."),Z=new g("W08","The 'callback' argument must be a function or an object that has 'handleEvent' method: %o"),zt=new g("W09","Event attribute handler must be a function: %o"),b=class{static get NONE(){return J}static get CAPTURING_PHASE(){return Q}static get AT_TARGET(){return ee}static get BUBBLING_PHASE(){return te}constructor(e,n){Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let r=n!=null?n:{};X.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 l(this).type}get target(){return l(this).target}get srcElement(){return l(this).target}get currentTarget(){return l(this).currentTarget}composedPath(){let e=l(this).currentTarget;return e?[e]:[]}get NONE(){return J}get CAPTURING_PHASE(){return Q}get AT_TARGET(){return ee}get BUBBLING_PHASE(){return te}get eventPhase(){return l(this).dispatchFlag?2:0}stopPropagation(){l(this).stopPropagationFlag=!0}get cancelBubble(){return l(this).stopPropagationFlag}set cancelBubble(e){e?l(this).stopPropagationFlag=!0:Ve.warn()}stopImmediatePropagation(){let e=l(this);e.stopPropagationFlag=e.stopImmediatePropagationFlag=!0}get bubbles(){return l(this).bubbles}get cancelable(){return l(this).cancelable}get returnValue(){return!l(this).canceledFlag}set returnValue(e){e?qe.warn():ne(l(this))}preventDefault(){ne(l(this))}get defaultPrevented(){return l(this).canceledFlag}get composed(){return l(this).composed}get isTrusted(){return!1}get timeStamp(){return l(this).timeStamp}initEvent(e,n=!1,r=!1){let i=l(this);if(i.dispatchFlag){$e.warn();return}X.set(this,{...i,type:String(e),bubbles:Boolean(n),cancelable:Boolean(r),target:null,currentTarget:null,stopPropagationFlag:!1,stopImmediatePropagationFlag:!1,canceledFlag:!1})}},J=0,Q=1,ee=2,te=3,X=new WeakMap;function l(t,e="this"){let n=X.get(t);return H(n!=null,"'%s' must be an object that Event constructor created, but got another one: %o",e,t),n}function ne(t){if(t.inPassiveListenerFlag){Ye.warn();return}if(!t.cancelable){Ge.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 Ze(t){return m.DOMException?new m.DOMException(t,"InvalidStateError"):(v==null&&(v=class oe extends Error{constructor(n){super(n),Error.captureStackTrace&&Error.captureStackTrace(this,oe)}get code(){return 11}get name(){return"InvalidStateError"}},Object.defineProperties(v.prototype,{code:{enumerable:!0},name:{enumerable:!0}}),ie(v),ie(v.prototype)),new v(t))}var v,re={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 ie(t){let e=Object.keys(re);for(let n=0;n<e.length;++n){let r=e[n],i=re[r];Object.defineProperty(t,r,{get(){return i},configurable:!0,enumerable:!0})}}var w=class extends b{static wrap(e){return new(le(e))(e)}constructor(e){super(e.type,{bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed}),e.cancelBubble&&super.stopPropagation(),e.defaultPrevented&&super.preventDefault(),ue.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,ce(e,i))}}stopPropagation(){super.stopPropagation();let{original:e}=E(this);"stopPropagation"in e&&e.stopPropagation()}get cancelBubble(){return super.cancelBubble}set cancelBubble(e){super.cancelBubble=e;let{original:n}=E(this);"cancelBubble"in n&&(n.cancelBubble=e)}stopImmediatePropagation(){super.stopImmediatePropagation();let{original:e}=E(this);"stopImmediatePropagation"in e&&e.stopImmediatePropagation()}get returnValue(){return super.returnValue}set returnValue(e){super.returnValue=e;let{original:n}=E(this);"returnValue"in n&&(n.returnValue=e)}preventDefault(){super.preventDefault();let{original:e}=E(this);"preventDefault"in e&&e.preventDefault()}get timeStamp(){let{original:e}=E(this);return"timeStamp"in e?e.timeStamp:super.timeStamp}},ue=new WeakMap;function E(t){let e=ue.get(t);return H(e!=null,"'this' is expected an Event object, but got",t),e}var P=new WeakMap;P.set(Object.prototype,w);typeof m!="undefined"&&typeof m.Event!="undefined"&&P.set(m.Event.prototype,w);function le(t){let e=Object.getPrototypeOf(t);if(e==null)return w;let n=P.get(e);return n==null&&(n=Je(le(e),e),P.set(e,n)),n}function Je(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],ce(e,r[i]));return n}function ce(t,e){let n=Object.getOwnPropertyDescriptor(t,e);return{get(){let r=E(this).original,i=r[e];return typeof i=="function"?i.bind(r):i},set(r){let i=E(this).original;i[e]=r},configurable:n.configurable,enumerable:n.enumerable}}function Qe(t,e,n,r,i,a){return{callback:t,flags:(e?1:0)|(n?2:0)|(r?4:0),signal:i,signalListener:a}}function et(t){t.flags|=8}function he(t){return(t.flags&1)===1}function pe(t){return(t.flags&2)===2}function de(t){return(t.flags&4)===4}function tt(t){return(t.flags&8)===8}function nt({callback:t},e,n){try{typeof t=="function"?t.call(e,n):typeof t.handleEvent=="function"&&t.handleEvent(n)}catch(r){We(r)}}function fe({listeners:t},e,n){for(let r=0;r<t.length;++r)if(t[r].callback===e&&he(t[r])===n)return r;return-1}function rt(t,e,n,r,i,a){let o;a&&(o=me.bind(null,t,e,n),a.addEventListener("abort",o));let s=Qe(e,n,r,i,a,o);return t.cow?(t.cow=!1,t.listeners=[...t.listeners,s]):t.listeners.push(s),s}function me(t,e,n){let r=fe(t,e,n);return r!==-1?ge(t,r):!1}function ge(t,e,n=!1){let r=t.listeners[e];return et(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 it(){return Object.create(null)}function st(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 k=class{constructor(){be.set(this,it())}addEventListener(e,n,r){let i=M(this),{callback:a,capture:o,once:s,passive:c,signal:h,type:p}=at(e,n,r);if(a==null||(h==null?void 0:h.aborted))return;let d=st(i,p),y=fe(d,a,o);if(y!==-1){ut(d.listeners[y],c,s,h);return}rt(d,a,o,c,s,h)}removeEventListener(e,n,r){let i=M(this),{callback:a,capture:o,type:s}=ot(e,n,r),c=i[s];a!=null&&c&&me(c,a,o)}dispatchEvent(e){let n=M(this)[String(e.type)];if(n==null)return!0;let r=e instanceof b?e:w.wrap(e),i=l(r,"event");if(i.dispatchFlag)throw Ze("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 c=o[s];if(!tt(c)&&(de(c)&&ge(n,s,!a)&&(s-=1),i.inPassiveListenerFlag=pe(c),nt(c,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}},be=new WeakMap;function M(t,e="this"){let n=be.get(t);return H(n!=null,"'%s' must be an object that EventTarget constructor created, but got another one: %o",e,t),n}function at(t,e,n){var r;return ye(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 ot(t,e,n){return ye(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 ye(t){if(!(typeof t=="function"||typeof t=="object"&&t!==null&&typeof t.handleEvent=="function")){if(t==null||typeof t=="object"){Z.warn(t);return}throw new TypeError(se(Z.message,[t]))}}function ut(t,e,n,r){Ke.warn(he(t)?"capture":"bubble",t.callback),pe(t)!==e&&N.warn("passive"),de(t)!==n&&N.warn("once"),t.signal!==r&&N.warn("signal")}var j=Object.getOwnPropertyNames(k.prototype);for(let t=0;t<j.length;++t)j[t]!=="constructor"&&Object.defineProperty(k.prototype,j[t],{enumerable:!0});typeof m!="undefined"&&typeof m.EventTarget!="undefined"&&Object.setPrototypeOf(k.prototype,m.EventTarget.prototype);var Oe=Xe(Ae()),Ie=30720,B=512e3,x=256,A=(t,{minChunkSize:e=x,maxChunkSize:n=B}={})=>t==null||typeof t=="number"&&t>=256&&t%256===0&&t>=e&&t<=n,O=(t,{minChunkSize:e=x,maxChunkSize:n=B}={})=>new TypeError(`chunkSize ${t} must be a positive number in multiples of 256, between ${e} and ${n}`),I=class{constructor(e,n={}){this.readableStream=e;var r,i,a;if(!A(n.defaultChunkSize,n))throw O(n.defaultChunkSize,n);this.defaultChunkSize=(r=n.defaultChunkSize)!=null?r:Ie,this.minChunkSize=(i=n.minChunkSize)!=null?i:x,this.maxChunkSize=(a=n.maxChunkSize)!=null?a:B}get chunkSize(){var e;return(e=this._chunkSize)!=null?e:this.defaultChunkSize}set chunkSize(e){if(!A(e,this))throw O(e,this);this._chunkSize=e}get chunkByteSize(){return this.chunkSize*1024}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}}}}finally{if(e){let r=e;e=void 0,yield r}n.releaseLock();return}}},St=[200,201,202,204,308],Le=[408,502,503,504],Be=(t,e)=>!!t&&St.includes(t.statusCode),kt=(t,{retryCodes:e=Le})=>!t||e.includes(t.statusCode),vt=(t,e)=>e.attemptCount>=e.attempts||!(Be(t)||kt(t,e)),L=class{constructor(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||Le,this.dynamicChunkSize=e.dynamicChunkSize||!1,this.maxFileBytes=(e.maxFileSize||0)*1024,this.chunkCount=0,this.attemptCount=0,this.offline=!1,this._paused=!1,this.success=!1,this.nextChunkRangeStart=0,this.chunkedStreamIterable=new I(this.file.stream(),{...e,defaultChunkSize:e.chunkSize}),this.chunkedStreamIterator=this.chunkedStreamIterable[Symbol.asyncIterator](),this.totalChunks=Math.ceil(this.file.size/this.chunkByteSize),this.eventTarget=new k,this.validateOptions(),this.getEndpoint().then(()=>this.sendChunks()),typeof window!="undefined"&&(window.addEventListener("online",()=>{!this.offline||(this.offline=!1,this.dispatch("online"),this.sendChunks())}),window.addEventListener("offline",()=>{this.offline=!0,this.dispatch("offline")}))}get maxChunkSize(){var e,n;return(n=(e=this.chunkedStreamIterable)==null?void 0:e.chunkSize)!=null?n:B}get minChunkSize(){var e,n;return(n=(e=this.chunkedStreamIterable)==null?void 0:e.chunkSize)!=null?n:x}get chunkSize(){var e,n;return(n=(e=this.chunkedStreamIterable)==null?void 0:e.chunkSize)!=null?n:Ie}set chunkSize(e){this.chunkedStreamIterable.chunkSize=e}get chunkByteSize(){return this.chunkedStreamIterable.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 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())}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!="object")throw new TypeError("headers must be null or an object");if(!A(this.chunkSize,{maxChunkSize:this.maxChunkSize,minChunkSize:this.minChunkSize}))throw O(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=>(this.endpointValue=e,this.endpointValue))}xhrPromise(e){let n=r=>{r.upload.onprogress=i=>{var p;let a=this.totalChunks-this.chunkCount,o=(this.file.size-this.nextChunkRangeStart)/this.file.size/a,s=this.nextChunkRangeStart/this.file.size,h=i.loaded/((p=i.total)!=null?p:this.chunkByteSize)*o;this.dispatch("progress",Math.min((s+h)*100,100))}};return new Promise((r,i)=>{this.currentXhr=(0,Oe.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,i={...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:i,url:this.endpointValue,method:this.method,body:e})}async sendChunkWithRetries(e){let n=async(s,c)=>{var d;let p=(new Date().getTime()-this.lastChunkStart.getTime())/1e3;if(this.dispatch("chunkSuccess",{chunk:this.chunkCount,chunkSize:this.chunkSize,attempts:this.attemptCount,timeInterval:p,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;p<10?y=Math.min(this.chunkSize*2,this.maxChunkSize):p>30&&(y=Math.max(this.chunkSize/2,this.minChunkSize)),this.chunkSize=Math.ceil(y/256)*256;let f=(this.file.size-this.nextChunkRangeStart)/this.chunkByteSize;this.totalChunks=Math.ceil(this.chunkCount+f)}return!0},r=async(s,c)=>(this.dispatch("error",{message:`Server responded with ${s.statusCode}. Stopping upload.`,chunk:this.chunkCount,attempts:this.attemptCount}),!1),i=async(s,c)=>(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}),new Promise(h=>{setTimeout(async()=>{if(this._paused||this.offline){this.pendingChunk=e,h(!1);return}let p=await this.sendChunkWithRetries(e);h(p)},this.delayBeforeAttempt*1e3)})),a;try{this.attemptCount=this.attemptCount+1,this.lastChunkStart=new Date,a=await this.sendChunk(e)}catch{}let o={retryCodes:this.retryCodes,attemptCount:this.attemptCount,attempts:this.attempts};return Be(a,o)?n(a,e):vt(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.chunkedStreamIterator.next(),r=!e&&n;if(e&&(r=await this.sendChunkWithRetries(e)),this.success=!!n,this.success&&r&&this.dispatch("success"),!r)return}}},wt=t=>new L(t);return He(Rt);})(); | ||
//# sourceMappingURL=upchunk.js.map |
{ | ||
"name": "@mux/upchunk", | ||
"version": "2.6.0", | ||
"version": "3.0.0", | ||
"description": "Dead simple chunked file uploads using Fetch", | ||
@@ -34,6 +34,7 @@ "main": "dist/upchunk.js", | ||
"clean": "rimraf ./dist", | ||
"test": "jest", | ||
"test": "yarn build:test && web-test-runner --config test/web-test-runner.config.mjs", | ||
"lint": "tslint --project .", | ||
"tslint-check": "tslint-config-prettier-check ./tslint.json", | ||
"start": "esbuild src/upchunk.ts --target=es2019 --format=iife --bundle --minify --sourcemap --outdir=./example --global-name=UpChunk --servedir=example", | ||
"build:test": "esbuild ./test/deps/xhr-mock.ts ./test/deps/xhr.ts --target=es2019 --format=esm --bundle --minify --outdir=./test/dist --out-extension:.js=.mjs", | ||
"start": "esbuild src/upchunk.ts --target=es2019 --format=iife --bundle --sourcemap --outdir=./example --global-name=UpChunk --servedir=example", | ||
"build:iife": "esbuild src/upchunk.ts --target=es2019 --format=iife --bundle --minify --sourcemap --outdir=./dist --global-name=UpChunk", | ||
@@ -47,13 +48,14 @@ "build:esm": "esbuild src/upchunk.ts --target=es2019 --format=esm --bundle --minify --sourcemap --outdir=./dist --out-extension:.js=.mjs", | ||
"devDependencies": { | ||
"@types/jest": "^25.2.3", | ||
"@open-wc/testing": "^3.1.6", | ||
"@web/dev-server-esbuild": "^0.3.3", | ||
"@web/dev-server-import-maps": "^0.0.7", | ||
"@web/test-runner": "^0.15.0", | ||
"esbuild": "^0.14.47", | ||
"jest": "^26.6.3", | ||
"nock": "^13.0.5", | ||
"npm-run-all": "^4.1.5", | ||
"rimraf": "^3.0.2", | ||
"ts-jest": "^26.1.0", | ||
"tslint": "^6.1.2", | ||
"tslint-config-airbnb": "^5.11.2", | ||
"tslint-config-prettier": "^1.18.0", | ||
"typescript": "^4.7.4" | ||
"typescript": "^4.7.4", | ||
"xhr-mock": "^2.5.1" | ||
}, | ||
@@ -60,0 +62,0 @@ "dependencies": { |
import { EventTarget, Event } from 'event-target-shim'; | ||
import xhr, { XhrUrlConfig, XhrHeaders, XhrResponse } from 'xhr'; | ||
import xhr, { type XhrUrlConfig, type XhrHeaders, type XhrResponse } from 'xhr'; | ||
const DEFAULT_CHUNK_SIZE = 30720; | ||
const DEFAULT_MAX_CHUNK_SIZE = 512000; // in kB | ||
const DEFAULT_MIN_CHUNK_SIZE = 256; // in kB | ||
// Predicate function that returns true if a given `chunkSize` is valid, otherwise false. | ||
// For `chunkSize` validity, we constrain by a min/max chunk size and conform to GCS: | ||
// "The chunk size should be a multiple of 256 KiB (256 x 1024 bytes), unless it's the last | ||
// chunk that completes the upload." (See: https://cloud.google.com/storage/docs/performing-resumable-uploads) | ||
export const isValidChunkSize = ( | ||
chunkSize: any, | ||
{ | ||
minChunkSize = DEFAULT_MIN_CHUNK_SIZE, | ||
maxChunkSize = DEFAULT_MAX_CHUNK_SIZE, | ||
} = {} | ||
): chunkSize is number | null | undefined => { | ||
return ( | ||
chunkSize == null || | ||
(typeof chunkSize === 'number' && | ||
chunkSize >= 256 && | ||
chunkSize % 256 === 0 && | ||
chunkSize >= minChunkSize && | ||
chunkSize <= maxChunkSize) | ||
); | ||
}; | ||
// Projection function that returns an error associated with invalid `chunkSize` values. | ||
export const getChunkSizeError = ( | ||
chunkSize: any, | ||
{ | ||
minChunkSize = DEFAULT_MIN_CHUNK_SIZE, | ||
maxChunkSize = DEFAULT_MAX_CHUNK_SIZE, | ||
} = {} | ||
) => { | ||
return new TypeError( | ||
`chunkSize ${chunkSize} must be a positive number in multiples of 256, between ${minChunkSize} and ${maxChunkSize}` | ||
); | ||
}; | ||
export type ChunkedStreamIterableOptions = { | ||
defaultChunkSize?: number; | ||
minChunkSize?: number; | ||
maxChunkSize?: number; | ||
}; | ||
// An Iterable that accepts a readableStream of binary data (Blob | Uint8Array) and provides | ||
// an asyncIterator which yields Blob values of the current chunkSize until done. Note that | ||
// chunkSize may change between iterations. | ||
export class ChunkedStreamIterable implements AsyncIterable<Blob> { | ||
protected _chunkSize: number | undefined; | ||
protected defaultChunkSize: number; | ||
public readonly minChunkSize: number; | ||
public readonly maxChunkSize: number; | ||
constructor( | ||
protected readableStream: ReadableStream<Uint8Array | Blob>, | ||
options: ChunkedStreamIterableOptions = {} | ||
) { | ||
if (!isValidChunkSize(options.defaultChunkSize, options)) { | ||
throw getChunkSizeError(options.defaultChunkSize, options); | ||
} | ||
this.defaultChunkSize = options.defaultChunkSize ?? DEFAULT_CHUNK_SIZE; | ||
this.minChunkSize = options.minChunkSize ?? DEFAULT_MIN_CHUNK_SIZE; | ||
this.maxChunkSize = options.maxChunkSize ?? DEFAULT_MAX_CHUNK_SIZE; | ||
} | ||
get chunkSize() { | ||
return this._chunkSize ?? this.defaultChunkSize; | ||
} | ||
set chunkSize(value) { | ||
if (!isValidChunkSize(value, this)) { | ||
throw getChunkSizeError(value, this); | ||
} | ||
this._chunkSize = value; | ||
} | ||
get chunkByteSize() { | ||
return this.chunkSize * 1024; | ||
} | ||
async *[Symbol.asyncIterator](): AsyncIterator<Blob> { | ||
let chunk; | ||
const reader = this.readableStream.getReader(); | ||
try { | ||
while (true) { | ||
const { done, value } = await reader.read(); | ||
if (done) { | ||
// Last chunk, if any bits remain | ||
if (chunk) { | ||
const outgoingChunk = chunk; | ||
chunk = undefined; | ||
yield outgoingChunk; | ||
} | ||
break; | ||
} | ||
const normalizedBlobChunk = | ||
value instanceof Uint8Array | ||
? new Blob([value], { type: 'application/octet-stream' }) | ||
: value; | ||
chunk = chunk | ||
? new Blob([chunk, normalizedBlobChunk]) | ||
: normalizedBlobChunk; | ||
// NOTE: Since we don't know how big the next chunk needs to be, we should | ||
// just have a single blob that we "peel away bytes from" for each chunk | ||
// as we iterate. | ||
while (chunk) { | ||
if (chunk.size === this.chunkByteSize) { | ||
const outgoingChunk = chunk; | ||
chunk = undefined; | ||
yield outgoingChunk; | ||
break; | ||
} else if (chunk.size < this.chunkByteSize) { | ||
break; | ||
} else { | ||
const outgoingChunk = chunk.slice(0, this.chunkByteSize); | ||
chunk = chunk.slice(this.chunkByteSize); | ||
yield outgoingChunk; | ||
} | ||
} | ||
} | ||
} finally { | ||
// Last chunk, if any bits remain | ||
if (chunk) { | ||
const outgoingChunk = chunk; | ||
chunk = undefined; | ||
yield outgoingChunk; | ||
} | ||
reader.releaseLock(); | ||
return; | ||
} | ||
} | ||
} | ||
const SUCCESSFUL_CHUNK_UPLOAD_CODES = [200, 201, 202, 204, 308]; | ||
const TEMPORARY_ERROR_CODES = [408, 502, 503, 504]; // These error codes imply a chunk may be retried | ||
type UploadPredOptions = { | ||
retryCodes?: typeof TEMPORARY_ERROR_CODES; | ||
attempts: number; | ||
attemptCount: number; | ||
}; | ||
const isSuccessfulChunkUpload = ( | ||
res: XhrResponse | undefined, | ||
_options?: any | ||
): res is XhrResponse => | ||
!!res && SUCCESSFUL_CHUNK_UPLOAD_CODES.includes(res.statusCode); | ||
const isRetriableChunkUpload = ( | ||
res: XhrResponse | undefined, | ||
{ retryCodes = TEMPORARY_ERROR_CODES }: UploadPredOptions | ||
) => !res || retryCodes.includes(res.statusCode); | ||
const isFailedChunkUpload = ( | ||
res: XhrResponse | undefined, | ||
options: UploadPredOptions | ||
): res is XhrResponse => { | ||
return ( | ||
options.attemptCount >= options.attempts || | ||
!(isSuccessfulChunkUpload(res) || isRetriableChunkUpload(res, options)) | ||
); | ||
}; | ||
type EventName = | ||
@@ -21,6 +183,3 @@ | 'attempt' | ||
type AllowedMethods = | ||
| 'PUT' | ||
| 'POST' | ||
| 'PATCH'; | ||
type AllowedMethods = 'PUT' | 'POST' | 'PATCH'; | ||
@@ -42,3 +201,3 @@ export interface UpChunkOptions { | ||
export class UpChunk { | ||
export class UpChunk { | ||
public endpoint: string | ((file?: File) => Promise<string>); | ||
@@ -48,3 +207,2 @@ public file: File; | ||
public method: AllowedMethods; | ||
public chunkSize: number; | ||
public attempts: number; | ||
@@ -54,6 +212,7 @@ public delayBeforeAttempt: number; | ||
public dynamicChunkSize: boolean; | ||
protected chunkedStreamIterable: ChunkedStreamIterable; | ||
protected chunkedStreamIterator; | ||
private chunk: Blob; | ||
protected pendingChunk?: Blob; | ||
private chunkCount: number; | ||
private chunkByteSize: number; | ||
private maxFileBytes: number; | ||
@@ -64,3 +223,3 @@ private endpointValue: string; | ||
private offline: boolean; | ||
private paused: boolean; | ||
private _paused: boolean; | ||
private success: boolean; | ||
@@ -70,16 +229,11 @@ private currentXhr?: XMLHttpRequest; | ||
private nextChunkRangeStart: number; | ||
private maxChunkSize: number; | ||
private minChunkSize: number; | ||
private reader: FileReader; | ||
private eventTarget: EventTarget<Record<EventName,UpchunkEvent>>; | ||
private eventTarget: EventTarget<Record<EventName, UpchunkEvent>>; | ||
constructor(options: UpChunkOptions) { | ||
this.endpoint = options.endpoint; | ||
this.file = options.file; | ||
this.headers = options.headers || ({} as XhrHeaders); | ||
this.method = options.method || 'PUT'; | ||
this.chunkSize = options.chunkSize || 30720; | ||
this.attempts = options.attempts || 5; | ||
@@ -92,13 +246,19 @@ this.delayBeforeAttempt = options.delayBeforeAttempt || 1; | ||
this.chunkCount = 0; | ||
this.chunkByteSize = this.chunkSize * 1024; | ||
this.totalChunks = Math.ceil(this.file.size / this.chunkByteSize); | ||
this.attemptCount = 0; | ||
this.offline = false; | ||
this.paused = false; | ||
this._paused = false; | ||
this.success = false; | ||
this.nextChunkRangeStart = 0; | ||
this.maxChunkSize = options.maxChunkSize || 512000; // in kB | ||
this.minChunkSize = options.minChunkSize || 256; // in kB | ||
this.reader = new FileReader(); | ||
// Types appear to be getting confused in env setup, using the overloaded NodeJS Blob definition, which uses NodeJS.ReadableStream instead | ||
// of the DOM type definitions. For definitions, See consumers.d.ts vs. lib.dom.d.ts. (CJP) | ||
this.chunkedStreamIterable = new ChunkedStreamIterable( | ||
this.file.stream() as unknown as ReadableStream<Uint8Array>, | ||
{ ...options, defaultChunkSize: options.chunkSize } | ||
); | ||
this.chunkedStreamIterator = | ||
this.chunkedStreamIterable[Symbol.asyncIterator](); | ||
this.totalChunks = Math.ceil(this.file.size / this.chunkByteSize); | ||
this.eventTarget = new EventTarget(); | ||
@@ -111,3 +271,3 @@ | ||
// trigger events when offline/back online | ||
if (typeof(window) !== 'undefined') { | ||
if (typeof window !== 'undefined') { | ||
window.addEventListener('online', () => { | ||
@@ -130,2 +290,26 @@ if (!this.offline) { | ||
protected get maxChunkSize() { | ||
return this.chunkedStreamIterable?.chunkSize ?? DEFAULT_MAX_CHUNK_SIZE; | ||
} | ||
protected get minChunkSize() { | ||
return this.chunkedStreamIterable?.chunkSize ?? DEFAULT_MIN_CHUNK_SIZE; | ||
} | ||
public get chunkSize() { | ||
return this.chunkedStreamIterable?.chunkSize ?? DEFAULT_CHUNK_SIZE; | ||
} | ||
public set chunkSize(value) { | ||
this.chunkedStreamIterable.chunkSize = value; | ||
} | ||
public get chunkByteSize() { | ||
return this.chunkedStreamIterable.chunkByteSize; | ||
} | ||
public get totalChunkSize() { | ||
return Math.ceil(this.file.size / this.chunkByteSize); | ||
} | ||
/** | ||
@@ -138,2 +322,20 @@ * Subscribe to an event | ||
/** | ||
* Subscribe to an event once | ||
*/ | ||
public once(eventName: EventName, fn: (event: CustomEvent) => void) { | ||
this.eventTarget.addEventListener(eventName, fn as EventListener, { once: true }); | ||
} | ||
/** | ||
* Unsubscribe to an event | ||
*/ | ||
public off(eventName: EventName, fn: (event: CustomEvent) => void) { | ||
this.eventTarget.removeEventListener(eventName, fn as EventListener); | ||
} | ||
public get paused() { | ||
return this._paused; | ||
} | ||
public abort() { | ||
@@ -145,8 +347,8 @@ this.pause(); | ||
public pause() { | ||
this.paused = true; | ||
this._paused = true; | ||
} | ||
public resume() { | ||
if (this.paused) { | ||
this.paused = false; | ||
if (this._paused) { | ||
this._paused = false; | ||
@@ -161,3 +363,5 @@ this.sendChunks(); | ||
private dispatch(eventName: EventName, detail?: any) { | ||
const event: UpchunkEvent = new CustomEvent(eventName, { detail }) as UpchunkEvent; | ||
const event: UpchunkEvent = new CustomEvent(eventName, { | ||
detail, | ||
}) as UpchunkEvent; | ||
@@ -186,12 +390,11 @@ this.eventTarget.dispatchEvent(event); | ||
if ( | ||
this.chunkSize && | ||
(typeof this.chunkSize !== 'number' || | ||
this.chunkSize < 256 || | ||
this.chunkSize % 256 !== 0 || | ||
this.chunkSize < this.minChunkSize || | ||
this.chunkSize > this.maxChunkSize) | ||
!isValidChunkSize(this.chunkSize, { | ||
maxChunkSize: this.maxChunkSize, | ||
minChunkSize: this.minChunkSize, | ||
}) | ||
) { | ||
throw new TypeError( | ||
`chunkSize must be a positive number in multiples of 256, between ${this.minChunkSize} and ${this.maxChunkSize}` | ||
); | ||
throw getChunkSizeError(this.chunkSize, { | ||
maxChunkSize: this.maxChunkSize, | ||
minChunkSize: this.minChunkSize, | ||
}); | ||
} | ||
@@ -257,24 +460,2 @@ if ( | ||
/** | ||
* Get portion of the file of x bytes corresponding to chunkSize | ||
*/ | ||
private getChunk() { | ||
return new Promise<void> ((resolve) => { | ||
// Since we start with 0-chunkSize for the range, we need to subtract 1. | ||
const length = | ||
this.totalChunks === 1 ? this.file.size : this.chunkByteSize; | ||
this.reader.onload = () => { | ||
if (this.reader.result !== null) { | ||
this.chunk = new Blob([this.reader.result], { | ||
type: 'application/octet-stream', | ||
}); | ||
} | ||
resolve(); | ||
}; | ||
this.reader.readAsArrayBuffer(this.file.slice(this.nextChunkRangeStart, this.nextChunkRangeStart + length)); | ||
}); | ||
} | ||
private xhrPromise(options: XhrUrlConfig): Promise<XhrResponse> { | ||
@@ -285,7 +466,14 @@ const beforeSend = (xhrObject: XMLHttpRequest) => { | ||
// const remainingBytes = this.file.size-(this.nextChunkRangeStart+event.loaded); | ||
const percentagePerChunk = (this.file.size-this.nextChunkRangeStart)/this.file.size/remainingChunks; | ||
const successfulPercentage = this.nextChunkRangeStart/this.file.size; | ||
const currentChunkProgress = event.loaded / (event.total ?? this.chunkByteSize); | ||
const percentagePerChunk = | ||
(this.file.size - this.nextChunkRangeStart) / | ||
this.file.size / | ||
remainingChunks; | ||
const successfulPercentage = this.nextChunkRangeStart / this.file.size; | ||
const currentChunkProgress = | ||
event.loaded / (event.total ?? this.chunkByteSize); | ||
const chunkPercentage = currentChunkProgress * percentagePerChunk; | ||
this.dispatch('progress', Math.min((successfulPercentage + chunkPercentage)*100, 100)); | ||
this.dispatch( | ||
'progress', | ||
Math.min((successfulPercentage + chunkPercentage) * 100, 100) | ||
); | ||
}; | ||
@@ -309,5 +497,5 @@ }; | ||
*/ | ||
protected async sendChunk() { | ||
protected async sendChunk(chunk: Blob) { | ||
const rangeStart = this.nextChunkRangeStart; | ||
const rangeEnd = rangeStart + this.chunk.size - 1; | ||
const rangeEnd = rangeStart + chunk.size - 1; | ||
const headers = { | ||
@@ -329,12 +517,66 @@ ...this.headers, | ||
method: this.method, | ||
body: this.chunk, | ||
body: chunk, | ||
}); | ||
} | ||
/** | ||
* Called on net failure. If retry counter !== 0, retry after delayBeforeAttempt | ||
*/ | ||
private manageRetries() { | ||
if (this.attemptCount < this.attempts) { | ||
setTimeout(() => this.sendChunks(), this.delayBeforeAttempt * 1000); | ||
protected async sendChunkWithRetries(chunk: Blob): Promise<boolean> { | ||
// What to do if a chunk was successfully uploaded | ||
const successfulChunkUploadCb = async (res: XhrResponse, _chunk?: Blob) => { | ||
// Side effects | ||
const lastChunkEnd = new Date(); | ||
const lastChunkInterval = | ||
(lastChunkEnd.getTime() - this.lastChunkStart.getTime()) / 1000; | ||
this.dispatch('chunkSuccess', { | ||
chunk: this.chunkCount, | ||
chunkSize: this.chunkSize, | ||
attempts: this.attemptCount, | ||
timeInterval: lastChunkInterval, | ||
response: res, | ||
}); | ||
this.attemptCount = 0; | ||
this.chunkCount = (this.chunkCount ?? 0) + 1; | ||
this.nextChunkRangeStart = this.nextChunkRangeStart + this.chunkByteSize; | ||
if (this.dynamicChunkSize) { | ||
let unevenChunkSize = this.chunkSize; | ||
if (lastChunkInterval < 10) { | ||
unevenChunkSize = Math.min(this.chunkSize * 2, this.maxChunkSize); | ||
} else if (lastChunkInterval > 30) { | ||
unevenChunkSize = Math.max(this.chunkSize / 2, this.minChunkSize); | ||
} | ||
// ensure it's a multiple of 256k | ||
this.chunkSize = Math.ceil(unevenChunkSize / 256) * 256; | ||
// Re-estimate the total number of chunks, by adding the completed | ||
// chunks to the remaining chunks | ||
const remainingChunks = | ||
(this.file.size - this.nextChunkRangeStart) / this.chunkByteSize; | ||
this.totalChunks = Math.ceil(this.chunkCount + remainingChunks); | ||
} | ||
return true; | ||
}; | ||
// What to do if a chunk upload failed, potentially after retries | ||
const failedChunkUploadCb = async (res: XhrResponse, _chunk?: Blob) => { | ||
// Side effects | ||
this.dispatch('error', { | ||
message: `Server responded with ${ | ||
(res as XhrResponse).statusCode | ||
}. Stopping upload.`, | ||
chunk: this.chunkCount, | ||
attempts: this.attemptCount, | ||
}); | ||
return false; | ||
}; | ||
// What to do if a chunk upload failed but is retriable and hasn't exceeded retry | ||
// count | ||
const retriableChunkUploadCb = async ( | ||
_res: XhrResponse | undefined, | ||
_chunk?: Blob | ||
) => { | ||
// Side effects | ||
this.dispatch('attemptFailure', { | ||
@@ -347,10 +589,40 @@ message: `An error occured uploading chunk ${this.chunkCount}. ${ | ||
}); | ||
return; | ||
return new Promise<boolean>((resolve) => { | ||
setTimeout(async () => { | ||
// Handle mid-flight _paused/offline cases here by storing the | ||
// "still retriable but yet to be uploaded chunk" in state. | ||
// See also: `sendChunks()` | ||
if (this._paused || this.offline) { | ||
this.pendingChunk = chunk; | ||
resolve(false); | ||
return; | ||
} | ||
const chunkUploadSuccess = await this.sendChunkWithRetries(chunk); | ||
resolve(chunkUploadSuccess); | ||
}, this.delayBeforeAttempt * 1000); | ||
}); | ||
}; | ||
let res: XhrResponse | undefined; | ||
try { | ||
this.attemptCount = this.attemptCount + 1; | ||
this.lastChunkStart = new Date(); | ||
res = await this.sendChunk(chunk); | ||
} catch (_err) { | ||
// this type of error can happen after network disconnection on CORS setup | ||
} | ||
this.dispatch('error', { | ||
message: `An error occured uploading chunk ${this.chunkCount}. No more retries, stopping upload`, | ||
chunk: this.chunkCount, | ||
attempts: this.attemptCount, | ||
}); | ||
const options = { | ||
retryCodes: this.retryCodes, | ||
attemptCount: this.attemptCount, | ||
attempts: this.attempts, | ||
}; | ||
if (isSuccessfulChunkUpload(res, options)) { | ||
return successfulChunkUploadCb(res, chunk); | ||
} | ||
if (isFailedChunkUpload(res, options)) { | ||
return failedChunkUploadCb(res, chunk); | ||
} | ||
// Retriable case | ||
return retriableChunkUploadCb(res, chunk); | ||
} | ||
@@ -362,83 +634,33 @@ | ||
*/ | ||
private sendChunks() { | ||
if (this.paused || this.offline || this.success) { | ||
return; | ||
private async sendChunks() { | ||
// A "pending chunk" is a chunk that was unsuccessful but still retriable when | ||
// uploading was _paused or the env is offline. Since this may be the last | ||
if (this.pendingChunk && !(this._paused || this.offline)) { | ||
const chunk = this.pendingChunk; | ||
this.pendingChunk = undefined; | ||
const chunkUploadSuccess = await this.sendChunkWithRetries(chunk); | ||
if (this.success && chunkUploadSuccess) { | ||
this.dispatch('success'); | ||
} | ||
} | ||
this.getChunk() | ||
.then(() => { | ||
this.attemptCount = this.attemptCount + 1; | ||
this.lastChunkStart = new Date(); | ||
return this.sendChunk() | ||
}) | ||
.then((res) => { | ||
if (SUCCESSFUL_CHUNK_UPLOAD_CODES.includes(res.statusCode)) { | ||
const lastChunkEnd = new Date(); | ||
const lastChunkInterval = (lastChunkEnd.getTime() - this.lastChunkStart.getTime()) / 1000; | ||
this.dispatch('chunkSuccess', { | ||
chunk: this.chunkCount, | ||
chunkSize: this.chunkSize, | ||
attempts: this.attemptCount, | ||
timeInterval: lastChunkInterval, | ||
response: res, | ||
}); | ||
this.attemptCount = 0; | ||
this.chunkCount = this.chunkCount + 1; | ||
this.nextChunkRangeStart = this.nextChunkRangeStart + this.chunkByteSize; | ||
if (this.chunkCount < this.totalChunks) { | ||
// dynamic chunk sizing | ||
if (this.dynamicChunkSize) { | ||
if (lastChunkInterval < 10) | ||
{ | ||
this.chunkSize = Math.min(this.chunkSize * 2,this.maxChunkSize); | ||
} else if (lastChunkInterval > 30) { | ||
this.chunkSize = Math.max(this.chunkSize / 2,this.minChunkSize); | ||
} | ||
// ensure it's a multiple of 256k | ||
this.chunkSize = Math.ceil(this.chunkSize / 256) * 256; | ||
// Now update the new chunkByteSize to the newly calculated chunk size | ||
this.chunkByteSize = this.chunkSize * 1024; | ||
// Re-estimate the total number of chunks, by adding the completed | ||
// chunks to the remaining chunks | ||
const remainingChunks = (this.file.size-this.nextChunkRangeStart)/this.chunkByteSize; | ||
this.totalChunks = Math.ceil(this.chunkCount + remainingChunks); | ||
} | ||
this.sendChunks(); | ||
} else { | ||
this.success = true; | ||
this.dispatch('success'); | ||
} | ||
} else if (this.retryCodes.includes(res.statusCode)) { | ||
if (this.paused || this.offline) { | ||
return; | ||
} | ||
// console.warn('DEBUG: Caught a temporary error: %j',res); | ||
this.manageRetries(); | ||
} else { | ||
if (this.paused || this.offline) { | ||
return; | ||
} | ||
this.dispatch('error', { | ||
message: `Server responded with ${res.statusCode}. Stopping upload.`, | ||
chunkNumber: this.chunkCount, | ||
attempts: this.attemptCount, | ||
}); | ||
} | ||
}) | ||
.catch((err) => { | ||
if (this.paused || this.offline) { | ||
return; | ||
} | ||
// console.warn('DEBUG: Caught an error: %j',err); | ||
// this type of error can happen after network disconnection on CORS setup | ||
this.manageRetries(); | ||
}); | ||
while (!(this.success || this._paused || this.offline)) { | ||
const { value: chunk, done } = await this.chunkedStreamIterator.next(); | ||
// NOTE: When `done`, `chunk` is undefined, so default `chunkUploadSuccess` | ||
// to be `true` on this condition, otherwise `false`. | ||
let chunkUploadSuccess = !chunk && done; | ||
if (chunk) { | ||
chunkUploadSuccess = await this.sendChunkWithRetries(chunk); | ||
} | ||
// NOTE: Need to disambiguate "last chunk to upload" (done) vs. "successfully" | ||
// uploaded last chunk to upload" (depends on status of sendChunkWithRetries), | ||
// specifically for "pending chunk" cases for the last chunk. | ||
this.success = !!done; | ||
if (this.success && chunkUploadSuccess) { | ||
this.dispatch('success'); | ||
} | ||
if (!chunkUploadSuccess) { | ||
return; | ||
} | ||
} | ||
} | ||
@@ -445,0 +667,0 @@ } |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
451290
12
12
964
1