index.node.cjs.js 133 KB

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