firebase
Version:
Firebase JavaScript library for web and Node.js
3 lines (2 loc) • 38.2 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(Ke,Je){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o,t,r,s,n=e(Ke);function i(t){const r=[];let s=0;for(let n=0;n<t.length;n++){let e=t.charCodeAt(n);e<128?r[s++]=e:(e<2048?r[s++]=e>>6|192:(55296==(64512&e)&&n+1<t.length&&56320==(64512&t.charCodeAt(n+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++n)),r[s++]=e>>18|240,r[s++]=e>>12&63|128):r[s++]=e>>12|224,r[s++]=e>>6&63|128),r[s++]=63&e|128)}return r}function a(e){return l(e).replace(/\./g,"")}const h={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var s=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const n=[];for(let u=0;u<r.length;u+=3){var i=r[u],o=u+1<r.length,a=o?r[u+1]:0,h=u+2<r.length,l=h?r[u+2]:0;let e=(15&a)<<2|l>>6,t=63&l;h||(t=64,o||(e=64)),n.push(s[i>>2],s[(3&i)<<4|a>>4],s[e],s[t])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(i(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,s=0;for(;r<e.length;){var n,i,o=e[r++];o<128?t[s++]=String.fromCharCode(o):191<o&&o<224?(n=e[r++],t[s++]=String.fromCharCode((31&o)<<6|63&n)):239<o&&o<365?(i=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t[s++]=String.fromCharCode(55296+(i>>10)),t[s++]=String.fromCharCode(56320+(1023&i))):(n=e[r++],i=e[r++],t[s++]=String.fromCharCode((15&o)<<12|(63&n)<<6|63&i))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_;const s=[];for(let h=0;h<e.length;){var n=r[e.charAt(h++)],i=h<e.length?r[e.charAt(h)]:0;++h;var o=h<e.length?r[e.charAt(h)]:64;++h;var a=h<e.length?r[e.charAt(h)]:64;if(++h,null==n||null==i||null==o||null==a)throw Error();s.push(n<<2|i>>4),64!==o&&(s.push(i<<4&240|o>>2),64!==a&&s.push(o<<6&192|a))}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},l=function(e){var t=i(e);return h.encodeByteArray(t,!0)};class u extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,u.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,c.prototype.create)}}class c{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var s,r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],i=i?(s=r,i.replace(d,(e,t)=>{var r=s[t];return null!=r?String(r):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${n}).`;return new u(n,i,r)}}const d=/\{\$([^}]+)}/g;function _(e){return e&&e._delegate?e._delegate:e}class p{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const f="firebasestorage.googleapis.com",g="storageBucket";class m extends u{constructor(e,t){super(b(e),`Firebase Storage: ${t} (${b(e)})`),this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,m.prototype)}_codeEquals(e){return b(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function b(e){return"storage/"+e}function v(){return new m("unknown","An unknown error occurred, please check the error payload for server response.")}function w(){return new m("canceled","User canceled the upload/download.")}function y(){return new m("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function T(e){return new m("invalid-argument",e)}function R(){return new m("app-deleted","The Firebase app was deleted.")}function k(e){return new m("invalid-root-operation","The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function S(e,t){return new m("invalid-format","String does not match format '"+e+"': "+t)}function C(e){throw new m("internal-error","Internal error: "+e)}class E{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let r;try{r=E.makeFromUrl(t,e)}catch(e){return new E(t,"")}if(""===r.path)return r;throw t=t,new m("invalid-default-bucket","Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let r=null;var s="([A-Za-z0-9.\\-_]+)";var n=new RegExp("^gs://"+s+"(/(.*))?$","i");function i(e){e.path_=decodeURIComponent(e.path)}var o=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${o}/v[A-Za-z0-9_]+/b/${s}/o(/([^?#]*).*)?$`,"i"),o=t===f?"(?:storage.googleapis.com|storage.cloud.google.com)":t,h=[{regex:n,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:i},{regex:new RegExp(`^https?://${o}/${s}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:i}];for(let c=0;c<h.length;c++){const d=h[c];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",r=new E(u,e),d.postModify(r);break}}if(null==r)throw t=e,new m("invalid-url","Invalid URL '"+t+"'.");return r}}class x{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function A(e){return"string"==typeof e||e instanceof String}function U(e){return O()&&e instanceof Blob}function O(){return"undefined"!=typeof Blob}function P(e,t,r,s){if(s<t)throw T(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r<s)throw T(`Invalid value for '${e}'. Expected ${r} or less.`)}function I(e,t,r){let s=null==r?`https://${t}`:t;return`${r}://${s}/v0${e}`}function M(e){const t=encodeURIComponent;let r="?";for(const n in e){var s;e.hasOwnProperty(n)&&(s=t(n)+"="+t(e[n]),r=r+s+"&")}return r=r.slice(0,-1),r}(t=o=o||{})[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT";class B{constructor(e,t,r,s,n,i,o,a,h,l,u){this.url_=e,this.method_=t,this.headers_=r,this.body_=s,this.successCodes_=n,this.additionalRetryCodes_=i,this.callback_=o,this.errorCallback_=a,this.timeout_=h,this.progressCallback_=l,this.connectionFactory_=u,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(s,e)=>{if(e)s(!1,new N(!1,null,!0));else{const n=this.connectionFactory_();this.pendingConnection_=n;const i=e=>{var t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)};null!==this.progressCallback_&&n.addUploadProgressListener(i),n.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&n.removeUploadProgressListener(i),this.pendingConnection_=null;var e,t=n.getErrorCode()===o.NO_ERROR,r=n.getStatus();t&&!this.isRetryStatusCode_(r)?(e=-1!==this.successCodes_.indexOf(r),s(!0,new N(e,n))):(e=n.getErrorCode()===o.ABORT,s(!1,new N(!1,null,e)))})}},t=(e,t)=>{const r=this.resolve_,s=this.reject_,n=t.connection;if(t.wasSuccessCode)try{var i=this.callback_(n,n.getResponse());void 0!==i?r(i):r()}catch(e){s(e)}else if(null!==n){const a=v();a.serverResponse=n.getErrorText(),this.errorCallback_?s(this.errorCallback_(n,a)):s(a)}else{var o;t.canceled?(o=(this.appDelete_?R:w)(),s(o)):(o=new m("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),s(o))}};this.canceled_?t(0,new N(!1,null,!0)):this.backoffId_=function(t,r,e){let s=1,n=null,i=null,o=!1,a=0;function h(){return 2===a}let l=!1;function u(...e){l||(l=!0,r.apply(null,e))}function c(e){n=setTimeout(()=>{n=null,t(_,h())},e)}function d(){i&&clearTimeout(i)}function _(t,...r){if(l)d();else{if(t)return d(),void u.call(null,t,...r);if(h()||o)return d(),void u.call(null,t,...r);s<64&&(s*=2);let e;e=1===a?(a=2,0):1e3*(s+Math.random()),c(e)}}let p=!1;function f(e){p||(p=!0,d(),l||(null!==n?(e||(a=2),clearTimeout(n),c(0)):e||(a=1)))}return c(0),i=setTimeout(()=>{f(o=!0)},e),f}(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}isRetryStatusCode_(e){var t=500<=e&&e<600,r=-1!==[408,429].indexOf(e),s=-1!==this.additionalRetryCodes_.indexOf(e);return t||r||s}}class N{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function D(...t){const r="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==r){const s=new r;for(let e=0;e<t.length;e++)s.append(t[e]);return s.getBlob()}if(O())return new Blob(t);throw new m("unsupported-environment","This browser doesn't seem to support creating Blobs")}const L={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class q{constructor(e,t){this.data=e,this.contentType=t||null}}function F(e,t){switch(e){case L.RAW:return new q(j(t));case L.BASE64:case L.BASE64URL:return new q(z(e,t));case L.DATA_URL:return new q((r=t,(s=new H(r)).base64?z(L.BASE64,s.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw S(L.DATA_URL,"Malformed data URL.")}return j(t)}(s.rest)),(r=t,new H(r).contentType))}var r,s;throw v()}function j(t){const r=[];for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);var s,n;e<=127?r.push(e):e<=2047?r.push(192|e>>6,128|63&e):55296==(64512&e)?i<t.length-1&&56320==(64512&t.charCodeAt(i+1))?(s=e,n=t.charCodeAt(++i),e=65536|(1023&s)<<10|1023&n,r.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):r.push(239,191,189):56320==(64512&e)?r.push(239,191,189):r.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(r)}function z(t,e){switch(t){case L.BASE64:var r=-1!==e.indexOf("-"),s=-1!==e.indexOf("_");if(r||s)throw S(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break;case L.BASE64URL:s=-1!==e.indexOf("+"),r=-1!==e.indexOf("/");if(s||r)throw S(t,"Invalid character '"+(s?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let n;try{n=atob(e)}catch(e){throw S(t,"Invalid character found")}const i=new Uint8Array(n.length);for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);return i}class H{constructor(e){this.base64=!1,this.contentType=null;var t,r,s=e.match(/^data:([^,]+)?,/);if(null===s)throw S(L.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const n=s[1]||null;null!=n&&(this.base64=(t=n,r=";base64",t.length>=r.length&&t.substring(t.length-r.length)===r),this.contentType=this.base64?n.substring(0,n.length-";base64".length):n),this.rest=e.substring(e.indexOf(",")+1)}}class ${constructor(e,t){let r=0,s="";U(e)?(this.data_=e,r=e.size,s=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=s}size(){return this.size_}type(){return this.type_}slice(e,t){if(U(this.data_)){var r=this.data_,r=(n=e,i=t,(s=r).webkitSlice?s.webkitSlice(n,i):s.mozSlice?s.mozSlice(n,i):s.slice?s.slice(n,i):null);return null===r?null:new $(r)}var s,n,i,r=new Uint8Array(this.data_.buffer,e,t-e);return new $(r,!0)}static getBlob(...e){if(O()){var t=e.map(e=>e instanceof $?e.data_:e);return new $(D.apply(null,t))}{const s=e.map(e=>A(e)?F(L.RAW,e).data:e.data_);let t=0;s.forEach(e=>{t+=e.byteLength});const n=new Uint8Array(t);let r=0;return s.forEach(e=>{for(let t=0;t<e.length;t++)n[r++]=e[t]}),new $(n,!0)}}uploadData(){return this.data_}}function W(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function V(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function G(e,t){return t}class X{constructor(e,t,r,s){this.server=e,this.local=t||e,this.writable=!!r,this.xform=s||G}}let K=null;function J(){if(K)return K;const e=[];e.push(new X("bucket")),e.push(new X("generation")),e.push(new X("metageneration")),e.push(new X("name","fullPath",!0));const t=new X("name");t.xform=function(e,t){return!A(t=t)||t.length<2?t:V(t)},e.push(t);const r=new X("size");return r.xform=function(e,t){return void 0!==t?Number(t):t},e.push(r),e.push(new X("timeCreated")),e.push(new X("updated")),e.push(new X("md5Hash",null,!0)),e.push(new X("cacheControl",null,!0)),e.push(new X("contentDisposition",null,!0)),e.push(new X("contentEncoding",null,!0)),e.push(new X("contentLanguage",null,!0)),e.push(new X("contentType",null,!0)),e.push(new X("metadata","customMetadata",!0)),K=e,K}function Z(r,s){Object.defineProperty(r,"ref",{get:function(){var e=r.bucket,t=r.fullPath,t=new E(e,t);return s._makeStorageReference(t)}})}function Y(e,t,r){var s=W(t);return null===s?null:function(e,t,r){const s={type:"file"};var n=r.length;for(let i=0;i<n;i++){const o=r[i];s[o.local]=o.xform(s,t[o.server])}return Z(s,e),s}(e,s,r)}function Q(e,t){const r={};var s=t.length;for(let i=0;i<s;i++){var n=t[i];n.writable&&(r[n.server]=e[n.local])}return JSON.stringify(r)}const ee="prefixes";function te(e,t,r){var s=W(r);return null===s?null:function(e,t,r){const s={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r[ee])for(const o of r[ee]){var n=o.replace(/\/$/,""),n=e._makeStorageReference(new E(t,n));s.prefixes.push(n)}if(r.items)for(const a of r.items){var i=e._makeStorageReference(new E(t,a.name));s.items.push(i)}return s}(e,t,s)}class re{constructor(e,t,r,s){this.url=e,this.method=t,this.handler=r,this.timeout=s,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function se(e){if(!e)throw v()}function ne(s,n){return function(e,t){var r=Y(s,t,n);return se(null!==r),r}}function ie(s,n){return function(e,t){var r=te(s,n,t);return se(null!==r),r}}function oe(s,n){return function(e,t){var r=Y(s,t,n);return se(null!==r),function(s,e,n,i){var t=W(e);if(null===t)return null;if(!A(t.downloadTokens))return null;const r=t.downloadTokens;if(0===r.length)return null;const o=encodeURIComponent,a=r.split(",");return a.map(e=>{var t=s.bucket,r=s.fullPath;return I("/b/"+o(t)+"/o/"+o(r),n,i)+M({alt:"media",token:e})})[0]}(r,t,s.host,s._protocol)}}function ae(n){return function(e,t){let r;var s;return r=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new m("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new m("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(s=n.bucket,new m("quota-exceeded","Quota for bucket '"+s+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(e=n.path,new m("unauthorized","User does not have permission to access '"+e+"'.")):t,r.serverResponse=t.serverResponse,r}}function he(s){const n=ae(s);return function(e,t){let r=n(e,t);return 404===e.getStatus()&&(r=(e=s.path,new m("object-not-found","Object '"+e+"' does not exist."))),r.serverResponse=t.serverResponse,r}}function le(e,t,r){var s=I(t.fullServerUrl(),e.host,e._protocol),n=e.maxOperationRetryTime;const i=new re(s,"GET",ne(e,r),n);return i.errorHandler=he(t),i}function ue(e,t,r){const s=Object.assign({},r);return s.fullPath=e.path,s.size=t.size(),s.contentType||(s.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),s}function ce(e,t,r,s,n){var i=t.bucketOnlyServerUrl();const o={"X-Goog-Upload-Protocol":"multipart"};var a=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();o["Content-Type"]="multipart/related; boundary="+a;var h=ue(t,s,n),l="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+Q(h,r)+"\r\n--"+a+"\r\nContent-Type: "+h.contentType+"\r\n\r\n",a="\r\n--"+a+"--";const u=$.getBlob(l,s,a);if(null===u)throw y();a={name:h.fullPath},h=I(i,e.host,e._protocol),i=e.maxUploadRetryTime;const c=new re(h,"POST",ne(e,r),i);return c.urlParams=a,c.headers=o,c.body=u.uploadData(),c.errorHandler=ae(t),c}class de{constructor(e,t,r,s){this.current=e,this.total=t,this.finalized=!!r,this.metadata=s||null}}function _e(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){se(!1)}const s=t||["active"];return se(!!r&&-1!==s.indexOf(r)),r}function pe(e,t,r,s,n){var i=t.bucketOnlyServerUrl(),o=ue(t,s,n),a={name:o.fullPath},h=I(i,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${s.size()}`,"X-Goog-Upload-Header-Content-Type":o.contentType,"Content-Type":"application/json; charset=utf-8"},i=Q(o,r),o=e.maxUploadRetryTime;const u=new re(h,"POST",function(e){_e(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){se(!1)}return se(A(t)),t},o);return u.urlParams=a,u.headers=l,u.body=i,u.errorHandler=ae(t),u}function fe(e,t,r,n){var s=e.maxUploadRetryTime;const i=new re(r,"POST",function(e){var t=_e(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){se(!1)}r||se(!1);var s=Number(r);return se(!isNaN(s)),new de(s,n.size(),"final"===t)},s);return i.headers={"X-Goog-Upload-Command":"query"},i.errorHandler=ae(t),i}function ge(e,o,t,a,r,h,s,n){const l=new de(0,0);if(s?(l.current=s.current,l.total=s.total):(l.current=0,l.total=a.size()),a.size()!==l.total)throw new m("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var i=l.total-l.current;let u=i;0<r&&(u=Math.min(u,r));var c=l.current,d=c+u,i={"X-Goog-Upload-Command":u===i?"upload, finalize":"upload","X-Goog-Upload-Offset":`${l.current}`};const _=a.slice(c,d);if(null===_)throw y();d=o.maxUploadRetryTime;const p=new re(t,"POST",function(e,t){var r=_e(e,["active","final"]),s=l.current+u,n=a.size();let i;return i="final"===r?ne(o,h)(e,t):null,new de(s,n,"final"===r,i)},d);return p.headers=i,p.body=_.uploadData(),p.progressCallback=n||null,p.errorHandler=ae(e),p}const me={STATE_CHANGED:"state_changed"},be={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function ve(e){switch(e){case"running":case"pausing":case"canceling":return be.RUNNING;case"paused":return be.PAUSED;case"success":return be.SUCCESS;case"canceled":return be.CANCELED;default:return be.ERROR}}class we{constructor(e,t,r){var s;"function"==typeof e||null!=t||null!=r?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=r?r:void 0):(this.next=(s=e).next,this.error=s.error,this.complete=s.complete)}}function ye(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class Te extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=o.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=o.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=o.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,r,s){if(this.sent_)throw C("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==s)for(const n in s)s.hasOwnProperty(n)&&this.xhr_.setRequestHeader(n,s[n].toString());return void 0!==r?this.xhr_.send(r):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw C("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw C("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw C("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw C("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function Re(){return new Te}class ke{constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=J(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{this._request=void 0,this._chunkMultiplier=1,e._codeEquals("canceled")?(this._needToFetchStatus=!0,this.completeTransitions_()):(this._error=e,this._transition("error"))},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals("canceled")?this.completeTransitions_():(this._error=e,this._transition("error"))},this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){const t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this._continueUpload():this._oneShotUpload())}_resolveToken(r){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":r(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var r=pe(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const s=this._ref.storage._makeRequest(r,Re,e,t);this._request=s,s.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const n=this._uploadUrl;this._resolveToken((e,t)=>{var r=fe(this._ref.storage,this._ref._location,n,this._blob);const s=this._ref.storage._makeRequest(r,Re,e,t);this._request=s,s.getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const n=262144*this._chunkMultiplier,i=new de(this._transferred,this._blob.size()),o=this._uploadUrl;this._resolveToken((e,t)=>{let r;try{r=ge(this._ref._location,this._ref.storage,o,this._blob,n,this._mappings,i,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const s=this._ref.storage._makeRequest(r,Re,e,t);this._request=s,s.getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){262144*this._chunkMultiplier<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var r=le(this._ref.storage,this._ref._location,this._mappings);const s=this._ref.storage._makeRequest(r,Re,e,t);this._request=s,s.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var r=ce(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const s=this._ref.storage._makeRequest(r,Re,e,t);this._request=s,s.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request&&this._request.cancel();break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=w(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=ve(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,s){const n=new we(t||void 0,r||void 0,s||void 0);return this._addObserver(n),()=>{this._removeObserver(n)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(ve(this._state)){case be.SUCCESS:ye(this._resolve.bind(null,this.snapshot))();break;case be.CANCELED:case be.ERROR:const t=this._reject;ye(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(ve(this._state)){case be.RUNNING:case be.PAUSED:e.next&&ye(e.next.bind(e,this.snapshot))();break;case be.SUCCESS:e.complete&&ye(e.complete.bind(e))();break;case be.CANCELED:case be.ERROR:default:e.error&&ye(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class Se{constructor(e,t){this._service=e,t instanceof E?this._location=t:this._location=E.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Se(e,t)}get root(){var e=new E(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return V(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new E(this._location.bucket,e);return new Se(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw k(e)}}function Ce(e){const t={prefixes:[],items:[]};return async function e(t,r,s){const n={pageToken:s};const i=await Ee(t,n);r.prefixes.push(...i.prefixes);r.items.push(...i.items);null!=i.nextPageToken&&await e(t,r,i.nextPageToken)}(e,t).then(()=>t)}function Ee(e,t){null!=t&&"number"==typeof t.maxResults&&P("options.maxResults",1,1e3,t.maxResults);var r=t||{},r=function(e,t,r,s,n){const i={};t.isRoot?i.prefix="":i.prefix=t.path+"/",r&&0<r.length&&(i.delimiter=r),s&&(i.pageToken=s),n&&(i.maxResults=n);var o=I(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime;const h=new re(o,"GET",ie(e,t.bucket),a);return h.urlParams=i,h.errorHandler=ae(t),h}(e.storage,e._location,"/",r.pageToken,r.maxResults);return e.storage.makeRequestWithTokens(r,Re)}function xe(e,t){e._throwIfRoot("updateMetadata");var r=function(e,t,r,s){var n=I(t.fullServerUrl(),e.host,e._protocol),i=Q(r,s),o=e.maxOperationRetryTime;const a=new re(n,"PATCH",ne(e,s),o);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=i,a.errorHandler=he(t),a}(e.storage,e._location,t,J());return e.storage.makeRequestWithTokens(r,Re)}function Ae(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,r){var s=I(t.fullServerUrl(),e.host,e._protocol),n=e.maxOperationRetryTime;const i=new re(s,"GET",oe(e,r),n);return i.errorHandler=he(t),i}(e.storage,e._location,J());return e.storage.makeRequestWithTokens(t,Re).then(e=>{if(null===e)throw new m("no-download-url","The given file does not have any download URLs.");return e})}function Ue(e){e._throwIfRoot("deleteObject");var t=function(e,t){var r=I(t.fullServerUrl(),e.host,e._protocol),s=e.maxOperationRetryTime;const n=new re(r,"DELETE",function(e,t){},s);return n.successCodes=[200,204],n.errorHandler=he(t),n}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,Re)}function Oe(e,t){var r,s=(r=e._location.path,s=t.split("/").filter(e=>0<e.length).join("/"),0===r.length?s:r+"/"+s),s=new E(e._location.bucket,s);return new Se(e.storage,s)}function Pe(e,t){if(e instanceof Ne){var r=e;if(null==r._bucket)throw new m("no-default-bucket","No default bucket found. Did you set the '"+g+"' property when initializing the app?");r=new Se(r,r._bucket);return null!=t?Pe(r,t):r}return void 0!==t?Oe(e,t):e}function Ie(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof Ne)return r=e,s=t,new Se(r,s);throw T("To use ref(service, url), the first argument must be a Storage instance.")}return Pe(e,t);var r,s}function Me(e,t){var r=null==t?void 0:t[g];return null==r?null:E.makeFromBucketSpec(r,e)}function Be(e,t,r,s={}){e.host=`${t}:${r}`,e._protocol="http";var n=s["mockUserToken"];n&&(e._overrideAuthToken="string"==typeof n?n:function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var r=t||"demo-project",s=e.iat||0,n=e.sub||e.user_id;if(!n)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return n=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:s,exp:s+3600,auth_time:s,sub:n,user_id:n,firebase:{sign_in_provider:"custom",identities:{}}},e),[a(JSON.stringify({alg:"none",type:"JWT"})),a(JSON.stringify(n)),""].join(".")}(n,e.app.options.projectId))}class Ne{constructor(e,t,r,s,n){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=s,this._firebaseVersion=n,this._bucket=null,this._host=f,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=s?E.makeFromBucketSpec(s,this._host):Me(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=E.makeFromBucketSpec(this._url,e):this._bucket=Me(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){P("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){P("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Se(this,e)}_makeRequest(e,t,r,s){if(this._deleted)return new x(R());{const l=(n=e,i=this._appId,o=r,e=s,r=t,s=this._firebaseVersion,a=M(n.urlParams),h=n.url+a,a=Object.assign({},n.headers),t=a,(i=i)&&(t["X-Firebase-GMPID"]=i),i=a,null!==(o=o)&&0<o.length&&(i.Authorization="Firebase "+o),s=s,a["X-Firebase-Storage-Version"]="webjs/"+(null!=s?s:"AppManager"),s=a,null!==(e=e)&&(s["X-Firebase-AppCheck"]=e),new B(h,n.method,a,n.body,n.successCodes,n.additionalRetryCodes,n.handler,n.errorHandler,n.timeout,n.progressCallback,r));return this._requests.add(l),l.getPromise().then(()=>this._requests.delete(l),()=>this._requests.delete(l)),l}var n,i,o,a,h}async makeRequestWithTokens(e,t){var[r,s]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,s).getPromise()}}const De="@firebase/storage";function Le(e,t,r){return e=_(e),t=t,r=r,(e=e)._throwIfRoot("uploadBytesResumable"),new ke(e,new $(t),r)}function qe(e){return function(e){e._throwIfRoot("getMetadata");var t=le(e.storage,e._location,J());return e.storage.makeRequestWithTokens(t,Re)}(e=_(e))}function Fe(e,t){return Ie(e=_(e),t)}function je(e,{instanceIdentifier:t}){var r=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),n=e.getProvider("app-check-internal");return new Ne(r,s,n,t,Je.SDK_VERSION)}Je._registerComponent(new p("storage",je,"PUBLIC").setMultipleInstances(!0)),Je.registerVersion(De,"0.9.5",""),Je.registerVersion(De,"0.9.5","esm2017");class ze{constructor(e,t,r){this._delegate=e,this.task=t,this.ref=r}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class He{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new ze(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new ze(e,this,this._ref))},e)}on(e,t,r,s){let n=void 0;return t&&(n="function"==typeof t?e=>t(new ze(e,this,this._ref)):{next:t.next?e=>t.next(new ze(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,n,r||void 0,s||void 0)}}class $e{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new We(e,this._service))}get items(){return this._delegate.items.map(e=>new We(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class We{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=Oe(this._delegate,e);return new We(t,this.storage)}get root(){return new We(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new We(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new He(Le(this._delegate,e,t),this)}putString(e,t=L.RAW,r){this._throwIfRoot("putString");var s=F(t,e);const n=Object.assign({},r);return null==n.contentType&&null!=s.contentType&&(n.contentType=s.contentType),new He(new ke(this._delegate,new $(s.data,!0),n),this)}listAll(){return Ce(_(this._delegate)).then(e=>new $e(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,Ee(t=_(t),e).then(e=>new $e(e,this.storage));var t}getMetadata(){return qe(this._delegate)}updateMetadata(e){return xe(_(this._delegate),e)}getDownloadURL(){return Ae(_(this._delegate))}delete(){return this._throwIfRoot("delete"),Ue(_(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw k(e)}}class Ve{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(Ge(e))throw T("ref() expected a child path but got a URL, use refFromURL instead.");return new We(Fe(this._delegate,e),this)}refFromURL(e){if(!Ge(e))throw T("refFromURL() expected a full URL but got a child path, use ref() instead.");try{E.makeFromUrl(e,this._delegate.host)}catch(e){throw T("refFromUrl() expected a valid full URL but got an invalid one.")}return new We(Fe(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,r={}){var s;[s,e,t,r={}]=[this._delegate,e,t,r],Be(s,e,t,r)}}function Ge(e){return/^[A-Za-z]+:\/\//.test(e)}function Xe(e,{instanceIdentifier:t}){var r=e.getProvider("app-compat").getImmediate(),s=e.getProvider("storage").getImmediate({identifier:t});return new Ve(r,s)}r=n.default,s={TaskState:be,TaskEvent:me,StringFormat:L,Storage:Ve,Reference:We},r.INTERNAL.registerComponent(new p("storage-compat",Xe,"PUBLIC").setServiceProps(s).setMultipleInstances(!0)),r.registerVersion("@firebase/storage-compat","0.1.13")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-storage-compat.js - be sure to load firebase-app.js first.")}});
//# sourceMappingURL=firebase-storage-compat.js.map