@firebase/storage 0.13.2 → 0.13.3

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