PageSourceSearch

https://elixir-dr.eka.care/stetho/main/shared/firebase/firestore.js

js eka.care collected 2026-10-01 15:08:22 UTC 798,161 bytes, 21,017 lines download raw bytes

1import { L as Logger, h as _registerComponent, C as Component, r as registerVersion, g as _isFirebaseServerApp, F as FirebaseError, q as LogLevel, t as getModularInstance, u as deepEqual, v as isCloudWorkstation, w as pingServer, x as updateEmulatorBanner, y as createMockUserToken, l as getApp, e as _getProvider, z as getDefaultEmulatorHostnameAndPort, i as _removeServiceInstance, A as getGlobal, B as isIndexedDBAvailable, E as getUA, G as isSafari, H as isSafariOrWebkit, S as SDK_VERSION } from "./chunks/index.esm2017-DLIaLXO3.js";
2var commonjsGlobal$1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : {};
3/** @license
4Copyright The Closure Library Authors.
5SPDX-License-Identifier: Apache-2.0
6*/
7var Integer;
8var Md5;
9(function() {
10  var h;
11  /** @license
12  
13   Copyright The Closure Library Authors.
14   SPDX-License-Identifier: Apache-2.0
15  */
16  function k2(f, a) {
17    function c() {
18    }
19    c.prototype = a.prototype;
20    f.D = a.prototype;
21    f.prototype = new c();
22    f.prototype.constructor = f;
23    f.C = function(d, e, g) {
24      for (var b = Array(arguments.length - 2), r = 2; r < arguments.length; r++) b[r - 2] = arguments[r];
25      return a.prototype[e].apply(d, b);
26    };
27  }
28  function l() {
29    this.blockSize = -1;
30  }
31  function m() {
32    this.blockSize = -1;
33    this.blockSize = 64;
34    this.g = Array(4);
35    this.B = Array(this.blockSize);
36    this.o = this.h = 0;
37    this.s();
38  }
39  k2(m, l);
40  m.prototype.s = function() {
41    this.g[0] = 1732584193;
42    this.g[1] = 4023233417;
43    this.g[2] = 2562383102;
44    this.g[3] = 271733878;
45    this.o = this.h = 0;
46  };
47  function n(f, a, c) {
48    c || (c = 0);
49    var d = Array(16);
50    if ("string" === typeof a) for (var e = 0; 16 > e; ++e) d[e] = a.charCodeAt(c++) | a.charCodeAt(c++) << 8 | a.charCodeAt(c++) << 16 | a.charCodeAt(c++) << 24;
51    else for (e = 0; 16 > e; ++e) d[e] = a[c++] | a[c++] << 8 | a[c++] << 16 | a[c++] << 24;
52    a = f.g[0];
53    c = f.g[1];
54    e = f.g[2];
55    var g = f.g[3];
56    var b = a + (g ^ c & (e ^ g)) + d[0] + 3614090360 & 4294967295;
57    a = c + (b << 7 & 4294967295 | b >>> 25);
58    b = g + (e ^ a & (c ^ e)) + d[1] + 3905402710 & 4294967295;
59    g = a + (b << 12 & 4294967295 | b >>> 20);
60    b = e + (c ^ g & (a ^ c)) + d[2] + 606105819 & 4294967295;
61    e = g + (b << 17 & 4294967295 | b >>> 15);
62    b = c + (a ^ e & (g ^ a)) + d[3] + 3250441966 & 4294967295;
63    c = e + (b << 22 & 4294967295 | b >>> 10);
64    b = a + (g ^ c & (e ^ g)) + d[4] + 4118548399 & 4294967295;
65    a = c + (b << 7 & 4294967295 | b >>> 25);
66    b = g + (e ^ a & (c ^ e)) + d[5] + 1200080426 & 4294967295;
67    g = a + (b << 12 & 4294967295 | b >>> 20);
68    b = e + (c ^ g & (a ^ c)) + d[6] + 2821735955 & 4294967295;
69    e = g + (b << 17 & 4294967295 | b >>> 15);
70    b = c + (a ^ e & (g ^ a)) + d[7] + 4249261313 & 4294967295;
71    c = e + (b << 22 & 4294967295 | b >>> 10);
72    b = a + (g ^ c & (e ^ g)) + d[8] + 1770035416 & 4294967295;
73    a = c + (b << 7 & 4294967295 | b >>> 25);
74    b = g + (e ^ a & (c ^ e)) + d[9] + 2336552879 & 4294967295;
75    g = a + (b << 12 & 4294967295 | b >>> 20);
76    b = e + (c ^ g & (a ^ c)) + d[10] + 4294925233 & 4294967295;
77    e = g + (b << 17 & 4294967295 | b >>> 15);
78    b = c + (a ^ e & (g ^ a)) + d[11] + 2304563134 & 4294967295;
79    c = e + (b << 22 & 4294967295 | b >>> 10);
80    b = a + (g ^ c & (e ^ g)) + d[12] + 1804603682 & 4294967295;
81    a = c + (b << 7 & 4294967295 | b >>> 25);
82    b = g + (e ^ a & (c ^ e)) + d[13] + 4254626195 & 4294967295;
83    g = a + (b << 12 & 4294967295 | b >>> 20);
84    b = e + (c ^ g & (a ^ c)) + d[14] + 2792965006 & 4294967295;
85    e = g + (b << 17 & 4294967295 | b >>> 15);
86    b = c + (a ^ e & (g ^ a)) + d[15] + 1236535329 & 4294967295;
87    c = e + (b << 22 & 4294967295 | b >>> 10);
88    b = a + (e ^ g & (c ^ e)) + d[1] + 4129170786 & 4294967295;
89    a = c + (b << 5 & 4294967295 | b >>> 27);
90    b = g + (c ^ e & (a ^ c)) + d[6] + 3225465664 & 4294967295;
91    g = a + (b << 9 & 4294967295 | b >>> 23);
92    b = e + (a ^ c & (g ^ a)) + d[11] + 643717713 & 4294967295;
93    e = g + (b << 14 & 4294967295 | b >>> 18);
94    b = c + (g ^ a & (e ^ g)) + d[0] + 3921069994 & 4294967295;
95    c = e + (b << 20 & 4294967295 | b >>> 12);
96    b = a + (e ^ g & (c ^ e)) + d[5] + 3593408605 & 4294967295;
97    a = c + (b << 5 & 4294967295 | b >>> 27);
98    b = g + (c ^ e & (a ^ c)) + d[10] + 38016083 & 4294967295;
99    g = a + (b << 9 & 4294967295 | b >>> 23);
100    b = e + (a ^ c & (g ^ a)) + d[15] + 3634488961 & 4294967295;
101    e = g + (b << 14 & 4294967295 | b >>> 18);
102    b = c + (g ^ a & (e ^ g)) + d[4] + 3889429448 & 4294967295;
103    c = e + (b << 20 & 4294967295 | b >>> 12);
104    b = a + (e ^ g & (c ^ e)) + d[9] + 568446438 & 4294967295;
105    a = c + (b << 5 & 4294967295 | b >>> 27);
106    b = g + (c ^ e & (a ^ c)) + d[14] + 3275163606 & 4294967295;
107    g = a + (b << 9 & 4294967295 | b >>> 23);
108    b = e + (a ^ c & (g ^ a)) + d[3] + 4107603335 & 4294967295;
109    e = g + (b << 14 & 4294967295 | b >>> 18);
110    b = c + (g ^ a & (e ^ g)) + d[8] + 1163531501 & 4294967295;
111    c = e + (b << 20 & 4294967295 | b >>> 12);
112    b = a + (e ^ g & (c ^ e)) + d[13] + 2850285829 & 4294967295;
113    a = c + (b << 5 & 4294967295 | b >>> 27);
114    b = g + (c ^ e & (a ^ c)) + d[2] + 4243563512 & 4294967295;
115    g = a + (b << 9 & 4294967295 | b >>> 23);
116    b = e + (a ^ c & (g ^ a)) + d[7] + 1735328473 & 4294967295;
117    e = g + (b << 14 & 4294967295 | b >>> 18);
118    b = c + (g ^ a & (e ^ g)) + d[12] + 2368359562 & 4294967295;
119    c = e + (b << 20 & 4294967295 | b >>> 12);
120    b = a + (c ^ e ^ g) + d[5] + 4294588738 & 4294967295;
121    a = c + (b << 4 & 4294967295 | b >>> 28);
122    b = g + (a ^ c ^ e) + d[8] + 2272392833 & 4294967295;
123    g = a + (b << 11 & 4294967295 | b >>> 21);
124    b = e + (g ^ a ^ c) + d[11] + 1839030562 & 4294967295;
125    e = g + (b << 16 & 4294967295 | b >>> 16);
126    b = c + (e ^ g ^ a) + d[14] + 4259657740 & 4294967295;
127    c = e + (b << 23 & 4294967295 | b >>> 9);
128    b = a + (c ^ e ^ g) + d[1] + 2763975236 & 4294967295;
129    a = c + (b << 4 & 4294967295 | b >>> 28);
130    b = g + (a ^ c ^ e) + d[4] + 1272893353 & 4294967295;
131    g = a + (b << 11 & 4294967295 | b >>> 21);
132    b = e + (g ^ a ^ c) + d[7] + 4139469664 & 4294967295;
133    e = g + (b << 16 & 4294967295 | b >>> 16);
134    b = c + (e ^ g ^ a) + d[10] + 3200236656 & 4294967295;
135    c = e + (b << 23 & 4294967295 | b >>> 9);
136    b = a + (c ^ e ^ g) + d[13] + 681279174 & 4294967295;
137    a = c + (b << 4 & 4294967295 | b >>> 28);
138    b = g + (a ^ c ^ e) + d[0] + 3936430074 & 4294967295;
139    g = a + (b << 11 & 4294967295 | b >>> 21);
140    b = e + (g ^ a ^ c) + d[3] + 3572445317 & 4294967295;
141    e = g + (b << 16 & 4294967295 | b >>> 16);
142    b = c + (e ^ g ^ a) + d[6] + 76029189 & 4294967295;
143    c = e + (b << 23 & 4294967295 | b >>> 9);
144    b = a + (c ^ e ^ g) + d[9] + 3654602809 & 4294967295;
145    a = c + (b << 4 & 4294967295 | b >>> 28);
146    b = g + (a ^ c ^ e) + d[12] + 3873151461 & 4294967295;
147    g = a + (b << 11 & 4294967295 | b >>> 21);
148    b = e + (g ^ a ^ c) + d[15] + 530742520 & 4294967295;
149    e = g + (b << 16 & 4294967295 | b >>> 16);
150    b = c + (e ^ g ^ a) + d[2] + 3299628645 & 4294967295;
151    c = e + (b << 23 & 4294967295 | b >>> 9);
152    b = a + (e ^ (c | ~g)) + d[0] + 4096336452 & 4294967295;
153    a = c + (b << 6 & 4294967295 | b >>> 26);
154    b = g + (c ^ (a | ~e)) + d[7] + 1126891415 & 4294967295;
155    g = a + (b << 10 & 4294967295 | b >>> 22);
156    b = e + (a ^ (g | ~c)) + d[14] + 2878612391 & 4294967295;
157    e = g + (b << 15 & 4294967295 | b >>> 17);
158    b = c + (g ^ (e | ~a)) + d[5] + 4237533241 & 4294967295;
159    c = e + (b << 21 & 4294967295 | b >>> 11);
160    b = a + (e ^ (c | ~g)) + d[12] + 1700485571 & 4294967295;
161    a = c + (b << 6 & 4294967295 | b >>> 26);
162    b = g + (c ^ (a | ~e)) + d[3] + 2399980690 & 4294967295;
163    g = a + (b << 10 & 4294967295 | b >>> 22);
164    b = e + (a ^ (g | ~c)) + d[10] + 4293915773 & 4294967295;
165    e = g + (b << 15 & 4294967295 | b >>> 17);
166    b = c + (g ^ (e | ~a)) + d[1] + 2240044497 & 4294967295;
167    c = e + (b << 21 & 4294967295 | b >>> 11);
168    b = a + (e ^ (c | ~g)) + d[8] + 1873313359 & 4294967295;
169    a = c + (b << 6 & 4294967295 | b >>> 26);
170    b = g + (c ^ (a | ~e)) + d[15] + 4264355552 & 4294967295;
171    g = a + (b << 10 & 4294967295 | b >>> 22);
172    b = e + (a ^ (g | ~c)) + d[6] + 2734768916 & 4294967295;
173    e = g + (b << 15 & 4294967295 | b >>> 17);
174    b = c + (g ^ (e | ~a)) + d[13] + 1309151649 & 4294967295;
175    c = e + (b << 21 & 4294967295 | b >>> 11);
176    b = a + (e ^ (c | ~g)) + d[4] + 4149444226 & 4294967295;
177    a = c + (b << 6 & 4294967295 | b >>> 26);
178    b = g + (c ^ (a | ~e)) + d[11] + 3174756917 & 4294967295;
179    g = a + (b << 10 & 4294967295 | b >>> 22);
180    b = e + (a ^ (g | ~c)) + d[2] + 718787259 & 4294967295;
181    e = g + (b << 15 & 4294967295 | b >>> 17);
182    b = c + (g ^ (e | ~a)) + d[9] + 3951481745 & 4294967295;
183    f.g[0] = f.g[0] + a & 4294967295;
184    f.g[1] = f.g[1] + (e + (b << 21 & 4294967295 | b >>> 11)) & 4294967295;
185    f.g[2] = f.g[2] + e & 4294967295;
186    f.g[3] = f.g[3] + g & 4294967295;
187  }
188  m.prototype.u = function(f, a) {
189    void 0 === a && (a = f.length);
190    for (var c = a - this.blockSize, d = this.B, e = this.h, g = 0; g < a; ) {
191      if (0 == e) for (; g <= c; ) n(this, f, g), g += this.blockSize;
192      if ("string" === typeof f) for (; g < a; ) {
193        if (d[e++] = f.charCodeAt(g++), e == this.blockSize) {
194          n(this, d);
195          e = 0;
196          break;
197        }
198      }
199      else for (; g < a; ) if (d[e++] = f[g++], e == this.blockSize) {
200        n(this, d);
201        e = 0;
202        break;
203      }
204    }
205    this.h = e;
206    this.o += a;
207  };
208  m.prototype.v = function() {
209    var f = Array((56 > this.h ? this.blockSize : 2 * this.blockSize) - this.h);
210    f[0] = 128;
211    for (var a = 1; a < f.length - 8; ++a) f[a] = 0;
212    var c = 8 * this.o;
213    for (a = f.length - 8; a < f.length; ++a) f[a] = c & 255, c /= 256;
214    this.u(f);
215    f = Array(16);
216    for (a = c = 0; 4 > a; ++a) for (var d = 0; 32 > d; d += 8) f[c++] = this.g[a] >>> d & 255;
217    return f;
218  };
219  function p(f, a) {
220    var c = q2;
221    return Object.prototype.hasOwnProperty.call(c, f) ? c[f] : c[f] = a(f);
222  }
223  function t(f, a) {
224    this.h = a;
225    for (var c = [], d = true, e = f.length - 1; 0 <= e; e--) {
226      var g = f[e] | 0;
227      d && g == a || (c[e] = g, d = false);
228    }
229    this.g = c;
230  }
231  var q2 = {};
232  function u(f) {
233    return -128 <= f && 128 > f ? p(f, function(a) {
234      return new t([a | 0], 0 > a ? -1 : 0);
235    }) : new t([f | 0], 0 > f ? -1 : 0);
236  }
237  function v(f) {
238    if (isNaN(f) || !isFinite(f)) return w;
239    if (0 > f) return x2(v(-f));
240    for (var a = [], c = 1, d = 0; f >= c; d++) a[d] = f / c | 0, c *= 4294967296;
241    return new t(a, 0);
242  }
243  function y(f, a) {
244    if (0 == f.length) throw Error("number format error: empty string");
245    a = a || 10;
246    if (2 > a || 36 < a) throw Error("radix out of range: " + a);
247    if ("-" == f.charAt(0)) return x2(y(f.substring(1), a));
248    if (0 <= f.indexOf("-")) throw Error('number format error: interior "-" character');
249    for (var c = v(Math.pow(a, 8)), d = w, e = 0; e < f.length; e += 8) {
250      var g = Math.min(8, f.length - e), b = parseInt(f.substring(e, e + g), a);
251      8 > g ? (g = v(Math.pow(a, g)), d = d.j(g).add(v(b))) : (d = d.j(c), d = d.add(v(b)));
252    }
253    return d;
254  }
255  var w = u(0), z2 = u(1), A = u(16777216);
256  h = t.prototype;
257  h.m = function() {
258    if (B2(this)) return -x2(this).m();
259    for (var f = 0, a = 1, c = 0; c < this.g.length; c++) {
260      var d = this.i(c);
261      f += (0 <= d ? d : 4294967296 + d) * a;
262      a *= 4294967296;
263    }
264    return f;
265  };
266  h.toString = function(f) {
267    f = f || 10;
268    if (2 > f || 36 < f) throw Error("radix out of range: " + f);
269    if (C(this)) return "0";
270    if (B2(this)) return "-" + x2(this).toString(f);
271    for (var a = v(Math.pow(f, 6)), c = this, d = ""; ; ) {
272      var e = D(c, a).g;
273      c = F2(c, e.j(a));
274      var g = ((0 < c.g.length ? c.g[0] : c.h) >>> 0).toString(f);
275      c = e;
276      if (C(c)) return g + d;
277      for (; 6 > g.length; ) g = "0" + g;
278      d = g + d;
279    }
280  };
281  h.i = function(f) {
282    return 0 > f ? 0 : f < this.g.length ? this.g[f] : this.h;
283  };
284  function C(f) {
285    if (0 != f.h) return false;
286    for (var a = 0; a < f.g.length; a++) if (0 != f.g[a]) return false;
287    return true;
288  }
289  function B2(f) {
290    return -1 == f.h;
291  }
292  h.l = function(f) {
293    f = F2(this, f);
294    return B2(f) ? -1 : C(f) ? 0 : 1;
295  };
296  function x2(f) {
297    for (var a = f.g.length, c = [], d = 0; d < a; d++) c[d] = ~f.g[d];
298    return new t(c, ~f.h).add(z2);
299  }
300  h.abs = function() {
301    return B2(this) ? x2(this) : this;
302  };
303  h.add = function(f) {
304    for (var a = Math.max(this.g.length, f.g.length), c = [], d = 0, e = 0; e <= a; e++) {
305      var g = d + (this.i(e) & 65535) + (f.i(e) & 65535), b = (g >>> 16) + (this.i(e) >>> 16) + (f.i(e) >>> 16);
306      d = b >>> 16;
307      g &= 65535;
308      b &= 65535;
309      c[e] = b << 16 | g;
310    }
311    return new t(c, c[c.length - 1] & -2147483648 ? -1 : 0);
312  };
313  function F2(f, a) {
314    return f.add(x2(a));
315  }
316  h.j = function(f) {
317    if (C(this) || C(f)) return w;
318    if (B2(this)) return B2(f) ? x2(this).j(x2(f)) : x2(x2(this).j(f));
319    if (B2(f)) return x2(this.j(x2(f)));
320    if (0 > this.l(A) && 0 > f.l(A)) return v(this.m() * f.m());
321    for (var a = this.g.length + f.g.length, c = [], d = 0; d < 2 * a; d++) c[d] = 0;
322    for (d = 0; d < this.g.length; d++) for (var e = 0; e < f.g.length; e++) {
323      var g = this.i(d) >>> 16, b = this.i(d) & 65535, r = f.i(e) >>> 16, E = f.i(e) & 65535;
324      c[2 * d + 2 * e] += b * E;
325      G2(c, 2 * d + 2 * e);
326      c[2 * d + 2 * e + 1] += g * E;
327      G2(c, 2 * d + 2 * e + 1);
328      c[2 * d + 2 * e + 1] += b * r;
329      G2(c, 2 * d + 2 * e + 1);
330      c[2 * d + 2 * e + 2] += g * r;
331      G2(c, 2 * d + 2 * e + 2);
332    }
333    for (d = 0; d < a; d++) c[d] = c[2 * d + 1] << 16 | c[2 * d];
334    for (d = a; d < 2 * a; d++) c[d] = 0;
335    return new t(c, 0);
336  };
337  function G2(f, a) {
338    for (; (f[a] & 65535) != f[a]; ) f[a + 1] += f[a] >>> 16, f[a] &= 65535, a++;
339  }
340  function H2(f, a) {
341    this.g = f;
342    this.h = a;
343  }
344  function D(f, a) {
345    if (C(a)) throw Error("division by zero");
346    if (C(f)) return new H2(w, w);
347    if (B2(f)) return a = D(x2(f), a), new H2(x2(a.g), x2(a.h));
348    if (B2(a)) return a = D(f, x2(a)), new H2(x2(a.g), a.h);
349    if (30 < f.g.length) {
350      if (B2(f) || B2(a)) throw Error("slowDivide_ only works with positive integers.");
351      for (var c = z2, d = a; 0 >= d.l(f); ) c = I(c), d = I(d);
352      var e = J2(c, 1), g = J2(d, 1);
353      d = J2(d, 2);
354      for (c = J2(c, 2); !C(d); ) {
355        var b = g.add(d);
356        0 >= b.l(f) && (e = e.add(c), g = b);
357        d = J2(d, 1);
358        c = J2(c, 1);
359      }
360      a = F2(f, e.j(a));
361      return new H2(e, a);
362    }
363    for (e = w; 0 <= f.l(a); ) {
364      c = Math.max(1, Math.floor(f.m() / a.m()));
365      d = Math.ceil(Math.log(c) / Math.LN2);
366      d = 48 >= d ? 1 : Math.pow(2, d - 48);
367      g = v(c);
368      for (b = g.j(a); B2(b) || 0 < b.l(f); ) c -= d, g = v(c), b = g.j(a);
369      C(g) && (g = z2);
370      e = e.add(g);
371      f = F2(f, b);
372    }
373    return new H2(e, f);
374  }
375  h.A = function(f) {
376    return D(this, f).h;
377  };
378  h.and = function(f) {
379    for (var a = Math.max(this.g.length, f.g.length), c = [], d = 0; d < a; d++) c[d] = this.i(d) & f.i(d);
380    return new t(c, this.h & f.h);
381  };
382  h.or = function(f) {
383    for (var a = Math.max(this.g.length, f.g.length), c = [], d = 0; d < a; d++) c[d] = this.i(d) | f.i(d);
384    return new t(c, this.h | f.h);
385  };
386  h.xor = function(f) {
387    for (var a = Math.max(this.g.length, f.g.length), c = [], d = 0; d < a; d++) c[d] = this.i(d) ^ f.i(d);
388    return new t(c, this.h ^ f.h);
389  };
390  function I(f) {
391    for (var a = f.g.length + 1, c = [], d = 0; d < a; d++) c[d] = f.i(d) << 1 | f.i(d - 1) >>> 31;
392    return new t(c, f.h);
393  }
394  function J2(f, a) {
395    var c = a >> 5;
396    a %= 32;
397    for (var d = f.g.length - c, e = [], g = 0; g < d; g++) e[g] = 0 < a ? f.i(g + c) >>> a | f.i(g + c + 1) << 32 - a : f.i(g + c);
398    return new t(e, f.h);
399  }
400  m.prototype.digest = m.prototype.v;
401  m.prototype.reset = m.prototype.s;
402  m.prototype.update = m.prototype.u;
403  Md5 = m;
404  t.prototype.add = t.prototype.add;
405  t.prototype.multiply = t.prototype.j;
406  t.prototype.modulo = t.prototype.A;
407  t.prototype.compare = t.prototype.l;
408  t.prototype.toNumber = t.prototype.m;
409  t.prototype.toString = t.prototype.toString;
410  t.prototype.getBits = t.prototype.i;
411  t.fromNumber = v;
412  t.fromString = y;
413  Integer = t;
414}).apply(typeof commonjsGlobal$1 !== "undefined" ? commonjsGlobal$1 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
415var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : {};
416/** @license
417Copyright The Closure Library Authors.
418SPDX-License-Identifier: Apache-2.0
419*/
420var XhrIo;
421var WebChannel;
422var EventType;
423var ErrorCode;
424var Stat;
425var Event;
426var getStatEventTarget;
427var createWebChannelTransport;
428(function() {
429  var h, aa = "function" == typeof Object.defineProperties ? Object.defineProperty : function(a, b, c) {
430    if (a == Array.prototype || a == Object.prototype) return a;
431    a[b] = c.value;
432    return a;
433  };
434  function ba(a) {
435    a = ["object" == typeof globalThis && globalThis, a, "object" == typeof window && window, "object" == typeof self && self, "object" == typeof commonjsGlobal && commonjsGlobal];
436    for (var b = 0; b < a.length; ++b) {
437      var c = a[b];
438      if (c && c.Math == Math) return c;
439    }
440    throw Error("Cannot find global object");
441  }
442  var ca = ba(this);
443  function da(a, b) {
444    if (b) a: {
445      var c = ca;
446      a = a.split(".");
447      for (var d = 0; d < a.length - 1; d++) {
448        var e = a[d];
449        if (!(e in c)) break a;
450        c = c[e];
451      }
452      a = a[a.length - 1];
453      d = c[a];
454      b = b(d);
455      b != d && null != b && aa(c, a, { configurable: true, writable: true, value: b });
456    }
457  }
458  function ea(a, b) {
459    a instanceof String && (a += "");
460    var c = 0, d = false, e = { next: function() {
461      if (!d && c < a.length) {
462        var f = c++;
463        return { value: b(f, a[f]), done: false };
464      }
465      d = true;
466      return { done: true, value: void 0 };
467    } };
468    e[Symbol.iterator] = function() {
469      return e;
470    };
471    return e;
472  }
473  da("Array.prototype.values", function(a) {
474    return a ? a : function() {
475      return ea(this, function(b, c) {
476        return c;
477      });
478    };
479  });
480  /** @license
481  
482   Copyright The Closure Library Authors.
483   SPDX-License-Identifier: Apache-2.0
484  */
485  var fa = fa || {}, k2 = this || self;
486  function ha(a) {
487    var b = typeof a;
488    b = "object" != b ? b : a ? Array.isArray(a) ? "array" : b : "null";
489    return "array" == b || "object" == b && "number" == typeof a.length;
490  }
491  function n(a) {
492    var b = typeof a;
493    return "object" == b && null != a || "function" == b;
494  }
495  function ia(a, b, c) {
496    return a.call.apply(a.bind, arguments);
497  }
498  function ja(a, b, c) {
499    if (!a) throw Error();
500    if (2 < arguments.length) {
501      var d = Array.prototype.slice.call(arguments, 2);
502      return function() {
503        var e = Array.prototype.slice.call(arguments);
504        Array.prototype.unshift.apply(e, d);
505        return a.apply(b, e);
506      };
507    }
508    return function() {
509      return a.apply(b, arguments);
510    };
511  }
512  function p(a, b, c) {
513    p = Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? ia : ja;
514    return p.apply(null, arguments);
515  }
516  function ka(a, b) {
517    var c = Array.prototype.slice.call(arguments, 1);
518    return function() {
519      var d = c.slice();
520      d.push.apply(d, arguments);
521      return a.apply(this, d);
522    };
523  }
524  function r(a, b) {
525    function c() {
526    }
527    c.prototype = b.prototype;
528    a.aa = b.prototype;
529    a.prototype = new c();
530    a.prototype.constructor = a;
531    a.Qb = function(d, e, f) {
532      for (var g = Array(arguments.length - 2), m = 2; m < arguments.length; m++) g[m - 2] = arguments[m];
533      return b.prototype[e].apply(d, g);
534    };
535  }
536  function la(a) {
537    const b = a.length;
538    if (0 < b) {
539      const c = Array(b);
540      for (let d = 0; d < b; d++) c[d] = a[d];
541      return c;
542    }
543    return [];
544  }
545  function ma(a, b) {
546    for (let c = 1; c < arguments.length; c++) {
547      const d = arguments[c];
548      if (ha(d)) {
549        const e = a.length || 0, f = d.length || 0;
550        a.length = e + f;
551        for (let g = 0; g < f; g++) a[e + g] = d[g];
552      } else a.push(d);
553    }
554  }
555  class na {
556    constructor(a, b) {
557      this.i = a;
558      this.j = b;
559      this.h = 0;
560      this.g = null;
561    }
562    get() {
563      let a;
564      0 < this.h ? (this.h--, a = this.g, this.g = a.next, a.next = null) : a = this.i();
565      return a;
566    }
567  }
568  function t(a) {
569    return /^[\s\xa0]*$/.test(a);
570  }
571  function u() {
572    var a = k2.navigator;
573    return a && (a = a.userAgent) ? a : "";
574  }
575  function oa(a) {
576    oa[" "](a);
577    return a;
578  }
579  oa[" "] = function() {
580  };
581  var pa = -1 != u().indexOf("Gecko") && !(-1 != u().toLowerCase().indexOf("webkit") && -1 == u().indexOf("Edge")) && !(-1 != u().indexOf("Trident") || -1 != u().indexOf("MSIE")) && -1 == u().indexOf("Edge");
582  function qa(a, b, c) {
583    for (const d in a) b.call(c, a[d], d, a);
584  }
585  function ra(a, b) {
586    for (const c in a) b.call(void 0, a[c], c, a);
587  }
588  function sa(a) {
589    const b = {};
590    for (const c in a) b[c] = a[c];
591    return b;
592  }
593  const ta = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleStr
593ing toString valueOf".split(" ");
594  function ua(a, b) {
595    let c, d;
596    for (let e = 1; e < arguments.length; e++) {
597      d = arguments[e];
598      for (c in d) a[c] = d[c];
599      for (let f = 0; f < ta.length; f++) c = ta[f], Object.prototype.hasOwnProperty.call(d, c) && (a[c] = d[c]);
600    }
601  }
602  function va(a) {
603    var b = 1;
604    a = a.split(":");
605    const c = [];
606    for (; 0 < b && a.length; ) c.push(a.shift()), b--;
607    a.length && c.push(a.join(":"));
608    return c;
609  }
610  function wa(a) {
611    k2.setTimeout(() => {
612      throw a;
613    }, 0);
614  }
615  function xa() {
616    var a = za;
617    let b = null;
618    a.g && (b = a.g, a.g = a.g.next, a.g || (a.h = null), b.next = null);
619    return b;
620  }
621  class Aa {
622    constructor() {
623      this.h = this.g = null;
624    }
625    add(a, b) {
626      const c = Ba.get();
627      c.set(a, b);
628      this.h ? this.h.next = c : this.g = c;
629      this.h = c;
630    }
631  }
632  var Ba = new na(() => new Ca(), (a) => a.reset());
633  class Ca {
634    constructor() {
635      this.next = this.g = this.h = null;
636    }
637    set(a, b) {
638      this.h = a;
639      this.g = b;
640      this.next = null;
641    }
642    reset() {
643      this.next = this.g = this.h = null;
644    }
645  }
646  let x2, y = false, za = new Aa(), Ea = () => {
647    const a = k2.Promise.resolve(void 0);
648    x2 = () => {
649      a.then(Da);
650    };
651  };
652  var Da = () => {
653    for (var a; a = xa(); ) {
654      try {
655        a.h.call(a.g);
656      } catch (c) {
657        wa(c);
658      }
659      var b = Ba;
660      b.j(a);
661      100 > b.h && (b.h++, a.next = b.g, b.g = a);
662    }
663    y = false;
664  };
665  function z2() {
666    this.s = this.s;
667    this.C = this.C;
668  }
669  z2.prototype.s = false;
670  z2.prototype.ma = function() {
671    this.s || (this.s = true, this.N());
672  };
673  z2.prototype.N = function() {
674    if (this.C) for (; this.C.length; ) this.C.shift()();
675  };
676  function A(a, b) {
677    this.type = a;
678    this.g = this.target = b;
679    this.defaultPrevented = false;
680  }
681  A.prototype.h = function() {
682    this.defaultPrevented = true;
683  };
684  var Fa = function() {
685    if (!k2.addEventListener || !Object.defineProperty) return false;
686    var a = false, b = Object.defineProperty({}, "passive", { get: function() {
687      a = true;
688    } });
689    try {
690      const c = () => {
691      };
692      k2.addEventListener("test", c, b);
693      k2.removeEventListener("test", c, b);
694    } catch (c) {
695    }
696    return a;
697  }();
698  function C(a, b) {
699    A.call(this, a ? a.type : "");
700    this.relatedTarget = this.g = this.target = null;
701    this.button = this.screenY = this.screenX = this.clientY = this.clientX = 0;
702    this.key = "";
703    this.metaKey = this.shiftKey = this.altKey = this.ctrlKey = false;
704    this.state = null;
705    this.pointerId = 0;
706    this.pointerType = "";
707    this.i = null;
708    if (a) {
709      var c = this.type = a.type, d = a.changedTouches && a.changedTouches.length ? a.changedTouches[0] : null;
710      this.target = a.target || a.srcElement;
711      this.g = b;
712      if (b = a.relatedTarget) {
713        if (pa) {
714          a: {
715            try {
716              oa(b.nodeName);
717              var e = true;
718              break a;
719            } catch (f) {
720            }
721            e = false;
722          }
723          e || (b = null);
724        }
725      } else "mouseover" == c ? b = a.fromElement : "mouseout" == c && (b = a.toElement);
726      this.relatedTarget = b;
727      d ? (this.clientX = void 0 !== d.clientX ? d.clientX : d.pageX, this.clientY = void 0 !== d.clientY ? d.clientY : d.pageY, this.screenX = d.screenX || 0, this.screenY = d.screenY || 0) : (this.clientX = void 0 !== a.clientX ? a.clientX : a.pageX, this.clientY = void 0 !== a.clientY ? a.clientY : a.pageY, this.screenX = a.screenX || 0, this.screenY = a.screenY || 0);
728      this.button = a.button;
729      this.key = a.key || "";
730      this.ctrlKey = a.ctrlKey;
731      this.altKey = a.altKey;
732      this.shiftKey = a.shiftKey;
733      this.metaKey = a.metaKey;
734      this.pointerId = a.pointerId || 0;
735      this.pointerType = "string" === typeof a.pointerType ? a.pointerType : Ga[a.pointerType] || "";
736      this.state = a.state;
737      this.i = a;
738      a.defaultPrevented && C.aa.h.call(this);
739    }
740  }
741  r(C, A);
742  var Ga = { 2: "touch", 3: "pen", 4: "mouse" };
743  C.prototype.h = function() {
744    C.aa.h.call(this);
745    var a = this.i;
746    a.preventDefault ? a.preventDefault() : a.returnValue = false;
747  };
748  var D = "closure_listenable_" + (1e6 * Math.random() | 0);
749  var Ha = 0;
750  function Ia(a, b, c, d, e) {
751    this.listener = a;
752    this.proxy = null;
753    this.src = b;
754    this.type = c;
755    this.capture = !!d;
756    this.ha = e;
757    this.key = ++Ha;
758    this.da = this.fa = false;
759  }
760  function Ja(a) {
761    a.da = true;
762    a.listener = null;
763    a.proxy = null;
764    a.src = null;
765    a.ha = null;
766  }
767  function Ka(a) {
768    this.src = a;
769    this.g = {};
770    this.h = 0;
771  }
772  Ka.prototype.add = function(a, b, c, d, e) {
773    var f = a.toString();
774    a = this.g[f];
775    a || (a = this.g[f] = [], this.h++);
776    var g = La(a, b, d, e);
777    -1 < g ? (b = a[g], c || (b.fa = false)) : (b = new Ia(b, this.src, f, !!d, e), b.fa = c, a.push(b));
778    return b;
779  };
780  function Ma(a, b) {
781    var c = b.type;
782    if (c in a.g) {
783      var d = a.g[c], e = Array.prototype.indexOf.call(d, b, void 0), f;
784      (f = 0 <= e) && Array.prototype.splice.call(d, e, 1);
785      f && (Ja(b), 0 == a.g[c].length && (delete a.g[c], a.h--));
786    }
787  }
788  function La(a, b, c, d) {
789    for (var e = 0; e < a.length; ++e) {
790      var f = a[e];
791      if (!f.da && f.listener == b && f.capture == !!c && f.ha == d) return e;
792    }
793    return -1;
794  }
795  var Na = "closure_lm_" + (1e6 * Math.random() | 0), Oa = {};
796  function Qa(a, b, c, d, e) {
797    if (Array.isArray(b)) {
798      for (var f = 0; f < b.length; f++) Qa(a, b[f], c, d, e);
799      return null;
800    }
801    c = Sa(c);
802    return a && a[D] ? a.K(b, c, n(d) ? !!d.capture : false, e) : Ta(a, b, c, false, d, e);
803  }
804  function Ta(a, b, c, d, e, f) {
805    if (!b) throw Error("Invalid event type");
806    var g = n(e) ? !!e.capture : !!e, m = Ua(a);
807    m || (a[Na] = m = new Ka(a));
808    c = m.add(b, c, d, g, f);
809    if (c.proxy) return c;
810    d = Va();
811    c.proxy = d;
812    d.src = a;
813    d.listener = c;
814    if (a.addEventListener) Fa || (e = g), void 0 === e && (e = false), a.addEventListener(b.toString(), d, e);
815    else if (a.attachEvent) a.attachEvent(Wa(b.toString()), d);
816    else if (a.addListener && a.removeListener) a.addListener(d);
817    else throw Error("addEventListener and attachEvent are unavailable.");
818    return c;
819  }
820  function Va() {
821    function a(c) {
822      return b.call(a.src, a.listener, c);
823    }
824    const b = Xa;
825    return a;
826  }
827  function Ya(a, b, c, d, e) {
828    if (Array.isArray(b)) for (var f = 0; f < b.length; f++) Ya(a, b[f], c, d, e);
829    else (d = n(d) ? !!d.capture : !!d, c = Sa(c), a && a[D]) ? (a = a.i, b = String(b).toString(), b in a.g && (f = a.g[b], c = La(f, c, d, e), -1 < c && (Ja(f[c]), Array.prototype.splice.call(f, c, 1), 0 == f.length && (delete a.g[b], a.h--)))) : a && (a = Ua(a)) && (b = a.g[b.toString()], a = -1, b && (a = La(b, c, d, e)), (c = -1 < a ? b[a] : null) && Za(c));
830  }
831  function Za(a) {
832    if ("number" !== typeof a && a && !a.da) {
833      var b = a.src;
834      if (b && b[D]) Ma(b.i, a);
835      else {
836        var c = a.type, d = a.proxy;
837        b.removeEventListener ? b.removeEventListener(c, d, a.capture) : b.detachEvent ? b.detachEvent(Wa(c), d) : b.addListener && b.removeListener && b.removeListener(d);
838        (c = Ua(b)) ? (Ma(c, a), 0 == c.h && (c.src = null, b[Na] = null)) : Ja(a);
839      }
840    }
841  }
842  function Wa(a) {
843    return a in Oa ? Oa[a] : Oa[a] = "on" + a;
844  }
845  function Xa(a, b) {
846    if (a.da) a = true;
847    else {
848      b = new C(b, this);
849      var c = a.listener, d = a.ha || a.src;
850      a.fa && Za(a);
851      a = c.call(d, b);
852    }
853    return a;
854  }
855  function Ua(a) {
856    a = a[Na];
857    return a instanceof Ka ? a : null;
858  }
859  var $a = "__closure_events_fn_" + (1e9 * Math.random() >>> 0);
860  function Sa(a) {
861    if ("function" === typeof a) return a;
862    a[$a] || (a[$a] = function(b) {
863      return a.handleEvent(b);
864    });
865    return a[$a];
866  }
867  function E() {
868    z2.call(this);
869    this.i = new Ka(this);
870    this.M = this;
871    this.F = null;
872  }
873  r(E, z2);
874  E.prototype[D] = true;
875  E.prototype.removeEventListener = function(a, b, c, d) {
876    Ya(this, a, b, c, d);
877  };
878  function F2(a, b) {
879    var c, d = a.F;
880    if (d) for (c = []; d; d = d.F) c.push(d);
881    a = a.M;
882    d = b.type || b;
883    if ("string" === typeof b) b = new A(b, a);
884    else if (b instanceof A) b.target = b.target || a;
885    else {
886      var e = b;
887      b = new A(d, a);
888      ua(b, e);
889    }
890    e = true;
891    if (c) for (var f = c.length - 1; 0 <= f; f--) {
892      var g = b.g = c[f];
893      e = ab(g, d, true, b) && e;
894    }
895    g = b.g = a;
896    e = ab(g, d, true, b) && e;
897    e = ab(g, d, false, b) && e;
898    if (c) for (f = 0; f < c.length; f++) g = b.g = c[f], e = ab(g, d, false, b) && e;
899  }
900  E.prototype.N = function() {
901    E.aa.N.call(this);
902    if (this.i) {
903      var a = this.i, c;
904      for (c in a.g) {
905        for (var d = a.g[c], e = 0; e < d.length; e++) Ja(d[e]);
906        delete a.g[c];
907        a.h--;
908      }
909    }
910    this.F = null;
911  };
912  E.prototype.K = function(a, b, c, d) {
913    return this.i.add(String(a), b, false, c, d);
914  };
915  E.prototype.L = function(a, b, c, d) {
916    return this.i.add(String(a), b, true, c, d);
917  };
918  function ab(a, b, c, d) {
919    b = a.i.g[String(b)];
920    if (!b) return true;
921    b = b.concat();
922    for (var e = true, f = 0; f < b.length; ++f) {
923      var g = b[f];
924      if (g && !g.da && g.capture == c) {
925        var m = g.listener, q2 = g.ha || g.src;
926        g.fa && Ma(a.i, g);
927        e = false !== m.call(q2, d) && e;
928      }
929    }
930    return e && !d.defaultPrevented;
931  }
932  function bb(a, b, c) {
933    if ("function" === typeof a) c && (a = p(a, c));
934    else if (a && "function" == typeof a.handleEvent) a = p(a.handleEvent, a);
935    else throw Error("Invalid listener argument");
936    return 2147483647 < Number(b) ? -1 : k2.setTimeout(a, b || 0);
937  }
938  function cb(a) {
939    a.g = bb(() => {
940      a.g = null;
941      a.i && (a.i = false, cb(a));
942    }, a.l);
943    const b = a.h;
944    a.h = null;
945    a.m.apply(null, b);
946  }
947  class eb extends z2 {
948    constructor(a, b) {
949      super();
950      this.m = a;
951      this.l = b;
952      this.h = null;
953      this.i = false;
954      this.g = null;
955    }
956    j(a) {
957      this.h = arguments;
958      this.g ? this.i = true : cb(this);
959    }
960    N() {
961      super.N();
962      this.g && (k2.clearTimeout(this.g), this.g = null, this.i = false, this.h = null);
963    }
964  }
965  function G2(a) {
966    z2.call(this);
967    this.h = a;
968    this.g = {};
969  }
970  r(G2, z2);
971  var fb = [];
972  function gb(a) {
973    qa(a.g, function(b, c) {
974      this.g.hasOwnProperty(c) && Za(b);
975    }, a);
976    a.g = {};
977  }
978  G2.prototype.N = function() {
979    G2.aa.N.call(this);
980    gb(this);
981  };
982  G2.prototype.handleEvent = function() {
983    throw Error("EventHandler.handleEvent not implemented");
984  };
985  var hb = k2.JSON.stringify;
986  var ib = k2.JSON.parse;
987  var jb = class {
988    stringify(a) {
989      return k2.JSON.stringify(a, void 0);
990    }
991    parse(a) {
992      return k2.JSON.parse(a, void 0);
993    }
994  };
995  function kb() {
996  }
997  kb.prototype.h = null;
998  function lb(a) {
999    return a.h || (a.h = a.i());
1000  }
1001  function mb() {
1002  }
1003  var H2 = { OPEN: "a", kb: "b", Ja: "c", wb: "d" };
1004  function nb() {
1005    A.call(this, "d");
1006  }
1007  r(nb, A);
1008  function ob() {
1009    A.call(this, "c");
1010  }
1011  r(ob, A);
1012  var I = {}, pb = null;
1013  function qb() {
1014    return pb = pb || new E();
1015  }
1016  I.La = "serverreachability";
1017  function rb(a) {
1018    A.call(this, I.La, a);
1019  }
1020  r(rb, A);
1021  function J2(a) {
1022    const b = qb();
1023    F2(b, new rb(b));
1024  }
1025  I.STAT_EVENT = "statevent";
1026  function sb(a, b) {
1027    A.call(this, I.STAT_EVENT, a);
1028    this.stat = b;
1029  }
1030  r(sb, A);
1031  function K2(a) {
1032    const b = qb();
1033    F2(b, new sb(b, a));
1034  }
1035  I.Ma = "timingevent";
1036  function tb(a, b) {
1037    A.call(this, I.Ma, a);
1038    this.size = b;
1039  }
1040  r(tb, A);
1041  function ub(a, b) {
1042    if ("function" !== typeof a) throw Error("Fn must not be null and must be a function");
1043    return k2.setTimeout(function() {
1044      a();
1045    }, b);
1046  }
1047  function vb() {
1048    this.g = true;
1049  }
1050  vb.prototype.xa = function() {
1051    this.g = false;
1052  };
1053  function wb(a, b, c, d, e, f) {
1054    a.info(function() {
1055      if (a.g) if (f) {
1056        var g = "";
1057        for (var m = f.split("&"), q2 = 0; q2 < m.length; q2++) {
1058          var l = m[q2].split("=");
1059          if (1 < l.length) {
1060            var v = l[0];
1061            l = l[1];
1062            var w = v.split("_");
1063            g = 2 <= w.length && "type" == w[1] ? g + (v + "=" + l + "&") : g + (v + "=redacted&");
1064          }
1065        }
1066      } else g = null;
1067      else g = f;
1068      return "XMLHTTP REQ (" + d + ") [attempt " + e + "]: " + b + "\n" + c + "\n" + g;
1069    });
1070  }
1071  function xb(a, b, c, d, e, f, g) {
1072    a.info(function() {
1073      return "XMLHTTP RESP (" + d + ") [ attempt " + e + "]: " + b + "\n" + c + "\n" + f + " " + g;
1074    });
1075  }
1076  function L2(a, b, c, d) {
1077    a.info(function() {
1078      return "XMLHTTP TEXT (" + b + "): " + yb(a, c) + (d ? " " + d : "");
1079    });
1080  }
1081  function zb(a, b) {
1082    a.info(function() {
1083      return "TIMEOUT: " + b;
1084    });
1085  }
1086  vb.prototype.info = function() {
1087  };
1088  function yb(a, b) {
1089    if (!a.g) return b;
1090    if (!b) return null;
1091    try {
1092      var c = JSON.parse(b);
1093      if (c) {
1094        for (a = 0; a < c.length; a++) if (Array.isArray(c[a])) {
1095          var d = c[a];
1096          if (!(2 > d.length)) {
1097            var e = d[1];
1098            if (Array.isArray(e) && !(1 > e.length)) {
1099              var f = e[0];
1100              if ("noop" != f && "stop" != f && "close" != f) for (var g = 1; g < e.length; g++) e[g] = "";
1101            }
1102          }
1103        }
1104      }
1105      return hb(c);
1106    } catch (m) {
1107      return b;
1108    }
1109  }
1110  var Ab = { NO_ERROR: 0, gb: 1, tb: 2, sb: 3, nb: 4, rb: 5, ub: 6, Ia: 7, TIMEOUT: 8, xb: 9 };
1111  var Bb = { lb: "complete", Hb: "success", Ja: "error", Ia: "abort", zb: "ready", Ab: "readystatechange", TIMEOUT: "timeout", vb: "incrementaldata", yb: "progress", ob: "downloadprogress", Pb: "uploadprogress" };
1112  var Cb;
1113  function Db() {
1114  }
1115  r(Db, kb);
1116  Db.prototype.g = function() {
1117    return new XMLHttpRequest();
1118  };
1119  Db.prototype.i = function() {
1120    return {};
1121  };
1122  Cb = new Db();
1123  function M2(a, b, c, d) {
1124    this.j = a;
1125    this.i = b;
1126    this.l = c;
1127    this.R = d || 1;
1128    this.U = new G2(this);
1129    this.I = 45e3;
1130    this.H = null;
1131    this.o = false;
1132    this.m = this.A = this.v = this.L = this.F = this.S = this.B = null;
1133    this.D = [];
1134    this.g = null;
1135    this.C = 0;
1136    this.s = this.u = null;
1137    this.X = -1;
1138    this.J = false;
1139    this.O = 0;
1140    this.M = null;
1141    this.W = this.K = this.T = this.P = false;
1142    this.h = new Eb();
1143  }
1144  function Eb() {
1145    this.i = null;
1146    this.g = "";
1147    this.h = false;
1148  }
1149  var Fb = {}, Gb = {};
1150  function Hb(a, b, c) {
1151    a.L = 1;
1152    a.v = Ib(N2(b));
1153    a.m = c;
1154    a.P = true;
1155    Jb(a, null);
1156  }
1157  function Jb(a, b) {
1158    a.F = Date.now();
1159    Kb(a);
1160    a.A = N2(a.v);
1161    var c = a.A, d = a.R;
1162    Array.isArray(d) || (d = [String(d)]);
1163    Lb(c.i, "t", d);
1164    a.C = 0;
1165    c = a.j.J;
1166    a.h = new Eb();
1167    a.g = Mb(a.j, c ? b : null, !a.m);
1168    0 < a.O && (a.M = new eb(p(a.Y, a, a.g), a.O));
1169    b = a.U;
1170    c = a.g;
1171    d = a.ca;
1172    var e = "readystatechange";
1173    Array.isArray(e) || (e && (fb[0] = e.toString()), e = fb);
1174    for (var f = 0; f < e.length; f++) {
1175      var g = Qa(c, e[f], d || b.handleEvent, false, b.h || b);
1176      if (!g) break;
1177      b.g[g.key] = g;
1178    }
1179    b = a.H ? sa(a.H) : {};
1180    a.m ? (a.u || (a.u = "POST"), b["Content-Type"] = "application/x-www-form-urlencoded", a.g.ea(
1181      a.A,
1182      a.u,
1183      a.m,
1184      b
1185    )) : (a.u = "GET", a.g.ea(a.A, a.u, null, b));
1186    J2();
1187    wb(a.i, a.u, a.A, a.l, a.R, a.m);
1188  }
1189  M2.prototype.ca = function(a) {
1190    a = a.target;
1191    const b = this.M;
1192    b && 3 == P(a) ? b.j() : this.Y(a);
1193  };
1194  M2.prototype.Y = function(a) {
1195    try {
1196      if (a == this.g) a: {
1197        const w = P(this.g);
1198        var b = this.g.Ba();
1199        const O2 = this.g.Z();
1200        if (!(3 > w) && (3 != w || this.g && (this.h.h || this.g.oa() || Nb(this.g)))) {
1201          this.J || 4 != w || 7 == b || (8 == b || 0 >= O2 ? J2(3) : J2(2));
1202          Ob(this);
1203          var c = this.g.Z();
1204          this.X = c;
1205          b: if (Pb(this)) {
1206            var d = Nb(this.g);
1207            a = "";
1208            var e = d.length, f = 4 == P(this.g);
1209            if (!this.h.i) {
1210              if ("undefined" === typeof TextDecoder) {
1211                Q2(this);
1212                Qb(this);
1213                var g = "";
1214                break b;
1215              }
1216              this.h.i = new k2.TextDecoder();
1217            }
1218            for (b = 0; b < e; b++) this.h.h = true, a += this.h.i.decode(d[b], { stream: !(f && b == e - 1) });
1219            d.length = 0;
1220            this.h.g += a;
1221            this.C = 0;
1222            g = this.h.g;
1223          } else g = this.g.oa();
1224          this.o = 200 == c;
1225          xb(this.i, this.u, this.A, this.l, this.R, w, c);
1226          if (this.o) {
1227            if (this.T && !this.K) {
1228              b: {
1229                if (this.g) {
1230                  var m, q2 = this.g;
1231                  if ((m = q2.g ? q2.g.getResponseHeader("X-HTTP-Initial-Response") : null) && !t(m)) {
1232                    var l = m;
1233                    break b;
1234                  }
1235                }
1236                l = null;
1237              }
1238              if (c = l) L2(this.i, this.l, c, "Initial handshake response via X-HTTP-Initial-Response"), this.K = true, Rb(this, c);
1239              else {
1240                this.o = false;
1241                this.s = 3;
1242                K2(12);
1243                Q2(this);
1244                Qb(this);
1245                break a;
1246              }
1247            }
1248            if (this.P) {
1249              c = true;
1250              let B2;
1251              for (; !this.J && this.C < g.length; ) if (B2 = Sb(this, g), B2 == Gb) {
1252                4 == w && (this.s = 4, K2(14), c = false);
1253                L2(this.i, this.l, null, "[Incomplete Response]");
1254                break;
1255              } else if (B2 == Fb) {
1256                this.s = 4;
1257                K2(15);
1258                L2(this.i, this.l, g, "[Invalid Chunk]");
1259                c = false;
1260                break;
1261              } else L2(this.i, this.l, B2, null), Rb(this, B2);
1262              Pb(this) && 0 != this.C && (this.h.g = this.h.g.slice(this.C), this.C = 0);
1263              4 != w || 0 != g.length || this.h.h || (this.s = 1, K2(16), c = false);
1264              this.o = this.o && c;
1265              if (!c) L2(this.i, this.l, g, "[Invalid Chunked Response]"), Q2(this), Qb(this);
1266              else if (0 < g.length && !this.W) {
1267                this.W = true;
1268                var v = this.j;
1269                v.g == this && v.ba && !v.M && (v.j.info("Great, no buffering proxy detected. Bytes received: " + g.length), Tb(v), v.M = true, K2(11));
1270              }
1271            } else L2(this.i, this.l, g, null), Rb(this, g);
1272            4 == w && Q2(this);
1273            this.o && !this.J && (4 == w ? Ub(this.j, this) : (this.o = false, Kb(this)));
1274          } else Vb(this.g), 400 == c && 0 < g.indexOf("Unknown SID") ? (this.s = 3, K2(12)) : (this.s = 0, K2(13)), Q2(this), Qb(this);
1275        }
1276      }
1277    } catch (w) {
1278    } finally {
1279    }
1280  };
1281  function Pb(a) {
1282    return a.g ? "GET" == a.u && 2 != a.L && a.j.Ca : false;
1283  }
1284  function Sb(a, b) {
1285    var c = a.C, d = b.indexOf("\n", c);
1286    if (-1 == d) return Gb;
1287    c = Number(b.substring(c, d));
1288    if (isNaN(c)) return Fb;
1289    d += 1;
1290    if (d + c > b.length) return Gb;
1291    b = b.slice(d, d + c);
1292    a.C = d + c;
1293    return b;
1294  }
1295  M2.prototype.cancel = function() {
1296    this.J = true;
1297    Q2(this);
1298  };
1299  function Kb(a) {
1300    a.S = Date.now() + a.I;
1301    Wb(a, a.I);
1302  }
1303  function Wb(a, b) {
1304    if (null != a.B) throw Error("WatchDog timer not null");
1305    a.B = ub(p(a.ba, a), b);
1306  }
1307  function Ob(a) {
1308    a.B && (k2.clearTimeout(a.B), a.B = null);
1309  }
1310  M2.prototype.ba = function() {
1311    this.B = null;
1312    const a = Date.now();
1313    0 <= a - this.S ? (zb(this.i, this.A), 2 != this.L && (J2(), K2(17)), Q2(this), this.s = 2, Qb(this)) : Wb(this, this.S - a);
1314  };
1315  function Qb(a) {
1316    0 == a.j.G || a.J || Ub(a.j, a);
1317  }
1318  function Q2(a) {
1319    Ob(a);
1320    var b = a.M;
1321    b && "function" == typeof b.ma && b.ma();
1322    a.M = null;
1323    gb(a.U);
1324    a.g && (b = a.g, a.g = null, b.abort(), b.ma());
1325  }
1326  function Rb(a, b) {
1327    try {
1328      var c = a.j;
1329      if (0 != c.G && (c.g == a || Xb(c.h, a))) {
1330        if (!a.K && Xb(c.h, a) && 3 == c.G) {
1331          try {
1332            var d = c.Da.g.parse(b);
1333          } catch (l) {
1334            d = null;
1335          }
1336          if (Array.isArray(d) && 3 == d.length) {
1337            var e = d;
1338            if (0 == e[0]) a: {
1339              if (!c.u) {
1340                if (c.g) if (c.g.F + 3e3 < a.F) Yb(c), Zb(c);
1341                else break a;
1342                $b(c);
1343                K2(18);
1344              }
1345            }
1346            else c.za = e[1], 0 < c.za - c.T && 37500 > e[2] && c.F && 0 == c.v && !c.C && (c.C = ub(p(c.Za, c), 6e3));
1347            if (1 >= ac(c.h) && c.ca) {
1348              try {
1349                c.ca();
1350              } catch (l) {
1351              }
1352              c.ca = void 0;
1353            }
1354          } else R(c, 11);
1355        } else if ((a.K || c.g == a) && Yb(c), !t(b)) for (e = c.Da.g.parse(b), b = 0; b < e.length; b++) {
1356          let l = e[b];
1357          c.T = l[0];
1358          l = l[1];
1359          if (2 == c.G) if ("c" == l[0]) {
1360            c.K = l[1];
1361            c.ia = l[2];
1362            const v = l[3];
1363            null != v && (c.la = v, c.j.info("VER=" + c.la));
1364            const w = l[4];
1365            null != w && (c.Aa = w, c.j.info("SVER=" + c.Aa));
1366            const O2 = l[5];
1367            null != O2 && "number" === typeof O2 && 0 < O2 && (d = 1.5 * O2, c.L = d, c.j.info("backChannelRequestTimeoutMs_=" + d));
1368            d = c;
1369            const B2 = a.g;
1370            if (B2) {
1371              const ya = B2.g ? B2.g.getResponseHeader("X-Client-Wire-Protocol") : null;
1372              if (ya) {
1373                var f = d.h;
1374                f.g || -1 == ya.indexOf("spdy") && -1 == ya.indexOf("quic") && -1 == ya.indexOf("h2") || (f.j = f.l, f.g = /* @__PURE__ */ new Set(), f.h && (bc(f, f.h), f.h = null));
1375              }
1376              if (d.D) {
1377                const db = B2.g ? B2.g.getResponseHeader("X-HTTP-Session-Id") : null;
1378                db && (d.ya = db, S(d.I, d.D, db));
1379              }
1380            }
1381            c.G = 3;
1382            c.l && c.l.ua();
1383            c.ba && (c.R = Date.now() - a.F, c.j.info("Handshake RTT: " + c.R + "ms"));
1384            d = c;
1385            var g = a;
1386            d.qa = cc(d, d.J ? d.ia : null, d.W);
1387            if (g.K) {
1388              dc(d.h, g);
1389              var m = g, q2 = d.L;
1390              q2 && (m.I = q2);
1391              m.B && (Ob(m), Kb(m));
1392              d.g = g;
1393            } else ec(d);
1394            0 < c.i.length && fc(c);
1395          } else "stop" != l[0] && "close" != l[0] || R(c, 7);
1396          else 3 == c.G && ("stop" == l[0] || "close" == l[0] ? "stop" == l[0] ? R(c, 7) : gc(c) : "noop" != l[0] && c.l && c.l.ta(l), c.v = 0);
1397        }
1398      }
1399      J2(4);
1400    } catch (l) {
1401    }
1402  }
1403  var hc = class {
1404    constructor(a, b) {
1405      this.g = a;
1406      this.map = b;
1407    }
1408  };
1409  function ic(a) {
1410    this.l = a || 10;
1411    k2.PerformanceNavigationTiming ? (a = k2.performance.getEntriesByType("navigation"), a = 0 < a.length && ("hq" == a[0].nextHopProtocol || "h2" == a[0].nextHopProtocol)) : a = !!(k2.chrome && 
1411k2.chrome.loadTimes && k2.chrome.loadTimes() && k2.chrome.loadTimes().wasFetchedViaSpdy);
1412    this.j = a ? this.l : 1;
1413    this.g = null;
1414    1 < this.j && (this.g = /* @__PURE__ */ new Set());
1415    this.h = null;
1416    this.i = [];
1417  }
1418  function jc(a) {
1419    return a.h ? true : a.g ? a.g.size >= a.j : false;
1420  }
1421  function ac(a) {
1422    return a.h ? 1 : a.g ? a.g.size : 0;
1423  }
1424  function Xb(a, b) {
1425    return a.h ? a.h == b : a.g ? a.g.has(b) : false;
1426  }
1427  function bc(a, b) {
1428    a.g ? a.g.add(b) : a.h = b;
1429  }
1430  function dc(a, b) {
1431    a.h && a.h == b ? a.h = null : a.g && a.g.has(b) && a.g.delete(b);
1432  }
1433  ic.prototype.cancel = function() {
1434    this.i = kc(this);
1435    if (this.h) this.h.cancel(), this.h = null;
1436    else if (this.g && 0 !== this.g.size) {
1437      for (const a of this.g.values()) a.cancel();
1438      this.g.clear();
1439    }
1440  };
1441  function kc(a) {
1442    if (null != a.h) return a.i.concat(a.h.D);
1443    if (null != a.g && 0 !== a.g.size) {
1444      let b = a.i;
1445      for (const c of a.g.values()) b = b.concat(c.D);
1446      return b;
1447    }
1448    return la(a.i);
1449  }
1450  function lc(a) {
1451    if (a.V && "function" == typeof a.V) return a.V();
1452    if ("undefined" !== typeof Map && a instanceof Map || "undefined" !== typeof Set && a instanceof Set) return Array.from(a.values());
1453    if ("string" === typeof a) return a.split("");
1454    if (ha(a)) {
1455      for (var b = [], c = a.length, d = 0; d < c; d++) b.push(a[d]);
1456      return b;
1457    }
1458    b = [];
1459    c = 0;
1460    for (d in a) b[c++] = a[d];
1461    return b;
1462  }
1463  function mc(a) {
1464    if (a.na && "function" == typeof a.na) return a.na();
1465    if (!a.V || "function" != typeof a.V) {
1466      if ("undefined" !== typeof Map && a instanceof Map) return Array.from(a.keys());
1467      if (!("undefined" !== typeof Set && a instanceof Set)) {
1468        if (ha(a) || "string" === typeof a) {
1469          var b = [];
1470          a = a.length;
1471          for (var c = 0; c < a; c++) b.push(c);
1472          return b;
1473        }
1474        b = [];
1475        c = 0;
1476        for (const d in a) b[c++] = d;
1477        return b;
1478      }
1479    }
1480  }
1481  function nc(a, b) {
1482    if (a.forEach && "function" == typeof a.forEach) a.forEach(b, void 0);
1483    else if (ha(a) || "string" === typeof a) Array.prototype.forEach.call(a, b, void 0);
1484    else for (var c = mc(a), d = lc(a), e = d.length, f = 0; f < e; f++) b.call(void 0, d[f], c && c[f], a);
1485  }
1486  var oc = RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");
1487  function pc(a, b) {
1488    if (a) {
1489      a = a.split("&");
1490      for (var c = 0; c < a.length; c++) {
1491        var d = a[c].indexOf("="), e = null;
1492        if (0 <= d) {
1493          var f = a[c].substring(0, d);
1494          e = a[c].substring(d + 1);
1495        } else f = a[c];
1496        b(f, e ? decodeURIComponent(e.replace(/\+/g, " ")) : "");
1497      }
1498    }
1499  }
1500  function T(a) {
1501    this.g = this.o = this.j = "";
1502    this.s = null;
1503    this.m = this.l = "";
1504    this.h = false;
1505    if (a instanceof T) {
1506      this.h = a.h;
1507      qc(this, a.j);
1508      this.o = a.o;
1509      this.g = a.g;
1510      rc(this, a.s);
1511      this.l = a.l;
1512      var b = a.i;
1513      var c = new sc();
1514      c.i = b.i;
1515      b.g && (c.g = new Map(b.g), c.h = b.h);
1516      tc(this, c);
1517      this.m = a.m;
1518    } else a && (b = String(a).match(oc)) ? (this.h = false, qc(this, b[1] || "", true), this.o = uc(b[2] || ""), this.g = uc(b[3] || "", true), rc(this, b[4]), this.l = uc(b[5] || "", true), tc(this, b[6] || "", true), this.m = uc(b[7] || "")) : (this.h = false, this.i = new sc(null, this.h));
1519  }
1520  T.prototype.toString = function() {
1521    var a = [], b = this.j;
1522    b && a.push(vc(b, wc, true), ":");
1523    var c = this.g;
1524    if (c || "file" == b) a.push("//"), (b = this.o) && a.push(vc(b, wc, true), "@"), a.push(encodeURIComponent(String(c)).replace(/%25([0-9a-fA-F]{2})/g, "%$1")), c = this.s, null != c && a.push(":", String(c));
1525    if (c = this.l) this.g && "/" != c.charAt(0) && a.push("/"), a.push(vc(c, "/" == c.charAt(0) ? xc : yc, true));
1526    (c = this.i.toString()) && a.push("?", c);
1527    (c = this.m) && a.push("#", vc(c, zc));
1528    return a.join("");
1529  };
1530  function N2(a) {
1531    return new T(a);
1532  }
1533  function qc(a, b, c) {
1534    a.j = c ? uc(b, true) : b;
1535    a.j && (a.j = a.j.replace(/:$/, ""));
1536  }
1537  function rc(a, b) {
1538    if (b) {
1539      b = Number(b);
1540      if (isNaN(b) || 0 > b) throw Error("Bad port number " + b);
1541      a.s = b;
1542    } else a.s = null;
1543  }
1544  function tc(a, b, c) {
1545    b instanceof sc ? (a.i = b, Ac(a.i, a.h)) : (c || (b = vc(b, Bc)), a.i = new sc(b, a.h));
1546  }
1547  function S(a, b, c) {
1548    a.i.set(b, c);
1549  }
1550  function Ib(a) {
1551    S(a, "zx", Math.floor(2147483648 * Math.random()).toString(36) + Math.abs(Math.floor(2147483648 * Math.random()) ^ Date.now()).toString(36));
1552    return a;
1553  }
1554  function uc(a, b) {
1555    return a ? b ? decodeURI(a.replace(/%25/g, "%2525")) : decodeURIComponent(a) : "";
1556  }
1557  function vc(a, b, c) {
1558    return "string" === typeof a ? (a = encodeURI(a).replace(b, Cc), c && (a = a.replace(/%25([0-9a-fA-F]{2})/g, "%$1")), a) : null;
1559  }
1560  function Cc(a) {
1561    a = a.charCodeAt(0);
1562    return "%" + (a >> 4 & 15).toString(16) + (a & 15).toString(16);
1563  }
1564  var wc = /[#\/\?@]/g, yc = /[#\?:]/g, xc = /[#\?]/g, Bc = /[#\?@]/g, zc = /#/g;
1565  function sc(a, b) {
1566    this.h = this.g = null;
1567    this.i = a || null;
1568    this.j = !!b;
1569  }
1570  function U2(a) {
1571    a.g || (a.g = /* @__PURE__ */ new Map(), a.h = 0, a.i && pc(a.i, function(b, c) {
1572      a.add(decodeURIComponent(b.replace(/\+/g, " ")), c);
1573    }));
1574  }
1575  h = sc.prototype;
1576  h.add = function(a, b) {
1577    U2(this);
1578    this.i = null;
1579    a = V(this, a);
1580    var c = this.g.get(a);
1581    c || this.g.set(a, c = []);
1582    c.push(b);
1583    this.h += 1;
1584    return this;
1585  };
1586  function Dc(a, b) {
1587    U2(a);
1588    b = V(a, b);
1589    a.g.has(b) && (a.i = null, a.h -= a.g.get(b).length, a.g.delete(b));
1590  }
1591  function Ec(a, b) {
1592    U2(a);
1593    b = V(a, b);
1594    return a.g.has(b);
1595  }
1596  h.forEach = function(a, b) {
1597    U2(this);
1598    this.g.forEach(function(c, d) {
1599      c.forEach(function(e) {
1600        a.call(b, e, d, this);
1601      }, this);
1602    }, this);
1603  };
1604  h.na = function() {
1605    U2(this);
1606    const a = Array.from(this.g.values()), b = Array.from(this.g.keys()), c = [];
1607    for (let d = 0; d < b.length; d++) {
1608      const e = a[d];
1609      for (let f = 0; f < e.length; f++) c.push(b[d]);
1610    }
1611    return c;
1612  };
1613  h.V = function(a) {
1614    U2(this);
1615    let b = [];
1616    if ("string" === typeof a) Ec(this, a) && (b = b.concat(this.g.get(V(this, a))));
1617    else {
1618      a = Array.from(this.g.values());
1619      for (let c = 0; c < a.length; c++) b = b.concat(a[c]);
1620    }
1621    return b;
1622  };
1623  h.set = function(a, b) {
1624    U2(this);
1625    this.i = null;
1626    a = V(this, a);
1627    Ec(this, a) && (this.h -= this.g.get(a).length);
1628    this.g.set(a, [b]);
1629    this.h += 1;
1630    return this;
1631  };
1632  h.get = function(a, b) {
1633    if (!a) return b;
1634    a = this.V(a);
1635    return 0 < a.length ? String(a[0]) : b;
1636  };
1637  function Lb(a, b, c) {
1638    Dc(a, b);
1639    0 < c.length && (a.i = null, a.g.set(V(a, b), la(c)), a.h += c.length);
1640  }
1641  h.toString = function() {
1642    if (this.i) return this.i;
1643    if (!this.g) return "";
1644    const a = [], b = Array.from(this.g.keys());
1645    for (var c = 0; c < b.length; c++) {
1646      var d = b[c];
1647      const f = encodeURIComponent(String(d)), g = this.V(d);
1648      for (d = 0; d < g.length; d++) {
1649        var e = f;
1650        "" !== g[d] && (e += "=" + encodeURIComponent(String(g[d])));
1651        a.push(e);
1652      }
1653    }
1654    return this.i = a.join("&");
1655  };
1656  function V(a, b) {
1657    b = String(b);
1658    a.j && (b = b.toLowerCase());
1659    return b;
1660  }
1661  function Ac(a, b) {
1662    b && !a.j && (U2(a), a.i = null, a.g.forEach(function(c, d) {
1663      var e = d.toLowerCase();
1664      d != e && (Dc(this, d), Lb(this, e, c));
1665    }, a));
1666    a.j = b;
1667  }
1668  function Fc(a, b) {
1669    const c = new vb();
1670    if (k2.Image) {
1671      const d = new Image();
1672      d.onload = ka(W2, c, "TestLoadImage: loaded", true, b, d);
1673      d.onerror = ka(W2, c, "TestLoadImage: error", false, b, d);
1674      d.onabort = ka(W2, c, "TestLoadImage: abort", false, b, d);
1675      d.ontimeout = ka(W2, c, "TestLoadImage: timeout", false, b, d);
1676      k2.setTimeout(function() {
1677        if (d.ontimeout) d.ontimeout();
1678      }, 1e4);
1679      d.src = a;
1680    } else b(false);
1681  }
1682  function Gc(a, b) {
1683    const c = new vb(), d = new AbortController(), e = setTimeout(() => {
1684      d.abort();
1685      W2(c, "TestPingServer: timeout", false, b);
1686    }, 1e4);
1687    fetch(a, { signal: d.signal }).then((f) => {
1688      clearTimeout(e);
1689      f.ok ? W2(c, "TestPingServer: ok", true, b) : W2(c, "TestPingServer: server error", false, b);
1690    }).catch(() => {
1691      clearTimeout(e);
1692      W2(c, "TestPingServer: error", false, b);
1693    });
1694  }
1695  function W2(a, b, c, d, e) {
1696    try {
1697      e && (e.onload = null, e.onerror = null, e.onabort = null, e.ontimeout = null), d(c);
1698    } catch (f) {
1699    }
1700  }
1701  function Hc() {
1702    this.g = new jb();
1703  }
1704  function Ic(a, b, c) {
1705    const d = c || "";
1706    try {
1707      nc(a, function(e, f) {
1708        let g = e;
1709        n(e) && (g = hb(e));
1710        b.push(d + f + "=" + encodeURIComponent(g));
1711      });
1712    } catch (e) {
1713      throw b.push(d + "type=" + encodeURIComponent("_badmap")), e;
1714    }
1715  }
1716  function Jc(a) {
1717    this.l = a.Ub || null;
1718    this.j = a.eb || false;
1719  }
1720  r(Jc, kb);
1721  Jc.prototype.g = function() {
1722    return new Kc(this.l, this.j);
1723  };
1724  Jc.prototype.i = /* @__PURE__ */ function(a) {
1725    return function() {
1726      return a;
1727    };
1728  }({});
1729  function Kc(a, b) {
1730    E.call(this);
1731    this.D = a;
1732    this.o = b;
1733    this.m = void 0;
1734    this.status = this.readyState = 0;
1735    this.responseType = this.responseText = this.response = this.statusText = "";
1736    this.onreadystatechange = null;
1737    this.u = new Headers();
1738    this.h = null;
1739    this.B = "GET";
1740    this.A = "";
1741    this.g = false;
1742    this.v = this.j = this.l = null;
1743  }
1744  r(Kc, E);
1745  h = Kc.prototype;
1746  h.open = function(a, b) {
1747    if (0 != this.readyState) throw this.abort(), Error("Error reopening a connection");
1748    this.B = a;
1749    this.A = b;
1750    this.readyState = 1;
1751    Lc(this);
1752  };
1753  h.send = function(a) {
1754    if (1 != this.readyState) throw this.abort(), Error("need to call open() first. ");
1755    this.g = true;
1756    const b = { headers: this.u, method: this.B, credentials: this.m, cache: void 0 };
1757    a && (b.body = a);
1758    (this.D || k2).fetch(new Request(this.A, b)).then(this.Sa.bind(this), this.ga.bind(this));
1759  };
1760  h.abort = function() {
1761    this.response = this.responseText = "";
1762    this.u = new Headers();
1763    this.status = 0;
1764    this.j && this.j.cancel("Request was aborted.").catch(() => {
1765    });
1766    1 <= this.readyState && this.g && 4 != this.readyState && (this.g = false, Mc(this));
1767    this.readyState = 0;
1768  };
1769  h.Sa = function(a) {
1770    if (this.g && (this.l = a, this.h || (this.status = this.l.status, this.statusText = this.l.statusText, this.h = a.headers, this.readyState = 2, Lc(this)), this.g && (this.readyState = 3, Lc(this), this.g))) if ("arraybuffer" === this.responseType) a.arrayBuffer().then(this.Qa.bind(this), this.ga.bind(this));
1771    else if ("undefined" !== typeof k2.ReadableStream && "body" in a) {
1772      this.j = a.body.getReader();
1773      if (this.o) {
1774        if (this.responseType) throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');
1775        this.response = [];
1776      } else this.response = this.responseText = "", this.v = new TextDecoder();
1777      Nc(this);
1778    } else a.text().then(this.Ra.bind(this), this.ga.bind(this));
1779  };
1780  function Nc(a) {
1781    a.j.read().then(a.Pa.bind(a)).catch(a.ga.bind(a));
1782  }
1783  h.Pa = function(a) {
1784    if (this.g) {
1785      if (this.o && a.value) this.response.push(a.value);
1786      else if (!this.o) {
1787        var b = a.value ? a.value : new Uint8Array(0);
1788        if (b = this.v.decode(b, { stream: !a.done })) this.response = this.responseText += b;
1789      }
1790      a.done ? Mc(this) : Lc(this);
1791      3 == this.readyState && Nc(this);
1792    }
1793  };
1794  h.Ra = function(a) {
1795    this.g && (this.response = this.responseText = a, Mc(this));
1796  };
1797  h.Qa = function(a) {
1798    this.g && (this.response = a, Mc(this));
1799  };
1800  h.ga = function() {
1801    this.g && Mc(this);
1802  };
1803  function Mc(a) {
1804    a.readyState = 4;
1805    a.l = null;
1806    a.j = null;
1807    a.v = null;
1808    Lc(a);
1809  }
1810  h.setRequestHeader = function(a, b) {
1811    this.u.append(a, b);
1812  };
1813  h.getResponseHeader = function(a) {
1814    return this.h ? this.h.get(a.toLowerCase()) || "" : "";
1815  };
1816  h.getAllResponseHeaders = function() {
1817    if (!this.h) return "";
1818    const a = [], b = this.h.entries();
1819    for (var c = b.next(); !c.done; ) c = c.value, a.push(c[0] + ": " + c[1]), c = b.next();
1820    return a.join("\r\n");
1821  };
1822  function Lc(a) {
1823    a.onreadystatechange && a.onreadystatechange.call(a);
1824  }
1825  Object.defineProperty(Kc.prototype, "withCredentials", { get: function() {
1826    return "include" === this.m;
1827  }, set: function(a) {
1828    this.m = a ? "include" : "same-origin";
1829  } });
1830  function Oc(a) {
1831    let b = "";
1832    qa(a, function(c, d) {
1833      b += d;
1834      b += ":";
1835      b += c;
1836      b += "\r\n";
1837    });
1838    return b;
1839  }
1840  function Pc(a, b, c) {
1841    a: {
1842      for (d in c) {
1843        var d = false;
1844        break a;
1845      }
1846      d = true;
1847    }
1848    d || (c = Oc(c), "string" === typeof a ? null != c && encodeURIComponent(String(c)) : S(a, b, c));
1849  }
1850  function X2(a) {
1851    E.call(this);
1852    this.headers = /* @__PURE__ */ new Map();
1853    this.o = a || null;
1854    this.h = false;
1855    this.v = this.g = null;
1856    this.D = "";
1857    this.m = 0;
1858    this.l = "";
1859    this.j = this.B = this.u = this.A = false;
1860    this.I = null;
1861    this.H = "";
1862    this.J = false;
1863  }
1864  r(X2, E);
1865  var Qc = /^https?$/i, Rc = ["POST", "PUT"];
1866  h = X2.prototype;
1867  h.Ha = function(a) {
1868    this.J = a;
1869  };
1870  h.ea = function(a, b, c, d) {
1871    if (this.g) throw Error("[goog.net.XhrIo] Object is active with another request=" + this.D + "; newUri=" + a);
1872    b = b ? b.toUpperCase() : "GET";
1873    this.D = a;
1874    this.l = "";
1875    this.m = 0;
1876    this.A = false;
1877    this.h = true;
1878    this.g = this.o ? this.o.g() : Cb.g();
1879    this.v = this.o ? lb(this.o) : lb(Cb);
1880    this.g.onreadystatechange = p(this.Ea, this);
1881    try {
1882      this.B = true, this.g.open(b, String(a), true), this.B = false;
1883    } catch (f) {
1884      Sc(this, f);
1885      return;
1886    }
1887    a = c || "";
1888    c = new Map(this.headers);
1889    if (d) if (Object.getPrototypeOf(d) === Object.prototype) for (var e in d) c.set(e, d[e]);
1890    else if ("function" === typeof d.keys && "function" === typeof d.get) for (const f of d.keys()) c.set(f, d.get(f));
1891    else throw Error("Unknown input type for opt_headers: " + String(d));
1892    d = Array.from(c.keys()).find((f) => "content-type" == f.toLowerCase());
1893    e = k2.FormData && a instanceof k2.FormData;
1894    !(0 <= Array.prototype.indexOf.call(Rc, b, void 0)) || d || e || c.set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
1895    for (const [f, g] of c) this.g.setRequestHeader(f, g);
1896    this.H && (this.g.responseType = this.H);
1897    "withCredentials" in this.g && this.g.withCredentials !== this.J && (this.g.withCredentials = this.J);
1898    try {
1899      Tc(this), this.u = true, this.g.send(a), this.u = false;
1900    } catch (f) {
1901      Sc(this, f);
1902    }
1903  };
1904  function Sc(a, b) {
1905    a.h = false;
1906    a.g && (a.j = true, a.g.abort(), a.j = false);
1907    a.l = b;
1908    a.m = 5;
1909    Uc(a);
1910    Vc(a);
1911  }
1912  function Uc(a) {
1913    a.A || (a.A = true, F2(a, "complete"), F2(a, "error"));
1914  }
1915  h.abort = function(a) {
1916    this.g && this.h && (this.h = false, this.j = true, this.g.abort(), this.j = false, this.m = a || 7, F2(this, "complete"), F2(this, "abort"), Vc(this));
1917  };
1918  h.N = function() {
1919    this.g && (this.h && (this.h = false, this.j = true, this.g.abort(), this.j = false), Vc(this, true));
1920    X2.aa.N.call(this);
1921  };
1922  h.Ea = function() {
1923    this.s || (this.B || this.u || this.j ? Wc(this) : this.bb());
1924  };
1925  h.bb = function() {
1926    Wc(this);
1927  };
1928  function Wc(a) {
1929    if (a.h && "undefined" != typeof fa && (!a.v[1] || 4 != P(a) || 2 != a.Z())) {
1930      if (a.u && 4 == P(a)) bb(a.Ea, 0, a);
1931      else if (F2(a, "readystatechange"), 4 == P(a)) {
1932        a.h = false;
1933        try {
1934          const g = a.Z();
1935          a: switch (g) {
1936            case 200:
1937            case 201:
1938            case 202:
1939            case 204:
1940            case 206:
1941            case 304:
1942            case 1223:
1943              var b = true;
1944              break a;
1945            default:
1946              b = false;
1947          }
1948          var c;
1949          if (!(c = b)) {
1950            var d;
1951            if (d = 0 === g) {
1952              var e = String(a.D).match(oc)[1] || null;
1953              !e && k2.self && k2.self.location && (e = k2.self.location.protocol.slice(0, -1));
1954              d = !Qc.test(e ? e.toLowerCase() : "");
1955            }
1956            c = d;
1957          }
1958          if (c) F2(a, "complete"), F2(a, "success");
1959          else {
1960            a.m = 6;
1961            try {
1962              var f = 2 < P(a) ? a.g.statusText : "";
1963            } catch (m) {
1964              f = "";
1965            }
1966            a.l = f + " [" + a.Z() + "]";
1967            Uc(a);
1968          }
1969        } finally {
1970          Vc(a);
1971        }
1972      }
1973    }
1974  }
1975  function Vc(a, b) {
1976    if (a.g) {
1977      Tc(a);
1978      const c = a.g, d = a.v[0] ? () => {
1979      } : null;
1980      a.g = null;
1981      a.v = null;
1982      b || F2(a, "ready");
1983      try {
1984        c.onreadystatechange = d;
1985      } catch (e) {
1986      }
1987    }
1988  }
1989  function Tc(a) {
1990    a.I && (k2.clearTimeout(a.I), a.I = null);
1991  }
1992  h.isActive = function() {
1993    return !!this.g;
1994  };
1995  function P(a) {
1996    return a.g ? a.g.readyState : 0;
1997  }
1998  h.Z = function() {
1999    try {
2000      return 2 < P(this) ? this.g.status : -1;
2001    } catch (a) {
2002      return -1;
2003    }
2004  };
2005  h.oa = function() {
2006    try {
2007      return this.g ? this.g.responseText : "";
2008    } catch (a) {
2009      return "";
2010    }
2011  };
2012  h.Oa = function(a) {
2013    if (this.g) {
2014      var b = this.g.responseText;
2015      a && 0 == b.indexOf(a) && (b = b.substring(a.length));
2016      return ib(b);
2017    }
2018  };
2019  function Nb(a) {
2020    try {
2021      if (!a.g) return null;
2022      if ("response" in a.g) return a.g.response;
2023      switch (a.H) {
2024        case "":
2025        case "text":
2026          return a.g.responseText;
2027        case "arraybuffer":
2028          if ("mozResponseArrayBuffer" in a.g) return a.g.mozResponseArrayBuffer;
2029      }
2030      return null;
2031    } catch (b) {
2032      return null;
2033    }
2034  }
2035  function Vb(a) {
2036    const b = {};
2037    a = (a.g && 2 <= P(a) ? a.g.getAllResponseHeaders() || "" : "").split("\r\n");
2038    for (let d = 0; d < a.length; d++) {
2039      if (t(a[d])) continue;
2040      var c = va(a[d]);
2041      const e = c[0];
2042      c = c[1];
2043      if ("string" !== typeof c) continue;
2044      c = c.trim();
2045      const f = b[e] || [];
2046      b[e] = f;
2047      f.push(c);
2048    }
2049    ra(b, function(d) {
2050      return d.join(", ");
2051    });
2052  }
2053  h.Ba = function() {
2054    return this.m;
2055  };
2056  h.Ka = function() {
2057    return "string" === typeof this.l ? this.l : String(this.l);
2058  };
2059  function Xc(a, b, c) {
2060    return c && c.internalChannelParams ? c.internalChannelParams[a] || b : b;
2061  }
2062  function Yc(a) {
2063    this.Aa = 0;
2064    this.i = [];
2065    this.j = new vb();
2066    this.ia = this.qa = this.I = this.W = this.g = this.ya = this.D = this.H = this.m = this.S = this.o = null;
2067    this.Ya = this.U = 0;
2068    this.Va = Xc("failFast", false, a);
2069    this.F = this.C = this.u = this.s = this.l = null;
2070    this.X = true;
2071    this.za = this.T = -1;
2072    this.Y = this.v = this.B = 0;
2073    this.Ta = Xc("baseRetryDelayMs", 5e3, a);
2074    this.cb = Xc("retryDelaySeedMs", 1e4, a);
2075    this.Wa = Xc("forwardChannelMaxRetries", 2, a);
2076    this.wa = Xc("forwardChannelRequestTimeoutMs", 2e4, a);
2077    this.pa = a && a.xmlHttpFactory || void 0;
2078    this.Xa = a && a.Tb || void 0;
2079    this.Ca = a && a.useFetchStreams || false;
2080    this.L = void 0;
2081    this.J = a && a.supportsCrossDomainXhr || false;
2082    this.K = "";
2083    this.h = new ic(a && a.concurrentRequestLimit);
2084    this.Da = new Hc();
2085    this.P = a && a.fastHandshake || false;
2086    this.O = a && a.encodeInitMessageHeaders || false;
2087    this.P && this.O && (this.O = false);
2088    this.Ua = a && a.Rb || false;
2089    a && a.xa && this.j.xa();
2090    a && a.forceLongPolling && (this.X = false);
2091    this.ba = !this.P && this.X && a && a.detectBufferingProxy || false;
2092    this.ja = void 0;
2093    a && a.longPollingTimeout && 0 < a.longPollingTimeout && (this.ja = a.longPollingTimeout);
2094    this.ca = void 0;
2095    this.R = 0;
2096    this.M = false;
2097    this.ka = this.A = null;
2098  }
2099  h = Yc.prototype;
2100  h.la = 8;
2101  h.G = 1;
2102  h.connect = function(a, b, c, d) {
2103    K2(0);
2104    this.W = a;
2105    this.H = b || {};
2106    c && void 0 !== d && (this.H.OSID = c, this.H.OAID = d);
2107    this.F = this.X;
2108    this.I = cc(this, null, this.W);
2109    fc(this);
2110  };
2111  function gc(a) {
2112    Zc(a);
2113    if (3 == a.G) {
2114      var b = a.U++, c = N2(a.I);
2115      S(c, "SID", a.K);
2116      S(c, "RID", b);
2117      S(c, "TYPE", "terminate");
2118      $c(a, c);
2119      b = new M2(a, a.j, b);
2120      b.L = 2;
2121      b.v = Ib(N2(c));
2122      c = false;
2123      if (k2.navigator && k2.navigator.sendBeacon) try {
2124        c = k2.navigator.sendBeacon(b.v.toString(), "");
2125      } catch (d) {
2126      }
2127      !c && k2.Image && (new Image().src = b.v, c = true);
2128      c || (b.g = Mb(b.j, null), b.g.ea(b.v));
2129      b.F = Date.now();
2130      Kb(b);
2131    }
2132    ad(a);
2133  }
2134  function Zb(a) {
2135    a.g && (Tb(a), a.g.cancel(), a.g = null);
2136  }
2137  function Zc(a) {
2138    Zb(a);
2139    a.u && (k2.clearTimeout(a.u), a.u = null);
2140    Yb(a);
2141    a.h.cancel();
2142    a.s && ("number" === typeof a.s && k2.clearTimeout(a.s), a.s = null);
2143  }
2144  function fc(a) {
2145    if (!jc(a.h) && !a.s) {
2146      a.s = true;
2147      var b = a.Ga;
2148      x2 || Ea();
2149      y || (x2(), y = true);
2150      za.add(b, a);
2151      a.B = 0;
2152    }
2153  }
2154  function bd(a, b) {
2155    if (ac(a.h) >= a.h.j - (a.s ? 1 : 0)) return false;
2156    if (a.s) return a.i = b.D.concat(a.i), true;
2157    if (1 == a.G || 2 == a.G || a.B >= (a.Va ? 0 : a.Wa)) return false;
2158    a.s = ub(p(a.Ga, a, b), cd(a, a.B));
2159    a.B++;
2160    return true;
2161  }
2162  h.Ga = function(a) {
2163    if (this.s) if (this.s = null, 1 == this.G) {
2164      if (!a) {
2165        this.U = Math.floor(1e5 * Math.random());
2166        a = this.U++;
2167        const e = new M2(this, this.j, a);
2168        let f = this.o;
2169        this.S && (f ? (f = sa(f), ua(f, this.S)) : f = this.S);
2170        null !== this.m || this.O || (e.H = f, f = null);
2171        if (this.P) a: {
2172          var b = 0;
2173          for (var c = 0; c < this.i.length; c++) {
2174            b: {
2175              var d = this.i[c];
2176              if ("__data__" in d.map && (d = d.map.__data__, "string" === typeof d)) {
2177                d = d.length;
2178                break b;
2179              }
2180              d = void 0;
2181            }
2182            if (void 0 === d) break;
2183            b += d;
2184            if (4096 < b) {
2185              b = c;
2186              break a;
2187            }
2188            if (4096 === b || c === this.i.length - 1) {
2189              b = c + 1;
2190              break a;
2191            }
2192          }
2193          b = 1e3;
2194        }
2195        else b = 1e3;
2196        b = dd(this, e, b);
2197        c = N2(this.I);
2198        S(c, "RID", a);
2199        S(c, "CVER", 22);
2200        this.D && S(c, "X-HTTP-Session-Id", this.D);
2201        $c(this, c);
2202        f && (this.O ? b = "headers=" + encodeURIComponent(String(Oc(f))) + "&" + b : this.m && Pc(c, this.m, f));
2203        bc(this.h, e);
2204        this.Ua && S(c, "TYPE", "init");
2205        this.P ? (S(c, "$req", b), S(c, "SID", "null"), e.T = true, Hb(e, c, null)) : Hb(e, c, b);
2206        this.G = 2;
2207      }
2208    } else 3 == this.G && (a ? ed(this, a) : 0 == this.i.length || jc(this.h) || ed(this));
2209  };
2210  function ed(a, b) {
2211    var c;
2212    b ? c = b.l : c = a.U++;
2213    const d = N2(a.I);
2214    S(d, "SID", a.K);
2215    S(d, "RID", c);
2216    S(d, "AID", a.T);
2217    $c(a, d);
2218    a.m && a.o && Pc(d, a.m, a.o);
2219    c = new M2(a, a.j, c, a.B + 1);
2220    null === a.m && (c.H = a.o);
2221    b && (a.i = b.D.concat(a.i));
2222    b = dd(a, c, 1e3);
2223    c.I = Math.round(0.5 * a.wa) + Math.round(0.5 * a.wa * Math.random());
2224    bc(a.h, c);
2225    Hb(c, d, b);
2226  }
2227  function $c(a, b) {
2228    a.H && qa(a.H, function(c, d) {
2229      S(b, d, c);
2230    });
2231    a.l && nc({}, function(c, d) {
2232      S(b, d, c);
2233    });
2234  }
2235  function dd(a, b, c) {
2236    c = Math.min(a.i.length, c);
2237    var d = a.l ? p(a.l.Na, a.l, a) : null;
2238    a: {
2239      var e = a.i;
2240      let f = -1;
2241      for (; ; ) {
2242        const g = ["count=" + c];
2243        -1 == f ? 0 < c ? (f = e[0].g, g.push("ofs=" + f)) : f = 0 : g.push("ofs=" + f);
2244        let m = true;
2245        for (let q2 = 0; q2 < c; q2++) {
2246          let l = e[q2].g;
2247          const v = e[q2].map;
2248          l -= f;
2249          if (0 > l) f = Math.max(0, e[q2].g - 100), m = false;
2250          else try {
2251            Ic(v, g, "req" + l + "_");
2252          } catch (w) {
2253            d && d(v);
2254          }
2255        }
2256        if (m) {
2257          d = g.join("&");
2258          break a;
2259        }
2260      }
2261    }
2262    a = a.i.splice(0, c);
2263    b.D = a;
2264    return d;
2265  }
2266  function ec(a) {
2267    if (!a.g && !a.u) {
2268      a.Y = 1;
2269      var b = a.Fa;
2270      x2 || Ea();
2271      y || (x2(), y = true);
2272      za.add(b, a);
2273      a.v = 0;
2274    }
2275  }
2276  function $b(a) {
2277    if (a.g || a.u || 3 <= a.v) return false;
2278    a.Y++;
2279    a.u = ub(p(a.Fa, a), cd(a, a.v));
2280    a.v++;
2281    return true;
2282  }
2283  h.Fa = function() {
2284    this.u = null;
2285    fd(this);
2286    if (this.ba && !(this.M || null == this.g || 0 >= this.R)) {
2287      var a = 2 * this.R;
2288      this.j.info("BP detection timer enabled: " + a);
2289      this.A = ub(p(this.ab, this), a);
2290    }
2291  };
2292  h.ab = function() {
2293    this.A && (this.A = null, this.j.info("BP detection timeout reached."), this.j.info("Buffering proxy detected and switch to long-polling!"), this.F = false, this.M = true, K2(10), Zb(this), fd(this));
2294  };
2295  function Tb(a) {
2296    null != a.A && (k2.clearTimeout(a.A), a.A = null);
2297  }
2298  function fd(a) {
2299    a.g = new M2(a, a.j, "rpc", a.Y);
2300    null === a.m && (a.g.H = a.o);
2301    a.g.O = 0;
2302    var b = N2(a.qa);
2303    S(b, "RID", "rpc");
2304    S(b, "SID", a.K);
2305    S(b, "AID", a.T);
2306    S(b, "CI", a.F ? "0" : "1");
2307    !a.F && a.ja && S(b, "TO", a.ja);
2308    S(b, "TYPE", "xmlhttp");
2309    $c(a, b);
2310    a.m && a.o && Pc(b, a.m, a.o);
2311    a.L && (a.g.I = a.L);
2312    var c = a.g;
2313    a = a.ia;
2314    c.L = 1;
2315    c.v = Ib(N2(b));
2316    c.m = null;
2317    c.P = true;
2318    Jb(c, a);
2319  }
2320  h.Za = function() {
2321    null != this.C && (this.C = null, Zb(this), $b(this), K2(19));
2322  };
2323  function Yb(a) {
2324    null != a.C && (k2.clearTimeout(a.C), a.C = null);
2325  }
2326  function Ub(a, b) {
2327    var c = null;
2328    if (a.g == b) {
2329      Yb(a);
2330      Tb(a);
2331      a.g = null;
2332      var d = 2;
2333    } else if (Xb(a.h, b)) c = b.D, dc(a.h, b), d = 1;
2334    else return;
2335    if (0 != a.G) {
2336      if (b.o) if (1 == d) {
2337        c = b.m ? b.m.length : 0;
2338        b = Date.now() - b.F;
2339        var e = a.B;
2340        d = qb();
2341        F2(d, new tb(d, c));
2342        fc(a);
2343      } else ec(a);
2344      else if (e = b.s, 3 == e || 0 == e && 0 < b.X || !(1 == d && bd(a, b) || 2 == d && $b(a))) switch (c && 0 < c.length && (b = a.h, b.i = b.i.concat(c)), e) {
2345        case 1:
2346          R(a, 5);
2347          break;
2348        case 4:
2349          R(a, 10);
2350          break;
2351        case 3:
2352          R(a, 6);
2353          break;
2354        default:
2355          R(a, 2);
2356      }
2357    }
2358  }
2359  function cd(a, b) {
2360    let c = a.Ta + Math.floor(Math.random() * a.cb);
2361    a.isActive() || (c *= 2);
2362    return c * b;
2363  }
2364  function R(a, b) {
2365    a.j.info("Error code " + b);
2366    if (2 == b) {
2367      var c = p(a.fb, a), d = a.Xa;
2368      const e = !d;
2369      d = new T(d || "//www.google.com/images/cleardot.gif");
2370      k2.location && "http" == k2.location.protocol || qc(d, "https");
2371      Ib(d);
2372      e ? Fc(d.toString(), c) : Gc(d.toString(), c);
2373    } else K2(2);
2374    a.G = 0;
2375    a.l && a.l.sa(b);
2376    ad(a);
2377    Zc(a);
2378  }
2379  h.fb = function(a) {
2380    a ? (this.j.info("Successfully pinged google.com"), K2(2)) : (this.j.info("Failed to ping google.com"), K2(1));
2381  };
2382  function ad(a) {
2383    a.G = 0;
2384    a.ka = [];
2385    if (a.l) {
2386      const b = kc(a.h);
2387      if (0 != b.length || 0 != a.i.length) ma(a.ka, b), ma(a.ka, a.i), a.h.i.length = 0, la(a.i), a.i.length = 0;
2388      a.l.ra();
2389    }
2390  }
2391  function cc(a, b, c) {
2392    var d = c instanceof T ? N2(c) : new T(c);
2393    if ("" != d.g) b && (d.g = b + "." + d.g), rc(d, d.s);
2394    else {
2395      var e = k2.location;
2396      d = e.protocol;
2397      b = b ? b + "." + e.hostname : e.hostname;
2398      e = +e.port;
2399      var f = new T(null);
2400      d && qc(f, d);
2401      b && (f.g = b);
2402      e && rc(f, e);
2403      c && (f.l = c);
2404      d = f;
2405    }
2406    c = a.D;
2407    b = a.ya;
2408    c && b && S(d, c, b);
2409    S(d, "VER", a.la);
2410    $c(a, d);
2411    return d;
2412  }
2413  function Mb(a, b, c) {
2414    if (b && !a.J) throw Error("Can't create secondary domain capable XhrIo object.");
2415    b = a.Ca && !a.pa ? new X2(new Jc({ eb: c })) : new X2(a.pa);
2416    b.Ha(a.J);
2417    return b;
2418  }
2419  h.isActive = function() {
2420    return !!this.l && this.l.isActive(this);
2421  };
2422  function gd() {
2423  }
2424  h = gd.prototype;
2425  h.ua = function() {
2426  };
2427  h.ta = function() {
2428  };
2429  h.sa = function() {
2430  };
2431  h.ra = function() {
2432  };
2433  h.isActive = function() {
2434    return true;
2435  };
2436  h.Na = function() {
2437  };
2438  function hd() {
2439  }
2440  hd.prototype.g = function(a, b) {
2441    return new Y2(a, b);
2442  };
2443  function Y2(a, b) {
2444    E.call(this);
2445    this.g = new Yc(b);
2446    this.l = a;
2447    this.h = b && b.messageUrlParams || null;
2448    a = b && b.messageHeaders || null;
2449    b && b.clientProtocolHeaderRequired && (a ? a["X-Client-Protocol"] = "webchannel" : a = { "X-Client-Protocol": "webchannel" });
2450    this.g.o = a;
2451    a = b && b.initMessageHeaders || null;
2452    b && b.messageContentType && (a ? a["X-WebChannel-Content-Type"] = b.messageContentType : a = { "X-WebChannel-Content-Type": b.messageContentType });
2453    b && b.va && (a ? a["X-WebChannel-Client-Profile"] = b.va : a = { "X-WebChannel-Client-Profile": b.va });
2454    this.g.S = a;
2455    (a = b && b.Sb) && !t(a) && (this.g.m = a);
2456    this.v = b && b.supportsCrossDomainXhr || false;
2457    this.u = b && b.sendRawJson || false;
2458    (b = b && b.httpSessionIdParam) && !t(b) && (this.g.D = b, a = this.h, null !== a && b in a && (a = this.h, b in a && delete a[b]));
2459    this.j = new Z2(this);
2460  }
2461  r(Y2, E);
2462  Y2.prototype.m = function() {
2463    this.g.l = this.j;
2464    this.v && (this.g.J = true);
2465    this.g.connect(this.l, this.h || void 0);
2466  };
2467  Y2.prototype.close = function() {
2468    gc(this.g);
2469  };
2470  Y2.prototype.o = function(a) {
2471    var b = this.g;
2472    if ("string" === typeof a) {
2473      var c = {};
2474      c.__data__ = a;
2475      a = c;
2476    } else this.u && (c = {}, c.__data__ = hb(a), a = c);
2477    b.i.push(new hc(b.Ya++, a));
2478    3 == b.G && fc(b);
2479  };
2480  Y2.prototype.N = function() {
2481    this.g.l = null;
2482    delete this.j;
2483    gc(this.g);
2484    delete this.g;
2485    Y2.aa.N.call(this);
2486  };
2487  function id(a) {
2488    nb.call(this);
2489    a.__headers__ && (this.headers = a.__headers__, this.statusCode = a.__status__, delete a.__headers__, delete a.__status__);
2490    var b = a.__sm__;
2491    if (b) {
2492      a: {
2493        for (const c in b) {
2494          a = c;
2495          break a;
2496        }
2497        a = void 0;
2498      }
2499      if (this.i = a) a = this.i, b = null !== b && a in b ? b[a] : void 0;
2500      this.data = b;
2501    } else this.data = a;
2502  }
2503  r(id, nb);
2504  function jd() {
2505    ob.call(this);
2506    this.status = 1;
2507  }
2508  r(jd, ob);
2509  function Z2(a) {
2510    this.g = a;
2511  }
2512  r(Z2, gd);
2513  Z2.prototype.ua = function() {
2514    F2(this.g, "a");
2515  };
2516  Z2.prototype.ta = function(a) {
2517    F2(this.g, new id(a));
2518  };
2519  Z2.prototype.sa = function(a) {
2520    F2(this.g, new jd());
2521  };
2522  Z2.prototype.ra = function() {
2523    F2(this.g, "b");
2524  };
2525  hd.prototype.createWebChannel = hd.prototype.g;
2526  Y2.prototype.send = Y2.prototype.o;
2527  Y2.prototype.open = Y2.prototype.m;
2528  Y2.prototype.close = Y2.prototype.close;
2529  createWebChannelTransport = function() {
2530    return new hd();
2531  };
2532  getStatEventTarget = function() {
2533    return qb();
2534  };
2535  Event = I;
2536  Stat = { mb: 0, pb: 1, qb: 2, Jb: 3, Ob: 4, Lb: 5, Mb: 6, Kb: 7, Ib: 8, Nb: 9, PROXY: 10, NOPROXY: 11, Gb: 12, Cb: 13, Db: 14, Bb: 15, Eb: 16, Fb: 17, ib: 18, hb: 19, jb: 20 };
2537  Ab.NO_ERROR = 0;
2538  Ab.TIMEOUT = 8;
2539  Ab.HTTP_ERROR = 6;
2540  ErrorCode = Ab;
2541  Bb.COMPLETE = "complete";
2542  EventType = Bb;
2543  mb.EventType = H2;
2544  H2.OPEN = "a";
2545  H2.CLOSE = "b";
2546  H2.ERROR = "c";
2547  H2.MESSAGE = "d";
2548  E.prototype.listen = E.prototype.K;
2549  WebChannel = mb;
2550  X2.prototype.listenOnce = X2.prototype.L;
2551  X2.prototype.getLastError = X2.prototype.Ka;
2552  X2.prototype.getLastErrorCode = X2.prototype.Ba;
2553  X2.prototype.getStatus = X2.prototype.Z;
2554  X2.prototype.getResponseJson = X2.prototype.Oa;
2555  X2.prototype.getResponseText = X2.prototype.oa;
2556  X2.prototype.send = X2.prototype.ea;
2557  X2.prototype.setWithCredentials = X2.prototype.Ha;
2558  XhrIo = X2;
2559}).apply(typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
2560const F = "@firebase/firestore", M = "4.8.0";
2561/**
2562 * @license
2563 * Copyright 2017 Google LLC
2564 *
2565 * Licensed under the Apache License, Version 2.0 (the "License");
2566 * you may not use this file except in compliance with the License.
2567 * You may obtain a copy of the License at
2568 *
2569 *   http://www.apache.org/licenses/LICENSE-2.0
2570 *
2571 * Unless required by applicable law or agreed to in writing, software
2572 * distributed under the License is distributed on an "AS IS" BASIS,
2573 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2574 * See the License for the specific language governing permissions and
2575 * limitations under the License.
2576 */
2577class User {
2578  constructor(e) {
2579    this.uid = e;
2580  }
2581  isAuthenticated() {
2582    return null != this.uid;
2583  }
2584  /**
2585   * Returns a key representing this user, suitable for inclusion in a
2586   * dictionary.
2587   */
2588  toKey() {
2589    return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
2590  }
2591  isEqual(e) {
2592    return e.uid === this.uid;
2593  }
2594}
2595User.UNAUTHENTICATED = new User(null), // TODO(mikelehen): Look into getting a proper uid-equivalent for
2596// non-FirebaseAuth providers.
2597User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), User.MOCK_USER = new User("mock-user");
2598/**
2599 * @license
2600 * Copyright 2017 Google LLC
2601 *
2602 * Licensed under the Apache License, Version 2.0 (the "License");
2603 * you may not use this file except in compliance with the License.
2604 * You may obtain a copy of the License at
2605 *
2606 *   http://www.apache.org/licenses/LICENSE-2.0
2607 *
2608 * Unless required by applicable law or agreed to in writing, software
2609 * distributed under the License is distributed on an "AS IS" BASIS,
2610 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2611 * See the License for the specific language governing permissions and
2612 * limitations under the License.
2613 */
2614let x = "11.10.0";
2615/**
2616 * @license
2617 * Copyright 2017 Google LLC
2618 *
2619 * Licensed under the Apache License, Version 2.0 (the "License");
2620 * you may not use this file except in compliance with the License.
2621 * You may obtain a copy of the License at
2622 *
2623 *   http://www.apache.org/licenses/LICENSE-2.0
2624 *
2625 * Unless required by applicable law or agreed to in writing, software
2626 * distributed under the License is distributed on an "AS IS" BASIS,
2627 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2628 * See the License for the specific language governing permissions and
2629 * limitations under the License.
2630 */
2631const O = new Logger("@firebase/firestore");
2632function __PRIVATE_getLogLevel() {
2633  return O.logLevel;
2634}
2635function setLogLevel(e) {
2636  O.setLogLevel(e);
2637}
2638function __PRIVATE_logDebug(e, ...t) {
2639  if (O.logLevel <= LogLevel.DEBUG) {
2640    const n = t.map(__PRIVATE_argToString);
2641    O.debug(`Firestore (${x}): ${e}`, ...n);
2642  }
2643}
2644function __PRIVATE_logError(e, ...t) {
2645  if (O.logLevel <= LogLevel.ERROR) {
2646    const n = t.map(__PRIVATE_argToString);
2647    O.error(`Firestore (${x}): ${e}`, ...n);
2648  }
2649}
2650function __PRIVATE_logWarn(e, ...t) {
2651  if (O.logLevel <= LogLevel.WARN) {
2652    const n = t.map(__PRIVATE_argToString);
2653    O.warn(`Firestore (${x}): ${e}`, ...n);
2654  }
2655}
2656function __PRIVATE_argToString(e) {
2657  if ("string" == typeof e) return e;
2658  try {
2659    /**
2660    * @license
2661    * Copyright 2020 Google LLC
2662    *
2663    * Licensed under the Apache License, Version 2.0 (the "License");
2664    * you may not use this file except in compliance with the License.
2665    * You may obtain a copy of the License at
2666    *
2667    *   http://www.apache.org/licenses/LICENSE-2.0
2668    *
2669    * Unless required by applicable law or agreed to in writing, software
2670    * distributed under the License is distributed on an "AS IS" BASIS,
2671    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2672    * See the License for the specific language governing permissions and
2673    * limitations under the License.
2674    */
2675    return function __PRIVATE_formatJSON(e2) {
2676      return JSON.stringify(e2);
2677    }(e);
2678  } catch (t) {
2679    return e;
2680  }
2681}
2682/**
2683 * @license
2684 * Copyright 2017 Google LLC
2685 *
2686 * Licensed under the Apache License, Version 2.0 (the "License");
2687 * you may not use this file except in compliance with the License.
2688 * You may obtain a copy of the License at
2689 *
2690 *   http://www.apache.org/licenses/LICENSE-2.0
2691 *
2692 * Unless required by applicable law or agreed to in writing, softw
2692are
2693 * distributed under the License is distributed on an "AS IS" BASIS,
2694 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2695 * See the License for the specific language governing permissions and
2696 * limitations under the License.
2697 */
2698function fail(e, t, n) {
2699  let r = "Unexpected state";
2700  "string" == typeof t ? r = t : n = t, __PRIVATE__fail(e, r, n);
2701}
2702function __PRIVATE__fail(e, t, n) {
2703  let r = `FIRESTORE (${x}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;
2704  if (void 0 !== n) try {
2705    r += " CONTEXT: " + JSON.stringify(n);
2706  } catch (e2) {
2707    r += " CONTEXT: " + n;
2708  }
2709  throw __PRIVATE_logError(r), new Error(r);
2710}
2711function __PRIVATE_hardAssert(e, t, n, r) {
2712  let i = "Unexpected state";
2713  "string" == typeof n ? i = n : r = n, e || __PRIVATE__fail(t, i, r);
2714}
2715function __PRIVATE_debugAssert(e, t) {
2716  e || fail(57014, t);
2717}
2718function __PRIVATE_debugCast(e, t) {
2719  return e;
2720}
2721/**
2722 * @license
2723 * Copyright 2017 Google LLC
2724 *
2725 * Licensed under the Apache License, Version 2.0 (the "License");
2726 * you may not use this file except in compliance with the License.
2727 * You may obtain a copy of the License at
2728 *
2729 *   http://www.apache.org/licenses/LICENSE-2.0
2730 *
2731 * Unless required by applicable law or agreed to in writing, software
2732 * distributed under the License is distributed on an "AS IS" BASIS,
2733 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2734 * See the License for the specific language governing permissions and
2735 * limitations under the License.
2736 */
2737const N = {
2738  // Causes are copied from:
2739  // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
2740  /** Not an error; returned on success. */
2741  OK: "ok",
2742  /** The operation was cancelled (typically by the caller). */
2743  CANCELLED: "cancelled",
2744  /** Unknown error or an error from a different error domain. */
2745  UNKNOWN: "unknown",
2746  /**
2747   * Client specified an invalid argument. Note that this differs from
2748   * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
2749   * problematic regardless of the state of the system (e.g., a malformed file
2750   * name).
2751   */
2752  INVALID_ARGUMENT: "invalid-argument",
2753  /**
2754   * Deadline expired before operation could complete. For operations that
2755   * change the state of the system, this error may be returned even if the
2756   * operation has completed successfully. For example, a successful response
2757   * from a server could have been delayed long enough for the deadline to
2758   * expire.
2759   */
2760  DEADLINE_EXCEEDED: "deadline-exceeded",
2761  /** Some requested entity (e.g., file or directory) was not found. */
2762  NOT_FOUND: "not-found",
2763  /**
2764   * Some entity that we attempted to create (e.g., file or directory) already
2765   * exists.
2766   */
2767  ALREADY_EXISTS: "already-exists",
2768  /**
2769   * The caller does not have permission to execute the specified operation.
2770   * PERMISSION_DENIED must not be used for rejections caused by exhausting
2771   * some resource (use RESOURCE_EXHAUSTED instead for those errors).
2772   * PERMISSION_DENIED must not be used if the caller cannot be identified
2773   * (use UNAUTHENTICATED instead for those errors).
2774   */
2775  PERMISSION_DENIED: "permission-denied",
2776  /**
2777   * The request does not have valid authentication credentials for the
2778   * operation.
2779   */
2780  UNAUTHENTICATED: "unauthenticated",
2781  /**
2782   * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
2783   * entire file system is out of space.
2784   */
2785  RESOURCE_EXHAUSTED: "resource-exhausted",
2786  /**
2787   * Operation was rejected because the system is not in a state required for
2788   * the operation's execution. For example, directory to be deleted may be
2789   * non-empty, an rmdir operation is applied to a non-directory, etc.
2790   *
2791   * A litmus test that may help a service implementor in deciding
2792   * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
2793   *  (a) Use UNAVAILABLE if the client can retry just the failing call.
2794   *  (b) Use ABORTED if the client should retry at a higher-level
2795   *      (e.g., restarting a read-modify-write sequence).
2796   *  (c) Use FAILED_PRECONDITION if the client should not retry until
2797   *      the system state has been explicitly fixed. E.g., if an "rmdir"
2798   *      fails because the directory is non-empty, FAILED_PRECONDITION
2799   *      should be returned since the client should not retry unless
2800   *      they have first fixed up the directory by deleting files from it.
2801   *  (d) Use FAILED_PRECONDITION if the client performs conditional
2802   *      REST Get/Update/Delete on a resource and the resource on the
2803   *      server does not match the condition. E.g., conflicting
2804   *      read-modify-write on the same resource.
2805   */
2806  FAILED_PRECONDITION: "failed-precondition",
2807  /**
2808   * The operation was aborted, typically due to a concurrency issue like
2809   * sequencer check failures, transaction aborts, etc.
2810   *
2811   * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
2812   * and UNAVAILABLE.
2813   */
2814  ABORTED: "aborted",
2815  /**
2816   * Operation was attempted past the valid range. E.g., seeking or reading
2817   * past end of file.
2818   *
2819   * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
2820   * if the system state changes. For example, a 32-bit file system will
2821   * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
2822   * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
2823   * an offset past the current file size.
2824   *
2825   * There is a fair bit of overlap between FAILED_PRECONDITION and
2826   * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
2827   * when it applies so that callers who are iterating through a space can
2828   * easily look for an OUT_OF_RANGE error to detect when they are done.
2829   */
2830  OUT_OF_RANGE: "out-of-range",
2831  /** Operation is not implemented or not supported/enabled in this service. */
2832  UNIMPLEMENTED: "unimplemented",
2833  /**
2834   * Internal errors. Means some invariants expected by underlying System has
2835   * been broken. If you see one of these errors, Something is very broken.
2836   */
2837  INTERNAL: "internal",
2838  /**
2839   * The service is currently unavailable. This is a most likely a transient
2840   * condition and may be corrected by retrying with a backoff.
2841   *
2842   * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
2843   * and UNAVAILABLE.
2844   */
2845  UNAVAILABLE: "unavailable",
2846  /** Unrecoverable data loss or corruption. */
2847  DATA_LOSS: "data-loss"
2848};
2849class FirestoreError extends FirebaseError {
2850  /** @hideconstructor */
2851  constructor(e, t) {
2852    super(e, t), this.code = e, this.message = t, // HACK: We write a toString property directly because Error is not a real
2853    // class and so inheritance does not work correctly. We could alternatively
2854    // do the same "back-door inheritance" trick that FirebaseError does.
2855    this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
2856  }
2857}
2858/**
2859 * @license
2860 * Copyright 2017 Google LLC
2861 *
2862 * Licensed under the Apache License, Version 2.0 (the "License");
2863 * you may not use this file except in compliance with the License.
2864 * You may obtain a copy of the License at
2865 *
2866 *   http://www.apache.org/licenses/LICENSE-2.0
2867 *
2868 * Unless required by applicable law or agreed to in writing, software
2869 * distributed under the License is distributed on an "AS IS" BASIS,
2870 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2871 * See the License for the specific language governing permissions and
2872 * limitations under the License.
2873 */
2874class __PRIVATE_Deferred {
2875  constructor() {
2876    this.promise = new Promise((e, t) => {
2877      this.resolve = e, this.reject = t;
2878    });
2879  }
2880}
2881/**
2882 * @license
2883 * Copyright 2017 Google LLC
2884 *
2885 * Licensed under the Apache License, Version 2.0 (the "License");
2886 * you may not use this file except in compliance with the License.
2887 * You may obtain a copy of the License at
2888 *
2889 *   http://www.apache.org/licenses/LICENSE-2.0
2890 *
2891 * Unless required by applicable law or agreed to in writing, software
2892 * distributed under the License is distributed on an "AS IS" BASIS,
2893 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2894 * See the License for the specific language governing permissions and
2895 * limitations under the License.
2896 */
2897class __PRIVATE_OAuthToken {
2898  constructor(e, t) {
2899    this.user = t, this.type = "OAuth", this.headers = /* @__PURE__ */ new Map(), this.headers.set("Authorization", `Bearer ${e}`);
2900  }
2901}
2902class __PRIVATE_EmptyAuthCredentialsProvider {
2903  getToken() {
2904    return Promise.resolve(null);
2905  }
2906  invalidateToken() {
2907  }
2908  start(e, t) {
2909    e.enqueueRetryable(() => t(User.UNAUTHENTICATED));
2910  }
2911  shutdown() {
2912  }
2913}
2914class __PRIVATE_EmulatorAuthCredentialsProvider {
2915  constructor(e) {
2916    this.token = e, /**
2917    * Stores the listener registered with setChangeListener()
2918    * This isn't actually necessary since the UID never changes, but we use this
2919    * to verify the listen contract is adhered to in tests.
2920    */
2921    this.changeListener = null;
2922  }
2923  getToken() {
2924    return Promise.resolve(this.token);
2925  }
2926  invalidateToken() {
2927  }
2928  start(e, t) {
2929    this.changeListener = t, // Fire with initial user.
2930    e.enqueueRetryable(() => t(this.token.user));
2931  }
2932  shutdown() {
2933    this.changeListener = null;
2934  }
2935}
2936class __PRIVATE_FirebaseAuthCredentialsProvider {
2937  constructor(e) {
2938    this.t = e, /** Tracks the current User. */
2939    this.currentUser = User.UNAUTHENTICATED, /**
2940    * Counter used to detect if the token changed while a getToken request was
2941    * outstanding.
2942    */
2943    this.i = 0, this.forceRefresh = false, this.auth = null;
2944  }
2945  start(e, t) {
2946    __PRIVATE_hardAssert(void 0 === this.o, 42304);
2947    let n = this.i;
2948    const __PRIVATE_guardedChangeListener = (e2) => this.i !== n ? (n = this.i, t(e2)) : Promise.resolve();
2949    let r = new __PRIVATE_Deferred();
2950    this.o = () => {
2951      this.i++, this.currentUser = this.u(), r.resolve(), r = new __PRIVATE_Deferred(), e.enqueueRetryable(() => __PRIVATE_guardedChangeListener(this.currentUser));
2952    };
2953    const __PRIVATE_awaitNextToken = () => {
2954      const t2 = r;
2955      e.enqueueRetryable(async () => {
2956        await t2.promise, await __PRIVATE_guardedChangeListener(this.currentUser);
2957      });
2958    }, __PRIVATE_registerAuth = (e2) => {
2959      __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = e2, this.o && (this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken());
2960    };
2961    this.t.onInit((e2) => __PRIVATE_registerAuth(e2)), // Our users can initialize Auth right after Firestore, so we give it
2962    // a chance to register itself with the component framework before we
2963    // determine whether to start up in unauthenticated mode.
2964    setTimeout(() => {
2965      if (!this.auth) {
2966        const e2 = this.t.getImmediate({
2967          optional: true
2968        });
2969        e2 ? __PRIVATE_registerAuth(e2) : (
2970          // If auth is still not available, proceed with `null` user
2971          (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth not yet detected"), r.resolve(), r = new __PRIVATE_Deferred())
2972        );
2973      }
2974    }, 0), __PRIVATE_awaitNextToken();
2975  }
2976  getToken() {
2977    const e = this.i, t = this.forceRefresh;
2978    return this.forceRefresh = false, this.auth ? this.auth.getToken(t).then((t2) => (
2979      // Cancel the request since the token changed while the request was
2980      // outstanding so the response is potentially for a previous user (which
2981      // user, we can't be sure).
2982      this.i !== e ? (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."), this.getToken()) : t2 ? (__PRIVATE_hardAssert("string" == typeof t2.accessToken, 31837, {
2983        l: t2
2984      }), new __PRIVATE_OAuthToken(t2.accessToken, this.currentUser)) : null
2985    )) : Promise.resolve(null);
2986  }
2987  invalidateToken() {
2988    this.forceRefresh = true;
2989  }
2990  shutdown() {
2991    this.auth && this.o && this.auth.removeAuthTokenListener(this.o), this.o = void 0;
2992  }
2993  // Auth.getUid() can return null even with a user logged in. It is because
2994  // getUid() is synchronous, but the auth code populating Uid is asynchronous.
2995  // This method should only be called in the AuthTokenListener callback
2996  // to guarantee to get the actual user.
2997  u() {
2998    const e = this.auth && this.auth.getUid();
2999    return __PRIVATE_hardAssert(null === e || "string" == typeof e, 2055, {
3000      h: e
3001    }), new User(e);
3002  }
3003}
3004class __PRIVATE_FirstPartyToken {
3005  constructor(e, t, n) {
3006    this.P = e, this.T = t, this.I = n, this.type = "FirstParty", this.user = User.FIRST_PARTY, this.A = /* @__PURE__ */ new Map();
3007  }
3008  /**
3009   * Gets an authorization token, using a provided factory function, or return
3010   * null.
3011   */
3012  R() {
3013    return this.I ? this.I() : null;
3014  }
3015  get headers() {
3016    this.A.set("X-Goog-AuthUser", this.P);
3017    const e = this.R();
3018    return e && this.A.set("Authorization", e), this.T && this.A.set("X-Goog-Iam-Authorization-Token", this.T), this.A;
3019  }
3020}
3021class __PRIVATE_FirstPartyAuthCredentialsProvider {
3022  constructor(e, t, n) {
3023    this.P = e, this.T = t, this.I = n;
3024  }
3025  getToken() {
3026    return Promise.resolve(new __PRIVATE_FirstPartyToken(this.P, this.T, this.I));
3027  }
3028  start(e, t) {
3029    e.enqueueRetryable(() => t(User.FIRST_PARTY));
3030  }
3031  shutdown() {
3032  }
3033  invalidateToken() {
3034  }
3035}
3036class AppCheckToken {
3037  constructor(e) {
3038    this.value = e, this.type = "AppCheck", this.headers = /* @__PURE__ */ new Map(), e && e.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
3039  }
3040}
3041class __PRIVATE_FirebaseAppCheckTokenProvider {
3042  constructor(t, n) {
3043    this.V = n, this.forceRefresh = false, this.appCheck = null, this.m = null, this.p = null, _isFirebaseServerApp(t) && t.settings.appCheckToken && (this.p = t.settings.appCheckToken);
3044  }
3045  start(e, t) {
3046    __PRIVATE_hardAssert(void 0 === this.o, 3512);
3047    const onTokenChanged = (e2) => {
3048      null != e2.error && __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${e2.error.message}`);
3049      const n = e2.token !== this.m;
3050      return this.m = e2.token, __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`), n ? t(e2.token) : Promise.resolve();
3051    };
3052    this.o = (t2) => {
3053      e.enqueueRetryable(() => onTokenChanged(t2));
3054    };
3055    const __PRIVATE_registerAppCheck = (e2) => {
3056      __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = e2, this.o && this.appCheck.addTokenListener(this.o);
3057    };
3058    this.V.onInit((e2) => __PRIVATE_registerAppCheck(e2)), // Our users can initialize AppCheck after Firestore, so we give it
3059    // a chance to register itself with the component framework.
3060    setTimeout(() => {
3061      if (!this.appCheck) {
3062        const e2 = this.V.getImmediate({
3063          optional: true
3064        });
3065        e2 ? __PRIVATE_registerAppCheck(e2) : (
3066          // If AppCheck is still not available, proceed without it.
3067          __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck not yet detected")
3068        );
3069      }
3070    }, 0);
3071  }
3072  getToken() {
3073    if (this.p) return Promise.resolve(new AppCheckToken(this.p));
3074    const e = this.forceRefresh;
3075    return this.forceRefresh = false, this.appCheck ? this.appCheck.getToken(e).then((e2) => e2 ? (__PRIVATE_hardAssert("string" == typeof e2.token, 44558, {
3076      tokenResult: e2
3077    }), this.m = e2.token, new AppCheckToken(e2.token)) : null) : Promise.resolve(null);
3078  }
3079  invalidateToken() {
3080    this.forceRefresh = true;
3081  }
3082  shutdown() {
3083    this.appCheck && this.o && this.appCheck.removeTokenListener(this.o), this.o = void 0;
3084  }
3085}
3086class __PRIVATE_EmptyAppCheckTokenProvider {
3087  getToken() {
3088    return Promise.resolve(new AppCheckToken(""));
3089  }
3090  invalidateToken() {
3091  }
3092  start(e, t) {
3093  }
3094  shutdown() {
3095  }
3096}
3097/**
3098 * @license
3099 * Copyright 2020 Google LLC
3100 *
3101 * Licensed under the Apache License, Version 2.0 (the "License");
3102 * you may not use this file except in compliance with the License.
3103 * You may obtain a copy of the License at
3104 *
3105 *   http://www.apache.org/licenses/LICENSE-2.0
3106 *
3107 * Unless required by applicable law or agreed to in writing, software
3108 * distributed under the License is distributed on an "AS IS" BASIS,
3109 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3110 * See the License for the specific language governing permissions and
3111 * limitations under the License.
3112 */
3113function __PRIVATE_randomBytes(e) {
3114  const t = (
3115    // eslint-disable-next-line @typescript-eslint/no-explicit-any
3116    "undefined" != typeof self && (self.crypto || self.msCrypto)
3117  ), n = new Uint8Array(e);
3118  if (t && "function" == typeof t.getRandomValues) t.getRandomValues(n);
3119  else
3120    for (let t2 = 0; t2 < e; t2++) n[t2] = Math.floor(256 * Math.random());
3121  return n;
3122}
3123/**
3124 * @license
3125 * Copyright 2023 Google LLC
3126 *
3127 * Licensed under the Apache License, Version 2.0 (the "License");
3128 * you may not use this file except in compliance with the License.
3129 * You may obtain a copy of the License at
3130 *
3131 *   http://www.apache.org/licenses/LICENSE-2.0
3132 *
3133 * Unless required by applicable law or agreed to in writing, software
3134 * distributed under the License is distributed on an "AS IS" BASIS,
3135 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3136 * See the License for the specific language governing permissions and
3137 * limitations under the License.
3138 */
3139function __PRIVATE_newTextEncoder() {
3140  return new TextEncoder();
3141}
3142/**
3143 * @license
3144 * Copyright 2017 Google LLC
3145 *
3146 * Licensed under the Apache License, Version 2.0 (the "License");
3147 * you may not use this file except in compliance with the License.
3148 * You may obtain a copy of the License at
3149 *
3150 *   http://www.apache.org/licenses/LICENSE-2.0
3151 *
3152 * Unless required by applicable law or agreed to in writing, software
3153 * distributed under the License is distributed on an "AS IS" BASIS,
3154 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3155 * See the License for the specific language governing permissions and
3156 * limitations under the License.
3157 */
3158class __PRIVATE_AutoId {
3159  static newId() {
3160    const e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", t = 62 * Math.floor(256 / 62);
3161    let n = "";
3162    for (; n.length < 20; ) {
3163      const r = __PRIVATE_randomBytes(40);
3164      for (let i = 0; i < r.length; ++i)
3165        n.length < 20 && r[i] < t && (n += e.charAt(r[i] % 62));
3166    }
3167    return n;
3168  }
3169}
3170function __PRIVATE_primitiveComparator(e, t) {
3171  return e < t ? -1 : e > t ? 1 : 0;
3172}
3173function __PRIVATE_compareUtf8Strings(e, t) {
3174  let n = 0;
3175  for (; n < e.length && n < t.length; ) {
3176    const r = e.codePointAt(n), i = t.codePointAt(n);
3177    if (r !== i) {
3178      if (r < 128 && i < 128)
3179        return __PRIVATE_primitiveComparator(r, i);
3180      {
3181        const s = __PRIVATE_newTextEncoder(), o = __PRIVATE_compareByteArrays$1(s.encode(__PRIVATE_getUtf8SafeSubstring(e, n)), s.encode(__PRIVATE_getUtf8SafeSubstring(t, n)));
3182        return 0 !== o ? o : __PRIVATE_primitiveComparator(r, i);
3183      }
3184    }
3185    n += r > 65535 ? 2 : 1;
3186  }
3187  return __PRIVATE_primitiveComparator(e.length, t.length);
3188}
3189function __PRIVATE_getUtf8SafeSubstring(e, t) {
3190  return e.codePointAt(t) > 65535 ? e.substring(t, t + 2) : e.substring(t, t + 1);
3191}
3192function __PRIVATE_compareByteArrays$1(e, t) {
3193  for (let n = 0; n < e.length && n < t.length; ++n) if (e[n] !== t[n]) return __PRIVATE_primitiveComparator(e[n], t[n]);
3194  return __PRIVATE_primitiveComparator(e.length, t.length);
3195}
3196function __PRIVATE_arrayEquals(e, t, n) {
3197  return e.length === t.length && e.every((e2, r) => n(e2, t[r]));
3198}
3199function __PRIVATE_immediateSuccessor(e) {
3200  return e + "\0";
3201}
3202/**
3203 * @license
3204 * Copyright 2017 Google LLC
3205 *
3206 * Licensed under the Apache License, Version 2.0 (the "License");
3207 * you may not use this file except in compliance with the License.
3208 * You may obtain a copy of the License at
3209 *
3210 *   http://www.apache.org/licenses/LICENSE-2.0
3211 *
3212 * Unless required by applicable law or agreed to in writing, softw
vendor: 22,315 bytes, lines 3212-3842
3212are
3213 * distributed under the License is distributed on an "AS IS" BASIS,
3214 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3215 * See the License for the specific language governing permissions and
3216 * limitations under the License.
3217 */
3218const B = "__name__";
3219class BasePath {
3220  constructor(e, t, n) {
3221    void 0 === t ? t = 0 : t > e.length && fail(637, {
3222      offset: t,
3223      range: e.length
3224    }), void 0 === n ? n = e.length - t : n > e.length - t && fail(1746, {
3225      length: n,
3226      range: e.length - t
3227    }), this.segments = e, this.offset = t, this.len = n;
3228  }
3229  get length() {
3230    return this.len;
3231  }
3232  isEqual(e) {
3233    return 0 === BasePath.comparator(this, e);
3234  }
3235  child(e) {
3236    const t = this.segments.slice(this.offset, this.limit());
3237    return e instanceof BasePath ? e.forEach((e2) => {
3238      t.push(e2);
3239    }) : t.push(e), this.construct(t);
3240  }
3241  /** The index of one past the last segment of the path. */
3242  limit() {
3243    return this.offset + this.length;
3244  }
3245  popFirst(e) {
3246    return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e);
3247  }
3248  popLast() {
3249    return this.construct(this.segments, this.offset, this.length - 1);
3250  }
3251  firstSegment() {
3252    return this.segments[this.offset];
3253  }
3254  lastSegment() {
3255    return this.get(this.length - 1);
3256  }
3257  get(e) {
3258    return this.segments[this.offset + e];
3259  }
3260  isEmpty() {
3261    return 0 === this.length;
3262  }
3263  isPrefixOf(e) {
3264    if (e.length < this.length) return false;
3265    for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return false;
3266    return true;
3267  }
3268  isImmediateParentOf(e) {
3269    if (this.length + 1 !== e.length) return false;
3270    for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return false;
3271    return true;
3272  }
3273  forEach(e) {
3274    for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]);
3275  }
3276  toArray() {
3277    return this.segments.slice(this.offset, this.limit());
3278  }
3279  /**
3280   * Compare 2 paths segment by segment, prioritizing numeric IDs
3281   * (e.g., "__id123__") in numeric ascending order, followed by string
3282   * segments in lexicographical order.
3283   */
3284  static comparator(e, t) {
3285    const n = Math.min(e.length, t.length);
3286    for (let r = 0; r < n; r++) {
3287      const n2 = BasePath.compareSegments(e.get(r), t.get(r));
3288      if (0 !== n2) return n2;
3289    }
3290    return __PRIVATE_primitiveComparator(e.length, t.length);
3291  }
3292  static compareSegments(e, t) {
3293    const n = BasePath.isNumericId(e), r = BasePath.isNumericId(t);
3294    return n && !r ? -1 : !n && r ? 1 : n && r ? BasePath.extractNumericId(e).compare(BasePath.extractNumericId(t)) : __PRIVATE_compareUtf8Strings(e, t);
3295  }
3296  // Checks if a segment is a numeric ID (starts with "__id" and ends with "__").
3297  static isNumericId(e) {
3298    return e.startsWith("__id") && e.endsWith("__");
3299  }
3300  static extractNumericId(e) {
3301    return Integer.fromString(e.substring(4, e.length - 2));
3302  }
3303}
3304class ResourcePath extends BasePath {
3305  construct(e, t, n) {
3306    return new ResourcePath(e, t, n);
3307  }
3308  canonicalString() {
3309    return this.toArray().join("/");
3310  }
3311  toString() {
3312    return this.canonicalString();
3313  }
3314  /**
3315   * Returns a string representation of this path
3316   * where each path segment has been encoded with
3317   * `encodeURIComponent`.
3318   */
3319  toUriEncodedString() {
3320    return this.toArray().map(encodeURIComponent).join("/");
3321  }
3322  /**
3323   * Creates a resource path from the given slash-delimited string. If multiple
3324   * arguments are provided, all components are combined. Leading and trailing
3325   * slashes from all components are ignored.
3326   */
3327  static fromString(...e) {
3328    const t = [];
3329    for (const n of e) {
3330      if (n.indexOf("//") >= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
3331      t.push(...n.split("/").filter((e2) => e2.length > 0));
3332    }
3333    return new ResourcePath(t);
3334  }
3335  static emptyPath() {
3336    return new ResourcePath([]);
3337  }
3338}
3339const L = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
3340class FieldPath$1 extends BasePath {
3341  construct(e, t, n) {
3342    return new FieldPath$1(e, t, n);
3343  }
3344  /**
3345   * Returns true if the string could be used as a segment in a field path
3346   * without escaping.
3347   */
3348  static isValidIdentifier(e) {
3349    return L.test(e);
3350  }
3351  canonicalString() {
3352    return this.toArray().map((e) => (e = e.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), FieldPath$1.isValidIdentifier(e) || (e = "`" + e + "`"), e)).join(".");
3353  }
3354  toString() {
3355    return this.canonicalString();
3356  }
3357  /**
3358   * Returns true if this field references the key of a document.
3359   */
3360  isKeyField() {
3361    return 1 === this.length && this.get(0) === B;
3362  }
3363  /**
3364   * The field designating the key of a document.
3365   */
3366  static keyField() {
3367    return new FieldPath$1([B]);
3368  }
3369  /**
3370   * Parses a field string from the given server-formatted string.
3371   *
3372   * - Splitting the empty string is not allowed (for now at least).
3373   * - Empty segments within the string (e.g. if there are two consecutive
3374   *   separators) are not allowed.
3375   *
3376   * TODO(b/37244157): we should make this more strict. Right now, it allows
3377   * non-identifier path components, even if they aren't escaped.
3378   */
3379  static fromServerFormat(e) {
3380    const t = [];
3381    let n = "", r = 0;
3382    const __PRIVATE_addCurrentSegment = () => {
3383      if (0 === n.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
3384      t.push(n), n = "";
3385    };
3386    let i = false;
3387    for (; r < e.length; ) {
3388      const t2 = e[r];
3389      if ("\\" === t2) {
3390        if (r + 1 === e.length) throw new FirestoreError(N.INVALID_ARGUMENT, "Path has trailing escape character: " + e);
3391        const t3 = e[r + 1];
3392        if ("\\" !== t3 && "." !== t3 && "`" !== t3) throw new FirestoreError(N.INVALID_ARGUMENT, "Path has invalid escape sequence: " + e);
3393        n += t3, r += 2;
3394      } else "`" === t2 ? (i = !i, r++) : "." !== t2 || i ? (n += t2, r++) : (__PRIVATE_addCurrentSegment(), r++);
3395    }
3396    if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(N.INVALID_ARGUMENT, "Unterminated ` in path: " + e);
3397    return new FieldPath$1(t);
3398  }
3399  static emptyPath() {
3400    return new FieldPath$1([]);
3401  }
3402}
3403/**
3404 * @license
3405 * Copyright 2017 Google LLC
3406 *
3407 * Licensed under the Apache License, Version 2.0 (the "License");
3408 * you may not use this file except in compliance with the License.
3409 * You may obtain a copy of the License at
3410 *
3411 *   http://www.apache.org/licenses/LICENSE-2.0
3412 *
3413 * Unless required by applicable law or agreed to in writing, software
3414 * distributed under the License is distributed on an "AS IS" BASIS,
3415 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3416 * See the License for the specific language governing permissions and
3417 * limitations under the License.
3418 */
3419class DocumentKey {
3420  constructor(e) {
3421    this.path = e;
3422  }
3423  static fromPath(e) {
3424    return new DocumentKey(ResourcePath.fromString(e));
3425  }
3426  static fromName(e) {
3427    return new DocumentKey(ResourcePath.fromString(e).popFirst(5));
3428  }
3429  static empty() {
3430    return new DocumentKey(ResourcePath.emptyPath());
3431  }
3432  get collectionGroup() {
3433    return this.path.popLast().lastSegment();
3434  }
3435  /** Returns true if the document is in the specified collectionId. */
3436  hasCollectionId(e) {
3437    return this.path.length >= 2 && this.path.get(this.path.length - 2) === e;
3438  }
3439  /** Returns the collection group (i.e. the name of the parent collection) for this key. */
3440  getCollectionGroup() {
3441    return this.path.get(this.path.length - 2);
3442  }
3443  /** Returns the fully qualified path to the parent collection. */
3444  getCollectionPath() {
3445    return this.path.popLast();
3446  }
3447  isEqual(e) {
3448    return null !== e && 0 === ResourcePath.comparator(this.path, e.path);
3449  }
3450  toString() {
3451    return this.path.toString();
3452  }
3453  static comparator(e, t) {
3454    return ResourcePath.comparator(e.path, t.path);
3455  }
3456  static isDocumentKey(e) {
3457    return e.length % 2 == 0;
3458  }
3459  /**
3460   * Creates and returns a new document key with the given segments.
3461   *
3462   * @param segments - The segments of the path to the document
3463   * @returns A new instance of DocumentKey
3464   */
3465  static fromSegments(e) {
3466    return new DocumentKey(new ResourcePath(e.slice()));
3467  }
3468}
3469/**
3470 * @license
3471 * Copyright 2017 Google LLC
3472 *
3473 * Licensed under the Apache License, Version 2.0 (the "License");
3474 * you may not use this file except in compliance with the License.
3475 * You may obtain a copy of the License at
3476 *
3477 *   http://www.apache.org/licenses/LICENSE-2.0
3478 *
3479 * Unless required by applicable law or agreed to in writing, software
3480 * distributed under the License is distributed on an "AS IS" BASIS,
3481 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3482 * See the License for the specific language governing permissions and
3483 * limitations under the License.
3484 */
3485function __PRIVATE_validateNonEmptyArgument(e, t, n) {
3486  if (!n) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`);
3487}
3488function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) {
3489  if (true === t && true === r) throw new FirestoreError(N.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`);
3490}
3491function __PRIVATE_validateDocumentPath(e) {
3492  if (!DocumentKey.isDocumentKey(e)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`);
3493}
3494function __PRIVATE_validateCollectionPath(e) {
3495  if (DocumentKey.isDocumentKey(e)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`);
3496}
3497function __PRIVATE_isPlainObject(e) {
3498  return "object" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e));
3499}
3500function __PRIVATE_valueDescription(e) {
3501  if (void 0 === e) return "undefined";
3502  if (null === e) return "null";
3503  if ("string" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), JSON.stringify(e);
3504  if ("number" == typeof e || "boolean" == typeof e) return "" + e;
3505  if ("object" == typeof e) {
3506    if (e instanceof Array) return "an array";
3507    {
3508      const t = (
3509        /** try to get the constructor name for an object. */
3510        function __PRIVATE_tryGetCustomObjectType(e2) {
3511          if (e2.constructor) return e2.constructor.name;
3512          return null;
3513        }(e)
3514      );
3515      return t ? `a custom ${t} object` : "an object";
3516    }
3517  }
3518  return "function" == typeof e ? "a function" : fail(12329, {
3519    type: typeof e
3520  });
3521}
3522function __PRIVATE_cast(e, t) {
3523  if ("_delegate" in e && // Unwrap Compat types
3524  // eslint-disable-next-line @typescript-eslint/no-explicit-any
3525  (e = e._delegate), !(e instanceof t)) {
3526    if (t.name === e.constructor.name) throw new FirestoreError(N.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
3527    {
3528      const n = __PRIVATE_valueDescription(e);
3529      throw new FirestoreError(N.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`);
3530    }
3531  }
3532  return e;
3533}
3534function __PRIVATE_validatePositiveNumber(e, t) {
3535  if (t <= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`);
3536}
3537/**
3538 * @license
3539 * Copyright 2025 Google LLC
3540 *
3541 * Licensed under the Apache License, Version 2.0 (the "License");
3542 * you may not use this file except in compliance with the License.
3543 * You may obtain a copy of the License at
3544 *
3545 *   http://www.apache.org/licenses/LICENSE-2.0
3546 *
3547 * Unless required by applicable law or agreed to in writing, software
3548 * distributed under the License is distributed on an "AS IS" BASIS,
3549 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3550 * See the License for the specific language governing permissions and
3551 * limitations under the License.
3552 */
3553function property(e, t) {
3554  const n = {
3555    typeString: e
3556  };
3557  return t && (n.value = t), n;
3558}
3559function __PRIVATE_validateJSON(e, t) {
3560  if (!__PRIVATE_isPlainObject(e)) throw new FirestoreError(N.INVALID_ARGUMENT, "JSON must be an object");
3561  let n;
3562  for (const r in t) if (t[r]) {
3563    const i = t[r].typeString, s = "value" in t[r] ? {
3564      value: t[r].value
3565    } : void 0;
3566    if (!(r in e)) {
3567      n = `JSON missing required field: '${r}'`;
3568      break;
3569    }
3570    const o = e[r];
3571    if (i && typeof o !== i) {
3572      n = `JSON field '${r}' must be a ${i}.`;
3573      break;
3574    }
3575    if (void 0 !== s && o !== s.value) {
3576      n = `Expected '${r}' field to equal '${s.value}'`;
3577      break;
3578    }
3579  }
3580  if (n) throw new FirestoreError(N.INVALID_ARGUMENT, n);
3581  return true;
3582}
3583/**
3584 * @license
3585 * Copyright 2017 Google LLC
3586 *
3587 * Licensed under the Apache License, Version 2.0 (the "License");
3588 * you may not use this file except in compliance with the License.
3589 * You may obtain a copy of the License at
3590 *
3591 *   http://www.apache.org/licenses/LICENSE-2.0
3592 *
3593 * Unless required by applicable law or agreed to in writing, software
3594 * distributed under the License is distributed on an "AS IS" BASIS,
3595 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3596 * See the License for the specific language governing permissions and
3597 * limitations under the License.
3598 */
3599const k = -62135596800, q = 1e6;
3600class Timestamp {
3601  /**
3602   * Creates a new timestamp with the current date, with millisecond precision.
3603   *
3604   * @returns a new timestamp representing the current date.
3605   */
3606  static now() {
3607    return Timestamp.fromMillis(Date.now());
3608  }
3609  /**
3610   * Creates a new timestamp from the given date.
3611   *
3612   * @param date - The date to initialize the `Timestamp` from.
3613   * @returns A new `Timestamp` representing the same point in time as the given
3614   *     date.
3615   */
3616  static fromDate(e) {
3617    return Timestamp.fromMillis(e.getTime());
3618  }
3619  /**
3620   * Creates a new timestamp from the given number of milliseconds.
3621   *
3622   * @param milliseconds - Number of milliseconds since Unix epoch
3623   *     1970-01-01T00:00:00Z.
3624   * @returns A new `Timestamp` representing the same point in time as the given
3625   *     number of milliseconds.
3626   */
3627  static fromMillis(e) {
3628    const t = Math.floor(e / 1e3), n = Math.floor((e - 1e3 * t) * q);
3629    return new Timestamp(t, n);
3630  }
3631  /**
3632   * Creates a new timestamp.
3633   *
3634   * @param seconds - The number of seconds of UTC time since Unix epoch
3635   *     1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
3636   *     9999-12-31T23:59:59Z inclusive.
3637   * @param nanoseconds - The non-negative fractions of a second at nanosecond
3638   *     resolution. Negative second values with fractions must still have
3639   *     non-negative nanoseconds values that count forward in time. Must be
3640   *     from 0 to 999,999,999 inclusive.
3641   */
3642  constructor(e, t) {
3643    if (this.seconds = e, this.nanoseconds = t, t < 0) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t);
3644    if (t >= 1e9) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t);
3645    if (e < k) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e);
3646    if (e >= 253402300800) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e);
3647  }
3648  /**
3649   * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
3650   * causes a loss of precision since `Date` objects only support millisecond
3651   * precision.
3652   *
3653   * @returns JavaScript `Date` object representing the same point in time as
3654   *     this `Timestamp`, with millisecond precision.
3655   */
3656  toDate() {
3657    return new Date(this.toMillis());
3658  }
3659  /**
3660   * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
3661   * epoch). This operation causes a loss of precision.
3662   *
3663   * @returns The point in time corresponding to this timestamp, represented as
3664   *     the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
3665   */
3666  toMillis() {
3667    return 1e3 * this.seconds + this.nanoseconds / q;
3668  }
3669  _compareTo(e) {
3670    return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds);
3671  }
3672  /**
3673   * Returns true if this `Timestamp` is equal to the provided one.
3674   *
3675   * @param other - The `Timestamp` to compare against.
3676   * @returns true if this `Timestamp` is equal to the provided one.
3677   */
3678  isEqual(e) {
3679    return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds;
3680  }
3681  /** Returns a textual representation of this `Timestamp`. */
3682  toString() {
3683    return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
3684  }
3685  /**
3686   * Returns a JSON-serializable representation of this `Timestamp`.
3687   */
3688  toJSON() {
3689    return {
3690      type: Timestamp._jsonSchemaVersion,
3691      seconds: this.seconds,
3692      nanoseconds: this.nanoseconds
3693    };
3694  }
3695  /**
3696   * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.
3697   */
3698  static fromJSON(e) {
3699    if (__PRIVATE_validateJSON(e, Timestamp._jsonSchema)) return new Timestamp(e.seconds, e.nanoseconds);
3700  }
3701  /**
3702   * Converts this object to a primitive string, which allows `Timestamp` objects
3703   * to be compared using the `>`, `<=`, `>=` and `>` operators.
3704   */
3705  valueOf() {
3706    const e = this.seconds - k;
3707    return String(e).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
3708  }
3709}
3710Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = {
3711  type: property("string", Timestamp._jsonSchemaVersion),
3712  seconds: property("number"),
3713  nanoseconds: property("number")
3714};
3715/**
3716 * @license
3717 * Copyright 2017 Google LLC
3718 *
3719 * Licensed under the Apache License, Version 2.0 (the "License");
3720 * you may not use this file except in compliance with the License.
3721 * You may obtain a copy of the License at
3722 *
3723 *   http://www.apache.org/licenses/LICENSE-2.0
3724 *
3725 * Unless required by applicable law or agreed to in writing, software
3726 * distributed under the License is distributed on an "AS IS" BASIS,
3727 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3728 * See the License for the specific language governing permissions and
3729 * limitations under the License.
3730 */
3731class SnapshotVersion {
3732  static fromTimestamp(e) {
3733    return new SnapshotVersion(e);
3734  }
3735  static min() {
3736    return new SnapshotVersion(new Timestamp(0, 0));
3737  }
3738  static max() {
3739    return new SnapshotVersion(new Timestamp(253402300799, 999999999));
3740  }
3741  constructor(e) {
3742    this.timestamp = e;
3743  }
3744  compareTo(e) {
3745    return this.timestamp._compareTo(e.timestamp);
3746  }
3747  isEqual(e) {
3748    return this.timestamp.isEqual(e.timestamp);
3749  }
3750  /** Returns a number representation of the version for use in spec tests. */
3751  toMicroseconds() {
3752    return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
3753  }
3754  toString() {
3755    return "SnapshotVersion(" + this.timestamp.toString() + ")";
3756  }
3757  toTimestamp() {
3758    return this.timestamp;
3759  }
3760}
3761/**
3762 * @license
3763 * Copyright 2021 Google LLC
3764 *
3765 * Licensed under the Apache License, Version 2.0 (the "License");
3766 * you may not use this file except in compliance with the License.
3767 * You may obtain a copy of the License at
3768 *
3769 *   http://www.apache.org/licenses/LICENSE-2.0
3770 *
3771 * Unless required by applicable law or agreed to in writing, software
3772 * distributed under the License is distributed on an "AS IS" BASIS,
3773 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3774 * See the License for the specific language governing permissions and
3775 * limitations under the License.
3776 */
3777const Q = -1;
3778class FieldIndex {
3779  constructor(e, t, n, r) {
3780    this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r;
3781  }
3782}
3783function __PRIVATE_fieldIndexGetArraySegment(e) {
3784  return e.fields.find((e2) => 2 === e2.kind);
3785}
3786function __PRIVATE_fieldIndexGetDirectionalSegments(e) {
3787  return e.fields.filter((e2) => 2 !== e2.kind);
3788}
3789function __PRIVATE_fieldIndexSemanticComparator(e, t) {
3790  let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);
3791  if (0 !== n) return n;
3792  for (let r = 0; r < Math.min(e.fields.length, t.fields.length); ++r) if (n = __PRIVATE_indexSegmentComparator(e.fields[r], t.fields[r]), 0 !== n) return n;
3793  return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length);
3794}
3795FieldIndex.UNKNOWN_ID = -1;
3796class IndexSegment {
3797  constructor(e, t) {
3798    this.fieldPath = e, this.kind = t;
3799  }
3800}
3801function __PRIVATE_indexSegmentComparator(e, t) {
3802  const n = FieldPath$1.comparator(e.fieldPath, t.fieldPath);
3803  return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind);
3804}
3805class IndexState {
3806  constructor(e, t) {
3807    this.sequenceNumber = e, this.offset = t;
3808  }
3809  /** The state of an index that has not yet been backfilled. */
3810  static empty() {
3811    return new IndexState(0, IndexOffset.min());
3812  }
3813}
3814function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) {
3815  const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r));
3816  return new IndexOffset(i, DocumentKey.empty(), t);
3817}
3818function __PRIVATE_newIndexOffsetFromDocument(e) {
3819  return new IndexOffset(e.readTime, e.key, Q);
3820}
3821class IndexOffset {
3822  constructor(e, t, n) {
3823    this.readTime = e, this.documentKey = t, this.largestBatchId = n;
3824  }
3825  /** Returns an offset that sorts before all regular offsets. */
3826  static min() {
3827    return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), Q);
3828  }
3829  /** Returns an offset that sorts after all regular offsets. */
3830  static max() {
3831    return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), Q);
3832  }
3833}
3834function __PRIVATE_indexOffsetComparator(e, t) {
3835  let n = e.readTime.compareTo(t.readTime);
3836  return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), 0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId));
3837}
3838/**
3839 * @license
3840 * Copyright 2020 Google LLC
3841 *
3842 * Licensed under the Apache License, Version 2.0 (the "License");
3843 * you may not use this file except in compliance with the License.
3844 * You may obtain a copy of the License at
3845 *
3846 *   http://www.apache.org/licenses/LICENSE-2.0
3847 *
3848 * Unless required by applicable law or agreed to in writing, software
3849 * distributed under the License is distributed on an "AS IS" BASIS,
3850 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3851 * See the License for the specific language governing permissions and
3852 * limitations under the License.
3853 */
3854const $ = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";
3855class PersistenceTransaction {
3856  constructor() {
3857    this.onCommittedListeners = [];
3858  }
3859  addOnCommittedListener(e) {
3860    this.onCommittedListeners.push(e);
3861  }
3862  raiseOnCommittedEvent() {
3863    this.onCommittedListeners.forEach((e) => e());
3864  }
3865}
3866/**
3867 * @license
3868 * Copyright 2017 Google LLC
3869 *
3870 * Licensed under the Apache License, Version 2.0 (the "License");
3871 * you may not use this file except in compliance with the License.
3872 * You may obtain a copy of the License at
3873 *
3874 *   http://www.apache.org/licenses/LICENSE-2.0
3875 *
3876 * Unless required by applicable law or agreed to in writing, software
3877 * distributed under the License is distributed on an "AS IS" BASIS,
3878 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3879 * See the License for the specific language governing permissions and
3880 * limitations under the License.
3881 */
3882async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) {
3883  if (e.code !== N.FAILED_PRECONDITION || e.message !== $) throw e;
3884  __PRIVATE_logDebug("LocalStore", "Unexpectedly lost primary lease");
3885}
3886/**
3887 * @license
3888 * Copyright 2017 Google LLC
3889 *
3890 * Licensed under the Apache License, Version 2.0 (the "License");
3891 * you may not use this file except in compliance with the License.
3892 * You may obtain a copy of the License at
3893 *
3894 *   http://www.apache.org/licenses/LICENSE-2.0
3895 *
3896 * Unless required by applicable law or agreed to in writing, software
3897 * distributed under the License is distributed on an "AS IS" BASIS,
3898 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3899 * See the License for the specific language governing permissions and
3900 * limitations under the License.
3901 */
3902class PersistencePromise {
3903  constructor(e) {
3904    this.nextCallback = null, this.catchCallback = null, // When the operation resolves, we'll set result or error and mark isDone.
3905    this.result = void 0, this.error = void 0, this.isDone = false, // Set to true when .then() or .catch() are called and prevents additional
3906    // chaining.
3907    this.callbackAttached = false, e((e2) => {
3908      this.isDone = true, this.result = e2, this.nextCallback && // value should be defined unless T is Void, but we can't express
3909      // that in the type system.
3910      this.nextCallback(e2);
3911    }, (e2) => {
3912      this.isDone = true, this.error = e2, this.catchCallback && this.catchCallback(e2);
3913    });
3914  }
3915  catch(e) {
3916    return this.next(void 0, e);
3917  }
3918  next(e, t) {
3919    return this.callbackAttached && fail(59440), this.callbackAttached = true, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise((n, r) => {
3920      this.nextCallback = (t2) => {
3921        this.wrapSuccess(e, t2).next(n, r);
3922      }, this.catchCallback = (e2) => {
3923        this.wrapFailure(t, e2).next(n, r);
3924      };
3925    });
3926  }
3927  toPromise() {
3928    return new Promise((e, t) => {
3929      this.next(e, t);
3930    });
3931  }
3932  wrapUserFunction(e) {
3933    try {
3934      const t = e();
3935      return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t);
3936    } catch (e2) {
3937      return PersistencePromise.reject(e2);
3938    }
3939  }
3940  wrapSuccess(e, t) {
3941    return e ? this.wrapUserFunction(() => e(t)) : PersistencePromise.resolve(t);
3942  }
3943  wrapFailure(e, t) {
3944    return e ? this.wrapUserFunction(() => e(t)) : PersistencePromise.reject(t);
3945  }
3946  static resolve(e) {
3947    return new PersistencePromise((t, n) => {
3948      t(e);
3949    });
3950  }
3951  static reject(e) {
3952    return new PersistencePromise((t, n) => {
3953      n(e);
3954    });
3955  }
3956  static waitFor(e) {
3957    return new PersistencePromise((t, n) => {
3958      let r = 0, i = 0, s = false;
3959      e.forEach((e2) => {
3960        ++r, e2.next(() => {
3961          ++i, s && i === r && t();
3962        }, (e3) => n(e3));
3963      }), s = true, i === r && t();
3964    });
3965  }
3966  /**
3967   * Given an array of predicate functions that asynchronously evaluate to a
3968   * boolean, implements a short-circuiting `or` between the results. Predicates
3969   * will be evaluated until one of them returns `true`, then stop. The final
3970   * result will be whether any of them returned `true`.
3971   */
3972  static or(e) {
3973    let t = PersistencePromise.resolve(false);
3974    for (const n of e) t = t.next((e2) => e2 ? PersistencePromise.resolve(e2) : n());
3975    return t;
3976  }
3977  static forEach(e, t) {
3978    const n = [];
3979    return e.forEach((e2, r) => {
3980      n.push(t.call(this, e2, r));
3981    }), this.waitFor(n);
3982  }
3983  /**
3984   * Concurrently map all array elements through asynchronous function.
3985   */
3986  static mapArray(e, t) {
3987    return new PersistencePromise((n, r) => {
3988      const i = e.length, s = new Array(i);
3989      let o = 0;
3990      for (let _ = 0; _ < i; _++) {
3991        const a = _;
3992        t(e[a]).next((e2) => {
3993          s[a] = e2, ++o, o === i && n(s);
3994        }, (e2) => r(e2));
3995      }
3996    });
3997  }
3998  /**
3999   * An alternative to recursive PersistencePromise calls, that avoids
4000   * potential memory problems from unbounded chains of promises.
4001   *
4002   * The `action` will be called repeatedly while `condition` is true.
4003   */
4004  static doWhile(e, t) {
4005    return new PersistencePromise((n, r) => {
4006      const process2 = () => {
4007        true === e() ? t().next(() => {
4008          process2();
4009        }, r) : n();
4010      };
4011      process2();
4012    });
4013  }
4014}
4015/**
4016 * @license
4017 * Copyright 2017 Google LLC
4018 *
4019 * Licensed under the Apache License, Version 2.0 (the "License");
4020 * you may not use this file except in compliance with the License.
4021 * You may obtain a copy of the License at
4022 *
4023 *   http://www.apache.org/licenses/LICENSE-2.0
4024 *
4025 * Unless required by applicable law or agreed to in writing, software
4026 * distributed under the License is distributed on an "AS IS" BASIS,
4027 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4028 * See the License for the specific language governing permissions and
4029 * limitations under the License.
4030 */
4031const U = "SimpleDb";
4032class __PRIVATE_SimpleDbTransaction {
4033  static open(e, t, n, r) {
4034    try {
4035      return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n));
4036    } catch (e2) {
4037      throw new __PRIVATE_IndexedDbTransactionError(t, e2);
4038    }
4039  }
4040  constructor(e, t) {
4041    this.action = e, this.transaction = t, this.aborted = false, /**
4042    * A `Promise` that resolves with the result of the IndexedDb transaction.
4043    */
4044    this.S = new __PRIVATE_Deferred(), this.transaction.oncomplete = () => {
4045      this.S.resolve();
4046    }, this.transaction.onabort = () => {
4047      t.error ? this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.S.resolve();
4048    }, this.transaction.onerror = (t2) => {
4049      const n = __PRIVATE_checkForAndReportiOSError(t2.target.error);
4050      this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, n));
4051    };
4052  }
4053  get D() {
4054    return this.S.promise;
4055  }
4056  abort(e) {
4057    e && this.S.reject(e), this.aborted || (__PRIVATE_logDebug(U, "Aborting transaction:", e ? e.message : "Client-initiated abort"), this.aborted = true, this.transaction.abort());
4058  }
4059  v() {
4060    const e = this.transaction;
4061    this.aborted || "function" != typeof e.commit || e.commit();
4062  }
4063  /**
4064   * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
4065   * operations performed on the SimpleDbStore happen within the context of this
4066   * transaction and it cannot be used anymore once the transaction is
4067   * completed.
4068   *
4069   * Note that we can't actually enforce that the KeyType and ValueType are
4070   * correct, but they allow type safety through the rest of the consuming code.
4071   */
4072  store(e) {
4073    const t = this.transaction.objectStore(e);
4074    return new __PRIVATE_SimpleDbStore(t);
4075  }
4076}
4077class __PRIVATE_SimpleDb {
4078  /** Deletes the specified database. */
4079  static delete(e) {
4080    __PRIVATE_logDebug(U, "Removing database:", e);
4081    return __PRIVATE_wrapRequest(getGlobal().indexedDB.deleteDatabase(e)).toPromise();
4082  }
4083  /** Returns true if IndexedDB is available in the current environment. */
4084  static C() {
4085    if (!isIndexedDBAvailable()) return false;
4086    if (__PRIVATE_SimpleDb.F()) return true;
4087    const e = getUA(), t = __PRIVATE_SimpleDb.M(e), n = 0 < t && t < 10, r = __PRIVATE_getAndroidVersion(e), i = 0 < r && r < 4.5;
4088    return !(e.indexOf("MSIE ") > 0 || e.indexOf("Trident/") > 0 || e.indexOf("Edge/") > 0 || n || i);
4089  }
4090  /**
4091   * Returns true if the backing IndexedDB store is the Node IndexedDBShim
4092   * (see https://github.com/axemclion/IndexedDBShim).
4093   */
4094  static F() {
4095    var e;
4096    return "undefined" != typeof process && "YES" === (null === (e = process.__PRIVATE_env) || void 0 === e ? void 0 : e.O);
4097  }
4098  /** Helper to get a typed SimpleDbStore from a transaction. */
4099  static N(e, t) {
4100    return e.store(t);
4101  }
4102  // visible for testing
4103  /** Parse User Agent to determine iOS version. Returns -1 if not found. */
4104  static M(e) {
4105    const t = e.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = t ? t[1].split("_").slice(0, 2).join(".") : "-1";
4106    return Number(n);
4107  }
4108  /*
4109   * Creates a new SimpleDb wrapper for IndexedDb database `name`.
4110   *
4111   * Note that `version` must not be a downgrade. IndexedDB does not support
4112   * downgrading the schema version. We currently do not support any way to do
4113   * versioning outside of IndexedDB's versioning mechanism, as only
4114   * version-upgrade transactions are allowed to do things like create
4115   * objectstores.
4116   */
4117  constructor(e, t, n) {
4118    this.name = e, this.version = t, this.B = n, this.L = null;
4119    12.2 === __PRIVATE_SimpleDb.M(getUA()) && __PRIVATE_logError("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");
4120  }
4121  /**
4122   * Opens the specified database, creating or upgrading it if necessary.
4123   */
4124  async k(e) {
4125    return this.db || (__PRIVATE_logDebug(U, "Opening database:", this.name), this.db = await new Promise((t, n) => {
4126      const r = indexedDB.open(this.name, this.version);
4127      r.onsuccess = (e2) => {
4128        const n2 = e2.target.result;
4129        t(n2);
4130      }, r.onblocked = () => {
4131        n(new __PRIVATE_IndexedDbTransactionError(e, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
4132      }, r.onerror = (t2) => {
4133        const r2 = t2.target.error;
4134        "VersionError" === r2.name ? n(new FirestoreError(N.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === r2.name ? n(new FirestoreError(N.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + r2)) : n(new __PRIVATE_IndexedDbTransactionError(e, r2));
4135      }, r.onupgradeneeded = (e2) => {
4136        __PRIVATE_logDebug(U, 'Database "' + this.name + '" requires upgrade from version:', e2.oldVersion);
4137        const t2 = e2.target.result;
4138        if (null !== this.L && this.L !== e2.oldVersion)
4139          throw new Error(`refusing to open IndexedDB database due to potential corruption of the IndexedDB database data; this corruption could be caused by clicking the "clear site data" button in a web browser; try reloading the web page to re-initialize the IndexedDB database: lastClosedDbVersion=${this.L}, event.oldVersion=${e2.oldVersion}, event.newVersion=${e2.newVersion}, db.version=${t2.version}`);
4140        this.B.q(t2, r.transaction, e2.oldVersion, this.version).next(() => {
4141          __PRIVATE_logDebug(U, "Database upgrade to version " + this.version + " complete");
4142        });
4143      };
4144    }), this.db.addEventListener("close", (e2) => {
4145      const t = e2.target;
4146      this.L = t.version;
4147    }, {
4148      passive: true
4149    })), this.db.addEventListener("versionchange", (e2) => {
4150      var t;
4151      null === e2.newVersion && (__PRIVATE_logWarn('Received "versionchange" event with newVersion===null; notifying the registered DatabaseDeletedListener, if any'), null === (t = this.databaseDeletedListener) || void 0 === t || t.call(this));
4152    }, {
4153      passive: true
4154    }), this.db;
4155  }
4156  setDatabaseDeletedListener(e) {
4157    if (this.databaseDeletedListener) throw new Error("setDatabaseDeletedListener() may only be called once, and it has already been called");
4158    this.databaseDeletedListener = e;
4159  }
4160  async runTransaction(e, t, n, r) {
4161    const i = "readonly" === t;
4162    let s = 0;
4163    for (; ; ) {
4164      ++s;
4165      try {
4166        this.db = await this.k(e);
4167        const t2 = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? "readonly" : "readwrite", n), s2 = r(t2).next((e2) => (t2.v(), e2)).catch((e2) => (
4168          // Abort the transaction if there was an error.
4169          (t2.abort(e2), PersistencePromise.reject(e2))
4170        )).toPromise();
4171        return s2.catch(() => {
4172        }), // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
4173        // fire), but still return the original transactionFnResult back to the
4174        // caller.
4175        await t2.D, s2;
4176      } catch (e2) {
4177        const t2 = e2, n2 = "FirebaseError" !== t2.name && s < 3;
4178        if (__PRIVATE_logDebug(U, "Transaction failed with error:", t2.message, "Retrying:", n2), this.close(), !n2) return Promise.reject(t2);
4179      }
4180    }
4181  }
4182  close() {
4183    this.db && this.db.close(), this.db = void 0;
4184  }
4185}
4186function __PRIVATE_getAndroidVersion(e) {
4187  const t = e.match(/Android ([\d.]+)/i), n = t ? t[1].split(".").slice(0, 2).join(".") : "-1";
4188  return Number(n);
4189}
4190class __PRIVATE_IterationController {
4191  constructor(e) {
4192    this.$ = e, this.U = false, this.K = null;
4193  }
4194  get isDone() {
4195    return this.U;
4196  }
4197  get W() {
4198    return this.K;
4199  }
4200  set cursor(e) {
4201    this.$ = e;
4202  }
4203  /**
4204   * This function can be called to stop iteration at any point.
4205   */
4206  done() {
4207    this.U = true;
4208  }
4209  /**
4210   * This function can be called to skip to that next key, which could be
4211   * an index or a primary key.
4212   */
4213  G(e) {
4214    this.K = e;
4215  }
4216  /**
4217   * Delete the current cursor value from the object store.
4218   *
4219   * NOTE: You CANNOT do this with a keysOnly query.
4220   */
4221  delete() {
4222    return __PRIVATE_wrapRequest(this.$.delete());
4223  }
4224}
4225class __PRIVATE_IndexedDbTransactionError extends FirestoreError {
4226  constructor(e, t) {
4227    super(N.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = "IndexedDbTransactionError";
4228  }
4229}
4230function __PRIVATE_isIndexedDbTransactionError(e) {
4231  return "IndexedDbTransactionError" === e.name;
4232}
4233class __PRIVATE_SimpleDbStore {
4234  constructor(e) {
4235    this.store = e;
4236  }
4237  put(e, t) {
4238    let n;
4239    return void 0 !== t ? (__PRIVATE_logDebug(U, "PUT", this.store.name, e, t), n = this.store.put(t, e)) : (__PRIVATE_logDebug(U, "PUT", this.store.name, "<auto-key>", e), n = this.store.put(e)), __PRIVATE_wrapRequest(n);
4240  }
4241  /**
4242   * Adds a new value into an Object Store and returns the new key. Similar to
4243   * IndexedDb's `add()`, this method will fail on primary key collisions.
4244   *
4245   * @param value - The object to write.
4246   * @returns The key of the value to add.
4247   */
4248  add(e) {
4249    __PRIVATE_logDebug(U, "ADD", this.store.name, e, e);
4250    return __PRIVATE_wrapRequest(this.store.add(e));
4251  }
4252  /**
4253   * Gets the object with the specified key from the specified store, or null
4254   * if no object exists with the specified key.
4255   *
4256   * @key The key of the object to get.
4257   * @returns The object with the specified key or null if no object exists.
4258   */
4259  get(e) {
4260    return __PRIVATE_wrapRequest(this.store.get(e)).next((t) => (
4261      // Normalize nonexistence to null.
4262      (void 0 === t && (t = null), __PRIVATE_logDebug(U, "GET", this.store.name, e, t), t)
4263    ));
4264  }
4265  delete(e) {
4266    __PRIVATE_logDebug(U, "DELETE", this.store.name, e);
4267    return __PRIVATE_wrapRequest(this.store.delete(e));
4268  }
4269  /**
4270   * If we ever need more of the count variants, we can add overloads. For now,
4271   * all we need is to count everything in a store.
4272   *
4273   * Returns the number of rows in the store.
4274   */
4275  count() {
4276    __PRIVATE_logDebug(U, "COUNT", this.store.name);
4277    return __PRIVATE_wrapRequest(this.store.count());
4278  }
4279  j(e, t) {
4280    const n = this.options(e, t), r = n.index ? this.store.index(n.index) : this.store;
4281    if ("function" == typeof r.getAll) {
4282      const e2 = r.getAll(n.range);
4283      return new PersistencePromise((t2, n2) => {
4284        e2.onerror = (e3) => {
4285          n2(e3.target.error);
4286        }, e2.onsuccess = (e3) => {
4287          t2(e3.target.result);
4288        };
4289      });
4290    }
4291    {
4292      const e2 = this.cursor(n), t2 = [];
4293      return this.J(e2, (e3, n2) => {
4294        t2.push(n2);
4295      }).next(() => t2);
4296    }
4297  }
4298  /**
4299   * Loads the first `count` elements from the provided index range. Loads all
4300   * elements if no limit is provided.
4301   */
4302  H(e, t) {
4303    const n = this.store.getAll(e, null === t ? void 0 : t);
4304    return new PersistencePromise((e2, t2) => {
4305      n.onerror = (e3) => {
4306        t2(e3.target.error);
4307      }, n.onsuccess = (t3) => {
4308        e2(t3.target.result);
4309      };
4310    });
4311  }
4312  Y(e, t) {
4313    __PRIVATE_logDebug(U, "DELETE ALL", this.store.name);
4314    const n = this.options(e, t);
4315    n.Z = false;
4316    const r = this.cursor(n);
4317    return this.J(r, (e2, t2, n2) => n2.delete());
4318  }
4319  X(e, t) {
4320    let n;
4321    t ? n = e : (n = {}, t = e);
4322    const r = this.cursor(n);
4323    return this.J(r, t);
4324  }
4325  /**
4326   * Iterates over a store, but waits for the given callback to complete for
4327   * each entry before iterating the next entry. This allows the callback to do
4328   * asynchronous work to determine if this iteration should continue.
4329   *
4330   * The provided callback should return `true` to continue iteration, and
4331   * `false` otherwise.
4332   */
4333  ee(e) {
4334    const t = this.cursor({});
4335    return new PersistencePromise((n, r) => {
4336      t.onerror = (e2) => {
4337        const t2 = __PRIVATE_checkForAndReportiOSError(e2.target.error);
4338        r(t2);
4339      }, t.onsuccess = (t2) => {
4340        const r2 = t2.target.result;
4341        r2 ? e(r2.primaryKey, r2.value).next((e2) => {
4342          e2 ? r2.continue() : n();
4343        }) : n();
4344      };
4345    });
4346  }
4347  J(e, t) {
4348    const n = [];
4349    return new PersistencePromise((r, i) => {
4350      e.onerror = (e2) => {
4351        i(e2.target.error);
4352      }, e.onsuccess = (e2) => {
4353        const i2 = e2.target.result;
4354        if (!i2) return void r();
4355        const s = new __PRIVATE_IterationController(i2), o = t(i2.primaryKey, i2.value, s);
4356        if (o instanceof PersistencePromise) {
4357          const e3 = o.catch((e4) => (s.done(), PersistencePromise.reject(e4)));
4358          n.push(e3);
4359        }
4360        s.isDone ? r() : null === s.W ? i2.continue() : i2.continue(s.W);
4361      };
4362    }).next(() => PersistencePromise.waitFor(n));
4363  }
4364  options(e, t) {
4365    let n;
4366    return void 0 !== e && ("string" == typeof e ? n = e : t = e), {
4367      index: n,
4368      range: t
4369    };
4370  }
4371  cursor(e) {
4372    let t = "next";
4373    if (e.reverse && (t = "prev"), e.index) {
4374      const n = this.store.index(e.index);
4375      return e.Z ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t);
4376    }
4377    return this.store.openCursor(e.range, t);
4378  }
4379}
4380function __PRIVATE_wrapRequest(e) {
4381  return new PersistencePromise((t, n) => {
4382    e.onsuccess = (e2) => {
4383      const n2 = e2.target.result;
4384      t(n2);
4385    }, e.onerror = (e2) => {
4386      const t2 = __PRIVATE_checkForAndReportiOSError(e2.target.error);
4387      n(t2);
4388    };
4389  });
4390}
4391let K = false;
4392function __PRIVATE_checkForAndReportiOSError(e) {
4393  const t = __PRIVATE_SimpleDb.M(getUA());
4394  if (t >= 12.2 && t < 13) {
4395    const t2 = "An internal error was encountered in the Indexed Database server";
4396    if (e.message.indexOf(t2) >= 0) {
4397      const e2 = new FirestoreError("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t2}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
4398      return K || (K = true, // Throw a global exception outside of this promise chain, for the user to
4399      // potentially catch.
4400      setTimeout(() => {
4401        throw e2;
4402      }, 0)), e2;
4403    }
4404  }
4405  return e;
4406}
4407const W = "IndexBackfiller";
4408class __PRIVATE_IndexBackfillerScheduler {
4409  constructor(e, t) {
4410    this.asyncQueue = e, this.te = t, this.task = null;
4411  }
4412  start() {
4413    this.ne(15e3);
4414  }
4415  stop() {
4416    this.task && (this.task.cancel(), this.task = null);
4417  }
4418  get started() {
4419    return null !== this.task;
4420  }
4421  ne(e) {
4422    __PRIVATE_logDebug(W, `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill", e, async () => {
4423      this.task = null;
4424      try {
4425        const e2 = await this.te.re();
4426        __PRIVATE_logDebug(W, `Documents written: ${e2}`);
4427      } catch (e2) {
4428        __PRIVATE_isIndexedDbTransactionError(e2) ? __PRIVATE_logDebug(W, "Ignoring IndexedDB error during index backfill: ", e2) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e2);
4429      }
4430      await this.ne(6e4);
4431    });
4432  }
4433}
4434class __PRIVATE_IndexBackfiller {
4435  constructor(e, t) {
4436    this.localStore = e, this.persistence = t;
4437  }
4438  async re(e = 50) {
4439    return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (t) => this.ie(t, e));
4440  }
4441  /** Writes index entries until the cap is reached. Returns the number of documents processed. */
4442  ie(e, t) {
4443    const n = /* @__PURE__ */ new Set();
4444    let r = t, i = true;
4445    return PersistencePromise.doWhile(() => true === i && r > 0, () => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t2) => {
4446      if (null !== t2 && !n.has(t2)) return __PRIVATE_logDebug(W, `Processing collection: ${t2}`), this.se(e, t2, r).next((e2) => {
4447        r -= e2, n.add(t2);
4448      });
4449      i = false;
4450    })).next(() => t - r);
4451  }
4452  /**
4453   * Writes entries for the provided collection group. Returns the number of documents processed.
4454   */
4455  se(e, t, n) {
4456    return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r) => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n2) => {
4457      const i = n2.changes;
4458      return this.localStore.indexManager.updateIndexEntries(e, i).next(() => this.oe(r, n2)).next((n3) => (__PRIVATE_logDebug(W, `Updating offset: ${n3}`), this.localStore.indexManager.updateCollectionGroup(e, t, n3))).next(() => i.size);
4459    }));
4460  }
4461  /** Returns the next offset based on the provided documents. */
4462  oe(e, t) {
4463    let n = e;
4464    return t.changes.forEach((e2, t2) => {
4465      const r = __PRIVATE_newIndexOffsetFromDocument(t2);
4466      __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r);
4467    }), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId));
4468  }
4469}
4470/**
4471 * @license
4472 * Copyright 2018 Google LLC
4473 *
4474 * Licensed under the Apache License, Version 2.0 (the "License");
4475 * you may not use this file except in compliance with the License.
4476 * You may obtain a copy of the License at
4477 *
4478 *   http://www.apache.org/licenses/LICENSE-2.0
4479 *
4480 * Unless required by applicable law or agreed to in writing, software
4481 * distributed under the License is distributed on an "AS IS" BASIS,
4482 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4483 * See the License for the specific language governing permissions and
4484 * limitations under the License.
4485 */
4486class __PRIVATE_ListenSequence {
4487  constructor(e, t) {
4488    this.previousValue = e, t && (t.sequenceNumberHandler = (e2) => this._e(e2), this.ae = (e2) => t.writeSequenceNumber(e2));
4489  }
4490  _e(e) {
4491    return this.previousValue = Math.max(e, this.previousValue), this.previousValue;
4492  }
4493  next() {
4494    const e = ++this.previousValue;
4495    return this.ae && this.ae(e), e;
4496  }
4497}
4498__PRIVATE_ListenSequence.ue = -1;
4499/**
4500 * @license
4501 * Copyright 2017 Google LLC
4502 *
4503 * Licensed under the Apache License, Version 2.0 (the "License");
4504 * you may not use this file except in compliance with the License.
4505 * You may obtain a copy of the License at
4506 *
4507 *   http://www.apache.org/licenses/LICENSE-2.0
4508 *
4509 * Unless required by applicable law or agreed to in writing, software
4510 * distributed under the License is distributed on an "AS IS" BASIS,
4511 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4512 * See the License for the specific language governing permissions and
4513 * limitations under the License.
4514 */
4515const G = -1;
4516function __PRIVATE_isNullOrUndefined(e) {
4517  return null == e;
4518}
4519function __PRIVATE_isNegativeZero(e) {
4520  return 0 === e && 1 / e == -1 / 0;
4521}
4522function isSafeInteger(e) {
4523  return "number" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER;
4524}
4525/**
4526 * @license
4527 * Copyright 2017 Google LLC
4528 *
4529 * Licensed under the Apache License, Version 2.0 (the "License");
4530 * you may not use this file except in compliance with the License.
4531 * You may obtain a copy of the License at
4532 *
4533 *   http://www.apache.org/licenses/LICENSE-2.0
4534 *
4535 * Unless required by applicable law or agreed to in writing, software
4536 * distributed under the License is distributed on an "AS IS" BASIS,
4537 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4538 * See the License for the specific language governing permissions and
4539 * limitations under the License.
4540 */
4541const z = "�";
4542function __PRIVATE_encodeResourcePath(e) {
4543  let t = "";
4544  for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), t = __PRIVATE_encodeSegment(e.get(n), t);
4545  return __PRIVATE_encodeSeparator(t);
4546}
4547function __PRIVATE_encodeSegment(e, t) {
4548  let n = t;
4549  const r = e.length;
4550  for (let t2 = 0; t2 < r; t2++) {
4551    const r2 = e.charAt(t2);
4552    switch (r2) {
4553      case "\0":
4554        n += "��";
4555        break;
4556      case z:
4557        n += "��";
4558        break;
4559      default:
4560        n += r2;
4561    }
4562  }
4563  return n;
4564}
4565function __PRIVATE_encodeSeparator(e) {
4566  return e + z + "�";
4567}
4568function __PRIVATE_decodeResourcePath(e) {
4569  const t = e.length;
4570  if (__PRIVATE_hardAssert(t >= 2, 64408, {
4571    path: e
4572  }), 2 === t) return __PRIVATE_hardAssert(e.charAt(0) === z && "�" === e.charAt(1), 56145, {
4573    path: e
4574  }), ResourcePath.emptyPath();
4575  const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = [];
4576  let r = "";
4577  for (let i = 0; i < t; ) {
4578    const t2 = e.indexOf(z, i);
4579    (t2 < 0 || t2 > __PRIVATE_lastReasonableEscapeIndex) && fail(50515, {
4580      path: e
4581    });
4582    switch (e.charAt(t2 + 1)) {
4583      case "�":
4584        const s = e.substring(i, t2);
4585        let o;
4586        0 === r.length ? (
4587          // Avoid copying for the common case of a segment that excludes \0
4588          // and \001
4589          o = s
4590        ) : (r += s, o = r, r = ""), n.push(o);
4591        break;
4592      case "�":
4593        r += e.substring(i, t2), r += "\0";
4594        break;
4595      case "�":
4596        r += e.substring(i, t2 + 1);
4597        break;
4598      default:
4599        fail(61167, {
4600          path: e
4601        });
4602    }
4603    i = t2 + 2;
4604  }
4605  return new ResourcePath(n);
4606}
4607/**
4608 * @license
4609 * Copyright 2022 Google LLC
4610 *
4611 * Licensed under the Apache License, Version 2.0 (the "License");
4612 * you may not use this file except in compliance with the License.
4613 * You may obtain a copy of the License at
4614 *
4615 *   http://www.apache.org/licenses/LICENSE-2.0
4616 *
4617 * Unless required by applicable law or agreed to in writing, software
4618 * distributed under the License is distributed on an "AS IS" BASIS,
4619 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4620 * See the License for the specific language governing permissions and
4621 * limitations under the License.
4622 */
4623const j = "remoteDocuments", J = "owner", H = "owner", Y = "mutationQueues", Z = "userId", X = "mutations", ee = "batchId", te = "userMutationsIndex", ne = ["userId", "batchId"];
4624/**
4625 * @license
4626 * Copyright 2022 Google LLC
4627 *
4628 * Licensed under the Apache License, Version 2.0 (the "License");
4629 * you may not use this file except in compliance with the License.
4630 * You may obtain a copy of the License at
4631 *
4632 *   http://www.apache.org/licenses/LICENSE-2.0
4633 *
4634 * Unless required by applicable law or agreed to in writing, software
4635 * distributed under the License is distributed on an "AS IS" BASIS,
4636 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4637 * See the License for the specific language governing permissions and
4638 * limitations under the License.
4639 */
4640function __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) {
4641  return [e, __PRIVATE_encodeResourcePath(t)];
4642}
4643function __PRIVATE_newDbDocumentMutationKey(e, t, n) {
4644  return [e, __PRIVATE_encodeResourcePath(t), n];
4645}
4646const re = {}, ie = "documentMutations", se = "remoteDocumentsV14", oe = ["prefixPath", "collectionGroup", "readTime", "documentId"], _e = "documentKeyIndex", ae = ["prefixPath", "collectionGroup", "documentId"], ue = "collectionGroupIndex", ce = ["collectionGroup", "readTime", "prefixPath", "documentId"], le = "remoteDocumentGlobal", he = "remoteDocumentGlobalKey", Pe = "targets", Te = "queryTargetsIndex", Ie = ["canonicalId", "targetId"], de = "targetDocuments", Ee = ["targetId", "path"], Ae = "documentTargetsIndex", Re = ["path", "targetId"], Ve = "targetGlobalKey", me = "targetGlobal", fe = "collectionParents", ge = ["collectionId", "parent"], pe = "clientMetadata", ye = "clientId", we = "bundles", Se = "bundleId", be = "namedQueries", De = "name", ve = "indexConfiguration", Ce = "indexId", Fe = "collectionGroupIndex", Me = "collectionGroup", xe = "indexState", Oe = ["indexId", "uid"], Ne = "sequenceNumberIndex", Be = ["uid", "sequenceNumber"], Le = "indexEntries", ke = ["indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey"], qe = "documentKeyIndex", Qe = ["indexId", "uid", "orderedDocumentKey"], $e = "documentOverlays", Ue = ["userId", "collectionPath", "documentId"], Ke = "collectionPathOverlayIndex", We = ["userId", "collectionPath", "largestBatchId"], Ge = "collectionGroupOverlayIndex", ze = ["userId", "collectionGroup", "largestBatchId"], je = "globals", Je = "name", He = [...[...[...[...[Y, X, ie, j, Pe, J, me, de], pe], le], fe], we, be], Ye = [...He, $e], Ze = [Y, X, ie, se, Pe, J, me, de, pe, le, fe, we, be, $e], Xe = Ze, et = [...Xe, ve, xe, Le], tt = et, nt = [...et, je], rt = nt;
4647/**
4648 * @license
4649 * Copyright 2020 Google LLC
4650 *
4651 * Licensed under the Apache License, Version 2.0 (the "License");
4652 * you may not use this file except in compliance with the License.
4653 * You may obtain a copy of the License at
4654 *
4655 *   http://www.apache.org/licenses/LICENSE-2.0
4656 *
4657 * Unless required by applicable law or agreed to in writing, software
4658 * distributed under the License is distributed on an "AS IS" BASIS,
4659 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4660 * See the License for the specific language governing permissions and
4661 * limitations under the License.
4662 */
4663class __PRIVATE_IndexedDbTransaction extends PersistenceTransaction {
4664  constructor(e, t) {
4665    super(), this.ce = e, this.currentSequenceNumber = t;
4666  }
4667}
4668function __PRIVATE_getStore(e, t) {
4669  const n = __PRIVATE_debugCast(e);
4670  return __PRIVATE_SimpleDb.N(n.ce, t);
4671}
4672/**
4673 * @license
4674 * Copyright 2017 Google LLC
4675 *
4676 * Licensed under the Apache License, Version 2.0 (the "License");
4677 * you may not use this file except in compliance with the License.
4678 * You may obtain a copy of the License at
4679 *
4680 *   http://www.apache.org/licenses/LICENSE-2.0
4681 *
4682 * Unless required by applicable law or agreed to in writing, software
4683 * distributed under the License is distributed on an "AS IS" BASIS,
4684 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4685 * See the License for the specific language governing permissions and
4686 * limitations under the License.
4687 */
4688function __PRIVATE_objectSize(e) {
4689  let t = 0;
4690  for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++;
4691  return t;
4692}
4693function forEach(e, t) {
4694  for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]);
4695}
4696function __PRIVATE_mapToArray(e, t) {
4697  const n = [];
4698  for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e));
4699  return n;
4700}
4701function isEmpty(e) {
4702  for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return false;
4703  return true;
4704}
4705/**
4706 * @license
4707 * Copyright 2017 Google LLC
4708 *
4709 * Licensed under the Apache License, Version 2.0 (the "License");
4710 * you may not use this file except in compliance with the License.
4711 * You may obtain a copy of the License at
4712 *
4713 *   http://www.apache.org/licenses/LICENSE-2.0
4714 *
4715 * Unless required by applicable law or agreed to in writing, software
4716 * distributed under the License is distributed on an "AS IS" BASIS,
4717 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4718 * See the License for the specific language governing permissions and
4719 * limitations under the License.
4720 */
4721class SortedMap {
4722  constructor(e, t) {
4723    this.comparator = e, this.root = t || LLRBNode.EMPTY;
4724  }
4725  // Returns a copy of the map, with the specified key/value added or replaced.
4726  insert(e, t) {
4727    return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));
4728  }
4729  // Returns a copy of the map, with the specified key removed.
4730  remove(e) {
4731    return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));
4732  }
4733  // Returns the value of the node with the given key, or null.
4734  get(e) {
4735    let t = this.root;
4736    for (; !t.isEmpty(); ) {
4737      const n = this.comparator(e, t.key);
4738      if (0 === n) return t.value;
4739      n < 0 ? t = t.left : n > 0 && (t = t.right);
4740    }
4741    return null;
4742  }
4743  // Returns the index of the element in this sorted map, or -1 if it doesn't
4744  // exist.
4745  indexOf(e) {
4746    let t = 0, n = this.root;
4747    for (; !n.isEmpty(); ) {
4748      const r = this.comparator(e, n.key);
4749      if (0 === r) return t + n.left.size;
4750      r < 0 ? n = n.left : (
4751        // Count all nodes left of the node plus the node itself
4752        (t += n.left.size + 1, n = n.right)
4753      );
4754    }
4755    return -1;
4756  }
4757  isEmpty() {
4758    return this.root.isEmpty();
4759  }
4760  // Returns the total number of nodes in the map.
4761  get size() {
4762    return this.root.size;
4763  }
4764  // Returns the minimum key in the map.
4765  minKey() {
4766    return this.root.minKey();
4767  }
4768  // Returns the maximum key in the map.
4769  maxKey() {
4770    return this.root.maxKey();
4771  }
4772  // Traverses the map in key order and calls the specified action function
4773  // for each key/value pair. If action returns true, traversal is aborted.
4774  // Returns the first truthy value returned by action, or the last falsey
4775  // value returned by action.
4776  inorderTraversal(e) {
4777    return this.root.inorderTraversal(e);
4778  }
4779  forEach(e) {
4780    this.inorderTraversal((t, n) => (e(t, n), false));
4781  }
4782  toString() {
4783    const e = [];
4784    return this.inorderTraversal((t, n) => (e.push(`${t}:${n}`), false)), `{${e.join(", ")}}`;
4785  }
4786  // Traverses the map in reverse key order and calls the specified action
4787  // function for each key/value pair. If action returns true, traversal is
4788  // aborted.
4789  // Returns the first truthy value returned by action, or the last falsey
4790  // value returned by action.
4791  reverseTraversal(e) {
4792    return this.root.reverseTraversal(e);
4793  }
4794  // Returns an iterator over the SortedMap.
4795  getIterator() {
4796    return new SortedMapIterator(this.root, null, this.comparator, false);
4797  }
4798  getIteratorFrom(e) {
4799    return new SortedMapIterator(this.root, e, this.comparator, false);
4800  }
4801  getReverseIterator() {
4802    return new SortedMapIterator(this.root, null, this.comparator, true);
4803  }
4804  getReverseIteratorFrom(e) {
4805    return new SortedMapIterator(this.root, e, this.comparator, true);
4806  }
4807}
4808class SortedMapIterator {
4809  constructor(e, t, n, r) {
4810    this.isReverse = r, this.nodeStack = [];
4811    let i = 1;
4812    for (; !e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, // flip the comparison if we're going in reverse
4813    t && r && (i *= -1), i < 0)
4814      e = this.isReverse ? e.left : e.right;
4815    else {
4816      if (0 === i) {
4817        this.nodeStack.push(e);
4818        break;
4819      }
4820      this.nodeStack.push(e), e = this.isReverse ? e.right : e.left;
4821    }
4822  }
4823  getNext() {
4824    let e = this.nodeStack.pop();
4825    const t = {
4826      key: e.key,
4827      value: e.value
4828    };
4829    if (this.isReverse) for (e = e.left; !e.isEmpty(); ) this.nodeStack.push(e), e = e.right;
4830    else for (e = e.right; !e.isEmpty(); ) this.nodeStack.push(e), e = e.left;
4831    return t;
4832  }
4833  hasNext() {
4834    return this.nodeStack.length > 0;
4835  }
4836  peek() {
4837    if (0 === this.nodeStack.length) return null;
4838    const e = this.nodeStack[this.nodeStack.length - 1];
4839    return {
4840      key: e.key,
4841      value: e.value
4842    };
4843  }
4844}
4845class LLRBNode {
4846  constructor(e, t, n, r, i) {
4847    this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size;
4848  }
4849  // Returns a copy of the current node, optionally replacing pieces of it.
4850  copy(e, t, n, r, i) {
4851    return new LLRBNode(null != e ? e : this.key, null != t ? t : this.value, null != n ? n : this.color, null != r ? r : this.left, null != i ? i : this.right);
4852  }
4853  isEmpty() {
4854    return false;
vendor: 4,191 bytes, lines 4855-4955
4855  }
4856  // Traverses the tree in key order and calls the specified action function
4857  // for each node. If action returns true, traversal is aborted.
4858  // Returns the first truthy value returned by action, or the last falsey
4859  // value returned by action.
4860  inorderTraversal(e) {
4861    return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e);
4862  }
4863  // Traverses the tree in reverse key order and calls the specified action
4864  // function for each node. If action returns true, traversal is aborted.
4865  // Returns the first truthy value returned by action, or the last falsey
4866  // value returned by action.
4867  reverseTraversal(e) {
4868    return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e);
4869  }
4870  // Returns the minimum node in the tree.
4871  min() {
4872    return this.left.isEmpty() ? this : this.left.min();
4873  }
4874  // Returns the maximum key in the tree.
4875  minKey() {
4876    return this.min().key;
4877  }
4878  // Returns the maximum key in the tree.
4879  maxKey() {
4880    return this.right.isEmpty() ? this.key : this.right.maxKey();
4881  }
4882  // Returns new tree, with the key/value added.
4883  insert(e, t, n) {
4884    let r = this;
4885    const i = n(e, r.key);
4886    return r = i < 0 ? r.copy(null, null, null, r.left.insert(e, t, n), null) : 0 === i ? r.copy(null, t, null, null, null) : r.copy(null, null, null, null, r.right.insert(e, t, n)), r.fixUp();
4887  }
4888  removeMin() {
4889    if (this.left.isEmpty()) return LLRBNode.EMPTY;
4890    let e = this;
4891    return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), e.fixUp();
4892  }
4893  // Returns new tree, with the specified item removed.
4894  remove(e, t) {
4895    let n, r = this;
4896    if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), r = r.copy(null, null, null, r.left.remove(e, t), null);
4897    else {
4898      if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), 0 === t(e, r.key)) {
4899        if (r.right.isEmpty()) return LLRBNode.EMPTY;
4900        n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin());
4901      }
4902      r = r.copy(null, null, null, null, r.right.remove(e, t));
4903    }
4904    return r.fixUp();
4905  }
4906  isRed() {
4907    return this.color;
4908  }
4909  // Returns new tree after performing any needed rotations.
4910  fixUp() {
4911    let e = this;
4912    return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e;
4913  }
4914  moveRedLeft() {
4915    let e = this.colorFlip();
4916    return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), e = e.rotateLeft(), e = e.colorFlip()), e;
4917  }
4918  moveRedRight() {
4919    let e = this.colorFlip();
4920    return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e;
4921  }
4922  rotateLeft() {
4923    const e = this.copy(null, null, LLRBNode.RED, null, this.right.left);
4924    return this.right.copy(null, null, this.color, e, null);
4925  }
4926  rotateRight() {
4927    const e = this.copy(null, null, LLRBNode.RED, this.left.right, null);
4928    return this.left.copy(null, null, this.color, null, e);
4929  }
4930  colorFlip() {
4931    const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null);
4932    return this.copy(null, null, !this.color, e, t);
4933  }
4934  // For testing.
4935  checkMaxDepth() {
4936    const e = this.check();
4937    return Math.pow(2, e) <= this.size + 1;
4938  }
4939  // In a balanced RB tree, the black-depth (number of black nodes) from root to
4940  // leaves is equal on both sides.  This function verifies that or asserts.
4941  check() {
4942    if (this.isRed() && this.left.isRed()) throw fail(43730, {
4943      key: this.key,
4944      value: this.value
4945    });
4946    if (this.right.isRed()) throw fail(14113, {
4947      key: this.key,
4948      value: this.value
4949    });
4950    const e = this.left.check();
4951    if (e !== this.right.check()) throw fail(27949);
4952    return e + (this.isRed() ? 0 : 1);
4953  }
4954}
4955LLRBNode.EMPTY = null, LLRBNode.RED = true, LLRBNode.BLACK = false;
4956LLRBNode.EMPTY = new // Represents an empty node (a leaf node in the Red-Black Tree).
4957class LLRBEmptyNode {
4958  constructor() {
4959    this.size = 0;
4960  }
4961  get key() {
4962    throw fail(57766);
4963  }
4964  get value() {
4965    throw fail(16141);
4966  }
4967  get color() {
4968    throw fail(16727);
4969  }
4970  get left() {
4971    throw fail(29726);
4972  }
4973  get right() {
4974    throw fail(36894);
4975  }
4976  // Returns a copy of the current node.
4977  copy(e, t, n, r, i) {
4978    return this;
4979  }
4980  // Returns a copy of the tree, with the specified key/value added.
4981  insert(e, t, n) {
4982    return new LLRBNode(e, t);
4983  }
4984  // Returns a copy of the tree, with the specified key removed.
4985  remove(e, t) {
4986    return this;
4987  }
4988  isEmpty() {
4989    return true;
4990  }
4991  inorderTraversal(e) {
4992    return false;
4993  }
4994  reverseTraversal(e) {
4995    return false;
4996  }
4997  minKey() {
4998    return null;
4999  }
5000  maxKey() {
5001    return null;
5002  }
5003  isRed() {
5004    return false;
5005  }
5006  // For testing.
5007  checkMaxDepth() {
5008    return true;
5009  }
5010  check() {
5011    return 0;
5012  }
5013}();
5014/**
5015 * @license
5016 * Copyright 2017 Google LLC
5017 *
5018 * Licensed under the Apache License, Version 2.0 (the "License");
5019 * you may not use this file except in compliance with the License.
5020 * You may obtain a copy of the License at
5021 *
5022 *   http://www.apache.org/licenses/LICENSE-2.0
5023 *
5024 * Unless required by applicable law or agreed to in writing, software
5025 * distributed under the License is distributed on an "AS IS" BASIS,
5026 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5027 * See the License for the specific language governing permissions and
5028 * limitations under the License.
5029 */
5030class SortedSet {
5031  constructor(e) {
5032    this.comparator = e, this.data = new SortedMap(this.comparator);
5033  }
5034  has(e) {
5035    return null !== this.data.get(e);
5036  }
5037  first() {
5038    return this.data.minKey();
5039  }
5040  last() {
5041    return this.data.maxKey();
5042  }
5043  get size() {
5044    return this.data.size;
5045  }
5046  indexOf(e) {
5047    return this.data.indexOf(e);
5048  }
5049  /** Iterates elements in order defined by "comparator" */
5050  forEach(e) {
5051    this.data.inorderTraversal((t, n) => (e(t), false));
5052  }
5053  /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
5054  forEachInRange(e, t) {
5055    const n = this.data.getIteratorFrom(e[0]);
5056    for (; n.hasNext(); ) {
5057      const r = n.getNext();
5058      if (this.comparator(r.key, e[1]) >= 0) return;
5059      t(r.key);
5060    }
5061  }
5062  /**
5063   * Iterates over `elem`s such that: start &lt;= elem until false is returned.
5064   */
5065  forEachWhile(e, t) {
5066    let n;
5067    for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) {
5068      if (!e(n.getNext().key)) return;
5069    }
5070  }
5071  /** Finds the least element greater than or equal to `elem`. */
5072  firstAfterOrEqual(e) {
5073    const t = this.data.getIteratorFrom(e);
5074    return t.hasNext() ? t.getNext().key : null;
5075  }
5076  getIterator() {
5077    return new SortedSetIterator(this.data.getIterator());
5078  }
5079  getIteratorFrom(e) {
5080    return new SortedSetIterator(this.data.getIteratorFrom(e));
5081  }
5082  /** Inserts or updates an element */
5083  add(e) {
5084    return this.copy(this.data.remove(e).insert(e, true));
5085  }
5086  /** Deletes an element */
5087  delete(e) {
5088    return this.has(e) ? this.copy(this.data.remove(e)) : this;
5089  }
5090  isEmpty() {
5091    return this.data.isEmpty();
5092  }
5093  unionWith(e) {
5094    let t = this;
5095    return t.size < e.size && (t = e, e = this), e.forEach((e2) => {
5096      t = t.add(e2);
5097    }), t;
5098  }
5099  isEqual(e) {
5100    if (!(e instanceof SortedSet)) return false;
5101    if (this.size !== e.size) return false;
5102    const t = this.data.getIterator(), n = e.data.getIterator();
5103    for (; t.hasNext(); ) {
5104      const e2 = t.getNext().key, r = n.getNext().key;
5105      if (0 !== this.comparator(e2, r)) return false;
5106    }
5107    return true;
5108  }
5109  toArray() {
5110    const e = [];
5111    return this.forEach((t) => {
5112      e.push(t);
5113    }), e;
5114  }
5115  toString() {
5116    const e = [];
5117    return this.forEach((t) => e.push(t)), "SortedSet(" + e.toString() + ")";
5118  }
5119  copy(e) {
5120    const t = new SortedSet(this.comparator);
5121    return t.data = e, t;
5122  }
5123}
5124class SortedSetIterator {
5125  constructor(e) {
5126    this.iter = e;
5127  }
5128  getNext() {
5129    return this.iter.getNext().key;
5130  }
5131  hasNext() {
5132    return this.iter.hasNext();
5133  }
5134}
5135function __PRIVATE_advanceIterator(e) {
5136  return e.hasNext() ? e.getNext() : void 0;
5137}
5138/**
5139 * @license
5140 * Copyright 2020 Google LLC
5141 *
5142 * Licensed under the Apache License, Version 2.0 (the "License");
5143 * you may not use this file except in compliance with the License.
5144 * You may obtain a copy of the License at
5145 *
5146 *   http://www.apache.org/licenses/LICENSE-2.0
5147 *
5148 * Unless required by applicable law or agreed to in writing, software
5149 * distributed under the License is distributed on an "AS IS" BASIS,
5150 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5151 * See the License for the specific language governing permissions and
5152 * limitations under the License.
5153 */
5154class FieldMask {
5155  constructor(e) {
5156    this.fields = e, // TODO(dimond): validation of FieldMask
5157    // Sort the field mask to support `FieldMask.isEqual()` and assert below.
5158    e.sort(FieldPath$1.comparator);
5159  }
5160  static empty() {
5161    return new FieldMask([]);
5162  }
5163  /**
5164   * Returns a new FieldMask object that is the result of adding all the given
5165   * fields paths to this field mask.
5166   */
5167  unionWith(e) {
5168    let t = new SortedSet(FieldPath$1.comparator);
5169    for (const e2 of this.fields) t = t.add(e2);
5170    for (const n of e) t = t.add(n);
5171    return new FieldMask(t.toArray());
5172  }
5173  /**
5174   * Verifies that `fieldPath` is included by at least one field in this field
5175   * mask.
5176   *
5177   * This is an O(n) operation, where `n` is the size of the field mask.
5178   */
5179  covers(e) {
5180    for (const t of this.fields) if (t.isPrefixOf(e)) return true;
5181    return false;
5182  }
5183  isEqual(e) {
5184    return __PRIVATE_arrayEquals(this.fields, e.fields, (e2, t) => e2.isEqual(t));
5185  }
5186}
5187/**
5188 * @license
5189 * Copyright 2023 Google LLC
5190 *
5191 * Licensed under the Apache License, Version 2.0 (the "License");
5192 * you may not use this file except in compliance with the License.
5193 * You may obtain a copy of the License at
5194 *
5195 *   http://www.apache.org/licenses/LICENSE-2.0
5196 *
5197 * Unless required by applicable law or agreed to in writing, software
5198 * distributed under the License is distributed on an "AS IS" BASIS,
5199 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5200 * See the License for the specific language governing permissions and
5201 * limitations under the License.
5202 */
5203class __PRIVATE_Base64DecodeError extends Error {
5204  constructor() {
5205    super(...arguments), this.name = "Base64DecodeError";
5206  }
5207}
5208/**
5209 * @license
5210 * Copyright 2020 Google LLC
5211 *
5212 * Licensed under the Apache License, Version 2.0 (the "License");
5213 * you may not use this file except in compliance with the License.
5214 * You may obtain a copy of the License at
5215 *
5216 *   http://www.apache.org/licenses/LICENSE-2.0
5217 *
5218 * Unless required by applicable law or agreed to in writing, software
5219 * distributed under the License is distributed on an "AS IS" BASIS,
5220 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5221 * See the License for the specific language governing permissions and
5222 * limitations under the License.
5223 */
5224function __PRIVATE_isBase64Available() {
5225  return "undefined" != typeof atob;
5226}
5227/**
5228 * @license
5229 * Copyright 2020 Google LLC
5230 *
5231 * Licensed under the Apache License, Version 2.0 (the "License");
5232 * you may not use this file except in compliance with the License.
5233 * You may obtain a copy of the License at
5234 *
5235 *   http://www.apache.org/licenses/LICENSE-2.0
5236 *
5237 * Unless required by applicable law or agreed to in writing, software
5238 * distributed under the License is distributed on an "AS IS" BASIS,
5239 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5240 * See the License for the specific language governing permissions and
5241 * limitations under the License.
5242 */
5243class ByteString {
5244  constructor(e) {
5245    this.binaryString = e;
5246  }
5247  static fromBase64String(e) {
5248    const t = function __PRIVATE_decodeBase64(e2) {
5249      try {
5250        return atob(e2);
5251      } catch (e3) {
5252        throw "undefined" != typeof DOMException && e3 instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + e3) : e3;
5253      }
5254    }(e);
5255    return new ByteString(t);
5256  }
5257  static fromUint8Array(e) {
5258    const t = (
5259      /**
5260      * Helper function to convert an Uint8array to a binary string.
5261      */
5262      function __PRIVATE_binaryStringFromUint8Array(e2) {
5263        let t2 = "";
5264        for (let n = 0; n < e2.length; ++n) t2 += String.fromCharCode(e2[n]);
5265        return t2;
5266      }(e)
5267    );
5268    return new ByteString(t);
5269  }
5270  [Symbol.iterator]() {
5271    let e = 0;
5272    return {
5273      next: () => e < this.binaryString.length ? {
5274        value: this.binaryString.charCodeAt(e++),
5275        done: false
5276      } : {
5277        value: void 0,
5278        done: true
5279      }
5280    };
5281  }
5282  toBase64() {
5283    return function __PRIVATE_encodeBase64(e) {
5284      return btoa(e);
5285    }(this.binaryString);
5286  }
5287  toUint8Array() {
5288    return function __PRIVATE_uint8ArrayFromBinaryString(e) {
5289      const t = new Uint8Array(e.length);
5290      for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n);
5291      return t;
5292    }(this.binaryString);
5293  }
5294  approximateByteSize() {
5295    return 2 * this.binaryString.length;
5296  }
5297  compareTo(e) {
5298    return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString);
5299  }
5300  isEqual(e) {
5301    return this.binaryString === e.binaryString;
5302  }
5303}
5304ByteString.EMPTY_BYTE_STRING = new ByteString("");
5305const it = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
5306function __PRIVATE_normalizeTimestamp(e) {
5307  if (__PRIVATE_hardAssert(!!e, 39018), "string" == typeof e) {
5308    let t = 0;
5309    const n = it.exec(e);
5310    if (__PRIVATE_hardAssert(!!n, 46558, {
5311      timestamp: e
5312    }), n[1]) {
5313      let e2 = n[1];
5314      e2 = (e2 + "000000000").substr(0, 9), t = Number(e2);
5315    }
5316    const r = new Date(e);
5317    return {
5318      seconds: Math.floor(r.getTime() / 1e3),
5319      nanos: t
5320    };
5321  }
5322  return {
5323    seconds: __PRIVATE_normalizeNumber(e.seconds),
5324    nanos: __PRIVATE_normalizeNumber(e.nanos)
5325  };
5326}
5327function __PRIVATE_normalizeNumber(e) {
5328  return "number" == typeof e ? e : "string" == typeof e ? Number(e) : 0;
5329}
5330function __PRIVATE_normalizeByteString(e) {
5331  return "string" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e);
5332}
5333/**
5334 * @license
5335 * Copyright 2020 Google LLC
5336 *
5337 * Licensed under the Apache License, Version 2.0 (the "License");
5338 * you may not use this file except in compliance with the License.
5339 * You may obtain a copy of the License at
5340 *
5341 *   http://www.apache.org/licenses/LICENSE-2.0
5342 *
5343 * Unless required by applicable law or agreed to in writing, software
5344 * distributed under the License is distributed on an "AS IS" BASIS,
5345 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5346 * See the License for the specific language governing permissions and
5347 * limitations under the License.
5348 */
5349const st = "server_timestamp", ot = "__type__", _t = "__previous_value__", at = "__local_write_time__";
5350function __PRIVATE_isServerTimestamp(e) {
5351  var t, n;
5352  return (null === (n = ((null === (t = null == e ? void 0 : e.mapValue) || void 0 === t ? void 0 : t.fields) || {})[ot]) || void 0 === n ? void 0 : n.stringValue) === st;
5353}
5354function __PRIVATE_getPreviousValue(e) {
5355  const t = e.mapValue.fields[_t];
5356  return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t;
5357}
5358function __PRIVATE_getLocalWriteTime(e) {
5359  const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields[at].timestampValue);
5360  return new Timestamp(t.seconds, t.nanos);
5361}
5362/**
5363 * @license
5364 * Copyright 2017 Google LLC
5365 *
5366 * Licensed under the Apache License, Version 2.0 (the "License");
5367 * you may not use this file except in compliance with the License.
5368 * You may obtain a copy of the License at
5369 *
5370 *   http://www.apache.org/licenses/LICENSE-2.0
5371 *
5372 * Unless required by applicable law or agreed to in writing, software
5373 * distributed under the License is distributed on an "AS IS" BASIS,
5374 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5375 * See the License for the specific language governing permissions and
5376 * limitations under the License.
5377 */
5378class DatabaseInfo {
5379  /**
5380   * Constructs a DatabaseInfo using the provided host, databaseId and
5381   * persistenceKey.
5382   *
5383   * @param databaseId - The database to use.
5384   * @param appId - The Firebase App Id.
5385   * @param persistenceKey - A unique identifier for this Firestore's local
5386   * storage (used in conjunction with the databaseId).
5387   * @param host - The Firestore backend host to connect to.
5388   * @param ssl - Whether to use SSL when connecting.
5389   * @param forceLongPolling - Whether to use the forceLongPolling option
5390   * when using WebChannel as the network transport.
5391   * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
5392   * option when using WebChannel as the network transport.
5393   * @param longPollingOptions Options that configure long-polling.
5394   * @param useFetchStreams Whether to use the Fetch API instead of
5395   * XMLHTTPRequest
5396   */
5397  constructor(e, t, n, r, i, s, o, _, a, u) {
5398    this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = _, this.useFetchStreams = a, this.isUsingEmulator = u;
5399  }
5400}
5401const ut = "(default)";
5402class DatabaseId {
5403  constructor(e, t) {
5404    this.projectId = e, this.database = t || ut;
5405  }
5406  static empty() {
5407    return new DatabaseId("", "");
5408  }
5409  get isDefaultDatabase() {
5410    return this.database === ut;
5411  }
5412  isEqual(e) {
5413    return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database;
5414  }
5415}
5416/**
5417 * @license
5418 * Copyright 2020 Google LLC
5419 *
5420 * Licensed under the Apache License, Version 2.0 (the "License");
5421 * you may not use this file except in compliance with the License.
5422 * You may obtain a copy of the License at
5423 *
5424 *   http://www.apache.org/licenses/LICENSE-2.0
5425 *
5426 * Unless required by applicable law or agreed to in writing, software
5427 * distributed under the License is distributed on an "AS IS" BASIS,
5428 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5429 * See the License for the specific language governing permissions and
5430 * limitations under the License.
5431 */
5432const ct = "__type__", lt = "__max__", ht = {
5433  mapValue: {
5434    fields: {
5435      __type__: {
5436        stringValue: lt
5437      }
5438    }
5439  }
5440}, Pt = "__vector__", Tt = "value", It = {
5441  nullValue: "NULL_VALUE"
5442};
5443function __PRIVATE_typeOrder(e) {
5444  return "nullValue" in e ? 0 : "booleanValue" in e ? 1 : "integerValue" in e || "doubleValue" in e ? 2 : "timestampValue" in e ? 3 : "stringValue" in e ? 5 : "bytesValue" in e ? 6 : "referenceValue" in e ? 7 : "geoPointValue" in e ? 8 : "arrayValue" in e ? 9 : "mapValue" in e ? __PRIVATE_isServerTimestamp(e) ? 4 : __PRIVATE_isMaxValue(e) ? 9007199254740991 : __PRIVATE_isVectorValue(e) ? 10 : 11 : fail(28295, {
5445    value: e
5446  });
5447}
5448function __PRIVATE_valueEquals(e, t) {
5449  if (e === t) return true;
5450  const n = __PRIVATE_typeOrder(e);
5451  if (n !== __PRIVATE_typeOrder(t)) return false;
5452  switch (n) {
5453    case 0:
5454    case 9007199254740991:
5455      return true;
5456    case 1:
5457      return e.booleanValue === t.booleanValue;
5458    case 4:
5459      return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t));
5460    case 3:
5461      return function __PRIVATE_timestampEquals(e2, t2) {
5462        if ("string" == typeof e2.timestampValue && "string" == typeof t2.timestampValue && e2.timestampValue.length === t2.timestampValue.length)
5463          return e2.timestampValue === t2.timestampValue;
5464        const n2 = __PRIVATE_normalizeTimestamp(e2.timestampValue), r = __PRIVATE_normalizeTimestamp(t2.timestampValue);
5465        return n2.seconds === r.seconds && n2.nanos === r.nanos;
5466      }(e, t);
5467    case 5:
5468      return e.stringValue === t.stringValue;
5469    case 6:
5470      return function __PRIVATE_blobEquals(e2, t2) {
5471        return __PRIVATE_normalizeByteString(e2.bytesValue).isEqual(__PRIVATE_normalizeByteString(t2.bytesValue));
5472      }(e, t);
5473    case 7:
5474      return e.referenceValue === t.referenceValue;
5475    case 8:
5476      return function __PRIVATE_geoPointEquals(e2, t2) {
5477        return __PRIVATE_normalizeNumber(e2.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t2.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e2.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t2.geoPointValue.longitude);
5478      }(e, t);
5479    case 2:
5480      return function __PRIVATE_numberEquals(e2, t2) {
5481        if ("integerValue" in e2 && "integerValue" in t2) return __PRIVATE_normalizeNumber(e2.integerValue) === __PRIVATE_normalizeNumber(t2.integerValue);
5482        if ("doubleValue" in e2 && "doubleValue" in t2) {
5483          const n2 = __PRIVATE_normalizeNumber(e2.doubleValue), r = __PRIVATE_normalizeNumber(t2.doubleValue);
5484          return n2 === r ? __PRIVATE_isNegativeZero(n2) === __PRIVATE_isNegativeZero(r) : isNaN(n2) && isNaN(r);
5485        }
5486        return false;
5487      }(e, t);
5488    case 9:
5489      return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], __PRIVATE_valueEquals);
5490    case 10:
5491    case 11:
5492      return function __PRIVATE_objectEquals(e2, t2) {
5493        const n2 = e2.mapValue.fields || {}, r = t2.mapValue.fields || {};
5494        if (__PRIVATE_objectSize(n2) !== __PRIVATE_objectSize(r)) return false;
5495        for (const e3 in n2) if (n2.hasOwnProperty(e3) && (void 0 === r[e3] || !__PRIVATE_valueEquals(n2[e3], r[e3]))) return false;
5496        return true;
5497      }(e, t);
5498    default:
5499      return fail(52216, {
5500        left: e
5501      });
5502  }
5503}
5504function __PRIVATE_arrayValueContains(e, t) {
5505  return void 0 !== (e.values || []).find((e2) => __PRIVATE_valueEquals(e2, t));
5506}
5507function __PRIVATE_valueCompare(e, t) {
5508  if (e === t) return 0;
5509  const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t);
5510  if (n !== r) return __PRIVATE_primitiveComparator(n, r);
5511  switch (n) {
5512    case 0:
5513    case 9007199254740991:
5514      return 0;
5515    case 1:
5516      return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue);
5517    case 2:
5518      return function __PRIVATE_compareNumbers(e2, t2) {
5519        const n2 = __PRIVATE_normalizeNumber(e2.integerValue || e2.doubleValue), r2 = __PRIVATE_normalizeNumber(t2.integerValue || t2.doubleValue);
5520        return n2 < r2 ? -1 : n2 > r2 ? 1 : n2 === r2 ? 0 : (
5521          // one or both are NaN.
5522          isNaN(n2) ? isNaN(r2) ? 0 : -1 : 1
5523        );
5524      }(e, t);
5525    case 3:
5526      return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue);
5527    case 4:
5528      return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t));
5529    case 5:
5530      return __PRIVATE_compareUtf8Strings(e.stringValue, t.stringValue);
5531    case 6:
5532      return function __PRIVATE_compareBlobs(e2, t2) {
5533        const n2 = __PRIVATE_normalizeByteString(e2), r2 = __PRIVATE_normalizeByteString(t2);
5534        return n2.compareTo(r2);
5535      }(e.bytesValue, t.bytesValue);
5536    case 7:
5537      return function __PRIVATE_compareReferences(e2, t2) {
5538        const n2 = e2.split("/"), r2 = t2.split("/");
5539        for (let e3 = 0; e3 < n2.length && e3 < r2.length; e3++) {
5540          const t3 = __PRIVATE_primitiveComparator(n2[e3], r2[e3]);
5541          if (0 !== t3) return t3;
5542        }
5543        return __PRIVATE_primitiveComparator(n2.length, r2.length);
5544      }(e.referenceValue, t.referenceValue);
5545    case 8:
5546      return function __PRIVATE_compareGeoPoints(e2, t2) {
5547        const n2 = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e2.latitude), __PRIVATE_normalizeNumber(t2.latitude));
5548        if (0 !== n2) return n2;
5549        return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e2.longitude), __PRIVATE_normalizeNumber(t2.longitude));
5550      }(e.geoPointValue, t.geoPointValue);
5551    case 9:
5552      return __PRIVATE_compareArrays(e.arrayValue, t.arrayValue);
5553    case 10:
5554      return function __PRIVATE_compareVectors(e2, t2) {
5555        var n2, r2, i, s;
5556        const o = e2.fields || {}, _ = t2.fields || {}, a = null === (n2 = o[Tt]) || void 0 === n2 ? void 0 : n2.arrayValue, u = null === (r2 = _[Tt]) || void 0 === r2 ? void 0 : r2.arrayValue, c = __PRIVATE_primitiveComparator((null === (i = null == a ? void 0 : a.values) || void 0 === i ? void 0 : i.length) || 0, (null === (s = null == u ? void 0 : u.values) || void 0 === s ? void 0 : s.length) || 0);
5557        if (0 !== c) return c;
5558        return __PRIVATE_compareArrays(a, u);
5559      }(e.mapValue, t.mapValue);
5560    case 11:
5561      return function __PRIVATE_compareMaps(e2, t2) {
5562        if (e2 === ht.mapValue && t2 === ht.mapValue) return 0;
5563        if (e2 === ht.mapValue) return 1;
5564        if (t2 === ht.mapValue) return -1;
5565        const n2 = e2.fields || {}, r2 = Object.keys(n2), i = t2.fields || {}, s = Object.keys(i);
5566        r2.sort(), s.sort();
5567        for (let e3 = 0; e3 < r2.length && e3 < s.length; ++e3) {
5568          const t3 = __PRIVATE_compareUtf8Strings(r2[e3], s[e3]);
5569          if (0 !== t3) return t3;
5570          const o = __PRIVATE_valueCompare(n2[r2[e3]], i[s[e3]]);
5571          if (0 !== o) return o;
5572        }
5573        return __PRIVATE_primitiveComparator(r2.length, s.length);
5574      }(e.mapValue, t.mapValue);
5575    default:
5576      throw fail(23264, {
5577        le: n
5578      });
5579  }
5580}
5581function __PRIVATE_compareTimestamps(e, t) {
5582  if ("string" == typeof e && "string" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t);
5583  const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds);
5584  return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos);
5585}
5586function __PRIVATE_compareArrays(e, t) {
5587  const n = e.values || [], r = t.values || [];
5588  for (let e2 = 0; e2 < n.length && e2 < r.length; ++e2) {
5589    const t2 = __PRIVATE_valueCompare(n[e2], r[e2]);
5590    if (t2) return t2;
5591  }
5592  return __PRIVATE_primitiveComparator(n.length, r.length);
5593}
5594function canonicalId(e) {
5595  return __PRIVATE_canonifyValue(e);
5596}
5597function __PRIVATE_canonifyValue(e) {
5598  return "nullValue" in e ? "null" : "booleanValue" in e ? "" + e.booleanValue : "integerValue" in e ? "" + e.integerValue : "doubleValue" in e ? "" + e.doubleValue : "timestampValue" in e ? function __PRIVATE_canonifyTimestamp(e2) {
5599    const t = __PRIVATE_normalizeTimestamp(e2);
5600    return `time(${t.seconds},${t.nanos})`;
5601  }(e.timestampValue) : "stringValue" in e ? e.stringValue : "bytesValue" in e ? function __PRIVATE_canonifyByteString(e2) {
5602    return __PRIVATE_normalizeByteString(e2).toBase64();
5603  }(e.bytesValue) : "referenceValue" in e ? function __PRIVATE_canonifyReference(e2) {
5604    return DocumentKey.fromName(e2).toString();
5605  }(e.referenceValue) : "geoPointValue" in e ? function __PRIVATE_canonifyGeoPoint(e2) {
5606    return `geo(${e2.latitude},${e2.longitude})`;
5607  }(e.geoPointValue) : "arrayValue" in e ? function __PRIVATE_canonifyArray(e2) {
5608    let t = "[", n = true;
5609    for (const r of e2.values || []) n ? n = false : t += ",", t += __PRIVATE_canonifyValue(r);
5610    return t + "]";
5611  }(e.arrayValue) : "mapValue" in e ? function __PRIVATE_canonifyMap(e2) {
5612    const t = Object.keys(e2.fields || {}).sort();
5613    let n = "{", r = true;
5614    for (const i of t) r ? r = false : n += ",", n += `${i}:${__PRIVATE_canonifyValue(e2.fields[i])}`;
5615    return n + "}";
5616  }(e.mapValue) : fail(61005, {
5617    value: e
5618  });
5619}
5620function __PRIVATE_estimateByteSize(e) {
5621  switch (__PRIVATE_typeOrder(e)) {
5622    case 0:
5623    case 1:
5624      return 4;
5625    case 2:
5626      return 8;
5627    case 3:
5628    case 8:
5629      return 16;
5630    case 4:
5631      const t = __PRIVATE_getPreviousValue(e);
5632      return t ? 16 + __PRIVATE_estimateByteSize(t) : 16;
5633    case 5:
5634      return 2 * e.stringValue.length;
5635    case 6:
5636      return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize();
5637    case 7:
5638      return e.referenceValue.length;
5639    case 9:
5640      return function __PRIVATE_estimateArrayByteSize(e2) {
5641        return (e2.values || []).reduce((e3, t2) => e3 + __PRIVATE_estimateByteSize(t2), 0);
5642      }(e.arrayValue);
5643    case 10:
5644    case 11:
5645      return function __PRIVATE_estimateMapByteSize(e2) {
5646        let t2 = 0;
5647        return forEach(e2.fields, (e3, n) => {
5648          t2 += e3.length + __PRIVATE_estimateByteSize(n);
5649        }), t2;
5650      }(e.mapValue);
5651    default:
5652      throw fail(13486, {
5653        value: e
5654      });
5655  }
5656}
5657function __PRIVATE_refValue(e, t) {
5658  return {
5659    referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`
5660  };
5661}
5662function isInteger(e) {
5663  return !!e && "integerValue" in e;
5664}
5665function isArray(e) {
5666  return !!e && "arrayValue" in e;
5667}
5668function __PRIVATE_isNullValue(e) {
5669  return !!e && "nullValue" in e;
5670}
5671function __PRIVATE_isNanValue(e) {
5672  return !!e && "doubleValue" in e && isNaN(Number(e.doubleValue));
5673}
5674function __PRIVATE_isMapValue(e) {
5675  return !!e && "mapValue" in e;
5676}
5677function __PRIVATE_isVectorValue(e) {
5678  var t, n;
5679  return (null === (n = ((null === (t = null == e ? void 0 : e.mapValue) || void 0 === t ? void 0 : t.fields) || {})[ct]) || void 0 === n ? void 0 : n.stringValue) === Pt;
5680}
5681function __PRIVATE_deepClone(e) {
5682  if (e.geoPointValue) return {
5683    geoPointValue: Object.assign({}, e.geoPointValue)
5684  };
5685  if (e.timestampValue && "object" == typeof e.timestampValue) return {
5686    timestampValue: Object.assign({}, e.timestampValue)
5687  };
5688  if (e.mapValue) {
5689    const t = {
5690      mapValue: {
5691        fields: {}
5692      }
5693    };
5694    return forEach(e.mapValue.fields, (e2, n) => t.mapValue.fields[e2] = __PRIVATE_deepClone(n)), t;
5695  }
5696  if (e.arrayValue) {
5697    const t = {
5698      arrayValue: {
5699        values: []
5700      }
5701    };
5702    for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]);
5703    return t;
5704  }
5705  return Object.assign({}, e);
5706}
5707function __PRIVATE_isMaxValue(e) {
5708  return (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue === lt;
5709}
5710const dt = {
5711  mapValue: {
5712    fields: {
5713      [ct]: {
5714        stringValue: Pt
5715      },
5716      [Tt]: {
5717        arrayValue: {}
5718      }
5719    }
5720  }
5721};
5722function __PRIVATE_valuesGetLowerBound(e) {
5723  return "nullValue" in e ? It : "booleanValue" in e ? {
5724    booleanValue: false
5725  } : "integerValue" in e || "doubleValue" in e ? {
5726    doubleValue: NaN
5727  } : "timestampValue" in e ? {
5728    timestampValue: {
5729      seconds: Number.MIN_SAFE_INTEGER
5730    }
5731  } : "stringValue" in e ? {
5732    stringValue: ""
5733  } : "bytesValue" in e ? {
5734    bytesValue: ""
5735  } : "referenceValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "geoPointValue" in e ? {
5736    geoPointValue: {
5737      latitude: -90,
5738      longitude: -180
5739    }
5740  } : "arrayValue" in e ? {
5741    arrayValue: {}
5742  } : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? dt : {
5743    mapValue: {}
5744  } : fail(35942, {
5745    value: e
5746  });
5747}
5748function __PRIVATE_valuesGetUpperBound(e) {
5749  return "nullValue" in e ? {
5750    booleanValue: false
5751  } : "booleanValue" in e ? {
5752    doubleValue: NaN
5753  } : "integerValue" in e || "doubleValue" in e ? {
5754    timestampValue: {
5755      seconds: Number.MIN_SAFE_INTEGER
5756    }
5757  } : "timestampValue" in e ? {
5758    stringValue: ""
5759  } : "stringValue" in e ? {
5760    bytesValue: ""
5761  } : "bytesValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "referenceValue" in e ? {
5762    geoPointValue: {
5763      latitude: -90,
5764      longitude: -180
5765    }
5766  } : "geoPointValue" in e ? {
5767    arrayValue: {}
5768  } : "arrayValue" in e ? dt : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? {
5769    mapValue: {}
5770  } : ht : fail(61959, {
5771    value: e
5772  });
5773}
5774function __PRIVATE_lowerBoundCompare(e, t) {
5775  const n = __PRIVATE_valueCompare(e.value, t.value);
5776  return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0;
5777}
5778function __PRIVATE_upperBoundCompare(e, t) {
5779  const n = __PRIVATE_valueCompare(e.value, t.value);
5780  return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0;
5781}
5782/**
5783 * @license
5784 * Copyright 2017 Google LLC
5785 *
5786 * Licensed under the Apache License, Version 2.0 (the "License");
5787 * you may not use this file except in compliance with the License.
5788 * You may obtain a copy of the License at
5789 *
5790 *   http://www.apache.org/licenses/LICENSE-2.0
5791 *
5792 * Unless required by applicable law or agreed to in writing, software
5793 * distributed under the License is distributed on an "AS IS" BASIS,
5794 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5795 * See the License for the specific language governing permissions and
5796 * limitations under the License.
5797 */
5798class ObjectValue {
5799  constructor(e) {
5800    this.value = e;
5801  }
5802  static empty() {
5803    return new ObjectValue({
5804      mapValue: {}
5805    });
5806  }
5807  /**
5808   * Returns the value at the given path or null.
5809   *
5810   * @param path - the path to search
5811   * @returns The value at the path or null if the path is not set.
5812   */
5813  field(e) {
5814    if (e.isEmpty()) return this.value;
5815    {
5816      let t = this.value;
5817      for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], !__PRIVATE_isMapValue(t)) return null;
5818      return t = (t.mapValue.fields || {})[e.lastSegment()], t || null;
5819    }
5820  }
5821  /**
5822   * Sets the field to the provided value.
5823   *
5824   * @param path - The field path to set.
5825   * @param value - The value to set.
5826   */
5827  set(e, t) {
5828    this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t);
5829  }
5830  /**
5831   * Sets the provided fields to the provided values.
5832   *
5833   * @param data - A map of fields to values (or null for deletes).
5834   */
5835  setAll(e) {
5836    let t = FieldPath$1.emptyPath(), n = {}, r = [];
5837    e.forEach((e2, i2) => {
5838      if (!t.isImmediateParentOf(i2)) {
5839        const e3 = this.getFieldsMap(t);
5840        this.applyChanges(e3, n, r), n = {}, r = [], t = i2.popLast();
5841      }
5842      e2 ? n[i2.lastSegment()] = __PRIVATE_deepClone(e2) : r.push(i2.lastSegment());
5843    });
5844    const i = this.getFieldsMap(t);
5845    this.applyChanges(i, n, r);
5846  }
5847  /**
5848   * Removes the field at the specified path. If there is no field at the
5849   * specified path, nothing is changed.
5850   *
5851   * @param path - The field path to remove.
5852   */
5853  delete(e) {
5854    const t = this.field(e.popLast());
5855    __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()];
5856  }
5857  isEqual(e) {
5858    return __PRIVATE_valueEquals(this.value, e.value);
5859  }
5860  /**
5861   * Returns the map that contains the leaf element of `path`. If the parent
5862   * entry does not yet exist, or if it is not a map, a new map will be created.
5863   */
5864  getFieldsMap(e) {
5865    let t = this.value;
5866    t.mapValue.fields || (t.mapValue = {
5867      fields: {}
5868    });
5869    for (let n = 0; n < e.length; ++n) {
5870      let r = t.mapValue.fields[e.get(n)];
5871      __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = {
5872        mapValue: {
5873          fields: {}
5874        }
5875      }, t.mapValue.fields[e.get(n)] = r), t = r;
5876    }
5877    return t.mapValue.fields;
5878  }
5879  /**
5880   * Modifies `fieldsMap` by adding, replacing or deleting the specified
5881   * entries.
5882   */
5883  applyChanges(e, t, n) {
5884    forEach(t, (t2, n2) => e[t2] = n2);
5885    for (const t2 of n) delete e[t2];
5886  }
5887  clone() {
5888    return new ObjectValue(__PRIVATE_deepClone(this.value));
5889  }
5890}
5891function __PRIVATE_extractFieldMask(e) {
5892  const t = [];
5893  return forEach(e.fields, (e2, n) => {
5894    const r = new FieldPath$1([e2]);
5895    if (__PRIVATE_isMapValue(n)) {
5896      const e3 = __PRIVATE_extractFieldMask(n.mapValue).fields;
5897      if (0 === e3.length)
5898        t.push(r);
5899      else
5900        for (const n2 of e3) t.push(r.child(n2));
5901    } else
5902      t.push(r);
5903  }), new FieldMask(t);
5904}
5905/**
5906 * @license
5907 * Copyright 2017 Google LLC
5908 *
5909 * Licensed under the Apache License, Version 2.0 (the "License");
5910 * you may not use this file except in compliance with the License.
5911 * You may obtain a copy of the License at
5912 *
5913 *   http://www.apache.org/licenses/LICENSE-2.0
5914 *
5915 * Unless required by applicable law or agreed to in writing, software
5916 * distributed under the License is distributed on an "AS IS" BASIS,
5917 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5918 * See the License for the specific language governing permissions and
5919 * limitations under the License.
5920 */
5921class MutableDocument {
5922  constructor(e, t, n, r, i, s, o) {
5923    this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, this.data = s, this.documentState = o;
5924  }
5925  /**
5926   * Creates a document with no known version or data, but which can serve as
5927   * base document for mutations.
5928   */
5929  static newInvalidDocument(e) {
5930    return new MutableDocument(
5931      e,
5932      0,
5933      /* version */
5934      SnapshotVersion.min(),
5935      /* readTime */
5936      SnapshotVersion.min(),
5937      /* createTime */
5938      SnapshotVersion.min(),
5939      ObjectValue.empty(),
5940      0
5941      /* DocumentState.SYNCED */
5942    );
5943  }
5944  /**
5945   * Creates a new document that is known to exist with the given data at the
5946   * given version.
5947   */
5948  static newFoundDocument(e, t, n, r) {
5949    return new MutableDocument(
5950      e,
5951      1,
5952      /* version */
5953      t,
5954      /* readTime */
5955      SnapshotVersion.min(),
5956      /* createTime */
5957      n,
5958      r,
5959      0
5960      /* DocumentState.SYNCED */
5961    );
5962  }
5963  /** Creates a new document that is known to not exist at the given version. */
5964  static newNoDocument(e, t) {
5965    return new MutableDocument(
5966      e,
5967      2,
5968      /* version */
5969      t,
5970      /* readTime */
5971      SnapshotVersion.min(),
5972      /* createTime */
5973      SnapshotVersion.min(),
5974      ObjectValue.empty(),
5975      0
5976      /* DocumentState.SYNCED */
5977    );
5978  }
5979  /**
5980   * Creates a new document that is known to exist at the given version but
5981   * whose data is not known (e.g. a document that was updated without a known
5982   * base document).
5983   */
5984  static newUnknownDocument(e, t) {
5985    return new MutableDocument(
5986      e,
5987      3,
5988      /* version */
5989      t,
5990      /* readTime */
5991      SnapshotVersion.min(),
5992      /* createTime */
5993      SnapshotVersion.min(),
5994      ObjectValue.empty(),
5995      2
5996      /* DocumentState.HAS_COMMITTED_MUTATIONS */
5997    );
5998  }
5999  /**
6000   * Changes the document type to indicate that it exists and that its version
6001   * and data are known.
6002   */
6003  convertToFoundDocument(e, t) {
6004    return !this.createTime.isEqual(SnapshotVersion.min()) || 2 !== this.documentType && 0 !== this.documentType || (this.createTime = e), this.version = e, this.documentType = 1, this.data = t, this.documentState = 0, this;
6005  }
6006  /**
6007   * Changes the document type to indicate that it doesn't exist at the given
6008   * version.
6009   */
6010  convertToNoDocument(e) {
6011    return this.version = e, this.documentType = 2, this.data = ObjectValue.empty(), this.documentState = 0, this;
6012  }
6013  /**
6014   * Changes the document type to indicate that it exists at a given version but
6015   * that its data is not known (e.g. a document that was updated without a known
6016   * base document).
6017   */
6018  convertToUnknownDocument(e) {
6019    return this.version = e, this.documentType = 3, this.data = ObjectValue.empty(), this.documentState = 2, this;
6020  }
6021  setHasCommittedMutations() {
6022    return this.documentState = 2, this;
6023  }
6024  setHasLocalMutations() {
6025    return this.documentState = 1, this.version = SnapshotVersion.min(), this;
6026  }
6027  setReadTime(e) {
6028    return this.readTime = e, this;
6029  }
6030  get hasLocalMutations() {
6031    return 1 === this.documentState;
6032  }
6033  get hasCommittedMutations() {
6034    return 2 === this.documentState;
6035  }
6036  get hasPendingWrites() {
6037    return this.hasLocalMutations || this.hasCommittedMutations;
6038  }
6039  isValidDocument() {
6040    return 0 !== this.documentType;
6041  }
6042  isFoundDocument() {
6043    return 1 === this.documentType;
6044  }
6045  isNoDocument() {
6046    return 2 === this.documentType;
6047  }
6048  isUnknownDocument() {
6049    return 3 === this.documentType;
6050  }
6051  isEqual(e) {
6052    return e instanceof MutableDocument && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data);
6053  }
6054  mutableCopy() {
6055    return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
6056  }
6057  toString() {
6058    return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
6059  }
6060}
6061/**
6062 * @license
6063 * Copyright 2022 Google LLC
6064 *
6065 * Licensed under the Apache License, Version 2.0 (the "License");
6066 * you may not use this file except in compliance with the License.
6067 * You may obtain a copy of the License at
6068 *
6069 *   http://www.apache.org/licenses/LICENSE-2.0
6070 *
6071 * Unless required by applicable law or agreed to in writing, software
6072 * distributed under the License is distributed on an "AS IS" BASIS,
6073 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6074 * See the License for the specific language governing permissions and
6075 * limitations under the License.
6076 */
6077class Bound {
6078  constructor(e, t) {
6079    this.position = e, this.inclusive = t;
6080  }
6081}
6082function __PRIVATE_boundCompareToDocument(e, t, n) {
6083  let r = 0;
6084  for (let i = 0; i < e.position.length; i++) {
6085    const s = t[i], o = e.position[i];
6086    if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(o.referenceValue), n.key);
6087    else {
6088      r = __PRIVATE_valueCompare(o, n.data.field(s.field));
6089    }
6090    if ("desc" === s.dir && (r *= -1), 0 !== r) break;
6091  }
6092  return r;
6093}
6094function __PRIVATE_boundEquals(e, t) {
6095  if (null === e) return null === t;
6096  if (null === t) return false;
6097  if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return false;
6098  for (let n = 0; n < e.position.length; n++) {
6099    if (!__PRIVATE_valueEquals(e.position[n], t.position[n])) return false;
6100  }
6101  return true;
6102}
6103/**
6104 * @license
6105 * Copyright 2022 Google LLC
6106 *
6107 * Licensed under the Apache License, Version 2.0 (the "License");
6108 * you may not use this file except in compliance with the License.
6109 * You may obtain a copy of the License at
6110 *
6111 *   http://www.apache.org/licenses/LICENSE-2.0
6112 *
6113 * Unless required by applicable law or agreed to in writing, software
6114 * distributed under the License is distributed on an "AS IS" BASIS,
6115 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6116 * See the License for the specific language governing permissions and
6117 * limitations under the License.
6118 */
6119class OrderBy {
6120  constructor(e, t = "asc") {
6121    this.field = e, this.dir = t;
6122  }
6123}
6124function __PRIVATE_orderByEquals(e, t) {
6125  return e.dir === t.dir && e.field.isEqual(t.field);
6126}
6127/**
6128 * @license
6129 * Copyright 2022 Google LLC
6130 *
6131 * Licensed under the Apache License, Version 2.0 (the "License");
6132 * you may not use this file except in compliance with the License.
6133 * You may obtain a copy of the License at
6134 *
6135 *   http://www.apache.org/licenses/LICENSE-2.0
6136 *
6137 * Unless required by applicable law or agreed to in writing, software
6138 * distributed under the License is distributed on an "AS IS" BASIS,
6139 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6140 * See the License for the specific language governing permissions and
6141 * limitations under the License.
6142 */
6143class Filter {
6144}
6145class FieldFilter extends Filter {
6146  constructor(e, t, n) {
6147    super(), this.field = e, this.op = t, this.value = n;
6148  }
6149  /**
6150   * Creates a filter based on the provided arguments.
6151   */
6152  static create(e, t, n) {
6153    return e.isKeyField() ? "in" === t || "not-in" === t ? this.createKeyFieldInFilter(e, t, n) : new __PRIVATE_KeyFieldFilter(e, t, n) : "array-contains" === t ? new __PRIVATE_ArrayContainsFilter(e, n) : "in" === t ? new __PRIVATE_InFilter(e, n) : "not-in" === t ? new __PRIVATE_NotInFilter(e, n) : "array-contains-any" === t ? new __PRIVATE_ArrayContainsAnyFilter(e, n) : new FieldFilter(e, t, n);
6154  }
6155  static createKeyFieldInFilter(e, t, n) {
6156    return "in" === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n);
6157  }
6158  matches(e) {
6159    const t = e.data.field(this.field);
6160    return "!=" === this.op ? null !== t && void 0 === t.nullValue && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value));
6161  }
6162  matchesComparison(e) {
6163    switch (this.op) {
6164      case "<":
6165        return e < 0;
6166      case "<=":
6167        return e <= 0;
6168      case "==":
6169        return 0 === e;
6170      case "!=":
6171        return 0 !== e;
6172      case ">":
6173        return e > 0;
6174      case ">=":
6175        return e >= 0;
6176      default:
6177        return fail(47266, {
6178          operator: this.op
6179        });
6180    }
6181  }
6182  isInequality() {
6183    return [
6184      "<",
6185      "<=",
6186      ">",
6187      ">=",
6188      "!=",
6189      "not-in"
6190      /* Operator.NOT_IN */
6191    ].indexOf(this.op) >= 0;
6192  }
6193  getFlattenedFilters() {
6194    return [this];
6195  }
6196  getFilters() {
6197    return [this];
6198  }
6199}
6200class CompositeFilter extends Filter {
6201  constructor(e, t) {
6202    super(), this.filters = e, this.op = t, this.he = null;
6203  }
6204  /**
6205   * Creates a filter based on the provided arguments.
6206   */
6207  static create(e, t) {
6208    return new CompositeFilter(e, t);
6209  }
6210  matches(e) {
6211    return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t) => !t.matches(e)) : void 0 !== this.filters.find((t) => t.matches(e));
6212  }
6213  getFlattenedFilters() {
6214    return null !== this.he || (this.he = this.filters.reduce((e, t) => e.concat(t.getFlattenedFilters()), [])), this.he;
6215  }
6216  // Returns a mutable copy of `this.filters`
6217  getFilters() {
6218    return Object.assign([], this.filters);
6219  }
6220}
6221function __PRIVATE_compositeFilterIsConjunction(e) {
6222  return "and" === e.op;
6223}
6224function __PRIVATE_compositeFilterIsDisjunction(e) {
6225  return "or" === e.op;
6226}
6227function __PRIVATE_compositeFilterIsFlatConjunction(e) {
6228  return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e);
6229}
6230function __PRIVATE_compositeFilterIsFlat(e) {
6231  for (const t of e.filters) if (t instanceof CompositeFilter) return false;
6232  return true;
6233}
6234function __PRIVATE_canonifyFilter(e) {
6235  if (e instanceof FieldFilter)
6236    return e.field.canonicalString() + e.op.toString() + canonicalId(e.value);
6237  if (__PRIVATE_compositeFilterIsFlatConjunction(e))
6238    return e.filters.map((e2) => __PRIVATE_canonifyFilter(e2)).join(",");
6239  {
6240    const t = e.filters.map((e2) => __PRIVATE_canonifyFilter(e2)).join(",");
6241    return `${e.op}(${t})`;
6242  }
6243}
6244function __PRIVATE_filterEquals(e, t) {
6245  return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e2, t2) {
6246    return t2 instanceof FieldFilter && e2.op === t2.op && e2.field.isEqual(t2.field) && __PRIVATE_valueEquals(e2.value, t2.value);
6247  }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e2, t2) {
6248    if (t2 instanceof CompositeFilter && e2.op === t2.op && e2.filters.length === t2.filters.length) {
6249      return e2.filters.reduce((e3, n, r) => e3 && __PRIVATE_filterEquals(n, t2.filters[r]), true);
6250    }
6251    return false;
6252  }(e, t) : void fail(19439);
6253}
6254function __PRIVATE_compositeFilterWithAddedFilters(e, t) {
6255  const n = e.filters.concat(t);
6256  return CompositeFilter.create(n, e.op);
6257}
6258function __PRIVATE_stringifyFilter(e) {
6259  return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e2) {
6260    return `${e2.field.canonicalString()} ${e2.op} ${canonicalId(e2.value)}`;
6261  }(e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e2) {
6262    return e2.op.toString() + " {" + e2.getFilters().map(__PRIVATE_stringifyFilter).join(" ,") + "}";
6263  }(e) : "Filter";
6264}
6265class __PRIVATE_KeyFieldFilter extends FieldFilter {
6266  constructor(e, t, n) {
6267    super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue);
6268  }
6269  matches(e) {
6270    const t = DocumentKey.comparator(e.key, this.key);
6271    return this.matchesComparison(t);
6272  }
6273}
6274class __PRIVATE_KeyFieldInFilter extends FieldFilter {
6275  constructor(e, t) {
6276    super(e, "in", t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in", t);
6277  }
6278  matches(e) {
6279    return this.keys.some((t) => t.isEqual(e.key));
6280  }
6281}
6282class __PRIVATE_KeyFieldNotInFilter extends FieldFilter {
6283  constructor(e, t) {
6284    super(e, "not-in", t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in", t);
6285  }
6286  matches(e) {
6287    return !this.keys.some((t) => t.isEqual(e.key));
6288  }
6289}
6290function __PRIVATE_extractDocumentKeysFromArrayValue(e, t) {
6291  var n;
6292  return ((null === (n = t.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((e2) => DocumentKey.fromName(e2.referenceValue));
6293}
6294class __PRIVATE_ArrayContainsFilter extends FieldFilter {
6295  constructor(e, t) {
6296    super(e, "array-contains", t);
6297  }
6298  matches(e) {
6299    const t = e.data.field(this.field);
6300    return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value);
6301  }
6302}
6303class __PRIVATE_InFilter extends FieldFilter {
6304  constructor(e, t) {
6305    super(e, "in", t);
6306  }
6307  matches(e) {
6308    const t = e.data.field(this.field);
6309    return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t);
6310  }
6311}
6312class __PRIVATE_NotInFilter extends FieldFilter {
6313  constructor(e, t) {
6314    super(e, "not-in", t);
6315  }
6316  matches(e) {
6317    if (__PRIVATE_arrayValueContains(this.value.arrayValue, {
6318      nullValue: "NULL_VALUE"
6319    })) return false;
6320    const t = e.data.field(this.field);
6321    return null !== t && void 0 === t.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, t);
6322  }
6323}
6324class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter {
6325  constructor(e, t) {
6326    super(e, "array-contains-any", t);
6327  }
6328  matches(e) {
6329    const t = e.data.field(this.field);
6330    return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e2) => __PRIVATE_arrayValueContains(this.value.arrayValue, e2));
6331  }
6332}
6333/**
6334 * @license
6335 * Copyright 2019 Google LLC
6336 *
6337 * Licensed under the Apache License, Version 2.0 (the "License");
6338 * you may not use this file except in compliance with the License.
6339 * You may obtain a copy of the License at
6340 *
6341 *   http://www.apache.org/licenses/LICENSE-2.0
6342 *
6343 * Unless required by applicable law or agreed to in writing, software
6344 * distributed under the License is distributed on an "AS IS" BASIS,
6345 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6346 * See the License for the specific language governing permissions and
6347 * limitations under the License.
6348 */
6349class __PRIVATE_TargetImpl {
vendor: 4,314 bytes, lines 6350-6479
6350  constructor(e, t = null, n = [], r = [], i = null, s = null, o = null) {
6351    this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, this.startAt = s, this.endAt = o, this.Pe = null;
6352  }
6353}
6354function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, o = null) {
6355  return new __PRIVATE_TargetImpl(e, t, n, r, i, s, o);
6356}
6357function __PRIVATE_canonifyTarget(e) {
6358  const t = __PRIVATE_debugCast(e);
6359  if (null === t.Pe) {
6360    let e2 = t.path.canonicalString();
6361    null !== t.collectionGroup && (e2 += "|cg:" + t.collectionGroup), e2 += "|f:", e2 += t.filters.map((e3) => __PRIVATE_canonifyFilter(e3)).join(","), e2 += "|ob:", e2 += t.orderBy.map((e3) => function __PRIVATE_canonifyOrderBy(e4) {
6362      return e4.field.canonicalString() + e4.dir;
6363    }(e3)).join(","), __PRIVATE_isNullOrUndefined(t.limit) || (e2 += "|l:", e2 += t.limit), t.startAt && (e2 += "|lb:", e2 += t.startAt.inclusive ? "b:" : "a:", e2 += t.startAt.position.map((e3) => canonicalId(e3)).join(",")), t.endAt && (e2 += "|ub:", e2 += t.endAt.inclusive ? "a:" : "b:", e2 += t.endAt.position.map((e3) => canonicalId(e3)).join(",")), t.Pe = e2;
6364  }
6365  return t.Pe;
6366}
6367function __PRIVATE_targetEquals(e, t) {
6368  if (e.limit !== t.limit) return false;
6369  if (e.orderBy.length !== t.orderBy.length) return false;
6370  for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return false;
6371  if (e.filters.length !== t.filters.length) return false;
6372  for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return false;
6373  return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt)));
6374}
6375function __PRIVATE_targetIsDocumentTarget(e) {
6376  return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;
6377}
6378function __PRIVATE_targetGetFieldFiltersForPath(e, t) {
6379  return e.filters.filter((e2) => e2 instanceof FieldFilter && e2.field.isEqual(t));
6380}
6381function __PRIVATE_targetGetAscendingBound(e, t, n) {
6382  let r = It, i = true;
6383  for (const n2 of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {
6384    let e2 = It, t2 = true;
6385    switch (n2.op) {
6386      case "<":
6387      case "<=":
6388        e2 = __PRIVATE_valuesGetLowerBound(n2.value);
6389        break;
6390      case "==":
6391      case "in":
6392      case ">=":
6393        e2 = n2.value;
6394        break;
6395      case ">":
6396        e2 = n2.value, t2 = false;
6397        break;
6398      case "!=":
6399      case "not-in":
6400        e2 = It;
6401    }
6402    __PRIVATE_lowerBoundCompare({
6403      value: r,
6404      inclusive: i
6405    }, {
6406      value: e2,
6407      inclusive: t2
6408    }) < 0 && (r = e2, i = t2);
6409  }
6410  if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {
6411    if (e.orderBy[s].field.isEqual(t)) {
6412      const e2 = n.position[s];
6413      __PRIVATE_lowerBoundCompare({
6414        value: r,
6415        inclusive: i
6416      }, {
6417        value: e2,
6418        inclusive: n.inclusive
6419      }) < 0 && (r = e2, i = n.inclusive);
6420      break;
6421    }
6422  }
6423  return {
6424    value: r,
6425    inclusive: i
6426  };
6427}
6428function __PRIVATE_targetGetDescendingBound(e, t, n) {
6429  let r = ht, i = true;
6430  for (const n2 of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {
6431    let e2 = ht, t2 = true;
6432    switch (n2.op) {
6433      case ">=":
6434      case ">":
6435        e2 = __PRIVATE_valuesGetUpperBound(n2.value), t2 = false;
6436        break;
6437      case "==":
6438      case "in":
6439      case "<=":
6440        e2 = n2.value;
6441        break;
6442      case "<":
6443        e2 = n2.value, t2 = false;
6444        break;
6445      case "!=":
6446      case "not-in":
6447        e2 = ht;
6448    }
6449    __PRIVATE_upperBoundCompare({
6450      value: r,
6451      inclusive: i
6452    }, {
6453      value: e2,
6454      inclusive: t2
6455    }) > 0 && (r = e2, i = t2);
6456  }
6457  if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {
6458    if (e.orderBy[s].field.isEqual(t)) {
6459      const e2 = n.position[s];
6460      __PRIVATE_upperBoundCompare({
6461        value: r,
6462        inclusive: i
6463      }, {
6464        value: e2,
6465        inclusive: n.inclusive
6466      }) > 0 && (r = e2, i = n.inclusive);
6467      break;
6468    }
6469  }
6470  return {
6471    value: r,
6472    inclusive: i
6473  };
6474}
6475/**
6476 * @license
6477 * Copyright 2017 Google LLC
6478 *
6479 * Licensed under the Apache License, Version 2.0 (the "License");
6480 * you may not use this file except in compliance with the License.
6481 * You may obtain a copy of the License at
6482 *
6483 *   http://www.apache.org/licenses/LICENSE-2.0
6484 *
6485 * Unless required by applicable law or agreed to in writing, software
6486 * distributed under the License is distributed on an "AS IS" BASIS,
6487 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6488 * See the License for the specific language governing permissions and
6489 * limitations under the License.
6490 */
6491class __PRIVATE_QueryImpl {
6492  /**
6493   * Initializes a Query with a path and optional additional query constraints.
6494   * Path must currently be empty if this is a collection group query.
6495   */
6496  constructor(e, t = null, n = [], r = [], i = null, s = "F", o = null, _ = null) {
6497    this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, this.limit = i, this.limitType = s, this.startAt = o, this.endAt = _, this.Te = null, // The corresponding `Target` of this `Query` instance, for use with
6498    // non-aggregate queries.
6499    this.Ie = null, // The corresponding `Target` of this `Query` instance, for use with
6500    // aggregate queries. Unlike targets for non-aggregate queries,
6501    // aggregate query targets do not contain normalized order-bys, they only
6502    // contain explicit order-bys.
6503    this.de = null, this.startAt, this.endAt;
6504  }
6505}
6506function __PRIVATE_newQuery(e, t, n, r, i, s, o, _) {
6507  return new __PRIVATE_QueryImpl(e, t, n, r, i, s, o, _);
6508}
6509function __PRIVATE_newQueryForPath(e) {
6510  return new __PRIVATE_QueryImpl(e);
6511}
6512function __PRIVATE_queryMatchesAllDocuments(e) {
6513  return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField());
6514}
6515function __PRIVATE_isCollectionGroupQuery(e) {
6516  return null !== e.collectionGroup;
6517}
6518function __PRIVATE_queryNormalizedOrderBy(e) {
6519  const t = __PRIVATE_debugCast(e);
6520  if (null === t.Te) {
6521    t.Te = [];
6522    const e2 = /* @__PURE__ */ new Set();
6523    for (const n2 of t.explicitOrderBy) t.Te.push(n2), e2.add(n2.field.canonicalString());
6524    const n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : "asc", r = function __PRIVATE_getInequalityFilterFields(e3) {
6525      let t2 = new SortedSet(FieldPath$1.comparator);
6526      return e3.filters.forEach((e4) => {
6527        e4.getFlattenedFilters().forEach((e5) => {
6528          e5.isInequality() && (t2 = t2.add(e5.field));
6529        });
6530      }), t2;
6531    }(t);
6532    r.forEach((r2) => {
6533      e2.has(r2.canonicalString()) || r2.isKeyField() || t.Te.push(new OrderBy(r2, n));
6534    }), // Add the document key field to the last if it is not explicitly ordered.
6535    e2.has(FieldPath$1.keyField().canonicalString()) || t.Te.push(new OrderBy(FieldPath$1.keyField(), n));
6536  }
6537  return t.Te;
6538}
6539function __PRIVATE_queryToTarget(e) {
6540  const t = __PRIVATE_debugCast(e);
6541  return t.Ie || (t.Ie = __PRIVATE__queryToTarget(t, __PRIVATE_queryNormalizedOrderBy(e))), t.Ie;
6542}
6543function __PRIVATE_queryToAggregateTarget(e) {
6544  const t = __PRIVATE_debugCast(e);
6545  return t.de || // Do not include implicit order-bys for aggregate queries.
6546  (t.de = __PRIVATE__queryToTarget(t, e.explicitOrderBy)), t.de;
6547}
6548function __PRIVATE__queryToTarget(e, t) {
6549  if ("F" === e.limitType) return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, e.startAt, e.endAt);
6550  {
6551    t = t.map((e2) => {
6552      const t2 = "desc" === e2.dir ? "asc" : "desc";
6553      return new OrderBy(e2.field, t2);
6554    });
6555    const n = e.endAt ? new Bound(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Bound(e.startAt.position, e.startAt.inclusive) : null;
6556    return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, n, r);
6557  }
6558}
6559function __PRIVATE_queryWithAddedFilter(e, t) {
6560  const n = e.filters.concat([t]);
6561  return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt);
6562}
6563function __PRIVATE_queryWithLimit(e, t, n) {
6564  return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt);
6565}
6566function __PRIVATE_queryEquals(e, t) {
6567  return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType;
6568}
6569function __PRIVATE_canonifyQuery(e) {
6570  return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`;
6571}
6572function __PRIVATE_stringifyQuery(e) {
6573  return `Query(target=${function __PRIVATE_stringifyTarget(e2) {
6574    let t = e2.path.canonicalString();
6575    return null !== e2.collectionGroup && (t += " collectionGroup=" + e2.collectionGroup), e2.filters.length > 0 && (t += `, filters: [${e2.filters.map((e3) => __PRIVATE_stringifyFilter(e3)).join(", ")}]`), __PRIVATE_isNullOrUndefined(e2.limit) || (t += ", limit: " + e2.limit), e2.orderBy.length > 0 && (t += `, orderBy: [${e2.orderBy.map((e3) => function __PRIVATE_stringifyOrderBy(e4) {
6576      return `${e4.field.canonicalString()} (${e4.dir})`;
6577    }(e3)).join(", ")}]`), e2.startAt && (t += ", startAt: ", t += e2.startAt.inclusive ? "b:" : "a:", t += e2.startAt.position.map((e3) =>
6577 canonicalId(e3)).join(",")), e2.endAt && (t += ", endAt: ", t += e2.endAt.inclusive ? "a:" : "b:", t += e2.endAt.position.map((e3) => canonicalId(e3)).join(",")), `Target(${t})`;
6578  }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`;
6579}
6580function __PRIVATE_queryMatches(e, t) {
6581  return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e2, t2) {
6582    const n = t2.key.path;
6583    return null !== e2.collectionGroup ? t2.key.hasCollectionId(e2.collectionGroup) && e2.path.isPrefixOf(n) : DocumentKey.isDocumentKey(e2.path) ? e2.path.isEqual(n) : e2.path.isImmediateParentOf(n);
6584  }(e, t) && function __PRIVATE_queryMatchesOrderBy(e2, t2) {
6585    for (const n of __PRIVATE_queryNormalizedOrderBy(e2))
6586      if (!n.field.isKeyField() && null === t2.data.field(n.field)) return false;
6587    return true;
6588  }(e, t) && function __PRIVATE_queryMatchesFilters(e2, t2) {
6589    for (const n of e2.filters) if (!n.matches(t2)) return false;
6590    return true;
6591  }(e, t) && function __PRIVATE_queryMatchesBounds(e2, t2) {
6592    if (e2.startAt && !/**
6593    * Returns true if a document sorts before a bound using the provided sort
6594    * order.
6595    */
6596    function __PRIVATE_boundSortsBeforeDocument(e3, t3, n) {
6597      const r = __PRIVATE_boundCompareToDocument(e3, t3, n);
6598      return e3.inclusive ? r <= 0 : r < 0;
6599    }(e2.startAt, __PRIVATE_queryNormalizedOrderBy(e2), t2)) return false;
6600    if (e2.endAt && !function __PRIVATE_boundSortsAfterDocument(e3, t3, n) {
6601      const r = __PRIVATE_boundCompareToDocument(e3, t3, n);
6602      return e3.inclusive ? r >= 0 : r > 0;
6603    }(e2.endAt, __PRIVATE_queryNormalizedOrderBy(e2), t2)) return false;
6604    return true;
6605  }(e, t);
6606}
6607function __PRIVATE_queryCollectionGroup(e) {
6608  return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2));
6609}
6610function __PRIVATE_newQueryComparator(e) {
6611  return (t, n) => {
6612    let r = false;
6613    for (const i of __PRIVATE_queryNormalizedOrderBy(e)) {
6614      const e2 = __PRIVATE_compareDocs(i, t, n);
6615      if (0 !== e2) return e2;
6616      r = r || i.field.isKeyField();
6617    }
6618    return 0;
6619  };
6620}
6621function __PRIVATE_compareDocs(e, t, n) {
6622  const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e2, t2, n2) {
6623    const r2 = t2.data.field(e2), i = n2.data.field(e2);
6624    return null !== r2 && null !== i ? __PRIVATE_valueCompare(r2, i) : fail(42886);
6625  }(e.field, t, n);
6626  switch (e.dir) {
6627    case "asc":
6628      return r;
6629    case "desc":
6630      return -1 * r;
6631    default:
6632      return fail(19790, {
6633        direction: e.dir
6634      });
6635  }
6636}
6637/**
6638 * @license
6639 * Copyright 2017 Google LLC
6640 *
6641 * Licensed under the Apache License, Version 2.0 (the "License");
6642 * you may not use this file except in compliance with the License.
6643 * You may obtain a copy of the License at
6644 *
6645 *   http://www.apache.org/licenses/LICENSE-2.0
6646 *
6647 * Unless required by applicable law or agreed to in writing, software
6648 * distributed under the License is distributed on an "AS IS" BASIS,
6649 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6650 * See the License for the specific language governing permissions and
6651 * limitations under the License.
6652 */
6653class ObjectMap {
6654  constructor(e, t) {
6655    this.mapKeyFn = e, this.equalsFn = t, /**
6656    * The inner map for a key/value pair. Due to the possibility of collisions we
6657    * keep a list of entries that we do a linear search through to find an actual
6658    * match. Note that collisions should be rare, so we still expect near
6659    * constant time lookups in practice.
6660    */
6661    this.inner = {}, /** The number of entries stored in the map */
6662    this.innerSize = 0;
6663  }
6664  /** Get a value for this key, or undefined if it does not exist. */
6665  get(e) {
6666    const t = this.mapKeyFn(e), n = this.inner[t];
6667    if (void 0 !== n) {
6668      for (const [t2, r] of n) if (this.equalsFn(t2, e)) return r;
6669    }
6670  }
6671  has(e) {
6672    return void 0 !== this.get(e);
6673  }
6674  /** Put this key and value in the map. */
6675  set(e, t) {
6676    const n = this.mapKeyFn(e), r = this.inner[n];
6677    if (void 0 === r) return this.inner[n] = [[e, t]], void this.innerSize++;
6678    for (let n2 = 0; n2 < r.length; n2++) if (this.equalsFn(r[n2][0], e))
6679      return void (r[n2] = [e, t]);
6680    r.push([e, t]), this.innerSize++;
6681  }
6682  /**
6683   * Remove this key from the map. Returns a boolean if anything was deleted.
6684   */
6685  delete(e) {
6686    const t = this.mapKeyFn(e), n = this.inner[t];
6687    if (void 0 === n) return false;
6688    for (let r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], e)) return 1 === n.length ? delete this.inner[t] : n.splice(r, 1), this.innerSize--, true;
6689    return false;
6690  }
6691  forEach(e) {
6692    forEach(this.inner, (t, n) => {
6693      for (const [t2, r] of n) e(t2, r);
6694    });
6695  }
6696  isEmpty() {
6697    return isEmpty(this.inner);
6698  }
6699  size() {
6700    return this.innerSize;
6701  }
6702}
6703/**
6704 * @license
6705 * Copyright 2017 Google LLC
6706 *
6707 * Licensed under the Apache License, Version 2.0 (the "License");
6708 * you may not use this file except in compliance with the License.
6709 * You may obtain a copy of the License at
6710 *
6711 *   http://www.apache.org/licenses/LICENSE-2.0
6712 *
6713 * Unless required by applicable law or agreed to in writing, software
6714 * distributed under the License is distributed on an "AS IS" BASIS,
6715 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6716 * See the License for the specific language governing permissions and
6717 * limitations under the License.
6718 */
6719const Et = new SortedMap(DocumentKey.comparator);
6720function __PRIVATE_mutableDocumentMap() {
6721  return Et;
6722}
6723const At = new SortedMap(DocumentKey.comparator);
6724function documentMap(...e) {
6725  let t = At;
6726  for (const n of e) t = t.insert(n.key, n);
6727  return t;
6728}
6729function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) {
6730  let t = At;
6731  return e.forEach((e2, n) => t = t.insert(e2, n.overlayedDocument)), t;
6732}
6733function __PRIVATE_newOverlayMap() {
6734  return __PRIVATE_newDocumentKeyMap();
6735}
6736function __PRIVATE_newMutationMap() {
6737  return __PRIVATE_newDocumentKeyMap();
6738}
6739function __PRIVATE_newDocumentKeyMap() {
6740  return new ObjectMap((e) => e.toString(), (e, t) => e.isEqual(t));
6741}
6742const Rt = new SortedMap(DocumentKey.comparator);
6743const Vt = new SortedSet(DocumentKey.comparator);
6744function __PRIVATE_documentKeySet(...e) {
6745  let t = Vt;
6746  for (const n of e) t = t.add(n);
6747  return t;
6748}
6749const mt = new SortedSet(__PRIVATE_primitiveComparator);
6750function __PRIVATE_targetIdSet() {
6751  return mt;
6752}
6753/**
6754 * @license
6755 * Copyright 2020 Google LLC
6756 *
6757 * Licensed under the Apache License, Version 2.0 (the "License");
6758 * you may not use this file except in compliance with the License.
6759 * You may obtain a copy of the License at
6760 *
6761 *   http://www.apache.org/licenses/LICENSE-2.0
6762 *
6763 * Unless required by applicable law or agreed to in writing, software
6764 * distributed under the License is distributed on an "AS IS" BASIS,
6765 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6766 * See the License for the specific language governing permissions and
6767 * limitations under the License.
6768 */
6769function __PRIVATE_toDouble(e, t) {
6770  if (e.useProto3Json) {
6771    if (isNaN(t)) return {
6772      doubleValue: "NaN"
6773    };
6774    if (t === 1 / 0) return {
6775      doubleValue: "Infinity"
6776    };
6777    if (t === -1 / 0) return {
6778      doubleValue: "-Infinity"
6779    };
6780  }
6781  return {
6782    doubleValue: __PRIVATE_isNegativeZero(t) ? "-0" : t
6783  };
6784}
6785function __PRIVATE_toInteger(e) {
6786  return {
6787    integerValue: "" + e
6788  };
6789}
6790function toNumber(e, t) {
6791  return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t);
6792}
6793/**
6794 * @license
6795 * Copyright 2018 Google LLC
6796 *
6797 * Licensed under the Apache License, Version 2.0 (the "License");
6798 * you may not use this file except in compliance with the License.
6799 * You may obtain a copy of the License at
6800 *
6801 *   http://www.apache.org/licenses/LICENSE-2.0
6802 *
6803 * Unless required by applicable law or agreed to in writing, software
6804 * distributed under the License is distributed on an "AS IS" BASIS,
6805 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6806 * See the License for the specific language governing permissions and
6807 * limitations under the License.
6808 */
6809class TransformOperation {
6810  constructor() {
6811    this._ = void 0;
6812  }
6813}
6814function __PRIVATE_applyTransformOperationToLocalView(e, t, n) {
6815  return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e2, t2) {
6816    const n2 = {
6817      fields: {
6818        [ot]: {
6819          stringValue: st
6820        },
6821        [at]: {
6822          timestampValue: {
6823            seconds: e2.seconds,
6824            nanos: e2.nanoseconds
6825          }
6826        }
6827      }
6828    };
6829    return t2 && __PRIVATE_isServerTimestamp(t2) && (t2 = __PRIVATE_getPreviousValue(t2)), t2 && (n2.fields[_t] = t2), {
6830      mapValue: n2
6831    };
6832  }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e2, t2) {
6833    const n2 = __PRIVATE_computeTransformOperationBaseValue(e2, t2), r = asNumber(n2) + asNumber(e2.Ee);
6834    return isInteger(n2) && isInteger(e2.Ee) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e2.serializer, r);
6835  }(e, t);
6836}
6837function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) {
6838  return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n;
6839}
6840function __PRIVATE_computeTransformOperationBaseValue(e, t) {
6841  return e instanceof __PRIVATE_NumericIncrementTransformOperation ? (
6842    /** Returns true if `value` is either an IntegerValue or a DoubleValue. */
6843    function __PRIVATE_isNumber(e2) {
6844      return isInteger(e2) || function __PRIVATE_isDouble(e3) {
6845        return !!e3 && "doubleValue" in e3;
6846      }(e2);
6847    }(t) ? t : {
6848      integerValue: 0
6849    }
6850  ) : null;
6851}
6852class __PRIVATE_ServerTimestampTransform extends TransformOperation {
6853}
6854class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation {
6855  constructor(e) {
6856    super(), this.elements = e;
6857  }
6858}
6859function __PRIVATE_applyArrayUnionTransformOperation(e, t) {
6860  const n = __PRIVATE_coercedFieldValuesArray(t);
6861  for (const t2 of e.elements) n.some((e2) => __PRIVATE_valueEquals(e2, t2)) || n.push(t2);
6862  return {
6863    arrayValue: {
6864      values: n
6865    }
6866  };
6867}
6868class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation {
6869  constructor(e) {
6870    super(), this.elements = e;
6871  }
6872}
6873function __PRIVATE_applyArrayRemoveTransformOperation(e, t) {
6874  let n = __PRIVATE_coercedFieldValuesArray(t);
6875  for (const t2 of e.elements) n = n.filter((e2) => !__PRIVATE_valueEquals(e2, t2));
6876  return {
6877    arrayValue: {
6878      values: n
6879    }
6880  };
6881}
6882class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation {
6883  constructor(e, t) {
6884    super(), this.serializer = e, this.Ee = t;
6885  }
6886}
6887function asNumber(e) {
6888  return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);
6889}
6890function __PRIVATE_coercedFieldValuesArray(e) {
6891  return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : [];
6892}
6893/**
6894 * @license
6895 * Copyright 2017 Google LLC
6896 *
6897 * Licensed under the Apache License, Version 2.0 (the "License");
6898 * you may not use this file except in compliance with the License.
6899 * You may obtain a copy of the License at
6900 *
6901 *   http://www.apache.org/licenses/LICENSE-2.0
6902 *
6903 * Unless required by applicable law or agreed to in writing, software
6904 * distributed under the License is distributed on an "AS IS" BASIS,
6905 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6906 * See the License for the specific language governing permissions and
6907 * limitations under the License.
6908 */
6909class FieldTransform {
6910  constructor(e, t) {
6911    this.field = e, this.transform = t;
6912  }
6913}
6914function __PRIVATE_fieldTransformEquals(e, t) {
6915  return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e2, t2) {
6916    return e2 instanceof __PRIVATE_ArrayUnionTransformOperation && t2 instanceof __PRIVATE_ArrayUnionTransformOperation || e2 instanceof __PRIVATE_ArrayRemoveTransformOperation && t2 instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e2.elements, t2.elements, __PRIVATE_valueEquals) : e2 instanceof __PRIVATE_NumericIncrementTransformOperation && t2 instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e2.Ee, t2.Ee) : e2 instanceof __PRIVATE_ServerTimestampTransform && t2 instanceof __PRIVATE_ServerTimestampTransform;
6917  }(e.transform, t.transform);
6918}
6919class MutationResult {
6920  constructor(e, t) {
6921    this.version = e, this.transformResults = t;
6922  }
6923}
6924class Precondition {
6925  constructor(e, t) {
6926    this.updateTime = e, this.exists = t;
6927  }
6928  /** Creates a new empty Precondition. */
6929  static none() {
6930    return new Precondition();
6931  }
6932  /** Creates a new Precondition with an exists flag. */
6933  static exists(e) {
6934    return new Precondition(void 0, e);
6935  }
6936  /** Creates a new Precondition based on a version a document exists at. */
6937  static updateTime(e) {
6938    return new Precondition(e);
6939  }
6940  /** Returns whether this Precondition is empty. */
6941  get isNone() {
6942    return void 0 === this.updateTime && void 0 === this.exists;
6943  }
6944  isEqual(e) {
6945    return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime);
6946  }
6947}
6948function __PRIVATE_preconditionIsValidForDocument(e, t) {
6949  return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument();
6950}
6951class Mutation {
6952}
6953function __PRIVATE_calculateOverlayMutation(e, t) {
6954  if (!e.hasLocalMutations || t && 0 === t.fields.length) return null;
6955  if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none());
6956  {
6957    const n = e.data, r = ObjectValue.empty();
6958    let i = new SortedSet(FieldPath$1.comparator);
6959    for (let e2 of t.fields) if (!i.has(e2)) {
6960      let t2 = n.field(e2);
6961      null === t2 && e2.length > 1 && (e2 = e2.popLast(), t2 = n.field(e2)), null === t2 ? r.delete(e2) : r.set(e2, t2), i = i.add(e2);
6962    }
6963    return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none());
6964  }
6965}
6966function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) {
6967  e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e2, t2, n2) {
6968    const r = e2.value.clone(), i = __PRIVATE_serverTransformResults(e2.fieldTransforms, t2, n2.transformResults);
6969    r.setAll(i), t2.convertToFoundDocument(n2.version, r).setHasCommittedMutations();
6970  }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e2, t2, n2) {
6971    if (!__PRIVATE_preconditionIsValidForDocument(e2.precondition, t2))
6972      return void t2.convertToUnknownDocument(n2.version);
6973    const r = __PRIVATE_serverTransformResults(e2.fieldTransforms, t2, n2.transformResults), i = t2.data;
6974    i.setAll(__PRIVATE_getPatch(e2)), i.setAll(r), t2.convertToFoundDocument(n2.version, i).setHasCommittedMutations();
6975  }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e2, t2, n2) {
6976    t2.convertToNoDocument(n2.version).setHasCommittedMutations();
6977  }(0, t, n);
6978}
6979function __PRIVATE_mutationApplyToLocalView(e, t, n, r) {
6980  return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e2, t2, n2, r2) {
6981    if (!__PRIVATE_preconditionIsValidForDocument(e2.precondition, t2))
6982      return n2;
6983    const i = e2.value.clone(), s = __PRIVATE_localTransformResults(e2.fieldTransforms, r2, t2);
6984    return i.setAll(s), t2.convertToFoundDocument(t2.version, i).setHasLocalMutations(), null;
6985  }(e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e2, t2, n2, r2) {
6986    if (!__PRIVATE_preconditionIsValidForDocument(e2.precondition, t2)) return n2;
6987    const i = __PRIVATE_localTransformResults(e2.fieldTransforms, r2, t2), s = t2.data;
6988    if (s.setAll(__PRIVATE_getPatch(e2)), s.setAll(i), t2.convertToFoundDocument(t2.version, s).setHasLocalMutations(), null === n2) return null;
6989    return n2.unionWith(e2.fieldMask.fields).unionWith(e2.fieldTransforms.map((e3) => e3.field));
6990  }(e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e2, t2, n2) {
6991    if (__PRIVATE_preconditionIsValidForDocument(e2.precondition, t2)) return t2.convertToNoDocument(t2.version).setHasLocalMutations(), null;
6992    return n2;
6993  }(e, t, n);
6994}
6995function __PRIVATE_mutationExtractBaseValue(e, t) {
6996  let n = null;
6997  for (const r of e.fieldTransforms) {
6998    const e2 = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e2 || null);
6999    null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i));
7000  }
7001  return n || null;
7002}
7003function __PRIVATE_mutationEquals(e, t) {
7004  return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e2, t2) {
7005    return void 0 === e2 && void 0 === t2 || !(!e2 || !t2) && __PRIVATE_arrayEquals(e2, t2, (e3, t3) => __PRIVATE_fieldTransformEquals(e3, t3));
7006  }(e.fieldTransforms, t.fieldTransforms) && (0 === e.type ? e.value.isEqual(t.value) : 1 !== e.type || e.data.isEqual(t.data) && e.fieldMask.isEqual(t.fieldMask)))));
7007}
7008class __PRIVATE_SetMutation extends Mutation {
7009  constructor(e, t, n, r = []) {
vendor: 4,872 bytes, lines 7010-7142
7010    super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, this.type = 0;
7011  }
7012  getFieldMask() {
7013    return null;
7014  }
7015}
7016class __PRIVATE_PatchMutation extends Mutation {
7017  constructor(e, t, n, r, i = []) {
7018    super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, this.fieldTransforms = i, this.type = 1;
7019  }
7020  getFieldMask() {
7021    return this.fieldMask;
7022  }
7023}
7024function __PRIVATE_getPatch(e) {
7025  const t = /* @__PURE__ */ new Map();
7026  return e.fieldMask.fields.forEach((n) => {
7027    if (!n.isEmpty()) {
7028      const r = e.data.field(n);
7029      t.set(n, r);
7030    }
7031  }), t;
7032}
7033function __PRIVATE_serverTransformResults(e, t, n) {
7034  const r = /* @__PURE__ */ new Map();
7035  __PRIVATE_hardAssert(e.length === n.length, 32656, {
7036    Ae: n.length,
7037    Re: e.length
7038  });
7039  for (let i = 0; i < n.length; i++) {
7040    const s = e[i], o = s.transform, _ = t.data.field(s.field);
7041    r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(o, _, n[i]));
7042  }
7043  return r;
7044}
7045function __PRIVATE_localTransformResults(e, t, n) {
7046  const r = /* @__PURE__ */ new Map();
7047  for (const i of e) {
7048    const e2 = i.transform, s = n.data.field(i.field);
7049    r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e2, s, t));
7050  }
7051  return r;
7052}
7053class __PRIVATE_DeleteMutation extends Mutation {
7054  constructor(e, t) {
7055    super(), this.key = e, this.precondition = t, this.type = 2, this.fieldTransforms = [];
7056  }
7057  getFieldMask() {
7058    return null;
7059  }
7060}
7061class __PRIVATE_VerifyMutation extends Mutation {
7062  constructor(e, t) {
7063    super(), this.key = e, this.precondition = t, this.type = 3, this.fieldTransforms = [];
7064  }
7065  getFieldMask() {
7066    return null;
7067  }
7068}
7069/**
7070 * @license
7071 * Copyright 2017 Google LLC
7072 *
7073 * Licensed under the Apache License, Version 2.0 (the "License");
7074 * you may not use this file except in compliance with the License.
7075 * You may obtain a copy of the License at
7076 *
7077 *   http://www.apache.org/licenses/LICENSE-2.0
7078 *
7079 * Unless required by applicable law or agreed to in writing, software
7080 * distributed under the License is distributed on an "AS IS" BASIS,
7081 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7082 * See the License for the specific language governing permissions and
7083 * limitations under the License.
7084 */
7085class MutationBatch {
7086  /**
7087   * @param batchId - The unique ID of this mutation batch.
7088   * @param localWriteTime - The original write time of this mutation.
7089   * @param baseMutations - Mutations that are used to populate the base
7090   * values when this mutation is applied locally. This can be used to locally
7091   * overwrite values that are persisted in the remote document cache. Base
7092   * mutations are never sent to the backend.
7093   * @param mutations - The user-provided mutations in this mutation batch.
7094   * User-provided mutations are applied both locally and remotely on the
7095   * backend.
7096   */
7097  constructor(e, t, n, r) {
7098    this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r;
7099  }
7100  /**
7101   * Applies all the mutations in this MutationBatch to the specified document
7102   * to compute the state of the remote document
7103   *
7104   * @param document - The document to apply mutations to.
7105   * @param batchResult - The result of applying the MutationBatch to the
7106   * backend.
7107   */
7108  applyToRemoteDocument(e, t) {
7109    const n = t.mutationResults;
7110    for (let t2 = 0; t2 < this.mutations.length; t2++) {
7111      const r = this.mutations[t2];
7112      if (r.key.isEqual(e.key)) {
7113        __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t2]);
7114      }
7115    }
7116  }
7117  /**
7118   * Computes the local view of a document given all the mutations in this
7119   * batch.
7120   *
7121   * @param document - The document to apply mutations to.
7122   * @param mutatedFields - Fields that have been updated before applying this mutation batch.
7123   * @returns A `FieldMask` representing all the fields that are mutated.
7124   */
7125  applyToLocalView(e, t) {
7126    for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));
7127    for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));
7128    return t;
7129  }
7130  /**
7131   * Computes the local view for all provided documents given the mutations in
7132   * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
7133   * replace all the mutation applications.
7134   */
7135  applyToLocalDocumentSet(e, t) {
7136    const n = __PRIVATE_newMutationMap();
7137    return this.mutations.forEach((r) => {
7138      const i = e.get(r.key), s = i.overlayedDocument;
7139      let o = this.applyToLocalView(s, i.mutatedFields);
7140      o = t.has(r.key) ? null : o;
7141      const _ = __PRIVATE_calculateOverlayMutation(s, o);
7142      null !== _ && n.set(r.key, _), s.isValidDocument() || s.convertToNoDocument(Snapsh
7142otVersion.min());
7143    }), n;
7144  }
7145  keys() {
7146    return this.mutations.reduce((e, t) => e.add(t.key), __PRIVATE_documentKeySet());
7147  }
7148  isEqual(e) {
7149    return this.batchId === e.batchId && __PRIVATE_arrayEquals(this.mutations, e.mutations, (e2, t) => __PRIVATE_mutationEquals(e2, t)) && __PRIVATE_arrayEquals(this.baseMutations, e.baseMutations, (e2, t) => __PRIVATE_mutationEquals(e2, t));
7150  }
7151}
7152class MutationBatchResult {
7153  constructor(e, t, n, r) {
7154    this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r;
7155  }
7156  /**
7157   * Creates a new MutationBatchResult for the given batch and results. There
7158   * must be one result for each mutation in the batch. This static factory
7159   * caches a document=&gt;version mapping (docVersions).
7160   */
7161  static from(e, t, n) {
7162    __PRIVATE_hardAssert(e.mutations.length === n.length, 58842, {
7163      Ve: e.mutations.length,
7164      me: n.length
7165    });
7166    let r = /* @__PURE__ */ function __PRIVATE_documentVersionMap() {
7167      return Rt;
7168    }();
7169    const i = e.mutations;
7170    for (let e2 = 0; e2 < i.length; e2++) r = r.insert(i[e2].key, n[e2].version);
7171    return new MutationBatchResult(e, t, n, r);
7172  }
7173}
7174/**
7175 * @license
7176 * Copyright 2022 Google LLC
7177 *
7178 * Licensed under the Apache License, Version 2.0 (the "License");
7179 * you may not use this file except in compliance with the License.
7180 * You may obtain a copy of the License at
7181 *
7182 *   http://www.apache.org/licenses/LICENSE-2.0
7183 *
7184 * Unless required by applicable law or agreed to in writing, software
7185 * distributed under the License is distributed on an "AS IS" BASIS,
7186 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7187 * See the License for the specific language governing permissions and
7188 * limitations under the License.
7189 */
7190class Overlay {
7191  constructor(e, t) {
7192    this.largestBatchId = e, this.mutation = t;
7193  }
7194  getKey() {
7195    return this.mutation.key;
7196  }
7197  isEqual(e) {
7198    return null !== e && this.mutation === e.mutation;
7199  }
7200  toString() {
7201    return `Overlay{
7202      largestBatchId: ${this.largestBatchId},
7203      mutation: ${this.mutation.toString()}
7204    }`;
7205  }
7206}
7207/**
7208 * @license
7209 * Copyright 2023 Google LLC
7210 *
7211 * Licensed under the Apache License, Version 2.0 (the "License");
7212 * you may not use this file except in compliance with the License.
7213 * You may obtain a copy of the License at
7214 *
7215 *   http://www.apache.org/licenses/LICENSE-2.0
7216 *
7217 * Unless required by applicable law or agreed to in writing, software
7218 * distributed under the License is distributed on an "AS IS" BASIS,
7219 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7220 * See the License for the specific language governing permissions and
7221 * limitations under the License.
7222 */
7223class __PRIVATE_AggregateImpl {
7224  constructor(e, t, n) {
7225    this.alias = e, this.aggregateType = t, this.fieldPath = n;
7226  }
7227}
7228/**
7229 * @license
7230 * Copyright 2017 Google LLC
7231 *
7232 * Licensed under the Apache License, Version 2.0 (the "License");
7233 * you may not use this file except in compliance with the License.
7234 * You may obtain a copy of the License at
7235 *
7236 *   http://www.apache.org/licenses/LICENSE-2.0
7237 *
7238 * Unless required by applicable law or agreed to in writing, software
7239 * distributed under the License is distributed on an "AS IS" BASIS,
7240 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7241 * See the License for the specific language governing permissions and
7242 * limitations under the License.
7243 */
7244class ExistenceFilter {
7245  constructor(e, t) {
7246    this.count = e, this.unchangedNames = t;
7247  }
7248}
7249/**
7250 * @license
7251 * Copyright 2017 Google LLC
7252 *
7253 * Licensed under the Apache License, Version 2.0 (the "License");
7254 * you may not use this file except in compliance with the License.
7255 * You may obtain a copy of the License at
7256 *
7257 *   http://www.apache.org/licenses/LICENSE-2.0
7258 *
7259 * Unless required by applicable law or agreed to in writing, software
7260 * distributed under the License is distributed on an "AS IS" BASIS,
7261 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7262 * See the License for the specific language governing permissions and
7263 * limitations under the License.
7264 */
7265var ft, gt;
7266function __PRIVATE_isPermanentError(e) {
7267  switch (e) {
7268    case N.OK:
7269      return fail(64938);
7270    case N.CANCELLED:
7271    case N.UNKNOWN:
7272    case N.DEADLINE_EXCEEDED:
7273    case N.RESOURCE_EXHAUSTED:
7274    case N.INTERNAL:
7275    case N.UNAVAILABLE:
7276    case N.UNAUTHENTICATED:
7277      return false;
7278    case N.INVALID_ARGUMENT:
7279    case N.NOT_FOUND:
7280    case N.ALREADY_EXISTS:
7281    case N.PERMISSION_DENIED:
7282    case N.FAILED_PRECONDITION:
7283    case N.ABORTED:
7284    case N.OUT_OF_RANGE:
7285    case N.UNIMPLEMENTED:
7286    case N.DATA_LOSS:
7287      return true;
7288    default:
7289      return fail(15467, {
7290        code: e
7291      });
7292  }
7293}
7294function __PRIVATE_mapCodeFromRpcCode(e) {
7295  if (void 0 === e)
7296    return __PRIVATE_logError("GRPC error has no .code"), N.UNKNOWN;
7297  switch (e) {
7298    case ft.OK:
7299      return N.OK;
7300    case ft.CANCELLED:
7301      return N.CANCELLED;
7302    case ft.UNKNOWN:
7303      return N.UNKNOWN;
7304    case ft.DEADLINE_EXCEEDED:
7305      return N.DEADLINE_EXCEEDED;
7306    case ft.RESOURCE_EXHAUSTED:
7307      return N.RESOURCE_EXHAUSTED;
7308    case ft.INTERNAL:
7309      return N.INTERNAL;
7310    case ft.UNAVAILABLE:
7311      return N.UNAVAILABLE;
7312    case ft.UNAUTHENTICATED:
7313      return N.UNAUTHENTICATED;
7314    case ft.INVALID_ARGUMENT:
7315      return N.INVALID_ARGUMENT;
7316    case ft.NOT_FOUND:
7317      return N.NOT_FOUND;
7318    case ft.ALREADY_EXISTS:
7319      return N.ALREADY_EXISTS;
7320    case ft.PERMISSION_DENIED:
7321      return N.PERMISSION_DENIED;
7322    case ft.FAILED_PRECONDITION:
7323      return N.FAILED_PRECONDITION;
7324    case ft.ABORTED:
7325      return N.ABORTED;
7326    case ft.OUT_OF_RANGE:
7327      return N.OUT_OF_RANGE;
7328    case ft.UNIMPLEMENTED:
7329      return N.UNIMPLEMENTED;
7330    case ft.DATA_LOSS:
7331      return N.DATA_LOSS;
7332    default:
7333      return fail(39323, {
7334        code: e
7335      });
7336  }
7337}
7338(gt = ft || (ft = {}))[gt.OK = 0] = "OK", gt[gt.CANCELLED = 1] = "CANCELLED", gt[gt.UNKNOWN = 2] = "UNKNOWN", gt[gt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", gt[gt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", gt[gt.NOT_FOUND = 5] = "NOT_FOUND", gt[gt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", gt[gt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", gt[gt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", gt[gt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", gt[gt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", gt[gt.ABORTED = 10] = "ABORTED", gt[gt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", gt[gt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", gt[gt.INTERNAL = 13] = "INTERNAL", gt[gt.UNAVAILABLE = 14] = "UNAVAILABLE", gt[gt.DATA_LOSS = 15] = "DATA_LOSS";
7339/**
7340 * @license
7341 * Copyright 2023 Google LLC
7342 *
7343 * Licensed under the Apache License, Version 2.0 (the "License");
7344 * you may not use this file except in compliance with the License.
7345 * You may obtain a copy of the License at
7346 *
7347 *   http://www.apache.org/licenses/LICENSE-2.0
7348 *
7349 * Unless required by applicable law or agreed to in writing, software
7350 * distributed under the License is distributed on an "AS IS" BASIS,
7351 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7352 * See the License for the specific language governing permissions and
7353 * limitations under the License.
7354 */
7355let pt = null;
7356/**
7357 * @license
7358 * Copyright 2022 Google LLC
7359 *
7360 * Licensed under the Apache License, Version 2.0 (the "License");
7361 * you may not use this file except in compliance with the License.
7362 * You may obtain a copy of the License at
7363 *
7364 *   http://www.apache.org/licenses/LICENSE-2.0
7365 *
7366 * Unless required by applicable law or agreed to in writing, software
7367 * distributed under the License is distributed on an "AS IS" BASIS,
7368 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7369 * See the License for the specific language governing permissions and
7370 * limitations under the License.
7371 */
7372const yt = new Integer([4294967295, 4294967295], 0);
7373function __PRIVATE_getMd5HashValue(e) {
7374  const t = __PRIVATE_newTextEncoder().encode(e), n = new Md5();
7375  return n.update(t), new Uint8Array(n.digest());
7376}
7377function __PRIVATE_get64BitUints(e) {
7378  const t = new DataView(e.buffer), n = t.getUint32(
7379    0,
7380    /* littleEndian= */
7381    true
7382  ), r = t.getUint32(
7383    4,
7384    /* littleEndian= */
7385    true
7386  ), i = t.getUint32(
7387    8,
7388    /* littleEndian= */
7389    true
7390  ), s = t.getUint32(
7391    12,
7392    /* littleEndian= */
7393    true
7394  );
7395  return [new Integer([n, r], 0), new Integer([i, s], 0)];
7396}
7397class BloomFilter {
7398  constructor(e, t, n) {
7399    if (this.bitmap = e, this.padding = t, this.hashCount = n, t 
vendor: 4,285 bytes, lines 7399-7499
7399< 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`);
7400    if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);
7401    if (e.length > 0 && 0 === this.hashCount)
7402      throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);
7403    if (0 === e.length && 0 !== t)
7404      throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`);
7405    this.fe = 8 * e.length - t, // Set the bit count in Integer to avoid repetition in mightContain().
7406    this.ge = Integer.fromNumber(this.fe);
7407  }
7408  // Calculate the ith hash value based on the hashed 64bit integers,
7409  // and calculate its corresponding bit index in the bitmap to be checked.
7410  pe(e, t, n) {
7411    let r = e.add(t.multiply(Integer.fromNumber(n)));
7412    return 1 === r.compare(yt) && (r = new Integer([r.getBits(0), r.getBits(1)], 0)), r.modulo(this.ge).toNumber();
7413  }
7414  // Return whether the bit on the given index in the bitmap is set to 1.
7415  ye(e) {
7416    return !!(this.bitmap[Math.floor(e / 8)] & 1 << e % 8);
7417  }
7418  mightContain(e) {
7419    if (0 === this.fe) return false;
7420    const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);
7421    for (let e2 = 0; e2 < this.hashCount; e2++) {
7422      const t2 = this.pe(n, r, e2);
7423      if (!this.ye(t2)) return false;
7424    }
7425    return true;
7426  }
7427  /** Create bloom filter for testing purposes only. */
7428  static create(e, t, n) {
7429    const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t);
7430    return n.forEach((e2) => s.insert(e2)), s;
7431  }
7432  insert(e) {
7433    if (0 === this.fe) return;
7434    const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);
7435    for (let e2 = 0; e2 < this.hashCount; e2++) {
7436      const t2 = this.pe(n, r, e2);
7437      this.we(t2);
7438    }
7439  }
7440  we(e) {
7441    const t = Math.floor(e / 8), n = e % 8;
7442    this.bitmap[t] |= 1 << n;
7443  }
7444}
7445class __PRIVATE_BloomFilterError extends Error {
7446  constructor() {
7447    super(...arguments), this.name = "BloomFilterError";
7448  }
7449}
7450/**
7451 * @license
7452 * Copyright 2017 Google LLC
7453 *
7454 * Licensed under the Apache License, Version 2.0 (the "License");
7455 * you may not use this file except in compliance with the License.
7456 * You may obtain a copy of the License at
7457 *
7458 *   http://www.apache.org/licenses/LICENSE-2.0
7459 *
7460 * Unless required by applicable law or agreed to in writing, software
7461 * distributed under the License is distributed on an "AS IS" BASIS,
7462 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7463 * See the License for the specific language governing permissions and
7464 * limitations under the License.
7465 */
7466class RemoteEvent {
7467  constructor(e, t, n, r, i) {
7468    this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, this.resolvedLimboDocuments = i;
7469  }
7470  /**
7471   * HACK: Views require RemoteEvents in order to determine whether the view is
7472   * CURRENT, but secondary tabs don't receive remote events. So this method is
7473   * used to create a synthesized RemoteEvent that can be used to apply a
7474   * CURRENT status change to a View, for queries executed in a different tab.
7475   */
7476  // PORTING NOTE: Multi-tab only
7477  static createSynthesizedRemoteEventForCurrentChange(e, t, n) {
7478    const r = /* @__PURE__ */ new Map();
7479    return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet());
7480  }
7481}
7482class TargetChange {
7483  constructor(e, t, n, r, i) {
7484    this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, this.removedDocuments = i;
7485  }
7486  /**
7487   * This method is used to create a synthesized TargetChanges that can be used to
7488   * apply a CURRENT status change to a View (for queries executed in a different
7489   * tab) or for new queries (to raise snapshots with correct CURRENT status).
7490   */
7491  static createSynthesizedTargetChangeForCurrentChange(e, t, n) {
7492    return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet());
7493  }
7494}
7495/**
7496 * @license
7497 * Copyright 2017 Google LLC
7498 *
7499 * Licensed under the Apache License, Version 2.0 (the "License");
7500 * you may not use this file except in compliance with the License.
7501 * You may obtain a copy of the License at
7502 *
7503 *   http://www.apache.org/licenses/LICENSE-2.0
7504 *
7505 * Unless required by applicable law or agreed to in writing, software
7506 * distributed under the License is distributed on an "AS IS" BASIS,
7507 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7508 * See the License for the specific language governing permissions and
7509 * limitations under the License.
7510 */
7511class __PRIVATE_DocumentWatchChange {
7512  constructor(e, t, n, r) {
7513    this.Se = e, this.removedTargetIds = t, this.key = n, this.be = r;
7514  }
7515}
7516class __PRIVATE_ExistenceFilterChange {
7517  constructor(e, t) {
7518    this.targetId = e, this.De = t;
7519  }
7520}
7521class __PRIVATE_WatchTargetChange {
7522  constructor(e, t, n = ByteString.EMPTY_BYTE_STRING, r = null) {
7523    this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r;
7524  }
7525}
7526class __PRIVATE_TargetState {
7527  constructor() {
7528    this.ve = 0, /**
7529    * Keeps track of the document changes since the last raised snapshot.
7530    *
7531    * These changes are continuously updated as we receive document updates and
7532    * always reflect the current set of changes against the last issued snapshot.
7533    */
7534    this.Ce = __PRIVATE_snapshotChangesMap(), /** See public getters for explanations of these fields. */
7535    this.Fe = ByteString.EMPTY_BYTE_STRING, this.Me = false, /**
7536    * Whether this target state should be included in the next snapshot. We
7537    * initialize to true so that newly-added targets are included in the next
7538    * RemoteEvent.
7539    */
7540    this.xe = true;
7541  }
7542  /**
7543   * Whether this target has been marked 'current'.
7544   *
7545   * 'Current' has special meaning in the RPC protocol: It implies that the
7546   * Watch backend has sent us all changes up to the point at which the target
7547   * was added and that the target is consistent with the rest of the watch
7548   * stream.
7549   */
7550  get current() {
7551    return this.Me;
7552  }
7553  /** The last resume token sent to us for this target. */
7554  get resumeToken() {
7555    return this.Fe;
7556  }
7557  /** Whether this target has pending target adds or target removes. */
7558  get Oe() {
7559    return 0 !== this.ve;
7560  }
7561  /** Whether we have modified any state that should trigger a snapshot. */
7562  get Ne() {
7563    return this.xe;
7564  }
7565  /**
7566   * Applies the resume token to the TargetChange, but only when it has a new
7567   * value. Empty resumeTokens are discarded.
7568   */
7569  Be(e) {
7570    e.approximateByteSize() > 0 && (this.xe = true, this.Fe = e);
7571  }
7572  /**
7573   * Creates a target change from the current set of changes.
7574   *
7575   * To reset the document changes after raising this snapshot, call
7576   * `clearPendingChanges()`.
7577   */
7578  Le() {
7579    let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet();
7580    return this.Ce.forEach((r, i) => {
7581      switch (i) {
7582        case 0:
7583          e = e.add(r);
7584          break;
7585        case 2:
7586          t = t.add(r);
7587          break;
7588        case 1:
7589          n = n.add(r);
7590          break;
7591        default:
7592          fail(38017, {
7593            changeType: i
7594          });
7595      }
7596    }), new TargetChange(this.Fe, this.Me, e, t, n);
7597  }
7598  /**
7599   * Resets the document changes and sets `hasPendingChanges` to false.
7600   */
7601  ke() {
7602    this.xe = false, this.Ce = __PRIVATE_snapshotChangesMap();
7603  }
7604  qe(e, t) {
7605    this.xe = true, this.Ce = this.Ce.insert(e, t);
7606  }
7607  Qe(e) {
7608    this.xe = true, this.Ce = this.Ce.remove(e);
7609  }
7610  $e() {
7611    this.ve += 1;
7612  }
7613  Ue() {
7614    this.ve -= 1, __PRIVATE_hardAssert(this.ve >= 0, 3241, {
7615      ve: this.ve
7616    });
7617  }
7618  Ke() {
7619    this.xe = true, this.Me = true;
7620  }
7621}
7622class __PRIVATE_WatchChangeAggregator {
7623  constructor(e) {
7624    this.We = e, /** The internal state of all tracked targets. */
7625    this.Ge = /* @__PURE__ */ new Map(), /** Keeps track of the documents to update since the last raised snapshot. */
7626    this.ze = __PRIVATE_mutableDocumentMap(), this.je = __PRIVATE_documentTargetMap(), /** A mapping of document keys to their set of target IDs. */
7627    this.Je = __PRIVATE_documentTargetMap(), /**
7628    * A map of targets with existence filter mismatches. These targets are
7629    * known to be inconsistent and their listens needs to be re-established by
7630    * RemoteStore.
7631    */
7632    this.He = new SortedMap(__PRIVATE_primitiveComparator);
7633  }
7634  /**
7635   * Processes and adds the DocumentWatchChange to the current set of changes.
7636   */
7637  Ye(e) {
7638    for (const t of e.Se) e.be && e.be.isFoundDocument() ? this.Ze(t, e.be) : this.Xe(t, e.key, e.be);
7639    for (const t of e.removedTargetIds) this.Xe(t, e.key, e.be);
7640  }
7641  /** Processes and adds the WatchTargetChange to the current set of changes. */
7642  et(e) {
7643    this.forEachTarget(e, (t) => {
7644      const n = this.tt(t);
7645      switch (e.state) {
7646        case 0:
7647          this.nt(t) && n.Be(e.resumeToken);
7648          break;
7649        case 1:
7650          n.Ue(), n.Oe || // We have a freshly added target, so we need to reset any state
7651          // that we had previously. This can happen e.g. when remove and add
7652          // back a target for existence filter mismatches.
7653          n.ke(), n.Be(e.resumeToken);
7654          break;
7655        case 2:
7656          n.Ue(), n.Oe || this.removeTarget(t);
7657          break;
7658        case 3:
7659          this.nt(t) && (n.Ke(), n.Be(e.resumeToken));
7660          break;
7661        case 4:
7662          this.nt(t) && // Reset the target and synthesizes removes for all existing
7663          // documents. The backend will re-add any documents that still
7664          // match the target before it sends the next global snapshot.
7665          (this.rt(t), n.Be(e.resumeToken));
7666          break;
7667        default:
7668          fail(56790, {
7669            state: e.state
7670          });
7671      }
7672    });
7673  }
7674  /**
7675   * Iterates over all targetIds that the watch change applies to: either the
7676   * targetIds explicitly listed in the change or the targetIds of all currently
7677   * active targets.
7678   */
7679  forEachTarget(e, t) {
7680    e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.Ge.forEach((e2, n) => {
7681      this.nt(n) && t(n);
7682    });
7683  }
7684  /**
7685   * Handles existence filters and synthesizes deletes for filter mismatches.
7686   * Targets that are invalidated by filter mismatches are added to
7687   * `pendingTargetResets`.
7688   */
7689  it(e) {
7690    const t = e.targetId, n = e.De.count, r = this.st(t);
7691    if (r) {
7692      const i = r.target;
7693      if (__PRIVATE_targetIsDocumentTarget(i)) if (0 === n) {
7694        const e2 = new DocumentKey(i.path);
7695        this.Xe(t, e2, MutableDocument.newNoDocument(e2, SnapshotVersion.min()));
7696      } else __PRIVATE_hardAssert(1 === n, 20013, {
7697        expectedCount: n
7698      });
7699      else {
7700        const r2 = this.ot(t);
7701        if (r2 !== n) {
7702          const n2 = this._t(e), i2 = n2 ? this.ut(n2, e, r2) : 1;
7703          if (0 !== i2) {
7704            this.rt(t);
7705            const e2 = 2 === i2 ? "TargetPurposeExistenceFilterMismatchBloom" : "TargetPurposeExistenceFilterMismatch";
7706            this.He = this.He.insert(t, e2);
7707          }
7708          null == pt || pt.ct(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e2, t2, n3, r3, i3) {
7709            var s, o, _, a, u, c;
7710            const l = {
7711              localCacheCount: e2,
7712              existenceFilterCount: t2.count,
7713              databaseId: n3.database,
7714              projectId: n3.projectId
7715            }, h = t2.unchangedNames;
7716            h && (l.bloomFilter = {
7717              applied: 0 === i3,
7718              hashCount: null !== (s = null == h ? void 0 : h.hashCount) && void 0 !== s ? s : 0,
7719              bitmapLength: null !== (a = null === (_ = null === (o = null == h ? void 0 : h.bits) || void 0 === o ? void 0 : o.bitmap) || void 0 === _ ? void 0 : _.length) && void 0 !== a ? a : 0,
7720              padding: null !== (c = null === (u = null == h ? void 0 : h.bits) || void 0 === u ? void 0 : u.padding) && void 0 !== c ? c : 0,
7721              mightContain: (e3) => {
7722                var t3;
7723                return null !== (t3 = null == r3 ? void 0 : r3.mightContain(e3)) && void 0 !== t3 && t3;
7724              }
7725            });
7726            return l;
7727          }(r2, e.De, this.We.lt(), n2, i2));
7728        }
7729      }
7730    }
7731  }
7732  /**
7733   * Parse the bloom filter from the "unchanged_names" field of an existence
7734   * filter.
7735   */
7736  _t(e) {
7737    const t = e.De.unchangedNames;
7738    if (!t || !t.bits) return null;
7739    const { bits: { bitmap: n = "", padding: r = 0 }, hashCount: i = 0 } = t;
7740    let s, o;
7741    try {
7742      s = __PRIVATE_normalizeByteString(n).toUint8Array();
7743    } catch (e2) {
7744      if (e2 instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn("Decoding the base64 bloom filter in existence filter failed (" + e2.message + "); ignoring the bloom filter and falling back to full re-query."), null;
7745      throw e2;
7746    }
7747    try {
7748      o = new BloomFilter(s, r, i);
7749    } catch (e2) {
7750      return __PRIVATE_logWarn(e2 instanceof __PRIVATE_BloomFilterError ? "BloomFilter error: " : "Applying bloom filter failed: ", e2), null;
7751    }
7752    return 0 === o.fe ? null : o;
7753  }
7754  /**
7755   * Apply bloom filter to remove the deleted documents, and return the
7756   * application status.
7757   */
7758  ut(e, t, n) {
7759    return t.De.count === n - this.ht(e, t.targetId) ? 0 : 2;
7760  }
7761  /**
7762   * Filter out removed documents based on bloom filter membership result and
7763   * return number of documents removed.
7764   */
7765  ht(e, t) {
7766    const n = this.We.getRemoteKeysForTarget(t);
7767    let r = 0;
7768    return n.forEach((n2) => {
7769      const i = this.We.lt(), s = `projects/${i.projectId}/databases/${i.database}/documents/${n2.path.canonicalString()}`;
7770      e.mightContain(s) || (this.Xe(
7771        t,
7772        n2,
7773        /*updatedDocument=*/
7774        null
7775      ), r++);
7776    }), r;
7777  }
7778  /**
7779   * Converts the currently accumulated state into a remote event at the
7780   * provided snapshot version. Resets the accumulated changes before returning.
7781   */
7782  Pt(e) {
7783    const t = /* @__PURE__ */ new Map();
7784    this.Ge.forEach((n2, r2) => {
7785      const i = this.st(r2);
7786      if (i) {
7787        if (n2.current && __PRIVATE_targetIsDocumentTarget(i.target)) {
7788          const t2 = new DocumentKey(i.target.path);
7789          this.Tt(t2).has(r2) || this.It(r2, t2) || this.Xe(r2, t2, MutableDocument.newNoDocument(t2, e));
7790        }
7791        n2.Ne && (t.set(r2, n2.Le()), n2.ke());
7792      }
7793    });
7794    let n = __PRIVATE_documentKeySet();
7795    this.Je.forEach((e2, t2) => {
7796      let r2 = true;
7797      t2.forEachWhile((e3) => {
7798        const t3 = this.st(e3);
7799        return !t3 || "TargetPurposeLimboResolution" === t3.purpose || (r2 = false, false);
7800      }), r2 && (n = n.add(e2));
7801    }), this.ze.forEach((t2, n2) => n2.setReadTime(e));
7802    const r = new RemoteEvent(e, t, this.He, this.ze, n);
7803    return this.ze = __PRIVATE_mutableDocumentMap(), this.je = __PRIVATE_documentTargetMap(), this.Je = __PRIVATE_documentTargetMap(), this.He = new SortedMap(__PRIVATE_primitiveComparator), r;
7804  }
7805  /**
7806   * Adds the provided document to the internal list of document updates and
7807   * its document key to the given target's mapping.
7808   */
7809  // Visible for testing.
7810  Ze(e, t) {
7811    if (!this.nt(e)) return;
7812    const n = this.It(e, t.key) ? 2 : 0;
7813    this.tt(e).qe(t.key, n), this.ze = this.ze.insert(t.key, t), this.je = this.je.insert(t.key, this.Tt(t.key).add(e)), this.Je = this.Je.insert(t.key, this.dt(t.key).add(e));
7814  }
7815  /**
7816   * Removes the provided document from the target mapping. If the
7817   * document no longer matches the target, but the document's state is still
7818   * known (e.g. we know that the document was deleted or we received the change
7819   * that caused the filter mismatch), the new document can be provided
7820   * to update the remote document cache.
7821   */
7822  // Visible for testing.
7823  Xe(e, t, n) {
7824    if (!this.nt(e)) return;
7825    const r = this.tt(e);
7826    this.It(e, t) ? r.qe(
7827      t,
7828      1
7829      /* ChangeType.Removed */
7830    ) : (
7831      // The document may have entered and left the target before we raised a
7832      // snapshot, so we can just ignore the change.
7833      r.Qe(t)
7834    ), this.Je = this.Je.insert(t, this.dt(t).delete(e)), this.Je = this.Je.insert(t, this.dt(t).add(e)), n && (this.ze = this.ze.insert(t, n));
7835  }
7836  removeTarget(e) {
7837    this.Ge.delete(e);
7838  }
7839  /**
7840   * Returns the current count of documents in the target. This includes both
7841   * the number of documents that the LocalStore considers to be part of the
7842   * target as well as any accumulated changes.
7843   */
7844  ot(e) {
7845    const t = this.tt(e).Le();
7846    return this.We.getRemoteKeysForTarget(e).size + t.addedDocuments.size - t.removedDocuments.size;
7847  }
7848  /**
7849   * Increment the number of acks needed from watch before we can consider the
7850   * server to be 'in-sync' with the client's active targets.
7851   */
7852  $e(e) {
7853    this.tt(e).$e();
7854  }
7855  tt(e) {
7856    let t = this.Ge.get(e);
7857    return t || (t = new __PRIVATE_TargetState(), this.Ge.set(e, t)), t;
7858  }
7859  dt(e) {
7860    let t = this.Je.get(e);
7861    return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.Je = this.Je.insert(e, t)), t;
7862  }
7863  Tt(e) {
7864    let t = this.je.get(e);
7865    return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.je = this.je.insert(e, t)), t;
7866  }
7867  /**
7868   * Verifies that the user is still interested in this target (by calling
7869   * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
7870   * from watch.
7871   */
7872  nt(e) {
7873    const t = null !== this.st(e);
7874    return t || __PRIVATE_logDebug("WatchChangeAggregator", "Detected inactive target", e), t;
7875  }
7876  /**
7877   * Returns the TargetData for an active target (i.e. a target that the user
7878   * is still interested in that has no outstanding target change requests).
7879   */
7880  st(e) {
7881    const t = this.Ge.get(e);
7882    return t && t.Oe ? null : this.We.Et(e);
7883  }
7884  /**
7885   * Resets the state of a Watch target to its initial state (e.g. sets
7886   * 'current' to false, clears the resume token and removes its target mapping
7887   * from all documents).
7888   */
7889  rt(e) {
7890    this.Ge.set(e, new __PRIVATE_TargetState());
7891    this.We.getRemoteKeysForTarget(e).forEach((t) => {
7892      this.Xe(
7893        e,
7894        t,
7895        /*updatedDocument=*/
7896        null
7897      );
7898    });
7899  }
7900  /**
7901   * Returns whether the LocalStore considers the document to be part of the
7902   * specified target.
7903   */
7904  It(e, t) {
7905    return this.We.getRemoteKeysForTarget(e).has(t);
7906  }
7907}
7908function __PRIVATE_documentTargetMap() {
7909  return new SortedMap(DocumentKey.comparator);
7910}
7911function __PRIVATE_snapshotChangesMap() {
7912  return new SortedMap(DocumentKey.comparator);
7913}
7914const wt = /* @__PURE__ */ (() => {
7915  const e = {
7916    asc: "ASCENDING",
7917    desc: "DESCENDING"
7918  };
7919  return e;
7920})(), St = /* @__PURE__ */ (() => {
7921  const e = {
7922    "<": "LESS_THAN",
7923    "<=": "LESS_THAN_OR_EQUAL",
7924    ">": "GREATER_THAN",
7925    ">=": "GREATER_THAN_OR_EQUAL",
7926    "==": "EQUAL",
7927    "!=": "NOT_EQUAL",
7928    "array-contains": "ARRAY_CONTAINS",
7929    in: "IN",
7930    "not-in": "NOT_IN",
7931    "array-contains-any": "ARRAY_CONTAINS_ANY"
7932  };
7933  return e;
7934})(), bt = /* @__PURE__ */ (() => {
7935  const e = {
7936    and: "AND",
7937    or: "OR"
7938  };
7939  return e;
7940})();
7941class JsonProtoSerializer {
7942  constructor(e, t) {
7943    this.databaseId = e, this.useProto3Json = t;
7944  }
7945}
7946function __PRIVATE_toInt32Proto(e, t) {
7947  return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : {
7948    value: t
7949  };
7950}
7951function toTimestamp(e, t) {
7952  if (e.useProto3Json) {
7953    return `${new Date(1e3 * t.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t.nanoseconds).slice(-9)}Z`;
7954  }
7955  return {
7956    seconds: "" + t.seconds,
7957    nanos: t.nanoseconds
7958  };
7959}
7960function __PRIVATE_toBytes(e, t) {
7961  return e.useProto3Json ? t.toBase64() : t.toUint8Array();
7962}
7963function __PRIVATE_toVersion(e, t) {
7964  return toTimestamp(e, t.toTimestamp());
7965}
7966function __PRIVATE_fromVersion(e) {
7967  return __PRIVATE_hardAssert(!!e, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(e2) {
7968    const t = __PRIVATE_normalizeTimestamp(e2);
7969    return new Timestamp(t.seconds, t.nanos);
7970  }(e));
7971}
7972function __PRIVATE_toResourceName(e, t) {
7973  return __PRIVATE_toResourcePath(e, t).canonicalString();
7974}
7975function __PRIVATE_toResourcePath(e, t) {
7976  const n = function __PRIVATE_fullyQualifiedPrefixPath(e2) {
7977    return new ResourcePath(["projects", e2.projectId, "databases", e2.database]);
7978  }(e).child("documents");
7979  return void 0 === t ? n : n.child(t);
7980}
7981function __PRIVATE_fromResourceName(e) {
7982  const t = ResourcePath.fromString(e);
7983  return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t), 10190, {
7984    key: t.toString()
7985  }), t;
vendor: 25,810 bytes, lines 7986-8678
7986}
7987function __PRIVATE_toName(e, t) {
7988  return __PRIVATE_toResourceName(e.databaseId, t.path);
7989}
7990function fromName(e, t) {
7991  const n = __PRIVATE_fromResourceName(t);
7992  if (n.get(1) !== e.databaseId.projectId) throw new FirestoreError(N.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + e.databaseId.projectId);
7993  if (n.get(3) !== e.databaseId.database) throw new FirestoreError(N.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + e.databaseId.database);
7994  return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n));
7995}
7996function __PRIVATE_toQueryPath(e, t) {
7997  return __PRIVATE_toResourceName(e.databaseId, t);
7998}
7999function __PRIVATE_fromQueryPath(e) {
8000  const t = __PRIVATE_fromResourceName(e);
8001  return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t);
8002}
8003function __PRIVATE_getEncodedDatabaseId(e) {
8004  return new ResourcePath(["projects", e.databaseId.projectId, "databases", e.databaseId.database]).canonicalString();
8005}
8006function __PRIVATE_extractLocalPathFromResourceName(e) {
8007  return __PRIVATE_hardAssert(e.length > 4 && "documents" === e.get(4), 29091, {
8008    key: e.toString()
8009  }), e.popFirst(5);
8010}
8011function __PRIVATE_toMutationDocument(e, t, n) {
8012  return {
8013    name: __PRIVATE_toName(e, t),
8014    fields: n.value.mapValue.fields
8015  };
8016}
8017function __PRIVATE_fromDocument(e, t, n) {
8018  const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), o = new ObjectValue({
8019    mapValue: {
8020      fields: t.fields
8021    }
8022  }), _ = MutableDocument.newFoundDocument(r, i, s, o);
8023  return n && _.setHasCommittedMutations(), n ? _.setHasCommittedMutations() : _;
8024}
8025function __PRIVATE_fromBatchGetDocumentsResponse(e, t) {
8026  return "found" in t ? function __PRIVATE_fromFound(e2, t2) {
8027    __PRIVATE_hardAssert(!!t2.found, 43571), t2.found.name, t2.found.updateTime;
8028    const n = fromName(e2, t2.found.name), r = __PRIVATE_fromVersion(t2.found.updateTime), i = t2.found.createTime ? __PRIVATE_fromVersion(t2.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({
8029      mapValue: {
8030        fields: t2.found.fields
8031      }
8032    });
8033    return MutableDocument.newFoundDocument(n, r, i, s);
8034  }(e, t) : "missing" in t ? function __PRIVATE_fromMissing(e2, t2) {
8035    __PRIVATE_hardAssert(!!t2.missing, 3894), __PRIVATE_hardAssert(!!t2.readTime, 22933);
8036    const n = fromName(e2, t2.missing), r = __PRIVATE_fromVersion(t2.readTime);
8037    return MutableDocument.newNoDocument(n, r);
8038  }(e, t) : fail(7234, {
8039    result: t
8040  });
8041}
8042function __PRIVATE_fromWatchChange(e, t) {
8043  let n;
8044  if ("targetChange" in t) {
8045    t.targetChange;
8046    const r = function __PRIVATE_fromWatchTargetChangeState(e2) {
8047      return "NO_CHANGE" === e2 ? 0 : "ADD" === e2 ? 1 : "REMOVE" === e2 ? 2 : "CURRENT" === e2 ? 3 : "RESET" === e2 ? 4 : fail(39313, {
8048        state: e2
8049      });
8050    }(t.targetChange.targetChangeType || "NO_CHANGE"), i = t.targetChange.targetIds || [], s = function __PRIVATE_fromBytes(e2, t2) {
8051      return e2.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t2 || "string" == typeof t2, 58123), ByteString.fromBase64String(t2 || "")) : (__PRIVATE_hardAssert(void 0 === t2 || // Check if the value is an instance of both Buffer and Uint8Array,
8052      // despite the fact that Buffer extends Uint8Array. In some
8053      // environments, such as jsdom, the prototype chain of Buffer
8054      // does not indicate that it extends Uint8Array.
8055      t2 instanceof Buffer || t2 instanceof Uint8Array, 16193), ByteString.fromUint8Array(t2 || new Uint8Array()));
8056    }(e, t.targetChange.resumeToken), o = t.targetChange.cause, _ = o && function __PRIVATE_fromRpcStatus(e2) {
8057      const t2 = void 0 === e2.code ? N.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e2.code);
8058      return new FirestoreError(t2, e2.message || "");
8059    }(o);
8060    n = new __PRIVATE_WatchTargetChange(r, i, s, _ || null);
8061  } else if ("documentChange" in t) {
8062    t.documentChange;
8063    const r = t.documentChange;
8064    r.document, r.document.name, r.document.updateTime;
8065    const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), o = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), _ = new ObjectValue({
8066      mapValue: {
8067        fields: r.document.fields
8068      }
8069    }), a = MutableDocument.newFoundDocument(i, s, o, _), u = r.targetIds || [], c = r.removedTargetIds || [];
8070    n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a);
8071  } else if ("documentDelete" in t) {
8072    t.documentDelete;
8073    const r = t.documentDelete;
8074    r.document;
8075    const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), o = MutableDocument.newNoDocument(i, s), _ = r.removedTargetIds || [];
8076    n = new __PRIVATE_DocumentWatchChange([], _, o.key, o);
8077  } else if ("documentRemove" in t) {
8078    t.documentRemove;
8079    const r = t.documentRemove;
8080    r.document;
8081    const i = fromName(e, r.document), s = r.removedTargetIds || [];
8082    n = new __PRIVATE_DocumentWatchChange([], s, i, null);
8083  } else {
8084    if (!("filter" in t)) return fail(11601, {
8085      At: t
8086    });
8087    {
8088      t.filter;
8089      const e2 = t.filter;
8090      e2.targetId;
8091      const { count: r = 0, unchangedNames: i } = e2, s = new ExistenceFilter(r, i), o = e2.targetId;
8092      n = new __PRIVATE_ExistenceFilterChange(o, s);
8093    }
8094  }
8095  return n;
8096}
8097function toMutation(e, t) {
8098  let n;
8099  if (t instanceof __PRIVATE_SetMutation) n = {
8100    update: __PRIVATE_toMutationDocument(e, t.key, t.value)
8101  };
8102  else if (t instanceof __PRIVATE_DeleteMutation) n = {
8103    delete: __PRIVATE_toName(e, t.key)
8104  };
8105  else if (t instanceof __PRIVATE_PatchMutation) n = {
8106    update: __PRIVATE_toMutationDocument(e, t.key, t.data),
8107    updateMask: __PRIVATE_toDocumentMask(t.fieldMask)
8108  };
8109  else {
8110    if (!(t instanceof __PRIVATE_VerifyMutation)) return fail(16599, {
8111      Rt: t.type
8112    });
8113    n = {
8114      verify: __PRIVATE_toName(e, t.key)
8115    };
8116  }
8117  return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e2) => function __PRIVATE_toFieldTransform(e3, t2) {
8118    const n2 = t2.transform;
8119    if (n2 instanceof __PRIVATE_ServerTimestampTransform) return {
8120      fieldPath: t2.field.canonicalString(),
8121      setToServerValue: "REQUEST_TIME"
8122    };
8123    if (n2 instanceof __PRIVATE_ArrayUnionTransformOperation) return {
8124      fieldPath: t2.field.canonicalString(),
8125      appendMissingElements: {
8126        values: n2.elements
8127      }
8128    };
8129    if (n2 instanceof __PRIVATE_ArrayRemoveTransformOperation) return {
8130      fieldPath: t2.field.canonicalString(),
8131      removeAllFromArray: {
8132        values: n2.elements
8133      }
8134    };
8135    if (n2 instanceof __PRIVATE_NumericIncrementTransformOperation) return {
8136      fieldPath: t2.field.canonicalString(),
8137      increment: n2.Ee
8138    };
8139    throw fail(20930, {
8140      transform: t2.transform
8141    });
8142  }(0, e2))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e2, t2) {
8143    return void 0 !== t2.updateTime ? {
8144      updateTime: __PRIVATE_toVersion(e2, t2.updateTime)
8145    } : void 0 !== t2.exists ? {
8146      exists: t2.exists
8147    } : fail(27497);
8148  }(e, t.precondition)), n;
8149}
8150function __PRIVATE_fromMutation(e, t) {
8151  const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e2) {
8152    return void 0 !== e2.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e2.updateTime)) : void 0 !== e2.exists ? Precondition.exists(e2.exists) : Precondition.none();
8153  }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t2) => function __PRIVATE_fromFieldTransform(e2, t3) {
8154    let n2 = null;
8155    if ("setToServerValue" in t3) __PRIVATE_hardAssert("REQUEST_TIME" === t3.setToServerValue, 16630, {
8156      proto: t3
8157    }), n2 = new __PRIVATE_ServerTimestampTransform();
8158    else if ("appendMissingElements" in t3) {
8159      const e3 = t3.appendMissingElements.values || [];
8160      n2 = new __PRIVATE_ArrayUnionTransformOperation(e3);
8161    } else if ("removeAllFromArray" in t3) {
8162      const e3 = t3.removeAllFromArray.values || [];
8163      n2 = new __PRIVATE_ArrayRemoveTransformOperation(e3);
8164    } else "increment" in t3 ? n2 = new __PRIVATE_NumericIncrementTransformOperation(e2, t3.increment) : fail(16584, {
8165      proto: t3
8166    });
8167    const r2 = FieldPath$1.fromServerFormat(t3.fieldPath);
8168    return new FieldTransform(r2, n2);
8169  }(e, t2)) : [];
8170  if (t.update) {
8171    t.update.name;
8172    const i = fromName(e, t.update.name), s = new ObjectValue({
8173      mapValue: {
8174        fields: t.update.fields
8175      }
8176    });
8177    if (t.updateMask) {
8178      const e2 = function __PRIVATE_fromDocumentMask(e3) {
8179        const t2 = e3.fieldPaths || [];
8180        return new FieldMask(t2.map((e4) => FieldPath$1.fromServerFormat(e4)));
8181      }(t.updateMask);
8182      return new __PRIVATE_PatchMutation(i, s, e2, n, r);
8183    }
8184    return new __PRIVATE_SetMutation(i, s, n, r);
8185  }
8186  if (t.delete) {
8187    const r2 = fromName(e, t.delete);
8188    return new __PRIVATE_DeleteMutation(r2, n);
8189  }
8190  if (t.verify) {
8191    const r2 = fromName(e, t.verify);
8192    return new __PRIVATE_VerifyMutation(r2, n);
8193  }
8194  return fail(1463, {
8195    proto: t
8196  });
8197}
8198function __PRIVATE_fromWriteResults(e, t) {
8199  return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t, 14353), e.map((e2) => function __PRIVATE_fromWriteResult(e3, t2) {
8200    let n = e3.updateTime ? __PRIVATE_fromVersion(e3.updateTime) : __PRIVATE_fromVersion(t2);
8201    return n.isEqual(SnapshotVersion.min()) && // The Firestore Emulator currently returns an update time of 0 for
8202    // deletes of non-existing documents (rather than null). This breaks the
8203    // test "get deleted doc while offline with source=cache" as NoDocuments
8204    // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
8205    // TODO(#2149): Remove this when Emulator is fixed
8206    (n = __PRIVATE_fromVersion(t2)), new MutationResult(n, e3.transformResults || []);
8207  }(e2, t))) : [];
8208}
8209function __PRIVATE_toDocumentsTarget(e, t) {
8210  return {
8211    documents: [__PRIVATE_toQueryPath(e, t.path)]
8212  };
8213}
8214function __PRIVATE_toQueryTarget(e, t) {
8215  const n = {
8216    structuredQuery: {}
8217  }, r = t.path;
8218  let i;
8219  null !== t.collectionGroup ? (i = r, n.structuredQuery.from = [{
8220    collectionId: t.collectionGroup,
8221    allDescendants: true
8222  }]) : (i = r.popLast(), n.structuredQuery.from = [{
8223    collectionId: r.lastSegment()
8224  }]), n.parent = __PRIVATE_toQueryPath(e, i);
8225  const s = function __PRIVATE_toFilters(e2) {
8226    if (0 === e2.length) return;
8227    return __PRIVATE_toFilter(CompositeFilter.create(
8228      e2,
8229      "and"
8230      /* CompositeOperator.AND */
8231    ));
8232  }(t.filters);
8233  s && (n.structuredQuery.where = s);
8234  const o = function __PRIVATE_toOrder(e2) {
8235    if (0 === e2.length) return;
8236    return e2.map((e3) => (
8237      // visible for testing
8238      function __PRIVATE_toPropertyOrder(e4) {
8239        return {
8240          field: __PRIVATE_toFieldPathReference(e4.field),
8241          direction: __PRIVATE_toDirection(e4.dir)
8242        };
8243      }(e3)
8244    ));
8245  }(t.orderBy);
8246  o && (n.structuredQuery.orderBy = o);
8247  const _ = __PRIVATE_toInt32Proto(e, t.limit);
8248  return null !== _ && (n.structuredQuery.limit = _), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e2) {
8249    return {
8250      before: e2.inclusive,
8251      values: e2.position
8252    };
8253  }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e2) {
8254    return {
8255      before: !e2.inclusive,
8256      values: e2.position
8257    };
8258  }(t.endAt)), {
8259    Vt: n,
8260    parent: i
8261  };
8262}
8263function __PRIVATE_toRunAggregationQueryRequest(e, t, n, r) {
8264  const { Vt: i, parent: s } = __PRIVATE_toQueryTarget(e, t), o = {}, _ = [];
8265  let a = 0;
8266  return n.forEach((e2) => {
8267    const t2 = r ? e2.alias : "aggregate_" + a++;
8268    o[t2] = e2.alias, "count" === e2.aggregateType ? _.push({
8269      alias: t2,
8270      count: {}
8271    }) : "avg" === e2.aggregateType ? _.push({
8272      alias: t2,
8273      avg: {
8274        field: __PRIVATE_toFieldPathReference(e2.fieldPath)
8275      }
8276    }) : "sum" === e2.aggregateType && _.push({
8277      alias: t2,
8278      sum: {
8279        field: __PRIVATE_toFieldPathReference(e2.fieldPath)
8280      }
8281    });
8282  }), {
8283    request: {
8284      structuredAggregationQuery: {
8285        aggregations: _,
8286        structuredQuery: i.structuredQuery
8287      },
8288      parent: i.parent
8289    },
8290    ft: o,
8291    parent: s
8292  };
8293}
8294function __PRIVATE_convertQueryTargetToQuery(e) {
8295  let t = __PRIVATE_fromQueryPath(e.parent);
8296  const n = e.structuredQuery, r = n.from ? n.from.length : 0;
8297  let i = null;
8298  if (r > 0) {
8299    __PRIVATE_hardAssert(1 === r, 65062);
8300    const e2 = n.from[0];
8301    e2.allDescendants ? i = e2.collectionId : t = t.child(e2.collectionId);
8302  }
8303  let s = [];
8304  n.where && (s = function __PRIVATE_fromFilters(e2) {
8305    const t2 = __PRIVATE_fromFilter(e2);
8306    if (t2 instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t2)) return t2.getFilters();
8307    return [t2];
8308  }(n.where));
8309  let o = [];
8310  n.orderBy && (o = function __PRIVATE_fromOrder(e2) {
8311    return e2.map((e3) => function __PRIVATE_fromPropertyOrder(e4) {
8312      return new OrderBy(
8313        __PRIVATE_fromFieldPathReference(e4.field),
8314        // visible for testing
8315        function __PRIVATE_fromDirection(e5) {
8316          switch (e5) {
8317            case "ASCENDING":
8318              return "asc";
8319            case "DESCENDING":
8320              return "desc";
8321            default:
8322              return;
8323          }
8324        }(e4.direction)
8325      );
8326    }(e3));
8327  }(n.orderBy));
8328  let _ = null;
8329  n.limit && (_ = function __PRIVATE_fromInt32Proto(e2) {
8330    let t2;
8331    return t2 = "object" == typeof e2 ? e2.value : e2, __PRIVATE_isNullOrUndefined(t2) ? null : t2;
8332  }(n.limit));
8333  let a = null;
8334  n.startAt && (a = function __PRIVATE_fromStartAtCursor(e2) {
8335    const t2 = !!e2.before, n2 = e2.values || [];
8336    return new Bound(n2, t2);
8337  }(n.startAt));
8338  let u = null;
8339  return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e2) {
8340    const t2 = !e2.before, n2 = e2.values || [];
8341    return new Bound(n2, t2);
8342  }(n.endAt)), __PRIVATE_newQuery(t, i, o, s, _, "F", a, u);
8343}
8344function __PRIVATE_toListenRequestLabels(e, t) {
8345  const n = function __PRIVATE_toLabel(e2) {
8346    switch (e2) {
8347      case "TargetPurposeListen":
8348        return null;
8349      case "TargetPurposeExistenceFilterMismatch":
8350        return "existence-filter-mismatch";
8351      case "TargetPurposeExistenceFilterMismatchBloom":
8352        return "existence-filter-mismatch-bloom";
8353      case "TargetPurposeLimboResolution":
8354        return "limbo-document";
8355      default:
8356        return fail(28987, {
8357          purpose: e2
8358        });
8359    }
8360  }(t.purpose);
8361  return null == n ? null : {
8362    "goog-listen-tags": n
8363  };
8364}
8365function __PRIVATE_fromFilter(e) {
8366  return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e2) {
8367    switch (e2.unaryFilter.op) {
8368      case "IS_NAN":
8369        const t = __PRIVATE_fromFieldPathReference(e2.unaryFilter.field);
8370        return FieldFilter.create(t, "==", {
8371          doubleValue: NaN
8372        });
8373      case "IS_NULL":
8374        const n = __PRIVATE_fromFieldPathReference(e2.unaryFilter.field);
8375        return FieldFilter.create(n, "==", {
8376          nullValue: "NULL_VALUE"
8377        });
8378      case "IS_NOT_NAN":
8379        const r = __PRIVATE_fromFieldPathReference(e2.unaryFilter.field);
8380        return FieldFilter.create(r, "!=", {
8381          doubleValue: NaN
8382        });
8383      case "IS_NOT_NULL":
8384        const i = __PRIVATE_fromFieldPathReference(e2.unaryFilter.field);
8385        return FieldFilter.create(i, "!=", {
8386          nullValue: "NULL_VALUE"
8387        });
8388      case "OPERATOR_UNSPECIFIED":
8389        return fail(61313);
8390      default:
8391        return fail(60726);
8392    }
8393  }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e2) {
8394    return FieldFilter.create(__PRIVATE_fromFieldPathReference(e2.fieldFilter.field), function __PRIVATE_fromOperatorName(e3) {
8395      switch (e3) {
8396        case "EQUAL":
8397          return "==";
8398        case "NOT_EQUAL":
8399          return "!=";
8400        case "GREATER_THAN":
8401          return ">";
8402        case "GREATER_THAN_OR_EQUAL":
8403          return ">=";
8404        case "LESS_THAN":
8405          return "<";
8406        case "LESS_THAN_OR_EQUAL":
8407          return "<=";
8408        case "ARRAY_CONTAINS":
8409          return "array-contains";
8410        case "IN":
8411          return "in";
8412        case "NOT_IN":
8413          return "not-in";
8414        case "ARRAY_CONTAINS_ANY":
8415          return "array-contains-any";
8416        case "OPERATOR_UNSPECIFIED":
8417          return fail(58110);
8418        default:
8419          return fail(50506);
8420      }
8421    }(e2.fieldFilter.op), e2.fieldFilter.value);
8422  }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e2) {
8423    return CompositeFilter.create(e2.compositeFilter.filters.map((e3) => __PRIVATE_fromFilter(e3)), function __PRIVATE_fromCompositeOperatorName(e3) {
8424      switch (e3) {
8425        case "AND":
8426          return "and";
8427        case "OR":
8428          return "or";
8429        default:
8430          return fail(1026);
8431      }
8432    }(e2.compositeFilter.op));
8433  }(e) : fail(30097, {
8434    filter: e
8435  });
8436}
8437function __PRIVATE_toDirection(e) {
8438  return wt[e];
8439}
8440function __PRIVATE_toOperatorName(e) {
8441  return St[e];
8442}
8443function __PRIVATE_toCompositeOperatorName(e) {
8444  return bt[e];
8445}
8446function __PRIVATE_toFieldPathReference(e) {
8447  return {
8448    fieldPath: e.canonicalString()
8449  };
8450}
8451function __PRIVATE_fromFieldPathReference(e) {
8452  return FieldPath$1.fromServerFormat(e.fieldPath);
8453}
8454function __PRIVATE_toFilter(e) {
8455  return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e2) {
8456    if ("==" === e2.op) {
8457      if (__PRIVATE_isNanValue(e2.value)) return {
8458        unaryFilter: {
8459          field: __PRIVATE_toFieldPathReference(e2.field),
8460          op: "IS_NAN"
8461        }
8462      };
8463      if (__PRIVATE_isNullValue(e2.value)) return {
8464        unaryFilter: {
8465          field: __PRIVATE_toFieldPathReference(e2.field),
8466          op: "IS_NULL"
8467        }
8468      };
8469    } else if ("!=" === e2.op) {
8470      if (__PRIVATE_isNanValue(e2.value)) return {
8471        unaryFilter: {
8472          field: __PRIVATE_toFieldPathReference(e2.field),
8473          op: "IS_NOT_NAN"
8474        }
8475      };
8476      if (__PRIVATE_isNullValue(e2.value)) return {
8477        unaryFilter: {
8478          field: __PRIVATE_toFieldPathReference(e2.field),
8479          op: "IS_NOT_NULL"
8480        }
8481      };
8482    }
8483    return {
8484      fieldFilter: {
8485        field: __PRIVATE_toFieldPathReference(e2.field),
8486        op: __PRIVATE_toOperatorName(e2.op),
8487        value: e2.value
8488      }
8489    };
8490  }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e2) {
8491    const t = e2.getFilters().map((e3) => __PRIVATE_toFilter(e3));
8492    if (1 === t.length) return t[0];
8493    return {
8494      compositeFilter: {
8495        op: __PRIVATE_toCompositeOperatorName(e2.op),
8496        filters: t
8497      }
8498    };
8499  }(e) : fail(54877, {
8500    filter: e
8501  });
8502}
8503function __PRIVATE_toDocumentMask(e) {
8504  const t = [];
8505  return e.fields.forEach((e2) => t.push(e2.canonicalString())), {
8506    fieldPaths: t
8507  };
8508}
8509function __PRIVATE_isValidResourceName(e) {
8510  return e.length >= 4 && "projects" === e.get(0) && "databases" === e.get(2);
8511}
8512/**
8513 * @license
8514 * Copyright 2017 Google LLC
8515 *
8516 * Licensed under the Apache License, Version 2.0 (the "License");
8517 * you may not use this file except in compliance with the License.
8518 * You may obtain a copy of the License at
8519 *
8520 *   http://www.apache.org/licenses/LICENSE-2.0
8521 *
8522 * Unless required by applicable law or agreed to in writing, software
8523 * distributed under the License is distributed on an "AS IS" BASIS,
8524 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8525 * See the License for the specific language governing permissions and
8526 * limitations under the License.
8527 */
8528class TargetData {
8529  constructor(e, t, n, r, i = SnapshotVersion.min(), s = SnapshotVersion.min(), o = ByteString.EMPTY_BYTE_STRING, _ = null) {
8530    this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, this.lastLimboFreeSnapshotVersion = s, this.resumeToken = o, this.expectedCount = _;
8531  }
8532  /** Creates a new target data instance with an updated sequence number. */
8533  withSequenceNumber(e) {
8534    return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);
8535  }
8536  /**
8537   * Creates a new target data instance with an updated resume token and
8538   * snapshot version.
8539   */
8540  withResumeToken(e, t) {
8541    return new TargetData(
8542      this.target,
8543      this.targetId,
8544      this.purpose,
8545      this.sequenceNumber,
8546      t,
8547      this.lastLimboFreeSnapshotVersion,
8548      e,
8549      /* expectedCount= */
8550      null
8551    );
8552  }
8553  /**
8554   * Creates a new target data instance with an updated expected count.
8555   */
8556  withExpectedCount(e) {
8557    return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e);
8558  }
8559  /**
8560   * Creates a new target data instance with an updated last limbo free
8561   * snapshot version number.
8562   */
8563  withLastLimboFreeSnapshotVersion(e) {
8564    return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount);
8565  }
8566}
8567/**
8568 * @license
8569 * Copyright 2017 Google LLC
8570 *
8571 * Licensed under the Apache License, Version 2.0 (the "License");
8572 * you may not use this file except in compliance with the License.
8573 * You may obtain a copy of the License at
8574 *
8575 *   http://www.apache.org/licenses/LICENSE-2.0
8576 *
8577 * Unless required by applicable law or agreed to in writing, software
8578 * distributed under the License is distributed on an "AS IS" BASIS,
8579 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8580 * See the License for the specific language governing permissions and
8581 * limitations under the License.
8582 */
8583class __PRIVATE_LocalSerializer {
8584  constructor(e) {
8585    this.gt = e;
8586  }
8587}
8588function __PRIVATE_fromDbRemoteDocument(e, t) {
8589  let n;
8590  if (t.document) n = __PRIVATE_fromDocument(e.gt, t.document, !!t.hasCommittedMutations);
8591  else if (t.noDocument) {
8592    const e2 = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime);
8593    n = MutableDocument.newNoDocument(e2, r), t.hasCommittedMutations && n.setHasCommittedMutations();
8594  } else {
8595    if (!t.unknownDocument) return fail(56709);
8596    {
8597      const e2 = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version);
8598      n = MutableDocument.newUnknownDocument(e2, r);
8599    }
8600  }
8601  return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e2) {
8602    const t2 = new Timestamp(e2[0], e2[1]);
8603    return SnapshotVersion.fromTimestamp(t2);
8604  }(t.readTime)), n;
8605}
8606function __PRIVATE_toDbRemoteDocument(e, t) {
8607  const n = t.key, r = {
8608    prefixPath: n.getCollectionPath().popLast().toArray(),
8609    collectionGroup: n.collectionGroup,
8610    documentId: n.path.lastSegment(),
8611    readTime: __PRIVATE_toDbTimestampKey(t.readTime),
8612    hasCommittedMutations: t.hasCommittedMutations
8613  };
8614  if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e2, t2) {
8615    return {
8616      name: __PRIVATE_toName(e2, t2.key),
8617      fields: t2.data.value.mapValue.fields,
8618      updateTime: toTimestamp(e2, t2.version.toTimestamp()),
8619      createTime: toTimestamp(e2, t2.createTime.toTimestamp())
8620    };
8621  }(e.gt, t);
8622  else if (t.isNoDocument()) r.noDocument = {
8623    path: n.path.toArray(),
8624    readTime: __PRIVATE_toDbTimestamp(t.version)
8625  };
8626  else {
8627    if (!t.isUnknownDocument()) return fail(57904, {
8628      document: t
8629    });
8630    r.unknownDocument = {
8631      path: n.path.toArray(),
8632      version: __PRIVATE_toDbTimestamp(t.version)
8633    };
8634  }
8635  return r;
8636}
8637function __PRIVATE_toDbTimestampKey(e) {
8638  const t = e.toTimestamp();
8639  return [t.seconds, t.nanoseconds];
8640}
8641function __PRIVATE_toDbTimestamp(e) {
8642  const t = e.toTimestamp();
8643  return {
8644    seconds: t.seconds,
8645    nanoseconds: t.nanoseconds
8646  };
8647}
8648function __PRIVATE_fromDbTimestamp(e) {
8649  const t = new Timestamp(e.seconds, e.nanoseconds);
8650  return SnapshotVersion.fromTimestamp(t);
8651}
8652function __PRIVATE_fromDbMutationBatch(e, t) {
8653  const n = (t.baseMutations || []).map((t2) => __PRIVATE_fromMutation(e.gt, t2));
8654  for (let e2 = 0; e2 < t.mutations.length - 1; ++e2) {
8655    const n2 = t.mutations[e2];
8656    if (e2 + 1 < t.mutations.length && void 0 !== t.mutations[e2 + 1].transform) {
8657      const r2 = t.mutations[e2 + 1];
8658      n2.updateTransforms = r2.transform.fieldTransforms, t.mutations.splice(e2 + 1, 1), ++e2;
8659    }
8660  }
8661  const r = t.mutations.map((t2) => __PRIVATE_fromMutation(e.gt, t2)), i = Timestamp.fromMillis(t.localWriteTimeMs);
8662  return new MutationBatch(t.batchId, i, n, r);
8663}
8664function __PRIVATE_fromDbTarget(e) {
8665  const t = __PRIVATE_fromDbTimestamp(e.readTime), n = void 0 !== e.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion) : SnapshotVersion.min();
8666  let r;
8667  return r = /**
8668  * A helper function for figuring out what kind of query has been stored.
8669  */
8670  function __PRIVATE_isDocumentQuery(e2) {
8671    return void 0 !== e2.documents;
8672  }(e.query) ? function __PRIVATE_fromDocumentsTarget(e2) {
8673    const t2 = e2.documents.length;
8674    return __PRIVATE_hardAssert(1 === t2, 1966, {
8675      count: t2
8676    }), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e2.documents[0])));
8677  }(e.query) : function __PRIVATE_fromQueryTarget(e2) {
8678    return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetTo
8678Query(e2));
8679  }(e.query), new TargetData(r, e.targetId, "TargetPurposeListen", e.lastListenSequenceNumber, t, n, ByteString.fromBase64String(e.resumeToken));
8680}
8681function __PRIVATE_toDbTarget(e, t) {
8682  const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion);
8683  let i;
8684  i = __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.gt, t.target) : __PRIVATE_toQueryTarget(e.gt, t.target).Vt;
8685  const s = t.resumeToken.toBase64();
8686  return {
8687    targetId: t.targetId,
8688    canonicalId: __PRIVATE_canonifyTarget(t.target),
8689    readTime: n,
8690    resumeToken: s,
8691    lastListenSequenceNumber: t.sequenceNumber,
8692    lastLimboFreeSnapshotVersion: r,
8693    query: i
8694  };
8695}
8696function __PRIVATE_fromBundledQuery(e) {
8697  const t = __PRIVATE_convertQueryTargetToQuery({
8698    parent: e.parent,
8699    structuredQuery: e.structuredQuery
8700  });
8701  return "LAST" === e.limitType ? __PRIVATE_queryWithLimit(
8702    t,
8703    t.limit,
8704    "L"
8705    /* LimitType.Last */
8706  ) : t;
8707}
8708function __PRIVATE_fromDbDocumentOverlay(e, t) {
8709  return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.gt, t.overlayMutation));
8710}
8711function __PRIVATE_toDbDocumentOverlayKey(e, t) {
8712  const n = t.path.lastSegment();
8713  return [e, __PRIVATE_encodeResourcePath(t.path.popLast()), n];
8714}
8715function __PRIVATE_toDbIndexState(e, t, n, r) {
8716  return {
8717    indexId: e,
8718    uid: t,
8719    sequenceNumber: n,
8720    readTime: __PRIVATE_toDbTimestamp(r.readTime),
8721    documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path),
8722    largestBatchId: r.largestBatchId
8723  };
8724}
8725/**
8726 * @license
8727 * Copyright 2020 Google LLC
8728 *
8729 * Licensed under the Apache License, Version 2.0 (the "License");
8730 * you may not use this file except in compliance with the License.
8731 * You may obtain a copy of the License at
8732 *
8733 *   http://www.apache.org/licenses/LICENSE-2.0
8734 *
8735 * Unless required by applicable law or agreed to in writing, software
8736 * distributed under the License is distributed on an "AS IS" BASIS,
8737 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8738 * See the License for the specific language governing permissions and
8739 * limitations under the License.
8740 */
8741class __PRIVATE_IndexedDbBundleCache {
8742  getBundleMetadata(e, t) {
8743    return __PRIVATE_bundlesStore(e).get(t).next((e2) => {
8744      if (e2) return function __PRIVATE_fromDbBundle(e3) {
8745        return {
8746          id: e3.bundleId,
8747          createTime: __PRIVATE_fromDbTimestamp(e3.createTime),
8748          version: e3.version
8749        };
8750      }(e2);
8751    });
8752  }
8753  saveBundleMetadata(e, t) {
8754    return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e2) {
8755      return {
8756        bundleId: e2.id,
8757        createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e2.createTime)),
8758        version: e2.version
8759      };
8760    }(t));
8761  }
8762  getNamedQuery(e, t) {
8763    return __PRIVATE_namedQueriesStore(e).get(t).next((e2) => {
8764      if (e2) return function __PRIVATE_fromDbNamedQuery(e3) {
8765        return {
8766          name: e3.name,
8767          query: __PRIVATE_fromBundledQuery(e3.bundledQuery),
8768          readTime: __PRIVATE_fromDbTimestamp(e3.readTime)
8769        };
8770      }(e2);
8771    });
8772  }
8773  saveNamedQuery(e, t) {
8774    return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e2) {
8775      return {
8776        name: e2.name,
8777        readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e2.readTime)),
8778        bundledQuery: e2.bundledQuery
8779      };
8780    }(t));
8781  }
8782}
8783function __PRIVATE_bundlesStore(e) {
8784  return __PRIVATE_getStore(e, we);
8785}
8786function __PRIVATE_namedQueriesStore(e) {
8787  return __PRIVATE_getStore(e, be);
8788}
8789/**
8790 * @license
8791 * Copyright 2022 Google LLC
8792 *
8793 * Licensed under the Apache License, Version 2.0 (the "License");
8794 * you may not use this file except in compliance with the License.
8795 * You may obtain a copy of the License at
8796 *
8797 *   http://www.apache.org/licenses/LICENSE-2.0
8798 *
8799 * Unless required by applicable law or agreed to in writing, software
8800 * distributed under the License is distributed on an "AS IS" BASIS,
8801 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8802 * See the License for the specific language governing permissions and
8803 * limitations under the License.
8804 */
8805class __PRIVATE_IndexedDbDocumentOverlayCache {
8806  /**
8807   * @param serializer - The document serializer.
8808   * @param userId - The userId for which we are accessing overlays.
8809   */
8810  constructor(e, t) {
8811    this.serializer = e, this.userId = t;
8812  }
8813  static yt(e, t) {
8814    const n = t.uid || "";
8815    return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n);
8816  }
8817  getOverlay(e, t) {
8818    return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e2) => e2 ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e2) : null);
8819  }
8820  getOverlays(e, t) {
8821    const n = __PRIVATE_newOverlayMap();
8822    return PersistencePromise.forEach(t, (t2) => this.getOverlay(e, t2).next((e2) => {
8823      null !== e2 && n.set(t2, e2);
8824    })).next(() => n);
8825  }
8826  saveOverlays(e, t, n) {
8827    const r = [];
8828    return n.forEach((n2, i) => {
8829      const s = new Overlay(t, i);
8830      r.push(this.wt(e, s));
8831    }), PersistencePromise.waitFor(r);
8832  }
8833  removeOverlaysForBatchId(e, t, n) {
8834    const r = /* @__PURE__ */ new Set();
8835    t.forEach((e2) => r.add(__PRIVATE_encodeResourcePath(e2.getCollectionPath())));
8836    const i = [];
8837    return r.forEach((t2) => {
8838      const r2 = IDBKeyRange.bound(
8839        [this.userId, t2, n],
8840        [this.userId, t2, n + 1],
8841        /*lowerOpen=*/
8842        false,
8843        /*upperOpen=*/
8844        true
8845      );
8846      i.push(__PRIVATE_documentOverlayStore(e).Y(Ke, r2));
8847    }), PersistencePromise.waitFor(i);
8848  }
8849  getOverlaysForCollection(e, t, n) {
8850    const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound(
8851      [this.userId, i, n],
8852      [this.userId, i, Number.POSITIVE_INFINITY],
8853      /*lowerOpen=*/
8854      true
8855    );
8856    return __PRIVATE_documentOverlayStore(e).j(Ke, s).next((e2) => {
8857      for (const t2 of e2) {
8858        const e3 = __PRIVATE_fromDbDocumentOverlay(this.serializer, t2);
8859        r.set(e3.getKey(), e3);
8860      }
8861      return r;
8862    });
8863  }
8864  getOverlaysForCollectionGroup(e, t, n, r) {
8865    const i = __PRIVATE_newOverlayMap();
8866    let s;
8867    const o = IDBKeyRange.bound(
8868      [this.userId, t, n],
8869      [this.userId, t, Number.POSITIVE_INFINITY],
8870      /*lowerOpen=*/
8871      true
8872    );
8873    return __PRIVATE_documentOverlayStore(e).X({
8874      index: Ge,
8875      range: o
8876    }, (e2, t2, n2) => {
8877      const o2 = __PRIVATE_fromDbDocumentOverlay(this.serializer, t2);
8878      i.size() < r || o2.largestBatchId === s ? (i.set(o2.getKey(), o2), s = o2.largestBatchId) : n2.done();
8879    }).next(() => i);
8880  }
8881  wt(e, t) {
8882    return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e2, t2, n) {
8883      const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t2, n.mutation.key);
8884      return {
8885        userId: t2,
8886        collectionPath: i,
8887        documentId: s,
8888        collectionGroup: n.mutation.key.getCollectionGroup(),
8889        largestBatchId: n.largestBatchId,
8890        overlayMutation: toMutation(e2.gt, n.mutation)
8891      };
8892    }(this.serializer, this.userId, t));
8893  }
8894}
8895function __PRIVATE_documentOverlayStore(e) {
8896  return __PRIVATE_getStore(e, $e);
8897}
8898/**
8899 * @license
8900 * Copyright 2024 Google LLC
8901 *
8902 * Licensed under the Apache License, Version 2.0 (the "License");
8903 * you may not use this file except in compliance with the License.
8904 * You may obtain a copy of the License at
8905 *
8906 *   http://www.apache.org/licenses/LICENSE-2.0
8907 *
8908 * Unless required by applicable law or agreed to in writing, software
8909 * distributed under the License is distributed on an "AS IS" BASIS,
8910 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8911 * See the License for the specific language governing permissions and
8912 * limitations under the License.
8913 */
8914class __PRIVATE_IndexedDbGlobalsCache {
8915  St(e) {
8916    return __PRIVATE_getStore(e, je);
8917  }
8918  getSessionToken(e) {
8919    return this.St(e).get("sessionToken").next((e2) => {
8920      const t = null == e2 ? void 0 : e2.value;
8921      return t ? ByteString.fromUint8Array(t) : ByteString.EMPTY_BYTE_STRING;
8922    });
8923  }
8924  setSessionToken(e, t) {
8925    return this.St(e).put({
8926      name: "sessionToken",
8927      value: t.toUint8Array()
8928    });
8929  }
8930}
8931/**
8932 * @license
8933 * Copyright 2021 Google LLC
8934 *
8935 * Licensed under the Apache License, Version 2.0 (the "License");
8936 * you may not use this file except in compliance with the License.
8937 * You may obtain a copy of the License at
8938 *
8939 *   http://www.apache.org/licenses/LICENSE-2.0
8940 *
8941 * Unless required by applicable law or agreed to in writing, software
8942 * distributed under the License is distributed on an "AS IS" BASIS,
8943 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8944 * See the License for the specific language governing permissions and
8945 * limitations under the License.
8946 */
8947class __PRIVATE_FirestoreIndexValueWriter {
8948  constructor() {
8949  }
8950  // The write methods below short-circuit writing terminators for values
8951  // containing a (terminating) truncated value.
8952  // As an example, consider the resulting encoding for:
8953  // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
8954  // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
8955  // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
8956  /** Writes an index value.  */
8957  bt(e, t) {
8958    this.Dt(e, t), // Write separator to split index values
8959    // (see go/firestore-storage-format#encodings).
8960    t.vt();
8961  }
8962  Dt(e, t) {
8963    if ("nullValue" in e) this.Ct(t, 5);
8964    else if ("booleanValue" in e) this.Ct(t, 10), t.Ft(e.booleanValue ? 1 : 0);
8965    else if ("integerValue" in e) this.Ct(t, 15), t.Ft(__PRIVATE_normalizeNumber(e.integerValue));
8966    else if ("doubleValue" in e) {
8967      const n = __PRIVATE_normalizeNumber(e.doubleValue);
8968      isNaN(n) ? this.Ct(t, 13) : (this.Ct(t, 15), __PRIVATE_isNegativeZero(n) ? (
8969        // -0.0, 0 and 0.0 are all considered the same
8970        t.Ft(0)
8971      ) : t.Ft(n));
8972    } else if ("timestampValue" in e) {
8973      let n = e.timestampValue;
8974      this.Ct(t, 20), "string" == typeof n && (n = __PRIVATE_normalizeTimestamp(n)), t.Mt(`${n.seconds || ""}`), t.Ft(n.nanos || 0);
8975    } else if ("stringValue" in e) this.xt(e.stringValue, t), this.Ot(t);
8976    else if ("bytesValue" in e) this.Ct(t, 30), t.Nt(__PRIVATE_normalizeByteString(e.bytesValue)), this.Ot(t);
8977    else if ("referenceValue" in e) this.Bt(e.referenceValue, t);
8978    else if ("geoPointValue" in e) {
8979      const n = e.geoPointValue;
8980      this.Ct(t, 45), t.Ft(n.latitude || 0), t.Ft(n.longitude || 0);
8981    } else "mapValue" in e ? __PRIVATE_isMaxValue(e) ? this.Ct(t, Number.MAX_SAFE_INTEGER) : __PRIVATE_isVectorValue(e) ? this.Lt(e.mapValue, t) : (this.kt(e.mapValue, t), this.Ot(t)) : "arrayValue" in e ? (this.qt(e.arrayValue, t), this.Ot(t)) : fail(19022, {
8982      Qt: e
8983    });
8984  }
8985  xt(e, t) {
8986    this.Ct(t, 25), this.$t(e, t);
8987  }
8988  $t(e, t) {
8989    t.Mt(e);
8990  }
8991  kt(e, t) {
8992    const n = e.fields || {};
8993    this.Ct(t, 55);
8994    for (const e2 of Object.keys(n)) this.xt(e2, t), this.Dt(n[e2], t);
8995  }
8996  Lt(e, t) {
8997    var n, r;
8998    const i = e.fields || {};
8999    this.Ct(t, 53);
9000    const s = Tt, o = (null === (r = null === (n = i[s].arrayValue) || void 0 === n ? void 0 : n.values) || void 0 === r ? void 0 : r.length) || 0;
9001    this.Ct(t, 15), t.Ft(__PRIVATE_normalizeNumber(o)), // Vectors then sort by position value
9002    this.xt(s, t), this.Dt(i[s], t);
9003  }
9004  qt(e, t) {
9005    const n = e.values || [];
9006    this.Ct(t, 50);
9007    for (const e2 of n) this.Dt(e2, t);
9008  }
9009  Bt(e, t) {
9010    this.Ct(t, 37);
9011    DocumentKey.fromName(e).path.forEach((e2) => {
9012      this.Ct(t, 60), this.$t(e2, t);
9013    });
9014  }
9015  Ct(e, t) {
9016    e.Ft(t);
9017  }
9018  Ot(e) {
9019    e.Ft(2);
9020  }
9021}
9022__PRIVATE_FirestoreIndexValueWriter.Ut = new __PRIVATE_FirestoreIndexValueWriter();
9023/**
9024 * @license
9025 * Copyright 2021 Google LLC
9026 *
9027 * Licensed under the Apache License, Version 2.0 (the "License");
9028 * you may not use this file except in compliance with the License.
9029 * You may obtain a copy of the License at
9030 *
9031 *   http://www.apache.org/licenses/LICENSE-2.0
9032 *
9033 * Unless required by applicable law | agreed to in writing, software
9034 * distributed under the License is distributed on an "AS IS" BASIS,
9035 * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.
9036 * See the License for the specific language governing permissions and
9037 * limitations under the License.
9038 */
9039const Dt = 255;
9040function __PRIVATE_numberOfLeadingZerosInByte(e) {
9041  if (0 === e) return 8;
9042  let t = 0;
9043  return e >> 4 || // Test if the first four bits are zero.
9044  (t += 4, e <<= 4), e >> 6 || // Test if the first two (or next two) bits are zero.
9045  (t += 2, e <<= 2), e >> 7 || // Test if the remaining bit is zero.
9046  (t += 1), t;
9047}
9048function __PRIVATE_unsignedNumLength(e) {
9049  const t = 64 - function __PRIVATE_numberOfLeadingZeros(e2) {
9050    let t2 = 0;
9051    for (let n = 0; n < 8; ++n) {
9052      const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e2[n]);
9053      if (t2 += r, 8 !== r) break;
9054    }
9055    return t2;
9056  }(e);
9057  return Math.ceil(t / 8);
9058}
9059class __PRIVATE_OrderedCodeWriter {
9060  constructor() {
9061    this.buffer = new Uint8Array(1024), this.position = 0;
9062  }
9063  Kt(e) {
9064    const t = e[Symbol.iterator]();
9065    let n = t.next();
9066    for (; !n.done; ) this.Wt(n.value), n = t.next();
9067    this.Gt();
9068  }
9069  zt(e) {
9070    const t = e[Symbol.iterator]();
9071    let n = t.next();
9072    for (; !n.done; ) this.jt(n.value), n = t.next();
9073    this.Jt();
9074  }
9075  /** Writes utf8 bytes into this byte sequence, ascending. */
9076  Ht(e) {
9077    for (const t of e) {
9078      const e2 = t.charCodeAt(0);
9079      if (e2 < 128) this.Wt(e2);
9080      else if (e2 < 2048) this.Wt(960 | e2 >>> 6), this.Wt(128 | 63 & e2);
9081      else if (t < "\uD800" || "\uDBFF" < t) this.Wt(480 | e2 >>> 12), this.Wt(128 | 63 & e2 >>> 6), this.Wt(128 | 63 & e2);
9082      else {
9083        const e3 = t.codePointAt(0);
9084        this.Wt(240 | e3 >>> 18), this.Wt(128 | 63 & e3 >>> 12), this.Wt(128 | 63 & e3 >>> 6), this.Wt(128 | 63 & e3);
9085      }
9086    }
9087    this.Gt();
9088  }
9089  /** Writes utf8 bytes into this byte sequence, descending */
9090  Yt(e) {
9091    for (const t of e) {
9092      const e2 = t.charCodeAt(0);
9093      if (e2 < 128) this.jt(e2);
9094      else if (e2 < 2048) this.jt(960 | e2 >>> 6), this.jt(128 | 63 & e2);
9095      else if (t < "\uD800" || "\uDBFF" < t) this.jt(480 | e2 >>> 12), this.jt(128 | 63 & e2 >>> 6), this.jt(128 | 63 & e2);
9096      else {
9097        const e3 = t.codePointAt(0);
9098        this.jt(240 | e3 >>> 18), this.jt(128 | 63 & e3 >>> 12), this.jt(128 | 63 & e3 >>> 6), this.jt(128 | 63 & e3);
9099      }
9100    }
9101    this.Jt();
9102  }
9103  Zt(e) {
9104    const t = this.Xt(e), n = __PRIVATE_unsignedNumLength(t);
9105    this.en(1 + n), this.buffer[this.position++] = 255 & n;
9106    for (let e2 = t.length - n; e2 < t.length; ++e2) this.buffer[this.position++] = 255 & t[e2];
9107  }
9108  tn(e) {
9109    const t = this.Xt(e), n = __PRIVATE_unsignedNumLength(t);
9110    this.en(1 + n), this.buffer[this.position++] = ~(255 & n);
9111    for (let e2 = t.length - n; e2 < t.length; ++e2) this.buffer[this.position++] = ~(255 & t[e2]);
9112  }
9113  /**
9114   * Writes the "infinity" byte sequence that sorts after all other byte
9115   * sequences written in ascending order.
9116   */
9117  nn() {
9118    this.rn(Dt), this.rn(255);
9119  }
9120  /**
9121   * Writes the "infinity" byte sequence that sorts before all other byte
9122   * sequences written in descending order.
9123   */
9124  sn() {
9125    this._n(Dt), this._n(255);
9126  }
9127  /**
9128   * Resets the buffer such that it is the same as when it was newly
9129   * constructed.
9130   */
9131  reset() {
9132    this.position = 0;
9133  }
9134  seed(e) {
9135    this.en(e.length), this.buffer.set(e, this.position), this.position += e.length;
9136  }
9137  /** Makes a copy of the encoded bytes in this buffer.  */
9138  an() {
9139    return this.buffer.slice(0, this.position);
9140  }
9141  /**
9142   * Encodes `val` into an encoding so that the order matches the IEEE 754
9143   * floating-point comparison results with the following exceptions:
9144   *   -0.0 < 0.0
9145   *   all non-NaN < NaN
9146   *   NaN = NaN
9147   */
9148  Xt(e) {
9149    const t = (
9150      /** Converts a JavaScript number to a byte array (using big endian encoding). */
9151      function __PRIVATE_doubleToLongBits(e2) {
9152        const t2 = new DataView(new ArrayBuffer(8));
9153        return t2.setFloat64(
9154          0,
9155          e2,
9156          /* littleEndian= */
9157          false
9158        ), new Uint8Array(t2.buffer);
9159      }(e)
9160    ), n = !!(128 & t[0]);
9161    t[0] ^= n ? 255 : 128;
9162    for (let e2 = 1; e2 < t.length; ++e2) t[e2] ^= n ? 255 : 0;
9163    return t;
9164  }
9165  /** Writes a single byte ascending to the buffer. */
9166  Wt(e) {
9167    const t = 255 & e;
9168    0 === t ? (this.rn(0), this.rn(255)) : t === Dt ? (this.rn(Dt), this.rn(0)) : this.rn(t);
9169  }
9170  /** Writes a single byte descending to the buffer.  */
9171  jt(e) {
9172    const t = 255 & e;
9173    0 === t ? (this._n(0), this._n(255)) : t === Dt ? (this._n(Dt), this._n(0)) : this._n(e);
9174  }
9175  Gt() {
9176    this.rn(0), this.rn(1);
9177  }
9178  Jt() {
9179    this._n(0), this._n(1);
9180  }
9181  rn(e) {
9182    this.en(1), this.buffer[this.position++] = e;
9183  }
9184  _n(e) {
9185    this.en(1), this.buffer[this.position++] = ~e;
9186  }
9187  en(e) {
9188    const t = e + this.position;
9189    if (t <= this.buffer.length) return;
9190    let n = 2 * this.buffer.length;
9191    n < t && (n = t);
9192    const r = new Uint8Array(n);
9193    r.set(this.buffer), // copy old data
9194    this.buffer = r;
9195  }
9196}
9197class __PRIVATE_AscendingIndexByteEncoder {
9198  constructor(e) {
9199    this.un = e;
9200  }
9201  Nt(e) {
9202    this.un.Kt(e);
9203  }
9204  Mt(e) {
9205    this.un.Ht(e);
9206  }
9207  Ft(e) {
9208    this.un.Zt(e);
9209  }
9210  vt() {
9211    this.un.nn();
9212  }
9213}
9214class __PRIVATE_DescendingIndexByteEncoder {
9215  constructor(e) {
9216    this.un = e;
9217  }
9218  Nt(e) {
9219    this.un.zt(e);
9220  }
9221  Mt(e) {
9222    this.un.Yt(e);
9223  }
9224  Ft(e) {
9225    this.un.tn(e);
9226  }
9227  vt() {
9228    this.un.sn();
9229  }
9230}
9231class __PRIVATE_IndexByteEncoder {
9232  constructor() {
9233    this.un = new __PRIVATE_OrderedCodeWriter(), this.cn = new __PRIVATE_AscendingIndexByteEncoder(this.un), this.ln = new __PRIVATE_DescendingIndexByteEncoder(this.un);
9234  }
9235  seed(e) {
9236    this.un.seed(e);
9237  }
9238  hn(e) {
9239    return 0 === e ? this.cn : this.ln;
9240  }
9241  an() {
9242    return this.un.an();
9243  }
9244  reset() {
9245    this.un.reset();
9246  }
9247}
9248/**
9249 * @license
9250 * Copyright 2022 Google LLC
9251 *
9252 * Licensed under the Apache License, Version 2.0 (the "License");
9253 * you may not use this file except in compliance with the License.
9254 * You may obtain a copy of the License at
9255 *
9256 *   http://www.apache.org/licenses/LICENSE-2.0
9257 *
9258 * Unless required by applicable law or agreed to in writing, software
9259 * distributed under the License is distributed on an "AS IS" BASIS,
9260 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9261 * See the License for the specific language governing permissions and
9262 * limitations under the License.
9263 */
9264class __PRIVATE_IndexEntry {
9265  constructor(e, t, n, r) {
9266    this.Pn = e, this.Tn = t, this.In = n, this.dn = r;
9267  }
9268  /**
9269   * Returns an IndexEntry entry that sorts immediately after the current
9270   * directional value.
9271   */
9272  En() {
9273    const e = this.dn.length, t = 0 === e || 255 === this.dn[e - 1] ? e + 1 : e, n = new Uint8Array(t);
9274    return n.set(this.dn, 0), t !== e ? n.set([0], this.dn.length) : ++n[n.length - 1], new __PRIVATE_IndexEntry(this.Pn, this.Tn, this.In, n);
9275  }
9276  // Create a representation of the Index Entry as a DbIndexEntry
9277  An(e, t, n) {
9278    return {
9279      indexId: this.Pn,
9280      uid: e,
9281      arrayValue: __PRIVATE_encodeKeySafeBytes(this.In),
9282      directionalValue: __PRIVATE_encodeKeySafeBytes(this.dn),
9283      orderedDocumentKey: __PRIVATE_encodeKeySafeBytes(t),
9284      documentKey: n.path.toArray()
9285    };
9286  }
9287  // Create a representation of the Index Entry as a DbIndexEntryKey
9288  Rn(e, t, n) {
9289    const r = this.An(e, t, n);
9290    return [r.indexId, r.uid, r.arrayValue, r.directionalValue, r.orderedDocumentKey, r.documentKey];
9291  }
9292}
9293function __PRIVATE_indexEntryComparator(e, t) {
9294  let n = e.Pn - t.Pn;
9295  return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.In, t.In), 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.dn, t.dn), 0 !== n ? n : DocumentKey.comparator(e.Tn, t.Tn)));
9296}
9297function __PRIVATE_compareByteArrays(e, t) {
9298  for (let n = 0; n < e.length && n < t.length; ++n) {
9299    const r = e[n] - t[n];
9300    if (0 !== r) return r;
9301  }
9302  return e.length - t.length;
9303}
9304function __PRIVATE_encodeKeySafeBytes(e) {
9305  return isSafariOrWebkit() ? (
9306    /**
9307    * Encodes a Uint8Array into a "sortable byte string".
9308    * A "sortable byte string" sorts in the same order as the Uint8Array.
9309    * This works because JS string comparison sorts strings based on code points.
9310    */
9311    function __PRIVATE_encodeUint8ArrayToSortableString(e2) {
9312      let t = "";
9313      for (let n = 0; n < e2.length; n++) t += String.fromCharCode(e2[n]);
9314      return t;
9315    }(e)
9316  ) : e;
9317}
9318function __PRIVATE_decodeKeySafeBytes(e) {
9319  return "string" != typeof e ? e : function __PRIVATE_decodeSortableStringToUint8Array(e2) {
9320    const t = new Uint8Array(e2.length);
9321    for (let n = 0; n < e2.length; n++) t[n] = e2.charCodeAt(n);
9322    return t;
9323  }(e);
9324}
9325class __PRIVATE_TargetIndexMatcher {
9326  constructor(e) {
9327    this.Vn = new SortedSet((e2, t) => FieldPath$1.comparator(e2.field, t.field)), this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), this.mn = e.orderBy, this.fn = [];
9328    for (const t of e.filters) {
9329      const e2 = t;
9330      e2.isInequality() ? this.Vn = this.Vn.add(e2) : this.fn.push(e2);
9331    }
9332  }
9333  get gn() {
9334    return this.Vn.size > 1;
9335  }
9336  /**
9337   * Returns whether the index can be used to serve the TargetIndexMatcher's
9338   * target.
9339   *
9340   * An index is considered capable of serving the target when:
9341   * - The target uses all index segments for its filters and orderBy clauses.
9342   *   The target can have additional filter and orderBy clauses, but not
9343   *   fewer.
9344   * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
9345   *   have a corresponding `CONTAINS` segment.
9346   * - All directional index segments can be mapped to the target as a series of
9347   *   equality filters, a single inequality filter and a series of orderBy
9348   *   clauses.
9349   * - The segments that represent the equality filters may appear out of order.
9350   * - The optional segment for the inequality filter must appear after all
9351   *   equality segments.
9352   * - The segments that represent that orderBy clause of the target must appear
9353   *   in order after all equality and inequality segments. Single orderBy
9354   *   clauses cannot be skipped, but a continuous orderBy suffix may be
9355   *   omitted.
9356   */
9357  pn(e) {
9358    if (__PRIVATE_hardAssert(e.collectionGroup === this.collectionId, 49279), this.gn)
9359      return false;
vendor: 4,563 bytes, lines 9360-9475
9360    const t = __PRIVATE_fieldIndexGetArraySegment(e);
9361    if (void 0 !== t && !this.yn(t)) return false;
9362    const n = __PRIVATE_fieldIndexGetDirectionalSegments(e);
9363    let r = /* @__PURE__ */ new Set(), i = 0, s = 0;
9364    for (; i < n.length && this.yn(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString());
9365    if (i === n.length) return true;
9366    if (this.Vn.size > 0) {
9367      const e2 = this.Vn.getIterator().getNext();
9368      if (!r.has(e2.field.canonicalString())) {
9369        const t2 = n[i];
9370        if (!this.wn(e2, t2) || !this.Sn(this.mn[s++], t2)) return false;
9371      }
9372      ++i;
9373    }
9374    for (; i < n.length; ++i) {
9375      const e2 = n[i];
9376      if (s >= this.mn.length || !this.Sn(this.mn[s++], e2)) return false;
9377    }
9378    return true;
9379  }
9380  /**
9381   * Returns a full matched field index for this target. Currently multiple
9382   * inequality query is not supported so function returns null.
9383   */
9384  bn() {
9385    if (this.gn) return null;
9386    let e = new SortedSet(FieldPath$1.comparator);
9387    const t = [];
9388    for (const n of this.fn) {
9389      if (n.field.isKeyField()) continue;
9390      if ("array-contains" === n.op || "array-contains-any" === n.op) t.push(new IndexSegment(
9391        n.field,
9392        2
9393        /* IndexKind.CONTAINS */
9394      ));
9395      else {
9396        if (e.has(n.field)) continue;
9397        e = e.add(n.field), t.push(new IndexSegment(
9398          n.field,
9399          0
9400          /* IndexKind.ASCENDING */
9401        ));
9402      }
9403    }
9404    for (const n of this.mn)
9405      n.field.isKeyField() || e.has(n.field) || (e = e.add(n.field), t.push(new IndexSegment(
9406        n.field,
9407        "asc" === n.dir ? 0 : 1
9408        /* IndexKind.DESCENDING */
9409      )));
9410    return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t, IndexState.empty());
9411  }
9412  yn(e) {
9413    for (const t of this.fn) if (this.wn(t, e)) return true;
9414    return false;
9415  }
9416  wn(e, t) {
9417    if (void 0 === e || !e.field.isEqual(t.fieldPath)) return false;
9418    const n = "array-contains" === e.op || "array-contains-any" === e.op;
9419    return 2 === t.kind === n;
9420  }
9421  Sn(e, t) {
9422    return !!e.field.isEqual(t.fieldPath) && (0 === t.kind && "asc" === e.dir || 1 === t.kind && "desc" === e.dir);
9423  }
9424}
9425/**
9426 * @license
9427 * Copyright 2022 Google LLC
9428 *
9429 * Licensed under the Apache License, Version 2.0 (the "License");
9430 * you may not use this file except in compliance with the License.
9431 * You may obtain a copy of the License at
9432 *
9433 *   http://www.apache.org/licenses/LICENSE-2.0
9434 *
9435 * Unless required by applicable law or agreed to in writing, software
9436 * distributed under the License is distributed on an "AS IS" BASIS,
9437 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9438 * See the License for the specific language governing permissions and
9439 * limitations under the License.
9440 */
9441function __PRIVATE_computeInExpansion(e) {
9442  var t, n;
9443  if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 20012), e instanceof FieldFilter) {
9444    if (e instanceof __PRIVATE_InFilter) {
9445      const r2 = (null === (n = null === (t = e.value.arrayValue) || void 0 === t ? void 0 : t.values) || void 0 === n ? void 0 : n.map((t2) => FieldFilter.create(e.field, "==", t2))) || [];
9446      return CompositeFilter.create(
9447        r2,
9448        "or"
9449        /* CompositeOperator.OR */
9450      );
9451    }
9452    return e;
9453  }
9454  const r = e.filters.map((e2) => __PRIVATE_computeInExpansion(e2));
9455  return CompositeFilter.create(r, e.op);
9456}
9457function __PRIVATE_getDnfTerms(e) {
9458  if (0 === e.getFilters().length) return [];
9459  const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e));
9460  return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t), 7391), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [t] : t.getFilters();
9461}
9462function __PRIVATE_isSingleFieldFilter(e) {
9463  return e instanceof FieldFilter;
9464}
9465function __PRIVATE_isFlatConjunction(e) {
9466  return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e);
9467}
9468function __PRIVATE_isDisjunctiveNormalForm(e) {
9469  return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || /**
9470  * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
9471  * field filters. e.g. (a == 10) || (b==20 && c==30)
9472  */
9473  function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e2) {
9474    if (e2 instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e2)) {
9475      for (const t of e2.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return false;
9476      return true;
9477    }
9478    return false;
9479  }(e);
9480}
9481function __PRIVATE_computeDistributedNormalForm(e) {
9482  if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 34018), e instanceof FieldFilter) return e;
9483  if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]);
9484  const t = e.filters.map((e2) => __PRIVATE_computeDistributedNormalForm(e2));
9485  let n = CompositeFilter.create(t, e.op);
9486  return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter, 64498), __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n), 40251), __PRIVATE_hardAssert(n.filters.length > 1, 57927), n.filters.reduce((e2, t2) => __PRIVATE_applyDistribution(e2, t2)));
9487}
9488function __PRIVATE_applyDistribution(e, t) {
9489  let n;
9490  return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 38388), __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter, 25473), // FieldFilter FieldFilter
9491  n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e2, t2) {
9492    return CompositeFilter.create(
9493      [e2, t2],
9494      "and"
9495      /* CompositeOperator.AND */
9496    );
9497  }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e2, t2) {
9498    if (__PRIVATE_hardAssert(e2.filters.length > 0 && t2.filters.length > 0, 48005), __PRIVATE_compositeFilterIsConjunction(e2) && __PRIVATE_compositeFilterIsConjunction(t2)) return __PRIVATE_compositeFilterWithAddedFilters(e2, t2.getFilters());
9499    const n2 = __PRIVATE_compositeFilterIsDisjunction(e2) ? e2 : t2, r = __PRIVATE_compositeFilterIsDisjunction(e2) ? t2 : e2, i = n2.filters.map((e3) => __PRIVATE_applyDistribution(e3, r));
9500    return CompositeFilter.create(
9501      i,
9502      "or"
9503      /* CompositeOperator.OR */
9504    );
9505  }(e, t), __PRIVATE_applyAssociation(n);
9506}
9507function __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) {
9508  if (__PRIVATE_compositeFilterIsConjunction(t))
9509    return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters());
9510  {
9511    const n = t.filters.map((t2) => __PRIVATE_applyDistribution(e, t2));
9512    return CompositeFilter.create(
9513      n,
9514      "or"
9515      /* CompositeOperator.OR */
9516    );
9517  }
9518}
9519function __PRIVATE_applyAssociation(e) {
9520  if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 11850), e instanceof FieldFilter) return e;
9521  const t = e.getFilters();
9522  if (1 === t.length) return __PRIVATE_applyAssociation(t[0]);
9523  if (__PRIVATE_compositeFilterIsFlat(e)) return e;
9524  const n = t.map((e2) => __PRIVATE_applyAssociation(e2)), r = [];
9525  return n.forEach((t2) => {
9526    t2 instanceof FieldFilter ? r.push(t2) : t2 instanceof CompositeFilter && (t2.op === e.op ? (
9527      // compositeFilter: (A | (B | C))
9528      // compositeSubfilter: (B | C)
9529      // Result: (A | B | C)
9530      r.push(...t2.filters)
9531    ) : (
9532      // compositeFilter: (A | (B & C))
9533      // compositeSubfilter: (B & C)
9534      // Result: (A | (B & C))
9535      r.push(t2)
9536    ));
9537  }), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op);
9538}
9539/**
9540 * @license
9541 * Copyright 2019 Google LLC
9542 *
9543 * Licensed under the Apache License, Version 2.0 (the "License");
9544 * you may not use this file except in compliance with the License.
9545 * You may obtain a copy of the License at
9546 *
9547 *   http://www.apache.org/licenses/LICENSE-2.0
9548 *
9549 * Unless required by applicable law or agreed to in writing, software
9550 * distributed under the License is distributed on an "AS IS" BASIS,
9551 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9552 * See the License for the specific language governing permissions and
9553 * limitations under the License.
9554 */
9555class __PRIVATE_MemoryIndexManager {
9556  constructor() {
9557    this.Dn = new __PRIVATE_MemoryCollectionParentIndex();
9558  }
9559  addToCollectionParentIndex(e, t) {
9560    return this.Dn.add(t), PersistencePromise.resolve();
9561  }
9562  getCollectionParents(e, t) {
9563    return PersistencePromise.resolve(this.Dn.getEntries(t));
9564  }
9565  addFieldIndex(e, t) {
9566    return PersistencePromise.resolve();
9567  }
9568  deleteFieldIndex(e, t) {
9569    return PersistencePromise.resolve();
9570  }
9571  deleteAllFieldIndexes(e) {
9572    return PersistencePromise.resolve();
9573  }
9574  createTargetIndexes(e, t) {
9575    return PersistencePromise.resolve();
9576  }
9577  getDocumentsMatchingTarget(e, t) {
9578    return PersistencePromise.resolve(null);
9579  }
9580  getIndexType(e, t) {
9581    return PersistencePromise.resolve(
9582      0
9583      /* IndexType.NONE */
9584    );
9585  }
9586  getFieldIndexes(e, t) {
9587    return PersistencePromise.resolve([]);
9588  }
9589  getNextCollectionGroupToUpdate(e) {
9590    return PersistencePromise.resolve(null);
9591  }
9592  getMinOffset(e, t) {
9593    return PersistencePromise.resolve(IndexOffset.min());
9594  }
9595  getMinOffsetFromCollectionGroup(e, t) {
9596    return PersistencePromise.resolve(IndexOffset.min());
9597  }
9598  updateCollectionGroup(e, t, n) {
9599    return PersistencePromise.resolve();
9600  }
9601  updateIndexEntries(e, t) {
9602    return PersistencePromise.resolve();
9603  }
9604}
9605class __PRIVATE_MemoryCollectionParentIndex {
9606  constructor() {
9607    this.index = {};
9608  }
9609  // Returns false if the entry already existed.
9610  add(e) {
9611    const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n);
9612    return this.index[t] = r.add(n), i;
9613  }
9614  has(e) {
9615    const t = e.lastSegment(), n = e.popLast(), r = this.index[t];
9616    return r && r.has(n);
9617  }
9618  getEntries(e) {
9619    return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray();
9620  }
9621}
9622/**
9623 * @license
9624 * Copyright 2019 Google LLC
9625 *
9626 * Licensed under the Apache License, Version 2.0 (the "License");
9627 * you may not use this file except in compliance with the License.
9628 * You may obtain a copy of the License at
9629 *
9630 *   http://www.apache.org/licenses/LICENSE-2.0
9631 *
9632 * Unless required by applicable law or agreed to in writing, software
9633 * distributed under the License is distributed on an "AS IS" BASIS,
9634 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9635 * See the License for the specific language governing permissions and
9636 * limitations under the License.
9637 */
9638const vt = "IndexedDbIndexManager", Ct = new Uint8Array(0);
9639class __PRIVATE_IndexedDbIndexManager {
9640  constructor(e, t) {
9641    this.databaseId = t, /**
9642    * An in-memory copy of the index entries we've already written since the SDK
9643    * launched. Used to avoid re-writing the same entry repeatedly.
9644    *
9645    * This is *NOT* a complete cache of what's in persistence and so can never be
9646    * used to satisfy reads.
9647    */
9648    this.vn = new __PRIVATE_MemoryCollectionParentIndex(), /**
9649    * Maps from a target to its equivalent list of sub-targets. Each sub-target
9650    * contains only one term from the target's disjunctive normal form (DNF).
9651    */
9652    this.Cn = new ObjectMap((e2) => __PRIVATE_canonifyTarget(e2), (e2, t2) => __PRIVATE_targetEquals(e2, t2)), this.uid = e.uid || "";
9653  }
9654  /**
9655   * Adds a new entry to the collection parent index.
9656   *
9657   * Repeated calls for the same collectionPath should be avoided within a
9658   * transaction as IndexedDbIndexManager only caches writes once a transaction
9659   * has been committed.
9660   */
9661  addToCollectionParentIndex(e, t) {
9662    if (!this.vn.has(t)) {
9663      const n = t.lastSegment(), r = t.popLast();
9664      e.addOnCommittedListener(() => {
9665        this.vn.add(t);
9666      });
9667      const i = {
9668        collectionId: n,
9669        parent: __PRIVATE_encodeResourcePath(r)
9670      };
9671      return __PRIVATE_collectionParentsStore(e).put(i);
9672    }
9673    return PersistencePromise.resolve();
9674  }
9675  getCollectionParents(e, t) {
9676    const n = [], r = IDBKeyRange.bound(
9677      [t, ""],
9678      [__PRIVATE_immediateSuccessor(t), ""],
9679      /*lowerOpen=*/
9680      false,
9681      /*upperOpen=*/
9682      true
9683    );
9684    return __PRIVATE_collectionParentsStore(e).j(r).next((e2) => {
9685      for (const r2 of e2) {
9686        if (r2.collectionId !== t) break;
9687        n.push(__PRIVATE_decodeResourcePath(r2.parent));
9688      }
9689      return n;
9690    });
9691  }
9692  addFieldIndex(e, t) {
9693    const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e2) {
9694      return {
9695        indexId: e2.indexId,
9696        collectionGroup: e2.collectionGroup,
9697        fields: e2.fields.map((e3) => [e3.fieldPath.canonicalString(), e3.kind])
9698      };
9699    }(t);
9700    delete r.indexId;
9701    const i = n.add(r);
9702    if (t.indexState) {
9703      const n2 = __PRIVATE_indexStateStore(e);
9704      return i.next((e2) => {
9705        n2.put(__PRIVATE_toDbIndexState(e2, this.uid, t.indexState.sequenceNumber, t.indexState.offset));
9706      });
9707    }
9708    return i.next();
9709  }
9710  deleteFieldIndex(e, t) {
9711    const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e);
9712    return n.delete(t.indexId).next(() => r.delete(IDBKeyRange.bound(
9713      [t.indexId],
9714      [t.indexId + 1],
9715      /*lowerOpen=*/
9716      false,
9717      /*upperOpen=*/
9718      true
9719    ))).next(() => i.delete(IDBKeyRange.bound(
9720      [t.indexId],
9721      [t.indexId + 1],
9722      /*lowerOpen=*/
9723      false,
9724      /*upperOpen=*/
9725      true
9726    )));
9727  }
9728  deleteAllFieldIndexes(e) {
9729    const t = __PRIVATE_indexConfigurationStore(e), n = __PRIVATE_indexEntriesStore(e), r = __PRIVATE_indexStateStore(e);
9730    return t.Y().next(() => n.Y()).next(() => r.Y());
9731  }
9732  createTargetIndexes(e, t) {
9733    return PersistencePromise.forEach(this.Fn(t), (t2) => this.getIndexType(e, t2).next((n) => {
9734      if (0 === n || 1 === n) {
9735        const n2 = new __PRIVATE_TargetIndexMatcher(t2).bn();
9736        if (null != n2) return this.addFieldIndex(e, n2);
9737      }
9738    }));
9739  }
9740  getDocumentsMatchingTarget(e, t) {
9741    const n = __PRIVATE_indexEntriesStore(e);
9742    let r = true;
9743    const i = /* @__PURE__ */ new Map();
9744    return PersistencePromise.forEach(this.Fn(t), (t2) => this.Mn(e, t2).next((e2) => {
9745      r && (r = !!e2), i.set(t2, e2);
9746    })).next(() => {
9747      if (r) {
9748        let e2 = __PRIVATE_documentKeySet();
9749        const r2 = [];
9750        return PersistencePromise.forEach(i, (i2, s) => {
9751          __PRIVATE_logDebug(vt, `Using index ${function __PRIVATE_fieldIndexToString(e3) {
9752            return `id=${e3.indexId}|cg=${e3.collectionGroup}|f=${e3.fields.map((e4) => `${e4.fieldPath}:${e4.kind}`).join(",")}`;
9753          }(i2)} to execute ${__PRIVATE_canonifyTarget(t)}`);
9754          const o = function __PRIVATE_targetGetArrayValues(e3, t2) {
9755            const n2 = __PRIVATE_fieldIndexGetArraySegment(t2);
9756            if (void 0 === n2) return null;
9757            for (const t3 of __PRIVATE_targetGetFieldFiltersForPath(e3, n2.fieldPath)) switch (t3.op) {
9758              case "array-contains-any":
9759                return t3.value.arrayValue.values || [];
9760              case "array-contains":
9761                return [t3.value];
9762            }
9763            return null;
9764          }(s, i2), _ = function __PRIVATE_targetGetNotInValues(e3, t2) {
9765            const n2 = /* @__PURE__ */ new Map();
9766            for (const r3 of __PRIVATE_fieldIndexGetDirectionalSegments(t2)) for (const t3 of __PRIVATE_targetGetFieldFiltersForPath(e3, r3.fieldPath)) switch (t3.op) {
9767              case "==":
9768              case "in":
9769                n2.set(r3.fieldPath.canonicalString(), t3.value);
9770                break;
9771              case "not-in":
9772              case "!=":
9773                return n2.set(r3.fieldPath.canonicalString(), t3.value), Array.from(n2.values());
9774            }
9775            return null;
9776          }(s, i2), a = function __PRIVATE_targetGetLowerBound(e3, t2) {
9777            const n2 = [];
9778            let r3 = true;
9779            for (const i3 of __PRIVATE_fieldIndexGetDirectionalSegments(t2)) {
9780              const t3 = 0 === i3.kind ? __PRIVATE_targetGetAscendingBound(e3, i3.fieldPath, e3.startAt) : __PRIVATE_targetGetDescendingBound(e3, i3.fieldPath, e3.startAt);
9781              n2.push(t3.value), r3 && (r3 = t3.inclusive);
9782            }
9783            return new Bound(n2, r3);
9784          }(s, i2), u = function __PRIVATE_targetGetUpperBound(e3, t2) {
9785            const n2 = [];
9786            let r3 = true;
9787            for (const i3 of __PRIVATE_fieldIndexGetDirectionalSegments(t2)) {
9788              const t3 = 0 === i3.kind ? __PRIVATE_targetGetDescendingBound(e3, i3.fieldPath, e3.endAt) : __PRIVATE_targetGetAscendingBound(e3, i3.fieldPath, e3.endAt);
9789              n2.push(t3.value), r3 && (r3 = t3.inclusive);
9790            }
9791            return new Bound(n2, r3);
9792          }
9792(s, i2), c = this.xn(i2, s, a), l = this.xn(i2, s, u), h = this.On(i2, s, _), P = this.Nn(i2.indexId, o, c, a.inclusive, l, u.inclusive, h);
9793          return PersistencePromise.forEach(P, (i3) => n.H(i3, t.limit).next((t2) => {
9794            t2.forEach((t3) => {
9795              const n2 = DocumentKey.fromSegments(t3.documentKey);
9796              e2.has(n2) || (e2 = e2.add(n2), r2.push(n2));
9797            });
9798          }));
9799        }).next(() => r2);
9800      }
9801      return PersistencePromise.resolve(null);
9802    });
9803  }
9804  Fn(e) {
9805    let t = this.Cn.get(e);
9806    if (t) return t;
9807    if (0 === e.filters.length) t = [e];
9808    else {
9809      t = __PRIVATE_getDnfTerms(CompositeFilter.create(
9810        e.filters,
9811        "and"
9812        /* CompositeOperator.AND */
9813      )).map((t2) => __PRIVATE_newTarget(e.path, e.collectionGroup, e.orderBy, t2.getFilters(), e.limit, e.startAt, e.endAt));
9814    }
9815    return this.Cn.set(e, t), t;
9816  }
9817  /**
9818   * Constructs a key range query on `DbIndexEntryStore` that unions all
9819   * bounds.
9820   */
9821  Nn(e, t, n, r, i, s, o) {
9822    const _ = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = _ / (null != t ? t.length : 1), u = [];
9823    for (let c = 0; c < _; ++c) {
9824      const _2 = t ? this.Bn(t[c / a]) : Ct, l = this.Ln(e, _2, n[c % a], r), h = this.kn(e, _2, i[c % a], s), P = o.map((t2) => this.Ln(
9825        e,
9826        _2,
9827        t2,
9828        /* inclusive= */
9829        true
9830      ));
9831      u.push(...this.createRange(l, h, P));
9832    }
9833    return u;
9834  }
9835  /** Generates the lower bound for `arrayValue` and `directionalValue`. */
9836  Ln(e, t, n, r) {
9837    const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);
9838    return r ? i : i.En();
9839  }
9840  /** Generates the upper bound for `arrayValue` and `directionalValue`. */
9841  kn(e, t, n, r) {
9842    const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);
9843    return r ? i.En() : i;
9844  }
9845  Mn(e, t) {
9846    const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment();
9847    return this.getFieldIndexes(e, r).next((e2) => {
9848      let t2 = null;
9849      for (const r2 of e2) {
9850        n.pn(r2) && (!t2 || r2.fields.length > t2.fields.length) && (t2 = r2);
9851      }
9852      return t2;
9853    });
9854  }
9855  getIndexType(e, t) {
9856    let n = 2;
9857    const r = this.Fn(t);
9858    return PersistencePromise.forEach(r, (t2) => this.Mn(e, t2).next((e2) => {
9859      e2 ? 0 !== n && e2.fields.length < function __PRIVATE_targetGetSegmentCount(e3) {
9860        let t3 = new SortedSet(FieldPath$1.comparator), n2 = false;
9861        for (const r2 of e3.filters) for (const e4 of r2.getFlattenedFilters())
9862          e4.field.isKeyField() || // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
9863          // For instance, it is possible to have an index for "a ARRAY a ASC". Even
9864          // though these are on the same field, they should be counted as two
9865          // separate segments in an index.
9866          ("array-contains" === e4.op || "array-contains-any" === e4.op ? n2 = true : t3 = t3.add(e4.field));
9867        for (const n3 of e3.orderBy)
9868          n3.field.isKeyField() || (t3 = t3.add(n3.field));
9869        return t3.size + (n2 ? 1 : 0);
9870      }(t2) && (n = 1) : n = 0;
9871    })).next(() => (
9872      // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
9873      // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
9874      // and apply the limit in memory as a post-processing step.
9875      function __PRIVATE_targetHasLimit(e2) {
9876        return null !== e2.limit;
9877      }(t) && r.length > 1 && 2 === n ? 1 : n
9878    ));
9879  }
9880  /**
9881   * Returns the byte encoded form of the directional values in the field index.
9882   * Returns `null` if the document does not have all fields specified in the
9883   * index.
9884   */
9885  qn(e, t) {
9886    const n = new __PRIVATE_IndexByteEncoder();
9887    for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {
9888      const e2 = t.data.field(r.fieldPath);
9889      if (null == e2) return null;
9890      const i = n.hn(r.kind);
9891      __PRIVATE_FirestoreIndexValueWriter.Ut.bt(e2, i);
9892    }
9893    return n.an();
9894  }
9895  /** Encodes a single value to the ascending index format. */
9896  Bn(e) {
9897    const t = new __PRIVATE_IndexByteEncoder();
9898    return __PRIVATE_FirestoreIndexValueWriter.Ut.bt(e, t.hn(
9899      0
9900      /* IndexKind.ASCENDING */
9901    )), t.an();
9902  }
9903  /**
9904   * Returns an encoded form of the document key that sorts based on the key
9905   * ordering of the field index.
9906   */
9907  Qn(e, t) {
9908    const n = new __PRIVATE_IndexByteEncoder();
9909    return __PRIVATE_FirestoreIndexValueWriter.Ut.bt(__PRIVATE_refValue(this.databaseId, t), n.hn(function __PRIVATE_fieldIndexGetKeyOrder(e2) {
9910      const t2 = __PRIVATE_fieldIndexGetDirectionalSegments(e2);
9911      return 0 === t2.length ? 0 : t2[t2.length - 1].kind;
9912    }(e))), n.an();
9913  }
9914  /**
9915   * Encodes the given field values according to the specification in `target`.
9916   * For IN queries, a list of possible values is returned.
9917   */
9918  On(e, t, n) {
9919    if (null === n) return [];
9920    let r = [];
9921    r.push(new __PRIVATE_IndexByteEncoder());
9922    let i = 0;
9923    for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {
9924      const e2 = n[i++];
9925      for (const n2 of r) if (this.$n(t, s.fieldPath) && isArray(e2)) r = this.Un(r, s, e2);
9926      else {
9927        const t2 = n2.hn(s.kind);
9928        __PRIVATE_FirestoreIndexValueWriter.Ut.bt(e2, t2);
9929      }
9930    }
9931    return this.Kn(r);
9932  }
9933  /**
9934   * Encodes the given bounds according to the specification in `target`. For IN
9935   * queries, a list of possible values is returned.
9936   */
9937  xn(e, t, n) {
9938    return this.On(e, t, n.position);
9939  }
9940  /** Returns the byte representation for the provided encoders. */
9941  Kn(e) {
9942    const t = [];
9943    for (let n = 0; n < e.length; ++n) t[n] = e[n].an();
9944    return t;
9945  }
9946  /**
9947   * Creates a separate encoder for each element of an array.
9948   *
9949   * The method appends each value to all existing encoders (e.g. filter("a",
9950   * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
9951   * list of new encoders is returned.
9952   */
9953  Un(e, t, n) {
9954    const r = [...e], i = [];
9955    for (const e2 of n.arrayValue.values || []) for (const n2 of r) {
9956      const r2 = new __PRIVATE_IndexByteEncoder();
9957      r2.seed(n2.an()), __PRIVATE_FirestoreIndexValueWriter.Ut.bt(e2, r2.hn(t.kind)), i.push(r2);
9958    }
9959    return i;
9960  }
9961  $n(e, t) {
9962    return !!e.filters.find((e2) => e2 instanceof FieldFilter && e2.field.isEqual(t) && ("in" === e2.op || "not-in" === e2.op));
9963  }
9964  getFieldIndexes(e, t) {
9965    const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e);
9966    return (t ? n.j(Fe, IDBKeyRange.bound(t, t)) : n.j()).next((e2) => {
9967      const t2 = [];
9968      return PersistencePromise.forEach(e2, (e3) => r.get([e3.indexId, this.uid]).next((n2) => {
9969        t2.push(function __PRIVATE_fromDbIndexConfiguration(e4, t3) {
9970          const n3 = t3 ? new IndexState(t3.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t3.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t3.documentKey)), t3.largestBatchId)) : IndexState.empty(), r2 = e4.fields.map(([e5, t4]) => new IndexSegment(FieldPath$1.fromServerFormat(e5), t4));
9971          return new FieldIndex(e4.indexId, e4.collectionGroup, r2, n3);
9972        }(e3, n2));
9973      })).next(() => t2);
9974    });
9975  }
9976  getNextCollectionGroupToUpdate(e) {
9977    return this.getFieldIndexes(e).next((e2) => 0 === e2.length ? null : (e2.sort((e3, t) => {
9978      const n = e3.indexState.sequenceNumber - t.indexState.sequenceNumber;
9979      return 0 !== n ? n : __PRIVATE_primitiveComparator(e3.collectionGroup, t.collectionGroup);
9980    }), e2[0].collectionGroup));
9981  }
9982  updateCollectionGroup(e, t, n) {
9983    const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e);
9984    return this.Wn(e).next((e2) => r.j(Fe, IDBKeyRange.bound(t, t)).next((t2) => PersistencePromise.forEach(t2, (t3) => i.put(__PRIVATE_toDbIndexState(t3.indexId, this.uid, e2, n)))));
9985  }
9986  updateIndexEntries(e, t) {
9987    const n = /* @__PURE__ */ new Map();
9988    return PersistencePromise.forEach(t, (t2, r) => {
9989      const i = n.get(t2.collectionGroup);
9990      return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t2.collectionGroup)).next((i2) => (n.set(t2.collectionGroup, i2), PersistencePromise.forEach(i2, (n2) => this.Gn(e, t2, n2).next((t3) => {
9991        const i3 = this.zn(r, n2);
9992        return t3.isEqual(i3) ? PersistencePromise.resolve() : this.jn(e, r, n2, t3, i3);
9993      }))));
9994    });
9995  }
9996  Jn(e, t, n, r) {
9997    return __PRIVATE_indexEntriesStore(e).put(r.An(this.uid, this.Qn(n, t.key), t.key));
9998  }
9999  Hn(e, t, n, r) {
10000    return __PRIVATE_indexEntriesStore(e).delete(r.Rn(this.uid, this.Qn(n, t.key), t.key));
10001  }
10002  Gn(e, t, n) {
10003    const r = __PRIVATE_indexEntriesStore(e);
10004    let i = new SortedSet(__PRIVATE_indexEntryComparator);
10005    return r.X({
10006      index: qe,
10007      range: IDBKeyRange.only([n.indexId, this.uid, __PRIVATE_encodeKeySafeBytes(this.Qn(n, t))])
10008    }, (e2, r2) => {
10009      i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, __PRIVATE_decodeKeySafeBytes(r2.arrayValue), __PRIVATE_decodeKeySafeBytes(r2.directionalValue)));
10010    }).next(() => i);
10011  }
10012  /** Creates the index entries for the given document. */
10013  zn(e, t) {
10014    let n = new SortedSet(__PRIVATE_indexEntryComparator);
10015    const r = this.qn(t, e);
10016    if (null == r) return n;
10017    const i = __PRIVATE_fieldIndexGetArraySegment(t);
10018    if (null != i) {
10019      const s = e.data.field(i.fieldPath);
10020      if (isArray(s)) for (const i2 of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this.Bn(i2), r));
10021    } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, Ct, r));
10022    return n;
10023  }
10024  /**
10025   * Updates the index entries for the provided document by deleting entries
10026   * that are no longer referenced in `newEntries` and adding all newly added
10027   * entries.
10028   */
10029  jn(e, t, n, r, i) {
10030    __PRIVATE_logDebug(vt, "Updating index entries for document '%s'", t.key);
10031    const s = [];
10032    return function __PRIVATE_diffSortedSets(e2, t2, n2, r2, i2) {
10033      const s2 = e2.getIterator(), o = t2.getIterator();
10034      let _ = __PRIVATE_advanceIterator(s2), a = __PRIVATE_advanceIterator(o);
10035      for (; _ || a; ) {
10036        let e3 = false, t3 = false;
10037        if (_ && a) {
10038          const r3 = n2(_, a);
10039          r3 < 0 ? (
10040            // The element was removed if the next element in our ordered
10041            // walkthrough is only in `before`.
10042            t3 = true
10043          ) : r3 > 0 && // The element was added if the next element in our ordered walkthrough
10044          // is only in `after`.
10045          (e3 = true);
10046        } else null != _ ? t3 = true : e3 = true;
10047        e3 ? (r2(a), a = __PRIVATE_advanceIterator(o)) : t3 ? (i2(_), _ = __PRIVATE_advanceIterator(s2)) : (_ = __PRIVATE_advanceIterator(s2), a = __PRIVATE_advanceIterator(o));
10048      }
10049    }(
10050      r,
10051      i,
10052      __PRIVATE_indexEntryComparator,
10053      /* onAdd= */
10054      (r2) => {
10055        s.push(this.Jn(e, t, n, r2));
10056      },
10057      /* onRemove= */
10058      (r2) => {
10059        s.push(this.Hn(e, t, n, r2));
10060      }
10061    ), PersistencePromise.waitFor(s);
10062  }
10063  Wn(e) {
10064    let t = 1;
10065    return __PRIVATE_indexStateStore(e).X({
10066      index: Ne,
10067      reverse: true,
10068      range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])
10069    }, (e2, n, r) => {
10070      r.done(), t = n.sequenceNumber + 1;
10071    }).next(() => t);
10072  }
10073  /**
10074   * Returns a new set of IDB ranges that splits the existing range and excludes
10075   * any values that match the `notInValue` from these ranges. As an example,
10076   * '[foo > 2 && foo != 3]` becomes  `[foo > 2 && < 3, foo > 3]`.
10077   */
10078  createRange(e, t, n) {
10079    n = n.sort((e2, t2) => __PRIVATE_indexEntryComparator(e2, t2)).filter((e2, t2, n2) => !t2 || 0 !== __PRIVATE_indexEntryComparator(e2, n2[t2 - 1]));
10080    const r = [];
10081    r.push(e);
10082    for (const i2 of n) {
10083      const n2 = __PRIVATE_indexEntryComparator(i2, e), s = __PRIVATE_indexEntryComparator(i2, t);
10084      if (0 === n2)
10085        r[0] = e.En();
10086      else if (n2 > 0 && s < 0)
10087        r.push(i2), r.push(i2.En());
10088      else if (s > 0)
10089        break;
10090    }
10091    r.push(t);
10092    const i = [];
10093    for (let e2 = 0; e2 < r.length; e2 += 2) {
10094      if (this.Yn(r[e2], r[e2 + 1])) return [];
10095      const t2 = r[e2].Rn(this.uid, Ct, DocumentKey.empty()), n2 = r[e2 + 1].Rn(this.uid, Ct, DocumentKey.empty());
10096      i.push(IDBKeyRange.bound(t2, n2));
10097    }
10098    return i;
10099  }
10100  Yn(e, t) {
10101    return __PRIVATE_indexEntryComparator(e, t) > 0;
10102  }
10103  getMinOffsetFromCollectionGroup(e, t) {
10104    return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes);
10105  }
10106  getMinOffset(e, t) {
10107    return PersistencePromise.mapArray(this.Fn(t), (t2) => this.Mn(e, t2).next((e2) => e2 || fail(44426))).next(__PRIVATE_getMinOffsetFromFieldIndexes);
10108  }
10109}
10110function __PRIVATE_collectionParentsStore(e) {
10111  return __PRIVATE_getStore(e, fe);
10112}
10113function __PRIVATE_indexEntriesStore(e) {
10114  return __PRIVATE_getStore(e, Le);
10115}
10116function __PRIVATE_indexConfigurationStore(e) {
10117  return __PRIVATE_getStore(e, ve);
10118}
10119function __PRIVATE_indexStateStore(e) {
10120  return __PRIVATE_getStore(e, xe);
10121}
10122function __PRIVATE_getMinOffsetFromFieldIndexes(e) {
10123  __PRIVATE_hardAssert(0 !== e.length, 28825);
10124  let t = e[0].indexState.offset, n = t.largestBatchId;
10125  for (let r = 1; r < e.length; r++) {
10126    const i = e[r].indexState.offset;
10127    __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId);
10128  }
10129  return new IndexOffset(t.readTime, t.documentKey, n);
10130}
10131/**
10132 * @license
10133 * Copyright 2018 Google LLC
10134 *
10135 * Licensed under the Apache License, Version 2.0 (the "License");
10136 * you may not use this file except in compliance with the License.
10137 * You may obtain a copy of the License at
10138 *
10139 *   http://www.apache.org/licenses/LICENSE-2.0
10140 *
10141 * Unless required by applicable law or agreed to in writing, software
10142 * distributed under the License is distributed on an "AS IS" BASIS,
10143 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10144 * See the License for the specific language governing permissions and
10145 * limitations under the License.
10146 */
10147const Ft = {
10148  didRun: false,
10149  sequenceNumbersCollected: 0,
10150  targetsRemoved: 0,
10151  documentsRemoved: 0
10152}, Mt = 41943040;
10153class LruParams {
10154  static withCacheSize(e) {
10155    return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
10156  }
10157  constructor(e, t, n) {
10158    this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n;
10159  }
10160}
10161/**
10162 * @license
10163 * Copyright 2020 Google LLC
10164 *
10165 * Licensed under the Apache License, Version 2.0 (the "License");
10166 * you may not use this file except in compliance with the License.
10167 * You may obtain a copy of the License at
10168 *
10169 *   http://www.apache.org/licenses/LICENSE-2.0
10170 *
10171 * Unless required by applicable law or agreed to in writing, software
10172 * distributed under the License is distributed on an "AS IS" BASIS,
10173 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10174 * See the License for the specific language governing permissions and
10175 * limitations under the License.
10176 */
10177function removeMutationBatch(e, t, n) {
10178  const r = e.store(X), i = e.store(ie), s = [], o = IDBKeyRange.only(n.batchId);
10179  let _ = 0;
10180  const a = r.X({
10181    range: o
10182  }, (e2, t2, n2) => (_++, n2.delete()));
10183  s.push(a.next(() => {
10184    __PRIVATE_hardAssert(1 === _, 47070, {
10185      batchId: n.batchId
10186    });
10187  }));
10188  const u = [];
10189  for (const e2 of n.mutations) {
10190    const r2 = __PRIVATE_newDbDocumentMutationKey(t, e2.key.path, n.batchId);
10191    s.push(i.delete(r2)), u.push(e2.key);
10192  }
10193  return PersistencePromise.waitFor(s).next(() => u);
10194}
10195function __PRIVATE_dbDocumentSize(e) {
10196  if (!e) return 0;
10197  let t;
10198  if (e.document) t = e.document;
10199  else if (e.unknownDocument) t = e.unknownDocument;
10200  else {
10201    if (!e.noDocument) throw fail(14731);
10202    t = e.noDocument;
10203  }
10204  return JSON.stringify(t).length;
10205}
10206/**
10207 * @license
10208 * Copyright 2017 Google LLC
10209 *
10210 * Licensed under the Apache License, Version 2.0 (the "License");
10211 * you may not use this file except in compliance with the License.
10212 * You may obtain a copy of the License at
10213 *
10214 *   http://www.apache.org/licenses/LICENSE-2.0
10215 *
10216 * Unless required by applicable law or agreed to in writing, software
10217 * distributed under the License is distributed on an "AS IS" BASIS,
10218 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10219 * See the License for the specific language governing permissions and
10220 * limitations under the License.
10221 */
10222LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(Mt, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), LruParams.DISABLED = new LruParams(-1, 0, 0);
10223class __PRIVATE_IndexedDbMutationQueue {
10224  constructor(e, t, n, r) {
10225    this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, /**
10226    * Caches the document keys for pending mutation batches. If the mutation
10227    * has been removed from IndexedDb, the cached value may continue to
10228    * be used to retrieve the batch's document keys. To remove a cached value
10229    * locally, `removeCachedMutationKeys()` should be invoked either directly
10230    * or through `removeMutationBatches()`.
10231    *
10232    * With multi-tab, when the primary client acknowledges or rejects a mutation,
10233    * this cache is used by secondary clients to invalidate the local
10234    * view of the documents that were previously affected by the mutation.
10235    */
10236    // PORTING NOTE: Multi-tab only.
10237    this.Zn = {};
10238  }
10239  /**
10240   * Creates a new mutation queue for the given user.
10241   * @param user - The user for which to create a mutation queue.
10242   * @param serializer - The serializer to use when persisting to IndexedDb.
10243   */
10244  static yt(e, t, n, r) {
10245    __PRIVATE_hardAssert("" !== e.uid, 64387);
10246    const i = e.isAuthenticated() ? e.uid : "";
10247    return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r);
10248  }
10249  checkEmpty(e) {
10250    let t = true;
10251    const n = IDBKeyRange.bound([this.userId, Number.NEGATIVE_INFINITY], [this.userId, Number.POSITIVE_INFINITY]);
10252    return __PRIVATE_mutationsStore(e).X({
10253      index: te,
10254      range: n
10255    }, (e2, n2, r) => {
10256      t = false, r.done();
10257    }).next(() => t);
10258  }
10259  addMutationBatch(e, t, n, r) {
10260    const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e);
10261    return s.add({}).next((o) => {
10262      __PRIVATE_hardAssert("number" == typeof o, 49019);
10263      const _ = new MutationBatch(o, t, n, r), a = function __PRIVATE_toDbMutationBatch(e2, t2, n2) {
10264        const r2 = n2.baseMutations.map((t3) => toMutation(e2.gt, t3)), i2 = n2.mutations.map((t3) => toMutation(e2.gt, t3));
10265        return {
10266          userId: t2,
10267          batchId: n2.batchId,
10268          localWriteTimeMs: n2.localWriteTime.toMillis(),
10269          baseMutations: r2,
10270          mutations: i2
10271        };
10272      }(this.serializer, this.userId, _), u = [];
10273      let c = new SortedSet((e2, t2) => __PRIVATE_primitiveComparator(e2.canonicalString(), t2.canonicalString()));
10274      for (const e2 of r) {
10275        const t2 = __PRIVATE_newDbDocumentMutationKey(this.userId, e2.key.path, o);
10276        c = c.add(e2.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t2, re));
10277      }
10278      return c.forEach((t2) => {
10279        u.push(this.indexManager.addToCollectionParentIndex(e, t2));
10280      }), e.addOnCommittedListener(() => {
10281        this.Zn[o] = _.keys();
10282      }), PersistencePromise.waitFor(u).next(() => _);
10283    });
10284  }
10285  lookupMutationBatch(e, t) {
10286    return __PRIVATE_mutationsStore(e).get(t).next((e2) => e2 ? (__PRIVATE_hardAssert(e2.userId === this.userId, 48, "Unexpected user for mutation batch", {
10287      userId: e2.userId,
10288      batchId: t
10289    }), __PRIVATE_fromDbMutationBatch(this.serializer, e2)) : null);
10290  }
10291  /**
10292   * Returns the document keys for the mutation batch with the given batchId.
10293   * For primary clients, this method returns `null` after
10294   * `removeMutationBatches()` has been called. Secondary clients return a
10295   * cached result until `removeCachedMutationKeys()` is invoked.
10296   */
10297  // PORTING NOTE: Multi-tab only.
10298  Xn(e, t) {
10299    return this.Zn[t] ? PersistencePromise.resolve(this.Zn[t]) : this.lookupMutationBatch(e, t).next((e2) => {
10300      if (e2) {
10301        const n = e2.keys();
10302        return this.Zn[t] = n, n;
10303      }
10304      return null;
10305    });
10306  }
10307  getNextMutationBatchAfterBatchId(e, t) {
10308    const n = t + 1, r = IDBKeyRange.lowerBound([this.userId, n]);
10309    let i = null;
10310    return __PRIVATE_mutationsStore(e).X({
10311      index: te,
10312      range: r
10313    }, (e2, t2, r2) => {
10314      t2.userId === this.userId && (__PRIVATE_hardAssert(t2.batchId >= n, 47524, {
10315        er: n
10316      }), i = __PRIVATE_fromDbMutationBatch(this.serializer, t2)), r2.done();
10317    }).next(() => i);
10318  }
10319  getHighestUnacknowledgedBatchId(e) {
10320    const t = IDBKeyRange.upperBound([this.userId, Number.POSITIVE_INFINITY]);
10321    let n = G;
10322    return __PRIVATE_mutationsStore(e).X({
10323      index: te,
10324      range: t,
10325      reverse: true
10326    }, (e2, t2, r) => {
10327      n = t2.batchId, r.done();
10328    }).next(() => n);
10329  }
10330  getAllMutationBatches(e) {
10331    const t = IDBKeyRange.bound([this.userId, G], [this.userId, Number.POSITIVE_INFINITY]);
10332    return __PRIVATE_mutationsStore(e).j(te, t).next((e2) => e2.map((e3) => __PRIVATE_fromDbMutationBatch(this.serializer, e3)));
10333  }
10334  getAllMutationBatchesAffectingDocumentKey(e, t) {
10335    const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = [];
10336    return __PRIVATE_documentMutationsStore(e).X({
10337      range: r
10338    }, (n2, r2, s) => {
10339      const [o, _, a] = n2, u = __PRIVATE_decodeResourcePath(_);
10340      if (o === this.userId && t.path.isEqual(u))
10341        return __PRIVATE_mutationsStore(e).get(a).next((e2) => {
10342          if (!e2) throw fail(61480, {
10343            tr: n2,
10344            batchId: a
10345          });
10346          __PRIVATE_hardAssert(e2.userId === this.userId, 10503, "Unexpected user for mutation batch", {
10347            userId: e2.userId,
10348            batchId: a
10349          }), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e2));
10350        });
10351      s.done();
10352    }).next(() => i);
10353  }
10354  getAllMutationBatchesAffectingDocumentKeys(e, t) {
10355    let n = new SortedSet(__PRIVATE_primitiveComparator);
10356    const r = [];
10357    return t.forEach((t2) => {
10358      const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t2.path), s = IDBKeyRange.lowerBound(i), o = __PRIVATE_documentMutationsStore(e).X({
10359        range: s
10360      }, (e2, r2, i2) => {
10361        const [s2, o2, _] = e2, a = __PRIVATE_decodeResourcePath(o2);
10362        s2 === this.userId && t2.path.isEqual(a) ? n = n.add(_) : i2.done();
10363      });
10364      r.push(o);
10365    }), PersistencePromise.waitFor(r).next(() => this.nr(e, n));
10366  }
10367  getAllMutationBatchesAffectingQuery(e, t) {
10368    const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i);
10369    let o = new SortedSet(__PRIVATE_primitiveComparator);
10370    return __PRIVATE_documentMutationsStore(e).X({
10371      range: s
10372    }, (e2, t2, i2) => {
10373      const [s2, _, a] = e2, u = __PRIVATE_decodeResourcePath(_);
10374      s2 === this.userId && n.isPrefixOf(u) ? (
10375        // Rows with document keys more than one segment longer than the
10376        // query path can't be matches. For example, a query on 'rooms'
10377        // can't match the document /rooms/abc/messages/xyx.
10378        // TODO(mcg): we'll need a different scanner when we implement
10379        // ancestor queries.
10380        u.length === r && (o = o.add(a))
10381      ) : i2.done();
10382    }).next(() => this.nr(e, o));
10383  }
10384  nr(e, t) {
10385    const n = [], r = [];
10386    return t.forEach((t2) => {
10387      r.push(__PRIVATE_mutationsStore(e).get(t2).next((e2) => {
10388        if (null === e2) throw fail(35274, {
10389          batchId: t2
10390        });
10391        __PRIVATE_hardAssert(e2.userId === this.userId, 9748, "Unexpected user for mutation batch", {
10392          userId: e2.userId,
10393          batchId: t2
10394        }), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e2));
10395      }));
10396    }), PersistencePromise.waitFor(r).next(() => n);
10397  }
10398  removeMutationBatch(e, t) {
10399    return removeMutationBatch(e.ce, this.userId, t).next((n) => (e.addOnCommittedListener(() => {
10400      this.rr(t.batchId);
10401    }), PersistencePromise.forEach(n, (t2) => this.referenceDelegate.markPotentiallyOrphaned(e, t2))));
10402  }
10403  /**
10404   * Clears the cached keys for a mutation batch. This method should be
10405   * called by secondary clients after they process mutation updates.
10406   *
10407   * Note that this method does not have to be called from primary clients as
10408   * the corresponding cache entries are cleared when an acknowledged or
10409   * rejected batch is removed from the mutation queue.
10410   */
10411  // PORTING NOTE: Multi-tab only
10412  rr(e) {
10413    delete this.Zn[e];
10414  }
10415  performConsistencyCheck(e) {
10416    return this.checkEmpty(e).next((t) => {
10417      if (!t) return PersistencePromise.resolve();
10418      const n = IDBKeyRange.lowerBound(
10419        /**
10420        * Creates a [userId] key for use in the DbDocumentMutations index to iterate
10421        * over all of a user's document mutations.
10422        */
10423        /* @__PURE__ */ function __PRIVATE_newDbDocumentMutationPrefixForUser(e2) {
10424          return [e2];
10425        }(this.userId)
10426      ), r = [];
10427      return __PRIVATE_documentMutationsStore(e).X({
10428        range: n
10429      }, (e2, t2, n2) => {
10430        if (e2[0] === this.userId) {
10431          const t3 = __PRIVATE_decodeResourcePath(e2[1]);
10432          r.push(t3);
10433        } else n2.done();
10434      }).next(() => {
10435        __PRIVATE_hardAssert(0 === r.length, 56720, {
10436          ir: r.map((e2) => e2.canonicalString())
10437        });
10438      });
10439    });
10440  }
10441  containsKey(e, t) {
10442    return __PRIVATE_mutationQueueContainsKey(e, this.userId, t);
10443  }
10444  // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
10445  /** Returns the mutation queue's metadata from IndexedDb. */
10446  sr(e) {
10447    return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e2) => e2 || {
10448      userId: this.userId,
10449      lastAcknowledgedBatchId: G,
10450      lastStreamToken: ""
10451    });
10452  }
10453}
10454function __PRIVATE_mutationQueueContainsKey(e, t, n) {
10455  const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r);
10456  let o = false;
10457  return __PRIVATE_documentMutationsStore(e).X({
10458    range: s,
10459    Z: true
10460  }, (e2, n2, r2) => {
10461    const [
10462      s2,
10463      _,
10464      /*batchID*/
10465      a
10466    ] = e2;
10467    s2 === t && _ === i && (o = true), r2.done();
10468  }).next(() => o);
10469}
10470function __PRIVATE_mutationsStore(e) {
10471  return __PRIVATE_getStore(e, X);
10472}
10473function __PRIVATE_documentMutationsStore(e) {
10474  return __PRIVATE_getStore(e, ie);
10475}
10476function __PRIVATE_mutationQueuesStore(e) {
10477  return __PRIVATE_getStore(e, Y);
10478}
10479/**
10480 * @license
10481 * Copyright 2017 Google LLC
10482 *
10483 * Licensed under the Apache License, Version 2.0 (the "License");
10484 * you may not use this file except in compliance with the License.
10485 * You may obtain a copy of the License at
10486 *
10487 *   http://www.apache.org/licenses/LICENSE-2.0
10488 *
10489 * Unless required by applicable law or agreed to in writing, software
10490 * distributed under the License is distributed on an "AS IS" BASIS,
10491 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10492 * See the License for the specific language governing permissions and
10493 * limitations under the License.
10494 */
10495class __PRIVATE_TargetIdGenerator {
10496  constructor(e) {
10497    this._r = e;
10498  }
10499  next() {
10500    return this._r += 2, this._r;
10501  }
10502  static ar() {
10503    return new __PRIVATE_TargetIdGenerator(0);
10504  }
10505  static ur() {
10506    return new __PRIVATE_TargetIdGenerator(-1);
10507  }
10508}
10509/**
10510 * @license
10511 * Copyright 2017 Google LLC
10512 *
10513 * Licensed under the Apache License, Version 2.0 (the "License");
10514 * you may not use this file except in compliance with the License.
10515 * You may obtain a copy of the License at
10516 *
10517 *   http://www.apache.org/licenses/LICENSE-2.0
10518 *
10519 * Unless required by applicable law or agreed to in writing, software
10520 * distributed under the License is distributed on an "AS IS" BASIS,
10521 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10522 * See the License for the specific language governing permissions and
10523 * limitations under the License.
10524 */
10525class __PRIVATE_IndexedDbTargetCache {
10526  constructor(e, t) {
10527    this.referenceDelegate = e, this.serializer = t;
10528  }
10529  // PORTING NOTE: We don't cache global metadata for the target cache, since
10530  // some of it (in particular `highestTargetId`) can be modified by secondary
10531  // tabs. We could perhaps be more granular (and e.g. still cache
10532  // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
10533  // to IndexedDb whenever we need to read metadata. We can revisit if it turns
10534  // out to have a meaningful performance impact.
10535  allocateTargetId(e) {
10536    return this.cr(e).next((t) => {
10537      const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId);
10538      return t.highestTargetId = n.next(), this.lr(e, t).next(() => t.highestTargetId);
10539    });
10540  }
10541  getLastRemoteSnapshotVersion(e) {
10542    return this.cr(e).next((e2) => SnapshotVersion.fromTimestamp(new Timestamp(e2.lastRemoteSnapshotVersion.seconds, e2.lastRemoteSnapshotVersion.nanoseconds)));
10543  }
10544  getHighestSequenceNumber(e) {
10545    return this.cr(e).next((e2) => e2.highestListenSequenceNumber);
10546  }
10547  setTargetsMetadata(e, t, n) {
10548    return this.cr(e).next((r) => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.lr(e, r)));
10549  }
10550  addTargetData(e, t) {
10551    return this.hr(e, t).next(() => this.cr(e).next((n) => (n.targetCount += 1, this.Pr(t, n), this.lr(e, n))));
10552  }
10553  updateTargetData(e, t) {
10554    return this.hr(e, t);
10555  }
10556  removeTargetData(e, t) {
10557    return this.removeMatchingKeysForTargetId(e, t.targetId).next(() => __PRIVATE_targetsStore(e).delete(t.targetId)).next(() => this.cr(e)).next((t2) => (__PRIVATE_hardAssert(t2.targetCount > 0, 8065), t2.targetCount -= 1, this.lr(e, t2)));
10558  }
10559  /**
10560   * Drops any targets with sequence number less than or equal to the upper bound, excepting those
10561   * present in `activeTargetIds`. Document associations for the removed targets are also removed.
10562   * Returns the number of targets removed.
10563   */
10564  removeTargets(e, t, n) {
10565    let r = 0;
10566    const i = [];
10567    return __PRIVATE_targetsStore(e).X((s, o) => {
10568      const _ = __PRIVATE_fromDbTarget(o);
10569      _.sequenceNumber <= t && null === n.get(_.targetId) && (r++, i.push(this.removeTargetData(e, _)));
10570    }).next(() => PersistencePromise.waitFor(i)).next(() => r);
10571  }
10572  /**
10573   * Call provided function with each `TargetData` that we have cached.
10574   */
10575  forEachTarget(e, t) {
10576    return __PRIVATE_targetsStore(e).X((e2, n) => {
10577      const r = __PRIVATE_fromDbTarget(n);
10578      t(r);
10579    });
10580  }
10581  cr(e) {
10582    return __PRIVATE_globalTargetStore(e).get(Ve).next((e2) => (__PRIVATE_hardAssert(null !== e2, 2888), e2));
10583  }
10584  lr(e, t) {
10585    return __PRIVATE_globalTargetStore(e).put(Ve, t);
10586  }
10587  hr(e, t) {
10588    return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t));
10589  }
10590  /**
10591   * In-place updates the provided metadata to account for values in the given
10592   * TargetData. Saving is done separately. Returns true if there were any
10593   * changes to the metadata.
10594   */
10595  Pr(e, t) {
10596    let n = false;
10597    return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = true), e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, n = true), n;
10598  }
10599  getTargetCount(e) {
10600    return this.cr(e).next((e2) => e2.targetCount);
10601  }
10602  getTargetData(e, t) {
10603    const n = __PRIVATE_canonifyTarget(t), r = IDBKeyRange.bound([n, Number.NEGATIVE_INFINITY], [n, Number.POSITIVE_INFINITY]);
10604    let i = null;
10605    return __PRIVATE_targetsStore(e).X({
10606      range: r,
10607      index: Te
10608    }, (e2, n2, r2) => {
10609      const s = __PRIVATE_fromDbTarget(n2);
10610      __PRIVATE_targetEquals(t, s.target) && (i = s, r2.done());
10611    }).next(() => i);
10612  }
10613  addMatchingKeys(e, t, n) {
10614    const r = [], i = __PRIVATE_documentTargetStore(e);
10615    return t.forEach((t2) => {
10616      const s = __PRIVATE_encodeResourcePath(t2.path);
10617      r.push(i.put({
10618        targetId: n,
10619        path: s
10620      })), r.push(this.referenceDelegate.addReference(e, n, t2));
10621    }), PersistencePromise.waitFor(r);
10622  }
10623  removeMatchingKeys(e, t, n) {
10624    const r = __PRIVATE_documentTargetStore(e);
10625    return PersistencePromise.forEach(t, (t2) => {
10626      const i = __PRIVATE_encodeResourcePath(t2.path);
10627      return PersistencePromise.waitFor([r.delete([n, i]), this.referenceDelegate.removeReference(e, n, t2)]);
10628    });
10629  }
10630  removeMatchingKeysForTargetId(e, t) {
10631    const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound(
10632      [t],
10633      [t + 1],
10634      /*lowerOpen=*/
10635      false,
10636      /*upperOpen=*/
10637      true
10638    );
10639    return n.delete(r);
10640  }
10641  getMatchingKeysForTargetId(e, t) {
10642    const n = IDBKeyRange.bound(
10643      [t],
10644      [t + 1],
10645      /*lowerOpen=*/
10646      false,
10647      /*upperOpen=*/
10648      true
10649    ), r = __PRIVATE_documentTargetStore(e);
10650    let i = __PRIVATE_documentKeySet();
10651    return r.X({
10652      range: n,
10653      Z: true
10654    }, (e2, t2, n2) => {
10655      const r2 = __PRIVATE_decodeResourcePath(e2[1]), s = new DocumentKey(r2);
10656      i = i.add(s);
10657    }).next(() => i);
10658  }
10659  containsKey(e, t) {
10660    const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound(
10661      [n],
10662      [__PRIVATE_immediateSuccessor(n)],
10663      /*lowerOpen=*/
10664      false,
10665      /*upperOpen=*/
10666      true
10667    );
10668    let i = 0;
10669    return __PRIVATE_documentTargetStore(e).X({
10670      index: Ae,
10671      Z: true,
10672      range: r
10673    }, ([e2, t2], n2, r2) => {
10674      0 !== e2 && (i++, r2.done());
10675    }).next(() => i > 0);
10676  }
10677  /**
10678   * Looks up a TargetData entry by target ID.
10679   *
10680   * @param targetId - The target ID of the TargetData entry to look up.
10681   * @returns The cached TargetData entry, or null if the cache has no entry for
10682   * the target.
10683   */
10684  // PORTING NOTE: Multi-tab only.
10685  Et(e, t) {
10686    return __PRIVATE_targetsStore(e).get(t).next((e2) => e2 ? __PRIVATE_fromDbTarget(e2) : null);
10687  }
10688}
10689function __PRIVATE_targetsStore(e) {
10690  return __PRIVATE_getStore(e, Pe);
10691}
10692function __PRIVATE_globalTargetStore(e) {
10693  return __PRIVATE_getStore(e, me);
10694}
10695function __PRIVATE_documentTargetStore(e) {
10696  return __PRIVATE_getStore(e, de);
10697}
10698/**
10699 * @license
10700 * Copyright 2020 Google LLC
10701 *
10702 * Licensed under the Apache License, Version 2.0 (the "License");
10703 * you may not use this file except in compliance with the License.
10704 * You may obtain a copy of the License at
10705 *
10706 *   http://www.apache.org/licenses/LICENSE-2.0
10707 *
10708 * Unless required by applicable law or agreed to in writing, software
10709 * distributed under the License is distributed on an "AS IS" BASIS,
10710 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10711 * See the License for the specific language governing permissions and
10712 * limitations under the License.
10713 */
10714const xt = "LruGarbageCollector", Ot = 1048576;
10715function __PRIVATE_bufferEntryComparator([e, t], [n, r]) {
10716  const i = __PRIVATE_primitiveComparator(e, n);
10717  return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i;
10718}
10719class __PRIVATE_RollingSequenceNumberBuffer {
10720  constructor(e) {
10721    this.Tr = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Ir = 0;
10722  }
10723  dr() {
10724    return ++this.Ir;
10725  }
10726  Er(e) {
10727    const t = [e, this.dr()];
10728    if (this.buffer.size < this.Tr) this.buffer = this.buffer.add(t);
10729    else {
10730      const e2 = this.buffer.last();
10731      __PRIVATE_bufferEntryComparator(t, e2) < 0 && (this.buffer = this.buffer.delete(e2).add(t));
10732    }
10733  }
10734  get maxValue() {
10735    return this.buffer.last()[0];
10736  }
10737}
10738class __PRIVATE_LruScheduler {
10739  constructor(e, t, n) {
10740    this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.Ar = null;
10741  }
10742  start() {
10743    -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Rr(6e4);
10744  }
10745  stop() {
10746    this.Ar && (this.Ar.cancel(), this.Ar = null);
10747  }
10748  get started() {
10749    return null !== this.Ar;
10750  }
10751  Rr(e) {
10752    __PRIVATE_logDebug(xt, `Garbage collection scheduled in ${e}ms`), this.Ar = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection", e, async () => {
10753      this.Ar = null;
10754      try {
10755        await this.localStore.collectGarbage(this.garbageCollector);
10756      } catch (e2) {
10757        __PRIVATE_isIndexedDbTransactionError(e2) ? __PRIVATE_logDebug(xt, "Ignoring IndexedDB error during garbage collection: ", e2) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e2);
10758      }
10759      await this.Rr(3e5);
10760    });
10761  }
10762}
10763class __PRIVATE_LruGarbageCollectorImpl {
10764  constructor(e, t) {
10765    this.Vr = e, this.params = t;
10766  }
10767  calculateTargetCount(e, t) {
10768    return this.Vr.mr(e).next((e2) => Math.floor(t / 100 * e2));
10769  }
10770  nthSequenceNumber(e, t) {
10771    if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence.ue);
10772    const n = new __PRIVATE_RollingSequenceNumberBuffer(t);
10773    return this.Vr.forEachTarget(e, (e2) => n.Er(e2.sequenceNumber)).next(() => this.Vr.gr(e, (e2) => n.Er(e2))).next(() => n.maxValue);
10774  }
10775  removeTargets(e, t, n) {
10776    return this.Vr.removeTargets(e, t, n);
10777  }
10778  removeOrphanedDocuments(e, t) {
10779    return this.Vr.removeOrphanedDocuments(e, t);
10780  }
10781  collect(e, t) {
10782    return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", "Garbage collection skipped; disabled"), PersistencePromise.resolve(Ft)) : this.getCacheSize(e).next((n) => n < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), Ft) : this.pr(e, t));
10783  }
10784  getCacheSize(e) {
10785    return this.Vr.getCacheSize(e);
10786  }
10787  pr(e, t) {
10788    let n, r, i, s, o, _, u;
10789    const c = Date.now();
10790    return this.calculateTargetCount(e, this.params.percentileToCollect).next((t2) => (
10791      // Cap at the configured max
10792      (t2 > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t2}`), r = this.params.maximumSequenceNumbersToCollect) : r = t2, s = Date.now(), this.nthSequenceNumber(e, r))
10793    )).next((r2) => (n = r2, o = Date.now(), this.removeTargets(e, n, t))).next((t2) => (i = t2, _ = Date.now(), this.removeOrphanedDocuments(e, n))).next((e2) => {
10794      if (u = Date.now(), __PRIVATE_getLogLevel() <= LogLevel.DEBUG) {
10795        __PRIVATE_logDebug("LruGarbageCollector", `LRU Garbage Collection
10796	Counted targets in ${s - c}ms
10797	Determined least recently used ${r} in ` + (o - s) + `ms
10798	Removed ${i} targets in ` + (_ - o) + `ms
10799	Removed ${e2} documents in ` + (u - _) + `ms
10800Total Duration: ${u - c}ms`);
10801      }
10802      return PersistencePromise.resolve({
10803        didRun: true,
10804        sequenceNumbersCollected: r,
10805        targetsRemoved: i,
10806        documentsRemoved: e2
10807      });
10808    });
10809  }
10810}
10811function __PRIVATE_newLruGarbageCollector(e, t) {
10812  return new __PRIVATE_LruGarbageCollectorImpl(e, t);
10813}
10814/**
10815 * @license
10816 * Copyright 2020 Google LLC
10817 *
10818 * Licensed under the Apache License, Version 2.0 (the "License");
10819 * you may not use this file except in compliance with the License.
10820 * You may obtain a copy of the License at
10821 *
10822 *   http://www.apache.org/licenses/LICENSE-2.0
10823 *
10824 * Unless required by applicable law or agreed to in writing, softw
10824are
10825 * distributed under the License is distributed on an "AS IS" BASIS,
10826 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10827 * See the License for the specific language governing permissions and
10828 * limitations under the License.
10829 */
10830class __PRIVATE_IndexedDbLruDelegateImpl {
10831  constructor(e, t) {
10832    this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);
10833  }
10834  mr(e) {
10835    const t = this.yr(e);
10836    return this.db.getTargetCache().getTargetCount(e).next((e2) => t.next((t2) => e2 + t2));
10837  }
10838  yr(e) {
10839    let t = 0;
10840    return this.gr(e, (e2) => {
10841      t++;
10842    }).next(() => t);
10843  }
10844  forEachTarget(e, t) {
10845    return this.db.getTargetCache().forEachTarget(e, t);
10846  }
10847  gr(e, t) {
10848    return this.wr(e, (e2, n) => t(n));
10849  }
10850  addReference(e, t, n) {
10851    return __PRIVATE_writeSentinelKey(e, n);
10852  }
10853  removeReference(e, t, n) {
10854    return __PRIVATE_writeSentinelKey(e, n);
10855  }
10856  removeTargets(e, t, n) {
10857    return this.db.getTargetCache().removeTargets(e, t, n);
10858  }
10859  markPotentiallyOrphaned(e, t) {
10860    return __PRIVATE_writeSentinelKey(e, t);
10861  }
10862  /**
10863   * Returns true if anything would prevent this document from being garbage
10864   * collected, given that the document in question is not present in any
10865   * targets and has a sequence number less than or equal to the upper bound for
10866   * the collection run.
10867   */
10868  Sr(e, t) {
10869    return function __PRIVATE_mutationQueuesContainKey(e2, t2) {
10870      let n = false;
10871      return __PRIVATE_mutationQueuesStore(e2).ee((r) => __PRIVATE_mutationQueueContainsKey(e2, r, t2).next((e3) => (e3 && (n = true), PersistencePromise.resolve(!e3)))).next(() => n);
10872    }(e, t);
10873  }
10874  removeOrphanedDocuments(e, t) {
10875    const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = [];
10876    let i = 0;
10877    return this.wr(e, (s, o) => {
10878      if (o <= t) {
10879        const t2 = this.Sr(e, s).next((t3) => {
10880          if (!t3)
10881            return i++, n.getEntry(e, s).next(() => (n.removeEntry(s, SnapshotVersion.min()), __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$
108811(e2) {
10882              return [0, __PRIVATE_encodeResourcePath(e2.path)];
10883            }(s))));
10884        });
10885        r.push(t2);
10886      }
10887    }).next(() => PersistencePromise.waitFor(r)).next(() => n.apply(e)).next(() => i);
10888  }
10889  removeTarget(e, t) {
10890    const n = t.withSequenceNumber(e.currentSequenceNumber);
10891    return this.db.getTargetCache().updateTargetData(e, n);
10892  }
10893  updateLimboDocument(e, t) {
10894    return __PRIVATE_writeSentinelKey(e, t);
10895  }
10896  /**
10897   * Call provided function for each document in the cache that is 'orphaned'. Orphaned
10898   * means not a part of any target, so the only entry in the target-document index for
10899   * that document will be the sentinel row (targetId 0), which will also have the sequence
10900   * number for the last time the document was accessed.
10901   */
10902  wr(e, t) {
10903    const n = __PRIVATE_documentTargetStore(e);
10904    let r, i = __PRIVATE_ListenSequence.ue;
10905    return n.X({
10906      index: Ae
10907    }, ([e2, n2], { path: s, sequenceNumber: o }) => {
10908      0 === e2 ? (
10909        // if nextToReport is valid, report it, this is a new key so the
10910        // last one must not be a member of any targets.
10911        (i !== __PRIVATE_ListenSequence.ue && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), // set nextToReport to be this sequence number. It's the next one we
10912        // might report, if we don't find any targets for this document.
10913        // Note that the sequence number must be defined when the targetId
10914        // is 0.
10915        i = o, r = s)
10916      ) : (
10917        // set nextToReport to be invalid, we know we don't need to report
10918        // this one since we found a target for it.
10919        i = __PRIVATE_ListenSequence.ue
10920      );
10921    }).next(() => {
10922      i !== __PRIVATE_ListenSequence.ue && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i);
10923    });
10924  }
10925  getCacheSize(e) {
10926    return this.db.getRemoteDocumentCache().getSize(e);
10927  }
10928}
10929function __PRIVATE_writeSentinelKey(e, t) {
10930  return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e2, t2) {
10931    return {
10932      targetId: 0,
10933      path: __PRIVATE_encodeResourcePath(e2.path),
10934      sequenceNumber: t2
10935    };
10936  }(t, e.currentSequenceNumber));
10937}
10938/**
10939 * @license
10940 * Copyright 2017 Google LLC
10941 *
10942 * Licensed under the Apache License, Version 2.0 (the "License");
10943 * you may not use this file except in compliance with the License.
10944 * You may obtain a copy of the License at
10945 *
10946 *   http://www.apache.org/licenses/LICENSE-2.0
10947 *
10948 * Unless required by applicable law or agreed to in writing, software
10949 * distributed under the License is distributed on an "AS IS" BASIS,
10950 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10951 * See the License for the specific language governing permissions and
10952 * limitations under the License.
10953 */
10954class RemoteDocumentChangeBuffer {
10955  constructor() {
10956    this.changes = new ObjectMap((e) => e.toString(), (e, t) => e.isEqual(t)), this.changesApplied = false;
10957  }
10958  /**
10959   * Buffers a `RemoteDocumentCache.addEntry()` call.
10960   *
10961   * You can only modify documents that have already been retrieved via
10962   * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
10963   */
10964  addEntry(e) {
10965    this.assertNotApplied(), this.changes.set(e.key, e);
10966  }
10967  /**
10968   * Buffers a `RemoteDocumentCache.removeEntry()` call.
10969   *
10970   * You can only remove documents that have already been retrieved via
10971   * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
10972   */
10973  removeEntry(e, t) {
10974    this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t));
10975  }
10976  /**
10977   * Looks up an entry in the cache. The buffered changes will first be checked,
10978   * and if no buffered change applies, this will forward to
10979   * `RemoteDocumentCache.getEntry()`.
10980   *
10981   * @param transaction - The transaction in which to perform any persistence
10982   *     operations.
10983   * @param documentKey - The key of the entry to look up.
10984   * @returns The cached document or an invalid document if we have nothing
10985   * cached.
10986   */
10987  getEntry(e, t) {
10988    this.assertNotApplied();
10989    const n = this.changes.get(t);
10990    return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t);
10991  }
10992  /**
10993   * Looks up several entries in the cache, forwarding to
10994   * `RemoteDocumentCache.getEntry()`.
10995   *
10996   * @param transaction - The transaction in which to perform any persistence
10997   *     operations.
10998   * @param documentKeys - The keys of the entries to look up.
10999   * @returns A map of cached documents, indexed by key. If an entry cannot be
11000   *     found, the corresponding key will be mapped to an invali
11000d document.
11001   */
11002  getEntries(e, t) {
11003    return this.getAllFromCache(e, t);
11004  }
11005  /**
11006   * Applies buffered changes to the underlying RemoteDocumentCache, using
11007   * the provided transaction.
11008   */
11009  apply(e) {
11010    return this.assertNotApplied(), this.changesApplied = true, this.applyChanges(e);
11011  }
11012  /** Helper to assert this.changes is not null  */
11013  assertNotApplied() {
11014  }
11015}
11016/**
11017 * @license
11018 * Copyright 2017 Google LLC
11019 *
11020 * Licensed under the Apache License, Version 2.0 (the "License");
11021 * you may not use this file except in compliance with the License.
11022 * You may obtain a copy of the License at
11023 *
11024 *   http://www.apache.org/licenses/LICENSE-2.0
11025 *
11026 * Unless required by applicable law or agreed to in writing, software
11027 * distributed under the License is distributed on an "AS IS" BASIS,
11028 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11029 * See the License for the specific language governing permissions and
11030 * limitations under the License.
11031 */
11032class __PRIVATE_IndexedDbRemoteDocumentCacheImpl {
11033  constructor(e) {
11034    this.serializer = e;
11035  }
11036  setIndexManager(e) {
11037    this.indexManager = e;
11038  }
11039  /**
11040   * Adds the supplied entries to the cache.
11041   *
11042   * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
11043   * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
11044   */
11045  addEntry(e, t, n) {
11046    return __PRIVATE_remoteDocumentsStore(e).put(n);
11047  }
11048  /**
11049   * Removes a document from the cache.
11050   *
11051   * All calls of `removeEntry`  are required to go through the RemoteDocumentChangeBuffer
11052   * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
11053   */
11054  removeEntry(e, t, n) {
11055    return __PRIVATE_remoteDocumentsStore(e).delete(
11056      /**
11057      * Returns a key that can be used for document lookups via the primary key of
11058      * the DbRemoteDocument object store.
11059      */
11060      function __PRIVATE_dbReadTimeKey(e2, t2) {
11061        const n2 = e2.path.toArray();
11062        return [
11063          /* prefix path */
11064          n2.slice(0, n2.length - 2),
11065          /* collection id */
11066          n2[n2.length - 2],
11067          __PRIVATE_toDbTimestampKey(t2),
11068          /* document id */
11069          n2[n2.length - 1]
11070        ];
11071      }(t, n)
11072    );
11073  }
11074  /**
11075   * Updates the current cache size.
11076   *
11077   * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
11078   * cache's metadata.
11079   */
11080  updateMetadata(e, t) {
11081    return this.getMetadata(e).next((n) => (n.byteSize += t, this.br(e, n)));
11082  }
11083  getEntry(e, t) {
11084    let n = MutableDocument.newInvalidDocument(t);
11085    return __PRIVATE_remoteDocumentsStore(e).X({
11086      index: _e,
11087      range: IDBKeyRange.only(__PRIVATE_dbKey(t))
11088    }, (e2, r) => {
11089      n = this.Dr(t, r);
11090    }).next(() => n);
11091  }
11092  /**
11093   * Looks up an entry in the cache.
11094   *
11095   * @param documentKey - The key of the entry to look up.
11096   * @returns The cached document entry and its size.
11097   */
11098  vr(e, t) {
11099    let n = {
11100      size: 0,
11101      document: MutableDocument.newInvalidDocument(t)
11102    };
11103    return __PRIVATE_remoteDocumentsStore(e).X({
11104      index: _e,
11105      range: IDBKeyRange.only(__PRIVATE_dbKey(t))
11106    }, (e2, r) => {
11107      n = {
11108        document: this.Dr(t, r),
11109        size: __PRIVATE_dbDocumentSize(r)
11110      };
11111    }).next(() => n);
11112  }
11113  getEntries(e, t) {
11114    let n = __PRIVATE_mutableDocumentMap();
11115    return this.Cr(e, t, (e2, t2) => {
11116      const r = this.Dr(e2, t2);
11117      n = n.insert(e2, r);
11118    }).next(() => n);
11119  }
11120  /**
11121   * Looks up several entries in the cache.
11122   *
11123   * @param documentKeys - The set of keys entries to look up.
11124   * @returns A map of documents indexed by key and a map of sizes indexed by
11125   *     key (zero if the document does not exist).
11126   */
11127  Fr(e, t) {
11128    let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator);
11129    return this.Cr(e, t, (e2, t2) => {
11130      const i = this.Dr(e2, t2);
11131      n = n.insert(e2, i), r = r.insert(e2, __PRIVATE_dbDocumentSize(t2));
11132    }).next(() => ({
11133      documents: n,
11134      Mr: r
11135    }));
11136  }
11137  Cr(e, t, n) {
11138    if (t.isEmpty()) return PersistencePromise.resolve();
11139    let r = new SortedSet(__PRIVATE_dbKeyComparator);
11140    t.forEach((e2) => r = r.add(e2));
11141    const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator();
11142    let o = s.getNext();
11143    return __PRIVATE_remoteDocumentsStore(e).X({
11144      index: _e,
11145      range: i
11146    }, (e2, t2, r2) => {
11147      const i2 = DocumentKey.fromSegments([...t2.prefixPath, t2.collectionGroup, t2.documentId]);
11148      for (; o && __PRIVATE_dbKeyComparator(o, i2) < 0; ) n(o, null), o = s.getNext();
11149      o && o.isEqual(i2) && // Key found in cache.
11150      (n(o, t2), o = s.hasNext() ? s.getNext() : null), // Skip to the next key (if there is one).
11151      o ? r2.G(__PRIVATE_dbKey(o)) : r2.done();
11152    }).next(() => {
11153      for (; o; ) n(o, null), o = s.hasNext() ? s.getNext() : null;
11154    });
11155  }
11156  getDocumentsMatchingQuery(e, t, n, r, i) {
11157    const s = t.path, o = [s.popLast().toArray(), s.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment()], _ = [s.popLast().toArray(), s.lastSegment(), [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], ""];
11158    return __PRIVATE_remoteDocumentsStore(e).j(IDBKeyRange.bound(o, _, true)).next((e2) => {
11159      null == i || i.incrementDocumentReadCount(e2.length);
11160      let n2 = __PRIVATE_mutableDocumentMap();
11161      for (const i2 of e2) {
11162        const e3 = this.Dr(DocumentKey.fromSegments(i2.prefixPath.concat(i2.collectionGroup, i2.documentId)), i2);
11163        e3.isFoundDocument() && (__PRIVATE_queryMatches(t, e3) || r.has(e3.key)) && // Either the document matches the given query, or it is mutated.
11164        (n2 = n2.insert(e3.key, e3));
11165      }
11166      return n2;
11167    });
11168  }
11169  getAllFromCollectionGroup(e, t, n, r) {
11170    let i = __PRIVATE_mutableDocumentMap();
11171    const s = __PRIVATE_dbCollectionGroupKey(t, n), o = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max());
11172    return __PRIVATE_remoteDocumentsStore(e).X({
11173      index: ue,
11174      range: IDBKeyRange.bound(s, o, true)
11175    }, (e2, t2, n2) => {
11176      const s2 = this.Dr(DocumentKey.fromSegments(t2.prefixPath.concat(t2.collectionGroup, t2.documentId)), t2);
11177      i = i.insert(s2.key, s2), i.size === r && n2.done();
11178    }).next(() => i);
11179  }
11180  newChangeBuffer(e) {
11181    return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals);
11182  }
11183  getSize(e) {
11184    return this.getMetadata(e).next((e2) => e2.byteSize);
11185  }
11186  getMetadata(e) {
11187    return __PRIVATE_documentGlobalStore(e).get(he).next((e2) => (__PRIVATE_hardAssert(!!e2, 20021), e2));
11188  }
11189  br(e, t) {
11190    return __PRIVATE_documentGlobalStore(e).put(he, t);
11191  }
11192  /**
11193   * Decodes `dbRemoteDoc` and returns the document (or an invali
11193d document if
11194   * the document corresponds to the format used for sentinel deletes).
11195   */
11196  Dr(e, t) {
11197    if (t) {
11198      const e2 = __PRIVATE_fromDbRemoteDocument(this.serializer, t);
11199      if (!(e2.isNoDocument() && e2.version.isEqual(SnapshotVersion.min()))) return e2;
11200    }
11201    return MutableDocument.newInvalidDocument(e);
11202  }
11203}
11204function __PRIVATE_newIndexedDbRemoteDocumentCache(e) {
11205  return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e);
11206}
11207class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {
11208  /**
11209   * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
11210   * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
11211   * `getNewDocumentChanges()`.
11212   */
11213  constructor(e, t) {
11214    super(), this.Or = e, this.trackRemovals = t, // A map of document sizes and read times prior to applying the changes in
11215    // this buffer.
11216    this.Nr = new ObjectMap((e2) => e2.toString(), (e2, t2) => e2.isEqual(t2));
11217  }
11218  applyChanges(e) {
11219    const t = [];
11220    let n = 0, r = new SortedSet((e2, t2) => __PRIVATE_primitiveComparator(e2.canonicalString(), t2.canonicalString()));
11221    return this.changes.forEach((i, s) => {
11222      const o = this.Nr.get(i);
11223      if (t.push(this.Or.removeEntry(e, i, o.readTime)), s.isValidDocument()) {
11224        const _ = __PRIVATE_toDbRemoteDocument(this.Or.serializer, s);
11225        r = r.add(i.path.popLast());
11226        const a = __PRIVATE_dbDocumentSize(_);
11227        n += a - o.size, t.push(this.Or.addEntry(e, i, _));
11228      } else if (n -= o.size, this.trackRemovals) {
11229        const n2 = __PRIVATE_toDbRemoteDocument(this.Or.serializer, s.convertToNoDocument(SnapshotVersion.min()));
11230        t.push(this.Or.addEntry(e, i, n2));
11231      }
11232    }), r.forEach((n2) => {
11233      t.push(this.Or.indexManager.addToCollectionParentIndex(e, n2));
11234    }), t.push(this.Or.updateMetadata(e, n)), PersistencePromise.waitFor(t);
11235  }
11236  getFromCache(e, t) {
11237    return this.Or.vr(e, t).next((e2) => (this.Nr.set(t, {
11238      size: e2.size,
11239      readTime: e2.document.readTime
11240    }), e2.document));
11241  }
11242  getAllFromCache(e, t) {
11243    return this.Or.Fr(e, t).next(({ documents: e2, Mr: t2 }) => (
11244      // Note: `getAllFromCache` returns two maps instead of a single map from
11245      // keys to `DocumentSizeEntry`s. This is to allow returning the
11246      // `MutableDocumentMap` directly, without a conversion.
11247      (t2.forEach((t3, n) => {
11248        this.Nr.set(t3, {
11249          size: n,
11250          readTime: e2.get(t3).readTime
11251        });
11252      }), e2)
11253    ));
11254  }
11255}
11256function __PRIVATE_documentGlobalStore(e) {
11257  return __PRIVATE_getStore(e, le);
11258}
11259function __PRIVATE_remoteDocumentsStore(e) {
11260  return __PRIVATE_getStore(e, se);
11261}
11262function __PRIVATE_dbKey(e) {
11263  const t = e.path.toArray();
11264  return [
11265    /* prefix path */
11266    t.slice(0, t.length - 2),
11267    /* collection id */
11268    t[t.length - 2],
11269    /* document id */
11270    t[t.length - 1]
11271  ];
11272}
11273function __PRIVATE_dbCollectionGroupKey(e, t) {
11274  const n = t.documentKey.path.toArray();
11275  return [
11276    /* collection id */
11277    e,
11278    __PRIVATE_toDbTimestampKey(t.readTime),
11279    /* prefix path */
11280    n.slice(0, n.length - 2),
11281    /* document id */
11282    n.length > 0 ? n[n.length - 1] : ""
11283  ];
11284}
11285function __PRIVATE_dbKeyComparator(e, t) {
11286  const n = e.path.toArray(), r = t.path.toArray();
11287  let i = 0;
11288  for (let e2 = 0; e2 < n.length - 2 && e2 < r.length - 2; ++e2) if (i = __PRIVATE_primitiveComparator(n[e2], r[e2]), i) return i;
11289  return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1]));
11290}
11291/**
11292 * @license
11293 * Copyright 2017 Google LLC
11294 *
11295 * Licensed under the Apache License, Version 2.0 (the "License");
11296 * you may not use this file except in compliance with the License.
11297 * You may obtain a copy of the License at
11298 *
11299 *   http://www.apache.org/licenses/LICENSE-2.0
11300 *
11301 * Unless required by applicable law or agreed to in writing, software
11302 * distributed under the License is distributed on an "AS IS" BASIS,
11303 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11304 * See the License for the specific language governing permissions and
11305 * limitations under the License.
11306 */
11307/**
11308 * @license
11309 * Copyright 2022 Google LLC
11310 *
11311 * Licensed under the Apache License, Version 2.0 (the "License");
11312 * you may not use this file except in compliance with the License.
11313 * You may obtain a copy of the License at
11314 *
11315 *   http://www.apache.org/licenses/LICENSE-2.0
11316 *
11317 * Unless required by applicable law or agreed to in writing, software
11318 * distributed under the License is distributed on an "AS IS" BASIS,
11319 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11320 * See the License for the specific language governing permissions and
11321 * limitations under the License.
11322 */
11323class OverlayedDocument {
11324  constructor(e, t) {
11325    this.overlayedDocument = e, this.mutatedFields = t;
11326  }
11327}
11328/**
11329 * @license
11330 * Copyright 2017 Google LLC
11331 *
11332 * Licensed under the Apache License, Version 2.0 (the "License");
11333 * you may not use this file except in compliance with the License.
11334 * You may obtain a copy of the License at
11335 *
11336 *   http://www.apache.org/licenses/LICENSE-2.0
11337 *
11338 * Unless required by applicable law or agreed to in writing, softw
11338are
11339 * distributed under the License is distributed on an "AS IS" BASIS,
11340 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11341 * See the License for the specific language governing permissions and
11342 * limitations under the License.
11343 */
11344class LocalDocumentsView {
11345  constructor(e, t, n, r) {
11346    this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, this.indexManager = r;
11347  }
11348  /**
11349   * Get the local view of the document identified by `key`.
11350   *
11351   * @returns Local view of the document or null if we don't have any cached
11352   * state for it.
11353   */
11354  getDocument(e, t) {
11355    let n = null;
11356    return this.documentOverlayCache.getOverlay(e, t).next((r) => (n = r, this.remoteDocumentCache.getEntry(e, t))).next((e2) => (null !== n && __PRIVATE_mutationApplyToLocalView(n.mutation, e2, FieldMask.empty(), Timestamp.now()), e2));
11357  }
11358  /**
11359   * Gets the local view of the documents identified by `keys`.
11360   *
11361   * If we don't have cached state for a document in `keys`, a NoDocument will
11362   * be stored for that key in the resulting set.
11363   */
11364  getDocuments(e, t) {
11365    return this.remoteDocumentCache.getEntries(e, t).next((t2) => this.getLocalViewOfDocuments(e, t2, __PRIVATE_documentKeySet()).next(() => t2));
11366  }
11367  /**
11368   * Similar to `getDocuments`, but creates the local view from the given
11369   * `baseDocs` without retrieving documents from the local store.
11370   *
11371   * @param transaction - The transaction this operation is scoped to.
11372   * @param docs - The documents to apply local mutations to get the local views.
11373   * @param existenceStateChanged - The set of document keys whose existence state
11374   *   is changed. This is useful to determine if some documents overlay needs
11375   *   to be recalculated.
11376   */
11377  getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) {
11378    const r = __PRIVATE_newOverlayMap();
11379    return this.populateOverlays(e, r, t).next(() => this.computeViews(e, t, r, n).next((e2) => {
11380      let t2 = documentMap();
11381      return e2.forEach((e3, n2) => {
11382        t2 = t2.insert(e3, n2.overlayedDocument);
11383      }), t2;
11384    }));
11385  }
11386  /**
11387   * Gets the overlayed documents for the given document map, which will include
11388   * the local view of those documents and a `FieldMask` indicating which fields
11389   * are mutated locally, `null` if overlay is a Set or Delete mutation.
11390   */
11391  getOverlayedDocuments(e, t) {
11392    const n = __PRIVATE_newOverlayMap();
11393    return this.populateOverlays(e, n, t).next(() => this.computeViews(e, t, n, __PRIVATE_documentKeySet()));
11394  }
11395  /**
11396   * Fetches the overlays for {@code docs} and adds them to provided overlay map
11397   * if the map does not already contain an entry for the given document key.
11398   */
11399  populateOverlays(e, t, n) {
11400    const r = [];
11401    return n.forEach((e2) => {
11402      t.has(e2) || r.push(e2);
11403    }), this.documentOverlayCache.getOverlays(e, r).next((e2) => {
11404      e2.forEach((e3, n2) => {
11405        t.set(e3, n2);
11406      });
11407    });
11408  }
11409  /**
11410   * Computes the local view for the given documents.
11411   *
11412   * @param docs - The documents to compute views for. It also has the base
11413   *   version of the documents.
11414   * @param overlays - The overlays that need to be applied to the given base
11415   *   version of the documents.
11416   * @param existenceStateChanged - A set of documents whose existence states
11417   *   might have changed. This is used to determine if we need to re-calculate
11418   *   overlays from mutation queues.
11419   * @return A map represents the local documents view.
11420   */
11421  computeViews(e, t, n, r) {
11422    let i = __PRIVATE_mutableDocumentMap();
11423    const s = __PRIVATE_newDocumentKeyMap(), o = function __PRIVATE_newOverlayedDocumentMap() {
11424      return __PRIVATE_newDocumentKeyMap();
11425    }();
11426    return t.forEach((e2, t2) => {
11427      const o2 = n.get(t2.key);
11428      r.has(t2.key) && (void 0 === o2 || o2.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t2.key, t2) : void 0 !== o2 ? (s.set(t2.key, o2.mutation.getFieldMask()), __PRIVATE_mutationApplyToLocalView(o2.mutation, t2, o2.mutation.getFieldMask(), Timestamp.now())) : (
11429        // no overlay exists
11430        // Using EMPTY to indicate there is no overlay for the document.
11431        s.set(t2.key, FieldMask.empty())
11432      );
11433    }), this.recalculateAndSaveOverlays(e, i).next((e2) => (e2.forEach((e3, t2) => s.set(e3, t2)), t.forEach((e3, t2) => {
11434      var n2;
11435      return o.set(e3, new OverlayedDocument(t2, null !== (n2 = s.get(e3)) && void 0 !== n2 ? n2 : null));
11436    }), o));
11437  }
11438  recalculateAndSaveOverlays(e, t) {
11439    const n = __PRIVATE_newDocumentKeyMap();
11440    let r = new SortedMap((e2, t2) => e2 - t2), i = __PRIVATE_documentKeySet();
11441    return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e2) => {
11442      for (const i2 of e2) i2.keys().forEach((e3) => {
11443        const s = t.get(e3);
11444        if (null === s) return;
11445        let o = n.get(e3) || FieldMask.empty();
11446        o = i2.applyToLocalView(s, o), n.set(e3, o);
11447        const _ = (r.get(i2.batchId) || __PRIVATE_documentKeySet()).add(e3);
11448        r = r.insert(i2.batchId, _);
11449      });
11450    }).next(() => {
11451      const s = [], o = r.getReverseIterator();
11452      for (; o.hasNext(); ) {
11453        const r2 = o.getNext(), _ = r2.key, a = r2.value, u = __PRIVATE_newMutationMap();
11454        a.forEach((e2) => {
11455          if (!i.has(e2)) {
11456            const r3 = __PRIVATE_calculateOverlayMutation(t.get(e2), n.get(e2));
11457            null !== r3 && u.set(e2, r3), i = i.add(e2);
11458          }
11459        }), s.push(this.documentOverlayCache.saveOverlays(e, _, u));
11460      }
11461      return PersistencePromise.waitFor(s);
11462    }).next(() => n);
11463  }
11464  /**
11465   * Recalculates overlays by reading the documents from remote document cache
11466   * first, and saves them after they are calculated.
11467   */
11468  recalculateAndSaveOverlaysForDocumentKeys(e, t) {
11469    return this.remoteDocumentCache.getEntries(e, t).next((t2) => this.recalculateAndSaveOverlays(e, t2));
11470  }
11471  /**
11472   * Performs a query against the local view of all documents.
11473   *
11474   * @param transaction - The persistence transaction.
11475   * @param query - The query to match documents against.
11476   * @param offset - Read time and key to start scanning by (exclusive).
11477   * @param context - A optional tracker to keep a record of important details
11478   *   during database local query execution.
11479   */
11480  getDocumentsMatchingQuery(e, t, n, r) {
11481    return function __PRIVATE_isDocumentQuery$1(e2) {
11482      return DocumentKey.isDocumentKey(e2.path) && null === e2.collectionGroup && 0 === e2.filters.length;
11483    }(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n, r) : this.getDocumentsMatchingCollectionQuery(e, t, n, r);
11484  }
11485  /**
11486   * Given a collection group, returns the next documents that follow the provided offset, along
11487   * with an updated batch ID.
11488   *
11489   * <p>The documents returned by this method are ordered by remote version from the provided
11490   * offset. If there are no more remote documents after the provided offset, documents with
11491   * mutations in order of batch id from the offset are returned. Since all documents in a batch are
11492   * returned together, the total number of documents returned can exceed {@code count}.
11493   *
11494   * @param transaction
11495   * @param collectionGroup The collection group for the documents.
11496   * @param offset The offset to index into.
11497   * @param count The number of documents to return
11498   * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
11499   */
11500  getNextDocuments(e, t, n, r) {
11501    return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i) => {
11502      const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap());
11503      let o = Q, _ = i;
11504      return s.next((t2) => PersistencePromise.forEach(t2, (t3, n2) => (o < n2.largestBatchId && (o = n2.largestBatchId), i.get(t3) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t3).next((e2) => {
11505        _ = _.insert(t3, e2);
11506      }))).next(() => this.populateOverlays(e, t2, i)).next(() => this.computeViews(e, _, t2, __PRIVATE_documentKeySet())).next((e2) => ({
11507        batchId: o,
11508        changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e2)
11509      })));
11510    });
11511  }
11512  getDocumentsMatchingDocumentQuery(e, t) {
11513    return this.getDocument(e, new DocumentKey(t)).next((e2) => {
11514      let t2 = documentMap();
11515      return e2.isFoundDocument() && (t2 = t2.insert(e2.key, e2)), t2;
11516    });
11517  }
11518  getDocumentsMatchingCollectionGroupQuery(e, t, n, r) {
11519    const i = t.collectionGroup;
11520    let s = documentMap();
11521    return this.indexManager.getCollectionParents(e, i).next((o) => PersistencePromise.forEach(o, (o2) => {
11522      const _ = function __PRIVATE_asCollectionQueryAtPath(e2, t2) {
11523        return new __PRIVATE_QueryImpl(
11524          t2,
11525          /*collectionGroup=*/
11526          null,
11527          e2.explicitOrderBy.slice(),
11528          e2.filters.slice(),
11529          e2.limit,
11530          e2.limitType,
11531          e2.startAt,
11532          e2.endAt
11533        );
11534      }(t, o2.child(i));
11535      return this.getDocumentsMatchingCollectionQuery(e, _, n, r).next((e2) => {
11536        e2.forEach((e3, t2) => {
11537          s = s.insert(e3, t2);
11538        });
11539      });
11540    }).next(() => s));
11541  }
11542  getDocumentsMatchingCollectionQuery(e, t, n, r) {
11543    let i;
11544    return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((s) => (i = s, this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r))).next((e2) => {
11545      i.forEach((t2, n3) => {
11546        const r2 = n3.getKey();
11547        null === e2.get(r2) && (e2 = e2.insert(r2, MutableDocument.newInvalidDocument(r2)));
11548      });
11549      let n2 = documentMap();
11550      return e2.forEach((e3, r2) => {
11551        const s = i.get(e3);
11552        void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, r2, FieldMask.empty(), Timestamp.now()), // Finally, insert the documents that still match the query
11553        __PRIVATE_queryMatches(t, r2) && (n2 = n2.insert(e3, r2));
11554      }), n2;
11555    });
11556  }
11557}
11558/**
11559 * @license
11560 * Copyright 2020 Google LLC
11561 *
11562 * Licensed under the Apache License, Version 2.0 (the "License");
11563 * you may not use this file except in compliance with the License.
11564 * You may obtain a copy of the License at
11565 *
11566 *   http://www.apache.org/licenses/LICENSE-2.0
11567 *
11568 * Unless required by applicable law or agreed to in writing, software
11569 * distributed under the License is distributed on an "AS IS" BASIS,
11570 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11571 * See the License for the specific language governing permissions and
11572 * limitations under the License.
11573 */
11574class __PRIVATE_MemoryBundleCache {
11575  constructor(e) {
11576    this.serializer = e, this.Br = /* @__PURE__ */ new Map(), this.Lr = /* @__PURE__ */ new Map();
11577  }
11578  getBundleMetadata(e, t) {
11579    return PersistencePromise.resolve(this.Br.get(t));
11580  }
11581  saveBundleMetadata(e, t) {
11582    return this.Br.set(
11583      t.id,
11584      /** Decodes a BundleMetadata proto into a BundleMetadata object. */
11585      function __PRIVATE_fromBundleMetadata(e2) {
11586        return {
11587          id: e2.id,
11588          version: e2.version,
11589          createTime: __PRIVATE_fromVersion(e2.createTime)
11590        };
11591      }(t)
11592    ), PersistencePromise.resolve();
11593  }
11594  getNamedQuery(e, t) {
11595    return PersistencePromise.resolve(this.Lr.get(t));
11596  }
11597  saveNamedQuery(e, t) {
11598    return this.Lr.set(t.name, function __PRIVATE_fromProtoNamedQuery(e2) {
11599      return {
11600        name: e2.name,
11601        query: __PRIVATE_fromBundledQuery(e2.bundledQuery),
11602        readTime: __PRIVATE_fromVersion(e2.readTime)
11603      };
11604    }(t)), PersistencePromise.resolve();
11605  }
11606}
11607/**
11608 * @license
11609 * Copyright 2022 Google LLC
11610 *
11611 * Licensed under the Apache License, Version 2.0 (the "License");
11612 * you may not use this file except in compliance with the License.
11613 * You may obtain a copy of the License at
11614 *
11615 *   http://www.apache.org/licenses/LICENSE-2.0
11616 *
11617 * Unless required by applicable law or agreed to in writing, software
11618 * distributed under the License is distributed on an "AS IS" BASIS,
11619 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11620 * See the License for the specific language governing permissions and
11621 * limitations under the License.
11622 */
11623class __PRIVATE_MemoryDocumentOverlayCache {
11624  constructor() {
11625    this.overlays = new SortedMap(DocumentKey.comparator), this.kr = /* @__PURE__ */ new Map();
11626  }
11627  getOverlay(e, t) {
11628    return PersistencePromise.resolve(this.overlays.get(t));
11629  }
11630  getOverlays(e, t) {
11631    const n = __PRIVATE_newOverlayMap();
11632    return PersistencePromise.forEach(t, (t2) => this.getOverlay(e, t2).next((e2) => {
11633      null !== e2 && n.set(t2, e2);
11634    })).next(() => n);
11635  }
11636  saveOverlays(e, t, n) {
11637    return n.forEach((n2, r) => {
11638      this.wt(e, t, r);
11639    }), PersistencePromise.resolve();
11640  }
11641  removeOverlaysForBatchId(e, t, n) {
11642    const r = this.kr.get(n);
11643    return void 0 !== r && (r.forEach((e2) => this.overlays = this.overlays.remove(e2)), this.kr.delete(n)), PersistencePromise.resolve();
11644  }
11645  getOverlaysForCollection(e, t, n) {
11646    const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child("")), o = this.overlays.getIteratorFrom(s);
11647    for (; o.hasNext(); ) {
11648      const e2 = o.getNext().value, s2 = e2.getKey();
11649      if (!t.isPrefixOf(s2.path)) break;
11650      s2.path.length === i && (e2.largestBatchId > n && r.set(e2.getKey(), e2));
11651    }
11652    return PersistencePromise.resolve(r);
11653  }
11654  getOverlaysForCollectionGroup(e, t, n, r) {
11655    let i = new SortedMap((e2, t2) => e2 - t2);
11656    const s = this.overlays.getIterator();
11657    for (; s.hasNext(); ) {
11658      const e2 = s.getNext().value;
11659      if (e2.getKey().getCollectionGroup() === t && e2.largestBatchId > n) {
11660        let t2 = i.get(e2.largestBatchId);
11661        null === t2 && (t2 = __PRIVATE_newOverlayMap(), i = i.insert(e2.largestBatchId, t2)), t2.set(e2.getKey(), e2);
11662      }
11663    }
11664    const o = __PRIVATE_newOverlayMap(), _ = i.getIterator();
11665    for (; _.hasNext(); ) {
11666      if (_.getNext().value.forEach((e2, t2) => o.set(e2, t2)), o.size() >= r) break;
11667    }
11668    return PersistencePromise.resolve(o);
11669  }
11670  wt(e, t, n) {
11671    const r = this.overlays.get(n.key);
11672    if (null !== r) {
11673      const e2 = this.kr.get(r.largestBatchId).delete(n.key);
11674      this.kr.set(r.largestBatchId, e2);
11675    }
11676    this.overlays = this.overlays.insert(n.key, new Overlay(t, n));
11677    let i = this.kr.get(t);
11678    void 0 === i && (i = __PRIVATE_documentKeySet(), this.kr.set(t, i)), this.kr.set(t, i.add(n.key));
11679  }
11680}
11681/**
11682 * @license
11683 * Copyright 2024 Google LLC
11684 *
11685 * Licensed under the Apache License, Version 2.0 (the "License");
11686 * you may not use this file except in compliance with the License.
11687 * You may obtain a copy of the License at
11688 *
11689 *   http://www.apache.org/licenses/LICENSE-2.0
11690 *
11691 * Unless required by applicable law or agreed to in writing, software
11692 * distributed under the License is distributed on an "AS IS" BASIS,
11693 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11694 * See the License for the specific language governing permissions and
11695 * limitations under the License.
11696 */
11697class __PRIVATE_MemoryGlobalsCache {
11698  constructor() {
11699    this.sessionToken = ByteString.EMPTY_BYTE_STRING;
11700  }
11701  getSessionToken(e) {
11702    return PersistencePromise.resolve(this.sessionToken);
11703  }
11704  setSessionToken(e, t) {
11705    return this.sessionToken = t, PersistencePromise.resolve();
11706  }
11707}
11708/**
11709 * @license
11710 * Copyright 2017 Google LLC
11711 *
11712 * Licensed under the Apache License, Version 2.0 (the "License");
11713 * you may not use this file except in compliance with the License.
11714 * You may obtain a copy of the License at
11715 *
11716 *   http://www.apache.org/licenses/LICENSE-2.0
11717 *
11718 * Unless required by applicable law or agreed to in writing, software
11719 * distributed under the License is distributed on an "AS IS" BASIS,
11720 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11721 * See the License for the specific language governing permissions and
11722 * limitations under the License.
11723 */
11724class __PRIVATE_ReferenceSet {
11725  constructor() {
11726    this.qr = new SortedSet(__PRIVATE_DocReference.Qr), // A set of outstanding references to a document sorted by target id.
11727    this.$r = new SortedSet(__PRIVATE_DocReference.Ur);
11728  }
11729  /** Returns true if the reference set contains no references. */
11730  isEmpty() {
11731    return this.qr.isEmpty();
11732  }
11733  /** Adds a reference to the given document key for the given ID. */
11734  addReference(e, t) {
11735    const n = new __PRIVATE_DocReference(e, t);
11736    this.qr = this.qr.add(n), this.$r = this.$r.add(n);
11737  }
11738  /** Add references to the given document keys for the given ID. */
11739  Kr(e, t) {
11740    e.forEach((e2) => this.addReference(e2, t));
11741  }
11742  /**
11743   * Removes a reference to the given document key for the given
11744   * ID.
11745   */
11746  removeReference(e, t) {
11747    this.Wr(new __PRIVATE_DocReference(e, t));
11748  }
11749  Gr(e, t) {
11750    e.forEach((e2) => this.removeReference(e2, t));
11751  }
11752  /**
11753   * Clears all references with a given ID. Calls removeRef() for each key
11754   * removed.
11755   */
11756  zr(e) {
11757    const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = [];
11758    return this.$r.forEachInRange([n, r], (e2) => {
11759      this.Wr(e2), i.push(e2.key);
11760    }), i;
11761  }
11762  jr() {
11763    this.qr.forEach((e) => this.Wr(e));
11764  }
11765  Wr(e) {
11766    this.qr = this.qr.delete(e), this.$r = this.$r.delete(e);
11767  }
11768  Jr(e) {
11769    const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1);
11770    let i = __PRIVATE_documentKeySet();
11771    return this.$r.forEachInRange([n, r], (e2) => {
11772      i = i.add(e2.key);
11773    }), i;
11774  }
11775  containsKey(e) {
11776    const t = new __PRIVATE_DocReference(e, 0), n = this.qr.firstAfterOrEqual(t);
11777    return null !== n && e.isEqual(n.key);
11778  }
11779}
11780class __PRIVATE_DocReference {
11781  constructor(e, t) {
11782    this.key = e, this.Hr = t;
11783  }
11784  /** Compare by key then by ID */
11785  static Qr(e, t) {
11786    return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.Hr, t.Hr);
11787  }
11788  /** Compare by ID then by key */
11789  static Ur(e, t) {
11790    return __PRIVATE_primitiveComparator(e.Hr, t.Hr) || DocumentKey.comparator(e.key, t.key);
11791  }
11792}
11793/**
11794 * @license
11795 * Copyright 2017 Google LLC
11796 *
11797 * Licensed under the Apache License, Version 2.0 (the "License");
11798 * you may not use this file except in compliance with the License.
11799 * You may obtain a copy of the License at
11800 *
11801 *   http://www.apache.org/licenses/LICENSE-2.0
11802 *
11803 * Unless required by applicable law or agreed to in writing, software
11804 * distributed under the License is distributed on an "AS IS" BASIS,
11805 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11806 * See the License for the specific language governing permissions and
11807 * limitations under the License.
11808 */
11809class __PRIVATE_MemoryMutationQueue {
11810  constructor(e, t) {
11811    this.indexManager = e, this.referenceDelegate = t, /**
11812    * The set of all mutations that have been sent but not yet been applied to
11813    * the backend.
11814    */
11815    this.mutationQueue = [], /** Next value to use when assigning sequential IDs to each mutation batch. */
11816    this.er = 1, /** An ordered mapping between documents and the mutations batch IDs. */
11817    this.Yr = new SortedSet(__PRIVATE_DocReference.Qr);
11818  }
11819  checkEmpty(e) {
11820    return PersistencePromise.resolve(0 === this.mutationQueue.length);
11821  }
11822  addMutationBatch(e, t, n, r) {
11823    const i = this.er;
11824    this.er++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
11825    const s = new MutationBatch(i, t, n, r);
11826    this.mutationQueue.push(s);
11827    for (const t2 of r) this.Yr = this.Yr.add(new __PRIVATE_DocReference(t2.key, i)), this.indexManager.addToCollectionParentIndex(e, t2.key.path.popLast());
11828    return PersistencePromise.resolve(s);
11829  }
11830  lookupMutationBatch(e, t) {
11831    return PersistencePromise.resolve(this.Zr(t));
11832  }
11833  getNextMutationBatchAfterBatchId(e, t) {
11834    const n = t + 1, r = this.Xr(n), i = r < 0 ? 0 : r;
11835    return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
11836  }
11837  getHighestUnacknowledgedBatchId() {
11838    return PersistencePromise.resolve(0 === this.mutationQueue.length ? G : this.er - 1);
11839  }
11840  getAllMutationBatches(e) {
11841    return PersistencePromise.resolve(this.mutationQueue.slice());
11842  }
11843  getAllMutationBatchesAffectingDocumentKey(e, t) {
11844    const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = [];
11845    return this.Yr.forEachInRange([n, r], (e2) => {
11846      const t2 = this.Zr(e2.Hr);
11847      i.push(t2);
11848    }), PersistencePromise.resolve(i);
11849  }
11850  getAllMutationBatchesAffectingDocumentKeys(e, t) {
11851    let n = new SortedSet(__PRIVATE_primitiveComparator);
11852    return t.forEach((e2) => {
11853      const t2 = new __PRIVATE_DocReference(e2, 0), r = new __PRIVATE_DocReference(e2, Number.POSITIVE_INFINITY);
11854      this.Yr.forEachInRange([t2, r], (e3) => {
11855        n = n.add(e3.Hr);
11856      });
11857    }), PersistencePromise.resolve(this.ei(n));
11858  }
11859  getAllMutationBatchesAffectingQuery(e, t) {
11860    const n = t.path, r = n.length + 1;
11861    let i = n;
11862    DocumentKey.isDocumentKey(i) || (i = i.child(""));
11863    const s = new __PRIVATE_DocReference(new DocumentKey(i), 0);
11864    let o = new SortedSet(__PRIVATE_primitiveComparator);
11865    return this.Yr.forEachWhile((e2) => {
11866      const t2 = e2.key.path;
11867      return !!n.isPrefixOf(t2) && // Rows with document keys more than one segment longer than the query
11868      // path can't be matches. For example, a query on 'rooms' can't match
11869      // the document /rooms/abc/messages/xyx.
11870      // TODO(mcg): we'll need a different scanner when we implement
11871      // ancestor queries.
11872      (t2.length === r && (o = o.add(e2.Hr)), true);
11873    }, s), PersistencePromise.resolve(this.ei(o));
11874  }
11875  ei(e) {
11876    const t = [];
11877    return e.forEach((e2) => {
11878      const n = this.Zr(e2);
11879      null !== n && t.push(n);
11880    }), t;
11881  }
11882  removeMutationBatch(e, t) {
11883    __PRIVATE_hardAssert(0 === this.ti(t.batchId, "removed"), 55003), this.mutationQueue.shift();
11884    let n = this.Yr;
11885    return PersistencePromise.forEach(t.mutations, (r) => {
11886      const i = new __PRIVATE_DocReference(r.key, t.batchId);
11887      return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key);
11888    }).next(() => {
11889      this.Yr = n;
11890    });
11891  }
11892  rr(e) {
11893  }
11894  containsKey(e, t) {
11895    const n = new __PRIVATE_DocReference(t, 0), r = this.Yr.firstAfterOrEqual(n);
11896    return PersistencePromise.resolve(t.isEqual(r && r.key));
11897  }
11898  performConsistencyCheck(e) {
11899    return this.mutationQueue.length, PersistencePromise.resolve();
11900  }
11901  /**
11902   * Finds the index of the given batchId in the mutation queue and asserts that
11903   * the resulting index is within the bounds of the queue.
11904   *
11905   * @param batchId - The batchId to search for
11906   * @param action - A description of what the caller is doing, phrased in passive
11907   * form (e.g. "acknowledged" in a routine that acknowledges batches).
11908   */
11909  ti(e, t) {
11910    return this.Xr(e);
11911  }
11912  /**
11913   * Finds the index of the given batchId in the mutation queue. This operation
11914   * is O(1).
11915   *
11916   * @returns The computed index of the batch with the given batchId, based on
11917   * the state of the queue. Note this index can be negative if the requested
11918   * batchId has already been removed from the queue or past the end of the
11919   * queue if the batchId is larger than the last added batch.
11920   */
11921  Xr(e) {
vendor: 3,980 bytes, lines 11922-12030
11922    if (0 === this.mutationQueue.length)
11923      return 0;
11924    return e - this.mutationQueue[0].batchId;
11925  }
11926  /**
11927   * A version of lookupMutationBatch that doesn't return a promise, this makes
11928   * other functions that uses this code easier to read and more efficient.
11929   */
11930  Zr(e) {
11931    const t = this.Xr(e);
11932    if (t < 0 || t >= this.mutationQueue.length) return null;
11933    return this.mutationQueue[t];
11934  }
11935}
11936/**
11937 * @license
11938 * Copyright 2017 Google LLC
11939 *
11940 * Licensed under the Apache License, Version 2.0 (the "License");
11941 * you may not use this file except in compliance with the License.
11942 * You may obtain a copy of the License at
11943 *
11944 *   http://www.apache.org/licenses/LICENSE-2.0
11945 *
11946 * Unless required by applicable law or agreed to in writing, software
11947 * distributed under the License is distributed on an "AS IS" BASIS,
11948 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11949 * See the License for the specific language governing permissions and
11950 * limitations under the License.
11951 */
11952class __PRIVATE_MemoryRemoteDocumentCacheImpl {
11953  /**
11954   * @param sizer - Used to assess the size of a document. For eager GC, this is
11955   * expected to just return 0 to avoid unnecessarily doing the work of
11956   * calculating the size.
11957   */
11958  constructor(e) {
11959    this.ni = e, /** Underlying cache of documents and their read times. */
11960    this.docs = function __PRIVATE_documentEntryMap() {
11961      return new SortedMap(DocumentKey.comparator);
11962    }(), /** Size of all cached documents. */
11963    this.size = 0;
11964  }
11965  setIndexManager(e) {
11966    this.indexManager = e;
11967  }
11968  /**
11969   * Adds the supplied entry to the cache and updates the cache size as appropriate.
11970   *
11971   * All calls of `addEntry`  are required to go through the RemoteDocumentChangeBuffer
11972   * returned by `newChangeBuffer()`.
11973   */
11974  addEntry(e, t) {
11975    const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.ni(t);
11976    return this.docs = this.docs.insert(n, {
11977      document: t.mutableCopy(),
11978      size: s
11979    }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast());
11980  }
11981  /**
11982   * Removes the specified entry from the cache and updates the cache size as appropriate.
11983   *
11984   * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
11985   * returned by `newChangeBuffer()`.
11986   */
11987  removeEntry(e) {
11988    const t = this.docs.get(e);
11989    t && (this.docs = this.docs.remove(e), this.size -= t.size);
11990  }
11991  getEntry(e, t) {
11992    const n = this.docs.get(t);
11993    return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t));
11994  }
11995  getEntries(e, t) {
11996    let n = __PRIVATE_mutableDocumentMap();
11997    return t.forEach((e2) => {
11998      const t2 = this.docs.get(e2);
11999      n = n.insert(e2, t2 ? t2.document.mutableCopy() : MutableDocument.newInvalidDocument(e2));
12000    }), PersistencePromise.resolve(n);
12001  }
12002  getDocumentsMatchingQuery(e, t, n, r) {
12003    let i = __PRIVATE_mutableDocumentMap();
12004    const s = t.path, o = new DocumentKey(s.child("__id-9223372036854775808__")), _ = this.docs.getIteratorFrom(o);
12005    for (; _.hasNext(); ) {
12006      const { key: e2, value: { document: o2 } } = _.getNext();
12007      if (!s.isPrefixOf(e2.path)) break;
12008      e2.path.length > s.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o2), n) <= 0 || (r.has(o2.key) || __PRIVATE_queryMatches(t, o2)) && (i = i.insert(o2.key, o2.mutableCopy())));
12009    }
12010    return PersistencePromise.resolve(i);
12011  }
12012  getAllFromCollectionGroup(e, t, n, r) {
12013    fail(9500);
12014  }
12015  ri(e, t) {
12016    return PersistencePromise.forEach(this.docs, (e2) => t(e2));
12017  }
12018  newChangeBuffer(e) {
12019    return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this);
12020  }
12021  getSize(e) {
12022    return PersistencePromise.resolve(this.size);
12023  }
12024}
12025class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {
12026  constructor(e) {
12027    super(), this.Or = e;
12028  }
12029  applyChanges(e) {
12030    const t = [];
12031    return this.changes.forEach((n, r) => {
12032      r.isValidDocument() ? t.push(this.Or.addEntry(e, r)) : this.Or.removeEntry(n);
12033    }), PersistencePromise.waitFor(t);
12034  }
12035  getFromCache(e, t) {
12036    return this.Or.getEntry(e, t);
12037  }
12038  getAllFromCache(e, t) {
12039    return this.Or.getEntries(e, t);
12040  }
12041}
12042/**
12043 * @license
12044 * Copyright 2017 Google LLC
12045 *
12046 * Licensed under the Apache License, Version 2.0 (the "License");
12047 * you may not use this file except in compliance with the License.
12048 * You may obtain a copy of the License at
12049 *
12050 *   http://www.apache.org/licenses/LICENSE-2.0
12051 *
12052 * Unless required by applicable law or agreed to in writing, software
12053 * distributed under the License is distributed on an "AS IS" BASIS,
12054 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12055 * See the License for the specific language governing permissions and
12056 * limitations under the License.
12057 */
12058class __PRIVATE_MemoryTargetCache {
12059  constructor(e) {
12060    this.persistence = e, /**
12061    * Maps a target to the data about that target
12062    */
12063    this.ii = new ObjectMap((e2) => __PRIVATE_canonifyTarget(e2), __PRIVATE_targetEquals), /** The last received snapshot version. */
12064    this.lastRemoteSnapshotVersion = SnapshotVersion.min(), /** The highest numbered target ID encountered. */
12065    this.highestTargetId = 0, /** The highest sequence number encountered. */
12066    this.si = 0, /**
12067    * A ordered bidirectional mapping between documents and the remote target
12068    * IDs.
12069    */
12070    this.oi = new __PRIVATE_ReferenceSet(), this.targetCount = 0, this._i = __PRIVATE_TargetIdGenerator.ar();
12071  }
12072  forEachTarget(e, t) {
12073    return this.ii.forEach((e2, n) => t(n)), PersistencePromise.resolve();
12074  }
12075  getLastRemoteSnapshotVersion(e) {
12076    return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);
12077  }
12078  getHighestSequenceNumber(e) {
12079    return PersistencePromise.resolve(this.si);
12080  }
12081  allocateTargetId(e) {
12082    return this.highestTargetId = this._i.next(), PersistencePromise.resolve(this.highestTargetId);
12083  }
12084  setTargetsMetadata(e, t, n) {
12085    return n && (this.lastRemoteSnapshotVersion = n), t > this.si && (this.si = t), PersistencePromise.resolve();
12086  }
12087  hr(e) {
12088    this.ii.set(e.target, e);
12089    const t = e.targetId;
12090    t > this.highestTargetId && (this._i = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), e.sequenceNumber > this.si && (this.si = e.sequenceNumber);
12091  }
12092  addTargetData(e, t) {
12093    return this.hr(t), this.targetCount += 1, PersistencePromise.resolve();
12094  }
12095  updateTargetData(e, t) {
12096    return this.hr(t), PersistencePromise.resolve();
12097  }
12098  removeTargetData(e, t) {
12099    return this.ii.delete(t.target), this.oi.zr(t.targetId), this.targetCount -= 1, PersistencePromise.resolve();
12100  }
12101  removeTargets(e, t, n) {
12102    let r = 0;
12103    const i = [];
12104    return this.ii.forEach((s, o) => {
12105      o.sequenceNumber <= t && null === n.get(o.targetId) && (this.ii.delete(s), i.push(this.removeMatchingKeysForTargetId(e, o.targetId)), r++);
12106    }), PersistencePromise.waitFor(i).next(() => r);
12107  }
12108  getTargetCount(e) {
12109    return PersistencePromise.resolve(this.targetCount);
12110  }
12111  getTargetData(e, t) {
12112    const n = this.ii.get(t) || null;
12113    return PersistencePromise.resolve(n);
12114  }
12115  addMatchingKeys(e, t, n) {
12116    return this.oi.Kr(t, n), PersistencePromise.resolve();
12117  }
12118  removeMatchingKeys(e, t, n) {
12119    this.oi.Gr(t, n);
12120    const r = this.persistence.referenceDelegate, i = [];
12121    return r && t.forEach((t2) => {
12122      i.push(r.markPotentiallyOrphaned(e, t2));
12123    }), PersistencePromise.waitFor(i);
12124  }
12125  removeMatchingKeysForTargetId(e, t) {
12126    return this.oi.zr(t), PersistencePromise.resolve();
12127  }
12128  getMatchingKeysForTargetId(e, t) {
12129    const n = this.oi.Jr(t);
12130    return PersistencePromise.resolve(n);
12131  }
12132  containsKey(e, t) {
12133    return PersistencePromise.resolve(this.oi.containsKey(t));
12134  }
12135}
12136/**
12137 * @license
12138 * Copyright 2017 Google LLC
12139 *
12140 * Licensed under the Apache License, Version 2.0 (the "License");
12141 * you may not use this file except in compliance with the License.
12142 * You may obtain a copy of the License at
12143 *
12144 *   http://www.apache.org/licenses/LICENSE-2.0
12145 *
12146 * Unless required by applicable law or agreed to in writing, softw
12146are
12147 * distributed under the License is distributed on an "AS IS" BASIS,
12148 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12149 * See the License for the specific language governing permissions and
12150 * limitations under the License.
12151 */
12152class __PRIVATE_MemoryPersistence {
12153  /**
12154   * The constructor accepts a factory for creating a reference delegate. This
12155   * allows both the delegate and this instance to have strong references to
12156   * each other without having nullable fields that would then need to be
12157   * checked or asserted on every access.
12158   */
12159  constructor(e, t) {
12160    this.ai = {}, this.overlays = {}, this.ui = new __PRIVATE_ListenSequence(0), this.ci = false, this.ci = true, this.li = new __PRIVATE_MemoryGlobalsCache(), this.referenceDelegate = e(this), this.hi = new __PRIVATE_MemoryTargetCache(this);
12161    this.indexManager = new __PRIVATE_MemoryIndexManager(), this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e2) {
12162      return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e2);
12163    }((e2) => this.referenceDelegate.Pi(e2)), this.serializer = new __PRIVATE_LocalSerializer(t), this.Ti = new __PRIVATE_MemoryBundleCache(this.serializer);
12164  }
12165  start() {
12166    return Promise.resolve();
12167  }
12168  shutdown() {
12169    return this.ci = false, Promise.resolve();
12170  }
12171  get started() {
12172    return this.ci;
12173  }
12174  setDatabaseDeletedListener() {
12175  }
12176  setNetworkEnabled() {
12177  }
12178  getIndexManager(e) {
12179    return this.indexManager;
12180  }
12181  getDocumentOverlayCache(e) {
12182    let t = this.overlays[e.toKey()];
12183    return t || (t = new __PRIVATE_MemoryDocumentOverlayCache(), this.overlays[e.toKey()] = t), t;
12184  }
12185  getMutationQueue(e, t) {
12186    let n = this.ai[e.toKey()];
12187    return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.ai[e.toKey()] = n), n;
12188  }
12189  getGlobalsCache() {
12190    return this.li;
12191  }
12192  getTargetCache() {
12193    return this.hi;
12194  }
12195  getRemoteDocumentCache() {
12196    return this.remoteDocumentCache;
12197  }
12198  getBundleCache() {
12199    return this.Ti;
12200  }
12201  runTransaction(e, t, n) {
12202    __PRIVATE_logDebug("MemoryPersistence", "Starting transaction:", e);
12203    const r = new __PRIVATE_MemoryTransaction(this.ui.next());
12204    return this.referenceDelegate.Ii(), n(r).next((e2) => this.referenceDelegate.di(r).next(() => e2)).toPromise().then((e2) => (r.raiseOnCommittedEvent(), e2));
12205  }
12206  Ei(e, t) {
12207    return PersistencePromise.or(Object.values(this.ai).map((n) => () => n.containsKey(e, t)));
12208  }
12209}
12210class __PRIVATE_MemoryTransaction extends PersistenceTransaction {
12211  constructor(e) {
12212    super(), this.currentSequenceNumber = e;
12213  }
12214}
12215class __PRIVATE_MemoryEagerDelegate {
12216  constructor(e) {
12217    this.persistence = e, /** Tracks all documents that are active in Query views. */
12218    this.Ai = new __PRIVATE_ReferenceSet(), /** The list of documents that are potentially GCed after each transaction. */
12219    this.Ri = null;
12220  }
12221  static Vi(e) {
12222    return new __PRIVATE_MemoryEagerDelegate(e);
12223  }
12224  get mi() {
12225    if (this.Ri) return this.Ri;
12226    throw fail(60996);
12227  }
12228  addReference(e, t, n) {
12229    return this.Ai.addReference(n, t), this.mi.delete(n.toString()), PersistencePromise.resolve();
12230  }
12231  removeReference(e, t, n) {
12232    return this.Ai.removeReference(n, t), this.mi.add(n.toString()), PersistencePromise.resolve();
12233  }
12234  markPotentiallyOrphaned(e, t) {
12235    return this.mi.add(t.toString()), PersistencePromise.resolve();
12236  }
12237  removeTarget(e, t) {
12238    this.Ai.zr(t.targetId).forEach((e2) => this.mi.add(e2.toString()));
12239    const n = this.persistence.getTargetCache();
12240    return n.getMatchingKeysForTargetId(e, t.targetId).next((e2) => {
12241      e2.forEach((e3) => this.mi.add(e3.toString()));
12242    }).next(() => n.removeTargetData(e, t));
12243  }
12244  Ii() {
12245    this.Ri = /* @__PURE__ */ new Set();
12246  }
12247  di(e) {
12248    const t = this.persistence.getRemoteDocumentCache().newChangeBuffer();
12249    return PersistencePromise.forEach(this.mi, (n) => {
12250      const r = DocumentKey.fromPath(n);
12251      return this.fi(e, r).next((e2) => {
12252        e2 || t.removeEntry(r, SnapshotVersion.min());
12253      });
12254    }).next(() => (this.Ri = null, t.apply(e)));
12255  }
12256  updateLimboDocument(e, t) {
12257    return this.fi(e, t).next((e2) => {
12258      e2 ? this.mi.delete(t.toString()) : this.mi.add(t.toString());
12259    });
12260  }
12261  Pi(e) {
12262    return 0;
12263  }
12264  fi(e, t) {
12265    return PersistencePromise.or([() => PersistencePromise.resolve(this.Ai.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.Ei(e, t)]);
12266  }
12267}
12268class __PRIVATE_MemoryLruDelegate {
12269  constructor(e, t) {
12270    this.persistence = e, this.gi = new ObjectMap((e2) => __PRIVATE_encodeResourcePath(e2.path), (e2, t2) => e2.isEqual(t2)), this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);
12271  }
12272  static Vi(e, t) {
12273    return new __PRIVATE_MemoryLruDelegate(e, t);
12274  }
12275  // No-ops, present so memory persistence doesn't have to care which delegate
12276  // it has.
12277  Ii() {
12278  }
12279  di(e) {
12280    return PersistencePromise.resolve();
12281  }
12282  forEachTarget(e, t) {
12283    return this.persistence.getTargetCache().forEachTarget(e, t);
12284  }
12285  mr(e) {
12286    const t = this.yr(e);
12287    return this.persistence.getTargetCache().getTargetCount(e).next((e2) => t.next((t2) => e2 + t2));
12288  }
12289  yr(e) {
12290    let t = 0;
12291    return this.gr(e, (e2) => {
12292      t++;
12293    }).next(() => t);
12294  }
12295  gr(e, t) {
12296    return PersistencePromise.forEach(this.gi, (n, r) => this.Sr(e, n, r).next((e2) => e2 ? PersistencePromise.resolve() : t(r)));
12297  }
12298  removeTargets(e, t, n) {
12299    return this.persistence.getTargetCache().removeTargets(e, t, n);
12300  }
12301  removeOrphanedDocuments(e, t) {
12302    let n = 0;
12303    const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer();
12304    return r.ri(e, (r2) => this.Sr(e, r2, t).next((e2) => {
12305      e2 || (n++, i.removeEntry(r2, SnapshotVersion.min()));
12306    })).next(() => i.apply(e)).next(() => n);
12307  }
12308  markPotentiallyOrphaned(e, t) {
12309    return this.gi.set(t, e.currentSequenceNumber), PersistencePromise.resolve();
12310  }
12311  removeTarget(e, t) {
12312    const n = t.withSequenceNumber(e.currentSequenceNumber);
12313    return this.persistence.getTargetCache().updateTargetData(e, n);
12314  }
12315  addReference(e, t, n) {
12316    return this.gi.set(n, e.currentSequenceNumber), PersistencePromise.resolve();
12317  }
12318  removeReference(e, t, n) {
12319    return this.gi.set(n, e.currentSequenceNumber), PersistencePromise.resolve();
12320  }
12321  updateLimboDocument(e, t) {
12322    return this.gi.set(t, e.currentSequenceNumber), PersistencePromise.resolve();
12323  }
12324  Pi(e) {
12325    let t = e.key.toString().length;
12326    return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t;
12327  }
12328  Sr(e, t, n) {
12329    return PersistencePromise.or([() => this.persistence.Ei(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => {
12330      const e2 = this.gi.get(t);
12331      return PersistencePromise.resolve(void 0 !== e2 && e2 > n);
12332    }]);
12333  }
12334  getCacheSize(e) {
12335    return this.persistence.getRemoteDocumentCache().getSize(e);
12336  }
12337}
12338/**
12339 * @license
12340 * Copyright 2020 Google LLC
12341 *
12342 * Licensed under the Apache License, Version 2.0 (the "License");
12343 * you may not use this file except in compliance with the License.
12344 * You may obtain a copy of the License at
12345 *
12346 *   http://www.apache.org/licenses/LICENSE-2.0
12347 *
12348 * Unless required by applicable law or agreed to in writing, software
12349 * distributed under the License is distributed on an "AS IS" BASIS,
12350 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12351 * See the License for the specific language governing permissions and
12352 * limitations under the License.
12353 */
12354class __PRIVATE_SchemaConverter {
12355  constructor(e) {
12356    this.serializer = e;
12357  }
12358  /**
12359   * Performs database creation and schema upgrades.
12360   *
12361   * Note that in production, this method is only ever used to upgrade the schema
12362   * to SCHEMA_VERSION. Different values of toVersion are only used for testing
12363   * and local feature development.
12364   */
12365  q(e, t, n, r) {
12366    const i = new __PRIVATE_SimpleDbTransaction("createOrUpgrade", t);
12367    n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e2) {
12368      e2.createObjectStore(J);
12369    }(e), function __PRIVATE_createMutationQueue(e2) {
12370      e2.createObjectStore(Y, {
12371        keyPath: Z
12372      });
12373      const t2 = e2.createObjectStore(X, {
12374        keyPath: ee,
12375        autoIncrement: true
12376      });
12377      t2.createIndex(te, ne, {
12378        unique: true
12379      }), e2.createObjectStore(ie);
12380    }(e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e2) {
12381      e2.createObjectStore(j);
12382    }(e));
12383    let s = PersistencePromise.resolve();
12384    return n < 3 && r >= 3 && // Brand new clients don't need to drop and recreate--only clients that
12385    // potentially have corrupt data.
12386    (0 !== n && (!function __PRIVATE_dropQueryCache(e2) {
12387      e2.deleteObjectStore(de), e2.deleteObjectStore(Pe), e2.deleteObjectStore(me);
12388    }(e), __PRIVATE_createQueryCache(e)), s = s.next(() => (
12389      /**
12390      * Creates the target global singleton row.
12391      *
12392      * @param txn - The version upgrade transaction for indexeddb
12393      */
12394      function __PRIVATE_writeEmptyTargetGlobalEntry(e2) {
12395        const t2 = e2.store(me), n2 = {
12396          highestTargetId: 0,
12397          highestListenSequenceNumber: 0,
12398          lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),
12399          targetCount: 0
12400        };
12401        return t2.put(Ve, n2);
12402      }(i)
12403    ))), n < 4 && r >= 4 && (0 !== n && // Schema version 3 uses auto-generated keys to generate globally unique
12404    // mutation batch IDs (this was previously ensured internally by the
12405    // client). To migrate to the new schema, we have to read all mutations
12406    // and write them back out. We preserve the existing batch IDs to guarantee
12407    // consistency with other object stores. Any further mutation batch IDs will
12408    // be auto-generated.
12409    (s = s.next(() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e2, t2) {
12410      const n2 = t2.store(X);
12411      return n2.j().next((n3) => {
12412        e2.deleteObjectStore(X);
12413        e2.createObjectStore(X, {
12414          keyPath: ee,
12415          autoIncrement: true
12416        }).createIndex(te, ne, {
12417          unique: true
12418        });
12419        const r2 = t2.store(X), i2 = n3.map((e3) => r2.put(e3));
12420        return PersistencePromise.waitFor(i2);
12421      });
12422    }(e, i))), s = s.next(() => {
12423      !function __PRIVATE_createClientMetadataStore(e2) {
12424        e2.createObjectStore(pe, {
12425          keyPath: ye
12426        });
12427      }(e);
12428    })), n < 5 && r >= 5 && (s = s.next(() => this.pi(i))), n < 6 && r >= 6 && (s = s.next(() => (function __PRIVATE_createDocumentGlobalStore(e2) {
12429      e2.createObjectStore(le);
12430    }(e), this.yi(i)))), n < 7 && r >= 7 && (s = s.next(() => this.wi(i))), n < 8 && r >= 8 && (s = s.next(() => this.Si(e, i))), n < 9 && r >= 9 && (s = s.next(() => {
12431      !function __PRIVATE_dropRemoteDocumentChangesStore(e2) {
12432        e2.objectStoreNames.contains("remoteDocumentChanges") && e2.deleteObjectStore("remoteDocumentChanges");
12433      }(e);
12434    })), n < 10 && r >= 10 && (s = s.next(() => this.bi(i))), n < 11 && r >= 11 && (s = s.next(() => {
12435      !function __PRIVATE_createBundlesStore(e2) {
12436        e2.createObjectStore(we, {
12437          keyPath: Se
12438        });
12439      }(e), function __PRIVATE_createNamedQueriesStore(e2) {
12440        e2.createObjectStore(be, {
12441          keyPath: De
12442        });
12443      }(e);
12444    })), n < 12 && r >= 12 && (s = s.next(() => {
12445      !function __PRIVATE_createDocumentOverlayStore(e2) {
12446        const t2 = e2.createObjectStore($e, {
12447          keyPath: Ue
12448        });
12449        t2.createIndex(Ke, We, {
12450          unique: false
12451        }), t2.createIndex(Ge, ze, {
12452          unique: false
12453        });
12454      }(e);
12455    })), n < 13 && r >= 13 && (s = s.next(() => function __PRIVATE_createRemoteDocumentCache(e2) {
12456      const t2 = e2.createObjectStore(se, {
12457        keyPath: oe
12458      });
12459      t2.createIndex(_e, ae), t2.createIndex(ue, ce);
12460    }(e)).next(() => this.Di(e, i)).next(() => e.deleteObjectStore(j))), n < 14 && r >= 14 && (s = s.next(() => this.Ci(e, i))), n < 15 && r >= 15 && (s = s.next(() => function __PRIVATE_createFieldIndex(e2) {
12461      const t2 = e2.createObjectStore(ve, {
12462        keyPath: Ce,
12463        autoIncrement: true
12464      });
12465      t2.createIndex(Fe, Me, {
12466        unique: false
12467      });
12468      const n2 = e2.createObjectStore(xe, {
12469        keyPath: Oe
12470      });
12471      n2.createIndex(Ne, Be, {
12472        unique: false
12473      });
12474      const r2 = e2.createObjectStore(Le, {
12475        keyPath: ke
12476      });
12477      r2.createIndex(qe, Qe, {
12478        unique: false
12479      });
12480    }(e))), n < 16 && r >= 16 && // Clear the object stores to remove possibly corrupted index entries
12481    (s = s.next(() => {
12482      t.objectStore(xe).clear();
12483    }).next(() => {
12484      t.objectStore(Le).clear();
12485    })), n < 17 && r >= 17 && (s = s.next(() => {
12486      !function __PRIVATE_createGlobalsStore(e2) {
12487        e2.createObjectStore(je, {
12488          keyPath: Je
12489        });
12490      }(e);
12491    })), n < 18 && r >= 18 && isSafariOrWebkit() && (s = s.next(() => {
12492      t.objectStore(xe).clear();
12493    }).next(() => {
12494      t.objectStore(Le).clear();
12495    })), s;
12496  }
12497  yi(e) {
12498    let t = 0;
12499    return e.store(j).X((e2, n) => {
12500      t += __PRIVATE_dbDocumentSize(n);
12501    }).next(() => {
12502      const n = {
12503        byteSize: t
12504      };
12505      return e.store(le).put(he, n);
12506    });
12507  }
12508  pi(e) {
12509    const t = e.store(Y), n = e.store(X);
12510    return t.j().next((t2) => PersistencePromise.forEach(t2, (t3) => {
12511      const r = IDBKeyRange.bound([t3.userId, G], [t3.userId, t3.lastAcknowledgedBatchId]);
12512      return n.j(te, r).next((n2) => PersistencePromise.forEach(n2, (n3) => {
12513        __PRIVATE_hardAssert(n3.userId === t3.userId, 18650, "Cannot process batch from unexpected user", {
12514          batchId: n3.batchId
12515        });
12516        const r2 = __PRIVATE_fromDbMutationBatch(this.serializer, n3);
12517        return removeMutationBatch(e, t3.userId, r2).next(() => {
12518        });
12519      }));
12520    }));
12521  }
12522  /**
12523   * Ensures that every document in the remote document cache has a corresponding sentinel row
12524   * with a sequence number. Missing rows are given the most recently used sequence number.
12525   */
12526  wi(e) {
12527    const t = e.store(de), n = e.store(j);
12528    return e.store(me).get(Ve).next((e2) => {
12529      const r = [];
12530      return n.X((n2, i) => {
12531        const s = new ResourcePath(n2), o = function __PRIVATE_sentinelKey(e3) {
12532          return [0, __PRIVATE_encodeResourcePath(e3)];
12533        }(s);
12534        r.push(t.get(o).next((n3) => n3 ? PersistencePromise.resolve() : ((n4) => t.put({
12535          targetId: 0,
12536          path: __PRIVATE_encodeResourcePath(n4),
12537          sequenceNumber: e2.highestListenSequenceNumber
12538        }))(s)));
12539      }).next(() => PersistencePromise.waitFor(r));
12540    });
12541  }
12542  Si(e, t) {
12543    e.createObjectStore(fe, {
12544      keyPath: ge
12545    });
12546    const n = t.store(fe), r = new __PRIVATE_MemoryCollectionParentIndex(), addEntry = (e2) => {
12547      if (r.add(e2)) {
12548        const t2 = e2.lastSegment(), r2 = e2.popLast();
12549        return n.put({
12550          collectionId: t2,
12551          parent: __PRIVATE_encodeResourcePath(r2)
12552        });
12553      }
12554    };
12555    return t.store(j).X({
12556      Z: true
12557    }, (e2, t2) => {
12558      const n2 = new ResourcePath(e2);
12559      return addEntry(n2.popLast());
12560    }).next(() =>
12560 t.store(ie).X({
12561      Z: true
12562    }, ([e2, t2, n2], r2) => {
12563      const i = __PRIVATE_decodeResourcePath(t2);
12564      return addEntry(i.popLast());
12565    }));
12566  }
12567  bi(e) {
12568    const t = e.store(Pe);
12569    return t.X((e2, n) => {
12570      const r = __PRIVATE_fromDbTarget(n), i = __PRIVATE_toDbTarget(this.serializer, r);
12571      return t.put(i);
12572    });
12573  }
12574  Di(e, t) {
12575    const n = t.store(j), r = [];
12576    return n.X((e2, n2) => {
12577      const i = t.store(se), s = function __PRIVATE_extractKey(e3) {
12578        return e3.document ? new DocumentKey(ResourcePath.fromString(e3.document.name).popFirst(5)) : e3.noDocument ? DocumentKey.fromSegments(e3.noDocument.path) : e3.unknownDocument ? DocumentKey.fromSegments(e3.unknownDocument.path) : fail(36783);
12579      }(n2).path.toArray(), o = {
12580        prefixPath: s.slice(0, s.length - 2),
12581        collectionGroup: s[s.length - 2],
12582        documentId: s[s.length - 1],
12583        readTime: n2.readTime || [0, 0],
12584        unknownDocument: n2.unknownDocument,
12585        noDocument: n2.noDocument,
12586        document: n2.document,
12587        hasCommittedMutations: !!n2.hasCommittedMutations
12588      };
12589      r.push(i.put(o));
12590    }).next(() => PersistencePromise.waitFor(r));
12591  }
12592  Ci(e, t) {
12593    const n = t.store(X), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Vi, this.serializer.gt);
12594    return n.j().next((e2) => {
12595      const n2 = /* @__PURE__ */ new Map();
12596      return e2.forEach((e3) => {
12597        var t2;
12598        let r2 = null !== (t2 = n2.get(e3.userId)) && void 0 !== t2 ? t2 : __PRIVATE_documentKeySet();
12599        __PRIVATE_fromDbMutationBatch(this.serializer, e3).keys().forEach((e4) => r2 = r2.add(e4)), n2.set(e3.userId, r2);
12600      }), PersistencePromise.forEach(n2, (e3, n3) => {
12601        const s = new User(n3), o = __PRIVATE_IndexedDbDocumentOverlayCache.yt(this.serializer, s), _ = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.yt(s, this.serializer, _, i.referenceDelegate);
12602        return new LocalDocumentsView(r, a, o, _).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence.ue), e3).next();
12603      });
12604    });
12605  }
12606}
12607function __PRIVATE_createQueryCache(e) {
12608  e.createObjectStore(de, {
12609    keyPath: Ee
12610  }).createIndex(Ae, Re, {
12611    unique: true
12612  });
12613  e.createObjectStore(Pe, {
12614    keyPath: "targetId"
12615  }).createIndex(Te, Ie, {
12616    unique: true
12617  }), e.createObjectStore(me);
12618}
12619const Nt = "IndexedDbPersistence", Bt = 18e5, Lt = 5e3, kt = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.", qt = "main";
12620class __PRIVATE_IndexedDbPersistence {
12621  constructor(e, t, n, r, i, s, o, _, a, u, c = 18) {
12622    if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, this.Fi = i, this.window = s, this.document = o, this.Mi = a, this.xi = u, this.Oi = c, this.ui = null, this.ci = false, this.isPrimary = false, this.networkEnabled = true, /** Our window.unload handler, if registered. */
12623    this.Ni = null, this.inForeground = false, /** Our 'visibilitychange' listener if registered. */
12624    this.Bi = null, /** The client metadata refresh task. */
12625    this.Li = null, /** The last time we garbage collected the client metadata object store. */
12626    this.ki = Number.NEGATIVE_INFINITY, /** A listener to notify on primary state changes. */
12627    this.qi = (e2) => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.C()) throw new FirestoreError(N.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
12628    this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.Qi = t + qt, this.serializer = new __PRIVATE_LocalSerializer(_), this.$i = new __PRIVATE_SimpleDb(this.Qi, this.Oi, new __PRIVATE_SchemaConverter(this.serializer)), this.li = new __PRIVATE_IndexedDbGlobalsCache(), this.hi = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), this.Ti = new __PRIVATE_IndexedDbBundleCache(), this.window && this.window.localStorage ? this.Ui = this.window.localStorage : (this.Ui = null, false === u && __PRIVATE_logError(Nt, "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
12629  }
12630  /**
12631   * Attempt to start IndexedDb persistence.
12632   *
12633   * @returns Whether persistence was enabled.
12634   */
12635  start() {
12636    return this.Ki().then(() => {
12637      if (!this.isPrimary && !this.allowTabSynchronization)
12638        throw new FirestoreError(N.FAILED_PRECONDITION, kt);
12639      return this.Wi(), this.Gi(), this.zi(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (e) => this.hi.getHighestSequenceNumber(e));
12640    }).then((e) => {
12641      this.ui = new __PRIVATE_ListenSequence(e, this.Mi);
12642    }).then(() => {
12643      this.ci = true;
12644    }).catch((e) => (this.$i && this.$i.close(), Promise.reject(e)));
12645  }
12646  /**
12647   * Registers a listener that gets called when the primary state of the
12648   * instance changes. Upon registering, this listener is invoked immediately
12649   * with the current primary state.
12650   *
12651   * PORTING NOTE: This is only used for Web multi-tab.
12652   */
12653  ji(e) {
12654    return this.qi = async (t) => {
12655      if (this.started) return e(t);
12656    }, e(this.isPrimary);
12657  }
12658  /**
12659   * Registers a listener that gets called when the underlying database receives
12660   * an event indicating that it either has been deleted or is pending deleti
12660on
12661   * and must be closed.
12662   *
12663   * For example, this callback will be called in the case that multi-tab
12664   * IndexedDB persistence is in use and another tab calls
12665   * clearIndexedDbPersistence(). In that case, this Firestore instance must
12666   * close its IndexedDB connection in order to allow the deletion initiated by
12667   * the other tab to proceed.
12668   *
12669   * This method may only be called once; subsequent invocations will result in
12670   * an exception, refusing to supersede the previously-registered listener.
12671   *
12672   * PORTING NOTE: This is only used for Web multi-tab.
12673   */
12674  setDatabaseDeletedListener(e) {
12675    this.$i.setDatabaseDeletedListener(e);
12676  }
12677  /**
12678   * Adjusts the current network state in the client's metadata, potentially
12679   * affecting the primary lease.
12680   *
12681   * PORTING NOTE: This is only used for Web multi-tab.
12682   */
12683  setNetworkEnabled(e) {
12684    this.networkEnabled !== e && (this.networkEnabled = e, // Schedule a primary lease refresh for immediate execution. The eventual
12685    // lease update will be propagated via `primaryStateListener`.
12686    this.Fi.enqueueAndForget(async () => {
12687      this.started && await this.Ki();
12688    }));
12689  }
12690  /**
12691   * Updates the client metadata in IndexedDb and attempts to either obtain or
12692   * extend the primary lease for the local client. Asynchronously notifies the
12693   * primary state listener if the client either newly obtained or released its
12694   * primary lease.
12695   */
12696  Ki() {
12697    return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (e) => __PRIVATE_clientMetadataStore(e).put({
12698      clientId: this.clientId,
12699      updateTimeMs: Date.now(),
12700      networkEnabled: this.networkEnabled,
12701      inForeground: this.inForeground
12702    }).next(() => {
12703      if (this.isPrimary) return this.Ji(e).next((e2) => {
12704        e2 || (this.isPrimary = false, this.Fi.enqueueRetryable(() => this.qi(false)));
12705      });
12706    }).next(() => this.Hi(e)).next((t) => this.isPrimary && !t ? this.Yi(e).next(() => false) : !!t && this.Zi(e).next(() => true))).catch((e) => {
12707      if (__PRIVATE_isIndexedDbTransactionError(e))
12708        return __PRIVATE_logDebug(Nt, "Failed to extend owner lease: ", e), this.isPrimary;
12709      if (!this.allowTabSynchronization) throw e;
12710      return __PRIVATE_logDebug(Nt, "Releasing owner lease after error during lease refresh", e), /* isPrimary= */
12711      false;
12712    }).then((e) => {
12713      this.isPrimary !== e && this.Fi.enqueueRetryable(() => this.qi(e)), this.isPrimary = e;
12714    });
12715  }
12716  Ji(e) {
12717    return __PRIVATE_primaryClientStore(e).get(H).next((e2) => PersistencePromise.resolve(this.Xi(e2)));
12718  }
12719  es(e) {
12720    return __PRIVATE_clientMetadataStore(e).delete(this.clientId);
12721  }
12722  /**
12723   * If the garbage collection threshold has passed, prunes the
12724   * RemoteDocumentChanges and the ClientMetadata store based on the last update
12725   * time of all clients.
12726   */
12727  async ts() {
12728    if (this.isPrimary && !this.ns(this.ki, Bt)) {
12729      this.ki = Date.now();
12730      const e = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (e2) => {
12731        const t = __PRIVATE_getStore(e2, pe);
12732        return t.j().next((e3) => {
12733          const n = this.rs(e3, Bt), r = e3.filter((e4) => -1 === n.indexOf(e4));
12734          return PersistencePromise.forEach(r, (e4) => t.delete(e4.clientId)).next(() => r);
12735        });
12736      }).catch(() => []);
12737      if (this.Ui) for (const t of e) this.Ui.removeItem(this.ss(t.clientId));
12738    }
12739  }
12740  /**
12741   * Schedules a recurring timer to update the client metadata and to either
12742   * extend or acquire the primary lease if the client is eligible.
12743   */
12744  zi() {
12745    this.Li = this.Fi.enqueueAfterDelay("client_metadata_refresh", 4e3, () => this.Ki().then(() => this.ts()).then(() => this.zi()));
12746  }
12747  /** Checks whether `client` is the local client. */
12748  Xi(e) {
12749    return !!e && e.ownerId === this.clientId;
12750  }
12751  /**
12752   * Evaluate the state of all active clients and determine whether the local
12753   * client is or can act as the holder of the primary lease. Returns whether
12754   * the client is eligible for the lease, but does not actually acquire it.
12755   * May return 'false' even if there is no active leaseholder and another
12756   * (foreground) client should become leaseholder instead.
12757   */
12758  Hi(e) {
12759    if (this.xi) return PersistencePromise.resolve(true);
12760    return __PRIVATE_primaryClientStore(e).get(H).next((t) => {
12761      if (null !== t && this.ns(t.leaseTimestampMs, Lt) && !this._s(t.ownerId)) {
12762        if (this.Xi(t) && this.networkEnabled) return true;
12763        if (!this.Xi(t)) {
12764          if (!t.allowTabSynchronization)
12765            throw new FirestoreError(N.FAILED_PRECONDITION, kt);
12766          return false;
12767        }
12768      }
12769      return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).j().next((e2) => void 0 === this.rs(e2, Lt).find((e3) => {
12770        if (this.clientId !== e3.clientId) {
12771          const t2 = !this.networkEnabled && e3.networkEnabled, n = !this.inForeground && e3.inForeground, r = this.networkEnabled === e3.networkEnabled;
12772          if (t2 || n && r) return true;
12773        }
12774        return false;
12775      }));
12776    }).next((e2) => (this.isPrimary !== e2 && __PRIVATE_logDebug(Nt, `Client ${e2 ? "is" : "is not"} eligible for a primary lease.`), e2));
12777  }
12778  async shutdown() {
12779    this.ci = false, this.us(), this.Li && (this.Li.cancel(), this.Li = null), this.cs(), this.ls(), // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
12780    // has obtained the primary lease.
12781    await this.$i.runTransaction("shutdown", "readwrite", [J, pe], (e) => {
12782      const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence.ue);
12783      return this.Yi(t).next(() => this.es(t));
12784    }), this.$i.close(), // Remove the entry marking the client as zombied from LocalStorage since
12785    // we successfully deleted its metadata from IndexedDb.
12786    this.hs();
12787  }
12788  /**
12789   * Returns clients that are not zombied and have an updateTime within the
12790   * provided threshold.
12791   */
12792  rs(e, t) {
12793    return e.filter((e2) => this.ns(e2.updateTimeMs, t) && !this._s(e2.clientId));
12794  }
12795  /**
12796   * Returns the IDs of the clients that are currently active. If multi-tab
12797   * is not supported, returns an array that only contains the local client's
12798   * ID.
12799   *
12800   * PORTING NOTE: This is only used for Web multi-tab.
12801   */
12802  Ps() {
12803    return this.runTransaction("getActiveClients", "readonly", (e) => __PRIVATE_clientMetadataStore(e).j().next((e2) => this.rs(e2, Bt).map((e3) => e3.clientId)));
12804  }
12805  get started() {
12806    return this.ci;
12807  }
12808  getGlobalsCache() {
12809    return this.li;
12810  }
12811  getMutationQueue(e, t) {
12812    return __PRIVATE_IndexedDbMutationQueue.yt(e, this.serializer, t, this.referenceDelegate);
12813  }
12814  getTargetCache() {
12815    return this.hi;
12816  }
12817  getRemoteDocumentCache() {
12818    return this.remoteDocumentCache;
12819  }
12820  getIndexManager(e) {
12821    return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.gt.databaseId);
12822  }
12823  getDocumentOverlayCache(e) {
12824    return __PRIVATE_IndexedDbDocumentOverlayCache.yt(this.serializer, e);
12825  }
12826  getBundleCache() {
12827    return this.Ti;
12828  }
12829  runTransaction(e, t, n) {
12830    __PRIVATE_logDebug(Nt, "Starting transaction:", e);
12831    const r = "readonly" === t ? "readonly" : "readwrite", i = (
12832      /** Returns the object stores for the provided schema. */
12833      function __PRIVATE_getObjectStores(e2) {
12834        return 18 === e2 ? rt : 17 === e2 ? nt : 16 === e2 ? tt : 15 === e2 ? et : 14 === e2 ? Xe : 13 === e2 ? Ze : 12 === e2 ? Ye : 11 === e2 ? He : void fail(60245);
12835      }(this.Oi)
12836    );
12837    let s;
12838    return this.$i.runTransaction(e, r, i, (r2) => (s = new __PRIVATE_IndexedDbTransaction(r2, this.ui ? this.ui.next() : __PRIVATE_ListenSequence.ue), "readwrite-primary" === t ? this.Ji(s).next((e2) => !!e2 || this.Hi(s)).next((t2) => {
12839      if (!t2) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), this.isPrimary = false, this.Fi.enqueueRetryable(() => this.qi(false)), new FirestoreError(N.FAILED_PRECONDITION, $);
12840      return n(s);
12841    }).next((e2) => this.Zi(s).next(() => e2)) : this.Ts(s).next(() => n(s)))).then((e2) => (s.raiseOnCommittedEvent(), e2));
12842  }
12843  /**
12844   * Verifies that the current tab is the primary leaseholder or alternatively
12845   * that the leaseholder has opted into multi-tab synchronization.
12846   */
12847  // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
12848  // be turned off.
12849  Ts(e) {
12850    return __PRIVATE_primaryClientStore(e).get(H).next((e2) => {
12851      if (null !== e2 && this.ns(e2.leaseTimestampMs, Lt) && !this._s(e2.ownerId) && !this.Xi(e2) && !(this.xi || this.allowTabSynchronization && e2.allowTabSynchronization)) throw new FirestoreError(N.FAILED_PRECONDITION, kt);
12852    });
12853  }
12854  /**
12855   * Obtains or extends the new primary lease for the local client. This
12856   * method does not verify that the client is eligible for this lease.
12857   */
12858  Zi(e) {
12859    const t = {
12860      ownerId: this.clientId,
12861      allowTabSynchronization: this.allowTabSynchronization,
12862      leaseTimestampMs: Date.now()
12863    };
12864    return __PRIVATE_primaryClientStore(e).put(H, t);
12865  }
12866  static C() {
12867    return __PRIVATE_SimpleDb.C();
12868  }
12869  /** Checks the primary lease and removes it if we are the current primary. */
12870  Yi(e) {
12871    const t = __PRIVATE_primaryClientStore(e);
12872    return t.get(H).next((e2) => this.Xi(e2) ? (__PRIVATE_logDebug(Nt, "Releasing primary lease."), t.delete(H)) : PersistencePromise.resolve());
12873  }
12874  /** Verifies that `updateTimeMs` is within `maxAgeMs`. */
12875  ns(e, t) {
12876    const n = Date.now();
12877    return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), false));
12878  }
12879  Wi() {
12880    null !== this.document && "function" == typeof this.document.addEventListener && (this.Bi = () => {
12881      this.Fi.enqueueAndForget(() => (this.inForeground = "visible" === this.document.visibilityState, this.Ki()));
12882    }, this.document.addEventListener("visibilitychange", this.Bi), this.inForeground = "visible" === this.document.visibilityState);
12883  }
12884  cs() {
12885    this.Bi && (this.document.removeEventListener("visibilitychange", this.Bi), this.Bi = null);
12886  }
12887  /**
12888   * Attaches a window.unload handler that will synchronously write our
12889   * clientId to a "zombie client id" location in LocalStorage. This can be used
12890   * by tabs trying to acquire the primary lease to determine that the lease
12891   * is no longer valid even if the timestamp is recent. This is particularly
12892   * important for the refresh case (so the tab correctly re-acquires the
12893   * primary lease). LocalStorage is used for this rather than IndexedDb because
12894   * it is a synchronous API and so can be used reliably from  an unload
12895   * handler.
12896   */
12897  Gi() {
12898    var e;
12899    "function" == typeof (null === (e = this.window) || void 0 === e ? void 0 : e.addEventListener) && (this.Ni = () => {
12900      this.us();
12901      const e2 = /(?:Version|Mobile)\/1[456]/;
12902      isSafari() && (navigator.appVersion.match(e2) || navigator.userAgent.match(e2)) && // On Safari 14, 15, and 16, we do not run any cleanup actions as it might
12903      // trigger a bug that prevents Safari from re-opening IndexedDB during
12904      // the next page load.
12905      // See https://bugs.webkit.org/show_bug.cgi?id=226547
12906      this.Fi.enterRestrictedMode(
12907        /* purgeExistingTasks= */
12908        true
12909      ), this.Fi.enqueueAndForget(() => this.shutdown());
12910    }, this.window.addEventListener("pagehide", this.Ni));
12911  }
12912  ls() {
12913    this.Ni && (this.window.removeEventListener("pagehide", this.Ni), this.Ni = null);
12914  }
12915  /**
12916   * Returns whether a client is "zombied" based on its LocalStorage entry.
12917   * Clients become zombied when their tab closes without running all of the
12918   * cleanup logic in `shutdown()`.
12919   */
12920  _s(e) {
12921    var t;
12922    try {
12923      const n = null !== (null === (t = this.Ui) || void 0 === t ? void 0 : t.getItem(this.ss(e)));
12924      return __PRIVATE_logDebug(Nt, `Client '${e}' ${n ? "is" : "is not"} zombied in LocalStorage`), n;
12925    } catch (e2) {
12926      return __PRIVATE_logError(Nt, "Failed to get zombied client id.", e2), false;
12927    }
12928  }
12929  /**
12930   * Record client as zombied (a client that had its tab closed). Zombied
12931   * clients are ignored during primary tab selection.
12932   */
12933  us() {
12934    if (this.Ui) try {
12935      this.Ui.setItem(this.ss(this.clientId), String(Date.now()));
12936    } catch (e) {
12937      __PRIVATE_logError("Failed to set zombie client id.", e);
12938    }
12939  }
12940  /** Removes the zombied client entry if it exists. */
12941  hs() {
12942    if (this.Ui) try {
12943      this.Ui.removeItem(this.ss(this.clientId));
12944    } catch (e) {
12945    }
12946  }
12947  ss(e) {
12948    return `firestore_zombie_${this.persistenceKey}_${e}`;
12949  }
12950}
12951function __PRIVATE_primaryClientStore(e) {
12952  return __PRIVATE_getStore(e, J);
12953}
12954function __PRIVATE_clientMetadataStore(e) {
12955  return __PRIVATE_getStore(e, pe);
12956}
12957function __PRIVATE_indexedDbStoragePrefix(e, t) {
12958  let n = e.projectId;
12959  return e.isDefaultDatabase || (n += "." + e.database), "firestore/" + t + "/" 
12959+ n + "/";
12960}
12961/**
12962 * @license
12963 * Copyright 2017 Google LLC
12964 *
12965 * Licensed under the Apache License, Version 2.0 (the "License");
12966 * you may not use this file except in compliance with the License.
12967 * You may obtain a copy of the License at
12968 *
12969 *   http://www.apache.org/licenses/LICENSE-2.0
12970 *
12971 * Unless required by applicable law or agreed to in writing, software
12972 * distributed under the License is distributed on an "AS IS" BASIS,
12973 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12974 * See the License for the specific language governing permissions and
12975 * limitations under the License.
12976 */
12977class __PRIVATE_LocalViewChanges {
12978  constructor(e, t, n, r) {
12979    this.targetId = e, this.fromCache = t, this.Is = n, this.ds = r;
12980  }
12981  static Es(e, t) {
12982    let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet();
12983    for (const e2 of t.docChanges) switch (e2.type) {
12984      case 0:
12985        n = n.add(e2.doc.key);
12986        break;
12987      case 1:
12988        r = r.add(e2.doc.key);
12989    }
12990    return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r);
12991  }
12992}
12993/**
12994 * @license
12995 * Copyright 2023 Google LLC
12996 *
12997 * Licensed under the Apache License, Version 2.0 (the "License");
12998 * you may not use this file except in compliance with the License.
12999 * You may obtain a copy of the License at
13000 *
13001 *   http://www.apache.org/licenses/LICENSE-2.0
13002 *
13003 * Unless required by applicable law or agreed to in writing, software
13004 * distributed under the License is distributed on an "AS IS" BASIS,
13005 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13006 * See the License for the specific language governing permissions and
13007 * limitations under the License.
13008 */
13009class QueryContext {
13010  constructor() {
13011    this._documentReadCount = 0;
13012  }
13013  get documentReadCount() {
13014    return this._documentReadCount;
13015  }
13016  incrementDocumentReadCount(e) {
13017    this._documentReadCount += e;
13018  }
13019}
13020/**
13021 * @license
13022 * Copyright 2019 Google LLC
13023 *
13024 * Licensed under the Apache License, Version 2.0 (the "License");
13025 * you may not use this file except in compliance with the License.
13026 * You may obtain a copy of the License at
13027 *
13028 *   http://www.apache.org/licenses/LICENSE-2.0
13029 *
13030 * Unless required by applicable law or agreed to in writing, software
13031 * distributed under the License is distributed on an "AS IS" BASIS,
13032 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13033 * See the License for the specific language governing permissions and
13034 * limitations under the License.
13035 */
13036class __PRIVATE_QueryEngine {
13037  constructor() {
13038    this.As = false, this.Rs = false, /**
13039    * SDK only decides whether it should create index when collection size is
13040    * larger than this.
13041    */
13042    this.Vs = 100, this.fs = /**
13043    * This cost represents the evaluation result of
13044    * (([index, docKey] + [docKey, docContent]) per document in the result set)
13045    * / ([docKey, docContent] per documents in full collection scan) coming from
13046    * experiment [enter PR experiment URL here].
13047    */
13048    function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() {
13049      return isSafari() ? 8 : __PRIVATE_getAndroidVersion(getUA()) > 0 ? 6 : 4;
13050    }();
13051  }
13052  /** Sets the document view to query against. */
13053  initialize(e, t) {
13054    this.gs = e, this.indexManager = t, this.As = true;
13055  }
13056  /** Returns all local documents matching the specified query. */
13057  getDocumentsMatchingQuery(e, t, n, r) {
13058    const i = {
13059      result: null
13060    };
13061    return this.ps(e, t).next((e2) => {
13062      i.result = e2;
13063    }).next(() => {
13064      if (!i.result) return this.ys(e, t, r, n).next((e2) => {
13065        i.result = e2;
13066      });
13067    }).next(() => {
13068      if (i.result) return;
13069      const n2 = new QueryContext();
13070      return this.ws(e, t, n2).next((r2) => {
13071        if (i.result = r2, this.Rs) return this.Ss(e, t, n2, r2.size);
13072      });
13073    }).next(() => i.result);
13074  }
13075  Ss(e, t, n, r) {
13076    return n.documentReadCount < this.Vs ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "SDK will not create cache indexes for query:", __PRIVATE_stringifyQuery(t), "since it only creates cache indexes for collection contains", "more than or equal to", this.Vs, "documents"), PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Query:", __PRIVATE_stringifyQuery(t), "scans", n.documentReadCount, "local documents and returns", r, "documents as results."), n.documentReadCount > this.fs * r ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "The SDK decides to create cache indexes for query:", __PRIVATE_stringifyQuery(t), "as using cache indexes may help improve performance."), this.indexManager.createTargetIndexes(e, __PRIVATE_queryToTarget(t))) : PersistencePromise.resolve());
13077  }
13078  /**
13079   * Performs an indexed query that evaluates the query based on a collection's
13080   * persisted index values. Returns `null` if an index is not available.
13081   */
13082  ps(e, t) {
13083    if (__PRIVATE_queryMatchesAllDocuments(t))
13084      return PersistencePromise.resolve(null);
13085    let n = __PRIVATE_queryToTarget(t);
13086    return this.indexManager.getIndexType(e, n).next((r) => 0 === r ? null : (null !== t.limit && 1 === r && // We cannot apply a limit for targets that are served using a partial
13087    // index. If a partial index will be used to serve the target, the
13088    // query may return a superset of documents that match the target
13089    // (e.g. if the index doesn't include all the target's filters), or
13090    // may return the correct set of documents in the wrong order (e.g. if
13091    // the index doesn't include a segment for one of the orderBys).
13092    // Therefore, a limit should not be applied in such cases.
13093    (t = __PRIVATE_queryWithLimit(
13094      t,
13095      null,
13096      "F"
13097      /* LimitType.First */
13098    ), n = __PRIVATE_queryToTarget(t)), this.indexManager.getDocumentsMatchingTarget(e, n).next((r2) => {
13099      const i = __PRIVATE_documentKeySet(...r2);
13100      return this.gs.getDocuments(e, i).next((r3) => this.indexManager.getMinOffset(e, n).next((n2) => {
13101        const s = this.bs(t, r3);
13102        return this.Ds(t, s, i, n2.readTime) ? this.ps(e, __PRIVATE_queryWithLimit(
13103          t,
13104          null,
13105          "F"
13106          /* LimitType.First */
13107        )) : this.vs(e, s, t, n2);
13108      }));
13109    }
13109)));
13110  }
13111  /**
13112   * Performs a query based on the target's persisted query mapping. Returns
13113   * `null` if the mapping is not available or cannot be used.
13114   */
13115  ys(e, t, n, r) {
13116    return __PRIVATE_queryMatchesAllDocuments(t) || r.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.gs.getDocuments(e, n).next((i) => {
13117      const s = this.bs(t, i);
13118      return this.Ds(t, s, n, r) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Re-using previous result from %s to execute query: %s", r.toString(), __PRIVATE_stringifyQuery(t)), this.vs(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, Q)).next((e2) => e2));
13119    });
13120  }
13121  /** Applies the query filter and sorting to the provided documents.  */
13122  bs(e, t) {
13123    let n = new SortedSet(__PRIVATE_newQueryComparator(e));
13124    return t.forEach((t2, r) => {
13125      __PRIVATE_queryMatches(e, r) && (n = n.add(r));
13126    }), n;
13127  }
13128  /**
13129   * Determines if a limit query needs to be refilled from cache, making it
13130   * ineligible for index-free execution.
13131   *
13132   * @param query - The query.
13133   * @param sortedPreviousResults - The documents that matched the query when it
13134   * was last synchronized, sorted by the query's comparator.
13135   * @param remoteKeys - The document keys that matched the query at the last
13136   * snapshot.
13137   * @param limboFreeSnapshotVersion - The version of the snapshot when the
13138   * query was last synchronized.
13139   */
13140  Ds(e, t, n, r) {
13141    if (null === e.limit)
13142      return false;
13143    if (n.size !== t.size)
13144      return true;
13145    const i = "F" === e.limitType ? t.last() : t.first();
13146    return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0);
13147  }
13148  ws(e, t, n) {
13149    return __PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Using full collection scan to execute query:", __PRIVATE_stringifyQuery(t)), this.gs.getDocumentsMatchingQuery(e, t, IndexOffset.min(), n);
13150  }
13151  /**
13152   * Combines the results from an indexed execution with the remaining documents
13153   * that have not yet been indexed.
13154   */
13155  vs(e, t, n, r) {
13156    return this.gs.getDocumentsMatchingQuery(e, n, r).next((e2) => (
13157      // Merge with existing results
13158      (t.forEach((t2) => {
13159        e2 = e2.insert(t2.key, t2);
13160      }), e2)
13161    ));
13162  }
13163}
13164/**
13165 * @license
13166 * Copyright 2020 Google LLC
13167 *
13168 * Licensed under the Apache License, Version 2.0 (the "License");
13169 * you may not use this file except in compliance with the License.
13170 * You may obtain a copy of the License at
13171 *
13172 *   http://www.apache.org/licenses/LICENSE-2.0
13173 *
13174 * Unless required by applicable law or agreed to in writing, software
13175 * distributed under the License is distributed on an "AS IS" BASIS,
13176 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13177 * See the License for the specific language governing permissions and
13178 * limitations under the License.
13179 */
13180const Qt = "LocalStore", $t = 3e8;
13181class __PRIVATE_LocalStoreImpl {
13182  constructor(e, t, n, r) {
13183    this.persistence = e, this.Cs = t, this.serializer = r, /**
13184    * Maps a targetID to data about its target.
13185    *
13186    * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
13187    * of `applyRemoteEvent()` idempotent.
13188    */
13189    this.Fs = new SortedMap(__PRIVATE_primitiveComparator), /** Maps a target to its targetID. */
13190    // TODO(wuandy): Evaluate if TargetId can be part of Target.
13191    this.Ms = new ObjectMap((e2) => __PRIVATE_canonifyTarget(e2), __PRIVATE_targetEquals), /**
13192    * A per collection group index of the last read time processed by
13193    * `getNewDocumentChanges()`.
13194    *
13195    * PORTING NOTE: This is only used for multi-tab synchronization.
13196    */
13197    this.xs = /* @__PURE__ */ new Map(), this.Os = e.getRemoteDocumentCache(), this.hi = e.getTargetCache(), this.Ti = e.getBundleCache(), this.Ns(n);
13198  }
13199  Ns(e) {
13200    this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.Os, this.mutation
13200Queue, this.documentOverlayCache, this.indexManager), this.Os.setIndexManager(this.indexManager), this.Cs.initialize(this.localDocuments, this.indexManager);
13201  }
13202  collectGarbage(e) {
13203    return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (t) => e.collect(t, this.Fs));
13204  }
13205}
13206function __PRIVATE_newLocalStore(e, t, n, r) {
13207  return new __PRIVATE_LocalStoreImpl(e, t, n, r);
13208}
13209async function __PRIVATE_localStoreHandleUserChange(e, t) {
13210  const n = __PRIVATE_debugCast(e);
13211  return await n.persistence.runTransaction("Handle user change", "readonly", (e2) => {
13212    let r;
13213    return n.mutationQueue.getAllMutationBatches(e2).next((i) => (r = i, n.Ns(t), n.mutationQueue.getAllMutationBatches(e2))).next((t2) => {
13214      const i = [], s = [];
13215      let o = __PRIVATE_documentKeySet();
13216      for (const e3 of r) {
13217        i.push(e3.batchId);
13218        for (const t3 of e3.mutations) o = o.add(t3.key);
13219      }
13220      for (const e3 of t2) {
13221        s.push(e3.batchId);
13222        for (const t3 of e3.mutations) o = o.add(t3.key);
13223      }
13224      return n.localDocuments.getDocuments(e2, o).next((e3) => ({
13225        Bs: e3,
13226        removedBatchIds: i,
13227        addedBatchIds: s
13228      }));
13229    });
13230  });
13231}
13232function __PRIVATE_localStoreAcknowledgeBatch(e, t) {
13233  const n = __PRIVATE_debugCast(e);
13234  return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (e2) => {
13235    const r = t.batch.keys(), i = n.Os.newChangeBuffer({
13236      trackRemovals: true
13237    });
13238    return function __PRIVATE_applyWriteToRemoteDocuments(e3, t2, n2, r2) {
13239      const i2 = n2.batch, s = i2.keys();
13240      let o = PersistencePromise.resolve();
13241      return s.forEach((e4) => {
13242        o = o.next(() => r2.getEntry(t2, e4)).next((t3) => {
13243          const s2 = n2.docVersions.get(e4);
13244          __PRIVATE_hardAssert(null !== s2, 48541), t3.version.compareTo(s2) < 0 && (i2.applyToRemoteDocument(t3, n2), t3.isValidDocument() && // We use the commitVersion as the readTime rather than the
13245          // document's updateTime since the updateTime is not advanced
13246          // for updates that do not modify the underlying document.
13247          (t3.setReadTime(n2.commitVersion), r2.addEntry(t3)));
13248        });
13249      }), o.next(() => e3.mutationQueue.removeMutationBatch(t2, i2));
13250    }(n, e2, t, i).next(() => i.apply(e2)).next(() =>
13250 n.mutationQueue.performConsistencyCheck(e2)).next(() => n.documentOverlayCache.removeOverlaysForBatchId(e2, r, t.batch.batchId)).next(() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e2, function __PRIVATE_getKeysWithTransformResults(e3) {
13251      let t2 = __PRIVATE_documentKeySet();
13252      for (let n2 = 0; n2 < e3.mutationResults.length; ++n2) {
13253        e3.mutationResults[n2].transformResults.length > 0 && (t2 = t2.add(e3.batch.mutations[n2].key));
13254      }
13255      return t2;
13256    }(t))).next(() => n.localDocuments.getDocuments(e2, r));
13257  });
13258}
13259function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) {
13260  const t = __PRIVATE_debugCast(e);
13261  return t.persistence.runTransaction("Get last remote snapshot version", "readonly", (e2) => t.hi.getLastRemoteSnapshotVersion(e2));
13262}
13263function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) {
13264  const n = __PRIVATE_debugCast(e), r = t.snapshotVersion;
13265  let i = n.Fs;
13266  return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (e2) => {
13267    const s = n.Os.newChangeBuffer({
13268      trackRemovals: true
13269    });
13270    i = n.Fs;
13271    const o = [];
13272    t.targetChanges.forEach((s2, _2) => {
13273      const a2 = i.get(_2);
13274      if (!a2) return;
13275      o.push(n.hi.removeMatchingKeys(e2, s2.removedDocuments, _2).next(() => n.hi.addMatchingKeys(e2, s2.addedDocuments, _2)));
13276      let u = a2.withSequenceNumber(e2.currentSequenceNumber);
13277      null !== t.targetMismatches.get(_2) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s2.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s2.resumeToken, r)), i = i.insert(_2, u), // Update the target data if there are target changes (or if
13278      // sufficient time has passed since the last update).
13279      /**
13280      * Returns true if the newTargetData should be persisted during an update of
13281      * an active target. TargetData should always be persisted when a target is
13282      * being released and should not call this function.
13283      *
13284      * While the target is active, TargetData updates can be omitted when nothing
13285      * about the target has changed except metadata like the resume token or
13286      * snapshot version. Occasionally it's worth the extra write to prevent these
13287      * values from getting too stale after a crash, but this doesn't have to be
13288      * too frequent.
13289      */
13290      function __PRIVATE_shouldPersistTargetData(e3, t2, n2) {
13291        if (0 === e3.resumeToken.approximateByteSize()) return true;
13292        const r2 = t2.snapshotVersion.toMicroseconds() - e3.snapshotVersion.toMicroseconds();
13293        if (r2 >= $t) return true;
13294        const i2 = n2.addedDocuments.size + n2.modifiedDocuments.size + n2.removedDocuments.size;
13295        return i2 > 0;
13296      }(a2, u, s2) && o.push(n.hi.updateTargetData(e2, u));
13297    });
13298    let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();
13299    if (t.documentUpdates.forEach((r2) => {
13300      t.resolvedLimboDocuments.has(r2) && o.push(n.persistence.referenceDelegate.updateLimboDocument(e2, r2));
13301    }), // Each loop iteration only affects its "own" doc, so it's safe to get all
13302    // the remote documents in advance in a single call.
13303    o.push(__PRIVATE_populateDocumentChangeBuffer(e2, s, t.documentUpdates).next((e3) => {
13304      _ = e3.Ls, a = e3.ks;
13305    })), !r.isEqual(SnapshotVersion.min())) {
13306      const t2 = n.hi.getLastRemoteSnapshotVersion(e2).next((t3) => n.hi.setTargetsMetadata(e2, e2.currentSequenceNumber, r));
13307      o.push(t2);
13308    }
13309    return PersistencePromise.waitFor(o).next(() => s.apply(e2)).next(() => n.localDocuments.getLocalViewOfDocuments(e2, _, a)).next(() => _);
13310  }).then((e2) => (n.Fs = i, e2));
13311}
13312function __PRIVATE_populateDocumentChangeBuffer(e, t, n) {
13313  let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet();
13314  return n.forEach((e2) => r = r.add(e2)), t.getEntries(e, r).next((e2) => {
13315    let r2 = __PRIVATE_mutableDocumentMap();
13316    return n.forEach((n2, s) => {
13317      const o = e2.get(n2);
13318      s.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n2)), // Note: The order of the steps below is important, since we want
13319      // to ensure that rejected limbo resolutions (which fabricate
13320      // NoDocuments with SnapshotVersion.min()) never add documents to
13321      // cache.
13322      s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? (
13323        // NoDocuments with SnapshotVersion.min() are used in manufactured
13324        // events. We remove these documents from cache since we lost
13325        // access.
13326        (t.removeEntry(n2, s.readTime), r2 = r2.insert(n2, s))
13327      ) : !o.isValidDocument() || s.version.compareTo(o.version) > 0 || 0 === s.version.compareTo(o.version) && o.hasPendingWrites ? (t.addEntry(s), r2 = r2.insert(n2, s)) : __PRIVATE_logDebug(Qt, "Ignoring outdated watch update for ", n2, ". Current version:", o.version, " Watch version:", s.version);
13328    }), {
13329      Ls: r2,
13330      ks: i
13331    };
13332  });
13333}
13334function __PRIVATE_localStoreGetNextMutationBatch(e, t) {
13335  const n = __PRIVATE_debugCast(e);
13336  return n.persistence.runTransaction("Get next mutation batch", "readonly", (e2) => (void 0 === t && (t = G), n.mutationQueue.getNextMutationBatchAfterBatchId(e2, t)));
13337}
13338function __PRIVATE_localStoreAllocateTarget(e, t) {
13339  const n = __PRIVATE_debugCast(e);
13340  return n.persistence.runTransaction("Allocate target", "readwrite", (e2) => {
13341    let r;
13342    return n.hi.getTargetData(e2, t).next((i) => i ? (
13343      // This target has been listened to previously, so reuse the
13344      // previous targetID.
13345      // TODO(mcg): freshen last accessed date?
13346      (r = i, PersistencePromise.resolve(r))
13347    ) : n.hi.allocateTargetId(e2).next((i2) => (r = new TargetData(t, i2, "TargetPurposeListen", e2.currentSequenceNumber), n.hi.addTargetData(e2, r).next(() => r))));
13348  }).then((e2) => {
13349    const r = n.Fs.get(e2.targetId);
13350    return (null === r || e2.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.Fs = n.Fs.insert(e2.targetId, e2), n.Ms.set(t, e2.targetId)), e2;
13351  });
13352}
13353async function __PRIVATE_localStoreReleaseTarget(e, t, n) {
13354  const r = __PRIVATE_debugCast(e), i = r.Fs.get(t), s = n ? "readwrite" : "readwrite-primary";
13355  try {
13356    n || await r.persistence.runTransaction("Release target", s, (e2) => r.persistence.referenceDelegate.removeTarget(e2, i));
13357  } catch (e2) {
13358    if (!__PRIVATE_isIndexedDbTransactionError(e2)) throw e2;
13359    __PRIVATE_logDebug(Qt, `Failed to update sequence numbers for target ${t}: ${e2}`);
13360  }
13361  r.Fs = r.Fs.remove(t), r.Ms.delete(i.target);
13362}
13363function __PRIVATE_localStoreExecuteQuery(e, t, n) {
13364  const r = __PRIVATE_debugCast(e);
13365  let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet();
13366  return r.persistence.runTransaction(
13367    "Execute query",
13368    "readwrite",
13369    // Use readwrite instead of readonly so indexes can be created
13370    // Use readwrite instead of readonly so indexes can be created
13371    (e2) => function __PRIVATE_localStoreGetTargetData(e3, t2, n2) {
13372      const r2 = __PRIVATE_debugCast(e3), i2 = r2.Ms.get(n2);
13373      return void 0 !== i2 ? PersistencePromise.resolve(r2.Fs.get(i2)) : r2.hi.getTargetData(t2, n2);
13374    }(r, e2, __PRIVATE_queryToTarget(t)).next((t2) => {
13375      if (t2) return i = t2.lastLimboFreeSnapshotVersion, r.hi.getMatchingKeysForTargetId(e2, t2.targetId).next((e3) => {
13376        s = e3;
13377      });
13378    }).next(() => r.Cs.getDocumentsMatchingQuery(e2, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet())).next((e3) => (__PRIVATE_setMaxReadTime(r, __PRIVATE_queryCollectionGroup(t), e3), {
13379      documents: e3,
13380      qs: s
13381    }))
13382  );
13383}
13384function __PRIVATE_localStoreGetCachedTarget(e, t) {
13385  const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.hi), i = n.Fs.get(t);
13386  return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (e2) => r.Et(e2, t).next((e3) => e3 ? e3.target : null));
13387}
13388function __PRIVATE_localStoreGetNewDocumentChanges(e, t) {
13389  const n = __PRIVATE_debugCast(e), r = n.xs.get(t) || SnapshotVersion.min();
13390  return n.persistence.runTransaction("Get new document changes", "readonly", (e2) => n.Os.getAllFromCollectionGroup(
13391    e2,
13392    t,
13393    __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, Q),
13394    /* limit= */
13395    Number.MAX_SAFE_INTEGER
13396  )).then((e2) => (__PRIVATE_setMaxReadTime(n, t, e2), e2));
13397}
13398function __PRIVATE_setMaxReadTime(e, t, n) {
13399  let r = e.xs.get(t) || SnapshotVersion.min();
13400  n.forEach((e2, t2) => {
13401    t2.readTime.compareTo(r) > 0 && (r = t2.readTime);
13402  }), e.xs.set(t, r);
13403}
13404async function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) {
13405  const i = __PRIVATE_debugCast(e);
13406  let s = __PRIVATE_documentKeySet(), o = __PRIVATE_mutableDocumentMap();
13407  for (const e2 of n) {
13408    const n2 = t.Qs(e2.metadata.name);
13409    e2.document && (s = s.add(n2));
13410    const r2 = t.$s(e2);
13411    r2.setReadTime(t.Us(e2.metadata.readTime)), o = o.insert(n2, r2);
13412  }
13413  const _ = i.Os.newChangeBuffer({
13414    trackRemovals: true
13415  }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e2) {
13416    return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e2}`)));
13417  }(r));
13418  return i.persistence.runTransaction("Apply bundle documents", "readwrite", (e2) => __PRIVATE_populateDocumentChangeBuffer(e2, _, o).next((t2) => (_.apply(e2), t2)).next((t2) => i.hi.removeMatchingKeysForTargetId(e2, a.targetId).next(() => i.hi.addMatchingKeys(e2, s, a.targetId)).next(() => i.localDocuments.getLocalViewOfDocuments(e2, t2.Ls, t2.ks)).next(() => t2.Ls)));
13419}
13420async function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) {
13421  const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e);
13422  return i.persistence.runTransaction("Save named query", "readwrite", (e2) => {
13423    const s = __PRIVATE_fromVersion(t.readTime);
13424    if (r.snapshotVersion.compareTo(s) >= 0) return i.Ti.saveNamedQuery(e2, t);
13425    const o = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s);
13426    return i.Fs = i.Fs.insert(o.targetId, o), i.hi.updateTargetData(e2, o).next(() => i.hi.removeMatchingKeysForTargetId(e2, r.targetId)).next(() => i.hi.addMatchingKeys(e2, n, r.targetId)).next(() => i.Ti.saveNamedQuery(e2, t));
13427  });
13428}
13429/**
13430 * @license
13431 * Copyright 2019 Google LLC
13432 *
13433 * Licensed under the Apache License, Version 2.0 (the "License");
13434 * you may not use this file except in compliance with the License.
13435 * You may obtain a copy of the License at
13436 *
13437 *   http://www.apache.org/licenses/LICENSE-2.0
13438 *
13439 * Unless required by applicable law or agreed to in writing, software
13440 * distributed under the License is distributed on an "AS IS" BASIS,
13441 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13442 * See the License for the specific language governing permissions and
13443 * limitations under the License.
13444 */
13445const Ut = "firestore_clients";
13446function createWebStorageClientStateKey(e, t) {
13447  return `${Ut}_${e}_${t}`;
13448}
13449const Kt = "firestore_mutations";
13450function createWebStorageMutationBatchKey(e, t, n) {
13451  let r = `${Kt}_${e}_${n}`;
13452  return t.isAuthenticated() && (r += `_${t.uid}`), r;
13453}
13454const Wt = "firestore_targets";
13455function createWebStorageQueryTargetMetadataKey(e, t) {
13456  return `${Wt}_${e}_${t}`;
13457}
13458/**
13459 * @license
13460 * Copyright 2018 Google LLC
13461 *
13462 * Licensed under the Apache License, Version 2.0 (the "License");
13463 * you may not use this file except in compliance with the License.
13464 * You may obtain a copy of the License at
13465 *
13466 *   http://www.apache.org/licenses/LICENSE-2.0
13467 *
13468 * Unless required by applicable law or agreed to in writing, software
13469 * distributed under the License is distributed on an "AS IS" BASIS,
13470 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13471 * See the License for the specific language governing permissions and
13472 * limitations under the License.
13473 */
vendor: 4,403 bytes, lines 13474-13576
13474const Gt = "SharedClientState";
13475class __PRIVATE_MutationMetadata {
13476  constructor(e, t, n, r) {
13477    this.user = e, this.batchId = t, this.state = n, this.error = r;
13478  }
13479  /**
13480   * Parses a MutationMetadata from its JSON representation in WebStorage.
13481   * Logs a warning and returns null if the format of the data is not valid.
13482   */
13483  static Ks(e, t, n) {
13484    const r = JSON.parse(n);
13485    let i, s = "object" == typeof r && -1 !== ["pending", "acknowledged", "rejected"].indexOf(r.state) && (void 0 === r.error || "object" == typeof r.error);
13486    return s && r.error && (s = "string" == typeof r.error.message && "string" == typeof r.error.code, s && (i = new FirestoreError(r.error.code, r.error.message))), s ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(Gt, `Failed to parse mutation state for ID '${t}': ${n}`), null);
13487  }
13488  Ws() {
13489    const e = {
13490      state: this.state,
13491      updateTimeMs: Date.now()
13492    };
13493    return this.error && (e.error = {
13494      code: this.error.code,
13495      message: this.error.message
13496    }), JSON.stringify(e);
13497  }
13498}
13499class __PRIVATE_QueryTargetMetadata {
13500  constructor(e, t, n) {
13501    this.targetId = e, this.state = t, this.error = n;
13502  }
13503  /**
13504   * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
13505   * Logs a warning and returns null if the format of the data is not valid.
13506   */
13507  static Ks(e, t) {
13508    const n = JSON.parse(t);
13509    let r, i = "object" == typeof n && -1 !== ["not-current", "current", "rejected"].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error);
13510    return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code, i && (r = new FirestoreError(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(Gt, `Failed to parse target state for ID '${e}': ${t}`), null);
13511  }
13512  Ws() {
13513    const e = {
13514      state: this.state,
13515      updateTimeMs: Date.now()
13516    };
13517    return this.error && (e.error = {
13518      code: this.error.code,
13519      message: this.error.message
13520    }), JSON.stringify(e);
13521  }
13522}
13523class __PRIVATE_RemoteClientState {
13524  constructor(e, t) {
13525    this.clientId = e, this.activeTargetIds = t;
13526  }
13527  /**
13528   * Parses a RemoteClientState from the JSON representation in WebStorage.
13529   * Logs a warning and returns null if the format of the data is not valid.
13530   */
13531  static Ks(e, t) {
13532    const n = JSON.parse(t);
13533    let r = "object" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet();
13534    for (let e2 = 0; r && e2 < n.activeTargetIds.length; ++e2) r = isSafeInteger(n.activeTargetIds[e2]), i = i.add(n.activeTargetIds[e2]);
13535    return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(Gt, `Failed to parse client data for instance '${e}': ${t}`), null);
13536  }
13537}
13538class __PRIVATE_SharedOnlineState {
13539  constructor(e, t) {
13540    this.clientId = e, this.onlineState = t;
13541  }
13542  /**
13543   * Parses a SharedOnlineState from its JSON representation in WebStorage.
13544   * Logs a warning and returns null if the format of the data is not valid.
13545   */
13546  static Ks(e) {
13547    const t = JSON.parse(e);
13548    return "object" == typeof t && -1 !== ["Unknown", "Online", "Offline"].indexOf(t.onlineState) && "string" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(Gt, `Failed to parse online state: ${e}`), null);
13549  }
13550}
13551class __PRIVATE_LocalClientState {
13552  constructor() {
13553    this.activeTargetIds = __PRIVATE_targetIdSet();
13554  }
13555  Gs(e) {
13556    this.activeTargetIds = this.activeTargetIds.add(e);
13557  }
13558  zs(e) {
13559    this.activeTargetIds = this.activeTargetIds.delete(e);
13560  }
13561  /**
13562   * Converts this entry into a JSON-encoded format we can use for WebStorage.
13563   * Does not encode `clientId` as it is part of the key in WebStorage.
13564   */
13565  Ws() {
13566    const e = {
13567      activeTargetIds: this.activeTargetIds.toArray(),
13568      updateTimeMs: Date.now()
13569    };
13570    return JSON.stringify(e);
13571  }
13572}
13573class __PRIVATE_WebStorageSharedClientState {
13574  constructor(e, t, n, r, i) {
13575    this.window = e, this.Fi = t, this.persistenceKey = n, this.js = r, this.syncEngine = null, this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.Js = this.Hs.bind(this), this.Ys = new SortedMap(__PRIVATE_primitiveComparator), this.started = false, /**
13576    * Captures WebStorage events that occur before `start()` is called. These
13577    * events are replayed once `WebStorageSharedClientState` is started.
13578    */
13579    this.Zs = [];
13580    const s = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13581    this.storage = this.window.localStorage, this.currentUser = i, this.Xs = createWebStorageClientStateKey(this.persistenceKey, this.js), this.eo = /** Assembles the key for the current sequence number. */
13582    function createWebStorageSequenceNumberKey(e2) {
13583      return `firestore_sequence_number_${e2}`;
13584    }(this.persistenceKey), this.Ys = this.Ys.insert(this.js, new __PRIVATE_LocalClientState()), this.no = new RegExp(`^${Ut}_${s}_([^_]*)$`), this.ro = new RegExp(`^${Kt}_${s}_(\\d+)(?:_(.*))?$`), this.io = new RegExp(`^${Wt}_${s}_(\\d+)$`), this.so = /** Assembles the key for the online state of the primary tab. */
13585    function createWebStorageOnlineStateKey(e2) {
13586      return `firestore_online_state_${e2}`;
13587    }(this.persistenceKey), this.oo = function createBundleLoadedKey(e2) {
13588      return `firestore_bundle_loaded_v2_${e2}`;
13589    }(this.persistenceKey), // Rather than adding the storage observer during start(), we add the
13590    // storage observer during initialization. This ensures that we collect
13591    // events before other components populate their initial state (during their
13592    // respective start() calls). Otherwise, we might for example miss a
13593    // mutation that is added after LocalStore's start() processed the existing
13594    // mutations but before we observe WebStorage events.
13595    this.window.addEventListener("storage", this.Js);
13596  }
13597  /** Returns 'true' if WebStorage is available in the current environment. */
13598  static C(e) {
13599    return !(!e || !e.localStorage);
13600  }
13601  async start() {
13602    const e = await this.syncEngine.Ps();
13603    for (const t2 of e) {
13604      if (t2 === this.js) continue;
13605      const e2 = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t2));
13606      if (e2) {
13607        const n = __PRIVATE_RemoteClientState.Ks(t2, e2);
13608        n && (this.Ys = this.Ys.insert(n.clientId, n));
13609      }
13610    }
13611    this._o();
13612    const t = this.storage.getItem(this.so);
13613    if (t) {
13614      const e2 = this.ao(t);
13615      e2 && this.uo(e2);
13616    }
13617    for (const e2 of this.Zs) this.Hs(e2);
13618    this.Zs = [], // Register a window unload hook to remove the client metadata entry from
13619    // WebStorage even if `shutdown()` was not called.
13620    this.window.addEventListener("pagehide", () => this.shutdown()), this.started = true;
13621  }
13622  writeSequenceNumber(e) {
13623    this.setItem(this.eo, JSON.stringify(e));
13624  }
13625  getAllActiveQueryTargets() {
13626    return this.co(this.Ys);
13627  }
13628  isActiveQueryTarget(e) {
13629    let t = false;
13630    return this.Ys.forEach((n, r) => {
13631      r.activeTargetIds.has(e) && (t = true);
13632    }), t;
13633  }
13634  addPendingMutation(e) {
13635    this.lo(e, "pending");
13636  }
13637  updateMutationState(e, t, n) {
13638    this.lo(e, t, n), // Once a final mutation result is observed by other clients, they no longer
13639    // access the mutation's metadata entry. Since WebStorage replays events
13640    // in order, it is safe to delete the entry right after updating it.
13641    this.ho(e);
13642  }
13643  addLocalQueryTarget(e, t = true) {
13644    let n = "not-current";
13645    if (this.isActiveQueryTarget(e)) {
13646      const t2 = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));
13647      if (t2) {
13648        const r = __PRIVATE_QueryTargetMetadata.Ks(e, t2);
13649        r && (n = r.state);
13650      }
13651    }
13652    return t && this.Po.Gs(e), this._o(), n;
13653  }
13654  removeLocalQueryTarget(e) {
13655    this.Po.zs(e), this._o();
13656  }
13657  isLocalQueryTarget(e) {
13658    return this.Po.activeTargetIds.has(e);
13659  }
13660  clearQueryState(e) {
13661    this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));
13662  }
13663  updateQueryState(e, t, n) {
13664    this.To(e, t, n);
13665  }
13666  handleUserChange(e, t, n) {
13667    t.forEach((e2) => {
13668      this.ho(e2);
13669    }), this.currentUser = e, n.forEach((e2) => {
13670      this.addPendingMutation(e2);
13671    });
13672  }
13673  setOnlineState(e) {
13674    this.Io(e);
13675  }
13676  notifyBundleLoaded(e) {
13677    this.Eo(e);
13678  }
13679  shutdown() {
13680    this.started && (this.window.removeEventListener("storage", this.Js), this.removeItem(this.Xs), this.started = false);
13681  }
13682  getItem(e) {
13683    const t = this.storage.getItem(e);
13684    return __PRIVATE_logDebug(Gt, "READ", e, t), t;
13685  }
13686  setItem(e, t) {
13687    __PRIVATE_logDebug(Gt, "SET", e, t), this.storage.setItem(e, t);
13688  }
13689  removeItem(e) {
13690    __PRIVATE_logDebug(Gt, "REMOVE", e), this.storage.removeItem(e);
13691  }
13692  Hs(e) {
13693    const t = e;
13694    if (t.storageArea === this.storage) {
13695      if (__PRIVATE_logDebug(Gt, "EVENT", t.key, t.newValue), t.key === this.Xs) return void __PRIVATE_logError("Received WebStorage notification for local change. Another client might have garbage-collected our state");
13696      this.Fi.enqueueRetryable(async () => {
13697        if (this.started) {
13698          if (null !== t.key) {
13699            if (this.no.test(t.key)) {
13700              if (null == t.newValue) {
13701                const e2 = this.Ao(t.key);
13702                return this.Ro(e2, null);
13703              }
13704              {
13705                const e2 = this.Vo(t.key, t.newValue);
13706                if (e2) return this.Ro(e2.clientId, e2);
13707              }
13708            } else if (this.ro.test(t.key)) {
13709              if (null !== t.newValue) {
13710                const e2 = this.mo(t.key, t.newValue);
13711                if (e2) return this.fo(e2);
13712              }
13713            } else if (this.io.test(t.key)) {
13714              if (null !== t.newValue) {
13715                const e2 = this.po(t.key, t.newValue);
13716                if (e2) return this.yo(e2);
13717              }
13718            } else if (t.key === this.so) {
13719              if (null !== t.newValue) {
13720                const e2 = this.ao(t.newValue);
13721                if (e2) return this.uo(e2);
13722              }
13723            } else if (t.key === this.eo) {
13724              const e2 = function __PRIVATE_fromWebStorageSequenceNumber(e3) {
13725                let t2 = __PRIVATE_ListenSequence.ue;
13726                if (null != e3) try {
13727                  const n = JSON.parse(e3);
13728                  __PRIVATE_hardAssert("number" == typeof n, 30636, {
13729                    wo: e3
13730                  }), t2 = n;
13731                } catch (e4) {
13732                  __PRIVATE_logError(Gt, "Failed to read sequence number from WebStorage", e4);
13733                }
13734                return t2;
13735              }(t.newValue);
13736              e2 !== __PRIVATE_ListenSequence.ue && this.sequenceNumberHandler(e2);
13737            } else if (t.key === this.oo) {
13738              const e2 = this.So(t.newValue);
13739              await Promise.all(e2.map((e3) => this.syncEngine.bo(e3)));
13740            }
13741          }
13742        } else this.Zs.push(t);
13743      });
13744    }
13745  }
13746  get Po() {
13747    return this.Ys.get(this.js);
13748  }
13749  _o() {
13750    this.setItem(this.Xs, this.Po.Ws());
13751  }
13752  lo(e, t, n) {
13753    const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);
13754    this.setItem(i, r.Ws());
13755  }
13756  ho(e) {
13757    const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);
13758    this.removeItem(t);
13759  }
13760  Io(e) {
13761    const t = {
13762      clientId: this.js,
13763      onlineState: e
13764    };
13765    this.storage.setItem(this.so, JSON.stringify(t));
13766  }
13767  To(e, t, n) {
13768    const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n);
13769    this.setItem(r, i.Ws());
13770  }
13771  Eo(e) {
13772    const t = JSON.stringify(Array.from(e));
13773    this.setItem(this.oo, t);
13774  }
13775  /**
13776   * Parses a client state key in WebStorage. Returns null if the key does not
13777   * match the expected key format.
13778   */
13779  Ao(e) {
13780    const t = this.no.exec(e);
13781    return t ? t[1] : null;
13782  }
13783  /**
13784   * Parses a client state in WebStorage. Returns 'null' if the value could not
13785   * be parsed.
13786   */
13787  Vo(e, t) {
13788    const n = this.Ao(e);
13789    return __PRIVATE_RemoteClientState.Ks(n, t);
13790  }
13791  /**
13792   * Parses a mutation batch state in WebStorage. Returns 'null' if the value
13793   * could not be parsed.
13794   */
13795  mo(e, t) {
13796    const n = this.ro.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
13797    return __PRIVATE_MutationMetadata.Ks(new User(i), r, t);
13798  }
13799  /**
13800   * Parses a query target state from WebStorage. Returns 'null' if the value
13801   * could not be parsed.
13802   */
13803  po(e, t) {
13804    const n = this.io.exec(e), r = Number(n[1]);
13805    return __PRIVATE_QueryTargetMetadata.Ks(r, t);
13806  }
13807  /**
13808   * Parses an online state from WebStorage. Returns 'null' if the value
13809   * could not be parsed.
13810   */
13811  ao(e) {
13812    return __PRIVATE_SharedOnlineState.Ks(e);
13813  }
13814  So(e) {
13815    return JSON.parse(e);
13816  }
13817  async fo(e) {
13818    if (e.user.uid === this.currentUser.uid) return this.syncEngine.Do(e.batchId, e.state, e.error);
13819    __PRIVATE_logDebug(Gt, `Ignoring mutation for non-active user ${e.user.uid}`);
13820  }
13821  yo(e) {
13822    return this.syncEngine.vo(e.targetId, e.state, e.error);
13823  }
13824  Ro(e, t) {
13825    const n = t ? this.Ys.insert(e, t) : this.Ys.remove(e), r = this.co(this.Ys), i = this.co(n), s = [], o = [];
13826    return i.forEach((e2) => {
13827      r.has(e2) || s.push(e2);
13828    }), r.forEach((e2) => {
13829      i.has(e2) || o.push(e2);
13830    }), this.syncEngine.Co(s, o).then(() => {
13831      this.Ys = n;
13832    });
13833  }
13834  uo(e) {
13835    this.Ys.get(e.clientId) && this.onlineStateHandler(e.onlineState);
13836  }
13837  co(e) {
13838    let t = __PRIVATE_targetIdSet();
13839    return e.forEach((e2, n) => {
13840      t = t.unionWith(n.activeTargetIds);
13841    }), t;
13842  }
13843}
13844class __PRIVATE_MemorySharedClientState {
13845  constructor() {
13846    this.Fo = new __PRIVATE_LocalClientState(), this.Mo = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
13847  }
13848  addPendingMutation(e) {
13849  }
13850  updateMutationState(e, t, n) {
13851  }
13852  addLocalQueryTarget(e, t = true) {
13853    return t && this.Fo.Gs(e), this.Mo[e] || "not-current";
13854  }
13855  updateQueryState(e, t, n) {
13856    this.Mo[e] = t;
13857  }
13858  removeLocalQueryTarget(e) {
13859    this.Fo.zs(e);
13860  }
13861  isLocalQueryTarget(e) {
13862    return this.Fo.activeTargetIds.has(e);
13863  }
13864  clearQueryState(e) {
13865    delete this.Mo[e];
13866  }
13867  getAllActiveQueryTargets() {
13868    return this.Fo.activeTargetIds;
13869  }
13870  isActiveQueryTarget(e) {
13871    return this.Fo.activeTargetIds.has(e);
13872  }
13873  start() {
13874    return this.Fo = new __PRIVATE_LocalClientState(), Promise.resolve();
13875  }
13876  handleUserChange(e, t, n) {
13877  }
13878  setOnlineState(e) {
13879  }
13880  shutdown() {
13881  }
13882  writeSequenceNumber(e) {
13883  }
13884  notifyBundleLoaded(e) {
13885  }
13886}
13887/**
13888 * @license
13889 * Copyright 2019 Google LLC
13890 *
13891 * Licensed under the Apache License, Version 2.0 (the "License");
13892 * you may not use this file except in compliance with the License.
13893 * You may obtain a copy of the License at
13894 *
13895 *   http://www.apache.org/licenses/LICENSE-2.0
13896 *
13897 * Unless required by applicable law or agreed to in writing, software
13898 * distributed under the License is distributed on an "AS IS" BASIS,
13899 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13900 * See the License for the specific language governing permissions and
13901 * limitations under the License.
13902 */
13903class __PRIVATE_NoopConnectivityMonitor {
13904  xo(e) {
13905  }
13906  shutdown() {
13907  }
13908}
13909/**
13910 * @license
13911 * Copyright 2019 Google LLC
13912 *
13913 * Licensed under the Apache License, Version 2.0 (the "License");
13914 * you may not use this file except in compliance with the License.
13915 * You may obtain a copy of the License at
13916 *
13917 *   http://www.apache.org/licenses/LICENSE-2.0
13918 *
13919 * Unless required by applicable law or agreed to in writing, software
13920 * distributed under the License is distributed on an "AS IS" BASIS,
13921 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13922 * See the License for the specific language governing permissions and
13923 * limitations under the License.
13924 */
13925const zt = "ConnectivityMonitor";
13926class __PRIVATE_BrowserConnectivityMonitor {
13927  constructor() {
13928    this.Oo = () => this.No(), this.Bo = () => this.Lo(), this.ko = [], this.qo();
13929  }
13930  xo(e) {
13931    this.ko.push(e);
13932  }
13933  shutdown() {
13934    window.removeEventListener("online", this.Oo), window.removeEventListener("offline", this.Bo);
13935  }
13936  qo() {
13937    window.addEventListener("online", this.Oo), window.addEventListener("offline", this.Bo);
13938  }
13939  No() {
13940    __PRIVATE_logDebug(zt, "Network connectivity changed: AVAILABLE");
13941    for (const e of this.ko) e(
13942      0
13943      /* NetworkStatus.AVAILABLE */
13944    );
13945  }
13946  Lo() {
13947    __PRIVATE_logDebug(zt, "Network connectivity changed: UNAVAILABLE");
13948    for (const e of this.ko) e(
13949      1
13950      /* NetworkStatus.UNAVAILABLE */
13951    );
13952  }
13953  // TODO(chenbrian): Consider passing in window either into this component or
13954  // here for testing via FakeWindow.
13955  /** Checks that all used attributes of window are available. */
13956  static C() {
13957    return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
13958  }
13959}
13960/**
13961 * @license
13962 * Copyright 2023 Google LLC
13963 *
13964 * Licensed under the Apache License, Version 2.0 (the "License");
13965 * you may not use this file except in compliance with the License.
13966 * You may obtain a copy of the License at
13967 *
13968 *   http://www.apache.org/licenses/LICENSE-2.0
13969 *
13970 * Unless required by applicable law or agreed to in writing, softw
13970are
13971 * distributed under the License is distributed on an "AS IS" BASIS,
13972 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13973 * See the License for the specific language governing permissions and
13974 * limitations under the License.
13975 */
13976let jt = null;
13977function __PRIVATE_generateUniqueDebugId() {
13978  return null === jt ? jt = function __PRIVATE_generateInitialUniqueDebugId() {
13979    return 268435456 + Math.round(2147483648 * Math.random());
13980  }() : jt++, "0x" + jt.toString(16);
13981}
13982/**
13983 * @license
13984 * Copyright 2020 Google LLC
13985 *
13986 * Licensed under the Apache License, Version 2.0 (the "License");
13987 * you may not use this file except in compliance with the License.
13988 * You may obtain a copy of the License at
13989 *
13990 *   http://www.apache.org/licenses/LICENSE-2.0
13991 *
13992 * Unless required by applicable law or agreed to in writing, software
13993 * distributed under the License is distributed on an "AS IS" BASIS,
13994 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13995 * See the License for the specific language governing permissions and
13996 * limitations under the License.
13997 */
13998const Jt = "RestConnection", Ht = {
13999  BatchGetDocuments: "batchGet",
14000  Commit: "commit",
14001  RunQuery: "runQuery",
14002  RunAggregationQuery: "runAggregationQuery"
14003};
14004class __PRIVATE_RestConnection {
14005  get Qo() {
14006    return false;
14007  }
14008  constructor(e) {
14009    this.databaseInfo = e, this.databaseId = e.databaseId;
14010    const t = e.ssl ? "https" : "http", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database);
14011    this.$o = t + "://" + e.host, this.Uo = `projects/${n}/databases/${r}`, this.Ko = this.databaseId.database === ut ? `project_id=${n}` : `project_id=${n}&database_id=${r}`;
14012  }
14013  Wo(e, t, n, r, i) {
14014    const s = __PRIVATE_generateUniqueDebugId(), o = this.Go(e, t.toUriEncodedString());
14015    __PRIVATE_logDebug(Jt, `Sending RPC '${e}' ${s}:`, o, n);
14016    const _ = {
14017      "google-cloud-resource-prefix": this.Uo,
14018      "x-goog-request-params": this.Ko
14019    };
14020    this.zo(_, r, i);
14021    const { host: a } = new URL(o), u = isCloudWorkstation(a);
14022    return this.jo(e, o, _, n, u).then((t2) => (__PRIVATE_logDebug(Jt, `Received RPC '${e}' ${s}: `, t2), t2), (t2) => {
14023      throw __PRIVATE_logWarn(Jt, `RPC '${e}' ${s} failed with error: `, t2, "url: ", o, "request:", n), t2;
14024    });
14025  }
14026  Jo(e, t, n, r, i, s) {
14027    return this.Wo(e, t, n, r, i);
14028  }
14029  /**
14030   * Modifies the headers for a request, adding any authorization token if
14031   * present and any additional headers for the request.
14032   */
14033  zo(e, t, n) {
14034    e["X-Goog-Api-Client"] = // SDK_VERSION is updated to different value at runtime depending on the entry point,
14035    // so we need to get its value when we need it in a function.
14036    function __PRIVATE_getGoogApiClientValue() {
14037      return "gl-js/ fire/" + x;
14038    }(), // Content-Type: text/plain will avoid preflight requests which might
14039    // mess with CORS and redirects by proxies. If we add custom headers
14040    // we will need to change this code to potentially use the $httpOverwrite
14041    // parameter supported by ESF to avoid triggering preflight requests.
14042    e["Content-Type"] = "text/plain", this.databaseInfo.appId && (e["X-Firebase-GMPID"] = this.databaseInfo.appId), t && t.headers.forEach((t2, n2) => e[n2] = t2), n && n.headers.forEach((t2, n2) => e[n2] = t2);
14043  }
14044  Go(e, t) {
14045    const n = Ht[e];
14046    return `${this.$o}/v1/${t}:${n}`;
14047  }
14048  /**
14049   * Closes and cleans up any resources associated with the connection. This
14050   * implementation is a no-op because there are no resources associated
14051   * with the RestConnection that need to be cleaned up.
14052   */
14053  terminate() {
14054  }
14055}
14056/**
14057 * @license
14058 * Copyright 2017 Google LLC
14059 *
14060 * Licensed under the Apache License, Version 2.0 (the "License");
14061 * you may not use this file except in compliance with the License.
14062 * You may obtain a copy of the License at
14063 *
14064 *   http://www.apache.org/licenses/LICENSE-2.0
14065 *
14066 * Unless required by applicable law or agreed to in writing, software
14067 * distributed under the License is distributed on an "AS IS" BASIS,
14068 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14069 * See the License for the specific language governing permissions and
14070 * limitations under the License.
14071 */
14072class __PRIVATE_StreamBridge {
14073  constructor(e) {
14074    this.Ho = e.Ho, this.Yo = e.Yo;
14075  }
14076  Zo(e) {
14077    this.Xo = e;
14078  }
14079  e_(e) {
14080    this.t_ = e;
14081  }
14082  n_(e) {
14083    this.r_ = e;
14084  }
14085  onMessage(e) {
14086    this.i_ = e;
14087  }
14088  close() {
14089    this.Yo();
14090  }
14091  send(e) {
14092    this.Ho(e);
14093  }
14094  s_() {
14095    this.Xo();
14096  }
14097  o_() {
14098    this.t_();
14099  }
14100  __(e) {
14101    this.r_(e);
14102  }
14103  a_(e) {
14104    this.i_(e);
14105  }
14106}
14107/**
14108 * @license
14109 * Copyright 2017 Google LLC
14110 *
14111 * Licensed under the Apache License, Version 2.0 (the "License");
14112 * you may not use this file except in compliance with the License.
14113 * You may obtain a copy of the License at
14114 *
14115 *   http://www.apache.org/licenses/LICENSE-2.0
14116 *
14117 * Unless required by applicable law or agreed to in writing, software
14118 * distributed under the License is distributed on an "AS IS" BASIS,
14119 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14120 * See the License for the specific language governing permissions and
14121 * limitations under the License.
14122 */
14123const Yt = "WebChannelConnection";
14124class __PRIVATE_WebChannelConnection extends __PRIVATE_RestConnection {
14125  constructor(e) {
14126    super(e), /** A collection of open WebChannel instances */
14127    this.u_ = [], this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions;
14128  }
14129  jo(e, t, n, r, i) {
14130    const s = __PRIVATE_generateUniqueDebugId();
14131    return new Promise((i2, o) => {
14132      const _ = new XhrIo();
14133      _.setWithCredentials(true), _.listenOnce(EventType.COMPLETE, () => {
14134        try {
14135          switch (_.getLastErrorCode()) {
14136            case ErrorCode.NO_ERROR:
14137              const t2 = _.getResponseJson();
14138              __PRIVATE_logDebug(Yt, `XHR for RPC '${e}' ${s} received:`, JSON.stringify(t2)), i2(t2);
14139              break;
14140            case ErrorCode.TIMEOUT:
14141              __PRIVATE_logDebug(Yt, `RPC '${e}' ${s} timed out`), o(new FirestoreError(N.DEADLINE_EXCEEDED, "Request time out"));
14142              break;
14143            case ErrorCode.HTTP_ERROR:
14144              const n2 = _.getStatus();
14145              if (__PRIVATE_logDebug(Yt, `RPC '${e}' ${s} failed with status:`, n2, "response text:", _.getResponseText()), n2 > 0) {
14146                let e2 = _.getResponseJson();
14147                Array.isArray(e2) && (e2 = e2[0]);
14148                const t3 = null == e2 ? void 0 : e2.error;
14149                if (t3 && t3.status && t3.message) {
14150                  const e3 = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e4) {
14151                    const t4 = e4.toLowerCase().replace(/_/g, "-");
14152                    return Object.values(N).indexOf(t4) >= 0 ? t4 : N.UNKNOWN;
14153                  }(t3.status);
14154                  o(new FirestoreError(e3, t3.message));
14155                } else o(new FirestoreError(N.UNKNOWN, "Server responded with status " + _.getStatus()));
14156              } else
14157                o(new FirestoreError(N.UNAVAILABLE, "Connection failed."));
14158              break;
14159            default:
14160              fail(9055, {
14161                c_: e,
14162                streamId: s,
14163                l_: _.getLastErrorCode(),
14164                h_: _.getLastError()
14165              });
14166          }
14167        } finally {
14168          __PRIVATE_logDebug(Yt, `RPC '${e}' ${s} completed.`);
14169        }
14170      });
14171      const a = JSON.stringify(r);
14172      __PRIVATE_logDebug(Yt, `RPC '${e}' ${s} sending request:`, r), _.send(t, "POST", a, n, 15);
14173    });
14174  }
14175  P_(e, t, n) {
14176    const r = __PRIVATE_generateUniqueDebugId(), i = [this.$o, "/", "google.firestore.v1.Firestore", "/", e, "/channel"], s = createWebChannelTransport(), o = getStatEventTarget(), _ = {
14177      // Required for backend stickiness, routing behavior is based on this
14178      // parameter.
14179      httpSessionIdParam: "gsessionid",
14180      initMessageHeaders: {},
14181      messageUrlParams: {
14182        // This param is used to improve routing and project isolation by the
14183        // backend and must be included in every request.
14184        database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
14185      },
14186      sendRawJson: true,
14187      supportsCrossDomainXhr: true,
14188      internalChannelParams: {
14189        // Override the default timeout (randomized between 10-20 seconds) since
14190        // a large write batch on a slow internet connection may take a long
14191        // time to send to the backend. Rather than have WebChannel impose a
14192        // tight timeout which could lead to infinite timeouts and retries, we
14193        // set it very large (5-10 minutes) and rely on the browser's builtin
14194        // timeouts to kick in if the request isn't working.
14195        forwardChannelRequestTimeoutMs: 6e5
14196      },
14197      forceLongPolling: this.forceLongPolling,
14198      detectBufferingProxy: this.autoDetectLongPolling
14199    }, a = this.longPollingOptions.timeoutSeconds;
14200    void 0 !== a && (_.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (_.useFetchStreams = true), this.zo(_.initMessageHeaders, t, n), // Sending the custom headers we just added to request.initMessageHeaders
14201    // (Authorization, etc.) will trigger the browser to make a CORS preflight
14202    // request because the XHR will no longer meet the criteria for a "simple"
14203    // CORS request:
14204    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
14205    // Therefore to avoid the CORS preflight request (an extra network
14206    // roundtrip), we use the encodeInitMessageHeaders option to specify that
14207    // the headers should instead be encoded in the request's POST payload,
14208    // which is recognized by the webchannel backend.
14209    _.encodeInitMessageHeaders = true;
14210    const u = i.join("");
14211    __PRIVATE_logDebug(Yt, `Creating RPC '${e}' stream ${r}: ${u}`, _);
14212    const c = s.createWebChannel(u, _);
14213    this.T_(c);
14214    let l = false, h = false;
14215    const P = new __PRIVATE_StreamBridge({
14216      Ho: (t2) => {
14217        h ? __PRIVATE_logDebug(Yt, `Not sending because RPC '${e}' stream ${r} is closed:`, t2) : (l || (__PRIVATE_logDebug(Yt, `Opening RPC '${e}' stream ${r} transport.`), c.open(), l = true), __PRIVATE_logDebug(Yt, `RPC '${e}' stream ${r} sending:`, t2), c.send(t2));
14218      },
14219      Yo: () => c.close()
14220    }), __PRIVATE_unguardedEventListen = (e2, t2, n2) => {
14221      e2.listen(t2, (e3) => {
14222        try {
14223          n2(e3);
14224        } catch (e4) {
14225          setTimeout(() => {
14226            throw e4;
14227          }, 0);
14228        }
14229      });
14230    };
14231    return __PRIVATE_unguardedEventListen(c, WebChannel.EventType.OPEN, () => {
14232      h || (__PRIVATE_logDebug(Yt, `RPC '${e}' stream ${r} transport opened.`), P.s_());
14233    }), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.CLOSE, () => {
14234      h || (h = true, __PRIVATE_logDebug(Yt, `RPC '${e}' stream ${r} transport closed`), P.__(), this.I_(c));
14235    }), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.ERROR, (t2) => {
14236      h || (h = true, __PRIVATE_logWarn(Yt, `RPC '${e}' stream ${r} transport errored. Name:`, t2.name, "Message:", t2.message), P.__(new FirestoreError(N.UNAVAILABLE, "The operation could not be completed")));
14237    }), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.MESSAGE, (t2) => {
14238      var n2;
14239      if (!h) {
14240        const i2 = t2.data[0];
14241        __PRIVATE_hardAssert(!!i2, 16349);
14242        const s2 = i2, o2 = (null == s2 ? void 0 : s2.error) || (null === (n2 = s2[0]) || void 0 === n2 ? void 0 : n2.error);
14243        if (o2) {
14244          __PRIVATE_logDebug(Yt, `RPC '${e}' stream ${r} received error:`, o2);
14245          const t3 = o2.status;
14246          let n3 = (
14247            /**
14248            * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
14249            *
14250            * @returns The Code equivalent to the given status string or undefined if
14251            *     there is no match.
14252            */
14253            function __PRIVATE_mapCodeFromRpcStatus(e2) {
14254              const t4 = ft[e2];
14255              if (void 0 !== t4) return __PRIVATE_mapCodeFromRpcCode(t4);
14256            }(t3)
14257          ), i3 = o2.message;
14258          void 0 === n3 && (n3 = N.INTERNAL, i3 = "Unknown error status: " + t3 + " with message " + o2.message), // Mark closed so no further events are propagated
14259          h = true, P.__(new FirestoreError(n3, i3)), c.close();
14260        } else __PRIVATE_logDebug(Yt, `RPC '${e}' stream ${r} received:`, i2), P.a_(i2);
14261      }
14262    }), __PRIVATE_unguardedEventListen(o, Event.STAT_EVENT, (t2) => {
14263      t2.stat === Stat.PROXY ? __PRIVATE_logDebug(Yt, `RPC '${e}' stream ${r} detected buffering proxy`) : t2.stat === Stat.NOPROXY && __PRIVATE_logDebug(Yt, `RPC '${e}' stream ${r} detected no buffering proxy`);
14264    }), setTimeout(() => {
14265      P.o_();
14266    }, 0), P;
14267  }
14268  /**
14269   * Closes and cleans up any resources associated with the connection.
14270   */
14271  terminate() {
14272    this.u_.forEach((e) => e.close()), this.u_ = [];
14273  }
14274  /**
14275   * Add a WebChannel instance to the collection of open instances.
14276   * @param webChannel
14277   */
14278  T_(e) {
14279    this.u_.push(e);
14280  }
14281  /**
14282   * Remove a WebChannel instance from the collection of open instances.
14283   * @param webChannel
14284   */
14285  I_(e) {
14286    this.u_ = this.u_.filter((t) => t === e);
14287  }
14288}
14289/**
14290 * @license
14291 * Copyright 2020 Google LLC
14292 *
14293 * Licensed under the Apache License, Version 2.0 (the "License");
14294 * you may not use this file except in compliance with the License.
14295 * You may obtain a copy of the License at
14296 *
14297 *   http://www.apache.org/licenses/LICENSE-2.0
14298 *
14299 * Unless required by applicable law or agreed to in writing, software
14300 * distributed under the License is distributed on an "AS IS" BASIS,
14301 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14302 * See the License for the specific language governing permissions and
14303 * limitations under the License.
14304 */
14305/**
14306 * @license
14307 * Copyright 2020 Google LLC
14308 *
14309 * Licensed under the Apache License, Version 2.0 (the "License");
14310 * you may not use this file except in compliance with the License.
14311 * You may obtain a copy of the License at
14312 *
14313 *   http://www.apache.org/licenses/LICENSE-2.0
14314 *
14315 * Unless required by applicable law or agreed to in writing, softw
14315are
14316 * distributed under the License is distributed on an "AS IS" BASIS,
14317 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14318 * See the License for the specific language governing permissions and
14319 * limitations under the License.
14320 */
14321function __PRIVATE_getWindow() {
14322  return "undefined" != typeof window ? window : null;
14323}
14324function getDocument() {
14325  return "undefined" != typeof document ? document : null;
14326}
14327/**
14328 * @license
14329 * Copyright 2020 Google LLC
14330 *
14331 * Licensed under the Apache License, Version 2.0 (the "License");
14332 * you may not use this file except in compliance with the License.
14333 * You may obtain a copy of the License at
14334 *
14335 *   http://www.apache.org/licenses/LICENSE-2.0
14336 *
14337 * Unless required by applicable law or agreed to in writing, software
14338 * distributed under the License is distributed on an "AS IS" BASIS,
14339 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14340 * See the License for the specific language governing permissions and
14341 * limitations under the License.
14342 */
14343function __PRIVATE_newSerializer(e) {
14344  return new JsonProtoSerializer(
14345    e,
14346    /* useProto3Json= */
14347    true
14348  );
14349}
14350/**
14351 * @license
14352 * Copyright 2017 Google LLC
14353 *
14354 * Licensed under the Apache License, Version 2.0 (the "License");
14355 * you may not use this file except in compliance with the License.
14356 * You may obtain a copy of the License at
14357 *
14358 *   http://www.apache.org/licenses/LICENSE-2.0
14359 *
14360 * Unless required by applicable law or agreed to in writing, software
14361 * distributed under the License is distributed on an "AS IS" BASIS,
14362 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14363 * See the License for the specific language governing permissions and
14364 * limitations under the License.
14365 */
14366class __PRIVATE_ExponentialBackoff {
14367  constructor(e, t, n = 1e3, r = 1.5, i = 6e4) {
14368    this.Fi = e, this.timerId = t, this.d_ = n, this.E_ = r, this.A_ = i, this.R_ = 0, this.V_ = null, /** The last backoff attempt, as epoch milliseconds. */
14369    this.m_ = Date.now(), this.reset();
14370  }
14371  /**
14372   * Resets the backoff delay.
14373   *
14374   * The very next backoffAndWait() will have no delay. If it is called again
14375   * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
14376   * subsequent ones will increase according to the backoffFactor.
14377   */
14378  reset() {
14379    this.R_ = 0;
14380  }
14381  /**
14382   * Resets the backoff delay to the maximum delay (e.g. for use after a
14383   * RESOURCE_EXHAUSTED error).
14384   */
14385  f_() {
14386    this.R_ = this.A_;
14387  }
14388  /**
14389   * Returns a promise that resolves after currentDelayMs, and increases the
14390   * delay for any subsequent attempts. If there was a pending backoff operation
14391   * already, it will be canceled.
14392   */
14393  g_(e) {
14394    this.cancel();
14395    const t = Math.floor(this.R_ + this.p_()), n = Math.max(0, Date.now() - this.m_), r = Math.max(0, t - n);
14396    r > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.R_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), this.V_ = this.Fi.enqueueAfterDelay(this.timerId, r, () => (this.m_ = Date.now(), e())), // Apply backoff factor to determine next delay and ensure it is within
14397    // bounds.
14398    this.R_ *= this.E_, this.R_ < this.d_ && (this.R_ = this.d_), this.R_ > this.A_ && (this.R_ = this.A_);
14399  }
14400  y_() {
14401    null !== this.V_ && (this.V_.skipDelay(), this.V_ = null);
14402  }
14403  cancel() {
14404    null !== this.V_ && (this.V_.cancel(), this.V_ = null);
14405  }
14406  /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */
14407  p_() {
14408    return (Math.random() - 0.5) * this.R_;
14409  }
14410}
14411/**
14412 * @license
14413 * Copyright 2017 Google LLC
14414 *
14415 * Licensed under the Apache License, Version 2.0 (the "License");
14416 * you may not use this file except in compliance with the License.
14417 * You may obtain a copy of the License at
14418 *
14419 *   http://www.apache.org/licenses/LICENSE-2.0
14420 *
14421 * Unless required by applicable law or agreed to in writing, software
14422 * distributed under the License is distributed on an "AS IS" BASIS,
14423 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14424 * See the License for the specific language governing permissions and
14425 * limitations under the License.
14426 */
14427const Zt = "PersistentStream";
14428class __PRIVATE_PersistentStream {
14429  constructor(e, t, n, r, i, s, o, _) {
14430    this.Fi = e, this.w_ = n, this.S_ = r, this.connection = i, this.authCredentialsProvider = s, this.appCheckCredentialsProvider = o, this.listener = _, this.state = 0, /**
14431    * A close count that's incremented every time the stream is closed; used by
14432    * getCloseGuardedDispatcher() to invalidate callbacks that happen after
14433    * close.
14434    */
14435    this.b_ = 0, this.D_ = null, this.v_ = null, this.stream = null, /**
14436    * Count of response messages received.
14437    */
14438    this.C_ = 0, this.F_ = new __PRIVATE_ExponentialBackoff(e, t);
14439  }
14440  /**
14441   * Returns true if start() has been called and no error has occurred. True
14442   * indicates the stream is open or in the process of opening (which
14443   * encompasses respecting backoff, getting auth tokens, and starting the
14444   * actual RPC). Use isOpen() to determine if the stream is open and ready for
14445   * outbound requests.
14446   */
14447  M_() {
14448    return 1 === this.state || 5 === this.state || this.x_();
14449  }
14450  /**
14451   * Returns true if the underlying RPC is open (the onOpen() listener has been
14452   * called) and the stream is ready for outbound requests.
14453   */
14454  x_() {
14455    return 2 === this.state || 3 === this.state;
14456  }
14457  /**
14458   * Starts the RPC. Only allowed if isStarted() returns false. The stream is
14459   * not immediately ready for use: onOpen() will be invoked when the RPC is
14460   * ready for outbound requests, at which point isOpen() will return true.
14461   *
14462   * When start returns, isStarted() will return true.
14463   */
14464  start() {
14465    this.C_ = 0, 4 !== this.state ? this.auth() : this.O_();
14466  }
14467  /**
14468   * Stops the RPC. This call is idempotent and allowed regardless of the
14469   * current isStarted() state.
14470   *
14471   * When stop returns, isStarted() and isOpen() will both return false.
14472   */
14473  async stop() {
14474    this.M_() && await this.close(
14475      0
14476      /* PersistentStreamState.Initial */
14477    );
14478  }
14479  /**
14480   * After an error the stream will usually back off on the next attempt to
14481   * start it. If the error warrants an immediate restart of the stream, the
14482   * sender can use this to indicate that the receiver should not back off.
14483   *
14484   * Each error will call the onClose() listener. That function can decide to
14485   * inhibit backoff if required.
14486   */
14487  N_() {
14488    this.state = 0, this.F_.reset();
14489  }
14490  /**
14491   * Marks this stream as idle. If no further actions are performed on the
14492   * stream for one minute, the stream will automatically close itself and
14493   * notify the stream's onClose() handler with Status.OK. The stream will then
14494   * be in a !isStarted() state, requiring the caller to start the stream again
14495   * before further use.
14496   *
14497   * Only streams that are in state 'Open' can be marked idle, as all other
14498   * states imply pending network operations.
14499   */
14500  B_() {
14501    this.x_() && null === this.D_ && (this.D_ = this.Fi.enqueueAfterDelay(this.w_, 6e4, () => this.L_()));
14502  }
14503  /** Sends a message to the underlying stream. */
14504  k_(e) {
14505    this.q_(), this.stream.send(e);
14506  }
14507  /** Called by the idle timer when the stream should close due to inactivity. */
14508  async L_() {
14509    if (this.x_())
14510      return this.close(
14511        0
14512        /* PersistentStreamState.Initial */
14513      );
14514  }
14515  /** Marks the stream as active again. */
14516  q_() {
14517    this.D_ && (this.D_.cancel(), this.D_ = null);
14518  }
14519  /** Cancels the health check delayed operation. */
14520  Q_() {
14521    this.v_ && (this.v_.cancel(), this.v_ = null);
14522  }
14523  /**
14524   * Closes the stream and cleans up as necessary:
14525   *
14526   * * closes the underlying GRPC stream;
14527   * * calls the onClose handler with the given 'error';
14528   * * sets internal stream state to 'finalState';
14529   * * adjusts the backoff timer based on the error
14530   *
14531   * A new stream can be opened by calling start().
14532   *
14533   * @param finalState - the intended state of the stream after closing.
14534   * @param error - the error the connection was closed with.
14535   */
14536  async close(e, t) {
14537    this.q_(), this.Q_(), this.F_.cancel(), // Invalidates any stream-related callbacks (e.g. from auth or the
14538    // underlying stream), guaranteeing they won't execute.
14539    this.b_++, 4 !== e ? (
14540      // If this is an intentional close ensure we don't delay our next connection attempt.
14541      this.F_.reset()
14542    ) : t && t.code === N.RESOURCE_EXHAUSTED ? (
14543      // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
14544      (__PRIVATE_logError(t.toString()), __PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."), this.F_.f_())
14545    ) : t && t.code === N.UNAUTHENTICATED && 3 !== this.state && // "unauthenticated" error means the token was rejected. This should rarely
14546    // happen since both Auth and AppCheck ensure a sufficient TTL when we
14547    // request a token. If a user manually resets their system clock this can
14548    // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
14549    // before we received the first message and we need to invali
14549date the token
14550    // to ensure that we fetch a new token.
14551    (this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), // Clean up the underlying stream because we are no longer interested in events.
14552    null !== this.stream && (this.U_(), this.stream.close(), this.stream = null), // This state must be assigned before calling onClose() to allow the callback to
14553    // inhibit backoff or otherwise manipulate the state in its non-started state.
14554    this.state = e, // Notify the listener that the stream closed.
14555    await this.listener.n_(t);
14556  }
14557  /**
14558   * Can be overridden to perform additional cleanup before the stream is closed.
14559   * Calling super.tearDown() is not required.
14560   */
14561  U_() {
14562  }
14563  auth() {
14564    this.state = 1;
14565    const e = this.K_(this.b_), t = this.b_;
14566    Promise.all([this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken()]).then(([e2, n]) => {
14567      this.b_ === t && // Normally we'd have to schedule the callback on the AsyncQueue.
14568      // However, the following calls are safe to be called outside the
14569      // AsyncQueue since they don't chain asynchronous calls
14570      this.W_(e2, n);
14571    }, (t2) => {
14572      e(() => {
14573        const e2 = new FirestoreError(N.UNKNOWN, "Fetching auth token failed: " + t2.message);
14574        return this.G_(e2);
14575      });
14576    });
14577  }
14578  W_(e, t) {
14579    const n = this.K_(this.b_);
14580    this.stream = this.z_(e, t), this.stream.Zo(() => {
14581      n(() => this.listener.Zo());
14582    }), this.stream.e_(() => {
14583      n(() => (this.state = 2, this.v_ = this.Fi.enqueueAfterDelay(this.S_, 1e4, () => (this.x_() && (this.state = 3), Promise.resolve())), this.listener.e_()));
14584    }), this.stream.n_((e2) => {
14585      n(() => this.G_(e2));
14586    }), this.stream.onMessage((e2) => {
14587      n(() => 1 == ++this.C_ ? this.j_(e2) : this.onNext(e2));
14588    });
14589  }
14590  O_() {
14591    this.state = 5, this.F_.g_(async () => {
14592      this.state = 0, this.start();
14593    });
14594  }
14595  // Visible for tests
14596  G_(e) {
14597    return __PRIVATE_logDebug(Zt, `close with error: ${e}`), this.stream = null, this.close(4, e);
14598  }
14599  /**
14600   * Returns a "dispatcher" function that dispatches operations onto the
14601   * AsyncQueue but only runs them if closeCount remains unchanged. This allows
14602   * us to turn auth / stream callbacks into no-ops if the stream is closed /
14603   * re-opened, etc.
14604   */
14605  K_(e) {
14606    return (t) => {
14607      this.Fi.enqueueAndForget(() => this.b_ === e ? t() : (__PRIVATE_logDebug(Zt, "stream callback skipped by getCloseGuardedDispatcher."), Promise.resolve()));
14608    };
14609  }
14610}
14611class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream {
14612  constructor(e, t, n, r, i, s) {
14613    super(e, "listen_stream_connection_backoff", "listen_stream_idle", "health_check_timeout", t, n, r, s), this.serializer = i;
14614  }
14615  z_(e, t) {
14616    return this.connection.P_("Listen", e, t);
14617  }
14618  j_(e) {
14619    return this.onNext(e);
14620  }
14621  onNext(e) {
14622    this.F_.reset();
14623    const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e2) {
14624      if (!("targetChange" in e2)) return SnapshotVersion.min();
14625      const t2 = e2.targetChange;
14626      return t2.targetIds && t2.targetIds.length ? SnapshotVersion.min() : t2.readTime ? __PRIVATE_fromVersion(t2.readTime) : SnapshotVersion.min();
14627    }(e);
14628    return this.listener.J_(t, n);
14629  }
14630  /**
14631   * Registers interest in the results of the given target. If the target
14632   * includes a resumeToken it will be included in the request. Results that
14633   * affect the target will be streamed back as WatchChange messages that
14634   * reference the targetId.
14635   */
14636  H_(e) {
14637    const t = {};
14638    t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e2, t2) {
14639      let n2;
14640      const r = t2.target;
14641      if (n2 = __PRIVATE_targetIsDocumentTarget(r) ? {
14642        documents: __PRIVATE_toDocumentsTarget(e2, r)
14643      } : {
14644        query: __PRIVATE_toQueryTarget(e2, r).Vt
14645      }, n2.targetId = t2.targetId, t2.resumeToken.approximateByteSize() > 0) {
14646        n2.resumeToken = __PRIVATE_toBytes(e2, t2.resumeToken);
14647        const r2 = __PRIVATE_toInt32Proto(e2, t2.expectedCount);
14648        null !== r2 && (n2.expectedCount = r2);
14649      } else if (t2.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {
14650        n2.readTime = toTimestamp(e2, t2.snapshotVersion.toTimestamp());
14651        const r2 = __PRIVATE_toInt32Proto(e2, t2.expectedCount);
14652        null !== r2 && (n2.expectedCount = r2);
14653      }
14654      return n2;
14655    }(this.serializer, e);
14656    const n = __PRIVATE_toListenRequestLabels(this.serializer, e);
14657    n && (t.labels = n), this.k_(t);
14658  }
14659  /**
14660   * Unregisters interest in the results of the target associated with the
14661   * given targetId.
14662   */
14663  Y_(e) {
14664    const t = {};
14665    t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, this.k_(t);
14666  }
14667}
14668class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream {
14669  constructor(e, t, n, r, i, s) {
14670    super(e, "write_stream_connection_backoff", "write_stream_idle", "health_check_timeout", t, n, r, s), this.serializer = i;
14671  }
14672  /**
14673   * Tracks whether or not a handshake has been successfully exchanged and
14674   * the stream is ready to accept mutations.
14675   */
14676  get Z_() {
14677    return this.C_ > 0;
14678  }
14679  // Override of PersistentStream.start
14680  start() {
14681    this.lastStreamToken = void 0, super.start();
14682  }
14683  U_() {
14684    this.Z_ && this.X_([]);
14685  }
14686  z_(e, t) {
14687    return this.connection.P_("Write", e, t);
14688  }
14689  j_(e) {
14690    return __PRIVATE_hardAssert(!!e.streamToken, 31322), this.lastStreamToken = e.streamToken, // The first response is always the handshake response
14691    __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length, 55816), this.listener.ea();
14692  }
14693  onNext(e) {
14694    __PRIVATE_hardAssert(!!e.streamToken, 12678), this.lastStreamToken = e.streamToken, // A successful first write response means the stream is healthy,
14695    // Note, that we could consider a successful handshake healthy, however,
14696    // the write itself might be causing an error we want to back off from.
14697    this.F_.reset();
14698    const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime);
14699    return this.listener.ta(n, t);
14700  }
14701  /**
14702   * Sends an initial streamToken to the server, performing the handshake
14703   * required to make the StreamingWrite RPC work. Subsequent
14704   * calls should wait until onHandshakeComplete was called.
14705   */
14706  na() {
14707    const e = {};
14708    e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.k_(e);
14709  }
14710  /** Sends a group of mutations to the Firestore backend to apply. */
14711  X_(e) {
14712    const t = {
14713      streamToken: this.lastStreamToken,
14714      writes: e.map((e2) => toMutation(this.serializer, e2))
14715    };
14716    this.k_(t);
14717  }
14718}
14719/**
14720 * @license
14721 * Copyright 2017 Google LLC
14722 *
14723 * Licensed under the Apache License, Version 2.0 (the "License");
14724 * you may not use this file except in compliance with the License.
14725 * You may obtain a copy of the License at
14726 *
14727 *   http://www.apache.org/licenses/LICENSE-2.0
14728 *
14729 * Unless required by applicable law or agreed to in writing, software
14730 * distributed under the License is distributed on an "AS IS" BASIS,
14731 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14732 * See the License for the specific language governing permissions and
14733 * limitations under the License.
14734 */
14735class Datastore {
14736}
14737class __PRIVATE_DatastoreImpl extends Datastore {
14738  constructor(e, t, n, r) {
14739    super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, this.serializer = r, this.ra = false;
14740  }
14741  ia() {
14742    if (this.ra) throw new FirestoreError(N.FAILED_PRECONDITION, "The client has already been terminated.");
14743  }
14744  /** Invokes the provided RPC with auth and AppCheck tokens. */
14745  Wo(e, t, n, r) {
14746    return this.ia(), Promise.all([this.authCredentials.getToken(), this.appCheckCredentials.getToken()]).then(([i, s]) => this.connection.Wo(e, __PRIVATE_toResourcePath(t, n), r, i, s)).catch((e2) => {
14747      throw "FirebaseError" === e2.name ? (e2.code === N.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), this.appCheckCredentials.invalidateToken()), e2) : new FirestoreError(N.UNKNOWN, e2.toString());
14748    });
14749  }
14750  /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */
14751  Jo(e, t, n, r, i) {
14752    return this.ia(), Promise.all([this.authCredentials.getToken(), this.appCheckCredentials.getToken()]).then(([s, o]) => this.connection.Jo(e, __PRIVATE_toResourcePath(t, n), r, s, o, i)).catch((e2) => {
14753      throw "FirebaseError" === e2.name ? (e2.code === N.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), this.appCheckCredentials.invalidateToken()), e2) : new FirestoreError(N.UNKNOWN, e2.toString());
14754    });
14755  }
14756  terminate() {
14757    this.ra = true, this.connection.terminate();
14758  }
14759}
14760class __PRIVATE_OnlineStateTracker {
14761  constructor(e, t) {
14762    this.asyncQueue = e, this.onlineStateHandler = t, /** The current OnlineState. */
14763    this.state = "Unknown", /**
14764    * A count of consecutive failures to open the stream. If it reaches the
14765    * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
14766    * Offline.
14767    */
14768    this.sa = 0, /**
14769    * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
14770    * transition from OnlineState.Unknown to OnlineState.Offline without waiting
14771    * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
14772    */
14773    this.oa = null, /**
14774    * Whether the client should log a warning message if it fails to connect to
14775    * the backend (initially true, cleared after a successful stream, or if we've
14776    * logged the message already).
14777    */
14778    this._a = true;
14779  }
14780  /**
14781   * Called by RemoteStore when a watch stream is started (including on each
14782   * backoff attempt).
14783   *
14784   * If this is the first attempt, it sets the OnlineState to Unknown and starts
14785   * the onlineStateTimer.
14786   */
14787  aa() {
14788    0 === this.sa && (this.ua(
14789      "Unknown"
14790      /* OnlineState.Unknown */
14791    ), this.oa = this.asyncQueue.enqueueAfterDelay("online_state_timeout", 1e4, () => (this.oa = null, this.ca("Backend didn't respond within 10 seconds."), this.ua(
14792      "Offline"
14793      /* OnlineState.Offline */
14794    ), Promise.resolve())));
14795  }
14796  /**
14797   * Updates our OnlineState as appropriate after the watch stream reports a
14798   * failure. The first failure moves us to the 'Unknown' state. We then may
14799   * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
14800   * actually transition to the 'Offline' state.
14801   */
14802  la(e) {
14803    "Online" === this.state ? this.ua(
14804      "Unknown"
14805      /* OnlineState.Unknown */
14806    ) : (this.sa++, this.sa >= 1 && (this.ha(), this.ca(`Connection failed 1 times. Most recent error: ${e.toString()}`), this.ua(
14807      "Offline"
14808      /* OnlineState.Offline */
14809    )));
14810  }
14811  /**
14812   * Explicitly sets the OnlineState to the specified state.
14813   *
14814   * Note that this resets our timers / failure counters, etc. used by our
14815   * Offline heuristics, so must not be used in place of
14816   * handleWatchStreamStart() and handleWatchStreamFailure().
14817   */
14818  set(e) {
14819    this.ha(), this.sa = 0, "Online" === e && // We've connected to watch at least once. Don't warn the developer
14820    // about being offline going forward.
14821    (this._a = false), this.ua(e);
14822  }
14823  ua(e) {
14824    e !== this.state && (this.state = e, this.onlineStateHandler(e));
14825  }
14826  ca(e) {
14827    const t = `Could not reach Cloud Firestore backend. ${e}
14828This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
14829    this._a ? (__PRIVATE_logError(t), this._a = false) : __PRIVATE_logDebug("OnlineStateTracker", t);
14830  }
14831  ha() {
14832    null !== this.oa && (this.oa.cancel(), this.oa = null);
14833  }
14834}
14835/**
14836 * @license
14837 * Copyright 2017 Google LLC
14838 *
14839 * Licensed under the Apache License, Version 2.0 (the "License");
14840 * you may not use this file except in compliance with the License.
14841 * You may obtain a copy of the License at
14842 *
14843 *   http://www.apache.org/licenses/LICENSE-2.0
14844 *
14845 * Unless required by applicable law or agreed to in writing, software
14846 * distributed under the License is distributed on an "AS IS" BASIS,
14847 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14848 * See the License for the specific language governing permissions and
14849 * limitations under the License.
14850 */
14851const Xt = "RemoteStore";
14852class __PRIVATE_RemoteStoreImpl {
14853  constructor(e, t, n, r, i) {
14854    this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, /**
14855    * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
14856    * LocalStore via fillWritePipeline() and have or will send to the write
14857    * stream.
14858    *
14859    * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
14860    * restart the write stream. When the stream is established the writes in the
14861    * pipeline will be sent in order.
14862    *
14863    * Writes remain in writePipeline until they are acknowledged by the backend
14864    * and thus will automatically be re-sent if the stream is interrupted /
14865    * restarted before they're acknowledged.
14866    *
14867    * Write responses from the backend are linked to their originating request
14868    * purely based on order, and so we can just shift() writes from the front of
14869    * the writePipeline as we receive responses.
14870    */
14871    this.Pa = [], /**
14872    * A mapping of watched targets that the client cares about tracking and the
14873    * user has explicitly called a 'listen' for this target.
14874    *
14875    * These targets may or may not have been sent to or acknowledged by the
14876    * server. On re-establishing the listen stream, these targets should be sent
14877    * to the server. The targets removed with unlistens are removed eagerly
14878    * without waiting for confirmation from the listen stream.
14879    */
14880    this.Ta = /* @__PURE__ */ new Map(), /**
14881    * A set of reasons for why the RemoteStore may be offline. If empty, the
14882    * RemoteStore may start its network connections.
14883    */
14884    this.Ia = /* @__PURE__ */ new Set(), /**
14885    * Event handlers that get called when the network is disabled or enabled.
14886    *
14887    * PORTING NOTE: These functions are used on the Web client to create the
14888    * underlying streams (to support tree-shakeable streams). On Android and iOS,
14889    * the streams are created during construction of RemoteStore.
14890    */
14891    this.da = [], this.Ea = i, this.Ea.xo((e2) => {
14892      n.enqueueAndForget(async () => {
14893        __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(Xt, "Restarting streams for network reachability change."), await async function __PRIVATE_restartNetwork(e3) {
14894          const t2 = __PRIVATE_debugCast(e3);
14895          t2.Ia.add(
14896            4
14897            /* OfflineCause.ConnectivityChange */
14898          ), await __PRIVATE_disableNetworkInternal(t2), t2.Aa.set(
14899            "Unknown"
14900            /* OnlineState.Unknown */
14901          ), t2.Ia.delete(
14902            4
14903            /* OfflineCause.ConnectivityChange */
14904          ), await __PRIVATE_enableNetworkInternal(t2);
14905        }(this));
14906      });
14907    }), this.Aa = new __PRIVATE_OnlineStateTracker(n, r);
14908  }
14909}
14910async function __PRIVATE_enableNetworkInternal(e) {
14911  if (__PRIVATE_canUseNetwork(e)) for (const t of e.da) await t(
14912    /* enabled= */
14913    true
14914  );
14915}
14916async function __PRIVATE_disableNetworkInternal(e) {
14917  for (const t of e.da) await t(
14918    /* enabled= */
14919    false
14920  );
14921}
14922function __PRIVATE_remoteStoreListen(e, t) {
14923  const n = __PRIVATE_debugCast(e);
14924  n.Ta.has(t.targetId) || // Mark this as something the client is currently listening for.
14925  (n.Ta.set(t.targetId, t), __PRIVATE_shouldStartWatchStream(n) ? (
14926    // The listen will be sent in onWatchStreamOpen
14927    __PRIVATE_startWatchStream(n)
14928  ) : __PRIVATE_ensureWatchStream(n).x_() && __PRIVATE_sendWatchRequest(n, t));
14929}
14930function __PRIVATE_remoteStoreUnlisten(e, t) {
14931  const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n);
14932  n.Ta.delete(t), r.x_() && __PRIVATE_sendUnwatchRequest(n, t), 0 === n.Ta.size && (r.x_() ? r.B_() : __PRIVATE_canUseNetwork(n) && // Revert to OnlineState.Unknown if the watch stream is not open and we
14933  // have no listeners, since without any listens to send we cannot
14934  // confirm if the stream is healthy and upgrade to OnlineState.Online.
14935  n.Aa.set(
14936    "Unknown"
14937    /* OnlineState.Unknown */
14938  ));
14939}
14940function __PRIVATE_sendWatchRequest(e, t) {
14941  if (e.Ra.$e(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {
14942    const n = e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;
14943    t = t.withExpectedCount(n);
14944  }
14945  __PRIVATE_ensureWatchStream(e).H_(t);
14946}
14947function __PRIVATE_sendUnwatchRequest(e, t) {
14948  e.Ra.$e(t), __PRIVATE_ensureWatchStream(e).Y_(t);
14949}
14950function __PRIVATE_startWatchStream(e) {
14951  e.Ra = new __PRIVATE_WatchChangeAggregator({
14952    getRemoteKeysForTarget: (t) => e.remoteSyncer.getRemoteKeysForTarget(t),
14953    Et: (t) => e.Ta.get(t) || null,
14954    lt: () => e.datastore.serializer.databaseId
14955  }), __PRIVATE_ensureWatchStream(e).start(), e.Aa.aa();
14956}
14957function __PRIVATE_shouldStartWatchStream(e) {
14958  return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).M_() && e.Ta.size > 0;
14959}
14960function __PRIVATE_canUseNetwork(e) {
14961  return 0 === __PRIVATE_debugCast(e).Ia.size;
14962}
14963function __PRIVATE_cleanUpWatchStreamState(e) {
14964  e.Ra = void 0;
14965}
14966async function __PRIVATE_onWatchStreamConnected(e) {
14967  e.Aa.set(
14968    "Online"
14969    /* OnlineState.Online */
14970  );
14971}
14972async function __PRIVATE_onWatchStreamOpen(e) {
14973  e.Ta.forEach((t, n) => {
14974    __PRIVATE_sendWatchRequest(e, t);
14975  });
14976}
14977async function __PRIVATE_onWatchStreamClose(e, t) {
14978  __PRIVATE_cleanUpWatchStreamState(e), // If we still need the watch stream, retry the connection.
14979  __PRIVATE_shouldStartWatchStream(e) ? (e.Aa.la(t), __PRIVATE_startWatchStream(e)) : (
14980    // No need to restart watch stream because there are no active targets.
14981    // The online state is set to unknown because there is no active attempt
14982    // at establishing a connection
14983    e.Aa.set(
14984      "Unknown"
14985      /* OnlineState.Unknown */
14986    )
14987  );
14988}
14989async function __PRIVATE_onWatchStreamChange(e, t, n) {
14990  if (
14991    // Mark the client as online since we got a message from the server
14992    e.Aa.set(
14993      "Online"
14994      /* OnlineState.Online */
14995    ), t instanceof __PRIVATE_WatchTargetChange && 2 === t.state && t.cause
14996  )
14997    try {
14998      await async function __PRIVATE_handleTargetError(e2, t2) {
14999        const n2 = t2.cause;
15000        for (const r of t2.targetIds)
15001          e2.Ta.has(r) && (await e2.remoteSyncer.rejectListen(r, n2), e2.Ta.delete(r), e2.Ra.removeTarget(r));
15002      }(e, t);
15003    } catch (n2) {
15004      __PRIVATE_logDebug(Xt, "Failed to remove targets %s: %s ", t.targetIds.join(","), n2), await __PRIVATE_disableNetworkUntilRecovery(e, n2);
15005    }
15006  else if (t instanceof __PRIVATE_DocumentWatchChange ? e.Ra.Ye(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.Ra.it(t) : e.Ra.et(t), !n.isEqual(SnapshotVersion.min())) try {
15007    const t2 = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);
15008    n.compareTo(t2) >= 0 && // We have received a target change with a global snapshot if the snapshot
15009    // version is not equal to SnapshotVersion.min().
15010    /**
15011    * Takes a batch of changes from the Datastore, repackages them as a
15012    * RemoteEvent, and passes that on to the listener, which is typically the
15013    * SyncEngine.
15014    */
15015    await function __PRIVATE_raiseWatchSnapshot(e2, t3) {
15016      const n2 = e2.Ra.Pt(t3);
15017      return n2.targetChanges.forEach((n3, r) => {
15018        if (n3.resumeToken.approximateByteSize() > 0) {
15019          const i = e2.Ta.get(r);
15020          i && e2.Ta.set(r, i.withResumeToken(n3.resumeToken, t3));
15021        }
15022      }), // Re-establish listens for the targets that have been invalidated by
15023      // existence filter mismatches.
15024      n2.targetMismatches.forEach((t4, n3) => {
15025        const r = e2.Ta.get(t4);
15026        if (!r)
15027          return;
15028        e2.Ta.set(t4, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), // Cause a hard reset by unwatching and rewatching immediately, but
15029        // deliberately don't send a resume token so that we get a full update.
15030        __PRIVATE_sendUnwatchRequest(e2, t4);
15031        const i = new TargetData(r.target, t4, n3, r.sequenceNumber);
15032        __PRIVATE_sendWatchRequest(e2, i);
15033      }), e2.remoteSyncer.applyRemoteEvent(n2);
15034    }(e, n);
15035  } catch (t2) {
15036    __PRIVATE_logDebug(Xt, "Failed to raise snapshot:", t2), await __PRIVATE_disableNetworkUntilRecovery(e, t2);
15037  }
15038}
15039async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) {
15040  if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t;
15041  e.Ia.add(
15042    1
15043    /* OfflineCause.IndexedDbFailed */
15044  ), // Disable network and raise offline snapshots
15045  await __PRIVATE_disableNetworkInternal(e), e.Aa.set(
15046    "Offline"
15047    /* OnlineState.Offline */
15048  ), n || // Use a simple read operation to determine if IndexedDB recovered.
15049  // Ideally, we would expose a health check directly on SimpleDb, but
15050  // RemoteStore only has access to persistence through LocalStore.
15051  (n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), // Probe IndexedDB periodically and re-enable network
15052  e.asyncQueue.enqueueRetryable(async () => {
15053    __PRIVATE_logDebug(Xt, "Retrying IndexedDB access"), await n(), e.Ia.delete(
15054      1
15055      /* OfflineCause.IndexedDbFailed */
15056    ), await __PRIVATE_enableNetworkInternal(e);
15057  });
15058}
15059function __PRIVATE_executeWithRecovery(e, t) {
15060  return t().catch((n) => __PRIVATE_disableNetworkUntilRecovery(e, n, t));
15061}
15062async function __PRIVATE_fillWritePipeline(e) {
15063  const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t);
15064  let r = t.Pa.length > 0 ? t.Pa[t.Pa.length - 1].batchId : G;
15065  for (; __PRIVATE_canAddToWritePipeline(t); ) try {
15066    const e2 = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r);
15067    if (null === e2) {
15068      0 === t.Pa.length && n.B_();
15069      break;
15070    }
15071    r = e2.batchId, __PRIVATE_addToWritePipeline(t, e2);
15072  } catch (e2) {
15073    await __PRIVATE_disableNetworkUntilRecovery(t, e2);
15074  }
15075  __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t);
15076}
15077function __PRIVATE_canAddToWritePipeline(e) {
15078  return __PRIVATE_canUseNetwork(e) && e.Pa.length < 10;
15079}
15080function __PRIVATE_addToWritePipeline(e, t) {
15081  e.Pa.push(t);
15082  const n = __PRIVATE_ensureWriteStream(e);
15083  n.x_() && n.Z_ && n.X_(t.mutations);
15084}
15085function __PRIVATE_shouldStartWriteStream(e) {
15086  return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).M_() && e.Pa.length > 0;
15087}
15088function __PRIVATE_startWriteStream(e) {
15089  __PRIVATE_ensureWriteStream(e).start();
15090}
15091async function __PRIVATE_onWriteStreamOpen(e) {
15092  __PRIVATE_ensureWriteStream(e).na();
15093}
15094async function __PRIVATE_onWriteHandshakeComplete(e) {
15095  const t = __PRIVATE_ensureWriteStream(e);
15096  for (const n of e.Pa) t.X_(n.mutations);
15097}
15098async function __PRIVATE_onMutationResult(e, t, n) {
15099  const r = e.Pa.shift(), i = MutationBatchResult.from(r, t, n);
15100  await __PRIVATE_executeWithRecovery(e, () => e.remoteSyncer.applySuccessfulWrite(i)), // It's possible that with the completion of this mutation another
15101  // slot has freed up.
15102  await __PRIVATE_fillWritePipeline(e);
15103}
15104async function __PRIVATE_onWriteStreamClose(e, t) {
15105  t && __PRIVATE_ensureWriteStream(e).Z_ && // This error affects the actual write.
15106  await async function __PRIVATE_handleWriteError(e2, t2) {
15107    if (function __PRIVATE_isPermanentWriteError(e3) {
15108      return __PRIVATE_isPermanentError(e3) && e3 !== N.ABORTED;
15109    }(t2.code)) {
15110      const n = e2.Pa.shift();
15111      __PRIVATE_ensureWriteStream(e2).N_(), await __PRIVATE_executeWithRecovery(e2, () => e2.remoteSyncer.rejectFailedWrite(n.batchId, t2)), // It's possible that with the completion of this mutation
15112      // another slot has freed up.
15113      await __PRIVATE_fillWritePipeline(e2);
15114    }
15115  }(e, t), // The write stream might have been started by refilling the write
15116  // pipeline for failed writes
15117  __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e);
15118}
15119async function __PRIVATE_remoteStoreHandleCredentialChange(e, t) {
15120  const n = __PRIVATE_debugCast(e);
15121  n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(Xt, "RemoteStore received new credentials");
15122  const r = __PRIVATE_canUseNetwork(n);
15123  n.Ia.add(
15124    3
15125    /* OfflineCause.CredentialChange */
15126  ), await __PRIVATE_disableNetworkInternal(n), r && // Don't set the network status to Unknown if we are offline.
15127  n.Aa.set(
15128    "Unknown"
15129    /* OnlineState.Unknown */
15130  ), await n.remoteSyncer.handleCredentialChange(t), n.Ia.delete(
15131    3
15132    /* OfflineCause.CredentialChange */
15133  ), await __PRIVATE_enableNetworkInternal(n);
15134}
15135async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) {
15136  const n = __PRIVATE_debugCast(e);
15137  t ? (n.Ia.delete(
15138    2
15139    /* OfflineCause.IsSecondary */
15140  ), await __PRIVATE_enableNetworkInternal(n)) : t || (n.Ia.add(
15141    2
15142    /* OfflineCause.IsSecondary */
15143  ), await __PRIVATE_disableNetworkInternal(n), n.Aa.set(
15144    "Unknown"
15145    /* OnlineState.Unknown */
15146  ));
15147}
15148function __PRIVATE_ensureWatchStream(e) {
15149  return e.Va || // Create stream (but note that it is not started yet).
15150  (e.Va = function __PRIVATE_newPersistentWatchStream(e2, t, n) {
15151    const r = __PRIVATE_debugCast(e2);
15152    return r.ia(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);
15153  }(e.datastore, e.asyncQueue, {
15154    Zo: __PRIVATE_onWatchStreamConnected.bind(null, e),
15155    e_: __PRIVATE_onWatchStreamOpen.bind(null, e),
15156    n_: __PRIVATE_onWatchStreamClose.bind(null, e),
15157    J_: __PRIVATE_onWatchStreamChange.bind(null, e)
15158  }), e.da.push(async (t) => {
15159    t ? (e.Va.N_(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.Aa.set(
15160      "Unknown"
15161      /* OnlineState.Unknown */
15162    )) : (await e.Va.stop(), __PRIVATE_cleanUpWatchStreamState(e));
15163  })), e.Va;
15164}
15165function __PRIVATE_ensureWriteStream(e) {
15166  return e.ma || // Create stream (but note that it is not started yet).
15167  (e.ma = function __PRIVATE_newPersistentWriteStream(e2, t, n) {
15168    const r = __PRIVATE_debugCast(e2);
15169    return r.ia(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);
15170  }(e.datastore, e.asyncQueue, {
15171    Zo: () => Promise.resolve(),
15172    e_: __PRIVATE_onWriteStreamOpen.bind(null, e),
15173    n_: __PRIVATE_onWriteStreamClose.bind(null, e),
15174    ea: __PRIVATE_onWriteHandshakeComplete.bind(null, e),
15175    ta: __PRIVATE_onMutationResult.bind(null, e)
15176  }), e.da.push(async (t) => {
15177    t ? (e.ma.N_(), // This will start the write stream if necessary.
15178    await __PRIVATE_fillWritePipeline(e)) : (await e.ma.stop(), e.Pa.length > 0 && (__PRIVATE_logDebug(Xt, `Stopping write stream with ${e.Pa.length} pending writes`), e.Pa = []));
15179  })), e.ma;
15180}
15181/**
15182 * @license
15183 * Copyright 2017 Google LLC
15184 *
15185 * Licensed under the Apache License, Version 2.0 (the "License");
15186 * you may not use this file except in compliance with the License.
15187 * You may obtain a copy of the License at
15188 *
15189 *   http://www.apache.org/licenses/LICENSE-2.0
15190 *
15191 * Unless required by applicable law or agreed to in writing, software
15192 * distributed under the License is distributed on an "AS IS" BASIS,
15193 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15194 * See the License for the specific language governing permissions and
15195 * limitations under the License.
15196 */
15197class DelayedOperation {
15198  constructor(e, t, n, r, i) {
15199    this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, this.deferred = new __PRIVATE_Deferred(), this.then = this.deferred.promise.then.bind(this.deferred.promise), // It's normal for the deferred promise to be canceled (due to cancellation)
15200    // and so we attach a dummy catch callback to avoid
15201    // 'UnhandledPromiseRejectionWarning' log spam.
15202    this.deferred.promise.catch((e2) => {
15203    });
15204  }
15205  get promise() {
15206    return this.deferred.promise;
15207  }
15208  /**
15209   * Creates and returns a DelayedOperation that has been scheduled to be
15210   * executed on the provided asyncQueue after the provided delayMs.
15211   *
15212   * @param asyncQueue - The queue to schedule the operation on.
15213   * @param id - A Timer ID identifying the type of operation this is.
15214   * @param delayMs - The delay (ms) before the operation should be scheduled.
15215   * @param op - The operation to run.
15216   * @param removalCallback - A callback to be called synchronously once the
15217   *   operation is executed or canceled, notifying the AsyncQueue to remove it
15218   *   from its delayedOperations list.
15219   *   PORTING NOTE: This exists to prevent making removeDelayedOperation() and
15220   *   the DelayedOperation class public.
15221   */
15222  static createAndSchedule(e, t, n, r, i) {
15223    const s = Date.now() + n, o = new DelayedOperation(e, t, s, r, i);
15224    return o.start(n), o;
15225  }
15226  /**
15227   * Starts the timer. This is called immediately after construction by
15228   * createAndSchedule().
15229   */
15230  start(e) {
15231    this.timerHandle = setTimeout(() => this.handleDelayElapsed(), e);
15232  }
15233  /**
15234   * Queues the operation to run immediately (if it hasn't already been run or
15235   * canceled).
15236   */
15237  skipDelay() {
15238    return this.handleDelayElapsed();
15239  }
15240  /**
15241   * Cancels the operation if it hasn't already been executed or canceled. The
15242   * promise will be rejected.
15243   *
15244   * As long as the operation has not yet been run, calling cancel() provides a
15245   * guarantee that the operation will not be run.
15246   */
15247  cancel(e) {
15248    null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(N.CANCELLED, "Operation cancelled" + (e ? ": " + e : ""))));
15249  }
15250  handleDelayElapsed() {
15251    this.asyncQueue.enqueueAndForget(() => null !== this.timerHandle ? (this.clearTimeout(), this.op().then((e) => this.deferred.resolve(e))) : Promise.resolve());
15252  }
15253  clearTimeout() {
15254    null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), this.timerHandle = null);
15255  }
15256}
15257function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) {
15258  if (__PRIVATE_logError("AsyncQueue", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new FirestoreError(N.UNAVAILABLE, `${t}: ${e}`);
15259  throw e;
15260}
15261/**
15262 * @license
15263 * Copyright 2017 Google LLC
15264 *
15265 * Licensed under the Apache License, Version 2.0 (the "License");
15266 * you may not use this file except in compliance with the License.
15267 * You may obtain a copy of the License at
15268 *
15269 *   http://www.apache.org/licenses/LICENSE-2.0
15270 *
15271 * Unless required by applicable law or agreed to in writing, software
15272 * distributed under the License is distributed on an "AS IS" BASIS,
15273 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15274 * See the License for the specific language governing permissions and
15275 * limitations under the License.
15276 */
15277class DocumentSet {
15278  /**
15279   * Returns an empty copy of the existing DocumentSet, using the same
15280   * comparator.
15281   */
15282  static emptySet(e) {
15283    return new DocumentSet(e.comparator);
15284  }
15285  /** The default ordering is by key if the comparator is omitted */
15286  constructor(e) {
15287    this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e2, t) => DocumentKey.comparator(e2.key, t.key), this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator);
15288  }
15289  has(e) {
15290    return null != this.keyedMap.get(e);
15291  }
15292  get(e) {
15293    return this.keyedMap.get(e);
15294  }
15295  first() {
15296    return this.sortedSet.minKey();
15297  }
15298  last() {
15299    return this.sortedSet.maxKey();
15300  }
15301  isEmpty() {
15302    return this.sortedSet.isEmpty();
15303  }
15304  /**
15305   * Returns the index of the provided key in the document set, or -1 if the
15306   * document key is not present in the set;
15307   */
15308  indexOf(e) {
15309    const t = this.keyedMap.get(e);
15310    return t ? this.sortedSet.indexOf(t) : -1;
15311  }
15312  get size() {
15313    return this.sortedSet.size;
15314  }
15315  /** Iterates documents in order defined by "comparator" */
15316  forEach(e) {
15317    this.sortedSet.inorderTraversal((t, n) => (e(t), false));
15318  }
15319  /** Inserts or updates a document with the same key */
15320  add(e) {
15321    const t = this.delete(e.key);
15322    return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null));
15323  }
15324  /** Deletes a document with a given key */
15325  delete(e) {
15326    const t = this.get(e);
15327    return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this;
15328  }
15329  isEqual(e) {
15330    if (!(e instanceof DocumentSet)) return false;
15331    if (this.size !== e.size) return false;
15332    const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator();
15333    for (; t.hasNext(); ) {
15334      const e2 = t.getNext().key, r = n.getNext().key;
15335      if (!e2.isEqual(r)) return false;
15336    }
15337    return true;
15338  }
15339  toString() {
15340    const e = [];
15341    return this.forEach((t) => {
15342      e.push(t.toString());
15343    }), 0 === e.length ? "DocumentSet ()" : "DocumentSet (\n  " + e.join("  \n") + "\n)";
15344  }
15345  copy(e, t) {
15346    const n = new DocumentSet();
15347    return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n;
15348  }
15349}
15350/**
15351 * @license
15352 * Copyright 2017 Google LLC
15353 *
15354 * Licensed under the Apache License, Version 2.0 (the "License");
15355 * you may not use this file except in compliance with the License.
15356 * You may obtain a copy of the License at
15357 *
15358 *   http://www.apache.org/licenses/LICENSE-2.0
15359 *
15360 * Unless required by applicable law or agreed to in writing, software
15361 * distributed under the License is distributed on an "AS IS" BASIS,
15362 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15363 * See the License for the specific language governing permissions and
15364 * limitations under the License.
15365 */
15366class __PRIVATE_DocumentChangeSet {
15367  constructor() {
15368    this.fa = new SortedMap(DocumentKey.comparator);
15369  }
15370  track(e) {
15371    const t = e.doc.key, n = this.fa.get(t);
15372    n ? (
15373      // Merge the new change with the existing change.
15374      0 !== e.type && 3 === n.type ? this.fa = this.fa.insert(t, e) : 3 === e.type && 1 !== n.type ? this.fa = this.fa.insert(t, {
15375        type: n.type,
15376        doc: e.doc
15377      }) : 2 === e.type && 2 === n.type ? this.fa = this.fa.insert(t, {
15378        type: 2,
15379        doc: e.doc
15380      }) : 2 === e.type && 0 === n.type ? this.fa = this.fa.insert(t, {
15381        type: 0,
15382        doc: e.doc
15383      }) : 1 === e.type && 0 === n.type ? this.fa = this.fa.remove(t) : 1 === e.type && 2 === n.type ? this.fa = this.fa.insert(t, {
15384        type: 1,
15385        doc: n.doc
15386      }) : 0 === e.type && 1 === n.type ? this.fa = this.fa.insert(t, {
15387        type: 2,
15388        doc: e.doc
15389      }) : (
15390        // This includes these cases, which don't make sense:
15391        // Added->Added
15392        // Removed->Removed
15393        // Modified->Added
15394        // Removed->Modified
15395        // Metadata->Added
15396        // Removed->Metadata
15397        fail(63341, {
15398          At: e,
15399          ga: n
15400        })
15401      )
15402    ) : this.fa = this.fa.insert(t, e);
15403  }
15404  pa() {
15405    const e = [];
15406    return this.fa.inorderTraversal((t, n) => {
15407      e.push(n);
15408    }), e;
15409  }
15410}
15411class ViewSnapshot {
15412  constructor(e, t, n, r, i, s, o, _, a) {
15413    this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, this.fromCache = s, this.syncStateChanged = o, this.excludesMetadataChanges = _, this.hasCachedResults = a;
15414  }
15415  /** Returns a view snapshot as if all documents in the snapshot were added. */
15416  static fromInitialDocuments(e, t, n, r, i) {
15417    const s = [];
15418    return t.forEach((e2) => {
15419      s.push({
15420        type: 0,
15421        doc: e2
15422      });
15423    }), new ViewSnapshot(
15424      e,
15425      t,
15426      DocumentSet.emptySet(t),
15427      s,
15428      n,
15429      r,
15430      /* syncStateChanged= */
15431      true,
15432      /* excludesMetadataChanges= */
15433      false,
15434      i
15435    );
15436  }
15437  get hasPendingWrites() {
15438    return !this.mutatedKeys.isEmpty();
15439  }
15440  isEqual(e) {
15441    if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryEquals(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return false;
15442    const t = this.docChanges, n = e.docChanges;
15443    if (t.length !== n.length) return false;
15444    for (let e2 = 0; e2 < t.length; e2++) if (t[e2].type !== n[e2].type || !t[e2].doc.isEqual(n[e2].doc)) return false;
15445    return true;
15446  }
15447}
15448/**
15449 * @license
15450 * Copyright 2017 Google LLC
15451 *
15452 * Licensed under the Apache License, Version 2.0 (the "License");
15453 * you may not use this file except in compliance with the License.
15454 * You may obtain a copy of the License at
15455 *
15456 *   http://www.apache.org/licenses/LICENSE-2.0
15457 *
15458 * Unless required by applicable law or agreed to in writing, software
15459 * distributed under the License is distributed on an "AS IS" BASIS,
15460 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15461 * See the License for the specific language governing permissions and
15462 * limitations under the License.
15463 */
15464class __PRIVATE_QueryListenersInfo {
15465  constructor() {
15466    this.ya = void 0, this.wa = [];
15467  }
15468  // Helper methods that checks if the query has listeners that listening to remote store
15469  Sa() {
15470    return this.wa.some((e) => e.ba());
15471  }
15472}
15473class __PRIVATE_EventManagerImpl {
15474  constructor() {
15475    this.queries = __PRIVATE_newQueriesObjectMap(), this.onlineState = "Unknown", this.Da = /* @__PURE__ */ new Set();
15476  }
15477  terminate() {
15478    !function __PRIVATE_errorAllTargets(e, t) {
15479      const n = __PRIVATE_debugCast(e), r = n.queries;
15480      n.queries = __PRIVATE_newQueriesObjectMap(), r.forEach((e2, n2) => {
15481        for (const e3 of n2.wa) e3.onError(t);
15482      });
15483    }(this, new FirestoreError(N.ABORTED, "Firestore shutting down"));
15484  }
15485}
15486function __PRIVATE_newQueriesObjectMap() {
15487  return new ObjectMap((e) => __PRIVATE_canonifyQuery(e), __PRIVATE_queryEquals);
15488}
15489async function __PRIVATE_eventManagerListen(e, t) {
15490  const n = __PRIVATE_debugCast(e);
15491  let r = 3;
15492  const i = t.query;
15493  let s = n.queries.get(i);
15494  s ? !s.Sa() && t.ba() && // Query has been listening to local cache, and tries to add a new listener sourced from watch.
15495  (r = 2) : (s = new __PRIVATE_QueryListenersInfo(), r = t.ba() ? 0 : 1);
15496  try {
15497    switch (r) {
15498      case 0:
15499        s.ya = await n.onListen(
15500          i,
15501          /** enableRemoteListen= */
15502          true
15503        );
15504        break;
15505      case 1:
15506        s.ya = await n.onListen(
15507          i,
15508          /** enableRemoteListen= */
15509          false
15510        );
15511        break;
15512      case 2:
15513        await n.onFirstRemoteStoreListen(i);
15514    }
15515  } catch (e2) {
15516    const n2 = __PRIVATE_wrapInUserErrorIfRecoverable(e2, `Initialization of query '${__PRIVATE_stringifyQuery(t.query)}' failed`);
15517    return void t.onError(n2);
15518  }
15519  if (n.queries.set(i, s), s.wa.push(t), // Run global snapshot listeners if a consistent snapshot has been emitted.
15520  t.va(n.onlineState), s.ya) {
15521    t.Ca(s.ya) && __PRIVATE_raiseSnapshotsInSyncEvent(n);
15522  }
15523}
15524async function __PRIVATE_eventManagerUnlisten(e, t) {
15525  const n = __PRIVATE_debugCast(e), r = t.query;
15526  let i = 3;
15527  const s = n.queries.get(r);
15528  if (s) {
15529    const e2 = s.wa.indexOf(t);
15530    e2 >= 0 && (s.wa.splice(e2, 1), 0 === s.wa.length ? i = t.ba() ? 0 : 1 : !s.Sa() && t.ba() && // The removed listener is the last one that sourced from watch.
15531    (i = 2));
15532  }
15533  switch (i) {
15534    case 0:
15535      return n.queries.delete(r), n.onUnlisten(
15536        r,
15537        /** disableRemoteListen= */
15538        true
15539      );
15540    case 1:
15541      return n.queries.delete(r), n.onUnlisten(
15542        r,
15543        /** disableRemoteListen= */
15544        false
15545      );
15546    case 2:
15547      return n.onLastRemoteStoreUnlisten(r);
15548    default:
15549      return;
15550  }
15551}
15552function __PRIVATE_eventManagerOnWatchChange(e, t) {
15553  const n = __PRIVATE_debugCast(e);
15554  let r = false;
15555  for (const e2 of t) {
15556    const t2 = e2.query, i = n.queries.get(t2);
15557    if (i) {
15558      for (const t3 of i.wa) t3.Ca(e2) && (r = true);
15559      i.ya = e2;
15560    }
15561  }
15562  r && __PRIVATE_raiseSnapshotsInSyncEvent(n);
15563}
15564function __PRIVATE_eventManagerOnWatchError(e, t, n) {
15565  const r = __PRIVATE_debugCast(e), i = r.queries.get(t);
15566  if (i) for (const e2 of i.wa) e2.onError(n);
15567  r.queries.delete(t);
15568}
15569function __PRIVATE_raiseSnapshotsInSyncEvent(e) {
15570  e.Da.forEach((e2) => {
15571    e2.next();
15572  });
15573}
15574var en, tn;
15575(tn = en || (en = {})).Fa = "default", /** Listen to changes in cache only */
15576tn.Cache = "cache";
15577class __PRIVATE_QueryListener {
15578  constructor(e, t, n) {
15579    this.query = e, this.Ma = t, /**
15580    * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
15581    * observer. This flag is set to true once we've actually raised an event.
15582    */
15583    this.xa = false, this.Oa = null, this.onlineState = "Unknown", this.options = n || {};
15584  }
15585  /**
15586   * Applies the new ViewSnapshot to this listener, raising a user-facing event
15587   * if applicable (depending on what changed, whether the user has opted into
15588   * metadata-only changes, etc.). Returns true if a user-facing event was
15589   * indeed raised.
15590   */
15591  Ca(e) {
15592    if (!this.options.includeMetadataChanges) {
15593      const t2 = [];
15594      for (const n of e.docChanges) 3 !== n.type && t2.push(n);
15595      e = new ViewSnapshot(
15596        e.query,
15597        e.docs,
15598        e.oldDocs,
15599        t2,
15600        e.mutatedKeys,
15601        e.fromCache,
15602        e.syncStateChanged,
15603        /* excludesMetadataChanges= */
15604        true,
15605        e.hasCachedResults
15606      );
15607    }
15608    let t = false;
vendor: 5,605 bytes, lines 15609-15772
15609    return this.xa ? this.Na(e) && (this.Ma.next(e), t = true) : this.Ba(e, this.onlineState) && (this.La(e), t = true), this.Oa = e, t;
15610  }
15611  onError(e) {
15612    this.Ma.error(e);
15613  }
15614  /** Returns whether a snapshot was raised. */
15615  va(e) {
15616    this.onlineState = e;
15617    let t = false;
15618    return this.Oa && !this.xa && this.Ba(this.Oa, e) && (this.La(this.Oa), t = true), t;
15619  }
15620  Ba(e, t) {
15621    if (!e.fromCache) return true;
15622    if (!this.ba()) return true;
15623    const n = "Offline" !== t;
15624    return (!this.options.ka || !n) && (!e.docs.isEmpty() || e.hasCachedResults || "Offline" === t);
15625  }
15626  Na(e) {
15627    if (e.docChanges.length > 0) return true;
15628    const t = this.Oa && this.Oa.hasPendingWrites !== e.hasPendingWrites;
15629    return !(!e.syncStateChanged && !t) && true === this.options.includeMetadataChanges;
15630  }
15631  La(e) {
15632    e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), this.xa = true, this.Ma.next(e);
15633  }
15634  ba() {
15635    return this.options.source !== en.Cache;
15636  }
15637}
15638/**
15639 * @license
15640 * Copyright 2020 Google LLC
15641 *
15642 * Licensed under the Apache License, Version 2.0 (the "License");
15643 * you may not use this file except in compliance with the License.
15644 * You may obtain a copy of the License at
15645 *
15646 *   http://www.apache.org/licenses/LICENSE-2.0
15647 *
15648 * Unless required by applicable law or agreed to in writing, software
15649 * distributed under the License is distributed on an "AS IS" BASIS,
15650 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15651 * See the License for the specific language governing permissions and
15652 * limitations under the License.
15653 */
15654class __PRIVATE_SizedBundleElement {
15655  constructor(e, t) {
15656    this.qa = e, this.byteLength = t;
15657  }
15658  Qa() {
15659    return "metadata" in this.qa;
15660  }
15661}
15662/**
15663 * @license
15664 * Copyright 2020 Google LLC
15665 *
15666 * Licensed under the Apache License, Version 2.0 (the "License");
15667 * you may not use this file except in compliance with the License.
15668 * You may obtain a copy of the License at
15669 *
15670 *   http://www.apache.org/licenses/LICENSE-2.0
15671 *
15672 * Unless required by applicable law or agreed to in writing, software
15673 * distributed under the License is distributed on an "AS IS" BASIS,
15674 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15675 * See the License for the specific language governing permissions and
15676 * limitations under the License.
15677 */
15678class __PRIVATE_BundleConverterImpl {
15679  constructor(e) {
15680    this.serializer = e;
15681  }
15682  Qs(e) {
15683    return fromName(this.serializer, e);
15684  }
15685  /**
15686   * Converts a BundleDocument to a MutableDocument.
15687   */
15688  $s(e) {
15689    return e.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e.document, false) : MutableDocument.newNoDocument(this.Qs(e.metadata.name), this.Us(e.metadata.readTime));
15690  }
15691  Us(e) {
15692    return __PRIVATE_fromVersion(e);
15693  }
15694}
15695class __PRIVATE_BundleLoader {
15696  constructor(e, t) {
15697    this.$a = e, this.serializer = t, /** Batched queries to be saved into storage */
15698    this.Ua = [], /** Batched documents to be saved into storage */
15699    this.Ka = [], /** The collection groups affected by this bundle. */
15700    this.collectionGroups = /* @__PURE__ */ new Set(), this.progress = __PRIVATE_bundleInitialProgress(e);
15701  }
15702  /**
15703   * Returns the named queries that have been parsed from the SizeBundleElements added by
15704   * calling {@link adSizedElement}.
15705   */
15706  get queries() {
15707    return this.Ua;
15708  }
15709  /**
15710   * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by
15711   * calling {@link addSizedElement}.
15712   */
15713  get documents() {
15714    return this.Ka;
15715  }
15716  /**
15717   * Adds an element from the bundle to the loader.
15718   *
15719   * Returns a new progress if adding the element leads to a new progress,
15720   * otherwise returns null.
15721   */
15722  Wa(e) {
15723    this.progress.bytesLoaded += e.byteLength;
15724    let t = this.progress.documentsLoaded;
15725    if (e.qa.namedQuery) this.Ua.push(e.qa.namedQuery);
15726    else if (e.qa.documentMetadata) {
15727      this.Ka.push({
15728        metadata: e.qa.documentMetadata
15729      }), e.qa.documentMetadata.exists || ++t;
15730      const n = ResourcePath.fromString(e.qa.documentMetadata.name);
15731      this.collectionGroups.add(n.get(n.length - 2));
15732    } else e.qa.document && (this.Ka[this.Ka.length - 1].document = e.qa.document, ++t);
15733    return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, Object.assign({}, this.progress)) : null;
15734  }
15735  Ga(e) {
15736    const t = /* @__PURE__ */ new Map(), n = new __PRIVATE_BundleConverterImpl(this.serializer);
15737    for (const r of e) if (r.metadata.queries) {
15738      const e2 = n.Qs(r.metadata.name);
15739      for (const n2 of r.metadata.queries) {
15740        const r2 = (t.get(n2) || __PRIVATE_documentKeySet()).add(e2);
15741        t.set(n2, r2);
15742      }
15743    }
15744    return t;
15745  }
15746  /**
15747   * Update the progress to 'Success' and return the updated progress.
15748   */
15749  async za(e) {
15750    const t = await __PRIVATE_localStoreApplyBundledDocuments(e, new __PRIVATE_BundleConverterImpl(this.serializer), this.Ka, this.$a.id), n = this.Ga(this.documents);
15751    for (const t2 of this.Ua) await __PRIVATE_localStoreSaveNamedQuery(e, t2, n.get(t2.name));
15752    return this.progress.taskState = "Success", {
15753      progress: this.progress,
15754      ja: this.collectionGroups,
15755      Ja: t
15756    };
15757  }
15758}
15759function __PRIVATE_bundleInitialProgress(e) {
15760  return {
15761    taskState: "Running",
15762    documentsLoaded: 0,
15763    bytesLoaded: 0,
15764    totalDocuments: e.totalDocuments,
15765    totalBytes: e.totalBytes
15766  };
15767}
15768/**
15769 * @license
15770 * Copyright 2017 Google LLC
15771 *
15772 * Licensed under the Apache License, Version 2.0 (the "License");
15773 * you may not use this file except in compliance with the License.
15774 * You may obtain a copy of the License at
15775 *
15776 *   http://www.apache.org/licenses/LICENSE-2.0
15777 *
15778 * Unless required by applicable law or agreed to in writing, software
15779 * distributed under the License is distributed on an "AS IS" BASIS,
15780 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15781 * See the License for the specific language governing permissions and
15782 * limitations under the License.
15783 */
15784class __PRIVATE_AddedLimboDocument {
15785  constructor(e) {
15786    this.key = e;
15787  }
15788}
15789class __PRIVATE_RemovedLimboDocument {
15790  constructor(e) {
15791    this.key = e;
15792  }
15793}
15794class __PRIVATE_View {
15795  constructor(e, t) {
15796    this.query = e, this.Ha = t, this.Ya = null, this.hasCachedResults = false, /**
15797    * A flag whether the view is current with the backend. A view is considered
15798    * current after it has seen the current flag from the backend and did not
15799    * lose consistency within the watch stream (e.g. because of an existence
15800    * filter mismatch).
15801    */
15802    this.current = false, /** Documents in the view but not in the remote target */
15803    this.Za = __PRIVATE_documentKeySet(), /** Document Keys that have local changes */
15804    this.mutatedKeys = __PRIVATE_documentKeySet(), this.Xa = __PRIVATE_newQueryComparator(e), this.eu = new DocumentSet(this.Xa);
15805  }
15806  /**
15807   * The set of remote documents that the server has told us belongs to the target associated with
15808   * this view.
15809   */
15810  get tu() {
15811    return this.Ha;
15812  }
15813  /**
15814   * Iterates over a set of doc changes, applies the query limit, and computes
15815   * what the new results should be, what the changes were, and whether we may
15816   * need to go back to the local cache for more results. Does not make any
15817   * changes to the view.
15818   * @param docChanges - The doc changes to apply to this view.
15819   * @param previousChanges - If this is being called with a refill, then start
15820   *        with this set of docs and changes instead of the current view.
15821   * @returns a new set of docs, changes, and refill flag.
15822   */
15823  nu(e, t) {
15824    const n = t ? t.ru : new __PRIVATE_DocumentChangeSet(), r = t ? t.eu : this.eu;
15825    let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, o = false;
15826    const _ = "F" === this.query.limitType && r.size === this.query.limit ? r.last() : null, a = "L" === this.query.limitType && r.size === this.query.limit ? r.first() : null;
15827    if (e.inorderTraversal((e2, t2) => {
15828      const u = r.get(e2), c = __PRIVATE_queryMatches(this.query, t2) ? t2 : null, l = !!u && this.mutatedKeys.has(u.key), h = !!c && (c.hasLocalMutations || // We only consider committed mutations for documents that were
15829      // mutated during the lifetime of the view.
15830      this.mutatedKeys.has(c.key) && c.hasCommittedMutations);
15831      let P = false;
15832      if (u && c) {
15833        u.data.isEqual(c.data) ? l !== h && (n.track({
15834          type: 3,
15835          doc: c
15836        }), P = true) : this.iu(u, c) || (n.track({
15837          type: 2,
15838          doc: c
15839        }), P = true, (_ && this.Xa(c, _) > 0 || a && this.Xa(c, a) < 0) && // This doc moved from inside the limit to outside the limit.
15840        // That means there may be some other doc in the local cache
15841        // that should be included instead.
15842        (o = true));
15843      } else !u && c ? (n.track({
15844        type: 0,
15845        doc: c
15846      }), P = true) : u && !c && (n.track({
15847        type: 1,
15848        doc: u
15849      }), P = true, (_ || a) && // A doc was removed from a full limit query. We'll need to
15850      // requery from the local cache to see if we know about some other
15851      // doc that should be in the results.
15852      (o = true));
15853      P && (c ? (s = s.add(c), i = h ? i.add(e2) : i.delete(e2)) : (s = s.delete(e2), i = i.delete(e2)));
15854    }), null !== this.query.limit) for (; s.size > this.query.limit; ) {
15855      const e2 = "F" === this.query.limitType ? s.last() : s.first();
15856      s = s.delete(e2.key), i = i.delete(e2.key), n.track({
15857        type: 1,
15858        doc: e2
15859      });
15860    }
15861    return {
15862      eu: s,
15863      ru: n,
15864      Ds: o,
15865      mutatedKeys: i
15866    };
15867  }
15868  iu(e, t) {
15869    return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations;
15870  }
15871  /**
15872   * Updates the view with the given ViewDocumentChanges and optionally updates
15873   * limbo docs and sync state from the provided target change.
15874   * @param docChanges - The set of changes to make to the view's docs.
15875   * @param limboResolutionEnabled - Whether to update limbo documents based on
15876   *        this change.
15877   * @param targetChange - A target change to apply for computing limbo docs and
15878   *        sync state.
15879   * @param targetIsPendingReset - Whether the target is pending to reset due to
15880   *        existence filter mismatch. If not explicitly specified, it is treated
15881   *        equivalently to `false`.
15882   * @returns A new ViewChange with the given docs, changes, and sync state.
15883   */
15884  // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
15885  applyChanges(e, t, n, r) {
15886    const i = this.eu;
15887    this.eu = e.eu, this.mutatedKeys = e.mutatedKeys;
15888    const s = e.ru.pa();
15889    s.sort((e2, t2) => function __PRIVATE_compareChangeType(e3, t3) {
15890      const order = (e4) => {
15891        switch (e4) {
15892          case 0:
15893            return 1;
15894          case 2:
15895          case 3:
15896            return 2;
15897          case 1:
15898            return 0;
15899          default:
15900            return fail(20277, {
15901              At: e4
15902            });
15903        }
15904      };
15905      return order(e3) - order(t3);
15906    }(e2.type, t2.type) || this.Xa(e2.doc, t2.doc)), this.su(n), r = null != r && r;
15907    const o = t && !r ? this.ou() : [], _ = 0 === this.Za.size && this.current && !r ? 1 : 0, a = _ !== this.Ya;
15908    if (this.Ya = _, 0 !== s.length || a) {
15909      return {
15910        snapshot: new ViewSnapshot(
15911          this.query,
15912          e.eu,
15913          i,
15914          s,
15915          e.mutatedKeys,
15916          0 === _,
15917          a,
15918          /* excludesMetadataChanges= */
15919          false,
15920          !!n && n.resumeToken.approximateByteSize() > 0
15921        ),
15922        _u: o
15923      };
15924    }
15925    return {
15926      _u: o
15927    };
15928  }
15929  /**
15930   * Applies an OnlineState change to the view, potentially generating a
15931   * ViewChange if the view's syncState changes as a result.
15932   */
15933  va(e) {
15934    return this.current && "Offline" === e ? (
15935      // If we're offline, set `current` to false and then call applyChanges()
15936      // to refresh our syncState and generate a ViewChange as appropriate. We
15937      // are guaranteed to get a new TargetChange that sets `current` back to
15938      // true once the client is back online.
15939      (this.current = false, this.applyChanges(
15940        {
15941          eu: this.eu,
15942          ru: new __PRIVATE_DocumentChangeSet(),
15943          mutatedKeys: this.mutatedKeys,
15944          Ds: false
15945        },
15946        /* limboResolutionEnabled= */
15947        false
15948      ))
15949    ) : {
15950      _u: []
15951    };
15952  }
15953  /**
15954   * Returns whether the doc for the given key should be in limbo.
15955   */
15956  au(e) {
15957    return !this.Ha.has(e) && // The local store doesn't think it's a result, so it shouldn't be in limbo.
15958    (!!this.eu.has(e) && !this.eu.get(e).hasLocalMutations);
15959  }
15960  /**
15961   * Updates syncedDocuments, current, and limbo docs based on the given change.
15962   * Returns the list of changes to which docs are in limbo.
15963   */
15964  su(e) {
15965    e && (e.addedDocuments.forEach((e2) => this.Ha = this.Ha.add(e2)), e.modifiedDocuments.forEach((e2) => {
15966    }), e.removedDocuments.forEach((e2) => this.Ha = this.Ha.delete(e2)), this.current = e.current);
15967  }
15968  ou() {
15969    if (!this.current) return [];
15970    const e = this.Za;
15971    this.Za = __PRIVATE_documentKeySet(), this.eu.forEach((e2) => {
15972      this.au(e2.key) && (this.Za = this.Za.add(e2.key));
15973    });
15974    const t = [];
15975    return e.forEach((e2) => {
15976      this.Za.has(e2) || t.push(new __PRIVATE_RemovedLimboDocument(e2));
15977    }), this.Za.forEach((n) => {
15978      e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n));
15979    }), t;
15980  }
15981  /**
15982   * Update the in-memory state of the current view with the state read from
15983   * persistence.
15984   *
15985   * We update the query view whenever a client's primary status changes:
15986   * - When a client transitions from primary to secondary, it can miss
15987   *   LocalStorage updates and its query views may temporarily not be
15988   *   synchronized with the state on disk.
15989   * - For secondary to primary transitions, the client needs to update the list
15990   *   of `syncedDocuments` since secondary clients update their query views
15991   *   based purely on synthesized RemoteEvents.
15992   *
15993   * @param queryResult.documents - The documents that match the query according
15994   * to the LocalStore.
15995   * @param queryResult.remoteKeys - The keys of the documents that match the
15996   * query according to the backend.
15997   *
15998   * @returns The ViewChange that resulted from this synchronization.
15999   */
16000  // PORTING NOTE: Multi-tab only.
16001  uu(e) {
16002    this.Ha = e.qs, this.Za = __PRIVATE_documentKeySet();
16003    const t = this.nu(e.documents);
16004    return this.applyChanges(
16005      t,
16006      /* limboResolutionEnabled= */
16007      true
16008    );
16009  }
16010  /**
16011   * Returns a view snapshot as if this query was just listened to. Contains
16012   * a document add for every existing document and the `fromCache` and
16013   * `hasPendingWrites` status of the already established view.
16014   */
16015  // PORTING NOTE: Multi-tab only.
16016  cu() {
16017    return ViewSnapshot.fromInitialDocuments(this.query, this.eu, this.mutatedKeys, 0 === this.Ya, this.hasCachedResults);
16018  }
16019}
16020const nn = "SyncEngine";
16021class __PRIVATE_QueryView {
16022  constructor(e, t, n) {
16023    this.query = e, this.targetId = t, this.view = n;
16024  }
16025}
16026class LimboResolution {
16027  constructor(e) {
16028    this.key = e, /**
16029    * Set to true once we've received a document. This is used in
16030    * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
16031    * decide whether it needs to manufacture a delete event for the target once
16032    * the target is CURRENT.
16033    */
16034    this.lu = false;
16035  }
16036}
16037class __PRIVATE_SyncEngineImpl {
16038  constructor(e, t, n, r, i, s) {
16039    this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.hu = {}, this.Pu = new ObjectMap((e2) => __PRIVATE_canonifyQuery(e2), __PRIVATE_queryEquals), this.Tu = /* @__PURE__ */ new Map(), /**
16040    * The keys of documents that are in limbo for which we haven't yet started a
16041    * limbo resolution query. The strings in this set are the result of calling
16042    * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
16043    *
16044    * The `Set` type was chosen because it provides efficient lookup and removal
16045    * of arbitrary elements and it also maintains insertion order, providing the
16046    * desired queue-like FIFO semantics.
16047    */
16048    this.Iu = /* @__PURE__ */ new Set(), /**
16049    * Keeps track of the target ID for each document that is in limbo with an
16050    * active target.
16051    */
16052    this.du = new SortedMap(DocumentKey.comparator), /**
16053    * Keeps track of the information about an active limbo resolution for each
16054    * active target ID that was started for the purpose of limbo resolution.
16055    */
16056    this.Eu = /* @__PURE__ */ new Map(), this.Au = new __PRIVATE_ReferenceSet(), /** Stores user completion handlers, indexed by User and BatchId. */
16057    this.Ru = {}, /** Stores user callbacks waiting for all pending writes to be acknowledged. */
16058    this.Vu = /* @__PURE__ */ new Map(), this.mu = __PRIVATE_TargetIdGenerator.ur(), this.onlineState = "Unknown", // The primary state is set to `true` or `false` immediately after Firestore
16059    // startup. In the interim, a client should only be considered primary if
16060    // `isPrimary` is true.
16061    this.fu = void 0;
16062  }
16063  get isPrimaryClient() {
16064    return true === this.fu;
16065  }
16066}
16067async function __PRIVATE_syncEngineListen(e, t, n = true) {
16068  const r = __PRIVATE_ensureWatchCallbacks(e);
16069  let i;
16070  const s = r.Pu.get(t);
16071  return s ? (
16072    // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
16073    // already exists when EventManager calls us for the first time. This
16074    // happens when the primary tab is already listening to this query on
16075    // behalf of another tab and the user of the primary also starts listening
16076    // to the query. EventManager will not have an assigned target ID in this
16077    // case and calls `listen` to obtain this ID.
16078    (r.sharedClientState.addLocalQueryTarget(s.targetId), i = s.view.cu())
16079  ) : i = await __PRIVATE_allocateTargetAndMaybeListen(
16080    r,
16081    t,
16082    n,
16083    /** shouldInitializeView= */
16084    true
16085  ), i;
16086}
16087async function __PRIVATE_triggerRemoteStoreListen(e, t) {
16088  const n = __PRIVATE_ensureWatchCallbacks(e);
16089  await __PRIVATE_allocateTargetAndMaybeListen(
16090    n,
16091    t,
16092    /** shouldListenToRemote= */
16093    true,
16094    /** shouldInitializeView= */
16095    false
16096  );
16097}
16098async function __PRIVATE_allocateTargetAndMaybeListen(e, t, n, r) {
16099  const i = await __PRIVATE_localStoreAllocateTarget(e.localStore, __PRIVATE_queryToTarget(t)), s = i.targetId, o = e.sharedClientState.addLocalQueryTarget(s, n);
16100  let _;
16101  return r && (_ = await __PRIVATE_initializeViewAndComputeSnapshot(e, t, s, "current" === o, i.resumeToken)), e.isPrimaryClient && n && __PRIVATE_remoteStoreListen(e.remoteStore, i), _;
16102}
16103async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) {
16104  e.gu = (t2, n2, r2) => async function __PRIVATE_applyDocChanges(e2, t3, n3, r3) {
16105    let i2 = t3.view.nu(n3);
16106    i2.Ds && // The query has a limit and some docs were removed, so we need
16107    // to re-run the query against the local store to make sure we
16108    // didn't lose any good docs that had been past the limit.
16109    (i2 = await __PRIVATE_localStoreExecuteQuery(
16110      e2.localStore,
16111      t3.query,
16112      /* usePreviousResults= */
16113      false
16114    ).then(({ documents: e3 }) => t3.view.nu(e3, i2)));
16115    const s2 = r3 && r3.targetChanges.get(t3.targetId), o2 = r3 && null != r3.targetMismatches.get(t3.targetId), _2 = t3.view.applyChanges(
16116      i2,
16117      /* limboResolutionEnabled= */
16118      e2.isPrimaryClient,
16119      s2,
16120      o2
16121    );
16122    return __PRIVATE_updateTrackedLimbos(e2, t3.targetId, _2._u), _2.snapshot;
16123  }(e, t2, n2, r2);
16124  const s = await __PRIVATE_localStoreExecuteQuery(
16125    e.localStore,
16126    t,
16127    /* usePreviousResults= */
16128    true
16129  ), o = new __PRIVATE_View(t, s.qs), _ = o.nu(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && "Offline" !== e.onlineState, i), u = o.applyChanges(
16130    _,
16131    /* limboResolutionEnabled= */
16132    e.isPrimaryClient,
16133    a
16134  );
16135  __PRIVATE_updateTrackedLimbos(e, n, u._u);
16136  const c = new __PRIVATE_QueryView(t, n, o);
16137  return e.Pu.set(t, c), e.Tu.has(n) ? e.Tu.get(n).push(t) : e.Tu.set(n, [t]), u.snapshot;
16138}
16139async function __PRIVATE_syncEngineUnlisten(e, t, n) {
16140  const r = __PRIVATE_debugCast(e), i = r.Pu.get(t), s = r.Tu.get(i.targetId);
16141  if (s.length > 1) return r.Tu.set(i.targetId, s.filter((e2) => !__PRIVATE_queryEquals(e2, t))), void r.Pu.delete(t);
16142  if (r.isPrimaryClient) {
16143    r.sharedClientState.removeLocalQueryTarget(i.targetId);
16144    r.sharedClientState.isActiveQueryTarget(i.targetId) || await __PRIVATE_localStoreReleaseTarget(
16145      r.localStore,
16146      i.targetId,
16147      /*keepPersistedTargetData=*/
16148      false
16149    ).then(() => {
16150      r.sharedClientState.clearQueryState(i.targetId), n && __PRIVATE_remoteStoreUnlisten(r.remoteStore, i.targetId), __PRIVATE_removeAndCleanupTarget(r, i.targetId);
16151    }).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
16152  } else __PRIVATE_removeAndCleanupTarget(r, i.targetId), await __PRIVATE_localStoreReleaseTarget(
16153    r.localStore,
16154    i.targetId,
16155    /*keepPersistedTargetData=*/
16156    true
16157  );
16158}
16159async function __PRIVATE_triggerRemoteStoreUnlisten(e, t) {
16160  const n = __PRIVATE_debugCast(e), r = n.Pu.get(t), i = n.Tu.get(r.targetId);
16161  n.isPrimaryClient && 1 === i.length && // PORTING NOTE: Unregister the target ID with local Firestore client as
16162  // watch target.
16163  (n.sharedClientState.removeLocalQueryTarget(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId));
16164}
16165async function __PRIVATE_syncEngineWrite(e, t, n) {
16166  const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e);
16167  try {
16168    const e2 = await function __PRIVATE_localStoreWriteLocally(e3, t2) {
16169      const n2 = __PRIVATE_debugCast(e3), r2 = Timestamp.now(), i = t2.reduce((e4, t3) => e4.add(t3.key), __PRIVATE_documentKeySet());
16170      let s, o;
16171      return n2.persistence.runTransaction("Locally write mutations", "readwrite", (e4) => {
16172        let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();
16173        return n2.Os.getEntries(e4, i).next((e5) => {
16174          _ = e5, _.forEach((e6, t3) => {
16175            t3.isValidDocument() || (a = a.add(e6));
16176          });
16177        }).next(() => n2.localDocuments.getOverlayedDocuments(e4, _)).next((i2) => {
16178          s = i2;
16179          const o2 = [];
16180          for (const e5 of t2) {
16181            const t3 = __PRIVATE_mutationExtractBaseValue(e5, s.get(e5.key).overlayedDocument);
16182            null != t3 && // NOTE: The base state should only be applied if there's some
16183            // existing document to override, so use a Precondition of
16184            // exists=true
16185            o2.push(new __PRIVATE_PatchMutation(e5.key, t3, __PRIVATE_extractFieldMask(t3.value.mapValue), Precondition.exists(true)));
16186          }
16187          return n2.mutationQueue.addMutationBatch(e4, r2, o2, t2);
16188        }).next((t3) => {
16189          o = t3;
16190          const r3 = t3.applyToLocalDocumentSet(s, a);
16191          return n2.documentOverlayCache.saveOverlays(e4, t3.batchId, r3);
16192        });
16193      }).then(() => ({
16194        batchId: o.batchId,
16195        changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s)
16196      }));
16197    }(r.localStore, t);
16198    r.sharedClientState.addPendingMutation(e2.batchId), function __PRIVATE_addMutationCallback(e3, t2, n2) {
16199      let r2 = e3.Ru[e3.currentUser.toKey()];
16200      r2 || (r2 = new SortedMap(__PRIVATE_primitiveComparator));
16201      r2 = r2.insert(t2, n2), e3.Ru[e3.currentUser.toKey()] = r2;
16202    }(r, e2.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e2.changes), await __PRIVATE_fillWritePipeline(r.remoteStore);
16203  } catch (e2) {
16204    const t2 = __PRIVATE_wrapInUserErrorIfRecoverable(e2, "Failed to persist write");
16205    n.reject(t2);
16206  }
16207}
16208async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) {
16209  const n = __PRIVATE_debugCast(e);
16210  try {
16211    const e2 = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t);
16212    t.targetChanges.forEach((e3, t2) => {
16213      const r = n.Eu.get(t2);
16214      r && // Since this is a limbo resolution lookup, it's for a single document
16215      // and it could be added, modified, or removed, but not a combination.
16216      (__PRIVATE_hardAssert(e3.addedDocuments.size + e3.modifiedDocuments.size + e3.removedDocuments.size <= 1, 22616), e3.addedDocuments.size > 0 ? r.lu = true : e3.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.lu, 14607) : e3.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.lu, 42227), r.lu = false));
16217    }), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e2, t);
16218  } catch (e2) {
16219    await __PRIVATE_ignoreIfPrimaryLeaseLoss(e2);
16220  }
16221}
16222function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) {
16223  const r = __PRIVATE_debugCast(e);
16224  if (r.isPrimaryClient && 0 === n || !r.isPrimaryClient && 1 === n) {
16225    const e2 = [];
16226    r.Pu.forEach((n2, r2) => {
16227      const i = r2.view.va(t);
16228      i.snapshot && e2.push(i.snapshot);
16229    }), function __PRIVATE_eventManagerOnOnlineStateChange(e3, t2) {
16230      const n2 = __PRIVATE_debugCast(e3);
16231      n2.onlineState = t2;
16232      let r2 = false;
16233      n2.queries.forEach((e4, n3) => {
16234        for (const e5 of n3.wa)
16235          e5.va(t2) && (r2 = true);
16236      }), r2 && __PRIVATE_raiseSnapshotsInSyncEvent(n2);
16237    }(r.eventManager, t), e2.length && r.hu.J_(e2), r.onlineState = t, r.isPrimaryClient && r.sharedCl
16237ientState.setOnlineState(t);
16238  }
16239}
16240async function __PRIVATE_syncEngineRejectListen(e, t, n) {
16241  const r = __PRIVATE_debugCast(e);
16242  r.sharedClientState.updateQueryState(t, "rejected", n);
16243  const i = r.Eu.get(t), s = i && i.key;
16244  if (s) {
16245    let e2 = new SortedMap(DocumentKey.comparator);
16246    e2 = e2.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min()));
16247    const n2 = __PRIVATE_documentKeySet().add(s), i2 = new RemoteEvent(
16248      SnapshotVersion.min(),
16249      /* targetChanges= */
16250      /* @__PURE__ */ new Map(),
16251      /* targetMismatches= */
16252      new SortedMap(__PRIVATE_primitiveComparator),
16253      e2,
16254      n2
16255    );
16256    await __PRIVATE_syncEngineApplyRemoteEvent(r, i2), // Since this query failed, we won't want to manually unlisten to it.
16257    // We only remove it from bookkeeping after we successfully applied the
16258    // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
16259    // this query when the RemoteStore restarts the Watch stream, which should
16260    // re-trigger the target failure.
16261    r.du = r.du.remove(s), r.Eu.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r);
16262  } else await __PRIVATE_localStoreReleaseTarget(
16263    r.localStore,
16264    t,
16265    /* keepPersistedTargetData */
16266    false
16267  ).then(() => __PRIVATE_removeAndCleanupTarget(r, t, n)).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
16268}
16269async function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) {
16270  const n = __PRIVATE_debugCast(e), r = t.batch.batchId;
16271  try {
16272    const e2 = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t);
16273    __PRIVATE_processUserCallback(
16274      n,
16275      r,
16276      /*error=*/
16277      null
16278    ), __PRIVATE_triggerPendingWritesCallbacks(n, r), n.sharedClientState.updateMutationState(r, "acknowledged"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e2);
16279  } catch (e2) {
16280    await __PRIVATE_ignoreIfPrimaryLeaseLoss(e2);
16281  }
16282}
16283async function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) {
16284  const r = __PRIVATE_debugCast(e);
16285  try {
16286    const e2 = await function __PRIVATE_localStoreRejectBatch(e3, t2) {
16287      const n2 = __PRIVATE_debugCast(e3);
16288      return n2.persistence.runTransaction("Reject batch", "readwrite-primary", (e4) => {
16289        let r2;
16290        return n2.mutationQueue.lookupMutationBatch(e4, t2).next((t3) => (__PRIVATE_hardAssert(null !== t3, 37113), r2 = t3.keys(), n2.mutationQueue.removeMutationBatch(e4, t3))).next(() => n2.mutationQueue.performConsistencyCheck(e4)).next(() => n2.documentOverlayCache.removeOverlaysForBatchId(e4, r2, t2)).next(() => n2.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e4, r2)).next(() => n2.localDocuments.getDocuments(e4, r2));
16291      });
16292    }(r.localStore, t);
16293    __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), r.sharedCl
16293ientState.updateMutationState(t, "rejected", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e2);
16294  } catch (n2) {
16295    await __PRIVATE_ignoreIfPrimaryLeaseLoss(n2);
16296  }
16297}
16298async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) {
16299  const n = __PRIVATE_debugCast(e);
16300  __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(nn, "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
16301  try {
16302    const e2 = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e3) {
16303      const t2 = __PRIVATE_debugCast(e3);
16304      return t2.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (e4) => t2.mutationQueue.getHighestUnacknowledgedBatchId(e4));
16305    }(n.localStore);
16306    if (e2 === G)
16307      return void t.resolve();
16308    const r = n.Vu.get(e2) || [];
16309    r.push(t), n.Vu.set(e2, r);
16310  } catch (e2) {
16311    const n2 = __PRIVATE_wrapInUserErrorIfRecoverable(e2, "Initialization of waitForPendingWrites() operation failed");
16312    t.reject(n2);
16313  }
16314}
16315function __PRIVATE_triggerPendingWritesCallbacks(e, t) {
16316  (e.Vu.get(t) || []).forEach((e2) => {
16317    e2.resolve();
16318  }), e.Vu.delete(t);
16319}
16320function __PRIVATE_processUserCallback(e, t, n) {
16321  const r = __PRIVATE_debugCast(e);
16322  let i = r.Ru[r.currentUser.toKey()];
16323  if (i) {
16324    const e2 = i.get(t);
16325    e2 && (n ? e2.reject(n) : e2.resolve(), i = i.remove(t)), r.Ru[r.currentUser.toKey()] = i;
16326  }
16327}
16328function __PRIVATE_removeAndCleanupTarget(e, t, n = null) {
16329  e.sharedClientState.removeLocalQueryTarget(t);
16330  for (const r of e.Tu.get(t)) e.Pu.delete(r), n && e.hu.pu(r, n);
16331  if (e.Tu.delete(t), e.isPrimaryClient) {
16332    e.Au.zr(t).forEach((t2) => {
16333      e.Au.containsKey(t2) || // We removed the last reference for this key
16334      __PRIVATE_removeLimboTarget(e, t2);
16335    });
16336  }
16337}
16338function __PRIVATE_removeLimboTarget(e, t) {
16339  e.Iu.delete(t.path.canonicalString());
16340  const n = e.du.get(t);
16341  null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.du = e.du.remove(t), e.Eu.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e));
16342}
16343function __PRIVATE_updateTrackedLimbos(e, t, n) {
16344  for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.Au.addReference(r.key, t), __PRIVATE_trackLimboChange(e, r);
16345  else if (r instanceof __PRIVATE_RemovedLimboDocument) {
16346    __PRIVATE_logDebug(nn, "Document no longer in limbo: " + r.key), e.Au.removeReference(r.key, t);
16347    e.Au.containsKey(r.key) || // We removed the last reference for this key
16348    __PRIVATE_removeLimboTarget(e, r.key);
16349  } else fail(19791, {
16350    yu: r
16351  });
16352}
16353function __PRIVATE_trackLimboChange(e, t) {
16354  const n = t.key, r = n.path.canonicalString();
16355  e.du.get(n) || e.Iu.has(r) || (__PRIVATE_logDebug(nn, "New document in limbo: " + n), e.Iu.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e));
16356}
16357function __PRIVATE_pumpEnqueuedLimboResolutions(e) {
16358  for (; e.Iu.size > 0 && e.du.size < e.maxConcurrentLimboResolutions; ) {
16359    const t = e.Iu.values().next().value;
16360    e.Iu.delete(t);
16361    const n = new DocumentKey(ResourcePath.fromString(t)), r = e.mu.next();
16362    e.Eu.set(r, new LimboResolution(n)), e.du = e.du.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, "TargetPurposeLimboResolution", __PRIVATE_ListenSequence.ue));
16363  }
16364}
16365async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) {
16366  const r = __PRIVATE_debugCast(e), i = [], s = [], o = [];
16367  r.Pu.isEmpty() || (r.Pu.forEach((e2, _) => {
16368    o.push(r.gu(_, t, n).then((e3) => {
16369      var t2;
16370      if ((e3 || n) && r.isPrimaryClient) {
16371        const i2 = e3 ? !e3.fromCache : null === (t2 = null == n ? void 0 : n.targetChanges.get(_.targetId)) || void 0 === t2 ? void 0 : t2.current;
16372        r.sharedClientState.updateQueryState(_.targetId, i2 ? "current" : "not-current");
16373      }
16374      if (e3) {
16375        i.push(e3);
16376        const t3 = __PRIVATE_LocalViewChanges.Es(_.targetId, e3);
16377        s.push(t3);
16378      }
16379    }));
16380  }), await Promise.all(o), r.hu.J_(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e2, t2) {
16381    const n2 = __PRIVATE_debugCast(e2);
16382    try {
16383      await n2.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (e3) => PersistencePromise.forEach(t2, (t3) => PersistencePromise.forEach(t3.Is, (r2) => n2.persistence.referenceDelegate.addReference(e3, t3.targetId, r2)).next(() => PersistencePromise.forEach(t3.ds, (r2) => n2.persistence.referenceDelegate.removeReference(e3, t3.targetId, r2)))));
16384    } catch (e3) {
16385      if (!__PRIVATE_isIndexedDbTransactionError(e3)) throw e3;
16386      __PRIVATE_logDebug(Qt, "Failed to update sequence numbers: " + e3);
16387    }
16388    for (const e3 of t2) {
16389      const t3 = e3.targetId;
16390      if (!e3.fromCache) {
16391        const e4 = n2.Fs.get(t3), r2 = e4.snapshotVersion, i2 = e4.withLastLimboFreeSnapshotVersion(r2);
16392        n2.Fs = n2.Fs.insert(t3, i2);
16393      }
16394    }
16395  }(r.localStore, s));
16396}
16397async function __PRIVATE_syncEngineHandleCredentialChange(e, t) {
16398  const n = __PRIVATE_debugCast(e);
16399  if (!n.currentUser.isEqual(t)) {
16400    __PRIVATE_logDebug(nn, "User change. New user:", t.toKey());
16401    const e2 = await __PRIVATE_localStoreHandleUserChange(n.localStore, t);
16402    n.currentUser = t, // Fails tasks waiting for pending writes requested by previous user.
16403    function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e3, t2) {
16404      e3.Vu.forEach((e4) => {
16405        e4.forEach((e5) => {
16406          e5.reject(new FirestoreError(N.CANCELLED, t2));
16407        });
16408      }), e3.Vu.clear();
16409    }(n, "'waitForPendingWrites' promise is rejected due to a user change."), // TODO(b/114226417): Consider calling this only in the primary tab.
16410    n.sharedClientState.handleUserChange(t, e2.removedBatchIds, e2.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e2.Bs);
16411  }
16412}
16413function __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) {
16414  const n = __PRIVATE_debugCast(e), r = n.Eu.get(t);
16415  if (r && r.lu) return __PRIVATE_documentKeySet().add(r.key);
16416  {
16417    let e2 = __PRIVATE_documentKeySet();
16418    const r2 = n.Tu.get(t);
16419    if (!r2) return e2;
16420    for (const t2 of r2) {
16421      const r3 = n.Pu.get(t2);
16422      e2 = e2.unionWith(r3.view.tu);
16423    }
16424    return e2;
16425  }
16426}
16427async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) {
16428  const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(
16429    n.localStore,
16430    t.query,
16431    /* usePreviousResults= */
16432    true
16433  ), i = t.view.uu(r);
16434  return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i._u), i;
16435}
16436async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) {
16437  const n = __PRIVATE_debugCast(e);
16438  return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e2) => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e2));
16439}
16440async function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) {
16441  const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e2, t2) {
16442    const n2 = __PRIVATE_debugCast(e2), r2 = __PRIVATE_debugCast(n2.mutationQueue);
16443    return n2.persistence.runTransaction("Lookup mutation documents", "readonly", (e3) => r2.Xn(e3, t2).next((t3) => t3 ? n2.localDocuments.getDocuments(e3, t3) : PersistencePromise.resolve(null)));
16444  }(i.localStore, t);
16445  null !== s ? ("pending" === n ? (
16446    // If we are the primary client, we need to send this write to the
16447    // backend. Secondary clients will ignore these writes since their remote
16448    // connection is disabled.
16449    await __PRIVATE_fillWritePipeline(i.remoteStore)
16450  ) : "acknowledged" === n || "rejected" === n ? (
16451    // NOTE: Both these methods are no-ops for batches that originated from
16452    // other clients.
16453    (__PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e2, t2) {
16454      __PRIVATE_debugCast(__PRIVATE_debugCast(e2).mutationQueue).rr(t2);
16455    }(i.localStore, t))
16456  ) : fail(6720, "Unknown batchState", {
16457    wu: n
16458  }), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : (
16459    // A throttled tab may not have seen the mutation before it was completed
16460    // and removed from the mutation queue, in which case we won't have cached
16461    // the affected documents. In this case we can safely ignore the update
16462    // since that means we didn't apply the mutation locally at all (if we
16463    // had, we would have cached the affected documents), and so we will just
16464    // see any resulting document changes via normal remote document updates
16465    // as applicable.
16466    __PRIVATE_logDebug(nn, "Cannot apply mutation batch with id: " + t)
16467  );
16468}
16469async function __PRIVATE_syncEngineApplyPrimaryState(e, t) {
16470  const n = __PRIVATE_debugCast(e);
16471  if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), true === t && true !== n.fu) {
16472    const e2 = n.sharedClientState.getAllActiveQueryTargets(), t2 = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e2.toArray());
16473    n.fu = true, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, true);
16474    for (const e3 of t2) __PRIVATE_remoteStoreListen(n.remoteStore, e3);
16475  } else if (false === t && false !== n.fu) {
16476    const e2 = [];
16477    let t2 = Promise.resolve();
16478    n.Tu.forEach((r, i) => {
16479      n.sharedClientState.isLocalQueryTarget(i) ? e2.push(i) : t2 = t2.then(() => (__PRIVATE_removeAndCleanupTarget(n, i), __PRIVATE_localStoreReleaseTarget(
16480        n.localStore,
16481        i,
16482        /*keepPersistedTargetData=*/
16483        true
16484      ))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i);
16485    }), await t2, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e2), // PORTING NOTE: Multi-Tab only.
16486    function __PRIVATE_resetLimboDocuments(e3) {
16487      const t3 = __PRIVATE_debugCast(e3);
16488      t3.Eu.forEach((e4, n2) => {
16489        __PRIVATE_remoteStoreUnlisten(t3.remoteStore, n2);
16490      }), t3.Au.jr(), t3.Eu = /* @__PURE__ */ new Map(), t3.du = new SortedMap(DocumentKey.comparator);
16491    }(n), n.fu = false, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, false);
16492  }
16493}
16494async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) {
16495  const r = __PRIVATE_debugCast(e), i = [], s = [];
16496  for (const e2 of t) {
16497    let t2;
16498    const n2 = r.Tu.get(e2);
16499    if (n2 && 0 !== n2.length) {
16500      t2 = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_queryToTarget(n2[0]));
16501      for (const e3 of n2) {
16502        const t3 = r.Pu.get(e3), n3 = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t3);
16503        n3.snapshot && s.push(n3.snapshot);
16504      }
16505    } else {
16506      const n3 = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e2);
16507      t2 = await __PRIVATE_localStoreAllocateTarget(r.localStore, n3), await __PRIVATE_initializeViewAndComputeSnapshot(
16508        r,
16509        __PRIVATE_synthesizeTargetToQuery(n3),
16510        e2,
16511        /*current=*/
16512        false,
16513        t2.resumeToken
16514      );
16515    }
16516    i.push(t2);
16517  }
16518  return r.hu.J_(s), i;
16519}
16520function __PRIVATE_synthesizeTargetToQuery(e) {
16521  return __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, "F", e.startAt, e.endAt);
16522}
16523function __PRIVATE_syncEngineGetActiveClients(e) {
16524  return function __PRIVATE_localStoreGetActiveClients(e2) {
16525    return __PRIVATE_debugCast(__PRIVATE_debugCast(e2).persistence).Ps();
16526  }(__PRIVATE_debugCast(e).localStore);
16527}
16528async function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) {
16529  const i = __PRIVATE_debugCast(e);
16530  if (i.fu)
16531    return void __PRIVATE_logDebug(nn, "Ignoring unexpected query state notification.");
16532  const s = i.Tu.get(t);
16533  if (s && s.length > 0) switch (n) {
16534    case "current":
16535    case "not-current": {
16536      const e2 = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, __PRIVATE_queryCollectionGroup(s[0])), r2 = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, "current" === n, ByteString.EMPTY_BYTE_STRING);
16537      await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e2, r2);
16538      break;
16539    }
16540    case "rejected":
16541      await __PRIVATE_localStoreReleaseTarget(
16542        i.localStore,
16543        t,
16544        /* keepPersistedTargetData */
16545        true
16546      ), __PRIVATE_removeAndCleanupTarget(i, t, r);
16547      break;
16548    default:
16549      fail(64155, n);
16550  }
16551}
16552async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) {
16553  const r = __PRIVATE_ensureWatchCallbacks(e);
16554  if (r.fu) {
16555    for (const e2 of t) {
16556      if (r.Tu.has(e2) && r.sharedClientState.isActiveQueryTarget(e2)) {
16557        __PRIVATE_logDebug(nn, "Adding an already active target " + e2);
16558        continue;
16559      }
16560      const t2 = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e2), n2 = await __PRIVATE_localStoreAllocateTarget(r.localStore, t2);
16561      await __PRIVATE_initializeViewAndComputeSnapshot(
16562        r,
16563        __PRIVATE_synthesizeTargetToQuery(t2),
16564        n2.targetId,
16565        /*current=*/
16566        false,
16567        n2.resumeToken
16568      ), __PRIVATE_remoteStoreListen(r.remoteStore, n2);
16569    }
16570    for (const e2 of n)
16571      r.Tu.has(e2) && // Release queries that are still active.
16572      await __PRIVATE_localStoreReleaseTarget(
16573        r.localStore,
16574        e2,
16575        /* keepPersistedTargetData */
16576        false
16577      ).then(() => {
16578        __PRIVATE_remoteStoreUnlisten(r.remoteStore, e2), __PRIVATE_removeAndCleanupTarget(r, e2);
16579      }).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
16580  }
16581}
16582function __PRIVATE_ensureWatchCallbacks(e) {
16583  const t = __PRIVATE_debugCast(e);
16584  return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), t.hu.J_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.hu.pu = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), t;
16585}
16586function __PRIVATE_syncEngineEnsureWriteCallbacks(e) {
16587  const t = __PRIVATE_debugCast(e);
16588  return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), t;
16589}
16590function __PRIVATE_syncEngineLoadBundle(e, t, n) {
16591  const r = __PRIVATE_debugCast(e);
16592  (async function __PRIVATE_loadBundleImpl(e2, t2, n2) {
16593    try {
16594      const r2 = await t2.getMetadata();
16595      if (await function __PRIVATE_localStoreHasNewerBundle(e3, t3) {
16596        const n3 = __PRIVATE_debugCast(e3), r3 = __PRIVATE_fromVersion(t3.createTime);
16597        return n3.persistence.runTransaction("hasNewerBundle", "readonly", (e4) => n3.Ti.getBundleMetadata(e4, t3.id)).then((e4) => !!e4 && e4.createTime.compareTo(r3) >= 0);
16598      }(e2.localStore, r2)) return await t2.close(), n2._completeWith(function __PRIVATE_bundleSuccessProgress(e3) {
16599        return {
16600          taskState: "Success",
16601          documentsLoaded: e3.totalDocuments,
16602          bytesLoaded: e3.totalBytes,
16603          totalDocuments: e3.totalDocuments,
16604          totalBytes: e3.totalBytes
16605        };
16606      }(r2)), Promise.resolve(/* @__PURE__ */ new Set());
16607      n2._updateProgress(__PRIVATE_bundleInitialProgress(r2));
16608      const i = new __PRIVATE_BundleLoader(r2, t2.serializer);
16609      let s = await t2.Su();
16610      for (; s; ) {
16611        const e3 = await i.Wa(s);
16612        e3 && n2._updateProgress(e3), s = await t2.Su();
16613      }
16614      const o = await i.za(e2.localStore);
16615      return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(
16616        e2,
16617        o.Ja,
16618        /* remoteEvent */
16619        void 0
16620      ), // Save metadata, so loading the same bundle will skip.
16621      await function __PRIVATE_localStoreSaveBundle(e3, t3) {
16622        const n3 = __PRIVATE_debugCast(e3);
16623        return n3.persistence.runTransaction("Save bundle", "readwrite", (e4) => n3.Ti.saveBundleMetadata(e4, t3));
16624      }(e2.localStore, r2), n2._completeWith(o.progress), Promise.resolve(o.ja);
16625    } catch (e3) {
16626      return __PRIVATE_logWarn(nn, `Loading bundle failed with ${e3}`), n2._failWith(e3), Promise.resolve(/* @__PURE__ */ new Set());
16627    }
16628  })(r, t, n).then((e2) => {
16629    r.sharedClientState.notifyBundleLoaded(e2);
16630  });
16631}
16632class __PRIVATE_MemoryOfflineComponentProvider {
16633  constructor() {
16634    this.kind = "memory", this.synchronizeTabs = false;
16635  }
16636  async initialize(e) {
16637    this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.bu(e), this.persistence = this.Du(e), await this.persistence.start(), this.localStore = this.vu(e), this.gcScheduler = this.Cu(e, this.localStore), this.indexBackfillerScheduler = this.Fu(e, this.localStore);
16638  }
16639  Cu(e, t) {
16640    return null;
16641  }
16642  Fu(e, t) {
16643    return null;
16644  }
16645  vu(e) {
16646    return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine(), e.initialUser, this.serializer);
16647  }
16648  Du(e) {
16649    return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Vi, this.serializer);
16650  }
16651  bu(e) {
16652    return new __PRIVATE_MemorySharedClientState();
16653  }
16654  async terminate() {
16655    var e, t;
16656    null === (e = this.gcScheduler) || void 0 === e || e.stop(), null === (t = this.indexBackfillerScheduler) || void 0 === t || t.stop(), this.sharedClientState.shutdown(), await this.persistence.shutdown();
16657  }
16658}
16659__PRIVATE_MemoryOfflineComponentProvider.provider = {
16660  build: () => new __PRIVATE_MemoryOfflineComponentProvider()
16661};
16662class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {
16663  constructor(e) {
16664    super(), this.cacheSizeBytes = e;
16665  }
16666  Cu(e, t) {
16667    __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate, 46915);
16668    const n = this.persistence.referenceDelegate.garbageCollector;
16669    return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);
16670  }
16671  Du(e) {
16672    const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;
16673    return new __PRIVATE_MemoryPersistence((e2) => __PRIVATE_MemoryLruDelegate.Vi(e2, t), this.serializer);
16674  }
16675}
16676class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {
16677  constructor(e, t, n) {
16678    super(), this.Mu = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.kind = "persistent", this.synchronizeTabs = false;
16679  }
16680  async initialize(e) {
16681    await super.initialize(e), await this.Mu.initialize(this, e), // Enqueue writes from a previous session
16682    await __PRIVATE_syncEngineEnsureWriteCallbacks(this.Mu.syncEngine), await __PRIVATE_fillWritePipeline(this.Mu.remoteStore), // NOTE: This will immediately call the listener, so we make sure to
16683    // set it after localStore / remoteStore are started.
16684    await this.persistence.ji(() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), Promise.resolve()));
16685  }
16686  vu(e) {
16687    return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine(), e.initialUser, this.serializer);
16688  }
16689  Cu(e, t) {
16690    const n = this.persistence.referenceDelegate.garbageCollector;
16691    return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);
16692  }
16693  Fu(e, t) {
16694    const n = new __PRIVATE_IndexBackfiller(t, this.persistence);
16695    return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n);
16696  }
16697  Du(e) {
16698    const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;
16699    return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership);
16700  }
16701  bu(e) {
16702    return new __PRIVATE_MemorySharedClientState();
16703  }
16704}
16705class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider {
16706  constructor(e, t) {
16707    super(
16708      e,
16709      t,
16710      /* forceOwnership= */
16711      false
16712    ), this.Mu = e, this.cacheSizeBytes = t, this.synchronizeTabs = true;
16713  }
16714  async initialize(e) {
16715    await super.initialize(e);
16716    const t = this.Mu.syncEngine;
16717    this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = {
16718      Do: __PRIVATE_syncEngineApplyBatchState.bind(null, t),
16719      vo: __PRIVATE_syncEngineApplyTargetState.bind(null, t),
16720      Co: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t),
16721      Ps: __PRIVATE_syncEngineGetActiveClients.bind(null, t),
16722      bo: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t)
16723    }, await this.sharedClientState.start()), // NOTE: This will immediately call the listener, so we make sure to
16724    // set it after localStore / remoteStore are started.
16725    await this.persistence.ji(async (e2) => {
16726      await __PRIVATE_syncEngineApplyPrimaryState(this.Mu.syncEngine, e2), this.gcScheduler && (e2 && !this.gcScheduler.started ? this.gcScheduler.start() : e2 || this.gcScheduler.stop()), this.indexBackfillerScheduler && (e2 && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e2 || this.indexBackfillerScheduler.stop());
16727    });
16728  }
16729  bu(e) {
16730    const t = __PRIVATE_getWindow();
16731    if (!__PRIVATE_WebStorageSharedClientState.C(t)) throw new FirestoreError(N.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
16732    const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey);
16733    return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser);
16734  }
16735}
16736class OnlineComponentProvider {
16737  async initialize(e, t) {
16738    this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(
16739      t,
16740      /* startAsPrimary=*/
16741      !e.synchronizeTabs
16742    ), this.sharedClientState.onlineStateHandler = (e2) => __PRIVATE_syncEngineApplyOnlineStateChange(
16743      this.syncEngine,
16744      e2,
16745      1
16746      /* OnlineStateSource.SharedClientState */
16747    ), this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient));
16748  }
16749  createEventManager(e) {
16750    return function __PRIVATE_newEventManager() {
16751      return new __PRIVATE_EventManagerImpl();
16752    }();
16753  }
16754  createDatastore(e) {
16755    const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = function __PRIVATE_newConnection(e2) {
16756      return new __PRIVATE_WebChannelConnection(e2);
16757    }(e.databaseInfo);
16758    return function __PRIVATE_newDatastore(e2, t2, n2, r) {
16759      return new __PRIVATE_DatastoreImpl(e2, t2, n2, r);
16760    }(e.authCredentials, e.appCheckCredentials, n, t);
16761  }
16762  createRemoteStore(e) {
16763    return function __PRIVATE_newRemoteStore(e2, t, n, r, i) {
16764      return new __PRIVATE_RemoteStoreImpl(e2, t, n, r, i);
16765    }(this.localStore, this.datastore, e.asyncQueue, (e2) => __PRIVATE_syncEngineApplyOnlineStateChange(
16766      this.syncEngine,
16767      e2,
16768      0
16769      /* OnlineStateSource.RemoteStore */
16770    ), function __PRIVATE_newConnectivityMonitor() {
16771      return __PRIVATE_BrowserConnectivityMonitor.C() ? new __PRIVATE_BrowserConnectivityMonitor() : new __PRIVATE_NoopConnectivityMonitor();
16772    }());
16773  }
16774  createSyncEngine(e, t) {
16775    return function __PRIVATE_newSyncEngine(e2, t2, n, r, i, s, o) {
16776      const _ = new __PRIVATE_SyncEngineImpl(e2, t2, n, r, i, s);
16777      return o && (_.fu = true), _;
16778    }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t);
16779  }
16780  async terminate() {
16781    var e, t;
16782    await async function __PRIVATE_remoteStoreShutdown(e2) {
16783      const t2 = __PRIVATE_debugCast(e2);
16784      __PRIVATE_logDebug(Xt, "RemoteStore shutting down."), t2.Ia.add(
16785        5
16786        /* OfflineCause.Shutdown */
16787      ), await __PRIVATE_disableNetworkInternal(t2), t2.Ea.shutdown(), // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
16788      // triggering spurious listener events with cached data, etc.
16789      t2.Aa.set(
16790        "Unknown"
16791        /* OnlineState.Unknown */
16792      );
16793    }(this.remoteStore), null === (e = this.datastore) || void 0 === e || e.terminate(), null === (t = this.eventManager) || void 0 === t || t.terminate();
16794  }
16795}
16796OnlineComponentProvider.provider = {
16797  build: () => new OnlineComponentProvider()
16798};
16799function __PRIVATE_toByteStreamReaderHelper(e, t = 10240) {
16800  let n = 0;
16801  return {
16802    // eslint-disable-next-line @typescript-eslint/no-explicit-any
16803    async read() {
16804      if (n < e.byteLength) {
16805        const r = {
16806          value: e.slice(n, n + t),
16807          done: false
16808        };
16809        return n += t, r;
16810      }
16811      return {
16812        done: true
16813      };
16814    },
16815    async cancel() {
16816    },
16817    releaseLock() {
16818    },
16819    closed: Promise.resolve()
16820  };
16821}
16822/**
16823 * @license
16824 * Copyright 2020 Google LLC
16825 *
16826 * Licensed under the Apache License, Version 2.0 (the "License");
16827 * you may not use this file except in compliance with the License.
16828 * You may obtain a copy of the License at
16829 *
16830 *   http://www.apache.org/licenses/LICENSE-2.0
16831 *
16832 * Unless required by applicable law or agreed to in writing, software
16833 * distributed under the License is distributed on an "AS IS" BASIS,
16834 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16835 * See the License for the specific language governing permissions and
16836 * limitations under the License.
16837 */
16838/**
16839 * @license
16840 * Copyright 2017 Google LLC
16841 *
16842 * Licensed under the Apache License, Version 2.0 (the "License");
16843 * you may not use this file except in compliance with the License.
16844 * You may obtain a copy of the License at
16845 *
16846 *   http://www.apache.org/licenses/LICENSE-2.0
16847 *
16848 * Unless required by applicable law or agreed to in writing, software
16849 * distributed under the License is distributed on an "AS IS" BASIS,
16850 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16851 * See the License for the specific language governing permissions and
16852 * limitations under the License.
16853 */
16854class __PRIVATE_AsyncObserver {
16855  constructor(e) {
16856    this.observer = e, /**
16857    * When set to true, will not raise future events. Necessary to deal with
16858    * async detachment of listener.
16859    */
16860    this.muted = false;
16861  }
16862  next(e) {
16863    this.muted || this.observer.next && this.xu(this.observer.next, e);
16864  }
16865  error(e) {
16866    this.muted || (this.observer.error ? this.xu(this.observer.error, e) : __PRIVATE_logError("Uncaught Error in snapshot listener:", e.toString()));
16867  }
16868  Ou() {
16869    this.muted = true;
16870  }
16871  xu(e, t) {
16872    setTimeout(() => {
16873      this.muted || e(t);
16874    }, 0);
16875  }
16876}
16877/**
16878 * @license
16879 * Copyright 2020 Google LLC
16880 *
16881 * Licensed under the Apache License, Version 2.0 (the "License");
16882 * you may not use this file except in compliance with the License.
16883 * You may obtain a copy of the License at
16884 *
16885 *   http://www.apache.org/licenses/LICENSE-2.0
16886 *
16887 * Unless required by applicable law or agreed to in writing, software
16888 * distributed under the License is distributed on an "AS IS" BASIS,
16889 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16890 * See the License for the specific language governing permissions and
16891 * limitations under the License.
16892 */
16893class __PRIVATE_BundleReaderImpl {
vendor: 6,047 bytes, lines 16894-17065
16894  constructor(e, t) {
16895    this.Nu = e, this.serializer = t, /** Cached bundle metadata. */
16896    this.metadata = new __PRIVATE_Deferred(), /**
16897    * Internal buffer to hold bundle content, accumulating incomplete element
16898    * content.
16899    */
16900    this.buffer = new Uint8Array(), this.Bu = function __PRIVATE_newTextDecoder() {
16901      return new TextDecoder("utf-8");
16902    }(), // Read the metadata (which is the first element).
16903    this.Lu().then((e2) => {
16904      e2 && e2.Qa() ? this.metadata.resolve(e2.qa.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is
16905             ${JSON.stringify(null == e2 ? void 0 : e2.qa)}`));
16906    }, (e2) => this.metadata.reject(e2));
16907  }
16908  close() {
16909    return this.Nu.cancel();
16910  }
16911  async getMetadata() {
16912    return this.metadata.promise;
16913  }
16914  async Su() {
16915    return await this.getMetadata(), this.Lu();
16916  }
16917  /**
16918   * Reads from the head of internal buffer, and pulling more data from
16919   * underlying stream if a complete element cannot be found, until an
16920   * element(including the prefixed length and the JSON string) is found.
16921   *
16922   * Once a complete element is read, it is dropped from internal buffer.
16923   *
16924   * Returns either the bundled element, or null if we have reached the end of
16925   * the stream.
16926   */
16927  async Lu() {
16928    const e = await this.ku();
16929    if (null === e) return null;
16930    const t = this.Bu.decode(e), n = Number(t);
16931    isNaN(n) && this.qu(`length string (${t}) is not valid number`);
16932    const r = await this.Qu(n);
16933    return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n);
16934  }
16935  /** First index of '{' from the underlying buffer. */
16936  $u() {
16937    return this.buffer.findIndex((e) => e === "{".charCodeAt(0));
16938  }
16939  /**
16940   * Reads from the beginning of the internal buffer, until the first '{', and
16941   * return the content.
16942   *
16943   * If reached end of the stream, returns a null.
16944   */
16945  async ku() {
16946    for (; this.$u() < 0; ) {
16947      if (await this.Uu()) break;
16948    }
16949    if (0 === this.buffer.length) return null;
16950    const e = this.$u();
16951    e < 0 && this.qu("Reached the end of bundle when a length string is expected.");
16952    const t = this.buffer.slice(0, e);
16953    return this.buffer = this.buffer.slice(e), t;
16954  }
16955  /**
16956   * Reads from a specified position from the internal buffer, for a specified
16957   * number of bytes, pulling more data from the underlying stream if needed.
16958   *
16959   * Returns a string decoded from the read bytes.
16960   */
16961  async Qu(e) {
16962    for (; this.buffer.length < e; ) {
16963      await this.Uu() && this.qu("Reached the end of bundle when more is expected.");
16964    }
16965    const t = this.Bu.decode(this.buffer.slice(0, e));
16966    return this.buffer = this.buffer.slice(e), t;
16967  }
16968  qu(e) {
16969    throw this.Nu.cancel(), new Error(`Invalid bundle format: ${e}`);
16970  }
16971  /**
16972   * Pulls more data from underlying stream to internal buffer.
16973   * Returns a boolean indicating whether the stream is finished.
16974   */
16975  async Uu() {
16976    const e = await this.Nu.read();
16977    if (!e.done) {
16978      const t = new Uint8Array(this.buffer.length + e.value.length);
16979      t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t;
16980    }
16981    return e.done;
16982  }
16983}
16984/**
16985 * @license
16986 * Copyright 2025 Google LLC
16987 *
16988 * Licensed under the Apache License, Version 2.0 (the "License");
16989 * you may not use this file except in compliance with the License.
16990 * You may obtain a copy of the License at
16991 *
16992 *   http://www.apache.org/licenses/LICENSE-2.0
16993 *
16994 * Unless required by applicable law or agreed to in writing, software
16995 * distributed under the License is distributed on an "AS IS" BASIS,
16996 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16997 * See the License for the specific language governing permissions and
16998 * limitations under the License.
16999 */
17000class __PRIVATE_BundleReaderSyncImpl {
17001  constructor(e, t) {
17002    this.bundleData = e, this.serializer = t, this.cursor = 0, this.elements = [];
17003    let n = this.Su();
17004    if (!n || !n.Qa()) throw new Error(`The first element of the bundle is not a metadata object, it is
17005         ${JSON.stringify(null == n ? void 0 : n.qa)}`);
17006    this.metadata = n;
17007    do {
17008      n = this.Su(), null !== n && this.elements.push(n);
17009    } while (null !== n);
17010  }
17011  /* Returns the parsed metadata of the bundle. */
17012  getMetadata() {
17013    return this.metadata;
17014  }
17015  /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */
17016  Ku() {
17017    return this.elements;
17018  }
17019  /**
17020   * Parses the next element of the bundle.
17021   *
17022   * @returns a SizedBundleElement representation of the next element in the bundle, or null if
17023   * no more elements exist.
17024   */
17025  Su() {
17026    if (this.cursor === this.bundleData.length) return null;
17027    const e = this.ku(), t = this.Qu(e);
17028    return new __PRIVATE_SizedBundleElement(JSON.parse(t), e);
17029  }
17030  /**
17031   * Reads from a specified position from the bundleData string, for a specified
17032   * number of bytes.
17033   *
17034   * @param length how many characters to read.
17035   * @returns a string parsed from the bundle.
17036   */
17037  Qu(e) {
17038    if (this.cursor + e > this.bundleData.length) throw new FirestoreError(N.INTERNAL, "Reached the end of bundle when more is expected.");
17039    return this.bundleData.slice(this.cursor, this.cursor += e);
17040  }
17041  /**
17042   * Reads from the current cursor until the first '{'.
17043   *
17044   * @returns  A string to integer represention of the parsed value.
17045   * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths
17046   * prefix bundle objects.
17047   */
17048  ku() {
17049    const e = this.cursor;
17050    let t = this.cursor;
17051    for (; t < this.bundleData.length; ) {
17052      if ("{" === this.bundleData[t]) {
17053        if (t === e) throw new Error("First character is a bracket and not a number");
17054        return this.cursor = t, Number(this.bundleData.slice(e, t));
17055      }
17056      t++;
17057    }
17058    throw new Error("Reached the end of bundle when more is expected.");
17059  }
17060}
17061/**
17062 * @license
17063 * Copyright 2017 Google LLC
17064 *
17065 * Licensed under the Apache License, Version 2.0 (the "License");
17066 * you may not use this file except in compliance with the License.
17067 * You may obtain a copy of the License at
17068 *
17069 *   http://www.apache.org/licenses/LICENSE-2.0
17070 *
17071 * Unless required by applicable law or agreed to in writing, software
17072 * distributed under the License is distributed on an "AS IS" BASIS,
17073 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17074 * See the License for the specific language governing permissions and
17075 * limitations under the License.
17076 */
17077class Transaction$2 {
17078  constructor(e) {
17079    this.datastore = e, // The version of each document that was read during this transaction.
17080    this.readVersions = /* @__PURE__ */ new Map(), this.mutations = [], this.committed = false, /**
17081    * A deferred usage error that occurred previously in this transaction that
17082    * will cause the transaction to fail once it actually commits.
17083    */
17084    this.lastTransactionError = null, /**
17085    * Set of documents that have been written in the transaction.
17086    *
17087    * When there's more than one write to the same key in a transaction, any
17088    * writes after the first are handled differently.
17089    */
17090    this.writtenDocs = /* @__PURE__ */ new Set();
17091  }
17092  async lookup(e) {
17093    if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(N.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes."), this.lastTransactionError;
17094    const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e2, t2) {
17095      const n = __PRIVATE_debugCast(e2), r = {
17096        documents: t2.map((e3) => __PRIVATE_toName(n.serializer, e3))
17097      }, i = await n.Jo("BatchGetDocuments", n.serializer.databaseId, ResourcePath.emptyPath(), r, t2.length), s = /* @__PURE__ */ new Map();
17098      i.forEach((e3) => {
17099        const t3 = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e3);
17100        s.set(t3.key.toString(), t3);
17101      });
17102      const o = [];
17103      return t2.forEach((e3) => {
17104        const t3 = s.get(e3.toString());
17105        __PRIVATE_hardAssert(!!t3, 55234, {
17106          key: e3
17107        }), o.push(t3);
17108      }), o;
17109    }(this.datastore, e);
17110    return t.forEach((e2) => this.recordVersion(e2)), t;
17111  }
17112  set(e, t) {
17113    this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());
17114  }
17115  update(e, t) {
17116    try {
17117      this.write(t.toMutation(e, this.preconditionForUpdate(e)));
17118    } catch (e2) {
17119      this.lastTransactionError = e2;
17120    }
17121    this.writtenDocs.add(e.toString());
17122  }
17123  delete(e) {
17124    this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());
17125  }
17126  async commit() {
17127    if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError;
17128    const e = this.readVersions;
17129    this.mutations.forEach((t) => {
17130      e.delete(t.key.toString());
17131    }), // For each document that was read but not written to, we want to perform
17132    // a `verify` operation.
17133    e.forEach((e2, t) => {
17134      const n = DocumentKey.fromPath(t);
17135      this.mutations.push(new __PRIVATE_VerifyMutation(n, this.prec
17135ondition(n)));
17136    }), await async function __PRIVATE_invokeCommitRpc(e2, t) {
17137      const n = __PRIVATE_debugCast(e2), r = {
17138        writes: t.map((e3) => toMutation(n.serializer, e3))
17139      };
17140      await n.Wo("Commit", n.serializer.databaseId, ResourcePath.emptyPath(), r);
17141    }(this.datastore, this.mutations), this.committed = true;
17142  }
17143  recordVersion(e) {
17144    let t;
17145    if (e.isFoundDocument()) t = e.version;
17146    else {
17147      if (!e.isNoDocument()) throw fail(50498, {
17148        Wu: e.constructor.name
17149      });
17150      t = SnapshotVersion.min();
17151    }
17152    const n = this.readVersions.get(e.key.toString());
17153    if (n) {
17154      if (!t.isEqual(n))
17155        throw new FirestoreError(N.ABORTED, "Document version changed between two reads.");
17156    } else this.readVersions.set(e.key.toString(), t);
17157  }
17158  /**
17159   * Returns the version of this document when it was read in this transaction,
17160   * as a precondition, or no precondition if it was not read.
17161   */
17162  precondition(e) {
17163    const t = this.readVersions.get(e.toString());
17164    return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(false) : Precondition.updateTime(t) : Precondition.none();
17165  }
17166  /**
17167   * Returns the precondition for a document if the operation is an update.
17168   */
17169  preconditionForUpdate(e) {
17170    const t = this.readVersions.get(e.toString());
17171    if (!this.writtenDocs.has(e.toString()) && t) {
17172      if (t.isEqual(SnapshotVersion.min()))
17173        throw new FirestoreError(N.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
17174      return Precondition.updateTime(t);
17175    }
17176    return Precondition.exists(true);
17177  }
17178  write(e) {
17179    this.ensureCommitNotCalled(), this.mutations.push(e);
17180  }
17181  ensureCommitNotCalled() {
17182  }
17183}
17184/**
17185 * @license
17186 * Copyright 2019 Google LLC
17187 *
17188 * Licensed under the Apache License, Version 2.0 (the "License");
17189 * you may not use this file except in compliance with the License.
17190 * You may obtain a copy of the License at
17191 *
17192 *   http://www.apache.org/licenses/LICENSE-2.0
17193 *
17194 * Unless required by applicable law or agreed to in writing, software
17195 * distributed under the License is distributed on an "AS IS" BASIS,
17196 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17197 * See the License for the specific language governing permissions and
17198 * limitations under the License.
17199 */
17200class __PRIVATE_TransactionRunner {
17201  constructor(e, t, n, r, i) {
17202    this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, this.deferred = i, this.Gu = n.maxAttempts, this.F_ = new __PRIVATE_ExponentialBackoff(
17203      this.asyncQueue,
17204      "transaction_retry"
17205      /* TimerId.TransactionRetry */
17206    );
17207  }
17208  /** Runs the transaction and sets the result on deferred. */
17209  zu() {
17210    this.Gu -= 1, this.ju();
17211  }
17212  ju() {
17213    this.F_.g_(async () => {
17214      const e = new Transaction$2(this.datastore), t = this.Ju(e);
17215      t && t.then((t2) => {
17216        this.asyncQueue.enqueueAndForget(() => e.commit().then(() => {
17217          this.deferred.resolve(t2);
17218        }).catch((e2) => {
17219          this.Hu(e2);
17220        }));
17221      }).catch((e2) => {
17222        this.Hu(e2);
17223      });
17224    });
17225  }
17226  Ju(e) {
17227    try {
17228      const t = this.updateFunction(e);
17229      return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error("Transaction callback must return a Promise")), null);
17230    } catch (e2) {
17231      return this.deferred.reject(e2), null;
17232    }
17233  }
17234  Hu(e) {
17235    this.Gu > 0 && this.Yu(e) ? (this.Gu -= 1, this.asyncQueue.enqueueAndForget(() => (this.ju(), Promise.resolve()))) : this.deferred.reject(e);
17236  }
17237  Yu(e) {
17238    if ("FirebaseError" === e.name) {
17239      const t = e.code;
17240      return "aborted" === t || "failed-precondition" === t || "already-exists" === t || !__PRIVATE_isPermanentError(t);
17241    }
17242    return false;
17243  }
17244}
17245/**
17246 * @license
17247 * Copyright 2017 Google LLC
17248 *
17249 * Licensed under the Apache License, Version 2.0 (the "License");
17250 * you may not use this file except in compliance with the License.
17251 * You may obtain a copy of the License at
17252 *
17253 *   http://www.apache.org/licenses/LICENSE-2.0
17254 *
17255 * Unless required by applicable law or agreed to in writing, softw
17255are
17256 * distributed under the License is distributed on an "AS IS" BASIS,
17257 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17258 * See the License for the specific language governing permissions and
17259 * limitations under the License.
17260 */
17261const rn = "FirestoreClient";
17262class FirestoreClient {
17263  constructor(e, t, n, r, i) {
17264    this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this.databaseInfo = r, this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), this.appCheckCredentialListener = () => Promise.resolve(), this._uninitializedComponentsProvider = i, this.authCredentials.start(n, async (e2) => {
17265      __PRIVATE_logDebug(rn, "Received user=", e2.uid), await this.authCredentialListener(e2), this.user = e2;
17266    }), this.appCheckCredentials.start(n, (e2) => (__PRIVATE_logDebug(rn, "Received new app check token=", e2), this.appCheckCredentialListener(e2, this.user)));
17267  }
17268  get configuration() {
17269    return {
17270      asyncQueue: this.asyncQueue,
17271      databaseInfo: this.databaseInfo,
17272      clientId: this.clientId,
17273      authCredentials: this.authCredentials,
17274      appCheckCredentials: this.appCheckCredentials,
17275      initialUser: this.user,
17276      maxConcurrentLimboResolutions: 100
17277    };
17278  }
17279  setCredentialChangeListener(e) {
17280    this.authCredentialListener = e;
17281  }
17282  setAppCheckTokenChangeListener(e) {
17283    this.appCheckCredentialListener = e;
17284  }
17285  terminate() {
17286    this.asyncQueue.enterRestrictedMode();
17287    const e = new __PRIVATE_Deferred();
17288    return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {
17289      try {
17290        this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), // The credentials provider must be terminated after shutting down the
17291        // RemoteStore as it will prevent the RemoteStore from retrieving auth
17292        // tokens.
17293        this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve();
17294      } catch (t) {
17295        const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, "Failed to shutdown persistence");
17296        e.reject(n);
17297      }
17298    }), e.promise;
17299  }
17300}
17301async function __PRIVATE_setOfflineComponentProvider(e, t) {
17302  e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(rn, "Initializing OfflineComponentProvider");
17303  const n = e.configuration;
17304  await t.initialize(n);
17305  let r = n.initialUser;
17306  e.setCredentialChangeListener(async (e2) => {
17307    r.isEqual(e2) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e2), r = e2);
17308  }), t.persistence.setDatabaseDeletedListener(() => {
17309    __PRIVATE_logWarn("Terminating Firestore due to IndexedDb database deletion"), e.terminate().then(() => {
17310      __PRIVATE_logDebug("Terminating Firestore due to IndexedDb database deletion completed successfully");
17311    }).catch((e2) => {
17312      __PRIVATE_logWarn("Terminating Firestore due to IndexedDb database deletion failed", e2);
17313    });
17314  }), e._offlineComponents = t;
17315}
17316async function __PRIVATE_setOnlineComponentProvider(e, t) {
17317  e.asyncQueue.verifyOperationInProgress();
17318  const n = await __PRIVATE_ensureOfflineComponents(e);
17319  __PRIVATE_logDebug(rn, "Initializing OnlineComponentProvider"), await t.initialize(n, e.configuration), // The CredentialChangeListener of the online component provider takes
17320  // precedence over the offline component provider.
17321  e.setCredentialChangeListener((e2) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e2)), e.setAppCheckTokenChangeListener((e2, n2) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n2)), e._onlineComponents = t;
17322}
17323async function __PRIVATE_ensureOfflineComponents(e) {
17324  if (!e._offlineComponents) if (e._uninitializedComponentsProvider) {
17325    __PRIVATE_logDebug(rn, "Using user provided OfflineComponentProvider");
17326    try {
17327      await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline);
17328    } catch (t) {
17329      const n = t;
17330      if (!function __PRIVATE_canFallbackFromIndexedDbError(e2) {
17331        return "FirebaseError" === e2.name ? e2.code === N.FAILED_PRECONDITION || e2.code === N.UNIMPLEMENT
17331ED : !("undefined" != typeof DOMException && e2 instanceof DOMException) || // When the browser is out of quota we could get either quota exceeded
17332        // or an aborted error depending on whether the error happened during
17333        // schema migration.
17334        22 === e2.code || 20 === e2.code || // Firefox Private Browsing mode disables IndexedDb and returns
17335        // INVALID_STATE for any usage.
17336        11 === e2.code;
17337      }(n)) throw n;
17338      __PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: " + n), await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_MemoryOfflineComponentProvider());
17339    }
17340  } else __PRIVATE_logDebug(rn, "Using default OfflineComponentProvider"), await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0));
17341  return e._offlineComponents;
17342}
17343async function __PRIVATE_ensureOnlineComponents(e) {
17344  return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(rn, "Using user provided OnlineComponentProvider"), await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(rn, "Using default OnlineComponentProvider"), await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider()))), e._onlineComponents;
17345}
17346function __PRIVATE_getPersistence(e) {
17347  return __PRIVATE_ensureOfflineComponents(e).then((e2) => e2.persistence);
17348}
17349function __PRIVATE_getLocalStore(e) {
17350  return __PRIVATE_ensureOfflineComponents(e).then((e2) => e2.localStore);
17351}
17352function __PRIVATE_getRemoteStore(e) {
17353  return __PRIVATE_ensureOnlineComponents(e).then((e2) => e2.remoteStore);
17354}
17355function __PRIVATE_getSyncEngine(e) {
17356  return __PRIVATE_ensureOnlineComponents(e).then((e2) => e2.syncEngine);
17357}
17358function __PRIVATE_getDatastore(e) {
17359  return __PRIVATE_ensureOnlineComponents(e).then((e2) => e2.datastore);
17360}
17361async function __PRIVATE_getEventManager(e) {
17362  const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager;
17363  return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), n.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t.syncEngine), n.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t.syncEngine), n;
17364}
17365function __PRIVATE_firestoreClientEnableNetwork(e) {
17366  return e.asyncQueue.enqueue(async () => {
17367    const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);
17368    return t.setNetworkEnabled(true), function __PRIVATE_remoteStoreEnableNetwork(e2) {
17369      const t2 = __PRIVATE_debugCast(e2);
17370      return t2.Ia.delete(
17371        0
17372        /* OfflineCause.UserDisabled */
17373      ), __PRIVATE_enableNetworkInternal(t2);
17374    }(n);
17375  });
17376}
17377function __PRIVATE_firestoreClientDisableNetwork(e) {
17378  return e.asyncQueue.enqueue(async () => {
17379    const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);
17380    return t.setNetworkEnabled(false), async function __PRIVATE_remoteStoreDisableNetwork(e2) {
17381      const t2 = __PRIVATE_debugCast(e2);
17382      t2.Ia.add(
17383        0
17384        /* OfflineCause.UserDisabled */
17385      ), await __PRIVATE_disableNetworkInternal(t2), // Set the OnlineState to Offline so get()s return from cache, etc.
17386      t2.Aa.set(
17387        "Offline"
17388        /* OnlineState.Offline */
17389      );
17390    }(n);
17391  });
17392}
17393function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) {
17394  const n = new __PRIVATE_Deferred();
17395  return e.asyncQueue.enqueueAndForget(async () => async function __PRIVATE_readDocumentFromCache(e2, t2, n2) {
17396    try {
17397      const r = await function __PRIVATE_localStoreReadDocument(e3, t3) {
17398        const n3 = __PRIVATE_debugCast(e3);
17399        return n3.persistence.runTransaction("read document", "readonly", (e4) => n3.localDocuments.getDocument(e4, t3));
17400      }(e2, t2);
17401      r.isFoundDocument() ? n2.resolve(r) : r.isNoDocument() ? n2.resolve(null) : n2.reject(new FirestoreError(N.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"));
17402    } catch (e3) {
17403      const r = __PRIVATE_wrapInUserErrorIfRecoverable(e3, `Failed to get document '${t2} from cache`);
17404      n2.reject(r);
17405    }
17406  }(await __PRIVATE_getLocalStore(e), t, n)), n.promise;
17407}
17408function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) {
17409  const r = new __PRIVATE_Deferred();
17410  return e.asyncQueue.enqueueAndForget(async () => function __PRIVATE_readDocumentViaSnapshotListener(e2, t2, n2, r2, i) {
17411    const s = new __PRIVATE_AsyncObserver({
17412      next: (_) => {
17413        s.Ou(), t2.enqueueAndForget(() => __PRIVATE_eventManagerUnlisten(e2, o));
17414        const a = _.docs.has(n2);
17415        !a && _.fromCache ? (
17416          // TODO(dimond): If we're online and the document doesn't
17417          // exist then we resolve with a doc.exists set to false. If
17418          // we're offline however, we reject the Promise in this
17419          // case. Two options: 1) Cache the negative response from
17420          // the server so we can deliver that even when you're
17421          // offline 2) Actually reject the Promise in the online case
17422          // if the document doesn't exist.
17423          i.reject(new FirestoreError(N.UNAVAILABLE, "Failed to get document because the client is offline."))
17424        ) : a && _.fromCache && r2 && "server" === r2.source ? i.reject(new FirestoreError(N.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(_);
17425      },
17426      error: (e3) => i.reject(e3)
17427    }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n2.path), s, {
17428      includeMetadataChanges: true,
17429      ka: true
17430    });
17431    return __PRIVATE_eventManagerListen(e2, o);
17432  }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r)), r.promise;
17433}
17434function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) {
17435  const n = new __PRIVATE_Deferred();
17436  return e.asyncQueue.enqueueAndForget(async () => async function __PRIVATE_executeQueryFromCache(e2, t2, n2) {
17437    try {
17438      const r = await __PRIVATE_localStoreExecuteQuery(
17439        e2,
17440        t2,
17441        /* usePreviousResults= */
17442        true
17443      ), i = new __PRIVATE_View(t2, r.qs), s = i.nu(r.documents), o = i.applyChanges(
17444        s,
17445        /* limboResolutionEnabled= */
17446        false
17447      );
17448      n2.resolve(o.snapshot);
17449    } catch (e3) {
17450      const r = __PRIVATE_wrapInUserErrorIfRecoverable(e3, `Failed to execute query '${t2} against cache`);
17451      n2.reject(r);
17452    }
17453  }(await __PRIVATE_getLocalStore(e), t, n)), n.promise;
17454}
17455function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) {
17456  const r = new __PRIVATE_Deferred();
17457  return e.asyncQueue.enqueueAndForget(async () => function __PRIVATE_executeQueryViaSnapshotListener(e2, t2, n2, r2, i) {
17458    const s = new __PRIVATE_AsyncObserver({
17459      next: (n3) => {
17460        s.Ou(), t2.enqueueAndForget(() => __PRIVATE_eventManagerUnlisten(e2, o)), n3.fromCache && "server" === r2.source ? i.reject(new FirestoreError(N.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n3);
17461      },
17462      error: (e3) => i.reject(e3)
17463    }), o = new __PRIVATE_QueryListener(n2, s, {
17464      includeMetadataChanges: true,
17465      ka: true
17466    });
17467    return __PRIVATE_eventManagerListen(e2, o);
17468  }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r)), r.promise;
17469}
17470function __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) {
17471  const r = new __PRIVATE_Deferred();
17472  return e.asyncQueue.enqueueAndForget(async () => {
17473    try {
17474      const i = await __PRIVATE_getDatastore(e);
17475      r.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e2, t2, n2) {
17476        var r2;
17477        const i2 = __PRIVATE_debugCast(e2), { request: s, ft: o, parent: _ } = __PRIVATE_toRunAggregationQueryRequest(i2.serializer, __PRIVATE_queryToAggregateTarget(t2), n2);
17478        i2.connection.Qo || delete s.parent;
17479        const a = (await i2.Jo(
17480          "RunAggregationQuery",
17481          i2.serializer.databaseId,
17482          _,
17483          s,
17484          /*expectedResponseCount=*/
17485          1
17486        )).filter((e3) => !!e3.result);
17487        __PRIVATE_hardAssert(1 === a.length, 64727);
17488        const u = null === (r2 = a[0].result) || void 0 === r2 ? void 0 : r2.aggregateFields;
17489        return Object.keys(u).reduce((e3, t3) => (e3[o[t3]] = u[t3], e3), {});
17490      }(i, t, n));
17491    } catch (e2) {
17492      r.reject(e2);
17493    }
17494  }), r.promise;
17495}
17496function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) {
17497  const n = new __PRIVATE_AsyncObserver(t);
17498  return e.asyncQueue.enqueueAndForget(async () => function __PRIVATE_addSnapshotsInSyncListener(e2, t2) {
17499    __PRIVATE_debugCast(e2).Da.add(t2), // Immediately fire an initial event, indicating all existing listeners
17500    // are in-sync.
17501    t2.next();
17502  }(await __PRIVATE_getEventManager(e), n)), () => {
17503    n.Ou(), e.asyncQueue.enqueueAndForget(async () => function __PRIVATE_removeSnapshotsInSyncListener(e2, t2) {
17504      __PRIVATE_debugCast(e2).Da.delete(t2);
17505    }(await __PRIVATE_getEventManager(e), n));
17506  };
17507}
17508function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) {
17509  const i = function __PRIVATE_createBundleReader(e2, t2) {
17510    let n2;
17511    n2 = "string" == typeof e2 ? __PRIVATE_newTextEncoder().encode(e2) : e2;
17512    return function __PRIVATE_newBundleReader(e3, t3) {
17513      return new __PRIVATE_BundleReaderImpl(e3, t3);
17514    }(function __PRIVATE_toByteStreamReader(e3, t3) {
17515      if (e3 instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e3, t3);
17516      if (e3 instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e3), t3);
17517      if (e3 instanceof ReadableStream) return e3.getReader();
17518      throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
17519    }(n2), t2);
17520  }(n, __PRIVATE_newSerializer(t));
17521  e.asyncQueue.enqueueAndForget(async () => {
17522    __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r);
17523  });
17524}
17525function __PRIVATE_firestoreClientGetNamedQuery(e, t) {
17526  return e.asyncQueue.enqueue(async () => function __PRIVATE_localStoreGetNamedQuery(e2, t2) {
17527    const n = __PRIVATE_debugCast(e2);
17528    return n.persistence.runTransaction("Get named query", "readonly", (e3) => n.Ti.getNamedQuery(e3, t2));
17529  }(await __PRIVATE_getLocalStore(e), t));
17530}
17531function __PRIVATE_createBundleReaderSync(e, t) {
17532  return function __PRIVATE_newBundleReaderSync(e2, t2) {
17533    return new __PRIVATE_BundleReaderSyncImpl(e2, t2);
17534  }(e, t);
17535}
17536function __PRIVATE_firestoreClientSetIndexConfiguration(e, t) {
17537  return e.asyncQueue.enqueue(async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e2, t2) {
17538    const n = __PRIVATE_debugCast(e2), r = n.indexManager, i = [];
17539    return n.persistence.runTransaction("Configure indexes", "readwrite", (e3) => r.getFieldIndexes(e3).next((n2) => (
17540      /**
17541      * @license
17542      * Copyright 2017 Google LLC
17543      *
17544      * Licensed under the Apache License, Version 2.0 (the "License");
17545      * you may not use this file except in compliance with the License.
17546      * You may obtain a copy of the License at
17547      *
17548      *   http://www.apache.org/licenses/LICENSE-2.0
17549      *
17550      * Unless required by applicable law or agreed to in writing, software
17551      * distributed under the License is distributed on an "AS IS" BASIS,
17552      * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17553      * See the License for the specific language governing permissions and
17554      * limitations under the License.
17555      */
17556      /**
17557      * Compares two array for equality using comparator. The method computes the
17558      * intersection and invokes `onAdd` for every element that is in `after` but not
17559      * `before`. `onRemove` is invoked for every element in `before` but missing
17560      * from `after`.
17561      *
17562      * The method creates a copy of both `before` and `after` and runs in O(n log
17563      * n), where n is the size of the two lists.
17564      *
17565      * @param before - The elements that exist in the original array.
17566      * @param after - The elements to diff against the original array.
17567      * @param comparator - The comparator for the elements in before and after.
17568      * @param onAdd - A function to invoke for every element that is part of `
17569      * after` but not `before`.
17570      * @param onRemove - A function to invoke for every element that is part of
17571      * `before` but not `after`.
17572      */
17573      function __PRIVATE_diffArrays(e4, t3, n3, r2, i2) {
17574        e4 = [...e4], t3 = [...t3], e4.sort(n3), t3.sort(n3);
17575        const s = e4.length, o = t3.length;
17576        let _ = 0, a = 0;
17577        for (; _ < o && a < s; ) {
17578          const s2 = n3(e4[a], t3[_]);
17579          s2 < 0 ? (
17580            // The element was removed if the next element in our ordered
17581            // walkthrough is only in `before`.
17582            i2(e4[a++])
17583          ) : s2 > 0 ? (
17584            // The element was added if the next element in our ordered walkthrough
17585            // is only in `after`.
17586            r2(t3[_++])
17587          ) : (_++, a++);
17588        }
17589        for (; _ < o; ) r2(t3[_++]);
17590        for (; a < s; ) i2(e4[a++]);
17591      }(n2, t2, __PRIVATE_fieldIndexSemanticComparator, (t3) => {
17592        i.push(r.addFieldIndex(e3, t3));
17593      }, (t3) => {
17594        i.push(r.deleteFieldIndex(e3, t3));
17595      })
17596    )).next(() => PersistencePromise.waitFor(i)));
17597  }(await __PRIVATE_getLocalStore(e), t));
17598}
17599function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e, t) {
17600  return e.asyncQueue.enqueue(async () => function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e2, t2) {
17601    __PRIVATE_debugCast(e2).Cs.Rs = t2;
17602  }(await __PRIVATE_getLocalStore(e), t));
17603}
17604function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e) {
17605  return e.asyncQueue.enqueue(async () => function __PRIVATE_localStoreDeleteAllFieldIndexes(e2) {
17606    const t = __PRIVATE_debugCast(e2), n = t.indexManager;
17607    return t.persistence.runTransaction("Delete All Indexes", "readwrite", (e3) => n.deleteAllFieldIndexes(e3));
17608  }(await __PRIVATE_getLocalStore(e)));
17609}
17610/**
17611 * @license
17612 * Copyright 2023 Google LLC
17613 *
17614 * Licensed under the Apache License, Version 2.0 (the "License");
17615 * you may not use this file except in compliance with the License.
17616 * You may obtain a copy of the License at
17617 *
17618 *   http://www.apache.org/licenses/LICENSE-2.0
17619 *
17620 * Unless required by applicable law or agreed to in writing, software
17621 * distributed under the License is distributed on an "AS IS" BASIS,
17622 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17623 * See the License for the specific language governing permissions and
17624 * limitations under the License.
17625 */
17626function __PRIVATE_cloneLongPollingOptions(e) {
17627  const t = {};
17628  return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t;
17629}
17630/**
17631 * @license
17632 * Copyright 2020 Google LLC
17633 *
17634 * Licensed under the Apache License, Version 2.0 (the "License");
17635 * you may not use this file except in compliance with the License.
17636 * You may obtain a copy of the License at
17637 *
17638 *   http://www.apache.org/licenses/LICENSE-2.0
17639 *
17640 * Unless required by applicable law or agreed to in writing, software
17641 * distributed under the License is distributed on an "AS IS" BASIS,
17642 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17643 * See the License for the specific language governing permissions and
17644 * limitations under the License.
17645 */
17646const sn = /* @__PURE__ */ new Map();
17647/**
17648 * @license
17649 * Copyright 2020 Google LLC
17650 *
17651 * Licensed under the Apache License, Version 2.0 (the "License");
17652 * you may not use this file except in compliance with the License.
17653 * You may obtain a copy of the License at
17654 *
17655 *   http://www.apache.org/licenses/LICENSE-2.0
17656 *
17657 * Unless required by applicable law or agreed to in writing, software
17658 * distributed under the License is distributed on an "AS IS" BASIS,
17659 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17660 * See the License for the specific language governing permissions and
17661 * limitations under the License.
17662 */
17663const on = "firestore.googleapis.com", _n = true;
17664class FirestoreSettingsImpl {
17665  constructor(e) {
17666    var t, n;
17667    if (void 0 === e.host) {
17668      if (void 0 !== e.ssl) throw new FirestoreError(N.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
17669      this.host = on, this.ssl = _n;
17670    } else this.host = e.host, this.ssl = null !== (t = e.ssl) && void 0 !== t ? t : _n;
17671    if (this.isUsingEmulator = void 0 !== e.emulatorOptions, this.credentials = e.credentials, this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, this.localCache = e.localCache, void 0 === e.cacheSizeBytes) this.cacheSizeBytes = Mt;
17672    else {
17673      if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < Ot) throw new FirestoreError(N.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
17674      this.cacheSizeBytes = e.cacheSizeBytes;
17675    }
17676    __PRIVATE_validateIsNotUsedTogether("experimentalForceLongPolling", e.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", e.experimentalAutoDetectLongPolling), this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = false : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : (
17677      // For backwards compatibility, coerce the value to boolean even though
17678      // the TypeScript compiler has narrowed the type to boolean already.
17679      // noinspection PointlessBooleanExpressionJS
17680      this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling
17681    ), this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(null !== (n = e.experimentalLongPollingOptions) && void 0 !== n ? n : {}), function __PRIVATE_validateLongPollingOptions(e2) {
17682      if (void 0 !== e2.timeoutSeconds) {
17683        if (isNaN(e2.timeoutSeconds)) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e2.timeoutSeconds} (must not be NaN)`);
17684        if (e2.timeoutSeconds < 5) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e2.timeoutSeconds} (minimum allowed value is 5)`);
17685        if (e2.timeoutSeconds > 30) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e2.timeoutSeconds} (maximum allowed value is 30)`);
17686      }
17687    }(this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams;
17688  }
17689  isEqual(e) {
17690    return this.host === e.host && this.ssl === e.ssl && this.credentials === e.credentials && this.cacheSizeBytes === e.cacheSizeBytes && this.experimentalForceLongPolling === e.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(e2, t) {
17691      return e2.timeoutSeconds === t.timeoutSeconds;
17692    }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams;
17693  }
17694}
17695class Firestore$1 {
17696  /** @hideconstructor */
17697  constructor(e, t, n, r) {
17698    this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, this._app = r, /**
17699    * Whether it's a Firestore or Firestore Lite instance.
17700    */
17701    this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), this._settingsFrozen = false, this._emulatorOptions = {}, // A task that is assigned when the terminate() is invoked and resolved when
17702    // all components have shut down. Otherwise, Firestore is not terminated,
17703    // which can mean either the FirestoreClient is in the process of starting,
17704    // or restarting.
17705    this._terminateTask = "notTerminated";
17706  }
17707  /**
17708   * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
17709   * instance.
17710   */
17711  get app() {
17712    if (!this._app) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
17713    return this._app;
17714  }
17715  get _initialized() {
17716    return this._settingsFrozen;
17717  }
17718  get _terminated() {
17719    return "notTerminated" !== this._terminateTask;
17720  }
17721  _setSettings(e) {
17722    if (this._settingsFrozen) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
17723    this._settings = new FirestoreSettingsImpl(e), this._emulatorOptions = e.emulatorOptions || {}, void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e2) {
17724      if (!e2) return new __PRIVATE_EmptyAuthCredentialsProvider();
17725      switch (e2.type) {
17726        case "firstParty":
17727          return new __PRIVATE_FirstPartyAuthCredentialsProvider(e2.sessionIndex || "0", e2.iamToken || null, e2.authTokenFactory || null);
17728        case "provider":
17729          return e2.client;
17730        default:
17731          throw new FirestoreError(N.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invali
17731d credential type");
17732      }
17733    }(e.credentials));
17734  }
17735  _getSettings() {
17736    return this._settings;
17737  }
17738  _getEmulatorOptions() {
17739    return this._emulatorOptions;
17740  }
17741  _freezeSettings() {
17742    return this._settingsFrozen = true, this._settings;
17743  }
17744  _delete() {
17745    return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), this._terminateTask;
17746  }
17747  async _restart() {
17748    "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated";
17749  }
17750  /** Returns a JSON-serializable representation of this `Firestore` instance. */
17751  toJSON() {
17752    return {
17753      app: this._app,
17754      databaseId: this._databaseId,
17755      settings: this._settings
17756    };
17757  }
17758  /**
17759   * Terminates all components used by this client. Subclasses can override
17760   * this method to clean up their own dependencies, but must also call this
17761   * method.
17762   *
17763   * Only ever called once.
17764   */
17765  _terminate() {
17766    return function __PRIVATE_removeComponents(e) {
17767      const t = sn.get(e);
17768      t && (__PRIVATE_logDebug("ComponentProvider", "Removing Datastore"), sn.delete(e), t.terminate());
17769    }(this), Promise.resolve();
17770  }
17771}
17772function connectFirestoreEmulator(e, t, n, r = {}) {
17773  var i;
17774  e = __PRIVATE_cast(e, Firestore$1);
17775  const s = isCloudWorkstation(t), o = e._getSettings(), _ = Object.assign(Object.assign({}, o), {
17776    emulatorOptions: e._getEmulatorOptions()
17777  }), a = `${t}:${n}`;
17778  s && (pingServer(`https://${a}`), updateEmulatorBanner("Firestore", true)), o.host !== on && o.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");
17779  const u = Object.assign(Object.assign({}, o), {
17780    host: a,
17781    ssl: s,
17782    emulatorOptions: r
17783  });
17784  if (!deepEqual(u, _) && (e._setSettings(u), r.mockUserToken)) {
17785    let t2, n2;
17786    if ("string" == typeof r.mockUserToken) t2 = r.mockUserToken, n2 = User.MOCK_USER;
17787    else {
17788      t2 = createMockUserToken(r.mockUserToken, null === (i = e._app) || void 0 === i ? void 0 : i.options.projectId);
17789      const s2 = r.mockUserToken.sub || r.mockUserToken.user_id;
17790      if (!s2) throw new FirestoreError(N.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
17791      n2 = new User(s2);
17792    }
17793    e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t2, n2));
17794  }
17795}
17796/**
17797 * @license
17798 * Copyright 2020 Google LLC
17799 *
17800 * Licensed under the Apache License, Version 2.0 (the "License");
17801 * you may not use this file except in compliance with the License.
17802 * You may obtain a copy of the License at
17803 *
17804 *   http://www.apache.org/licenses/LICENSE-2.0
17805 *
17806 * Unless required by applicable law or agreed to in writing, software
17807 * distributed under the License is distributed on an "AS IS" BASIS,
17808 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17809 * See the License for the specific language governing permissions and
17810 * limitations under the License.
17811 */
17812class Query {
17813  // This is the lite version of the Query class in the main SDK.
17814  /** @hideconstructor protected */
17815  constructor(e, t, n) {
17816    this.converter = t, this._query = n, /** The type of this Firestore reference. */
17817    this.type = "query", this.firestore = e;
17818  }
17819  withConverter(e) {
17820    return new Query(this.firestore, e, this._query);
17821  }
17822}
17823class DocumentReference {
17824  /** @hideconstructor */
17825  constructor(e, t, n) {
17826    this.converter = t, this._key = n, /** The type of this Firestore reference. */
17827    this.type = "document", this.firestore = e;
17828  }
17829  get _path() {
17830    return this._key.path;
17831  }
17832  /**
17833   * The document's identifier within its collection.
17834   */
17835  get id() {
17836    return this._key.path.lastSegment();
17837  }
17838  /**
17839   * A string representing the path of the referenced document (relative
17840   * to the root of the database).
17841   */
17842  get path() {
17843    return this._key.path.canonicalString();
17844  }
17845  /**
17846   * The collection this `DocumentReference` belongs to.
17847   */
17848  get parent() {
17849    return new CollectionReference(this.firestore, this.converter, this._key.path.popLast());
17850  }
17851  withConverter(e) {
17852    return new DocumentReference(this.firestore, e, this._key);
17853  }
17854  /**
17855   * Returns a JSON-serializable representation of this `DocumentReference` instance.
17856   *
17857   * @returns a JSON representation of this object.
17858   */
17859  toJSON() {
17860    return {
17861      type: DocumentReference._jsonSchemaVersion,
17862      referencePath: this._key.toString()
17863    };
17864  }
17865  static fromJSON(e, t, n) {
17866    if (__PRIVATE_validateJSON(t, DocumentReference._jsonSchema)) return new DocumentReference(e, n || null, new DocumentKey(ResourcePath.fromString(t.referencePath)));
17867  }
17868}
17869DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = {
vendor: 4,272 bytes, lines 17870-17973
17870  type: property("string", DocumentReference._jsonSchemaVersion),
17871  referencePath: property("string")
17872};
17873class CollectionReference extends Query {
17874  /** @hideconstructor */
17875  constructor(e, t, n) {
17876    super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, /** The type of this Firestore reference. */
17877    this.type = "collection";
17878  }
17879  /** The collection's identifier. */
17880  get id() {
17881    return this._query.path.lastSegment();
17882  }
17883  /**
17884   * A string representing the path of the referenced collection (relative
17885   * to the root of the database).
17886   */
17887  get path() {
17888    return this._query.path.canonicalString();
17889  }
17890  /**
17891   * A reference to the containing `DocumentReference` if this is a
17892   * subcollection. If this isn't a subcollection, the reference is null.
17893   */
17894  get parent() {
17895    const e = this._path.popLast();
17896    return e.isEmpty() ? null : new DocumentReference(
17897      this.firestore,
17898      /* converter= */
17899      null,
17900      new DocumentKey(e)
17901    );
17902  }
17903  withConverter(e) {
17904    return new CollectionReference(this.firestore, e, this._path);
17905  }
17906}
17907function collection(e, t, ...n) {
17908  if (e = getModularInstance(e), __PRIVATE_validateNonEmptyArgument("collection", "path", t), e instanceof Firestore$1) {
17909    const r = ResourcePath.fromString(t, ...n);
17910    return __PRIVATE_validateCollectionPath(r), new CollectionReference(
17911      e,
17912      /* converter= */
17913      null,
17914      r
17915    );
17916  }
17917  {
17918    if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(N.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
17919    const r = e._path.child(ResourcePath.fromString(t, ...n));
17920    return __PRIVATE_validateCollectionPath(r), new CollectionReference(
17921      e.firestore,
17922      /* converter= */
17923      null,
17924      r
17925    );
17926  }
17927}
17928function collectionGroup(e, t) {
17929  if (e = __PRIVATE_cast(e, Firestore$1), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", t), t.indexOf("/") >= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
17930  return new Query(
17931    e,
17932    /* converter= */
17933    null,
17934    function __PRIVATE_newQueryForCollectionGroup(e2) {
17935      return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e2);
17936    }(t)
17937  );
17938}
17939function doc(e, t, ...n) {
17940  if (e = getModularInstance(e), // We allow omission of 'pathString' but explicitly prohibit passing in both
17941  // 'undefined' and 'null'.
17942  1 === arguments.length && (t = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", t), e instanceof Firestore$1) {
17943    const r = ResourcePath.fromString(t, ...n);
17944    return __PRIVATE_validateDocumentPath(r), new DocumentReference(
17945      e,
17946      /* converter= */
17947      null,
17948      new DocumentKey(r)
17949    );
17950  }
17951  {
17952    if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(N.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
17953    const r = e._path.child(ResourcePath.fromString(t, ...n));
17954    return __PRIVATE_validateDocumentPath(r), new DocumentReference(e.firestore, e instanceof CollectionReference ? e.converter : null, new DocumentKey(r));
17955  }
17956}
17957function refEqual(e, t) {
17958  return e = getModularInstance(e), t = getModularInstance(t), (e instanceof DocumentReference || e instanceof CollectionReference) && (t instanceof DocumentReference || t instanceof CollectionReference) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter);
17959}
17960function queryEqual(e, t) {
17961  return e = getModularInstance(e), t = getModularInstance(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter);
17962}
17963/**
17964 * @license
17965 * Copyright 2020 Google LLC
17966 *
17967 * Licensed under the Apache License, Version 2.0 (the "License");
17968 * you may not use this file except in compliance with the License.
17969 * You may obtain a copy of the License at
17970 *
17971 *   http://www.apache.org/licenses/LICENSE-2.0
17972 *
17973 * Unless required by applicable law or agreed to in writing, softw
17973are
17974 * distributed under the License is distributed on an "AS IS" BASIS,
17975 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17976 * See the License for the specific language governing permissions and
17977 * limitations under the License.
17978 */
17979const an = "AsyncQueue";
17980class __PRIVATE_AsyncQueueImpl {
17981  constructor(e = Promise.resolve()) {
17982    this.Zu = [], // Is this AsyncQueue being shut down? Once it is set to true, it will not
17983    // be changed again.
17984    this.Xu = false, // Operations scheduled to be queued in the future. Operations are
17985    // automatically removed after they are run or canceled.
17986    this.ec = [], // visible for testing
17987    this.tc = null, // Flag set while there's an outstanding AsyncQueue operation, used for
17988    // assertion sanity-checks.
17989    this.nc = false, // Enabled during shutdown on Safari to prevent future access to IndexedDB.
17990    this.rc = false, // List of TimerIds to fast-forward delays for.
17991    this.sc = [], // Backoff timer used to schedule retries for retryable operations
17992    this.F_ = new __PRIVATE_ExponentialBackoff(
17993      this,
17994      "async_queue_retry"
17995      /* TimerId.AsyncQueueRetry */
17996    ), // Visibility handler that triggers an immediate retry of all retryable
17997    // operations. Meant to speed up recovery when we regain file system access
17998    // after page comes into foreground.
17999    this.oc = () => {
18000      const e2 = getDocument();
18001      e2 && __PRIVATE_logDebug(an, "Visibility state changed to " + e2.visibilityState), this.F_.y_();
18002    }, this._c = e;
18003    const t = getDocument();
18004    t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.oc);
18005  }
18006  get isShuttingDown() {
18007    return this.Xu;
18008  }
18009  /**
18010   * Adds a new operation to the queue without waiting for it to complete (i.e.
18011   * we ignore the Promise result).
18012   */
18013  enqueueAndForget(e) {
18014    this.enqueue(e);
18015  }
18016  enqueueAndForgetEvenWhileRestricted(e) {
18017    this.ac(), // eslint-disable-next-line @typescript-eslint/no-floating-promises
18018    this.uc(e);
18019  }
18020  enterRestrictedMode(e) {
18021    if (!this.Xu) {
18022      this.Xu = true, this.rc = e || false;
18023      const t = getDocument();
18024      t && "function" == typeof t.removeEventListener && t.removeEventListener("visibilitychange", this.oc);
18025    }
18026  }
18027  enqueue(e) {
18028    if (this.ac(), this.Xu)
18029      return new Promise(() => {
18030      });
18031    const t = new __PRIVATE_Deferred();
18032    return this.uc(() => this.Xu && this.rc ? Promise.resolve() : (e().then(t.resolve, t.reject), t.promise)).then(() => t.promise);
18033  }
18034  enqueueRetryable(e) {
18035    this.enqueueAndForget(() => (this.Zu.push(e), this.cc()));
18036  }
18037  /**
18038   * Runs the next operation from the retryable queue. If the operation fails,
18039   * reschedules with backoff.
18040   */
18041  async cc() {
18042    if (0 !== this.Zu.length) {
18043      try {
18044        await this.Zu[0](), this.Zu.shift(), this.F_.reset();
18045      } catch (e) {
18046        if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;
18047        __PRIVATE_logDebug(an, "Operation failed with retryable error: " + e);
18048      }
18049      this.Zu.length > 0 && // If there are additional operations, we re-schedule `retryNextOp()`.
18050      // This is necessary to run retryable operations that failed during
18051      // their initial attempt since we don't know whether they are already
18052      // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
18053      // needs to  be re-run, we will run `op1`, `op1`, `op2` using the
18054      // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
18055      // call scheduled here.
18056      // Since `backoffAndRun()` cancels an existing backoff and schedules a
18057      // new backoff on every call, there is only ever a single additional
18058      // operation in the queue.
18059      this.F_.g_(() => this.cc());
18060    }
18061  }
18062  uc(e) {
18063    const t = this._c.then(() => (this.nc = true, e().catch((e2) => {
18064      this.tc = e2, this.nc = false;
18065      throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(e2)), e2;
18066    }).then((e2) => (this.nc = false, e2))));
18067    return this._c = t, t;
18068  }
18069  enqueueAfterDelay(e, t, n) {
18070    this.ac(), // Fast-forward delays for timerIds that have been overridden.
18071    this.sc.indexOf(e) > -1 && (t = 0);
18072    const r = DelayedOperation.createAndSchedule(this, e, t, n, (e2) => this.lc(e2));
18073    return this.ec.push(r), r;
18074  }
18075  ac() {
18076    this.tc && fail(47125, {
18077      hc: __PRIVATE_getMessageOrStack(this.tc)
18078    });
18079  }
18080  verifyOperationInProgress() {
18081  }
18082  /**
18083   * Waits until all currently queued tasks are finished executing. Delayed
18084   * operations are not run.
18085   */
18086  async Pc() {
18087    let e;
18088    do {
18089      e = this._c, await e;
18090    } while (e !== this._c);
18091  }
18092  /**
18093   * For Tests: Determine if a delayed operation with a particular TimerId
18094   * exists.
18095   */
18096  Tc(e) {
18097    for (const t of this.ec) if (t.timerId === e) return true;
18098    return false;
18099  }
18100  /**
18101   * For Tests: Runs some or all delayed operations early.
18102   *
18103   * @param lastTimerId - Delayed operations up to and including this TimerId
18104   * will be drained. Pass TimerId.All to run all delayed operations.
18105   * @returns a Promise that resolves once all operations have been run.
18106   */
18107  Ic(e) {
18108    return this.Pc().then(() => {
18109      this.ec.sort((e2, t) => e2.targetTimeMs - t.targetTimeMs);
18110      for (const t of this.ec) if (t.skipDelay(), "all" !== e && t.timerId === e) break;
18111      return this.Pc();
18112    });
18113  }
18114  /**
18115   * For Tests: Skip all subsequent delays for a timer id.
18116   */
18117  dc(e) {
18118    this.sc.push(e);
18119  }
18120  /** Called once a DelayedOperation is run or canceled. */
18121  lc(e) {
18122    const t = this.ec.indexOf(e);
18123    this.ec.splice(t, 1);
18124  }
18125}
18126function __PRIVATE_getMessageOrStack(e) {
18127  let t = e.message || "";
18128  return e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + "\n" + e.stack), t;
18129}
18130/**
18131 * @license
18132 * Copyright 2017 Google LLC
18133 *
18134 * Licensed under the Apache License, Version 2.0 (the "License");
18135 * you may not use this file except in compliance with the License.
18136 * You may obtain a copy of the License at
18137 *
18138 *   http://www.apache.org/licenses/LICENSE-2.0
18139 *
18140 * Unless required by applicable law or agreed to in writing, software
18141 * distributed under the License is distributed on an "AS IS" BASIS,
18142 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18143 * See the License for the specific language governing permissions and
18144 * limitations under the License.
18145 */
18146function __PRIVATE_isPartialObserver(e) {
18147  return function __PRIVATE_implementsAnyMethods(e2, t) {
18148    if ("object" != typeof e2 || null === e2) return false;
18149    const n = e2;
18150    for (const e3 of t) if (e3 in n && "function" == typeof n[e3]) return true;
18151    return false;
18152  }(e, ["next", "error", "complete"]);
18153}
18154class LoadBundleTask {
18155  constructor() {
18156    this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred(), this._lastProgress = {
18157      taskState: "Running",
18158      totalBytes: 0,
18159      totalDocuments: 0,
18160      bytesLoaded: 0,
18161      documentsLoaded: 0
18162    };
18163  }
18164  /**
18165   * Registers functions to listen to bundle loading progress events.
18166   * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
18167   *   each time a Firestore document is loaded from the bundle.
18168   * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
18169   *   error, and there should be no more updates after this.
18170   * @param complete - Called when the loading task is complete.
18171   */
18172  onProgress(e, t, n) {
18173    this._progressObserver = {
18174      next: e,
18175      error: t,
18176      complete: n
18177    };
18178  }
18179  /**
18180   * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
18181   *
18182   * @param onRejected - Called when an error occurs during bundle loading.
18183   */
18184  catch(e) {
18185    return this._taskCompletionResolver.promise.catch(e);
18186  }
18187  /**
18188   * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
18189   *
18190   * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
18191   *   The update will always have its `taskState` set to `"Success"`.
18192   * @param onRejected - Called when an error occurs during bundle loading.
18193   */
18194  then(e, t) {
18195    return this._taskCompletionResolver.promise.then(e, t);
18196  }
18197  /**
18198   * Notifies all observers that bundle loading has completed, with a provided
18199   * `LoadBundleTaskProgress` object.
18200   *
18201   * @private
18202   */
18203  _completeWith(e) {
18204    this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), this._taskCompletionResolver.resolve(e);
18205  }
18206  /**
18207   * Notifies all observers that bundle loading has failed, with a provided
18208   * `Error` as the reason.
18209   *
18210   * @private
18211   */
18212  _failWith(e) {
18213    this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress), this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e);
18214  }
18215  /**
18216   * Notifies a progress update of loading a bundle.
18217   * @param progress - The new progress.
18218   *
18219   * @private
18220   */
18221  _updateProgress(e) {
18222    this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e);
18223  }
18224}
18225/**
18226 * @license
18227 * Copyright 2020 Google LLC
18228 *
18229 * Licensed under the Apache License, Version 2.0 (the "License");
18230 * you may not use this file except in compliance with the License.
18231 * You may obtain a copy of the License at
18232 *
18233 *   http://www.apache.org/licenses/LICENSE-2.0
18234 *
18235 * Unless required by applicable law or agreed to in writing, software
18236 * distributed under the License is distributed on an "AS IS" BASIS,
18237 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18238 * See the License for the specific language governing permissions and
18239 * limitations under the License.
18240 */
18241const un = -1;
18242class Firestore extends Firestore$1 {
18243  /** @hideconstructor */
18244  constructor(e, t, n, r) {
18245    super(e, t, n, r), /**
18246    * Whether it's a {@link Firestore} or Firestore Lite instance.
18247    */
18248    this.type = "firestore", this._queue = new __PRIVATE_AsyncQueueImpl(), this._persistenceKey = (null == r ? void 0 : r.name) || "[DEFAULT]";
18249  }
18250  async _terminate() {
18251    if (this._firestoreClient) {
18252      const e = this._firestoreClient.terminate();
18253      this._queue = new __PRIVATE_AsyncQueueImpl(e), this._firestoreClient = void 0, await e;
18254    }
18255  }
18256}
18257function initializeFirestore(e, t, n) {
18258  n || (n = ut);
18259  const r = _getProvider(e, "firestore");
18260  if (r.isInitialized(n)) {
18261    const e2 = r.getImmediate({
18262      identifier: n
18263    }), i = r.getOptions(n);
18264    if (deepEqual(i, t)) return e2;
18265    throw new FirestoreError(N.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.");
18266  }
18267  if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new FirestoreError(N.INVALID_ARGUMENT, "cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");
18268  if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cac
18268heSizeBytes < Ot) throw new FirestoreError(N.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
18269  return t.host && isCloudWorkstation(t.host) && pingServer(t.host), r.initialize({
18270    options: t,
18271    instanceIdentifier: n
18272  });
18273}
18274function getFirestore(e, n) {
18275  const r = "object" == typeof e ? e : getApp(), i = "string" == typeof e ? e : n || ut, s = _getProvider(r, "firestore").getImmediate({
18276    identifier: i
18277  });
18278  if (!s._initialized) {
18279    const e2 = getDefaultEmulatorHostnameAndPort("firestore");
18280    e2 && connectFirestoreEmulator(s, ...e2);
18281  }
18282  return s;
18283}
18284function ensureFirestoreConfigured(e) {
18285  if (e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "The client has already been terminated.");
18286  return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient;
18287}
18288function __PRIVATE_configureFirestore(e) {
18289  var t, n, r;
18290  const i = e._freezeSettings(), s = function __PRIVATE_makeDatabaseInfo(e2, t2, n2, r2) {
18291    return new DatabaseInfo(e2, t2, n2, r2.host, r2.ssl, r2.experimentalForceLongPolling, r2.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r2.experimentalLongPollingOptions), r2.useFetchStreams, r2.isUsingEmulator);
18292  }(e._databaseId, (null === (t = e._app) || void 0 === t ? void 0 : t.options.appId) || "", e._persistenceKey, i);
18293  e._componentsProvider || (null === (n = i.localCache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (r = i.localCache) || void 0 === r ? void 0 : r._onlineComponentProvider) && (e._componentsProvider = {
18294    _offline: i.localCache._offlineComponentProvider,
18295    _online: i.localCache._onlineComponentProvider
18296  }), e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, s, e._componentsProvider && function __PRIVATE_buildComponentProvider(e2) {
18297    const t2 = null == e2 ? void 0 : e2._online.build();
18298    return {
18299      _offline: null == e2 ? void 0 : e2._offline.build(t2),
18300      _online: t2
18301    };
18302  }(e._componentsProvider));
18303}
18304function enableIndexedDbPersistence(e, t) {
18305  __PRIVATE_logWarn("enableIndexedDbPersistence() will be deprecated 
18305in the future, you can use `FirestoreSettings.cache` instead.");
18306  const n = e._freezeSettings();
18307  return __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, {
18308    build: (e2) => new __PRIVATE_IndexedDbOfflineComponentProvider(e2, n.cacheSizeBytes, null == t ? void 0 : t.forceOwnership)
18309  }), Promise.resolve();
18310}
18311async function enableMultiTabIndexedDbPersistence(e) {
18312  __PRIVATE_logWarn("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
18313  const t = e._freezeSettings();
18314  __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, {
18315    build: (e2) => new __PRIVATE_MultiTabOfflineComponentProvider(e2, t.cacheSizeBytes)
18316  });
18317}
18318function __PRIVATE_setPersistenceProviders(e, t, n) {
18319  if ((e = __PRIVATE_cast(e, Firestore))._firestoreClient || e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");
18320  if (e._componentsProvider || e._getSettings().localCache) throw new FirestoreError(N.FAILED_PRECONDITION, "SDK cache is already specified.");
18321  e._componentsProvider = {
18322    _online: t,
18323    _offline: n
18324  }, __PRIVATE_configureFirestore(e);
18325}
18326function clearIndexedDbPersistence(e) {
18327  if (e._initialized && !e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
18328  const t = new __PRIVATE_Deferred();
18329  return e._queue.enqueueAndForgetEvenWhileRestricted(async () => {
18330    try {
18331      await async function __PRIVATE_indexedDbClearPersistence(e2) {
18332        if (!__PRIVATE_SimpleDb.C()) return Promise.resolve();
18333        const t2 = e2 + qt;
18334        await __PRIVATE_SimpleDb.delete(t2);
18335      }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve();
18336    } catch (e2) {
18337      t.reject(e2);
18338    }
18339  }), t.promise;
18340}
18341function waitForPendingWrites(e) {
18342  return function __PRIVATE_firestoreClientWaitForPendingWrites(e2) {
18343    const t = new __PRIVATE_Deferred();
18344    return e2.asyncQueue.enqueueAndForget(async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e2), t)), t.promise;
18345  }(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));
18346}
18347function enableNetwork(e) {
18348  return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));
18349}
18350function disableNetwork(e) {
18351  return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)));
18352}
18353function terminate(e) {
18354  return _removeServiceInstance(e.app, "firestore", e._databaseId.database), e._delete();
18355}
18356function loadBundle(e, t) {
18357  const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), r = new LoadBundleTask();
18358  return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r;
18359}
18360function namedQuery(e, t) {
18361  return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), t).then((t2) => t2 ? new Query(e, null, t2.query) : null);
18362}
18363/**
18364 * @license
18365 * Copyright 2020 Google LLC
18366 *
18367 * Licensed under the Apache License, Version 2.0 (the "License");
18368 * you may not use this file except in compliance with the License.
18369 * You may obtain a copy of the License at
18370 *
18371 *   http://www.apache.org/licenses/LICENSE-2.0
18372 *
18373 * Unless required by applicable law or agreed to in writing, software
18374 * distributed under the License is distributed on an "AS IS" BASIS,
18375 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18376 * See the License for the specific language governing permissions and
18377 * limitations under the License.
18378 */
18379/**
18380 * @license
18381 * Copyright 2022 Google LLC
18382 *
18383 * Licensed under the Apache License, Version 2.0 (the "License");
18384 * you may not use this file except in compliance with the License.
18385 * You may obtain a copy of the License at
18386 *
18387 *   http://www.apache.org/licenses/LICENSE-2.0
18388 *
18389 * Unless required by applicable law or agreed to in writing, softw
18389are
18390 * distributed under the License is distributed on an "AS IS" BASIS,
18391 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18392 * See the License for the specific language governing permissions and
18393 * limitations under the License.
18394 */
18395class AggregateField {
18396  /**
18397   * Create a new AggregateField<T>
18398   * @param aggregateType Specifies the type of aggregation operation to perform.
18399   * @param _internalFieldPath Optionally specifies the field that is aggregated.
18400   * @internal
18401   */
18402  constructor(e = "count", t) {
18403    this._internalFieldPath = t, /** A type string to uniquely identify instances of this class. */
18404    this.type = "AggregateField", this.aggregateType = e;
18405  }
18406}
18407class AggregateQuerySnapshot {
18408  /** @hideconstructor */
18409  constructor(e, t, n) {
18410    this._userDataWriter = t, this._data = n, /** A type string to uniquely identify instances of this class. */
18411    this.type = "AggregateQuerySnapshot", this.query = e;
18412  }
18413  /**
18414   * Returns the results of the aggregations performed over the underlying
18415   * query.
18416   *
18417   * The keys of the returned object will be the same as those of the
18418   * `AggregateSpec` object specified to the aggregation method, and the values
18419   * will be the corresponding aggregation result.
18420   *
18421   * @returns The results of the aggregations performed over the underlying
18422   * query.
18423   */
18424  data() {
18425    return this._userDataWriter.convertObjectMap(this._data);
18426  }
18427}
18428/**
18429 * @license
18430 * Copyright 2020 Google LLC
18431 *
18432 * Licensed under the Apache License, Version 2.0 (the "License");
18433 * you may not use this file except in compliance with the License.
18434 * You may obtain a copy of the License at
18435 *
18436 *   http://www.apache.org/licenses/LICENSE-2.0
18437 *
18438 * Unless required by applicable law or agreed to in writing, software
18439 * distributed under the License is distributed on an "AS IS" BASIS,
18440 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18441 * See the License for the specific language governing permissions and
18442 * limitations under the License.
18443 */
18444class Bytes {
18445  /** @hideconstructor */
18446  constructor(e) {
18447    this._byteString = e;
18448  }
18449  /**
18450   * Creates a new `Bytes` object from the given Base64 string, converting it to
18451   * bytes.
18452   *
18453   * @param base64 - The Base64 string used to create the `Bytes` object.
18454   */
18455  static fromBase64String(e) {
18456    try {
18457      return new Bytes(ByteString.fromBase64String(e));
18458    } catch (e2) {
18459      throw new FirestoreError(N.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e2);
18460    }
18461  }
18462  /**
18463   * Creates a new `Bytes` object from the given Uint8Array.
18464   *
18465   * @param array - The Uint8Array used to create the `Bytes` object.
18466   */
18467  static fromUint8Array(e) {
18468    return new Bytes(ByteString.fromUint8Array(e));
18469  }
18470  /**
18471   * Returns the underlying bytes as a Base64-encoded string.
18472   *
18473   * @returns The Base64-encoded string created from the `Bytes` object.
18474   */
18475  toBase64() {
18476    return this._byteString.toBase64();
18477  }
18478  /**
18479   * Returns the underlying bytes in a new `Uint8Array`.
18480   *
18481   * @returns The Uint8Array created from the `Bytes` object.
18482   */
18483  toUint8Array() {
18484    return this._byteString.toUint8Array();
18485  }
18486  /**
18487   * Returns a string representation of the `Bytes` object.
18488   *
18489   * @returns A string representation of the `Bytes` object.
18490   */
18491  toString() {
18492    return "Bytes(base64: " + this.toBase64() + ")";
18493  }
18494  /**
18495   * Returns true if this `Bytes` object is equal to the provided one.
18496   *
18497   * @param other - The `Bytes` object to compare against.
18498   * @returns true if this `Bytes` object is equal to the provided one.
18499   */
18500  isEqual(e) {
18501    return this._byteString.isEqual(e._byteString);
18502  }
18503  /**
18504   * Returns a JSON-serializable representation of this `Bytes` instance.
18505   *
18506   * @returns a JSON representation of this object.
18507   */
18508  toJSON() {
18509    return {
18510      type: Bytes._jsonSchemaVersion,
18511      bytes: this.toBase64()
18512    };
18513  }
18514  /**
18515   * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.
18516   *
18517   * @param json a JSON object represention of a `Bytes` instance
18518   * @returns an instance of {@link Bytes}
vendor: 4,456 bytes, lines 18518-18646
18518 if the JSON object could be parsed. Throws a
18519   * {@link FirestoreError} if an error occurs.
18520   */
18521  static fromJSON(e) {
18522    if (__PRIVATE_validateJSON(e, Bytes._jsonSchema)) return Bytes.fromBase64String(e.bytes);
18523  }
18524}
18525Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = {
18526  type: property("string", Bytes._jsonSchemaVersion),
18527  bytes: property("string")
18528};
18529/**
18530 * @license
18531 * Copyright 2020 Google LLC
18532 *
18533 * Licensed under the Apache License, Version 2.0 (the "License");
18534 * you may not use this file except in compliance with the License.
18535 * You may obtain a copy of the License at
18536 *
18537 *   http://www.apache.org/licenses/LICENSE-2.0
18538 *
18539 * Unless required by applicable law or agreed to in writing, software
18540 * distributed under the License is distributed on an "AS IS" BASIS,
18541 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18542 * See the License for the specific language governing permissions and
18543 * limitations under the License.
18544 */
18545class FieldPath {
18546  /**
18547   * Creates a `FieldPath` from the provided field names. If more than one field
18548   * name is provided, the path will point to a nested field in a document.
18549   *
18550   * @param fieldNames - A list of field names.
18551   */
18552  constructor(...e) {
18553    for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
18554    this._internalPath = new FieldPath$1(e);
18555  }
18556  /**
18557   * Returns true if this `FieldPath` is equal to the provided one.
18558   *
18559   * @param other - The `FieldPath` to compare against.
18560   * @returns true if this `FieldPath` is equal to the provided one.
18561   */
18562  isEqual(e) {
18563    return this._internalPath.isEqual(e._internalPath);
18564  }
18565}
18566function documentId() {
18567  return new FieldPath(B);
18568}
18569/**
18570 * @license
18571 * Copyright 2020 Google LLC
18572 *
18573 * Licensed under the Apache License, Version 2.0 (the "License");
18574 * you may not use this file except in compliance with the License.
18575 * You may obtain a copy of the License at
18576 *
18577 *   http://www.apache.org/licenses/LICENSE-2.0
18578 *
18579 * Unless required by applicable law or agreed to in writing, software
18580 * distributed under the License is distributed on an "AS IS" BASIS,
18581 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18582 * See the License for the specific language governing permissions and
18583 * limitations under the License.
18584 */
18585class FieldValue {
18586  /**
18587   * @param _methodName - The public API endpoint that returns this class.
18588   * @hideconstructor
18589   */
18590  constructor(e) {
18591    this._methodName = e;
18592  }
18593}
18594/**
18595 * @license
18596 * Copyright 2017 Google LLC
18597 *
18598 * Licensed under the Apache License, Version 2.0 (the "License");
18599 * you may not use this file except in compliance with the License.
18600 * You may obtain a copy of the License at
18601 *
18602 *   http://www.apache.org/licenses/LICENSE-2.0
18603 *
18604 * Unless required by applicable law or agreed to in writing, software
18605 * distributed under the License is distributed on an "AS IS" BASIS,
18606 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18607 * See the License for the specific language governing permissions and
18608 * limitations under the License.
18609 */
18610class GeoPoint {
18611  /**
18612   * Creates a new immutable `GeoPoint` object with the provided latitude and
18613   * longitude values.
18614   * @param latitude - The latitude as number between -90 and 90.
18615   * @param longitude - The longitude as number between -180 and 180.
18616   */
18617  constructor(e, t) {
18618    if (!isFinite(e) || e < -90 || e > 90) throw new FirestoreError(N.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + e);
18619    if (!isFinite(t) || t < -180 || t > 180) throw new FirestoreError(N.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + t);
18620    this._lat = e, this._long = t;
18621  }
18622  /**
18623   * The latitude of this `GeoPoint` instance.
18624   */
18625  get latitude() {
18626    return this._lat;
18627  }
18628  /**
18629   * The longitude of this `GeoPoint` instance.
18630   */
18631  get longitude() {
18632    return this._long;
18633  }
18634  /**
18635   * Returns true if this `GeoPoint` is equal to the provided one.
18636   *
18637   * @param other - The `GeoPoint` to compare against.
18638   * @returns true if this `GeoPoint` is equal to the provided one.
18639   */
18640  isEqual(e) {
18641    return this._lat === e._lat && this._long === e._long;
18642  }
18643  /**
18644   * Actually private to JS consumers of our API, so this function is prefixed
18645   * with an underscore.
18646   */
18647  _compareTo(e) {
18648    return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long);
18649  }
18650  /**
18651   * Returns a JSON-serializable representation of this `GeoPoint` instance.
18652   *
18653   * @returns a JSON representation of this object.
18654   */
18655  toJSON() {
18656    return {
18657      latitude: this._lat,
18658      longitude: this._long,
18659      type: GeoPoint._jsonSchemaVersion
18660    };
18661  }
18662  /**
18663   * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.
18664   *
18665   * @param json a JSON object represention of a `GeoPoint` instance
18666   * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a
18667   * {@link FirestoreError} if an error occurs.
18668   */
18669  static fromJSON(e) {
18670    if (__PRIVATE_validateJSON(e, GeoPoint._jsonSchema)) return new GeoPoint(e.latitude, e.longitude);
18671  }
18672}
18673GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = {
18674  type: property("string", GeoPoint._jsonSchemaVersion),
18675  latitude: property("number"),
18676  longitude: property("number")
18677};
18678/**
18679 * @license
18680 * Copyright 2024 Google LLC
18681 *
18682 * Licensed under the Apache License, Version 2.0 (the "License");
18683 * you may not use this file except in compliance with the License.
18684 * You may obtain a copy of the License at
18685 *
18686 *   http://www.apache.org/licenses/LICENSE-2.0
18687 *
18688 * Unless required by applicable law or agreed to in writing, software
18689 * distributed under the License is distributed on an "AS IS" BASIS,
18690 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18691 * See the License for the specific language governing permissions and
18692 * limitations under the License.
18693 */
18694class VectorValue {
18695  /**
18696   * @private
18697   * @internal
18698   */
18699  constructor(e) {
18700    this._values = (e || []).map((e2) => e2);
18701  }
18702  /**
18703   * Returns a copy of the raw number array form of the vector.
18704   */
18705  toArray() {
18706    return this._values.map((e) => e);
18707  }
18708  /**
18709   * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.
18710   */
18711  isEqual(e) {
18712    return function __PRIVATE_isPrimitiveArrayEqual(e2, t) {
18713      if (e2.length !== t.length) return false;
18714      for (let n = 0; n < e2.length; ++n) if (e2[n] !== t[n]) return false;
18715      return true;
18716    }(this._values, e._values);
18717  }
18718  /**
18719   * Returns a JSON-serializable representation of this `VectorValue` instance.
18720   *
18721   * @returns a JSON representation of this object.
18722   */
18723  toJSON() {
18724    return {
18725      type: VectorValue._jsonSchemaVersion,
18726      vectorValues: this._values
18727    };
18728  }
18729  /**
18730   * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.
18731   *
18732   * @param json a JSON object represention of a `VectorValue` instance.
18733   * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a
18734   * {@link FirestoreError} if an error occurs.
18735   */
18736  static fromJSON(e) {
18737    if (__PRIVATE_validateJSON(e, VectorValue._jsonSchema)) {
18738      if (Array.isArray(e.vectorValues) && e.vectorValues.every((e2) => "number" == typeof e2)) return new VectorValue(e.vectorValues);
18739      throw new FirestoreError(N.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array");
18740    }
18741  }
18742}
18743VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = {
18744  type: property("string", VectorValue._jsonSchemaVersion),
18745  vectorValues: property("object")
18746};
18747/**
18748 * @license
18749 * Copyright 2017 Google LLC
18750 *
18751 * Licensed under the Apache License, Version 2.0 (the "License");
18752 * you may not use this file except in compliance with the License.
18753 * You may obtain a copy of the License at
18754 *
18755 *   http://www.apache.org/licenses/LICENSE-2.0
18756 *
18757 * Unless required by applicable law or agreed to in writing, software
18758 * distributed under the License is distributed on an "AS IS" BASIS,
18759 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18760 * See the License for the specific language governing permissions and
18761 * limitations under the License.
18762 */
18763const cn = /^__.*__$/;
18764class ParsedSetData {
18765  constructor(e, t, n) {
18766    this.data = e, this.fieldMask = t, this.fieldTransforms = n;
18767  }
18768  toMutation(e, t) {
18769    return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms);
18770  }
18771}
18772class ParsedUpdateData {
18773  constructor(e, t, n) {
18774    this.data = e, this.fieldMask = t, this.fieldTransforms = n;
18775  }
18776  toMutation(e, t) {
18777    return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms);
18778  }
18779}
18780function __PRIVATE_isWrite(e) {
18781  switch (e) {
18782    case 0:
18783    case 2:
18784    case 1:
18785      return true;
18786    case 3:
18787    case 4:
18788      return false;
18789    default:
18790      throw fail(40011, {
18791        Ec: e
18792      });
18793  }
18794}
18795class __PRIVATE_ParseContextImpl {
18796  /**
18797   * Initializes a ParseContext with the given source and path.
18798   *
18799   * @param settings - The settings for the parser.
18800   * @param databaseId - The database ID of the Firestore instance.
18801   * @param serializer - The serializer to use to generate the Value proto.
18802   * @param ignoreUndefinedProperties - Whether to ignore undefined properties
18803   * rather than throw.
18804   * @param fieldTransforms - A mutable list of field transforms encountered
18805   * while parsing the data.
18806   * @param fieldMask - A mutable list of field paths encountered while parsing
18807   * the data.
18808   *
18809   * TODO(b/34871131): We don't support array paths right now, so path can be
18810   * null to indicate the context represents any location within an array (in
18811   * which case certain features will not work and errors will be somewhat
18812   * compromised).
18813   */
18814  constructor(e, t, n, r, i, s) {
18815    this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, // Minor hack: If fieldTransforms is undefined, we assume this is an
18816    // external call and we need to validate the entire path.
18817    void 0 === i && this.Ac(), this.fieldTransforms = i || [], this.fieldMask = s || [];
18818  }
18819  get path() {
18820    return this.settings.path;
18821  }
18822  get Ec() {
18823    return this.settings.Ec;
18824  }
18825  /** Returns a new context with the specified settings overwritten. */
18826  Rc(e) {
18827    return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({}, this.settings), e), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
18828  }
18829  Vc(e) {
18830    var t;
18831    const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.Rc({
18832      path: n,
18833      mc: false
18834    });
18835    return r.fc(e), r;
18836  }
18837  gc(e) {
18838    var t;
18839    const n = null === (t = this.path) || void 0 === t ? void 0 : t.child(e), r = this.Rc({
18840      path: n,
18841      mc: false
18842    });
18843    return r.Ac(), r;
18844  }
18845  yc(e) {
18846    return this.Rc({
18847      path: void 0,
18848      mc: true
18849    });
18850  }
18851  wc(e) {
18852    return __PRIVATE_createError(e, this.settings.methodName, this.settings.Sc || false, this.path, this.settings.bc);
18853  }
18854  /** Returns 'true' if 'fieldPath' was traversed when creating this context. */
18855  contains(e) {
18856    return void 0 !== this.fieldMask.find((t) => e.isPrefixOf(t)) || void 0 !== this.fieldTransforms.find((t) => e.isPrefixOf(t.field));
18857  }
18858  Ac() {
18859    if (this.path) for (let e = 0; e < this.path.length; e++) this.fc(this.path.get(e));
18860  }
18861  fc(e) {
18862    if (0 === e.length) throw this.wc("Document fields must not be empty");
18863    if (__PRIVATE_isWrite(this.Ec) && cn.test(e)) throw this.wc('Document fields cannot begin and end with "__"');
18864  }
18865}
18866class __PRIVATE_UserDataReader {
18867  constructor(e, t, n) {
18868    this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e);
18869  }
18870  /** Creates a new top-level parse context. */
18871  Dc(e, t, n, r = false) {
18872    return new __PRIVATE_ParseContextImpl({
18873      Ec: e,
18874      methodName: t,
18875      bc: n,
18876      path: FieldPath$1.emptyPath(),
18877      mc: false,
18878      Sc: r
18879    }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
18880  }
18881}
18882function __PRIVATE_newUserDataReader(e) {
18883  const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId);
18884  return new __PRIVATE_UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n);
18885}
18886function __PRIVATE_parseSetData(e, t, n, r, i, s = {}) {
18887  const o = e.Dc(s.merge || s.mergeFields ? 2 : 0, t, n, i);
18888  __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, r);
18889  const _ = __PRIVATE_parseObject(r, o);
18890  let a, u;
18891  if (s.merge) a = new FieldMask(o.fieldMask), u = o.fieldTransforms;
18892  else if (s.mergeFields) {
18893    const e2 = [];
18894    for (const r2 of s.mergeFields) {
18895      const i2 = __PRIVATE_fieldPathFromArgument$1(t, r2, n);
18896      if (!o.contains(i2)) throw new FirestoreError(N.INVALID_ARGUMENT, `Field '${i2}' is specified in your field mask but missing from your input data.`);
18897      __PRIVATE_fieldMaskContains(e2, i2) || e2.push(i2);
18898    }
18899    a = new FieldMask(e2), u = o.fieldTransforms.filter((e3) => a.covers(e3.field));
18900  } else a = null, u = o.fieldTransforms;
18901  return new ParsedSetData(new ObjectValue(_), a, u);
18902}
18903class __PRIVATE_DeleteFieldValueImpl extends FieldValue {
18904  _toFieldTransform(e) {
18905    if (2 !== e.Ec) throw 1 === e.Ec ? e.wc(`${this._methodName}() can only appear at the top level of your update data`) : e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
18906    return e.fieldMask.push(e.path), null;
18907  }
18908  isEqual(e) {
18909    return e instanceof __PRIVATE_DeleteFieldValueImpl;
18910  }
18911}
18912function __PRIVATE_createSentinelChildContext(e, t, n) {
18913  return new __PRIVATE_ParseContextImpl({
18914    Ec: 3,
18915    bc: t.settings.bc,
18916    methodName: e._methodName,
18917    mc: n
18918  }, t.databaseId, t.serializer, t.ignoreUndefinedProperties);
18919}
18920class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue {
18921  _toFieldTransform(e) {
18922    return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform());
18923  }
18924  isEqual(e) {
18925    return e instanceof __PRIVATE_ServerTimestampFieldValueImpl;
18926  }
18927}
18928class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue {
18929  constructor(e, t) {
18930    super(e), this.vc = t;
18931  }
18932  _toFieldTransform(e) {
18933    const t = __PRIVATE_createSentinelChildContext(
18934      this,
18935      e,
18936      /*array=*/
18937      true
18938    ), n = this.vc.map((e2) => __PRIVATE_parseData(e2, t)), r = new __PRIVATE_ArrayUnionTransformOperation(n);
18939    return new FieldTransform(e.path, r);
18940  }
18941  isEqual(e) {
18942    return e instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.vc, e.vc);
18943  }
18944}
18945class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue {
18946  constructor(e, t) {
18947    super(e), this.vc = t;
18948  }
18949  _toFieldTransform(e) {
18950    const t = __PRIVATE_createSentinelChildContext(
18951      this,
18952      e,
18953      /*array=*/
18954      true
18955    ), n = this.vc.map((e2) => __PRIVATE_parseData(e2, t)), r = new __PRIVATE_ArrayRemoveTransformOperation(n);
18956    return new FieldTransform(e.path, r);
18957  }
18958  isEqual(e) {
18959    return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.vc, e.vc);
18960  }
18961}
18962class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue {
18963  constructor(e, t) {
18964    super(e), this.Cc = t;
18965  }
18966  _toFieldTransform(e) {
18967    const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.Cc));
18968    return new FieldTransform(e.path, t);
18969  }
18970  isEqual(e) {
18971    return e instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.Cc === e.Cc;
18972  }
18973}
vendor: 4,755 bytes, lines 18974-19097
18974function __PRIVATE_parseUpdateData(e, t, n, r) {
18975  const i = e.Dc(1, t, n);
18976  __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, r);
18977  const s = [], o = ObjectValue.empty();
18978  forEach(r, (e2, r2) => {
18979    const _2 = __PRIVATE_fieldPathFromDotSeparatedString(t, e2, n);
18980    r2 = getModularInstance(r2);
18981    const a = i.gc(_2);
18982    if (r2 instanceof __PRIVATE_DeleteFieldValueImpl)
18983      s.push(_2);
18984    else {
18985      const e3 = __PRIVATE_parseData(r2, a);
18986      null != e3 && (s.push(_2), o.set(_2, e3));
18987    }
18988  });
18989  const _ = new FieldMask(s);
18990  return new ParsedUpdateData(o, _, i.fieldTransforms);
18991}
18992function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, s) {
18993  const o = e.Dc(1, t, n), _ = [__PRIVATE_fieldPathFromArgument$1(t, r, n)], a = [i];
18994  if (s.length % 2 != 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);
18995  for (let e2 = 0; e2 < s.length; e2 += 2) _.push(__PRIVATE_fieldPathFromArgument$1(t, s[e2])), a.push(s[e2 + 1]);
18996  const u = [], c = ObjectValue.empty();
18997  for (let e2 = _.length - 1; e2 >= 0; --e2) if (!__PRIVATE_fieldMaskContains(u, _[e2])) {
18998    const t2 = _[e2];
18999    let n2 = a[e2];
19000    n2 = getModularInstance(n2);
19001    const r2 = o.gc(t2);
19002    if (n2 instanceof __PRIVATE_DeleteFieldValueImpl)
19003      u.push(t2);
19004    else {
19005      const e3 = __PRIVATE_parseData(n2, r2);
19006      null != e3 && (u.push(t2), c.set(t2, e3));
19007    }
19008  }
19009  const l = new FieldMask(u);
19010  return new ParsedUpdateData(c, l, o.fieldTransforms);
19011}
19012function __PRIVATE_parseQueryValue(e, t, n, r = false) {
19013  return __PRIVATE_parseData(n, e.Dc(r ? 4 : 3, t));
19014}
19015function __PRIVATE_parseData(e, t) {
19016  if (__PRIVATE_looksLikeJsonObject(
19017    // Unwrap the API type from the Compat SDK. This will return the API type
19018    // from firestore-exp.
19019    e = getModularInstance(e)
19020  )) return __PRIVATE_validatePlainObject("Unsupported field value:", t, e), __PRIVATE_parseObject(e, t);
19021  if (e instanceof FieldValue)
19022    return function __PRIVATE_parseSentinelFieldValue(e2, t2) {
19023      if (!__PRIVATE_isWrite(t2.Ec)) throw t2.wc(`${e2._methodName}() can only be used with update() and set()`);
19024      if (!t2.path) throw t2.wc(`${e2._methodName}() is not currently supported inside arrays`);
19025      const n = e2._toFieldTransform(t2);
19026      n && t2.fieldTransforms.push(n);
19027    }(e, t), null;
19028  if (void 0 === e && t.ignoreUndefinedProperties)
19029    return null;
19030  if (
19031    // If context.path is null we are inside an array and we don't support
19032    // field mask paths more granular than the top-level array.
19033    t.path && t.fieldMask.push(t.path), e instanceof Array
19034  ) {
19035    if (t.settings.mc && 4 !== t.Ec) throw t.wc("Nested arrays are not supported");
19036    return function __PRIVATE_parseArray(e2, t2) {
19037      const n = [];
19038      let r = 0;
19039      for (const i of e2) {
19040        let e3 = __PRIVATE_parseData(i, t2.yc(r));
19041        null == e3 && // Just include nulls in the array for fields being replaced with a
19042        // sentinel.
19043        (e3 = {
19044          nullValue: "NULL_VALUE"
19045        }), n.push(e3), r++;
19046      }
19047      return {
19048        arrayValue: {
19049          values: n
19050        }
19051      };
19052    }(e, t);
19053  }
19054  return function __PRIVATE_parseScalarValue(e2, t2) {
19055    if (null === (e2 = getModularInstance(e2))) return {
19056      nullValue: "NULL_VALUE"
19057    };
19058    if ("number" == typeof e2) return toNumber(t2.serializer, e2);
19059    if ("boolean" == typeof e2) return {
19060      booleanValue: e2
19061    };
19062    if ("string" == typeof e2) return {
19063      stringValue: e2
19064    };
19065    if (e2 instanceof Date) {
19066      const n = Timestamp.fromDate(e2);
19067      return {
19068        timestampValue: toTimestamp(t2.serializer, n)
19069      };
19070    }
19071    if (e2 instanceof Timestamp) {
19072      const n = new Timestamp(e2.seconds, 1e3 * Math.floor(e2.nanoseconds / 1e3));
19073      return {
19074        timestampValue: toTimestamp(t2.serializer, n)
19075      };
19076    }
19077    if (e2 instanceof GeoPoint) return {
19078      geoPointValue: {
19079        latitude: e2.latitude,
19080        longitude: e2.longitude
19081      }
19082    };
19083    if (e2 instanceof Bytes) return {
19084      bytesValue: __PRIVATE_toBytes(t2.serializer, e2._byteString)
19085    };
19086    if (e2 instanceof DocumentReference) {
19087      const n = t2.databaseId, r = e2.firestore._databaseId;
19088      if (!r.isEqual(n)) throw t2.wc(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);
19089      return {
19090        referenceValue: __PRIVATE_toResourceName(e2.firestore._databaseId || t2.databaseId, e2._key.path)
19091      };
19092    }
19093    if (e2 instanceof VectorValue)
19094      return function __PRIVATE_parseVectorValue(e3, t3) {
19095        const n = {
19096          fields: {
19097            [ct]: {
19098              stringValue: Pt
19099            },
19100            [Tt]: {
19101              arrayValue: {
19102                values: e3.toArray().map((e4) => {
19103                  if ("number" != typeof e4) throw t3.wc("VectorValues must only contain numeric values.");
19104                  return __PRIVATE_toDouble(t3.serializer, e4);
19105                })
19106              }
19107            }
19108          }
19109        };
19110        return {
19111          mapValue: n
19112        };
19113      }(e2, t2);
19114    throw t2.wc(`Unsupported field value: ${__PRIVATE_valueDescription(e2)}`);
19115  }(e, t);
19116}
19117function __PRIVATE_parseObject(e, t) {
19118  const n = {};
19119  return isEmpty(e) ? (
19120    // If we encounter an empty object, we explicitly add it to the update
19121    // mask to ensure that the server creates a map entry.
19122    t.path && t.path.length > 0 && t.fieldMask.push(t.path)
19123  ) : forEach(e, (e2, r) => {
19124    const i = __PRIVATE_parseData(r, t.Vc(e2));
19125    null != i && (n[e2] = i);
19126  }), {
19127    mapValue: {
19128      fields: n
19129    }
19130  };
19131}
19132function __PRIVATE_looksLikeJsonObject(e) {
19133  return !("object" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof DocumentReference || e instanceof FieldValue || e instanceof VectorValue);
19134}
19135function __PRIVATE_validatePlainObject(e, t, n) {
19136  if (!__PRIVATE_looksLikeJsonObject(n) || !__PRIVATE_isPlainObject(n)) {
19137    const r = __PRIVATE_valueDescription(n);
19138    throw "an object" === r ? t.wc(e + " a custom object") : t.wc(e + " " + r);
19139  }
19140}
19141function __PRIVATE_fieldPathFromArgument$1(e, t, n) {
19142  if (
19143    // If required, replace the FieldPath Compat class with the firestore-exp
19144    // FieldPath.
19145    (t = getModularInstance(t)) instanceof FieldPath
19146  ) return t._internalPath;
19147  if ("string" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t);
19148  throw __PRIVATE_createError(
19149    "Field path arguments must be of type string or ",
19150    e,
19151    /* hasConverter= */
19152    false,
19153    /* path= */
19154    void 0,
19155    n
19156  );
19157}
19158const ln = new RegExp("[~\\*/\\[\\]]");
19159function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) {
19160  if (t.search(ln) >= 0) throw __PRIVATE_createError(
19161    `Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,
19162    e,
19163    /* hasConverter= */
19164    false,
19165    /* path= */
19166    void 0,
19167    n
19168  );
19169  try {
19170    return new FieldPath(...t.split("."))._internalPath;
19171  } catch (r) {
19172    throw __PRIVATE_createError(
19173      `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,
19174      e,
19175      /* hasConverter= */
19176      false,
19177      /* path= */
19178      void 0,
19179      n
19180    );
19181  }
19182}
19183function __PRIVATE_createError(e, t, n, r, i) {
19184  const s = r && !r.isEmpty(), o = void 0 !== i;
19185  let _ = `Function ${t}() called with invalid data`;
19186  n && (_ += " (via `toFirestore()`)"), _ += ". ";
19187  let a = "";
19188  return (s || o) && (a += " (found", s && (a += ` in field ${r}`), o && (a += ` in document ${i}`), a += ")"), new FirestoreError(N.INVALID_ARGUMENT, _ + e + a);
19189}
19190function __PRIVATE_fieldMaskContains(e, t) {
19191  return e.some((e2) => e2.isEqual(t));
19192}
19193/**
19194 * @license
19195 * Copyright 2020 Google LLC
19196 *
19197 * Licensed under the Apache License, Version 2.0 (the "License");
19198 * you may not use this file except in compliance with the License.
19199 * You may obtain a copy of the License at
19200 *
19201 *   http://www.apache.org/licenses/LICENSE-2.0
19202 *
19203 * Unless required by applicable law or agreed to in writing, software
19204 * distributed under the License is distributed on an "AS IS" BASIS,
19205 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19206 * See the License for the specific language governing permissions and
19207 * limitations under the License.
19208 */
19209class DocumentSnapshot$1 {
19210  // Note: This class is stripped down version of the DocumentSnapshot in
19211  // the legacy SDK. The changes are:
19212  // - No support for SnapshotMetadata.
19213  // - No support for SnapshotOptions.
19214  /** @hideconstructor protected */
19215  constructor(e, t, n, r, i) {
19216    this._firestore = e, this._userDataWriter = t, this._key = n, this._document = r, this._converter = i;
19217  }
19218  /** Property of the `DocumentSnapshot` that provides the document's ID. */
19219  get id() {
19220    return this._key.path.lastSegment();
19221  }
19222  /**
19223   * The `DocumentReference` for the document included in the `DocumentSnapshot`.
19224   */
19225  get ref() {
19226    return new DocumentReference(this._firestore, this._converter, this._key);
19227  }
19228  /**
19229   * Signals whether or not the document at the snapshot's location exists.
19230   *
19231   * @returns true if the document exists.
19232   */
19233  exists() {
19234    return null !== this._document;
19235  }
19236  /**
19237   * Retrieves all fields in the document as an `Object`. Returns `undefined` if
19238   * the document doesn't exist.
19239   *
19240   * @returns An `Object` containing all fields in the document or `undefined`
19241   * if the document doesn't exist.
19242   */
19243  data() {
19244    if (this._document) {
19245      if (this._converter) {
19246        const e = new QueryDocumentSnapshot$1(
19247          this._firestore,
19248          this._userDataWriter,
19249          this._key,
19250          this._document,
19251          /* converter= */
19252          null
19253        );
19254        return this._converter.fromFirestore(e);
19255      }
19256      return this._userDataWriter.convertValue(this._document.data.value);
19257    }
19258  }
19259  /**
19260   * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
19261   * document or field doesn't exist.
19262   *
19263   * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
19264   * field.
19265   * @returns The data at the specified field location or undefined if no such
19266   * field exists in the document.
19267   */
19268  // We are using `any` here to avoid an explicit cast by our users.
19269  // eslint-disable-next-line @typescript-eslint/no-explicit-any
19270  get(e) {
19271    if (this._document) {
19272      const t = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e));
19273      if (null !== t) return this._userDataWriter.convertValue(t);
19274    }
19275  }
19276}
19277class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 {
19278  /**
19279   * Retrieves all fields in the document as an `Object`.
19280   *
19281   * @override
19282   * @returns An `Object` containing all fields in the document.
19283   */
19284  data() {
19285    return super.data();
19286  }
19287}
19288function __PRIVATE_fieldPathFromArgument(e, t) {
19289  return "string" == typeof t ? __PRIVATE_fieldPathFromDotSeparatedString(e, t) : t instanceof FieldPath ? t._internalPath : t._delegate._internalPath;
19290}
19291/**
19292 * @license
19293 * Copyright 2020 Google LLC
19294 *
19295 * Licensed under the Apache License, Version 2.0 (the "License");
19296 * you may not use this file except in compliance with the License.
19297 * You may obtain a copy of the License at
19298 *
19299 *   http://www.apache.org/licenses/LICENSE-2.0
19300 *
19301 * Unless required by applicable law or agreed to in writing, software
19302 * distributed under the License is distributed on an "AS IS" BASIS,
19303 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19304 * See the License for the specific language governing permissions and
19305 * limitations under the License.
19306 */
19307function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e) {
19308  if ("L" === e.limitType && 0 === e.explicitOrderBy.length) throw new FirestoreError(N.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
19309}
19310class AppliableConstraint {
19311}
19312class QueryConstraint extends AppliableConstraint {
19313}
19314function query(e, t, ...n) {
19315  let r = [];
19316  t instanceof AppliableConstraint && r.push(t), r = r.concat(n), function __PRIVATE_validateQueryConstraintArray(e2) {
19317    const t2 = e2.filter((e3) => e3 instanceof QueryCompositeFilterConstraint).length, n2 = e2.filter((e3) => e3 instanceof QueryFieldFilterConstraint).length;
19318    if (t2 > 1 || t2 > 0 && n2 > 0) throw new FirestoreError(N.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");
19319  }(r);
19320  for (const t2 of r) e = t2._apply(e);
19321  return e;
19322}
19323class QueryFieldFilterConstraint extends QueryConstraint {
19324  /**
19325   * @internal
19326   */
19327  constructor(e, t, n) {
19328    super(), this._field = e, this._op = t, this._value = n, /** The type of this query constraint */
19329    this.type = "where";
19330  }
19331  static _create(e, t, n) {
19332    return new QueryFieldFilterConstraint(e, t, n);
19333  }
19334  _apply(e) {
19335    const t = this._parse(e);
19336    return __PRIVATE_validateNewFieldFilter(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t));
19337  }
19338  _parse(e) {
19339    const t = __PRIVATE_newUserDataReader(e.firestore), n = function __PRIVATE_newQueryFilter(e2, t2, n2, r, i, s, o) {
19340      let _;
19341      if (i.isKeyField()) {
19342        if ("array-contains" === s || "array-contains-any" === s) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s}' queries on documentId().`);
19343        if ("in" === s || "not-in" === s) {
19344          __PRIVATE_validateDisjunctiveFilterElements(o, s);
19345          const t3 = [];
19346          for (const n3 of o) t3.push(__PRIVATE_parseDocumentIdValue(r, e2, n3));
19347          _ = {
19348            arrayValue: {
19349              values: t3
19350            }
19351          };
19352        } else _ = __PRIVATE_parseDocumentIdValue(r, e2, o);
19353      }
vendor: 6,102 bytes, lines 19353-19533
19353 else "in" !== s && "not-in" !== s && "array-contains-any" !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), _ = __PRIVATE_parseQueryValue(
19354        n2,
19355        t2,
19356        o,
19357        /* allowArrays= */
19358        "in" === s || "not-in" === s
19359      );
19360      const a = FieldFilter.create(i, s, _);
19361      return a;
19362    }(e._query, "where", t, e.firestore._databaseId, this._field, this._op, this._value);
19363    return n;
19364  }
19365}
19366function where(e, t, n) {
19367  const r = t, i = __PRIVATE_fieldPathFromArgument("where", e);
19368  return QueryFieldFilterConstraint._create(i, r, n);
19369}
19370class QueryCompositeFilterConstraint extends AppliableConstraint {
19371  /**
19372   * @internal
19373   */
19374  constructor(e, t) {
19375    super(), this.type = e, this._queryConstraints = t;
19376  }
19377  static _create(e, t) {
19378    return new QueryCompositeFilterConstraint(e, t);
19379  }
19380  _parse(e) {
19381    const t = this._queryConstraints.map((t2) => t2._parse(e)).filter((e2) => e2.getFilters().length > 0);
19382    return 1 === t.length ? t[0] : CompositeFilter.create(t, this._getOperator());
19383  }
19384  _apply(e) {
19385    const t = this._parse(e);
19386    return 0 === t.getFilters().length ? e : (function __PRIVATE_validateNewFilter(e2, t2) {
19387      let n = e2;
19388      const r = t2.getFlattenedFilters();
19389      for (const e3 of r) __PRIVATE_validateNewFieldFilter(n, e3), n = __PRIVATE_queryWithAddedFilter(n, e3);
19390    }(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t)));
19391  }
19392  _getQueryConstraints() {
19393    return this._queryConstraints;
19394  }
19395  _getOperator() {
19396    return "and" === this.type ? "and" : "or";
19397  }
19398}
19399function or(...e) {
19400  return e.forEach((e2) => __PRIVATE_validateQueryFilterConstraint("or", e2)), QueryCompositeFilterConstraint._create("or", e);
19401}
19402function and(...e) {
19403  return e.forEach((e2) => __PRIVATE_validateQueryFilterConstraint("and", e2)), QueryCompositeFilterConstraint._create("and", e);
19404}
19405class QueryOrderByConstraint extends QueryConstraint {
19406  /**
19407   * @internal
19408   */
19409  constructor(e, t) {
19410    super(), this._field = e, this._direction = t, /** The type of this query constraint */
19411    this.type = "orderBy";
19412  }
19413  static _create(e, t) {
19414    return new QueryOrderByConstraint(e, t);
19415  }
19416  _apply(e) {
19417    const t = function __PRIVATE_newQueryOrderBy(e2, t2, n) {
19418      if (null !== e2.startAt) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
19419      if (null !== e2.endAt) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
19420      const r = new OrderBy(t2, n);
19421      return r;
19422    }(e._query, this._field, this._direction);
19423    return new Query(e.firestore, e.converter, function __PRIVATE_queryWithAddedOrderBy(e2, t2) {
19424      const n = e2.explicitOrderBy.concat([t2]);
19425      return new __PRIVATE_QueryImpl(e2.path, e2.collectionGroup, n, e2.filters.slice(), e2.limit, e2.limitType, e2.startAt, e2.endAt);
19426    }(e._query, t));
19427  }
19428}
19429function orderBy(e, t = "asc") {
19430  const n = t, r = __PRIVATE_fieldPathFromArgument("orderBy", e);
19431  return QueryOrderByConstraint._create(r, n);
19432}
19433class QueryLimitConstraint extends QueryConstraint {
19434  /**
19435   * @internal
19436   */
19437  constructor(e, t, n) {
19438    super(), this.type = e, this._limit = t, this._limitType = n;
19439  }
19440  static _create(e, t, n) {
19441    return new QueryLimitConstraint(e, t, n);
19442  }
19443  _apply(e) {
19444    return new Query(e.firestore, e.converter, __PRIVATE_queryWithLimit(e._query, this._limit, this._limitType));
19445  }
19446}
19447function limit(e) {
19448  return __PRIVATE_validatePositiveNumber("limit", e), QueryLimitConstraint._create(
19449    "limit",
19450    e,
19451    "F"
19452    /* LimitType.First */
19453  );
19454}
19455function limitToLast(e) {
19456  return __PRIVATE_validatePositiveNumber("limitToLast", e), QueryLimitConstraint._create(
19457    "limitToLast",
19458    e,
19459    "L"
19460    /* LimitType.Last */
19461  );
19462}
19463class QueryStartAtConstraint extends QueryConstraint {
19464  /**
19465   * @internal
19466   */
19467  constructor(e, t, n) {
19468    super(), this.type = e, this._docOrFields = t, this._inclusive = n;
19469  }
19470  static _create(e, t, n) {
19471    return new QueryStartAtConstraint(e, t, n);
19472  }
19473  _apply(e) {
19474    const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);
19475    return new Query(e.firestore, e.converter, function __PRIVATE_queryWithStartAt(e2, t2) {
19476      return new __PRIVATE_QueryImpl(e2.path, e2.collectionGroup, e2.explicitOrderBy.slice(), e2.filters.slice(), e2.limit, e2.limitType, t2, e2.endAt);
19477    }(e._query, t));
19478  }
19479}
19480function startAt(...e) {
19481  return QueryStartAtConstraint._create(
19482    "startAt",
19483    e,
19484    /*inclusive=*/
19485    true
19486  );
19487}
19488function startAfter(...e) {
19489  return QueryStartAtConstraint._create(
19490    "startAfter",
19491    e,
19492    /*inclusive=*/
19493    false
19494  );
19495}
19496class QueryEndAtConstraint extends QueryConstraint {
19497  /**
19498   * @internal
19499   */
19500  constructor(e, t, n) {
19501    super(), this.type = e, this._docOrFields = t, this._inclusive = n;
19502  }
19503  static _create(e, t, n) {
19504    return new QueryEndAtConstraint(e, t, n);
19505  }
19506  _apply(e) {
19507    const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive);
19508    return new Query(e.firestore, e.converter, function __PRIVATE_queryWithEndAt(e2, t2) {
19509      return new __PRIVATE_QueryImpl(e2.path, e2.collectionGroup, e2.explicitOrderBy.slice(), e2.filters.slice(), e2.limit, e2.limitType, e2.startAt, t2);
19510    }(e._query, t));
19511  }
19512}
19513function endBefore(...e) {
19514  return QueryEndAtConstraint._create(
19515    "endBefore",
19516    e,
19517    /*inclusive=*/
19518    false
19519  );
19520}
19521function endAt(...e) {
19522  return QueryEndAtConstraint._create(
19523    "endAt",
19524    e,
19525    /*inclusive=*/
19526    true
19527  );
19528}
19529function __PRIVATE_newQueryBoundFromDocOrFields(e, t, n, r) {
19530  if (n[0] = getModularInstance(n[0]), n[0] instanceof DocumentSnapshot$1) return function __PRIVATE_newQueryBoundFromDocument(e2, t2, n2, r2, i) {
19531    if (!r2) throw new FirestoreError(N.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n2}().`);
19532    const s = [];
19533    for (const n3 of __PRIVATE_queryNormalizedOrderBy(e2)) if (n3.f
vendor: 4,663 bytes, lines 19533-19612
19533ield.isKeyField()) s.push(__PRIVATE_refValue(t2, r2.key));
19534    else {
19535      const e3 = r2.data.field(n3.field);
19536      if (__PRIVATE_isServerTimestamp(e3)) throw new FirestoreError(N.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n3.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
19537      if (null === e3) {
19538        const e4 = n3.field.canonicalString();
19539        throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e4}' (used as the orderBy) does not exist.`);
19540      }
19541      s.push(e3);
19542    }
19543    return new Bound(s, i);
19544  }(e._query, e.firestore._databaseId, t, n[0]._document, r);
19545  {
19546    const i = __PRIVATE_newUserDataReader(e.firestore);
19547    return function __PRIVATE_newQueryBoundFromFields(e2, t2, n2, r2, i2, s) {
19548      const o = e2.explicitOrderBy;
19549      if (i2.length > o.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Too many arguments provided to ${r2}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
19550      const _ = [];
19551      for (let s2 = 0; s2 < i2.length; s2++) {
19552        const a = i2[s2];
19553        if (o[s2].field.isKeyField()) {
19554          if ("string" != typeof a) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r2}(), but got a ${typeof a}`);
19555          if (!__PRIVATE_isCollectionGroupQuery(e2) && -1 !== a.indexOf("/")) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r2}() must be a plain document ID, but '${a}' contains a slash.`);
19556          const n3 = e2.path.child(ResourcePath.fromString(a));
19557          if (!DocumentKey.isDocumentKey(n3)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r2}() must result in a valid document path, but '${n3}' is not because it contains an odd number of segments.`);
19558          const i3 = new DocumentKey(n3);
19559          _.push(__PRIVATE_refValue(t2, i3));
19560        } else {
19561          const e3 = __PRIVATE_parseQueryValue(n2, r2, a);
19562          _.push(e3);
19563        }
19564      }
19565      return new Bound(_, s);
19566    }(e._query, e.firestore._databaseId, i, t, n, r);
19567  }
19568}
19569function __PRIVATE_parseDocumentIdValue(e, t, n) {
19570  if ("string" == typeof (n = getModularInstance(n))) {
19571    if ("" === n) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
19572    if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== n.indexOf("/")) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
19573    const r = t.path.child(ResourcePath.fromString(n));
19574    if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);
19575    return __PRIVATE_refValue(e, new DocumentKey(r));
19576  }
19577  if (n instanceof DocumentReference) return __PRIVATE_refValue(e, n._key);
19578  throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n)}.`);
19579}
19580function __PRIVATE_validateDisjunctiveFilterElements(e, t) {
19581  if (!Array.isArray(e) || 0 === e.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);
19582}
19583function __PRIVATE_validateNewFieldFilter(e, t) {
19584  const n = function __PRIVATE_findOpInsideFilters(e2, t2) {
19585    for (const n2 of e2) for (const e3 of n2.getFlattenedFilters()) if (t2.indexOf(e3.op) >= 0) return e3.op;
19586    return null;
19587  }(e.filters, function __PRIVATE_conflictingOps(e2) {
19588    switch (e2) {
19589      case "!=":
19590        return [
19591          "!=",
19592          "not-in"
19593          /* Operator.NOT_IN */
19594        ];
19595      case "array-contains-any":
19596      case "in":
19597        return [
19598          "not-in"
19599          /* Operator.NOT_IN */
19600        ];
19601      case "not-in":
19602        return [
19603          "array-contains-any",
19604          "in",
19605          "not-in",
19606          "!="
19607          /* Operator.NOT_EQUAL */
19608        ];
19609      default:
19610        return [];
19611    }
19612  }
19612(t.op));
19613  if (null !== n)
19614    throw n === t.op ? new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t.op.toString()}' filter.`) : new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`);
19615}
19616function __PRIVATE_validateQueryFilterConstraint(e, t) {
19617  if (!(t instanceof QueryFieldFilterConstraint || t instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
19618}
19619class AbstractUserDataWriter {
19620  convertValue(e, t = "none") {
19621    switch (__PRIVATE_typeOrder(e)) {
19622      case 0:
19623        return null;
19624      case 1:
19625        return e.booleanValue;
19626      case 2:
19627        return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);
19628      case 3:
19629        return this.convertTimestamp(e.timestampValue);
19630      case 4:
19631        return this.convertServerTimestamp(e, t);
19632      case 5:
19633        return e.stringValue;
19634      case 6:
19635        return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));
19636      case 7:
19637        return this.convertReference(e.referenceValue);
19638      case 8:
19639        return this.convertGeoPoint(e.geoPointValue);
19640      case 9:
19641        return this.convertArray(e.arrayValue, t);
19642      case 11:
19643        return this.convertObject(e.mapValue, t);
19644      case 10:
19645        return this.convertVectorValue(e.mapValue);
19646      default:
19647        throw fail(62114, {
19648          value: e
19649        });
19650    }
19651  }
19652  convertObject(e, t) {
19653    return this.convertObjectMap(e.fields, t);
19654  }
19655  /**
19656   * @internal
19657   */
19658  convertObjectMap(e, t = "none") {
19659    const n = {};
19660    return forEach(e, (e2, r) => {
19661      n[e2] = this.convertValue(r, t);
19662    }), n;
19663  }
19664  /**
19665   * @internal
19666   */
19667  convertVectorValue(e) {
19668    var t, n, r;
19669    const i = null === (r = null === (n = null === (t = e.fields) || void 0 === t ? void 0 : t[Tt].arrayValue) || void 0 === n ? void 0 : n.values) || void 0 === r ? void 0 : r.map((e2) => __PRIVATE_normalizeNumber(e2.doubleValue));
19670    return new VectorValue(i);
19671  }
19672  convertGeoPoint(e) {
19673    return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude));
19674  }
19675  convertArray(e, t) {
19676    return (e.values || []).map((e2) => this.convertValue(e2, t));
19677  }
19678  convertServerTimestamp(e, t) {
19679    switch (t) {
19680      case "previous":
19681        const n = __PRIVATE_getPreviousValue(e);
19682        return null == n ? null : this.convertValue(n, t);
19683      case "estimate":
19684        return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));
19685      default:
19686        return null;
19687    }
19688  }
19689  convertTimestamp(e) {
19690    const t = __PRIVATE_normalizeTimestamp(e);
19691    return new Timestamp(t.seconds, t.nanos);
19692  }
19693  convertDocumentKey(e, t) {
19694    const n = ResourcePath.fromString(e);
19695    __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n), 9688, {
19696      name: e
19697    });
19698    const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5));
19699    return r.isEqual(t) || // TODO(b/64130202): Somehow support foreign references.
19700    __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`), i;
19701  }
19702}
19703/**
19704 * @license
19705 * Copyright 2020 Google LLC
19706 *
19707 * Licensed under the Apache License, Version 2.0 (the "License");
19708 * you may not use this file except in compliance with the License.
19709 * You may obtain a copy of the License at
19710 *
19711 *   http://www.apache.org/licenses/LICENSE-2.0
19712 *
19713 * Unless required by applicable law or agreed to in writing, software
19714 * distributed under the License is distributed on an "AS IS" BASIS,
19715 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19716 * See the License for the specific language governing permissions and
19717 * limitations under the License.
19718 */
19719function __PRIVATE_applyFirestoreDataConverter(e, t, n) {
19720  let r;
19721  return r = e ? n && (n.merge || n.mergeFields) ? e.toFirestore(t, n) : e.toFirestore(t) : t, r;
19722}
19723class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter {
19724  constructor(e) {
19725    super(), this.firestore = e;
19726  }
19727  convertBytes(e) {
19728    return new Bytes(e);
19729  }
19730  convertReference(e) {
19731    const t = this.convertDocumentKey(e, this.firestore._databaseId);
19732    return new DocumentReference(
19733      this.firestore,
19734      /* converter= */
19735      null,
19736      t
19737    );
19738  }
19739}
19740/**
19741 * @license
19742 * Copyright 2022 Google LLC
19743 *
19744 * Licensed under the Apache License, Version 2.0 (the "License");
19745 * you may not use this file except in compliance with the License.
19746 * You may obtain a copy of the License at
19747 *
19748 *   http://www.apache.org/licenses/LICENSE-2.0
19749 *
19750 * Unless required by applicable law or agreed to in writing, software
19751 * distributed under the License is distributed on an "AS IS" BASIS,
19752 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19753 * See the License for the specific language governing permissions and
19754 * limitations under the License.
19755 */
19756function sum(e) {
19757  return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", e));
19758}
19759function average(e) {
19760  return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", e));
19761}
19762function count() {
19763  return new AggregateField("count");
19764}
19765function aggregateFieldEqual(e, t) {
19766  var n, r;
19767  return e instanceof AggregateField && t instanceof AggregateField && e.aggregateType === t.aggregateType && (null === (n = e._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (r = t._internalFieldPath) || void 0 === r ? void 0 : r.canonicalString());
19768}
19769function aggregateQuerySnapshotEqual(e, t) {
19770  return queryEqual(e.query, t.query) && deepEqual(e.data(), t.data());
19771}
19772/**
19773 * @license
19774 * Copyright 2025 Google LLC
19775 *
19776 * Licensed under the Apache License, Version 2.0 (the "License");
19777 * you may not use this file except in compliance with the License.
19778 * You may obtain a copy of the License at
19779 *
19780 *   http://www.apache.org/licenses/LICENSE-2.0
19781 *
19782 * Unless required by applicable law or agreed to in writing, software
19783 * distributed under the License is distributed on an "AS IS" BASIS,
19784 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19785 * See the License for the specific language governing permissions and
19786 * limitations under the License.
19787 */
19788/**
19789 * @license
19790 * Copyright 2020 Google LLC
19791 *
19792 * Licensed under the Apache License, Version 2.0 (the "License");
19793 * you may not use this file except in compliance with the License.
19794 * You may obtain a copy of the License at
19795 *
19796 *   http://www.apache.org/licenses/LICENSE-2.0
19797 *
19798 * Unless required by applicable law or agreed to in writing, software
19799 * distributed under the License is distributed on an "AS IS" BASIS,
19800 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19801 * See the License for the specific language governing permissions and
19802 * limitations under the License.
19803 */
19804const hn = "NOT SUPPORTED";
19805class SnapshotMetadata {
19806  /** @hideconstructor */
19807  constructor(e, t) {
19808    this.hasPendingWrites = e, this.fromCache = t;
19809  }
19810  /**
19811   * Returns true if this `SnapshotMetadata` is equal to the provided one.
19812   *
19813   * @param other - The `SnapshotMetadata` to compare against.
19814   * @returns true if this `SnapshotMetadata` is equal to the provided one.
19815   */
19816  isEqual(e) {
19817    return this.hasPendingWrites === e.hasPendingWrites && this.fromCache === e.fromCache;
19818  }
19819}
19820class DocumentSnapshot extends DocumentSnapshot$1 {
19821  /** @hideconstructor protected */
19822  constructor(e, t, n, r, i, s) {
19823    super(e, t, n, r, s), this._firestore = e, this._firestoreImpl = e, this.metadata = i;
19824  }
19825  /**
19826   * Returns whether or not the data exists. True if the document exists.
19827   */
19828  exists() {
19829    return super.exists();
19830  }
19831  /**
19832   * Retrieves all fields in the document as an `Object`. Returns `undefined` if
19833   * the document doesn't exist.
19834   *
19835   * By default, `serverTimestamp()` values that have not yet been
19836   * set to their final value will be returned as `null`. You can override
19837   * this by passing an options object.
19838   *
19839   * @param options - An options object to configure how data is retrieved from
19840   * the snapshot (for example the desired behavior for server timestamps that
19841   * have not yet been set to their final value).
19842   * @returns An `Object` containing all fields in the document or `undefined` if
19843   * the document doesn't exist.
19844   */
19845  data(e = {}) {
19846    if (this._document) {
19847      if (this._converter) {
19848        const t = new QueryDocumentSnapshot(
19849          this._firestore,
19850          this._userDataWriter,
19851          this._key,
19852          this._document,
19853          this.metadata,
19854          /* converter= */
19855          null
19856        );
19857        return this._converter.fromFirestore(t, e);
19858      }
19859      return this._userDataWriter.convertValue(this._document.data.value, e.serverTimestamps);
19860    }
19861  }
19862  /**
19863   * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
19864   * document or field doesn't exist.
19865   *
19866   * By default, a `serverTimestamp()` that has not yet been set to
19867   * its final value will be returned as `null`. You can override this by
19868   * passing an options object.
19869   *
19870   * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
19871   * field.
19872   * @param options - An options object to configure how the field is retrieved
19873   * from the snapshot (for example the desired behavior for server timestamps
19874   * that have not yet been set to their final value).
19875   * @returns The data at the specified field location or undefined if no such
19876   * field exists in the document.
19877   */
19878  // We are using `any` here to avoid an explicit cast by our users.
19879  // eslint-disable-next-line @typescript-eslint/no-explicit-any
19880  get(e, t = {}) {
19881    if (this._document) {
19882      const n = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e));
19883      if (null !== n) return this._userDataWriter.convertValue(n, t.serverTimestamps);
19884    }
19885  }
19886  /**
19887   * Returns a JSON-serializable representation of this `DocumentSnapshot` instance.
19888   *
19889   * @returns a JSON representation of this object.  Throws a {@link FirestoreError} if this
19890   * `DocumentSnapshot` has pending writes.
19891   */
19892  toJSON() {
19893    if (this.metadata.hasPendingWrites) throw new FirestoreError(N.FAILED_PRECONDITION, "DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");
19894    const e = this._document, t = {};
19895    if (t.type = DocumentSnapshot._jsonSchemaVersion, t.bundle = "", t.bundleSource = "DocumentSnapshot", t.bundleName = this._key.toString(), !e || !e.isValidDocument() || !e.isFoundDocument()) return t;
19896    this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields, "previous");
19897    return t.bundle = (this._firestore, this.ref.path, "NOT SUPPORTED"), t;
19898  }
19899}
19900function documentSnapshotFromJSON(e, t, n) {
19901  if (__PRIVATE_validateJSON(t, DocumentSnapshot._jsonSchema)) {
19902    if (t.bundle === hn) throw new FirestoreError(N.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported.");
19903    const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Ku(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r);
19904    for (const e2 of s) o.Wa(e2);
19905    const _ = o.documents;
19906    if (1 !== _.length) throw new FirestoreError(N.INVALID_ARGUMENT, `E
19906xpected bundle data to contain 1 document, but it contains ${_.length} documents.`);
19907    const a = __PRIVATE_fromDocument(r, _[0].document), u = new DocumentKey(ResourcePath.fromString(t.bundleName));
19908    return new DocumentSnapshot(e, new __PRIVATE_LiteUserDataWriter(e), u, a, new SnapshotMetadata(
19909      /* hasPendingWrites= */
19910      false,
19911      /* fromCache= */
19912      false
19913    ), n || null);
19914  }
19915}
19916DocumentSnapshot._jsonSchemaVersion = "firestore/documentSnapshot/1.0", DocumentSnapshot._jsonSchema = {
19917  type: property("string", DocumentSnapshot._jsonSchemaVersion),
19918  bundleSource: property("string", "DocumentSnapshot"),
19919  bundleName: property("string"),
19920  bundle: property("string")
19921};
19922class QueryDocumentSnapshot extends DocumentSnapshot {
19923  /**
19924   * Retrieves all fields in the document as an `Object`.
19925   *
19926   * By default, `serverTimestamp()` values that have not yet been
19927   * set to their final value will be returned as `null`. You can override
19928   * this by passing an options object.
19929   *
19930   * @override
19931   * @param options - An options object to configure how data is retrieved from
19932   * the snapshot (for example the desired behavior for server timestamps that
19933   * have not yet been set to their final value).
19934   * @returns An `Object` containing all fields in the document.
19935   */
19936  data(e = {}) {
19937    return super.data(e);
19938  }
19939}
19940class QuerySnapshot {
19941  /** @hideconstructor */
19942  constructor(e, t, n, r) {
19943    this._firestore = e, this._userDataWriter = t, this._snapshot = r, this.metadata = new SnapshotMetadata(r.hasPendingWrites, r.fromCache), this.query = n;
19944  }
19945  /** An array of all the documents in the `QuerySnapshot`. */
19946  get docs() {
19947    const e = [];
19948    return this.forEach((t) => e.push(t)), e;
19949  }
19950  /** The number of documents in the `QuerySnapshot`. */
19951  get size() {
19952    return this._snapshot.docs.size;
19953  }
19954  /** True if there are no documents in the `QuerySnapshot`. */
19955  get empty() {
19956    return 0 === this.size;
19957  }
19958  /**
19959   * Enumerates all of the documents in the `QuerySnapshot`.
19960   *
19961   * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
19962   * each document in the snapshot.
19963   * @param thisArg - The `this` binding for the callback.
19964   */
19965  forEach(e, t) {
19966    this._snapshot.docs.forEach((n) => {
19967      e.call(t, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n.key, n, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));
19968    });
19969  }
19970  /**
19971   * Returns an array of the documents changes since the last snapshot. If this
19972   * is the first snapshot, all documents will be in the list as 'added'
19973   * changes.
19974   *
19975   * @param options - `SnapshotListenOptions` that control whether metadata-only
19976   * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
19977   * snapshot events.
19978   */
19979  docChanges(e = {}) {
19980    const t = !!e.includeMetadataChanges;
19981    if (t && this._snapshot.excludesMetadataChanges) throw new FirestoreError(N.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
19982    return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t || (this._cachedChanges = /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
19983    function __PRIVATE_changesFromSnapshot(e2, t2) {
19984      if (e2._snapshot.oldDocs.isEmpty()) {
19985        let t3 = 0;
19986        return e2._snapshot.docChanges.map((n) => {
19987          const r = new QueryDocumentSnapshot(e2._firestore, e2._userDataWriter, n.doc.key, n.doc, new SnapshotMetadata(e2._snapshot.mutatedKeys.has(n.doc.key), e2._snapshot.fromCache), e2.query.converter);
19988          return n.doc, {
19989            type: "added",
19990            doc: r,
19991            oldIndex: -1,
19992            newIndex: t3++
19993          };
19994        });
19995      }
19996      {
19997        let n = e2._snapshot.oldDocs;
19998        return e2._snapshot.docChanges.filter((e3) => t2 || 3 !== e3.type).map((t3) => {
19999          const r = new QueryDocumentSnapshot(e2._firestore, e2._userDataWriter, t3.doc.key, t3.doc, new SnapshotMetadata(e2._snapshot.mutatedKeys.has(t3.doc.key), e2._snapshot.fromCache), e2.query.converter);
20000          let i = -1, s = -1;
20001          return 0 !== t3.type && (i = n.indexOf(t3.doc.key), n = n.delete(t3.doc.key)), 1 !== t3.type && (n = n.add(t3.doc), s = n.indexOf(t3.doc.key)), {
20002            type: __PRIVATE_resultChangeType(t3.type),
20003            doc: r,
20004            oldIndex: i,
20005            newIndex: s
20006          };
20007        });
20008      }
20009    }(this, t), this._cachedChangesIncludeMetadataChanges = t), this._cachedChanges;
20010  }
20011  /**
20012   * Returns a JSON-serializable representation of this `QuerySnapsh
20012ot` instance.
20013   *
20014   * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this
20015   * `QuerySnapshot` has pending writes.
20016   */
20017  toJSON() {
20018    if (this.metadata.hasPendingWrites) throw new FirestoreError(N.FAILED_PRECONDITION, "QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");
20019    const e = {};
20020    e.type = QuerySnapshot._jsonSchemaVersion, e.bundleSource = "QuerySnapshot", e.bundleName = __PRIVATE_AutoId.newId(), this._firestore._databaseId.database, this._firestore._databaseId.projectId;
20021    const t = [], n = [], r = [];
20022    return this.docs.forEach((e2) => {
20023      null !== e2._document && (t.push(e2._document), n.push(this._userDataWriter.convertObjectMap(e2._document.data.value.mapValue.fields, "previous")), r.push(e2.ref.path));
20024    }), e.bundle = (this._firestore, this.query._query, e.bundleName, "NOT SUPPORTED"), e;
20025  }
20026}
20027function querySnapshotFromJSON(e, t, n) {
20028  if (__PRIVATE_validateJSON(t, QuerySnapshot._jsonSchema)) {
20029    if (t.bundle === hn) throw new FirestoreError(N.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported.");
20030    const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Ku(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r);
20031    for (const e2 of s) o.Wa(e2);
20032    if (1 !== o.queries.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Snapshot data expected 1 query but found ${o.queries.length} queries.`);
20033    const _ = __PRIVATE_fromBundledQuery(o.queries[0].bundledQuery), a = o.documents;
20034    let u = new DocumentSet();
20035    a.map((e2) => {
20036      const t2 = __PRIVATE_fromDocument(r, e2.document);
20037      u = u.add(t2);
20038    });
20039    const c = ViewSnapshot.fromInitialDocuments(
20040      _,
20041      u,
20042      __PRIVATE_documentKeySet(),
20043      /* fromCache= */
20044      false,
20045      /* hasCachedResults= */
20046      false
20047    ), l = new Query(e, n || null, _);
20048    return new QuerySnapshot(e, new __PRIVATE_LiteUserDataWriter(e), l, c);
20049  }
20050}
20051function __PRIVATE_resultChangeType(e) {
20052  switch (e) {
20053    case 0:
20054      return "added";
20055    case 2:
20056    case 3:
20057      return "modified";
20058    case 1:
20059      return "removed";
20060    default:
20061      return fail(61501, {
20062        type: e
20063      });
20064  }
20065}
20066function snapshotEqual(e, t) {
20067  return e instanceof DocumentSnapshot && t instanceof DocumentSnapshot ? e._firestore === t._firestore && e._key.isEqual(t._key) && (null === e._document ? null === t._document : e._document.isEqual(t._document)) && e._converter === t._converter : e instanceof QuerySnapshot && t instanceof QuerySnapshot && (e._firestore === t._firestore && queryEqual(e.query, t.query) && e.metadata.isEqual(t.metadata) && e._snapshot.isEqual(t._snapshot));
20068}
20069/**
20070 * @license
20071 * Copyright 2020 Google LLC
20072 *
20073 * Licensed under the Apache License, Version 2.0 (the "License");
20074 * you may not use this file except in compliance with the License.
20075 * You may obtain a copy of the License at
20076 *
20077 *   http://www.apache.org/licenses/LICENSE-2.0
20078 *
20079 * Unless required by applicable law or agreed to in writing, software
20080 * distributed under the License is distributed on an "AS IS" BASIS,
20081 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20082 * See the License for the specific language governing permissions and
20083 * limitations under the License.
20084 */
20085function getDoc(e) {
20086  e = __PRIVATE_cast(e, DocumentReference);
20087  const t = __PRIVATE_cast(e.firestore, Firestore);
20088  return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key).then((n) => __PRIVATE_convertToDocSnapshot(t, e, n));
20089}
20090QuerySnapshot._jsonSchemaVersion = "firestore/querySnapshot/1.0", QuerySnapshot._jsonSchema = {
20091  type: property("string", QuerySnapshot._jsonSchemaVersion),
20092  bundleSource: property("string", "QuerySnapshot"),
20093  bundleName: property("string"),
20094  bundle: property("string")
20095};
20096class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter {
20097  constructor(e) {
20098    super(), this.firestore = e;
20099  }
20100  convertBytes(e) {
20101    return new Bytes(e);
20102  }
20103  convertReference(e) {
20104    const t = this.convertDocumentKey(e, this.firestore._databaseId);
20105    return new DocumentReference(
20106      this.firestore,
20107      /* converter= */
20108      null,
20109      t
20110    );
20111  }
20112}
20113function getDocFromCache(e) {
20114  e = __PRIVATE_cast(e, DocumentReference);
20115  const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);
20116  return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n, e._key).then((n2) => new DocumentSnapshot(t, r, e._key, n2, new SnapshotMetadata(
20117    null !== n2 && n2.hasLocalMutations,
20118    /* fromCache= */
20119    true
20120  ), e.converter));
20121}
20122function getDocFromServer(e) {
20123  e = __PRIVATE_cast(e, DocumentReference);
20124  const t = __PRIVATE_cast(e.firestore, Firestore);
20125  return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key, {
20126    source: "server"
20127  }).then((n) => __PRIVATE_convertToDocSnapshot(t, e, n));
20128}
20129function getDocs(e) {
20130  e = __PRIVATE_cast(e, Query);
20131  const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);
20132  return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query).then((n2) => new QuerySnapshot(t, r, e, n2));
20133}
20134function getDocsFromCache(e) {
20135  e = __PRIVATE_cast(e, Query);
20136  const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);
20137  return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n, e._query).then((n2) => new QuerySnapshot(t, r, e, n2));
20138}
20139function getDocsFromServer(e) {
20140  e = __PRIVATE_cast(e, Query);
20141  const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t);
20142  return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query, {
20143    source: "server"
20144  }).then((n2) => new QuerySnapshot(t, r, e, n2));
20145}
20146function setDoc(e, t, n) {
20147  e = __PRIVATE_cast(e, DocumentReference);
20148  const r = __PRIVATE_cast(e.firestore, Firestore), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t, n);
20149  return executeWrite(r, [__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r), "setDoc", e._key, i, null !== e.converter, n).toMutation(e._key, Precondition.none())]);
20150}
20151function updateDoc(e, t, n, ...r) {
20152  e = __PRIVATE_cast(e, DocumentReference);
20153  const i = __PRIVATE_cast(e.firestore, Firestore), s = __PRIVATE_newUserDataReader(i);
20154  let o;
20155  o = "string" == typeof // For Compat types, we have to "extract" the underlying types before
20156  // performing validation.
20157  (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s, "updateDoc", e._key, t, n, r) : __PRIVATE_parseUpdateData(s, "updateDoc", e._key, t);
20158  return executeWrite(i, [o.toMutation(e._key, Precondition.exists(true))]);
20159}
20160function deleteDoc(e) {
20161  return executeWrite(__PRIVATE_cast(e.firestore, Firestore), [new __PRIVATE_DeleteMutation(e._key, Precondition.none())]);
20162}
20163function addDoc(e, t) {
20164  const n = __PRIVATE_cast(e.firestore, Firestore), r = doc(e), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t);
20165  return executeWrite(n, [__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore), "addDoc", r._key, i, null !== e.converter, {}).toMutation(r._key, Precondition.exists(false))]).then(() => r);
20166}
20167function onSnapshot(e, ...t) {
20168  var n, r, i;
20169  e = getModularInstance(e);
20170  let s = {
20171    includeMetadataChanges: false,
20172    source: "default"
20173  }, o = 0;
20174  "object" != typeof t[o] || __PRIVATE_isPartialObserver(t[o]) || (s = t[o++]);
20175  const _ = {
20176    includeMetadataChanges: s.includeMetadataChanges,
20177    source: s.source
20178  };
20179  if (__PRIVATE_isPartialObserver(t[o])) {
20180    const e2 = t[o];
20181    t[o] = null === (n = e2.next) || void 0 === n ? void 0 : n.bind(e2), t[o + 1] = null === (r = e2.error) || void 0 === r ? void 0 : r.bind(e2), t[o + 2] = null === (i = e2.complete) || void 0 === i ? void 0 : i.bind(e2);
20182  }
20183  let a, u, c;
20184  if (e instanceof DocumentReference) u = __PRIVATE_cast(e.firestore, Firestore), c = __PRIVATE_newQueryForPath(e._key.path), a = {
20185    next: (n2) => {
20186      t[o] && t[o](__PRIVATE_convertToDocSnapshot(u, e, n2));
20187    },
20188    error: t[o + 1],
20189    complete: t[o + 2]
20190  };
20191  else {
20192    const n2 = __PRIVATE_cast(e, Query);
20193    u = __PRIVATE_cast(n2.firestore, Firestore), c = n2._query;
20194    const r2 = new __PRIVATE_ExpUserDataWriter(u);
20195    a = {
20196      next: (e2) => {
20197        t[o] && t[o](new QuerySnapshot(u, r2, n2, e2));
20198      },
20199      error: t[o + 1],
20200      complete: t[o + 2]
20201    }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query);
20202  }
20203  return function __PRIVATE_firestoreClientListen(e2, t2, n2, r2) {
20204    const i2 = new __PRIVATE_AsyncObserver(r2), s2 = new __PRIVATE_QueryListener(t2, i2, n2);
20205    return e2.asyncQueue.enqueueAndForget(async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e2), s2)), () => {
20206      i2.Ou(), e2.asyncQueue.enqueueAndForget(async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e2), s2));
20207    };
20208  }(ensureFirestoreConfigured(u), c, _, a);
20209}
20210function onSnapshotResume(e, t, ...n) {
20211  const r = getModularInstance(e), i = (
20212    /**
20213    * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson`
20214    * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The
20215    * data is normalized into a typed object.
20216    *
20217    * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}.
20218    * @returns A normalized object that contains all of the required bundle JSON fields. If
20219    * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty
20220    * strings, then the {@link snapshotJson.error} field will be a non empty string.
20221    *
20222    * @internal
20223    */
20224    function __PRIVATE_normalizeSnapshotJsonFields(e2) {
20225      const t2 = {
20226        bundle: "",
20227        bundleName: "",
20228        bundleSource: ""
20229      }, n2 = ["bundle", "bundleName", "bundleSource"];
20230      for (const r2 of n2) {
20231        if (!(r2 in e2)) {
20232          t2.error = `snapshotJson missing required field: ${r2}`;
20233          break;
20234        }
20235        const n3 = e2[r2];
20236        if ("string" != typeof n3) {
20237          t2.error = `snapshotJson field '${r2}' must be a string.`;
20238          break;
20239        }
20240        if (0 === n3.length) {
20241          t2.error = `snapshotJson field '${r2}' cannot be an empty string.`;
20242          break;
20243        }
20244        "bundle" === r2 ? t2.bundle = n3 : "bundleName" === r2 ? t2.bundleName = n3 : "bundleSource" === r2 && (t2.bundleSource = n3);
20245      }
20246      return t2;
20247    }(t)
20248  );
20249  if (i.error) throw new FirestoreError(N.INVALID_ARGUMENT, i.error);
20250  let s, o = 0;
20251  if ("object" != typeof n[o] || __PRIVATE_isPartialObserver(n[o]) || (s = n[o++]), "QuerySnapshot" === i.bundleSource) {
20252    let e2 = null;
20253    if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) {
20254      const t2 = n[o++];
20255      e2 = {
20256        next: t2.next,
20257        error: t2.error,
20258        complete: t2.complete
20259      };
20260    } else e2 = {
20261      next: n[o++],
20262      error: n[o++],
20263      complete: n[o++]
20264    };
20265    return function __PRIVATE_onSnapshotQuerySnapshotBundle(e3, t2, n2, r2, i2) {
20266      let s2, o2 = false;
20267      const _ = loadBundle(e3, t2.bundle);
20268      return _.then(() => namedQuery(e3, t2.bundleName)).then((e4) => {
20269        if (e4 && !o2) {
20270          i2 && e4.withConverter(i2), s2 = onSnapshot(e4, n2 || {}, r2);
20271        }
20272      }).catch((e4) => (r2.error && r2.error(e4), () => {
20273      })), () => {
20274        o2 || (o2 = true, s2 && s2());
20275      };
20276    }(r, i, s, e2, n[o]);
20277  }
20278  if ("DocumentSnapshot" === i.bundleSource) {
20279    let e2 = null;
20280    if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) {
20281      const t2 = n[o++];
20282      e2 = {
20283        next: t2.next,
20284        error: t2.error,
20285        complete: t2.complete
20286      };
20287    } else e2 = {
20288      next: n[o++],
20289      error: n[o++],
20290      complete: n[o++]
20291    };
20292    return function __PRIVATE_onSnapshotDocumentSnapshotBundle(e3, t2, n2, r2, i2) {
20293      let s2, o2 = false;
20294      const _ = loadBundle(e3, t2.bundle);
20295      return _.then(() => {
20296        if (!o2) {
20297          const o3 = new DocumentReference(e3, i2 || null, DocumentKey.fromPath(t2.bundleName));
20298          s2 = onSnapshot(o3, n2 || {}, r2);
20299        }
20300      }).catch((e4) => (r2.error && r2.error(e4), () => {
20301      })), () => {
20302        o2 || (o2 = true, s2 && s2());
20303      };
20304    }(r, i, s, e2, n[o]);
20305  }
20306  throw new FirestoreError(N.INVALID_ARGUMENT, `unsupported bundle source: ${i.bundleSource}`);
20307}
20308function onSnapshotsInSync(e, t) {
20309  return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), __PRIVATE_isPartialObserver(t) ? t : {
20310    next: t
20311  });
20312}
20313function executeWrite(e, t) {
20314  return function __PRIVATE_firestoreClientWrite(e2, t2) {
20315    const n = new __PRIVATE_Deferred();
20316    return e2.asyncQueue.enqueueAndForget(async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e2), t2, n)), n.promise;
20317  }(ensureFirestoreConfigured(e), t);
20318}
20319function __PRIVATE_convertToDocSnapshot(e, t, n) {
20320  const r = n.docs.get(t._key), i = new __PRIVATE_ExpUserDataWriter(e);
20321  return new DocumentSnapshot(e, i, t._key, r, new SnapshotMetadata(n.hasPendingWrites, n.fromCache), t.converter);
20322}
20323function getCountFromServer(e) {
20324  return getAggregateFromServer(e, {
20325    count: count()
20326  });
20327}
20328function getAggregateFromServer(e, t) {
20329  const n = __PRIVATE_cast(e.firestore, Firestore), r = ensureFirestoreConfigured(n), i = __PRIVATE_mapToArray(t, (e2, t2) => new __PRIVATE_AggregateImpl(t2, e2.aggregateType, e2._internalFieldPath));
20330  return __PRIVATE_firestoreClientRunAggregateQuery(r, e._query, i).then((t2) => (
20331    /**
20332    * Converts the core aggregation result to an `AggregateQuerySnapsh
20332ot`
20333    * that can be returned to the consumer.
20334    * @param query
20335    * @param aggregateResult Core aggregation result
20336    * @internal
20337    */
20338    function __PRIVATE_convertToAggregateQuerySnapshot(e2, t3, n2) {
20339      const r2 = new __PRIVATE_ExpUserDataWriter(e2), i2 = new AggregateQuerySnapshot(t3, r2, n2);
20340      return i2;
20341    }(n, e, t2)
20342  ));
20343}
20344class __PRIVATE_MemoryLocalCacheImpl {
20345  constructor(e) {
20346    this.kind = "memory", this._onlineComponentProvider = OnlineComponentProvider.provider, (null == e ? void 0 : e.garbageCollector) ? this._offlineComponentProvider = e.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = {
20347      build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0)
20348    };
20349  }
20350  toJSON() {
20351    return {
20352      kind: this.kind
20353    };
20354  }
20355}
20356class __PRIVATE_PersistentLocalCacheImpl {
20357  constructor(e) {
20358    let t;
20359    this.kind = "persistent", (null == e ? void 0 : e.tabManager) ? (e.tabManager._initialize(e), t = e.tabManager) : (t = persistentSingleTabManager(void 0), t._initialize(e)), this._onlineComponentProvider = t._onlineComponentProvider, this._offlineComponentProvider = t._offlineComponentProvider;
20360  }
20361  toJSON() {
20362    return {
20363      kind: this.kind
20364    };
20365  }
20366}
20367class __PRIVATE_MemoryEagerGarbageCollectorImpl {
20368  constructor() {
20369    this.kind = "memoryEager", this._offlineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider.provider;
20370  }
20371  toJSON() {
20372    return {
20373      kind: this.kind
20374    };
20375  }
20376}
20377class __PRIVATE_MemoryLruGarbageCollectorImpl {
20378  constructor(e) {
20379    this.kind = "memoryLru", this._offlineComponentProvider = {
20380      build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(e)
20381    };
20382  }
20383  toJSON() {
20384    return {
20385      kind: this.kind
20386    };
20387  }
20388}
20389function memoryEagerGarbageCollector() {
20390  return new __PRIVATE_MemoryEagerGarbageCollectorImpl();
20391}
20392function memoryLruGarbageCollector(e) {
20393  return new __PRIVATE_MemoryLruGarbageCollectorImpl(null == e ? void 0 : e.cacheSizeBytes);
20394}
20395function memoryLocalCache(e) {
20396  return new __PRIVATE_MemoryLocalCacheImpl(e);
20397}
20398function persistentLocalCache(e) {
20399  return new __PRIVATE_PersistentLocalCacheImpl(e);
20400}
20401class __PRIVATE_SingleTabManagerImpl {
20402  constructor(e) {
20403    this.forceOwnership = e, this.kind = "persistentSingleTab";
20404  }
20405  toJSON() {
20406    return {
20407      kind: this.kind
20408    };
20409  }
20410  /**
20411   * @internal
20412   */
20413  _initialize(e) {
20414    this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = {
20415      build: (t) => new __PRIVATE_IndexedDbOfflineComponentProvider(t, null == e ? void 0 : e.cacheSizeBytes, this.forceOwnership)
20416    };
20417  }
20418}
20419class __PRIVATE_MultiTabManagerImpl {
20420  constructor() {
20421    this.kind = "PersistentMultipleTab";
20422  }
20423  toJSON() {
20424    return {
20425      kind: this.kind
20426    };
20427  }
20428  /**
20429   * @internal
20430   */
20431  _initialize(e) {
20432    this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = {
20433      build: (t) => new __PRIVATE_MultiTabOfflineComponentProvider(t, null == e ? void 0 : e.cacheSizeBytes)
20434    };
20435  }
20436}
20437function persistentSingleTabManager(e) {
20438  return new __PRIVATE_SingleTabManagerImpl(null == e ? void 0 : e.forceOwnership);
20439}
20440function persistentMultipleTabManager() {
20441  return new __PRIVATE_MultiTabManagerImpl();
20442}
20443/**
20444 * @license
20445 * Copyright 2022 Google LLC
20446 *
20447 * Licensed under the Apache License, Version 2.0 (the "License");
20448 * you may not use this file except in compliance with the License.
20449 * You may obtain a copy of the License at
20450 *
20451 *   http://www.apache.org/licenses/LICENSE-2.0
20452 *
20453 * Unless required by applicable law or agreed to in writing, software
20454 * distributed under the License is distributed on an "AS IS" BASIS,
20455 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20456 * See the License for the specific language governing permissions and
20457 * limitations under the License.
20458 */
20459const Pn = {
20460  maxAttempts: 5
20461};
20462/**
20463 * @license
20464 * Copyright 2020 Google LLC
20465 *
20466 * Licensed under the Apache License, Version 2.0 (the "License");
20467 * you may not use this file except in compliance with the License.
20468 * You may obtain a copy of the License at
20469 *
20470 *   http://www.apache.org/licenses/LICENSE-2.0
20471 *
20472 * Unless required by applicable law or agreed to in writing, softw
20472are
20473 * distributed under the License is distributed on an "AS IS" BASIS,
20474 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20475 * See the License for the specific language governing permissions and
20476 * limitations under the License.
20477 */
20478class WriteBatch {
20479  /** @hideconstructor */
20480  constructor(e, t) {
20481    this._firestore = e, this._commitHandler = t, this._mutations = [], this._committed = false, this._dataReader = __PRIVATE_newUserDataReader(e);
20482  }
20483  set(e, t, n) {
20484    this._verifyNotCommitted();
20485    const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", r._key, i, null !== r.converter, n);
20486    return this._mutations.push(s.toMutation(r._key, Precondition.none())), this;
20487  }
20488  update(e, t, n, ...r) {
20489    this._verifyNotCommitted();
20490    const i = __PRIVATE_validateReference(e, this._firestore);
20491    let s;
20492    return s = "string" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, t), this._mutations.push(s.toMutation(i._key, Precondition.exists(true))), this;
20493  }
20494  /**
20495   * Deletes the document referred to by the provided {@link DocumentReference}.
20496   *
20497   * @param documentRef - A reference to the document to be deleted.
20498   * @returns This `WriteBatch` instance. Used for chaining method calls.
20499   */
20500  delete(e) {
20501    this._verifyNotCommitted();
20502    const t = __PRIVATE_validateReference(e, this._firestore);
20503    return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t._key, Precondition.none())), this;
20504  }
20505  /**
20506   * Commits all of the writes in this write batch as a single atomic unit.
20507   *
20508   * The result of these writes will only be reflected in document reads that
20509   * occur after the returned promise resolves. If the client is offline, the
20510   * write fails. If you would like to see local modifications or buffer writes
20511   * until the client is online, use the full Firestore SDK.
20512   *
20513   * @returns A `Promise` resolved once all of the writes in the batch have been
20514   * successfully written to the backend as an atomic unit (note that it won't
20515   * resolve while you're offline).
20516   */
20517  commit() {
20518    return this._verifyNotCommitted(), this._committed = true, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
20519  }
20520  _verifyNotCommitted() {
20521    if (this._committed) throw new FirestoreError(N.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
20522  }
20523}
20524function __PRIVATE_validateReference(e, t) {
20525  if ((e = getModularInstance(e)).firestore !== t) throw new FirestoreError(N.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
20526  return e;
20527}
20528/**
20529 * @license
20530 * Copyright 2020 Google LLC
20531 *
20532 * Licensed under the Apache License, Version 2.0 (the "License");
20533 * you may not use this file except in compliance with the License.
20534 * You may obtain a copy of the License at
20535 *
20536 *   http://www.apache.org/licenses/LICENSE-2.0
20537 *
20538 * Unless required by applicable law or agreed to in writing, software
20539 * distributed under the License is distributed on an "AS IS" BASIS,
20540 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20541 * See the License for the specific language governing permissions and
20542 * limitations under the License.
20543 */
20544class Transaction$1 {
20545  /** @hideconstructor */
20546  constructor(e, t) {
20547    this._firestore = e, this._transaction = t, this._dataReader = __PRIVATE_newUserDataReader(e);
20548  }
20549  /**
20550   * Reads the document referenced by the provided {@link DocumentReference}.
20551   *
20552   * @param documentRef - A reference to the document to be read.
20553   * @returns A `DocumentSnapshot` with the read data.
20554   */
20555  get(e) {
20556    const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_LiteUserDataWriter(this._firestore);
20557    return this._transaction.lookup([t._key]).then((e2) => {
20558      if (!e2 || 1 !== e2.length) return fail(24041);
20559      const r = e2[0];
20560      if (r.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n, r.key, r, t.converter);
20561      if (r.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n, t._key, null, t.converter);
20562      throw fail(18433, {
20563        doc: r
20564      });
20565    });
20566  }
20567  set(e, t, n) {
20568    const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", r._key, i, null !== r.converter, n);
20569    return this._transaction.set(r._key, s), this;
20570  }
20571  update(e, t, n, ...r) {
20572    const i = __PRIVATE_validateReference(e, this._firestore);
20573    let s;
20574    return s = "string" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpd
20574ateVarargs(this._dataReader, "Transaction.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, t), this._transaction.update(i._key, s), this;
20575  }
20576  /**
20577   * Deletes the document referred to by the provided {@link DocumentReference}.
20578   *
20579   * @param documentRef - A reference to the document to be deleted.
20580   * @returns This `Transaction` instance. Used for chaining method calls.
20581   */
20582  delete(e) {
20583    const t = __PRIVATE_validateReference(e, this._firestore);
20584    return this._transaction.delete(t._key), this;
20585  }
20586}
20587/**
20588 * @license
20589 * Copyright 2020 Google LLC
20590 *
20591 * Licensed under the Apache License, Version 2.0 (the "License");
20592 * you may not use this file except in compliance with the License.
20593 * You may obtain a copy of the License at
20594 *
20595 *   http://www.apache.org/licenses/LICENSE-2.0
20596 *
20597 * Unless required by applicable law or agreed to in writing, software
20598 * distributed under the License is distributed on an "AS IS" BASIS,
20599 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20600 * See the License for the specific language governing permissions and
20601 * limitations under the License.
20602 */
20603class Transaction extends Transaction$1 {
20604  // This class implements the same logic as the Transaction API in the Lite SDK
20605  // but is subclassed in order to return its own DocumentSnapshot types.
20606  /** @hideconstructor */
20607  constructor(e, t) {
20608    super(e, t), this._firestore = e;
20609  }
20610  /**
20611   * Reads the document referenced by the provided {@link DocumentReference}.
20612   *
20613   * @param documentRef - A reference to the document to be read.
20614   * @returns A `DocumentSnapshot` with the read data.
20615   */
20616  get(e) {
20617    const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_ExpUserDataWriter(this._firestore);
20618    return super.get(e).then((e2) => new DocumentSnapshot(this._firestore, n, t._key, e2._document, new SnapshotMetadata(
20619      /* hasPendingWrites= */
20620      false,
20621      /* fromCache= */
20622      false
20623    ), t.converter));
20624  }
20625}
20626function runTransaction(e, t, n) {
20627  e = __PRIVATE_cast(e, Firestore);
20628  const r = Object.assign(Object.assign({}, Pn), n);
20629  !function __PRIVATE_validateTransactionOptions(e2) {
20630    if (e2.maxAttempts < 1) throw new FirestoreError(N.INVALID_ARGUMENT, "Max attempts must be at least 1");
20631  }(r);
20632  return function __PRIVATE_firestoreClientTransaction(e2, t2, n2) {
20633    const r2 = new __PRIVATE_Deferred();
20634    return e2.asyncQueue.enqueueAndForget(async () => {
20635      const i = await __PRIVATE_getDatastore(e2);
20636      new __PRIVATE_TransactionRunner(e2.asyncQueue, i, n2, t2, r2).zu();
20637    }), r2.promise;
20638  }(ensureFirestoreConfigured(e), (n2) => t(new Transaction(e, n2)), r);
20639}
20640/**
20641 * @license
20642 * Copyright 2020 Google LLC
20643 *
20644 * Licensed under the Apache License, Version 2.0 (the "License");
20645 * you may not use this file except in compliance with the License.
20646 * You may obtain a copy of the License at
20647 *
20648 *   http://www.apache.org/licenses/LICENSE-2.0
20649 *
20650 * Unless required by applicable law or agreed to in writing, software
20651 * distributed under the License is distributed on an "AS IS" BASIS,
20652 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20653 * See the License for the specific language governing permissions and
20654 * limitations under the License.
20655 */
20656function deleteField() {
20657  return new __PRIVATE_DeleteFieldValueImpl("deleteField");
20658}
20659function serverTimestamp() {
20660  return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp");
20661}
20662function arrayUnion(...e) {
20663  return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", e);
20664}
20665function arrayRemove(...e) {
20666  return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", e);
20667}
20668function increment(e) {
20669  return new __PRIVATE_NumericIncrementFieldValueImpl("increment", e);
20670}
20671function vector(e) {
20672  return new VectorValue(e);
20673}
20674/**
20675 * @license
20676 * Copyright 2020 Google LLC
20677 *
20678 * Licensed under the Apache License, Version 2.0 (the "License");
20679 * you may not use this file except in compliance with the License.
20680 * You may obtain a copy of the License at
20681 *
20682 *   http://www.apache.org/licenses/LICENSE-2.0
20683 *
20684 * Unless required by applicable law or agreed to in writing, softw
20684are
20685 * distributed under the License is distributed on an "AS IS" BASIS,
20686 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20687 * See the License for the specific language governing permissions and
20688 * limitations under the License.
20689 */
20690function writeBatch(e) {
20691  return ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), new WriteBatch(e, (t) => executeWrite(e, t));
20692}
20693/**
20694 * @license
20695 * Copyright 2021 Google LLC
20696 *
20697 * Licensed under the Apache License, Version 2.0 (the "License");
20698 * you may not use this file except in compliance with the License.
20699 * You may obtain a copy of the License at
20700 *
20701 *   http://www.apache.org/licenses/LICENSE-2.0
20702 *
20703 * Unless required by applicable law or agreed to in writing, software
20704 * distributed under the License is distributed on an "AS IS" BASIS,
20705 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20706 * See the License for the specific language governing permissions and
20707 * limitations under the License.
20708 */
20709function setIndexConfiguration(e, t) {
20710  const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore));
20711  if (!n._uninitializedComponentsProvider || "memory" === n._uninitializedComponentsProvider._offline.kind)
20712    return __PRIVATE_logWarn("Cannot enable indexes when persistence is disabled"), Promise.resolve();
20713  const r = function __PRIVATE_parseIndexes(e2) {
20714    const t2 = "string" == typeof e2 ? function __PRIVATE_tryParseJson(e3) {
20715      try {
20716        return JSON.parse(e3);
20717      } catch (e4) {
20718        throw new FirestoreError(N.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == e4 ? void 0 : e4.message));
20719      }
20720    }(e2) : e2, n2 = [];
20721    if (Array.isArray(t2.indexes)) for (const e3 of t2.indexes) {
20722      const t3 = __PRIVATE_tryGetString(e3, "collectionGroup"), r2 = [];
20723      if (Array.isArray(e3.fields)) for (const t4 of e3.fields) {
20724        const e4 = __PRIVATE_fieldPathFromDotSeparatedString("setIndexConfiguration", __PRIVATE_tryGetString(t4, "fieldPath"));
20725        "CONTAINS" === t4.arrayConfig ? r2.push(new IndexSegment(
20726          e4,
20727          2
20728          /* IndexKind.CONTAINS */
20729        )) : "ASCENDING" === t4.order ? r2.push(new IndexSegment(
20730          e4,
20731          0
20732          /* IndexKind.ASCENDING */
20733        )) : "DESCENDING" === t4.order && r2.push(new IndexSegment(
20734          e4,
20735          1
20736          /* IndexKind.DESCENDING */
20737        ));
20738      }
20739      n2.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t3, r2, IndexState.empty()));
20740    }
20741    return n2;
20742  }(t);
20743  return __PRIVATE_firestoreClientSetIndexConfiguration(n, r);
20744}
20745function __PRIVATE_tryGetString(e, t) {
20746  if ("string" != typeof e[t]) throw new FirestoreError(N.INVALID_ARGUMENT, "Missing string value for: " + t);
20747  return e[t];
20748}
20749/**
20750 * @license
20751 * Copyright 2023 Google LLC
20752 *
20753 * Licensed under the Apache License, Version 2.0 (the "License");
20754 * you may not use this file except in compliance with the License.
20755 * You may obtain a copy of the License at
20756 *
20757 *   http://www.apache.org/licenses/LICENSE-2.0
20758 *
20759 * Unless required by applicable law or agreed to in writing, software
20760 * distributed under the License is distributed on an "AS IS" BASIS,
20761 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20762 * See the License for the specific language governing permissions and
20763 * limitations under the License.
20764 */
20765class PersistentCacheIndexManager {
20766  /** @hideconstructor */
20767  constructor(e) {
20768    this._firestore = e, /** A type string to uniquely identify instances of this class. */
20769    this.type = "PersistentCacheIndexManager";
20770  }
20771}
20772function getPersistentCacheIndexManager(e) {
20773  var t;
20774  e = __PRIVATE_cast(e, Firestore);
20775  const n = Tn.get(e);
20776  if (n) return n;
20777  if ("persistent" !== (null === (t = ensureFirestoreConfigured(e)._uninitializedComponentsProvider) || void 0 === t ? void 0 : t._offline.kind)) return null;
20778  const r = new PersistentCacheIndexManager(e);
20779  return Tn.set(e, r), r;
20780}
20781function enablePersistentCacheIndexAutoCreation(e) {
20782  __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, true);
20783}
20784function disablePersistentCacheIndexAutoCreation(e) {
20785  __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, false);
20786}
20787function deleteAllPersistentCacheIndexes(e) {
20788  __PRIVATE_firestoreClientDeleteAllFieldIndexes(ensureFirestoreConfigured(e._firestore)).then((e2) => __PRIVATE_logDebug("deleting all persistent cache indexes succeeded")).catch((e2) => __PRIVATE_logWarn("deleting all persistent cache indexes failed", e2));
20789}
20790function __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, t) {
20791  __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(ensureFirestoreConfigured(e._firestore), t).then((e2) => __PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${t} succeeded`)).catch((e2) => __PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${t} failed`, e2));
20792}
20793const Tn = /* @__PURE__ */ new WeakMap();
20794/**
20795 * @license
20796 * Copyright 2017 Google LLC
20797 *
20798 * Licensed under the Apache License, Version 2.0 (the "License");
20799 * you may not use this file except in compliance with the License.
20800 * You may obtain a copy of the License at
20801 *
20802 *   http://www.apache.org/licenses/LICENSE-2.0
20803 *
20804 * Unless required by applicable law or agreed to in writing, software
20805 * distributed under the License is distributed on an "AS IS" BASIS,
20806 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20807 * See the License for the specific language governing permissions and
20808 * limitations under the License.
20809 */
20810function _internalQueryToProtoQueryTarget(e) {
20811  var t;
20812  const n = null === (t = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore))._onlineComponents) || void 0 === t ? void 0 : t.datastore.serializer;
20813  return void 0 === n ? null : __PRIVATE_toQueryTarget(n, __PRIVATE_queryToTarget(e._query)).Vt;
20814}
20815function _internalAggregationQueryToProtoRunAggregationQueryRequest(e, t) {
20816  var n;
20817  const r = __PRIVATE_mapToArray(t, (e2, t2) => new __PRIVATE_AggregateImpl(t2, e2.aggregateType, e2._internalFieldPath)), i = null === (n = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore))._onlineComponents) || void 0 === n ? void 0 : n.datastore.serializer;
20818  return void 0 === i ? null : __PRIVATE_toRunAggregationQueryRequest(
20819    i,
20820    __PRIVATE_queryToAggregateTarget(e._query),
20821    r,
20822    /* skipAliasing= */
20823    true
20824  ).request;
20825}
20826/**
20827 * @license
20828 * Copyright 2023 Google LLC
20829 *
20830 * Licensed under the Apache License, Version 2.0 (the "License");
20831 * you may not use this file except in compliance with the License.
20832 * You may obtain a copy of the License at
20833 *
20834 *   http://www.apache.org/licenses/LICENSE-2.0
20835 *
20836 * Unless required by applicable law or agreed to in writing, software
20837 * distributed under the License is distributed on an "AS IS" BASIS,
20838 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20839 * See the License for the specific language governing permissions and
20840 * limitations under the License.
20841 */
20842class TestingHooks {
20843  constructor() {
20844    throw new Error("instances of this class should not be created");
20845  }
20846  /**
20847   * Registers a callback to be notified when an existence filter mismatch
20848   * occurs in the Watch listen stream.
20849   *
20850   * The relative order in which callbacks are notified is unspecified; do not
20851   * rely on any particular ordering. If a given callback is registered multiple
20852   * times then it will be notified multiple times, once per registration.
20853   *
20854   * @param callback the callback to invoke upon existence filter mismatch.
20855   *
20856   * @return a function that, when called, unregisters the given callback; only
20857   * the first invocation of the returned function does anything; all subsequent
20858   * invocations do nothing.
20859   */
20860  static onExistenceFilterMismatch(e) {
20861    return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e);
20862  }
20863}
20864class __PRIVATE_TestingHooksSpiImpl {
20865  constructor() {
20866    this.Fc = /* @__PURE__ */ new Map();
20867  }
20868  static get instance() {
20869    return In || (In = new __PRIVATE_TestingHooksSpiImpl(), function __PRIVATE_setTestingHooksSpi(e) {
20870      if (pt) throw new Error("a TestingHooksSpi instance is already set");
20871      pt = e;
20872    }(In)), In;
20873  }
20874  ct(e) {
20875    this.Fc.forEach((t) => t(e));
20876  }
20877  onExistenceFilterMismatch(e) {
20878    const t = Symbol(), n = this.Fc;
20879    return n.set(t, e), () => n.delete(t);
20880  }
20881}
20882let In = null;
20883!function __PRIVATE_registerFirestore(e, t = true) {
20884  !function __PRIVATE_setSDKVersion(e2) {
20885    x = e2;
20886  }(SDK_VERSION), _registerComponent(new Component("firestore", (e2, { instanceIdentifier: n, options: r }) => {
20887    const i = e2.getProvider("app").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e2.getProvider("auth-internal")), new __PRIVATE_FirebaseAppCheckTokenProvider(i, e2.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(e3, t2) {
20888      if (!Object.prototype.hasOwnProperty.apply(e3.options, ["projectId"])) throw new FirestoreError(N.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
20889      return new DatabaseId(e3.options.projectId, t2);
20890    }(i, n), i);
20891    return r = Object.assign({
20892      useFetchStreams: t
20893    }, r), s._setSettings(r), s;
20894  }, "PUBLIC").setMultipleInstances(true)), registerVersion(F, M, e), // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
20895  registerVersion(F, M, "esm2017");
20896}();
20897export {
20898  AbstractUserDataWriter,
20899  AggregateField,
20900  AggregateQuerySnapshot,
20901  Bytes,
20902  un as CACHE_SIZE_UNLIMITED,
20903  CollectionReference,
20904  DocumentReference,
20905  DocumentSnapshot,
20906  FieldPath,
20907  FieldValue,
20908  Firestore,
20909  FirestoreError,
20910  GeoPoint,
20911  LoadBundleTask,
20912  PersistentCacheIndexManager,
20913  Query,
20914  QueryCompositeFilterConstraint,
20915  QueryConstraint,
20916  QueryDocumentSnapshot,
20917  QueryEndAtConstraint,
20918  QueryFieldFilterConstraint,
20919  QueryLimitConstraint,
20920  QueryOrderByConstraint,
20921  QuerySnapshot,
20922  QueryStartAtConstraint,
20923  SnapshotMetadata,
20924  Timestamp,
20925  Transaction,
20926  VectorValue,
20927  WriteBatch,
20928  __PRIVATE_AutoId as _AutoId,
20929  ByteString as _ByteString,
20930  DatabaseId as _DatabaseId,
20931  DocumentKey as _DocumentKey,
20932  __PRIVATE_EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider,
20933  __PRIVATE_EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider,
20934  FieldPath$1 as _FieldPath,
20935  TestingHooks as _TestingHooks,
20936  __PRIVATE_cast as _cast,
20937  __PRIVATE_debugAssert as _debugAssert,
20938  _internalAggregationQueryToProtoRunAggregationQueryRequest,
20939  _internalQueryToProtoQueryTarget,
20940  __PRIVATE_isBase64Available as _isBase64Available,
20941  __PRIVATE_logWarn as _logWarn,
20942  __PRIVATE_validateIsNotUsedTogether as _validateIsNotUsedTogether,
20943  addDoc,
20944  aggregateFieldEqual,
20945  aggregateQuerySnapshotEqual,
20946  and,
20947  arrayRemove,
20948  arrayUnion,
20949  average,
20950  clearIndexedDbPersistence,
20951  collection,
20952  collectionGroup,
20953  connectFirestoreEmulator,
20954  count,
20955  deleteAllPersistentCacheIndexes,
20956  deleteDoc,
20957  deleteField,
20958  disableNetwork,
20959  disablePersistentCacheIndexAutoCreation,
20960  doc,
20961  documentId,
20962  documentSnapshotFromJSON,
20963  enableIndexedDbPersistence,
20964  enableMultiTabIndexedDbPersistence,
20965  enableNetwork,
20966  enablePersistentCacheIndexAutoCreation,
20967  endAt,
20968  endBefore,
20969  ensureFirestoreConfigured,
20970  executeWrite,
20971  getAggregateFromServer,
20972  getCountFromServer,
20973  getDoc,
20974  getDocFromCache,
20975  getDocFromServer,
20976  getDocs,
20977  getDocsFromCache,
20978  getDocsFromServer,
20979  getFirestore,
20980  getPersistentCacheIndexManager,
20981  increment,
20982  initializeFirestore,
20983  limit,
20984  limitToLast,
20985  loadBundle,
20986  memoryEagerGarbageCollector,
20987  memoryLocalCache,
20988  memoryLruGarbageCollector,
20989  namedQuery,
20990  onSnapshot,
20991  onSnapshotResume,
20992  onSnapshotsInSync,
20993  or,
20994  orderBy,
20995  persistentLocalCache,
20996  persistentMultipleTabManager,
20997  persistentSingleTabManager,
20998  query,
20999  queryEqual,
21000  querySnapshotFromJSON,
21001  refEqual,
21002  runTransaction,
21003  serverTimestamp,
21004  setDoc,
21005  setIndexConfiguration,
21006  setLogLevel,
21007  snapshotEqual,
21008  startAfter,
21009  startAt,
21010  sum,
21011  terminate,
21012  updateDoc,
21013  vector,
21014  waitForPendingWrites,
21015  where,
21016  writeBatch
21017};

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