index.esm2017.js 131 KB

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