PageSourceSearch

https://smarttvcast-screenmirroring.web.app/__/firebase/9.6.11/firebase-storage.js

js smarttvcast-screenmirroring.web.app collected 2026-10-03 12:36:13 UTC 145,863 bytes, 4,041 lines download raw bytes

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

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.