index.browser.cjs.js 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var app = require('@firebase/app');
  4. var tslib = require('tslib');
  5. var util = require('@firebase/util');
  6. var component = require('@firebase/component');
  7. /**
  8. * @license
  9. * Copyright 2017 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /**
  24. * @fileoverview Constants used in the Firebase Storage library.
  25. */
  26. /**
  27. * Domain name for firebase storage.
  28. */
  29. var DEFAULT_HOST = 'firebasestorage.googleapis.com';
  30. /**
  31. * The key in Firebase config json for the storage bucket.
  32. */
  33. var CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';
  34. /**
  35. * 2 minutes
  36. *
  37. * The timeout for all operations except upload.
  38. */
  39. var DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;
  40. /**
  41. * 10 minutes
  42. *
  43. * The timeout for upload.
  44. */
  45. var DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;
  46. /**
  47. * 1 second
  48. */
  49. var DEFAULT_MIN_SLEEP_TIME_MILLIS = 1000;
  50. /**
  51. * @license
  52. * Copyright 2017 Google LLC
  53. *
  54. * Licensed under the Apache License, Version 2.0 (the "License");
  55. * you may not use this file except in compliance with the License.
  56. * You may obtain a copy of the License at
  57. *
  58. * http://www.apache.org/licenses/LICENSE-2.0
  59. *
  60. * Unless required by applicable law or agreed to in writing, software
  61. * distributed under the License is distributed on an "AS IS" BASIS,
  62. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  63. * See the License for the specific language governing permissions and
  64. * limitations under the License.
  65. */
  66. /**
  67. * An error returned by the Firebase Storage SDK.
  68. * @public
  69. */
  70. var StorageError = /** @class */ (function (_super) {
  71. tslib.__extends(StorageError, _super);
  72. /**
  73. * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and
  74. * added to the end of the message.
  75. * @param message - Error message.
  76. * @param status_ - Corresponding HTTP Status Code
  77. */
  78. function StorageError(code, message, status_) {
  79. if (status_ === void 0) { status_ = 0; }
  80. var _this = _super.call(this, prependCode(code), "Firebase Storage: ".concat(message, " (").concat(prependCode(code), ")")) || this;
  81. _this.status_ = status_;
  82. /**
  83. * Stores custom error data unique to the `StorageError`.
  84. */
  85. _this.customData = { serverResponse: null };
  86. _this._baseMessage = _this.message;
  87. // Without this, `instanceof StorageError`, in tests for example,
  88. // returns false.
  89. Object.setPrototypeOf(_this, StorageError.prototype);
  90. return _this;
  91. }
  92. Object.defineProperty(StorageError.prototype, "status", {
  93. get: function () {
  94. return this.status_;
  95. },
  96. set: function (status) {
  97. this.status_ = status;
  98. },
  99. enumerable: false,
  100. configurable: true
  101. });
  102. /**
  103. * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.
  104. */
  105. StorageError.prototype._codeEquals = function (code) {
  106. return prependCode(code) === this.code;
  107. };
  108. Object.defineProperty(StorageError.prototype, "serverResponse", {
  109. /**
  110. * Optional response message that was added by the server.
  111. */
  112. get: function () {
  113. return this.customData.serverResponse;
  114. },
  115. set: function (serverResponse) {
  116. this.customData.serverResponse = serverResponse;
  117. if (this.customData.serverResponse) {
  118. this.message = "".concat(this._baseMessage, "\n").concat(this.customData.serverResponse);
  119. }
  120. else {
  121. this.message = this._baseMessage;
  122. }
  123. },
  124. enumerable: false,
  125. configurable: true
  126. });
  127. return StorageError;
  128. }(util.FirebaseError));
  129. /**
  130. * @public
  131. * Error codes that can be attached to `StorageError` objects.
  132. */
  133. exports.StorageErrorCode = void 0;
  134. (function (StorageErrorCode) {
  135. // Shared between all platforms
  136. StorageErrorCode["UNKNOWN"] = "unknown";
  137. StorageErrorCode["OBJECT_NOT_FOUND"] = "object-not-found";
  138. StorageErrorCode["BUCKET_NOT_FOUND"] = "bucket-not-found";
  139. StorageErrorCode["PROJECT_NOT_FOUND"] = "project-not-found";
  140. StorageErrorCode["QUOTA_EXCEEDED"] = "quota-exceeded";
  141. StorageErrorCode["UNAUTHENTICATED"] = "unauthenticated";
  142. StorageErrorCode["UNAUTHORIZED"] = "unauthorized";
  143. StorageErrorCode["UNAUTHORIZED_APP"] = "unauthorized-app";
  144. StorageErrorCode["RETRY_LIMIT_EXCEEDED"] = "retry-limit-exceeded";
  145. StorageErrorCode["INVALID_CHECKSUM"] = "invalid-checksum";
  146. StorageErrorCode["CANCELED"] = "canceled";
  147. // JS specific
  148. StorageErrorCode["INVALID_EVENT_NAME"] = "invalid-event-name";
  149. StorageErrorCode["INVALID_URL"] = "invalid-url";
  150. StorageErrorCode["INVALID_DEFAULT_BUCKET"] = "invalid-default-bucket";
  151. StorageErrorCode["NO_DEFAULT_BUCKET"] = "no-default-bucket";
  152. StorageErrorCode["CANNOT_SLICE_BLOB"] = "cannot-slice-blob";
  153. StorageErrorCode["SERVER_FILE_WRONG_SIZE"] = "server-file-wrong-size";
  154. StorageErrorCode["NO_DOWNLOAD_URL"] = "no-download-url";
  155. StorageErrorCode["INVALID_ARGUMENT"] = "invalid-argument";
  156. StorageErrorCode["INVALID_ARGUMENT_COUNT"] = "invalid-argument-count";
  157. StorageErrorCode["APP_DELETED"] = "app-deleted";
  158. StorageErrorCode["INVALID_ROOT_OPERATION"] = "invalid-root-operation";
  159. StorageErrorCode["INVALID_FORMAT"] = "invalid-format";
  160. StorageErrorCode["INTERNAL_ERROR"] = "internal-error";
  161. StorageErrorCode["UNSUPPORTED_ENVIRONMENT"] = "unsupported-environment";
  162. })(exports.StorageErrorCode || (exports.StorageErrorCode = {}));
  163. function prependCode(code) {
  164. return 'storage/' + code;
  165. }
  166. function unknown() {
  167. var message = 'An unknown error occurred, please check the error payload for ' +
  168. 'server response.';
  169. return new StorageError(exports.StorageErrorCode.UNKNOWN, message);
  170. }
  171. function objectNotFound(path) {
  172. return new StorageError(exports.StorageErrorCode.OBJECT_NOT_FOUND, "Object '" + path + "' does not exist.");
  173. }
  174. function quotaExceeded(bucket) {
  175. return new StorageError(exports.StorageErrorCode.QUOTA_EXCEEDED, "Quota for bucket '" +
  176. bucket +
  177. "' exceeded, please view quota on " +
  178. 'https://firebase.google.com/pricing/.');
  179. }
  180. function unauthenticated() {
  181. var message = 'User is not authenticated, please authenticate using Firebase ' +
  182. 'Authentication and try again.';
  183. return new StorageError(exports.StorageErrorCode.UNAUTHENTICATED, message);
  184. }
  185. function unauthorizedApp() {
  186. return new StorageError(exports.StorageErrorCode.UNAUTHORIZED_APP, 'This app does not have permission to access Firebase Storage on this project.');
  187. }
  188. function unauthorized(path) {
  189. return new StorageError(exports.StorageErrorCode.UNAUTHORIZED, "User does not have permission to access '" + path + "'.");
  190. }
  191. function retryLimitExceeded() {
  192. return new StorageError(exports.StorageErrorCode.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');
  193. }
  194. function canceled() {
  195. return new StorageError(exports.StorageErrorCode.CANCELED, 'User canceled the upload/download.');
  196. }
  197. function invalidUrl(url) {
  198. return new StorageError(exports.StorageErrorCode.INVALID_URL, "Invalid URL '" + url + "'.");
  199. }
  200. function invalidDefaultBucket(bucket) {
  201. return new StorageError(exports.StorageErrorCode.INVALID_DEFAULT_BUCKET, "Invalid default bucket '" + bucket + "'.");
  202. }
  203. function noDefaultBucket() {
  204. return new StorageError(exports.StorageErrorCode.NO_DEFAULT_BUCKET, 'No default bucket ' +
  205. "found. Did you set the '" +
  206. CONFIG_STORAGE_BUCKET_KEY +
  207. "' property when initializing the app?");
  208. }
  209. function cannotSliceBlob() {
  210. return new StorageError(exports.StorageErrorCode.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');
  211. }
  212. function serverFileWrongSize() {
  213. return new StorageError(exports.StorageErrorCode.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');
  214. }
  215. function noDownloadURL() {
  216. return new StorageError(exports.StorageErrorCode.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');
  217. }
  218. function missingPolyFill(polyFill) {
  219. return new StorageError(exports.StorageErrorCode.UNSUPPORTED_ENVIRONMENT, "".concat(polyFill, " is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information."));
  220. }
  221. /**
  222. * @internal
  223. */
  224. function invalidArgument(message) {
  225. return new StorageError(exports.StorageErrorCode.INVALID_ARGUMENT, message);
  226. }
  227. function appDeleted() {
  228. return new StorageError(exports.StorageErrorCode.APP_DELETED, 'The Firebase app was deleted.');
  229. }
  230. /**
  231. * @param name - The name of the operation that was invalid.
  232. *
  233. * @internal
  234. */
  235. function invalidRootOperation(name) {
  236. return new StorageError(exports.StorageErrorCode.INVALID_ROOT_OPERATION, "The operation '" +
  237. name +
  238. "' cannot be performed on a root reference, create a non-root " +
  239. "reference using child, such as .child('file.png').");
  240. }
  241. /**
  242. * @param format - The format that was not valid.
  243. * @param message - A message describing the format violation.
  244. */
  245. function invalidFormat(format, message) {
  246. return new StorageError(exports.StorageErrorCode.INVALID_FORMAT, "String does not match format '" + format + "': " + message);
  247. }
  248. /**
  249. * @param message - A message describing the internal error.
  250. */
  251. function internalError(message) {
  252. throw new StorageError(exports.StorageErrorCode.INTERNAL_ERROR, 'Internal error: ' + message);
  253. }
  254. /**
  255. * @license
  256. * Copyright 2017 Google LLC
  257. *
  258. * Licensed under the Apache License, Version 2.0 (the "License");
  259. * you may not use this file except in compliance with the License.
  260. * You may obtain a copy of the License at
  261. *
  262. * http://www.apache.org/licenses/LICENSE-2.0
  263. *
  264. * Unless required by applicable law or agreed to in writing, software
  265. * distributed under the License is distributed on an "AS IS" BASIS,
  266. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  267. * See the License for the specific language governing permissions and
  268. * limitations under the License.
  269. */
  270. /**
  271. * Firebase Storage location data.
  272. *
  273. * @internal
  274. */
  275. var Location = /** @class */ (function () {
  276. function Location(bucket, path) {
  277. this.bucket = bucket;
  278. this.path_ = path;
  279. }
  280. Object.defineProperty(Location.prototype, "path", {
  281. get: function () {
  282. return this.path_;
  283. },
  284. enumerable: false,
  285. configurable: true
  286. });
  287. Object.defineProperty(Location.prototype, "isRoot", {
  288. get: function () {
  289. return this.path.length === 0;
  290. },
  291. enumerable: false,
  292. configurable: true
  293. });
  294. Location.prototype.fullServerUrl = function () {
  295. var encode = encodeURIComponent;
  296. return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);
  297. };
  298. Location.prototype.bucketOnlyServerUrl = function () {
  299. var encode = encodeURIComponent;
  300. return '/b/' + encode(this.bucket) + '/o';
  301. };
  302. Location.makeFromBucketSpec = function (bucketString, host) {
  303. var bucketLocation;
  304. try {
  305. bucketLocation = Location.makeFromUrl(bucketString, host);
  306. }
  307. catch (e) {
  308. // Not valid URL, use as-is. This lets you put bare bucket names in
  309. // config.
  310. return new Location(bucketString, '');
  311. }
  312. if (bucketLocation.path === '') {
  313. return bucketLocation;
  314. }
  315. else {
  316. throw invalidDefaultBucket(bucketString);
  317. }
  318. };
  319. Location.makeFromUrl = function (url, host) {
  320. var location = null;
  321. var bucketDomain = '([A-Za-z0-9.\\-_]+)';
  322. function gsModify(loc) {
  323. if (loc.path.charAt(loc.path.length - 1) === '/') {
  324. loc.path_ = loc.path_.slice(0, -1);
  325. }
  326. }
  327. var gsPath = '(/(.*))?$';
  328. var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');
  329. var gsIndices = { bucket: 1, path: 3 };
  330. function httpModify(loc) {
  331. loc.path_ = decodeURIComponent(loc.path);
  332. }
  333. var version = 'v[A-Za-z0-9_]+';
  334. var firebaseStorageHost = host.replace(/[.]/g, '\\.');
  335. var firebaseStoragePath = '(/([^?#]*).*)?$';
  336. var firebaseStorageRegExp = new RegExp("^https?://".concat(firebaseStorageHost, "/").concat(version, "/b/").concat(bucketDomain, "/o").concat(firebaseStoragePath), 'i');
  337. var firebaseStorageIndices = { bucket: 1, path: 3 };
  338. var cloudStorageHost = host === DEFAULT_HOST
  339. ? '(?:storage.googleapis.com|storage.cloud.google.com)'
  340. : host;
  341. var cloudStoragePath = '([^?#]*)';
  342. var cloudStorageRegExp = new RegExp("^https?://".concat(cloudStorageHost, "/").concat(bucketDomain, "/").concat(cloudStoragePath), 'i');
  343. var cloudStorageIndices = { bucket: 1, path: 2 };
  344. var groups = [
  345. { regex: gsRegex, indices: gsIndices, postModify: gsModify },
  346. {
  347. regex: firebaseStorageRegExp,
  348. indices: firebaseStorageIndices,
  349. postModify: httpModify
  350. },
  351. {
  352. regex: cloudStorageRegExp,
  353. indices: cloudStorageIndices,
  354. postModify: httpModify
  355. }
  356. ];
  357. for (var i = 0; i < groups.length; i++) {
  358. var group = groups[i];
  359. var captures = group.regex.exec(url);
  360. if (captures) {
  361. var bucketValue = captures[group.indices.bucket];
  362. var pathValue = captures[group.indices.path];
  363. if (!pathValue) {
  364. pathValue = '';
  365. }
  366. location = new Location(bucketValue, pathValue);
  367. group.postModify(location);
  368. break;
  369. }
  370. }
  371. if (location == null) {
  372. throw invalidUrl(url);
  373. }
  374. return location;
  375. };
  376. return Location;
  377. }());
  378. /**
  379. * A request whose promise always fails.
  380. */
  381. var FailRequest = /** @class */ (function () {
  382. function FailRequest(error) {
  383. this.promise_ = Promise.reject(error);
  384. }
  385. /** @inheritDoc */
  386. FailRequest.prototype.getPromise = function () {
  387. return this.promise_;
  388. };
  389. /** @inheritDoc */
  390. FailRequest.prototype.cancel = function (_appDelete) {
  391. };
  392. return FailRequest;
  393. }());
  394. /**
  395. * @license
  396. * Copyright 2017 Google LLC
  397. *
  398. * Licensed under the Apache License, Version 2.0 (the "License");
  399. * you may not use this file except in compliance with the License.
  400. * You may obtain a copy of the License at
  401. *
  402. * http://www.apache.org/licenses/LICENSE-2.0
  403. *
  404. * Unless required by applicable law or agreed to in writing, software
  405. * distributed under the License is distributed on an "AS IS" BASIS,
  406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  407. * See the License for the specific language governing permissions and
  408. * limitations under the License.
  409. */
  410. /**
  411. * Accepts a callback for an action to perform (`doRequest`),
  412. * and then a callback for when the backoff has completed (`backoffCompleteCb`).
  413. * The callback sent to start requires an argument to call (`onRequestComplete`).
  414. * When `start` calls `doRequest`, it passes a callback for when the request has
  415. * completed, `onRequestComplete`. Based on this, the backoff continues, with
  416. * another call to `doRequest` and the above loop continues until the timeout
  417. * is hit, or a successful response occurs.
  418. * @description
  419. * @param doRequest Callback to perform request
  420. * @param backoffCompleteCb Callback to call when backoff has been completed
  421. */
  422. function start(doRequest,
  423. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  424. backoffCompleteCb, timeout) {
  425. // TODO(andysoto): make this code cleaner (probably refactor into an actual
  426. // type instead of a bunch of functions with state shared in the closure)
  427. var waitSeconds = 1;
  428. // Would type this as "number" but that doesn't work for Node so ¯\_(ツ)_/¯
  429. // TODO: find a way to exclude Node type definition for storage because storage only works in browser
  430. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  431. var retryTimeoutId = null;
  432. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  433. var globalTimeoutId = null;
  434. var hitTimeout = false;
  435. var cancelState = 0;
  436. function canceled() {
  437. return cancelState === 2;
  438. }
  439. var triggeredCallback = false;
  440. function triggerCallback() {
  441. var args = [];
  442. for (var _i = 0; _i < arguments.length; _i++) {
  443. args[_i] = arguments[_i];
  444. }
  445. if (!triggeredCallback) {
  446. triggeredCallback = true;
  447. backoffCompleteCb.apply(null, args);
  448. }
  449. }
  450. function callWithDelay(millis) {
  451. retryTimeoutId = setTimeout(function () {
  452. retryTimeoutId = null;
  453. doRequest(responseHandler, canceled());
  454. }, millis);
  455. }
  456. function clearGlobalTimeout() {
  457. if (globalTimeoutId) {
  458. clearTimeout(globalTimeoutId);
  459. }
  460. }
  461. function responseHandler(success) {
  462. var args = [];
  463. for (var _i = 1; _i < arguments.length; _i++) {
  464. args[_i - 1] = arguments[_i];
  465. }
  466. if (triggeredCallback) {
  467. clearGlobalTimeout();
  468. return;
  469. }
  470. if (success) {
  471. clearGlobalTimeout();
  472. triggerCallback.call.apply(triggerCallback, tslib.__spreadArray([null, success], args, false));
  473. return;
  474. }
  475. var mustStop = canceled() || hitTimeout;
  476. if (mustStop) {
  477. clearGlobalTimeout();
  478. triggerCallback.call.apply(triggerCallback, tslib.__spreadArray([null, success], args, false));
  479. return;
  480. }
  481. if (waitSeconds < 64) {
  482. /* TODO(andysoto): don't back off so quickly if we know we're offline. */
  483. waitSeconds *= 2;
  484. }
  485. var waitMillis;
  486. if (cancelState === 1) {
  487. cancelState = 2;
  488. waitMillis = 0;
  489. }
  490. else {
  491. waitMillis = (waitSeconds + Math.random()) * 1000;
  492. }
  493. callWithDelay(waitMillis);
  494. }
  495. var stopped = false;
  496. function stop(wasTimeout) {
  497. if (stopped) {
  498. return;
  499. }
  500. stopped = true;
  501. clearGlobalTimeout();
  502. if (triggeredCallback) {
  503. return;
  504. }
  505. if (retryTimeoutId !== null) {
  506. if (!wasTimeout) {
  507. cancelState = 2;
  508. }
  509. clearTimeout(retryTimeoutId);
  510. callWithDelay(0);
  511. }
  512. else {
  513. if (!wasTimeout) {
  514. cancelState = 1;
  515. }
  516. }
  517. }
  518. callWithDelay(0);
  519. globalTimeoutId = setTimeout(function () {
  520. hitTimeout = true;
  521. stop(true);
  522. }, timeout);
  523. return stop;
  524. }
  525. /**
  526. * Stops the retry loop from repeating.
  527. * If the function is currently "in between" retries, it is invoked immediately
  528. * with the second parameter as "true". Otherwise, it will be invoked once more
  529. * after the current invocation finishes iff the current invocation would have
  530. * triggered another retry.
  531. */
  532. function stop(id) {
  533. id(false);
  534. }
  535. /**
  536. * @license
  537. * Copyright 2017 Google LLC
  538. *
  539. * Licensed under the Apache License, Version 2.0 (the "License");
  540. * you may not use this file except in compliance with the License.
  541. * You may obtain a copy of the License at
  542. *
  543. * http://www.apache.org/licenses/LICENSE-2.0
  544. *
  545. * Unless required by applicable law or agreed to in writing, software
  546. * distributed under the License is distributed on an "AS IS" BASIS,
  547. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  548. * See the License for the specific language governing permissions and
  549. * limitations under the License.
  550. */
  551. function isJustDef(p) {
  552. return p !== void 0;
  553. }
  554. // eslint-disable-next-line @typescript-eslint/ban-types
  555. function isFunction(p) {
  556. return typeof p === 'function';
  557. }
  558. function isNonArrayObject(p) {
  559. return typeof p === 'object' && !Array.isArray(p);
  560. }
  561. function isString(p) {
  562. return typeof p === 'string' || p instanceof String;
  563. }
  564. function isNativeBlob(p) {
  565. return isNativeBlobDefined() && p instanceof Blob;
  566. }
  567. function isNativeBlobDefined() {
  568. // Note: The `isNode()` check can be removed when `node-fetch` adds native Blob support
  569. // PR: https://github.com/node-fetch/node-fetch/pull/1664
  570. return typeof Blob !== 'undefined' && !util.isNode();
  571. }
  572. function validateNumber(argument, minValue, maxValue, value) {
  573. if (value < minValue) {
  574. throw invalidArgument("Invalid value for '".concat(argument, "'. Expected ").concat(minValue, " or greater."));
  575. }
  576. if (value > maxValue) {
  577. throw invalidArgument("Invalid value for '".concat(argument, "'. Expected ").concat(maxValue, " or less."));
  578. }
  579. }
  580. /**
  581. * @license
  582. * Copyright 2017 Google LLC
  583. *
  584. * Licensed under the Apache License, Version 2.0 (the "License");
  585. * you may not use this file except in compliance with the License.
  586. * You may obtain a copy of the License at
  587. *
  588. * http://www.apache.org/licenses/LICENSE-2.0
  589. *
  590. * Unless required by applicable law or agreed to in writing, software
  591. * distributed under the License is distributed on an "AS IS" BASIS,
  592. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  593. * See the License for the specific language governing permissions and
  594. * limitations under the License.
  595. */
  596. function makeUrl(urlPart, host, protocol) {
  597. var origin = host;
  598. if (protocol == null) {
  599. origin = "https://".concat(host);
  600. }
  601. return "".concat(protocol, "://").concat(origin, "/v0").concat(urlPart);
  602. }
  603. function makeQueryString(params) {
  604. var encode = encodeURIComponent;
  605. var queryPart = '?';
  606. for (var key in params) {
  607. if (params.hasOwnProperty(key)) {
  608. var nextPart = encode(key) + '=' + encode(params[key]);
  609. queryPart = queryPart + nextPart + '&';
  610. }
  611. }
  612. // Chop off the extra '&' or '?' on the end
  613. queryPart = queryPart.slice(0, -1);
  614. return queryPart;
  615. }
  616. /**
  617. * @license
  618. * Copyright 2017 Google LLC
  619. *
  620. * Licensed under the Apache License, Version 2.0 (the "License");
  621. * you may not use this file except in compliance with the License.
  622. * You may obtain a copy of the License at
  623. *
  624. * http://www.apache.org/licenses/LICENSE-2.0
  625. *
  626. * Unless required by applicable law or agreed to in writing, software
  627. * distributed under the License is distributed on an "AS IS" BASIS,
  628. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  629. * See the License for the specific language governing permissions and
  630. * limitations under the License.
  631. */
  632. /**
  633. * Error codes for requests made by the the XhrIo wrapper.
  634. */
  635. var ErrorCode;
  636. (function (ErrorCode) {
  637. ErrorCode[ErrorCode["NO_ERROR"] = 0] = "NO_ERROR";
  638. ErrorCode[ErrorCode["NETWORK_ERROR"] = 1] = "NETWORK_ERROR";
  639. ErrorCode[ErrorCode["ABORT"] = 2] = "ABORT";
  640. })(ErrorCode || (ErrorCode = {}));
  641. /**
  642. * @license
  643. * Copyright 2022 Google LLC
  644. *
  645. * Licensed under the Apache License, Version 2.0 (the "License");
  646. * you may not use this file except in compliance with the License.
  647. * You may obtain a copy of the License at
  648. *
  649. * http://www.apache.org/licenses/LICENSE-2.0
  650. *
  651. * Unless required by applicable law or agreed to in writing, software
  652. * distributed under the License is distributed on an "AS IS" BASIS,
  653. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  654. * See the License for the specific language governing permissions and
  655. * limitations under the License.
  656. */
  657. /**
  658. * Checks the status code to see if the action should be retried.
  659. *
  660. * @param status Current HTTP status code returned by server.
  661. * @param additionalRetryCodes additional retry codes to check against
  662. */
  663. function isRetryStatusCode(status, additionalRetryCodes) {
  664. // The codes for which to retry came from this page:
  665. // https://cloud.google.com/storage/docs/exponential-backoff
  666. var isFiveHundredCode = status >= 500 && status < 600;
  667. var extraRetryCodes = [
  668. // Request Timeout: web server didn't receive full request in time.
  669. 408,
  670. // Too Many Requests: you're getting rate-limited, basically.
  671. 429
  672. ];
  673. var isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;
  674. var isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;
  675. return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;
  676. }
  677. /**
  678. * @license
  679. * Copyright 2017 Google LLC
  680. *
  681. * Licensed under the Apache License, Version 2.0 (the "License");
  682. * you may not use this file except in compliance with the License.
  683. * You may obtain a copy of the License at
  684. *
  685. * http://www.apache.org/licenses/LICENSE-2.0
  686. *
  687. * Unless required by applicable law or agreed to in writing, software
  688. * distributed under the License is distributed on an "AS IS" BASIS,
  689. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  690. * See the License for the specific language governing permissions and
  691. * limitations under the License.
  692. */
  693. /**
  694. * Handles network logic for all Storage Requests, including error reporting and
  695. * retries with backoff.
  696. *
  697. * @param I - the type of the backend's network response.
  698. * @param - O the output type used by the rest of the SDK. The conversion
  699. * happens in the specified `callback_`.
  700. */
  701. var NetworkRequest = /** @class */ (function () {
  702. function NetworkRequest(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry) {
  703. if (retry === void 0) { retry = true; }
  704. var _this = this;
  705. this.url_ = url_;
  706. this.method_ = method_;
  707. this.headers_ = headers_;
  708. this.body_ = body_;
  709. this.successCodes_ = successCodes_;
  710. this.additionalRetryCodes_ = additionalRetryCodes_;
  711. this.callback_ = callback_;
  712. this.errorCallback_ = errorCallback_;
  713. this.timeout_ = timeout_;
  714. this.progressCallback_ = progressCallback_;
  715. this.connectionFactory_ = connectionFactory_;
  716. this.retry = retry;
  717. this.pendingConnection_ = null;
  718. this.backoffId_ = null;
  719. this.canceled_ = false;
  720. this.appDelete_ = false;
  721. this.promise_ = new Promise(function (resolve, reject) {
  722. _this.resolve_ = resolve;
  723. _this.reject_ = reject;
  724. _this.start_();
  725. });
  726. }
  727. /**
  728. * Actually starts the retry loop.
  729. */
  730. NetworkRequest.prototype.start_ = function () {
  731. var _this = this;
  732. var doTheRequest = function (backoffCallback, canceled) {
  733. if (canceled) {
  734. backoffCallback(false, new RequestEndStatus(false, null, true));
  735. return;
  736. }
  737. var connection = _this.connectionFactory_();
  738. _this.pendingConnection_ = connection;
  739. var progressListener = function (progressEvent) {
  740. var loaded = progressEvent.loaded;
  741. var total = progressEvent.lengthComputable ? progressEvent.total : -1;
  742. if (_this.progressCallback_ !== null) {
  743. _this.progressCallback_(loaded, total);
  744. }
  745. };
  746. if (_this.progressCallback_ !== null) {
  747. connection.addUploadProgressListener(progressListener);
  748. }
  749. // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.
  750. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  751. connection
  752. .send(_this.url_, _this.method_, _this.body_, _this.headers_)
  753. .then(function () {
  754. if (_this.progressCallback_ !== null) {
  755. connection.removeUploadProgressListener(progressListener);
  756. }
  757. _this.pendingConnection_ = null;
  758. var hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;
  759. var status = connection.getStatus();
  760. if (!hitServer ||
  761. (isRetryStatusCode(status, _this.additionalRetryCodes_) &&
  762. _this.retry)) {
  763. var wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;
  764. backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));
  765. return;
  766. }
  767. var successCode = _this.successCodes_.indexOf(status) !== -1;
  768. backoffCallback(true, new RequestEndStatus(successCode, connection));
  769. });
  770. };
  771. /**
  772. * @param requestWentThrough - True if the request eventually went
  773. * through, false if it hit the retry limit or was canceled.
  774. */
  775. var backoffDone = function (requestWentThrough, status) {
  776. var resolve = _this.resolve_;
  777. var reject = _this.reject_;
  778. var connection = status.connection;
  779. if (status.wasSuccessCode) {
  780. try {
  781. var result = _this.callback_(connection, connection.getResponse());
  782. if (isJustDef(result)) {
  783. resolve(result);
  784. }
  785. else {
  786. resolve();
  787. }
  788. }
  789. catch (e) {
  790. reject(e);
  791. }
  792. }
  793. else {
  794. if (connection !== null) {
  795. var err = unknown();
  796. err.serverResponse = connection.getErrorText();
  797. if (_this.errorCallback_) {
  798. reject(_this.errorCallback_(connection, err));
  799. }
  800. else {
  801. reject(err);
  802. }
  803. }
  804. else {
  805. if (status.canceled) {
  806. var err = _this.appDelete_ ? appDeleted() : canceled();
  807. reject(err);
  808. }
  809. else {
  810. var err = retryLimitExceeded();
  811. reject(err);
  812. }
  813. }
  814. }
  815. };
  816. if (this.canceled_) {
  817. backoffDone(false, new RequestEndStatus(false, null, true));
  818. }
  819. else {
  820. this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);
  821. }
  822. };
  823. /** @inheritDoc */
  824. NetworkRequest.prototype.getPromise = function () {
  825. return this.promise_;
  826. };
  827. /** @inheritDoc */
  828. NetworkRequest.prototype.cancel = function (appDelete) {
  829. this.canceled_ = true;
  830. this.appDelete_ = appDelete || false;
  831. if (this.backoffId_ !== null) {
  832. stop(this.backoffId_);
  833. }
  834. if (this.pendingConnection_ !== null) {
  835. this.pendingConnection_.abort();
  836. }
  837. };
  838. return NetworkRequest;
  839. }());
  840. /**
  841. * A collection of information about the result of a network request.
  842. * @param opt_canceled - Defaults to false.
  843. */
  844. var RequestEndStatus = /** @class */ (function () {
  845. function RequestEndStatus(wasSuccessCode, connection, canceled) {
  846. this.wasSuccessCode = wasSuccessCode;
  847. this.connection = connection;
  848. this.canceled = !!canceled;
  849. }
  850. return RequestEndStatus;
  851. }());
  852. function addAuthHeader_(headers, authToken) {
  853. if (authToken !== null && authToken.length > 0) {
  854. headers['Authorization'] = 'Firebase ' + authToken;
  855. }
  856. }
  857. function addVersionHeader_(headers, firebaseVersion) {
  858. headers['X-Firebase-Storage-Version'] =
  859. 'webjs/' + (firebaseVersion !== null && firebaseVersion !== void 0 ? firebaseVersion : 'AppManager');
  860. }
  861. function addGmpidHeader_(headers, appId) {
  862. if (appId) {
  863. headers['X-Firebase-GMPID'] = appId;
  864. }
  865. }
  866. function addAppCheckHeader_(headers, appCheckToken) {
  867. if (appCheckToken !== null) {
  868. headers['X-Firebase-AppCheck'] = appCheckToken;
  869. }
  870. }
  871. function makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry) {
  872. if (retry === void 0) { retry = true; }
  873. var queryPart = makeQueryString(requestInfo.urlParams);
  874. var url = requestInfo.url + queryPart;
  875. var headers = Object.assign({}, requestInfo.headers);
  876. addGmpidHeader_(headers, appId);
  877. addAuthHeader_(headers, authToken);
  878. addVersionHeader_(headers, firebaseVersion);
  879. addAppCheckHeader_(headers, appCheckToken);
  880. return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry);
  881. }
  882. /**
  883. * @license
  884. * Copyright 2017 Google LLC
  885. *
  886. * Licensed under the Apache License, Version 2.0 (the "License");
  887. * you may not use this file except in compliance with the License.
  888. * You may obtain a copy of the License at
  889. *
  890. * http://www.apache.org/licenses/LICENSE-2.0
  891. *
  892. * Unless required by applicable law or agreed to in writing, software
  893. * distributed under the License is distributed on an "AS IS" BASIS,
  894. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  895. * See the License for the specific language governing permissions and
  896. * limitations under the License.
  897. */
  898. function getBlobBuilder() {
  899. if (typeof BlobBuilder !== 'undefined') {
  900. return BlobBuilder;
  901. }
  902. else if (typeof WebKitBlobBuilder !== 'undefined') {
  903. return WebKitBlobBuilder;
  904. }
  905. else {
  906. return undefined;
  907. }
  908. }
  909. /**
  910. * Concatenates one or more values together and converts them to a Blob.
  911. *
  912. * @param args The values that will make up the resulting blob.
  913. * @return The blob.
  914. */
  915. function getBlob$1() {
  916. var args = [];
  917. for (var _i = 0; _i < arguments.length; _i++) {
  918. args[_i] = arguments[_i];
  919. }
  920. var BlobBuilder = getBlobBuilder();
  921. if (BlobBuilder !== undefined) {
  922. var bb = new BlobBuilder();
  923. for (var i = 0; i < args.length; i++) {
  924. bb.append(args[i]);
  925. }
  926. return bb.getBlob();
  927. }
  928. else {
  929. if (isNativeBlobDefined()) {
  930. return new Blob(args);
  931. }
  932. else {
  933. throw new StorageError(exports.StorageErrorCode.UNSUPPORTED_ENVIRONMENT, "This browser doesn't seem to support creating Blobs");
  934. }
  935. }
  936. }
  937. /**
  938. * Slices the blob. The returned blob contains data from the start byte
  939. * (inclusive) till the end byte (exclusive). Negative indices cannot be used.
  940. *
  941. * @param blob The blob to be sliced.
  942. * @param start Index of the starting byte.
  943. * @param end Index of the ending byte.
  944. * @return The blob slice or null if not supported.
  945. */
  946. function sliceBlob(blob, start, end) {
  947. if (blob.webkitSlice) {
  948. return blob.webkitSlice(start, end);
  949. }
  950. else if (blob.mozSlice) {
  951. return blob.mozSlice(start, end);
  952. }
  953. else if (blob.slice) {
  954. return blob.slice(start, end);
  955. }
  956. return null;
  957. }
  958. /**
  959. * @license
  960. * Copyright 2021 Google LLC
  961. *
  962. * Licensed under the Apache License, Version 2.0 (the "License");
  963. * you may not use this file except in compliance with the License.
  964. * You may obtain a copy of the License at
  965. *
  966. * http://www.apache.org/licenses/LICENSE-2.0
  967. *
  968. * Unless required by applicable law or agreed to in writing, software
  969. * distributed under the License is distributed on an "AS IS" BASIS,
  970. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  971. * See the License for the specific language governing permissions and
  972. * limitations under the License.
  973. */
  974. /** Converts a Base64 encoded string to a binary string. */
  975. function decodeBase64(encoded) {
  976. if (typeof atob === 'undefined') {
  977. throw missingPolyFill('base-64');
  978. }
  979. return atob(encoded);
  980. }
  981. /**
  982. * @license
  983. * Copyright 2017 Google LLC
  984. *
  985. * Licensed under the Apache License, Version 2.0 (the "License");
  986. * you may not use this file except in compliance with the License.
  987. * You may obtain a copy of the License at
  988. *
  989. * http://www.apache.org/licenses/LICENSE-2.0
  990. *
  991. * Unless required by applicable law or agreed to in writing, software
  992. * distributed under the License is distributed on an "AS IS" BASIS,
  993. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  994. * See the License for the specific language governing permissions and
  995. * limitations under the License.
  996. */
  997. /**
  998. * An enumeration of the possible string formats for upload.
  999. * @public
  1000. */
  1001. var StringFormat = {
  1002. /**
  1003. * Indicates the string should be interpreted "raw", that is, as normal text.
  1004. * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte
  1005. * sequence.
  1006. * Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence
  1007. * 48 65 6c 6c 6f 21 20 f0 9f 98 8a
  1008. */
  1009. RAW: 'raw',
  1010. /**
  1011. * Indicates the string should be interpreted as base64-encoded data.
  1012. * Padding characters (trailing '='s) are optional.
  1013. * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence
  1014. * ad 69 8e fb e1 3a b7 bf eb 97
  1015. */
  1016. BASE64: 'base64',
  1017. /**
  1018. * Indicates the string should be interpreted as base64url-encoded data.
  1019. * Padding characters (trailing '='s) are optional.
  1020. * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence
  1021. * ad 69 8e fb e1 3a b7 bf eb 97
  1022. */
  1023. BASE64URL: 'base64url',
  1024. /**
  1025. * Indicates the string is a data URL, such as one obtained from
  1026. * canvas.toDataURL().
  1027. * Example: the string 'data:application/octet-stream;base64,aaaa'
  1028. * becomes the byte sequence
  1029. * 69 a6 9a
  1030. * (the content-type "application/octet-stream" is also applied, but can
  1031. * be overridden in the metadata object).
  1032. */
  1033. DATA_URL: 'data_url'
  1034. };
  1035. var StringData = /** @class */ (function () {
  1036. function StringData(data, contentType) {
  1037. this.data = data;
  1038. this.contentType = contentType || null;
  1039. }
  1040. return StringData;
  1041. }());
  1042. /**
  1043. * @internal
  1044. */
  1045. function dataFromString(format, stringData) {
  1046. switch (format) {
  1047. case StringFormat.RAW:
  1048. return new StringData(utf8Bytes_(stringData));
  1049. case StringFormat.BASE64:
  1050. case StringFormat.BASE64URL:
  1051. return new StringData(base64Bytes_(format, stringData));
  1052. case StringFormat.DATA_URL:
  1053. return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));
  1054. // do nothing
  1055. }
  1056. // assert(false);
  1057. throw unknown();
  1058. }
  1059. function utf8Bytes_(value) {
  1060. var b = [];
  1061. for (var i = 0; i < value.length; i++) {
  1062. var c = value.charCodeAt(i);
  1063. if (c <= 127) {
  1064. b.push(c);
  1065. }
  1066. else {
  1067. if (c <= 2047) {
  1068. b.push(192 | (c >> 6), 128 | (c & 63));
  1069. }
  1070. else {
  1071. if ((c & 64512) === 55296) {
  1072. // The start of a surrogate pair.
  1073. var valid = i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;
  1074. if (!valid) {
  1075. // The second surrogate wasn't there.
  1076. b.push(239, 191, 189);
  1077. }
  1078. else {
  1079. var hi = c;
  1080. var lo = value.charCodeAt(++i);
  1081. c = 65536 | ((hi & 1023) << 10) | (lo & 1023);
  1082. b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));
  1083. }
  1084. }
  1085. else {
  1086. if ((c & 64512) === 56320) {
  1087. // Invalid low surrogate.
  1088. b.push(239, 191, 189);
  1089. }
  1090. else {
  1091. b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));
  1092. }
  1093. }
  1094. }
  1095. }
  1096. }
  1097. return new Uint8Array(b);
  1098. }
  1099. function percentEncodedBytes_(value) {
  1100. var decoded;
  1101. try {
  1102. decoded = decodeURIComponent(value);
  1103. }
  1104. catch (e) {
  1105. throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');
  1106. }
  1107. return utf8Bytes_(decoded);
  1108. }
  1109. function base64Bytes_(format, value) {
  1110. switch (format) {
  1111. case StringFormat.BASE64: {
  1112. var hasMinus = value.indexOf('-') !== -1;
  1113. var hasUnder = value.indexOf('_') !== -1;
  1114. if (hasMinus || hasUnder) {
  1115. var invalidChar = hasMinus ? '-' : '_';
  1116. throw invalidFormat(format, "Invalid character '" +
  1117. invalidChar +
  1118. "' found: is it base64url encoded?");
  1119. }
  1120. break;
  1121. }
  1122. case StringFormat.BASE64URL: {
  1123. var hasPlus = value.indexOf('+') !== -1;
  1124. var hasSlash = value.indexOf('/') !== -1;
  1125. if (hasPlus || hasSlash) {
  1126. var invalidChar = hasPlus ? '+' : '/';
  1127. throw invalidFormat(format, "Invalid character '" + invalidChar + "' found: is it base64 encoded?");
  1128. }
  1129. value = value.replace(/-/g, '+').replace(/_/g, '/');
  1130. break;
  1131. }
  1132. // do nothing
  1133. }
  1134. var bytes;
  1135. try {
  1136. bytes = decodeBase64(value);
  1137. }
  1138. catch (e) {
  1139. if (e.message.includes('polyfill')) {
  1140. throw e;
  1141. }
  1142. throw invalidFormat(format, 'Invalid character found');
  1143. }
  1144. var array = new Uint8Array(bytes.length);
  1145. for (var i = 0; i < bytes.length; i++) {
  1146. array[i] = bytes.charCodeAt(i);
  1147. }
  1148. return array;
  1149. }
  1150. var DataURLParts = /** @class */ (function () {
  1151. function DataURLParts(dataURL) {
  1152. this.base64 = false;
  1153. this.contentType = null;
  1154. var matches = dataURL.match(/^data:([^,]+)?,/);
  1155. if (matches === null) {
  1156. throw invalidFormat(StringFormat.DATA_URL, "Must be formatted 'data:[<mediatype>][;base64],<data>");
  1157. }
  1158. var middle = matches[1] || null;
  1159. if (middle != null) {
  1160. this.base64 = endsWith(middle, ';base64');
  1161. this.contentType = this.base64
  1162. ? middle.substring(0, middle.length - ';base64'.length)
  1163. : middle;
  1164. }
  1165. this.rest = dataURL.substring(dataURL.indexOf(',') + 1);
  1166. }
  1167. return DataURLParts;
  1168. }());
  1169. function dataURLBytes_(dataUrl) {
  1170. var parts = new DataURLParts(dataUrl);
  1171. if (parts.base64) {
  1172. return base64Bytes_(StringFormat.BASE64, parts.rest);
  1173. }
  1174. else {
  1175. return percentEncodedBytes_(parts.rest);
  1176. }
  1177. }
  1178. function dataURLContentType_(dataUrl) {
  1179. var parts = new DataURLParts(dataUrl);
  1180. return parts.contentType;
  1181. }
  1182. function endsWith(s, end) {
  1183. var longEnough = s.length >= end.length;
  1184. if (!longEnough) {
  1185. return false;
  1186. }
  1187. return s.substring(s.length - end.length) === end;
  1188. }
  1189. /**
  1190. * @license
  1191. * Copyright 2017 Google LLC
  1192. *
  1193. * Licensed under the Apache License, Version 2.0 (the "License");
  1194. * you may not use this file except in compliance with the License.
  1195. * You may obtain a copy of the License at
  1196. *
  1197. * http://www.apache.org/licenses/LICENSE-2.0
  1198. *
  1199. * Unless required by applicable law or agreed to in writing, software
  1200. * distributed under the License is distributed on an "AS IS" BASIS,
  1201. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1202. * See the License for the specific language governing permissions and
  1203. * limitations under the License.
  1204. */
  1205. /**
  1206. * @param opt_elideCopy - If true, doesn't copy mutable input data
  1207. * (e.g. Uint8Arrays). Pass true only if you know the objects will not be
  1208. * modified after this blob's construction.
  1209. *
  1210. * @internal
  1211. */
  1212. var FbsBlob = /** @class */ (function () {
  1213. function FbsBlob(data, elideCopy) {
  1214. var size = 0;
  1215. var blobType = '';
  1216. if (isNativeBlob(data)) {
  1217. this.data_ = data;
  1218. size = data.size;
  1219. blobType = data.type;
  1220. }
  1221. else if (data instanceof ArrayBuffer) {
  1222. if (elideCopy) {
  1223. this.data_ = new Uint8Array(data);
  1224. }
  1225. else {
  1226. this.data_ = new Uint8Array(data.byteLength);
  1227. this.data_.set(new Uint8Array(data));
  1228. }
  1229. size = this.data_.length;
  1230. }
  1231. else if (data instanceof Uint8Array) {
  1232. if (elideCopy) {
  1233. this.data_ = data;
  1234. }
  1235. else {
  1236. this.data_ = new Uint8Array(data.length);
  1237. this.data_.set(data);
  1238. }
  1239. size = data.length;
  1240. }
  1241. this.size_ = size;
  1242. this.type_ = blobType;
  1243. }
  1244. FbsBlob.prototype.size = function () {
  1245. return this.size_;
  1246. };
  1247. FbsBlob.prototype.type = function () {
  1248. return this.type_;
  1249. };
  1250. FbsBlob.prototype.slice = function (startByte, endByte) {
  1251. if (isNativeBlob(this.data_)) {
  1252. var realBlob = this.data_;
  1253. var sliced = sliceBlob(realBlob, startByte, endByte);
  1254. if (sliced === null) {
  1255. return null;
  1256. }
  1257. return new FbsBlob(sliced);
  1258. }
  1259. else {
  1260. var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);
  1261. return new FbsBlob(slice, true);
  1262. }
  1263. };
  1264. FbsBlob.getBlob = function () {
  1265. var args = [];
  1266. for (var _i = 0; _i < arguments.length; _i++) {
  1267. args[_i] = arguments[_i];
  1268. }
  1269. if (isNativeBlobDefined()) {
  1270. var blobby = args.map(function (val) {
  1271. if (val instanceof FbsBlob) {
  1272. return val.data_;
  1273. }
  1274. else {
  1275. return val;
  1276. }
  1277. });
  1278. return new FbsBlob(getBlob$1.apply(null, blobby));
  1279. }
  1280. else {
  1281. var uint8Arrays = args.map(function (val) {
  1282. if (isString(val)) {
  1283. return dataFromString(StringFormat.RAW, val).data;
  1284. }
  1285. else {
  1286. // Blobs don't exist, so this has to be a Uint8Array.
  1287. return val.data_;
  1288. }
  1289. });
  1290. var finalLength_1 = 0;
  1291. uint8Arrays.forEach(function (array) {
  1292. finalLength_1 += array.byteLength;
  1293. });
  1294. var merged_1 = new Uint8Array(finalLength_1);
  1295. var index_1 = 0;
  1296. uint8Arrays.forEach(function (array) {
  1297. for (var i = 0; i < array.length; i++) {
  1298. merged_1[index_1++] = array[i];
  1299. }
  1300. });
  1301. return new FbsBlob(merged_1, true);
  1302. }
  1303. };
  1304. FbsBlob.prototype.uploadData = function () {
  1305. return this.data_;
  1306. };
  1307. return FbsBlob;
  1308. }());
  1309. /**
  1310. * @license
  1311. * Copyright 2017 Google LLC
  1312. *
  1313. * Licensed under the Apache License, Version 2.0 (the "License");
  1314. * you may not use this file except in compliance with the License.
  1315. * You may obtain a copy of the License at
  1316. *
  1317. * http://www.apache.org/licenses/LICENSE-2.0
  1318. *
  1319. * Unless required by applicable law or agreed to in writing, software
  1320. * distributed under the License is distributed on an "AS IS" BASIS,
  1321. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1322. * See the License for the specific language governing permissions and
  1323. * limitations under the License.
  1324. */
  1325. /**
  1326. * Returns the Object resulting from parsing the given JSON, or null if the
  1327. * given string does not represent a JSON object.
  1328. */
  1329. function jsonObjectOrNull(s) {
  1330. var obj;
  1331. try {
  1332. obj = JSON.parse(s);
  1333. }
  1334. catch (e) {
  1335. return null;
  1336. }
  1337. if (isNonArrayObject(obj)) {
  1338. return obj;
  1339. }
  1340. else {
  1341. return null;
  1342. }
  1343. }
  1344. /**
  1345. * @license
  1346. * Copyright 2017 Google LLC
  1347. *
  1348. * Licensed under the Apache License, Version 2.0 (the "License");
  1349. * you may not use this file except in compliance with the License.
  1350. * You may obtain a copy of the License at
  1351. *
  1352. * http://www.apache.org/licenses/LICENSE-2.0
  1353. *
  1354. * Unless required by applicable law or agreed to in writing, software
  1355. * distributed under the License is distributed on an "AS IS" BASIS,
  1356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1357. * See the License for the specific language governing permissions and
  1358. * limitations under the License.
  1359. */
  1360. /**
  1361. * @fileoverview Contains helper methods for manipulating paths.
  1362. */
  1363. /**
  1364. * @return Null if the path is already at the root.
  1365. */
  1366. function parent(path) {
  1367. if (path.length === 0) {
  1368. return null;
  1369. }
  1370. var index = path.lastIndexOf('/');
  1371. if (index === -1) {
  1372. return '';
  1373. }
  1374. var newPath = path.slice(0, index);
  1375. return newPath;
  1376. }
  1377. function child(path, childPath) {
  1378. var canonicalChildPath = childPath
  1379. .split('/')
  1380. .filter(function (component) { return component.length > 0; })
  1381. .join('/');
  1382. if (path.length === 0) {
  1383. return canonicalChildPath;
  1384. }
  1385. else {
  1386. return path + '/' + canonicalChildPath;
  1387. }
  1388. }
  1389. /**
  1390. * Returns the last component of a path.
  1391. * '/foo/bar' -> 'bar'
  1392. * '/foo/bar/baz/' -> 'baz/'
  1393. * '/a' -> 'a'
  1394. */
  1395. function lastComponent(path) {
  1396. var index = path.lastIndexOf('/', path.length - 2);
  1397. if (index === -1) {
  1398. return path;
  1399. }
  1400. else {
  1401. return path.slice(index + 1);
  1402. }
  1403. }
  1404. /**
  1405. * @license
  1406. * Copyright 2017 Google LLC
  1407. *
  1408. * Licensed under the Apache License, Version 2.0 (the "License");
  1409. * you may not use this file except in compliance with the License.
  1410. * You may obtain a copy of the License at
  1411. *
  1412. * http://www.apache.org/licenses/LICENSE-2.0
  1413. *
  1414. * Unless required by applicable law or agreed to in writing, software
  1415. * distributed under the License is distributed on an "AS IS" BASIS,
  1416. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1417. * See the License for the specific language governing permissions and
  1418. * limitations under the License.
  1419. */
  1420. function noXform_(metadata, value) {
  1421. return value;
  1422. }
  1423. var Mapping = /** @class */ (function () {
  1424. function Mapping(server, local, writable, xform) {
  1425. this.server = server;
  1426. this.local = local || server;
  1427. this.writable = !!writable;
  1428. this.xform = xform || noXform_;
  1429. }
  1430. return Mapping;
  1431. }());
  1432. var mappings_ = null;
  1433. function xformPath(fullPath) {
  1434. if (!isString(fullPath) || fullPath.length < 2) {
  1435. return fullPath;
  1436. }
  1437. else {
  1438. return lastComponent(fullPath);
  1439. }
  1440. }
  1441. function getMappings() {
  1442. if (mappings_) {
  1443. return mappings_;
  1444. }
  1445. var mappings = [];
  1446. mappings.push(new Mapping('bucket'));
  1447. mappings.push(new Mapping('generation'));
  1448. mappings.push(new Mapping('metageneration'));
  1449. mappings.push(new Mapping('name', 'fullPath', true));
  1450. function mappingsXformPath(_metadata, fullPath) {
  1451. return xformPath(fullPath);
  1452. }
  1453. var nameMapping = new Mapping('name');
  1454. nameMapping.xform = mappingsXformPath;
  1455. mappings.push(nameMapping);
  1456. /**
  1457. * Coerces the second param to a number, if it is defined.
  1458. */
  1459. function xformSize(_metadata, size) {
  1460. if (size !== undefined) {
  1461. return Number(size);
  1462. }
  1463. else {
  1464. return size;
  1465. }
  1466. }
  1467. var sizeMapping = new Mapping('size');
  1468. sizeMapping.xform = xformSize;
  1469. mappings.push(sizeMapping);
  1470. mappings.push(new Mapping('timeCreated'));
  1471. mappings.push(new Mapping('updated'));
  1472. mappings.push(new Mapping('md5Hash', null, true));
  1473. mappings.push(new Mapping('cacheControl', null, true));
  1474. mappings.push(new Mapping('contentDisposition', null, true));
  1475. mappings.push(new Mapping('contentEncoding', null, true));
  1476. mappings.push(new Mapping('contentLanguage', null, true));
  1477. mappings.push(new Mapping('contentType', null, true));
  1478. mappings.push(new Mapping('metadata', 'customMetadata', true));
  1479. mappings_ = mappings;
  1480. return mappings_;
  1481. }
  1482. function addRef(metadata, service) {
  1483. function generateRef() {
  1484. var bucket = metadata['bucket'];
  1485. var path = metadata['fullPath'];
  1486. var loc = new Location(bucket, path);
  1487. return service._makeStorageReference(loc);
  1488. }
  1489. Object.defineProperty(metadata, 'ref', { get: generateRef });
  1490. }
  1491. function fromResource(service, resource, mappings) {
  1492. var metadata = {};
  1493. metadata['type'] = 'file';
  1494. var len = mappings.length;
  1495. for (var i = 0; i < len; i++) {
  1496. var mapping = mappings[i];
  1497. metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);
  1498. }
  1499. addRef(metadata, service);
  1500. return metadata;
  1501. }
  1502. function fromResourceString(service, resourceString, mappings) {
  1503. var obj = jsonObjectOrNull(resourceString);
  1504. if (obj === null) {
  1505. return null;
  1506. }
  1507. var resource = obj;
  1508. return fromResource(service, resource, mappings);
  1509. }
  1510. function downloadUrlFromResourceString(metadata, resourceString, host, protocol) {
  1511. var obj = jsonObjectOrNull(resourceString);
  1512. if (obj === null) {
  1513. return null;
  1514. }
  1515. if (!isString(obj['downloadTokens'])) {
  1516. // This can happen if objects are uploaded through GCS and retrieved
  1517. // through list, so we don't want to throw an Error.
  1518. return null;
  1519. }
  1520. var tokens = obj['downloadTokens'];
  1521. if (tokens.length === 0) {
  1522. return null;
  1523. }
  1524. var encode = encodeURIComponent;
  1525. var tokensList = tokens.split(',');
  1526. var urls = tokensList.map(function (token) {
  1527. var bucket = metadata['bucket'];
  1528. var path = metadata['fullPath'];
  1529. var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);
  1530. var base = makeUrl(urlPart, host, protocol);
  1531. var queryString = makeQueryString({
  1532. alt: 'media',
  1533. token: token
  1534. });
  1535. return base + queryString;
  1536. });
  1537. return urls[0];
  1538. }
  1539. function toResourceString(metadata, mappings) {
  1540. var resource = {};
  1541. var len = mappings.length;
  1542. for (var i = 0; i < len; i++) {
  1543. var mapping = mappings[i];
  1544. if (mapping.writable) {
  1545. resource[mapping.server] = metadata[mapping.local];
  1546. }
  1547. }
  1548. return JSON.stringify(resource);
  1549. }
  1550. /**
  1551. * @license
  1552. * Copyright 2019 Google LLC
  1553. *
  1554. * Licensed under the Apache License, Version 2.0 (the "License");
  1555. * you may not use this file except in compliance with the License.
  1556. * You may obtain a copy of the License at
  1557. *
  1558. * http://www.apache.org/licenses/LICENSE-2.0
  1559. *
  1560. * Unless required by applicable law or agreed to in writing, software
  1561. * distributed under the License is distributed on an "AS IS" BASIS,
  1562. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1563. * See the License for the specific language governing permissions and
  1564. * limitations under the License.
  1565. */
  1566. var PREFIXES_KEY = 'prefixes';
  1567. var ITEMS_KEY = 'items';
  1568. function fromBackendResponse(service, bucket, resource) {
  1569. var listResult = {
  1570. prefixes: [],
  1571. items: [],
  1572. nextPageToken: resource['nextPageToken']
  1573. };
  1574. if (resource[PREFIXES_KEY]) {
  1575. for (var _i = 0, _a = resource[PREFIXES_KEY]; _i < _a.length; _i++) {
  1576. var path = _a[_i];
  1577. var pathWithoutTrailingSlash = path.replace(/\/$/, '');
  1578. var reference = service._makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));
  1579. listResult.prefixes.push(reference);
  1580. }
  1581. }
  1582. if (resource[ITEMS_KEY]) {
  1583. for (var _b = 0, _c = resource[ITEMS_KEY]; _b < _c.length; _b++) {
  1584. var item = _c[_b];
  1585. var reference = service._makeStorageReference(new Location(bucket, item['name']));
  1586. listResult.items.push(reference);
  1587. }
  1588. }
  1589. return listResult;
  1590. }
  1591. function fromResponseString(service, bucket, resourceString) {
  1592. var obj = jsonObjectOrNull(resourceString);
  1593. if (obj === null) {
  1594. return null;
  1595. }
  1596. var resource = obj;
  1597. return fromBackendResponse(service, bucket, resource);
  1598. }
  1599. /**
  1600. * Contains a fully specified request.
  1601. *
  1602. * @param I - the type of the backend's network response.
  1603. * @param O - the output response type used by the rest of the SDK.
  1604. */
  1605. var RequestInfo = /** @class */ (function () {
  1606. function RequestInfo(url, method,
  1607. /**
  1608. * Returns the value with which to resolve the request's promise. Only called
  1609. * if the request is successful. Throw from this function to reject the
  1610. * returned Request's promise with the thrown error.
  1611. * Note: The XhrIo passed to this function may be reused after this callback
  1612. * returns. Do not keep a reference to it in any way.
  1613. */
  1614. handler, timeout) {
  1615. this.url = url;
  1616. this.method = method;
  1617. this.handler = handler;
  1618. this.timeout = timeout;
  1619. this.urlParams = {};
  1620. this.headers = {};
  1621. this.body = null;
  1622. this.errorHandler = null;
  1623. /**
  1624. * Called with the current number of bytes uploaded and total size (-1 if not
  1625. * computable) of the request body (i.e. used to report upload progress).
  1626. */
  1627. this.progressCallback = null;
  1628. this.successCodes = [200];
  1629. this.additionalRetryCodes = [];
  1630. }
  1631. return RequestInfo;
  1632. }());
  1633. /**
  1634. * @license
  1635. * Copyright 2017 Google LLC
  1636. *
  1637. * Licensed under the Apache License, Version 2.0 (the "License");
  1638. * you may not use this file except in compliance with the License.
  1639. * You may obtain a copy of the License at
  1640. *
  1641. * http://www.apache.org/licenses/LICENSE-2.0
  1642. *
  1643. * Unless required by applicable law or agreed to in writing, software
  1644. * distributed under the License is distributed on an "AS IS" BASIS,
  1645. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1646. * See the License for the specific language governing permissions and
  1647. * limitations under the License.
  1648. */
  1649. /**
  1650. * Throws the UNKNOWN StorageError if cndn is false.
  1651. */
  1652. function handlerCheck(cndn) {
  1653. if (!cndn) {
  1654. throw unknown();
  1655. }
  1656. }
  1657. function metadataHandler(service, mappings) {
  1658. function handler(xhr, text) {
  1659. var metadata = fromResourceString(service, text, mappings);
  1660. handlerCheck(metadata !== null);
  1661. return metadata;
  1662. }
  1663. return handler;
  1664. }
  1665. function listHandler(service, bucket) {
  1666. function handler(xhr, text) {
  1667. var listResult = fromResponseString(service, bucket, text);
  1668. handlerCheck(listResult !== null);
  1669. return listResult;
  1670. }
  1671. return handler;
  1672. }
  1673. function downloadUrlHandler(service, mappings) {
  1674. function handler(xhr, text) {
  1675. var metadata = fromResourceString(service, text, mappings);
  1676. handlerCheck(metadata !== null);
  1677. return downloadUrlFromResourceString(metadata, text, service.host, service._protocol);
  1678. }
  1679. return handler;
  1680. }
  1681. function sharedErrorHandler(location) {
  1682. function errorHandler(xhr, err) {
  1683. var newErr;
  1684. if (xhr.getStatus() === 401) {
  1685. if (
  1686. // This exact message string is the only consistent part of the
  1687. // server's error response that identifies it as an App Check error.
  1688. xhr.getErrorText().includes('Firebase App Check token is invalid')) {
  1689. newErr = unauthorizedApp();
  1690. }
  1691. else {
  1692. newErr = unauthenticated();
  1693. }
  1694. }
  1695. else {
  1696. if (xhr.getStatus() === 402) {
  1697. newErr = quotaExceeded(location.bucket);
  1698. }
  1699. else {
  1700. if (xhr.getStatus() === 403) {
  1701. newErr = unauthorized(location.path);
  1702. }
  1703. else {
  1704. newErr = err;
  1705. }
  1706. }
  1707. }
  1708. newErr.status = xhr.getStatus();
  1709. newErr.serverResponse = err.serverResponse;
  1710. return newErr;
  1711. }
  1712. return errorHandler;
  1713. }
  1714. function objectErrorHandler(location) {
  1715. var shared = sharedErrorHandler(location);
  1716. function errorHandler(xhr, err) {
  1717. var newErr = shared(xhr, err);
  1718. if (xhr.getStatus() === 404) {
  1719. newErr = objectNotFound(location.path);
  1720. }
  1721. newErr.serverResponse = err.serverResponse;
  1722. return newErr;
  1723. }
  1724. return errorHandler;
  1725. }
  1726. function getMetadata$2(service, location, mappings) {
  1727. var urlPart = location.fullServerUrl();
  1728. var url = makeUrl(urlPart, service.host, service._protocol);
  1729. var method = 'GET';
  1730. var timeout = service.maxOperationRetryTime;
  1731. var requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  1732. requestInfo.errorHandler = objectErrorHandler(location);
  1733. return requestInfo;
  1734. }
  1735. function list$2(service, location, delimiter, pageToken, maxResults) {
  1736. var urlParams = {};
  1737. if (location.isRoot) {
  1738. urlParams['prefix'] = '';
  1739. }
  1740. else {
  1741. urlParams['prefix'] = location.path + '/';
  1742. }
  1743. if (delimiter && delimiter.length > 0) {
  1744. urlParams['delimiter'] = delimiter;
  1745. }
  1746. if (pageToken) {
  1747. urlParams['pageToken'] = pageToken;
  1748. }
  1749. if (maxResults) {
  1750. urlParams['maxResults'] = maxResults;
  1751. }
  1752. var urlPart = location.bucketOnlyServerUrl();
  1753. var url = makeUrl(urlPart, service.host, service._protocol);
  1754. var method = 'GET';
  1755. var timeout = service.maxOperationRetryTime;
  1756. var requestInfo = new RequestInfo(url, method, listHandler(service, location.bucket), timeout);
  1757. requestInfo.urlParams = urlParams;
  1758. requestInfo.errorHandler = sharedErrorHandler(location);
  1759. return requestInfo;
  1760. }
  1761. function getBytes$1(service, location, maxDownloadSizeBytes) {
  1762. var urlPart = location.fullServerUrl();
  1763. var url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';
  1764. var method = 'GET';
  1765. var timeout = service.maxOperationRetryTime;
  1766. var requestInfo = new RequestInfo(url, method, function (_, data) { return data; }, timeout);
  1767. requestInfo.errorHandler = objectErrorHandler(location);
  1768. if (maxDownloadSizeBytes !== undefined) {
  1769. requestInfo.headers['Range'] = "bytes=0-".concat(maxDownloadSizeBytes);
  1770. requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];
  1771. }
  1772. return requestInfo;
  1773. }
  1774. function getDownloadUrl(service, location, mappings) {
  1775. var urlPart = location.fullServerUrl();
  1776. var url = makeUrl(urlPart, service.host, service._protocol);
  1777. var method = 'GET';
  1778. var timeout = service.maxOperationRetryTime;
  1779. var requestInfo = new RequestInfo(url, method, downloadUrlHandler(service, mappings), timeout);
  1780. requestInfo.errorHandler = objectErrorHandler(location);
  1781. return requestInfo;
  1782. }
  1783. function updateMetadata$2(service, location, metadata, mappings) {
  1784. var urlPart = location.fullServerUrl();
  1785. var url = makeUrl(urlPart, service.host, service._protocol);
  1786. var method = 'PATCH';
  1787. var body = toResourceString(metadata, mappings);
  1788. var headers = { 'Content-Type': 'application/json; charset=utf-8' };
  1789. var timeout = service.maxOperationRetryTime;
  1790. var requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  1791. requestInfo.headers = headers;
  1792. requestInfo.body = body;
  1793. requestInfo.errorHandler = objectErrorHandler(location);
  1794. return requestInfo;
  1795. }
  1796. function deleteObject$2(service, location) {
  1797. var urlPart = location.fullServerUrl();
  1798. var url = makeUrl(urlPart, service.host, service._protocol);
  1799. var method = 'DELETE';
  1800. var timeout = service.maxOperationRetryTime;
  1801. function handler(_xhr, _text) { }
  1802. var requestInfo = new RequestInfo(url, method, handler, timeout);
  1803. requestInfo.successCodes = [200, 204];
  1804. requestInfo.errorHandler = objectErrorHandler(location);
  1805. return requestInfo;
  1806. }
  1807. function determineContentType_(metadata, blob) {
  1808. return ((metadata && metadata['contentType']) ||
  1809. (blob && blob.type()) ||
  1810. 'application/octet-stream');
  1811. }
  1812. function metadataForUpload_(location, blob, metadata) {
  1813. var metadataClone = Object.assign({}, metadata);
  1814. metadataClone['fullPath'] = location.path;
  1815. metadataClone['size'] = blob.size();
  1816. if (!metadataClone['contentType']) {
  1817. metadataClone['contentType'] = determineContentType_(null, blob);
  1818. }
  1819. return metadataClone;
  1820. }
  1821. /**
  1822. * Prepare RequestInfo for uploads as Content-Type: multipart.
  1823. */
  1824. function multipartUpload(service, location, mappings, blob, metadata) {
  1825. var urlPart = location.bucketOnlyServerUrl();
  1826. var headers = {
  1827. 'X-Goog-Upload-Protocol': 'multipart'
  1828. };
  1829. function genBoundary() {
  1830. var str = '';
  1831. for (var i = 0; i < 2; i++) {
  1832. str = str + Math.random().toString().slice(2);
  1833. }
  1834. return str;
  1835. }
  1836. var boundary = genBoundary();
  1837. headers['Content-Type'] = 'multipart/related; boundary=' + boundary;
  1838. var metadata_ = metadataForUpload_(location, blob, metadata);
  1839. var metadataString = toResourceString(metadata_, mappings);
  1840. var preBlobPart = '--' +
  1841. boundary +
  1842. '\r\n' +
  1843. 'Content-Type: application/json; charset=utf-8\r\n\r\n' +
  1844. metadataString +
  1845. '\r\n--' +
  1846. boundary +
  1847. '\r\n' +
  1848. 'Content-Type: ' +
  1849. metadata_['contentType'] +
  1850. '\r\n\r\n';
  1851. var postBlobPart = '\r\n--' + boundary + '--';
  1852. var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);
  1853. if (body === null) {
  1854. throw cannotSliceBlob();
  1855. }
  1856. var urlParams = { name: metadata_['fullPath'] };
  1857. var url = makeUrl(urlPart, service.host, service._protocol);
  1858. var method = 'POST';
  1859. var timeout = service.maxUploadRetryTime;
  1860. var requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  1861. requestInfo.urlParams = urlParams;
  1862. requestInfo.headers = headers;
  1863. requestInfo.body = body.uploadData();
  1864. requestInfo.errorHandler = sharedErrorHandler(location);
  1865. return requestInfo;
  1866. }
  1867. /**
  1868. * @param current The number of bytes that have been uploaded so far.
  1869. * @param total The total number of bytes in the upload.
  1870. * @param opt_finalized True if the server has finished the upload.
  1871. * @param opt_metadata The upload metadata, should
  1872. * only be passed if opt_finalized is true.
  1873. */
  1874. var ResumableUploadStatus = /** @class */ (function () {
  1875. function ResumableUploadStatus(current, total, finalized, metadata) {
  1876. this.current = current;
  1877. this.total = total;
  1878. this.finalized = !!finalized;
  1879. this.metadata = metadata || null;
  1880. }
  1881. return ResumableUploadStatus;
  1882. }());
  1883. function checkResumeHeader_(xhr, allowed) {
  1884. var status = null;
  1885. try {
  1886. status = xhr.getResponseHeader('X-Goog-Upload-Status');
  1887. }
  1888. catch (e) {
  1889. handlerCheck(false);
  1890. }
  1891. var allowedStatus = allowed || ['active'];
  1892. handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);
  1893. return status;
  1894. }
  1895. function createResumableUpload(service, location, mappings, blob, metadata) {
  1896. var urlPart = location.bucketOnlyServerUrl();
  1897. var metadataForUpload = metadataForUpload_(location, blob, metadata);
  1898. var urlParams = { name: metadataForUpload['fullPath'] };
  1899. var url = makeUrl(urlPart, service.host, service._protocol);
  1900. var method = 'POST';
  1901. var headers = {
  1902. 'X-Goog-Upload-Protocol': 'resumable',
  1903. 'X-Goog-Upload-Command': 'start',
  1904. 'X-Goog-Upload-Header-Content-Length': "".concat(blob.size()),
  1905. 'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType'],
  1906. 'Content-Type': 'application/json; charset=utf-8'
  1907. };
  1908. var body = toResourceString(metadataForUpload, mappings);
  1909. var timeout = service.maxUploadRetryTime;
  1910. function handler(xhr) {
  1911. checkResumeHeader_(xhr);
  1912. var url;
  1913. try {
  1914. url = xhr.getResponseHeader('X-Goog-Upload-URL');
  1915. }
  1916. catch (e) {
  1917. handlerCheck(false);
  1918. }
  1919. handlerCheck(isString(url));
  1920. return url;
  1921. }
  1922. var requestInfo = new RequestInfo(url, method, handler, timeout);
  1923. requestInfo.urlParams = urlParams;
  1924. requestInfo.headers = headers;
  1925. requestInfo.body = body;
  1926. requestInfo.errorHandler = sharedErrorHandler(location);
  1927. return requestInfo;
  1928. }
  1929. /**
  1930. * @param url From a call to fbs.requests.createResumableUpload.
  1931. */
  1932. function getResumableUploadStatus(service, location, url, blob) {
  1933. var headers = { 'X-Goog-Upload-Command': 'query' };
  1934. function handler(xhr) {
  1935. var status = checkResumeHeader_(xhr, ['active', 'final']);
  1936. var sizeString = null;
  1937. try {
  1938. sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');
  1939. }
  1940. catch (e) {
  1941. handlerCheck(false);
  1942. }
  1943. if (!sizeString) {
  1944. // null or empty string
  1945. handlerCheck(false);
  1946. }
  1947. var size = Number(sizeString);
  1948. handlerCheck(!isNaN(size));
  1949. return new ResumableUploadStatus(size, blob.size(), status === 'final');
  1950. }
  1951. var method = 'POST';
  1952. var timeout = service.maxUploadRetryTime;
  1953. var requestInfo = new RequestInfo(url, method, handler, timeout);
  1954. requestInfo.headers = headers;
  1955. requestInfo.errorHandler = sharedErrorHandler(location);
  1956. return requestInfo;
  1957. }
  1958. /**
  1959. * Any uploads via the resumable upload API must transfer a number of bytes
  1960. * that is a multiple of this number.
  1961. */
  1962. var RESUMABLE_UPLOAD_CHUNK_SIZE = 256 * 1024;
  1963. /**
  1964. * @param url From a call to fbs.requests.createResumableUpload.
  1965. * @param chunkSize Number of bytes to upload.
  1966. * @param status The previous status.
  1967. * If not passed or null, we start from the beginning.
  1968. * @throws fbs.Error If the upload is already complete, the passed in status
  1969. * has a final size inconsistent with the blob, or the blob cannot be sliced
  1970. * for upload.
  1971. */
  1972. function continueResumableUpload(location, service, url, blob, chunkSize, mappings, status, progressCallback) {
  1973. // TODO(andysoto): standardize on internal asserts
  1974. // assert(!(opt_status && opt_status.finalized));
  1975. var status_ = new ResumableUploadStatus(0, 0);
  1976. if (status) {
  1977. status_.current = status.current;
  1978. status_.total = status.total;
  1979. }
  1980. else {
  1981. status_.current = 0;
  1982. status_.total = blob.size();
  1983. }
  1984. if (blob.size() !== status_.total) {
  1985. throw serverFileWrongSize();
  1986. }
  1987. var bytesLeft = status_.total - status_.current;
  1988. var bytesToUpload = bytesLeft;
  1989. if (chunkSize > 0) {
  1990. bytesToUpload = Math.min(bytesToUpload, chunkSize);
  1991. }
  1992. var startByte = status_.current;
  1993. var endByte = startByte + bytesToUpload;
  1994. var uploadCommand = '';
  1995. if (bytesToUpload === 0) {
  1996. uploadCommand = 'finalize';
  1997. }
  1998. else if (bytesLeft === bytesToUpload) {
  1999. uploadCommand = 'upload, finalize';
  2000. }
  2001. else {
  2002. uploadCommand = 'upload';
  2003. }
  2004. var headers = {
  2005. 'X-Goog-Upload-Command': uploadCommand,
  2006. 'X-Goog-Upload-Offset': "".concat(status_.current)
  2007. };
  2008. var body = blob.slice(startByte, endByte);
  2009. if (body === null) {
  2010. throw cannotSliceBlob();
  2011. }
  2012. function handler(xhr, text) {
  2013. // TODO(andysoto): Verify the MD5 of each uploaded range:
  2014. // the 'x-range-md5' header comes back with status code 308 responses.
  2015. // We'll only be able to bail out though, because you can't re-upload a
  2016. // range that you previously uploaded.
  2017. var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);
  2018. var newCurrent = status_.current + bytesToUpload;
  2019. var size = blob.size();
  2020. var metadata;
  2021. if (uploadStatus === 'final') {
  2022. metadata = metadataHandler(service, mappings)(xhr, text);
  2023. }
  2024. else {
  2025. metadata = null;
  2026. }
  2027. return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);
  2028. }
  2029. var method = 'POST';
  2030. var timeout = service.maxUploadRetryTime;
  2031. var requestInfo = new RequestInfo(url, method, handler, timeout);
  2032. requestInfo.headers = headers;
  2033. requestInfo.body = body.uploadData();
  2034. requestInfo.progressCallback = progressCallback || null;
  2035. requestInfo.errorHandler = sharedErrorHandler(location);
  2036. return requestInfo;
  2037. }
  2038. /**
  2039. * @license
  2040. * Copyright 2017 Google LLC
  2041. *
  2042. * Licensed under the Apache License, Version 2.0 (the "License");
  2043. * you may not use this file except in compliance with the License.
  2044. * You may obtain a copy of the License at
  2045. *
  2046. * http://www.apache.org/licenses/LICENSE-2.0
  2047. *
  2048. * Unless required by applicable law or agreed to in writing, software
  2049. * distributed under the License is distributed on an "AS IS" BASIS,
  2050. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2051. * See the License for the specific language governing permissions and
  2052. * limitations under the License.
  2053. */
  2054. /**
  2055. * An event that is triggered on a task.
  2056. * @internal
  2057. */
  2058. var TaskEvent = {
  2059. /**
  2060. * For this event,
  2061. * <ul>
  2062. * <li>The `next` function is triggered on progress updates and when the
  2063. * task is paused/resumed with an `UploadTaskSnapshot` as the first
  2064. * argument.</li>
  2065. * <li>The `error` function is triggered if the upload is canceled or fails
  2066. * for another reason.</li>
  2067. * <li>The `complete` function is triggered if the upload completes
  2068. * successfully.</li>
  2069. * </ul>
  2070. */
  2071. STATE_CHANGED: 'state_changed'
  2072. };
  2073. // type keys = keyof TaskState
  2074. /**
  2075. * Represents the current state of a running upload.
  2076. * @internal
  2077. */
  2078. var TaskState = {
  2079. /** The task is currently transferring data. */
  2080. RUNNING: 'running',
  2081. /** The task was paused by the user. */
  2082. PAUSED: 'paused',
  2083. /** The task completed successfully. */
  2084. SUCCESS: 'success',
  2085. /** The task was canceled. */
  2086. CANCELED: 'canceled',
  2087. /** The task failed with an error. */
  2088. ERROR: 'error'
  2089. };
  2090. function taskStateFromInternalTaskState(state) {
  2091. switch (state) {
  2092. case "running" /* InternalTaskState.RUNNING */:
  2093. case "pausing" /* InternalTaskState.PAUSING */:
  2094. case "canceling" /* InternalTaskState.CANCELING */:
  2095. return TaskState.RUNNING;
  2096. case "paused" /* InternalTaskState.PAUSED */:
  2097. return TaskState.PAUSED;
  2098. case "success" /* InternalTaskState.SUCCESS */:
  2099. return TaskState.SUCCESS;
  2100. case "canceled" /* InternalTaskState.CANCELED */:
  2101. return TaskState.CANCELED;
  2102. case "error" /* InternalTaskState.ERROR */:
  2103. return TaskState.ERROR;
  2104. default:
  2105. // TODO(andysoto): assert(false);
  2106. return TaskState.ERROR;
  2107. }
  2108. }
  2109. /**
  2110. * @license
  2111. * Copyright 2017 Google LLC
  2112. *
  2113. * Licensed under the Apache License, Version 2.0 (the "License");
  2114. * you may not use this file except in compliance with the License.
  2115. * You may obtain a copy of the License at
  2116. *
  2117. * http://www.apache.org/licenses/LICENSE-2.0
  2118. *
  2119. * Unless required by applicable law or agreed to in writing, software
  2120. * distributed under the License is distributed on an "AS IS" BASIS,
  2121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2122. * See the License for the specific language governing permissions and
  2123. * limitations under the License.
  2124. */
  2125. var Observer = /** @class */ (function () {
  2126. function Observer(nextOrObserver, error, complete) {
  2127. var asFunctions = isFunction(nextOrObserver) || error != null || complete != null;
  2128. if (asFunctions) {
  2129. this.next = nextOrObserver;
  2130. this.error = error !== null && error !== void 0 ? error : undefined;
  2131. this.complete = complete !== null && complete !== void 0 ? complete : undefined;
  2132. }
  2133. else {
  2134. var observer = nextOrObserver;
  2135. this.next = observer.next;
  2136. this.error = observer.error;
  2137. this.complete = observer.complete;
  2138. }
  2139. }
  2140. return Observer;
  2141. }());
  2142. /**
  2143. * @license
  2144. * Copyright 2017 Google LLC
  2145. *
  2146. * Licensed under the Apache License, Version 2.0 (the "License");
  2147. * you may not use this file except in compliance with the License.
  2148. * You may obtain a copy of the License at
  2149. *
  2150. * http://www.apache.org/licenses/LICENSE-2.0
  2151. *
  2152. * Unless required by applicable law or agreed to in writing, software
  2153. * distributed under the License is distributed on an "AS IS" BASIS,
  2154. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2155. * See the License for the specific language governing permissions and
  2156. * limitations under the License.
  2157. */
  2158. /**
  2159. * Returns a function that invokes f with its arguments asynchronously as a
  2160. * microtask, i.e. as soon as possible after the current script returns back
  2161. * into browser code.
  2162. */
  2163. // eslint-disable-next-line @typescript-eslint/ban-types
  2164. function async(f) {
  2165. return function () {
  2166. var argsToForward = [];
  2167. for (var _i = 0; _i < arguments.length; _i++) {
  2168. argsToForward[_i] = arguments[_i];
  2169. }
  2170. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2171. Promise.resolve().then(function () { return f.apply(void 0, argsToForward); });
  2172. };
  2173. }
  2174. /**
  2175. * @license
  2176. * Copyright 2017 Google LLC
  2177. *
  2178. * Licensed under the Apache License, Version 2.0 (the "License");
  2179. * you may not use this file except in compliance with the License.
  2180. * You may obtain a copy of the License at
  2181. *
  2182. * http://www.apache.org/licenses/LICENSE-2.0
  2183. *
  2184. * Unless required by applicable law or agreed to in writing, software
  2185. * distributed under the License is distributed on an "AS IS" BASIS,
  2186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2187. * See the License for the specific language governing permissions and
  2188. * limitations under the License.
  2189. */
  2190. /** An override for the text-based Connection. Used in tests. */
  2191. var textFactoryOverride = null;
  2192. /**
  2193. * Network layer for browsers. We use this instead of goog.net.XhrIo because
  2194. * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.
  2195. */
  2196. var XhrConnection = /** @class */ (function () {
  2197. function XhrConnection() {
  2198. var _this = this;
  2199. this.sent_ = false;
  2200. this.xhr_ = new XMLHttpRequest();
  2201. this.initXhr();
  2202. this.errorCode_ = ErrorCode.NO_ERROR;
  2203. this.sendPromise_ = new Promise(function (resolve) {
  2204. _this.xhr_.addEventListener('abort', function () {
  2205. _this.errorCode_ = ErrorCode.ABORT;
  2206. resolve();
  2207. });
  2208. _this.xhr_.addEventListener('error', function () {
  2209. _this.errorCode_ = ErrorCode.NETWORK_ERROR;
  2210. resolve();
  2211. });
  2212. _this.xhr_.addEventListener('load', function () {
  2213. resolve();
  2214. });
  2215. });
  2216. }
  2217. XhrConnection.prototype.send = function (url, method, body, headers) {
  2218. if (this.sent_) {
  2219. throw internalError('cannot .send() more than once');
  2220. }
  2221. this.sent_ = true;
  2222. this.xhr_.open(method, url, true);
  2223. if (headers !== undefined) {
  2224. for (var key in headers) {
  2225. if (headers.hasOwnProperty(key)) {
  2226. this.xhr_.setRequestHeader(key, headers[key].toString());
  2227. }
  2228. }
  2229. }
  2230. if (body !== undefined) {
  2231. this.xhr_.send(body);
  2232. }
  2233. else {
  2234. this.xhr_.send();
  2235. }
  2236. return this.sendPromise_;
  2237. };
  2238. XhrConnection.prototype.getErrorCode = function () {
  2239. if (!this.sent_) {
  2240. throw internalError('cannot .getErrorCode() before sending');
  2241. }
  2242. return this.errorCode_;
  2243. };
  2244. XhrConnection.prototype.getStatus = function () {
  2245. if (!this.sent_) {
  2246. throw internalError('cannot .getStatus() before sending');
  2247. }
  2248. try {
  2249. return this.xhr_.status;
  2250. }
  2251. catch (e) {
  2252. return -1;
  2253. }
  2254. };
  2255. XhrConnection.prototype.getResponse = function () {
  2256. if (!this.sent_) {
  2257. throw internalError('cannot .getResponse() before sending');
  2258. }
  2259. return this.xhr_.response;
  2260. };
  2261. XhrConnection.prototype.getErrorText = function () {
  2262. if (!this.sent_) {
  2263. throw internalError('cannot .getErrorText() before sending');
  2264. }
  2265. return this.xhr_.statusText;
  2266. };
  2267. /** Aborts the request. */
  2268. XhrConnection.prototype.abort = function () {
  2269. this.xhr_.abort();
  2270. };
  2271. XhrConnection.prototype.getResponseHeader = function (header) {
  2272. return this.xhr_.getResponseHeader(header);
  2273. };
  2274. XhrConnection.prototype.addUploadProgressListener = function (listener) {
  2275. if (this.xhr_.upload != null) {
  2276. this.xhr_.upload.addEventListener('progress', listener);
  2277. }
  2278. };
  2279. XhrConnection.prototype.removeUploadProgressListener = function (listener) {
  2280. if (this.xhr_.upload != null) {
  2281. this.xhr_.upload.removeEventListener('progress', listener);
  2282. }
  2283. };
  2284. return XhrConnection;
  2285. }());
  2286. var XhrTextConnection = /** @class */ (function (_super) {
  2287. tslib.__extends(XhrTextConnection, _super);
  2288. function XhrTextConnection() {
  2289. return _super !== null && _super.apply(this, arguments) || this;
  2290. }
  2291. XhrTextConnection.prototype.initXhr = function () {
  2292. this.xhr_.responseType = 'text';
  2293. };
  2294. return XhrTextConnection;
  2295. }(XhrConnection));
  2296. function newTextConnection() {
  2297. return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();
  2298. }
  2299. var XhrBytesConnection = /** @class */ (function (_super) {
  2300. tslib.__extends(XhrBytesConnection, _super);
  2301. function XhrBytesConnection() {
  2302. return _super !== null && _super.apply(this, arguments) || this;
  2303. }
  2304. XhrBytesConnection.prototype.initXhr = function () {
  2305. this.xhr_.responseType = 'arraybuffer';
  2306. };
  2307. return XhrBytesConnection;
  2308. }(XhrConnection));
  2309. function newBytesConnection() {
  2310. return new XhrBytesConnection();
  2311. }
  2312. var XhrBlobConnection = /** @class */ (function (_super) {
  2313. tslib.__extends(XhrBlobConnection, _super);
  2314. function XhrBlobConnection() {
  2315. return _super !== null && _super.apply(this, arguments) || this;
  2316. }
  2317. XhrBlobConnection.prototype.initXhr = function () {
  2318. this.xhr_.responseType = 'blob';
  2319. };
  2320. return XhrBlobConnection;
  2321. }(XhrConnection));
  2322. function newBlobConnection() {
  2323. return new XhrBlobConnection();
  2324. }
  2325. /**
  2326. * @license
  2327. * Copyright 2017 Google LLC
  2328. *
  2329. * Licensed under the Apache License, Version 2.0 (the "License");
  2330. * you may not use this file except in compliance with the License.
  2331. * You may obtain a copy of the License at
  2332. *
  2333. * http://www.apache.org/licenses/LICENSE-2.0
  2334. *
  2335. * Unless required by applicable law or agreed to in writing, software
  2336. * distributed under the License is distributed on an "AS IS" BASIS,
  2337. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2338. * See the License for the specific language governing permissions and
  2339. * limitations under the License.
  2340. */
  2341. /**
  2342. * Represents a blob being uploaded. Can be used to pause/resume/cancel the
  2343. * upload and manage callbacks for various events.
  2344. * @internal
  2345. */
  2346. var UploadTask = /** @class */ (function () {
  2347. /**
  2348. * @param ref - The firebaseStorage.Reference object this task came
  2349. * from, untyped to avoid cyclic dependencies.
  2350. * @param blob - The blob to upload.
  2351. */
  2352. function UploadTask(ref, blob, metadata) {
  2353. if (metadata === void 0) { metadata = null; }
  2354. var _this = this;
  2355. /**
  2356. * Number of bytes transferred so far.
  2357. */
  2358. this._transferred = 0;
  2359. this._needToFetchStatus = false;
  2360. this._needToFetchMetadata = false;
  2361. this._observers = [];
  2362. this._error = undefined;
  2363. this._uploadUrl = undefined;
  2364. this._request = undefined;
  2365. this._chunkMultiplier = 1;
  2366. this._resolve = undefined;
  2367. this._reject = undefined;
  2368. this._ref = ref;
  2369. this._blob = blob;
  2370. this._metadata = metadata;
  2371. this._mappings = getMappings();
  2372. this._resumable = this._shouldDoResumable(this._blob);
  2373. this._state = "running" /* InternalTaskState.RUNNING */;
  2374. this._errorHandler = function (error) {
  2375. _this._request = undefined;
  2376. _this._chunkMultiplier = 1;
  2377. if (error._codeEquals(exports.StorageErrorCode.CANCELED)) {
  2378. _this._needToFetchStatus = true;
  2379. _this.completeTransitions_();
  2380. }
  2381. else {
  2382. var backoffExpired = _this.isExponentialBackoffExpired();
  2383. if (isRetryStatusCode(error.status, [])) {
  2384. if (backoffExpired) {
  2385. error = retryLimitExceeded();
  2386. }
  2387. else {
  2388. _this.sleepTime = Math.max(_this.sleepTime * 2, DEFAULT_MIN_SLEEP_TIME_MILLIS);
  2389. _this._needToFetchStatus = true;
  2390. _this.completeTransitions_();
  2391. return;
  2392. }
  2393. }
  2394. _this._error = error;
  2395. _this._transition("error" /* InternalTaskState.ERROR */);
  2396. }
  2397. };
  2398. this._metadataErrorHandler = function (error) {
  2399. _this._request = undefined;
  2400. if (error._codeEquals(exports.StorageErrorCode.CANCELED)) {
  2401. _this.completeTransitions_();
  2402. }
  2403. else {
  2404. _this._error = error;
  2405. _this._transition("error" /* InternalTaskState.ERROR */);
  2406. }
  2407. };
  2408. this.sleepTime = 0;
  2409. this.maxSleepTime = this._ref.storage.maxUploadRetryTime;
  2410. this._promise = new Promise(function (resolve, reject) {
  2411. _this._resolve = resolve;
  2412. _this._reject = reject;
  2413. _this._start();
  2414. });
  2415. // Prevent uncaught rejections on the internal promise from bubbling out
  2416. // to the top level with a dummy handler.
  2417. this._promise.then(null, function () { });
  2418. }
  2419. UploadTask.prototype.isExponentialBackoffExpired = function () {
  2420. return this.sleepTime > this.maxSleepTime;
  2421. };
  2422. UploadTask.prototype._makeProgressCallback = function () {
  2423. var _this = this;
  2424. var sizeBefore = this._transferred;
  2425. return function (loaded) { return _this._updateProgress(sizeBefore + loaded); };
  2426. };
  2427. UploadTask.prototype._shouldDoResumable = function (blob) {
  2428. return blob.size() > 256 * 1024;
  2429. };
  2430. UploadTask.prototype._start = function () {
  2431. var _this = this;
  2432. if (this._state !== "running" /* InternalTaskState.RUNNING */) {
  2433. // This can happen if someone pauses us in a resume callback, for example.
  2434. return;
  2435. }
  2436. if (this._request !== undefined) {
  2437. return;
  2438. }
  2439. if (this._resumable) {
  2440. if (this._uploadUrl === undefined) {
  2441. this._createResumable();
  2442. }
  2443. else {
  2444. if (this._needToFetchStatus) {
  2445. this._fetchStatus();
  2446. }
  2447. else {
  2448. if (this._needToFetchMetadata) {
  2449. // Happens if we miss the metadata on upload completion.
  2450. this._fetchMetadata();
  2451. }
  2452. else {
  2453. this.pendingTimeout = setTimeout(function () {
  2454. _this.pendingTimeout = undefined;
  2455. _this._continueUpload();
  2456. }, this.sleepTime);
  2457. }
  2458. }
  2459. }
  2460. }
  2461. else {
  2462. this._oneShotUpload();
  2463. }
  2464. };
  2465. UploadTask.prototype._resolveToken = function (callback) {
  2466. var _this = this;
  2467. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2468. Promise.all([
  2469. this._ref.storage._getAuthToken(),
  2470. this._ref.storage._getAppCheckToken()
  2471. ]).then(function (_a) {
  2472. var authToken = _a[0], appCheckToken = _a[1];
  2473. switch (_this._state) {
  2474. case "running" /* InternalTaskState.RUNNING */:
  2475. callback(authToken, appCheckToken);
  2476. break;
  2477. case "canceling" /* InternalTaskState.CANCELING */:
  2478. _this._transition("canceled" /* InternalTaskState.CANCELED */);
  2479. break;
  2480. case "pausing" /* InternalTaskState.PAUSING */:
  2481. _this._transition("paused" /* InternalTaskState.PAUSED */);
  2482. break;
  2483. }
  2484. });
  2485. };
  2486. // TODO(andysoto): assert false
  2487. UploadTask.prototype._createResumable = function () {
  2488. var _this = this;
  2489. this._resolveToken(function (authToken, appCheckToken) {
  2490. var requestInfo = createResumableUpload(_this._ref.storage, _this._ref._location, _this._mappings, _this._blob, _this._metadata);
  2491. var createRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2492. _this._request = createRequest;
  2493. createRequest.getPromise().then(function (url) {
  2494. _this._request = undefined;
  2495. _this._uploadUrl = url;
  2496. _this._needToFetchStatus = false;
  2497. _this.completeTransitions_();
  2498. }, _this._errorHandler);
  2499. });
  2500. };
  2501. UploadTask.prototype._fetchStatus = function () {
  2502. var _this = this;
  2503. // TODO(andysoto): assert(this.uploadUrl_ !== null);
  2504. var url = this._uploadUrl;
  2505. this._resolveToken(function (authToken, appCheckToken) {
  2506. var requestInfo = getResumableUploadStatus(_this._ref.storage, _this._ref._location, url, _this._blob);
  2507. var statusRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2508. _this._request = statusRequest;
  2509. statusRequest.getPromise().then(function (status) {
  2510. status = status;
  2511. _this._request = undefined;
  2512. _this._updateProgress(status.current);
  2513. _this._needToFetchStatus = false;
  2514. if (status.finalized) {
  2515. _this._needToFetchMetadata = true;
  2516. }
  2517. _this.completeTransitions_();
  2518. }, _this._errorHandler);
  2519. });
  2520. };
  2521. UploadTask.prototype._continueUpload = function () {
  2522. var _this = this;
  2523. var chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
  2524. var status = new ResumableUploadStatus(this._transferred, this._blob.size());
  2525. // TODO(andysoto): assert(this.uploadUrl_ !== null);
  2526. var url = this._uploadUrl;
  2527. this._resolveToken(function (authToken, appCheckToken) {
  2528. var requestInfo;
  2529. try {
  2530. requestInfo = continueResumableUpload(_this._ref._location, _this._ref.storage, url, _this._blob, chunkSize, _this._mappings, status, _this._makeProgressCallback());
  2531. }
  2532. catch (e) {
  2533. _this._error = e;
  2534. _this._transition("error" /* InternalTaskState.ERROR */);
  2535. return;
  2536. }
  2537. var uploadRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken,
  2538. /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.
  2539. );
  2540. _this._request = uploadRequest;
  2541. uploadRequest.getPromise().then(function (newStatus) {
  2542. _this._increaseMultiplier();
  2543. _this._request = undefined;
  2544. _this._updateProgress(newStatus.current);
  2545. if (newStatus.finalized) {
  2546. _this._metadata = newStatus.metadata;
  2547. _this._transition("success" /* InternalTaskState.SUCCESS */);
  2548. }
  2549. else {
  2550. _this.completeTransitions_();
  2551. }
  2552. }, _this._errorHandler);
  2553. });
  2554. };
  2555. UploadTask.prototype._increaseMultiplier = function () {
  2556. var currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
  2557. // Max chunk size is 32M.
  2558. if (currentSize * 2 < 32 * 1024 * 1024) {
  2559. this._chunkMultiplier *= 2;
  2560. }
  2561. };
  2562. UploadTask.prototype._fetchMetadata = function () {
  2563. var _this = this;
  2564. this._resolveToken(function (authToken, appCheckToken) {
  2565. var requestInfo = getMetadata$2(_this._ref.storage, _this._ref._location, _this._mappings);
  2566. var metadataRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2567. _this._request = metadataRequest;
  2568. metadataRequest.getPromise().then(function (metadata) {
  2569. _this._request = undefined;
  2570. _this._metadata = metadata;
  2571. _this._transition("success" /* InternalTaskState.SUCCESS */);
  2572. }, _this._metadataErrorHandler);
  2573. });
  2574. };
  2575. UploadTask.prototype._oneShotUpload = function () {
  2576. var _this = this;
  2577. this._resolveToken(function (authToken, appCheckToken) {
  2578. var requestInfo = multipartUpload(_this._ref.storage, _this._ref._location, _this._mappings, _this._blob, _this._metadata);
  2579. var multipartRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2580. _this._request = multipartRequest;
  2581. multipartRequest.getPromise().then(function (metadata) {
  2582. _this._request = undefined;
  2583. _this._metadata = metadata;
  2584. _this._updateProgress(_this._blob.size());
  2585. _this._transition("success" /* InternalTaskState.SUCCESS */);
  2586. }, _this._errorHandler);
  2587. });
  2588. };
  2589. UploadTask.prototype._updateProgress = function (transferred) {
  2590. var old = this._transferred;
  2591. this._transferred = transferred;
  2592. // A progress update can make the "transferred" value smaller (e.g. a
  2593. // partial upload not completed by server, after which the "transferred"
  2594. // value may reset to the value at the beginning of the request).
  2595. if (this._transferred !== old) {
  2596. this._notifyObservers();
  2597. }
  2598. };
  2599. UploadTask.prototype._transition = function (state) {
  2600. if (this._state === state) {
  2601. return;
  2602. }
  2603. switch (state) {
  2604. case "canceling" /* InternalTaskState.CANCELING */:
  2605. case "pausing" /* InternalTaskState.PAUSING */:
  2606. // TODO(andysoto):
  2607. // assert(this.state_ === InternalTaskState.RUNNING ||
  2608. // this.state_ === InternalTaskState.PAUSING);
  2609. this._state = state;
  2610. if (this._request !== undefined) {
  2611. this._request.cancel();
  2612. }
  2613. else if (this.pendingTimeout) {
  2614. clearTimeout(this.pendingTimeout);
  2615. this.pendingTimeout = undefined;
  2616. this.completeTransitions_();
  2617. }
  2618. break;
  2619. case "running" /* InternalTaskState.RUNNING */:
  2620. // TODO(andysoto):
  2621. // assert(this.state_ === InternalTaskState.PAUSED ||
  2622. // this.state_ === InternalTaskState.PAUSING);
  2623. var wasPaused = this._state === "paused" /* InternalTaskState.PAUSED */;
  2624. this._state = state;
  2625. if (wasPaused) {
  2626. this._notifyObservers();
  2627. this._start();
  2628. }
  2629. break;
  2630. case "paused" /* InternalTaskState.PAUSED */:
  2631. // TODO(andysoto):
  2632. // assert(this.state_ === InternalTaskState.PAUSING);
  2633. this._state = state;
  2634. this._notifyObservers();
  2635. break;
  2636. case "canceled" /* InternalTaskState.CANCELED */:
  2637. // TODO(andysoto):
  2638. // assert(this.state_ === InternalTaskState.PAUSED ||
  2639. // this.state_ === InternalTaskState.CANCELING);
  2640. this._error = canceled();
  2641. this._state = state;
  2642. this._notifyObservers();
  2643. break;
  2644. case "error" /* InternalTaskState.ERROR */:
  2645. // TODO(andysoto):
  2646. // assert(this.state_ === InternalTaskState.RUNNING ||
  2647. // this.state_ === InternalTaskState.PAUSING ||
  2648. // this.state_ === InternalTaskState.CANCELING);
  2649. this._state = state;
  2650. this._notifyObservers();
  2651. break;
  2652. case "success" /* InternalTaskState.SUCCESS */:
  2653. // TODO(andysoto):
  2654. // assert(this.state_ === InternalTaskState.RUNNING ||
  2655. // this.state_ === InternalTaskState.PAUSING ||
  2656. // this.state_ === InternalTaskState.CANCELING);
  2657. this._state = state;
  2658. this._notifyObservers();
  2659. break;
  2660. }
  2661. };
  2662. UploadTask.prototype.completeTransitions_ = function () {
  2663. switch (this._state) {
  2664. case "pausing" /* InternalTaskState.PAUSING */:
  2665. this._transition("paused" /* InternalTaskState.PAUSED */);
  2666. break;
  2667. case "canceling" /* InternalTaskState.CANCELING */:
  2668. this._transition("canceled" /* InternalTaskState.CANCELED */);
  2669. break;
  2670. case "running" /* InternalTaskState.RUNNING */:
  2671. this._start();
  2672. break;
  2673. }
  2674. };
  2675. Object.defineProperty(UploadTask.prototype, "snapshot", {
  2676. /**
  2677. * A snapshot of the current task state.
  2678. */
  2679. get: function () {
  2680. var externalState = taskStateFromInternalTaskState(this._state);
  2681. return {
  2682. bytesTransferred: this._transferred,
  2683. totalBytes: this._blob.size(),
  2684. state: externalState,
  2685. metadata: this._metadata,
  2686. task: this,
  2687. ref: this._ref
  2688. };
  2689. },
  2690. enumerable: false,
  2691. configurable: true
  2692. });
  2693. /**
  2694. * Adds a callback for an event.
  2695. * @param type - The type of event to listen for.
  2696. * @param nextOrObserver -
  2697. * The `next` function, which gets called for each item in
  2698. * the event stream, or an observer object with some or all of these three
  2699. * properties (`next`, `error`, `complete`).
  2700. * @param error - A function that gets called with a `StorageError`
  2701. * if the event stream ends due to an error.
  2702. * @param completed - A function that gets called if the
  2703. * event stream ends normally.
  2704. * @returns
  2705. * If only the event argument is passed, returns a function you can use to
  2706. * add callbacks (see the examples above). If more than just the event
  2707. * argument is passed, returns a function you can call to unregister the
  2708. * callbacks.
  2709. */
  2710. UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {
  2711. var _this = this;
  2712. // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.
  2713. var observer = new Observer(nextOrObserver || undefined, error || undefined, completed || undefined);
  2714. this._addObserver(observer);
  2715. return function () {
  2716. _this._removeObserver(observer);
  2717. };
  2718. };
  2719. /**
  2720. * This object behaves like a Promise, and resolves with its snapshot data
  2721. * when the upload completes.
  2722. * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.
  2723. * @param onRejected - The rejection callback.
  2724. */
  2725. UploadTask.prototype.then = function (onFulfilled, onRejected) {
  2726. // These casts are needed so that TypeScript can infer the types of the
  2727. // resulting Promise.
  2728. return this._promise.then(onFulfilled, onRejected);
  2729. };
  2730. /**
  2731. * Equivalent to calling `then(null, onRejected)`.
  2732. */
  2733. UploadTask.prototype.catch = function (onRejected) {
  2734. return this.then(null, onRejected);
  2735. };
  2736. /**
  2737. * Adds the given observer.
  2738. */
  2739. UploadTask.prototype._addObserver = function (observer) {
  2740. this._observers.push(observer);
  2741. this._notifyObserver(observer);
  2742. };
  2743. /**
  2744. * Removes the given observer.
  2745. */
  2746. UploadTask.prototype._removeObserver = function (observer) {
  2747. var i = this._observers.indexOf(observer);
  2748. if (i !== -1) {
  2749. this._observers.splice(i, 1);
  2750. }
  2751. };
  2752. UploadTask.prototype._notifyObservers = function () {
  2753. var _this = this;
  2754. this._finishPromise();
  2755. var observers = this._observers.slice();
  2756. observers.forEach(function (observer) {
  2757. _this._notifyObserver(observer);
  2758. });
  2759. };
  2760. UploadTask.prototype._finishPromise = function () {
  2761. if (this._resolve !== undefined) {
  2762. var triggered = true;
  2763. switch (taskStateFromInternalTaskState(this._state)) {
  2764. case TaskState.SUCCESS:
  2765. async(this._resolve.bind(null, this.snapshot))();
  2766. break;
  2767. case TaskState.CANCELED:
  2768. case TaskState.ERROR:
  2769. var toCall = this._reject;
  2770. async(toCall.bind(null, this._error))();
  2771. break;
  2772. default:
  2773. triggered = false;
  2774. break;
  2775. }
  2776. if (triggered) {
  2777. this._resolve = undefined;
  2778. this._reject = undefined;
  2779. }
  2780. }
  2781. };
  2782. UploadTask.prototype._notifyObserver = function (observer) {
  2783. var externalState = taskStateFromInternalTaskState(this._state);
  2784. switch (externalState) {
  2785. case TaskState.RUNNING:
  2786. case TaskState.PAUSED:
  2787. if (observer.next) {
  2788. async(observer.next.bind(observer, this.snapshot))();
  2789. }
  2790. break;
  2791. case TaskState.SUCCESS:
  2792. if (observer.complete) {
  2793. async(observer.complete.bind(observer))();
  2794. }
  2795. break;
  2796. case TaskState.CANCELED:
  2797. case TaskState.ERROR:
  2798. if (observer.error) {
  2799. async(observer.error.bind(observer, this._error))();
  2800. }
  2801. break;
  2802. default:
  2803. // TODO(andysoto): assert(false);
  2804. if (observer.error) {
  2805. async(observer.error.bind(observer, this._error))();
  2806. }
  2807. }
  2808. };
  2809. /**
  2810. * Resumes a paused task. Has no effect on a currently running or failed task.
  2811. * @returns True if the operation took effect, false if ignored.
  2812. */
  2813. UploadTask.prototype.resume = function () {
  2814. var valid = this._state === "paused" /* InternalTaskState.PAUSED */ ||
  2815. this._state === "pausing" /* InternalTaskState.PAUSING */;
  2816. if (valid) {
  2817. this._transition("running" /* InternalTaskState.RUNNING */);
  2818. }
  2819. return valid;
  2820. };
  2821. /**
  2822. * Pauses a currently running task. Has no effect on a paused or failed task.
  2823. * @returns True if the operation took effect, false if ignored.
  2824. */
  2825. UploadTask.prototype.pause = function () {
  2826. var valid = this._state === "running" /* InternalTaskState.RUNNING */;
  2827. if (valid) {
  2828. this._transition("pausing" /* InternalTaskState.PAUSING */);
  2829. }
  2830. return valid;
  2831. };
  2832. /**
  2833. * Cancels a currently running or paused task. Has no effect on a complete or
  2834. * failed task.
  2835. * @returns True if the operation took effect, false if ignored.
  2836. */
  2837. UploadTask.prototype.cancel = function () {
  2838. var valid = this._state === "running" /* InternalTaskState.RUNNING */ ||
  2839. this._state === "pausing" /* InternalTaskState.PAUSING */;
  2840. if (valid) {
  2841. this._transition("canceling" /* InternalTaskState.CANCELING */);
  2842. }
  2843. return valid;
  2844. };
  2845. return UploadTask;
  2846. }());
  2847. /**
  2848. * @license
  2849. * Copyright 2019 Google LLC
  2850. *
  2851. * Licensed under the Apache License, Version 2.0 (the "License");
  2852. * you may not use this file except in compliance with the License.
  2853. * You may obtain a copy of the License at
  2854. *
  2855. * http://www.apache.org/licenses/LICENSE-2.0
  2856. *
  2857. * Unless required by applicable law or agreed to in writing, software
  2858. * distributed under the License is distributed on an "AS IS" BASIS,
  2859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2860. * See the License for the specific language governing permissions and
  2861. * limitations under the License.
  2862. */
  2863. /**
  2864. * Provides methods to interact with a bucket in the Firebase Storage service.
  2865. * @internal
  2866. * @param _location - An fbs.location, or the URL at
  2867. * which to base this object, in one of the following forms:
  2868. * gs://<bucket>/<object-path>
  2869. * http[s]://firebasestorage.googleapis.com/
  2870. * <api-version>/b/<bucket>/o/<object-path>
  2871. * Any query or fragment strings will be ignored in the http[s]
  2872. * format. If no value is passed, the storage object will use a URL based on
  2873. * the project ID of the base firebase.App instance.
  2874. */
  2875. var Reference = /** @class */ (function () {
  2876. function Reference(_service, location) {
  2877. this._service = _service;
  2878. if (location instanceof Location) {
  2879. this._location = location;
  2880. }
  2881. else {
  2882. this._location = Location.makeFromUrl(location, _service.host);
  2883. }
  2884. }
  2885. /**
  2886. * Returns the URL for the bucket and path this object references,
  2887. * in the form gs://<bucket>/<object-path>
  2888. * @override
  2889. */
  2890. Reference.prototype.toString = function () {
  2891. return 'gs://' + this._location.bucket + '/' + this._location.path;
  2892. };
  2893. Reference.prototype._newRef = function (service, location) {
  2894. return new Reference(service, location);
  2895. };
  2896. Object.defineProperty(Reference.prototype, "root", {
  2897. /**
  2898. * A reference to the root of this object's bucket.
  2899. */
  2900. get: function () {
  2901. var location = new Location(this._location.bucket, '');
  2902. return this._newRef(this._service, location);
  2903. },
  2904. enumerable: false,
  2905. configurable: true
  2906. });
  2907. Object.defineProperty(Reference.prototype, "bucket", {
  2908. /**
  2909. * The name of the bucket containing this reference's object.
  2910. */
  2911. get: function () {
  2912. return this._location.bucket;
  2913. },
  2914. enumerable: false,
  2915. configurable: true
  2916. });
  2917. Object.defineProperty(Reference.prototype, "fullPath", {
  2918. /**
  2919. * The full path of this object.
  2920. */
  2921. get: function () {
  2922. return this._location.path;
  2923. },
  2924. enumerable: false,
  2925. configurable: true
  2926. });
  2927. Object.defineProperty(Reference.prototype, "name", {
  2928. /**
  2929. * The short name of this object, which is the last component of the full path.
  2930. * For example, if fullPath is 'full/path/image.png', name is 'image.png'.
  2931. */
  2932. get: function () {
  2933. return lastComponent(this._location.path);
  2934. },
  2935. enumerable: false,
  2936. configurable: true
  2937. });
  2938. Object.defineProperty(Reference.prototype, "storage", {
  2939. /**
  2940. * The `StorageService` instance this `StorageReference` is associated with.
  2941. */
  2942. get: function () {
  2943. return this._service;
  2944. },
  2945. enumerable: false,
  2946. configurable: true
  2947. });
  2948. Object.defineProperty(Reference.prototype, "parent", {
  2949. /**
  2950. * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if
  2951. * this reference is the root.
  2952. */
  2953. get: function () {
  2954. var newPath = parent(this._location.path);
  2955. if (newPath === null) {
  2956. return null;
  2957. }
  2958. var location = new Location(this._location.bucket, newPath);
  2959. return new Reference(this._service, location);
  2960. },
  2961. enumerable: false,
  2962. configurable: true
  2963. });
  2964. /**
  2965. * Utility function to throw an error in methods that do not accept a root reference.
  2966. */
  2967. Reference.prototype._throwIfRoot = function (name) {
  2968. if (this._location.path === '') {
  2969. throw invalidRootOperation(name);
  2970. }
  2971. };
  2972. return Reference;
  2973. }());
  2974. /**
  2975. * Download the bytes at the object's location.
  2976. * @returns A Promise containing the downloaded bytes.
  2977. */
  2978. function getBytesInternal(ref, maxDownloadSizeBytes) {
  2979. ref._throwIfRoot('getBytes');
  2980. var requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);
  2981. return ref.storage
  2982. .makeRequestWithTokens(requestInfo, newBytesConnection)
  2983. .then(function (bytes) {
  2984. return maxDownloadSizeBytes !== undefined
  2985. ? // GCS may not honor the Range header for small files
  2986. bytes.slice(0, maxDownloadSizeBytes)
  2987. : bytes;
  2988. });
  2989. }
  2990. /**
  2991. * Download the bytes at the object's location.
  2992. * @returns A Promise containing the downloaded blob.
  2993. */
  2994. function getBlobInternal(ref, maxDownloadSizeBytes) {
  2995. ref._throwIfRoot('getBlob');
  2996. var requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);
  2997. return ref.storage
  2998. .makeRequestWithTokens(requestInfo, newBlobConnection)
  2999. .then(function (blob) {
  3000. return maxDownloadSizeBytes !== undefined
  3001. ? // GCS may not honor the Range header for small files
  3002. blob.slice(0, maxDownloadSizeBytes)
  3003. : blob;
  3004. });
  3005. }
  3006. /**
  3007. * Uploads data to this object's location.
  3008. * The upload is not resumable.
  3009. *
  3010. * @param ref - StorageReference where data should be uploaded.
  3011. * @param data - The data to upload.
  3012. * @param metadata - Metadata for the newly uploaded data.
  3013. * @returns A Promise containing an UploadResult
  3014. */
  3015. function uploadBytes$1(ref, data, metadata) {
  3016. ref._throwIfRoot('uploadBytes');
  3017. var requestInfo = multipartUpload(ref.storage, ref._location, getMappings(), new FbsBlob(data, true), metadata);
  3018. return ref.storage
  3019. .makeRequestWithTokens(requestInfo, newTextConnection)
  3020. .then(function (finalMetadata) {
  3021. return {
  3022. metadata: finalMetadata,
  3023. ref: ref
  3024. };
  3025. });
  3026. }
  3027. /**
  3028. * Uploads data to this object's location.
  3029. * The upload can be paused and resumed, and exposes progress updates.
  3030. * @public
  3031. * @param ref - StorageReference where data should be uploaded.
  3032. * @param data - The data to upload.
  3033. * @param metadata - Metadata for the newly uploaded data.
  3034. * @returns An UploadTask
  3035. */
  3036. function uploadBytesResumable$1(ref, data, metadata) {
  3037. ref._throwIfRoot('uploadBytesResumable');
  3038. return new UploadTask(ref, new FbsBlob(data), metadata);
  3039. }
  3040. /**
  3041. * Uploads a string to this object's location.
  3042. * The upload is not resumable.
  3043. * @public
  3044. * @param ref - StorageReference where string should be uploaded.
  3045. * @param value - The string to upload.
  3046. * @param format - The format of the string to upload.
  3047. * @param metadata - Metadata for the newly uploaded string.
  3048. * @returns A Promise containing an UploadResult
  3049. */
  3050. function uploadString$1(ref, value, format, metadata) {
  3051. if (format === void 0) { format = StringFormat.RAW; }
  3052. ref._throwIfRoot('uploadString');
  3053. var data = dataFromString(format, value);
  3054. var metadataClone = tslib.__assign({}, metadata);
  3055. if (metadataClone['contentType'] == null && data.contentType != null) {
  3056. metadataClone['contentType'] = data.contentType;
  3057. }
  3058. return uploadBytes$1(ref, data.data, metadataClone);
  3059. }
  3060. /**
  3061. * List all items (files) and prefixes (folders) under this storage reference.
  3062. *
  3063. * This is a helper method for calling list() repeatedly until there are
  3064. * no more results. The default pagination size is 1000.
  3065. *
  3066. * Note: The results may not be consistent if objects are changed while this
  3067. * operation is running.
  3068. *
  3069. * Warning: listAll may potentially consume too many resources if there are
  3070. * too many results.
  3071. * @public
  3072. * @param ref - StorageReference to get list from.
  3073. *
  3074. * @returns A Promise that resolves with all the items and prefixes under
  3075. * the current storage reference. `prefixes` contains references to
  3076. * sub-directories and `items` contains references to objects in this
  3077. * folder. `nextPageToken` is never returned.
  3078. */
  3079. function listAll$1(ref) {
  3080. var accumulator = {
  3081. prefixes: [],
  3082. items: []
  3083. };
  3084. return listAllHelper(ref, accumulator).then(function () { return accumulator; });
  3085. }
  3086. /**
  3087. * Separated from listAll because async functions can't use "arguments".
  3088. * @param ref
  3089. * @param accumulator
  3090. * @param pageToken
  3091. */
  3092. function listAllHelper(ref, accumulator, pageToken) {
  3093. return tslib.__awaiter(this, void 0, void 0, function () {
  3094. var opt, nextPage;
  3095. var _a, _b;
  3096. return tslib.__generator(this, function (_c) {
  3097. switch (_c.label) {
  3098. case 0:
  3099. opt = {
  3100. // maxResults is 1000 by default.
  3101. pageToken: pageToken
  3102. };
  3103. return [4 /*yield*/, list$1(ref, opt)];
  3104. case 1:
  3105. nextPage = _c.sent();
  3106. (_a = accumulator.prefixes).push.apply(_a, nextPage.prefixes);
  3107. (_b = accumulator.items).push.apply(_b, nextPage.items);
  3108. if (!(nextPage.nextPageToken != null)) return [3 /*break*/, 3];
  3109. return [4 /*yield*/, listAllHelper(ref, accumulator, nextPage.nextPageToken)];
  3110. case 2:
  3111. _c.sent();
  3112. _c.label = 3;
  3113. case 3: return [2 /*return*/];
  3114. }
  3115. });
  3116. });
  3117. }
  3118. /**
  3119. * List items (files) and prefixes (folders) under this storage reference.
  3120. *
  3121. * List API is only available for Firebase Rules Version 2.
  3122. *
  3123. * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
  3124. * delimited folder structure.
  3125. * Refer to GCS's List API if you want to learn more.
  3126. *
  3127. * To adhere to Firebase Rules's Semantics, Firebase Storage does not
  3128. * support objects whose paths end with "/" or contain two consecutive
  3129. * "/"s. Firebase Storage List API will filter these unsupported objects.
  3130. * list() may fail if there are too many unsupported objects in the bucket.
  3131. * @public
  3132. *
  3133. * @param ref - StorageReference to get list from.
  3134. * @param options - See ListOptions for details.
  3135. * @returns A Promise that resolves with the items and prefixes.
  3136. * `prefixes` contains references to sub-folders and `items`
  3137. * contains references to objects in this folder. `nextPageToken`
  3138. * can be used to get the rest of the results.
  3139. */
  3140. function list$1(ref, options) {
  3141. if (options != null) {
  3142. if (typeof options.maxResults === 'number') {
  3143. validateNumber('options.maxResults',
  3144. /* minValue= */ 1,
  3145. /* maxValue= */ 1000, options.maxResults);
  3146. }
  3147. }
  3148. var op = options || {};
  3149. var requestInfo = list$2(ref.storage, ref._location,
  3150. /*delimiter= */ '/', op.pageToken, op.maxResults);
  3151. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3152. }
  3153. /**
  3154. * A `Promise` that resolves with the metadata for this object. If this
  3155. * object doesn't exist or metadata cannot be retreived, the promise is
  3156. * rejected.
  3157. * @public
  3158. * @param ref - StorageReference to get metadata from.
  3159. */
  3160. function getMetadata$1(ref) {
  3161. ref._throwIfRoot('getMetadata');
  3162. var requestInfo = getMetadata$2(ref.storage, ref._location, getMappings());
  3163. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3164. }
  3165. /**
  3166. * Updates the metadata for this object.
  3167. * @public
  3168. * @param ref - StorageReference to update metadata for.
  3169. * @param metadata - The new metadata for the object.
  3170. * Only values that have been explicitly set will be changed. Explicitly
  3171. * setting a value to null will remove the metadata.
  3172. * @returns A `Promise` that resolves
  3173. * with the new metadata for this object.
  3174. * See `firebaseStorage.Reference.prototype.getMetadata`
  3175. */
  3176. function updateMetadata$1(ref, metadata) {
  3177. ref._throwIfRoot('updateMetadata');
  3178. var requestInfo = updateMetadata$2(ref.storage, ref._location, metadata, getMappings());
  3179. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3180. }
  3181. /**
  3182. * Returns the download URL for the given Reference.
  3183. * @public
  3184. * @returns A `Promise` that resolves with the download
  3185. * URL for this object.
  3186. */
  3187. function getDownloadURL$1(ref) {
  3188. ref._throwIfRoot('getDownloadURL');
  3189. var requestInfo = getDownloadUrl(ref.storage, ref._location, getMappings());
  3190. return ref.storage
  3191. .makeRequestWithTokens(requestInfo, newTextConnection)
  3192. .then(function (url) {
  3193. if (url === null) {
  3194. throw noDownloadURL();
  3195. }
  3196. return url;
  3197. });
  3198. }
  3199. /**
  3200. * Deletes the object at this location.
  3201. * @public
  3202. * @param ref - StorageReference for object to delete.
  3203. * @returns A `Promise` that resolves if the deletion succeeds.
  3204. */
  3205. function deleteObject$1(ref) {
  3206. ref._throwIfRoot('deleteObject');
  3207. var requestInfo = deleteObject$2(ref.storage, ref._location);
  3208. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3209. }
  3210. /**
  3211. * Returns reference for object obtained by appending `childPath` to `ref`.
  3212. *
  3213. * @param ref - StorageReference to get child of.
  3214. * @param childPath - Child path from provided ref.
  3215. * @returns A reference to the object obtained by
  3216. * appending childPath, removing any duplicate, beginning, or trailing
  3217. * slashes.
  3218. *
  3219. */
  3220. function _getChild$1(ref, childPath) {
  3221. var newPath = child(ref._location.path, childPath);
  3222. var location = new Location(ref._location.bucket, newPath);
  3223. return new Reference(ref.storage, location);
  3224. }
  3225. /**
  3226. * @license
  3227. * Copyright 2017 Google LLC
  3228. *
  3229. * Licensed under the Apache License, Version 2.0 (the "License");
  3230. * you may not use this file except in compliance with the License.
  3231. * You may obtain a copy of the License at
  3232. *
  3233. * http://www.apache.org/licenses/LICENSE-2.0
  3234. *
  3235. * Unless required by applicable law or agreed to in writing, software
  3236. * distributed under the License is distributed on an "AS IS" BASIS,
  3237. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3238. * See the License for the specific language governing permissions and
  3239. * limitations under the License.
  3240. */
  3241. function isUrl(path) {
  3242. return /^[A-Za-z]+:\/\//.test(path);
  3243. }
  3244. /**
  3245. * Returns a firebaseStorage.Reference for the given url.
  3246. */
  3247. function refFromURL(service, url) {
  3248. return new Reference(service, url);
  3249. }
  3250. /**
  3251. * Returns a firebaseStorage.Reference for the given path in the default
  3252. * bucket.
  3253. */
  3254. function refFromPath(ref, path) {
  3255. if (ref instanceof FirebaseStorageImpl) {
  3256. var service = ref;
  3257. if (service._bucket == null) {
  3258. throw noDefaultBucket();
  3259. }
  3260. var reference = new Reference(service, service._bucket);
  3261. if (path != null) {
  3262. return refFromPath(reference, path);
  3263. }
  3264. else {
  3265. return reference;
  3266. }
  3267. }
  3268. else {
  3269. // ref is a Reference
  3270. if (path !== undefined) {
  3271. return _getChild$1(ref, path);
  3272. }
  3273. else {
  3274. return ref;
  3275. }
  3276. }
  3277. }
  3278. function ref$1(serviceOrRef, pathOrUrl) {
  3279. if (pathOrUrl && isUrl(pathOrUrl)) {
  3280. if (serviceOrRef instanceof FirebaseStorageImpl) {
  3281. return refFromURL(serviceOrRef, pathOrUrl);
  3282. }
  3283. else {
  3284. throw invalidArgument('To use ref(service, url), the first argument must be a Storage instance.');
  3285. }
  3286. }
  3287. else {
  3288. return refFromPath(serviceOrRef, pathOrUrl);
  3289. }
  3290. }
  3291. function extractBucket(host, config) {
  3292. var bucketString = config === null || config === void 0 ? void 0 : config[CONFIG_STORAGE_BUCKET_KEY];
  3293. if (bucketString == null) {
  3294. return null;
  3295. }
  3296. return Location.makeFromBucketSpec(bucketString, host);
  3297. }
  3298. function connectStorageEmulator$1(storage, host, port, options) {
  3299. if (options === void 0) { options = {}; }
  3300. storage.host = "".concat(host, ":").concat(port);
  3301. storage._protocol = 'http';
  3302. var mockUserToken = options.mockUserToken;
  3303. if (mockUserToken) {
  3304. storage._overrideAuthToken =
  3305. typeof mockUserToken === 'string'
  3306. ? mockUserToken
  3307. : util.createMockUserToken(mockUserToken, storage.app.options.projectId);
  3308. }
  3309. }
  3310. /**
  3311. * A service that provides Firebase Storage Reference instances.
  3312. * @param opt_url - gs:// url to a custom Storage Bucket
  3313. *
  3314. * @internal
  3315. */
  3316. var FirebaseStorageImpl = /** @class */ (function () {
  3317. function FirebaseStorageImpl(
  3318. /**
  3319. * FirebaseApp associated with this StorageService instance.
  3320. */
  3321. app, _authProvider,
  3322. /**
  3323. * @internal
  3324. */
  3325. _appCheckProvider,
  3326. /**
  3327. * @internal
  3328. */
  3329. _url, _firebaseVersion) {
  3330. this.app = app;
  3331. this._authProvider = _authProvider;
  3332. this._appCheckProvider = _appCheckProvider;
  3333. this._url = _url;
  3334. this._firebaseVersion = _firebaseVersion;
  3335. this._bucket = null;
  3336. /**
  3337. * This string can be in the formats:
  3338. * - host
  3339. * - host:port
  3340. */
  3341. this._host = DEFAULT_HOST;
  3342. this._protocol = 'https';
  3343. this._appId = null;
  3344. this._deleted = false;
  3345. this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;
  3346. this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;
  3347. this._requests = new Set();
  3348. if (_url != null) {
  3349. this._bucket = Location.makeFromBucketSpec(_url, this._host);
  3350. }
  3351. else {
  3352. this._bucket = extractBucket(this._host, this.app.options);
  3353. }
  3354. }
  3355. Object.defineProperty(FirebaseStorageImpl.prototype, "host", {
  3356. /**
  3357. * The host string for this service, in the form of `host` or
  3358. * `host:port`.
  3359. */
  3360. get: function () {
  3361. return this._host;
  3362. },
  3363. set: function (host) {
  3364. this._host = host;
  3365. if (this._url != null) {
  3366. this._bucket = Location.makeFromBucketSpec(this._url, host);
  3367. }
  3368. else {
  3369. this._bucket = extractBucket(host, this.app.options);
  3370. }
  3371. },
  3372. enumerable: false,
  3373. configurable: true
  3374. });
  3375. Object.defineProperty(FirebaseStorageImpl.prototype, "maxUploadRetryTime", {
  3376. /**
  3377. * The maximum time to retry uploads in milliseconds.
  3378. */
  3379. get: function () {
  3380. return this._maxUploadRetryTime;
  3381. },
  3382. set: function (time) {
  3383. validateNumber('time',
  3384. /* minValue=*/ 0,
  3385. /* maxValue= */ Number.POSITIVE_INFINITY, time);
  3386. this._maxUploadRetryTime = time;
  3387. },
  3388. enumerable: false,
  3389. configurable: true
  3390. });
  3391. Object.defineProperty(FirebaseStorageImpl.prototype, "maxOperationRetryTime", {
  3392. /**
  3393. * The maximum time to retry operations other than uploads or downloads in
  3394. * milliseconds.
  3395. */
  3396. get: function () {
  3397. return this._maxOperationRetryTime;
  3398. },
  3399. set: function (time) {
  3400. validateNumber('time',
  3401. /* minValue=*/ 0,
  3402. /* maxValue= */ Number.POSITIVE_INFINITY, time);
  3403. this._maxOperationRetryTime = time;
  3404. },
  3405. enumerable: false,
  3406. configurable: true
  3407. });
  3408. FirebaseStorageImpl.prototype._getAuthToken = function () {
  3409. return tslib.__awaiter(this, void 0, void 0, function () {
  3410. var auth, tokenData;
  3411. return tslib.__generator(this, function (_a) {
  3412. switch (_a.label) {
  3413. case 0:
  3414. if (this._overrideAuthToken) {
  3415. return [2 /*return*/, this._overrideAuthToken];
  3416. }
  3417. auth = this._authProvider.getImmediate({ optional: true });
  3418. if (!auth) return [3 /*break*/, 2];
  3419. return [4 /*yield*/, auth.getToken()];
  3420. case 1:
  3421. tokenData = _a.sent();
  3422. if (tokenData !== null) {
  3423. return [2 /*return*/, tokenData.accessToken];
  3424. }
  3425. _a.label = 2;
  3426. case 2: return [2 /*return*/, null];
  3427. }
  3428. });
  3429. });
  3430. };
  3431. FirebaseStorageImpl.prototype._getAppCheckToken = function () {
  3432. return tslib.__awaiter(this, void 0, void 0, function () {
  3433. var appCheck, result;
  3434. return tslib.__generator(this, function (_a) {
  3435. switch (_a.label) {
  3436. case 0:
  3437. appCheck = this._appCheckProvider.getImmediate({ optional: true });
  3438. if (!appCheck) return [3 /*break*/, 2];
  3439. return [4 /*yield*/, appCheck.getToken()];
  3440. case 1:
  3441. result = _a.sent();
  3442. // TODO: What do we want to do if there is an error getting the token?
  3443. // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be
  3444. // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use
  3445. // the token (actual or dummy) to send requests.
  3446. return [2 /*return*/, result.token];
  3447. case 2: return [2 /*return*/, null];
  3448. }
  3449. });
  3450. });
  3451. };
  3452. /**
  3453. * Stop running requests and prevent more from being created.
  3454. */
  3455. FirebaseStorageImpl.prototype._delete = function () {
  3456. if (!this._deleted) {
  3457. this._deleted = true;
  3458. this._requests.forEach(function (request) { return request.cancel(); });
  3459. this._requests.clear();
  3460. }
  3461. return Promise.resolve();
  3462. };
  3463. /**
  3464. * Returns a new firebaseStorage.Reference object referencing this StorageService
  3465. * at the given Location.
  3466. */
  3467. FirebaseStorageImpl.prototype._makeStorageReference = function (loc) {
  3468. return new Reference(this, loc);
  3469. };
  3470. /**
  3471. * @param requestInfo - HTTP RequestInfo object
  3472. * @param authToken - Firebase auth token
  3473. */
  3474. FirebaseStorageImpl.prototype._makeRequest = function (requestInfo, requestFactory, authToken, appCheckToken, retry) {
  3475. var _this = this;
  3476. if (retry === void 0) { retry = true; }
  3477. if (!this._deleted) {
  3478. var request_1 = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry);
  3479. this._requests.add(request_1);
  3480. // Request removes itself from set when complete.
  3481. request_1.getPromise().then(function () { return _this._requests.delete(request_1); }, function () { return _this._requests.delete(request_1); });
  3482. return request_1;
  3483. }
  3484. else {
  3485. return new FailRequest(appDeleted());
  3486. }
  3487. };
  3488. FirebaseStorageImpl.prototype.makeRequestWithTokens = function (requestInfo, requestFactory) {
  3489. return tslib.__awaiter(this, void 0, void 0, function () {
  3490. var _a, authToken, appCheckToken;
  3491. return tslib.__generator(this, function (_b) {
  3492. switch (_b.label) {
  3493. case 0: return [4 /*yield*/, Promise.all([
  3494. this._getAuthToken(),
  3495. this._getAppCheckToken()
  3496. ])];
  3497. case 1:
  3498. _a = _b.sent(), authToken = _a[0], appCheckToken = _a[1];
  3499. return [2 /*return*/, this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise()];
  3500. }
  3501. });
  3502. });
  3503. };
  3504. return FirebaseStorageImpl;
  3505. }());
  3506. var name = "@firebase/storage";
  3507. var version = "0.11.2";
  3508. /**
  3509. * @license
  3510. * Copyright 2020 Google LLC
  3511. *
  3512. * Licensed under the Apache License, Version 2.0 (the "License");
  3513. * you may not use this file except in compliance with the License.
  3514. * You may obtain a copy of the License at
  3515. *
  3516. * http://www.apache.org/licenses/LICENSE-2.0
  3517. *
  3518. * Unless required by applicable law or agreed to in writing, software
  3519. * distributed under the License is distributed on an "AS IS" BASIS,
  3520. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3521. * See the License for the specific language governing permissions and
  3522. * limitations under the License.
  3523. */
  3524. /**
  3525. * Type constant for Firebase Storage.
  3526. */
  3527. var STORAGE_TYPE = 'storage';
  3528. /**
  3529. * Downloads the data at the object's location. Returns an error if the object
  3530. * is not found.
  3531. *
  3532. * To use this functionality, you have to whitelist your app's origin in your
  3533. * Cloud Storage bucket. See also
  3534. * https://cloud.google.com/storage/docs/configuring-cors
  3535. *
  3536. * @public
  3537. * @param ref - StorageReference where data should be downloaded.
  3538. * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
  3539. * retrieve.
  3540. * @returns A Promise containing the object's bytes
  3541. */
  3542. function getBytes(ref, maxDownloadSizeBytes) {
  3543. ref = util.getModularInstance(ref);
  3544. return getBytesInternal(ref, maxDownloadSizeBytes);
  3545. }
  3546. /**
  3547. * Uploads data to this object's location.
  3548. * The upload is not resumable.
  3549. * @public
  3550. * @param ref - {@link StorageReference} where data should be uploaded.
  3551. * @param data - The data to upload.
  3552. * @param metadata - Metadata for the data to upload.
  3553. * @returns A Promise containing an UploadResult
  3554. */
  3555. function uploadBytes(ref, data, metadata) {
  3556. ref = util.getModularInstance(ref);
  3557. return uploadBytes$1(ref, data, metadata);
  3558. }
  3559. /**
  3560. * Uploads a string to this object's location.
  3561. * The upload is not resumable.
  3562. * @public
  3563. * @param ref - {@link StorageReference} where string should be uploaded.
  3564. * @param value - The string to upload.
  3565. * @param format - The format of the string to upload.
  3566. * @param metadata - Metadata for the string to upload.
  3567. * @returns A Promise containing an UploadResult
  3568. */
  3569. function uploadString(ref, value, format, metadata) {
  3570. ref = util.getModularInstance(ref);
  3571. return uploadString$1(ref, value, format, metadata);
  3572. }
  3573. /**
  3574. * Uploads data to this object's location.
  3575. * The upload can be paused and resumed, and exposes progress updates.
  3576. * @public
  3577. * @param ref - {@link StorageReference} where data should be uploaded.
  3578. * @param data - The data to upload.
  3579. * @param metadata - Metadata for the data to upload.
  3580. * @returns An UploadTask
  3581. */
  3582. function uploadBytesResumable(ref, data, metadata) {
  3583. ref = util.getModularInstance(ref);
  3584. return uploadBytesResumable$1(ref, data, metadata);
  3585. }
  3586. /**
  3587. * A `Promise` that resolves with the metadata for this object. If this
  3588. * object doesn't exist or metadata cannot be retreived, the promise is
  3589. * rejected.
  3590. * @public
  3591. * @param ref - {@link StorageReference} to get metadata from.
  3592. */
  3593. function getMetadata(ref) {
  3594. ref = util.getModularInstance(ref);
  3595. return getMetadata$1(ref);
  3596. }
  3597. /**
  3598. * Updates the metadata for this object.
  3599. * @public
  3600. * @param ref - {@link StorageReference} to update metadata for.
  3601. * @param metadata - The new metadata for the object.
  3602. * Only values that have been explicitly set will be changed. Explicitly
  3603. * setting a value to null will remove the metadata.
  3604. * @returns A `Promise` that resolves with the new metadata for this object.
  3605. */
  3606. function updateMetadata(ref, metadata) {
  3607. ref = util.getModularInstance(ref);
  3608. return updateMetadata$1(ref, metadata);
  3609. }
  3610. /**
  3611. * List items (files) and prefixes (folders) under this storage reference.
  3612. *
  3613. * List API is only available for Firebase Rules Version 2.
  3614. *
  3615. * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
  3616. * delimited folder structure.
  3617. * Refer to GCS's List API if you want to learn more.
  3618. *
  3619. * To adhere to Firebase Rules's Semantics, Firebase Storage does not
  3620. * support objects whose paths end with "/" or contain two consecutive
  3621. * "/"s. Firebase Storage List API will filter these unsupported objects.
  3622. * list() may fail if there are too many unsupported objects in the bucket.
  3623. * @public
  3624. *
  3625. * @param ref - {@link StorageReference} to get list from.
  3626. * @param options - See {@link ListOptions} for details.
  3627. * @returns A `Promise` that resolves with the items and prefixes.
  3628. * `prefixes` contains references to sub-folders and `items`
  3629. * contains references to objects in this folder. `nextPageToken`
  3630. * can be used to get the rest of the results.
  3631. */
  3632. function list(ref, options) {
  3633. ref = util.getModularInstance(ref);
  3634. return list$1(ref, options);
  3635. }
  3636. /**
  3637. * List all items (files) and prefixes (folders) under this storage reference.
  3638. *
  3639. * This is a helper method for calling list() repeatedly until there are
  3640. * no more results. The default pagination size is 1000.
  3641. *
  3642. * Note: The results may not be consistent if objects are changed while this
  3643. * operation is running.
  3644. *
  3645. * Warning: `listAll` may potentially consume too many resources if there are
  3646. * too many results.
  3647. * @public
  3648. * @param ref - {@link StorageReference} to get list from.
  3649. *
  3650. * @returns A `Promise` that resolves with all the items and prefixes under
  3651. * the current storage reference. `prefixes` contains references to
  3652. * sub-directories and `items` contains references to objects in this
  3653. * folder. `nextPageToken` is never returned.
  3654. */
  3655. function listAll(ref) {
  3656. ref = util.getModularInstance(ref);
  3657. return listAll$1(ref);
  3658. }
  3659. /**
  3660. * Returns the download URL for the given {@link StorageReference}.
  3661. * @public
  3662. * @param ref - {@link StorageReference} to get the download URL for.
  3663. * @returns A `Promise` that resolves with the download
  3664. * URL for this object.
  3665. */
  3666. function getDownloadURL(ref) {
  3667. ref = util.getModularInstance(ref);
  3668. return getDownloadURL$1(ref);
  3669. }
  3670. /**
  3671. * Deletes the object at this location.
  3672. * @public
  3673. * @param ref - {@link StorageReference} for object to delete.
  3674. * @returns A `Promise` that resolves if the deletion succeeds.
  3675. */
  3676. function deleteObject(ref) {
  3677. ref = util.getModularInstance(ref);
  3678. return deleteObject$1(ref);
  3679. }
  3680. function ref(serviceOrRef, pathOrUrl) {
  3681. serviceOrRef = util.getModularInstance(serviceOrRef);
  3682. return ref$1(serviceOrRef, pathOrUrl);
  3683. }
  3684. /**
  3685. * @internal
  3686. */
  3687. function _getChild(ref, childPath) {
  3688. return _getChild$1(ref, childPath);
  3689. }
  3690. /**
  3691. * Gets a {@link FirebaseStorage} instance for the given Firebase app.
  3692. * @public
  3693. * @param app - Firebase app to get {@link FirebaseStorage} instance for.
  3694. * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.
  3695. * If not passed, uses the app's default Storage Bucket.
  3696. * @returns A {@link FirebaseStorage} instance.
  3697. */
  3698. function getStorage(app$1, bucketUrl) {
  3699. if (app$1 === void 0) { app$1 = app.getApp(); }
  3700. app$1 = util.getModularInstance(app$1);
  3701. var storageProvider = app._getProvider(app$1, STORAGE_TYPE);
  3702. var storageInstance = storageProvider.getImmediate({
  3703. identifier: bucketUrl
  3704. });
  3705. var emulator = util.getDefaultEmulatorHostnameAndPort('storage');
  3706. if (emulator) {
  3707. connectStorageEmulator.apply(void 0, tslib.__spreadArray([storageInstance], emulator, false));
  3708. }
  3709. return storageInstance;
  3710. }
  3711. /**
  3712. * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.
  3713. *
  3714. * @param storage - The {@link FirebaseStorage} instance
  3715. * @param host - The emulator host (ex: localhost)
  3716. * @param port - The emulator port (ex: 5001)
  3717. * @param options - Emulator options. `options.mockUserToken` is the mock auth
  3718. * token to use for unit testing Security Rules.
  3719. * @public
  3720. */
  3721. function connectStorageEmulator(storage, host, port, options) {
  3722. if (options === void 0) { options = {}; }
  3723. connectStorageEmulator$1(storage, host, port, options);
  3724. }
  3725. /**
  3726. * @license
  3727. * Copyright 2021 Google LLC
  3728. *
  3729. * Licensed under the Apache License, Version 2.0 (the "License");
  3730. * you may not use this file except in compliance with the License.
  3731. * You may obtain a copy of the License at
  3732. *
  3733. * http://www.apache.org/licenses/LICENSE-2.0
  3734. *
  3735. * Unless required by applicable law or agreed to in writing, software
  3736. * distributed under the License is distributed on an "AS IS" BASIS,
  3737. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3738. * See the License for the specific language governing permissions and
  3739. * limitations under the License.
  3740. */
  3741. /**
  3742. * Downloads the data at the object's location. Returns an error if the object
  3743. * is not found.
  3744. *
  3745. * To use this functionality, you have to whitelist your app's origin in your
  3746. * Cloud Storage bucket. See also
  3747. * https://cloud.google.com/storage/docs/configuring-cors
  3748. *
  3749. * This API is not available in Node.
  3750. *
  3751. * @public
  3752. * @param ref - StorageReference where data should be downloaded.
  3753. * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
  3754. * retrieve.
  3755. * @returns A Promise that resolves with a Blob containing the object's bytes
  3756. */
  3757. function getBlob(ref, maxDownloadSizeBytes) {
  3758. ref = util.getModularInstance(ref);
  3759. return getBlobInternal(ref, maxDownloadSizeBytes);
  3760. }
  3761. /**
  3762. * Downloads the data at the object's location. Raises an error event if the
  3763. * object is not found.
  3764. *
  3765. * This API is only available in Node.
  3766. *
  3767. * @public
  3768. * @param ref - StorageReference where data should be downloaded.
  3769. * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
  3770. * retrieve.
  3771. * @returns A stream with the object's data as bytes
  3772. */
  3773. function getStream(ref, maxDownloadSizeBytes) {
  3774. throw new Error('getStream() is only supported by NodeJS builds');
  3775. }
  3776. /**
  3777. * Cloud Storage for Firebase
  3778. *
  3779. * @packageDocumentation
  3780. */
  3781. function factory(container, _a) {
  3782. var url = _a.instanceIdentifier;
  3783. var app$1 = container.getProvider('app').getImmediate();
  3784. var authProvider = container.getProvider('auth-internal');
  3785. var appCheckProvider = container.getProvider('app-check-internal');
  3786. return new FirebaseStorageImpl(app$1, authProvider, appCheckProvider, url, app.SDK_VERSION);
  3787. }
  3788. function registerStorage() {
  3789. app._registerComponent(new component.Component(STORAGE_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  3790. //RUNTIME_ENV will be replaced during the compilation to "node" for nodejs and an empty string for browser
  3791. app.registerVersion(name, version, '');
  3792. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  3793. app.registerVersion(name, version, 'cjs5');
  3794. }
  3795. registerStorage();
  3796. exports.StorageError = StorageError;
  3797. exports.StringFormat = StringFormat;
  3798. exports._FbsBlob = FbsBlob;
  3799. exports._Location = Location;
  3800. exports._TaskEvent = TaskEvent;
  3801. exports._TaskState = TaskState;
  3802. exports._UploadTask = UploadTask;
  3803. exports._dataFromString = dataFromString;
  3804. exports._getChild = _getChild;
  3805. exports._invalidArgument = invalidArgument;
  3806. exports._invalidRootOperation = invalidRootOperation;
  3807. exports.connectStorageEmulator = connectStorageEmulator;
  3808. exports.deleteObject = deleteObject;
  3809. exports.getBlob = getBlob;
  3810. exports.getBytes = getBytes;
  3811. exports.getDownloadURL = getDownloadURL;
  3812. exports.getMetadata = getMetadata;
  3813. exports.getStorage = getStorage;
  3814. exports.getStream = getStream;
  3815. exports.list = list;
  3816. exports.listAll = listAll;
  3817. exports.ref = ref;
  3818. exports.updateMetadata = updateMetadata;
  3819. exports.uploadBytes = uploadBytes;
  3820. exports.uploadBytesResumable = uploadBytesResumable;
  3821. exports.uploadString = uploadString;
  3822. //# sourceMappingURL=index.browser.cjs.js.map