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

index.browser.cjs.js 136KB

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