index.cjs.js 132 KB

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