No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.esm5.js 136KB

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