{"version":3,"file":"firebase-storage.js","sources":["../util/dist/postinstall.mjs","../util/src/crypt.ts","../util/src/defaults.ts","../util/src/global.ts","../util/src/errors.ts","../util/src/compat.ts","../util/src/url.ts","../component/src/component.ts","../storage/src/implementation/constants.ts","../storage/src/implementation/error.ts","../storage/src/implementation/connection.ts","../storage/src/implementation/location.ts","../storage/src/implementation/failrequest.ts","../storage/src/implementation/type.ts","../storage/src/implementation/url.ts","../storage/src/implementation/utils.ts","../storage/src/implementation/request.ts","../storage/src/implementation/backoff.ts","../storage/src/implementation/fs.ts","../storage/src/platform/browser/base64.ts","../storage/src/implementation/string.ts","../storage/src/implementation/blob.ts","../storage/src/implementation/json.ts","../storage/src/implementation/path.ts","../storage/src/implementation/metadata.ts","../storage/src/implementation/list.ts","../storage/src/implementation/requestinfo.ts","../storage/src/implementation/requests.ts","../storage/src/implementation/taskenums.ts","../storage/src/implementation/observer.ts","../storage/src/implementation/async.ts","../storage/src/platform/browser/connection.ts","../storage/src/task.ts","../storage/src/reference.ts","../storage/src/service.ts","../util/src/emulator.ts","../storage/src/constants.ts","../storage/src/api.ts","../storage/src/api.browser.ts","../storage/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\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// This value is retrieved and hardcoded by the NPM postinstall script\nconst getDefaultsFromPostinstall = () => undefined;\n\nexport { getDefaultsFromPostinstall };\n","/**\n * @license\n * Copyright 2017 Google LLC\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\nconst stringToByteArray = function (str: string): number[] {\n  // TODO(user): Use native implementations if/when available\n  const out: number[] = [];\n  let p = 0;\n  for (let i = 0; i < str.length; i++) {\n    let c = str.charCodeAt(i);\n    if (c < 128) {\n      out[p++] = c;\n    } else if (c < 2048) {\n      out[p++] = (c >> 6) | 192;\n      out[p++] = (c & 63) | 128;\n    } else if (\n      (c & 0xfc00) === 0xd800 &&\n      i + 1 < str.length &&\n      (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n    ) {\n      // Surrogate Pair\n      c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n      out[p++] = (c >> 18) | 240;\n      out[p++] = ((c >> 12) & 63) | 128;\n      out[p++] = ((c >> 6) & 63) | 128;\n      out[p++] = (c & 63) | 128;\n    } else {\n      out[p++] = (c >> 12) | 224;\n      out[p++] = ((c >> 6) & 63) | 128;\n      out[p++] = (c & 63) | 128;\n    }\n  }\n  return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n  // TODO(user): Use native implementations if/when available\n  const out: string[] = [];\n  let pos = 0,\n    c = 0;\n  while (pos < bytes.length) {\n    const c1 = bytes[pos++];\n    if (c1 < 128) {\n      out[c++] = String.fromCharCode(c1);\n    } else if (c1 > 191 && c1 < 224) {\n      const c2 = bytes[pos++];\n      out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n    } else if (c1 > 239 && c1 < 365) {\n      // Surrogate Pair\n      const c2 = bytes[pos++];\n      const c3 = bytes[pos++];\n      const c4 = bytes[pos++];\n      const u =\n        (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n        0x10000;\n      out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n      out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n    } else {\n      const c2 = bytes[pos++];\n      const c3 = bytes[pos++];\n      out[c++] = String.fromCharCode(\n        ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n      );\n    }\n  }\n  return out.join('');\n};\n\ninterface Base64 {\n  byteToCharMap_: { [key: number]: string } | null;\n  charToByteMap_: { [key: string]: number } | null;\n  byteToCharMapWebSafe_: { [key: number]: string } | null;\n  charToByteMapWebSafe_: { [key: string]: number } | null;\n  ENCODED_VALS_BASE: string;\n  readonly ENCODED_VALS: string;\n  readonly ENCODED_VALS_WEBSAFE: string;\n  HAS_NATIVE_SUPPORT: boolean;\n  encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n  encodeString(input: string, webSafe?: boolean): string;\n  decodeString(input: string, webSafe: boolean): string;\n  decodeStringToByteArray(input: string, webSafe: boolean): number[];\n  init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n  /**\n   * Maps bytes to characters.\n   */\n  byteToCharMap_: null,\n\n  /**\n   * Maps characters to bytes.\n   */\n  charToByteMap_: null,\n\n  /**\n   * Maps bytes to websafe characters.\n   * @private\n   */\n  byteToCharMapWebSafe_: null,\n\n  /**\n   * Maps websafe characters to bytes.\n   * @private\n   */\n  charToByteMapWebSafe_: null,\n\n  /**\n   * Our default alphabet, shared between\n   * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n   */\n  ENCODED_VALS_BASE:\n    'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n  /**\n   * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n   */\n  get ENCODED_VALS() {\n    return this.ENCODED_VALS_BASE + '+/=';\n  },\n\n  /**\n   * Our websafe alphabet.\n   */\n  get ENCODED_VALS_WEBSAFE() {\n    return this.ENCODED_VALS_BASE + '-_.';\n  },\n\n  /**\n   * Whether this browser supports the atob and btoa functions. This extension\n   * started at Mozilla but is now implemented by many browsers. We use the\n   * ASSUME_* variables to avoid pulling in the full useragent detection library\n   * but still allowing the standard per-browser compilations.\n   *\n   */\n  HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n  /**\n   * Base64-encode an array of bytes.\n   *\n   * @param input An array of bytes (numbers with\n   *     value in [0, 255]) to encode.\n   * @param webSafe Boolean indicating we should use the\n   *     alternative alphabet.\n   * @return The base64 encoded string.\n   */\n  encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n    if (!Array.isArray(input)) {\n      throw Error('encodeByteArray takes an array as a parameter');\n    }\n\n    this.init_();\n\n    const byteToCharMap = webSafe\n      ? this.byteToCharMapWebSafe_!\n      : this.byteToCharMap_!;\n\n    const output = [];\n\n    for (let i = 0; i < input.length; i += 3) {\n      const byte1 = input[i];\n      const haveByte2 = i + 1 < input.length;\n      const byte2 = haveByte2 ? input[i + 1] : 0;\n      const haveByte3 = i + 2 < input.length;\n      const byte3 = haveByte3 ? input[i + 2] : 0;\n\n      const outByte1 = byte1 >> 2;\n      const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n      let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n      let outByte4 = byte3 & 0x3f;\n\n      if (!haveByte3) {\n        outByte4 = 64;\n\n        if (!haveByte2) {\n          outByte3 = 64;\n        }\n      }\n\n      output.push(\n        byteToCharMap[outByte1],\n        byteToCharMap[outByte2],\n        byteToCharMap[outByte3],\n        byteToCharMap[outByte4]\n      );\n    }\n\n    return output.join('');\n  },\n\n  /**\n   * Base64-encode a string.\n   *\n   * @param input A string to encode.\n   * @param webSafe If true, we should use the\n   *     alternative alphabet.\n   * @return The base64 encoded string.\n   */\n  encodeString(input: string, webSafe?: boolean): string {\n    // Shortcut for Mozilla browsers that implement\n    // a native base64 encoder in the form of \"btoa/atob\"\n    if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n      return btoa(input);\n    }\n    return this.encodeByteArray(stringToByteArray(input), webSafe);\n  },\n\n  /**\n   * Base64-decode a string.\n   *\n   * @param input to decode.\n   * @param webSafe True if we should use the\n   *     alternative alphabet.\n   * @return string representing the decoded value.\n   */\n  decodeString(input: string, webSafe: boolean): string {\n    // Shortcut for Mozilla browsers that implement\n    // a native base64 encoder in the form of \"btoa/atob\"\n    if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n      return atob(input);\n    }\n    return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n  },\n\n  /**\n   * Base64-decode a string.\n   *\n   * In base-64 decoding, groups of four characters are converted into three\n   * bytes.  If the encoder did not apply padding, the input length may not\n   * be a multiple of 4.\n   *\n   * In this case, the last group will have fewer than 4 characters, and\n   * padding will be inferred.  If the group has one or two characters, it decodes\n   * to one byte.  If the group has three characters, it decodes to two bytes.\n   *\n   * @param input Input to decode.\n   * @param webSafe True if we should use the web-safe alphabet.\n   * @return bytes representing the decoded value.\n   */\n  decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n    this.init_();\n\n    const charToByteMap = webSafe\n      ? this.charToByteMapWebSafe_!\n      : this.charToByteMap_!;\n\n    const output: number[] = [];\n\n    for (let i = 0; i < input.length; ) {\n      const byte1 = charToByteMap[input.charAt(i++)];\n\n      const haveByte2 = i < input.length;\n      const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n      ++i;\n\n      const haveByte3 = i < input.length;\n      const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n      ++i;\n\n      const haveByte4 = i < input.length;\n      const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n      ++i;\n\n      if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n        throw new DecodeBase64StringError();\n      }\n\n      const outByte1 = (byte1 << 2) | (byte2 >> 4);\n      output.push(outByte1);\n\n      if (byte3 !== 64) {\n        const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n        output.push(outByte2);\n\n        if (byte4 !== 64) {\n          const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n          output.push(outByte3);\n        }\n      }\n    }\n\n    return output;\n  },\n\n  /**\n   * Lazy static initialization function. Called before\n   * accessing any of the static map variables.\n   * @private\n   */\n  init_() {\n    if (!this.byteToCharMap_) {\n      this.byteToCharMap_ = {};\n      this.charToByteMap_ = {};\n      this.byteToCharMapWebSafe_ = {};\n      this.charToByteMapWebSafe_ = {};\n\n      // We want quick mappings back and forth, so we precompute two maps.\n      for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n        this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n        this.charToByteMap_[this.byteToCharMap_[i]] = i;\n        this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n        this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n        // Be forgiving when decoding and correctly decode both encodings.\n        if (i >= this.ENCODED_VALS_BASE.length) {\n          this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n          this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n        }\n      }\n    }\n  }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n  readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n  const utf8Bytes = stringToByteArray(str);\n  return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n  // Use base64url encoding and remove padding in the end (dot characters).\n  return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n  try {\n    return base64.decodeString(str, true);\n  } catch (e) {\n    console.error('base64Decode failed: ', e);\n  }\n  return null;\n};\n","/**\n * @license\n * Copyright 2022 Google LLC\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 { base64Decode } from './crypt';\nimport { getGlobal } from './global';\nimport { getDefaultsFromPostinstall } from './postinstall';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n  config?: Record<string, string>;\n  emulatorHosts?: Record<string, string>;\n  _authTokenSyncURL?: string;\n  _authIdTokenMaxAge?: number;\n  /**\n   * Override Firebase's runtime environment detection and\n   * force the SDK to act as if it were in the specified environment.\n   */\n  forceEnvironment?: 'browser' | 'node';\n  [key: string]: unknown;\n}\n\ndeclare global {\n  // Need `var` for this to work.\n  // eslint-disable-next-line no-var\n  var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n  getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n  if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n    return;\n  }\n  const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n  if (defaultsJsonString) {\n    return JSON.parse(defaultsJsonString);\n  }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n  if (typeof document === 'undefined') {\n    return;\n  }\n  let match;\n  try {\n    match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n  } catch (e) {\n    // Some environments such as Angular Universal SSR have a\n    // `document` object but error on accessing `document.cookie`.\n    return;\n  }\n  const decoded = match && base64Decode(match[1]);\n  return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n  try {\n    return (\n      getDefaultsFromPostinstall() ||\n      getDefaultsFromGlobal() ||\n      getDefaultsFromEnvVariable() ||\n      getDefaultsFromCookie()\n    );\n  } catch (e) {\n    /**\n     * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n     * to any environment case we have not accounted for. Log to\n     * info instead of swallowing so we can find these unknown cases\n     * and add paths for them if needed.\n     */\n    console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n    return;\n  }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n  productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n  productName: string\n): [hostname: string, port: number] | undefined => {\n  const host = getDefaultEmulatorHost(productName);\n  if (!host) {\n    return undefined;\n  }\n  const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n  if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n    throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n  }\n  // eslint-disable-next-line no-restricted-globals\n  const port = parseInt(host.substring(separatorIndex + 1), 10);\n  if (host[0] === '[') {\n    // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n    return [host.substring(1, separatorIndex - 1), port];\n  } else {\n    return [host.substring(0, separatorIndex), port];\n  }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record<string, string> | undefined =>\n  getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = <T extends ExperimentalKey>(\n  name: T\n): FirebaseDefaults[`_${T}`] =>\n  getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2022 Google LLC\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 * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n  if (typeof self !== 'undefined') {\n    return self;\n  }\n  if (typeof window !== 'undefined') {\n    return window;\n  }\n  if (typeof global !== 'undefined') {\n    return global;\n  }\n  throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 as FirebaseError)?.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]: unknown;\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  /** The custom name for all FirebaseErrors. */\n  readonly name: string = ERROR_NAME;\n\n  constructor(\n    /** The error code for this error. */\n    readonly code: string,\n    message: string,\n    /** Custom data for this error. */\n    public customData?: Record<string, unknown>\n  ) {\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    // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n    //                   which we can now use since we no longer target ES5.\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, customData);\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 ? String(value) : `<${key}?>`;\n  });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2021 Google LLC\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\nexport interface Compat<T> {\n  _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n  service: Compat<ExpService> | ExpService\n): ExpService {\n  if (service && (service as Compat<ExpService>)._delegate) {\n    return (service as Compat<ExpService>)._delegate;\n  } else {\n    return service as ExpService;\n  }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\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 * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n  // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n  // In HTTP request builders, it's called with the protocol.\n  // If called with protocol prefix, it's a valid URL, so we extract the hostname\n  // If called without, we assume the string is the hostname.\n  try {\n    const host =\n      url.startsWith('http://') || url.startsWith('https://')\n        ? new URL(url).hostname\n        : url;\n    return host.endsWith('.cloudworkstations.dev');\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise<boolean> {\n  const result = await fetch(endpoint, {\n    credentials: 'include'\n  });\n  return result.ok;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\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  onInstanceCreatedCallback\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  onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\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  setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n    this.onInstanceCreated = callback;\n    return this;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 * 1 second\n */\nexport const DEFAULT_MIN_SLEEP_TIME_MILLIS = 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 LLC\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 { FirebaseError } from '@firebase/util';\n\nimport { CONFIG_STORAGE_BUCKET_KEY } from './constants';\n\n/**\n * An error returned by the Firebase Storage SDK.\n * @public\n */\nexport class StorageError extends FirebaseError {\n  private readonly _baseMessage: string;\n  /**\n   * Stores custom error data unique to the `StorageError`.\n   */\n  customData: { serverResponse: string | null } = { serverResponse: null };\n\n  /**\n   * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and\n   *  added to the end of the message.\n   * @param message  - Error message.\n   * @param status_ - Corresponding HTTP Status Code\n   */\n  constructor(code: StorageErrorCode, message: string, private status_ = 0) {\n    super(\n      prependCode(code),\n      `Firebase Storage: ${message} (${prependCode(code)})`\n    );\n    this._baseMessage = this.message;\n    // Without this, `instanceof StorageError`, in tests for example,\n    // returns false.\n    Object.setPrototypeOf(this, StorageError.prototype);\n  }\n\n  get status(): number {\n    return this.status_;\n  }\n\n  set status(status: number) {\n    this.status_ = status;\n  }\n\n  /**\n   * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.\n   */\n  _codeEquals(code: StorageErrorCode): boolean {\n    return prependCode(code) === this.code;\n  }\n\n  /**\n   * Optional response message that was added by the server.\n   */\n  get serverResponse(): null | string {\n    return this.customData.serverResponse;\n  }\n\n  set serverResponse(serverResponse: string | null) {\n    this.customData.serverResponse = serverResponse;\n    if (this.customData.serverResponse) {\n      this.message = `${this._baseMessage}\\n${this.customData.serverResponse}`;\n    } else {\n      this.message = this._baseMessage;\n    }\n  }\n}\n\nexport const errors = {};\n\n/**\n * @public\n * Error codes that can be attached to `StorageError` objects.\n */\nexport enum StorageErrorCode {\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  UNAUTHORIZED_APP = 'unauthorized-app',\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  UNSUPPORTED_ENVIRONMENT = 'unsupported-environment'\n}\n\nexport function prependCode(code: StorageErrorCode): string {\n  return 'storage/' + code;\n}\n\nexport function unknown(): StorageError {\n  const message =\n    'An unknown error occurred, please check the error payload for ' +\n    'server response.';\n  return new StorageError(StorageErrorCode.UNKNOWN, message);\n}\n\nexport function objectNotFound(path: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.OBJECT_NOT_FOUND,\n    \"Object '\" + path + \"' does not exist.\"\n  );\n}\n\nexport function bucketNotFound(bucket: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.BUCKET_NOT_FOUND,\n    \"Bucket '\" + bucket + \"' does not exist.\"\n  );\n}\n\nexport function projectNotFound(project: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.PROJECT_NOT_FOUND,\n    \"Project '\" + project + \"' does not exist.\"\n  );\n}\n\nexport function quotaExceeded(bucket: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.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(): StorageError {\n  const message =\n    'User is not authenticated, please authenticate using Firebase ' +\n    'Authentication and try again.';\n  return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);\n}\n\nexport function unauthorizedApp(): StorageError {\n  return new StorageError(\n    StorageErrorCode.UNAUTHORIZED_APP,\n    'This app does not have permission to access Firebase Storage on this project.'\n  );\n}\n\nexport function unauthorized(path: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.UNAUTHORIZED,\n    \"User does not have permission to access '\" + path + \"'.\"\n  );\n}\n\nexport function retryLimitExceeded(): StorageError {\n  return new StorageError(\n    StorageErrorCode.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): StorageError {\n  return new StorageError(\n    StorageErrorCode.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(): StorageError {\n  return new StorageError(\n    StorageErrorCode.CANCELED,\n    'User canceled the upload/download.'\n  );\n}\n\nexport function invalidEventName(name: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.INVALID_EVENT_NAME,\n    \"Invalid event name '\" + name + \"'.\"\n  );\n}\n\nexport function invalidUrl(url: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.INVALID_URL,\n    \"Invalid URL '\" + url + \"'.\"\n  );\n}\n\nexport function invalidDefaultBucket(bucket: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.INVALID_DEFAULT_BUCKET,\n    \"Invalid default bucket '\" + bucket + \"'.\"\n  );\n}\n\nexport function noDefaultBucket(): StorageError {\n  return new StorageError(\n    StorageErrorCode.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(): StorageError {\n  return new StorageError(\n    StorageErrorCode.CANNOT_SLICE_BLOB,\n    'Cannot slice blob for upload. Please retry the upload.'\n  );\n}\n\nexport function serverFileWrongSize(): StorageError {\n  return new StorageError(\n    StorageErrorCode.SERVER_FILE_WRONG_SIZE,\n    'Server recorded incorrect upload file size, please retry the upload.'\n  );\n}\n\nexport function noDownloadURL(): StorageError {\n  return new StorageError(\n    StorageErrorCode.NO_DOWNLOAD_URL,\n    'The given file does not have any download URLs.'\n  );\n}\n\nexport function missingPolyFill(polyFill: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n    `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`\n  );\n}\n\n/**\n * @internal\n */\nexport function invalidArgument(message: string): StorageError {\n  return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);\n}\n\nexport function invalidArgumentCount(\n  argMin: number,\n  argMax: number,\n  fnName: string,\n  real: number\n): StorageError {\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 StorageError(\n    StorageErrorCode.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(): StorageError {\n  return new StorageError(\n    StorageErrorCode.APP_DELETED,\n    'The Firebase app was deleted.'\n  );\n}\n\n/**\n * @param name - The name of the operation that was invalid.\n *\n * @internal\n */\nexport function invalidRootOperation(name: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.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(format: string, message: string): StorageError {\n  return new StorageError(\n    StorageErrorCode.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 unsupportedEnvironment(message: string): StorageError {\n  throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, message);\n}\n\n/**\n * @param message - A message describing the internal error.\n */\nexport function internalError(message: string): StorageError {\n  throw new StorageError(\n    StorageErrorCode.INTERNAL_ERROR,\n    'Internal error: ' + message\n  );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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/** Network headers */\nexport type Headers = Record<string, string>;\n\n/** Response type exposed by the networking APIs. */\nexport type ConnectionType =\n  | string\n  | ArrayBuffer\n  | Blob\n  | ReadableStream<Uint8Array>;\n\n/**\n * A lightweight wrapper around XMLHttpRequest with a\n * goog.net.XhrIo-like interface.\n *\n * You can create a new connection by invoking `newTextConnection()`,\n * `newBytesConnection()` or `newStreamConnection()`.\n */\nexport interface Connection<T extends ConnectionType> {\n  /**\n   * Sends a request to the provided URL.\n   *\n   * This method never rejects its promise. In case of encountering an error,\n   * it sets an error code internally which can be accessed by calling\n   * getErrorCode() by callers.\n   */\n  send(\n    url: string,\n    method: string,\n    isUsingEmulator: boolean,\n    body?: ArrayBufferView | Blob | string | null,\n    headers?: Headers\n  ): Promise<void>;\n\n  getErrorCode(): ErrorCode;\n\n  getStatus(): number;\n\n  getResponse(): T;\n\n  getErrorText(): 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 * Error codes for requests made by the XhrIo wrapper.\n */\nexport enum ErrorCode {\n  NO_ERROR = 0,\n  NETWORK_ERROR = 1,\n  ABORT = 2\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 */\n\nimport { invalidDefaultBucket, invalidUrl } from './error';\nimport { DEFAULT_HOST } from './constants';\n\n/**\n * Firebase Storage location data.\n *\n * @internal\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, host: string): Location {\n    let bucketLocation;\n    try {\n      bucketLocation = Location.makeFromUrl(bucketString, host);\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 invalidDefaultBucket(bucketString);\n    }\n  }\n\n  static makeFromUrl(url: string, host: 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 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 firebaseStorageHost = host.replace(/[.]/g, '\\\\.');\n    const firebaseStoragePath = '(/([^?#]*).*)?$';\n    const firebaseStorageRegExp = new RegExp(\n      `^https?://${firebaseStorageHost}/${version}/b/${bucketDomain}/o${firebaseStoragePath}`,\n      'i'\n    );\n    const firebaseStorageIndices = { bucket: 1, path: 3 };\n\n    const cloudStorageHost =\n      host === DEFAULT_HOST\n        ? '(?:storage.googleapis.com|storage.cloud.google.com)'\n        : host;\n    const cloudStoragePath = '([^?#]*)';\n    const cloudStorageRegExp = new RegExp(\n      `^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`,\n      'i'\n    );\n    const cloudStorageIndices = { bucket: 1, path: 2 };\n\n    const groups = [\n      { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n      {\n        regex: firebaseStorageRegExp,\n        indices: firebaseStorageIndices,\n        postModify: httpModify\n      },\n      {\n        regex: cloudStorageRegExp,\n        indices: cloudStorageIndices,\n        postModify: httpModify\n      }\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 invalidUrl(url);\n    }\n    return location;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { StorageError } from './error';\nimport { Request } from './request';\n\n/**\n * A request whose promise always fails.\n */\nexport class FailRequest<T> implements Request<T> {\n  promise_: Promise<T>;\n\n  constructor(error: StorageError) {\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 LLC\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 { invalidArgument } from './error';\n\nexport function isJustDef<T>(p: T | null | undefined): p is T | null {\n  return p !== void 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isFunction(p: unknown): p is Function {\n  return typeof p === 'function';\n}\n\nexport function isNonArrayObject(p: unknown): boolean {\n  return typeof p === 'object' && !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 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\nexport function validateNumber(\n  argument: string,\n  minValue: number,\n  maxValue: number,\n  value: number\n): void {\n  if (value < minValue) {\n    throw invalidArgument(\n      `Invalid value for '${argument}'. Expected ${minValue} or greater.`\n    );\n  }\n  if (value > maxValue) {\n    throw invalidArgument(\n      `Invalid value for '${argument}'. Expected ${maxValue} or less.`\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { UrlParams } from './requestinfo';\n\nexport function makeUrl(\n  urlPart: string,\n  host: string,\n  protocol: string\n): string {\n  let origin = host;\n  if (protocol == null) {\n    origin = `https://${host}`;\n  }\n  return `${protocol}://${origin}/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      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 2022 Google LLC\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 * Checks the status code to see if the action should be retried.\n *\n * @param status Current HTTP status code returned by server.\n * @param additionalRetryCodes additional retry codes to check against\n */\nexport function isRetryStatusCode(\n  status: number,\n  additionalRetryCodes: number[]\n): 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 isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;\n  return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { id as backoffId, start, stop } from './backoff';\nimport { appDeleted, canceled, retryLimitExceeded, unknown } from './error';\nimport { ErrorHandler, RequestHandler, RequestInfo } from './requestinfo';\nimport { isJustDef } from './type';\nimport { makeQueryString } from './url';\nimport { Connection, ErrorCode, Headers, ConnectionType } from './connection';\nimport { isRetryStatusCode } from './utils';\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 * Handles network logic for all Storage Requests, including error reporting and\n * retries with backoff.\n *\n * @param I - the type of the backend's network response.\n * @param - O the output type used by the rest of the SDK. The conversion\n * happens in the specified `callback_`.\n */\nclass NetworkRequest<I extends ConnectionType, O> implements Request<O> {\n  private pendingConnection_: Connection<I> | null = null;\n  private backoffId_: backoffId | null = null;\n  private resolve_!: (value?: O | PromiseLike<O>) => void;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  private reject_!: (reason?: any) => void;\n  private canceled_: boolean = false;\n  private appDelete_: boolean = false;\n  private promise_: Promise<O>;\n\n  constructor(\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 callback_: RequestHandler<I, O>,\n    private errorCallback_: ErrorHandler | null,\n    private timeout_: number,\n    private progressCallback_: ((p1: number, p2: number) => void) | null,\n    private connectionFactory_: () => Connection<I>,\n    private retry = true,\n    private isUsingEmulator = false\n  ) {\n    this.promise_ = new Promise((resolve, reject) => {\n      this.resolve_ = resolve as (value?: O | PromiseLike<O>) => void;\n      this.reject_ = reject;\n      this.start_();\n    });\n  }\n\n  /**\n   * Actually starts the retry loop.\n   */\n  private start_(): void {\n    const doTheRequest: (\n      backoffCallback: (success: boolean, ...p2: unknown[]) => void,\n      canceled: boolean\n    ) => void = (backoffCallback, canceled) => {\n      if (canceled) {\n        backoffCallback(false, new RequestEndStatus(false, null, true));\n        return;\n      }\n      const connection = this.connectionFactory_();\n      this.pendingConnection_ = connection;\n\n      const progressListener: (\n        progressEvent: ProgressEvent\n      ) => void = progressEvent => {\n        const loaded = progressEvent.loaded;\n        const total = progressEvent.lengthComputable ? progressEvent.total : -1;\n        if (this.progressCallback_ !== null) {\n          this.progressCallback_(loaded, total);\n        }\n      };\n      if (this.progressCallback_ !== null) {\n        connection.addUploadProgressListener(progressListener);\n      }\n\n      // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      connection\n        .send(\n          this.url_,\n          this.method_,\n          this.isUsingEmulator,\n          this.body_,\n          this.headers_\n        )\n        .then(() => {\n          if (this.progressCallback_ !== null) {\n            connection.removeUploadProgressListener(progressListener);\n          }\n          this.pendingConnection_ = null;\n          const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;\n          const status = connection.getStatus();\n          if (\n            !hitServer ||\n            (isRetryStatusCode(status, this.additionalRetryCodes_) &&\n              this.retry)\n          ) {\n            const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;\n            backoffCallback(\n              false,\n              new RequestEndStatus(false, null, wasCanceled)\n            );\n            return;\n          }\n          const successCode = this.successCodes_.indexOf(status) !== -1;\n          backoffCallback(true, new RequestEndStatus(successCode, connection));\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    const backoffDone: (\n      requestWentThrough: boolean,\n      status: RequestEndStatus<I>\n    ) => void = (requestWentThrough, status) => {\n      const resolve = this.resolve_;\n      const reject = this.reject_;\n      const connection = status.connection as Connection<I>;\n      if (status.wasSuccessCode) {\n        try {\n          const result = this.callback_(connection, connection.getResponse());\n          if (isJustDef(result)) {\n            resolve(result);\n          } else {\n            resolve();\n          }\n        } catch (e) {\n          reject(e);\n        }\n      } else {\n        if (connection !== null) {\n          const err = unknown();\n          err.serverResponse = connection.getErrorText();\n          if (this.errorCallback_) {\n            reject(this.errorCallback_(connection, err));\n          } else {\n            reject(err);\n          }\n        } else {\n          if (status.canceled) {\n            const err = this.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_ = start(doTheRequest, backoffDone, this.timeout_);\n    }\n  }\n\n  /** @inheritDoc */\n  getPromise(): Promise<O> {\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      stop(this.backoffId_);\n    }\n    if (this.pendingConnection_ !== null) {\n      this.pendingConnection_.abort();\n    }\n  }\n}\n\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled - Defaults to false.\n */\nexport class RequestEndStatus<I extends ConnectionType> {\n  /**\n   * True if the request was canceled.\n   */\n  canceled: boolean;\n\n  constructor(\n    public wasSuccessCode: boolean,\n    public connection: Connection<I> | 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_(\n  headers: Headers,\n  firebaseVersion?: string\n): void {\n  headers['X-Firebase-Storage-Version'] =\n    'webjs/' + (firebaseVersion ?? 'AppManager');\n}\n\nexport function addGmpidHeader_(headers: Headers, appId: string | null): void {\n  if (appId) {\n    headers['X-Firebase-GMPID'] = appId;\n  }\n}\n\nexport function addAppCheckHeader_(\n  headers: Headers,\n  appCheckToken: string | null\n): void {\n  if (appCheckToken !== null) {\n    headers['X-Firebase-AppCheck'] = appCheckToken;\n  }\n}\n\nexport function makeRequest<I extends ConnectionType, O>(\n  requestInfo: RequestInfo<I, O>,\n  appId: string | null,\n  authToken: string | null,\n  appCheckToken: string | null,\n  requestFactory: () => Connection<I>,\n  firebaseVersion?: string,\n  retry = true,\n  isUsingEmulator = false\n): Request<O> {\n  const queryPart = makeQueryString(requestInfo.urlParams);\n  const url = requestInfo.url + queryPart;\n  const headers = Object.assign({}, requestInfo.headers);\n  addGmpidHeader_(headers, appId);\n  addAuthHeader_(headers, authToken);\n  addVersionHeader_(headers, firebaseVersion);\n  addAppCheckHeader_(headers, appCheckToken);\n  return new NetworkRequest<I, O>(\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    requestFactory,\n    retry,\n    isUsingEmulator\n  );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 * Accepts a callback for an action to perform (`doRequest`),\n * and then a callback for when the backoff has completed (`backoffCompleteCb`).\n * The callback sent to start requires an argument to call (`onRequestComplete`).\n * When `start` calls `doRequest`, it passes a callback for when the request has\n * completed, `onRequestComplete`. Based on this, the backoff continues, with\n * another call to `doRequest` and the above loop continues until the timeout\n * is hit, or a successful response occurs.\n * @description\n * @param doRequest Callback to perform request\n * @param backoffCompleteCb Callback to call when backoff has been completed\n */\nexport function start(\n  doRequest: (\n    onRequestComplete: (success: boolean) => void,\n    canceled: boolean\n  ) => void,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  backoffCompleteCb: (...args: any[]) => unknown,\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 retryTimeoutId: any = null;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  let globalTimeoutId: 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  function triggerCallback(...args: any[]): void {\n    if (!triggeredCallback) {\n      triggeredCallback = true;\n      backoffCompleteCb.apply(null, args);\n    }\n  }\n\n  function callWithDelay(millis: number): void {\n    retryTimeoutId = setTimeout(() => {\n      retryTimeoutId = null;\n      doRequest(responseHandler, canceled());\n    }, millis);\n  }\n\n  function clearGlobalTimeout(): void {\n    if (globalTimeoutId) {\n      clearTimeout(globalTimeoutId);\n    }\n  }\n\n  function responseHandler(success: boolean, ...args: any[]): void {\n    if (triggeredCallback) {\n      clearGlobalTimeout();\n      return;\n    }\n    if (success) {\n      clearGlobalTimeout();\n      triggerCallback.call(null, success, ...args);\n      return;\n    }\n    const mustStop = canceled() || hitTimeout;\n    if (mustStop) {\n      clearGlobalTimeout();\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    clearGlobalTimeout();\n    if (triggeredCallback) {\n      return;\n    }\n    if (retryTimeoutId !== null) {\n      if (!wasTimeout) {\n        cancelState = 2;\n      }\n      clearTimeout(retryTimeoutId);\n      callWithDelay(0);\n    } else {\n      if (!wasTimeout) {\n        cancelState = 1;\n      }\n    }\n  }\n  callWithDelay(0);\n  globalTimeoutId = 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 LLC\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 { isNativeBlobDefined } from './type';\nimport { StorageErrorCode, StorageError } from './error';\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 (isNativeBlobDefined()) {\n      return new Blob(args);\n    } else {\n      throw new StorageError(\n        StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n        \"This browser doesn't seem to support creating Blobs\"\n      );\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 2021 Google LLC\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 { missingPolyFill } from '../../implementation/error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n  if (typeof atob === 'undefined') {\n    throw missingPolyFill('base-64');\n  }\n  return atob(encoded);\n}\n\nexport function decodeUint8Array(data: Uint8Array): string {\n  return new TextDecoder().decode(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { unknown, invalidFormat } from './error';\nimport { decodeBase64 } from '../platform/base64';\n\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport type StringFormat = (typeof StringFormat)[keyof typeof StringFormat];\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport const StringFormat = {\n  /**\n   * Indicates the string should be interpreted \"raw\", that is, as normal text.\n   * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte\n   * sequence.\n   * Example: The string 'Hello! \\\\ud83d\\\\ude0a' becomes the byte sequence\n   * 48 65 6c 6c 6f 21 20 f0 9f 98 8a\n   */\n  RAW: 'raw',\n  /**\n   * Indicates the string should be interpreted as base64-encoded data.\n   * Padding characters (trailing '='s) are optional.\n   * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence\n   * ad 69 8e fb e1 3a b7 bf eb 97\n   */\n  BASE64: 'base64',\n  /**\n   * Indicates the string should be interpreted as base64url-encoded data.\n   * Padding characters (trailing '='s) are optional.\n   * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence\n   * ad 69 8e fb e1 3a b7 bf eb 97\n   */\n  BASE64URL: 'base64url',\n  /**\n   * Indicates the string is a data URL, such as one obtained from\n   * canvas.toDataURL().\n   * Example: the string 'data:application/octet-stream;base64,aaaa'\n   * becomes the byte sequence\n   * 69 a6 9a\n   * (the content-type \"application/octet-stream\" is also applied, but can\n   * be overridden in the metadata object).\n   */\n  DATA_URL: 'data_url'\n} as const;\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\n/**\n * @internal\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 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 invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\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 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 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 = decodeBase64(value);\n  } catch (e) {\n    if ((e as Error).message.includes('polyfill')) {\n      throw e;\n    }\n    throw 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\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 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 LLC\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 { sliceBlob, getBlob } from './fs';\nimport { StringFormat, dataFromString } from './string';\nimport { isNativeBlob, isNativeBlobDefined, isString } 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 *\n * @internal\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 (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 (isNativeBlob(this.data_)) {\n      const realBlob = this.data_ as Blob;\n      const sliced = 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 (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(getBlob.apply(null, blobby));\n    } else {\n      const uint8Arrays: Uint8Array[] = args.map(\n        (val: string | FbsBlob): Uint8Array => {\n          if (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 LLC\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 { isNonArrayObject } 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 (isNonArrayObject(obj)) {\n    return obj;\n  } else {\n    return null;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 LLC\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 { jsonObjectOrNull } from './json';\nimport { Location } from './location';\nimport { lastComponent } from './path';\nimport { isString } from './type';\nimport { makeUrl, makeQueryString } from './url';\nimport { Reference } from '../reference';\nimport { FirebaseStorageImpl } from '../service';\n\nexport function noXform_<T>(metadata: Metadata, value: T): T {\n  return value;\n}\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 (!isString(fullPath) || fullPath.length < 2) {\n    return fullPath;\n  } else {\n    return 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\n  ): number | undefined {\n    if (size !== undefined) {\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, service: FirebaseStorageImpl): 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 service._makeStorageReference(loc);\n  }\n  Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\n\nexport function fromResource(\n  service: FirebaseStorageImpl,\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, service);\n  return metadata;\n}\n\nexport function fromResourceString(\n  service: FirebaseStorageImpl,\n  resourceString: string,\n  mappings: Mappings\n): Metadata | null {\n  const obj = jsonObjectOrNull(resourceString);\n  if (obj === null) {\n    return null;\n  }\n  const resource = obj as Metadata;\n  return fromResource(service, resource, mappings);\n}\n\nexport function downloadUrlFromResourceString(\n  metadata: Metadata,\n  resourceString: string,\n  host: string,\n  protocol: string\n): string | null {\n  const obj = jsonObjectOrNull(resourceString);\n  if (obj === null) {\n    return null;\n  }\n  if (!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 = makeUrl(urlPart, host, protocol);\n    const queryString = makeQueryString({\n      alt: 'media',\n      token\n    });\n    return base + queryString;\n  });\n  return urls[0];\n}\n\nexport function toResourceString(\n  metadata: Partial<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","/**\n * @license\n * Copyright 2019 Google LLC\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 { Location } from './location';\nimport { jsonObjectOrNull } from './json';\nimport { ListResult } from '../list';\nimport { FirebaseStorageImpl } from '../service';\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 PREFIXES_KEY = 'prefixes';\nconst ITEMS_KEY = 'items';\n\nfunction fromBackendResponse(\n  service: FirebaseStorageImpl,\n  bucket: string,\n  resource: ListResultResponse\n): ListResult {\n  const listResult: ListResult = {\n    prefixes: [],\n    items: [],\n    nextPageToken: resource['nextPageToken']\n  };\n  if (resource[PREFIXES_KEY]) {\n    for (const path of resource[PREFIXES_KEY]) {\n      const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\n      const reference = service._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 = service._makeStorageReference(\n        new Location(bucket, item['name'])\n      );\n      listResult.items.push(reference);\n    }\n  }\n  return listResult;\n}\n\nexport function fromResponseString(\n  service: FirebaseStorageImpl,\n  bucket: string,\n  resourceString: string\n): ListResult | null {\n  const obj = jsonObjectOrNull(resourceString);\n  if (obj === null) {\n    return null;\n  }\n  const resource = obj as unknown as ListResultResponse;\n  return fromBackendResponse(service, bucket, resource);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { StorageError } from './error';\nimport { Headers, Connection, ConnectionType } from './connection';\n\n/**\n * Type for url params stored in RequestInfo.\n */\nexport interface UrlParams {\n  [name: string]: string | number;\n}\n\n/**\n * A function that converts a server response to the API type expected by the\n * SDK.\n *\n * @param I - the type of the backend's network response\n * @param O - the output response type used by the rest of the SDK.\n */\nexport type RequestHandler<I extends ConnectionType, O> = (\n  connection: Connection<I>,\n  response: I\n) => O;\n\n/** A function to handle an error. */\nexport type ErrorHandler = (\n  connection: Connection<ConnectionType>,\n  response: StorageError\n) => StorageError;\n\n/**\n * Contains a fully specified request.\n *\n * @param I - the type of the backend's network response.\n * @param O - the output response type used by the rest of the SDK.\n */\nexport class RequestInfo<I extends ConnectionType, O> {\n  urlParams: UrlParams = {};\n  headers: Headers = {};\n  body: Blob | string | Uint8Array | null = null;\n  errorHandler: ErrorHandler | 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: RequestHandler<I, O>,\n    public timeout: number\n  ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { FbsBlob } from './blob';\nimport {\n  StorageError,\n  cannotSliceBlob,\n  unauthenticated,\n  quotaExceeded,\n  unauthorized,\n  objectNotFound,\n  serverFileWrongSize,\n  unknown,\n  unauthorizedApp\n} from './error';\nimport { Location } from './location';\nimport {\n  Mappings,\n  fromResourceString,\n  downloadUrlFromResourceString,\n  toResourceString\n} from './metadata';\nimport { fromResponseString } from './list';\nimport { RequestInfo, UrlParams } from './requestinfo';\nimport { isString } from './type';\nimport { makeUrl } from './url';\nimport { Connection, ConnectionType } from './connection';\nimport { FirebaseStorageImpl } from '../service';\n\n/**\n * Throws the UNKNOWN StorageError if cndn is false.\n */\nexport function handlerCheck(cndn: boolean): void {\n  if (!cndn) {\n    throw unknown();\n  }\n}\n\nexport function metadataHandler(\n  service: FirebaseStorageImpl,\n  mappings: Mappings\n): (p1: Connection<string>, p2: string) => Metadata {\n  function handler(xhr: Connection<string>, text: string): Metadata {\n    const metadata = fromResourceString(service, text, mappings);\n    handlerCheck(metadata !== null);\n    return metadata as Metadata;\n  }\n  return handler;\n}\n\nexport function listHandler(\n  service: FirebaseStorageImpl,\n  bucket: string\n): (p1: Connection<string>, p2: string) => ListResult {\n  function handler(xhr: Connection<string>, text: string): ListResult {\n    const listResult = fromResponseString(service, bucket, text);\n    handlerCheck(listResult !== null);\n    return listResult as ListResult;\n  }\n  return handler;\n}\n\nexport function downloadUrlHandler(\n  service: FirebaseStorageImpl,\n  mappings: Mappings\n): (p1: Connection<string>, p2: string) => string | null {\n  function handler(xhr: Connection<string>, text: string): string | null {\n    const metadata = fromResourceString(service, text, mappings);\n    handlerCheck(metadata !== null);\n    return downloadUrlFromResourceString(\n      metadata as Metadata,\n      text,\n      service.host,\n      service._protocol\n    );\n  }\n  return handler;\n}\n\nexport function sharedErrorHandler(\n  location: Location\n): (p1: Connection<ConnectionType>, p2: StorageError) => StorageError {\n  function errorHandler(\n    xhr: Connection<ConnectionType>,\n    err: StorageError\n  ): StorageError {\n    let newErr: StorageError;\n    if (xhr.getStatus() === 401) {\n      if (\n        // This exact message string is the only consistent part of the\n        // server's error response that identifies it as an App Check error.\n        xhr.getErrorText().includes('Firebase App Check token is invalid')\n      ) {\n        newErr = unauthorizedApp();\n      } else {\n        newErr = unauthenticated();\n      }\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.status = xhr.getStatus();\n    newErr.serverResponse = err.serverResponse;\n    return newErr;\n  }\n  return errorHandler;\n}\n\nexport function objectErrorHandler(\n  location: Location\n): (p1: Connection<ConnectionType>, p2: StorageError) => StorageError {\n  const shared = sharedErrorHandler(location);\n\n  function errorHandler(\n    xhr: Connection<ConnectionType>,\n    err: StorageError\n  ): StorageError {\n    let newErr = shared(xhr, err);\n    if (xhr.getStatus() === 404) {\n      newErr = objectNotFound(location.path);\n    }\n    newErr.serverResponse = err.serverResponse;\n    return newErr;\n  }\n  return errorHandler;\n}\n\nexport function getMetadata(\n  service: FirebaseStorageImpl,\n  location: Location,\n  mappings: Mappings\n): RequestInfo<string, Metadata> {\n  const urlPart = location.fullServerUrl();\n  const url = makeUrl(urlPart, service.host, service._protocol);\n  const method = 'GET';\n  const timeout = service.maxOperationRetryTime;\n  const requestInfo = new RequestInfo(\n    url,\n    method,\n    metadataHandler(service, mappings),\n    timeout\n  );\n  requestInfo.errorHandler = objectErrorHandler(location);\n  return requestInfo;\n}\n\nexport function list(\n  service: FirebaseStorageImpl,\n  location: Location,\n  delimiter?: string,\n  pageToken?: string | null,\n  maxResults?: number | null\n): RequestInfo<string, 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 = makeUrl(urlPart, service.host, service._protocol);\n  const method = 'GET';\n  const timeout = service.maxOperationRetryTime;\n  const requestInfo = new RequestInfo(\n    url,\n    method,\n    listHandler(service, location.bucket),\n    timeout\n  );\n  requestInfo.urlParams = urlParams;\n  requestInfo.errorHandler = sharedErrorHandler(location);\n  return requestInfo;\n}\n\nexport function getBytes<I extends ConnectionType>(\n  service: FirebaseStorageImpl,\n  location: Location,\n  maxDownloadSizeBytes?: number\n): RequestInfo<I, I> {\n  const urlPart = location.fullServerUrl();\n  const url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';\n  const method = 'GET';\n  const timeout = service.maxOperationRetryTime;\n  const requestInfo = new RequestInfo(\n    url,\n    method,\n    (_: Connection<I>, data: I) => data,\n    timeout\n  );\n  requestInfo.errorHandler = objectErrorHandler(location);\n  if (maxDownloadSizeBytes !== undefined) {\n    requestInfo.headers['Range'] = `bytes=0-${maxDownloadSizeBytes}`;\n    requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];\n  }\n  return requestInfo;\n}\n\nexport function getDownloadUrl(\n  service: FirebaseStorageImpl,\n  location: Location,\n  mappings: Mappings\n): RequestInfo<string, string | null> {\n  const urlPart = location.fullServerUrl();\n  const url = makeUrl(urlPart, service.host, service._protocol);\n  const method = 'GET';\n  const timeout = service.maxOperationRetryTime;\n  const requestInfo = new RequestInfo(\n    url,\n    method,\n    downloadUrlHandler(service, mappings),\n    timeout\n  );\n  requestInfo.errorHandler = objectErrorHandler(location);\n  return requestInfo;\n}\n\nexport function updateMetadata(\n  service: FirebaseStorageImpl,\n  location: Location,\n  metadata: Partial<Metadata>,\n  mappings: Mappings\n): RequestInfo<string, Metadata> {\n  const urlPart = location.fullServerUrl();\n  const url = makeUrl(urlPart, service.host, service._protocol);\n  const method = 'PATCH';\n  const body = toResourceString(metadata, mappings);\n  const headers = { 'Content-Type': 'application/json; charset=utf-8' };\n  const timeout = service.maxOperationRetryTime;\n  const requestInfo = new RequestInfo(\n    url,\n    method,\n    metadataHandler(service, 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  service: FirebaseStorageImpl,\n  location: Location\n): RequestInfo<string, void> {\n  const urlPart = location.fullServerUrl();\n  const url = makeUrl(urlPart, service.host, service._protocol);\n  const method = 'DELETE';\n  const timeout = service.maxOperationRetryTime;\n\n  function handler(_xhr: Connection<string>, _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\n/**\n * Prepare RequestInfo for uploads as Content-Type: multipart.\n */\nexport function multipartUpload(\n  service: FirebaseStorageImpl,\n  location: Location,\n  mappings: Mappings,\n  blob: FbsBlob,\n  metadata?: Metadata | null\n): RequestInfo<string, 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 = str + Math.random().toString().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 = 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 = makeUrl(urlPart, service.host, service._protocol);\n  const method = 'POST';\n  const timeout = service.maxUploadRetryTime;\n  const requestInfo = new RequestInfo(\n    url,\n    method,\n    metadataHandler(service, 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 */\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_(\n  xhr: Connection<string>,\n  allowed?: string[]\n): 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  service: FirebaseStorageImpl,\n  location: Location,\n  mappings: Mappings,\n  blob: FbsBlob,\n  metadata?: Metadata | null\n): RequestInfo<string, string> {\n  const urlPart = location.bucketOnlyServerUrl();\n  const metadataForUpload = metadataForUpload_(location, blob, metadata);\n  const urlParams: UrlParams = { name: metadataForUpload['fullPath']! };\n  const url = makeUrl(urlPart, service.host, service._protocol);\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 = toResourceString(metadataForUpload, mappings);\n  const timeout = service.maxUploadRetryTime;\n\n  function handler(xhr: Connection<string>): 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(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  service: FirebaseStorageImpl,\n  location: Location,\n  url: string,\n  blob: FbsBlob\n): RequestInfo<string, ResumableUploadStatus> {\n  const headers = { 'X-Goog-Upload-Command': 'query' };\n\n  function handler(xhr: Connection<string>): 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 = service.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 RESUMABLE_UPLOAD_CHUNK_SIZE: 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  service: FirebaseStorageImpl,\n  url: string,\n  blob: FbsBlob,\n  chunkSize: number,\n  mappings: Mappings,\n  status?: ResumableUploadStatus | null,\n  progressCallback?: ((p1: number, p2: number) => void) | null\n): RequestInfo<string, 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  let uploadCommand = '';\n  if (bytesToUpload === 0) {\n    uploadCommand = 'finalize';\n  } else if (bytesLeft === bytesToUpload) {\n    uploadCommand = 'upload, finalize';\n  } else {\n    uploadCommand = 'upload';\n  }\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(\n    xhr: Connection<string>,\n    text: string\n  ): 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(service, 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 = service.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 LLC\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 * An event that is triggered on a task.\n * @internal\n */\nexport type TaskEvent = string;\n\n/**\n * An event that is triggered on a task.\n * @internal\n */\nexport const TaskEvent = {\n  /**\n   * For this event,\n   * <ul>\n   *   <li>The `next` function is triggered on progress updates and when the\n   *       task is paused/resumed with an `UploadTaskSnapshot` as the first\n   *       argument.</li>\n   *   <li>The `error` function is triggered if the upload is canceled or fails\n   *       for another reason.</li>\n   *   <li>The `complete` function is triggered if the upload completes\n   *       successfully.</li>\n   * </ul>\n   */\n  STATE_CHANGED: 'state_changed'\n};\n\n/**\n * Internal enum for task state.\n */\nexport const enum 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 * Represents the current state of a running upload.\n * @internal\n */\nexport type TaskState = (typeof TaskState)[keyof typeof TaskState];\n\n// type keys = keyof TaskState\n/**\n * Represents the current state of a running upload.\n * @internal\n */\nexport const TaskState = {\n  /** The task is currently transferring data. */\n  RUNNING: 'running',\n\n  /** The task was paused by the user. */\n  PAUSED: 'paused',\n\n  /** The task completed successfully. */\n  SUCCESS: 'success',\n\n  /** The task was canceled. */\n  CANCELED: 'canceled',\n\n  /** The task failed with an error. */\n  ERROR: 'error'\n} as const;\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 LLC\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 { isFunction } from './type';\nimport { StorageError } from './error';\n\n/**\n * Function that is called once for each value in a stream of values.\n */\nexport type NextFn<T> = (value: T) => void;\n\n/**\n * A function that is called with a `StorageError`\n * if the event stream ends due to an error.\n */\nexport type ErrorFn = (error: StorageError) => void;\n\n/**\n * A function that is called if the event stream ends normally.\n */\nexport type CompleteFn = () => void;\n\n/**\n * Unsubscribes from a stream.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * An observer identical to the `Observer` defined in packages/util except the\n * error passed into the ErrorFn is specifically a `StorageError`.\n */\nexport interface StorageObserver<T> {\n  /**\n   * Function that is called once for each value in the event stream.\n   */\n  next?: NextFn<T>;\n  /**\n   * A function that is called with a `StorageError`\n   * if the event stream ends due to an error.\n   */\n  error?: ErrorFn;\n  /**\n   * A function that is called if the event stream ends normally.\n   */\n  complete?: CompleteFn;\n}\n\n/**\n * Subscribes to an event stream.\n */\nexport type Subscribe<T> = (\n  next?: NextFn<T> | StorageObserver<T>,\n  error?: ErrorFn,\n  complete?: CompleteFn\n) => Unsubscribe;\n\nexport class Observer<T> implements StorageObserver<T> {\n  next?: NextFn<T>;\n  error?: ErrorFn;\n  complete?: CompleteFn;\n\n  constructor(\n    nextOrObserver?: NextFn<T> | StorageObserver<T>,\n    error?: ErrorFn,\n    complete?: CompleteFn\n  ) {\n    const asFunctions =\n      isFunction(nextOrObserver) || error != null || complete != null;\n    if (asFunctions) {\n      this.next = nextOrObserver as NextFn<T>;\n      this.error = error ?? undefined;\n      this.complete = complete ?? undefined;\n    } else {\n      const observer = nextOrObserver as {\n        next?: NextFn<T>;\n        error?: ErrorFn;\n        complete?: CompleteFn;\n      };\n      this.next = observer.next;\n      this.error = observer.error;\n      this.complete = observer.complete;\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 */\n// eslint-disable-next-line @typescript-eslint/ban-types\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 LLC\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 { isCloudWorkstation } from '@firebase/util';\nimport {\n  Connection,\n  ConnectionType,\n  ErrorCode,\n  Headers\n} from '../../implementation/connection';\nimport { internalError } from '../../implementation/error';\n\n/** An override for the text-based Connection. Used in tests. */\nlet textFactoryOverride: (() => Connection<string>) | null = null;\n\n/**\n * Network layer for browsers. We use this instead of goog.net.XhrIo because\n * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.\n */\nabstract class XhrConnection<T extends ConnectionType>\n  implements Connection<T>\n{\n  protected xhr_: XMLHttpRequest;\n  private errorCode_: ErrorCode;\n  private sendPromise_: Promise<void>;\n  protected sent_: boolean = false;\n\n  constructor() {\n    this.xhr_ = new XMLHttpRequest();\n    this.initXhr();\n    this.errorCode_ = ErrorCode.NO_ERROR;\n    this.sendPromise_ = new Promise(resolve => {\n      this.xhr_.addEventListener('abort', () => {\n        this.errorCode_ = ErrorCode.ABORT;\n        resolve();\n      });\n      this.xhr_.addEventListener('error', () => {\n        this.errorCode_ = ErrorCode.NETWORK_ERROR;\n        resolve();\n      });\n      this.xhr_.addEventListener('load', () => {\n        resolve();\n      });\n    });\n  }\n\n  abstract initXhr(): void;\n\n  send(\n    url: string,\n    method: string,\n    isUsingEmulator: boolean,\n    body?: ArrayBufferView | Blob | string,\n    headers?: Headers\n  ): Promise<void> {\n    if (this.sent_) {\n      throw internalError('cannot .send() more than once');\n    }\n    if (isCloudWorkstation(url) && isUsingEmulator) {\n      this.xhr_.withCredentials = true;\n    }\n    this.sent_ = true;\n    this.xhr_.open(method, url, true);\n    if (headers !== undefined) {\n      for (const key in headers) {\n        if (headers.hasOwnProperty(key)) {\n          this.xhr_.setRequestHeader(key, headers[key].toString());\n        }\n      }\n    }\n    if (body !== undefined) {\n      this.xhr_.send(body);\n    } else {\n      this.xhr_.send();\n    }\n    return this.sendPromise_;\n  }\n\n  getErrorCode(): ErrorCode {\n    if (!this.sent_) {\n      throw internalError('cannot .getErrorCode() before sending');\n    }\n    return this.errorCode_;\n  }\n\n  getStatus(): number {\n    if (!this.sent_) {\n      throw internalError('cannot .getStatus() before sending');\n    }\n    try {\n      return this.xhr_.status;\n    } catch (e) {\n      return -1;\n    }\n  }\n\n  getResponse(): T {\n    if (!this.sent_) {\n      throw internalError('cannot .getResponse() before sending');\n    }\n    return this.xhr_.response;\n  }\n\n  getErrorText(): string {\n    if (!this.sent_) {\n      throw internalError('cannot .getErrorText() before sending');\n    }\n    return this.xhr_.statusText;\n  }\n\n  /** Aborts the request. */\n  abort(): void {\n    this.xhr_.abort();\n  }\n\n  getResponseHeader(header: string): string | null {\n    return this.xhr_.getResponseHeader(header);\n  }\n\n  addUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n    if (this.xhr_.upload != null) {\n      this.xhr_.upload.addEventListener('progress', listener);\n    }\n  }\n\n  removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n    if (this.xhr_.upload != null) {\n      this.xhr_.upload.removeEventListener('progress', listener);\n    }\n  }\n}\n\nexport class XhrTextConnection extends XhrConnection<string> {\n  initXhr(): void {\n    this.xhr_.responseType = 'text';\n  }\n}\n\nexport function newTextConnection(): Connection<string> {\n  return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();\n}\n\nexport class XhrBytesConnection extends XhrConnection<ArrayBuffer> {\n  private data_?: ArrayBuffer;\n\n  initXhr(): void {\n    this.xhr_.responseType = 'arraybuffer';\n  }\n}\n\nexport function newBytesConnection(): Connection<ArrayBuffer> {\n  return new XhrBytesConnection();\n}\n\nexport class XhrBlobConnection extends XhrConnection<Blob> {\n  initXhr(): void {\n    this.xhr_.responseType = 'blob';\n  }\n}\n\nexport function newBlobConnection(): Connection<Blob> {\n  return new XhrBlobConnection();\n}\n\nexport function newStreamConnection(): Connection<ReadableStream> {\n  throw new Error('Streams are only supported on Node');\n}\n\nexport function injectTestConnection(\n  factory: (() => Connection<string>) | null\n): void {\n  textFactoryOverride = factory;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { FbsBlob } from './implementation/blob';\nimport {\n  canceled,\n  StorageErrorCode,\n  StorageError,\n  retryLimitExceeded\n} from './implementation/error';\nimport {\n  InternalTaskState,\n  TaskEvent,\n  TaskState,\n  taskStateFromInternalTaskState\n} from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport {\n  Observer,\n  Subscribe,\n  Unsubscribe,\n  StorageObserver as StorageObserverInternal,\n  NextFn\n} from './implementation/observer';\nimport { Request } from './implementation/request';\nimport { UploadTaskSnapshot, StorageObserver } from './public-types';\nimport { async as fbsAsync } from './implementation/async';\nimport { Mappings, getMappings } from './implementation/metadata';\nimport {\n  createResumableUpload,\n  getResumableUploadStatus,\n  RESUMABLE_UPLOAD_CHUNK_SIZE,\n  ResumableUploadStatus,\n  continueResumableUpload,\n  getMetadata,\n  multipartUpload\n} from './implementation/requests';\nimport { Reference } from './reference';\nimport { newTextConnection } from './platform/connection';\nimport { isRetryStatusCode } from './implementation/utils';\nimport { CompleteFn } from '@firebase/util';\nimport { DEFAULT_MIN_SLEEP_TIME_MILLIS } from './implementation/constants';\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 * @internal\n */\nexport class UploadTask {\n  private _ref: Reference;\n  /**\n   * The data to be uploaded.\n   */\n  _blob: FbsBlob;\n  /**\n   * Metadata related to the upload.\n   */\n  _metadata: Metadata | null;\n  private _mappings: Mappings;\n  /**\n   * Number of bytes transferred so far.\n   */\n  _transferred: number = 0;\n  private _needToFetchStatus: boolean = false;\n  private _needToFetchMetadata: boolean = false;\n  private _observers: Array<StorageObserverInternal<UploadTaskSnapshot>> = [];\n  private _resumable: boolean;\n  /**\n   * Upload state.\n   */\n  _state: InternalTaskState;\n  private _error?: StorageError = undefined;\n  private _uploadUrl?: string = undefined;\n  private _request?: Request<unknown> = undefined;\n  private _chunkMultiplier: number = 1;\n  private _errorHandler: (p1: StorageError) => void;\n  private _metadataErrorHandler: (p1: StorageError) => void;\n  private _resolve?: (p1: UploadTaskSnapshot) => void = undefined;\n  private _reject?: (p1: StorageError) => void = undefined;\n  private pendingTimeout?: ReturnType<typeof setTimeout>;\n  private _promise: Promise<UploadTaskSnapshot>;\n\n  private sleepTime: number;\n\n  private maxSleepTime: number;\n\n  isExponentialBackoffExpired(): boolean {\n    return this.sleepTime > this.maxSleepTime;\n  }\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(ref: Reference, blob: FbsBlob, metadata: Metadata | null = null) {\n    this._ref = ref;\n    this._blob = blob;\n    this._metadata = metadata;\n    this._mappings = getMappings();\n    this._resumable = this._shouldDoResumable(this._blob);\n    this._state = InternalTaskState.RUNNING;\n    this._errorHandler = error => {\n      this._request = undefined;\n      this._chunkMultiplier = 1;\n      if (error._codeEquals(StorageErrorCode.CANCELED)) {\n        this._needToFetchStatus = true;\n        this.completeTransitions_();\n      } else {\n        const backoffExpired = this.isExponentialBackoffExpired();\n        if (isRetryStatusCode(error.status, [])) {\n          if (backoffExpired) {\n            error = retryLimitExceeded();\n          } else {\n            this.sleepTime = Math.max(\n              this.sleepTime * 2,\n              DEFAULT_MIN_SLEEP_TIME_MILLIS\n            );\n            this._needToFetchStatus = true;\n            this.completeTransitions_();\n            return;\n          }\n        }\n        this._error = error;\n        this._transition(InternalTaskState.ERROR);\n      }\n    };\n    this._metadataErrorHandler = error => {\n      this._request = undefined;\n      if (error._codeEquals(StorageErrorCode.CANCELED)) {\n        this.completeTransitions_();\n      } else {\n        this._error = error;\n        this._transition(InternalTaskState.ERROR);\n      }\n    };\n    this.sleepTime = 0;\n    this.maxSleepTime = this._ref.storage.maxUploadRetryTime;\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 !== undefined) {\n      return;\n    }\n    if (this._resumable) {\n      if (this._uploadUrl === undefined) {\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.pendingTimeout = setTimeout(() => {\n              this.pendingTimeout = undefined;\n              this._continueUpload();\n            }, this.sleepTime);\n          }\n        }\n      }\n    } else {\n      this._oneShotUpload();\n    }\n  }\n\n  private _resolveToken(\n    callback: (authToken: string | null, appCheckToken: string | null) => void\n  ): void {\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    Promise.all([\n      this._ref.storage._getAuthToken(),\n      this._ref.storage._getAppCheckToken()\n    ]).then(([authToken, appCheckToken]) => {\n      switch (this._state) {\n        case InternalTaskState.RUNNING:\n          callback(authToken, appCheckToken);\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, appCheckToken) => {\n      const requestInfo = createResumableUpload(\n        this._ref.storage,\n        this._ref._location,\n        this._mappings,\n        this._blob,\n        this._metadata\n      );\n      const createRequest = this._ref.storage._makeRequest(\n        requestInfo,\n        newTextConnection,\n        authToken,\n        appCheckToken\n      );\n      this._request = createRequest;\n      createRequest.getPromise().then((url: string) => {\n        this._request = undefined;\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, appCheckToken) => {\n      const requestInfo = getResumableUploadStatus(\n        this._ref.storage,\n        this._ref._location,\n        url,\n        this._blob\n      );\n      const statusRequest = this._ref.storage._makeRequest(\n        requestInfo,\n        newTextConnection,\n        authToken,\n        appCheckToken\n      );\n      this._request = statusRequest;\n      statusRequest.getPromise().then(status => {\n        status = status as ResumableUploadStatus;\n        this._request = undefined;\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 = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n    const status = new 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, appCheckToken) => {\n      let requestInfo;\n      try {\n        requestInfo = continueResumableUpload(\n          this._ref._location,\n          this._ref.storage,\n          url,\n          this._blob,\n          chunkSize,\n          this._mappings,\n          status,\n          this._makeProgressCallback()\n        );\n      } catch (e) {\n        this._error = e as StorageError;\n        this._transition(InternalTaskState.ERROR);\n        return;\n      }\n      const uploadRequest = this._ref.storage._makeRequest(\n        requestInfo,\n        newTextConnection,\n        authToken,\n        appCheckToken,\n        /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.\n      );\n      this._request = uploadRequest;\n      uploadRequest.getPromise().then((newStatus: ResumableUploadStatus) => {\n        this._increaseMultiplier();\n        this._request = undefined;\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 = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n\n    // Max chunk size is 32M.\n    if (currentSize * 2 < 32 * 1024 * 1024) {\n      this._chunkMultiplier *= 2;\n    }\n  }\n\n  private _fetchMetadata(): void {\n    this._resolveToken((authToken, appCheckToken) => {\n      const requestInfo = getMetadata(\n        this._ref.storage,\n        this._ref._location,\n        this._mappings\n      );\n      const metadataRequest = this._ref.storage._makeRequest(\n        requestInfo,\n        newTextConnection,\n        authToken,\n        appCheckToken\n      );\n      this._request = metadataRequest;\n      metadataRequest.getPromise().then(metadata => {\n        this._request = undefined;\n        this._metadata = metadata;\n        this._transition(InternalTaskState.SUCCESS);\n      }, this._metadataErrorHandler);\n    });\n  }\n\n  private _oneShotUpload(): void {\n    this._resolveToken((authToken, appCheckToken) => {\n      const requestInfo = multipartUpload(\n        this._ref.storage,\n        this._ref._location,\n        this._mappings,\n        this._blob,\n        this._metadata\n      );\n      const multipartRequest = this._ref.storage._makeRequest(\n        requestInfo,\n        newTextConnection,\n        authToken,\n        appCheckToken\n      );\n      this._request = multipartRequest;\n      multipartRequest.getPromise().then(metadata => {\n        this._request = undefined;\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      case InternalTaskState.PAUSING:\n        // TODO(andysoto):\n        // assert(this.state_ === InternalTaskState.RUNNING ||\n        //        this.state_ === InternalTaskState.PAUSING);\n        this._state = state;\n        if (this._request !== undefined) {\n          this._request.cancel();\n        } else if (this.pendingTimeout) {\n          clearTimeout(this.pendingTimeout);\n          this.pendingTimeout = undefined;\n          this.completeTransitions_();\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  /**\n   * A snapshot of the current task state.\n   */\n  get snapshot(): UploadTaskSnapshot {\n    const externalState = taskStateFromInternalTaskState(this._state);\n    return {\n      bytesTransferred: this._transferred,\n      totalBytes: this._blob.size(),\n      state: externalState,\n      metadata: this._metadata!,\n      task: this,\n      ref: this._ref\n    };\n  }\n\n  /**\n   * Adds a callback for an event.\n   * @param type - The type of event to listen for.\n   * @param nextOrObserver -\n   *     The `next` function, which gets called for each item in\n   *     the event stream, or an observer object with some or all of these three\n   *     properties (`next`, `error`, `complete`).\n   * @param error - A function that gets called with a `StorageError`\n   *     if the event stream ends due to an error.\n   * @param completed - A function that gets called if the\n   *     event stream ends normally.\n   * @returns\n   *     If only the event argument is passed, returns a function you can use to\n   *     add callbacks (see the examples above). If more than just the event\n   *     argument is passed, returns a function you can call to unregister the\n   *     callbacks.\n   */\n  on(\n    type: TaskEvent,\n    nextOrObserver?:\n      | StorageObserver<UploadTaskSnapshot>\n      | null\n      | ((snapshot: UploadTaskSnapshot) => unknown),\n    error?: ((a: StorageError) => unknown) | null,\n    completed?: CompleteFn | null\n  ): Unsubscribe | Subscribe<UploadTaskSnapshot> {\n    // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.\n    const observer = new Observer(\n      (nextOrObserver as\n        | StorageObserverInternal<UploadTaskSnapshot>\n        | NextFn<UploadTaskSnapshot>) || undefined,\n      error || undefined,\n      completed || undefined\n    );\n    this._addObserver(observer);\n    return () => {\n      this._removeObserver(observer);\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: StorageError) => 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: StorageError) => 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 !== undefined) {\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: StorageError) => void;\n          fbsAsync(toCall.bind(null, this._error as StorageError))();\n          break;\n        default:\n          triggered = false;\n          break;\n      }\n      if (triggered) {\n        this._resolve = undefined;\n        this._reject = undefined;\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(\n            observer.error.bind(observer, this._error as StorageError)\n          )();\n        }\n        break;\n      default:\n        // TODO(andysoto): assert(false);\n        if (observer.error) {\n          fbsAsync(\n            observer.error.bind(observer, this._error as StorageError)\n          )();\n        }\n    }\n  }\n\n  /**\n   * Resumes a paused task. Has no effect on a currently running or failed task.\n   * @returns True if the operation took effect, false if ignored.\n   */\n  resume(): boolean {\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   * @returns True if the operation took effect, false if ignored.\n   */\n  pause(): boolean {\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   * @returns True if the operation took effect, false if ignored.\n   */\n  cancel(): boolean {\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 LLC\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 StorageReference class.\n */\n\nimport { FbsBlob } from './implementation/blob';\nimport { Location } from './implementation/location';\nimport { getMappings } from './implementation/metadata';\nimport { child, lastComponent, parent } from './implementation/path';\nimport {\n  deleteObject as requestsDeleteObject,\n  getBytes,\n  getDownloadUrl as requestsGetDownloadUrl,\n  getMetadata as requestsGetMetadata,\n  list as requestsList,\n  multipartUpload,\n  updateMetadata as requestsUpdateMetadata\n} from './implementation/requests';\nimport { ListOptions, UploadResult } from './public-types';\nimport { dataFromString, StringFormat } from './implementation/string';\nimport { Metadata } from './metadata';\nimport { FirebaseStorageImpl } from './service';\nimport { ListResult } from './list';\nimport { UploadTask } from './task';\nimport { invalidRootOperation, noDownloadURL } from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport {\n  newBlobConnection,\n  newBytesConnection,\n  newStreamConnection,\n  newTextConnection\n} from './platform/connection';\nimport { RequestInfo } from './implementation/requestinfo';\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @internal\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  _location: Location;\n\n  constructor(\n    private _service: FirebaseStorageImpl,\n    location: string | Location\n  ) {\n    if (location instanceof Location) {\n      this._location = location;\n    } else {\n      this._location = Location.makeFromUrl(location, _service.host);\n    }\n  }\n\n  /**\n   * Returns 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    return 'gs://' + this._location.bucket + '/' + this._location.path;\n  }\n\n  protected _newRef(\n    service: FirebaseStorageImpl,\n    location: Location\n  ): Reference {\n    return new Reference(service, location);\n  }\n\n  /**\n   * A reference to the root of this object's bucket.\n   */\n  get root(): Reference {\n    const location = new Location(this._location.bucket, '');\n    return this._newRef(this._service, location);\n  }\n\n  /**\n   * The name of the bucket containing this reference's object.\n   */\n  get bucket(): string {\n    return this._location.bucket;\n  }\n\n  /**\n   * The full path of this object.\n   */\n  get fullPath(): string {\n    return this._location.path;\n  }\n\n  /**\n   * The short name of this object, which is the last component of the full path.\n   * For example, if fullPath is 'full/path/image.png', name is 'image.png'.\n   */\n  get name(): string {\n    return lastComponent(this._location.path);\n  }\n\n  /**\n   * The `StorageService` instance this `StorageReference` is associated with.\n   */\n  get storage(): FirebaseStorageImpl {\n    return this._service;\n  }\n\n  /**\n   * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if\n   * this reference is the root.\n   */\n  get parent(): Reference | null {\n    const newPath = parent(this._location.path);\n    if (newPath === null) {\n      return null;\n    }\n    const location = new Location(this._location.bucket, newPath);\n    return new Reference(this._service, location);\n  }\n\n  /**\n   * Utility function to throw an error in methods that do not accept a root reference.\n   */\n  _throwIfRoot(name: string): void {\n    if (this._location.path === '') {\n      throw invalidRootOperation(name);\n    }\n  }\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded bytes.\n */\nexport function getBytesInternal(\n  ref: Reference,\n  maxDownloadSizeBytes?: number\n): Promise<ArrayBuffer> {\n  ref._throwIfRoot('getBytes');\n  const requestInfo = getBytes(\n    ref.storage,\n    ref._location,\n    maxDownloadSizeBytes\n  );\n  return ref.storage\n    .makeRequestWithTokens(requestInfo, newBytesConnection)\n    .then(bytes =>\n      maxDownloadSizeBytes !== undefined\n        ? // GCS may not honor the Range header for small files\n          (bytes as ArrayBuffer).slice(0, maxDownloadSizeBytes)\n        : (bytes as ArrayBuffer)\n    );\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded blob.\n */\nexport function getBlobInternal(\n  ref: Reference,\n  maxDownloadSizeBytes?: number\n): Promise<Blob> {\n  ref._throwIfRoot('getBlob');\n  const requestInfo = getBytes(\n    ref.storage,\n    ref._location,\n    maxDownloadSizeBytes\n  );\n  return ref.storage\n    .makeRequestWithTokens(requestInfo, newBlobConnection)\n    .then(blob =>\n      maxDownloadSizeBytes !== undefined\n        ? // GCS may not honor the Range header for small files\n          (blob as Blob).slice(0, maxDownloadSizeBytes)\n        : (blob as Blob)\n    );\n}\n\n/** Stream the bytes at the object's location. */\nexport function getStreamInternal(\n  ref: Reference,\n  maxDownloadSizeBytes?: number\n): ReadableStream {\n  ref._throwIfRoot('getStream');\n  const requestInfo: RequestInfo<ReadableStream, ReadableStream> = getBytes(\n    ref.storage,\n    ref._location,\n    maxDownloadSizeBytes\n  );\n\n  // Transforms the stream so that only `maxDownloadSizeBytes` bytes are piped to the result\n  const newMaxSizeTransform = (n: number): Transformer => {\n    let missingBytes = n;\n    return {\n      transform(chunk, controller: TransformStreamDefaultController) {\n        // GCS may not honor the Range header for small files\n        if (chunk.length < missingBytes) {\n          controller.enqueue(chunk);\n          missingBytes -= chunk.length;\n        } else {\n          controller.enqueue(chunk.slice(0, missingBytes));\n          controller.terminate();\n        }\n      }\n    };\n  };\n\n  const result =\n    maxDownloadSizeBytes !== undefined\n      ? new TransformStream(newMaxSizeTransform(maxDownloadSizeBytes))\n      : new TransformStream(); // The default transformer forwards all chunks to its readable side\n\n  ref.storage\n    .makeRequestWithTokens(requestInfo, newStreamConnection)\n    .then(readableStream => readableStream.pipeThrough(result))\n    .catch(err => result.writable.abort(err));\n\n  return result.readable;\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n *\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n  ref: Reference,\n  data: Blob | Uint8Array | ArrayBuffer,\n  metadata?: Metadata\n): Promise<UploadResult> {\n  ref._throwIfRoot('uploadBytes');\n  const requestInfo = multipartUpload(\n    ref.storage,\n    ref._location,\n    getMappings(),\n    new FbsBlob(data, true),\n    metadata\n  );\n  return ref.storage\n    .makeRequestWithTokens(requestInfo, newTextConnection)\n    .then(finalMetadata => {\n      return {\n        metadata: finalMetadata,\n        ref\n      };\n    });\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n  ref: Reference,\n  data: Blob | Uint8Array | ArrayBuffer,\n  metadata?: Metadata\n): UploadTask {\n  ref._throwIfRoot('uploadBytesResumable');\n  return new UploadTask(ref, new FbsBlob(data), metadata);\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - StorageReference where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the newly uploaded string.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n  ref: Reference,\n  value: string,\n  format: StringFormat = StringFormat.RAW,\n  metadata?: Metadata\n): Promise<UploadResult> {\n  ref._throwIfRoot('uploadString');\n  const data = dataFromString(format, value);\n  const metadataClone = { ...metadata } as Metadata;\n  if (metadataClone['contentType'] == null && data.contentType != null) {\n    metadataClone['contentType'] = data.contentType!;\n  }\n  return uploadBytes(ref, data.data, metadataClone);\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 * @public\n * @param ref - StorageReference to get list from.\n *\n * @returns 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 */\nexport function listAll(ref: Reference): Promise<ListResult> {\n  const accumulator: ListResult = {\n    prefixes: [],\n    items: []\n  };\n  return listAllHelper(ref, accumulator).then(() => accumulator);\n}\n\n/**\n * Separated from listAll because async functions can't use \"arguments\".\n * @param ref\n * @param accumulator\n * @param pageToken\n */\nasync function listAllHelper(\n  ref: Reference,\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 list(ref, opt);\n  accumulator.prefixes.push(...nextPage.prefixes);\n  accumulator.items.push(...nextPage.items);\n  if (nextPage.nextPageToken != null) {\n    await listAllHelper(ref, 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 * @public\n *\n * @param ref - StorageReference to get list from.\n * @param options - See ListOptions for details.\n * @returns 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 */\nexport function list(\n  ref: Reference,\n  options?: ListOptions | null\n): Promise<ListResult> {\n  if (options != null) {\n    if (typeof options.maxResults === 'number') {\n      validateNumber(\n        'options.maxResults',\n        /* minValue= */ 1,\n        /* maxValue= */ 1000,\n        options.maxResults\n      );\n    }\n  }\n  const op = options || {};\n  const requestInfo = requestsList(\n    ref.storage,\n    ref._location,\n    /*delimiter= */ '/',\n    op.pageToken,\n    op.maxResults\n  );\n  return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\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 retrieved, the promise is\n * rejected.\n * @public\n * @param ref - StorageReference to get metadata from.\n */\nexport function getMetadata(ref: Reference): Promise<Metadata> {\n  ref._throwIfRoot('getMetadata');\n  const requestInfo = requestsGetMetadata(\n    ref.storage,\n    ref._location,\n    getMappings()\n  );\n  return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - StorageReference to update metadata for.\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 * @returns A `Promise` that resolves\n *     with the new metadata for this object.\n *     See `firebaseStorage.Reference.prototype.getMetadata`\n */\nexport function updateMetadata(\n  ref: Reference,\n  metadata: Partial<Metadata>\n): Promise<Metadata> {\n  ref._throwIfRoot('updateMetadata');\n  const requestInfo = requestsUpdateMetadata(\n    ref.storage,\n    ref._location,\n    metadata,\n    getMappings()\n  );\n  return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns the download URL for the given Reference.\n * @public\n * @returns A `Promise` that resolves with the download\n *     URL for this object.\n */\nexport function getDownloadURL(ref: Reference): Promise<string> {\n  ref._throwIfRoot('getDownloadURL');\n  const requestInfo = requestsGetDownloadUrl(\n    ref.storage,\n    ref._location,\n    getMappings()\n  );\n  return ref.storage\n    .makeRequestWithTokens(requestInfo, newTextConnection)\n    .then(url => {\n      if (url === null) {\n        throw noDownloadURL();\n      }\n      return url;\n    });\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - StorageReference for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: Reference): Promise<void> {\n  ref._throwIfRoot('deleteObject');\n  const requestInfo = requestsDeleteObject(ref.storage, ref._location);\n  return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns reference for object obtained by appending `childPath` to `ref`.\n *\n * @param ref - StorageReference to get child of.\n * @param childPath - Child path from provided ref.\n * @returns A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n *\n */\nexport function _getChild(ref: Reference, childPath: string): Reference {\n  const newPath = child(ref._location.path, childPath);\n  const location = new Location(ref._location.bucket, newPath);\n  return new Reference(ref.storage, location);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\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 { Location } from './implementation/location';\nimport { FailRequest } from './implementation/failrequest';\nimport { Request, makeRequest } from './implementation/request';\nimport { RequestInfo } from './implementation/requestinfo';\nimport { Reference, _getChild } from './reference';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n  FirebaseApp,\n  FirebaseOptions,\n  _isFirebaseServerApp\n} from '@firebase/app';\nimport {\n  CONFIG_STORAGE_BUCKET_KEY,\n  DEFAULT_HOST,\n  DEFAULT_MAX_OPERATION_RETRY_TIME,\n  DEFAULT_MAX_UPLOAD_RETRY_TIME\n} from './implementation/constants';\nimport {\n  invalidArgument,\n  appDeleted,\n  noDefaultBucket\n} from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport { FirebaseStorage } from './public-types';\nimport {\n  createMockUserToken,\n  EmulatorMockTokenOptions,\n  isCloudWorkstation,\n  pingServer\n} from '@firebase/util';\nimport { Connection, ConnectionType } from './implementation/connection';\n\nexport function isUrl(path?: string): boolean {\n  return /^[A-Za-z]+:\\/\\//.test(path as string);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given url.\n */\nfunction refFromURL(service: FirebaseStorageImpl, url: string): Reference {\n  return new Reference(service, url);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\nfunction refFromPath(\n  ref: FirebaseStorageImpl | Reference,\n  path?: string\n): Reference {\n  if (ref instanceof FirebaseStorageImpl) {\n    const service = ref;\n    if (service._bucket == null) {\n      throw noDefaultBucket();\n    }\n    const reference = new Reference(service, service._bucket!);\n    if (path != null) {\n      return refFromPath(reference, path);\n    } else {\n      return reference;\n    }\n  } else {\n    // ref is a Reference\n    if (path !== undefined) {\n      return _getChild(ref, path);\n    } else {\n      return ref;\n    }\n  }\n}\n\n/**\n * Returns a storage Reference for the given url.\n * @param storage - `Storage` instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorageImpl, url?: string): Reference;\n/**\n * Returns a storage Reference for the given path in the\n * default bucket.\n * @param storageOrRef - `Storage` service or storage `Reference`.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if Storage\n * instance provided) or returns same reference (if Reference provided).\n * @public\n */\nexport function ref(\n  storageOrRef: FirebaseStorageImpl | Reference,\n  path?: string\n): Reference;\nexport function ref(\n  serviceOrRef: FirebaseStorageImpl | Reference,\n  pathOrUrl?: string\n): Reference | null {\n  if (pathOrUrl && isUrl(pathOrUrl)) {\n    if (serviceOrRef instanceof FirebaseStorageImpl) {\n      return refFromURL(serviceOrRef, pathOrUrl);\n    } else {\n      throw invalidArgument(\n        'To use ref(service, url), the first argument must be a Storage instance.'\n      );\n    }\n  } else {\n    return refFromPath(serviceOrRef, pathOrUrl);\n  }\n}\n\nfunction extractBucket(\n  host: string,\n  config?: FirebaseOptions\n): Location | null {\n  const bucketString = config?.[CONFIG_STORAGE_BUCKET_KEY];\n  if (bucketString == null) {\n    return null;\n  }\n  return Location.makeFromBucketSpec(bucketString, host);\n}\n\nexport function connectStorageEmulator(\n  storage: FirebaseStorageImpl,\n  host: string,\n  port: number,\n  options: {\n    mockUserToken?: EmulatorMockTokenOptions | string;\n  } = {}\n): void {\n  storage.host = `${host}:${port}`;\n  const useSsl = isCloudWorkstation(host);\n  // Workaround to get cookies in Firebase Studio\n  if (useSsl) {\n    void pingServer(`https://${storage.host}/b`);\n  }\n  storage._isUsingEmulator = true;\n  storage._protocol = useSsl ? 'https' : 'http';\n  const { mockUserToken } = options;\n  if (mockUserToken) {\n    storage._overrideAuthToken =\n      typeof mockUserToken === 'string'\n        ? mockUserToken\n        : createMockUserToken(mockUserToken, storage.app.options.projectId);\n  }\n}\n\n/**\n * A service that provides Firebase Storage Reference instances.\n * @param opt_url - gs:// url to a custom Storage Bucket\n *\n * @internal\n */\nexport class FirebaseStorageImpl implements FirebaseStorage {\n  _bucket: Location | null = null;\n  /**\n   * This string can be in the formats:\n   * - host\n   * - host:port\n   */\n  private _host: string = DEFAULT_HOST;\n  _protocol: string = 'https';\n  protected readonly _appId: string | null = null;\n  private readonly _requests: Set<Request<unknown>>;\n  private _deleted: boolean = false;\n  private _maxOperationRetryTime: number;\n  private _maxUploadRetryTime: number;\n  _overrideAuthToken?: string;\n\n  constructor(\n    /**\n     * FirebaseApp associated with this StorageService instance.\n     */\n    readonly app: FirebaseApp,\n    readonly _authProvider: Provider<FirebaseAuthInternalName>,\n    /**\n     * @internal\n     */\n    readonly _appCheckProvider: Provider<AppCheckInternalComponentName>,\n    /**\n     * @internal\n     */\n    readonly _url?: string,\n    readonly _firebaseVersion?: string,\n    public _isUsingEmulator = false\n  ) {\n    this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;\n    this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;\n    this._requests = new Set();\n    if (_url != null) {\n      this._bucket = Location.makeFromBucketSpec(_url, this._host);\n    } else {\n      this._bucket = extractBucket(this._host, this.app.options);\n    }\n  }\n\n  /**\n   * The host string for this service, in the form of `host` or\n   * `host:port`.\n   */\n  get host(): string {\n    return this._host;\n  }\n\n  set host(host: string) {\n    this._host = host;\n    if (this._url != null) {\n      this._bucket = Location.makeFromBucketSpec(this._url, host);\n    } else {\n      this._bucket = extractBucket(host, this.app.options);\n    }\n  }\n\n  /**\n   * The maximum time to retry uploads in milliseconds.\n   */\n  get maxUploadRetryTime(): number {\n    return this._maxUploadRetryTime;\n  }\n\n  set maxUploadRetryTime(time: number) {\n    validateNumber(\n      'time',\n      /* minValue=*/ 0,\n      /* maxValue= */ Number.POSITIVE_INFINITY,\n      time\n    );\n    this._maxUploadRetryTime = time;\n  }\n\n  /**\n   * The maximum time to retry operations other than uploads or downloads in\n   * milliseconds.\n   */\n  get maxOperationRetryTime(): number {\n    return this._maxOperationRetryTime;\n  }\n\n  set maxOperationRetryTime(time: number) {\n    validateNumber(\n      'time',\n      /* minValue=*/ 0,\n      /* maxValue= */ Number.POSITIVE_INFINITY,\n      time\n    );\n    this._maxOperationRetryTime = time;\n  }\n\n  async _getAuthToken(): Promise<string | null> {\n    if (this._overrideAuthToken) {\n      return this._overrideAuthToken;\n    }\n    const auth = this._authProvider.getImmediate({ optional: true });\n    if (auth) {\n      const tokenData = await auth.getToken();\n      if (tokenData !== null) {\n        return tokenData.accessToken;\n      }\n    }\n    return null;\n  }\n\n  async _getAppCheckToken(): Promise<string | null> {\n    if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {\n      return this.app.settings.appCheckToken;\n    }\n    const appCheck = this._appCheckProvider.getImmediate({ optional: true });\n    if (appCheck) {\n      const result = await appCheck.getToken();\n      // TODO: What do we want to do if there is an error getting the token?\n      // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be\n      // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use\n      // the token (actual or dummy) to send requests.\n      return result.token;\n    }\n    return null;\n  }\n\n  /**\n   * Stop running requests and prevent more from being created.\n   */\n  _delete(): Promise<void> {\n    if (!this._deleted) {\n      this._deleted = true;\n      this._requests.forEach(request => request.cancel());\n      this._requests.clear();\n    }\n    return Promise.resolve();\n  }\n\n  /**\n   * Returns a new firebaseStorage.Reference object referencing this StorageService\n   * at the given Location.\n   */\n  _makeStorageReference(loc: Location): Reference {\n    return new Reference(this, loc);\n  }\n\n  /**\n   * @param requestInfo - HTTP RequestInfo object\n   * @param authToken - Firebase auth token\n   */\n  _makeRequest<I extends ConnectionType, O>(\n    requestInfo: RequestInfo<I, O>,\n    requestFactory: () => Connection<I>,\n    authToken: string | null,\n    appCheckToken: string | null,\n    retry = true\n  ): Request<O> {\n    if (!this._deleted) {\n      const request = makeRequest(\n        requestInfo,\n        this._appId,\n        authToken,\n        appCheckToken,\n        requestFactory,\n        this._firebaseVersion,\n        retry,\n        this._isUsingEmulator\n      );\n      this._requests.add(request);\n      // Request removes itself from set when complete.\n      request.getPromise().then(\n        () => this._requests.delete(request),\n        () => this._requests.delete(request)\n      );\n      return request;\n    } else {\n      return new FailRequest(appDeleted());\n    }\n  }\n\n  async makeRequestWithTokens<I extends ConnectionType, O>(\n    requestInfo: RequestInfo<I, O>,\n    requestFactory: () => Connection<I>\n  ): Promise<O> {\n    const [authToken, appCheckToken] = await Promise.all([\n      this._getAuthToken(),\n      this._getAppCheckToken()\n    ]);\n\n    return this._makeRequest(\n      requestInfo,\n      requestFactory,\n      authToken,\n      appCheckToken\n    ).getPromise();\n  }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\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 { base64urlEncodeWithoutPadding } from './crypt';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n  | 'custom'\n  | 'email'\n  | 'password'\n  | 'phone'\n  | 'anonymous'\n  | 'google.com'\n  | 'facebook.com'\n  | 'github.com'\n  | 'twitter.com'\n  | 'microsoft.com'\n  | 'apple.com';\n\ninterface FirebaseIdToken {\n  // Always set to https://securetoken.google.com/PROJECT_ID\n  iss: string;\n\n  // Always set to PROJECT_ID\n  aud: string;\n\n  // The user's unique ID\n  sub: string;\n\n  // The token issue time, in seconds since epoch\n  iat: number;\n\n  // The token expiry time, normally 'iat' + 3600\n  exp: number;\n\n  // The user's unique ID. Must be equal to 'sub'\n  user_id: string;\n\n  // The time the user authenticated, normally 'iat'\n  auth_time: number;\n\n  // The sign in provider, only set when the provider is 'anonymous'\n  provider_id?: 'anonymous';\n\n  // The user's primary email\n  email?: string;\n\n  // The user's email verification status\n  email_verified?: boolean;\n\n  // The user's primary phone number\n  phone_number?: string;\n\n  // The user's display name\n  name?: string;\n\n  // The user's profile photo URL\n  picture?: string;\n\n  // Information on all identities linked to this user\n  firebase: {\n    // The primary sign-in provider\n    sign_in_provider: FirebaseSignInProvider;\n\n    // A map of providers to the user's list of unique identifiers from\n    // each provider\n    identities?: { [provider in FirebaseSignInProvider]?: string[] };\n  };\n\n  // Custom claims set by the developer\n  [claim: string]: unknown;\n\n  uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n  Partial<FirebaseIdToken>;\n\nexport function createMockUserToken(\n  token: EmulatorMockTokenOptions,\n  projectId?: string\n): string {\n  if (token.uid) {\n    throw new Error(\n      'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n    );\n  }\n  // Unsecured JWTs use \"none\" as the algorithm.\n  const header = {\n    alg: 'none',\n    type: 'JWT'\n  };\n\n  const project = projectId || 'demo-project';\n  const iat = token.iat || 0;\n  const sub = token.sub || token.user_id;\n  if (!sub) {\n    throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n  }\n\n  const payload: FirebaseIdToken = {\n    // Set all required fields to decent defaults\n    iss: `https://securetoken.google.com/${project}`,\n    aud: project,\n    iat,\n    exp: iat + 3600,\n    auth_time: iat,\n    sub,\n    user_id: sub,\n    firebase: {\n      sign_in_provider: 'custom',\n      identities: {}\n    },\n\n    // Override with user options\n    ...token\n  };\n\n  // Unsecured JWTs use the empty string as a signature.\n  const signature = '';\n  return [\n    base64urlEncodeWithoutPadding(JSON.stringify(header)),\n    base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n    signature\n  ].join('.');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\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 * Type constant for Firebase Storage.\n */\nexport const STORAGE_TYPE = 'storage';\n","/**\n * @license\n * Copyright 2020 Google LLC\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 { _getProvider, FirebaseApp, getApp } from '@firebase/app';\n\nimport {\n  ref as refInternal,\n  FirebaseStorageImpl,\n  connectStorageEmulator as connectEmulatorInternal\n} from './service';\nimport { Provider } from '@firebase/component';\n\nimport {\n  StorageReference,\n  FirebaseStorage,\n  UploadResult,\n  ListOptions,\n  ListResult,\n  UploadTask,\n  SettableMetadata,\n  UploadMetadata,\n  FullMetadata\n} from './public-types';\nimport { Metadata as MetadataInternal } from './metadata';\nimport {\n  uploadBytes as uploadBytesInternal,\n  uploadBytesResumable as uploadBytesResumableInternal,\n  uploadString as uploadStringInternal,\n  getMetadata as getMetadataInternal,\n  updateMetadata as updateMetadataInternal,\n  list as listInternal,\n  listAll as listAllInternal,\n  getDownloadURL as getDownloadURLInternal,\n  deleteObject as deleteObjectInternal,\n  Reference,\n  _getChild as _getChildInternal,\n  getBytesInternal\n} from './reference';\nimport { STORAGE_TYPE } from './constants';\nimport {\n  EmulatorMockTokenOptions,\n  getModularInstance,\n  getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\nimport { StringFormat } from './implementation/string';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\nexport { StorageError, StorageErrorCode } from './implementation/error';\n\n/**\n * Public types.\n */\nexport * from './public-types';\n\nexport { Location as _Location } from './implementation/location';\nexport { UploadTask as _UploadTask } from './task';\nexport type { Reference as _Reference } from './reference';\nexport type { FirebaseStorageImpl as _FirebaseStorageImpl } from './service';\nexport { FbsBlob as _FbsBlob } from './implementation/blob';\nexport { dataFromString as _dataFromString } from './implementation/string';\nexport {\n  invalidRootOperation as _invalidRootOperation,\n  invalidArgument as _invalidArgument\n} from './implementation/error';\nexport {\n  TaskEvent as _TaskEvent,\n  TaskState as _TaskState\n} from './implementation/taskenums';\nexport { StringFormat };\n\n/**\n * Downloads the data at the object's location. Returns an error if the object\n * is not found.\n *\n * To use this functionality, you have to whitelist your app's origin in your\n * Cloud Storage bucket. See also\n * https://cloud.google.com/storage/docs/configuring-cors\n *\n * @public\n * @param ref - StorageReference where data should be downloaded.\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\n * retrieve.\n * @returns A Promise containing the object's bytes\n */\nexport function getBytes(\n  ref: StorageReference,\n  maxDownloadSizeBytes?: number\n): Promise<ArrayBuffer> {\n  ref = getModularInstance(ref);\n  return getBytesInternal(ref as Reference, maxDownloadSizeBytes);\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n  ref: StorageReference,\n  data: Blob | Uint8Array | ArrayBuffer,\n  metadata?: UploadMetadata\n): Promise<UploadResult> {\n  ref = getModularInstance(ref);\n  return uploadBytesInternal(\n    ref as Reference,\n    data,\n    metadata as MetadataInternal\n  );\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the string to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n  ref: StorageReference,\n  value: string,\n  format?: StringFormat,\n  metadata?: UploadMetadata\n): Promise<UploadResult> {\n  ref = getModularInstance(ref);\n  return uploadStringInternal(\n    ref as Reference,\n    value,\n    format,\n    metadata as MetadataInternal\n  );\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n  ref: StorageReference,\n  data: Blob | Uint8Array | ArrayBuffer,\n  metadata?: UploadMetadata\n): UploadTask {\n  ref = getModularInstance(ref);\n  return uploadBytesResumableInternal(\n    ref as Reference,\n    data,\n    metadata as MetadataInternal\n  ) as UploadTask;\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 retrieved, the promise is\n * rejected.\n * @public\n * @param ref - {@link StorageReference} to get metadata from.\n */\nexport function getMetadata(ref: StorageReference): Promise<FullMetadata> {\n  ref = getModularInstance(ref);\n  return getMetadataInternal(ref as Reference) as Promise<FullMetadata>;\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - {@link StorageReference} to update metadata for.\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 * @returns A `Promise` that resolves with the new metadata for this object.\n */\nexport function updateMetadata(\n  ref: StorageReference,\n  metadata: SettableMetadata\n): Promise<FullMetadata> {\n  ref = getModularInstance(ref);\n  return updateMetadataInternal(\n    ref as Reference,\n    metadata as Partial<MetadataInternal>\n  ) as Promise<FullMetadata>;\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 * @public\n *\n * @param ref - {@link StorageReference} to get list from.\n * @param options - See {@link ListOptions} for details.\n * @returns 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 */\nexport function list(\n  ref: StorageReference,\n  options?: ListOptions\n): Promise<ListResult> {\n  ref = getModularInstance(ref);\n  return listInternal(ref as Reference, options);\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 * @public\n * @param ref - {@link StorageReference} to get list from.\n *\n * @returns 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 */\nexport function listAll(ref: StorageReference): Promise<ListResult> {\n  ref = getModularInstance(ref);\n  return listAllInternal(ref as Reference);\n}\n\n/**\n * Returns the download URL for the given {@link StorageReference}.\n * @public\n * @param ref - {@link StorageReference} to get the download URL for.\n * @returns A `Promise` that resolves with the download\n *     URL for this object.\n */\nexport function getDownloadURL(ref: StorageReference): Promise<string> {\n  ref = getModularInstance(ref);\n  return getDownloadURLInternal(ref as Reference);\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - {@link StorageReference} for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: StorageReference): Promise<void> {\n  ref = getModularInstance(ref);\n  return deleteObjectInternal(ref as Reference);\n}\n\n/**\n * Returns a {@link StorageReference} for the given url.\n * @param storage - {@link FirebaseStorage} instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorage, url?: string): StorageReference;\n/**\n * Returns a {@link StorageReference} for the given path in the\n * default bucket.\n * @param storageOrRef - {@link FirebaseStorage} or {@link StorageReference}.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if {@link FirebaseStorage}\n * instance provided) or returns same reference (if {@link StorageReference} provided).\n * @public\n */\nexport function ref(\n  storageOrRef: FirebaseStorage | StorageReference,\n  path?: string\n): StorageReference;\nexport function ref(\n  serviceOrRef: FirebaseStorage | StorageReference,\n  pathOrUrl?: string\n): StorageReference | null {\n  serviceOrRef = getModularInstance(serviceOrRef);\n  return refInternal(\n    serviceOrRef as FirebaseStorageImpl | Reference,\n    pathOrUrl\n  );\n}\n\n/**\n * @internal\n */\nexport function _getChild(ref: StorageReference, childPath: string): Reference {\n  return _getChildInternal(ref as Reference, childPath);\n}\n\n/**\n * Gets a {@link FirebaseStorage} instance for the given Firebase app.\n * @public\n * @param app - Firebase app to get {@link FirebaseStorage} instance for.\n * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.\n * If not passed, uses the app's default Storage Bucket.\n * @returns A {@link FirebaseStorage} instance.\n */\nexport function getStorage(\n  app: FirebaseApp = getApp(),\n  bucketUrl?: string\n): FirebaseStorage {\n  app = getModularInstance(app);\n  const storageProvider: Provider<'storage'> = _getProvider(app, STORAGE_TYPE);\n  const storageInstance = storageProvider.getImmediate({\n    identifier: bucketUrl\n  });\n  const emulator = getDefaultEmulatorHostnameAndPort('storage');\n  if (emulator) {\n    connectStorageEmulator(storageInstance, ...emulator);\n  }\n  return storageInstance;\n}\n\n/**\n * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.\n *\n * @param storage - The {@link FirebaseStorage} instance\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 5001)\n * @param options - Emulator options. `options.mockUserToken` is the mock auth\n * token to use for unit testing Security Rules.\n * @public\n */\nexport function connectStorageEmulator(\n  storage: FirebaseStorage,\n  host: string,\n  port: number,\n  options: {\n    mockUserToken?: EmulatorMockTokenOptions | string;\n  } = {}\n): void {\n  connectEmulatorInternal(storage as FirebaseStorageImpl, host, port, options);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\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 { StorageReference } from './public-types';\nimport { Reference, getBlobInternal } from './reference';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Downloads the data at the object's location. Returns an error if the object\n * is not found.\n *\n * To use this functionality, you have to whitelist your app's origin in your\n * Cloud Storage bucket. See also\n * https://cloud.google.com/storage/docs/configuring-cors\n *\n * This API is not available in Node.\n *\n * @public\n * @param ref - StorageReference where data should be downloaded.\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\n * retrieve.\n * @returns A Promise that resolves with a Blob containing the object's bytes\n */\nexport function getBlob(\n  ref: StorageReference,\n  maxDownloadSizeBytes?: number\n): Promise<Blob> {\n  ref = getModularInstance(ref);\n  return getBlobInternal(ref as Reference, maxDownloadSizeBytes);\n}\n\n/**\n * Downloads the data at the object's location. Raises an error event if the\n * object is not found.\n *\n * This API is only available in Node.\n *\n * @public\n * @param ref - StorageReference where data should be downloaded.\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\n * retrieve.\n * @returns A stream with the object's data as bytes\n */\nexport function getStream(\n  ref: StorageReference,\n  maxDownloadSizeBytes?: number\n): ReadableStream {\n  throw new Error('getStream() is only supported by NodeJS builds');\n}\n","/**\n * Cloud Storage for Firebase\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\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// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n  _registerComponent,\n  registerVersion,\n  SDK_VERSION\n} from '@firebase/app';\n\nimport { FirebaseStorageImpl } from '../src/service';\nimport {\n  Component,\n  ComponentType,\n  ComponentContainer,\n  InstanceFactoryOptions\n} from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\nimport { FirebaseStorage } from './public-types';\nimport { STORAGE_TYPE } from './constants';\n\nexport * from './api';\nexport * from './api.browser';\n\nfunction factory(\n  container: ComponentContainer,\n  { instanceIdentifier: url }: InstanceFactoryOptions\n): FirebaseStorage {\n  const app = container.getProvider('app').getImmediate();\n  const authProvider = container.getProvider('auth-internal');\n  const appCheckProvider = container.getProvider('app-check-internal');\n\n  return new FirebaseStorageImpl(\n    app,\n    authProvider,\n    appCheckProvider,\n    url,\n    SDK_VERSION\n  );\n}\n\nfunction registerStorage(): void {\n  _registerComponent(\n    new Component(\n      STORAGE_TYPE,\n      factory,\n      ComponentType.PUBLIC\n    ).setMultipleInstances(true)\n  );\n  //RUNTIME_ENV will be replaced during the compilation to \"node\" for nodejs and an empty string for browser\n  registerVersion(name, version, '__RUNTIME_ENV__');\n  // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n  registerVersion(name, version, '__BUILD_TARGET__');\n}\n\nregisterStorage();\n"],"names":["stringToByteArray","str","out","p","i","length","c","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","push","join","encodeString","btoa","decodeString","bytes","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","replace","getDefaultsFromGlobal","getGlobal","self","window","global","__FIREBASE_DEFAULTS__","getDefaultsFromCookie","document","match","cookie","e","decoded","console","error","base64Decode","JSON","parse","getDefaults","process","env","defaultsJsonString","getDefaultsFromEnvVariable","info","getDefaultEmulatorHostnameAndPort","productName","host","emulatorHosts","getDefaultEmulatorHost","separatorIndex","lastIndexOf","port","parseInt","substring","FirebaseError","code","message","customData","super","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","PATTERN","_","key","value","fullMessage","getModularInstance","_delegate","isCloudWorkstation","url","startsWith","URL","hostname","endsWith","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","StorageError","status_","prependCode","serverResponse","_baseMessage","status","_codeEquals","StorageErrorCode","ErrorCode","unknown","UNKNOWN","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","canceled","CANCELED","cannotSliceBlob","CANNOT_SLICE_BLOB","invalidArgument","INVALID_ARGUMENT","appDeleted","APP_DELETED","invalidRootOperation","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","Location","bucket","path","path_","isRoot","fullServerUrl","encode","encodeURIComponent","bucketOnlyServerUrl","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","invalidDefaultBucket","INVALID_DEFAULT_BUCKET","location","bucketDomain","gsRegex","RegExp","httpModify","loc","decodeURIComponent","firebaseStorageHost","groups","regex","indices","postModify","gsModify","slice","group","captures","exec","bucketValue","pathValue","invalidUrl","INVALID_URL","FailRequest","promise_","Promise","reject","getPromise","cancel","_appDelete","isString","isNativeBlob","isNativeBlobDefined","Blob","validateNumber","argument","minValue","maxValue","makeUrl","urlPart","protocol","origin","makeQueryString","params","queryPart","hasOwnProperty","isRetryStatusCode","additionalRetryCodes","isFiveHundredCode","isExtraRetryCode","indexOf","isAdditionalRetryCode","NetworkRequest","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","timeout_","progressCallback_","connectionFactory_","retry","isUsingEmulator","pendingConnection_","backoffId_","canceled_","appDelete_","resolve","resolve_","reject_","start_","doTheRequest","backoffCallback","RequestEndStatus","connection","progressListener","progressEvent","loaded","total","lengthComputable","addUploadProgressListener","send","then","removeUploadProgressListener","hitServer","getErrorCode","NO_ERROR","getStatus","wasCanceled","ABORT","successCode","backoffDone","requestWentThrough","wasSuccessCode","result","getResponse","isJustDef","err","getErrorText","start","doRequest","backoffCompleteCb","timeout","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","args","apply","callWithDelay","millis","setTimeout","responseHandler","clearGlobalTimeout","clearTimeout","success","call","waitMillis","Math","random","stopped","stop","wasTimeout","appDelete","id","abort","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob","undefined","bb","append","UNSUPPORTED_ENVIRONMENT","decodeBase64","encoded","missingPolyFill","polyFill","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","StringData","contentType","dataFromString","stringData","utf8Bytes_","base64Bytes_","dataURLBytes_","dataUrl","parts","DataURLParts","rest","percentEncodedBytes_","dataURLContentType_","b","Uint8Array","hasMinus","hasUnder","hasPlus","hasSlash","includes","array","dataURL","matches","middle","s","end","FbsBlob","elideCopy","size","blobType","data_","ArrayBuffer","byteLength","set","size_","type_","startByte","endByte","sliced","sliceBlob","blob","webkitSlice","mozSlice","buffer","blobby","map","val","uint8Arrays","finalLength","forEach","merged","index","uploadData","jsonObjectOrNull","obj","isNonArrayObject","lastComponent","noXform_","metadata","Mapping","server","local","writable","xform","mappings_","getMappings","mappings","nameMapping","mappingsXformPath","_metadata","fullPath","xformPath","sizeMapping","xformSize","Number","fromResource","resource","len","mapping","addRef","defineProperty","get","generateRef","_makeStorageReference","fromResourceString","resourceString","toResourceString","stringify","PREFIXES_KEY","ITEMS_KEY","fromResponseString","fromBackendResponse","listResult","prefixes","items","nextPageToken","pathWithoutTrailingSlash","reference","item","RequestInfo","method","handler","urlParams","headers","body","errorHandler","progressCallback","successCodes","handlerCheck","cndn","metadataHandler","xhr","text","downloadUrlHandler","downloadUrlFromResourceString","tokens","split","token","alt","_protocol","sharedErrorHandler","newErr","unauthorizedApp","UNAUTHORIZED_APP","unauthenticated","UNAUTHENTICATED","quotaExceeded","QUOTA_EXCEEDED","unauthorized","UNAUTHORIZED","objectErrorHandler","shared","objectNotFound","OBJECT_NOT_FOUND","getMetadata","maxOperationRetryTime","requestInfo","list","delimiter","pageToken","maxResults","listHandler","getBytes","maxDownloadSizeBytes","metadataForUpload_","metadataClone","assign","determineContentType_","multipartUpload","boundary","genBoundary","toString","metadata_","preBlobPart","postBlobPart","maxUploadRetryTime","ResumableUploadStatus","current","finalized","checkResumeHeader_","allowed","getResponseHeader","RESUMABLE_UPLOAD_CHUNK_SIZE","continueResumableUpload","chunkSize","serverFileWrongSize","SERVER_FILE_WRONG_SIZE","bytesLeft","bytesToUpload","min","uploadCommand","uploadStatus","newCurrent","TaskEvent","STATE_CHANGED","TaskState","RUNNING","PAUSED","SUCCESS","ERROR","taskStateFromInternalTaskState","state","Observer","nextOrObserver","complete","isFunction","next","observer","async","f","argsToForward","XhrConnection","sent_","xhr_","XMLHttpRequest","initXhr","errorCode_","sendPromise_","addEventListener","NETWORK_ERROR","withCredentials","open","setRequestHeader","response","statusText","header","listener","upload","removeEventListener","XhrTextConnection","responseType","newTextConnection","XhrBytesConnection","newBytesConnection","XhrBlobConnection","newBlobConnection","UploadTask","isExponentialBackoffExpired","sleepTime","maxSleepTime","ref","_transferred","_needToFetchStatus","_needToFetchMetadata","_observers","_error","_uploadUrl","_request","_chunkMultiplier","_resolve","_reject","_ref","_blob","_mappings","_resumable","_shouldDoResumable","_state","_errorHandler","completeTransitions_","backoffExpired","max","_transition","_metadataErrorHandler","storage","_promise","_start","_makeProgressCallback","sizeBefore","_updateProgress","_createResumable","_fetchStatus","_fetchMetadata","pendingTimeout","_continueUpload","_oneShotUpload","_resolveToken","all","_getAuthToken","_getAppCheckToken","authToken","appCheckToken","createResumableUpload","metadataForUpload","_location","createRequest","_makeRequest","getResumableUploadStatus","sizeString","isNaN","statusRequest","uploadRequest","newStatus","_increaseMultiplier","metadataRequest","multipartRequest","transferred","old","_notifyObservers","wasPaused","snapshot","externalState","bytesTransferred","totalBytes","task","on","completed","_addObserver","_removeObserver","onFulfilled","onRejected","_notifyObserver","splice","_finishPromise","triggered","fbsAsync","bind","resume","valid","pause","Reference","_service","_newRef","root","parent","newPath","_throwIfRoot","uploadBytes","makeRequestWithTokens","finalMetadata","listAll","accumulator","listAllHelper","opt","nextPage","options","op","requestsList","updateMetadata","requestsUpdateMetadata","getDownloadURL","getDownloadUrl","requestsGetDownloadUrl","noDownloadURL","NO_DOWNLOAD_URL","deleteObject","_xhr","_text","requestsDeleteObject","_getChild","childPath","child","canonicalChildPath","filter","component","refFromPath","FirebaseStorageImpl","_bucket","noDefaultBucket","NO_DEFAULT_BUCKET","serviceOrRef","pathOrUrl","isUrl","test","refFromURL","extractBucket","config","connectStorageEmulator","useSsl","pingServer","endpoint","fetch","credentials","ok","_isUsingEmulator","mockUserToken","_overrideAuthToken","createMockUserToken","projectId","uid","project","iat","sub","user_id","payload","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","alg","app","_authProvider","_appCheckProvider","_url","_firebaseVersion","_host","_appId","_deleted","_maxOperationRetryTime","_maxUploadRetryTime","_requests","Set","time","POSITIVE_INFINITY","auth","getImmediate","optional","tokenData","getToken","accessToken","_isFirebaseServerApp","settings","appCheck","_delete","request","clear","requestFactory","makeRequest","appId","firebaseVersion","addGmpidHeader_","addAuthHeader_","addVersionHeader_","addAppCheckHeader_","add","delete","STORAGE_TYPE","getBytesInternal","uploadBytesInternal","uploadString","uploadStringInternal","uploadBytesResumable","uploadBytesResumableInternal","requestsGetMetadata","getMetadataInternal","updateMetadataInternal","listInternal","listAllInternal","getDownloadURLInternal","deleteObjectInternal","refInternal","_getChildInternal","getStorage","getApp","bucketUrl","storageInstance","_getProvider","identifier","emulator","connectEmulatorInternal","getBlobInternal","getStream","factory","container","instanceIdentifier","getProvider","authProvider","appCheckProvider","SDK_VERSION","registerStorage","_registerComponent","registerVersion","version"],"mappings":"4IAiBA,MCAMA,oBAAoB,SAAUC,GAElC,MAAMC,EAAgB,GACtB,IAAIC,EAAI,EACR,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAAII,OAAQD,IAAK,CACnC,IAAIE,EAAIL,EAAIM,WAAWH,GACnBE,EAAI,IACNJ,EAAIC,KAAOG,EACFA,EAAI,MACbJ,EAAIC,KAAQG,GAAK,EAAK,IACtBJ,EAAIC,KAAY,GAAJG,EAAU,KAEL,QAAZ,MAAJA,IACDF,EAAI,EAAIH,EAAII,QACyB,QAAZ,MAAxBJ,EAAIM,WAAWH,EAAI,KAGpBE,EAAI,QAAgB,KAAJA,IAAe,KAA6B,KAAtBL,EAAIM,aAAaH,IACvDF,EAAIC,KAAQG,GAAK,GAAM,IACvBJ,EAAIC,KAASG,GAAK,GAAM,GAAM,IAC9BJ,EAAIC,KAASG,GAAK,EAAK,GAAM,IAC7BJ,EAAIC,KAAY,GAAJG,EAAU,MAEtBJ,EAAIC,KAAQG,GAAK,GAAM,IACvBJ,EAAIC,KAASG,GAAK,EAAK,GAAM,IAC7BJ,EAAIC,KAAY,GAAJG,EAAU,IAEzB,CACD,OAAOJ,CACT,EA6DaM,EAAiB,CAI5BC,eAAgB,KAKhBC,eAAgB,KAMhBC,sBAAuB,KAMvBC,sBAAuB,KAMvBC,kBACE,iEAKF,gBAAIC,GACF,OAAOC,KAAKF,kBAAoB,KACjC,EAKD,wBAAIG,GACF,OAAOD,KAAKF,kBAAoB,KACjC,EASDI,mBAAoC,mBAATC,KAW3B,eAAAC,CAAgBC,EAA8BC,GAC5C,IAAKC,MAAMC,QAAQH,GACjB,MAAMI,MAAM,iDAGdT,KAAKU,QAEL,MAAMC,EAAgBL,EAClBN,KAAKJ,sBACLI,KAAKN,eAE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