@fleox-agent-crm/agentcrm 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +143 -0
  2. package/README.md +223 -2
  3. package/changelog.json +76 -0
  4. package/dist/admin/admin-files.json +26 -0
  5. package/dist/admin/assets/chartsImpl-B45AAqnr.js +91 -0
  6. package/dist/admin/assets/firebase-C1x_l9P9.js +2 -0
  7. package/dist/admin/assets/gitJson-CAUSxl8d.js +3 -0
  8. package/dist/admin/assets/index-ChFauO8y.js +1181 -0
  9. package/dist/admin/assets/index-TcjySLVg.css +1 -0
  10. package/dist/admin/assets/index.esm-BFc7vwnl.js +400 -0
  11. package/dist/admin/assets/index.esm-CtEQZRb1.js +1651 -0
  12. package/dist/admin/assets/index.esm-Dum0J07z.js +16 -0
  13. package/dist/admin/assets/index.esm2017-EOzKbpUS.js +390 -0
  14. package/dist/admin/assets/lucide-react.min--rznIkmQ.js +6 -0
  15. package/dist/admin/assets/sdk-DgzLACmL.js +1717 -0
  16. package/dist/admin/config.js +3 -0
  17. package/dist/admin/favicon.svg +1 -0
  18. package/dist/admin/index.html +139 -0
  19. package/dist/admin/runtime/agentcrm-runtime.js +104 -0
  20. package/dist/admin/runtime/lucide-react.js +791 -0
  21. package/dist/admin/runtime/react-dom-client.js +17 -0
  22. package/dist/admin/runtime/react-dom.js +20 -0
  23. package/dist/admin/runtime/react-i18next.js +19 -0
  24. package/dist/admin/runtime/react-jsx-runtime.js +17 -0
  25. package/dist/admin/runtime/react.js +22 -0
  26. package/dist/agent/agentcrm.mjs +4057 -0
  27. package/dist/agent/chunks/_commonjsHelpers-ClciMIcB.mjs +14 -0
  28. package/dist/agent/chunks/activities-Cj_SIOay.mjs +227 -0
  29. package/dist/agent/chunks/api-Cz0Ubj-B.mjs +98 -0
  30. package/dist/agent/chunks/appearance-BloHbiLA.mjs +174 -0
  31. package/dist/agent/chunks/automations-DwWruxmu.mjs +698 -0
  32. package/dist/agent/chunks/backup-W3CjgkAJ.mjs +116 -0
  33. package/dist/agent/chunks/batch-CVETiJj5.mjs +142 -0
  34. package/dist/agent/chunks/compact-BGHI92tm.mjs +69 -0
  35. package/dist/agent/chunks/context-CxFfqS4D.mjs +65 -0
  36. package/dist/agent/chunks/core-Dy7vY9H6.mjs +255 -0
  37. package/dist/agent/chunks/dedupe-BepmsaHv.mjs +123 -0
  38. package/dist/agent/chunks/encoding-C9MzdP95.mjs +36 -0
  39. package/dist/agent/chunks/exportCsv-C6e6XEmB.mjs +130 -0
  40. package/dist/agent/chunks/extCheck-GgHG1dYB.mjs +200 -0
  41. package/dist/agent/chunks/extPackage-DuZ6GZhp.mjs +115 -0
  42. package/dist/agent/chunks/extScaffold-Aqyjf1nr.mjs +320 -0
  43. package/dist/agent/chunks/extensionActions-D2HtpQz4.mjs +48 -0
  44. package/dist/agent/chunks/extensions-Bp72uZ9a.mjs +164 -0
  45. package/dist/agent/chunks/featureRegistry-DSsZbhrh.mjs +149 -0
  46. package/dist/agent/chunks/fields-B0bitgmr.mjs +476 -0
  47. package/dist/agent/chunks/files-CjsPJSR6.mjs +158 -0
  48. package/dist/agent/chunks/files-D1daDgY0.mjs +367 -0
  49. package/dist/agent/chunks/firebase-DxGVQV9E.mjs +454 -0
  50. package/dist/agent/chunks/firebaseRules-iori-s7U.mjs +221 -0
  51. package/dist/agent/chunks/forms-BfuWaQjA.mjs +847 -0
  52. package/dist/agent/chunks/gitJson-fjr8mcHe.mjs +528 -0
  53. package/dist/agent/chunks/hosting-Bme7LxPc.mjs +144 -0
  54. package/dist/agent/chunks/http-Bk9ICb7I.mjs +127 -0
  55. package/dist/agent/chunks/ids-CvnmrMJX.mjs +59 -0
  56. package/dist/agent/chunks/ids-u-noYcy5.mjs +14 -0
  57. package/dist/agent/chunks/importCsv-LVmMTaWU.mjs +334 -0
  58. package/dist/agent/chunks/index-B-4W0-P4.mjs +535 -0
  59. package/dist/agent/chunks/index-BM8qeGOb.mjs +2489 -0
  60. package/dist/agent/chunks/index-Bnmav-Oh.mjs +311 -0
  61. package/dist/agent/chunks/index-CRkw3_iF.mjs +147 -0
  62. package/dist/agent/chunks/index-CWrrF1wl.mjs +111 -0
  63. package/dist/agent/chunks/index-DUSdTBkz.mjs +2988 -0
  64. package/dist/agent/chunks/index-RCmo-uld.mjs +26 -0
  65. package/dist/agent/chunks/index-w03ReRs4.mjs +9780 -0
  66. package/dist/agent/chunks/install-CbpD_7gd.mjs +188 -0
  67. package/dist/agent/chunks/jsx-runtime-Ca2uwGDr.mjs +76 -0
  68. package/dist/agent/chunks/loader-MPD9iAvh.mjs +184 -0
  69. package/dist/agent/chunks/lucide-react.min-Bt3gtepY.mjs +64 -0
  70. package/dist/agent/chunks/memory-WNR3VHUJ.mjs +56 -0
  71. package/dist/agent/chunks/migrate-CsClnnN8.mjs +182 -0
  72. package/dist/agent/chunks/modules-clWdE-K2.mjs +202 -0
  73. package/dist/agent/chunks/nodeImport-ylfRDvqt.mjs +38 -0
  74. package/dist/agent/chunks/package-B7mI6HGi.mjs +194 -0
  75. package/dist/agent/chunks/papaparse-Df7i1dHr.mjs +1309 -0
  76. package/dist/agent/chunks/pipelines-BAKpPk1w.mjs +234 -0
  77. package/dist/agent/chunks/plan-BmTat6-T.mjs +254 -0
  78. package/dist/agent/chunks/pluginRegistry-DyHtlkcr.mjs +83 -0
  79. package/dist/agent/chunks/query-C5nJB_3C.mjs +192 -0
  80. package/dist/agent/chunks/records-DcHFelq5.mjs +2195 -0
  81. package/dist/agent/chunks/registry-COfJrSmg.mjs +182 -0
  82. package/dist/agent/chunks/registry-DijAKZ24.mjs +431 -0
  83. package/dist/agent/chunks/relations-B9TynBmA.mjs +191 -0
  84. package/dist/agent/chunks/reports-BACHGccj.mjs +189 -0
  85. package/dist/agent/chunks/runtime-C0Xf0Axi.mjs +14873 -0
  86. package/dist/agent/chunks/runtimeConfig-CCOFg1RM.mjs +250 -0
  87. package/dist/agent/chunks/s3-Dz50-NuA.mjs +903 -0
  88. package/dist/agent/chunks/schema-C4lSslXv.mjs +373 -0
  89. package/dist/agent/chunks/schema-DnLj8dUO.mjs +213 -0
  90. package/dist/agent/chunks/sdk-whvfg786.mjs +43644 -0
  91. package/dist/agent/chunks/seed-6MRmQQBR.mjs +541 -0
  92. package/dist/agent/chunks/server-DC3t8r30.mjs +242 -0
  93. package/dist/agent/chunks/settings-Di8nzNEL.mjs +111 -0
  94. package/dist/agent/chunks/standardObjects-CheqfDqa.mjs +243 -0
  95. package/dist/agent/chunks/stats-BfuLWhVV.mjs +51 -0
  96. package/dist/agent/chunks/store-5gqRSKXg.mjs +122 -0
  97. package/dist/agent/chunks/themes-DPZFv3yc.mjs +43 -0
  98. package/dist/agent/chunks/tools-iSH-yMpl.mjs +884 -0
  99. package/dist/agent/chunks/types-BOy9PUl7.mjs +44 -0
  100. package/dist/agent/chunks/users-DI1BvS0f.mjs +107 -0
  101. package/dist/agent/chunks/utils-DmI8FtXP.mjs +83 -0
  102. package/dist/agent/chunks/views-DH1n9Lrt.mjs +109 -0
  103. package/dist/version.json +7 -0
  104. package/package.json +97 -4
  105. package/plugin/.claude-plugin/plugin.json +17 -0
  106. package/plugin/skills/agentcrm-admin/SKILL.md +191 -0
  107. package/plugin/skills/agentcrm-admin/references/appearance.md +26 -0
  108. package/plugin/skills/agentcrm-admin/references/import.md +16 -0
  109. package/plugin/skills/agentcrm-admin/references/records.md +30 -0
  110. package/plugin/skills/agentcrm-admin/references/schema.md +59 -0
  111. package/plugin/skills/agentcrm-extensions/SKILL.md +93 -0
  112. package/plugin/skills/agentcrm-extensions/references/module-recipes.md +213 -0
  113. package/plugin/skills/agentcrm-extensions/references/runtime-api.md +41 -0
  114. package/plugin/skills/agentcrm-extensions/references/testing.md +78 -0
  115. package/plugin/skills/agentcrm-extensions/references/theme-recipes.md +65 -0
  116. package/plugin/skills/agentcrm-install/SKILL.md +116 -0
  117. package/plugin/skills/agentcrm-install/references/firebase.md +18 -0
  118. package/plugin/skills/agentcrm-install/references/github.md +20 -0
  119. package/plugin/skills/agentcrm-install/references/mcp.md +17 -0
  120. package/plugin/skills/agentcrm-install/references/plans.md +45 -0
  121. package/plugin/skills/agentcrm-install/references/s3.md +24 -0
  122. package/plugin/skills/agentcrm-manage/SKILL.md +108 -0
  123. package/plugin/skills/agentcrm-manage/references/cron.md +11 -0
  124. package/plugin/skills/agentcrm-manage/references/doctor.md +18 -0
  125. package/plugin/skills/agentcrm-sales/SKILL.md +92 -0
  126. package/plugin/skills/agentcrm-sales/references/enrichment.md +13 -0
  127. package/plugin/skills/agentcrm-sales/references/playbooks.md +29 -0
  128. package/plugin/skills/agentcrm-sales/references/weekly-report.md +27 -0
  129. package/types/agentcrm-runtime.d.ts +894 -0
