mirror of
https://github.com/musix-org/musix-oss
synced 2024-11-10 11:20:19 +00:00
1 line
206 KiB
Plaintext
1 line
206 KiB
Plaintext
{"version":3,"file":"firebase-storage.js","sources":["../../node_modules/tslib/tslib.es6.js","../util/src/errors.ts","../component/src/component.ts","../storage/src/implementation/constants.ts","../storage/src/implementation/error.ts","../storage/src/implementation/string.ts","../storage/src/implementation/taskenums.ts","../storage/src/implementation/xhrio.ts","../storage/src/implementation/type.ts","../storage/src/implementation/xhrio_network.ts","../storage/src/implementation/xhriopool.ts","../storage/src/implementation/fs.ts","../storage/src/implementation/blob.ts","../storage/src/implementation/location.ts","../storage/src/implementation/json.ts","../storage/src/implementation/path.ts","../storage/src/implementation/url.ts","../storage/src/implementation/metadata.ts","../storage/src/implementation/list.ts","../storage/src/implementation/requestinfo.ts","../storage/src/implementation/requests.ts","../storage/src/implementation/observer.ts","../storage/src/tasksnapshot.ts","../storage/src/implementation/args.ts","../storage/src/implementation/async.ts","../storage/src/task.ts","../storage/src/reference.ts","../storage/src/implementation/failrequest.ts","../storage/src/implementation/requestmap.ts","../storage/src/implementation/authwrapper.ts","../storage/src/implementation/request.ts","../storage/src/implementation/backoff.ts","../storage/src/service.ts","../storage/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if (e.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: StringLike | undefined;\n}\n\nexport interface FirebaseError extends Error, ErrorData {\n // Unique code for error - format is service/error-code-string.\n readonly code: string;\n\n // Developer-friendly error message.\n readonly message: string;\n\n // Always 'FirebaseError'.\n readonly name: typeof ERROR_NAME;\n\n // Where available - stack backtrace in a string.\n readonly stack?: string;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n readonly name = ERROR_NAME;\n\n constructor(readonly code: string, message: string) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage);\n\n // Keys with an underscore at the end of their name are not included in\n // error.data for some reason.\n // TODO: Replace with Object.entries when lib is updated to es2017.\n for (const key of Object.keys(customData)) {\n if (key.slice(-1) !== '_') {\n if (key in error) {\n console.warn(\n `Overwriting FirebaseError base field \"${key}\" can cause unexpected behavior.`\n );\n }\n error[key] = customData[key];\n }\n }\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? value.toString() : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Constants used in the Firebase Storage library.\n */\n\n/**\n * Domain name for firebase storage.\n */\nexport const DEFAULT_HOST = 'firebasestorage.googleapis.com';\n\n/**\n * The key in Firebase config json for the storage bucket.\n */\nexport const CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';\n\n/**\n * 2 minutes\n *\n * The timeout for all operations except upload.\n */\nexport const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;\n\n/**\n * 10 minutes\n *\n * The timeout for upload.\n */\nexport const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;\n\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport const MIN_SAFE_INTEGER = -9007199254740991;\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { CONFIG_STORAGE_BUCKET_KEY } from './constants';\n\nexport class FirebaseStorageError implements Error {\n private code_: string;\n private message_: string;\n private serverResponse_: string | null;\n private name_: string;\n\n constructor(code: Code, message: string) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n\n codeProp(): string {\n return this.code;\n }\n\n codeEquals(code: Code): boolean {\n return prependCode(code) === this.codeProp();\n }\n\n serverResponseProp(): string | null {\n return this.serverResponse_;\n }\n\n setServerResponseProp(serverResponse: string | null): void {\n this.serverResponse_ = serverResponse;\n }\n\n get name(): string {\n return this.name_;\n }\n\n get code(): string {\n return this.code_;\n }\n\n get message(): string {\n return this.message_;\n }\n\n get serverResponse(): null | string {\n return this.serverResponse_;\n }\n}\n\nexport const errors = {};\n\n/**\n * @enum {string}\n */\nexport type Code = string;\nexport const Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\n\nexport function prependCode(code: Code): string {\n return 'storage/' + code;\n}\n\nexport function unknown(): FirebaseStorageError {\n const message =\n 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\n\nexport function objectNotFound(path: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.OBJECT_NOT_FOUND,\n \"Object '\" + path + \"' does not exist.\"\n );\n}\n\nexport function bucketNotFound(bucket: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.BUCKET_NOT_FOUND,\n \"Bucket '\" + bucket + \"' does not exist.\"\n );\n}\n\nexport function projectNotFound(project: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.PROJECT_NOT_FOUND,\n \"Project '\" + project + \"' does not exist.\"\n );\n}\n\nexport function quotaExceeded(bucket: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.QUOTA_EXCEEDED,\n \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.'\n );\n}\n\nexport function unauthenticated(): FirebaseStorageError {\n const message =\n 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\n\nexport function unauthorized(path: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.UNAUTHORIZED,\n \"User does not have permission to access '\" + path + \"'.\"\n );\n}\n\nexport function retryLimitExceeded(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.RETRY_LIMIT_EXCEEDED,\n 'Max retry time for operation exceeded, please try again.'\n );\n}\n\nexport function invalidChecksum(\n path: string,\n checksum: string,\n calculated: string\n): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_CHECKSUM,\n \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\"\n );\n}\n\nexport function canceled(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.CANCELED,\n 'User canceled the upload/download.'\n );\n}\n\nexport function invalidEventName(name: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_EVENT_NAME,\n \"Invalid event name '\" + name + \"'.\"\n );\n}\n\nexport function invalidUrl(url: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_URL,\n \"Invalid URL '\" + url + \"'.\"\n );\n}\n\nexport function invalidDefaultBucket(bucket: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_DEFAULT_BUCKET,\n \"Invalid default bucket '\" + bucket + \"'.\"\n );\n}\n\nexport function noDefaultBucket(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.NO_DEFAULT_BUCKET,\n 'No default bucket ' +\n \"found. Did you set the '\" +\n CONFIG_STORAGE_BUCKET_KEY +\n \"' property when initializing the app?\"\n );\n}\n\nexport function cannotSliceBlob(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.CANNOT_SLICE_BLOB,\n 'Cannot slice blob for upload. Please retry the upload.'\n );\n}\n\nexport function serverFileWrongSize(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.SERVER_FILE_WRONG_SIZE,\n 'Server recorded incorrect upload file size, please retry the upload.'\n );\n}\n\nexport function noDownloadURL(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.NO_DOWNLOAD_URL,\n 'The given file does not have any download URLs.'\n );\n}\n\nexport function invalidArgument(\n index: number,\n fnName: string,\n message: string\n): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_ARGUMENT,\n 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message\n );\n}\n\nexport function invalidArgumentCount(\n argMin: number,\n argMax: number,\n fnName: string,\n real: number\n): FirebaseStorageError {\n let countPart;\n let plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n } else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(\n Code.INVALID_ARGUMENT_COUNT,\n 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.'\n );\n}\n\nexport function appDeleted(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.APP_DELETED,\n 'The Firebase app was deleted.'\n );\n}\n\n/**\n * @param name The name of the operation that was invalid.\n */\nexport function invalidRootOperation(name: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_ROOT_OPERATION,\n \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\"\n );\n}\n\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nexport function invalidFormat(\n format: string,\n message: string\n): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_FORMAT,\n \"String does not match format '\" + format + \"': \" + message\n );\n}\n\n/**\n * @param message A message describing the internal error.\n */\nexport function internalError(message: string): FirebaseStorageError {\n throw new FirebaseStorageError(\n Code.INTERNAL_ERROR,\n 'Internal error: ' + message\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as errorsExports from './error';\n\n/**\n * @enum {string}\n */\nexport type StringFormat = string;\nexport const StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\n\nexport function formatValidator(stringFormat: unknown): void {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n\n/**\n * @struct\n */\nexport class StringData {\n contentType: string | null;\n\n constructor(public data: Uint8Array, contentType?: string | null) {\n this.contentType = contentType || null;\n }\n}\n\nexport function dataFromString(\n format: StringFormat,\n stringData: string\n): StringData {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(stringData));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, stringData));\n case StringFormat.DATA_URL:\n return new StringData(\n dataURLBytes_(stringData),\n dataURLContentType_(stringData)\n );\n default:\n // do nothing\n }\n\n // assert(false);\n throw errorsExports.unknown();\n}\n\nexport function utf8Bytes_(value: string): Uint8Array {\n const b: number[] = [];\n for (let i = 0; i < value.length; i++) {\n let c = value.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n } else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n } else {\n if ((c & 64512) === 55296) {\n // The start of a surrogate pair.\n const valid =\n i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n } else {\n const hi = c;\n const lo = value.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(\n 240 | (c >> 18),\n 128 | ((c >> 12) & 63),\n 128 | ((c >> 6) & 63),\n 128 | (c & 63)\n );\n }\n } else {\n if ((c & 64512) === 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n } else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\n\nexport function percentEncodedBytes_(value: string): Uint8Array {\n let decoded;\n try {\n decoded = decodeURIComponent(value);\n } catch (e) {\n throw errorsExports.invalidFormat(\n StringFormat.DATA_URL,\n 'Malformed data URL.'\n );\n }\n return utf8Bytes_(decoded);\n}\n\nexport function base64Bytes_(format: StringFormat, value: string): Uint8Array {\n switch (format) {\n case StringFormat.BASE64: {\n const hasMinus = value.indexOf('-') !== -1;\n const hasUnder = value.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n const invalidChar = hasMinus ? '-' : '_';\n throw errorsExports.invalidFormat(\n format,\n \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\"\n );\n }\n break;\n }\n case StringFormat.BASE64URL: {\n const hasPlus = value.indexOf('+') !== -1;\n const hasSlash = value.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n const invalidChar = hasPlus ? '+' : '/';\n throw errorsExports.invalidFormat(\n format,\n \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\"\n );\n }\n value = value.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n default:\n // do nothing\n }\n let bytes;\n try {\n bytes = atob(value);\n } catch (e) {\n throw errorsExports.invalidFormat(format, 'Invalid character found');\n }\n const array = new Uint8Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n\n/**\n * @struct\n */\nclass DataURLParts {\n base64: boolean = false;\n contentType: string | null = null;\n rest: string;\n\n constructor(dataURL: string) {\n const matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw errorsExports.invalidFormat(\n StringFormat.DATA_URL,\n \"Must be formatted 'data:[<mediatype>][;base64],<data>\"\n );\n }\n const middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n}\n\nexport function dataURLBytes_(dataUrl: string): Uint8Array {\n const parts = new DataURLParts(dataUrl);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n } else {\n return percentEncodedBytes_(parts.rest);\n }\n}\n\nexport function dataURLContentType_(dataUrl: string): string | null {\n const parts = new DataURLParts(dataUrl);\n return parts.contentType;\n}\n\nfunction endsWith(s: string, end: string): boolean {\n const longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n\n return s.substring(s.length - end.length) === end;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Enumerations used for upload tasks.\n */\n\n/**\n * Enum for task events.\n * @enum {string}\n */\nexport type TaskEvent = string;\nexport const TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\n\n/**\n * Internal enum for task state.\n * @enum {string}\n */\nexport type InternalTaskState = string;\nexport const InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\n\n/**\n * External (API-surfaced) enum for task state.\n * @enum {string}\n */\nexport type TaskState = string;\nexport const TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\n\nexport function taskStateFromInternalTaskState(\n state: InternalTaskState\n): TaskState {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview A lightweight wrapper around XMLHttpRequest with a\n * goog.net.XhrIo-like interface.\n */\n\nexport interface Headers {\n [name: string]: string | number;\n}\n\nexport interface XhrIo {\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string | null,\n headers?: Headers\n ): Promise<XhrIo>;\n\n getErrorCode(): ErrorCode;\n\n getStatus(): number;\n\n getResponseText(): string;\n\n /**\n * Abort the request.\n */\n abort(): void;\n\n getResponseHeader(header: string): string | null;\n\n addUploadProgressListener(listener: (p1: ProgressEvent) => void): void;\n\n removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void;\n}\n\n/**\n * @enum{number}\n */\nexport enum ErrorCode {\n NO_ERROR = 0,\n NETWORK_ERROR = 1,\n ABORT = 2\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @return False if the object is undefined or null, true otherwise.\n */\nexport function isDef<T>(p: T | null | undefined): p is T {\n return p != null;\n}\n\nexport function isJustDef<T>(p: T | null | undefined): p is T | null {\n return p !== void 0;\n}\n\nexport function isFunction(p: unknown): p is Function {\n return typeof p === 'function';\n}\n\nexport function isObject(p: unknown): p is { [key: string]: unknown } | null {\n return typeof p === 'object';\n}\n\nexport function isNonNullObject(p: unknown): p is object {\n return isObject(p) && p !== null;\n}\n\nexport function isNonArrayObject(p: unknown): boolean {\n return isObject(p) && !Array.isArray(p);\n}\n\nexport function isString(p: unknown): p is string {\n return typeof p === 'string' || p instanceof String;\n}\n\nexport function isInteger(p: unknown): p is number {\n return isNumber(p) && Number.isInteger(p);\n}\n\nexport function isNumber(p: unknown): p is number {\n return typeof p === 'number' || p instanceof Number;\n}\n\nexport function isNativeBlob(p: unknown): p is Blob {\n return isNativeBlobDefined() && p instanceof Blob;\n}\n\nexport function isNativeBlobDefined(): boolean {\n return typeof Blob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as errorsExports from './error';\nimport * as type from './type';\nimport { Headers, XhrIo, ErrorCode } from './xhrio';\n\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nexport class NetworkXhrIo implements XhrIo {\n private xhr_: XMLHttpRequest;\n private errorCode_: ErrorCode;\n private sendPromise_: Promise<XhrIo>;\n private sent_: boolean = false;\n\n constructor() {\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = new Promise(resolve => {\n this.xhr_.addEventListener('abort', () => {\n this.errorCode_ = ErrorCode.ABORT;\n resolve(this);\n });\n this.xhr_.addEventListener('error', () => {\n this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve(this);\n });\n this.xhr_.addEventListener('load', () => {\n resolve(this);\n });\n });\n }\n\n /**\n * @override\n */\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string | null,\n headers?: Headers\n ): Promise<XhrIo> {\n if (this.sent_) {\n throw errorsExports.internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (type.isDef(headers)) {\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n this.xhr_.setRequestHeader(key, headers[key].toString());\n }\n }\n }\n if (type.isDef(body)) {\n this.xhr_.send(body);\n } else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n }\n\n /**\n * @override\n */\n getErrorCode(): ErrorCode {\n if (!this.sent_) {\n throw errorsExports.internalError(\n 'cannot .getErrorCode() before sending'\n );\n }\n return this.errorCode_;\n }\n\n /**\n * @override\n */\n getStatus(): number {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n } catch (e) {\n return -1;\n }\n }\n\n /**\n * @override\n */\n getResponseText(): string {\n if (!this.sent_) {\n throw errorsExports.internalError(\n 'cannot .getResponseText() before sending'\n );\n }\n return this.xhr_.responseText;\n }\n\n /**\n * Aborts the request.\n * @override\n */\n abort(): void {\n this.xhr_.abort();\n }\n\n /**\n * @override\n */\n getResponseHeader(header: string): string | null {\n return this.xhr_.getResponseHeader(header);\n }\n\n /**\n * @override\n */\n addUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n }\n\n /**\n * @override\n */\n removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Replacement for goog.net.XhrIoPool that works with fbs.XhrIo.\n */\nimport { XhrIo } from './xhrio';\nimport { NetworkXhrIo } from './xhrio_network';\n\n/**\n * Factory-like class for creating XhrIo instances.\n */\nexport class XhrIoPool {\n createXhrIo(): XhrIo {\n return new NetworkXhrIo();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Some methods copied from goog.fs.\n * We don't include goog.fs because it pulls in a bunch of Deferred code that\n * bloats the size of the released binary.\n */\nimport * as type from './type';\n\nfunction getBlobBuilder(): typeof IBlobBuilder | undefined {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n } else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n } else {\n return undefined;\n }\n}\n\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob(...args: Array<string | Blob | ArrayBuffer>): Blob {\n const BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n const bb = new BlobBuilder();\n for (let i = 0; i < args.length; i++) {\n bb.append(args[i]);\n }\n return bb.getBlob();\n } else {\n if (type.isNativeBlobDefined()) {\n return new Blob(args);\n } else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob: Blob, start: number, end: number): Blob | null {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n } else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n } else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport * as fs from './fs';\nimport { StringFormat, dataFromString } from './string';\nimport * as type from './type';\n\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nexport class FbsBlob {\n private data_!: Blob | Uint8Array;\n private size_: number;\n private type_: string;\n\n constructor(data: Blob | Uint8Array | ArrayBuffer, elideCopy?: boolean) {\n let size: number = 0;\n let blobType: string = '';\n if (type.isNativeBlob(data)) {\n this.data_ = data as Blob;\n size = (data as Blob).size;\n blobType = (data as Blob).type;\n } else if (data instanceof ArrayBuffer) {\n if (elideCopy) {\n this.data_ = new Uint8Array(data);\n } else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n } else if (data instanceof Uint8Array) {\n if (elideCopy) {\n this.data_ = data as Uint8Array;\n } else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data as Uint8Array);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n\n size(): number {\n return this.size_;\n }\n\n type(): string {\n return this.type_;\n }\n\n slice(startByte: number, endByte: number): FbsBlob | null {\n if (type.isNativeBlob(this.data_)) {\n const realBlob = this.data_ as Blob;\n const sliced = fs.sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n } else {\n const slice = new Uint8Array(\n (this.data_ as Uint8Array).buffer,\n startByte,\n endByte - startByte\n );\n return new FbsBlob(slice, true);\n }\n }\n\n static getBlob(...args: Array<string | FbsBlob>): FbsBlob | null {\n if (type.isNativeBlobDefined()) {\n const blobby: Array<Blob | Uint8Array | string> = args.map(\n (val: string | FbsBlob): Blob | Uint8Array | string => {\n if (val instanceof FbsBlob) {\n return val.data_;\n } else {\n return val;\n }\n }\n );\n return new FbsBlob(fs.getBlob.apply(null, blobby));\n } else {\n const uint8Arrays: Uint8Array[] = args.map(\n (val: string | FbsBlob): Uint8Array => {\n if (type.isString(val)) {\n return dataFromString(StringFormat.RAW, val as string).data;\n } else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return (val as FbsBlob).data_ as Uint8Array;\n }\n }\n );\n let finalLength = 0;\n uint8Arrays.forEach((array: Uint8Array): void => {\n finalLength += array.byteLength;\n });\n const merged = new Uint8Array(finalLength);\n let index = 0;\n uint8Arrays.forEach((array: Uint8Array) => {\n for (let i = 0; i < array.length; i++) {\n merged[index++] = array[i];\n }\n });\n return new FbsBlob(merged, true);\n }\n }\n\n uploadData(): Blob | Uint8Array {\n return this.data_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\nimport * as errorsExports from './error';\nimport { DEFAULT_HOST } from './constants';\n\n/**\n * @struct\n */\nexport class Location {\n private path_: string;\n\n constructor(public readonly bucket: string, path: string) {\n this.path_ = path;\n }\n\n get path(): string {\n return this.path_;\n }\n\n get isRoot(): boolean {\n return this.path.length === 0;\n }\n\n fullServerUrl(): string {\n const encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n }\n\n bucketOnlyServerUrl(): string {\n const encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n }\n\n static makeFromBucketSpec(bucketString: string): Location {\n let bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n } catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n } else {\n throw errorsExports.invalidDefaultBucket(bucketString);\n }\n }\n\n static makeFromUrl(url: string): Location {\n let location: Location | null = null;\n const bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\n\n function gsModify(loc: Location): void {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n const gsPath = '(/(.*))?$';\n const path = '(/([^?#]*).*)?$';\n const gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n const gsIndices = { bucket: 1, path: 3 };\n\n function httpModify(loc: Location): void {\n loc.path_ = decodeURIComponent(loc.path);\n }\n const version = 'v[A-Za-z0-9_]+';\n const hostRegex = DEFAULT_HOST.replace(/[.]/g, '\\\\.');\n const httpRegex = new RegExp(\n `^https?://${hostRegex}/${version}/b/${bucketDomain}/o${path}`,\n 'i'\n );\n const httpIndices = { bucket: 1, path: 3 };\n const groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n const captures = group.regex.exec(url);\n if (captures) {\n const bucketValue = captures[group.indices.bucket];\n let pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw errorsExports.invalidUrl(url);\n }\n return location;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as type from './type';\n\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(\n s: string\n): { [name: string]: unknown } | null {\n let obj;\n try {\n obj = JSON.parse(s);\n } catch (e) {\n return null;\n }\n if (type.isNonArrayObject(obj)) {\n return obj;\n } else {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Contains helper methods for manipulating paths.\n */\n\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path: string): string | null {\n if (path.length === 0) {\n return null;\n }\n const index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n const newPath = path.slice(0, index);\n return newPath;\n}\n\nexport function child(path: string, childPath: string): string {\n const canonicalChildPath = childPath\n .split('/')\n .filter(component => component.length > 0)\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n } else {\n return path + '/' + canonicalChildPath;\n }\n}\n\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path: string): string {\n const index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n } else {\n return path.slice(index + 1);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport { DEFAULT_HOST } from './constants';\nimport { UrlParams } from './requestinfo';\n\nexport function makeUrl(urlPart: string): string {\n return `https://${DEFAULT_HOST}/v0${urlPart}`;\n}\n\nexport function makeQueryString(params: UrlParams): string {\n const encode = encodeURIComponent;\n let queryPart = '?';\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n // @ts-ignore TODO: remove once typescript is upgraded to 3.5.x\n const nextPart = encode(key) + '=' + encode(params[key]);\n queryPart = queryPart + nextPart + '&';\n }\n }\n\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the metadata format\n */\nimport { Metadata } from '../metadata';\n\nimport { AuthWrapper } from './authwrapper';\nimport * as json from './json';\nimport { Location } from './location';\nimport * as path from './path';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport { Reference } from '../reference';\n\nexport function noXform_<T>(metadata: Metadata, value: T): T {\n return value;\n}\n\n/**\n * @struct\n */\nclass Mapping<T> {\n local: string;\n writable: boolean;\n xform: (p1: Metadata, p2?: T) => T | undefined;\n\n constructor(\n public server: string,\n local?: string | null,\n writable?: boolean,\n xform?: ((p1: Metadata, p2?: T) => T | undefined) | null\n ) {\n this.local = local || server;\n this.writable = !!writable;\n this.xform = xform || noXform_;\n }\n}\ntype Mappings = Array<Mapping<string> | Mapping<number>>;\n\nexport { Mappings };\n\nlet mappings_: Mappings | null = null;\n\nexport function xformPath(fullPath: string | undefined): string | undefined {\n if (!type.isString(fullPath) || fullPath.length < 2) {\n return fullPath;\n } else {\n return path.lastComponent(fullPath);\n }\n}\n\nexport function getMappings(): Mappings {\n if (mappings_) {\n return mappings_;\n }\n const mappings: Mappings = [];\n mappings.push(new Mapping<string>('bucket'));\n mappings.push(new Mapping<string>('generation'));\n mappings.push(new Mapping<string>('metageneration'));\n mappings.push(new Mapping<string>('name', 'fullPath', true));\n\n function mappingsXformPath(\n _metadata: Metadata,\n fullPath: string | undefined\n ): string | undefined {\n return xformPath(fullPath);\n }\n const nameMapping = new Mapping<string>('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(\n _metadata: Metadata,\n size: number | string | undefined\n ): number | undefined {\n if (type.isDef(size)) {\n return Number(size);\n } else {\n return size;\n }\n }\n const sizeMapping = new Mapping<number>('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping<number>('timeCreated'));\n mappings.push(new Mapping<string>('updated'));\n mappings.push(new Mapping<string>('md5Hash', null, true));\n mappings.push(new Mapping<string>('cacheControl', null, true));\n mappings.push(new Mapping<string>('contentDisposition', null, true));\n mappings.push(new Mapping<string>('contentEncoding', null, true));\n mappings.push(new Mapping<string>('contentLanguage', null, true));\n mappings.push(new Mapping<string>('contentType', null, true));\n mappings.push(new Mapping<string>('metadata', 'customMetadata', true));\n mappings_ = mappings;\n return mappings_;\n}\n\nexport function addRef(metadata: Metadata, authWrapper: AuthWrapper): void {\n function generateRef(): Reference {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const loc = new Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\n\nexport function fromResource(\n authWrapper: AuthWrapper,\n resource: { [name: string]: unknown },\n mappings: Mappings\n): Metadata {\n const metadata: Metadata = {} as Metadata;\n metadata['type'] = 'file';\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const mapping = mappings[i];\n metadata[mapping.local] = (mapping as Mapping<unknown>).xform(\n metadata,\n resource[mapping.server]\n );\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\n\nexport function fromResourceString(\n authWrapper: AuthWrapper,\n resourceString: string,\n mappings: Mappings\n): Metadata | null {\n const obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as Metadata;\n return fromResource(authWrapper, resource, mappings);\n}\n\nexport function downloadUrlFromResourceString(\n metadata: Metadata,\n resourceString: string\n): string | null {\n const obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n if (!type.isString(obj['downloadTokens'])) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return null;\n }\n const tokens: string = obj['downloadTokens'] as string;\n if (tokens.length === 0) {\n return null;\n }\n const encode = encodeURIComponent;\n const tokensList = tokens.split(',');\n const urls = tokensList.map((token: string): string => {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n const base = UrlUtils.makeUrl(urlPart);\n const queryString = UrlUtils.makeQueryString({\n alt: 'media',\n token\n });\n return base + queryString;\n });\n return urls[0];\n}\n\nexport function toResourceString(\n metadata: Metadata,\n mappings: Mappings\n): string {\n const resource: {\n [prop: string]: unknown;\n } = {};\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\n\nexport function metadataValidator(p: unknown): void {\n if (!type.isObject(p) || !p) {\n throw 'Expected Metadata object.';\n }\n for (const key in p) {\n if (p.hasOwnProperty(key)) {\n const val = p[key];\n if (key === 'customMetadata') {\n if (!type.isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n } else {\n if (type.isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the listOptions and listResult format\n */\nimport { AuthWrapper } from './authwrapper';\nimport { Location } from './location';\nimport * as json from './json';\nimport * as type from './type';\nimport { ListResult } from '../list';\nimport * as errors from './error';\n\n/**\n * Represents the simplified object metadata returned by List API.\n * Other fields are filtered because list in Firebase Rules does not grant\n * the permission to read the metadata.\n */\ninterface ListMetadataResponse {\n name: string;\n bucket: string;\n}\n\n/**\n * Represents the JSON response of List API.\n */\ninterface ListResultResponse {\n prefixes: string[];\n items: ListMetadataResponse[];\n nextPageToken?: string;\n}\n\nconst MAX_RESULTS_KEY = 'maxResults';\nconst MAX_MAX_RESULTS = 1000;\nconst PAGE_TOKEN_KEY = 'pageToken';\nconst PREFIXES_KEY = 'prefixes';\nconst ITEMS_KEY = 'items';\n\nfunction fromBackendResponse(\n authWrapper: AuthWrapper,\n resource: ListResultResponse\n): ListResult {\n const listResult: ListResult = {\n prefixes: [],\n items: [],\n nextPageToken: resource['nextPageToken']\n };\n const bucket = authWrapper.bucket();\n if (bucket === null) {\n throw errors.noDefaultBucket();\n }\n if (resource[PREFIXES_KEY]) {\n for (const path of resource[PREFIXES_KEY]) {\n const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\n const reference = authWrapper.makeStorageReference(\n new Location(bucket, pathWithoutTrailingSlash)\n );\n listResult.prefixes.push(reference);\n }\n }\n\n if (resource[ITEMS_KEY]) {\n for (const item of resource[ITEMS_KEY]) {\n const reference = authWrapper.makeStorageReference(\n new Location(bucket, item['name'])\n );\n listResult.items.push(reference);\n }\n }\n return listResult;\n}\n\nexport function fromResponseString(\n authWrapper: AuthWrapper,\n resourceString: string\n): ListResult | null {\n const obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = (obj as unknown) as ListResultResponse;\n return fromBackendResponse(authWrapper, resource);\n}\n\nexport function listOptionsValidator(p: unknown): void {\n if (!type.isObject(p) || !p) {\n throw 'Expected ListOptions object.';\n }\n for (const key in p) {\n if (key === MAX_RESULTS_KEY) {\n if (\n !type.isInteger(p[MAX_RESULTS_KEY]) ||\n (p[MAX_RESULTS_KEY] as number) <= 0\n ) {\n throw 'Expected maxResults to be a positive number.';\n }\n if ((p[MAX_RESULTS_KEY] as number) > 1000) {\n throw `Expected maxResults to be less than or equal to ${MAX_MAX_RESULTS}.`;\n }\n } else if (key === PAGE_TOKEN_KEY) {\n if (p[PAGE_TOKEN_KEY] && !type.isString(p[PAGE_TOKEN_KEY])) {\n throw 'Expected pageToken to be string.';\n }\n } else {\n throw 'Unknown option: ' + key;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirebaseStorageError } from './error';\nimport { Headers, XhrIo } from './xhrio';\n\nexport interface UrlParams {\n [name: string]: string | number;\n}\n\nexport class RequestInfo<T> {\n urlParams: UrlParams = {};\n headers: Headers = {};\n body: Blob | string | Uint8Array | null = null;\n\n errorHandler:\n | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)\n | null = null;\n\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n progressCallback: ((p1: number, p2: number) => void) | null = null;\n successCodes: number[] = [200];\n additionalRetryCodes: number[] = [];\n\n constructor(\n public url: string,\n public method: string,\n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n public handler: (p1: XhrIo, p2: string) => T,\n public timeout: number\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods for interacting with the network.\n */\n\nimport { Metadata } from '../metadata';\nimport { ListResult } from '../list';\nimport { AuthWrapper } from './authwrapper';\nimport { FbsBlob } from './blob';\nimport {\n FirebaseStorageError,\n cannotSliceBlob,\n unauthenticated,\n quotaExceeded,\n unauthorized,\n objectNotFound,\n serverFileWrongSize,\n unknown\n} from './error';\nimport { Location } from './location';\nimport * as MetadataUtils from './metadata';\nimport * as ListResultUtils from './list';\nimport { RequestInfo, UrlParams } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport { XhrIo } from './xhrio';\n\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nexport function handlerCheck(cndn: boolean): void {\n if (!cndn) {\n throw unknown();\n }\n}\n\nexport function metadataHandler(\n authWrapper: AuthWrapper,\n mappings: MetadataUtils.Mappings\n): (p1: XhrIo, p2: string) => Metadata {\n function handler(xhr: XhrIo, text: string): Metadata {\n const metadata = MetadataUtils.fromResourceString(\n authWrapper,\n text,\n mappings\n );\n handlerCheck(metadata !== null);\n return metadata as Metadata;\n }\n return handler;\n}\n\nexport function listHandler(\n authWrapper: AuthWrapper\n): (p1: XhrIo, p2: string) => ListResult {\n function handler(xhr: XhrIo, text: string): ListResult {\n const listResult = ListResultUtils.fromResponseString(authWrapper, text);\n handlerCheck(listResult !== null);\n return listResult as ListResult;\n }\n return handler;\n}\n\nexport function downloadUrlHandler(\n authWrapper: AuthWrapper,\n mappings: MetadataUtils.Mappings\n): (p1: XhrIo, p2: string) => string | null {\n function handler(xhr: XhrIo, text: string): string | null {\n const metadata = MetadataUtils.fromResourceString(\n authWrapper,\n text,\n mappings\n );\n handlerCheck(metadata !== null);\n return MetadataUtils.downloadUrlFromResourceString(\n metadata as Metadata,\n text\n );\n }\n return handler;\n}\n\nexport function sharedErrorHandler(\n location: Location\n): (p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError {\n function errorHandler(\n xhr: XhrIo,\n err: FirebaseStorageError\n ): FirebaseStorageError {\n let newErr;\n if (xhr.getStatus() === 401) {\n newErr = unauthenticated();\n } else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n } else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n } else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\n\nexport function objectErrorHandler(\n location: Location\n): (p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError {\n const shared = sharedErrorHandler(location);\n\n function errorHandler(\n xhr: XhrIo,\n err: FirebaseStorageError\n ): FirebaseStorageError {\n let newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\n\nexport function getMetadata(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings\n): RequestInfo<Metadata> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'GET';\n const timeout = authWrapper.maxOperationRetryTime();\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(authWrapper, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function list(\n authWrapper: AuthWrapper,\n location: Location,\n delimiter?: string,\n pageToken?: string | null,\n maxResults?: number | null\n): RequestInfo<ListResult> {\n const urlParams: UrlParams = {};\n if (location.isRoot) {\n urlParams['prefix'] = '';\n } else {\n urlParams['prefix'] = location.path + '/';\n }\n if (delimiter && delimiter.length > 0) {\n urlParams['delimiter'] = delimiter;\n }\n if (pageToken) {\n urlParams['pageToken'] = pageToken;\n }\n if (maxResults) {\n urlParams['maxResults'] = maxResults;\n }\n const urlPart = location.bucketOnlyServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'GET';\n const timeout = authWrapper.maxOperationRetryTime();\n const requestInfo = new RequestInfo(\n url,\n method,\n listHandler(authWrapper),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\nexport function getDownloadUrl(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings\n): RequestInfo<string | null> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'GET';\n const timeout = authWrapper.maxOperationRetryTime();\n const requestInfo = new RequestInfo(\n url,\n method,\n downloadUrlHandler(authWrapper, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function updateMetadata(\n authWrapper: AuthWrapper,\n location: Location,\n metadata: Metadata,\n mappings: MetadataUtils.Mappings\n): RequestInfo<Metadata> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'PATCH';\n const body = MetadataUtils.toResourceString(metadata, mappings);\n const headers = { 'Content-Type': 'application/json; charset=utf-8' };\n const timeout = authWrapper.maxOperationRetryTime();\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(authWrapper, mappings),\n timeout\n );\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function deleteObject(\n authWrapper: AuthWrapper,\n location: Location\n): RequestInfo<void> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'DELETE';\n const timeout = authWrapper.maxOperationRetryTime();\n\n function handler(_xhr: XhrIo, _text: string): void {}\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function determineContentType_(\n metadata: Metadata | null,\n blob: FbsBlob | null\n): string {\n return (\n (metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream'\n );\n}\n\nexport function metadataForUpload_(\n location: Location,\n blob: FbsBlob,\n metadata?: Metadata | null\n): Metadata {\n const metadataClone = Object.assign({}, metadata);\n metadataClone['fullPath'] = location.path;\n metadataClone['size'] = blob.size();\n if (!metadataClone['contentType']) {\n metadataClone['contentType'] = determineContentType_(null, blob);\n }\n return metadataClone;\n}\n\nexport function multipartUpload(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<Metadata> {\n const urlPart = location.bucketOnlyServerUrl();\n const headers: { [prop: string]: string } = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n\n function genBoundary(): string {\n let str = '';\n for (let i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n const boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n const metadata_ = metadataForUpload_(location, blob, metadata);\n const metadataString = MetadataUtils.toResourceString(metadata_, mappings);\n const preBlobPart =\n '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata_['contentType'] +\n '\\r\\n\\r\\n';\n const postBlobPart = '\\r\\n--' + boundary + '--';\n const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n const urlParams: UrlParams = { name: metadata_['fullPath']! };\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'POST';\n const timeout = authWrapper.maxUploadRetryTime();\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(authWrapper, mappings),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nexport class ResumableUploadStatus {\n finalized: boolean;\n metadata: Metadata | null;\n\n constructor(\n public current: number,\n public total: number,\n finalized?: boolean,\n metadata?: Metadata | null\n ) {\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n}\n\nexport function checkResumeHeader_(xhr: XhrIo, allowed?: string[]): string {\n let status: string | null = null;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n } catch (e) {\n handlerCheck(false);\n }\n const allowedStatus = allowed || ['active'];\n handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);\n return status as string;\n}\n\nexport function createResumableUpload(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<string> {\n const urlPart = location.bucketOnlyServerUrl();\n const metadataForUpload = metadataForUpload_(location, blob, metadata);\n const urlParams: UrlParams = { name: metadataForUpload['fullPath']! };\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'POST';\n const headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType']!,\n 'Content-Type': 'application/json; charset=utf-8'\n };\n const body = MetadataUtils.toResourceString(metadataForUpload, mappings);\n const timeout = authWrapper.maxUploadRetryTime();\n\n function handler(xhr: XhrIo): string {\n checkResumeHeader_(xhr);\n let url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n } catch (e) {\n handlerCheck(false);\n }\n handlerCheck(type.isString(url));\n return url as string;\n }\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(\n authWrapper: AuthWrapper,\n location: Location,\n url: string,\n blob: FbsBlob\n): RequestInfo<ResumableUploadStatus> {\n const headers = { 'X-Goog-Upload-Command': 'query' };\n\n function handler(xhr: XhrIo): ResumableUploadStatus {\n const status = checkResumeHeader_(xhr, ['active', 'final']);\n let sizeString: string | null = null;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n } catch (e) {\n handlerCheck(false);\n }\n\n if (!sizeString) {\n // null or empty string\n handlerCheck(false);\n }\n\n const size = Number(sizeString);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n const method = 'POST';\n const timeout = authWrapper.maxUploadRetryTime();\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport const resumableUploadChunkSize: number = 256 * 1024;\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(\n location: Location,\n authWrapper: AuthWrapper,\n url: string,\n blob: FbsBlob,\n chunkSize: number,\n mappings: MetadataUtils.Mappings,\n status?: ResumableUploadStatus | null,\n progressCallback?: ((p1: number, p2: number) => void) | null\n): RequestInfo<ResumableUploadStatus> {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n const status_ = new ResumableUploadStatus(0, 0);\n if (status) {\n status_.current = status.current;\n status_.total = status.total;\n } else {\n status_.current = 0;\n status_.total = blob.size();\n }\n if (blob.size() !== status_.total) {\n throw serverFileWrongSize();\n }\n const bytesLeft = status_.total - status_.current;\n let bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n const startByte = status_.current;\n const endByte = startByte + bytesToUpload;\n const uploadCommand =\n bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n const headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status_.current\n };\n const body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n\n function handler(xhr: XhrIo, text: string): ResumableUploadStatus {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n const uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n const newCurrent = status_.current + bytesToUpload;\n const size = blob.size();\n let metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n } else {\n metadata = null;\n }\n return new ResumableUploadStatus(\n newCurrent,\n size,\n uploadStatus === 'final',\n metadata\n );\n }\n const method = 'POST';\n const timeout = authWrapper.maxUploadRetryTime();\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as type from './type';\nimport { FirebaseStorageError } from './error';\n\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error | FirebaseStorageError) => void;\nexport type CompleteFn = () => void;\nexport type Unsubscribe = () => void;\n\nexport interface StorageObserver<T> {\n next?: NextFn<T> | null;\n error?: ErrorFn | null;\n complete?: CompleteFn | null;\n}\n\nexport type Subscribe<T> = (\n next?: NextFn<T> | StorageObserver<T> | null,\n error?: ErrorFn | null,\n complete?: CompleteFn | null\n) => Unsubscribe;\n\n/**\n * @struct\n */\nexport class Observer<T> implements StorageObserver<T> {\n next?: NextFn<T> | null;\n error?: ErrorFn | null;\n complete?: CompleteFn | null;\n\n constructor(\n nextOrObserver?: NextFn<T> | StorageObserver<T> | null,\n error?: ErrorFn | null,\n complete?: CompleteFn | null\n ) {\n const asFunctions =\n type.isFunction(nextOrObserver) ||\n type.isDef(error) ||\n type.isDef(complete);\n if (asFunctions) {\n this.next = nextOrObserver as NextFn<T> | null;\n this.error = error || null;\n this.complete = complete || null;\n } else {\n const observer = nextOrObserver as {\n next?: NextFn<T> | null;\n error?: ErrorFn | null;\n complete?: CompleteFn | null;\n };\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { TaskState } from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport { Reference } from './reference';\nimport { UploadTask } from './task';\n\nexport class UploadTaskSnapshot {\n constructor(\n readonly bytesTransferred: number,\n readonly totalBytes: number,\n readonly state: TaskState,\n readonly metadata: Metadata | null,\n readonly task: UploadTask,\n readonly ref: Reference\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as ListOptionsUtils from './list';\nimport * as type from './type';\n\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nexport function validate(\n name: string,\n specs: ArgSpec[],\n passed: IArguments\n): void {\n let minArgs = specs.length;\n const maxArgs = specs.length;\n for (let i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n const validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw errorsExports.invalidArgumentCount(\n minArgs,\n maxArgs,\n name,\n passed.length\n );\n }\n for (let i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n } catch (e) {\n if (e instanceof Error) {\n throw errorsExports.invalidArgument(i, name, e.message);\n } else {\n throw errorsExports.invalidArgument(i, name, e);\n }\n }\n }\n}\n\n/**\n * @struct\n */\nexport class ArgSpec {\n validator: (p1: unknown) => void;\n optional: boolean;\n\n constructor(validator: (p1: unknown) => void, optional?: boolean) {\n const self = this;\n this.validator = function(p: unknown) {\n if (self.optional && !type.isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!optional;\n }\n}\n\nexport function and_(\n v1: (p1: unknown) => void,\n v2: (p1: unknown) => void\n): (p1: unknown) => void {\n return function(p) {\n v1(p);\n v2(p);\n };\n}\n\nexport function stringSpec(\n validator?: (p1: unknown) => void | null,\n optional?: boolean\n): ArgSpec {\n function stringValidator(p: unknown): void {\n if (!type.isString(p)) {\n throw 'Expected string.';\n }\n }\n let chainedValidator;\n if (validator) {\n chainedValidator = and_(stringValidator, validator);\n } else {\n chainedValidator = stringValidator;\n }\n return new ArgSpec(chainedValidator, optional);\n}\n\nexport function uploadDataSpec(): ArgSpec {\n function validator(p: unknown): void {\n const valid =\n p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (type.isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new ArgSpec(validator);\n}\n\nexport function metadataSpec(optional?: boolean): ArgSpec {\n return new ArgSpec(MetadataUtils.metadataValidator, optional);\n}\n\nexport function listOptionSpec(optional?: boolean): ArgSpec {\n return new ArgSpec(ListOptionsUtils.listOptionsValidator, optional);\n}\n\nexport function nonNegativeNumberSpec(): ArgSpec {\n function validator(p: unknown): void {\n const valid = type.isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new ArgSpec(validator);\n}\n\nexport function looseObjectSpec(\n validator?: ((p1: unknown) => void) | null,\n optional?: boolean\n): ArgSpec {\n function isLooseObjectValidator(p: unknown): void {\n const isLooseObject = p === null || (type.isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (validator !== undefined && validator !== null) {\n validator(p);\n }\n }\n return new ArgSpec(isLooseObjectValidator, optional);\n}\n\nexport function nullFunctionSpec(optional?: boolean): ArgSpec {\n function validator(p: unknown): void {\n const valid = p === null || type.isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new ArgSpec(validator, optional);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nexport function async(f: Function): Function {\n return (...argsToForward: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => f(...argsToForward));\n };\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { FbsBlob } from './implementation/blob';\nimport { FirebaseStorageError, Code, canceled } from './implementation/error';\nimport {\n InternalTaskState,\n TaskEvent,\n TaskState,\n taskStateFromInternalTaskState\n} from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport {\n CompleteFn,\n ErrorFn,\n NextFn,\n Observer,\n StorageObserver,\n Subscribe,\n Unsubscribe\n} from './implementation/observer';\nimport { Request } from './implementation/request';\nimport { UploadTaskSnapshot } from './tasksnapshot';\nimport {\n ArgSpec,\n nullFunctionSpec,\n looseObjectSpec,\n stringSpec,\n validate\n} from './implementation/args';\nimport { async as fbsAsync } from './implementation/async';\nimport { Location } from './implementation/location';\nimport * as fbsMetadata from './implementation/metadata';\nimport * as fbsRequests from './implementation/requests';\nimport * as typeUtils from './implementation/type';\nimport { Reference } from './reference';\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nexport class UploadTask {\n private ref_: Reference;\n private authWrapper_: AuthWrapper;\n private location_: Location;\n private blob_: FbsBlob;\n private metadata_: Metadata | null;\n private mappings_: fbsMetadata.Mappings;\n private transferred_: number = 0;\n private needToFetchStatus_: boolean = false;\n private needToFetchMetadata_: boolean = false;\n private observers_: Array<Observer<UploadTaskSnapshot>> = [];\n private resumable_: boolean;\n private state_: InternalTaskState;\n private error_: Error | null = null;\n private uploadUrl_: string | null = null;\n private request_: Request<unknown> | null = null;\n private chunkMultiplier_: number = 1;\n private errorHandler_: (p1: FirebaseStorageError) => void;\n private metadataErrorHandler_: (p1: FirebaseStorageError) => void;\n private resolve_: ((p1: UploadTaskSnapshot) => void) | null = null;\n private reject_: ((p1: Error) => void) | null = null;\n private promise_: Promise<UploadTaskSnapshot>;\n\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n constructor(\n ref: Reference,\n authWrapper: AuthWrapper,\n location: Location,\n mappings: fbsMetadata.Mappings,\n blob: FbsBlob,\n metadata: Metadata | null = null\n ) {\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = error => {\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n if (error.codeEquals(Code.CANCELED)) {\n this.needToFetchStatus_ = true;\n this.completeTransitions_();\n } else {\n this.error_ = error;\n this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = error => {\n this.request_ = null;\n if (error.codeEquals(Code.CANCELED)) {\n this.completeTransitions_();\n } else {\n this.error_ = error;\n this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = new Promise((resolve, reject) => {\n this.resolve_ = resolve;\n this.reject_ = reject;\n this.start_();\n });\n\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, () => {});\n }\n\n private makeProgressCallback_(): (p1: number, p2: number) => void {\n const sizeBefore = this.transferred_;\n return loaded => this.updateProgress_(sizeBefore + loaded);\n }\n\n private shouldDoResumable_(blob: FbsBlob): boolean {\n return blob.size() > 256 * 1024;\n }\n\n private start_(): void {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n } else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n } else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n } else {\n this.continueUpload_();\n }\n }\n }\n } else {\n this.oneShotUpload_();\n }\n }\n\n private resolveToken_(callback: (p1: string | null) => void): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.authWrapper_.getAuthToken().then(authToken => {\n switch (this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n }\n\n // TODO(andysoto): assert false\n\n private createResumable_(): void {\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.createResumableUpload(\n this.authWrapper_,\n this.location_,\n this.mappings_,\n this.blob_,\n this.metadata_\n );\n const createRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = createRequest;\n createRequest.getPromise().then((url: string) => {\n this.request_ = null;\n this.uploadUrl_ = url;\n this.needToFetchStatus_ = false;\n this.completeTransitions_();\n }, this.errorHandler_);\n });\n }\n\n private fetchStatus_(): void {\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this.uploadUrl_ as string;\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.getResumableUploadStatus(\n this.authWrapper_,\n this.location_,\n url,\n this.blob_\n );\n const statusRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = statusRequest;\n statusRequest.getPromise().then(status => {\n status = status as fbsRequests.ResumableUploadStatus;\n this.request_ = null;\n this.updateProgress_(status.current);\n this.needToFetchStatus_ = false;\n if (status.finalized) {\n this.needToFetchMetadata_ = true;\n }\n this.completeTransitions_();\n }, this.errorHandler_);\n });\n }\n\n private continueUpload_(): void {\n const chunkSize =\n fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n const status = new fbsRequests.ResumableUploadStatus(\n this.transferred_,\n this.blob_.size()\n );\n\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this.uploadUrl_ as string;\n this.resolveToken_(authToken => {\n let requestInfo;\n try {\n requestInfo = fbsRequests.continueResumableUpload(\n this.location_,\n this.authWrapper_,\n url,\n this.blob_,\n chunkSize,\n this.mappings_,\n status,\n this.makeProgressCallback_()\n );\n } catch (e) {\n this.error_ = e;\n this.transition_(InternalTaskState.ERROR);\n return;\n }\n const uploadRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then((newStatus: fbsRequests.ResumableUploadStatus) => {\n this.increaseMultiplier_();\n this.request_ = null;\n this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n this.metadata_ = newStatus.metadata;\n this.transition_(InternalTaskState.SUCCESS);\n } else {\n this.completeTransitions_();\n }\n }, this.errorHandler_);\n });\n }\n\n private increaseMultiplier_(): void {\n const currentSize =\n fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n }\n\n private fetchMetadata_(): void {\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.getMetadata(\n this.authWrapper_,\n this.location_,\n this.mappings_\n );\n const metadataRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = metadataRequest;\n metadataRequest.getPromise().then(metadata => {\n this.request_ = null;\n this.metadata_ = metadata;\n this.transition_(InternalTaskState.SUCCESS);\n }, this.metadataErrorHandler_);\n });\n }\n\n private oneShotUpload_(): void {\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.multipartUpload(\n this.authWrapper_,\n this.location_,\n this.mappings_,\n this.blob_,\n this.metadata_\n );\n const multipartRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = multipartRequest;\n multipartRequest.getPromise().then(metadata => {\n this.request_ = null;\n this.metadata_ = metadata;\n this.updateProgress_(this.blob_.size());\n this.transition_(InternalTaskState.SUCCESS);\n }, this.errorHandler_);\n });\n }\n\n private updateProgress_(transferred: number): void {\n const old = this.transferred_;\n this.transferred_ = transferred;\n\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n }\n\n private transition_(state: InternalTaskState): void {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n const wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n default: // Ignore\n }\n }\n\n private completeTransitions_(): void {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n }\n\n get snapshot(): UploadTaskSnapshot {\n const externalState = taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(\n this.transferred_,\n this.blob_.size(),\n externalState,\n this.metadata_,\n this,\n this.ref_\n );\n }\n\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n on(\n type: TaskEvent,\n nextOrObserver?:\n | NextFn<UploadTaskSnapshot>\n | StorageObserver<UploadTaskSnapshot>\n | null,\n error?: ErrorFn | null,\n completed?: CompleteFn | null\n ): Unsubscribe | Subscribe<UploadTaskSnapshot> {\n function typeValidator(): void {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw `Expected one of the event types: [${TaskEvent.STATE_CHANGED}].`;\n }\n }\n const nextOrObserverMessage =\n 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n const nextValidator = nullFunctionSpec(true).validator;\n const observerValidator = looseObjectSpec(null, true).validator;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function nextOrObserverValidator(p: any): void {\n try {\n nextValidator(p);\n return;\n } catch (e) {}\n try {\n observerValidator(p);\n const anyDefined =\n typeUtils.isJustDef(p['next']) ||\n typeUtils.isJustDef(p['error']) ||\n typeUtils.isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n } catch (e) {\n throw nextOrObserverMessage;\n }\n }\n const specs = [\n stringSpec(typeValidator),\n looseObjectSpec(nextOrObserverValidator, true),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n validate('on', specs, arguments);\n const self = this;\n\n function makeBinder(\n specs: ArgSpec[] | null\n ): Subscribe<UploadTaskSnapshot> {\n function binder(\n nextOrObserver?:\n | NextFn<UploadTaskSnapshot>\n | StorageObserver<UploadTaskSnapshot>\n | null,\n error?: ErrorFn | null,\n complete?: CompleteFn | null\n ): () => void {\n if (specs !== null) {\n validate('on', specs, arguments);\n }\n const observer = new Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return () => {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n\n function binderNextOrObserverValidator(p: unknown): void {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n const binderSpecs = [\n looseObjectSpec(binderNextOrObserverValidator),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n const typeOnly = !(\n typeUtils.isJustDef(nextOrObserver) ||\n typeUtils.isJustDef(error) ||\n typeUtils.isJustDef(completed)\n );\n if (typeOnly) {\n return makeBinder(binderSpecs);\n } else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n }\n\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n then<U>(\n onFulfilled?: ((value: UploadTaskSnapshot) => U | Promise<U>) | null,\n onRejected?: ((error: Error) => U | Promise<U>) | null\n ): Promise<U> {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then<U>(\n onFulfilled as (value: UploadTaskSnapshot) => U | Promise<U>,\n onRejected as ((error: unknown) => Promise<never>) | null\n );\n }\n\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n catch<T>(onRejected: (p1: Error) => T | Promise<T>): Promise<T> {\n return this.then(null, onRejected);\n }\n\n /**\n * Adds the given observer.\n */\n private addObserver_(observer: Observer<UploadTaskSnapshot>): void {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n }\n\n /**\n * Removes the given observer.\n */\n private removeObserver_(observer: Observer<UploadTaskSnapshot>): void {\n const i = this.observers_.indexOf(observer);\n if (i !== -1) {\n this.observers_.splice(i, 1);\n }\n }\n\n private notifyObservers_(): void {\n this.finishPromise_();\n const observers = this.observers_.slice();\n observers.forEach(observer => {\n this.notifyObserver_(observer);\n });\n }\n\n private finishPromise_(): void {\n if (this.resolve_ !== null) {\n let triggered = true;\n switch (taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n fbsAsync(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n const toCall = this.reject_ as (p1: Error) => void;\n fbsAsync(toCall.bind(null, this.error_ as Error))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n }\n\n private notifyObserver_(observer: Observer<UploadTaskSnapshot>): void {\n const externalState = taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error) {\n fbsAsync(observer.error.bind(observer, this.error_ as Error))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error) {\n fbsAsync(observer.error.bind(observer, this.error_ as Error))();\n }\n }\n }\n\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n resume(): boolean {\n validate('resume', [], arguments);\n const valid =\n this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n }\n\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n pause(): boolean {\n validate('pause', [], arguments);\n const valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n }\n\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n cancel(): boolean {\n validate('cancel', [], arguments);\n const valid =\n this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines the Firebase Storage Reference class.\n */\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { FbsBlob } from './implementation/blob';\nimport * as errorsExports from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as metadata from './implementation/metadata';\nimport * as path from './implementation/path';\nimport * as requests from './implementation/requests';\nimport {\n StringFormat,\n formatValidator,\n dataFromString\n} from './implementation/string';\nimport * as type from './implementation/type';\nimport { Metadata } from './metadata';\nimport { Service } from './service';\nimport { UploadTask } from './task';\nimport { ListOptions, ListResult } from './list';\nimport {\n listOptionSpec,\n stringSpec,\n validate,\n metadataSpec,\n uploadDataSpec\n} from './implementation/args';\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs://<bucket>/<object-path>\n * http[s]://firebasestorage.googleapis.com/\n * <api-version>/b/<bucket>/o/<object-path>\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nexport class Reference {\n protected location: Location;\n\n constructor(protected authWrapper: AuthWrapper, location: string | Location) {\n if (location instanceof Location) {\n this.location = location;\n } else {\n this.location = Location.makeFromUrl(location);\n }\n }\n\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs://<bucket>/<object-path>\n * @override\n */\n toString(): string {\n validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n }\n\n protected newRef(authWrapper: AuthWrapper, location: Location): Reference {\n return new Reference(authWrapper, location);\n }\n\n protected mappings(): metadata.Mappings {\n return metadata.getMappings();\n }\n\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n child(childPath: string): Reference {\n validate('child', [stringSpec()], arguments);\n const newPath = path.child(this.location.path, childPath);\n const location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n }\n\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get parent(): Reference | null {\n const newPath = path.parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n const location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n }\n\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get root(): Reference {\n const location = new Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n }\n\n get bucket(): string {\n return this.location.bucket;\n }\n\n get fullPath(): string {\n return this.location.path;\n }\n\n get name(): string {\n return path.lastComponent(this.location.path);\n }\n\n get storage(): Service {\n return this.authWrapper.service();\n }\n\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n put(\n data: Blob | Uint8Array | ArrayBuffer,\n metadata: Metadata | null = null\n ): UploadTask {\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new UploadTask(\n this,\n this.authWrapper,\n this.location,\n this.mappings(),\n new FbsBlob(data),\n metadata\n );\n }\n\n /**\n * Uploads a string to this object's location.\n * @param value The string to upload.\n * @param format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n putString(\n value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: Metadata\n ): UploadTask {\n validate(\n 'putString',\n [stringSpec(), stringSpec(formatValidator, true), metadataSpec(true)],\n arguments\n );\n this.throwIfRoot_('putString');\n const data = dataFromString(format, value);\n const metadataClone = Object.assign({}, metadata);\n if (\n !type.isDef(metadataClone['contentType']) &&\n type.isDef(data.contentType)\n ) {\n metadataClone['contentType'] = data.contentType!;\n }\n return new UploadTask(\n this,\n this.authWrapper,\n this.location,\n this.mappings(),\n new FbsBlob(data.data, true),\n metadataClone\n );\n }\n\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n delete(): Promise<void> {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.deleteObject(\n this.authWrapper,\n this.location\n );\n return this.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: listAll may potentially consume too many resources if there are\n * too many results.\n *\n * @return A Promise that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\n listAll(): Promise<ListResult> {\n validate('listAll', [], arguments);\n const accumulator = {\n prefixes: [],\n items: []\n };\n return this.listAllHelper(accumulator).then(() => accumulator);\n }\n\n private async listAllHelper(\n accumulator: ListResult,\n pageToken?: string\n ): Promise<void> {\n const opt: ListOptions = {\n // maxResults is 1000 by default.\n pageToken\n };\n const nextPage = await this.list(opt);\n accumulator.prefixes.push(...nextPage.prefixes);\n accumulator.items.push(...nextPage.items);\n if (nextPage.nextPageToken != null) {\n await this.listAllHelper(accumulator, nextPage.nextPageToken);\n }\n }\n\n /**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure.\n * Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n *\n * @param options See ListOptions for details.\n * @return A Promise that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\n list(options?: ListOptions | null): Promise<ListResult> {\n validate('list', [listOptionSpec(true)], arguments);\n const self = this;\n return this.authWrapper.getAuthToken().then(authToken => {\n const op = options || {};\n const requestInfo = requests.list(\n self.authWrapper,\n self.location,\n /*delimiter= */ '/',\n op.pageToken,\n op.maxResults\n );\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n getMetadata(): Promise<Metadata> {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.getMetadata(\n this.authWrapper,\n this.location,\n this.mappings()\n );\n return this.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n updateMetadata(metadata: Metadata): Promise<Metadata> {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.updateMetadata(\n this.authWrapper,\n this.location,\n metadata,\n this.mappings()\n );\n return this.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n getDownloadURL(): Promise<string> {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.getDownloadUrl(\n this.authWrapper,\n this.location,\n this.mappings()\n );\n return this.authWrapper\n .makeRequest(requestInfo, authToken)\n .getPromise()\n .then(url => {\n if (url === null) {\n throw errorsExports.noDownloadURL();\n }\n return url;\n });\n });\n }\n\n private throwIfRoot_(name: string): void {\n if (this.location.path === '') {\n throw errorsExports.invalidRootOperation(name);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirebaseStorageError } from './error';\nimport { Request } from './request';\n\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nexport class FailRequest<T> implements Request<T> {\n promise_: Promise<T>;\n\n constructor(error: FirebaseStorageError) {\n this.promise_ = Promise.reject<T>(error);\n }\n\n /** @inheritDoc */\n getPromise(): Promise<T> {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(_appDelete = false): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Request } from './request';\nimport * as constants from './constants';\n\nexport class RequestMap {\n private readonly map: Map<number, Request<unknown>> = new Map();\n private id: number;\n\n constructor() {\n this.id = constants.MIN_SAFE_INTEGER;\n }\n\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n *\n * @param request The request to register.\n */\n addRequest(request: Request<unknown>): void {\n const id = this.id;\n this.id++;\n this.map.set(id, request);\n\n request.getPromise().then(\n () => this.map.delete(id),\n () => this.map.delete(id)\n );\n }\n\n /**\n * Cancels all registered requests.\n */\n clear(): void {\n this.map.forEach(v => {\n v && v.cancel(true);\n });\n this.map.clear();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Reference } from '../reference';\nimport { Service } from '../service';\nimport * as constants from './constants';\nimport * as errorsExports from './error';\nimport { FailRequest } from './failrequest';\nimport { Location } from './location';\nimport { Request } from './request';\nimport { RequestInfo } from './requestinfo';\nimport { requestMaker } from './requestmaker';\nimport { RequestMap } from './requestmap';\nimport * as type from './type';\nimport { XhrIoPool } from './xhriopool';\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app-types';\nimport {\n _FirebaseApp,\n FirebaseAuthTokenData\n} from '@firebase/app-types/private';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\n\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nexport class AuthWrapper {\n private app_: FirebaseApp | null;\n private authProvider_: Provider<FirebaseAuthInternalName>;\n private bucket_: string | null = null;\n\n private storageRefMaker_: (p1: AuthWrapper, p2: Location) => Reference;\n private requestMaker_: requestMaker;\n private pool_: XhrIoPool;\n private service_: Service;\n private maxOperationRetryTime_: number;\n private maxUploadRetryTime_: number;\n private requestMap_: RequestMap;\n private deleted_: boolean = false;\n\n constructor(\n app: FirebaseApp | null,\n authProvider: Provider<FirebaseAuthInternalName>,\n maker: (p1: AuthWrapper, p2: Location) => Reference,\n requestMaker: requestMaker,\n service: Service,\n pool: XhrIoPool\n ) {\n this.app_ = app;\n if (this.app_ !== null) {\n const options = this.app_.options;\n if (type.isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.authProvider_ = authProvider;\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = constants.DEFAULT_MAX_OPERATION_RETRY_TIME;\n this.maxUploadRetryTime_ = constants.DEFAULT_MAX_UPLOAD_RETRY_TIME;\n this.requestMap_ = new RequestMap();\n }\n\n private static extractBucket_(config: FirebaseOptions): string | null {\n const bucketString = config[constants.CONFIG_STORAGE_BUCKET_KEY] || null;\n if (bucketString == null) {\n return null;\n }\n const loc: Location = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n }\n\n getAuthToken(): Promise<string | null> {\n const auth = this.authProvider_.getImmediate({ optional: true });\n if (auth) {\n return auth.getToken().then(\n (response: FirebaseAuthTokenData | null): string | null => {\n if (response !== null) {\n return response.accessToken;\n } else {\n return null;\n }\n },\n () => null\n );\n } else {\n return Promise.resolve(null);\n }\n }\n\n bucket(): string | null {\n if (this.deleted_) {\n throw errorsExports.appDeleted();\n } else {\n return this.bucket_;\n }\n }\n\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n service(): Service {\n return this.service_;\n }\n\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n makeStorageReference(loc: Location): Reference {\n return this.storageRefMaker_(this, loc);\n }\n\n makeRequest<T>(\n requestInfo: RequestInfo<T>,\n authToken: string | null\n ): Request<T> {\n if (!this.deleted_) {\n const request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n } else {\n return new FailRequest(errorsExports.appDeleted());\n }\n }\n\n /**\n * Stop running requests and prevent more from being created.\n */\n deleteApp(): void {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n }\n\n maxUploadRetryTime(): number {\n return this.maxUploadRetryTime_;\n }\n\n setMaxUploadRetryTime(time: number): void {\n this.maxUploadRetryTime_ = time;\n }\n\n maxOperationRetryTime(): number {\n return this.maxOperationRetryTime_;\n }\n\n setMaxOperationRetryTime(time: number): void {\n this.maxOperationRetryTime_ = time;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\nimport firebase from '@firebase/app';\nimport * as backoff from './backoff';\nimport {\n FirebaseStorageError,\n unknown,\n appDeleted,\n canceled,\n retryLimitExceeded\n} from './error';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport { Headers, XhrIo, ErrorCode } from './xhrio';\nimport { XhrIoPool } from './xhriopool';\n\n/**\n * @template T\n */\nexport interface Request<T> {\n getPromise(): Promise<T>;\n\n /**\n * Cancels the request. IMPORTANT: the promise may still be resolved with an\n * appropriate value (if the request is finished before you call this method,\n * but the promise has not yet been resolved), so don't just assume it will be\n * rejected if you call this function.\n * @param appDelete True if the cancelation came from the app being deleted.\n */\n cancel(appDelete?: boolean): void;\n}\n\n/**\n * @struct\n * @template T\n */\nclass NetworkRequest<T> implements Request<T> {\n private url_: string;\n private method_: string;\n private headers_: Headers;\n private body_: string | Blob | Uint8Array | null;\n private successCodes_: number[];\n private additionalRetryCodes_: number[];\n private pendingXhr_: XhrIo | null = null;\n private backoffId_: backoff.id | null = null;\n private resolve_: Function | null = null;\n private reject_: Function | null = null;\n private canceled_: boolean = false;\n private appDelete_: boolean = false;\n private callback_: (p1: XhrIo, p2: string) => T;\n private errorCallback_:\n | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)\n | null;\n private progressCallback_: ((p1: number, p2: number) => void) | null;\n private timeout_: number;\n private pool_: XhrIoPool;\n promise_: Promise<T>;\n\n constructor(\n url: string,\n method: string,\n headers: Headers,\n body: string | Blob | Uint8Array | null,\n successCodes: number[],\n additionalRetryCodes: number[],\n callback: (p1: XhrIo, p2: string) => T,\n errorCallback:\n | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)\n | null,\n timeout: number,\n progressCallback: ((p1: number, p2: number) => void) | null,\n pool: XhrIoPool\n ) {\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n this.promise_ = new Promise((resolve, reject) => {\n this.resolve_ = resolve;\n this.reject_ = reject;\n this.start_();\n });\n }\n\n /**\n * Actually starts the retry loop.\n */\n private start_(): void {\n const self = this;\n\n function doTheRequest(\n backoffCallback: (p1: boolean, ...p2: unknown[]) => void,\n canceled: boolean\n ): void {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n const xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n\n function progressListener(progressEvent: ProgressEvent): void {\n const loaded = progressEvent.loaded;\n const total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then((xhr: XhrIo) => {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr as XhrIo;\n const hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n const status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n const wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(\n false,\n new RequestEndStatus(false, null, wasCanceled)\n );\n return;\n }\n const successCode = self.successCodes_.indexOf(status) !== -1;\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(\n requestWentThrough: boolean,\n status: RequestEndStatus\n ): void {\n const resolve = self.resolve_ as Function;\n const reject = self.reject_ as Function;\n const xhr = status.xhr as XhrIo;\n if (status.wasSuccessCode) {\n try {\n const result = self.callback_(xhr, xhr.getResponseText());\n if (type.isJustDef(result)) {\n resolve(result);\n } else {\n resolve();\n }\n } catch (e) {\n reject(e);\n }\n } else {\n if (xhr !== null) {\n const err = unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n } else {\n reject(err);\n }\n } else {\n if (status.canceled) {\n const err = self.appDelete_ ? appDeleted() : canceled();\n reject(err);\n } else {\n const err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n } else {\n this.backoffId_ = backoff.start(doTheRequest, backoffDone, this.timeout_);\n }\n }\n\n /** @inheritDoc */\n getPromise(): Promise<T> {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(appDelete?: boolean): void {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n backoff.stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n }\n\n private isRetryStatusCode_(status: number): boolean {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n const isFiveHundredCode = status >= 500 && status < 600;\n const extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;\n const isRequestSpecificRetryCode =\n this.additionalRetryCodes_.indexOf(status) !== -1;\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n }\n}\n\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nexport class RequestEndStatus {\n /**\n * True if the request was canceled.\n */\n canceled: boolean;\n\n constructor(\n public wasSuccessCode: boolean,\n public xhr: XhrIo | null,\n canceled?: boolean\n ) {\n this.canceled = !!canceled;\n }\n}\n\nexport function addAuthHeader_(\n headers: Headers,\n authToken: string | null\n): void {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\n\nexport function addVersionHeader_(headers: Headers): void {\n const version =\n typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + version;\n}\n\n/**\n * @template T\n */\nexport function makeRequest<T>(\n requestInfo: RequestInfo<T>,\n authToken: string | null,\n pool: XhrIoPool\n): Request<T> {\n const queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);\n const url = requestInfo.url + queryPart;\n const headers = Object.assign({}, requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest<T>(\n url,\n requestInfo.method,\n headers,\n requestInfo.body,\n requestInfo.successCodes,\n requestInfo.additionalRetryCodes,\n requestInfo.handler,\n requestInfo.errorHandler,\n requestInfo.timeout,\n requestInfo.progressCallback,\n pool\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Provides a method for running a function with exponential\n * backoff.\n */\ntype id = (p1: boolean) => void;\n\nexport { id };\n\n/**\n * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nexport function start(\n f: (p1: (success: boolean) => void, canceled: boolean) => void,\n callback: Function,\n timeout: number\n): id {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n let waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n // TODO: find a way to exclude Node type definition for storage because storage only works in browser\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let timeoutId: any = null;\n let hitTimeout = false;\n let cancelState = 0;\n\n function canceled(): boolean {\n return cancelState === 2;\n }\n let triggeredCallback = false;\n\n // TODO: This disable can be removed and the 'ignoreRestArgs' option added to\n // the no-explicit-any rule when ESlint releases it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function triggerCallback(...args: any[]): void {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, args);\n }\n }\n\n function callWithDelay(millis: number): void {\n timeoutId = setTimeout(() => {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n\n // TODO: This disable can be removed and the 'ignoreRestArgs' option added to\n // the no-explicit-any rule when ESlint releases it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function handler(success: boolean, ...args: any[]): void {\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.call(null, success, ...args);\n return;\n }\n const mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.call(null, success, ...args);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n let waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n } else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n let stopped = false;\n\n function stop(wasTimeout: boolean): void {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n } else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(() => {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id: id): void {\n id(false);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { Location } from './implementation/location';\nimport * as RequestExports from './implementation/request';\nimport { XhrIoPool } from './implementation/xhriopool';\nimport { Reference } from './reference';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nexport class Service {\n authWrapper_: AuthWrapper;\n private app_: FirebaseApp;\n private bucket_: Location | null = null;\n private internals_: ServiceInternals;\n\n constructor(\n app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n pool: XhrIoPool,\n url?: string\n ) {\n function maker(authWrapper: AuthWrapper, loc: Location): Reference {\n return new Reference(authWrapper, loc);\n }\n this.authWrapper_ = new AuthWrapper(\n app,\n authProvider,\n maker,\n RequestExports.makeRequest,\n this,\n pool\n );\n this.app_ = app;\n if (url != null) {\n this.bucket_ = Location.makeFromBucketSpec(url);\n } else {\n const authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new ServiceInternals(this);\n }\n\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n ref(path?: string): Reference {\n function validator(path: unknown): void {\n if (typeof path !== 'string') {\n throw 'Path is not a string.';\n }\n if (/^[A-Za-z]+:\\/\\//.test(path as string)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n args.validate('ref', [args.stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n\n const ref = new Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n } else {\n return ref;\n }\n }\n\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n refFromURL(url: string): Reference {\n function validator(p: unknown): void {\n if (typeof p !== 'string') {\n throw 'Path is not a string.';\n }\n if (!/^[A-Za-z]+:\\/\\//.test(p as string)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n Location.makeFromUrl(p as string);\n } catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n args.validate('refFromURL', [args.stringSpec(validator, false)], arguments);\n return new Reference(this.authWrapper_, url);\n }\n\n get maxUploadRetryTime(): number {\n return this.authWrapper_.maxUploadRetryTime();\n }\n\n setMaxUploadRetryTime(time: number): void {\n args.validate(\n 'setMaxUploadRetryTime',\n [args.nonNegativeNumberSpec()],\n arguments\n );\n this.authWrapper_.setMaxUploadRetryTime(time);\n }\n\n setMaxOperationRetryTime(time: number): void {\n args.validate(\n 'setMaxOperationRetryTime',\n [args.nonNegativeNumberSpec()],\n arguments\n );\n this.authWrapper_.setMaxOperationRetryTime(time);\n }\n\n get app(): FirebaseApp {\n return this.app_;\n }\n\n get INTERNAL(): ServiceInternals {\n return this.internals_;\n }\n}\n\n/**\n * @struct\n */\nexport class ServiceInternals {\n service_: Service;\n\n constructor(service: Service) {\n this.service_ = service;\n }\n\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n delete(): Promise<void> {\n this.service_.authWrapper_.deleteApp();\n return Promise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase from '@firebase/app';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { StringFormat } from './src/implementation/string';\nimport { TaskEvent, TaskState } from './src/implementation/taskenums';\n\nimport { XhrIoPool } from './src/implementation/xhriopool';\nimport { Reference } from './src/reference';\nimport { Service } from './src/service';\nimport * as types from '@firebase/storage-types';\nimport {\n Component,\n ComponentType,\n ComponentContainer\n} from '@firebase/component';\n\nimport { name, version } from './package.json';\n\n/**\n * Type constant for Firebase Storage.\n */\nconst STORAGE_TYPE = 'storage';\n\nfunction factory(\n container: ComponentContainer,\n url?: string\n): types.FirebaseStorage {\n // Dependencies\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider('auth-internal');\n\n return (new Service(\n app,\n authProvider,\n new XhrIoPool(),\n url\n ) as unknown) as types.FirebaseStorage;\n}\n\nexport function registerStorage(instance: _FirebaseNamespace): void {\n const namespaceExports = {\n // no-inline\n TaskState,\n TaskEvent,\n StringFormat,\n Storage: Service,\n Reference\n };\n instance.INTERNAL.registerComponent(\n new Component(STORAGE_TYPE, factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterStorage(firebase as _FirebaseNamespace);\n\n/**\n * Define extension behavior for `registerStorage`\n */\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n storage?: {\n (app?: FirebaseApp): types.FirebaseStorage;\n Storage: typeof types.FirebaseStorage;\n\n StringFormat: {\n BASE64: types.StringFormat;\n BASE64URL: types.StringFormat;\n DATA_URL: types.StringFormat;\n RAW: types.StringFormat;\n };\n TaskEvent: {\n STATE_CHANGED: types.TaskEvent;\n };\n TaskState: {\n CANCELED: types.TaskState;\n ERROR: types.TaskState;\n PAUSED: types.TaskState;\n RUNNING: types.TaskState;\n SUCCESS: types.TaskState;\n };\n };\n }\n interface FirebaseApp {\n storage?(storageBucket?: string): types.FirebaseStorage;\n }\n}\n"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__generator","thisArg","body","f","y","t","g","_","label","sent","trys","ops","next","verb","throw","return","Symbol","iterator","this","n","v","op","TypeError","call","done","value","pop","length","push","e","step","__spreadArrays","s","i","il","arguments","r","k","a","j","jl","Error","prototype","create","__","constructor","code","message","_super","_this","FirebaseError","captureStackTrace","ErrorFactory","_i","data","customData","fullCode","service","template","errors","replace","PATTERN","key","toString","replaceTemplate","fullMessage","serviceName","error","_b","keys","_a","slice","console","warn","Component","mode","instantiationMode","multipleInstances","props","serviceProps","name","instanceFactory","type","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","FirebaseStorageError","prependCode","codeProp","serverResponse_","serverResponse","name_","code_","message_","Code","UNKNOWN","OBJECT_NOT_FOUND","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","QUOTA_EXCEEDED","UNAUTHENTICATED","UNAUTHORIZED","RETRY_LIMIT_EXCEEDED","INVALID_CHECKSUM","CANCELED","INVALID_EVENT_NAME","INVALID_URL","INVALID_DEFAULT_BUCKET","NO_DEFAULT_BUCKET","CANNOT_SLICE_BLOB","SERVER_FILE_WRONG_SIZE","NO_DOWNLOAD_URL","INVALID_ARGUMENT","INVALID_ARGUMENT_COUNT","APP_DELETED","INVALID_ROOT_OPERATION","INVALID_FORMAT","INTERNAL_ERROR","unknown","canceled","cannotSliceBlob","invalidArgument","index","fnName","appDeleted","invalidFormat","format","internalError","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","formatValidator","stringFormat","contentType","dataFromString","stringData","StringData","utf8Bytes_","base64Bytes_","dataUrl","parts","DataURLParts","base64","rest","decoded","decodeURIComponent","errorsExports.invalidFormat","percentEncodedBytes_","dataURLBytes_","dataURLContentType_","errorsExports.unknown","c","charCodeAt","Uint8Array","hasMinus","indexOf","hasUnder","hasPlus","hasSlash","bytes","atob","array","dataURL","matches","match","middle","end","substring","endsWith","ErrorCode","TaskEvent","STATE_CHANGED","InternalTaskState","TaskState","RUNNING","PAUSED","SUCCESS","ERROR","taskStateFromInternalTaskState","state","isDef","isJustDef","isFunction","isObject","isString","String","isNumber","Number","isNativeBlob","isNativeBlobDefined","Blob","NetworkXhrIo","url","method","headers","sent_","errorsExports.internalError","xhr_","open","type.isDef","setRequestHeader","send","sendPromise_","errorCode_","status","responseText","abort","header","getResponseHeader","listener","upload","addEventListener","removeEventListener","XMLHttpRequest","NO_ERROR","Promise","resolve","ABORT","NETWORK_ERROR","XhrIoPool","getBlob","args","BlobBuilder","WebKitBlobBuilder","undefined","bb","append","type.isNativeBlobDefined","FbsBlob","size_","type_","startByte","endByte","type.isNativeBlob","data_","sliced","blob","start","webkitSlice","mozSlice","fs.sliceBlob","buffer","blobby","map","val","fs.getBlob","apply","uint8Arrays","type.isString","finalLength_1","forEach","byteLength","merged_1","index_1","elideCopy","size","blobType","ArrayBuffer","set","Location","path_","path","encode","encodeURIComponent","bucket","bucketString","bucketLocation","makeFromUrl","errorsExports.invalidDefaultBucket","location","bucketDomain","gsRegex","RegExp","hostRegex","groups","regex","indices","postModify","loc","charAt","group","captures","exec","bucketValue","pathValue","errorsExports.invalidUrl","jsonObjectOrNull","obj","JSON","parse","isArray","type.isNonArrayObject","lastComponent","lastIndexOf","makeUrl","urlPart","makeQueryString","params","queryPart","noXform_","metadata","server","local","writable","xform","mappings_","getMappings","mappings","Mapping","nameMapping","_metadata","fullPath","path.lastComponent","xformPath","sizeMapping","addRef","authWrapper","defineProperty","get","makeStorageReference","fromResourceString","resourceString","json.jsonObjectOrNull","resource","len","mapping","fromResource","toResourceString","stringify","metadataValidator","type.isObject","MAX_RESULTS_KEY","MAX_MAX_RESULTS","PAGE_TOKEN_KEY","PREFIXES_KEY","ITEMS_KEY","fromBackendResponse","listResult","prefixes","items","nextPageToken","pathWithoutTrailingSlash","reference","_c","item","listOptionsValidator","isInteger","handler","timeout","handlerCheck","cndn","metadataHandler","xhr","text","MetadataUtils.fromResourceString","listHandler","ListResultUtils.fromResponseString","downloadUrlHandler","tokens","split","token","UrlUtils.makeUrl","UrlUtils.makeQueryString","alt","MetadataUtils.downloadUrlFromResourceString","sharedErrorHandler","err","newErr","getStatus","quotaExceeded","unauthorized","setServerResponseProp","serverResponseProp","objectErrorHandler","shared","objectNotFound","getMetadata","fullServerUrl","maxOperationRetryTime","requestInfo","RequestInfo","errorHandler","metadataForUpload_","metadataClone","assign","determineContentType_","multipartUpload","bucketOnlyServerUrl","X-Goog-Upload-Protocol","boundary","str","Math","random","genBoundary","metadata_","preBlobPart","MetadataUtils.toResourceString","postBlobPart","urlParams","maxUploadRetryTime","uploadData","current","total","finalized","checkResumeHeader_","allowed","createResumableUpload","metadataForUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","Content-Type","getResumableUploadStatus","sizeString","isNaN","ResumableUploadStatus","continueResumableUpload","chunkSize","progressCallback","status_","bytesLeft","bytesToUpload","min","X-Goog-Upload-Offset","uploadStatus","newCurrent","nextOrObserver","complete","type.isFunction","observer","bytesTransferred","totalBytes","task","ref","validate","specs","passed","minArgs","maxArgs","optional","argMin","argMax","real","countPart","plural","errorsExports.invalidArgumentCount","validator","errorsExports.invalidArgument","self","type.isJustDef","stringSpec","stringValidator","chainedValidator","v1","v2","and_","ArgSpec","uploadDataSpec","metadataSpec","MetadataUtils.metadataValidator","nonNegativeNumberSpec","type.isNumber","looseObjectSpec","nullFunctionSpec","async","argsToForward","then","UploadTask","sizeBefore","transferred_","loaded","updateProgress_","state_","request_","resumable_","uploadUrl_","createResumable_","needToFetchStatus_","fetchStatus_","needToFetchMetadata_","fetchMetadata_","continueUpload_","oneShotUpload_","callback","authWrapper_","getAuthToken","authToken","transition_","resolveToken_","fbsRequests.createResumableUpload","location_","blob_","createRequest","makeRequest","getPromise","completeTransitions_","errorHandler_","fbsRequests.getResumableUploadStatus","statusRequest","chunkMultiplier_","fbsRequests.ResumableUploadStatus","fbsRequests.continueResumableUpload","makeProgressCallback_","error_","uploadRequest","newStatus","increaseMultiplier_","fbsRequests.getMetadata","metadataRequest","metadataErrorHandler_","fbsRequests.multipartUpload","multipartRequest","transferred","old","notifyObservers_","cancel","wasPaused","start_","externalState","UploadTaskSnapshot","ref_","completed","nextOrObserverMessage","nextValidator","observerValidator","nextOrObserverValidator","typeUtils.isJustDef","makeBinder","Observer","addObserver_","removeObserver_","binderSpecs","onFulfilled","onRejected","promise_","observers_","notifyObserver_","splice","finishPromise_","resolve_","triggered","fbsAsync","bind","snapshot","reject_","valid","shouldDoResumable_","codeEquals","reject","Reference","metadata.getMappings","childPath","newPath","canonicalChildPath","filter","component","join","path.child","newRef","path.parent","throwIfRoot_","_xhr","_text","successCodes","requests.deleteObject","accumulator","listAllHelper","pageToken","_arguments","P","generator","fulfilled","rejected","result","opt","list","nextPage","options","ListOptionsUtils.listOptionsValidator","listOptionSpec","delimiter","maxResults","isRoot","requests.list","requests.getMetadata","requests.updateMetadata","requests.getDownloadUrl","errorsExports.invalidRootOperation","FailRequest","_appDelete","RequestMap","request","id","delete","clear","Map","AuthWrapper","config","constants.CONFIG_STORAGE_BUCKET_KEY","makeFromBucketSpec","auth","authProvider_","getImmediate","getToken","response","accessToken","deleted_","errorsExports.appDeleted","bucket_","service_","storageRefMaker_","requestMaker_","pool_","requestMap_","addRequest","app_","maxUploadRetryTime_","time","maxOperationRetryTime_","app","authProvider","maker","requestMaker","pool","extractBucket_","NetworkRequest","backoffDone","requestWentThrough","wasSuccessCode","callback_","getResponseText","errorCallback_","appDelete_","canceled_","RequestEndStatus","backoffId_","waitSeconds","timeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","millis","setTimeout","success","stopped","stop","wasTimeout","clearTimeout","backoff.start","backoffCallback","createXhrIo","pendingXhr_","progressCallback_","addUploadProgressListener","progressListener","url_","method_","body_","headers_","removeUploadProgressListener","hitServer","getErrorCode","isRetryStatusCode_","successCode","successCodes_","wasCanceled","progressEvent","lengthComputable","timeout_","appDelete","backoff.stop","isFiveHundredCode","isExtraRetryCode","isRequestSpecificRetryCode","additionalRetryCodes_","additionalRetryCodes","errorCallback","addAuthHeader_","version","firebase","SDK_VERSION","addVersionHeader_","Service","args.validate","args.stringSpec","test","child","args.nonNegativeNumberSpec","setMaxUploadRetryTime","setMaxOperationRetryTime","internals_","RequestExports.makeRequest","authWrapperBucket","ServiceInternals","deleteApp","instance","namespaceExports","factory","container","getProvider","Storage","INTERNAL","registerComponent","setServiceProps","setMultipleInstances","registerVersion"],"mappings":"4RAgBA,IAAIA,EAAgB,SAASC,EAAGC,GAI5B,OAHAF,EAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAgBC,OAAS,SAAUL,EAAGC,GAAKD,EAAEI,UAAYH,IACvE,SAAUD,EAAGC,GAAK,IAAK,IAAIK,KAAKL,EAAOA,EAAEM,eAAeD,KAAIN,EAAEM,GAAKL,EAAEK,MACpDN,EAAGC,IAwDrB,SAASO,EAAYC,EAASC,GACjC,IAAsGC,EAAGC,EAAGC,EAAGC,EAA3GC,EAAI,CAAEC,MAAO,EAAGC,KAAM,WAAa,GAAW,EAAPJ,EAAE,GAAQ,MAAMA,EAAE,GAAI,OAAOA,EAAE,IAAOK,KAAM,GAAIC,IAAK,IAChG,OAAOL,EAAI,CAAEM,KAAMC,EAAK,GAAIC,MAASD,EAAK,GAAIE,OAAUF,EAAK,IAAwB,mBAAXG,SAA0BV,EAAEU,OAAOC,UAAY,WAAa,OAAOC,OAAUZ,EACvJ,SAASO,EAAKM,GAAK,OAAO,SAAUC,GAAK,OACzC,SAAcC,GACV,GAAIlB,EAAG,MAAM,IAAImB,UAAU,mCAC3B,KAAOf,GAAG,IACN,GAAIJ,EAAI,EAAGC,IAAMC,EAAY,EAARgB,EAAG,GAASjB,EAAU,OAAIiB,EAAG,GAAKjB,EAAS,SAAOC,EAAID,EAAU,SAAMC,EAAEkB,KAAKnB,GAAI,GAAKA,EAAEQ,SAAWP,EAAIA,EAAEkB,KAAKnB,EAAGiB,EAAG,KAAKG,KAAM,OAAOnB,EAE3J,OADID,EAAI,EAAGC,IAAGgB,EAAK,CAAS,EAARA,EAAG,GAAQhB,EAAEoB,QACzBJ,EAAG,IACP,KAAK,EAAG,KAAK,EAAGhB,EAAIgB,EAAI,MACxB,KAAK,EAAc,OAAXd,EAAEC,QAAgB,CA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