index.node.esm.js 132 KB

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