@@ -0,0 +1,2988 @@
1
+ import { createRequire as __acrmRequire } from "node:module";
2
+ import { fileURLToPath as __acrmPath } from "node:url";
3
+ import { dirname as __acrmDirname } from "node:path";
4
+ const require2 = __acrmRequire(import.meta.url);
5
+ const __filename = __acrmPath(import.meta.url);
6
+ const __dirname = __acrmDirname(__filename);
7
+ import { F as FirebaseError, g as getModularInstance, _ as _getProvider, a as getDefaultEmulatorHostnameAndPort, b as getApp, i as isCloudWorkstation, p as pingServer, u as updateEmulatorBanner, c as createMockUserToken, d as _isFirebaseServerApp, e as _registerComponent, C as Component, r as registerVersion, S as SDK_VERSION } from "./sdk-whvfg786.mjs";
8
+ import "util";
9
+ import "crypto";
10
+ import "process";
11
+ import "tls";
12
+ import "fs";
13
+ import "os";
14
+ import "net";
15
+ import "events";
16
+ import "stream";
17
+ import "./_commonjsHelpers-ClciMIcB.mjs";
18
+ import "path";
19
+ import "http2";
20
+ import "http";
21
+ import "url";
22
+ import "dns";
23
+ import "zlib";
24
+ import "./firebase-DxGVQV9E.mjs";
25
+ import "./jsx-runtime-Ca2uwGDr.mjs";
26
+ import "./index-Bnmav-Oh.mjs";
27
+ import "./core-Dy7vY9H6.mjs";
28
+ import "./types-BOy9PUl7.mjs";
29
+ import "./index-RCmo-uld.mjs";
30
+ import "./ids-u-noYcy5.mjs";
31
+ /**
32
+ * @license
33
+ * Copyright 2017 Google LLC
34
+ *
35
+ * Licensed under the Apache License, Version 2.0 (the "License");
36
+ * you may not use this file except in compliance with the License.
37
+ * You may obtain a copy of the License at
38
+ *
39
+ * http://www.apache.org/licenses/LICENSE-2.0
40
+ *
41
+ * Unless required by applicable law or agreed to in writing, software
42
+ * distributed under the License is distributed on an "AS IS" BASIS,
43
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
44
+ * See the License for the specific language governing permissions and
45
+ * limitations under the License.
46
+ */
47
+ const DEFAULT_HOST = "firebasestorage.googleapis.com";
48
+ const CONFIG_STORAGE_BUCKET_KEY = "storageBucket";
49
+ const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1e3;
50
+ const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1e3;
51
+ const DEFAULT_MIN_SLEEP_TIME_MILLIS = 1e3;
52
+ /**
53
+ * @license
54
+ * Copyright 2017 Google LLC
55
+ *
56
+ * Licensed under the Apache License, Version 2.0 (the "License");
57
+ * you may not use this file except in compliance with the License.
58
+ * You may obtain a copy of the License at
59
+ *
60
+ * http://www.apache.org/licenses/LICENSE-2.0
61
+ *
62
+ * Unless required by applicable law or agreed to in writing, software
63
+ * distributed under the License is distributed on an "AS IS" BASIS,
64
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
65
+ * See the License for the specific language governing permissions and
66
+ * limitations under the License.
67
+ */
68
+ class StorageError extends FirebaseError {
69
+ /**
70
+ * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and
71
+ * added to the end of the message.
72
+ * @param message - Error message.
73
+ * @param status_ - Corresponding HTTP Status Code
74
+ */
75
+ constructor(code, message, status_ = 0) {
76
+ super(prependCode(code), `Firebase Storage: ${message} (${prependCode(code)})`);
77
+ this.status_ = status_;
78
+ this.customData = { serverResponse: null };
79
+ this._baseMessage = this.message;
80
+ Object.setPrototypeOf(this, StorageError.prototype);
81
+ }
82
+ get status() {
83
+ return this.status_;
84
+ }
85
+ set status(status) {
86
+ this.status_ = status;
87
+ }
88
+ /**
89
+ * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.
90
+ */
91
+ _codeEquals(code) {
92
+ return prependCode(code) === this.code;
93
+ }
94
+ /**
95
+ * Optional response message that was added by the server.
96
+ */
97
+ get serverResponse() {
98
+ return this.customData.serverResponse;
99
+ }
100
+ set serverResponse(serverResponse) {
101
+ this.customData.serverResponse = serverResponse;
102
+ if (this.customData.serverResponse) {
103
+ this.message = `${this._baseMessage}
104
+ ${this.customData.serverResponse}`;
105
+ } else {
106
+ this.message = this._baseMessage;
107
+ }
108
+ }
109
+ }
110
+ var StorageErrorCode;
111
+ (function(StorageErrorCode2) {
112
+ StorageErrorCode2["UNKNOWN"] = "unknown";
113
+ StorageErrorCode2["OBJECT_NOT_FOUND"] = "object-not-found";
114
+ StorageErrorCode2["BUCKET_NOT_FOUND"] = "bucket-not-found";
115
+ StorageErrorCode2["PROJECT_NOT_FOUND"] = "project-not-found";
116
+ StorageErrorCode2["QUOTA_EXCEEDED"] = "quota-exceeded";
117
+ StorageErrorCode2["UNAUTHENTICATED"] = "unauthenticated";
118
+ StorageErrorCode2["UNAUTHORIZED"] = "unauthorized";
119
+ StorageErrorCode2["UNAUTHORIZED_APP"] = "unauthorized-app";
120
+ StorageErrorCode2["RETRY_LIMIT_EXCEEDED"] = "retry-limit-exceeded";
121
+ StorageErrorCode2["INVALID_CHECKSUM"] = "invalid-checksum";
122
+ StorageErrorCode2["CANCELED"] = "canceled";
123
+ StorageErrorCode2["INVALID_EVENT_NAME"] = "invalid-event-name";
124
+ StorageErrorCode2["INVALID_URL"] = "invalid-url";
125
+ StorageErrorCode2["INVALID_DEFAULT_BUCKET"] = "invalid-default-bucket";
126
+ StorageErrorCode2["NO_DEFAULT_BUCKET"] = "no-default-bucket";
127
+ StorageErrorCode2["CANNOT_SLICE_BLOB"] = "cannot-slice-blob";
128
+ StorageErrorCode2["SERVER_FILE_WRONG_SIZE"] = "server-file-wrong-size";
129
+ StorageErrorCode2["NO_DOWNLOAD_URL"] = "no-download-url";
130
+ StorageErrorCode2["INVALID_ARGUMENT"] = "invalid-argument";
131
+ StorageErrorCode2["INVALID_ARGUMENT_COUNT"] = "invalid-argument-count";
132
+ StorageErrorCode2["APP_DELETED"] = "app-deleted";
133
+ StorageErrorCode2["INVALID_ROOT_OPERATION"] = "invalid-root-operation";
134
+ StorageErrorCode2["INVALID_FORMAT"] = "invalid-format";
135
+ StorageErrorCode2["INTERNAL_ERROR"] = "internal-error";
136
+ StorageErrorCode2["UNSUPPORTED_ENVIRONMENT"] = "unsupported-environment";
137
+ })(StorageErrorCode || (StorageErrorCode = {}));
138
+ function prependCode(code) {
139
+ return "storage/" + code;
140
+ }
141
+ function unknown() {
142
+ const message = "An unknown error occurred, please check the error payload for server response.";
143
+ return new StorageError(StorageErrorCode.UNKNOWN, message);
144
+ }
145
+ function objectNotFound(path) {
146
+ return new StorageError(StorageErrorCode.OBJECT_NOT_FOUND, "Object '" + path + "' does not exist.");
147
+ }
148
+ function quotaExceeded(bucket) {
149
+ return new StorageError(StorageErrorCode.QUOTA_EXCEEDED, "Quota for bucket '" + bucket + "' exceeded, please view quota on https://firebase.google.com/pricing/.");
150
+ }
151
+ function unauthenticated() {
152
+ const message = "User is not authenticated, please authenticate using Firebase Authentication and try again.";
153
+ return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);
154
+ }
155
+ function unauthorizedApp() {
156
+ return new StorageError(StorageErrorCode.UNAUTHORIZED_APP, "This app does not have permission to access Firebase Storage on this project.");
157
+ }
158
+ function unauthorized(path) {
159
+ return new StorageError(StorageErrorCode.UNAUTHORIZED, "User does not have permission to access '" + path + "'.");
160
+ }
161
+ function retryLimitExceeded() {
162
+ return new StorageError(StorageErrorCode.RETRY_LIMIT_EXCEEDED, "Max retry time for operation exceeded, please try again.");
163
+ }
164
+ function canceled() {
165
+ return new StorageError(StorageErrorCode.CANCELED, "User canceled the upload/download.");
166
+ }
167
+ function invalidUrl(url) {
168
+ return new StorageError(StorageErrorCode.INVALID_URL, "Invalid URL '" + url + "'.");
169
+ }
170
+ function invalidDefaultBucket(bucket) {
171
+ return new StorageError(StorageErrorCode.INVALID_DEFAULT_BUCKET, "Invalid default bucket '" + bucket + "'.");
172
+ }
173
+ function noDefaultBucket() {
174
+ return new StorageError(StorageErrorCode.NO_DEFAULT_BUCKET, "No default bucket found. Did you set the '" + CONFIG_STORAGE_BUCKET_KEY + "' property when initializing the app?");
175
+ }
176
+ function cannotSliceBlob() {
177
+ return new StorageError(StorageErrorCode.CANNOT_SLICE_BLOB, "Cannot slice blob for upload. Please retry the upload.");
178
+ }
179
+ function serverFileWrongSize() {
180
+ return new StorageError(StorageErrorCode.SERVER_FILE_WRONG_SIZE, "Server recorded incorrect upload file size, please retry the upload.");
181
+ }
182
+ function noDownloadURL() {
183
+ return new StorageError(StorageErrorCode.NO_DOWNLOAD_URL, "The given file does not have any download URLs.");
184
+ }
185
+ function invalidArgument(message) {
186
+ return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);
187
+ }
188
+ function appDeleted() {
189
+ return new StorageError(StorageErrorCode.APP_DELETED, "The Firebase app was deleted.");
190
+ }
191
+ function invalidRootOperation(name2) {
192
+ return new StorageError(StorageErrorCode.INVALID_ROOT_OPERATION, "The operation '" + name2 + "' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').");
193
+ }
194
+ function invalidFormat(format, message) {
195
+ return new StorageError(StorageErrorCode.INVALID_FORMAT, "String does not match format '" + format + "': " + message);
196
+ }
197
+ function internalError(message) {
198
+ throw new StorageError(StorageErrorCode.INTERNAL_ERROR, "Internal error: " + message);
199
+ }
200
+ /**
201
+ * @license
202
+ * Copyright 2017 Google LLC
203
+ *
204
+ * Licensed under the Apache License, Version 2.0 (the "License");
205
+ * you may not use this file except in compliance with the License.
206
+ * You may obtain a copy of the License at
207
+ *
208
+ * http://www.apache.org/licenses/LICENSE-2.0
209
+ *
210
+ * Unless required by applicable law or agreed to in writing, software
211
+ * distributed under the License is distributed on an "AS IS" BASIS,
212
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
213
+ * See the License for the specific language governing permissions and
214
+ * limitations under the License.
215
+ */
216
+ class Location {
217
+ constructor(bucket, path) {
218
+ this.bucket = bucket;
219
+ this.path_ = path;
220
+ }
221
+ get path() {
222
+ return this.path_;
223
+ }
224
+ get isRoot() {
225
+ return this.path.length === 0;
226
+ }
227
+ fullServerUrl() {
228
+ const encode = encodeURIComponent;
229
+ return "/b/" + encode(this.bucket) + "/o/" + encode(this.path);
230
+ }
231
+ bucketOnlyServerUrl() {
232
+ const encode = encodeURIComponent;
233
+ return "/b/" + encode(this.bucket) + "/o";
234
+ }
235
+ static makeFromBucketSpec(bucketString, host) {
236
+ let bucketLocation;
237
+ try {
238
+ bucketLocation = Location.makeFromUrl(bucketString, host);
239
+ } catch (e) {
240
+ return new Location(bucketString, "");
241
+ }
242
+ if (bucketLocation.path === "") {
243
+ return bucketLocation;
244
+ } else {
245
+ throw invalidDefaultBucket(bucketString);
246
+ }
247
+ }
248
+ static makeFromUrl(url, host) {
249
+ let location = null;
250
+ const bucketDomain = "([A-Za-z0-9.\\-_]+)";
251
+ function gsModify(loc) {
252
+ if (loc.path.charAt(loc.path.length - 1) === "/") {
253
+ loc.path_ = loc.path_.slice(0, -1);
254
+ }
255
+ }
256
+ const gsPath = "(/(.*))?$";
257
+ const gsRegex = new RegExp("^gs://" + bucketDomain + gsPath, "i");
258
+ const gsIndices = { bucket: 1, path: 3 };
259
+ function httpModify(loc) {
260
+ loc.path_ = decodeURIComponent(loc.path);
261
+ }
262
+ const version2 = "v[A-Za-z0-9_]+";
263
+ const firebaseStorageHost = host.replace(/[.]/g, "\\.");
264
+ const firebaseStoragePath = "(/([^?#]*).*)?$";
265
+ const firebaseStorageRegExp = new RegExp(`^https?://${firebaseStorageHost}/${version2}/b/${bucketDomain}/o${firebaseStoragePath}`, "i");
266
+ const firebaseStorageIndices = { bucket: 1, path: 3 };
267
+ const cloudStorageHost = host === DEFAULT_HOST ? "(?:storage.googleapis.com|storage.cloud.google.com)" : host;
268
+ const cloudStoragePath = "([^?#]*)";
269
+ const cloudStorageRegExp = new RegExp(`^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`, "i");
270
+ const cloudStorageIndices = { bucket: 1, path: 2 };
271
+ const groups = [
272
+ { regex: gsRegex, indices: gsIndices, postModify: gsModify },
273
+ {
274
+ regex: firebaseStorageRegExp,
275
+ indices: firebaseStorageIndices,
276
+ postModify: httpModify
277
+ },
278
+ {
279
+ regex: cloudStorageRegExp,
280
+ indices: cloudStorageIndices,
281
+ postModify: httpModify
282
+ }
283
+ ];
284
+ for (let i = 0; i < groups.length; i++) {
285
+ const group = groups[i];
286
+ const captures = group.regex.exec(url);
287
+ if (captures) {
288
+ const bucketValue = captures[group.indices.bucket];
289
+ let pathValue = captures[group.indices.path];
290
+ if (!pathValue) {
291
+ pathValue = "";
292
+ }
293
+ location = new Location(bucketValue, pathValue);
294
+ group.postModify(location);
295
+ break;
296
+ }
297
+ }
298
+ if (location == null) {
299
+ throw invalidUrl(url);
300
+ }
301
+ return location;
302
+ }
303
+ }
304
+ class FailRequest {
305
+ constructor(error) {
306
+ this.promise_ = Promise.reject(error);
307
+ }
308
+ /** @inheritDoc */
309
+ getPromise() {
310
+ return this.promise_;
311
+ }
312
+ /** @inheritDoc */
313
+ cancel(_appDelete = false) {
314
+ }
315
+ }
316
+ /**
317
+ * @license
318
+ * Copyright 2017 Google LLC
319
+ *
320
+ * Licensed under the Apache License, Version 2.0 (the "License");
321
+ * you may not use this file except in compliance with the License.
322
+ * You may obtain a copy of the License at
323
+ *
324
+ * http://www.apache.org/licenses/LICENSE-2.0
325
+ *
326
+ * Unless required by applicable law or agreed to in writing, software
327
+ * distributed under the License is distributed on an "AS IS" BASIS,
328
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
329
+ * See the License for the specific language governing permissions and
330
+ * limitations under the License.
331
+ */
332
+ function start(doRequest, backoffCompleteCb, timeout) {
333
+ let waitSeconds = 1;
334
+ let retryTimeoutId = null;
335
+ let globalTimeoutId = null;
336
+ let hitTimeout = false;
337
+ let cancelState = 0;
338
+ function canceled2() {
339
+ return cancelState === 2;
340
+ }
341
+ let triggeredCallback = false;
342
+ function triggerCallback(...args) {
343
+ if (!triggeredCallback) {
344
+ triggeredCallback = true;
345
+ backoffCompleteCb.apply(null, args);
346
+ }
347
+ }
348
+ function callWithDelay(millis) {
349
+ retryTimeoutId = setTimeout(() => {
350
+ retryTimeoutId = null;
351
+ doRequest(responseHandler, canceled2());
352
+ }, millis);
353
+ }
354
+ function clearGlobalTimeout() {
355
+ if (globalTimeoutId) {
356
+ clearTimeout(globalTimeoutId);
357
+ }
358
+ }
359
+ function responseHandler(success, ...args) {
360
+ if (triggeredCallback) {
361
+ clearGlobalTimeout();
362
+ return;
363
+ }
364
+ if (success) {
365
+ clearGlobalTimeout();
366
+ triggerCallback.call(null, success, ...args);
367
+ return;
368
+ }
369
+ const mustStop = canceled2() || hitTimeout;
370
+ if (mustStop) {
371
+ clearGlobalTimeout();
372
+ triggerCallback.call(null, success, ...args);
373
+ return;
374
+ }
375
+ if (waitSeconds < 64) {
376
+ waitSeconds *= 2;
377
+ }
378
+ let waitMillis;
379
+ if (cancelState === 1) {
380
+ cancelState = 2;
381
+ waitMillis = 0;
382
+ } else {
383
+ waitMillis = (waitSeconds + Math.random()) * 1e3;
384
+ }
385
+ callWithDelay(waitMillis);
386
+ }
387
+ let stopped = false;
388
+ function stop2(wasTimeout) {
389
+ if (stopped) {
390
+ return;
391
+ }
392
+ stopped = true;
393
+ clearGlobalTimeout();
394
+ if (triggeredCallback) {
395
+ return;
396
+ }
397
+ if (retryTimeoutId !== null) {
398
+ if (!wasTimeout) {
399
+ cancelState = 2;
400
+ }
401
+ clearTimeout(retryTimeoutId);
402
+ callWithDelay(0);
403
+ } else {
404
+ if (!wasTimeout) {
405
+ cancelState = 1;
406
+ }
407
+ }
408
+ }
409
+ callWithDelay(0);
410
+ globalTimeoutId = setTimeout(() => {
411
+ hitTimeout = true;
412
+ stop2(true);
413
+ }, timeout);
414
+ return stop2;
415
+ }
416
+ function stop(id) {
417
+ id(false);
418
+ }
419
+ /**
420
+ * @license
421
+ * Copyright 2017 Google LLC
422
+ *
423
+ * Licensed under the Apache License, Version 2.0 (the "License");
424
+ * you may not use this file except in compliance with the License.
425
+ * You may obtain a copy of the License at
426
+ *
427
+ * http://www.apache.org/licenses/LICENSE-2.0
428
+ *
429
+ * Unless required by applicable law or agreed to in writing, software
430
+ * distributed under the License is distributed on an "AS IS" BASIS,
431
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
432
+ * See the License for the specific language governing permissions and
433
+ * limitations under the License.
434
+ */
435
+ function isJustDef(p) {
436
+ return p !== void 0;
437
+ }
438
+ function isFunction(p) {
439
+ return typeof p === "function";
440
+ }
441
+ function isNonArrayObject(p) {
442
+ return typeof p === "object" && !Array.isArray(p);
443
+ }
444
+ function isString(p) {
445
+ return typeof p === "string" || p instanceof String;
446
+ }
447
+ function isNativeBlob(p) {
448
+ return isNativeBlobDefined() && p instanceof Blob;
449
+ }
450
+ function isNativeBlobDefined() {
451
+ return typeof Blob !== "undefined";
452
+ }
453
+ function validateNumber(argument, minValue, maxValue, value) {
454
+ if (value < minValue) {
455
+ throw invalidArgument(`Invalid value for '${argument}'. Expected ${minValue} or greater.`);
456
+ }
457
+ if (value > maxValue) {
458
+ throw invalidArgument(`Invalid value for '${argument}'. Expected ${maxValue} or less.`);
459
+ }
460
+ }
461
+ /**
462
+ * @license
463
+ * Copyright 2017 Google LLC
464
+ *
465
+ * Licensed under the Apache License, Version 2.0 (the "License");
466
+ * you may not use this file except in compliance with the License.
467
+ * You may obtain a copy of the License at
468
+ *
469
+ * http://www.apache.org/licenses/LICENSE-2.0
470
+ *
471
+ * Unless required by applicable law or agreed to in writing, software
472
+ * distributed under the License is distributed on an "AS IS" BASIS,
473
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
474
+ * See the License for the specific language governing permissions and
475
+ * limitations under the License.
476
+ */
477
+ function makeUrl(urlPart, host, protocol) {
478
+ let origin = host;
479
+ if (protocol == null) {
480
+ origin = `https://${host}`;
481
+ }
482
+ return `${protocol}://${origin}/v0${urlPart}`;
483
+ }
484
+ function makeQueryString(params) {
485
+ const encode = encodeURIComponent;
486
+ let queryPart = "?";
487
+ for (const key in params) {
488
+ if (params.hasOwnProperty(key)) {
489
+ const nextPart = encode(key) + "=" + encode(params[key]);
490
+ queryPart = queryPart + nextPart + "&";
491
+ }
492
+ }
493
+ queryPart = queryPart.slice(0, -1);
494
+ return queryPart;
495
+ }
496
+ var ErrorCode;
497
+ (function(ErrorCode2) {
498
+ ErrorCode2[ErrorCode2["NO_ERROR"] = 0] = "NO_ERROR";
499
+ ErrorCode2[ErrorCode2["NETWORK_ERROR"] = 1] = "NETWORK_ERROR";
500
+ ErrorCode2[ErrorCode2["ABORT"] = 2] = "ABORT";
501
+ })(ErrorCode || (ErrorCode = {}));
502
+ /**
503
+ * @license
504
+ * Copyright 2022 Google LLC
505
+ *
506
+ * Licensed under the Apache License, Version 2.0 (the "License");
507
+ * you may not use this file except in compliance with the License.
508
+ * You may obtain a copy of the License at
509
+ *
510
+ * http://www.apache.org/licenses/LICENSE-2.0
511
+ *
512
+ * Unless required by applicable law or agreed to in writing, software
513
+ * distributed under the License is distributed on an "AS IS" BASIS,
514
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
515
+ * See the License for the specific language governing permissions and
516
+ * limitations under the License.
517
+ */
518
+ function isRetryStatusCode(status, additionalRetryCodes) {
519
+ const isFiveHundredCode = status >= 500 && status < 600;
520
+ const extraRetryCodes = [
521
+ // Request Timeout: web server didn't receive full request in time.
522
+ 408,
523
+ // Too Many Requests: you're getting rate-limited, basically.
524
+ 429
525
+ ];
526
+ const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;
527
+ const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;
528
+ return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;
529
+ }
530
+ /**
531
+ * @license
532
+ * Copyright 2017 Google LLC
533
+ *
534
+ * Licensed under the Apache License, Version 2.0 (the "License");
535
+ * you may not use this file except in compliance with the License.
536
+ * You may obtain a copy of the License at
537
+ *
538
+ * http://www.apache.org/licenses/LICENSE-2.0
539
+ *
540
+ * Unless required by applicable law or agreed to in writing, software
541
+ * distributed under the License is distributed on an "AS IS" BASIS,
542
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
543
+ * See the License for the specific language governing permissions and
544
+ * limitations under the License.
545
+ */
546
+ class NetworkRequest {
547
+ constructor(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry = true, isUsingEmulator = false) {
548
+ this.url_ = url_;
549
+ this.method_ = method_;
550
+ this.headers_ = headers_;
551
+ this.body_ = body_;
552
+ this.successCodes_ = successCodes_;
553
+ this.additionalRetryCodes_ = additionalRetryCodes_;
554
+ this.callback_ = callback_;
555
+ this.errorCallback_ = errorCallback_;
556
+ this.timeout_ = timeout_;
557
+ this.progressCallback_ = progressCallback_;
558
+ this.connectionFactory_ = connectionFactory_;
559
+ this.retry = retry;
560
+ this.isUsingEmulator = isUsingEmulator;
561
+ this.pendingConnection_ = null;
562
+ this.backoffId_ = null;
563
+ this.canceled_ = false;
564
+ this.appDelete_ = false;
565
+ this.promise_ = new Promise((resolve, reject) => {
566
+ this.resolve_ = resolve;
567
+ this.reject_ = reject;
568
+ this.start_();
569
+ });
570
+ }
571
+ /**
572
+ * Actually starts the retry loop.
573
+ */
574
+ start_() {
575
+ const doTheRequest = (backoffCallback, canceled2) => {
576
+ if (canceled2) {
577
+ backoffCallback(false, new RequestEndStatus(false, null, true));
578
+ return;
579
+ }
580
+ const connection = this.connectionFactory_();
581
+ this.pendingConnection_ = connection;
582
+ const progressListener = (progressEvent) => {
583
+ const loaded = progressEvent.loaded;
584
+ const total = progressEvent.lengthComputable ? progressEvent.total : -1;
585
+ if (this.progressCallback_ !== null) {
586
+ this.progressCallback_(loaded, total);
587
+ }
588
+ };
589
+ if (this.progressCallback_ !== null) {
590
+ connection.addUploadProgressListener(progressListener);
591
+ }
592
+ connection.send(this.url_, this.method_, this.isUsingEmulator, this.body_, this.headers_).then(() => {
593
+ if (this.progressCallback_ !== null) {
594
+ connection.removeUploadProgressListener(progressListener);
595
+ }
596
+ this.pendingConnection_ = null;
597
+ const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;
598
+ const status = connection.getStatus();
599
+ if (!hitServer || isRetryStatusCode(status, this.additionalRetryCodes_) && this.retry) {
600
+ const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;
601
+ backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));
602
+ return;
603
+ }
604
+ const successCode = this.successCodes_.indexOf(status) !== -1;
605
+ backoffCallback(true, new RequestEndStatus(successCode, connection));
606
+ });
607
+ };
608
+ const backoffDone = (requestWentThrough, status) => {
609
+ const resolve = this.resolve_;
610
+ const reject = this.reject_;
611
+ const connection = status.connection;
612
+ if (status.wasSuccessCode) {
613
+ try {
614
+ const result = this.callback_(connection, connection.getResponse());
615
+ if (isJustDef(result)) {
616
+ resolve(result);
617
+ } else {
618
+ resolve();
619
+ }
620
+ } catch (e) {
621
+ reject(e);
622
+ }
623
+ } else {
624
+ if (connection !== null) {
625
+ const err = unknown();
626
+ err.serverResponse = connection.getErrorText();
627
+ if (this.errorCallback_) {
628
+ reject(this.errorCallback_(connection, err));
629
+ } else {
630
+ reject(err);
631
+ }
632
+ } else {
633
+ if (status.canceled) {
634
+ const err = this.appDelete_ ? appDeleted() : canceled();
635
+ reject(err);
636
+ } else {
637
+ const err = retryLimitExceeded();
638
+ reject(err);
639
+ }
640
+ }
641
+ }
642
+ };
643
+ if (this.canceled_) {
644
+ backoffDone(false, new RequestEndStatus(false, null, true));
645
+ } else {
646
+ this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);
647
+ }
648
+ }
649
+ /** @inheritDoc */
650
+ getPromise() {
651
+ return this.promise_;
652
+ }
653
+ /** @inheritDoc */
654
+ cancel(appDelete) {
655
+ this.canceled_ = true;
656
+ this.appDelete_ = appDelete || false;
657
+ if (this.backoffId_ !== null) {
658
+ stop(this.backoffId_);
659
+ }
660
+ if (this.pendingConnection_ !== null) {
661
+ this.pendingConnection_.abort();
662
+ }
663
+ }
664
+ }
665
+ class RequestEndStatus {
666
+ constructor(wasSuccessCode, connection, canceled2) {
667
+ this.wasSuccessCode = wasSuccessCode;
668
+ this.connection = connection;
669
+ this.canceled = !!canceled2;
670
+ }
671
+ }
672
+ function addAuthHeader_(headers, authToken) {
673
+ if (authToken !== null && authToken.length > 0) {
674
+ headers["Authorization"] = "Firebase " + authToken;
675
+ }
676
+ }
677
+ function addVersionHeader_(headers, firebaseVersion) {
678
+ headers["X-Firebase-Storage-Version"] = "webjs/" + (firebaseVersion !== null && firebaseVersion !== void 0 ? firebaseVersion : "AppManager");
679
+ }
680
+ function addGmpidHeader_(headers, appId) {
681
+ if (appId) {
682
+ headers["X-Firebase-GMPID"] = appId;
683
+ }
684
+ }
685
+ function addAppCheckHeader_(headers, appCheckToken) {
686
+ if (appCheckToken !== null) {
687
+ headers["X-Firebase-AppCheck"] = appCheckToken;
688
+ }
689
+ }
690
+ function makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry = true, isUsingEmulator = false) {
691
+ const queryPart = makeQueryString(requestInfo.urlParams);
692
+ const url = requestInfo.url + queryPart;
693
+ const headers = Object.assign({}, requestInfo.headers);
694
+ addGmpidHeader_(headers, appId);
695
+ addAuthHeader_(headers, authToken);
696
+ addVersionHeader_(headers, firebaseVersion);
697
+ addAppCheckHeader_(headers, appCheckToken);
698
+ return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry, isUsingEmulator);
699
+ }
700
+ /**
701
+ * @license
702
+ * Copyright 2017 Google LLC
703
+ *
704
+ * Licensed under the Apache License, Version 2.0 (the "License");
705
+ * you may not use this file except in compliance with the License.
706
+ * You may obtain a copy of the License at
707
+ *
708
+ * http://www.apache.org/licenses/LICENSE-2.0
709
+ *
710
+ * Unless required by applicable law or agreed to in writing, software
711
+ * distributed under the License is distributed on an "AS IS" BASIS,
712
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
713
+ * See the License for the specific language governing permissions and
714
+ * limitations under the License.
715
+ */
716
+ function getBlobBuilder() {
717
+ if (typeof BlobBuilder !== "undefined") {
718
+ return BlobBuilder;
719
+ } else if (typeof WebKitBlobBuilder !== "undefined") {
720
+ return WebKitBlobBuilder;
721
+ } else {
722
+ return void 0;
723
+ }
724
+ }
725
+ function getBlob$1(...args) {
726
+ const BlobBuilder2 = getBlobBuilder();
727
+ if (BlobBuilder2 !== void 0) {
728
+ const bb = new BlobBuilder2();
729
+ for (let i = 0; i < args.length; i++) {
730
+ bb.append(args[i]);
731
+ }
732
+ return bb.getBlob();
733
+ } else {
734
+ if (isNativeBlobDefined()) {
735
+ return new Blob(args);
736
+ } else {
737
+ throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, "This browser doesn't seem to support creating Blobs");
738
+ }
739
+ }
740
+ }
741
+ function sliceBlob(blob, start2, end) {
742
+ if (blob.webkitSlice) {
743
+ return blob.webkitSlice(start2, end);
744
+ } else if (blob.mozSlice) {
745
+ return blob.mozSlice(start2, end);
746
+ } else if (blob.slice) {
747
+ return blob.slice(start2, end);
748
+ }
749
+ return null;
750
+ }
751
+ /**
752
+ * @license
753
+ * Copyright 2021 Google LLC
754
+ *
755
+ * Licensed under the Apache License, Version 2.0 (the "License");
756
+ * you may not use this file except in compliance with the License.
757
+ * You may obtain a copy of the License at
758
+ *
759
+ * http://www.apache.org/licenses/LICENSE-2.0
760
+ *
761
+ * Unless required by applicable law or agreed to in writing, software
762
+ * distributed under the License is distributed on an "AS IS" BASIS,
763
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
764
+ * See the License for the specific language governing permissions and
765
+ * limitations under the License.
766
+ */
767
+ function decodeBase64(encoded) {
768
+ if (/[^-A-Za-z0-9+/=]/.test(encoded)) {
769
+ throw invalidFormat("base64", "Invalid character found");
770
+ }
771
+ return Buffer.from(encoded, "base64").toString("binary");
772
+ }
773
+ /**
774
+ * @license
775
+ * Copyright 2017 Google LLC
776
+ *
777
+ * Licensed under the Apache License, Version 2.0 (the "License");
778
+ * you may not use this file except in compliance with the License.
779
+ * You may obtain a copy of the License at
780
+ *
781
+ * http://www.apache.org/licenses/LICENSE-2.0
782
+ *
783
+ * Unless required by applicable law or agreed to in writing, software
784
+ * distributed under the License is distributed on an "AS IS" BASIS,
785
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
786
+ * See the License for the specific language governing permissions and
787
+ * limitations under the License.
788
+ */
789
+ const StringFormat = {
790
+ /**
791
+ * Indicates the string should be interpreted "raw", that is, as normal text.
792
+ * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte
793
+ * sequence.
794
+ * Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence
795
+ * 48 65 6c 6c 6f 21 20 f0 9f 98 8a
796
+ */
797
+ RAW: "raw",
798
+ /**
799
+ * Indicates the string should be interpreted as base64-encoded data.
800
+ * Padding characters (trailing '='s) are optional.
801
+ * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence
802
+ * ad 69 8e fb e1 3a b7 bf eb 97
803
+ */
804
+ BASE64: "base64",
805
+ /**
806
+ * Indicates the string should be interpreted as base64url-encoded data.
807
+ * Padding characters (trailing '='s) are optional.
808
+ * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence
809
+ * ad 69 8e fb e1 3a b7 bf eb 97
810
+ */
811
+ BASE64URL: "base64url",
812
+ /**
813
+ * Indicates the string is a data URL, such as one obtained from
814
+ * canvas.toDataURL().
815
+ * Example: the string 'data:application/octet-stream;base64,aaaa'
816
+ * becomes the byte sequence
817
+ * 69 a6 9a
818
+ * (the content-type "application/octet-stream" is also applied, but can
819
+ * be overridden in the metadata object).
820
+ */
821
+ DATA_URL: "data_url"
822
+ };
823
+ class StringData {
824
+ constructor(data, contentType) {
825
+ this.data = data;
826
+ this.contentType = contentType || null;
827
+ }
828
+ }
829
+ function dataFromString(format, stringData) {
830
+ switch (format) {
831
+ case StringFormat.RAW:
832
+ return new StringData(utf8Bytes_(stringData));
833
+ case StringFormat.BASE64:
834
+ case StringFormat.BASE64URL:
835
+ return new StringData(base64Bytes_(format, stringData));
836
+ case StringFormat.DATA_URL:
837
+ return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));
838
+ }
839
+ throw unknown();
840
+ }
841
+ function utf8Bytes_(value) {
842
+ const b = [];
843
+ for (let i = 0; i < value.length; i++) {
844
+ let c = value.charCodeAt(i);
845
+ if (c <= 127) {
846
+ b.push(c);
847
+ } else {
848
+ if (c <= 2047) {
849
+ b.push(192 | c >> 6, 128 | c & 63);
850
+ } else {
851
+ if ((c & 64512) === 55296) {
852
+ const valid = i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;
853
+ if (!valid) {
854
+ b.push(239, 191, 189);
855
+ } else {
856
+ const hi = c;
857
+ const lo = value.charCodeAt(++i);
858
+ c = 65536 | (hi & 1023) << 10 | lo & 1023;
859
+ b.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
860
+ }
861
+ } else {
862
+ if ((c & 64512) === 56320) {
863
+ b.push(239, 191, 189);
864
+ } else {
865
+ b.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
866
+ }
867
+ }
868
+ }
869
+ }
870
+ }
871
+ return new Uint8Array(b);
872
+ }
873
+ function percentEncodedBytes_(value) {
874
+ let decoded;
875
+ try {
876
+ decoded = decodeURIComponent(value);
877
+ } catch (e) {
878
+ throw invalidFormat(StringFormat.DATA_URL, "Malformed data URL.");
879
+ }
880
+ return utf8Bytes_(decoded);
881
+ }
882
+ function base64Bytes_(format, value) {
883
+ switch (format) {
884
+ case StringFormat.BASE64: {
885
+ const hasMinus = value.indexOf("-") !== -1;
886
+ const hasUnder = value.indexOf("_") !== -1;
887
+ if (hasMinus || hasUnder) {
888
+ const invalidChar = hasMinus ? "-" : "_";
889
+ throw invalidFormat(format, "Invalid character '" + invalidChar + "' found: is it base64url encoded?");
890
+ }
891
+ break;
892
+ }
893
+ case StringFormat.BASE64URL: {
894
+ const hasPlus = value.indexOf("+") !== -1;
895
+ const hasSlash = value.indexOf("/") !== -1;
896
+ if (hasPlus || hasSlash) {
897
+ const invalidChar = hasPlus ? "+" : "/";
898
+ throw invalidFormat(format, "Invalid character '" + invalidChar + "' found: is it base64 encoded?");
899
+ }
900
+ value = value.replace(/-/g, "+").replace(/_/g, "/");
901
+ break;
902
+ }
903
+ }
904
+ let bytes;
905
+ try {
906
+ bytes = decodeBase64(value);
907
+ } catch (e) {
908
+ if (e.message.includes("polyfill")) {
909
+ throw e;
910
+ }
911
+ throw invalidFormat(format, "Invalid character found");
912
+ }
913
+ const array = new Uint8Array(bytes.length);
914
+ for (let i = 0; i < bytes.length; i++) {
915
+ array[i] = bytes.charCodeAt(i);
916
+ }
917
+ return array;
918
+ }
919
+ class DataURLParts {
920
+ constructor(dataURL) {
921
+ this.base64 = false;
922
+ this.contentType = null;
923
+ const matches = dataURL.match(/^data:([^,]+)?,/);
924
+ if (matches === null) {
925
+ throw invalidFormat(StringFormat.DATA_URL, "Must be formatted 'data:[<mediatype>][;base64],<data>");
926
+ }
927
+ const middle = matches[1] || null;
928
+ if (middle != null) {
929
+ this.base64 = endsWith(middle, ";base64");
930
+ this.contentType = this.base64 ? middle.substring(0, middle.length - ";base64".length) : middle;
931
+ }
932
+ this.rest = dataURL.substring(dataURL.indexOf(",") + 1);
933
+ }
934
+ }
935
+ function dataURLBytes_(dataUrl) {
936
+ const parts = new DataURLParts(dataUrl);
937
+ if (parts.base64) {
938
+ return base64Bytes_(StringFormat.BASE64, parts.rest);
939
+ } else {
940
+ return percentEncodedBytes_(parts.rest);
941
+ }
942
+ }
943
+ function dataURLContentType_(dataUrl) {
944
+ const parts = new DataURLParts(dataUrl);
945
+ return parts.contentType;
946
+ }
947
+ function endsWith(s, end) {
948
+ const longEnough = s.length >= end.length;
949
+ if (!longEnough) {
950
+ return false;
951
+ }
952
+ return s.substring(s.length - end.length) === end;
953
+ }
954
+ /**
955
+ * @license
956
+ * Copyright 2017 Google LLC
957
+ *
958
+ * Licensed under the Apache License, Version 2.0 (the "License");
959
+ * you may not use this file except in compliance with the License.
960
+ * You may obtain a copy of the License at
961
+ *
962
+ * http://www.apache.org/licenses/LICENSE-2.0
963
+ *
964
+ * Unless required by applicable law or agreed to in writing, software
965
+ * distributed under the License is distributed on an "AS IS" BASIS,
966
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
967
+ * See the License for the specific language governing permissions and
968
+ * limitations under the License.
969
+ */
970
+ class FbsBlob {
971
+ constructor(data, elideCopy) {
972
+ let size = 0;
973
+ let blobType = "";
974
+ if (isNativeBlob(data)) {
975
+ this.data_ = data;
976
+ size = data.size;
977
+ blobType = data.type;
978
+ } else if (data instanceof ArrayBuffer) {
979
+ if (elideCopy) {
980
+ this.data_ = new Uint8Array(data);
981
+ } else {
982
+ this.data_ = new Uint8Array(data.byteLength);
983
+ this.data_.set(new Uint8Array(data));
984
+ }
985
+ size = this.data_.length;
986
+ } else if (data instanceof Uint8Array) {
987
+ if (elideCopy) {
988
+ this.data_ = data;
989
+ } else {
990
+ this.data_ = new Uint8Array(data.length);
991
+ this.data_.set(data);
992
+ }
993
+ size = data.length;
994
+ }
995
+ this.size_ = size;
996
+ this.type_ = blobType;
997
+ }
998
+ size() {
999
+ return this.size_;
1000
+ }
1001
+ type() {
1002
+ return this.type_;
1003
+ }
1004
+ slice(startByte, endByte) {
1005
+ if (isNativeBlob(this.data_)) {
1006
+ const realBlob = this.data_;
1007
+ const sliced = sliceBlob(realBlob, startByte, endByte);
1008
+ if (sliced === null) {
1009
+ return null;
1010
+ }
1011
+ return new FbsBlob(sliced);
1012
+ } else {
1013
+ const slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);
1014
+ return new FbsBlob(slice, true);
1015
+ }
1016
+ }
1017
+ static getBlob(...args) {
1018
+ if (isNativeBlobDefined()) {
1019
+ const blobby = args.map((val) => {
1020
+ if (val instanceof FbsBlob) {
1021
+ return val.data_;
1022
+ } else {
1023
+ return val;
1024
+ }
1025
+ });
1026
+ return new FbsBlob(getBlob$1.apply(null, blobby));
1027
+ } else {
1028
+ const uint8Arrays = args.map((val) => {
1029
+ if (isString(val)) {
1030
+ return dataFromString(StringFormat.RAW, val).data;
1031
+ } else {
1032
+ return val.data_;
1033
+ }
1034
+ });
1035
+ let finalLength = 0;
1036
+ uint8Arrays.forEach((array) => {
1037
+ finalLength += array.byteLength;
1038
+ });
1039
+ const merged = new Uint8Array(finalLength);
1040
+ let index = 0;
1041
+ uint8Arrays.forEach((array) => {
1042
+ for (let i = 0; i < array.length; i++) {
1043
+ merged[index++] = array[i];
1044
+ }
1045
+ });
1046
+ return new FbsBlob(merged, true);
1047
+ }
1048
+ }
1049
+ uploadData() {
1050
+ return this.data_;
1051
+ }
1052
+ }
1053
+ /**
1054
+ * @license
1055
+ * Copyright 2017 Google LLC
1056
+ *
1057
+ * Licensed under the Apache License, Version 2.0 (the "License");
1058
+ * you may not use this file except in compliance with the License.
1059
+ * You may obtain a copy of the License at
1060
+ *
1061
+ * http://www.apache.org/licenses/LICENSE-2.0
1062
+ *
1063
+ * Unless required by applicable law or agreed to in writing, software
1064
+ * distributed under the License is distributed on an "AS IS" BASIS,
1065
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1066
+ * See the License for the specific language governing permissions and
1067
+ * limitations under the License.
1068
+ */
1069
+ function jsonObjectOrNull(s) {
1070
+ let obj;
1071
+ try {
1072
+ obj = JSON.parse(s);
1073
+ } catch (e) {
1074
+ return null;
1075
+ }
1076
+ if (isNonArrayObject(obj)) {
1077
+ return obj;
1078
+ } else {
1079
+ return null;
1080
+ }
1081
+ }
1082
+ /**
1083
+ * @license
1084
+ * Copyright 2017 Google LLC
1085
+ *
1086
+ * Licensed under the Apache License, Version 2.0 (the "License");
1087
+ * you may not use this file except in compliance with the License.
1088
+ * You may obtain a copy of the License at
1089
+ *
1090
+ * http://www.apache.org/licenses/LICENSE-2.0
1091
+ *
1092
+ * Unless required by applicable law or agreed to in writing, software
1093
+ * distributed under the License is distributed on an "AS IS" BASIS,
1094
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1095
+ * See the License for the specific language governing permissions and
1096
+ * limitations under the License.
1097
+ */
1098
+ function parent(path) {
1099
+ if (path.length === 0) {
1100
+ return null;
1101
+ }
1102
+ const index = path.lastIndexOf("/");
1103
+ if (index === -1) {
1104
+ return "";
1105
+ }
1106
+ const newPath = path.slice(0, index);
1107
+ return newPath;
1108
+ }
1109
+ function child(path, childPath) {
1110
+ const canonicalChildPath = childPath.split("/").filter((component) => component.length > 0).join("/");
1111
+ if (path.length === 0) {
1112
+ return canonicalChildPath;
1113
+ } else {
1114
+ return path + "/" + canonicalChildPath;
1115
+ }
1116
+ }
1117
+ function lastComponent(path) {
1118
+ const index = path.lastIndexOf("/", path.length - 2);
1119
+ if (index === -1) {
1120
+ return path;
1121
+ } else {
1122
+ return path.slice(index + 1);
1123
+ }
1124
+ }
1125
+ /**
1126
+ * @license
1127
+ * Copyright 2017 Google LLC
1128
+ *
1129
+ * Licensed under the Apache License, Version 2.0 (the "License");
1130
+ * you may not use this file except in compliance with the License.
1131
+ * You may obtain a copy of the License at
1132
+ *
1133
+ * http://www.apache.org/licenses/LICENSE-2.0
1134
+ *
1135
+ * Unless required by applicable law or agreed to in writing, software
1136
+ * distributed under the License is distributed on an "AS IS" BASIS,
1137
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1138
+ * See the License for the specific language governing permissions and
1139
+ * limitations under the License.
1140
+ */
1141
+ function noXform_(metadata, value) {
1142
+ return value;
1143
+ }
1144
+ class Mapping {
1145
+ constructor(server, local, writable, xform) {
1146
+ this.server = server;
1147
+ this.local = local || server;
1148
+ this.writable = !!writable;
1149
+ this.xform = xform || noXform_;
1150
+ }
1151
+ }
1152
+ let mappings_ = null;
1153
+ function xformPath(fullPath) {
1154
+ if (!isString(fullPath) || fullPath.length < 2) {
1155
+ return fullPath;
1156
+ } else {
1157
+ return lastComponent(fullPath);
1158
+ }
1159
+ }
1160
+ function getMappings() {
1161
+ if (mappings_) {
1162
+ return mappings_;
1163
+ }
1164
+ const mappings = [];
1165
+ mappings.push(new Mapping("bucket"));
1166
+ mappings.push(new Mapping("generation"));
1167
+ mappings.push(new Mapping("metageneration"));
1168
+ mappings.push(new Mapping("name", "fullPath", true));
1169
+ function mappingsXformPath(_metadata, fullPath) {
1170
+ return xformPath(fullPath);
1171
+ }
1172
+ const nameMapping = new Mapping("name");
1173
+ nameMapping.xform = mappingsXformPath;
1174
+ mappings.push(nameMapping);
1175
+ function xformSize(_metadata, size) {
1176
+ if (size !== void 0) {
1177
+ return Number(size);
1178
+ } else {
1179
+ return size;
1180
+ }
1181
+ }
1182
+ const sizeMapping = new Mapping("size");
1183
+ sizeMapping.xform = xformSize;
1184
+ mappings.push(sizeMapping);
1185
+ mappings.push(new Mapping("timeCreated"));
1186
+ mappings.push(new Mapping("updated"));
1187
+ mappings.push(new Mapping("md5Hash", null, true));
1188
+ mappings.push(new Mapping("cacheControl", null, true));
1189
+ mappings.push(new Mapping("contentDisposition", null, true));
1190
+ mappings.push(new Mapping("contentEncoding", null, true));
1191
+ mappings.push(new Mapping("contentLanguage", null, true));
1192
+ mappings.push(new Mapping("contentType", null, true));
1193
+ mappings.push(new Mapping("metadata", "customMetadata", true));
1194
+ mappings_ = mappings;
1195
+ return mappings_;
1196
+ }
1197
+ function addRef(metadata, service) {
1198
+ function generateRef() {
1199
+ const bucket = metadata["bucket"];
1200
+ const path = metadata["fullPath"];
1201
+ const loc = new Location(bucket, path);
1202
+ return service._makeStorageReference(loc);
1203
+ }
1204
+ Object.defineProperty(metadata, "ref", { get: generateRef });
1205
+ }
1206
+ function fromResource(service, resource, mappings) {
1207
+ const metadata = {};
1208
+ metadata["type"] = "file";
1209
+ const len = mappings.length;
1210
+ for (let i = 0; i < len; i++) {
1211
+ const mapping = mappings[i];
1212
+ metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);
1213
+ }
1214
+ addRef(metadata, service);
1215
+ return metadata;
1216
+ }
1217
+ function fromResourceString(service, resourceString, mappings) {
1218
+ const obj = jsonObjectOrNull(resourceString);
1219
+ if (obj === null) {
1220
+ return null;
1221
+ }
1222
+ const resource = obj;
1223
+ return fromResource(service, resource, mappings);
1224
+ }
1225
+ function downloadUrlFromResourceString(metadata, resourceString, host, protocol) {
1226
+ const obj = jsonObjectOrNull(resourceString);
1227
+ if (obj === null) {
1228
+ return null;
1229
+ }
1230
+ if (!isString(obj["downloadTokens"])) {
1231
+ return null;
1232
+ }
1233
+ const tokens = obj["downloadTokens"];
1234
+ if (tokens.length === 0) {
1235
+ return null;
1236
+ }
1237
+ const encode = encodeURIComponent;
1238
+ const tokensList = tokens.split(",");
1239
+ const urls = tokensList.map((token) => {
1240
+ const bucket = metadata["bucket"];
1241
+ const path = metadata["fullPath"];
1242
+ const urlPart = "/b/" + encode(bucket) + "/o/" + encode(path);
1243
+ const base = makeUrl(urlPart, host, protocol);
1244
+ const queryString = makeQueryString({
1245
+ alt: "media",
1246
+ token
1247
+ });
1248
+ return base + queryString;
1249
+ });
1250
+ return urls[0];
1251
+ }
1252
+ function toResourceString(metadata, mappings) {
1253
+ const resource = {};
1254
+ const len = mappings.length;
1255
+ for (let i = 0; i < len; i++) {
1256
+ const mapping = mappings[i];
1257
+ if (mapping.writable) {
1258
+ resource[mapping.server] = metadata[mapping.local];
1259
+ }
1260
+ }
1261
+ return JSON.stringify(resource);
1262
+ }
1263
+ /**
1264
+ * @license
1265
+ * Copyright 2019 Google LLC
1266
+ *
1267
+ * Licensed under the Apache License, Version 2.0 (the "License");
1268
+ * you may not use this file except in compliance with the License.
1269
+ * You may obtain a copy of the License at
1270
+ *
1271
+ * http://www.apache.org/licenses/LICENSE-2.0
1272
+ *
1273
+ * Unless required by applicable law or agreed to in writing, software
1274
+ * distributed under the License is distributed on an "AS IS" BASIS,
1275
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1276
+ * See the License for the specific language governing permissions and
1277
+ * limitations under the License.
1278
+ */
1279
+ const PREFIXES_KEY = "prefixes";
1280
+ const ITEMS_KEY = "items";
1281
+ function fromBackendResponse(service, bucket, resource) {
1282
+ const listResult = {
1283
+ prefixes: [],
1284
+ items: [],
1285
+ nextPageToken: resource["nextPageToken"]
1286
+ };
1287
+ if (resource[PREFIXES_KEY]) {
1288
+ for (const path of resource[PREFIXES_KEY]) {
1289
+ const pathWithoutTrailingSlash = path.replace(/\/$/, "");
1290
+ const reference = service._makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));
1291
+ listResult.prefixes.push(reference);
1292
+ }
1293
+ }
1294
+ if (resource[ITEMS_KEY]) {
1295
+ for (const item of resource[ITEMS_KEY]) {
1296
+ const reference = service._makeStorageReference(new Location(bucket, item["name"]));
1297
+ listResult.items.push(reference);
1298
+ }
1299
+ }
1300
+ return listResult;
1301
+ }
1302
+ function fromResponseString(service, bucket, resourceString) {
1303
+ const obj = jsonObjectOrNull(resourceString);
1304
+ if (obj === null) {
1305
+ return null;
1306
+ }
1307
+ const resource = obj;
1308
+ return fromBackendResponse(service, bucket, resource);
1309
+ }
1310
+ class RequestInfo {
1311
+ constructor(url, method, handler, timeout) {
1312
+ this.url = url;
1313
+ this.method = method;
1314
+ this.handler = handler;
1315
+ this.timeout = timeout;
1316
+ this.urlParams = {};
1317
+ this.headers = {};
1318
+ this.body = null;
1319
+ this.errorHandler = null;
1320
+ this.progressCallback = null;
1321
+ this.successCodes = [200];
1322
+ this.additionalRetryCodes = [];
1323
+ }
1324
+ }
1325
+ /**
1326
+ * @license
1327
+ * Copyright 2017 Google LLC
1328
+ *
1329
+ * Licensed under the Apache License, Version 2.0 (the "License");
1330
+ * you may not use this file except in compliance with the License.
1331
+ * You may obtain a copy of the License at
1332
+ *
1333
+ * http://www.apache.org/licenses/LICENSE-2.0
1334
+ *
1335
+ * Unless required by applicable law or agreed to in writing, software
1336
+ * distributed under the License is distributed on an "AS IS" BASIS,
1337
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1338
+ * See the License for the specific language governing permissions and
1339
+ * limitations under the License.
1340
+ */
1341
+ function handlerCheck(cndn) {
1342
+ if (!cndn) {
1343
+ throw unknown();
1344
+ }
1345
+ }
1346
+ function metadataHandler(service, mappings) {
1347
+ function handler(xhr, text) {
1348
+ const metadata = fromResourceString(service, text, mappings);
1349
+ handlerCheck(metadata !== null);
1350
+ return metadata;
1351
+ }
1352
+ return handler;
1353
+ }
1354
+ function listHandler(service, bucket) {
1355
+ function handler(xhr, text) {
1356
+ const listResult = fromResponseString(service, bucket, text);
1357
+ handlerCheck(listResult !== null);
1358
+ return listResult;
1359
+ }
1360
+ return handler;
1361
+ }
1362
+ function downloadUrlHandler(service, mappings) {
1363
+ function handler(xhr, text) {
1364
+ const metadata = fromResourceString(service, text, mappings);
1365
+ handlerCheck(metadata !== null);
1366
+ return downloadUrlFromResourceString(metadata, text, service.host, service._protocol);
1367
+ }
1368
+ return handler;
1369
+ }
1370
+ function sharedErrorHandler(location) {
1371
+ function errorHandler(xhr, err) {
1372
+ let newErr;
1373
+ if (xhr.getStatus() === 401) {
1374
+ if (
1375
+ // This exact message string is the only consistent part of the
1376
+ // server's error response that identifies it as an App Check error.
1377
+ xhr.getErrorText().includes("Firebase App Check token is invalid")
1378
+ ) {
1379
+ newErr = unauthorizedApp();
1380
+ } else {
1381
+ newErr = unauthenticated();
1382
+ }
1383
+ } else {
1384
+ if (xhr.getStatus() === 402) {
1385
+ newErr = quotaExceeded(location.bucket);
1386
+ } else {
1387
+ if (xhr.getStatus() === 403) {
1388
+ newErr = unauthorized(location.path);
1389
+ } else {
1390
+ newErr = err;
1391
+ }
1392
+ }
1393
+ }
1394
+ newErr.status = xhr.getStatus();
1395
+ newErr.serverResponse = err.serverResponse;
1396
+ return newErr;
1397
+ }
1398
+ return errorHandler;
1399
+ }
1400
+ function objectErrorHandler(location) {
1401
+ const shared = sharedErrorHandler(location);
1402
+ function errorHandler(xhr, err) {
1403
+ let newErr = shared(xhr, err);
1404
+ if (xhr.getStatus() === 404) {
1405
+ newErr = objectNotFound(location.path);
1406
+ }
1407
+ newErr.serverResponse = err.serverResponse;
1408
+ return newErr;
1409
+ }
1410
+ return errorHandler;
1411
+ }
1412
+ function getMetadata$2(service, location, mappings) {
1413
+ const urlPart = location.fullServerUrl();
1414
+ const url = makeUrl(urlPart, service.host, service._protocol);
1415
+ const method = "GET";
1416
+ const timeout = service.maxOperationRetryTime;
1417
+ const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
1418
+ requestInfo.errorHandler = objectErrorHandler(location);
1419
+ return requestInfo;
1420
+ }
1421
+ function list$2(service, location, delimiter, pageToken, maxResults) {
1422
+ const urlParams = {};
1423
+ if (location.isRoot) {
1424
+ urlParams["prefix"] = "";
1425
+ } else {
1426
+ urlParams["prefix"] = location.path + "/";
1427
+ }
1428
+ if (delimiter.length > 0) {
1429
+ urlParams["delimiter"] = delimiter;
1430
+ }
1431
+ if (pageToken) {
1432
+ urlParams["pageToken"] = pageToken;
1433
+ }
1434
+ if (maxResults) {
1435
+ urlParams["maxResults"] = maxResults;
1436
+ }
1437
+ const urlPart = location.bucketOnlyServerUrl();
1438
+ const url = makeUrl(urlPart, service.host, service._protocol);
1439
+ const method = "GET";
1440
+ const timeout = service.maxOperationRetryTime;
1441
+ const requestInfo = new RequestInfo(url, method, listHandler(service, location.bucket), timeout);
1442
+ requestInfo.urlParams = urlParams;
1443
+ requestInfo.errorHandler = sharedErrorHandler(location);
1444
+ return requestInfo;
1445
+ }
1446
+ function getBytes$1(service, location, maxDownloadSizeBytes) {
1447
+ const urlPart = location.fullServerUrl();
1448
+ const url = makeUrl(urlPart, service.host, service._protocol) + "?alt=media";
1449
+ const method = "GET";
1450
+ const timeout = service.maxOperationRetryTime;
1451
+ const requestInfo = new RequestInfo(url, method, (_, data) => data, timeout);
1452
+ requestInfo.errorHandler = objectErrorHandler(location);
1453
+ if (maxDownloadSizeBytes !== void 0) {
1454
+ requestInfo.headers["Range"] = `bytes=0-${maxDownloadSizeBytes}`;
1455
+ requestInfo.successCodes = [
1456
+ 200,
1457
+ 206
1458
+ /* Partial Content */
1459
+ ];
1460
+ }
1461
+ return requestInfo;
1462
+ }
1463
+ function getDownloadUrl(service, location, mappings) {
1464
+ const urlPart = location.fullServerUrl();
1465
+ const url = makeUrl(urlPart, service.host, service._protocol);
1466
+ const method = "GET";
1467
+ const timeout = service.maxOperationRetryTime;
1468
+ const requestInfo = new RequestInfo(url, method, downloadUrlHandler(service, mappings), timeout);
1469
+ requestInfo.errorHandler = objectErrorHandler(location);
1470
+ return requestInfo;
1471
+ }
1472
+ function updateMetadata$2(service, location, metadata, mappings) {
1473
+ const urlPart = location.fullServerUrl();
1474
+ const url = makeUrl(urlPart, service.host, service._protocol);
1475
+ const method = "PATCH";
1476
+ const body = toResourceString(metadata, mappings);
1477
+ const headers = { "Content-Type": "application/json; charset=utf-8" };
1478
+ const timeout = service.maxOperationRetryTime;
1479
+ const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
1480
+ requestInfo.headers = headers;
1481
+ requestInfo.body = body;
1482
+ requestInfo.errorHandler = objectErrorHandler(location);
1483
+ return requestInfo;
1484
+ }
1485
+ function deleteObject$2(service, location) {
1486
+ const urlPart = location.fullServerUrl();
1487
+ const url = makeUrl(urlPart, service.host, service._protocol);
1488
+ const method = "DELETE";
1489
+ const timeout = service.maxOperationRetryTime;
1490
+ function handler(_xhr, _text) {
1491
+ }
1492
+ const requestInfo = new RequestInfo(url, method, handler, timeout);
1493
+ requestInfo.successCodes = [200, 204];
1494
+ requestInfo.errorHandler = objectErrorHandler(location);
1495
+ return requestInfo;
1496
+ }
1497
+ function determineContentType_(metadata, blob) {
1498
+ return metadata && metadata["contentType"] || blob && blob.type() || "application/octet-stream";
1499
+ }
1500
+ function metadataForUpload_(location, blob, metadata) {
1501
+ const metadataClone = Object.assign({}, metadata);
1502
+ metadataClone["fullPath"] = location.path;
1503
+ metadataClone["size"] = blob.size();
1504
+ if (!metadataClone["contentType"]) {
1505
+ metadataClone["contentType"] = determineContentType_(null, blob);
1506
+ }
1507
+ return metadataClone;
1508
+ }
1509
+ function multipartUpload(service, location, mappings, blob, metadata) {
1510
+ const urlPart = location.bucketOnlyServerUrl();
1511
+ const headers = {
1512
+ "X-Goog-Upload-Protocol": "multipart"
1513
+ };
1514
+ function genBoundary() {
1515
+ let str = "";
1516
+ for (let i = 0; i < 2; i++) {
1517
+ str = str + Math.random().toString().slice(2);
1518
+ }
1519
+ return str;
1520
+ }
1521
+ const boundary = genBoundary();
1522
+ headers["Content-Type"] = "multipart/related; boundary=" + boundary;
1523
+ const metadata_ = metadataForUpload_(location, blob, metadata);
1524
+ const metadataString = toResourceString(metadata_, mappings);
1525
+ const preBlobPart = "--" + boundary + "\r\nContent-Type: application/json; charset=utf-8\r\n\r\n" + metadataString + "\r\n--" + boundary + "\r\nContent-Type: " + metadata_["contentType"] + "\r\n\r\n";
1526
+ const postBlobPart = "\r\n--" + boundary + "--";
1527
+ const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);
1528
+ if (body === null) {
1529
+ throw cannotSliceBlob();
1530
+ }
1531
+ const urlParams = { name: metadata_["fullPath"] };
1532
+ const url = makeUrl(urlPart, service.host, service._protocol);
1533
+ const method = "POST";
1534
+ const timeout = service.maxUploadRetryTime;
1535
+ const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
1536
+ requestInfo.urlParams = urlParams;
1537
+ requestInfo.headers = headers;
1538
+ requestInfo.body = body.uploadData();
1539
+ requestInfo.errorHandler = sharedErrorHandler(location);
1540
+ return requestInfo;
1541
+ }
1542
+ class ResumableUploadStatus {
1543
+ constructor(current, total, finalized, metadata) {
1544
+ this.current = current;
1545
+ this.total = total;
1546
+ this.finalized = !!finalized;
1547
+ this.metadata = metadata || null;
1548
+ }
1549
+ }
1550
+ function checkResumeHeader_(xhr, allowed) {
1551
+ let status = null;
1552
+ try {
1553
+ status = xhr.getResponseHeader("X-Goog-Upload-Status");
1554
+ } catch (e) {
1555
+ handlerCheck(false);
1556
+ }
1557
+ const allowedStatus = allowed || ["active"];
1558
+ handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);
1559
+ return status;
1560
+ }
1561
+ function createResumableUpload(service, location, mappings, blob, metadata) {
1562
+ const urlPart = location.bucketOnlyServerUrl();
1563
+ const metadataForUpload = metadataForUpload_(location, blob, metadata);
1564
+ const urlParams = { name: metadataForUpload["fullPath"] };
1565
+ const url = makeUrl(urlPart, service.host, service._protocol);
1566
+ const method = "POST";
1567
+ const headers = {
1568
+ "X-Goog-Upload-Protocol": "resumable",
1569
+ "X-Goog-Upload-Command": "start",
1570
+ "X-Goog-Upload-Header-Content-Length": `${blob.size()}`,
1571
+ "X-Goog-Upload-Header-Content-Type": metadataForUpload["contentType"],
1572
+ "Content-Type": "application/json; charset=utf-8"
1573
+ };
1574
+ const body = toResourceString(metadataForUpload, mappings);
1575
+ const timeout = service.maxUploadRetryTime;
1576
+ function handler(xhr) {
1577
+ checkResumeHeader_(xhr);
1578
+ let url2;
1579
+ try {
1580
+ url2 = xhr.getResponseHeader("X-Goog-Upload-URL");
1581
+ } catch (e) {
1582
+ handlerCheck(false);
1583
+ }
1584
+ handlerCheck(isString(url2));
1585
+ return url2;
1586
+ }
1587
+ const requestInfo = new RequestInfo(url, method, handler, timeout);
1588
+ requestInfo.urlParams = urlParams;
1589
+ requestInfo.headers = headers;
1590
+ requestInfo.body = body;
1591
+ requestInfo.errorHandler = sharedErrorHandler(location);
1592
+ return requestInfo;
1593
+ }
1594
+ function getResumableUploadStatus(service, location, url, blob) {
1595
+ const headers = { "X-Goog-Upload-Command": "query" };
1596
+ function handler(xhr) {
1597
+ const status = checkResumeHeader_(xhr, ["active", "final"]);
1598
+ let sizeString = null;
1599
+ try {
1600
+ sizeString = xhr.getResponseHeader("X-Goog-Upload-Size-Received");
1601
+ } catch (e) {
1602
+ handlerCheck(false);
1603
+ }
1604
+ if (!sizeString) {
1605
+ handlerCheck(false);
1606
+ }
1607
+ const size = Number(sizeString);
1608
+ handlerCheck(!isNaN(size));
1609
+ return new ResumableUploadStatus(size, blob.size(), status === "final");
1610
+ }
1611
+ const method = "POST";
1612
+ const timeout = service.maxUploadRetryTime;
1613
+ const requestInfo = new RequestInfo(url, method, handler, timeout);
1614
+ requestInfo.headers = headers;
1615
+ requestInfo.errorHandler = sharedErrorHandler(location);
1616
+ return requestInfo;
1617
+ }
1618
+ const RESUMABLE_UPLOAD_CHUNK_SIZE = 256 * 1024;
1619
+ function continueResumableUpload(location, service, url, blob, chunkSize, mappings, status, progressCallback) {
1620
+ const status_ = new ResumableUploadStatus(0, 0);
1621
+ if (status) {
1622
+ status_.current = status.current;
1623
+ status_.total = status.total;
1624
+ } else {
1625
+ status_.current = 0;
1626
+ status_.total = blob.size();
1627
+ }
1628
+ if (blob.size() !== status_.total) {
1629
+ throw serverFileWrongSize();
1630
+ }
1631
+ const bytesLeft = status_.total - status_.current;
1632
+ let bytesToUpload = bytesLeft;
1633
+ if (chunkSize > 0) {
1634
+ bytesToUpload = Math.min(bytesToUpload, chunkSize);
1635
+ }
1636
+ const startByte = status_.current;
1637
+ const endByte = startByte + bytesToUpload;
1638
+ let uploadCommand = "";
1639
+ if (bytesToUpload === 0) {
1640
+ uploadCommand = "finalize";
1641
+ } else if (bytesLeft === bytesToUpload) {
1642
+ uploadCommand = "upload, finalize";
1643
+ } else {
1644
+ uploadCommand = "upload";
1645
+ }
1646
+ const headers = {
1647
+ "X-Goog-Upload-Command": uploadCommand,
1648
+ "X-Goog-Upload-Offset": `${status_.current}`
1649
+ };
1650
+ const body = blob.slice(startByte, endByte);
1651
+ if (body === null) {
1652
+ throw cannotSliceBlob();
1653
+ }
1654
+ function handler(xhr, text) {
1655
+ const uploadStatus = checkResumeHeader_(xhr, ["active", "final"]);
1656
+ const newCurrent = status_.current + bytesToUpload;
1657
+ const size = blob.size();
1658
+ let metadata;
1659
+ if (uploadStatus === "final") {
1660
+ metadata = metadataHandler(service, mappings)(xhr, text);
1661
+ } else {
1662
+ metadata = null;
1663
+ }
1664
+ return new ResumableUploadStatus(newCurrent, size, uploadStatus === "final", metadata);
1665
+ }
1666
+ const method = "POST";
1667
+ const timeout = service.maxUploadRetryTime;
1668
+ const requestInfo = new RequestInfo(url, method, handler, timeout);
1669
+ requestInfo.headers = headers;
1670
+ requestInfo.body = body.uploadData();
1671
+ requestInfo.progressCallback = progressCallback || null;
1672
+ requestInfo.errorHandler = sharedErrorHandler(location);
1673
+ return requestInfo;
1674
+ }
1675
+ /**
1676
+ * @license
1677
+ * Copyright 2017 Google LLC
1678
+ *
1679
+ * Licensed under the Apache License, Version 2.0 (the "License");
1680
+ * you may not use this file except in compliance with the License.
1681
+ * You may obtain a copy of the License at
1682
+ *
1683
+ * http://www.apache.org/licenses/LICENSE-2.0
1684
+ *
1685
+ * Unless required by applicable law or agreed to in writing, software
1686
+ * distributed under the License is distributed on an "AS IS" BASIS,
1687
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1688
+ * See the License for the specific language governing permissions and
1689
+ * limitations under the License.
1690
+ */
1691
+ const TaskEvent = {
1692
+ /**
1693
+ * For this event,
1694
+ * <ul>
1695
+ * <li>The `next` function is triggered on progress updates and when the
1696
+ * task is paused/resumed with an `UploadTaskSnapshot` as the first
1697
+ * argument.</li>
1698
+ * <li>The `error` function is triggered if the upload is canceled or fails
1699
+ * for another reason.</li>
1700
+ * <li>The `complete` function is triggered if the upload completes
1701
+ * successfully.</li>
1702
+ * </ul>
1703
+ */
1704
+ STATE_CHANGED: "state_changed"
1705
+ };
1706
+ const TaskState = {
1707
+ /** The task is currently transferring data. */
1708
+ RUNNING: "running",
1709
+ /** The task was paused by the user. */
1710
+ PAUSED: "paused",
1711
+ /** The task completed successfully. */
1712
+ SUCCESS: "success",
1713
+ /** The task was canceled. */
1714
+ CANCELED: "canceled",
1715
+ /** The task failed with an error. */
1716
+ ERROR: "error"
1717
+ };
1718
+ function taskStateFromInternalTaskState(state) {
1719
+ switch (state) {
1720
+ case "running":
1721
+ case "pausing":
1722
+ case "canceling":
1723
+ return TaskState.RUNNING;
1724
+ case "paused":
1725
+ return TaskState.PAUSED;
1726
+ case "success":
1727
+ return TaskState.SUCCESS;
1728
+ case "canceled":
1729
+ return TaskState.CANCELED;
1730
+ case "error":
1731
+ return TaskState.ERROR;
1732
+ default:
1733
+ return TaskState.ERROR;
1734
+ }
1735
+ }
1736
+ /**
1737
+ * @license
1738
+ * Copyright 2017 Google LLC
1739
+ *
1740
+ * Licensed under the Apache License, Version 2.0 (the "License");
1741
+ * you may not use this file except in compliance with the License.
1742
+ * You may obtain a copy of the License at
1743
+ *
1744
+ * http://www.apache.org/licenses/LICENSE-2.0
1745
+ *
1746
+ * Unless required by applicable law or agreed to in writing, software
1747
+ * distributed under the License is distributed on an "AS IS" BASIS,
1748
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1749
+ * See the License for the specific language governing permissions and
1750
+ * limitations under the License.
1751
+ */
1752
+ class Observer {
1753
+ constructor(nextOrObserver, error, complete) {
1754
+ const asFunctions = isFunction(nextOrObserver) || error != null || complete != null;
1755
+ if (asFunctions) {
1756
+ this.next = nextOrObserver;
1757
+ this.error = error !== null && error !== void 0 ? error : void 0;
1758
+ this.complete = complete !== null && complete !== void 0 ? complete : void 0;
1759
+ } else {
1760
+ const observer = nextOrObserver;
1761
+ this.next = observer.next;
1762
+ this.error = observer.error;
1763
+ this.complete = observer.complete;
1764
+ }
1765
+ }
1766
+ }
1767
+ /**
1768
+ * @license
1769
+ * Copyright 2017 Google LLC
1770
+ *
1771
+ * Licensed under the Apache License, Version 2.0 (the "License");
1772
+ * you may not use this file except in compliance with the License.
1773
+ * You may obtain a copy of the License at
1774
+ *
1775
+ * http://www.apache.org/licenses/LICENSE-2.0
1776
+ *
1777
+ * Unless required by applicable law or agreed to in writing, software
1778
+ * distributed under the License is distributed on an "AS IS" BASIS,
1779
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1780
+ * See the License for the specific language governing permissions and
1781
+ * limitations under the License.
1782
+ */
1783
+ function async(f) {
1784
+ return (...argsToForward) => {
1785
+ Promise.resolve().then(() => f(...argsToForward));
1786
+ };
1787
+ }
1788
+ class FetchConnection {
1789
+ constructor() {
1790
+ this.errorText_ = "";
1791
+ this.sent_ = false;
1792
+ this.errorCode_ = ErrorCode.NO_ERROR;
1793
+ }
1794
+ async send(url, method, isUsingEmulator, body, headers) {
1795
+ if (this.sent_) {
1796
+ throw internalError("cannot .send() more than once");
1797
+ }
1798
+ this.sent_ = true;
1799
+ try {
1800
+ const response = await newFetch(url, method, isUsingEmulator, headers, body);
1801
+ this.headers_ = response.headers;
1802
+ this.statusCode_ = response.status;
1803
+ this.errorCode_ = ErrorCode.NO_ERROR;
1804
+ this.body_ = await response.arrayBuffer();
1805
+ } catch (e) {
1806
+ this.errorText_ = e === null || e === void 0 ? void 0 : e.message;
1807
+ this.statusCode_ = 0;
1808
+ this.errorCode_ = ErrorCode.NETWORK_ERROR;
1809
+ }
1810
+ }
1811
+ getErrorCode() {
1812
+ if (this.errorCode_ === void 0) {
1813
+ throw internalError("cannot .getErrorCode() before receiving response");
1814
+ }
1815
+ return this.errorCode_;
1816
+ }
1817
+ getStatus() {
1818
+ if (this.statusCode_ === void 0) {
1819
+ throw internalError("cannot .getStatus() before receiving response");
1820
+ }
1821
+ return this.statusCode_;
1822
+ }
1823
+ getErrorText() {
1824
+ return this.errorText_;
1825
+ }
1826
+ abort() {
1827
+ }
1828
+ getResponseHeader(header) {
1829
+ if (!this.headers_) {
1830
+ throw internalError("cannot .getResponseHeader() before receiving response");
1831
+ }
1832
+ return this.headers_.get(header);
1833
+ }
1834
+ addUploadProgressListener(listener) {
1835
+ }
1836
+ removeUploadProgressListener(listener) {
1837
+ }
1838
+ }
1839
+ class FetchTextConnection extends FetchConnection {
1840
+ getResponse() {
1841
+ if (!this.body_) {
1842
+ throw internalError("cannot .getResponse() before receiving response");
1843
+ }
1844
+ return Buffer.from(this.body_).toString("utf-8");
1845
+ }
1846
+ }
1847
+ function newTextConnection() {
1848
+ return new FetchTextConnection();
1849
+ }
1850
+ class FetchBytesConnection extends FetchConnection {
1851
+ getResponse() {
1852
+ if (!this.body_) {
1853
+ throw internalError("cannot .getResponse() before sending");
1854
+ }
1855
+ return this.body_;
1856
+ }
1857
+ }
1858
+ function newBytesConnection() {
1859
+ return new FetchBytesConnection();
1860
+ }
1861
+ class FetchStreamConnection extends FetchConnection {
1862
+ constructor() {
1863
+ super(...arguments);
1864
+ this.stream_ = null;
1865
+ }
1866
+ async send(url, method, isUsingEmulator, body, headers) {
1867
+ if (this.sent_) {
1868
+ throw internalError("cannot .send() more than once");
1869
+ }
1870
+ this.sent_ = true;
1871
+ try {
1872
+ const response = await newFetch(url, method, isUsingEmulator, headers, body);
1873
+ this.headers_ = response.headers;
1874
+ this.statusCode_ = response.status;
1875
+ this.errorCode_ = ErrorCode.NO_ERROR;
1876
+ this.stream_ = response.body;
1877
+ } catch (e) {
1878
+ this.errorText_ = e === null || e === void 0 ? void 0 : e.message;
1879
+ this.statusCode_ = 0;
1880
+ this.errorCode_ = ErrorCode.NETWORK_ERROR;
1881
+ }
1882
+ }
1883
+ getResponse() {
1884
+ if (!this.stream_) {
1885
+ throw internalError("cannot .getResponse() before sending");
1886
+ }
1887
+ return this.stream_;
1888
+ }
1889
+ }
1890
+ function newFetch(url, method, isUsingEmulator, headers, body) {
1891
+ const fetchArgs = {
1892
+ method,
1893
+ headers: headers || {},
1894
+ body
1895
+ };
1896
+ if (isCloudWorkstation(url) && isUsingEmulator) {
1897
+ fetchArgs.credentials = "include";
1898
+ }
1899
+ return fetch(url, fetchArgs);
1900
+ }
1901
+ function newStreamConnection() {
1902
+ return new FetchStreamConnection();
1903
+ }
1904
+ /**
1905
+ * @license
1906
+ * Copyright 2017 Google LLC
1907
+ *
1908
+ * Licensed under the Apache License, Version 2.0 (the "License");
1909
+ * you may not use this file except in compliance with the License.
1910
+ * You may obtain a copy of the License at
1911
+ *
1912
+ * http://www.apache.org/licenses/LICENSE-2.0
1913
+ *
1914
+ * Unless required by applicable law or agreed to in writing, software
1915
+ * distributed under the License is distributed on an "AS IS" BASIS,
1916
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1917
+ * See the License for the specific language governing permissions and
1918
+ * limitations under the License.
1919
+ */
1920
+ class UploadTask {
1921
+ isExponentialBackoffExpired() {
1922
+ return this.sleepTime > this.maxSleepTime;
1923
+ }
1924
+ /**
1925
+ * @param ref - The firebaseStorage.Reference object this task came
1926
+ * from, untyped to avoid cyclic dependencies.
1927
+ * @param blob - The blob to upload.
1928
+ */
1929
+ constructor(ref2, blob, metadata = null) {
1930
+ this._transferred = 0;
1931
+ this._needToFetchStatus = false;
1932
+ this._needToFetchMetadata = false;
1933
+ this._observers = [];
1934
+ this._error = void 0;
1935
+ this._uploadUrl = void 0;
1936
+ this._request = void 0;
1937
+ this._chunkMultiplier = 1;
1938
+ this._resolve = void 0;
1939
+ this._reject = void 0;
1940
+ this._ref = ref2;
1941
+ this._blob = blob;
1942
+ this._metadata = metadata;
1943
+ this._mappings = getMappings();
1944
+ this._resumable = this._shouldDoResumable(this._blob);
1945
+ this._state = "running";
1946
+ this._errorHandler = (error) => {
1947
+ this._request = void 0;
1948
+ this._chunkMultiplier = 1;
1949
+ if (error._codeEquals(StorageErrorCode.CANCELED)) {
1950
+ this._needToFetchStatus = true;
1951
+ this.completeTransitions_();
1952
+ } else {
1953
+ const backoffExpired = this.isExponentialBackoffExpired();
1954
+ if (isRetryStatusCode(error.status, [])) {
1955
+ if (backoffExpired) {
1956
+ error = retryLimitExceeded();
1957
+ } else {
1958
+ this.sleepTime = Math.max(this.sleepTime * 2, DEFAULT_MIN_SLEEP_TIME_MILLIS);
1959
+ this._needToFetchStatus = true;
1960
+ this.completeTransitions_();
1961
+ return;
1962
+ }
1963
+ }
1964
+ this._error = error;
1965
+ this._transition(
1966
+ "error"
1967
+ /* InternalTaskState.ERROR */
1968
+ );
1969
+ }
1970
+ };
1971
+ this._metadataErrorHandler = (error) => {
1972
+ this._request = void 0;
1973
+ if (error._codeEquals(StorageErrorCode.CANCELED)) {
1974
+ this.completeTransitions_();
1975
+ } else {
1976
+ this._error = error;
1977
+ this._transition(
1978
+ "error"
1979
+ /* InternalTaskState.ERROR */
1980
+ );
1981
+ }
1982
+ };
1983
+ this.sleepTime = 0;
1984
+ this.maxSleepTime = this._ref.storage.maxUploadRetryTime;
1985
+ this._promise = new Promise((resolve, reject) => {
1986
+ this._resolve = resolve;
1987
+ this._reject = reject;
1988
+ this._start();
1989
+ });
1990
+ this._promise.then(null, () => {
1991
+ });
1992
+ }
1993
+ _makeProgressCallback() {
1994
+ const sizeBefore = this._transferred;
1995
+ return (loaded) => this._updateProgress(sizeBefore + loaded);
1996
+ }
1997
+ _shouldDoResumable(blob) {
1998
+ return blob.size() > 256 * 1024;
1999
+ }
2000
+ _start() {
2001
+ if (this._state !== "running") {
2002
+ return;
2003
+ }
2004
+ if (this._request !== void 0) {
2005
+ return;
2006
+ }
2007
+ if (this._resumable) {
2008
+ if (this._uploadUrl === void 0) {
2009
+ this._createResumable();
2010
+ } else {
2011
+ if (this._needToFetchStatus) {
2012
+ this._fetchStatus();
2013
+ } else {
2014
+ if (this._needToFetchMetadata) {
2015
+ this._fetchMetadata();
2016
+ } else {
2017
+ this.pendingTimeout = setTimeout(() => {
2018
+ this.pendingTimeout = void 0;
2019
+ this._continueUpload();
2020
+ }, this.sleepTime);
2021
+ }
2022
+ }
2023
+ }
2024
+ } else {
2025
+ this._oneShotUpload();
2026
+ }
2027
+ }
2028
+ _resolveToken(callback) {
2029
+ Promise.all([
2030
+ this._ref.storage._getAuthToken(),
2031
+ this._ref.storage._getAppCheckToken()
2032
+ ]).then(([authToken, appCheckToken]) => {
2033
+ switch (this._state) {
2034
+ case "running":
2035
+ callback(authToken, appCheckToken);
2036
+ break;
2037
+ case "canceling":
2038
+ this._transition(
2039
+ "canceled"
2040
+ /* InternalTaskState.CANCELED */
2041
+ );
2042
+ break;
2043
+ case "pausing":
2044
+ this._transition(
2045
+ "paused"
2046
+ /* InternalTaskState.PAUSED */
2047
+ );
2048
+ break;
2049
+ }
2050
+ });
2051
+ }
2052
+ // TODO(andysoto): assert false
2053
+ _createResumable() {
2054
+ this._resolveToken((authToken, appCheckToken) => {
2055
+ const requestInfo = createResumableUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);
2056
+ const createRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
2057
+ this._request = createRequest;
2058
+ createRequest.getPromise().then((url) => {
2059
+ this._request = void 0;
2060
+ this._uploadUrl = url;
2061
+ this._needToFetchStatus = false;
2062
+ this.completeTransitions_();
2063
+ }, this._errorHandler);
2064
+ });
2065
+ }
2066
+ _fetchStatus() {
2067
+ const url = this._uploadUrl;
2068
+ this._resolveToken((authToken, appCheckToken) => {
2069
+ const requestInfo = getResumableUploadStatus(this._ref.storage, this._ref._location, url, this._blob);
2070
+ const statusRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
2071
+ this._request = statusRequest;
2072
+ statusRequest.getPromise().then((status) => {
2073
+ status = status;
2074
+ this._request = void 0;
2075
+ this._updateProgress(status.current);
2076
+ this._needToFetchStatus = false;
2077
+ if (status.finalized) {
2078
+ this._needToFetchMetadata = true;
2079
+ }
2080
+ this.completeTransitions_();
2081
+ }, this._errorHandler);
2082
+ });
2083
+ }
2084
+ _continueUpload() {
2085
+ const chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
2086
+ const status = new ResumableUploadStatus(this._transferred, this._blob.size());
2087
+ const url = this._uploadUrl;
2088
+ this._resolveToken((authToken, appCheckToken) => {
2089
+ let requestInfo;
2090
+ try {
2091
+ requestInfo = continueResumableUpload(this._ref._location, this._ref.storage, url, this._blob, chunkSize, this._mappings, status, this._makeProgressCallback());
2092
+ } catch (e) {
2093
+ this._error = e;
2094
+ this._transition(
2095
+ "error"
2096
+ /* InternalTaskState.ERROR */
2097
+ );
2098
+ return;
2099
+ }
2100
+ const uploadRequest = this._ref.storage._makeRequest(
2101
+ requestInfo,
2102
+ newTextConnection,
2103
+ authToken,
2104
+ appCheckToken,
2105
+ /*retry=*/
2106
+ false
2107
+ // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.
2108
+ );
2109
+ this._request = uploadRequest;
2110
+ uploadRequest.getPromise().then((newStatus) => {
2111
+ this._increaseMultiplier();
2112
+ this._request = void 0;
2113
+ this._updateProgress(newStatus.current);
2114
+ if (newStatus.finalized) {
2115
+ this._metadata = newStatus.metadata;
2116
+ this._transition(
2117
+ "success"
2118
+ /* InternalTaskState.SUCCESS */
2119
+ );
2120
+ } else {
2121
+ this.completeTransitions_();
2122
+ }
2123
+ }, this._errorHandler);
2124
+ });
2125
+ }
2126
+ _increaseMultiplier() {
2127
+ const currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
2128
+ if (currentSize * 2 < 32 * 1024 * 1024) {
2129
+ this._chunkMultiplier *= 2;
2130
+ }
2131
+ }
2132
+ _fetchMetadata() {
2133
+ this._resolveToken((authToken, appCheckToken) => {
2134
+ const requestInfo = getMetadata$2(this._ref.storage, this._ref._location, this._mappings);
2135
+ const metadataRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
2136
+ this._request = metadataRequest;
2137
+ metadataRequest.getPromise().then((metadata) => {
2138
+ this._request = void 0;
2139
+ this._metadata = metadata;
2140
+ this._transition(
2141
+ "success"
2142
+ /* InternalTaskState.SUCCESS */
2143
+ );
2144
+ }, this._metadataErrorHandler);
2145
+ });
2146
+ }
2147
+ _oneShotUpload() {
2148
+ this._resolveToken((authToken, appCheckToken) => {
2149
+ const requestInfo = multipartUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);
2150
+ const multipartRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
2151
+ this._request = multipartRequest;
2152
+ multipartRequest.getPromise().then((metadata) => {
2153
+ this._request = void 0;
2154
+ this._metadata = metadata;
2155
+ this._updateProgress(this._blob.size());
2156
+ this._transition(
2157
+ "success"
2158
+ /* InternalTaskState.SUCCESS */
2159
+ );
2160
+ }, this._errorHandler);
2161
+ });
2162
+ }
2163
+ _updateProgress(transferred) {
2164
+ const old = this._transferred;
2165
+ this._transferred = transferred;
2166
+ if (this._transferred !== old) {
2167
+ this._notifyObservers();
2168
+ }
2169
+ }
2170
+ _transition(state) {
2171
+ if (this._state === state) {
2172
+ return;
2173
+ }
2174
+ switch (state) {
2175
+ case "canceling":
2176
+ case "pausing":
2177
+ this._state = state;
2178
+ if (this._request !== void 0) {
2179
+ this._request.cancel();
2180
+ } else if (this.pendingTimeout) {
2181
+ clearTimeout(this.pendingTimeout);
2182
+ this.pendingTimeout = void 0;
2183
+ this.completeTransitions_();
2184
+ }
2185
+ break;
2186
+ case "running":
2187
+ const wasPaused = this._state === "paused";
2188
+ this._state = state;
2189
+ if (wasPaused) {
2190
+ this._notifyObservers();
2191
+ this._start();
2192
+ }
2193
+ break;
2194
+ case "paused":
2195
+ this._state = state;
2196
+ this._notifyObservers();
2197
+ break;
2198
+ case "canceled":
2199
+ this._error = canceled();
2200
+ this._state = state;
2201
+ this._notifyObservers();
2202
+ break;
2203
+ case "error":
2204
+ this._state = state;
2205
+ this._notifyObservers();
2206
+ break;
2207
+ case "success":
2208
+ this._state = state;
2209
+ this._notifyObservers();
2210
+ break;
2211
+ }
2212
+ }
2213
+ completeTransitions_() {
2214
+ switch (this._state) {
2215
+ case "pausing":
2216
+ this._transition(
2217
+ "paused"
2218
+ /* InternalTaskState.PAUSED */
2219
+ );
2220
+ break;
2221
+ case "canceling":
2222
+ this._transition(
2223
+ "canceled"
2224
+ /* InternalTaskState.CANCELED */
2225
+ );
2226
+ break;
2227
+ case "running":
2228
+ this._start();
2229
+ break;
2230
+ }
2231
+ }
2232
+ /**
2233
+ * A snapshot of the current task state.
2234
+ */
2235
+ get snapshot() {
2236
+ const externalState = taskStateFromInternalTaskState(this._state);
2237
+ return {
2238
+ bytesTransferred: this._transferred,
2239
+ totalBytes: this._blob.size(),
2240
+ state: externalState,
2241
+ metadata: this._metadata,
2242
+ task: this,
2243
+ ref: this._ref
2244
+ };
2245
+ }
2246
+ /**
2247
+ * Adds a callback for an event.
2248
+ * @param type - The type of event to listen for.
2249
+ * @param nextOrObserver -
2250
+ * The `next` function, which gets called for each item in
2251
+ * the event stream, or an observer object with some or all of these three
2252
+ * properties (`next`, `error`, `complete`).
2253
+ * @param error - A function that gets called with a `StorageError`
2254
+ * if the event stream ends due to an error.
2255
+ * @param completed - A function that gets called if the
2256
+ * event stream ends normally.
2257
+ * @returns
2258
+ * If only the event argument is passed, returns a function you can use to
2259
+ * add callbacks (see the examples above). If more than just the event
2260
+ * argument is passed, returns a function you can call to unregister the
2261
+ * callbacks.
2262
+ */
2263
+ on(type, nextOrObserver, error, completed) {
2264
+ const observer = new Observer(nextOrObserver || void 0, error || void 0, completed || void 0);
2265
+ this._addObserver(observer);
2266
+ return () => {
2267
+ this._removeObserver(observer);
2268
+ };
2269
+ }
2270
+ /**
2271
+ * This object behaves like a Promise, and resolves with its snapshot data
2272
+ * when the upload completes.
2273
+ * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.
2274
+ * @param onRejected - The rejection callback.
2275
+ */
2276
+ then(onFulfilled, onRejected) {
2277
+ return this._promise.then(onFulfilled, onRejected);
2278
+ }
2279
+ /**
2280
+ * Equivalent to calling `then(null, onRejected)`.
2281
+ */
2282
+ catch(onRejected) {
2283
+ return this.then(null, onRejected);
2284
+ }
2285
+ /**
2286
+ * Adds the given observer.
2287
+ */
2288
+ _addObserver(observer) {
2289
+ this._observers.push(observer);
2290
+ this._notifyObserver(observer);
2291
+ }
2292
+ /**
2293
+ * Removes the given observer.
2294
+ */
2295
+ _removeObserver(observer) {
2296
+ const i = this._observers.indexOf(observer);
2297
+ if (i !== -1) {
2298
+ this._observers.splice(i, 1);
2299
+ }
2300
+ }
2301
+ _notifyObservers() {
2302
+ this._finishPromise();
2303
+ const observers = this._observers.slice();
2304
+ observers.forEach((observer) => {
2305
+ this._notifyObserver(observer);
2306
+ });
2307
+ }
2308
+ _finishPromise() {
2309
+ if (this._resolve !== void 0) {
2310
+ let triggered = true;
2311
+ switch (taskStateFromInternalTaskState(this._state)) {
2312
+ case TaskState.SUCCESS:
2313
+ async(this._resolve.bind(null, this.snapshot))();
2314
+ break;
2315
+ case TaskState.CANCELED:
2316
+ case TaskState.ERROR:
2317
+ const toCall = this._reject;
2318
+ async(toCall.bind(null, this._error))();
2319
+ break;
2320
+ default:
2321
+ triggered = false;
2322
+ break;
2323
+ }
2324
+ if (triggered) {
2325
+ this._resolve = void 0;
2326
+ this._reject = void 0;
2327
+ }
2328
+ }
2329
+ }
2330
+ _notifyObserver(observer) {
2331
+ const externalState = taskStateFromInternalTaskState(this._state);
2332
+ switch (externalState) {
2333
+ case TaskState.RUNNING:
2334
+ case TaskState.PAUSED:
2335
+ if (observer.next) {
2336
+ async(observer.next.bind(observer, this.snapshot))();
2337
+ }
2338
+ break;
2339
+ case TaskState.SUCCESS:
2340
+ if (observer.complete) {
2341
+ async(observer.complete.bind(observer))();
2342
+ }
2343
+ break;
2344
+ case TaskState.CANCELED:
2345
+ case TaskState.ERROR:
2346
+ if (observer.error) {
2347
+ async(observer.error.bind(observer, this._error))();
2348
+ }
2349
+ break;
2350
+ default:
2351
+ if (observer.error) {
2352
+ async(observer.error.bind(observer, this._error))();
2353
+ }
2354
+ }
2355
+ }
2356
+ /**
2357
+ * Resumes a paused task. Has no effect on a currently running or failed task.
2358
+ * @returns True if the operation took effect, false if ignored.
2359
+ */
2360
+ resume() {
2361
+ const valid = this._state === "paused" || this._state === "pausing";
2362
+ if (valid) {
2363
+ this._transition(
2364
+ "running"
2365
+ /* InternalTaskState.RUNNING */
2366
+ );
2367
+ }
2368
+ return valid;
2369
+ }
2370
+ /**
2371
+ * Pauses a currently running task. Has no effect on a paused or failed task.
2372
+ * @returns True if the operation took effect, false if ignored.
2373
+ */
2374
+ pause() {
2375
+ const valid = this._state === "running";
2376
+ if (valid) {
2377
+ this._transition(
2378
+ "pausing"
2379
+ /* InternalTaskState.PAUSING */
2380
+ );
2381
+ }
2382
+ return valid;
2383
+ }
2384
+ /**
2385
+ * Cancels a currently running or paused task. Has no effect on a complete or
2386
+ * failed task.
2387
+ * @returns True if the operation took effect, false if ignored.
2388
+ */
2389
+ cancel() {
2390
+ const valid = this._state === "running" || this._state === "pausing";
2391
+ if (valid) {
2392
+ this._transition(
2393
+ "canceling"
2394
+ /* InternalTaskState.CANCELING */
2395
+ );
2396
+ }
2397
+ return valid;
2398
+ }
2399
+ }
2400
+ /**
2401
+ * @license
2402
+ * Copyright 2019 Google LLC
2403
+ *
2404
+ * Licensed under the Apache License, Version 2.0 (the "License");
2405
+ * you may not use this file except in compliance with the License.
2406
+ * You may obtain a copy of the License at
2407
+ *
2408
+ * http://www.apache.org/licenses/LICENSE-2.0
2409
+ *
2410
+ * Unless required by applicable law or agreed to in writing, software
2411
+ * distributed under the License is distributed on an "AS IS" BASIS,
2412
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2413
+ * See the License for the specific language governing permissions and
2414
+ * limitations under the License.
2415
+ */
2416
+ class Reference {
2417
+ constructor(_service, location) {
2418
+ this._service = _service;
2419
+ if (location instanceof Location) {
2420
+ this._location = location;
2421
+ } else {
2422
+ this._location = Location.makeFromUrl(location, _service.host);
2423
+ }
2424
+ }
2425
+ /**
2426
+ * Returns the URL for the bucket and path this object references,
2427
+ * in the form gs://<bucket>/<object-path>
2428
+ * @override
2429
+ */
2430
+ toString() {
2431
+ return "gs://" + this._location.bucket + "/" + this._location.path;
2432
+ }
2433
+ _newRef(service, location) {
2434
+ return new Reference(service, location);
2435
+ }
2436
+ /**
2437
+ * A reference to the root of this object's bucket.
2438
+ */
2439
+ get root() {
2440
+ const location = new Location(this._location.bucket, "");
2441
+ return this._newRef(this._service, location);
2442
+ }
2443
+ /**
2444
+ * The name of the bucket containing this reference's object.
2445
+ */
2446
+ get bucket() {
2447
+ return this._location.bucket;
2448
+ }
2449
+ /**
2450
+ * The full path of this object.
2451
+ */
2452
+ get fullPath() {
2453
+ return this._location.path;
2454
+ }
2455
+ /**
2456
+ * The short name of this object, which is the last component of the full path.
2457
+ * For example, if fullPath is 'full/path/image.png', name is 'image.png'.
2458
+ */
2459
+ get name() {
2460
+ return lastComponent(this._location.path);
2461
+ }
2462
+ /**
2463
+ * The `StorageService` instance this `StorageReference` is associated with.
2464
+ */
2465
+ get storage() {
2466
+ return this._service;
2467
+ }
2468
+ /**
2469
+ * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if
2470
+ * this reference is the root.
2471
+ */
2472
+ get parent() {
2473
+ const newPath = parent(this._location.path);
2474
+ if (newPath === null) {
2475
+ return null;
2476
+ }
2477
+ const location = new Location(this._location.bucket, newPath);
2478
+ return new Reference(this._service, location);
2479
+ }
2480
+ /**
2481
+ * Utility function to throw an error in methods that do not accept a root reference.
2482
+ */
2483
+ _throwIfRoot(name2) {
2484
+ if (this._location.path === "") {
2485
+ throw invalidRootOperation(name2);
2486
+ }
2487
+ }
2488
+ }
2489
+ function getBytesInternal(ref2, maxDownloadSizeBytes) {
2490
+ ref2._throwIfRoot("getBytes");
2491
+ const requestInfo = getBytes$1(ref2.storage, ref2._location, maxDownloadSizeBytes);
2492
+ return ref2.storage.makeRequestWithTokens(requestInfo, newBytesConnection).then((bytes) => maxDownloadSizeBytes !== void 0 ? (
2493
+ // GCS may not honor the Range header for small files
2494
+ bytes.slice(0, maxDownloadSizeBytes)
2495
+ ) : bytes);
2496
+ }
2497
+ function getStreamInternal(ref2, maxDownloadSizeBytes) {
2498
+ ref2._throwIfRoot("getStream");
2499
+ const requestInfo = getBytes$1(ref2.storage, ref2._location, maxDownloadSizeBytes);
2500
+ const newMaxSizeTransform = (n) => {
2501
+ let missingBytes = n;
2502
+ return {
2503
+ transform(chunk, controller) {
2504
+ if (chunk.length < missingBytes) {
2505
+ controller.enqueue(chunk);
2506
+ missingBytes -= chunk.length;
2507
+ } else {
2508
+ controller.enqueue(chunk.slice(0, missingBytes));
2509
+ controller.terminate();
2510
+ }
2511
+ }
2512
+ };
2513
+ };
2514
+ const result = maxDownloadSizeBytes !== void 0 ? new TransformStream(newMaxSizeTransform(maxDownloadSizeBytes)) : new TransformStream();
2515
+ ref2.storage.makeRequestWithTokens(requestInfo, newStreamConnection).then((readableStream) => readableStream.pipeThrough(result)).catch((err) => result.writable.abort(err));
2516
+ return result.readable;
2517
+ }
2518
+ function uploadBytes$1(ref2, data, metadata) {
2519
+ ref2._throwIfRoot("uploadBytes");
2520
+ const requestInfo = multipartUpload(ref2.storage, ref2._location, getMappings(), new FbsBlob(data, true), metadata);
2521
+ return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection).then((finalMetadata) => {
2522
+ return {
2523
+ metadata: finalMetadata,
2524
+ ref: ref2
2525
+ };
2526
+ });
2527
+ }
2528
+ function uploadBytesResumable$1(ref2, data, metadata) {
2529
+ ref2._throwIfRoot("uploadBytesResumable");
2530
+ return new UploadTask(ref2, new FbsBlob(data), metadata);
2531
+ }
2532
+ function uploadString$1(ref2, value, format = StringFormat.RAW, metadata) {
2533
+ ref2._throwIfRoot("uploadString");
2534
+ const data = dataFromString(format, value);
2535
+ const metadataClone = Object.assign({}, metadata);
2536
+ if (metadataClone["contentType"] == null && data.contentType != null) {
2537
+ metadataClone["contentType"] = data.contentType;
2538
+ }
2539
+ return uploadBytes$1(ref2, data.data, metadataClone);
2540
+ }
2541
+ function listAll$1(ref2) {
2542
+ const accumulator = {
2543
+ prefixes: [],
2544
+ items: []
2545
+ };
2546
+ return listAllHelper(ref2, accumulator).then(() => accumulator);
2547
+ }
2548
+ async function listAllHelper(ref2, accumulator, pageToken) {
2549
+ const opt = {
2550
+ // maxResults is 1000 by default.
2551
+ pageToken
2552
+ };
2553
+ const nextPage = await list$1(ref2, opt);
2554
+ accumulator.prefixes.push(...nextPage.prefixes);
2555
+ accumulator.items.push(...nextPage.items);
2556
+ if (nextPage.nextPageToken != null) {
2557
+ await listAllHelper(ref2, accumulator, nextPage.nextPageToken);
2558
+ }
2559
+ }
2560
+ function list$1(ref2, options) {
2561
+ if (options != null) {
2562
+ if (typeof options.maxResults === "number") {
2563
+ validateNumber(
2564
+ "options.maxResults",
2565
+ /* minValue= */
2566
+ 1,
2567
+ /* maxValue= */
2568
+ 1e3,
2569
+ options.maxResults
2570
+ );
2571
+ }
2572
+ }
2573
+ const op = options || {};
2574
+ const requestInfo = list$2(
2575
+ ref2.storage,
2576
+ ref2._location,
2577
+ /*delimiter= */
2578
+ "/",
2579
+ op.pageToken,
2580
+ op.maxResults
2581
+ );
2582
+ return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
2583
+ }
2584
+ function getMetadata$1(ref2) {
2585
+ ref2._throwIfRoot("getMetadata");
2586
+ const requestInfo = getMetadata$2(ref2.storage, ref2._location, getMappings());
2587
+ return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
2588
+ }
2589
+ function updateMetadata$1(ref2, metadata) {
2590
+ ref2._throwIfRoot("updateMetadata");
2591
+ const requestInfo = updateMetadata$2(ref2.storage, ref2._location, metadata, getMappings());
2592
+ return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
2593
+ }
2594
+ function getDownloadURL$1(ref2) {
2595
+ ref2._throwIfRoot("getDownloadURL");
2596
+ const requestInfo = getDownloadUrl(ref2.storage, ref2._location, getMappings());
2597
+ return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection).then((url) => {
2598
+ if (url === null) {
2599
+ throw noDownloadURL();
2600
+ }
2601
+ return url;
2602
+ });
2603
+ }
2604
+ function deleteObject$1(ref2) {
2605
+ ref2._throwIfRoot("deleteObject");
2606
+ const requestInfo = deleteObject$2(ref2.storage, ref2._location);
2607
+ return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
2608
+ }
2609
+ function _getChild$1(ref2, childPath) {
2610
+ const newPath = child(ref2._location.path, childPath);
2611
+ const location = new Location(ref2._location.bucket, newPath);
2612
+ return new Reference(ref2.storage, location);
2613
+ }
2614
+ /**
2615
+ * @license
2616
+ * Copyright 2017 Google LLC
2617
+ *
2618
+ * Licensed under the Apache License, Version 2.0 (the "License");
2619
+ * you may not use this file except in compliance with the License.
2620
+ * You may obtain a copy of the License at
2621
+ *
2622
+ * http://www.apache.org/licenses/LICENSE-2.0
2623
+ *
2624
+ * Unless required by applicable law or agreed to in writing, software
2625
+ * distributed under the License is distributed on an "AS IS" BASIS,
2626
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2627
+ * See the License for the specific language governing permissions and
2628
+ * limitations under the License.
2629
+ */
2630
+ function isUrl(path) {
2631
+ return /^[A-Za-z]+:\/\//.test(path);
2632
+ }
2633
+ function refFromURL(service, url) {
2634
+ return new Reference(service, url);
2635
+ }
2636
+ function refFromPath(ref2, path) {
2637
+ if (ref2 instanceof FirebaseStorageImpl) {
2638
+ const service = ref2;
2639
+ if (service._bucket == null) {
2640
+ throw noDefaultBucket();
2641
+ }
2642
+ const reference = new Reference(service, service._bucket);
2643
+ if (path != null) {
2644
+ return refFromPath(reference, path);
2645
+ } else {
2646
+ return reference;
2647
+ }
2648
+ } else {
2649
+ if (path !== void 0) {
2650
+ return _getChild$1(ref2, path);
2651
+ } else {
2652
+ return ref2;
2653
+ }
2654
+ }
2655
+ }
2656
+ function ref$1(serviceOrRef, pathOrUrl) {
2657
+ if (pathOrUrl && isUrl(pathOrUrl)) {
2658
+ if (serviceOrRef instanceof FirebaseStorageImpl) {
2659
+ return refFromURL(serviceOrRef, pathOrUrl);
2660
+ } else {
2661
+ throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.");
2662
+ }
2663
+ } else {
2664
+ return refFromPath(serviceOrRef, pathOrUrl);
2665
+ }
2666
+ }
2667
+ function extractBucket(host, config) {
2668
+ const bucketString = config === null || config === void 0 ? void 0 : config[CONFIG_STORAGE_BUCKET_KEY];
2669
+ if (bucketString == null) {
2670
+ return null;
2671
+ }
2672
+ return Location.makeFromBucketSpec(bucketString, host);
2673
+ }
2674
+ function connectStorageEmulator$1(storage, host, port, options = {}) {
2675
+ storage.host = `${host}:${port}`;
2676
+ const useSsl = isCloudWorkstation(host);
2677
+ if (useSsl) {
2678
+ void pingServer(`https://${storage.host}/b`);
2679
+ updateEmulatorBanner("Storage", true);
2680
+ }
2681
+ storage._isUsingEmulator = true;
2682
+ storage._protocol = useSsl ? "https" : "http";
2683
+ const { mockUserToken } = options;
2684
+ if (mockUserToken) {
2685
+ storage._overrideAuthToken = typeof mockUserToken === "string" ? mockUserToken : createMockUserToken(mockUserToken, storage.app.options.projectId);
2686
+ }
2687
+ }
2688
+ class FirebaseStorageImpl {
2689
+ constructor(app, _authProvider, _appCheckProvider, _url, _firebaseVersion, _isUsingEmulator = false) {
2690
+ this.app = app;
2691
+ this._authProvider = _authProvider;
2692
+ this._appCheckProvider = _appCheckProvider;
2693
+ this._url = _url;
2694
+ this._firebaseVersion = _firebaseVersion;
2695
+ this._isUsingEmulator = _isUsingEmulator;
2696
+ this._bucket = null;
2697
+ this._host = DEFAULT_HOST;
2698
+ this._protocol = "https";
2699
+ this._appId = null;
2700
+ this._deleted = false;
2701
+ this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;
2702
+ this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;
2703
+ this._requests = /* @__PURE__ */ new Set();
2704
+ if (_url != null) {
2705
+ this._bucket = Location.makeFromBucketSpec(_url, this._host);
2706
+ } else {
2707
+ this._bucket = extractBucket(this._host, this.app.options);
2708
+ }
2709
+ }
2710
+ /**
2711
+ * The host string for this service, in the form of `host` or
2712
+ * `host:port`.
2713
+ */
2714
+ get host() {
2715
+ return this._host;
2716
+ }
2717
+ set host(host) {
2718
+ this._host = host;
2719
+ if (this._url != null) {
2720
+ this._bucket = Location.makeFromBucketSpec(this._url, host);
2721
+ } else {
2722
+ this._bucket = extractBucket(host, this.app.options);
2723
+ }
2724
+ }
2725
+ /**
2726
+ * The maximum time to retry uploads in milliseconds.
2727
+ */
2728
+ get maxUploadRetryTime() {
2729
+ return this._maxUploadRetryTime;
2730
+ }
2731
+ set maxUploadRetryTime(time) {
2732
+ validateNumber(
2733
+ "time",
2734
+ /* minValue=*/
2735
+ 0,
2736
+ /* maxValue= */
2737
+ Number.POSITIVE_INFINITY,
2738
+ time
2739
+ );
2740
+ this._maxUploadRetryTime = time;
2741
+ }
2742
+ /**
2743
+ * The maximum time to retry operations other than uploads or downloads in
2744
+ * milliseconds.
2745
+ */
2746
+ get maxOperationRetryTime() {
2747
+ return this._maxOperationRetryTime;
2748
+ }
2749
+ set maxOperationRetryTime(time) {
2750
+ validateNumber(
2751
+ "time",
2752
+ /* minValue=*/
2753
+ 0,
2754
+ /* maxValue= */
2755
+ Number.POSITIVE_INFINITY,
2756
+ time
2757
+ );
2758
+ this._maxOperationRetryTime = time;
2759
+ }
2760
+ async _getAuthToken() {
2761
+ if (this._overrideAuthToken) {
2762
+ return this._overrideAuthToken;
2763
+ }
2764
+ const auth = this._authProvider.getImmediate({ optional: true });
2765
+ if (auth) {
2766
+ const tokenData = await auth.getToken();
2767
+ if (tokenData !== null) {
2768
+ return tokenData.accessToken;
2769
+ }
2770
+ }
2771
+ return null;
2772
+ }
2773
+ async _getAppCheckToken() {
2774
+ if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {
2775
+ return this.app.settings.appCheckToken;
2776
+ }
2777
+ const appCheck = this._appCheckProvider.getImmediate({ optional: true });
2778
+ if (appCheck) {
2779
+ const result = await appCheck.getToken();
2780
+ return result.token;
2781
+ }
2782
+ return null;
2783
+ }
2784
+ /**
2785
+ * Stop running requests and prevent more from being created.
2786
+ */
2787
+ _delete() {
2788
+ if (!this._deleted) {
2789
+ this._deleted = true;
2790
+ this._requests.forEach((request) => request.cancel());
2791
+ this._requests.clear();
2792
+ }
2793
+ return Promise.resolve();
2794
+ }
2795
+ /**
2796
+ * Returns a new firebaseStorage.Reference object referencing this StorageService
2797
+ * at the given Location.
2798
+ */
2799
+ _makeStorageReference(loc) {
2800
+ return new Reference(this, loc);
2801
+ }
2802
+ /**
2803
+ * @param requestInfo - HTTP RequestInfo object
2804
+ * @param authToken - Firebase auth token
2805
+ */
2806
+ _makeRequest(requestInfo, requestFactory, authToken, appCheckToken, retry = true) {
2807
+ if (!this._deleted) {
2808
+ const request = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry, this._isUsingEmulator);
2809
+ this._requests.add(request);
2810
+ request.getPromise().then(() => this._requests.delete(request), () => this._requests.delete(request));
2811
+ return request;
2812
+ } else {
2813
+ return new FailRequest(appDeleted());
2814
+ }
2815
+ }
2816
+ async makeRequestWithTokens(requestInfo, requestFactory) {
2817
+ const [authToken, appCheckToken] = await Promise.all([
2818
+ this._getAuthToken(),
2819
+ this._getAppCheckToken()
2820
+ ]);
2821
+ return this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise();
2822
+ }
2823
+ }
2824
+ const name = "@firebase/storage";
2825
+ const version = "0.13.14";
2826
+ /**
2827
+ * @license
2828
+ * Copyright 2020 Google LLC
2829
+ *
2830
+ * Licensed under the Apache License, Version 2.0 (the "License");
2831
+ * you may not use this file except in compliance with the License.
2832
+ * You may obtain a copy of the License at
2833
+ *
2834
+ * http://www.apache.org/licenses/LICENSE-2.0
2835
+ *
2836
+ * Unless required by applicable law or agreed to in writing, software
2837
+ * distributed under the License is distributed on an "AS IS" BASIS,
2838
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2839
+ * See the License for the specific language governing permissions and
2840
+ * limitations under the License.
2841
+ */
2842
+ const STORAGE_TYPE = "storage";
2843
+ /**
2844
+ * @license
2845
+ * Copyright 2020 Google LLC
2846
+ *
2847
+ * Licensed under the Apache License, Version 2.0 (the "License");
2848
+ * you may not use this file except in compliance with the License.
2849
+ * You may obtain a copy of the License at
2850
+ *
2851
+ * http://www.apache.org/licenses/LICENSE-2.0
2852
+ *
2853
+ * Unless required by applicable law or agreed to in writing, software
2854
+ * distributed under the License is distributed on an "AS IS" BASIS,
2855
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2856
+ * See the License for the specific language governing permissions and
2857
+ * limitations under the License.
2858
+ */
2859
+ function getBytes(ref2, maxDownloadSizeBytes) {
2860
+ ref2 = getModularInstance(ref2);
2861
+ return getBytesInternal(ref2, maxDownloadSizeBytes);
2862
+ }
2863
+ function uploadBytes(ref2, data, metadata) {
2864
+ ref2 = getModularInstance(ref2);
2865
+ return uploadBytes$1(ref2, data, metadata);
2866
+ }
2867
+ function uploadString(ref2, value, format, metadata) {
2868
+ ref2 = getModularInstance(ref2);
2869
+ return uploadString$1(ref2, value, format, metadata);
2870
+ }
2871
+ function uploadBytesResumable(ref2, data, metadata) {
2872
+ ref2 = getModularInstance(ref2);
2873
+ return uploadBytesResumable$1(ref2, data, metadata);
2874
+ }
2875
+ function getMetadata(ref2) {
2876
+ ref2 = getModularInstance(ref2);
2877
+ return getMetadata$1(ref2);
2878
+ }
2879
+ function updateMetadata(ref2, metadata) {
2880
+ ref2 = getModularInstance(ref2);
2881
+ return updateMetadata$1(ref2, metadata);
2882
+ }
2883
+ function list(ref2, options) {
2884
+ ref2 = getModularInstance(ref2);
2885
+ return list$1(ref2, options);
2886
+ }
2887
+ function listAll(ref2) {
2888
+ ref2 = getModularInstance(ref2);
2889
+ return listAll$1(ref2);
2890
+ }
2891
+ function getDownloadURL(ref2) {
2892
+ ref2 = getModularInstance(ref2);
2893
+ return getDownloadURL$1(ref2);
2894
+ }
2895
+ function deleteObject(ref2) {
2896
+ ref2 = getModularInstance(ref2);
2897
+ return deleteObject$1(ref2);
2898
+ }
2899
+ function ref(serviceOrRef, pathOrUrl) {
2900
+ serviceOrRef = getModularInstance(serviceOrRef);
2901
+ return ref$1(serviceOrRef, pathOrUrl);
2902
+ }
2903
+ function _getChild(ref2, childPath) {
2904
+ return _getChild$1(ref2, childPath);
2905
+ }
2906
+ function getStorage(app = getApp(), bucketUrl) {
2907
+ app = getModularInstance(app);
2908
+ const storageProvider = _getProvider(app, STORAGE_TYPE);
2909
+ const storageInstance = storageProvider.getImmediate({
2910
+ identifier: bucketUrl
2911
+ });
2912
+ const emulator = getDefaultEmulatorHostnameAndPort("storage");
2913
+ if (emulator) {
2914
+ connectStorageEmulator(storageInstance, ...emulator);
2915
+ }
2916
+ return storageInstance;
2917
+ }
2918
+ function connectStorageEmulator(storage, host, port, options = {}) {
2919
+ connectStorageEmulator$1(storage, host, port, options);
2920
+ }
2921
+ /**
2922
+ * @license
2923
+ * Copyright 2021 Google LLC
2924
+ *
2925
+ * Licensed under the Apache License, Version 2.0 (the "License");
2926
+ * you may not use this file except in compliance with the License.
2927
+ * You may obtain a copy of the License at
2928
+ *
2929
+ * http://www.apache.org/licenses/LICENSE-2.0
2930
+ *
2931
+ * Unless required by applicable law or agreed to in writing, software
2932
+ * distributed under the License is distributed on an "AS IS" BASIS,
2933
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2934
+ * See the License for the specific language governing permissions and
2935
+ * limitations under the License.
2936
+ */
2937
+ function getBlob(ref2, maxDownloadSizeBytes) {
2938
+ throw new Error("getBlob() is only available in Browser-like environments");
2939
+ }
2940
+ function getStream(ref2, maxDownloadSizeBytes) {
2941
+ ref2 = getModularInstance(ref2);
2942
+ return getStreamInternal(ref2, maxDownloadSizeBytes);
2943
+ }
2944
+ function factory(container, { instanceIdentifier: url }) {
2945
+ const app = container.getProvider("app").getImmediate();
2946
+ const authProvider = container.getProvider("auth-internal");
2947
+ const appCheckProvider = container.getProvider("app-check-internal");
2948
+ return new FirebaseStorageImpl(app, authProvider, appCheckProvider, url, SDK_VERSION);
2949
+ }
2950
+ function registerStorage() {
2951
+ _registerComponent(new Component(
2952
+ STORAGE_TYPE,
2953
+ factory,
2954
+ "PUBLIC"
2955
+ /* ComponentType.PUBLIC */
2956
+ ).setMultipleInstances(true));
2957
+ registerVersion(name, version);
2958
+ }
2959
+ registerStorage();
2960
+ export {
2961
+ StorageError,
2962
+ StorageErrorCode,
2963
+ StringFormat,
2964
+ FbsBlob as _FbsBlob,
2965
+ Location as _Location,
2966
+ TaskEvent as _TaskEvent,
2967
+ TaskState as _TaskState,
2968
+ UploadTask as _UploadTask,
2969
+ dataFromString as _dataFromString,
2970
+ _getChild,
2971
+ invalidArgument as _invalidArgument,
2972
+ invalidRootOperation as _invalidRootOperation,
2973
+ connectStorageEmulator,
2974
+ deleteObject,
2975
+ getBlob,
2976
+ getBytes,
2977
+ getDownloadURL,
2978
+ getMetadata,
2979
+ getStorage,
2980
+ getStream,
2981
+ list,
2982
+ listAll,
2983
+ ref,
2984
+ updateMetadata,
2985
+ uploadBytes,
2986
+ uploadBytesResumable,
2987
+ uploadString
2988
+ };