/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD AND TERSER
if you want to view the source, please visit the github repository of this plugin
*/

"use strict";

var __create = Object.create, __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty, __defNormalProp = (s, r, o) => r in s ? __defProp(s, r, {
  enumerable: true,
  configurable: true,
  writable: true,
  value: o
}) : s[r] = o, __commonJS = (s, r) => function __require() {
  return r || (0, s[__getOwnPropNames(s)[0]])((r = {
    exports: {}
  }).exports, r), r.exports;
}, __export = (s, r) => {
  for (var o in r) __defProp(s, o, {
    get: r[o],
    enumerable: true
  });
}, __copyProps = (s, r, o, u) => {
  if (r && "object" == typeof r || "function" == typeof r) for (let g of __getOwnPropNames(r)) if (!__hasOwnProp.call(s, g) && g !== o) __defProp(s, g, {
    get: () => r[g],
    enumerable: !(u = __getOwnPropDesc(r, g)) || u.enumerable
  });
  return s;
}, __toESM = (s, r, o) => (o = null != s ? __create(__getProtoOf(s)) : {}, __copyProps(r || !s || !s.__esModule ? __defProp(o, "default", {
  value: s,
  enumerable: true
}) : o, s)), __toCommonJS = s => __copyProps(__defProp({}, "__esModule", {
  value: true
}), s), __publicField = (s, r, o) => {
  __defNormalProp(s, "symbol" != typeof r ? r + "" : r, o);
  return o;
}, __accessCheck = (s, r, o) => {
  if (!r.has(s)) throw TypeError("Cannot " + o);
}, __privateGet = (s, r, o) => {
  __accessCheck(s, r, "read from private field");
  return o ? o.call(s) : r.get(s);
}, __privateAdd = (s, r, o) => {
  if (r.has(s)) throw TypeError("Cannot add the same private member more than once");
  r instanceof WeakSet ? r.add(s) : r.set(s, o);
}, __privateSet = (s, r, o, u) => {
  __accessCheck(s, r, "write to private field");
  u ? u.call(s, o) : r.set(s, o);
  return o;
}, __privateMethod = (s, r, o) => {
  __accessCheck(s, r, "access private method");
  return o;
}, require_diff_match_patch = __commonJS({
  "node_modules/diff-match-patch/index.js"(s, r) {
    var diff_match_patch2 = function() {
      this.Diff_Timeout = 1;
      this.Diff_EditCost = 4;
      this.Match_Threshold = .5;
      this.Match_Distance = 1e3;
      this.Patch_DeleteThreshold = .5;
      this.Patch_Margin = 4;
      this.Match_MaxBits = 32;
    }, o = -1;
    diff_match_patch2.Diff = function(s, r) {
      return [ s, r ];
    };
    diff_match_patch2.prototype.diff_main = function(s, r, o, u) {
      if ("undefined" == typeof u) if (this.Diff_Timeout <= 0) u = Number.MAX_VALUE; else u = (new Date).getTime() + 1e3 * this.Diff_Timeout;
      var g = u;
      if (null == s || null == r) throw new Error("Null input. (diff_main)");
      if (s == r) if (s) return [ new diff_match_patch2.Diff(0, s) ]; else return [];
      if ("undefined" == typeof o) o = true;
      var _ = o, m = this.diff_commonPrefix(s, r), b = s.substring(0, m);
      s = s.substring(m);
      r = r.substring(m);
      m = this.diff_commonSuffix(s, r);
      var E = s.substring(s.length - m);
      s = s.substring(0, s.length - m);
      r = r.substring(0, r.length - m);
      var w = this.diff_compute_(s, r, _, g);
      if (b) w.unshift(new diff_match_patch2.Diff(0, b));
      if (E) w.push(new diff_match_patch2.Diff(0, E));
      this.diff_cleanupMerge(w);
      return w;
    };
    diff_match_patch2.prototype.diff_compute_ = function(s, r, u, g) {
      var _;
      if (!s) return [ new diff_match_patch2.Diff(1, r) ];
      if (!r) return [ new diff_match_patch2.Diff(o, s) ];
      var m = s.length > r.length ? s : r, b = s.length > r.length ? r : s, E = m.indexOf(b);
      if (-1 != E) {
        _ = [ new diff_match_patch2.Diff(1, m.substring(0, E)), new diff_match_patch2.Diff(0, b), new diff_match_patch2.Diff(1, m.substring(E + b.length)) ];
        if (s.length > r.length) _[0][0] = _[2][0] = o;
        return _;
      }
      if (1 == b.length) return [ new diff_match_patch2.Diff(o, s), new diff_match_patch2.Diff(1, r) ];
      var w = this.diff_halfMatch_(s, r);
      if (w) {
        var S = w[0], L = w[1], O = w[2], D = w[3], C = w[4], k = this.diff_main(S, O, u, g), T = this.diff_main(L, D, u, g);
        return k.concat([ new diff_match_patch2.Diff(0, C) ], T);
      }
      if (u && s.length > 100 && r.length > 100) return this.diff_lineMode_(s, r, g); else return this.diff_bisect_(s, r, g);
    };
    diff_match_patch2.prototype.diff_lineMode_ = function(s, r, u) {
      var g = this.diff_linesToChars_(s, r);
      s = g.chars1;
      r = g.chars2;
      var _ = g.lineArray, m = this.diff_main(s, r, false, u);
      this.diff_charsToLines_(m, _);
      this.diff_cleanupSemantic(m);
      m.push(new diff_match_patch2.Diff(0, ""));
      for (var b = 0, E = 0, w = 0, S = "", L = ""; b < m.length; ) {
        switch (m[b][0]) {
         case 1:
          w++;
          L += m[b][1];
          break;

         case o:
          E++;
          S += m[b][1];
          break;

         case 0:
          if (E >= 1 && w >= 1) {
            m.splice(b - E - w, E + w);
            b = b - E - w;
            for (var O = this.diff_main(S, L, false, u), D = O.length - 1; D >= 0; D--) m.splice(b, 0, O[D]);
            b += O.length;
          }
          w = 0;
          E = 0;
          S = "";
          L = "";
          break;
        }
        b++;
      }
      m.pop();
      return m;
    };
    diff_match_patch2.prototype.diff_bisect_ = function(s, r, u) {
      for (var g = s.length, _ = r.length, m = Math.ceil((g + _) / 2), b = m, E = 2 * m, w = new Array(E), S = new Array(E), L = 0; L < E; L++) {
        w[L] = -1;
        S[L] = -1;
      }
      w[b + 1] = 0;
      S[b + 1] = 0;
      for (var O = g - _, D = O % 2 != 0, C = 0, k = 0, T = 0, A = 0, R = 0; R < m && !((new Date).getTime() > u); R++) {
        for (var I = -R + C; I <= R - k; I += 2) {
          var x = b + I;
          if (I == -R || I != R && w[x - 1] < w[x + 1]) V = w[x + 1]; else V = w[x - 1] + 1;
          for (var P = V - I; V < g && P < _ && s.charAt(V) == r.charAt(P); ) {
            V++;
            P++;
          }
          w[x] = V;
          if (V > g) k += 2; else if (P > _) C += 2; else if (D) if ((F = b + O - I) >= 0 && F < E && -1 != S[F]) if (V >= (B = g - S[F])) return this.diff_bisectSplit_(s, r, V, P, u);
        }
        for (var N = -R + T; N <= R - A; N += 2) {
          var B, F = b + N;
          if (N == -R || N != R && S[F - 1] < S[F + 1]) B = S[F + 1]; else B = S[F - 1] + 1;
          for (var M = B - N; B < g && M < _ && s.charAt(g - B - 1) == r.charAt(_ - M - 1); ) {
            B++;
            M++;
          }
          S[F] = B;
          if (B > g) A += 2; else if (M > _) T += 2; else if (!D) if ((x = b + O - N) >= 0 && x < E && -1 != w[x]) {
            var V;
            P = b + (V = w[x]) - x;
            if (V >= (B = g - B)) return this.diff_bisectSplit_(s, r, V, P, u);
          }
        }
      }
      return [ new diff_match_patch2.Diff(o, s), new diff_match_patch2.Diff(1, r) ];
    };
    diff_match_patch2.prototype.diff_bisectSplit_ = function(s, r, o, u, g) {
      var _ = s.substring(0, o), m = r.substring(0, u), b = s.substring(o), E = r.substring(u), w = this.diff_main(_, m, false, g), S = this.diff_main(b, E, false, g);
      return w.concat(S);
    };
    diff_match_patch2.prototype.diff_linesToChars_ = function(s, r) {
      var o = [], u = {};
      o[0] = "";
      function diff_linesToCharsMunge_(s) {
        for (var r = "", _ = 0, m = -1, b = o.length; m < s.length - 1; ) {
          if (-1 == (m = s.indexOf("\n", _))) m = s.length - 1;
          var E = s.substring(_, m + 1);
          if (u.hasOwnProperty ? u.hasOwnProperty(E) : void 0 !== u[E]) r += String.fromCharCode(u[E]); else {
            if (b == g) {
              E = s.substring(_);
              m = s.length;
            }
            r += String.fromCharCode(b);
            u[E] = b;
            o[b++] = E;
          }
          _ = m + 1;
        }
        return r;
      }
      var g = 4e4, _ = diff_linesToCharsMunge_(s);
      g = 65535;
      return {
        chars1: _,
        chars2: diff_linesToCharsMunge_(r),
        lineArray: o
      };
    };
    diff_match_patch2.prototype.diff_charsToLines_ = function(s, r) {
      for (var o = 0; o < s.length; o++) {
        for (var u = s[o][1], g = [], _ = 0; _ < u.length; _++) g[_] = r[u.charCodeAt(_)];
        s[o][1] = g.join("");
      }
    };
    diff_match_patch2.prototype.diff_commonPrefix = function(s, r) {
      if (!s || !r || s.charAt(0) != r.charAt(0)) return 0;
      for (var o = 0, u = Math.min(s.length, r.length), g = u, _ = 0; o < g; ) {
        if (s.substring(_, g) == r.substring(_, g)) _ = o = g; else u = g;
        g = Math.floor((u - o) / 2 + o);
      }
      return g;
    };
    diff_match_patch2.prototype.diff_commonSuffix = function(s, r) {
      if (!s || !r || s.charAt(s.length - 1) != r.charAt(r.length - 1)) return 0;
      for (var o = 0, u = Math.min(s.length, r.length), g = u, _ = 0; o < g; ) {
        if (s.substring(s.length - g, s.length - _) == r.substring(r.length - g, r.length - _)) _ = o = g; else u = g;
        g = Math.floor((u - o) / 2 + o);
      }
      return g;
    };
    diff_match_patch2.prototype.diff_commonOverlap_ = function(s, r) {
      var o = s.length, u = r.length;
      if (0 == o || 0 == u) return 0;
      if (o > u) s = s.substring(o - u); else if (o < u) r = r.substring(0, o);
      var g = Math.min(o, u);
      if (s == r) return g;
      for (var _ = 0, m = 1; ;) {
        var b = s.substring(g - m), E = r.indexOf(b);
        if (-1 == E) return _;
        m += E;
        if (0 == E || s.substring(g - m) == r.substring(0, m)) {
          _ = m;
          m++;
        }
      }
    };
    diff_match_patch2.prototype.diff_halfMatch_ = function(s, r) {
      if (this.Diff_Timeout <= 0) return null;
      var o = s.length > r.length ? s : r, u = s.length > r.length ? r : s;
      if (o.length < 4 || 2 * u.length < o.length) return null;
      var g = this;
      function diff_halfMatchI_(s, r, o) {
        for (var u, _, m, b, E = s.substring(o, o + Math.floor(s.length / 4)), w = -1, S = ""; -1 != (w = r.indexOf(E, w + 1)); ) {
          var L = g.diff_commonPrefix(s.substring(o), r.substring(w)), O = g.diff_commonSuffix(s.substring(0, o), r.substring(0, w));
          if (S.length < O + L) {
            S = r.substring(w - O, w) + r.substring(w, w + L);
            u = s.substring(0, o - O);
            _ = s.substring(o + L);
            m = r.substring(0, w - O);
            b = r.substring(w + L);
          }
        }
        if (2 * S.length >= s.length) return [ u, _, m, b, S ]; else return null;
      }
      var _, m, b, E, w, S = diff_halfMatchI_(o, u, Math.ceil(o.length / 4)), L = diff_halfMatchI_(o, u, Math.ceil(o.length / 2));
      if (!S && !L) return null; else if (!L) _ = S; else if (!S) _ = L; else _ = S[4].length > L[4].length ? S : L;
      if (s.length > r.length) {
        m = _[0];
        b = _[1];
        E = _[2];
        w = _[3];
      } else {
        E = _[0];
        w = _[1];
        m = _[2];
        b = _[3];
      }
      return [ m, b, E, w, _[4] ];
    };
    diff_match_patch2.prototype.diff_cleanupSemantic = function(s) {
      for (var r = false, u = [], g = 0, _ = null, m = 0, b = 0, E = 0, w = 0, S = 0; m < s.length; ) {
        if (0 == s[m][0]) {
          u[g++] = m;
          b = w;
          E = S;
          w = 0;
          S = 0;
          _ = s[m][1];
        } else {
          if (1 == s[m][0]) w += s[m][1].length; else S += s[m][1].length;
          if (_ && _.length <= Math.max(b, E) && _.length <= Math.max(w, S)) {
            s.splice(u[g - 1], 0, new diff_match_patch2.Diff(o, _));
            s[u[g - 1] + 1][0] = 1;
            g--;
            m = --g > 0 ? u[g - 1] : -1;
            b = 0;
            E = 0;
            w = 0;
            S = 0;
            _ = null;
            r = true;
          }
        }
        m++;
      }
      if (r) this.diff_cleanupMerge(s);
      this.diff_cleanupSemanticLossless(s);
      m = 1;
      for (;m < s.length; ) {
        if (s[m - 1][0] == o && 1 == s[m][0]) {
          var L = s[m - 1][1], O = s[m][1], D = this.diff_commonOverlap_(L, O), C = this.diff_commonOverlap_(O, L);
          if (D >= C) {
            if (D >= L.length / 2 || D >= O.length / 2) {
              s.splice(m, 0, new diff_match_patch2.Diff(0, O.substring(0, D)));
              s[m - 1][1] = L.substring(0, L.length - D);
              s[m + 1][1] = O.substring(D);
              m++;
            }
          } else if (C >= L.length / 2 || C >= O.length / 2) {
            s.splice(m, 0, new diff_match_patch2.Diff(0, L.substring(0, C)));
            s[m - 1][0] = 1;
            s[m - 1][1] = O.substring(0, O.length - C);
            s[m + 1][0] = o;
            s[m + 1][1] = L.substring(C);
            m++;
          }
          m++;
        }
        m++;
      }
    };
    diff_match_patch2.prototype.diff_cleanupSemanticLossless = function(s) {
      function diff_cleanupSemanticScore_(s, r) {
        if (!s || !r) return 6;
        var o = s.charAt(s.length - 1), u = r.charAt(0), g = o.match(diff_match_patch2.nonAlphaNumericRegex_), _ = u.match(diff_match_patch2.nonAlphaNumericRegex_), m = g && o.match(diff_match_patch2.whitespaceRegex_), b = _ && u.match(diff_match_patch2.whitespaceRegex_), E = m && o.match(diff_match_patch2.linebreakRegex_), w = b && u.match(diff_match_patch2.linebreakRegex_), S = E && s.match(diff_match_patch2.blanklineEndRegex_), L = w && r.match(diff_match_patch2.blanklineStartRegex_);
        if (S || L) return 5; else if (E || w) return 4; else if (g && !m && b) return 3; else if (m || b) return 2; else if (g || _) return 1;
        return 0;
      }
      for (var r = 1; r < s.length - 1; ) {
        if (0 == s[r - 1][0] && 0 == s[r + 1][0]) {
          var o = s[r - 1][1], u = s[r][1], g = s[r + 1][1], _ = this.diff_commonSuffix(o, u);
          if (_) {
            var m = u.substring(u.length - _);
            o = o.substring(0, o.length - _);
            u = m + u.substring(0, u.length - _);
            g = m + g;
          }
          for (var b = o, E = u, w = g, S = diff_cleanupSemanticScore_(o, u) + diff_cleanupSemanticScore_(u, g); u.charAt(0) === g.charAt(0); ) {
            o += u.charAt(0);
            u = u.substring(1) + g.charAt(0);
            g = g.substring(1);
            var L = diff_cleanupSemanticScore_(o, u) + diff_cleanupSemanticScore_(u, g);
            if (L >= S) {
              S = L;
              b = o;
              E = u;
              w = g;
            }
          }
          if (s[r - 1][1] != b) {
            if (b) s[r - 1][1] = b; else {
              s.splice(r - 1, 1);
              r--;
            }
            s[r][1] = E;
            if (w) s[r + 1][1] = w; else {
              s.splice(r + 1, 1);
              r--;
            }
          }
        }
        r++;
      }
    };
    diff_match_patch2.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
    diff_match_patch2.whitespaceRegex_ = /\s/;
    diff_match_patch2.linebreakRegex_ = /[\r\n]/;
    diff_match_patch2.blanklineEndRegex_ = /\n\r?\n$/;
    diff_match_patch2.blanklineStartRegex_ = /^\r?\n\r?\n/;
    diff_match_patch2.prototype.diff_cleanupEfficiency = function(s) {
      for (var r = false, u = [], g = 0, _ = null, m = 0, b = false, E = false, w = false, S = false; m < s.length; ) {
        if (0 == s[m][0]) {
          if (s[m][1].length < this.Diff_EditCost && (w || S)) {
            u[g++] = m;
            b = w;
            E = S;
            _ = s[m][1];
          } else {
            g = 0;
            _ = null;
          }
          w = S = false;
        } else {
          if (s[m][0] == o) S = true; else w = true;
          if (_ && (b && E && w && S || _.length < this.Diff_EditCost / 2 && b + E + w + S == 3)) {
            s.splice(u[g - 1], 0, new diff_match_patch2.Diff(o, _));
            s[u[g - 1] + 1][0] = 1;
            g--;
            _ = null;
            if (b && E) {
              w = S = true;
              g = 0;
            } else {
              m = --g > 0 ? u[g - 1] : -1;
              w = S = false;
            }
            r = true;
          }
        }
        m++;
      }
      if (r) this.diff_cleanupMerge(s);
    };
    diff_match_patch2.prototype.diff_cleanupMerge = function(s) {
      s.push(new diff_match_patch2.Diff(0, ""));
      for (var r, u = 0, g = 0, _ = 0, m = "", b = ""; u < s.length; ) switch (s[u][0]) {
       case 1:
        _++;
        b += s[u][1];
        u++;
        break;

       case o:
        g++;
        m += s[u][1];
        u++;
        break;

       case 0:
        if (g + _ > 1) {
          if (0 !== g && 0 !== _) {
            if (0 !== (r = this.diff_commonPrefix(b, m))) {
              if (u - g - _ > 0 && 0 == s[u - g - _ - 1][0]) s[u - g - _ - 1][1] += b.substring(0, r); else {
                s.splice(0, 0, new diff_match_patch2.Diff(0, b.substring(0, r)));
                u++;
              }
              b = b.substring(r);
              m = m.substring(r);
            }
            if (0 !== (r = this.diff_commonSuffix(b, m))) {
              s[u][1] = b.substring(b.length - r) + s[u][1];
              b = b.substring(0, b.length - r);
              m = m.substring(0, m.length - r);
            }
          }
          u -= g + _;
          s.splice(u, g + _);
          if (m.length) {
            s.splice(u, 0, new diff_match_patch2.Diff(o, m));
            u++;
          }
          if (b.length) {
            s.splice(u, 0, new diff_match_patch2.Diff(1, b));
            u++;
          }
          u++;
        } else if (0 !== u && 0 == s[u - 1][0]) {
          s[u - 1][1] += s[u][1];
          s.splice(u, 1);
        } else u++;
        _ = 0;
        g = 0;
        m = "";
        b = "";
        break;
      }
      if ("" === s[s.length - 1][1]) s.pop();
      var E = false;
      u = 1;
      for (;u < s.length - 1; ) {
        if (0 == s[u - 1][0] && 0 == s[u + 1][0]) if (s[u][1].substring(s[u][1].length - s[u - 1][1].length) == s[u - 1][1]) {
          s[u][1] = s[u - 1][1] + s[u][1].substring(0, s[u][1].length - s[u - 1][1].length);
          s[u + 1][1] = s[u - 1][1] + s[u + 1][1];
          s.splice(u - 1, 1);
          E = true;
        } else if (s[u][1].substring(0, s[u + 1][1].length) == s[u + 1][1]) {
          s[u - 1][1] += s[u + 1][1];
          s[u][1] = s[u][1].substring(s[u + 1][1].length) + s[u + 1][1];
          s.splice(u + 1, 1);
          E = true;
        }
        u++;
      }
      if (E) this.diff_cleanupMerge(s);
    };
    diff_match_patch2.prototype.diff_xIndex = function(s, r) {
      var u, g = 0, _ = 0, m = 0, b = 0;
      for (u = 0; u < s.length; u++) {
        if (1 !== s[u][0]) g += s[u][1].length;
        if (s[u][0] !== o) _ += s[u][1].length;
        if (g > r) break;
        m = g;
        b = _;
      }
      if (s.length != u && s[u][0] === o) return b; else return b + (r - m);
    };
    diff_match_patch2.prototype.diff_prettyHtml = function(s) {
      for (var r = [], u = /&/g, g = /</g, _ = />/g, m = /\n/g, b = 0; b < s.length; b++) {
        var E = s[b][0], w = s[b][1].replace(u, "&amp;").replace(g, "&lt;").replace(_, "&gt;").replace(m, "&para;<br>");
        switch (E) {
         case 1:
          r[b] = '<ins style="background:#e6ffe6;">' + w + "</ins>";
          break;

         case o:
          r[b] = '<del style="background:#ffe6e6;">' + w + "</del>";
          break;

         case 0:
          r[b] = "<span>" + w + "</span>";
          break;
        }
      }
      return r.join("");
    };
    diff_match_patch2.prototype.diff_text1 = function(s) {
      for (var r = [], o = 0; o < s.length; o++) if (1 !== s[o][0]) r[o] = s[o][1];
      return r.join("");
    };
    diff_match_patch2.prototype.diff_text2 = function(s) {
      for (var r = [], u = 0; u < s.length; u++) if (s[u][0] !== o) r[u] = s[u][1];
      return r.join("");
    };
    diff_match_patch2.prototype.diff_levenshtein = function(s) {
      for (var r = 0, u = 0, g = 0, _ = 0; _ < s.length; _++) {
        var m = s[_][0], b = s[_][1];
        switch (m) {
         case 1:
          u += b.length;
          break;

         case o:
          g += b.length;
          break;

         case 0:
          r += Math.max(u, g);
          u = 0;
          g = 0;
          break;
        }
      }
      return r += Math.max(u, g);
    };
    diff_match_patch2.prototype.diff_toDelta = function(s) {
      for (var r = [], u = 0; u < s.length; u++) switch (s[u][0]) {
       case 1:
        r[u] = "+" + encodeURI(s[u][1]);
        break;

       case o:
        r[u] = "-" + s[u][1].length;
        break;

       case 0:
        r[u] = "=" + s[u][1].length;
        break;
      }
      return r.join("\t").replace(/%20/g, " ");
    };
    diff_match_patch2.prototype.diff_fromDelta = function(s, r) {
      for (var u = [], g = 0, _ = 0, m = r.split(/\t/g), b = 0; b < m.length; b++) {
        var E = m[b].substring(1);
        switch (m[b].charAt(0)) {
         case "+":
          try {
            u[g++] = new diff_match_patch2.Diff(1, decodeURI(E));
          } catch (s) {
            throw new Error("Illegal escape in diff_fromDelta: " + E);
          }
          break;

         case "-":
         case "=":
          var w = parseInt(E, 10);
          if (isNaN(w) || w < 0) throw new Error("Invalid number in diff_fromDelta: " + E);
          var S = s.substring(_, _ += w);
          if ("=" == m[b].charAt(0)) u[g++] = new diff_match_patch2.Diff(0, S); else u[g++] = new diff_match_patch2.Diff(o, S);
          break;

         default:
          if (m[b]) throw new Error("Invalid diff operation in diff_fromDelta: " + m[b]);
        }
      }
      if (_ != s.length) throw new Error("Delta length (" + _ + ") does not equal source text length (" + s.length + ").");
      return u;
    };
    diff_match_patch2.prototype.match_main = function(s, r, o) {
      if (null == s || null == r || null == o) throw new Error("Null input. (match_main)");
      o = Math.max(0, Math.min(o, s.length));
      if (s == r) return 0; else if (!s.length) return -1; else if (s.substring(o, o + r.length) == r) return o; else return this.match_bitap_(s, r, o);
    };
    diff_match_patch2.prototype.match_bitap_ = function(s, r, o) {
      if (r.length > this.Match_MaxBits) throw new Error("Pattern too long for this browser.");
      var u = this.match_alphabet_(r), g = this;
      function match_bitapScore_(s, u) {
        var _ = s / r.length, m = Math.abs(o - u);
        if (!g.Match_Distance) return m ? 1 : _; else return _ + m / g.Match_Distance;
      }
      var _ = this.Match_Threshold, m = s.indexOf(r, o);
      if (-1 != m) {
        _ = Math.min(match_bitapScore_(0, m), _);
        if (-1 != (m = s.lastIndexOf(r, o + r.length))) _ = Math.min(match_bitapScore_(0, m), _);
      }
      var b, E, w = 1 << r.length - 1;
      m = -1;
      for (var S, L = r.length + s.length, O = 0; O < r.length; O++) {
        b = 0;
        E = L;
        for (;b < E; ) {
          if (match_bitapScore_(O, o + E) <= _) b = E; else L = E;
          E = Math.floor((L - b) / 2 + b);
        }
        L = E;
        var D = Math.max(1, o - E + 1), C = Math.min(o + E, s.length) + r.length, k = Array(C + 2);
        k[C + 1] = (1 << O) - 1;
        for (var T = C; T >= D; T--) {
          var A = u[s.charAt(T - 1)];
          if (0 === O) k[T] = (k[T + 1] << 1 | 1) & A; else k[T] = (k[T + 1] << 1 | 1) & A | (S[T + 1] | S[T]) << 1 | 1 | S[T + 1];
          if (k[T] & w) {
            var R = match_bitapScore_(O, T - 1);
            if (R <= _) {
              _ = R;
              if ((m = T - 1) > o) D = Math.max(1, 2 * o - m); else break;
            }
          }
        }
        if (match_bitapScore_(O + 1, o) > _) break;
        S = k;
      }
      return m;
    };
    diff_match_patch2.prototype.match_alphabet_ = function(s) {
      for (var r = {}, o = 0; o < s.length; o++) r[s.charAt(o)] = 0;
      for (o = 0; o < s.length; o++) r[s.charAt(o)] |= 1 << s.length - o - 1;
      return r;
    };
    diff_match_patch2.prototype.patch_addContext_ = function(s, r) {
      if (0 != r.length) {
        if (null === s.start2) throw Error("patch not initialized");
        for (var o = r.substring(s.start2, s.start2 + s.length1), u = 0; r.indexOf(o) != r.lastIndexOf(o) && o.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin; ) {
          u += this.Patch_Margin;
          o = r.substring(s.start2 - u, s.start2 + s.length1 + u);
        }
        u += this.Patch_Margin;
        var g = r.substring(s.start2 - u, s.start2);
        if (g) s.diffs.unshift(new diff_match_patch2.Diff(0, g));
        var _ = r.substring(s.start2 + s.length1, s.start2 + s.length1 + u);
        if (_) s.diffs.push(new diff_match_patch2.Diff(0, _));
        s.start1 -= g.length;
        s.start2 -= g.length;
        s.length1 += g.length + _.length;
        s.length2 += g.length + _.length;
      }
    };
    diff_match_patch2.prototype.patch_make = function(s, r, u) {
      var g, _;
      if ("string" == typeof s && "string" == typeof r && "undefined" == typeof u) {
        g = s;
        if ((_ = this.diff_main(g, r, true)).length > 2) {
          this.diff_cleanupSemantic(_);
          this.diff_cleanupEfficiency(_);
        }
      } else if (s && "object" == typeof s && "undefined" == typeof r && "undefined" == typeof u) {
        _ = s;
        g = this.diff_text1(_);
      } else if ("string" == typeof s && r && "object" == typeof r && "undefined" == typeof u) {
        g = s;
        _ = r;
      } else if ("string" == typeof s && "string" == typeof r && u && "object" == typeof u) {
        g = s;
        _ = u;
      } else throw new Error("Unknown call format to patch_make.");
      if (0 === _.length) return [];
      for (var m = [], b = new diff_match_patch2.patch_obj, E = 0, w = 0, S = 0, L = g, O = g, D = 0; D < _.length; D++) {
        var C = _[D][0], k = _[D][1];
        if (!E && 0 !== C) {
          b.start1 = w;
          b.start2 = S;
        }
        switch (C) {
         case 1:
          b.diffs[E++] = _[D];
          b.length2 += k.length;
          O = O.substring(0, S) + k + O.substring(S);
          break;

         case o:
          b.length1 += k.length;
          b.diffs[E++] = _[D];
          O = O.substring(0, S) + O.substring(S + k.length);
          break;

         case 0:
          if (k.length <= 2 * this.Patch_Margin && E && _.length != D + 1) {
            b.diffs[E++] = _[D];
            b.length1 += k.length;
            b.length2 += k.length;
          } else if (k.length >= 2 * this.Patch_Margin) if (E) {
            this.patch_addContext_(b, L);
            m.push(b);
            b = new diff_match_patch2.patch_obj;
            E = 0;
            L = O;
            w = S;
          }
          break;
        }
        if (1 !== C) w += k.length;
        if (C !== o) S += k.length;
      }
      if (E) {
        this.patch_addContext_(b, L);
        m.push(b);
      }
      return m;
    };
    diff_match_patch2.prototype.patch_deepCopy = function(s) {
      for (var r = [], o = 0; o < s.length; o++) {
        var u = s[o], g = new diff_match_patch2.patch_obj;
        g.diffs = [];
        for (var _ = 0; _ < u.diffs.length; _++) g.diffs[_] = new diff_match_patch2.Diff(u.diffs[_][0], u.diffs[_][1]);
        g.start1 = u.start1;
        g.start2 = u.start2;
        g.length1 = u.length1;
        g.length2 = u.length2;
        r[o] = g;
      }
      return r;
    };
    diff_match_patch2.prototype.patch_apply = function(s, r) {
      if (0 == s.length) return [ r, [] ];
      s = this.patch_deepCopy(s);
      var u = this.patch_addPadding(s);
      r = u + r + u;
      this.patch_splitMax(s);
      for (var g = 0, _ = [], m = 0; m < s.length; m++) {
        var b, E = s[m].start2 + g, w = this.diff_text1(s[m].diffs), S = -1;
        if (w.length > this.Match_MaxBits) {
          if (-1 != (b = this.match_main(r, w.substring(0, this.Match_MaxBits), E))) if (-1 == (S = this.match_main(r, w.substring(w.length - this.Match_MaxBits), E + w.length - this.Match_MaxBits)) || b >= S) b = -1;
        } else b = this.match_main(r, w, E);
        if (-1 == b) {
          _[m] = false;
          g -= s[m].length2 - s[m].length1;
        } else {
          _[m] = true;
          g = b - E;
          var L;
          if (-1 == S) L = r.substring(b, b + w.length); else L = r.substring(b, S + this.Match_MaxBits);
          if (w == L) r = r.substring(0, b) + this.diff_text2(s[m].diffs) + r.substring(b + w.length); else {
            var O = this.diff_main(w, L, false);
            if (w.length > this.Match_MaxBits && this.diff_levenshtein(O) / w.length > this.Patch_DeleteThreshold) _[m] = false; else {
              this.diff_cleanupSemanticLossless(O);
              for (var D, C = 0, k = 0; k < s[m].diffs.length; k++) {
                var T = s[m].diffs[k];
                if (0 !== T[0]) D = this.diff_xIndex(O, C);
                if (1 === T[0]) r = r.substring(0, b + D) + T[1] + r.substring(b + D); else if (T[0] === o) r = r.substring(0, b + D) + r.substring(b + this.diff_xIndex(O, C + T[1].length));
                if (T[0] !== o) C += T[1].length;
              }
            }
          }
        }
      }
      return [ r = r.substring(u.length, r.length - u.length), _ ];
    };
    diff_match_patch2.prototype.patch_addPadding = function(s) {
      for (var r = this.Patch_Margin, o = "", u = 1; u <= r; u++) o += String.fromCharCode(u);
      for (u = 0; u < s.length; u++) {
        s[u].start1 += r;
        s[u].start2 += r;
      }
      var g = s[0], _ = g.diffs;
      if (0 == _.length || 0 != _[0][0]) {
        _.unshift(new diff_match_patch2.Diff(0, o));
        g.start1 -= r;
        g.start2 -= r;
        g.length1 += r;
        g.length2 += r;
      } else if (r > _[0][1].length) {
        var m = r - _[0][1].length;
        _[0][1] = o.substring(_[0][1].length) + _[0][1];
        g.start1 -= m;
        g.start2 -= m;
        g.length1 += m;
        g.length2 += m;
      }
      if (0 == (_ = (g = s[s.length - 1]).diffs).length || 0 != _[_.length - 1][0]) {
        _.push(new diff_match_patch2.Diff(0, o));
        g.length1 += r;
        g.length2 += r;
      } else if (r > _[_.length - 1][1].length) {
        m = r - _[_.length - 1][1].length;
        _[_.length - 1][1] += o.substring(0, m);
        g.length1 += m;
        g.length2 += m;
      }
      return o;
    };
    diff_match_patch2.prototype.patch_splitMax = function(s) {
      for (var r = this.Match_MaxBits, u = 0; u < s.length; u++) if (!(s[u].length1 <= r)) {
        var g = s[u];
        s.splice(u--, 1);
        for (var _ = g.start1, m = g.start2, b = ""; 0 !== g.diffs.length; ) {
          var E = new diff_match_patch2.patch_obj, w = true;
          E.start1 = _ - b.length;
          E.start2 = m - b.length;
          if ("" !== b) {
            E.length1 = E.length2 = b.length;
            E.diffs.push(new diff_match_patch2.Diff(0, b));
          }
          for (;0 !== g.diffs.length && E.length1 < r - this.Patch_Margin; ) {
            var S = g.diffs[0][0], L = g.diffs[0][1];
            if (1 === S) {
              E.length2 += L.length;
              m += L.length;
              E.diffs.push(g.diffs.shift());
              w = false;
            } else if (S === o && 1 == E.diffs.length && 0 == E.diffs[0][0] && L.length > 2 * r) {
              E.length1 += L.length;
              _ += L.length;
              w = false;
              E.diffs.push(new diff_match_patch2.Diff(S, L));
              g.diffs.shift();
            } else {
              L = L.substring(0, r - E.length1 - this.Patch_Margin);
              E.length1 += L.length;
              _ += L.length;
              if (0 === S) {
                E.length2 += L.length;
                m += L.length;
              } else w = false;
              E.diffs.push(new diff_match_patch2.Diff(S, L));
              if (L == g.diffs[0][1]) g.diffs.shift(); else g.diffs[0][1] = g.diffs[0][1].substring(L.length);
            }
          }
          b = (b = this.diff_text2(E.diffs)).substring(b.length - this.Patch_Margin);
          var O = this.diff_text1(g.diffs).substring(0, this.Patch_Margin);
          if ("" !== O) {
            E.length1 += O.length;
            E.length2 += O.length;
            if (0 !== E.diffs.length && 0 === E.diffs[E.diffs.length - 1][0]) E.diffs[E.diffs.length - 1][1] += O; else E.diffs.push(new diff_match_patch2.Diff(0, O));
          }
          if (!w) s.splice(++u, 0, E);
        }
      }
    };
    diff_match_patch2.prototype.patch_toText = function(s) {
      for (var r = [], o = 0; o < s.length; o++) r[o] = s[o];
      return r.join("");
    };
    diff_match_patch2.prototype.patch_fromText = function(s) {
      var r = [];
      if (!s) return r;
      for (var u = s.split("\n"), g = 0, _ = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; g < u.length; ) {
        var m = u[g].match(_);
        if (!m) throw new Error("Invalid patch string: " + u[g]);
        var b = new diff_match_patch2.patch_obj;
        r.push(b);
        b.start1 = parseInt(m[1], 10);
        if ("" === m[2]) {
          b.start1--;
          b.length1 = 1;
        } else if ("0" == m[2]) b.length1 = 0; else {
          b.start1--;
          b.length1 = parseInt(m[2], 10);
        }
        b.start2 = parseInt(m[3], 10);
        if ("" === m[4]) {
          b.start2--;
          b.length2 = 1;
        } else if ("0" == m[4]) b.length2 = 0; else {
          b.start2--;
          b.length2 = parseInt(m[4], 10);
        }
        g++;
        for (;g < u.length; ) {
          var E = u[g].charAt(0);
          try {
            var w = decodeURI(u[g].substring(1));
          } catch (s) {
            throw new Error("Illegal escape in patch_fromText: " + w);
          }
          if ("-" == E) b.diffs.push(new diff_match_patch2.Diff(o, w)); else if ("+" == E) b.diffs.push(new diff_match_patch2.Diff(1, w)); else if (" " == E) b.diffs.push(new diff_match_patch2.Diff(0, w)); else if ("@" == E) break; else if ("" === E) ; else throw new Error('Invalid patch mode "' + E + '" in: ' + w);
          g++;
        }
      }
      return r;
    };
    diff_match_patch2.patch_obj = function() {
      this.diffs = [];
      this.start1 = null;
      this.start2 = null;
      this.length1 = 0;
      this.length2 = 0;
    };
    diff_match_patch2.patch_obj.prototype.toString = function() {
      var s, r;
      if (0 === this.length1) s = this.start1 + ",0"; else if (1 == this.length1) s = this.start1 + 1; else s = this.start1 + 1 + "," + this.length1;
      if (0 === this.length2) r = this.start2 + ",0"; else if (1 == this.length2) r = this.start2 + 1; else r = this.start2 + 1 + "," + this.length2;
      for (var u, g = [ "@@ -" + s + " +" + r + " @@\n" ], _ = 0; _ < this.diffs.length; _++) {
        switch (this.diffs[_][0]) {
         case 1:
          u = "+";
          break;

         case o:
          u = "-";
          break;

         case 0:
          u = " ";
          break;
        }
        g[_ + 1] = u + encodeURI(this.diffs[_][1]) + "\n";
      }
      return g.join("").replace(/%20/g, " ");
    };
    r.exports = diff_match_patch2;
    r.exports["diff_match_patch"] = diff_match_patch2;
    r.exports["DIFF_DELETE"] = o;
    r.exports["DIFF_INSERT"] = 1;
    r.exports["DIFF_EQUAL"] = 0;
  }
}), require_balanced_match = __commonJS({
  "node_modules/balanced-match/index.js"(s, r) {
    "use strict";
    r.exports = balanced;
    function balanced(s, r, o) {
      if (s instanceof RegExp) s = maybeMatch(s, o);
      if (r instanceof RegExp) r = maybeMatch(r, o);
      var u = range2(s, r, o);
      return u && {
        start: u[0],
        end: u[1],
        pre: o.slice(0, u[0]),
        body: o.slice(u[0] + s.length, u[1]),
        post: o.slice(u[1] + r.length)
      };
    }
    function maybeMatch(s, r) {
      var o = r.match(s);
      return o ? o[0] : null;
    }
    balanced.range = range2;
    function range2(s, r, o) {
      var u, g, _, m, b, E = o.indexOf(s), w = o.indexOf(r, E + 1), S = E;
      if (E >= 0 && w > 0) {
        if (s === r) return [ E, w ];
        u = [];
        _ = o.length;
        for (;S >= 0 && !b; ) {
          if (S == E) {
            u.push(S);
            E = o.indexOf(s, S + 1);
          } else if (1 == u.length) b = [ u.pop(), w ]; else {
            if ((g = u.pop()) < _) {
              _ = g;
              m = w;
            }
            w = o.indexOf(r, S + 1);
          }
          S = E < w && E >= 0 ? E : w;
        }
        if (u.length) b = [ _, m ];
      }
      return b;
    }
  }
}), require_brace_expansion = __commonJS({
  "node_modules/brace-expansion/index.js"(s, r) {
    var o = require_balanced_match();
    r.exports = function expandTop(s) {
      if (!s) return [];
      if ("{}" === s.substr(0, 2)) s = "\\{\\}" + s.substr(2);
      return expand2(function escapeBraces(s) {
        return s.split("\\\\").join(u).split("\\{").join(g).split("\\}").join(_).split("\\,").join(m).split("\\.").join(b);
      }(s), true).map(unescapeBraces);
    };
    var u = "\0SLASH" + Math.random() + "\0", g = "\0OPEN" + Math.random() + "\0", _ = "\0CLOSE" + Math.random() + "\0", m = "\0COMMA" + Math.random() + "\0", b = "\0PERIOD" + Math.random() + "\0";
    function numeric(s) {
      return parseInt(s, 10) == s ? parseInt(s, 10) : s.charCodeAt(0);
    }
    function unescapeBraces(s) {
      return s.split(u).join("\\").split(g).join("{").split(_).join("}").split(m).join(",").split(b).join(".");
    }
    function parseCommaParts(s) {
      if (!s) return [ "" ];
      var r = [], u = o("{", "}", s);
      if (!u) return s.split(",");
      var g = u.pre, _ = u.body, m = u.post, b = g.split(",");
      b[b.length - 1] += "{" + _ + "}";
      var E = parseCommaParts(m);
      if (m.length) {
        b[b.length - 1] += E.shift();
        b.push.apply(b, E);
      }
      r.push.apply(r, b);
      return r;
    }
    function embrace(s) {
      return "{" + s + "}";
    }
    function isPadded(s) {
      return /^-?0\d/.test(s);
    }
    function lte(s, r) {
      return s <= r;
    }
    function gte(s, r) {
      return s >= r;
    }
    function expand2(s, r) {
      var u = [], g = o("{", "}", s);
      if (!g) return [ s ];
      var m = g.pre, b = g.post.length ? expand2(g.post, false) : [ "" ];
      if (/\$$/.test(g.pre)) for (var E = 0; E < b.length; E++) {
        var w = m + "{" + g.body + "}" + b[E];
        u.push(w);
      } else {
        var S, L, O = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(g.body), D = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(g.body), C = O || D, k = g.body.indexOf(",") >= 0;
        if (!C && !k) if (g.post.match(/,.*\}/)) return expand2(s = g.pre + "{" + g.body + _ + g.post); else return [ s ];
        if (C) S = g.body.split(/\.\./); else if (1 === (S = parseCommaParts(g.body)).length) if (1 === (S = expand2(S[0], false).map(embrace)).length) return b.map((function(s) {
          return g.pre + S[0] + s;
        }));
        if (C) {
          var T = numeric(S[0]), A = numeric(S[1]), R = Math.max(S[0].length, S[1].length), I = 3 == S.length ? Math.abs(numeric(S[2])) : 1, x = lte;
          if (A < T) {
            I *= -1;
            x = gte;
          }
          var P = S.some(isPadded);
          L = [];
          for (var N = T; x(N, A); N += I) {
            var B;
            if (D) {
              if ("\\" === (B = String.fromCharCode(N))) B = "";
            } else {
              B = String(N);
              if (P) {
                var F = R - B.length;
                if (F > 0) {
                  var M = new Array(F + 1).join("0");
                  if (N < 0) B = "-" + M + B.slice(1); else B = M + B;
                }
              }
            }
            L.push(B);
          }
        } else {
          L = [];
          for (var V = 0; V < S.length; V++) L.push.apply(L, expand2(S[V], false));
        }
        for (V = 0; V < L.length; V++) for (E = 0; E < b.length; E++) {
          w = m + L[V] + b[E];
          if (!r || C || w) u.push(w);
        }
      }
      return u;
    }
  }
}), require_nextTick = __commonJS({
  "(disabled):node_modules/immediate/lib/nextTick"() {}
}), require_queueMicrotask = __commonJS({
  "node_modules/immediate/lib/queueMicrotask.js"(s) {
    "use strict";
    s.test = function() {
      return "function" == typeof window.queueMicrotask;
    };
    s.install = function(s) {
      return function() {
        window.queueMicrotask(s);
      };
    };
  }
}), require_mutation = __commonJS({
  "node_modules/immediate/lib/mutation.js"(s) {
    "use strict";
    var r = window.MutationObserver || window.WebKitMutationObserver;
    s.test = function() {
      return r;
    };
    s.install = function(s) {
      var o = 0, u = new r(s), g = window.document.createTextNode("");
      u.observe(g, {
        characterData: true
      });
      return function() {
        g.data = o = ++o % 2;
      };
    };
  }
}), require_messageChannel = __commonJS({
  "node_modules/immediate/lib/messageChannel.js"(s) {
    "use strict";
    s.test = function() {
      if (window.setImmediate) return false; else return "undefined" != typeof window.MessageChannel;
    };
    s.install = function(s) {
      var r = new window.MessageChannel;
      r.port1.onmessage = s;
      return function() {
        r.port2.postMessage(0);
      };
    };
  }
}), require_stateChange = __commonJS({
  "node_modules/immediate/lib/stateChange.js"(s) {
    "use strict";
    s.test = function() {
      return "document" in window && "onreadystatechange" in window.document.createElement("script");
    };
    s.install = function(s) {
      return function() {
        var r = window.document.createElement("script");
        r.onreadystatechange = function() {
          s();
          r.onreadystatechange = null;
          r.parentNode.removeChild(r);
          r = null;
        };
        window.document.documentElement.appendChild(r);
        return s;
      };
    };
  }
}), require_timeout = __commonJS({
  "node_modules/immediate/lib/timeout.js"(s) {
    "use strict";
    s.test = function() {
      return true;
    };
    s.install = function(s) {
      return function() {
        setTimeout(s, 0);
      };
    };
  }
}), require_lib = __commonJS({
  "node_modules/immediate/lib/index.js"(s, r) {
    "use strict";
    var o, u, g, _ = [ require_nextTick(), require_queueMicrotask(), require_mutation(), require_messageChannel(), require_stateChange(), require_timeout() ], m = -1, b = [], E = false;
    function cleanUpNextTick() {
      if (o && u) {
        o = false;
        if (u.length) b = u.concat(b); else m = -1;
        if (b.length) nextTick();
      }
    }
    function nextTick() {
      if (!o) {
        E = false;
        o = true;
        for (var s = b.length, r = setTimeout(cleanUpNextTick); s; ) {
          u = b;
          b = [];
          for (;u && ++m < s; ) u[m].run();
          m = -1;
          s = b.length;
        }
        u = null;
        m = -1;
        o = false;
        clearTimeout(r);
      }
    }
    for (var w = -1, S = _.length; ++w < S; ) if (_[w] && _[w].test && _[w].test()) {
      g = _[w].install(nextTick);
      break;
    }
    function Item(s, r) {
      this.fun = s;
      this.array = r;
    }
    Item.prototype.run = function() {
      var s = this.fun, r = this.array;
      switch (r.length) {
       case 0:
        return s();

       case 1:
        return s(r[0]);

       case 2:
        return s(r[0], r[1]);

       case 3:
        return s(r[0], r[1], r[2]);

       default:
        return s.apply(null, r);
      }
    };
    r.exports = function immediate2(s) {
      var r = new Array(arguments.length - 1);
      if (arguments.length > 1) for (var u = 1; u < arguments.length; u++) r[u - 1] = arguments[u];
      b.push(new Item(s, r));
      if (!E && !o) {
        E = true;
        g();
      }
    };
  }
}), require_events = __commonJS({
  "node_modules/events/events.js"(s, r) {
    "use strict";
    var o, u = "object" == typeof Reflect ? Reflect : null, g = u && "function" == typeof u.apply ? u.apply : function ReflectApply2(s, r, o) {
      return Function.prototype.apply.call(s, r, o);
    };
    if (u && "function" == typeof u.ownKeys) o = u.ownKeys; else if (Object.getOwnPropertySymbols) o = function ReflectOwnKeys2(s) {
      return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s));
    }; else o = function ReflectOwnKeys2(s) {
      return Object.getOwnPropertyNames(s);
    };
    var _ = Number.isNaN || function NumberIsNaN2(s) {
      return s != s;
    };
    function EventEmitter2() {
      EventEmitter2.init.call(this);
    }
    r.exports = EventEmitter2;
    r.exports.once = function once2(s, r) {
      return new Promise((function(o, u) {
        function errorListener(o) {
          s.removeListener(r, resolver);
          u(o);
        }
        function resolver() {
          if ("function" == typeof s.removeListener) s.removeListener("error", errorListener);
          o([].slice.call(arguments));
        }
        eventTargetAgnosticAddListener(s, r, resolver, {
          once: true
        });
        if ("error" !== r) (function addErrorHandlerIfEventEmitter(s, r, o) {
          if ("function" == typeof s.on) eventTargetAgnosticAddListener(s, "error", r, o);
        })(s, errorListener, {
          once: true
        });
      }));
    };
    EventEmitter2.EventEmitter = EventEmitter2;
    EventEmitter2.prototype._events = void 0;
    EventEmitter2.prototype._eventsCount = 0;
    EventEmitter2.prototype._maxListeners = void 0;
    var m = 10;
    function checkListener(s) {
      if ("function" != typeof s) throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof s);
    }
    Object.defineProperty(EventEmitter2, "defaultMaxListeners", {
      enumerable: true,
      get: function() {
        return m;
      },
      set: function(s) {
        if ("number" != typeof s || s < 0 || _(s)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + s + ".");
        m = s;
      }
    });
    EventEmitter2.init = function() {
      if (void 0 === this._events || this._events === Object.getPrototypeOf(this)._events) {
        this._events = Object.create(null);
        this._eventsCount = 0;
      }
      this._maxListeners = this._maxListeners || void 0;
    };
    EventEmitter2.prototype.setMaxListeners = function setMaxListeners(s) {
      if ("number" != typeof s || s < 0 || _(s)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + s + ".");
      this._maxListeners = s;
      return this;
    };
    function _getMaxListeners(s) {
      if (void 0 === s._maxListeners) return EventEmitter2.defaultMaxListeners; else return s._maxListeners;
    }
    EventEmitter2.prototype.getMaxListeners = function getMaxListeners() {
      return _getMaxListeners(this);
    };
    EventEmitter2.prototype.emit = function emit2(s) {
      for (var r = [], o = 1; o < arguments.length; o++) r.push(arguments[o]);
      var u = "error" === s, _ = this._events;
      if (void 0 !== _) u = u && void 0 === _.error; else if (!u) return false;
      if (u) {
        var m;
        if (r.length > 0) m = r[0];
        if (m instanceof Error) throw m;
        var b = new Error("Unhandled error." + (m ? " (" + m.message + ")" : ""));
        b.context = m;
        throw b;
      }
      var E = _[s];
      if (void 0 === E) return false;
      if ("function" == typeof E) g(E, this, r); else {
        var w = E.length, S = arrayClone(E, w);
        for (o = 0; o < w; ++o) g(S[o], this, r);
      }
      return true;
    };
    function _addListener(s, r, o, u) {
      var g, _, m;
      checkListener(o);
      if (void 0 === (_ = s._events)) {
        _ = s._events = Object.create(null);
        s._eventsCount = 0;
      } else {
        if (void 0 !== _.newListener) {
          s.emit("newListener", r, o.listener ? o.listener : o);
          _ = s._events;
        }
        m = _[r];
      }
      if (void 0 === m) {
        m = _[r] = o;
        ++s._eventsCount;
      } else {
        if ("function" == typeof m) m = _[r] = u ? [ o, m ] : [ m, o ]; else if (u) m.unshift(o); else m.push(o);
        if ((g = _getMaxListeners(s)) > 0 && m.length > g && !m.warned) {
          m.warned = true;
          var b = new Error("Possible EventEmitter memory leak detected. " + m.length + " " + String(r) + " listeners added. Use emitter.setMaxListeners() to increase limit");
          b.name = "MaxListenersExceededWarning";
          b.emitter = s;
          b.type = r;
          b.count = m.length;
          (function ProcessEmitWarning(s) {
            if (console && console.warn) console.warn(s);
          })(b);
        }
      }
      return s;
    }
    EventEmitter2.prototype.addListener = function addListener(s, r) {
      return _addListener(this, s, r, false);
    };
    EventEmitter2.prototype.on = EventEmitter2.prototype.addListener;
    EventEmitter2.prototype.prependListener = function prependListener(s, r) {
      return _addListener(this, s, r, true);
    };
    function onceWrapper() {
      if (!this.fired) {
        this.target.removeListener(this.type, this.wrapFn);
        this.fired = true;
        if (0 === arguments.length) return this.listener.call(this.target); else return this.listener.apply(this.target, arguments);
      }
    }
    function _onceWrap(s, r, o) {
      var u = {
        fired: false,
        wrapFn: void 0,
        target: s,
        type: r,
        listener: o
      }, g = onceWrapper.bind(u);
      g.listener = o;
      u.wrapFn = g;
      return g;
    }
    EventEmitter2.prototype.once = function once3(s, r) {
      checkListener(r);
      this.on(s, _onceWrap(this, s, r));
      return this;
    };
    EventEmitter2.prototype.prependOnceListener = function prependOnceListener(s, r) {
      checkListener(r);
      this.prependListener(s, _onceWrap(this, s, r));
      return this;
    };
    EventEmitter2.prototype.removeListener = function removeListener(s, r) {
      var o, u, g, _, m;
      checkListener(r);
      if (void 0 === (u = this._events)) return this;
      if (void 0 === (o = u[s])) return this;
      if (o === r || o.listener === r) if (0 == --this._eventsCount) this._events = Object.create(null); else {
        delete u[s];
        if (u.removeListener) this.emit("removeListener", s, o.listener || r);
      } else if ("function" != typeof o) {
        g = -1;
        for (_ = o.length - 1; _ >= 0; _--) if (o[_] === r || o[_].listener === r) {
          m = o[_].listener;
          g = _;
          break;
        }
        if (g < 0) return this;
        if (0 === g) o.shift(); else (function spliceOne(s, r) {
          for (;r + 1 < s.length; r++) s[r] = s[r + 1];
          s.pop();
        })(o, g);
        if (1 === o.length) u[s] = o[0];
        if (void 0 !== u.removeListener) this.emit("removeListener", s, m || r);
      }
      return this;
    };
    EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
    EventEmitter2.prototype.removeAllListeners = function removeAllListeners(s) {
      var r, o, u;
      if (void 0 === (o = this._events)) return this;
      if (void 0 === o.removeListener) {
        if (0 === arguments.length) {
          this._events = Object.create(null);
          this._eventsCount = 0;
        } else if (void 0 !== o[s]) if (0 == --this._eventsCount) this._events = Object.create(null); else delete o[s];
        return this;
      }
      if (0 === arguments.length) {
        var g, _ = Object.keys(o);
        for (u = 0; u < _.length; ++u) if ("removeListener" !== (g = _[u])) this.removeAllListeners(g);
        this.removeAllListeners("removeListener");
        this._events = Object.create(null);
        this._eventsCount = 0;
        return this;
      }
      if ("function" == typeof (r = o[s])) this.removeListener(s, r); else if (void 0 !== r) for (u = r.length - 1; u >= 0; u--) this.removeListener(s, r[u]);
      return this;
    };
    function _listeners(s, r, o) {
      var u = s._events;
      if (void 0 === u) return [];
      var g = u[r];
      if (void 0 === g) return [];
      if ("function" == typeof g) return o ? [ g.listener || g ] : [ g ]; else return o ? function unwrapListeners(s) {
        for (var r = new Array(s.length), o = 0; o < r.length; ++o) r[o] = s[o].listener || s[o];
        return r;
      }(g) : arrayClone(g, g.length);
    }
    EventEmitter2.prototype.listeners = function listeners(s) {
      return _listeners(this, s, true);
    };
    EventEmitter2.prototype.rawListeners = function rawListeners(s) {
      return _listeners(this, s, false);
    };
    EventEmitter2.listenerCount = function(s, r) {
      if ("function" == typeof s.listenerCount) return s.listenerCount(r); else return listenerCount2.call(s, r);
    };
    EventEmitter2.prototype.listenerCount = listenerCount2;
    function listenerCount2(s) {
      var r = this._events;
      if (void 0 !== r) {
        var o = r[s];
        if ("function" == typeof o) return 1; else if (void 0 !== o) return o.length;
      }
      return 0;
    }
    EventEmitter2.prototype.eventNames = function eventNames() {
      return this._eventsCount > 0 ? o(this._events) : [];
    };
    function arrayClone(s, r) {
      for (var o = new Array(r), u = 0; u < r; ++u) o[u] = s[u];
      return o;
    }
    function eventTargetAgnosticAddListener(s, r, o, u) {
      if ("function" == typeof s.on) if (u.once) s.once(r, o); else s.on(r, o); else if ("function" == typeof s.addEventListener) s.addEventListener(r, (function wrapListener(g) {
        if (u.once) s.removeEventListener(r, wrapListener);
        o(g);
      })); else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof s);
    }
  }
}), require_spark_md5 = __commonJS({
  "node_modules/spark-md5/spark-md5.js"(s, r) {
    (function(o) {
      if ("object" == typeof s) r.exports = o(); else if ("function" == typeof define && define.amd) define(o); else {
        var u;
        try {
          u = window;
        } catch (s) {
          u = self;
        }
        u.SparkMD5 = o();
      }
    })((function(s) {
      "use strict";
      var r = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ];
      function md5cycle(s, r) {
        var o = s[0], u = s[1], g = s[2], _ = s[3];
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[0] - 680876936 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[1] - 389564586 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[2] + 606105819 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[3] - 1044525330 | 0) << 22 | u >>> 10) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[4] - 176418897 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[5] + 1200080426 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[6] - 1473231341 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[7] - 45705983 | 0) << 22 | u >>> 10) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[8] + 1770035416 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[9] - 1958414417 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[10] - 42063 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[11] - 1990404162 | 0) << 22 | u >>> 10) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[12] + 1804603682 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[13] - 40341101 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[14] - 1502002290 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[15] + 1236535329 | 0) << 22 | u >>> 10) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[1] - 165796510 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[6] - 1069501632 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[11] + 643717713 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[0] - 373897302 | 0) << 20 | u >>> 12) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[5] - 701558691 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[10] + 38016083 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[15] - 660478335 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[4] - 405537848 | 0) << 20 | u >>> 12) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[9] + 568446438 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[14] - 1019803690 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[3] - 187363961 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[8] + 1163531501 | 0) << 20 | u >>> 12) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[13] - 1444681467 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[2] - 51403784 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[7] + 1735328473 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[12] - 1926607734 | 0) << 20 | u >>> 12) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[5] - 378558 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[8] - 2022574463 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[11] + 1839030562 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[14] - 35309556 | 0) << 23 | u >>> 9) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[1] - 1530992060 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[4] + 1272893353 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[7] - 155497632 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[10] - 1094730640 | 0) << 23 | u >>> 9) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[13] + 681279174 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[0] - 358537222 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[3] - 722521979 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[6] + 76029189 | 0) << 23 | u >>> 9) + g | 0;
        u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[9] - 640364487 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[12] - 421815835 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[15] + 530742520 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[2] - 995338651 | 0) << 23 | u >>> 9) + g | 0;
        u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[0] - 198630844 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[7] + 1126891415 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[14] - 1416354905 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[5] - 57434055 | 0) << 21 | u >>> 11) + g | 0;
        u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[12] + 1700485571 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[3] - 1894986606 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[10] - 1051523 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[1] - 2054922799 | 0) << 21 | u >>> 11) + g | 0;
        u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[8] + 1873313359 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[15] - 30611744 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[6] - 1560198380 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[13] + 1309151649 | 0) << 21 | u >>> 11) + g | 0;
        u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[4] - 145523070 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[11] - 1120210379 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[2] + 718787259 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[9] - 343485551 | 0) << 21 | u >>> 11) + g | 0;
        s[0] = o + s[0] | 0;
        s[1] = u + s[1] | 0;
        s[2] = g + s[2] | 0;
        s[3] = _ + s[3] | 0;
      }
      function md5blk(s) {
        var r, o = [];
        for (r = 0; r < 64; r += 4) o[r >> 2] = s.charCodeAt(r) + (s.charCodeAt(r + 1) << 8) + (s.charCodeAt(r + 2) << 16) + (s.charCodeAt(r + 3) << 24);
        return o;
      }
      function md5blk_array(s) {
        var r, o = [];
        for (r = 0; r < 64; r += 4) o[r >> 2] = s[r] + (s[r + 1] << 8) + (s[r + 2] << 16) + (s[r + 3] << 24);
        return o;
      }
      function md51(s) {
        var r, o, u, g, _, m, b = s.length, E = [ 1732584193, -271733879, -1732584194, 271733878 ];
        for (r = 64; r <= b; r += 64) md5cycle(E, md5blk(s.substring(r - 64, r)));
        o = (s = s.substring(r - 64)).length;
        u = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
        for (r = 0; r < o; r += 1) u[r >> 2] |= s.charCodeAt(r) << (r % 4 << 3);
        u[r >> 2] |= 128 << (r % 4 << 3);
        if (r > 55) {
          md5cycle(E, u);
          for (r = 0; r < 16; r += 1) u[r] = 0;
        }
        g = (g = 8 * b).toString(16).match(/(.*?)(.{0,8})$/);
        _ = parseInt(g[2], 16);
        m = parseInt(g[1], 16) || 0;
        u[14] = _;
        u[15] = m;
        md5cycle(E, u);
        return E;
      }
      function rhex(s) {
        var o, u = "";
        for (o = 0; o < 4; o += 1) u += r[s >> 8 * o + 4 & 15] + r[s >> 8 * o & 15];
        return u;
      }
      function hex(s) {
        var r;
        for (r = 0; r < s.length; r += 1) s[r] = rhex(s[r]);
        return s.join("");
      }
      if ("5d41402abc4b2a76b9719d911017c592" !== hex(md51("hello"))) ;
      if ("undefined" != typeof ArrayBuffer && !ArrayBuffer.prototype.slice) (function() {
        function clamp(s, r) {
          if ((s = 0 | s || 0) < 0) return Math.max(s + r, 0); else return Math.min(s, r);
        }
        ArrayBuffer.prototype.slice = function(r, o) {
          var u, g, _, m, b = this.byteLength, E = clamp(r, b), w = b;
          if (o !== s) w = clamp(o, b);
          if (E > w) return new ArrayBuffer(0);
          u = w - E;
          g = new ArrayBuffer(u);
          _ = new Uint8Array(g);
          m = new Uint8Array(this, E, u);
          _.set(m);
          return g;
        };
      })();
      function toUtf8(s) {
        if (/[\u0080-\uFFFF]/.test(s)) s = unescape(encodeURIComponent(s));
        return s;
      }
      function hexToBinaryString(s) {
        var r, o = [], u = s.length;
        for (r = 0; r < u - 1; r += 2) o.push(parseInt(s.substr(r, 2), 16));
        return String.fromCharCode.apply(String, o);
      }
      function SparkMD5() {
        this.reset();
      }
      SparkMD5.prototype.append = function(s) {
        this.appendBinary(toUtf8(s));
        return this;
      };
      SparkMD5.prototype.appendBinary = function(s) {
        this._buff += s;
        this._length += s.length;
        var r, o = this._buff.length;
        for (r = 64; r <= o; r += 64) md5cycle(this._hash, md5blk(this._buff.substring(r - 64, r)));
        this._buff = this._buff.substring(r - 64);
        return this;
      };
      SparkMD5.prototype.end = function(s) {
        var r, o, u = this._buff, g = u.length, _ = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
        for (r = 0; r < g; r += 1) _[r >> 2] |= u.charCodeAt(r) << (r % 4 << 3);
        this._finish(_, g);
        o = hex(this._hash);
        if (s) o = hexToBinaryString(o);
        this.reset();
        return o;
      };
      SparkMD5.prototype.reset = function() {
        this._buff = "";
        this._length = 0;
        this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];
        return this;
      };
      SparkMD5.prototype.getState = function() {
        return {
          buff: this._buff,
          length: this._length,
          hash: this._hash.slice()
        };
      };
      SparkMD5.prototype.setState = function(s) {
        this._buff = s.buff;
        this._length = s.length;
        this._hash = s.hash;
        return this;
      };
      SparkMD5.prototype.destroy = function() {
        delete this._hash;
        delete this._buff;
        delete this._length;
      };
      SparkMD5.prototype._finish = function(s, r) {
        var o, u, g, _ = r;
        s[_ >> 2] |= 128 << (_ % 4 << 3);
        if (_ > 55) {
          md5cycle(this._hash, s);
          for (_ = 0; _ < 16; _ += 1) s[_] = 0;
        }
        o = (o = 8 * this._length).toString(16).match(/(.*?)(.{0,8})$/);
        u = parseInt(o[2], 16);
        g = parseInt(o[1], 16) || 0;
        s[14] = u;
        s[15] = g;
        md5cycle(this._hash, s);
      };
      SparkMD5.hash = function(s, r) {
        return SparkMD5.hashBinary(toUtf8(s), r);
      };
      SparkMD5.hashBinary = function(s, r) {
        var o = hex(md51(s));
        return r ? hexToBinaryString(o) : o;
      };
      SparkMD5.ArrayBuffer = function() {
        this.reset();
      };
      SparkMD5.ArrayBuffer.prototype.append = function(s) {
        var r, o = function concatenateArrayBuffers(s, r, o) {
          var u = new Uint8Array(s.byteLength + r.byteLength);
          u.set(new Uint8Array(s));
          u.set(new Uint8Array(r), s.byteLength);
          return o ? u : u.buffer;
        }(this._buff.buffer, s, true), u = o.length;
        this._length += s.byteLength;
        for (r = 64; r <= u; r += 64) md5cycle(this._hash, md5blk_array(o.subarray(r - 64, r)));
        this._buff = r - 64 < u ? new Uint8Array(o.buffer.slice(r - 64)) : new Uint8Array(0);
        return this;
      };
      SparkMD5.ArrayBuffer.prototype.end = function(s) {
        var r, o, u = this._buff, g = u.length, _ = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
        for (r = 0; r < g; r += 1) _[r >> 2] |= u[r] << (r % 4 << 3);
        this._finish(_, g);
        o = hex(this._hash);
        if (s) o = hexToBinaryString(o);
        this.reset();
        return o;
      };
      SparkMD5.ArrayBuffer.prototype.reset = function() {
        this._buff = new Uint8Array(0);
        this._length = 0;
        this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];
        return this;
      };
      SparkMD5.ArrayBuffer.prototype.getState = function() {
        var s = SparkMD5.prototype.getState.call(this);
        s.buff = function arrayBuffer2Utf8Str(s) {
          return String.fromCharCode.apply(null, new Uint8Array(s));
        }(s.buff);
        return s;
      };
      SparkMD5.ArrayBuffer.prototype.setState = function(s) {
        s.buff = function utf8Str2ArrayBuffer(s, r) {
          var o, u = s.length, g = new ArrayBuffer(u), _ = new Uint8Array(g);
          for (o = 0; o < u; o += 1) _[o] = s.charCodeAt(o);
          return r ? _ : g;
        }(s.buff, true);
        return SparkMD5.prototype.setState.call(this, s);
      };
      SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
      SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
      SparkMD5.ArrayBuffer.hash = function(s, r) {
        var o = function md51_array(s) {
          var r, o, u, g, _, m, b = s.length, E = [ 1732584193, -271733879, -1732584194, 271733878 ];
          for (r = 64; r <= b; r += 64) md5cycle(E, md5blk_array(s.subarray(r - 64, r)));
          o = (s = r - 64 < b ? s.subarray(r - 64) : new Uint8Array(0)).length;
          u = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
          for (r = 0; r < o; r += 1) u[r >> 2] |= s[r] << (r % 4 << 3);
          u[r >> 2] |= 128 << (r % 4 << 3);
          if (r > 55) {
            md5cycle(E, u);
            for (r = 0; r < 16; r += 1) u[r] = 0;
          }
          g = (g = 8 * b).toString(16).match(/(.*?)(.{0,8})$/);
          _ = parseInt(g[2], 16);
          m = parseInt(g[1], 16) || 0;
          u[14] = _;
          u[15] = m;
          md5cycle(E, u);
          return E;
        }(new Uint8Array(s)), u = hex(o);
        return r ? hexToBinaryString(u) : u;
      };
      return SparkMD5;
    }));
  }
}), require_vuvuzela = __commonJS({
  "node_modules/vuvuzela/index.js"(s) {
    "use strict";
    s.stringify = function stringify3(s) {
      var r = [];
      r.push({
        obj: s
      });
      for (var o, u, g, _, m, b, E, w, S, L, O = ""; o = r.pop(); ) {
        u = o.obj;
        O += o.prefix || "";
        if (g = o.val || "") O += g; else if ("object" != typeof u) O += "undefined" == typeof u ? null : JSON.stringify(u); else if (null === u) O += "null"; else if (Array.isArray(u)) {
          r.push({
            val: "]"
          });
          for (_ = u.length - 1; _ >= 0; _--) {
            m = 0 === _ ? "" : ",";
            r.push({
              obj: u[_],
              prefix: m
            });
          }
          r.push({
            val: "["
          });
        } else {
          b = [];
          for (E in u) if (u.hasOwnProperty(E)) b.push(E);
          r.push({
            val: "}"
          });
          for (_ = b.length - 1; _ >= 0; _--) {
            S = u[w = b[_]];
            L = _ > 0 ? "," : "";
            L += JSON.stringify(w) + ":";
            r.push({
              obj: S,
              prefix: L
            });
          }
          r.push({
            val: "{"
          });
        }
      }
      return O;
    };
    function pop2(s, r, o) {
      var u = o[o.length - 1];
      if (s === u.element) {
        o.pop();
        u = o[o.length - 1];
      }
      var g = u.element, _ = u.index;
      if (Array.isArray(g)) g.push(s); else if (_ === r.length - 2) g[r.pop()] = s; else r.push(s);
    }
    s.parse = function(s) {
      for (var r, o, u, g, _, m, b, E, w, S = [], L = [], O = 0; ;) {
        if ("}" === (r = s[O++]) || "]" === r || "undefined" == typeof r) if (1 === S.length) return S.pop(); else {
          pop2(S.pop(), S, L);
          continue;
        }
        switch (r) {
         case " ":
         case "\t":
         case "\n":
         case ":":
         case ",":
          break;

         case "n":
          O += 3;
          pop2(null, S, L);
          break;

         case "t":
          O += 3;
          pop2(true, S, L);
          break;

         case "f":
          O += 4;
          pop2(false, S, L);
          break;

         case "0":
         case "1":
         case "2":
         case "3":
         case "4":
         case "5":
         case "6":
         case "7":
         case "8":
         case "9":
         case "-":
          o = "";
          O--;
          for (;;) {
            u = s[O++];
            if (/[\d\.\-e\+]/.test(u)) o += u; else {
              O--;
              break;
            }
          }
          pop2(parseFloat(o), S, L);
          break;

         case '"':
          g = "";
          _ = void 0;
          m = 0;
          for (;'"' !== (b = s[O++]) || "\\" === _ && m % 2 == 1; ) {
            g += b;
            if ("\\" === (_ = b)) m++; else m = 0;
          }
          pop2(JSON.parse('"' + g + '"'), S, L);
          break;

         case "[":
          E = {
            element: [],
            index: S.length
          };
          S.push(E.element);
          L.push(E);
          break;

         case "{":
          w = {
            element: {},
            index: S.length
          };
          S.push(w.element);
          L.push(w);
          break;

         default:
          throw new Error("unexpectedly reached end of input: " + r);
        }
      }
    };
  }
}), require_pouchdb_wrappers = __commonJS({
  "node_modules/pouchdb-wrappers/index.js"(s, r) {
    "use strict";
    function replacementMethod(s, r) {
      return function(...o) {
        function doMethod() {
          let u = null;
          const g = "query" === r ? 1 : 0;
          if (o.length > g && "function" == typeof o[o.length - 1]) u = o.pop();
          let _ = s._originals[r].bind(s);
          for (const o of s._handlers[r]) _ = o.bind(s, _);
          const m = _(...o);
          if (m.then && u) (function nodify(s, r) {
            s.then(((...s) => {
              r(null, ...s);
            })).catch((s => {
              r(s);
            }));
          })(m, u);
          return m;
        }
        if ("changes" !== r && s.taskqueue && !s.taskqueue.isReady) return new Promise(((r, o) => {
          s.taskqueue.addTask((s => {
            if (s) o(s); else r();
          }));
        })).then(doMethod); else return doMethod();
      };
    }
    var o = {
      install: function installWrappers(s, r = {}) {
        if (!s._originals || !s._handlers) {
          s._originals = {};
          s._handlers = {};
        }
        for (const [o, u] of Object.entries(r)) {
          if (!(o in s)) throw new Error(`Method '${o}' does not exist on given base, so it cannot be wrapped.`);
          if (!(o in s._originals)) s._originals[o] = s[o];
          if (o in s._handlers) s._handlers[o].unshift(u); else {
            s._handlers[o] = [ u ];
            s[o] = replacementMethod(s, o);
          }
        }
      },
      uninstall: function uninstallWrappers(s, r) {
        if (!s._originals || !s._handlers) throw new Error("No wrapper methods installed, so no methods can be uninstalled.");
        for (const [o, u] of Object.entries(r)) {
          const r = `Wrapper method for '${o}' not installed: ${u.toString()}`;
          if (!(o in s._handlers)) throw new Error(r);
          const g = s._handlers[o].indexOf(u);
          if (-1 === g) throw new Error(r); else s._handlers[o].splice(g, 1);
        }
      }
    };
    try {
      r.exports = o;
    } catch (s) {}
    try {
      window.PouchDBWrappers = o;
    } catch (s) {}
  }
}), require_transform_pouch = __commonJS({
  "node_modules/transform-pouch/index.js"(s, r) {
    "use strict";
    var o = require_pouchdb_wrappers();
    function isntInternalKey(s) {
      return "_" !== s[0];
    }
    function isUntransformable(s) {
      if ("string" == typeof s._id && /^_local/.test(s._id)) return true;
      if (s._deleted) return 0 === Object.keys(s).filter(isntInternalKey).length; else return false;
    }
    r.exports = {
      transform: transform2,
      filter: transform2
    };
    function transform2(s) {
      const incoming = function(r) {
        if (!isUntransformable(r) && s.incoming) return s.incoming(r); else return r;
      }, outgoing = function(r) {
        if (!isUntransformable(r) && s.outgoing) return s.outgoing(r); else return r;
      }, r = {
        async get(s, ...r) {
          const o = await s(...r);
          if (Array.isArray(o)) {
            await Promise.all(o.map((async s => {
              if (s.ok) s.ok = await outgoing(s.ok);
            })));
            return o;
          } else return outgoing(o);
        },
        async bulkDocs(s, r, ...o) {
          if (r.docs) r.docs = await Promise.all(r.docs.map(incoming)); else r = await Promise.all(r.map(incoming));
          return s(r, ...o);
        },
        async allDocs(s, ...r) {
          const o = await s(...r);
          await Promise.all(o.rows.map((async s => {
            if (s.doc) s.doc = await outgoing(s.doc);
          })));
          return o;
        },
        async bulkGet(s, ...r) {
          const mapDoc = async s => {
            if (s.ok) return {
              ok: await outgoing(s.ok)
            }; else return s;
          };
          let {results: o, ...u} = await s(...r);
          o = await Promise.all(o.map((async s => {
            const {id: r, docs: o} = s;
            if (r && o && Array.isArray(o)) return {
              id: r,
              docs: await Promise.all(o.map(mapDoc))
            }; else return s;
          })));
          return {
            results: o,
            ...u
          };
        },
        changes(s, ...r) {
          async function modifyChange(s) {
            if (s.doc) {
              s.doc = await outgoing(s.doc);
              return s;
            }
            return s;
          }
          async function modifyChanges(s) {
            if (s.results) {
              s.results = await Promise.all(s.results.map(modifyChange));
              return s;
            }
            return s;
          }
          const o = s(...r), {on: u, then: g} = o;
          return Object.assign(o, {
            on(s, r) {
              const g = r;
              if ("change" === s) r = async s => {
                g(await modifyChange(s));
              }; else if ("complete" === s) r = async s => {
                g(await modifyChanges(s));
              };
              return u.call(o, s, r);
            },
            then: (s, r) => g.call(o, modifyChanges).then(s, r)
          });
        }
      };
      if ("http" === this.type()) {
        r.put = async function(s, r, ...o) {
          return s(r = await incoming(r), ...o);
        };
        r.query = async function(s, ...r) {
          const o = await s(...r);
          await Promise.all(o.rows.map((async s => {
            if (s.doc) s.doc = await outgoing(s.doc);
          })));
          return o;
        };
      }
      o.install(this, r);
    }
    if ("undefined" != typeof window && window.PouchDB) window.PouchDB.plugin(s);
  }
}), main_exports = {};

__export(main_exports, {
  default: () => ObsidianLiveSyncPlugin
});

module.exports = __toCommonJS(main_exports);

var symbolFilePath = Symbol(), symbolFilePathWithPrefix = Symbol(), symbolId = Symbol(), MAX_DOC_SIZE_BIN = 102400, VER = 10, LEAF_WAIT_TIMEOUT = 9e4, REPLICATION_BUSY_TIMEOUT = 3e6, LOG_LEVEL_DEBUG = -1, LOG_LEVEL_VERBOSE = 1, LOG_LEVEL_INFO = 10, LOG_LEVEL_NOTICE = 100, LOG_LEVEL_URGENT = 1e3, CANCELLED = Symbol("cancelled"), AUTO_MERGED = Symbol("auto_merged"), NOT_CONFLICTED = Symbol("not_conflicted"), MISSING_OR_ERROR = Symbol("missing_or_error"), LEAVE_TO_SUBSEQUENT = Symbol("leave_to_subsequent_proc"), TIME_ARGUMENT_INFINITY = Symbol("infinity"), RESULT_TIMED_OUT = Symbol("timed out"), RESULT_NOT_FOUND = Symbol("NotFound"), VERSIONINFO_DOCID = "obsydian_livesync_version", MILSTONE_DOCID = "_local/obsydian_livesync_milestone", NODEINFO_DOCID = "_local/obsydian_livesync_nodeinfo", MODE_SELECTIVE = 0, MODE_AUTOMATIC = 1, MODE_PAUSED = 2, DEFAULT_SETTINGS = {
  couchDB_URI: "",
  couchDB_USER: "",
  couchDB_PASSWORD: "",
  couchDB_DBNAME: "",
  liveSync: false,
  syncOnSave: false,
  syncOnStart: false,
  savingDelay: 200,
  lessInformationInLog: false,
  gcDelay: 300,
  versionUpFlash: "",
  minimumChunkSize: 20,
  longLineThreshold: 250,
  showVerboseLog: false,
  suspendFileWatching: false,
  trashInsteadDelete: true,
  periodicReplication: false,
  periodicReplicationInterval: 60,
  syncOnFileOpen: false,
  encrypt: false,
  passphrase: "",
  usePathObfuscation: false,
  doNotDeleteFolder: false,
  resolveConflictsByNewerFile: false,
  batchSave: false,
  deviceAndVaultName: "",
  usePluginSettings: false,
  showOwnPlugins: false,
  showStatusOnEditor: true,
  showStatusOnStatusbar: true,
  showOnlyIconsOnEditor: false,
  usePluginSync: false,
  autoSweepPlugins: false,
  autoSweepPluginsPeriodic: false,
  notifyPluginOrSettingUpdated: false,
  checkIntegrityOnSave: false,
  batch_size: 25,
  batches_limit: 25,
  useHistory: false,
  disableRequestURI: false,
  skipOlderFilesOnSync: true,
  checkConflictOnlyOnOpen: false,
  showMergeDialogOnlyOnActive: false,
  syncInternalFiles: false,
  syncInternalFilesBeforeReplication: false,
  syncInternalFilesIgnorePatterns: "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/",
  syncInternalFilesInterval: 60,
  additionalSuffixOfDatabaseName: "",
  ignoreVersionCheck: false,
  lastReadUpdates: 0,
  deleteMetadataOfDeletedFiles: false,
  syncIgnoreRegEx: "",
  syncOnlyRegEx: "",
  customChunkSize: 0,
  readChunksOnline: true,
  watchInternalFileChanges: true,
  automaticallyDeleteMetadataOfDeletedFiles: 0,
  disableMarkdownAutoMerge: false,
  writeDocumentsIfConflicted: false,
  useDynamicIterationCount: false,
  syncAfterMerge: false,
  configPassphraseStore: "",
  encryptedPassphrase: "",
  encryptedCouchDBConnection: "",
  permitEmptyPassphrase: false,
  useIndexedDBAdapter: true,
  useTimeouts: false,
  writeLogToTheFile: false,
  doNotPaceReplication: false,
  hashCacheMaxCount: 300,
  hashCacheMaxAmount: 50,
  concurrencyOfReadChunksOnline: 40,
  minimumIntervalOfReadChunksOnline: 50,
  hashAlg: "xxhash64",
  suspendParseReplicationResult: false,
  doNotSuspendOnFetching: false,
  useIgnoreFiles: false,
  ignoreFiles: ".gitignore",
  syncOnEditorSave: false,
  pluginSyncExtendedSetting: {},
  syncMaxSizeInMB: 50,
  settingSyncFile: "",
  writeCredentialsForSettingSync: false,
  notifyAllSettingSyncFile: false,
  isConfigured: void 0,
  settingVersion: 0
}, PREFERRED_SETTING_CLOUDANT = {
  syncMaxSizeInMB: 50,
  customChunkSize: 0,
  concurrencyOfReadChunksOnline: 100,
  minimumIntervalOfReadChunksOnline: 333
}, PREFERRED_SETTING_SELF_HOSTED = {
  ...PREFERRED_SETTING_CLOUDANT,
  customChunkSize: 50,
  concurrencyOfReadChunksOnline: 30,
  minimumIntervalOfReadChunksOnline: 25
}, PREFIXMD_LOGFILE = "LIVESYNC_LOG_", FLAGMD_REDFLAG = "redflag.md", FLAGMD_REDFLAG2 = "redflag2.md", FLAGMD_REDFLAG2_HR = "flag_rebuild.md", FLAGMD_REDFLAG3 = "redflag3.md", FLAGMD_REDFLAG3_HR = "flag_fetch.md", SYNCINFO_ID = "syncinfo", SALT_OF_PASSPHRASE = "rHGMPtr6oWw7VSa3W3wpa8fT8U", PREFIX_OBFUSCATED = "f:", PREFIX_CHUNK = "h:", PREFIX_ENCRYPTED_CHUNK = "h:+", import_obsidian = require("obsidian"), import_obsidian2 = require("obsidian"), import_diff_match_patch = __toESM(require_diff_match_patch(), 1), normalizePath = import_obsidian2.normalizePath, PERIODIC_PLUGIN_SWEEP = 60, CHeader = "h:", PSCHeader = "ps:", ICHeader = "i:", ICHeaderEnd = "i;", ICHeaderLength = ICHeader.length, ICXHeader = "ix:", FileWatchEventQueueMax = 10, configURIBase = "obsidian://setuplivesync?settings=", LEVEL_INFO = LOG_LEVEL_INFO, defaultLoggerEnv = {
  minLogLevel: LOG_LEVEL_INFO
}, defaultLogger = function defaultLogger2(s, r = LEVEL_INFO, o) {
  if (r < defaultLoggerEnv.minLogLevel) return;
  const u = (new Date).toLocaleString(), g = "string" == typeof s ? s : s instanceof Error ? `${s.name}:${s.message}` : JSON.stringify(s, null, 2);
  if (s instanceof Error) console.dir(s.stack);
  const _ = `${u}\t${r}\t${g}`;
  console.log(_);
}, _logger = defaultLogger;

function setGlobalLogFunction(s) {
  _logger = s;
}

function Logger(s, r, o) {
  _logger(s, r, o);
}

var _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _fillNegs, fillNegs_fn, _parseAST, parseAST_fn, _partsToRegExp, partsToRegExp_fn, _parseGlob, parseGlob_fn, LRUCache = class {
  constructor(s, r, o = false) {
    this.cache = new Map([]);
    this.revCache = new Map([]);
    this.maxCache = 200;
    this.maxCachedLength = 5e7;
    this.cachedLength = 0;
    this.enableReversed = true;
    this.maxCache = s || 200;
    this.maxCachedLength = 1e6 * (r || 1);
    this.enableReversed = !o;
    Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`, LOG_LEVEL_VERBOSE);
  }
  clear() {
    this.cache.clear();
    this.revCache.clear();
  }
  has(s) {
    return this.cache.has(s);
  }
  get(s) {
    const r = this.cache.get(s);
    if (r) {
      this.cache.delete(s);
      this.cache.set(s, r);
      if (this.enableReversed) {
        this.revCache.delete(r);
        this.revCache.set(r, s);
      }
    }
    return r;
  }
  revGet(s) {
    const r = this.revCache.get(s);
    if (s) {
      this.cache.delete(r);
      this.revCache.delete(s);
      this.cache.set(r, s);
      this.revCache.set(s, r);
    }
    return r;
  }
  set(s, r) {
    this.cache.set(s, r);
    if (this.enableReversed) this.revCache.set(r, s);
    this.cachedLength += `${r}`.length;
    if (this.cache.size > this.maxCache || this.cachedLength > this.maxCachedLength) for (const [s, r] of this.cache) {
      this.cache.delete(s);
      if (this.enableReversed) this.revCache.delete(r);
      this.cachedLength -= `${r}`.length;
      if (this.cache.size <= this.maxCache && this.cachedLength <= this.maxCachedLength) break;
    }
  }
}, import_brace_expansion = __toESM(require_brace_expansion(), 1), MAX_PATTERN_LENGTH = 65536, assertValidPattern = s => {
  if ("string" != typeof s) throw new TypeError("invalid pattern");
  if (s.length > MAX_PATTERN_LENGTH) throw new TypeError("pattern is too long");
}, posixClasses = {
  "[:alnum:]": [ "\\p{L}\\p{Nl}\\p{Nd}", true ],
  "[:alpha:]": [ "\\p{L}\\p{Nl}", true ],
  "[:ascii:]": [ "\\x00-\\x7f", false ],
  "[:blank:]": [ "\\p{Zs}\\t", true ],
  "[:cntrl:]": [ "\\p{Cc}", true ],
  "[:digit:]": [ "\\p{Nd}", true ],
  "[:graph:]": [ "\\p{Z}\\p{C}", true, true ],
  "[:lower:]": [ "\\p{Ll}", true ],
  "[:print:]": [ "\\p{C}", true ],
  "[:punct:]": [ "\\p{P}", true ],
  "[:space:]": [ "\\p{Z}\\t\\r\\n\\v\\f", true ],
  "[:upper:]": [ "\\p{Lu}", true ],
  "[:word:]": [ "\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true ],
  "[:xdigit:]": [ "A-Fa-f0-9", false ]
}, braceEscape = s => s.replace(/[[\]\\-]/g, "\\$&"), regexpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), rangesToString = s => s.join(""), parseClass = (s, r) => {
  const o = r;
  if ("[" !== s.charAt(o)) throw new Error("not in a brace expression");
  const u = [], g = [];
  let _ = o + 1, m = false, b = false, E = false, w = false, S = o, L = "";
  e: for (;_ < s.length; ) {
    const r = s.charAt(_);
    if ("!" !== r && "^" !== r || _ !== o + 1) {
      if ("]" === r && m && !E) {
        S = _ + 1;
        break;
      }
      m = true;
      if ("\\" === r) if (!E) {
        E = true;
        _++;
        continue;
      }
      if ("[" === r && !E) for (const [r, [m, E, w]] of Object.entries(posixClasses)) if (s.startsWith(r, _)) {
        if (L) return [ "$.", false, s.length - o, true ];
        _ += r.length;
        if (w) g.push(m); else u.push(m);
        b = b || E;
        continue e;
      }
      E = false;
      if (!L) if (!s.startsWith("-]", _ + 1)) if (!s.startsWith("-", _ + 1)) {
        u.push(braceEscape(r));
        _++;
      } else {
        L = r;
        _ += 2;
      } else {
        u.push(braceEscape(r + "-"));
        _ += 2;
      } else {
        if (r > L) u.push(braceEscape(L) + "-" + braceEscape(r)); else if (r === L) u.push(braceEscape(r));
        L = "";
        _++;
      }
    } else {
      w = true;
      _++;
    }
  }
  if (S < _) return [ "", false, 0, false ];
  if (!u.length && !g.length) return [ "$.", false, s.length - o, true ];
  if (0 === g.length && 1 === u.length && /^\\?.$/.test(u[0]) && !w) {
    const s = 2 === u[0].length ? u[0].slice(-1) : u[0];
    return [ regexpEscape(s), false, S - o, false ];
  }
  const O = "[" + (w ? "^" : "") + rangesToString(u) + "]", D = "[" + (w ? "" : "^") + rangesToString(g) + "]";
  return [ u.length && g.length ? "(" + O + "|" + D + ")" : u.length ? O : D, b, S - o, true ];
}, unescape2 = (s, {windowsPathsNoEscape: r = false} = {}) => r ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"), types = new Set([ "!", "?", "+", "*", "@" ]), isExtglobType = s => types.has(s), startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))", startNoDot = "(?!\\.)", addPatternStart = new Set([ "[", "." ]), justDots = new Set([ "..", "." ]), reSpecials = new Set("().*{}+?[]^$\\!"), regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), qmark = "[^/]", star = qmark + "*?", starNoEmpty = qmark + "+?", _AST = class _AST {
  constructor(s, r, o = {}) {
    __privateAdd(this, _fillNegs);
    __privateAdd(this, _partsToRegExp);
    __publicField(this, "type");
    __privateAdd(this, _root, void 0);
    __privateAdd(this, _hasMagic, void 0);
    __privateAdd(this, _uflag, false);
    __privateAdd(this, _parts, []);
    __privateAdd(this, _parent, void 0);
    __privateAdd(this, _parentIndex, void 0);
    __privateAdd(this, _negs, void 0);
    __privateAdd(this, _filledNegs, false);
    __privateAdd(this, _options, void 0);
    __privateAdd(this, _toString, void 0);
    __privateAdd(this, _emptyExt, false);
    this.type = s;
    if (s) __privateSet(this, _hasMagic, true);
    __privateSet(this, _parent, r);
    __privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this);
    __privateSet(this, _options, __privateGet(this, _root) === this ? o : __privateGet(__privateGet(this, _root), _options));
    __privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs));
    if ("!" === s && !__privateGet(__privateGet(this, _root), _filledNegs)) __privateGet(this, _negs).push(this);
    __privateSet(this, _parentIndex, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0);
  }
  get hasMagic() {
    if (void 0 !== __privateGet(this, _hasMagic)) return __privateGet(this, _hasMagic);
    for (const s of __privateGet(this, _parts)) if ("string" != typeof s) if (s.type || s.hasMagic) return __privateSet(this, _hasMagic, true);
    return __privateGet(this, _hasMagic);
  }
  toString() {
    if (void 0 !== __privateGet(this, _toString)) return __privateGet(this, _toString);
    if (!this.type) return __privateSet(this, _toString, __privateGet(this, _parts).map((s => String(s))).join("")); else return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((s => String(s))).join("|") + ")");
  }
  push(...s) {
    for (const r of s) if ("" !== r) {
      if ("string" != typeof r && !(r instanceof _AST && __privateGet(r, _parent) === this)) throw new Error("invalid part: " + r);
      __privateGet(this, _parts).push(r);
    }
  }
  toJSON() {
    var s;
    const r = null === this.type ? __privateGet(this, _parts).slice().map((s => "string" == typeof s ? s : s.toJSON())) : [ this.type, ...__privateGet(this, _parts).map((s => s.toJSON())) ];
    if (this.isStart() && !this.type) r.unshift([]);
    if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && "!" === (null == (s = __privateGet(this, _parent)) ? void 0 : s.type))) r.push({});
    return r;
  }
  isStart() {
    var s;
    if (__privateGet(this, _root) === this) return true;
    if (!(null == (s = __privateGet(this, _parent)) ? void 0 : s.isStart())) return false;
    if (0 === __privateGet(this, _parentIndex)) return true;
    const r = __privateGet(this, _parent);
    for (let s = 0; s < __privateGet(this, _parentIndex); s++) {
      const o = __privateGet(r, _parts)[s];
      if (!(o instanceof _AST && "!" === o.type)) return false;
    }
    return true;
  }
  isEnd() {
    var s, r, o;
    if (__privateGet(this, _root) === this) return true;
    if ("!" === (null == (s = __privateGet(this, _parent)) ? void 0 : s.type)) return true;
    if (!(null == (r = __privateGet(this, _parent)) ? void 0 : r.isEnd())) return false;
    if (!this.type) return null == (o = __privateGet(this, _parent)) ? void 0 : o.isEnd();
    const u = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0;
    return __privateGet(this, _parentIndex) === u - 1;
  }
  copyIn(s) {
    if ("string" == typeof s) this.push(s); else this.push(s.clone(this));
  }
  clone(s) {
    const r = new _AST(this.type, s);
    for (const s of __privateGet(this, _parts)) r.copyIn(s);
    return r;
  }
  static fromGlob(s, r = {}) {
    var o;
    const u = new _AST(null, void 0, r);
    __privateMethod(o = _AST, _parseAST, parseAST_fn).call(o, s, u, 0, r);
    return u;
  }
  toMMPattern() {
    if (this !== __privateGet(this, _root)) return __privateGet(this, _root).toMMPattern();
    const s = this.toString(), [r, o, u, g] = this.toRegExpSource();
    if (!(u || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && s.toUpperCase() !== s.toLowerCase())) return o;
    const _ = (__privateGet(this, _options).nocase ? "i" : "") + (g ? "u" : "");
    return Object.assign(new RegExp(`^${r}$`, _), {
      _src: r,
      _glob: s
    });
  }
  toRegExpSource(s) {
    var r;
    const o = null != s ? s : !!__privateGet(this, _options).dot;
    if (__privateGet(this, _root) === this) __privateMethod(this, _fillNegs, fillNegs_fn).call(this);
    if (!this.type) {
      const u = this.isStart() && this.isEnd(), g = __privateGet(this, _parts).map((r => {
        var o;
        const [g, _, m, b] = "string" == typeof r ? __privateMethod(o = _AST, _parseGlob, parseGlob_fn).call(o, r, __privateGet(this, _hasMagic), u) : r.toRegExpSource(s);
        __privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || m);
        __privateSet(this, _uflag, __privateGet(this, _uflag) || b);
        return g;
      })).join("");
      let _ = "";
      if (this.isStart()) if ("string" == typeof __privateGet(this, _parts)[0]) if (!(1 === __privateGet(this, _parts).length && justDots.has(__privateGet(this, _parts)[0]))) {
        const r = addPatternStart, u = o && r.has(g.charAt(0)) || g.startsWith("\\.") && r.has(g.charAt(2)) || g.startsWith("\\.\\.") && r.has(g.charAt(4)), m = !o && !s && r.has(g.charAt(0));
        _ = u ? startNoTraversal : m ? startNoDot : "";
      }
      let m = "";
      if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && "!" === (null == (r = __privateGet(this, _parent)) ? void 0 : r.type)) m = "(?:$|\\/)";
      return [ _ + g + m, unescape2(g), __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)), __privateGet(this, _uflag) ];
    }
    const u = "*" === this.type || "+" === this.type, g = "!" === this.type ? "(?:(?!(?:" : "(?:";
    let _ = __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, o);
    if (this.isStart() && this.isEnd() && !_ && "!" !== this.type) {
      const s = this.toString();
      __privateSet(this, _parts, [ s ]);
      this.type = null;
      __privateSet(this, _hasMagic, void 0);
      return [ s, unescape2(this.toString()), false, false ];
    }
    let m = !u || s || o || !startNoDot ? "" : __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, true);
    if (m === _) m = "";
    if (m) _ = `(?:${_})(?:${m})*?`;
    let b = "";
    if ("!" === this.type && __privateGet(this, _emptyExt)) b = (this.isStart() && !o ? startNoDot : "") + starNoEmpty; else b = g + _ + ("!" === this.type ? "))" + (this.isStart() && !o && !s ? startNoDot : "") + star + ")" : "@" === this.type ? ")" : "?" === this.type ? ")?" : "+" === this.type && m ? ")" : "*" === this.type && m ? ")?" : `)${this.type}`);
    return [ b, unescape2(_), __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)), __privateGet(this, _uflag) ];
  }
};

_root = new WeakMap;

_hasMagic = new WeakMap;

_uflag = new WeakMap;

_parts = new WeakMap;

_parent = new WeakMap;

_parentIndex = new WeakMap;

_negs = new WeakMap;

_filledNegs = new WeakMap;

_options = new WeakMap;

_toString = new WeakMap;

_emptyExt = new WeakMap;

_fillNegs = new WeakSet;

fillNegs_fn = function() {
  if (this !== __privateGet(this, _root)) throw new Error("should only call on root");
  if (__privateGet(this, _filledNegs)) return this;
  this.toString();
  __privateSet(this, _filledNegs, true);
  let s;
  for (;s = __privateGet(this, _negs).pop(); ) {
    if ("!" !== s.type) continue;
    let r = s, o = __privateGet(r, _parent);
    for (;o; ) {
      for (let u = __privateGet(r, _parentIndex) + 1; !o.type && u < __privateGet(o, _parts).length; u++) for (const r of __privateGet(s, _parts)) {
        if ("string" == typeof r) throw new Error("string part in extglob AST??");
        r.copyIn(__privateGet(o, _parts)[u]);
      }
      r = o;
      o = __privateGet(r, _parent);
    }
  }
  return this;
};

_parseAST = new WeakSet;

parseAST_fn = function(s, r, o, u) {
  var g, _;
  let m = false, b = false, E = -1, w = false;
  if (null === r.type) {
    let _ = o, S = "";
    for (;_ < s.length; ) {
      const o = s.charAt(_++);
      if (!m && "\\" !== o) if (!b) {
        if ("[" === o) {
          b = true;
          E = _;
          w = false;
          S += o;
          continue;
        }
        if (u.noext || !isExtglobType(o) || "(" !== s.charAt(_)) S += o; else {
          r.push(S);
          S = "";
          const m = new _AST(o, r);
          _ = __privateMethod(g = _AST, _parseAST, parseAST_fn).call(g, s, m, _, u);
          r.push(m);
        }
      } else {
        if (_ === E + 1) {
          if ("^" === o || "!" === o) w = true;
        } else if ("]" === o && !(_ === E + 2 && w)) b = false;
        S += o;
      } else {
        m = !m;
        S += o;
      }
    }
    r.push(S);
    return _;
  }
  let S = o + 1, L = new _AST(null, r);
  const O = [];
  let D = "";
  for (;S < s.length; ) {
    const o = s.charAt(S++);
    if (!m && "\\" !== o) if (!b) {
      if ("[" === o) {
        b = true;
        E = S;
        w = false;
        D += o;
        continue;
      }
      if (!isExtglobType(o) || "(" !== s.charAt(S)) if ("|" !== o) {
        if (")" === o) {
          if ("" === D && 0 === __privateGet(r, _parts).length) __privateSet(r, _emptyExt, true);
          L.push(D);
          D = "";
          r.push(...O, L);
          return S;
        }
        D += o;
      } else {
        L.push(D);
        D = "";
        O.push(L);
        L = new _AST(null, r);
      } else {
        L.push(D);
        D = "";
        const r = new _AST(o, L);
        L.push(r);
        S = __privateMethod(_ = _AST, _parseAST, parseAST_fn).call(_, s, r, S, u);
      }
    } else {
      if (S === E + 1) {
        if ("^" === o || "!" === o) w = true;
      } else if ("]" === o && !(S === E + 2 && w)) b = false;
      D += o;
    } else {
      m = !m;
      D += o;
    }
  }
  r.type = null;
  __privateSet(r, _hasMagic, void 0);
  __privateSet(r, _parts, [ s.substring(o - 1) ]);
  return S;
};

_partsToRegExp = new WeakSet;

partsToRegExp_fn = function(s) {
  return __privateGet(this, _parts).map((r => {
    if ("string" == typeof r) throw new Error("string type in extglob ast??");
    const [o, u, g, _] = r.toRegExpSource(s);
    __privateSet(this, _uflag, __privateGet(this, _uflag) || _);
    return o;
  })).filter((s => !(this.isStart() && this.isEnd() && !s))).join("|");
};

_parseGlob = new WeakSet;

parseGlob_fn = function(s, r, o = false) {
  let u = false, g = "", _ = false;
  for (let m = 0; m < s.length; m++) {
    const b = s.charAt(m);
    if (!u) if ("\\" !== b) {
      if ("[" === b) {
        const [o, u, b, E] = parseClass(s, m);
        if (b) {
          g += o;
          _ = _ || u;
          m += b - 1;
          r = r || E;
          continue;
        }
      }
      if ("*" !== b) if ("?" !== b) g += regExpEscape(b); else {
        g += qmark;
        r = true;
      } else {
        if (o && "*" === s) g += starNoEmpty; else g += star;
        r = true;
      }
    } else if (m === s.length - 1) g += "\\\\"; else u = true; else {
      u = false;
      g += (reSpecials.has(b) ? "\\" : "") + b;
    }
  }
  return [ g, unescape2(s), !!r, _ ];
};

__privateAdd(_AST, _parseAST);

__privateAdd(_AST, _parseGlob);

var AST = _AST, escape = (s, {windowsPathsNoEscape: r = false} = {}) => r ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&"), minimatch = (s, r, o = {}) => {
  assertValidPattern(r);
  if (!o.nocomment && "#" === r.charAt(0)) return false; else return new Minimatch(r, o).match(s);
}, starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/, starDotExtTest = s => r => !r.startsWith(".") && r.endsWith(s), starDotExtTestDot = s => r => r.endsWith(s), starDotExtTestNocase = s => {
  s = s.toLowerCase();
  return r => !r.startsWith(".") && r.toLowerCase().endsWith(s);
}, starDotExtTestNocaseDot = s => {
  s = s.toLowerCase();
  return r => r.toLowerCase().endsWith(s);
}, starDotStarRE = /^\*+\.\*+$/, starDotStarTest = s => !s.startsWith(".") && s.includes("."), starDotStarTestDot = s => "." !== s && ".." !== s && s.includes("."), dotStarRE = /^\.\*+$/, dotStarTest = s => "." !== s && ".." !== s && s.startsWith("."), starRE = /^\*+$/, starTest = s => 0 !== s.length && !s.startsWith("."), starTestDot = s => 0 !== s.length && "." !== s && ".." !== s, qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/, qmarksTestNocase = ([s, r = ""]) => {
  const o = qmarksTestNoExt([ s ]);
  if (!r) return o;
  r = r.toLowerCase();
  return s => o(s) && s.toLowerCase().endsWith(r);
}, qmarksTestNocaseDot = ([s, r = ""]) => {
  const o = qmarksTestNoExtDot([ s ]);
  if (!r) return o;
  r = r.toLowerCase();
  return s => o(s) && s.toLowerCase().endsWith(r);
}, qmarksTestDot = ([s, r = ""]) => {
  const o = qmarksTestNoExtDot([ s ]);
  return !r ? o : s => o(s) && s.endsWith(r);
}, qmarksTest = ([s, r = ""]) => {
  const o = qmarksTestNoExt([ s ]);
  return !r ? o : s => o(s) && s.endsWith(r);
}, qmarksTestNoExt = ([s]) => {
  const r = s.length;
  return s => s.length === r && !s.startsWith(".");
}, qmarksTestNoExtDot = ([s]) => {
  const r = s.length;
  return s => s.length === r && "." !== s && ".." !== s;
}, defaultPlatform = "object" == typeof process && process ? "object" == typeof process.env && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", path = {
  win32: {
    sep: "\\"
  },
  posix: {
    sep: "/"
  }
}, sep = "win32" === defaultPlatform ? path.win32.sep : path.posix.sep;

minimatch.sep = sep;

var GLOBSTAR = Symbol("globstar **");

minimatch.GLOBSTAR = GLOBSTAR;

var qmark2 = "[^/]", star2 = qmark2 + "*?", twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (s, r = {}) => o => minimatch(o, s, r);

minimatch.filter = filter;

var ext = (s, r = {}) => Object.assign({}, s, r), defaults = s => {
  if (!s || "object" != typeof s || !Object.keys(s).length) return minimatch;
  const r = minimatch;
  return Object.assign(((o, u, g = {}) => r(o, u, ext(s, g))), {
    Minimatch: class Minimatch extends r.Minimatch {
      constructor(r, o = {}) {
        super(r, ext(s, o));
      }
      static defaults(o) {
        return r.defaults(ext(s, o)).Minimatch;
      }
    },
    AST: class AST extends r.AST {
      constructor(r, o, u = {}) {
        super(r, o, ext(s, u));
      }
      static fromGlob(o, u = {}) {
        return r.AST.fromGlob(o, ext(s, u));
      }
    },
    unescape: (o, u = {}) => r.unescape(o, ext(s, u)),
    escape: (o, u = {}) => r.escape(o, ext(s, u)),
    filter: (o, u = {}) => r.filter(o, ext(s, u)),
    defaults: o => r.defaults(ext(s, o)),
    makeRe: (o, u = {}) => r.makeRe(o, ext(s, u)),
    braceExpand: (o, u = {}) => r.braceExpand(o, ext(s, u)),
    match: (o, u, g = {}) => r.match(o, u, ext(s, g)),
    sep: r.sep,
    GLOBSTAR
  });
};

minimatch.defaults = defaults;

var braceExpand = (s, r = {}) => {
  assertValidPattern(s);
  if (r.nobrace || !/\{(?:(?!\{).)*\}/.test(s)) return [ s ]; else return (0, import_brace_expansion.default)(s);
};

minimatch.braceExpand = braceExpand;

var makeRe = (s, r = {}) => new Minimatch(s, r).makeRe();

minimatch.makeRe = makeRe;

var match = (s, r, o = {}) => {
  const u = new Minimatch(r, o);
  s = s.filter((s => u.match(s)));
  if (u.options.nonull && !s.length) s.push(r);
  return s;
};

minimatch.match = match;

var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/, regExpEscape2 = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), Minimatch = class {
  constructor(s, r = {}) {
    __publicField(this, "options");
    __publicField(this, "set");
    __publicField(this, "pattern");
    __publicField(this, "windowsPathsNoEscape");
    __publicField(this, "nonegate");
    __publicField(this, "negate");
    __publicField(this, "comment");
    __publicField(this, "empty");
    __publicField(this, "preserveMultipleSlashes");
    __publicField(this, "partial");
    __publicField(this, "globSet");
    __publicField(this, "globParts");
    __publicField(this, "nocase");
    __publicField(this, "isWindows");
    __publicField(this, "platform");
    __publicField(this, "windowsNoMagicRoot");
    __publicField(this, "regexp");
    assertValidPattern(s);
    r = r || {};
    this.options = r;
    this.pattern = s;
    this.platform = r.platform || defaultPlatform;
    this.isWindows = "win32" === this.platform;
    this.windowsPathsNoEscape = !!r.windowsPathsNoEscape || false === r.allowWindowsEscape;
    if (this.windowsPathsNoEscape) this.pattern = this.pattern.replace(/\\/g, "/");
    this.preserveMultipleSlashes = !!r.preserveMultipleSlashes;
    this.regexp = null;
    this.negate = false;
    this.nonegate = !!r.nonegate;
    this.comment = false;
    this.empty = false;
    this.partial = !!r.partial;
    this.nocase = !!this.options.nocase;
    this.windowsNoMagicRoot = void 0 !== r.windowsNoMagicRoot ? r.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
    this.globSet = [];
    this.globParts = [];
    this.set = [];
    this.make();
  }
  hasMagic() {
    if (this.options.magicalBraces && this.set.length > 1) return true;
    for (const s of this.set) for (const r of s) if ("string" != typeof r) return true;
    return false;
  }
  debug(...s) {}
  make() {
    const s = this.pattern, r = this.options;
    if (!r.nocomment && "#" === s.charAt(0)) {
      this.comment = true;
      return;
    }
    if (!s) {
      this.empty = true;
      return;
    }
    this.parseNegate();
    this.globSet = [ ...new Set(this.braceExpand()) ];
    if (r.debug) this.debug = (...s) => console.error(...s);
    this.debug(this.pattern, this.globSet);
    const o = this.globSet.map((s => this.slashSplit(s)));
    this.globParts = this.preprocess(o);
    this.debug(this.pattern, this.globParts);
    let u = this.globParts.map(((s, r, o) => {
      if (this.isWindows && this.windowsNoMagicRoot) {
        const r = !("" !== s[0] || "" !== s[1] || "?" !== s[2] && globMagic.test(s[2]) || globMagic.test(s[3])), o = /^[a-z]:/i.test(s[0]);
        if (r) return [ ...s.slice(0, 4), ...s.slice(4).map((s => this.parse(s))) ]; else if (o) return [ s[0], ...s.slice(1).map((s => this.parse(s))) ];
      }
      return s.map((s => this.parse(s)));
    }));
    this.debug(this.pattern, u);
    this.set = u.filter((s => -1 === s.indexOf(false)));
    if (this.isWindows) for (let s = 0; s < this.set.length; s++) {
      const r = this.set[s];
      if ("" === r[0] && "" === r[1] && "?" === this.globParts[s][2] && "string" == typeof r[3] && /^[a-z]:$/i.test(r[3])) r[2] = "?";
    }
    this.debug(this.pattern, this.set);
  }
  preprocess(s) {
    if (this.options.noglobstar) for (let r = 0; r < s.length; r++) for (let o = 0; o < s[r].length; o++) if ("**" === s[r][o]) s[r][o] = "*";
    const {optimizationLevel: r = 1} = this.options;
    if (r >= 2) {
      s = this.firstPhasePreProcess(s);
      s = this.secondPhasePreProcess(s);
    } else if (r >= 1) s = this.levelOneOptimize(s); else s = this.adjascentGlobstarOptimize(s);
    return s;
  }
  adjascentGlobstarOptimize(s) {
    return s.map((s => {
      let r = -1;
      for (;-1 !== (r = s.indexOf("**", r + 1)); ) {
        let o = r;
        for (;"**" === s[o + 1]; ) o++;
        if (o !== r) s.splice(r, o - r);
      }
      return s;
    }));
  }
  levelOneOptimize(s) {
    return s.map((s => 0 === (s = s.reduce(((s, r) => {
      const o = s[s.length - 1];
      if ("**" === r && "**" === o) return s;
      if (".." === r) if (o && ".." !== o && "." !== o && "**" !== o) {
        s.pop();
        return s;
      }
      s.push(r);
      return s;
    }), [])).length ? [ "" ] : s));
  }
  levelTwoFileOptimize(s) {
    if (!Array.isArray(s)) s = this.slashSplit(s);
    let r = false;
    do {
      r = false;
      if (!this.preserveMultipleSlashes) {
        for (let o = 1; o < s.length - 1; o++) {
          const u = s[o];
          if (1 !== o || "" !== u || "" !== s[0]) if ("." === u || "" === u) {
            r = true;
            s.splice(o, 1);
            o--;
          }
        }
        if ("." === s[0] && 2 === s.length && ("." === s[1] || "" === s[1])) {
          r = true;
          s.pop();
        }
      }
      let o = 0;
      for (;-1 !== (o = s.indexOf("..", o + 1)); ) {
        const u = s[o - 1];
        if (u && "." !== u && ".." !== u && "**" !== u) {
          r = true;
          s.splice(o - 1, 2);
          o -= 2;
        }
      }
    } while (r);
    return 0 === s.length ? [ "" ] : s;
  }
  firstPhasePreProcess(s) {
    let r = false;
    do {
      r = false;
      for (let o of s) {
        let u = -1;
        for (;-1 !== (u = o.indexOf("**", u + 1)); ) {
          let g = u;
          for (;"**" === o[g + 1]; ) g++;
          if (g > u) o.splice(u + 1, g - u);
          let _ = o[u + 1];
          const m = o[u + 2], b = o[u + 3];
          if (".." !== _) continue;
          if (!m || "." === m || ".." === m || !b || "." === b || ".." === b) continue;
          r = true;
          o.splice(u, 1);
          const E = o.slice(0);
          E[u] = "**";
          s.push(E);
          u--;
        }
        if (!this.preserveMultipleSlashes) {
          for (let s = 1; s < o.length - 1; s++) {
            const u = o[s];
            if (1 !== s || "" !== u || "" !== o[0]) if ("." === u || "" === u) {
              r = true;
              o.splice(s, 1);
              s--;
            }
          }
          if ("." === o[0] && 2 === o.length && ("." === o[1] || "" === o[1])) {
            r = true;
            o.pop();
          }
        }
        let g = 0;
        for (;-1 !== (g = o.indexOf("..", g + 1)); ) {
          const s = o[g - 1];
          if (s && "." !== s && ".." !== s && "**" !== s) {
            r = true;
            const s = 1 === g && "**" === o[g + 1] ? [ "." ] : [];
            o.splice(g - 1, 2, ...s);
            if (0 === o.length) o.push("");
            g -= 2;
          }
        }
      }
    } while (r);
    return s;
  }
  secondPhasePreProcess(s) {
    for (let r = 0; r < s.length - 1; r++) for (let o = r + 1; o < s.length; o++) {
      const u = this.partsMatch(s[r], s[o], !this.preserveMultipleSlashes);
      if (u) {
        s[r] = u;
        s[o] = [];
      }
    }
    return s.filter((s => s.length));
  }
  partsMatch(s, r, o = false) {
    let u = 0, g = 0, _ = [], m = "";
    for (;u < s.length && g < r.length; ) if (s[u] === r[g]) {
      _.push("b" === m ? r[g] : s[u]);
      u++;
      g++;
    } else if (o && "**" === s[u] && r[g] === s[u + 1]) {
      _.push(s[u]);
      u++;
    } else if (o && "**" === r[g] && s[u] === r[g + 1]) {
      _.push(r[g]);
      g++;
    } else if ("*" === s[u] && r[g] && (this.options.dot || !r[g].startsWith(".")) && "**" !== r[g]) {
      if ("b" === m) return false;
      m = "a";
      _.push(s[u]);
      u++;
      g++;
    } else if ("*" === r[g] && s[u] && (this.options.dot || !s[u].startsWith(".")) && "**" !== s[u]) {
      if ("a" === m) return false;
      m = "b";
      _.push(r[g]);
      u++;
      g++;
    } else return false;
    return s.length === r.length && _;
  }
  parseNegate() {
    if (this.nonegate) return;
    const s = this.pattern;
    let r = false, o = 0;
    for (let u = 0; u < s.length && "!" === s.charAt(u); u++) {
      r = !r;
      o++;
    }
    if (o) this.pattern = s.slice(o);
    this.negate = r;
  }
  matchOne(s, r, o = false) {
    const u = this.options;
    if (this.isWindows) {
      const o = "string" == typeof s[0] && /^[a-z]:$/i.test(s[0]), u = !o && "" === s[0] && "" === s[1] && "?" === s[2] && /^[a-z]:$/i.test(s[3]), g = "string" == typeof r[0] && /^[a-z]:$/i.test(r[0]), _ = u ? 3 : o ? 0 : void 0, m = !g && "" === r[0] && "" === r[1] && "?" === r[2] && "string" == typeof r[3] && /^[a-z]:$/i.test(r[3]) ? 3 : g ? 0 : void 0;
      if ("number" == typeof _ && "number" == typeof m) {
        const [o, u] = [ s[_], r[m] ];
        if (o.toLowerCase() === u.toLowerCase()) {
          r[m] = o;
          if (m > _) r = r.slice(m); else if (_ > m) s = s.slice(_);
        }
      }
    }
    const {optimizationLevel: g = 1} = this.options;
    if (g >= 2) s = this.levelTwoFileOptimize(s);
    this.debug("matchOne", this, {
      file: s,
      pattern: r
    });
    this.debug("matchOne", s.length, r.length);
    for (var _ = 0, m = 0, b = s.length, E = r.length; _ < b && m < E; _++, m++) {
      this.debug("matchOne loop");
      var w = r[m], S = s[_];
      this.debug(r, w, S);
      if (false === w) return false;
      if (w === GLOBSTAR) {
        this.debug("GLOBSTAR", [ r, w, S ]);
        var L = _, O = m + 1;
        if (O === E) {
          this.debug("** at the end");
          for (;_ < b; _++) if ("." === s[_] || ".." === s[_] || !u.dot && "." === s[_].charAt(0)) return false;
          return true;
        }
        for (;L < b; ) {
          var D = s[L];
          this.debug("\nglobstar while", s, L, r, O, D);
          if (this.matchOne(s.slice(L), r.slice(O), o)) {
            this.debug("globstar found match!", L, b, D);
            return true;
          } else {
            if ("." === D || ".." === D || !u.dot && "." === D.charAt(0)) {
              this.debug("dot detected!", s, L, r, O);
              break;
            }
            this.debug("globstar swallow a segment, and continue");
            L++;
          }
        }
        if (o) {
          this.debug("\n>>> no match, partial?", s, L, r, O);
          if (L === b) return true;
        }
        return false;
      }
      let g;
      if ("string" == typeof w) {
        g = S === w;
        this.debug("string match", w, S, g);
      } else {
        g = w.test(S);
        this.debug("pattern match", w, S, g);
      }
      if (!g) return false;
    }
    if (_ === b && m === E) return true; else if (_ === b) return o; else if (m === E) return _ === b - 1 && "" === s[_]; else throw new Error("wtf?");
  }
  braceExpand() {
    return braceExpand(this.pattern, this.options);
  }
  parse(s) {
    assertValidPattern(s);
    const r = this.options;
    if ("**" === s) return GLOBSTAR;
    if ("" === s) return "";
    let o, u = null;
    if (o = s.match(starRE)) u = r.dot ? starTestDot : starTest; else if (o = s.match(starDotExtRE)) u = (r.nocase ? r.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : r.dot ? starDotExtTestDot : starDotExtTest)(o[1]); else if (o = s.match(qmarksRE)) u = (r.nocase ? r.dot ? qmarksTestNocaseDot : qmarksTestNocase : r.dot ? qmarksTestDot : qmarksTest)(o); else if (o = s.match(starDotStarRE)) u = r.dot ? starDotStarTestDot : starDotStarTest; else if (o = s.match(dotStarRE)) u = dotStarTest;
    const g = AST.fromGlob(s, this.options).toMMPattern();
    return u ? Object.assign(g, {
      test: u
    }) : g;
  }
  makeRe() {
    if (this.regexp || false === this.regexp) return this.regexp;
    const s = this.set;
    if (!s.length) {
      this.regexp = false;
      return this.regexp;
    }
    const r = this.options, o = r.noglobstar ? star2 : r.dot ? twoStarDot : twoStarNoDot, u = new Set(r.nocase ? [ "i" ] : []);
    let g = s.map((s => {
      const r = s.map((s => {
        if (s instanceof RegExp) for (const r of s.flags.split("")) u.add(r);
        return "string" == typeof s ? regExpEscape2(s) : s === GLOBSTAR ? GLOBSTAR : s._src;
      }));
      r.forEach(((s, u) => {
        const g = r[u + 1], _ = r[u - 1];
        if (s === GLOBSTAR && _ !== GLOBSTAR) if (void 0 === _) if (void 0 !== g && g !== GLOBSTAR) r[u + 1] = "(?:\\/|" + o + "\\/)?" + g; else r[u] = o; else if (void 0 === g) r[u - 1] = _ + "(?:\\/|" + o + ")?"; else if (g !== GLOBSTAR) {
          r[u - 1] = _ + "(?:\\/|\\/" + o + "\\/)" + g;
          r[u + 1] = GLOBSTAR;
        }
      }));
      return r.filter((s => s !== GLOBSTAR)).join("/");
    })).join("|");
    const [_, m] = s.length > 1 ? [ "(?:", ")" ] : [ "", "" ];
    g = "^" + _ + g + m + "$";
    if (this.negate) g = "^(?!" + g + ").+$";
    try {
      this.regexp = new RegExp(g, [ ...u ].join(""));
    } catch (s) {
      this.regexp = false;
    }
    return this.regexp;
  }
  slashSplit(s) {
    if (this.preserveMultipleSlashes) return s.split("/"); else if (this.isWindows && /^\/\/[^\/]+/.test(s)) return [ "", ...s.split(/\/+/) ]; else return s.split(/\/+/);
  }
  match(s, r = this.partial) {
    this.debug("match", s, this.pattern);
    if (this.comment) return false;
    if (this.empty) return "" === s;
    if ("/" === s && r) return true;
    const o = this.options;
    if (this.isWindows) s = s.split("\\").join("/");
    const u = this.slashSplit(s);
    this.debug(this.pattern, "split", u);
    const g = this.set;
    this.debug(this.pattern, "set", g);
    let _ = u[u.length - 1];
    if (!_) for (let s = u.length - 2; !_ && s >= 0; s--) _ = u[s];
    for (let s = 0; s < g.length; s++) {
      const m = g[s];
      let b = u;
      if (o.matchBase && 1 === m.length) b = [ _ ];
      if (this.matchOne(b, m, r)) if (o.flipNegate) return true; else return !this.negate;
    }
    if (o.flipNegate) return false; else return this.negate;
  }
  static defaults(s) {
    return minimatch.defaults(s).Minimatch;
  }
};

minimatch.AST = AST;

minimatch.Minimatch = Minimatch;

minimatch.escape = escape;

minimatch.unescape = unescape2;

var webcrypto, import_crypto = require("crypto");

if ("undefined" != typeof window && window.crypto) webcrypto = window.crypto; else {
  const s = import_crypto.webcrypto;
  webcrypto = s;
}

var e, t = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 2, 127, 127, 0, 96, 3, 127, 127, 127, 1, 127, 3, 3, 2, 1, 0, 5, 3, 1, 0, 1, 7, 23, 3, 3, 109, 101, 109, 2, 0, 5, 120, 120, 104, 51, 50, 0, 0, 5, 120, 120, 104, 54, 52, 0, 1, 10, 152, 9, 2, 242, 2, 1, 4, 127, 32, 0, 32, 1, 106, 33, 3, 32, 1, 32, 1, 65, 16, 79, 4, 127, 32, 3, 65, 16, 107, 33, 6, 32, 2, 65, 168, 136, 141, 161, 2, 106, 33, 1, 32, 2, 65, 137, 235, 208, 208, 7, 107, 33, 4, 32, 2, 65, 207, 140, 162, 142, 6, 106, 33, 5, 3, 64, 32, 1, 32, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 1, 32, 4, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 2, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 5, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 5, 32, 6, 32, 0, 65, 4, 106, 34, 0, 79, 13, 0, 11, 32, 2, 65, 12, 119, 32, 5, 65, 18, 119, 106, 32, 4, 65, 7, 119, 106, 32, 1, 65, 1, 119, 106, 5, 32, 2, 65, 177, 207, 217, 178, 1, 106, 11, 106, 33, 2, 3, 64, 32, 3, 32, 0, 65, 4, 106, 79, 4, 64, 32, 2, 32, 0, 40, 2, 0, 65, 189, 220, 202, 149, 124, 108, 106, 65, 17, 119, 65, 175, 214, 211, 190, 2, 108, 33, 2, 32, 0, 65, 4, 106, 33, 0, 12, 1, 11, 11, 3, 64, 32, 0, 32, 3, 73, 4, 64, 32, 2, 32, 0, 45, 0, 0, 65, 177, 207, 217, 178, 1, 108, 106, 65, 11, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 0, 65, 1, 106, 33, 0, 12, 1, 11, 11, 32, 2, 32, 2, 65, 15, 118, 115, 65, 247, 148, 175, 175, 120, 108, 34, 0, 65, 13, 118, 32, 0, 115, 65, 189, 220, 202, 149, 124, 108, 34, 0, 65, 16, 118, 32, 0, 115, 11, 161, 6, 2, 4, 126, 3, 127, 32, 0, 65, 4, 106, 53, 2, 0, 32, 0, 53, 2, 0, 66, 32, 134, 132, 33, 2, 32, 1, 32, 0, 65, 8, 106, 34, 6, 106, 33, 7, 32, 1, 65, 32, 79, 4, 126, 32, 7, 65, 32, 107, 33, 8, 32, 2, 66, 214, 235, 130, 238, 234, 253, 137, 245, 224, 0, 124, 33, 3, 32, 2, 66, 177, 169, 172, 193, 173, 184, 212, 166, 61, 125, 33, 4, 32, 2, 66, 249, 234, 208, 208, 231, 201, 161, 228, 225, 0, 124, 33, 5, 3, 64, 32, 3, 32, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 3, 32, 4, 32, 6, 65, 8, 106, 34, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 4, 32, 2, 32, 6, 65, 8, 106, 34, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 2, 32, 5, 32, 6, 65, 8, 106, 34, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 5, 32, 8, 32, 6, 65, 8, 106, 34, 6, 79, 13, 0, 11, 32, 2, 66, 12, 137, 32, 5, 66, 18, 137, 124, 32, 4, 66, 7, 137, 124, 32, 3, 66, 1, 137, 124, 32, 3, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 5, 32, 2, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 1, 173, 124, 33, 2, 3, 64, 32, 7, 32, 6, 65, 8, 106, 79, 4, 64, 32, 2, 32, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 27, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 33, 2, 32, 6, 65, 8, 106, 33, 6, 12, 1, 11, 11, 32, 6, 65, 4, 106, 32, 7, 77, 4, 64, 32, 2, 32, 6, 53, 2, 0, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 23, 137, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 124, 33, 2, 32, 6, 65, 4, 106, 33, 6, 11, 3, 64, 32, 6, 32, 7, 73, 4, 64, 32, 2, 32, 6, 49, 0, 0, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 126, 133, 66, 11, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 2, 32, 6, 65, 1, 106, 33, 6, 12, 1, 11, 11, 32, 0, 32, 2, 32, 2, 66, 33, 136, 133, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 34, 2, 66, 29, 136, 32, 2, 133, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 126, 34, 2, 66, 32, 136, 32, 2, 133, 34, 2, 66, 32, 136, 62, 2, 0, 32, 0, 65, 4, 106, 32, 2, 62, 2, 0, 11 ]);

function n(s, r, o) {
  if (r.buffer.byteLength < s.byteLength + o) {
    const u = Math.ceil((s.byteLength + o - r.buffer.byteLength) / 65536);
    r.grow(u);
  }
  new Uint8Array(r.buffer, o).set(s);
}

async function xxhash_wasm_default() {
  const {instance: {exports: {mem: s, xxh32: r, xxh64: o}}} = await WebAssembly.instantiate(t);
  function h2(o) {
    let u = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
    return n(o, s, 0), r(0, o.byteLength, u) >>> 0;
  }
  function c(r) {
    let u = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, g = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
    n(r, s, 8);
    const _ = new DataView(s.buffer);
    return _.setUint32(0, u, true), _.setUint32(4, g, true), o(0, r.byteLength), _;
  }
  return {
    h32: function(s) {
      let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
      e || (e = new TextEncoder);
      return h2(e.encode(s), r).toString(16);
    },
    h32Raw: h2,
    h64: function(s) {
      let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, o = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
      e || (e = new TextEncoder);
      const u = c(e.encode(s), r, o);
      return u.getUint32(0, true).toString(16) + u.getUint32(4, true).toString(16);
    },
    h64Raw: function(s) {
      let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, o = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
      return new Uint8Array(c(s, r, o).buffer, 0, 8);
    }
  };
}

var t2 = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 48, 8, 96, 3, 127, 127, 127, 0, 96, 3, 127, 127, 127, 1, 127, 96, 2, 127, 127, 0, 96, 2, 127, 126, 0, 96, 1, 127, 1, 127, 96, 1, 127, 1, 126, 96, 3, 127, 127, 126, 1, 126, 96, 3, 126, 127, 127, 1, 126, 3, 11, 10, 1, 1, 2, 0, 4, 6, 7, 3, 0, 5, 5, 3, 1, 0, 1, 7, 85, 9, 3, 109, 101, 109, 2, 0, 5, 120, 120, 104, 51, 50, 0, 0, 6, 105, 110, 105, 116, 51, 50, 0, 2, 8, 117, 112, 100, 97, 116, 101, 51, 50, 0, 3, 8, 100, 105, 103, 101, 115, 116, 51, 50, 0, 4, 5, 120, 120, 104, 54, 52, 0, 5, 6, 105, 110, 105, 116, 54, 52, 0, 7, 8, 117, 112, 100, 97, 116, 101, 54, 52, 0, 8, 8, 100, 105, 103, 101, 115, 116, 54, 52, 0, 9, 10, 211, 23, 10, 242, 1, 1, 4, 127, 32, 0, 32, 1, 106, 33, 3, 32, 1, 65, 16, 79, 4, 127, 32, 3, 65, 16, 107, 33, 6, 32, 2, 65, 168, 136, 141, 161, 2, 106, 33, 3, 32, 2, 65, 247, 148, 175, 175, 120, 106, 33, 4, 32, 2, 65, 177, 243, 221, 241, 121, 107, 33, 5, 3, 64, 32, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 3, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 3, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 4, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 2, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 5, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 5, 32, 0, 65, 4, 106, 34, 0, 32, 6, 77, 13, 0, 11, 32, 2, 65, 12, 119, 32, 5, 65, 18, 119, 106, 32, 4, 65, 7, 119, 106, 32, 3, 65, 1, 119, 106, 5, 32, 2, 65, 177, 207, 217, 178, 1, 106, 11, 32, 1, 106, 32, 0, 32, 1, 65, 15, 113, 16, 1, 11, 146, 1, 0, 32, 1, 32, 2, 106, 33, 2, 3, 64, 32, 1, 65, 4, 106, 32, 2, 75, 69, 4, 64, 32, 1, 40, 2, 0, 65, 189, 220, 202, 149, 124, 108, 32, 0, 106, 65, 17, 119, 65, 175, 214, 211, 190, 2, 108, 33, 0, 32, 1, 65, 4, 106, 33, 1, 12, 1, 11, 11, 3, 64, 32, 1, 32, 2, 79, 69, 4, 64, 32, 1, 45, 0, 0, 65, 177, 207, 217, 178, 1, 108, 32, 0, 106, 65, 11, 119, 65, 177, 243, 221, 241, 121, 108, 33, 0, 32, 1, 65, 1, 106, 33, 1, 12, 1, 11, 11, 32, 0, 65, 15, 118, 32, 0, 115, 65, 247, 148, 175, 175, 120, 108, 34, 0, 32, 0, 65, 13, 118, 115, 65, 189, 220, 202, 149, 124, 108, 34, 0, 32, 0, 65, 16, 118, 115, 11, 63, 0, 32, 0, 65, 8, 106, 32, 1, 65, 168, 136, 141, 161, 2, 106, 54, 2, 0, 32, 0, 65, 12, 106, 32, 1, 65, 247, 148, 175, 175, 120, 106, 54, 2, 0, 32, 0, 65, 16, 106, 32, 1, 54, 2, 0, 32, 0, 65, 20, 106, 32, 1, 65, 177, 243, 221, 241, 121, 107, 54, 2, 0, 11, 211, 4, 1, 6, 127, 32, 1, 32, 2, 106, 33, 6, 32, 0, 65, 24, 106, 33, 5, 32, 0, 65, 40, 106, 40, 2, 0, 33, 3, 32, 0, 32, 0, 40, 2, 0, 32, 2, 106, 54, 2, 0, 32, 0, 65, 4, 106, 34, 4, 32, 4, 40, 2, 0, 32, 2, 65, 16, 79, 32, 0, 40, 2, 0, 65, 16, 79, 114, 114, 54, 2, 0, 32, 2, 32, 3, 106, 65, 16, 73, 4, 64, 32, 3, 32, 5, 106, 32, 1, 32, 2, 252, 10, 0, 0, 32, 0, 65, 40, 106, 32, 2, 32, 3, 106, 54, 2, 0, 15, 11, 32, 3, 4, 64, 32, 3, 32, 5, 106, 32, 1, 65, 16, 32, 3, 107, 34, 2, 252, 10, 0, 0, 32, 0, 65, 8, 106, 34, 3, 40, 2, 0, 32, 5, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 12, 106, 34, 3, 40, 2, 0, 32, 5, 65, 4, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 16, 106, 34, 3, 40, 2, 0, 32, 5, 65, 8, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 20, 106, 34, 3, 40, 2, 0, 32, 5, 65, 12, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 40, 106, 65, 0, 54, 2, 0, 32, 1, 32, 2, 106, 33, 1, 11, 32, 1, 32, 6, 65, 16, 107, 77, 4, 64, 32, 6, 65, 16, 107, 33, 8, 32, 0, 65, 8, 106, 40, 2, 0, 33, 2, 32, 0, 65, 12, 106, 40, 2, 0, 33, 3, 32, 0, 65, 16, 106, 40, 2, 0, 33, 4, 32, 0, 65, 20, 106, 40, 2, 0, 33, 7, 3, 64, 32, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 2, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 3, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 3, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 4, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 7, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 7, 32, 1, 65, 4, 106, 34, 1, 32, 8, 77, 13, 0, 11, 32, 0, 65, 8, 106, 32, 2, 54, 2, 0, 32, 0, 65, 12, 106, 32, 3, 54, 2, 0, 32, 0, 65, 16, 106, 32, 4, 54, 2, 0, 32, 0, 65, 20, 106, 32, 7, 54, 2, 0, 11, 32, 1, 32, 6, 73, 4, 64, 32, 5, 32, 1, 32, 6, 32, 1, 107, 34, 1, 252, 10, 0, 0, 32, 0, 65, 40, 106, 32, 1, 54, 2, 0, 11, 11, 97, 1, 1, 127, 32, 0, 65, 16, 106, 40, 2, 0, 33, 1, 32, 0, 65, 4, 106, 40, 2, 0, 4, 127, 32, 1, 65, 12, 119, 32, 0, 65, 20, 106, 40, 2, 0, 65, 18, 119, 106, 32, 0, 65, 12, 106, 40, 2, 0, 65, 7, 119, 106, 32, 0, 65, 8, 106, 40, 2, 0, 65, 1, 119, 106, 5, 32, 1, 65, 177, 207, 217, 178, 1, 106, 11, 32, 0, 40, 2, 0, 106, 32, 0, 65, 24, 106, 32, 0, 65, 40, 106, 40, 2, 0, 16, 1, 11, 157, 4, 2, 1, 127, 3, 126, 32, 0, 32, 1, 106, 33, 3, 32, 1, 65, 32, 79, 4, 126, 32, 3, 65, 32, 107, 33, 3, 32, 2, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 124, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 33, 4, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 33, 5, 32, 2, 66, 0, 124, 33, 6, 32, 2, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 125, 33, 2, 3, 64, 32, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 4, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 4, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 5, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 5, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 6, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 2, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 2, 32, 0, 65, 8, 106, 34, 0, 32, 3, 77, 13, 0, 11, 32, 6, 66, 12, 137, 32, 2, 66, 18, 137, 124, 32, 5, 66, 7, 137, 124, 32, 4, 66, 1, 137, 124, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 6, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 5, 32, 2, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 1, 173, 124, 32, 0, 32, 1, 65, 31, 113, 16, 6, 11, 137, 2, 0, 32, 1, 32, 2, 106, 33, 2, 3, 64, 32, 1, 65, 8, 106, 32, 2, 77, 4, 64, 32, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 32, 0, 133, 66, 27, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 33, 0, 32, 1, 65, 8, 106, 33, 1, 12, 1, 11, 11, 32, 1, 65, 4, 106, 32, 2, 77, 4, 64, 32, 1, 53, 2, 0, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 32, 0, 133, 66, 23, 137, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 124, 33, 0, 32, 1, 65, 4, 106, 33, 1, 11, 3, 64, 32, 1, 32, 2, 73, 4, 64, 32, 1, 49, 0, 0, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 126, 32, 0, 133, 66, 11, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 0, 32, 1, 65, 1, 106, 33, 1, 12, 1, 11, 11, 32, 0, 66, 33, 136, 32, 0, 133, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 34, 0, 32, 0, 66, 29, 136, 133, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 126, 34, 0, 32, 0, 66, 32, 136, 133, 11, 88, 0, 32, 0, 65, 8, 106, 32, 1, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 124, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 55, 3, 0, 32, 0, 65, 16, 106, 32, 1, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 55, 3, 0, 32, 0, 65, 24, 106, 32, 1, 55, 3, 0, 32, 0, 65, 32, 106, 32, 1, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 125, 55, 3, 0, 11, 132, 5, 2, 3, 127, 4, 126, 32, 1, 32, 2, 106, 33, 5, 32, 0, 65, 40, 106, 33, 4, 32, 0, 65, 200, 0, 106, 40, 2, 0, 33, 3, 32, 0, 32, 0, 41, 3, 0, 32, 2, 173, 124, 55, 3, 0, 32, 2, 32, 3, 106, 65, 32, 73, 4, 64, 32, 3, 32, 4, 106, 32, 1, 32, 2, 252, 10, 0, 0, 32, 0, 65, 200, 0, 106, 32, 2, 32, 3, 106, 54, 2, 0, 15, 11, 32, 3, 4, 64, 32, 3, 32, 4, 106, 32, 1, 65, 32, 32, 3, 107, 34, 2, 252, 10, 0, 0, 32, 0, 65, 8, 106, 34, 3, 41, 3, 0, 32, 4, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 16, 106, 34, 3, 41, 3, 0, 32, 4, 65, 8, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 24, 106, 34, 3, 41, 3, 0, 32, 4, 65, 16, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 32, 106, 34, 3, 41, 3, 0, 32, 4, 65, 24, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 200, 0, 106, 65, 0, 54, 2, 0, 32, 1, 32, 2, 106, 33, 1, 11, 32, 1, 65, 32, 106, 32, 5, 77, 4, 64, 32, 5, 65, 32, 107, 33, 2, 32, 0, 65, 8, 106, 41, 3, 0, 33, 6, 32, 0, 65, 16, 106, 41, 3, 0, 33, 7, 32, 0, 65, 24, 106, 41, 3, 0, 33, 8, 32, 0, 65, 32, 106, 41, 3, 0, 33, 9, 3, 64, 32, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 6, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 7, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 7, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 8, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 8, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 9, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 9, 32, 1, 65, 8, 106, 34, 1, 32, 2, 77, 13, 0, 11, 32, 0, 65, 8, 106, 32, 6, 55, 3, 0, 32, 0, 65, 16, 106, 32, 7, 55, 3, 0, 32, 0, 65, 24, 106, 32, 8, 55, 3, 0, 32, 0, 65, 32, 106, 32, 9, 55, 3, 0, 11, 32, 1, 32, 5, 73, 4, 64, 32, 4, 32, 1, 32, 5, 32, 1, 107, 34, 1, 252, 10, 0, 0, 32, 0, 65, 200, 0, 106, 32, 1, 54, 2, 0, 11, 11, 200, 2, 1, 5, 126, 32, 0, 65, 24, 106, 41, 3, 0, 33, 1, 32, 0, 41, 3, 0, 34, 2, 66, 32, 90, 4, 126, 32, 0, 65, 8, 106, 41, 3, 0, 34, 3, 66, 1, 137, 32, 0, 65, 16, 106, 41, 3, 0, 34, 4, 66, 7, 137, 124, 32, 1, 66, 12, 137, 32, 0, 65, 32, 106, 41, 3, 0, 34, 5, 66, 18, 137, 124, 124, 32, 3, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 1, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 5, 32, 1, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 2, 124, 32, 0, 65, 40, 106, 32, 2, 66, 31, 131, 167, 16, 6, 11 ]);

async function e2() {
  const {instance: {exports: {mem: s, xxh32: r, xxh64: o, init32: u, update32: g, digest32: _, init64: m, update64: b, digest64: E}}} = await WebAssembly.instantiate(t2);
  let w = new Uint8Array(s.buffer);
  function c(r, o) {
    if (s.buffer.byteLength < r + o) {
      const u = Math.ceil((r + o - s.buffer.byteLength) / 65536);
      s.grow(u), w = new Uint8Array(s.buffer);
    }
  }
  function l(s, r, o, u, g, _) {
    c(s);
    const m = new Uint8Array(s);
    return w.set(m), o(0, r), m.set(w.slice(0, s)), {
      update(r) {
        let o;
        return w.set(m), "string" == typeof r ? (c(3 * r.length, s), o = L.encodeInto(r, w.subarray(s)).written) : (c(r.byteLength, s), 
        w.set(r, s), o = r.byteLength), u(0, s, o), m.set(w.slice(0, s)), this;
      },
      digest: () => (w.set(m), _(g(0)))
    };
  }
  function d3(s) {
    return s >>> 0;
  }
  const S = BigInt(2) ** BigInt(64) - BigInt(1);
  function y(s) {
    return s & S;
  }
  const L = new TextEncoder, O = BigInt(0);
  function p(s) {
    let o = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
    return c(3 * s.length, 0), d3(r(0, L.encodeInto(s, w).written, o));
  }
  function v(s) {
    let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : O;
    return c(3 * s.length, 0), y(o(0, L.encodeInto(s, w).written, r));
  }
  return {
    h32: p,
    h32ToString(s) {
      return p(s, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0).toString(16).padStart(8, "0");
    },
    h32Raw(s) {
      let o = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
      return c(s.byteLength, 0), w.set(s), d3(r(0, s.byteLength, o));
    },
    create32() {
      return l(48, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0, u, g, _, d3);
    },
    h64: v,
    h64ToString(s) {
      return v(s, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : O).toString(16).padStart(16, "0");
    },
    h64Raw(s) {
      let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : O;
      return c(s.byteLength, 0), w.set(s), y(o(0, s.byteLength, r));
    },
    create64() {
      return l(88, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : O, m, b, E, y);
    }
  };
}

var revMap = {}, numMap = {};

for (let s = 0; s < 256; s++) {
  revMap[`00${s.toString(16)}`.slice(-2)] = s;
  numMap[s] = `00${s.toString(16)}`.slice(-2);
}

function* range(s, r) {
  for (let o = s; o <= r; o++) yield o;
}

var table = {}, revTable = {};

[ ...range(192, 447) ].forEach(((s, r) => {
  table[r] = s;
  revTable[s] = r;
}));

var BINARY_CHUNK_MAX = 31457280;

function hexStringToUint8Array(s) {
  const r = s.length / 2, o = new Uint8Array(r);
  for (let u = 0; u < r; u++) o[u] = revMap[s[2 * u] + s[2 * u + 1]];
  return o;
}

function uint8ArrayToHexString(s) {
  return [ ...s ].map((s => numMap[s])).join("");
}

function btoa_node(s) {
  return Buffer.from(s, "binary").toString("base64");
}

function atob_node(s) {
  return Buffer.from(s, "base64").toString("binary");
}

var btoa2 = window && window.btoa ? window.btoa : btoa_node, atob2 = window && window.atob ? window.atob : atob_node, QUANTUM = 32768, writeString = s => {
  const r = new Uint8Array(4 * s.length), o = s.length;
  let u = 0, g = 0, _ = 0;
  for (;_ < o; ) {
    g = s.charCodeAt(_++);
    if (g < 128) r[u++] = g; else if (g < 2048) {
      r[u++] = 192 | g >>> 6;
      r[u++] = 128 | 63 & g;
    } else if (g < 55296 || g > 57343) {
      r[u++] = 224 | g >>> 12;
      r[u++] = 128 | g >>> 6 & 63;
      r[u++] = 128 | 63 & g;
    } else {
      g = 65536 + (g - 55296 << 10 | s.charCodeAt(_++) - 56320);
      r[u++] = 240 | g >>> 18;
      r[u++] = 128 | g >>> 12 & 63;
      r[u++] = 128 | g >>> 6 & 63;
      r[u++] = 128 | 63 & g;
    }
  }
  return r.slice(0, u);
}, readString = s => {
  let r = 0;
  const o = s.length;
  let u = "";
  for (;r < o; ) {
    const g = [], _ = Math.min(r + QUANTUM, o);
    for (;r < _; ) {
      const o = s[r++];
      if (o < 128) g.push(o); else if (192 == (224 & o)) g.push((31 & o) << 6 | 63 & s[r++]); else if (224 == (240 & o)) g.push((15 & o) << 12 | (63 & s[r++]) << 6 | 63 & s[r++]); else if (240 == (248 & o)) {
        let u = (7 & o) << 18 | (63 & s[r++]) << 12 | (63 & s[r++]) << 6 | 63 & s[r++];
        if (u < 65536) g.push(u); else {
          u -= 65536;
          g.push(55296 + (u >>> 10), 56320 + (1023 & u));
        }
      }
    }
    u += String.fromCharCode(...g);
  }
  return u;
}, encodeChunkSize = 15e7;

function arrayBufferToBase64internalBrowser(s) {
  return new Promise(((r, o) => {
    const u = new Blob([ s ], {
      type: "application/octet-binary"
    }), g = new FileReader;
    g.onload = function(u) {
      var g, _;
      const m = (null == (_ = null == (g = u.target) ? void 0 : g.result) ? void 0 : _.toString()) || "";
      if (0 != s.byteLength && ("" == m || "data:" == m)) return o(new TypeError("Could not parse the encoded string"));
      const b = m.substring(m.indexOf(",") + 1);
      r(b);
    };
    g.readAsDataURL(u);
  }));
}

function arrayBufferToBase64internalNode(s) {
  return Buffer.from(s.buffer).toString("base64");
}

var arrayBufferToBase64internal = window && window.btoa ? arrayBufferToBase64internalBrowser : arrayBufferToBase64internalNode;

async function arrayBufferToBase64Single(s) {
  const r = s instanceof Uint8Array ? s : new Uint8Array(s);
  if (r.byteLength < QUANTUM) return btoa2(String.fromCharCode.apply(null, [ ...r ])); else return await arrayBufferToBase64internal(r);
}

async function arrayBufferToBase64(s) {
  const r = s instanceof Uint8Array ? s : new Uint8Array(s);
  if (r.byteLength < QUANTUM) return [ btoa2(String.fromCharCode.apply(null, [ ...r ])) ];
  const o = r.byteLength, u = [];
  let g = 0;
  do {
    const s = g * encodeChunkSize, o = new DataView(r.buffer, s, Math.min(encodeChunkSize, r.byteLength - s));
    u.push(await arrayBufferToBase64internal(o));
    g++;
  } while (g * encodeChunkSize < o);
  return u;
}

function base64ToArrayBuffer(s) {
  if ("string" == typeof s) return base64ToArrayBufferInternal(s);
  const r = s.map((s => base64ToArrayBufferInternal(s))), o = r.reduce(((s, r) => s + r.byteLength), 0), u = new Uint8Array(o);
  let g = 0;
  r.forEach((s => {
    u.set(new Uint8Array(s), g);
    g += s.byteLength;
  }));
  return u.buffer;
}

var base64ToArrayBufferInternal = window && window.atob ? base64ToArrayBufferInternalBrowser : base64ToArrayBufferInternalNode;

function base64ToArrayBufferInternalNode(s) {
  try {
    return Buffer.from(s, "base64").buffer;
  } catch (s) {
    Logger("Base64 decode error (Node)", LOG_LEVEL_VERBOSE);
    Logger(s, LOG_LEVEL_VERBOSE);
    return new ArrayBuffer(0);
  }
}

function base64ToArrayBufferInternalBrowser(s) {
  try {
    const r = window.atob(s), o = r.length, u = new Uint8Array(o);
    for (let s = 0; s < o; s++) u[s] = r.charCodeAt(s);
    return u.buffer;
  } catch (s) {
    Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);
    Logger(s, LOG_LEVEL_VERBOSE);
    return new ArrayBuffer(0);
  }
}

function* pickPiece(s, r) {
  let o = "";
  e: do {
    const u = s.shift();
    if ("undefined" == typeof u) {
      yield o;
      break e;
    }
    if (u.startsWith("```") || u.startsWith(" ```") || u.startsWith("  ```") || u.startsWith("   ```")) {
      yield o;
      o = u + (0 != s.length ? "\n" : "");
      t: do {
        const r = s.shift();
        if ("undefined" == typeof r) break t;
        o += r + (0 != s.length ? "\n" : "");
      } while (s.length > 0 && !(s[0].startsWith("```") || s[0].startsWith(" ```") || s[0].startsWith("  ```") || s[0].startsWith("   ```")));
      const r = o.endsWith("="), g = o.length > 2048, _ = s.shift();
      if ("undefined" != typeof _) {
        o += _;
        o += 0 != s.length ? "\n" : "";
      }
      if (!r && !g) {
        const s = /(.*?[;,:<])/g, r = o.split(s).filter((s => "" != s));
        for (const s of r) yield s;
      } else yield o;
      o = "";
    } else {
      o += u + (0 != s.length ? "\n" : "");
      if (o.length >= r || 0 == s.length || "#" == s[0] || "#" == o[0]) {
        yield o;
        o = "";
      }
    }
  } while (s.length > 0);
}

var charNewLine = "\n".charCodeAt(0);

function splitPiecesText(s, r, o, u) {
  const g = "string" == typeof s ? [ s ] : s;
  return function* pieces() {
    for (const s of g) if (o) {
      const o = pickPiece(s.split("\n"), u);
      for (const s of o) {
        let o = s;
        do {
          let s = r;
          if (o.charCodeAt(s - 1) != o.codePointAt(s - 1)) s++;
          yield o.substring(0, s);
          o = o.substring(s);
        } while ("" != o);
      }
    } else {
      let o = s;
      do {
        const s = r, u = o.substring(0, s);
        o = o.substring(s);
        yield u;
      } while ("" != o);
    }
  };
}

async function splitPieces2(s, r, o, u, g) {
  if (isTextBlob(s)) return splitPiecesText(await s.text(), r, o, u);
  let _ = 0;
  if (g && g.endsWith(".pdf")) _ = "/".charCodeAt(0);
  let m = 1, b = Math.max(1e5, Math.min(1e8, s.size));
  for (;b > 10; ) {
    b /= 12.5;
    m++;
  }
  u = Math.floor(10 ** (m - 1));
  return async function* piecesBlob() {
    const o = s.size;
    let g = 0;
    do {
      let o = r;
      const m = new Uint8Array(await s.slice(g, g + r).arrayBuffer());
      let b = m.indexOf(_, u);
      o = -1 == b ? r : Math.min(r, b);
      if (-1 == b) b = m.indexOf(charNewLine, u);
      const E = m.slice(0, o);
      g += E.length;
      yield await arrayBufferToBase64Single(E);
    } while (g < o);
  };
}

function versionNumberString2Number(s) {
  return s.split(".").reverse().map(((s, r) => s / 1 * 1e3 ** r)).reduce(((s, r) => s + r), 0);
}

var hashFunc, escapeStringToHTML = s => {
  if (!s) return ""; else return s.replace(/[<>&"'`]/g, (s => ({
    "<": "&lt;",
    ">": "&gt;",
    "&": "&amp;",
    '"': "&quot;",
    "'": "&#39;",
    "`": "&#x60;"
  }[s])));
}, crc32kTable = new Uint32Array(256), crc32cTable = new Uint32Array(256);

function generateCRC32KTable() {
  for (let s = 0; s < 256; s++) {
    let r = s;
    for (let s = 0; s < 8; s++) if (1 & r) r = r >>> 1 ^ 3988292384; else r >>>= 1;
    crc32kTable[s] = r;
  }
}

function generateCRC32CTable() {
  for (let s = 0; s < 256; s++) {
    let r = s;
    for (let s = 0; s < 8; s++) if (1 & r) r = r >>> 1 ^ 517762881; else r >>>= 1;
    crc32cTable[s] = r;
  }
}

generateCRC32CTable();

generateCRC32KTable();

function decodeToArrayBuffer(s) {
  if (1 == s.length) return _decodeToArrayBuffer(s[0]);
  const r = s.map((s => _decodeToArrayBuffer(s))), o = r.reduce(((s, r) => s + r.byteLength), 0), u = new Uint8Array(o);
  let g = 0;
  r.forEach((s => {
    u.set(new Uint8Array(s), g);
    g += s.byteLength;
  }));
  return u.buffer;
}

function _decodeToArrayBuffer(s) {
  const r = new Uint8Array(s.length), o = s.length;
  for (let u = 0; u < o; u++) {
    const o = s.charCodeAt(u);
    if (o >= 38 && o <= 126 && 58 != o) r[u] = o; else r[u] = revTable[o];
  }
  return r.buffer;
}

function decodeBinary(s) {
  if (0 == s.length) return (new Uint8Array).buffer;
  if ("string" == typeof s) {
    if ("%" === s[0]) return _decodeToArrayBuffer(s.substring(1));
  } else if ("%" === s[0][0]) {
    const [r, ...o] = s;
    return decodeToArrayBuffer([ r.substring(1), ...o ]);
  }
  return base64ToArrayBuffer(s);
}

async function initHashFunc() {
  try {
    const {h32ToString: s} = await e2();
    hashFunc = s;
    Logger("xxhash for plugin initialised", LOG_LEVEL_VERBOSE);
  } catch (s) {
    Logger("Could not initialise xxhash. fallback...", LOG_LEVEL_VERBOSE);
    Logger(s);
    try {
      const {h32: s} = await xxhash_wasm_default();
      hashFunc = r => s(r);
    } catch (s) {
      Logger("Could not initialise old xxhash for plugin: use sha1", LOG_LEVEL_VERBOSE);
      Logger(s);
      hashFunc = s => s;
    }
  }
  return hashFunc;
}

initHashFunc();

async function sha1(s) {
  const r = writeString(s), o = await webcrypto.subtle.digest({
    name: "SHA-1"
  }, r);
  return await arrayBufferToBase64Single(o);
}

function digestHash(s) {
  return hashFunc(s);
}

function isValidFilenameInWidows(s) {
  if (/[\u0000-\u001f]|[\\":?<>|*#]/g.test(s)) return false;
  if (/(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi.test(s)) return false; else return true;
}

function isValidFilenameInDarwin(s) {
  return !/[\u0000-\u001f]|[:]/g.test(s);
}

function isValidFilenameInLinux(s) {
  return !/[\u0000-\u001f]|[:]/g.test(s);
}

function isValidFilenameInAndroid(s) {
  return !/[\u0000-\u001f]|[\\":?<>|*#]/g.test(s);
}

function isFilePath(s) {
  if (-1 === s.indexOf(":")) return true; else return false;
}

function stripAllPrefixes(s) {
  if (isFilePath(s)) return s;
  const [, r] = expandFilePathPrefix(s);
  return stripAllPrefixes(r);
}

function addPrefix(s, r) {
  if (r && s.startsWith(r)) return s; else return `${null != r ? r : ""}${s}`;
}

function expandFilePathPrefix(s) {
  let [r, o] = s.split(":", 2);
  if (!o) {
    o = r;
    r = "";
  } else r += ":";
  return [ r, o ];
}

function expandDocumentIDPrefix(s) {
  let [r, o] = s.split(":", 2);
  if (!o) {
    o = r;
    r = "";
  } else r += ":";
  return [ r, o ];
}

var hashString = memorizeFuncWithLRUCache((async s => {
  const r = writeString(s);
  let o = await webcrypto.subtle.digest("SHA-256", r);
  const u = s.length;
  for (let s = 0; s < u; s++) o = await webcrypto.subtle.digest("SHA-256", r);
  return uint8ArrayToHexString(new Uint8Array(o));
}));

async function path2id_base(s, r) {
  if (s.startsWith(PREFIX_OBFUSCATED)) return s;
  let o = s;
  if (o.startsWith("_")) o = "/" + o;
  if (!r) return o;
  const [u, g] = expandFilePathPrefix(o);
  if (g.startsWith(PREFIX_OBFUSCATED)) return o;
  const _ = await hashString(r), m = await hashString(`${_}:${s}`);
  return u + PREFIX_OBFUSCATED + m;
}

function id2path_base(s, r) {
  if (r && (null == r ? void 0 : r.path)) return id2path_base(r.path);
  if (s.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
  const [o, u] = expandDocumentIDPrefix(s);
  if (u.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
  if (u.startsWith("/")) return u.substring(1); else return o + u;
}

function getPath(s) {
  return id2path_base(s._id, s);
}

function stripPrefix(s) {
  const [r, o] = s.split(":", 2);
  if (!o) return r; else return o;
}

function shouldBeIgnored(s) {
  if (s == FLAGMD_REDFLAG) return true;
  if (s == FLAGMD_REDFLAG2) return true;
  if (s == FLAGMD_REDFLAG2_HR) return true;
  if (s == FLAGMD_REDFLAG3) return true;
  if (s == FLAGMD_REDFLAG3_HR) return true;
  if (s.startsWith(PREFIXMD_LOGFILE)) return true; else return false;
}

function isPlainText(s) {
  if (s.endsWith(".md")) return true;
  if (s.endsWith(".txt")) return true;
  if (s.endsWith(".svg")) return true;
  if (s.endsWith(".html")) return true;
  if (s.endsWith(".csv")) return true;
  if (s.endsWith(".css")) return true;
  if (s.endsWith(".js")) return true;
  if (s.endsWith(".xml")) return true;
  if (s.endsWith(".canvas")) return true; else return false;
}

function shouldSplitAsPlainText(s) {
  if (s.endsWith(".md")) return true;
  if (s.endsWith(".txt")) return true;
  if (s.endsWith(".canvas")) return true; else return false;
}

var matchOpts = {
  platform: "linux",
  dot: true,
  flipNegate: true,
  nocase: true
};

function isAccepted(s, r) {
  if (-1 !== s.indexOf("./") || -1 !== s.indexOf("../")) return false;
  const o = r.map((s => s.trim())).filter((s => s.length > 0 && !s.startsWith("#")));
  let u;
  for (const r of o) {
    if (r.endsWith("/")) if (minimatch(s, `${r}**`, matchOpts)) return false;
    const o = r.startsWith("!");
    if (minimatch(s, r, matchOpts) || !r.endsWith("/") && minimatch(s, r + "/**", matchOpts)) u = o;
  }
  return u;
}

async function isAcceptedAll(s, r, o) {
  const u = unique(s.substring(0, s.lastIndexOf("/")).split("/").reduce(((s, r) => [ ...s, s[s.length - 1] + "/" + r ]), [ "" ]).map((s => s.substring(1)))).reverse();
  for (const g of u) for (const u of r) {
    const r = g + "/" + u, _ = await o(r);
    if (false === _) continue;
    const m = isAccepted(s.substring(g.length ? g.length + 1 : 0), _);
    if (void 0 !== m) return m;
  }
  return true;
}

function makeUniqueString() {
  const s = [ ...Array(30) ].map((() => Math.floor(52 * Math.random()))).map((s => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[s])).join("");
  return `${Date.now()}-${s}`;
}

function Semaphore(s, r) {
  let o = s, u = 0, g = [];
  function execProcess() {
    g = g.filter((s => "DONE" != s.state));
    for (const s of g) if ("NONE" == s.state) {
      if (s.quantity + u > o) break;
      s.state = "RUNNING";
      u += s.quantity;
      if (null == s ? void 0 : s.timer) clearTimeout(s.timer);
      s.notify(true);
    }
  }
  function release(s) {
    const o = g.find((r => r.key == s));
    if (!o) throw new Error("Missing locked semaphore!");
    if ("RUNNING" == o.state) u -= o.quantity;
    o.state = "DONE";
    if (r) r(g.filter((s => "DONE" != s.state)));
    execProcess();
  }
  return {
    setLimit(s) {
      o = s;
    },
    _acquire(s, r, u) {
      const _ = makeUniqueString();
      if (o < s) throw Error("Too big quantity");
      let notify = s => {};
      const m = new Promise((s => {
        notify = r => {
          if (r) s((() => {
            release(_);
          })); else s(false);
        };
      })), b = {
        key: _,
        notify,
        semaphoreStopper: m,
        quantity: s,
        memo: r,
        state: "NONE"
      };
      if (u) b.timer = setTimeout((() => {
        release(_);
        notify(false);
      }), u);
      g.push(b);
      execProcess();
      return m;
    },
    acquire(s = 1, r) {
      return this._acquire(s, null != r ? r : "", 0);
    },
    tryAcquire(s = 1, r, o) {
      return this._acquire(s, null != o ? o : "", r);
    },
    peekQueues: () => g
  };
}

var semiStaticFieldBuffer, KeyBuffs = new Map, decKeyBuffs = new Map, KEY_RECYCLE_COUNT = 100, nonceBuffer = new Uint32Array(1);

async function getKeyForEncrypt(s, r) {
  const o = `${s}-${r}`, u = KeyBuffs.get(o);
  if (u) {
    u.count--;
    if (u.count > 0) return [ u.key, u.salt ];
    u.count--;
  }
  const g = 15 - s.length, _ = r ? 1e3 * (g > 0 ? g : 0) + 121 - g : 1e5, m = (new TextEncoder).encode(s), b = await webcrypto.subtle.digest({
    name: "SHA-256"
  }, m), E = await webcrypto.subtle.importKey("raw", b, {
    name: "PBKDF2"
  }, false, [ "deriveKey" ]), w = webcrypto.getRandomValues(new Uint8Array(16)), S = await webcrypto.subtle.deriveKey({
    name: "PBKDF2",
    salt: w,
    iterations: _,
    hash: "SHA-256"
  }, E, {
    name: "AES-GCM",
    length: 256
  }, false, [ "encrypt" ]);
  KeyBuffs.set(o, {
    key: S,
    salt: w,
    count: KEY_RECYCLE_COUNT
  });
  return [ S, w ];
}

var keyGCCount = 5 * KEY_RECYCLE_COUNT, decKeyIdx = 0, decKeyMin = 0;

async function getKeyForDecryption(s, r, o) {
  if (--keyGCCount < 0) {
    keyGCCount = KEY_RECYCLE_COUNT;
    const s = (decKeyIdx - decKeyMin) / 2;
    for (const [r, o] of decKeyBuffs) {
      if (o.count < s) decKeyBuffs.delete(r);
      decKeyMin = decKeyIdx;
    }
  }
  decKeyIdx++;
  const u = s + uint8ArrayToHexString(r) + o, g = decKeyBuffs.get(u);
  if (g) {
    g.count = decKeyIdx;
    return [ g.key, g.salt ];
  }
  const _ = 15 - s.length, m = o ? 1e3 * (_ > 0 ? _ : 0) + 121 - _ : 1e5, b = (new TextEncoder).encode(s), E = await webcrypto.subtle.digest({
    name: "SHA-256"
  }, b), w = await webcrypto.subtle.importKey("raw", E, {
    name: "PBKDF2"
  }, false, [ "deriveKey" ]), S = await webcrypto.subtle.deriveKey({
    name: "PBKDF2",
    salt: r,
    iterations: m,
    hash: "SHA-256"
  }, w, {
    name: "AES-GCM",
    length: 256
  }, false, [ "decrypt" ]);
  decKeyBuffs.set(u, {
    key: S,
    salt: r,
    count: 0
  });
  return [ S, r ];
}

function getSemiStaticField(s) {
  if (null != semiStaticFieldBuffer && !s) return semiStaticFieldBuffer; else return semiStaticFieldBuffer = webcrypto.getRandomValues(new Uint8Array(12));
}

function getNonce() {
  nonceBuffer[0]++;
  if (nonceBuffer[0] > 1e4) getSemiStaticField(true);
  return nonceBuffer;
}

async function encrypt(s, r, o) {
  const [u, g] = await getKeyForEncrypt(r, o), _ = getSemiStaticField(), m = getNonce(), b = new Uint8Array([ ..._, ...new Uint8Array(m.buffer) ]), E = writeString(s), w = await webcrypto.subtle.encrypt({
    name: "AES-GCM",
    iv: b
  }, u, E), S = "" + await arrayBufferToBase64Single(new Uint8Array(w));
  return `%${uint8ArrayToHexString(b)}${uint8ArrayToHexString(g)}${S}`;
}

async function getKeyForObfuscatePath(s, r, o) {
  const u = 15 - s.length, g = o ? 1e3 * (u > 0 ? u : 0) + 121 - u : 1e5, _ = (new TextEncoder).encode(s), m = await webcrypto.subtle.digest({
    name: "SHA-256"
  }, _), b = new Uint8Array(await webcrypto.subtle.digest({
    name: "SHA-256"
  }, new Uint8Array([ ...r, ..._ ]))), E = b.slice(0, 16), w = b.slice(16, 32), S = await webcrypto.subtle.importKey("raw", m, {
    name: "PBKDF2"
  }, false, [ "deriveKey" ]);
  return [ await webcrypto.subtle.deriveKey({
    name: "PBKDF2",
    salt: E,
    iterations: g,
    hash: "SHA-256"
  }, S, {
    name: "AES-GCM",
    length: 256
  }, false, [ "encrypt" ]), E, w ];
}

async function obfuscatePath(s, r, o) {
  const u = writeString(s), [g, _, m] = await getKeyForObfuscatePath(r, u, o), b = await webcrypto.subtle.encrypt({
    name: "AES-GCM",
    iv: m
  }, g, u), E = await arrayBufferToBase64Single(new Uint8Array(b));
  return `%${uint8ArrayToHexString(m)}${uint8ArrayToHexString(_)}${E}`;
}

async function decryptV2(s, r, o) {
  try {
    const u = s.substring(1, 33), g = s.substring(33, 65), _ = s.substring(65), [m] = await getKeyForDecryption(r, hexStringToUint8Array(g), o), b = hexStringToUint8Array(u), E = decodeBinary(_), w = await webcrypto.subtle.decrypt({
      name: "AES-GCM",
      iv: b
    }, m, E);
    return readString(new Uint8Array(w));
  } catch (s) {
    Logger("Couldn't decode! You should wrong the passphrases (V2)", LOG_LEVEL_VERBOSE);
    Logger(s, LOG_LEVEL_VERBOSE);
    throw s;
  }
}

async function decrypt(s, r, o) {
  try {
    if ("%" == s[0]) return decryptV2(s, r, o);
    if (!s.startsWith("[") || !s.endsWith("]")) throw new Error("Encrypted data corrupted!");
    const u = s.substring(1, s.length - 1).split(",").map((s => '"' == s[0] ? s.substring(1, s.length - 1) : s)), [g, _, m] = u, [b] = await getKeyForDecryption(r, hexStringToUint8Array(m), o), E = hexStringToUint8Array(_), w = atob2(g), S = w.length, L = new Uint8Array(S);
    for (let s = S; s >= 0; --s) L[s] = w.charCodeAt(s);
    const O = await webcrypto.subtle.decrypt({
      name: "AES-GCM",
      iv: E
    }, b, L), D = readString(new Uint8Array(O));
    return JSON.parse(D);
  } catch (s) {
    Logger("Couldn't decode! You should wrong the passphrases", LOG_LEVEL_VERBOSE);
    Logger(s, LOG_LEVEL_VERBOSE);
    throw s;
  }
}

async function tryDecrypt(s, r, o) {
  if (!r) return false;
  try {
    return await decrypt(s, r, o);
  } catch (s) {
    return false;
  }
}

async function testCrypt() {
  const s = "supercalifragilisticexpialidocious", r = await encrypt(s, "passwordTest", false);
  if (s != await decrypt(r, "passwordTest", false)) {
    Logger("WARNING! Your device would not support encryption.", LOG_LEVEL_VERBOSE);
    return false;
  } else {
    Logger("CRYPT LOGIC OK", LOG_LEVEL_VERBOSE);
    return true;
  }
}

var queueTails = new Map;

async function performTask(s) {
  const r = s.key;
  try {
    const r = await s.task();
    s.resolver(r);
  } catch (r) {
    s.rejector(r);
  } finally {
    const o = s.next;
    queueTails.set(r, o);
    if (o) performTask(o);
  }
}

function _enqueue(s, r, {swapIfExist: o, shareResult: u} = {}) {
  let resolver = () => {}, rejector = () => {};
  const g = new Promise(((s, r) => {
    resolver = s, rejector = r;
  })), _ = {
    task: r,
    resolver,
    rejector,
    key: s
  }, m = queueTails.get(s);
  if (void 0 === m) {
    queueTails.set(s, _);
    performTask(_);
  } else {
    const r = m;
    queueTails.set(s, _);
    r.next = _;
    if (o) r.rejector(new Error("Cancelled"));
  }
  return g;
}

function serialized(s, r) {
  return _enqueue(s, r);
}

function shareRunningResult(s, r) {
  const o = queueTails.get(s);
  if (!o) return _enqueue(s, r);
  const u = o.resolver, g = o.rejector;
  let resolver = () => {}, rejector = () => {};
  const _ = new Promise(((s, r) => {
    resolver = s, rejector = r;
  }));
  o.resolver = s => {
    u(s);
    resolver(s);
  };
  o.rejector = s => {
    g(s);
    rejector(s);
  };
  return _;
}

function skipIfDuplicated(s, r) {
  if (void 0 !== queueTails.get(s)) return Promise.resolve(null); else return _enqueue(s, r);
}

function isLockAcquired(s) {
  return void 0 !== queueTails.get(s);
}

var Notifier = class {
  constructor() {
    this.p = promiseWithResolver();
  }
  notify() {
    this.p.resolve();
    this.p = promiseWithResolver();
  }
  get nextNotify() {
    return this.p.promise;
  }
}, processNo = 0, QueueProcessor = class {
  constructor(s, r, o, u) {
    this._queue = [];
    this._enqueueProcessor = (s, r) => (s.push(r), s);
    this._isSuspended = true;
    this._nextProcessNeedsImmediate = false;
    this._waitId = "";
    this._instance = processNo++;
    this._keepResultUntilDownstreamConnected = false;
    this._keptResult = [];
    this._runOnUpdateBatch = () => {};
    this.concurrentLimit = 1;
    this.batchSize = 1;
    this.yieldThreshold = 1;
    this.delay = 0;
    this.interval = 0;
    this.processingEntities = 0;
    this.waitingEntries = 0;
    this._notifier = new Notifier;
    this._processingBatches = new Set;
    this.addProcessingBatch = s => {
      const r = this._processingBatches.add(s);
      this._updateBatchProcessStatus();
      return r;
    };
    this.deleteProcessingBatch = s => {
      const r = this._processingBatches.delete(s);
      this._updateBatchProcessStatus();
      return r;
    };
    this._processing = false;
    var g, _, m, b, E, w, S;
    this._root = this;
    this._processor = s;
    this.batchSize = null != (g = null == r ? void 0 : r.batchSize) ? g : 1;
    this.yieldThreshold = null != (m = null != (_ = null == r ? void 0 : r.yieldThreshold) ? _ : null == r ? void 0 : r.batchSize) ? m : 0;
    this.concurrentLimit = null != (b = null == r ? void 0 : r.concurrentLimit) ? b : 1;
    this.delay = null != (E = null == r ? void 0 : r.delay) ? E : 0;
    this.maintainDelay = null != (w = null == r ? void 0 : r.maintainDelay) ? w : false;
    this.interval = null != (S = null == r ? void 0 : r.interval) ? S : 0;
    if (null == r ? void 0 : r.keepResultUntilDownstreamConnected) this._keepResultUntilDownstreamConnected = r.keepResultUntilDownstreamConnected;
    if (null == r ? void 0 : r.remainingReactiveSource) this._remainingReactiveSource = null == r ? void 0 : r.remainingReactiveSource;
    if (null == r ? void 0 : r.totalRemainingReactiveSource) this._totalRemainingReactiveSource = null == r ? void 0 : r.totalRemainingReactiveSource;
    if (null == r ? void 0 : r.processingEntitiesReactiveSource) this._processingEntitiesReactiveSource = null == r ? void 0 : r.processingEntitiesReactiveSource;
    if (void 0 !== (null == r ? void 0 : r.suspended)) this._isSuspended = null == r ? void 0 : r.suspended;
    if (u) this.replaceEnqueueProcessor(u);
    if (void 0 !== (null == r ? void 0 : r.pipeTo)) this.pipeTo(r.pipeTo);
    if (o) this.enqueueAll(o);
    this._run();
  }
  get nowProcessing() {
    return this.processingEntities;
  }
  get totalNowProcessing() {
    var s;
    return this.nowProcessing + ((null == (s = this._pipeTo) ? void 0 : s.totalNowProcessing) || 0);
  }
  get remaining() {
    return this._queue.length + this.processingEntities + this.waitingEntries;
  }
  get totalRemaining() {
    var s;
    return this.remaining + ((null == (s = this._pipeTo) ? void 0 : s.totalRemaining) || 0);
  }
  updateStatus(s) {
    s();
    this._updateReactiveSource();
  }
  suspend() {
    this._isSuspended = true;
    this._notifier.notify();
    return this;
  }
  resume() {
    this._isSuspended = false;
    this._notifier.notify();
    this.requestNextFlush();
    this._run();
    return this;
  }
  resumePipeLine() {
    var s;
    null == (s = this._pipeTo) || s.resumePipeLine();
    this.resume();
    return this;
  }
  startPipeline() {
    this._root.resumePipeLine();
    return this;
  }
  get root() {
    return this._root;
  }
  replaceEnqueueProcessor(s) {
    this._enqueueProcessor = s;
    return this;
  }
  modifyQueue(s) {
    this._queue = s(this._queue);
    this._notifier.notify();
  }
  clearQueue() {
    this._queue = [];
    this._notifier.notify();
  }
  onUpdateProgress(s) {
    this._runOnUpdateBatch = s;
    return this;
  }
  pipeTo(s) {
    this._pipeTo = s;
    this._pipeTo._root = this._root;
    if (this._keptResult.length > 0) {
      const s = [ ...this._keptResult ];
      this._keptResult = [];
      this._pipeTo.enqueueAll(s);
    }
    return s;
  }
  isIdle() {
    return this._isIdle() && (!this._pipeTo ? true : this._pipeTo.isIdle());
  }
  _isIdle() {
    return 0 == this.totalRemaining;
  }
  async _idleDetector() {
    if (this._isSuspended) return Promise.resolve();
    if (this._isIdle()) return Promise.resolve();
    do {
      await Promise.race([ delay(3e3), this._notifier.nextNotify ]);
    } while (!this._isIdle());
    return Promise.resolve();
  }
  idleDetectors() {
    const s = this._idleDetector();
    if (this._pipeTo) return [ s, ...this._pipeTo.idleDetectors() ]; else return [ s ];
  }
  get isSuspended() {
    var s;
    return this._isSuspended || (null == (s = this._pipeTo) ? void 0 : s.isSuspended) || false;
  }
  _updateReactiveSource() {
    this._root.updateReactiveSource();
  }
  updateReactiveSource() {
    if (this._pipeTo) this._pipeTo.updateReactiveSource();
    if (this._remainingReactiveSource) this._remainingReactiveSource.value = this.remaining;
    if (this._totalRemainingReactiveSource) this._totalRemainingReactiveSource.value = this.totalRemaining;
    if (this._processingEntitiesReactiveSource) this._processingEntitiesReactiveSource.value = this.nowProcessing;
  }
  _updateBatchProcessStatus() {
    this._updateReactiveSource();
    this._runOnUpdateBatch();
  }
  _collectBatch() {
    return this._queue.splice(0, this.batchSize);
  }
  _canCollectBatch() {
    return 0 !== this._queue.length;
  }
  enqueue(s) {
    this._queue = this._enqueueProcessor(this._queue, s);
    this._updateBatchProcessStatus();
    this._notifier.notify();
    return this;
  }
  enqueueAll(s) {
    let r = this._queue;
    for (const o of s) r = this._enqueueProcessor(r, o);
    this._queue = r;
    this._updateBatchProcessStatus();
    this._notifier.notify();
    return this;
  }
  requestNextFlush() {
    if (this._canCollectBatch()) {
      this._nextProcessNeedsImmediate = true;
      this._notifier.notify();
    }
  }
  flush() {
    if (!this._isSuspended) {
      this.requestNextFlush();
      return this.waitForAllDownstream();
    }
  }
  async waitForAllDownstream(s) {
    const r = [];
    if (s) r.push(delay(s, RESULT_TIMED_OUT));
    do {
      const s = this.idleDetectors(), o = [ ...r, Promise.all(s) ];
      if (await Promise.race(o) === RESULT_TIMED_OUT) return false;
    } while (!this.isIdle());
    return true;
  }
  waitForPipeline(s) {
    this._root.startPipeline();
    return this._root.waitForAllDownstream(s);
  }
  async _runProcessor(s) {
    this.updateStatus((() => {
      this.processingEntities += s.length;
      this.waitingEntries -= s.length;
    }));
    try {
      const r = await this._processor(s);
      if (!r) return;
      if (this._pipeTo) this._pipeTo.enqueueAll(r); else if (this._keepResultUntilDownstreamConnected) this._keptResult.push(...r);
    } finally {
      this.updateStatus((() => {
        this.processingEntities -= s.length;
      }));
    }
  }
  async* pump() {
    let s, r = true;
    do {
      if (this._canCollectBatch()) {
        if (r) await this.delayUntilRequested(this.delay);
        s = this._collectBatch();
        if (0 != s.length) {
          this.updateStatus((() => {
            this.waitingEntries += s.length;
          }));
          yield s;
          if (this._canCollectBatch()) r = false;
        }
      } else {
        r = true;
        await Promise.race([ this._notifier.nextNotify, delay(3e3) ]);
      }
    } while (this._canCollectBatch() && !this._isSuspended);
  }
  async delayUntilRequested(s) {
    if (this._nextProcessNeedsImmediate) {
      this._nextProcessNeedsImmediate = false;
      return;
    }
    const r = delay(s, RESULT_TIMED_OUT);
    let o;
    do {
      o = await Promise.race([ this._notifier.nextNotify, r ]);
    } while (o !== RESULT_TIMED_OUT && false === this._nextProcessNeedsImmediate && this.yieldThreshold >= this._queue.length);
    this._nextProcessNeedsImmediate = false;
  }
  async _process() {
    if (this._processing && this._isSuspended) return;
    let s = 0;
    try {
      this._processing = true;
      do {
        const r = this.pump();
        for await (const o of r) {
          for (;this._processingBatches.size >= this.concurrentLimit; ) await this._notifier.nextNotify;
          const r = Date.now() + Math.random(), batchTask = async () => {
            try {
              if (this.interval && s) {
                const r = Date.now() - s;
                if (r < this.interval) {
                  const s = this.interval - r;
                  await delay(s);
                }
              }
              s = Date.now();
              await this._runProcessor(o);
            } catch (s) {
              Logger("Processor error!");
              Logger(s, LOG_LEVEL_VERBOSE);
            } finally {
              this.deleteProcessingBatch(r);
              this._notifier.notify();
            }
          };
          this.addProcessingBatch(r);
          this._notifier.notify();
          fireAndForget(batchTask);
        }
        await this._notifier.nextNotify;
      } while (!this._isSuspended);
    } finally {
      this._processing = false;
    }
  }
  _run() {
    if (!this._isSuspended) if (!this._processing) fireAndForget((() => this._process()));
  }
}, isValidRemoteCouchDBURI = s => {
  if (s.startsWith("https://")) return true;
  if (s.startsWith("http://")) return true; else return false;
};

function isCloudantURI(s) {
  if (-1 !== s.indexOf(".cloudantnosqldb.") || -1 !== s.indexOf(".cloudant.com")) return true; else return false;
}

var checkRemoteVersion = async (s, r, o = VER) => {
  try {
    const u = await s.get(VERSIONINFO_DOCID);
    if ("versioninfo" != u.type) return false;
    const g = u.version;
    if (g < o) if (await r(g, o)) {
      await bumpRemoteVersion(s);
      return true;
    }
    if (g == o) return true; else return false;
  } catch (r) {
    if (isErrorOfMissingDoc(r)) if (await bumpRemoteVersion(s)) return true; else return false;
    throw r;
  }
}, bumpRemoteVersion = async (s, r = VER) => {
  const o = {
    _id: VERSIONINFO_DOCID,
    version: r,
    type: "versioninfo"
  }, u = await resolveWithIgnoreKnownError(s.get(VERSIONINFO_DOCID), o);
  if ("versioninfo" != u.type) return false;
  o._rev = u._rev;
  await s.put(o);
  return true;
}, checkSyncInfo = async s => {
  try {
    const r = await s.get(SYNCINFO_ID);
    console.log(r);
    return true;
  } catch (r) {
    if (isErrorOfMissingDoc(r)) {
      const r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", o = [ ...Array(30) ].map((s => Math.floor(Math.random() * r.length))).map((s => r[s])).join(""), u = {
        _id: SYNCINFO_ID,
        type: "syncinfo",
        data: o
      };
      if (await s.put(u)) return true; else return false;
    } else {
      console.dir(r);
      return false;
    }
  }
}, enableEncryption = (s, r, o, u) => {
  const g = new Map;
  s.transform({
    incoming: async s => {
      const u = {
        ...s
      };
      if (isEncryptedChunkEntry(u) || isSyncInfoEntry(u)) try {
        u.data = await encrypt(u.data, r, o);
      } catch (s) {
        Logger("Encryption failed.", LOG_LEVEL_NOTICE);
        Logger(s);
        throw s;
      }
      if (isObfuscatedEntry(u)) try {
        u.path = await obfuscatePath(getPath(u), r, o);
      } catch (s) {
        Logger("Encryption failed.", LOG_LEVEL_NOTICE);
        Logger(s);
        throw s;
      }
      return u;
    },
    outgoing: async s => {
      var _, m;
      const b = {
        ...s
      }, E = isEncryptedChunkEntry(b) || isSyncInfoEntry(b), w = isObfuscatedEntry(b);
      if (E || w) {
        if (u && g.has(b._id)) return b;
        try {
          if (E) b.data = await decrypt(b.data, r, o);
          if (w) b.path = await decrypt(getPath(b), r, o);
          if (u) g.set(b._id, true);
        } catch (s) {
          if (o) try {
            if (E) b.data = await decrypt(b.data, r, false);
            if (w) b.path = await decrypt(getPath(b), r, o);
            if (u) g.set(b._id, true);
          } catch (s) {
            if (u && "SyntaxError" == s.name) return b;
            Logger("Decryption failed.", LOG_LEVEL_NOTICE);
            Logger(s, LOG_LEVEL_VERBOSE);
            Logger(`id:${b._id}-${null == (_ = b._rev) ? void 0 : _.substring(0, 10)}`, LOG_LEVEL_VERBOSE);
            throw s;
          } else {
            Logger("Decryption failed.", LOG_LEVEL_NOTICE);
            Logger(s, LOG_LEVEL_VERBOSE);
            Logger(`id:${b._id}-${null == (m = b._rev) ? void 0 : m.substring(0, 10)}`, LOG_LEVEL_VERBOSE);
            throw s;
          }
        }
      }
      return b;
    }
  });
};

function isErrorOfMissingDoc(s) {
  return 404 == (s && (null == s ? void 0 : s.status));
}

async function prepareChunkDesignDoc(s) {
  var r;
  const o = {
    _id: "_design/chunks",
    _rev: void 0,
    ver: 2,
    views: {
      collectDangling: {
        map: (function(s) {
          if (s._id.startsWith("h:")) emit([ s._id ], 0); else if ("children" in s) s.children.forEach((s => emit([ s ], 1)));
        }).toString(),
        reduce: "_sum"
      }
    }
  };
  let u = false;
  try {
    const g = await s.get(o._id);
    if (null != (r = null == g ? void 0 : g.ver) ? r : 0 < o.ver) {
      o._rev = g._rev;
      u = true;
    }
  } catch (s) {
    if (404 == s.status) u = true; else {
      Logger("Failed to make design document for operating chunks");
      Logger(s, LOG_LEVEL_VERBOSE);
      return false;
    }
  }
  try {
    if (u) await s.put(o);
  } catch (s) {
    Logger("Failed to make design document for operating chunks");
    Logger(s, LOG_LEVEL_VERBOSE);
    return false;
  }
  return true;
}

async function collectChunksUsage(s) {
  if (!await prepareChunkDesignDoc(s)) {
    Logger("Could not prepare design document for operating chunks");
    return [];
  }
  return (await s.query("chunks/collectDangling", {
    reduce: true,
    group: true
  })).rows;
}

function collectUnreferencedChunks(s) {
  return collectChunks(s, "DANGLING");
}

async function collectChunks(s, r) {
  const o = await collectChunksUsage(s), u = ("ALL" == r ? o : o.filter((s => "DANGLING" == r ? 0 == s.value : 0 != s.value))).flatMap((s => s.key));
  return (await s.allDocs({
    keys: u
  })).rows.filter((s => !("error" in s))).map((s => ({
    id: s.id,
    rev: s.value.rev
  })));
}

async function collectUnbalancedChunkIDs(s, r) {
  const o = await collectChunks(s, "INUSE"), u = await collectChunks(r, "INUSE");
  return {
    onlyOnLocal: o.filter((s => !u.some((r => r.id == s.id)))),
    onlyOnRemote: u.filter((s => !o.some((r => r.id == s.id))))
  };
}

async function purgeChunksLocal(s, r) {
  await serialized("purge-local", (async () => {
    try {
      Logger(`Purging unused ${r.length} chunks `, LOG_LEVEL_NOTICE, "purge-local-backup");
      const o = arrayToChunkedArray(r, 100);
      let u = {
        ok: 0,
        exist: 0,
        error: 0
      };
      for (const r of o) {
        const o = (await s.allDocs({
          keys: r.map((s => s.id)),
          include_docs: true
        })).rows.filter((s => "doc" in s)).map((s => {
          const r = {
            ...s.doc
          };
          delete r._rev;
          r._id = `_local/${r._id}`;
          return r;
        })), g = await s.bulkDocs(o);
        u = g.map((s => ({
          ok: "ok" in s ? 1 : 0,
          exist: "status" in s && 409 == s.status ? 1 : 0,
          error: "status" in s && 409 != s.status ? 1 : 0
        }))).reduce(((s, r) => ({
          ok: s.ok + r.ok,
          exist: s.exist + r.exist,
          error: s.error + r.error
        })), u);
        Logger(`Local chunk backed up: new:${u.ok} ,exist:${u.exist}, error:${u.error}`, LOG_LEVEL_NOTICE, "purge-local-backup");
        const _ = g.filter((s => "error" in s && 409 != s.status));
        for (const s of _) Logger(`Failed to back up: ${s.id} / ${s.rev}`, LOG_LEVEL_VERBOSE);
      }
    } catch (s) {
      Logger("Could not back up chunks");
      Logger(s, LOG_LEVEL_VERBOSE);
    }
    Logger(`Purging unused ${r.length} chunks... `, LOG_LEVEL_NOTICE, "purge-local");
    const o = arrayToChunkedArray(r, 100);
    let u = 0;
    for (const g of o) {
      const o = await s.purgeMulti(g.map((s => [ s.id, s.rev ])));
      u += Object.values(o).filter((s => "ok" in s)).length;
      Logger(`Purging:  ${u} / ${r.length}`, LOG_LEVEL_NOTICE, "purge-local");
    }
    Logger(`Purging unused chunks done!: ${u} chunks has been deleted.`, LOG_LEVEL_NOTICE, "purge-local");
  }));
}

var _requestToCouchDBFetch = async (s, r, o, u, g, _) => {
  const m = String.fromCharCode.apply(null, [ ...writeString(`${r}:${o}`) ]), b = window.btoa(m), E = `${s}/${u}`, w = {
    url: E,
    method: _ || (g ? "PUT" : "GET"),
    headers: new Headers({
      authorization: "Basic " + b,
      "content-type": "application/json"
    }),
    contentType: "application/json",
    body: JSON.stringify(g)
  };
  return await fetch(E, w);
};

async function purgeChunksRemote(s, r) {
  await serialized("purge-remote", (async () => {
    const o = function makeChunkedArrayFromArray(s) {
      const r = [];
      for (let o = 0; o < s.length; o += 100) r.push(s.slice(o, o + 100));
      return r;
    }(r);
    for (const r of o) {
      const o = await _requestToCouchDBFetch(`${s.couchDB_URI}/${s.couchDB_DBNAME}`, s.couchDB_USER, s.couchDB_PASSWORD, "_purge", Object.fromEntries(r.map((s => [ s.id, [ s.rev ] ]))), "POST");
      Logger(JSON.stringify(await o.json()), LOG_LEVEL_VERBOSE);
    }
  }));
}

function sizeToHumanReadable(s) {
  if (!s) return "-";
  const r = Math.floor(Math.log(s) / Math.log(1024));
  return Number.parseInt((s / Math.pow(1024, r)).toFixed(2)) + " " + [ "B", "kB", "MB", "GB", "TB" ][r];
}

async function purgeUnreferencedChunks(s, r, o, u = false) {
  const g = await s.info();
  let _ = 0;
  const getSize = function(s, r) {
    var o, u;
    return Number.parseInt(null != (u = null == (o = null == s ? void 0 : s.sizes) ? void 0 : o[r]) ? u : 0);
  }, m = o ? "-remote" : "-local";
  Logger(`${r ? "Counting" : "Cleaning"} ${o ? "remote" : "local"} database`, LOG_LEVEL_NOTICE);
  if (o) Logger(`Database active-size: ${sizeToHumanReadable(getSize(g, "active"))}, external-size:${sizeToHumanReadable(getSize(g, "external"))}, file-size: ${sizeToHumanReadable(getSize(g, "file"))}`, LOG_LEVEL_NOTICE);
  Logger(`Collecting unreferenced chunks on ${g.db_name}`, LOG_LEVEL_NOTICE, "gc-countchunk" + m);
  const b = await collectUnreferencedChunks(s);
  _ = b.length;
  if (0 == b.length) Logger(`No unreferenced chunks! ${g.db_name}`, LOG_LEVEL_NOTICE, "gc-countchunk" + m); else {
    Logger(`Number of unreferenced chunks on ${g.db_name}: ${b.length}`, LOG_LEVEL_NOTICE, "gc-countchunk" + m);
    if (r) {
      Logger(`DryRun of cleaning ${o ? "remote" : "local"} database up: Done`, LOG_LEVEL_NOTICE);
      return _;
    }
    if (o) {
      Logger("Cleaning unreferenced chunks on remote", LOG_LEVEL_NOTICE, "gc-purge" + m);
      await purgeChunksRemote(o, b);
    } else {
      Logger("Cleaning unreferenced chunks on local", LOG_LEVEL_NOTICE, "gc-purge" + m);
      await purgeChunksLocal(s, b);
    }
    Logger("Cleaning unreferenced chunks done!", LOG_LEVEL_NOTICE, "gc-purge" + m);
  }
  if (u) {
    Logger("Compacting database...", LOG_LEVEL_NOTICE, "gc-compact" + m);
    await s.compact();
    Logger("Compacting database done", LOG_LEVEL_NOTICE, "gc-compact" + m);
  }
  if (o) {
    const r = await s.info();
    Logger(`Processed database active-size: ${sizeToHumanReadable(getSize(r, "active"))}, external-size:${sizeToHumanReadable(getSize(r, "external"))}, file-size: ${sizeToHumanReadable(getSize(r, "file"))}`, LOG_LEVEL_NOTICE);
    Logger(`Reduced sizes: active-size: ${sizeToHumanReadable(getSize(g, "active") - getSize(r, "active"))}, external-size:${sizeToHumanReadable(getSize(g, "external") - getSize(r, "external"))}, file-size: ${sizeToHumanReadable(getSize(g, "file") - getSize(r, "file"))}`, LOG_LEVEL_NOTICE);
  }
  Logger(`Cleaning ${o ? "remote" : "local"} database up: Done`, LOG_LEVEL_NOTICE);
  return _;
}

function transferChunks(s, r, o, u, g) {
  let _ = 0;
  const m = g.length;
  return new QueueProcessor((async s => {
    const r = s.map((s => s.id));
    return (await u.allDocs({
      keys: r
    })).rows.filter((s => "error" in s && "not_found" == s.error)).map((s => s.key));
  }), {
    batchSize: 50,
    concurrentLimit: 5,
    suspended: true,
    delay: 100
  }, g).pipeTo(new QueueProcessor((async s => (await o.allDocs({
    keys: s,
    include_docs: true
  })).rows.filter((s => !("error" in s))).map((s => s.doc))), {
    batchSize: 25,
    concurrentLimit: 1,
    suspended: true,
    delay: 100
  })).pipeTo(new QueueProcessor((async o => {
    try {
      await u.bulkDocs(o, {
        new_edits: false
      });
    } catch (s) {
      Logger(`${r}: Something went wrong on balancing`, LOG_LEVEL_NOTICE);
      Logger(s, LOG_LEVEL_VERBOSE);
    } finally {
      _ += o.length;
      Logger(`${r}: ${_} / ${m}`, LOG_LEVEL_NOTICE, "balance-" + s);
    }
  }), {
    batchSize: 100,
    delay: 100,
    concurrentLimit: 2,
    suspended: false
  })).startPipeline().waitForPipeline();
}

async function balanceChunkPurgedDBs(s, r) {
  Logger("Complement missing chunks between databases", LOG_LEVEL_NOTICE);
  try {
    const {onlyOnLocal: o, onlyOnRemote: u} = await collectUnbalancedChunkIDs(s, r), g = transferChunks("l2r", "local -> remote", s, r, o), _ = transferChunks("r2l", "remote -> local", r, s, u);
    await Promise.all([ g, _ ]);
    Logger("local -> remote: Done", LOG_LEVEL_NOTICE, "balance-l2r");
    Logger("remote -> local: Done", LOG_LEVEL_NOTICE, "balance-r2l");
  } catch (s) {
    Logger("Something went wrong on balancing!", LOG_LEVEL_NOTICE);
    Logger(s, LOG_LEVEL_VERBOSE);
  }
  Logger("Complement completed!", LOG_LEVEL_NOTICE);
}

async function fetchAllUsedChunks(s, r) {
  try {
    const o = await collectChunks(r, "INUSE");
    await transferChunks("r2l", "remote -> local", r, s, o);
    Logger("remote -> local: Done", LOG_LEVEL_NOTICE, "balance-r2l");
  } catch (s) {
    Logger("Something went wrong on balancing!", LOG_LEVEL_NOTICE);
    Logger(s, LOG_LEVEL_VERBOSE);
  }
}

function polyfillPromiseWithResolvers() {
  let s, r;
  return {
    promise: new Promise(((o, u) => {
      s = o;
      r = u;
    })),
    resolve: s,
    reject: r
  };
}

var promiseWithResolver = polyfillPromiseWithResolvers;

function resolveWithIgnoreKnownError(s, r) {
  return new Promise(((o, u) => {
    s.then(o).catch((s => isErrorOfMissingDoc(s) ? o(r) : u(s)));
  }));
}

var _a, delay = (s, r) => new Promise((o => {
  setTimeout((() => {
    o(r);
  }), s);
}));

function getDocData(s) {
  return "string" == typeof s ? s : s.join("");
}

function isTextBlob(s) {
  return "text/plain" === s.type;
}

function createTextBlob(s) {
  const r = Array.isArray(s) ? s : [ s ];
  return new Blob(r, {
    endings: "transparent",
    type: "text/plain"
  });
}

function createBinaryBlob(s) {
  return new Blob([ s ], {
    endings: "transparent",
    type: "application/octet-stream"
  });
}

function createBlob(s) {
  if (s instanceof Blob) return s;
  if (s instanceof Uint8Array || s instanceof ArrayBuffer) return createBinaryBlob(s); else return createTextBlob(s);
}

function isTextDocument(s) {
  if ("plain" == s.type) return true;
  if ("plain" == s.datatype) return true;
  if (isPlainText(s.path)) return true; else return false;
}

function readAsBlob(s) {
  if (isTextDocument(s)) return createTextBlob(s.data); else return createBinaryBlob(decodeBinary(s.data));
}

function readContent(s) {
  if (isTextDocument(s)) return getDocData(s.data); else return decodeBinary(s.data);
}

var isIndexDBCmpExist = "undefined" != typeof (null == (_a = null == window ? void 0 : window.indexedDB) ? void 0 : _a.cmp);

async function isDocContentSame(s, r) {
  const o = createBlob(s), u = createBlob(r);
  if (o.size != u.size) return false;
  if (isIndexDBCmpExist) return 0 === window.indexedDB.cmp(await o.arrayBuffer(), await u.arrayBuffer());
  const g = 1e4, _ = o.size;
  let m = 0;
  for (;m < _; ) {
    const s = await o.slice(m, m + g).arrayBuffer(), r = await u.slice(m, m + g).arrayBuffer();
    m += g;
    if (await arrayBufferToBase64Single(s) != await arrayBufferToBase64Single(r)) return false;
  }
  return true;
}

function isObfuscatedEntry(s) {
  if (s._id.startsWith(PREFIX_OBFUSCATED)) return true; else return false;
}

function isEncryptedChunkEntry(s) {
  if (s._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) return true; else return false;
}

function isSyncInfoEntry(s) {
  if (s._id == SYNCINFO_ID) return true; else return false;
}

function memorizeFuncWithLRUCache(s) {
  const r = new LRUCache(100, 1e5, true);
  return o => {
    if (r.has(o)) return r.get(o);
    const u = s(o);
    r.set(o, u);
    return u;
  };
}

var traps = {};

async function waitForSignal(s, r) {
  return await waitForValue(s, r) !== RESULT_TIMED_OUT;
}

function waitForValue(s, r) {
  let o, u;
  const g = r ? setTimeout((() => {
    if (s in traps) traps[s] = traps[s].filter((s => s != u));
    if (o) o(RESULT_TIMED_OUT);
    o = void 0;
  }), r) : false;
  return new Promise((r => {
    if (!(s in traps)) traps[s] = [];
    o = r;
    u = s => {
      if (g) clearTimeout(g);
      r(s);
    };
    traps[s].push(u);
  }));
}

function sendSignal(s) {
  sendValue(s, true);
}

function sendValue(s, r) {
  if (!(s in traps)) return;
  const o = traps[s];
  delete traps[s];
  for (const s of o) s(r);
}

function onlyNot(s) {
  return function _onlyNot(r) {
    if (r === s) return false; else return true;
  };
}

var globalConcurrencyController = Semaphore(50);

function* arrayToChunkedArray(s, r) {
  const o = [ ...s ];
  for (;o.length; ) {
    const s = o.splice(0, r);
    yield s;
  }
}

function unique(s) {
  return [ ...new Set(s) ];
}

function fireAndForget(s) {
  if ("function" == typeof s) return fireAndForget(s());
  s.then((s => {})).catch((s => {}));
}

function isObjectDifferent(s, r) {
  if (typeof s != typeof r) return true;
  if ("object" == typeof s) if (null === s || null === r) return s !== r; else return [ ...new Set([ ...Object.keys(s), ...Object.keys(r) ]) ].map((o => isObjectDifferent(null == s ? void 0 : s[o], null == r ? void 0 : r[o]))).some((s => true == s)); else return s !== r;
}

function determineTypeFromBlob(s) {
  return isTextBlob(s) ? "plain" : "newnote";
}

function determineType(s, r) {
  if (r instanceof Blob) return determineTypeFromBlob(r);
  if (isPlainText(s)) return "plain";
  if (r instanceof Uint8Array) return "newnote";
  if (r instanceof ArrayBuffer) return "newnote"; else return "plain";
}

function isAnyNote(s) {
  return "type" in s && ("newnote" == s.type || "plain" == s.type);
}

function createSavingEntryFromLoadedEntry(s) {
  const r = readAsBlob(s), o = determineType(s.path, r);
  return {
    ...s,
    data: r,
    datatype: o,
    type: o,
    children: []
  };
}

var ExportedSet, ExportedMap, throttle = (s, r) => {
  let o, u = 0;
  return (...g) => {
    if (!u) {
      s(...g);
      u = Date.now();
    } else {
      clearTimeout(o);
      const _ = r - (Date.now() - u);
      o = setTimeout((() => {
        s(...g);
        u = Date.now();
      }), _);
    }
  };
};

function mangle(s) {
  return "$" + s;
}

function unmangle(s) {
  return s.substring(1);
}

function Map$1() {
  this._store = {};
}

Map$1.prototype.get = function(s) {
  var r = mangle(s);
  return this._store[r];
};

Map$1.prototype.set = function(s, r) {
  var o = mangle(s);
  this._store[o] = r;
  return true;
};

Map$1.prototype.has = function(s) {
  return mangle(s) in this._store;
};

Map$1.prototype.keys = function() {
  return Object.keys(this._store).map((s => unmangle(s)));
};

Map$1.prototype.delete = function(s) {
  var r = mangle(s), o = r in this._store;
  delete this._store[r];
  return o;
};

Map$1.prototype.forEach = function(s) {
  for (var r = Object.keys(this._store), o = 0, u = r.length; o < u; o++) {
    var g = r[o];
    s(this._store[g], g = unmangle(g));
  }
};

Object.defineProperty(Map$1.prototype, "size", {
  get: function() {
    return Object.keys(this._store).length;
  }
});

function Set$1(s) {
  this._store = new Map$1;
  if (s && Array.isArray(s)) for (var r = 0, o = s.length; r < o; r++) this.add(s[r]);
}

Set$1.prototype.add = function(s) {
  return this._store.set(s, true);
};

Set$1.prototype.has = function(s) {
  return this._store.has(s);
};

Set$1.prototype.forEach = function(s) {
  this._store.forEach((function(r, o) {
    s(o);
  }));
};

Object.defineProperty(Set$1.prototype, "size", {
  get: function() {
    return this._store.size;
  }
});

function supportsMapAndSet() {
  if ("undefined" == typeof Symbol || "undefined" == typeof Map || "undefined" == typeof Set) return false;
  var s = Object.getOwnPropertyDescriptor(Map, Symbol.species);
  return s && "get" in s && Map[Symbol.species] === Map;
}

if (supportsMapAndSet()) {
  ExportedSet = Set;
  ExportedMap = Map;
} else {
  ExportedSet = Set$1;
  ExportedMap = Map$1;
}

var import_immediate = __toESM(require_lib()), PouchError = class extends Error {
  constructor(s, r, o) {
    super();
    this.status = s;
    this.name = r;
    this.message = o;
    this.error = true;
  }
  toString() {
    return JSON.stringify({
      status: this.status,
      name: this.name,
      message: this.message,
      reason: this.reason
    });
  }
}, UNAUTHORIZED = new PouchError(401, "unauthorized", "Name or password is incorrect."), MISSING_BULK_DOCS = new PouchError(400, "bad_request", "Missing JSON list of 'docs'"), MISSING_DOC = new PouchError(404, "not_found", "missing"), REV_CONFLICT = new PouchError(409, "conflict", "Document update conflict"), INVALID_ID = new PouchError(400, "bad_request", "_id field must contain a string"), MISSING_ID = new PouchError(412, "missing_id", "_id is required for puts"), RESERVED_ID = new PouchError(400, "bad_request", "Only reserved document ids may start with underscore."), NOT_OPEN = new PouchError(412, "precondition_failed", "Database not open"), UNKNOWN_ERROR = new PouchError(500, "unknown_error", "Database encountered an unknown error"), BAD_ARG = new PouchError(500, "badarg", "Some query argument is invalid"), INVALID_REQUEST = new PouchError(400, "invalid_request", "Request was invalid"), QUERY_PARSE_ERROR = new PouchError(400, "query_parse_error", "Some query parameter is invalid"), DOC_VALIDATION = new PouchError(500, "doc_validation", "Bad special document member"), BAD_REQUEST = new PouchError(400, "bad_request", "Something wrong with the request"), NOT_AN_OBJECT = new PouchError(400, "bad_request", "Document must be a JSON object"), DB_MISSING = new PouchError(404, "not_found", "Database not found"), IDB_ERROR = new PouchError(500, "indexed_db_went_bad", "unknown"), WSQ_ERROR = new PouchError(500, "web_sql_went_bad", "unknown"), LDB_ERROR = new PouchError(500, "levelDB_went_went_bad", "unknown"), FORBIDDEN = new PouchError(403, "forbidden", "Forbidden by design doc validate_doc_update function"), INVALID_REV = new PouchError(400, "bad_request", "Invalid rev format"), FILE_EXISTS = new PouchError(412, "file_exists", "The database could not be created, the file already exists."), MISSING_STUB = new PouchError(412, "missing_stub", "A pre-existing attachment stub wasn't found"), INVALID_URL = new PouchError(413, "invalid_url", "Provided URL is invalid");

function createError(s, r) {
  function CustomPouchError(r) {
    for (var o = Object.getOwnPropertyNames(s), u = 0, g = o.length; u < g; u++) if ("function" != typeof s[o[u]]) this[o[u]] = s[o[u]];
    if (void 0 === this.stack) this.stack = (new Error).stack;
    if (void 0 !== r) this.reason = r;
  }
  CustomPouchError.prototype = PouchError.prototype;
  return new CustomPouchError(r);
}

function generateErrorFromResponse(s) {
  if ("object" != typeof s) {
    var r = s;
    (s = UNKNOWN_ERROR).data = r;
  }
  if ("error" in s && "conflict" === s.error) {
    s.name = "conflict";
    s.status = 409;
  }
  if (!("name" in s)) s.name = s.error || "unknown";
  if (!("status" in s)) s.status = 500;
  if (!("message" in s)) s.message = s.message || s.reason;
  if (!("stack" in s)) s.stack = (new Error).stack;
  return s;
}

var getRandomValues, import_events = __toESM(require_events()), rnds8 = new Uint8Array(16);

function rng() {
  if (!getRandomValues) if (!(getRandomValues = "undefined" != typeof crypto && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || "undefined" != typeof msCrypto && "function" == typeof msCrypto.getRandomValues && msCrypto.getRandomValues.bind(msCrypto))) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
  return getRandomValues(rnds8);
}

var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;

function validate(s) {
  return "string" == typeof s && regex_default.test(s);
}

var i, validate_default = validate, byteToHex = [];

for (i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).substr(1));

function stringify(s) {
  var r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, o = (byteToHex[s[r + 0]] + byteToHex[s[r + 1]] + byteToHex[s[r + 2]] + byteToHex[s[r + 3]] + "-" + byteToHex[s[r + 4]] + byteToHex[s[r + 5]] + "-" + byteToHex[s[r + 6]] + byteToHex[s[r + 7]] + "-" + byteToHex[s[r + 8]] + byteToHex[s[r + 9]] + "-" + byteToHex[s[r + 10]] + byteToHex[s[r + 11]] + byteToHex[s[r + 12]] + byteToHex[s[r + 13]] + byteToHex[s[r + 14]] + byteToHex[s[r + 15]]).toLowerCase();
  if (!validate_default(o)) throw TypeError("Stringified UUID is invalid");
  return o;
}

var stringify_default = stringify;

function v4(s, r, o) {
  var u = (s = s || {}).random || (s.rng || rng)();
  u[6] = 15 & u[6] | 64;
  u[8] = 63 & u[8] | 128;
  if (r) {
    o = o || 0;
    for (var g = 0; g < 16; ++g) r[o + g] = u[g];
    return r;
  }
  return stringify_default(u);
}

var v4_default = v4, thisAtob = function(s) {
  return atob(s);
}, thisBtoa = function(s) {
  return btoa(s);
};

function createBlob2(s, r) {
  s = s || [];
  r = r || {};
  try {
    return new Blob(s, r);
  } catch (g) {
    if ("TypeError" !== g.name) throw g;
    for (var o = new ("undefined" != typeof BlobBuilder ? BlobBuilder : "undefined" != typeof MSBlobBuilder ? MSBlobBuilder : "undefined" != typeof MozBlobBuilder ? MozBlobBuilder : WebKitBlobBuilder), u = 0; u < s.length; u += 1) o.append(s[u]);
    return o.getBlob(r.type);
  }
}

function binaryStringToArrayBuffer(s) {
  for (var r = s.length, o = new ArrayBuffer(r), u = new Uint8Array(o), g = 0; g < r; g++) u[g] = s.charCodeAt(g);
  return o;
}

function binStringToBluffer(s, r) {
  return createBlob2([ binaryStringToArrayBuffer(s) ], {
    type: r
  });
}

function b64ToBluffer(s, r) {
  return binStringToBluffer(thisAtob(s), r);
}

function arrayBufferToBinaryString(s) {
  for (var r = "", o = new Uint8Array(s), u = o.byteLength, g = 0; g < u; g++) r += String.fromCharCode(o[g]);
  return r;
}

function readAsBinaryString(s, r) {
  var o = new FileReader, u = "function" == typeof o.readAsBinaryString;
  o.onloadend = function(s) {
    var o = s.target.result || "";
    if (u) return r(o);
    r(arrayBufferToBinaryString(o));
  };
  if (u) o.readAsBinaryString(s); else o.readAsArrayBuffer(s);
}

function blobToBinaryString(s, r) {
  readAsBinaryString(s, (function(s) {
    r(s);
  }));
}

function blobToBase64(s, r) {
  blobToBinaryString(s, (function(s) {
    r(thisBtoa(s));
  }));
}

function readAsArrayBuffer(s, r) {
  var o = new FileReader;
  o.onloadend = function(s) {
    var o = s.target.result || new ArrayBuffer(0);
    r(o);
  };
  o.readAsArrayBuffer(s);
}

var import_spark_md5 = __toESM(require_spark_md5()), setImmediateShim = self.setImmediate || self.setTimeout, MD5_CHUNK_SIZE = 32768;

function rawToBase64(s) {
  return thisBtoa(s);
}

function sliceBlob(s, r, o) {
  if (s.webkitSlice) return s.webkitSlice(r, o); else return s.slice(r, o);
}

function appendBlob(s, r, o, u, g) {
  if (o > 0 || u < r.size) r = sliceBlob(r, o, u);
  readAsArrayBuffer(r, (function(r) {
    s.append(r);
    g();
  }));
}

function appendString(s, r, o, u, g) {
  if (o > 0 || u < r.length) r = r.substring(o, u);
  s.appendBinary(r);
  g();
}

function binaryMd5(s, r) {
  var o = "string" == typeof s, u = o ? s.length : s.size, g = Math.min(MD5_CHUNK_SIZE, u), _ = Math.ceil(u / g), m = 0, b = o ? new import_spark_md5.default : new import_spark_md5.default.ArrayBuffer, E = o ? appendString : appendBlob;
  function next() {
    setImmediateShim(loadNextChunk);
  }
  function done() {
    var s = rawToBase64(b.end(true));
    r(s);
    b.destroy();
  }
  function loadNextChunk() {
    var r = m * g, o = r + g;
    if (++m < _) E(b, s, r, o, next); else E(b, s, r, o, done);
  }
  loadNextChunk();
}

function stringMd5(s) {
  return import_spark_md5.default.hash(s);
}

function isBinaryObject(s) {
  return "undefined" != typeof ArrayBuffer && s instanceof ArrayBuffer || "undefined" != typeof Blob && s instanceof Blob;
}

function cloneArrayBuffer(s) {
  if ("function" == typeof s.slice) return s.slice(0);
  var r = new ArrayBuffer(s.byteLength), o = new Uint8Array(r), u = new Uint8Array(s);
  o.set(u);
  return r;
}

function cloneBinaryObject(s) {
  if (s instanceof ArrayBuffer) return cloneArrayBuffer(s);
  var r = s.size, o = s.type;
  if ("function" == typeof s.slice) return s.slice(0, r, o); else return s.webkitSlice(0, r, o);
}

var funcToString = Function.prototype.toString, objectCtorString = funcToString.call(Object);

function isPlainObject(s) {
  var r = Object.getPrototypeOf(s);
  if (null === r) return true;
  var o = r.constructor;
  return "function" == typeof o && o instanceof o && funcToString.call(o) == objectCtorString;
}

function clone(s) {
  var r, o, u;
  if (!s || "object" != typeof s) return s;
  if (Array.isArray(s)) {
    r = [];
    for (o = 0, u = s.length; o < u; o++) r[o] = clone(s[o]);
    return r;
  }
  if (s instanceof Date && isFinite(s)) return s.toISOString();
  if (isBinaryObject(s)) return cloneBinaryObject(s);
  if (!isPlainObject(s)) return s;
  r = {};
  for (o in s) if (Object.prototype.hasOwnProperty.call(s, o)) {
    var g = clone(s[o]);
    if ("undefined" != typeof g) r[o] = g;
  }
  return r;
}

function once(s) {
  var r = false;
  return function(...o) {
    if (r) throw new Error("once called more than once"); else {
      r = true;
      s.apply(this, o);
    }
  };
}

function toPromise(s) {
  return function(...r) {
    r = clone(r);
    var o = this, u = "function" == typeof r[r.length - 1] ? r.pop() : false, g = new Promise((function(u, g) {
      var _;
      try {
        var m = once((function(s, r) {
          if (s) g(s); else u(r);
        }));
        r.push(m);
        if ((_ = s.apply(o, r)) && "function" == typeof _.then) u(_);
      } catch (s) {
        g(s);
      }
    }));
    if (u) g.then((function(s) {
      u(null, s);
    }), u);
    return g;
  };
}

function logApiCall(s, r, o) {
  if (s.constructor.listeners("debug").length) {
    for (var u = [ "api", s.name, r ], g = 0; g < o.length - 1; g++) u.push(o[g]);
    s.constructor.emit("debug", u);
    var _ = o[o.length - 1];
    o[o.length - 1] = function(o, u) {
      var g = [ "api", s.name, r ];
      g = g.concat(o ? [ "error", o ] : [ "success", u ]);
      s.constructor.emit("debug", g);
      _(o, u);
    };
  }
}

function adapterFun(s, r) {
  return toPromise((function(...o) {
    if (this._closed) return Promise.reject(new Error("database is closed"));
    if (this._destroyed) return Promise.reject(new Error("database is destroyed"));
    var u = this;
    logApiCall(u, s, o);
    if (!this.taskqueue.isReady) return new Promise((function(r, g) {
      u.taskqueue.addTask((function(_) {
        if (_) g(_); else r(u[s].apply(u, o));
      }));
    })); else return r.apply(this, o);
  }));
}

function pick(s, r) {
  for (var o = {}, u = 0, g = r.length; u < g; u++) {
    var _ = r[u];
    if (_ in s) o[_] = s[_];
  }
  return o;
}

var hasLocal, MAX_NUM_CONCURRENT_REQUESTS = 6;

function identityFunction(s) {
  return s;
}

function formatResultForOpenRevsGet(s) {
  return [ {
    ok: s
  } ];
}

function bulkGet(s, r, o) {
  var u = r.docs, g = new ExportedMap;
  u.forEach((function(s) {
    if (g.has(s.id)) g.get(s.id).push(s); else g.set(s.id, [ s ]);
  }));
  var _ = g.size, m = 0, b = new Array(_), E = [];
  g.forEach((function(s, r) {
    E.push(r);
  }));
  var w = 0;
  (function nextBatch() {
    if (!(w >= E.length)) {
      var u = Math.min(w + MAX_NUM_CONCURRENT_REQUESTS, E.length), S = E.slice(w, u);
      (function processBatch(u, E) {
        u.forEach((function(u, w) {
          var S = E + w, L = g.get(u), O = pick(L[0], [ "atts_since", "attachments" ]);
          O.open_revs = L.map((function(s) {
            return s.rev;
          }));
          O.open_revs = O.open_revs.filter(identityFunction);
          var D = identityFunction;
          if (0 === O.open_revs.length) {
            delete O.open_revs;
            D = formatResultForOpenRevsGet;
          }
          [ "revs", "attachments", "binary", "ajax", "latest" ].forEach((function(s) {
            if (s in r) O[s] = r[s];
          }));
          s.get(u, O, (function(s, r) {
            var g;
            if (s) g = [ {
              error: s
            } ]; else g = D(r);
            (function gotResult(s, r, u) {
              b[s] = {
                id: r,
                docs: u
              };
              (function checkDone() {
                if (++m === _) (function collapseResultsAndFinish() {
                  var s = [];
                  b.forEach((function(r) {
                    r.docs.forEach((function(o) {
                      s.push({
                        id: r.id,
                        docs: [ o ]
                      });
                    }));
                  }));
                  o(null, {
                    results: s
                  });
                })();
              })();
            })(S, u, g);
            nextBatch();
          }));
        }));
      })(S, w);
      w += S.length;
    }
  })();
}

try {
  localStorage.setItem("_pouch_check_localstorage", 1);
  hasLocal = !!localStorage.getItem("_pouch_check_localstorage");
} catch (s) {
  hasLocal = false;
}

function hasLocalStorage() {
  return hasLocal;
}

var assign$1, Changes = class extends import_events.default {
  constructor() {
    super();
    this._listeners = {};
    if (hasLocalStorage()) addEventListener("storage", (s => {
      this.emit(s.key);
    }));
  }
  addListener(s, r, o, u) {
    if (!this._listeners[r]) {
      var g = false, _ = this;
      this._listeners[r] = eventFunction;
      this.on(s, eventFunction);
    }
    function eventFunction() {
      if (_._listeners[r]) if (!g) {
        g = true;
        var s = pick(u, [ "style", "include_docs", "attachments", "conflicts", "filter", "doc_ids", "view", "since", "query_params", "binary", "return_docs" ]);
        o.changes(s).on("change", (function(s) {
          if (s.seq > u.since && !u.cancelled) {
            u.since = s.seq;
            u.onChange(s);
          }
        })).on("complete", (function() {
          if ("waiting" === g) (0, import_immediate.default)(eventFunction);
          g = false;
        })).on("error", (function onError() {
          g = false;
        }));
      } else g = "waiting";
    }
  }
  removeListener(s, r) {
    if (r in this._listeners) {
      super.removeListener(s, this._listeners[r]);
      delete this._listeners[r];
    }
  }
  notifyLocalWindows(s) {
    if (hasLocalStorage()) localStorage[s] = "a" === localStorage[s] ? "b" : "a";
  }
  notify(s) {
    this.emit(s);
    this.notifyLocalWindows(s);
  }
};

function guardedConsole(s) {
  if ("undefined" != typeof console && "function" == typeof console[s]) {
    var r = Array.prototype.slice.call(arguments, 1);
    console[s].apply(console, r);
  }
}

function randomNumber(s, r) {
  var o = 6e5;
  s = parseInt(s, 10) || 0;
  if ((r = parseInt(r, 10)) != r || r <= s) r = (s || 1) << 1; else r += 1;
  if (r > o) {
    s = 3e5;
    r = o;
  }
  return ~~((r - s) * Math.random() + s);
}

function defaultBackOff(s) {
  var r = 0;
  if (!s) r = 2e3;
  return randomNumber(s, r);
}

function explainError(s, r) {
  guardedConsole("info", "The above " + s + " is totally normal. " + r);
}

if ("function" == typeof Object.assign) assign$1 = Object.assign; else assign$1 = function(s) {
  for (var r = Object(s), o = 1; o < arguments.length; o++) {
    var u = arguments[o];
    if (null != u) for (var g in u) if (Object.prototype.hasOwnProperty.call(u, g)) r[g] = u[g];
  }
  return r;
};

var assign$2 = assign$1;

function tryFilter(s, r, o) {
  try {
    return !s(r, o);
  } catch (s) {
    var u = "Filter function threw: " + s.toString();
    return createError(BAD_REQUEST, u);
  }
}

function filterChange(s) {
  var r = {}, o = s.filter && "function" == typeof s.filter;
  r.query = s.query_params;
  return function filter3(u) {
    if (!u.doc) u.doc = {};
    var g = o && tryFilter(s.filter, u.doc, r);
    if ("object" == typeof g) return g;
    if (g) return false;
    if (!s.include_docs) delete u.doc; else if (!s.attachments) for (var _ in u.doc._attachments) if (Object.prototype.hasOwnProperty.call(u.doc._attachments, _)) u.doc._attachments[_].stub = true;
    return true;
  };
}

function flatten(s) {
  for (var r = [], o = 0, u = s.length; o < u; o++) r = r.concat(s[o]);
  return r;
}

function f() {}

var res, hasName = f.name;

if (hasName) res = function(s) {
  return s.name;
}; else res = function(s) {
  var r = s.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
  if (r && r[1]) return r[1]; else return "";
};

function invalidIdError(s) {
  var r;
  if (!s) r = createError(MISSING_ID); else if ("string" != typeof s) r = createError(INVALID_ID); else if (/^_/.test(s) && !/^_(design|local)/.test(s)) r = createError(RESERVED_ID);
  if (r) throw r;
}

function isRemote(s) {
  if ("boolean" == typeof s._remote) return s._remote;
  if ("function" == typeof s.type) {
    guardedConsole("warn", "db.type() is deprecated and will be removed in a future version of PouchDB");
    return "http" === s.type();
  }
  return false;
}

function listenerCount(s, r) {
  return "listenerCount" in s ? s.listenerCount(r) : import_events.default.listenerCount(s, r);
}

function parseDesignDocFunctionName(s) {
  if (!s) return null;
  var r = s.split("/");
  if (2 === r.length) return r;
  if (1 === r.length) return [ s, s ]; else return null;
}

function normalizeDesignDocFunctionName(s) {
  var r = parseDesignDocFunctionName(s);
  return r ? r.join("/") : null;
}

var keys = [ "source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor" ], qName = "queryKey", qParser = /(?:^|&)([^&=]*)=?([^&]*)/g, parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

function parseUri(s) {
  for (var r = parser.exec(s), o = {}, u = 14; u--; ) {
    var g = keys[u], _ = r[u] || "", m = -1 !== [ "user", "password" ].indexOf(g);
    o[g] = m ? decodeURIComponent(_) : _;
  }
  o[qName] = {};
  o[keys[12]].replace(qParser, (function(s, r, u) {
    if (r) o[qName][r] = u;
  }));
  return o;
}

function scopeEval(s, r) {
  var o = [], u = [];
  for (var g in r) if (Object.prototype.hasOwnProperty.call(r, g)) {
    o.push(g);
    u.push(r[g]);
  }
  o.push(s);
  return Function.apply(null, o).apply(null, u);
}

function upsert(s, r, o) {
  return s.get(r).catch((function(s) {
    if (404 !== s.status) throw s;
    return {};
  })).then((function(u) {
    var g = u._rev, _ = o(u);
    if (!_) return {
      updated: false,
      rev: g
    };
    _._id = r;
    _._rev = g;
    return tryAndPut(s, _, o);
  }));
}

function tryAndPut(s, r, o) {
  return s.put(r).then((function(s) {
    return {
      updated: true,
      rev: s.rev
    };
  }), (function(u) {
    if (409 !== u.status) throw u;
    return upsert(s, r._id, o);
  }));
}

function rev(s, r) {
  if (!r) return v4_default().replace(/-/g, "").toLowerCase();
  var o = assign$2({}, s);
  delete o._rev_tree;
  return stringMd5(JSON.stringify(o));
}

var uuid = v4_default;

function winningRev(s) {
  for (var r, o, u, g, _ = s.rev_tree.slice(); g = _.pop(); ) {
    var m = g.ids, b = m[2], E = g.pos;
    if (!b.length) {
      var w = !!m[1].deleted, S = m[0];
      if (!r || (u !== w ? u : o !== E ? o < E : r < S)) {
        r = S;
        o = E;
        u = w;
      }
    } else for (var L = 0, O = b.length; L < O; L++) _.push({
      pos: E + 1,
      ids: b[L]
    });
  }
  return o + "-" + r;
}

function traverseRevTree(s, r) {
  for (var o, u = s.slice(); o = u.pop(); ) for (var g = o.pos, _ = o.ids, m = _[2], b = r(0 === m.length, g, _[0], o.ctx, _[1]), E = 0, w = m.length; E < w; E++) u.push({
    pos: g + 1,
    ids: m[E],
    ctx: b
  });
}

function sortByPos(s, r) {
  return s.pos - r.pos;
}

function collectLeaves(s) {
  var r = [];
  traverseRevTree(s, (function(s, o, u, g, _) {
    if (s) r.push({
      rev: o + "-" + u,
      pos: o,
      opts: _
    });
  }));
  r.sort(sortByPos).reverse();
  for (var o = 0, u = r.length; o < u; o++) delete r[o].pos;
  return r;
}

function collectConflicts(s) {
  for (var r = winningRev(s), o = collectLeaves(s.rev_tree), u = [], g = 0, _ = o.length; g < _; g++) {
    var m = o[g];
    if (m.rev !== r && !m.opts.deleted) u.push(m.rev);
  }
  return u;
}

function compactTree(s) {
  var r = [];
  traverseRevTree(s.rev_tree, (function(s, o, u, g, _) {
    if ("available" === _.status && !s) {
      r.push(o + "-" + u);
      _.status = "missing";
    }
  }));
  return r;
}

function findPathToLeaf(s, r) {
  let o = [];
  const u = s.slice();
  let g;
  for (;g = u.pop(); ) {
    const {pos: s, ids: _} = g, m = `${s}-${_[0]}`, b = _[2];
    o.push(m);
    if (m === r) {
      if (0 !== b.length) throw new Error("The requested revision is not a leaf");
      return o.reverse();
    }
    if (0 === b.length || b.length > 1) o = [];
    for (let r = 0, o = b.length; r < o; r++) u.push({
      pos: s + 1,
      ids: b[r]
    });
  }
  if (0 === o.length) throw new Error("The requested revision does not exist");
  return o.reverse();
}

function rootToLeaf(s) {
  for (var r, o = [], u = s.slice(); r = u.pop(); ) {
    var g = r.pos, _ = r.ids, m = _[0], b = _[1], E = _[2], w = 0 === E.length, S = r.history ? r.history.slice() : [];
    S.push({
      id: m,
      opts: b
    });
    if (w) o.push({
      pos: g + 1 - S.length,
      ids: S
    });
    for (var L = 0, O = E.length; L < O; L++) u.push({
      pos: g + 1,
      ids: E[L],
      history: S
    });
  }
  return o.reverse();
}

function sortByPos$1(s, r) {
  return s.pos - r.pos;
}

function binarySearch(s, r, o) {
  for (var u, g = 0, _ = s.length; g < _; ) if (o(s[u = g + _ >>> 1], r) < 0) g = u + 1; else _ = u;
  return g;
}

function insertSorted(s, r, o) {
  var u = binarySearch(s, r, o);
  s.splice(u, 0, r);
}

function pathToTree(s, r) {
  for (var o, u, g = r, _ = s.length; g < _; g++) {
    var m = s[g], b = [ m.id, m.opts, [] ];
    if (u) {
      u[2].push(b);
      u = b;
    } else o = u = b;
  }
  return o;
}

function compareTree(s, r) {
  return s[0] < r[0] ? -1 : 1;
}

function mergeTree(s, r) {
  for (var o = [ {
    tree1: s,
    tree2: r
  } ], u = false; o.length > 0; ) {
    var g = o.pop(), _ = g.tree1, m = g.tree2;
    if (_[1].status || m[1].status) _[1].status = "available" === _[1].status || "available" === m[1].status ? "available" : "missing";
    for (var b = 0; b < m[2].length; b++) if (_[2][0]) {
      for (var E = false, w = 0; w < _[2].length; w++) if (_[2][w][0] === m[2][b][0]) {
        o.push({
          tree1: _[2][w],
          tree2: m[2][b]
        });
        E = true;
      }
      if (!E) {
        u = "new_branch";
        insertSorted(_[2], m[2][b], compareTree);
      }
    } else {
      u = "new_leaf";
      _[2][0] = m[2][b];
    }
  }
  return {
    conflicts: u,
    tree: s
  };
}

function doMerge(s, r, o) {
  var u, g = [], _ = false, m = false;
  if (!s.length) return {
    tree: [ r ],
    conflicts: "new_leaf"
  };
  for (var b = 0, E = s.length; b < E; b++) {
    var w = s[b];
    if (w.pos === r.pos && w.ids[0] === r.ids[0]) {
      u = mergeTree(w.ids, r.ids);
      g.push({
        pos: w.pos,
        ids: u.tree
      });
      _ = _ || u.conflicts;
      m = true;
    } else if (true !== o) {
      var S = w.pos < r.pos ? w : r, L = w.pos < r.pos ? r : w, O = L.pos - S.pos, D = [], C = [];
      C.push({
        ids: S.ids,
        diff: O,
        parent: null,
        parentIdx: null
      });
      for (;C.length > 0; ) {
        var k = C.pop();
        if (0 !== k.diff) for (var T = k.ids[2], A = 0, R = T.length; A < R; A++) C.push({
          ids: T[A],
          diff: k.diff - 1,
          parent: k.ids,
          parentIdx: A
        }); else if (k.ids[0] === L.ids[0]) D.push(k);
      }
      var I = D[0];
      if (!I) g.push(w); else {
        u = mergeTree(I.ids, L.ids);
        I.parent[2][I.parentIdx] = u.tree;
        g.push({
          pos: S.pos,
          ids: S.ids
        });
        _ = _ || u.conflicts;
        m = true;
      }
    } else g.push(w);
  }
  if (!m) g.push(r);
  g.sort(sortByPos$1);
  return {
    tree: g,
    conflicts: _ || "internal_node"
  };
}

function stem(s, r) {
  for (var o, u, g = rootToLeaf(s), _ = 0, m = g.length; _ < m; _++) {
    var b, E = g[_], w = E.ids;
    if (w.length > r) {
      if (!o) o = {};
      var S = w.length - r;
      b = {
        pos: E.pos + S,
        ids: pathToTree(w, S)
      };
      for (var L = 0; L < S; L++) {
        var O = E.pos + L + "-" + w[L].id;
        o[O] = true;
      }
    } else b = {
      pos: E.pos,
      ids: pathToTree(w, 0)
    };
    if (u) u = doMerge(u, b, true).tree; else u = [ b ];
  }
  if (o) traverseRevTree(u, (function(s, r, u) {
    delete o[r + "-" + u];
  }));
  return {
    tree: u,
    revs: o ? Object.keys(o) : []
  };
}

function merge(s, r, o) {
  var u = doMerge(s, r), g = stem(u.tree, o);
  return {
    tree: g.tree,
    stemmedRevs: g.revs,
    conflicts: u.conflicts
  };
}

function removeLeafFromRevTree(s, r) {
  return s.flatMap((s => (s = removeLeafFromPath(s, r)) ? [ s ] : []));
}

function removeLeafFromPath(s, r) {
  const o = clone(s), u = [ o ];
  let g;
  for (;g = u.pop(); ) {
    const {pos: s, ids: [_, , m], parent: b} = g;
    if (0 === m.length && `${s}-${_}` === r) {
      if (!b) return null;
      b.ids[2] = b.ids[2].filter((function(s) {
        return s[0] !== _;
      }));
      return o;
    }
    for (let r = 0, o = m.length; r < o; r++) u.push({
      pos: s + 1,
      ids: m[r],
      parent: g
    });
  }
  return o;
}

function revExists(s, r) {
  for (var o, u = s.slice(), g = r.split("-"), _ = parseInt(g[0], 10), m = g[1]; o = u.pop(); ) {
    if (o.pos === _ && o.ids[0] === m) return true;
    for (var b = o.ids[2], E = 0, w = b.length; E < w; E++) u.push({
      pos: o.pos + 1,
      ids: b[E]
    });
  }
  return false;
}

function getTrees(s) {
  return s.ids;
}

function isDeleted(s, r) {
  if (!r) r = winningRev(s);
  for (var o, u = r.substring(r.indexOf("-") + 1), g = s.rev_tree.map(getTrees); o = g.pop(); ) {
    if (o[0] === u) return !!o[1].deleted;
    g = g.concat(o[2]);
  }
}

function isLocalId(s) {
  return /^_local/.test(s);
}

function latest(s, r) {
  for (var o, u = r.rev_tree.slice(); o = u.pop(); ) {
    var g = o.pos, _ = o.ids, m = _[0], b = _[1], E = _[2], w = 0 === E.length, S = o.history ? o.history.slice() : [];
    S.push({
      id: m,
      pos: g,
      opts: b
    });
    if (w) for (var L = 0, O = S.length; L < O; L++) {
      var D = S[L];
      if (D.pos + "-" + D.id === s) return g + "-" + m;
    }
    for (var C = 0, k = E.length; C < k; C++) u.push({
      pos: g + 1,
      ids: E[C],
      history: S
    });
  }
  throw new Error("Unable to resolve latest revision for id " + r.id + ", rev " + s);
}

var import_events2 = __toESM(require_events()), a = "undefined" != typeof AbortController ? AbortController : function() {
  return {
    abort: function() {}
  };
}, f2 = fetch, h = Headers;

function pad(s, r, o) {
  for (var u = "", g = o - s.length; u.length < g; ) u += r;
  return u;
}

function padLeft(s, r, o) {
  return pad(s, r, o) + s;
}

var MIN_MAGNITUDE = -324, MAGNITUDE_DIGITS = 3, SEP = "";

function collate(s, r) {
  if (s === r) return 0;
  s = normalizeKey(s);
  r = normalizeKey(r);
  var o = collationIndex(s), u = collationIndex(r);
  if (o - u != 0) return o - u;
  switch (typeof s) {
   case "number":
    return s - r;

   case "boolean":
    return s < r ? -1 : 1;

   case "string":
    return stringCollate(s, r);
  }
  return Array.isArray(s) ? arrayCollate(s, r) : objectCollate(s, r);
}

function normalizeKey(s) {
  switch (typeof s) {
   case "undefined":
    return null;

   case "number":
    if (s === 1 / 0 || s === -1 / 0 || isNaN(s)) return null; else return s;

   case "object":
    var r = s;
    if (Array.isArray(s)) {
      var o = s.length;
      s = new Array(o);
      for (var u = 0; u < o; u++) s[u] = normalizeKey(r[u]);
    } else if (s instanceof Date) return s.toJSON(); else if (null !== s) {
      s = {};
      for (var g in r) if (Object.prototype.hasOwnProperty.call(r, g)) {
        var _ = r[g];
        if ("undefined" != typeof _) s[g] = normalizeKey(_);
      }
    }
  }
  return s;
}

function indexify(s) {
  if (null !== s) switch (typeof s) {
   case "boolean":
    return s ? 1 : 0;

   case "number":
    return numToIndexableString(s);

   case "string":
    return s.replace(/\u0002/g, "").replace(/\u0001/g, "").replace(/\u0000/g, "");

   case "object":
    var r = Array.isArray(s), o = r ? s : Object.keys(s), u = -1, g = o.length, _ = "";
    if (r) for (;++u < g; ) _ += toIndexableString(o[u]); else for (;++u < g; ) {
      var m = o[u];
      _ += toIndexableString(m) + toIndexableString(s[m]);
    }
    return _;
  }
  return "";
}

function toIndexableString(s) {
  return collationIndex(s = normalizeKey(s)) + SEP + indexify(s) + "\0";
}

function parseNumber(s, r) {
  var o, u = r;
  if ("1" === s[r]) {
    o = 0;
    r++;
  } else {
    var g = "0" === s[r];
    r++;
    var _ = "", m = s.substring(r, r + MAGNITUDE_DIGITS), b = parseInt(m, 10) + MIN_MAGNITUDE;
    if (g) b = -b;
    r += MAGNITUDE_DIGITS;
    for (;;) {
      var E = s[r];
      if ("\0" === E) break; else _ += E;
      r++;
    }
    if (1 === (_ = _.split(".")).length) o = parseInt(_, 10); else o = parseFloat(_[0] + "." + _[1]);
    if (g) o -= 10;
    if (0 !== b) o = parseFloat(o + "e" + b);
  }
  return {
    num: o,
    length: r - u
  };
}

function pop(s, r) {
  var o = s.pop();
  if (r.length) {
    var u = r[r.length - 1];
    if (o === u.element) {
      r.pop();
      u = r[r.length - 1];
    }
    var g = u.element, _ = u.index;
    if (Array.isArray(g)) g.push(o); else if (_ === s.length - 2) g[s.pop()] = o; else s.push(o);
  }
}

function parseIndexableString(s) {
  for (var r = [], o = [], u = 0; ;) {
    var g = s[u++];
    if ("\0" === g) if (1 === r.length) return r.pop(); else {
      pop(r, o);
      continue;
    }
    switch (g) {
     case "1":
      r.push(null);
      break;

     case "2":
      r.push("1" === s[u]);
      u++;
      break;

     case "3":
      var _ = parseNumber(s, u);
      r.push(_.num);
      u += _.length;
      break;

     case "4":
      for (var m = ""; ;) {
        var b = s[u];
        if ("\0" === b) break;
        m += b;
        u++;
      }
      m = m.replace(/\u0001\u0001/g, "\0").replace(/\u0001\u0002/g, "").replace(/\u0002\u0002/g, "");
      r.push(m);
      break;

     case "5":
      var E = {
        element: [],
        index: r.length
      };
      r.push(E.element);
      o.push(E);
      break;

     case "6":
      var w = {
        element: {},
        index: r.length
      };
      r.push(w.element);
      o.push(w);
      break;

     default:
      throw new Error("bad collationIndex or unexpectedly reached end of input: " + g);
    }
  }
}

function arrayCollate(s, r) {
  for (var o = Math.min(s.length, r.length), u = 0; u < o; u++) {
    var g = collate(s[u], r[u]);
    if (0 !== g) return g;
  }
  return s.length === r.length ? 0 : s.length > r.length ? 1 : -1;
}

function stringCollate(s, r) {
  return s === r ? 0 : s > r ? 1 : -1;
}

function objectCollate(s, r) {
  for (var o = Object.keys(s), u = Object.keys(r), g = Math.min(o.length, u.length), _ = 0; _ < g; _++) {
    var m = collate(o[_], u[_]);
    if (0 !== m) return m;
    if (0 !== (m = collate(s[o[_]], r[u[_]]))) return m;
  }
  return o.length === u.length ? 0 : o.length > u.length ? 1 : -1;
}

function collationIndex(s) {
  var r = [ "boolean", "number", "string", "object" ].indexOf(typeof s);
  if (~r) {
    if (null === s) return 1;
    if (Array.isArray(s)) return 5; else return r < 3 ? r + 2 : r + 3;
  }
  if (Array.isArray(s)) return 5;
}

function numToIndexableString(s) {
  if (0 === s) return "1";
  var r = s.toExponential().split(/e\+?/), o = parseInt(r[1], 10), u = s < 0, g = u ? "0" : "2", _ = padLeft(((u ? -o : o) - MIN_MAGNITUDE).toString(), "0", MAGNITUDE_DIGITS);
  g += SEP + _;
  var m = Math.abs(parseFloat(r[0]));
  if (u) m = 10 - m;
  var b = m.toFixed(20);
  b = b.replace(/\.?0+$/, "");
  return g += SEP + b;
}

function getFieldFromDoc(s, r) {
  for (var o = s, u = 0, g = r.length; u < g && (o = o[r[u]]); u++) ;
  return o;
}

function setFieldInDoc(s, r, o) {
  for (var u = 0, g = r.length; u < g - 1; u++) {
    var _ = r[u];
    s = s[_] = s[_] || {};
  }
  s[r[g - 1]] = o;
}

function compare(s, r) {
  return s < r ? -1 : s > r ? 1 : 0;
}

function parseField(s) {
  for (var r = [], o = "", u = 0, g = s.length; u < g; u++) {
    var _ = s[u];
    if (u > 0 && "\\" === s[u - 1] && ("$" === _ || "." === _)) o = o.substring(0, o.length - 1) + _; else if ("." === _) {
      r.push(o);
      o = "";
    } else o += _;
  }
  r.push(o);
  return r;
}

var combinationFields = [ "$or", "$nor", "$not" ];

function isCombinationalField(s) {
  return combinationFields.indexOf(s) > -1;
}

function getKey(s) {
  return Object.keys(s)[0];
}

function getValue(s) {
  return s[getKey(s)];
}

function mergeAndedSelectors(s) {
  var r = {}, o = {
    $or: true,
    $nor: true
  };
  s.forEach((function(s) {
    Object.keys(s).forEach((function(u) {
      var g = s[u];
      if ("object" != typeof g) g = {
        $eq: g
      };
      if (isCombinationalField(u)) if (g instanceof Array) {
        if (o[u]) {
          o[u] = false;
          r[u] = g;
          return;
        }
        var _ = [];
        r[u].forEach((function(s) {
          Object.keys(g).forEach((function(r) {
            var o = g[r], u = Math.max(Object.keys(s).length, Object.keys(o).length), m = mergeAndedSelectors([ s, o ]);
            if (!(Object.keys(m).length <= u)) _.push(m);
          }));
        }));
        r[u] = _;
      } else r[u] = mergeAndedSelectors([ g ]); else {
        var m = r[u] = r[u] || {};
        Object.keys(g).forEach((function(s) {
          var r = g[s];
          if ("$gt" === s || "$gte" === s) return mergeGtGte(s, r, m); else if ("$lt" === s || "$lte" === s) return mergeLtLte(s, r, m); else if ("$ne" === s) return mergeNe(r, m); else if ("$eq" === s) return mergeEq(r, m); else if ("$regex" === s) return mergeRegex(r, m);
          m[s] = r;
        }));
      }
    }));
  }));
  return r;
}

function mergeGtGte(s, r, o) {
  if ("undefined" == typeof o.$eq) if ("undefined" != typeof o.$gte) {
    if ("$gte" === s) {
      if (r > o.$gte) o.$gte = r;
    } else if (r >= o.$gte) {
      delete o.$gte;
      o.$gt = r;
    }
  } else if ("undefined" != typeof o.$gt) {
    if ("$gte" === s) {
      if (r > o.$gt) {
        delete o.$gt;
        o.$gte = r;
      }
    } else if (r > o.$gt) o.$gt = r;
  } else o[s] = r;
}

function mergeLtLte(s, r, o) {
  if ("undefined" == typeof o.$eq) if ("undefined" != typeof o.$lte) {
    if ("$lte" === s) {
      if (r < o.$lte) o.$lte = r;
    } else if (r <= o.$lte) {
      delete o.$lte;
      o.$lt = r;
    }
  } else if ("undefined" != typeof o.$lt) {
    if ("$lte" === s) {
      if (r < o.$lt) {
        delete o.$lt;
        o.$lte = r;
      }
    } else if (r < o.$lt) o.$lt = r;
  } else o[s] = r;
}

function mergeNe(s, r) {
  if ("$ne" in r) r.$ne.push(s); else r.$ne = [ s ];
}

function mergeEq(s, r) {
  delete r.$gt;
  delete r.$gte;
  delete r.$lt;
  delete r.$lte;
  delete r.$ne;
  r.$eq = s;
}

function mergeRegex(s, r) {
  if ("$regex" in r) r.$regex.push(s); else r.$regex = [ s ];
}

function mergeAndedSelectorsNested(s) {
  for (var r in s) {
    if (Array.isArray(s)) for (var o in s) if (s[o]["$and"]) s[o] = mergeAndedSelectors(s[o]["$and"]);
    var u = s[r];
    if ("object" == typeof u) mergeAndedSelectorsNested(u);
  }
  return s;
}

function isAndInSelector(s, r) {
  for (var o in s) {
    if ("$and" === o) r = true;
    var u = s[o];
    if ("object" == typeof u) r = isAndInSelector(u, r);
  }
  return r;
}

function massageSelector(s) {
  var r = clone(s);
  if (isAndInSelector(r, false)) if ("$and" in (r = mergeAndedSelectorsNested(r))) r = mergeAndedSelectors(r["$and"]);
  [ "$or", "$nor" ].forEach((function(s) {
    if (s in r) r[s].forEach((function(s) {
      for (var r = Object.keys(s), o = 0; o < r.length; o++) {
        var u = r[o], g = s[u];
        if ("object" != typeof g || null === g) s[u] = {
          $eq: g
        };
      }
    }));
  }));
  if ("$not" in r) r["$not"] = mergeAndedSelectors([ r["$not"] ]);
  for (var o = Object.keys(r), u = 0; u < o.length; u++) {
    var g = o[u], _ = r[g];
    if ("object" != typeof _ || null === _) _ = {
      $eq: _
    };
    r[g] = _;
  }
  normalizeArrayOperators(r);
  return r;
}

function normalizeArrayOperators(s) {
  Object.keys(s).forEach((function(r) {
    var o = s[r];
    if (Array.isArray(o)) o.forEach((function(s) {
      if (s && "object" == typeof s) normalizeArrayOperators(s);
    })); else if ("$ne" === r) s.$ne = [ o ]; else if ("$regex" === r) s.$regex = [ o ]; else if (o && "object" == typeof o) normalizeArrayOperators(o);
  }));
}

function createFieldSorter(s) {
  function getFieldValuesAsArray(r) {
    return s.map((function(s) {
      var o = parseField(getKey(s));
      return getFieldFromDoc(r, o);
    }));
  }
  return function(s, r) {
    var o = collate(getFieldValuesAsArray(s.doc), getFieldValuesAsArray(r.doc));
    if (0 !== o) return o; else return compare(s.doc._id, r.doc._id);
  };
}

function filterInMemoryFields(s, r, o) {
  s = s.filter((function(s) {
    return rowFilter(s.doc, r.selector, o);
  }));
  if (r.sort) {
    var u = createFieldSorter(r.sort);
    s = s.sort(u);
    if ("string" != typeof r.sort[0] && "desc" === getValue(r.sort[0])) s = s.reverse();
  }
  if ("limit" in r || "skip" in r) {
    var g = r.skip || 0, _ = ("limit" in r ? r.limit : s.length) + g;
    s = s.slice(g, _);
  }
  return s;
}

function rowFilter(s, r, o) {
  return o.every((function(o) {
    var u = r[o], g = parseField(o), _ = getFieldFromDoc(s, g);
    if (isCombinationalField(o)) return matchCominationalSelector(o, u, s); else return matchSelector(u, s, g, _);
  }));
}

function matchSelector(s, r, o, u) {
  if (!s) return true;
  if ("object" == typeof s) return Object.keys(s).every((function(g) {
    var _ = s[g];
    if (0 === g.indexOf("$")) return match2(g, r, _, o, u); else {
      var m = parseField(g);
      if (void 0 === u && "object" != typeof _ && m.length > 0) return false;
      var b = getFieldFromDoc(u, m);
      if ("object" == typeof _) return matchSelector(_, r, o, b); else return match2("$eq", r, _, m, b);
    }
  })); else return s === u;
}

function matchCominationalSelector(s, r, o) {
  if ("$or" === s) return r.some((function(s) {
    return rowFilter(o, s, Object.keys(s));
  }));
  if ("$not" === s) return !rowFilter(o, r, Object.keys(r)); else return !r.find((function(s) {
    return rowFilter(o, s, Object.keys(s));
  }));
}

function match2(s, r, o, u, g) {
  if (!matchers[s]) throw new Error('unknown operator "' + s + '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
  return matchers[s](r, o, u, g);
}

function fieldExists(s) {
  return "undefined" != typeof s && null !== s;
}

function fieldIsNotUndefined(s) {
  return "undefined" != typeof s;
}

function modField(s, r) {
  if ("number" != typeof s || parseInt(s, 10) !== s) return false; else return s % r[0] === r[1];
}

function arrayContainsValue(s, r) {
  return r.some((function(r) {
    if (s instanceof Array) return s.some((function(s) {
      return 0 === collate(r, s);
    })); else return 0 === collate(r, s);
  }));
}

function arrayContainsAllValues(s, r) {
  return r.every((function(r) {
    return s.some((function(s) {
      return 0 === collate(r, s);
    }));
  }));
}

function arraySize(s, r) {
  return s.length === r;
}

function regexMatch(s, r) {
  return new RegExp(r).test(s);
}

function typeMatch(s, r) {
  switch (r) {
   case "null":
    return null === s;

   case "boolean":
    return "boolean" == typeof s;

   case "number":
    return "number" == typeof s;

   case "string":
    return "string" == typeof s;

   case "array":
    return s instanceof Array;

   case "object":
    return "[object Object]" === {}.toString.call(s);
  }
}

var matchers = {
  $elemMatch: function(s, r, o, u) {
    if (!Array.isArray(u)) return false;
    if (0 === u.length) return false;
    if ("object" == typeof u[0] && null !== u[0]) return u.some((function(s) {
      return rowFilter(s, r, Object.keys(r));
    })); else return u.some((function(u) {
      return matchSelector(r, s, o, u);
    }));
  },
  $allMatch: function(s, r, o, u) {
    if (!Array.isArray(u)) return false;
    if (0 === u.length) return false;
    if ("object" == typeof u[0] && null !== u[0]) return u.every((function(s) {
      return rowFilter(s, r, Object.keys(r));
    })); else return u.every((function(u) {
      return matchSelector(r, s, o, u);
    }));
  },
  $eq: function(s, r, o, u) {
    return fieldIsNotUndefined(u) && 0 === collate(u, r);
  },
  $gte: function(s, r, o, u) {
    return fieldIsNotUndefined(u) && collate(u, r) >= 0;
  },
  $gt: function(s, r, o, u) {
    return fieldIsNotUndefined(u) && collate(u, r) > 0;
  },
  $lte: function(s, r, o, u) {
    return fieldIsNotUndefined(u) && collate(u, r) <= 0;
  },
  $lt: function(s, r, o, u) {
    return fieldIsNotUndefined(u) && collate(u, r) < 0;
  },
  $exists: function(s, r, o, u) {
    if (r) return fieldIsNotUndefined(u); else return !fieldIsNotUndefined(u);
  },
  $mod: function(s, r, o, u) {
    return fieldExists(u) && modField(u, r);
  },
  $ne: function(s, r, o, u) {
    return r.every((function(s) {
      return 0 !== collate(u, s);
    }));
  },
  $in: function(s, r, o, u) {
    return fieldExists(u) && arrayContainsValue(u, r);
  },
  $nin: function(s, r, o, u) {
    return fieldExists(u) && !arrayContainsValue(u, r);
  },
  $size: function(s, r, o, u) {
    return fieldExists(u) && Array.isArray(u) && arraySize(u, r);
  },
  $all: function(s, r, o, u) {
    return Array.isArray(u) && arrayContainsAllValues(u, r);
  },
  $regex: function(s, r, o, u) {
    return fieldExists(u) && "string" == typeof u && r.every((function(s) {
      return regexMatch(u, s);
    }));
  },
  $type: function(s, r, o, u) {
    return typeMatch(u, r);
  }
};

function matchesSelector(s, r) {
  if ("object" != typeof r) throw new Error("Selector error: expected a JSON object");
  var o = filterInMemoryFields([ {
    doc: s
  } ], {
    selector: r = massageSelector(r)
  }, Object.keys(r));
  return o && 1 === o.length;
}

function evalFilter(s) {
  return scopeEval('"use strict";\nreturn ' + s + ";", {});
}

function evalView(s) {
  return scopeEval([ "return function(doc) {", '  "use strict";', "  var emitted = false;", "  var emit = function (a, b) {", "    emitted = true;", "  };", "  var view = " + s + ";", "  view(doc);", "  if (emitted) {", "    return true;", "  }", "};" ].join("\n"), {});
}

function validate2(s, r) {
  if (s.selector) if (s.filter && "_selector" !== s.filter) {
    var o = "string" == typeof s.filter ? s.filter : "function";
    return r(new Error('selector invalid for filter "' + o + '"'));
  }
  r();
}

function normalize(s) {
  if (s.view && !s.filter) s.filter = "_view";
  if (s.selector && !s.filter) s.filter = "_selector";
  if (s.filter && "string" == typeof s.filter) if ("_view" === s.filter) s.view = normalizeDesignDocFunctionName(s.view); else s.filter = normalizeDesignDocFunctionName(s.filter);
}

function shouldFilter(s, r) {
  return r.filter && "string" == typeof r.filter && !r.doc_ids && !isRemote(s.db);
}

function filter2(s, r) {
  var o = r.complete;
  if ("_view" === r.filter) {
    if (!r.view || "string" != typeof r.view) {
      var u = createError(BAD_REQUEST, "`view` filter parameter not found or invalid.");
      return o(u);
    }
    var g = parseDesignDocFunctionName(r.view);
    s.db.get("_design/" + g[0], (function(u, _) {
      if (s.isCancelled) return o(null, {
        status: "cancelled"
      });
      if (u) return o(generateErrorFromResponse(u));
      var m = _ && _.views && _.views[g[1]] && _.views[g[1]].map;
      if (!m) return o(createError(MISSING_DOC, _.views ? "missing json key: " + g[1] : "missing json key: views"));
      r.filter = evalView(m);
      s.doChanges(r);
    }));
  } else if (r.selector) {
    r.filter = function(s) {
      return matchesSelector(s, r.selector);
    };
    s.doChanges(r);
  } else {
    var _ = parseDesignDocFunctionName(r.filter);
    s.db.get("_design/" + _[0], (function(u, g) {
      if (s.isCancelled) return o(null, {
        status: "cancelled"
      });
      if (u) return o(generateErrorFromResponse(u));
      var m = g && g.filters && g.filters[_[1]];
      if (!m) return o(createError(MISSING_DOC, g && g.filters ? "missing json key: " + _[1] : "missing json key: filters"));
      r.filter = evalFilter(m);
      s.doChanges(r);
    }));
  }
}

function applyChangesFilterPlugin(s) {
  s._changesFilterPlugin = {
    validate: validate2,
    normalize,
    shouldFilter,
    filter: filter2
  };
}

var index_browser_es_default = applyChangesFilterPlugin;

function tryCatchInChangeListener(s, r, o, u) {
  try {
    s.emit("change", r, o, u);
  } catch (s) {
    guardedConsole("error", 'Error in .on("change", function):', s);
  }
}

function processChange(s, r, o) {
  var u = [ {
    rev: s._rev
  } ];
  if ("all_docs" === o.style) u = collectLeaves(r.rev_tree).map((function(s) {
    return {
      rev: s.rev
    };
  }));
  var g = {
    id: r.id,
    changes: u,
    doc: s
  };
  if (isDeleted(r, s._rev)) g.deleted = true;
  if (o.conflicts) {
    g.doc._conflicts = collectConflicts(r);
    if (!g.doc._conflicts.length) delete g.doc._conflicts;
  }
  return g;
}

var Changes2 = class extends import_events2.default {
  constructor(s, r, o) {
    super();
    this.db = s;
    var u = (r = r ? clone(r) : {}).complete = once(((r, o) => {
      if (r) {
        if (listenerCount(this, "error") > 0) this.emit("error", r);
      } else this.emit("complete", o);
      this.removeAllListeners();
      s.removeListener("destroyed", onDestroy2);
    }));
    if (o) {
      this.on("complete", (function(s) {
        o(null, s);
      }));
      this.on("error", o);
    }
    const onDestroy2 = () => {
      this.cancel();
    };
    s.once("destroyed", onDestroy2);
    r.onChange = (s, r, o) => {
      if (!this.isCancelled) tryCatchInChangeListener(this, s, r, o);
    };
    var g = new Promise((function(s, o) {
      r.complete = function(r, u) {
        if (r) o(r); else s(u);
      };
    }));
    this.once("cancel", (function() {
      s.removeListener("destroyed", onDestroy2);
      r.complete(null, {
        status: "cancelled"
      });
    }));
    this.then = g.then.bind(g);
    this["catch"] = g["catch"].bind(g);
    this.then((function(s) {
      u(null, s);
    }), u);
    if (!s.taskqueue.isReady) s.taskqueue.addTask((s => {
      if (s) r.complete(s); else if (this.isCancelled) this.emit("cancel"); else this.validateChanges(r);
    })); else this.validateChanges(r);
  }
  cancel() {
    this.isCancelled = true;
    if (this.db.taskqueue.isReady) this.emit("cancel");
  }
  validateChanges(s) {
    var r = s.complete;
    if (PouchDB._changesFilterPlugin) PouchDB._changesFilterPlugin.validate(s, (o => {
      if (o) return r(o);
      this.doChanges(s);
    })); else this.doChanges(s);
  }
  doChanges(s) {
    var r = s.complete;
    if ("live" in (s = clone(s)) && !("continuous" in s)) s.continuous = s.live;
    s.processChange = processChange;
    if ("latest" === s.since) s.since = "now";
    if (!s.since) s.since = 0;
    if ("now" !== s.since) {
      if (PouchDB._changesFilterPlugin) {
        PouchDB._changesFilterPlugin.normalize(s);
        if (PouchDB._changesFilterPlugin.shouldFilter(this, s)) return PouchDB._changesFilterPlugin.filter(this, s);
      } else [ "doc_ids", "filter", "selector", "view" ].forEach((function(r) {
        if (r in s) guardedConsole("warn", 'The "' + r + '" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.');
      }));
      if (!("descending" in s)) s.descending = false;
      s.limit = 0 === s.limit ? 1 : s.limit;
      s.complete = r;
      var o = this.db._changes(s);
      if (o && "function" == typeof o.cancel) {
        const s = this.cancel;
        this.cancel = (...r) => {
          o.cancel();
          s.apply(this, r);
        };
      }
    } else this.db.info().then((o => {
      if (!this.isCancelled) {
        s.since = o.update_seq;
        this.doChanges(s);
      } else r(null, {
        status: "cancelled"
      });
    }), r);
  }
};

function compare2(s, r) {
  return s < r ? -1 : s > r ? 1 : 0;
}

function yankError(s, r) {
  return function(o, u) {
    if (o || u[0] && u[0].error) {
      (o = o || u[0]).docId = r;
      s(o);
    } else s(null, u.length ? u[0] : u);
  };
}

function cleanDocs(s) {
  for (var r = 0; r < s.length; r++) {
    var o = s[r];
    if (o._deleted) delete o._attachments; else if (o._attachments) for (var u = Object.keys(o._attachments), g = 0; g < u.length; g++) {
      var _ = u[g];
      o._attachments[_] = pick(o._attachments[_], [ "data", "digest", "content_type", "length", "revpos", "stub" ]);
    }
  }
}

function compareByIdThenRev(s, r) {
  var o = compare2(s._id, r._id);
  if (0 !== o) return o; else return compare2(s._revisions ? s._revisions.start : 0, r._revisions ? r._revisions.start : 0);
}

function computeHeight(s) {
  var r = {}, o = [];
  traverseRevTree(s, (function(s, u, g, _) {
    var m = u + "-" + g;
    if (s) r[m] = 0;
    if (void 0 !== _) o.push({
      from: _,
      to: m
    });
    return m;
  }));
  o.reverse();
  o.forEach((function(s) {
    if (void 0 === r[s.from]) r[s.from] = 1 + r[s.to]; else r[s.from] = Math.min(r[s.from], 1 + r[s.to]);
  }));
  return r;
}

function allDocsKeysParse(s) {
  var r = "limit" in s ? s.keys.slice(s.skip, s.limit + s.skip) : s.skip > 0 ? s.keys.slice(s.skip) : s.keys;
  s.keys = r;
  s.skip = 0;
  delete s.limit;
  if (s.descending) {
    r.reverse();
    s.descending = false;
  }
}

function doNextCompaction(s) {
  var r = s._compactionQueue[0], o = r.opts, u = r.callback;
  s.get("_local/compaction").catch((function() {
    return false;
  })).then((function(r) {
    if (r && r.last_seq) o.last_seq = r.last_seq;
    s._compact(o, (function(r, o) {
      if (r) u(r); else u(null, o);
      (0, import_immediate.default)((function() {
        s._compactionQueue.shift();
        if (s._compactionQueue.length) doNextCompaction(s);
      }));
    }));
  }));
}

function appendPurgeSeq(s, r, o) {
  return s.get("_local/purges").then((function(s) {
    const u = s.purgeSeq + 1;
    s.purges.push({
      docId: r,
      rev: o,
      purgeSeq: u
    });
    if (s.purges.length > self.purged_infos_limit) s.purges.splice(0, s.purges.length - self.purged_infos_limit);
    s.purgeSeq = u;
    return s;
  })).catch((function(s) {
    if (404 !== s.status) throw s;
    return {
      _id: "_local/purges",
      purges: [ {
        docId: r,
        rev: o,
        purgeSeq: 0
      } ],
      purgeSeq: 0
    };
  })).then((function(r) {
    return s.put(r);
  }));
}

function attachmentNameError(s) {
  if ("_" === s.charAt(0)) return s + " is not a valid attachment name, attachment names cannot start with '_'"; else return false;
}

var AbstractPouchDB = class extends import_events2.default {
  _setup() {
    this.post = adapterFun("post", (function(s, r, o) {
      if ("function" == typeof r) {
        o = r;
        r = {};
      }
      if ("object" != typeof s || Array.isArray(s)) return o(createError(NOT_AN_OBJECT));
      this.bulkDocs({
        docs: [ s ]
      }, r, yankError(o, s._id));
    })).bind(this);
    this.put = adapterFun("put", (function(s, r, o) {
      if ("function" == typeof r) {
        o = r;
        r = {};
      }
      if ("object" != typeof s || Array.isArray(s)) return o(createError(NOT_AN_OBJECT));
      invalidIdError(s._id);
      if (isLocalId(s._id) && "function" == typeof this._putLocal) if (s._deleted) return this._removeLocal(s, o); else return this._putLocal(s, o);
      const putDoc = o => {
        if ("function" == typeof this._put && false !== r.new_edits) this._put(s, r, o); else this.bulkDocs({
          docs: [ s ]
        }, r, yankError(o, s._id));
      };
      if (r.force && s._rev) {
        (function transformForceOptionToNewEditsOption() {
          var o = s._rev.split("-"), u = o[1], g = parseInt(o[0], 10) + 1, _ = rev();
          s._revisions = {
            start: g,
            ids: [ _, u ]
          };
          s._rev = g + "-" + _;
          r.new_edits = false;
        })();
        putDoc((function(r) {
          var u = r ? null : {
            ok: true,
            id: s._id,
            rev: s._rev
          };
          o(r, u);
        }));
      } else putDoc(o);
    })).bind(this);
    this.putAttachment = adapterFun("putAttachment", (function(s, r, o, u, g) {
      var _ = this;
      if ("function" == typeof g) {
        g = u;
        u = o;
        o = null;
      }
      if ("undefined" == typeof g) {
        g = u;
        u = o;
        o = null;
      }
      if (!g) guardedConsole("warn", "Attachment", r, "on document", s, "is missing content_type");
      function createAttachment(s) {
        var o = "_rev" in s ? parseInt(s._rev, 10) : 0;
        s._attachments = s._attachments || {};
        s._attachments[r] = {
          content_type: g,
          data: u,
          revpos: ++o
        };
        return _.put(s);
      }
      return _.get(s).then((function(s) {
        if (s._rev !== o) throw createError(REV_CONFLICT);
        return createAttachment(s);
      }), (function(r) {
        if (r.reason === MISSING_DOC.message) return createAttachment({
          _id: s
        }); else throw r;
      }));
    })).bind(this);
    this.removeAttachment = adapterFun("removeAttachment", (function(s, r, o, u) {
      this.get(s, ((s, g) => {
        if (!s) if (g._rev === o) {
          if (!g._attachments) return u();
          delete g._attachments[r];
          if (0 === Object.keys(g._attachments).length) delete g._attachments;
          this.put(g, u);
        } else u(createError(REV_CONFLICT)); else u(s);
      }));
    })).bind(this);
    this.remove = adapterFun("remove", (function(s, r, o, u) {
      var g;
      if ("string" == typeof r) {
        g = {
          _id: s,
          _rev: r
        };
        if ("function" == typeof o) {
          u = o;
          o = {};
        }
      } else {
        g = s;
        if ("function" == typeof r) {
          u = r;
          o = {};
        } else {
          u = o;
          o = r;
        }
      }
      (o = o || {}).was_delete = true;
      var _ = {
        _id: g._id,
        _rev: g._rev || o.rev,
        _deleted: true
      };
      if (isLocalId(_._id) && "function" == typeof this._removeLocal) return this._removeLocal(g, u);
      this.bulkDocs({
        docs: [ _ ]
      }, o, yankError(u, _._id));
    })).bind(this);
    this.revsDiff = adapterFun("revsDiff", (function(s, r, o) {
      if ("function" == typeof r) {
        o = r;
        r = {};
      }
      var u = Object.keys(s);
      if (!u.length) return o(null, {});
      var g = 0, _ = new ExportedMap;
      function addToMissing(s, r) {
        if (!_.has(s)) _.set(s, {
          missing: []
        });
        _.get(s).missing.push(r);
      }
      u.map((function(r) {
        this._getRevisionTree(r, (function(m, b) {
          if (m && 404 === m.status && "missing" === m.message) _.set(r, {
            missing: s[r]
          }); else if (m) return o(m); else (function processDoc(r, o) {
            var u = s[r].slice(0);
            traverseRevTree(o, (function(s, o, g, _, m) {
              var b = o + "-" + g, E = u.indexOf(b);
              if (-1 !== E) {
                u.splice(E, 1);
                if ("available" !== m.status) addToMissing(r, b);
              }
            }));
            u.forEach((function(s) {
              addToMissing(r, s);
            }));
          })(r, b);
          if (++g === u.length) {
            var E = {};
            _.forEach((function(s, r) {
              E[r] = s;
            }));
            return o(null, E);
          }
        }));
      }), this);
    })).bind(this);
    this.bulkGet = adapterFun("bulkGet", (function(s, r) {
      bulkGet(this, s, r);
    })).bind(this);
    this.compactDocument = adapterFun("compactDocument", (function(s, r, o) {
      this._getRevisionTree(s, ((u, g) => {
        if (u) return o(u);
        var _ = computeHeight(g), m = [], b = [];
        Object.keys(_).forEach((function(s) {
          if (_[s] > r) m.push(s);
        }));
        traverseRevTree(g, (function(s, r, o, u, g) {
          var _ = r + "-" + o;
          if ("available" === g.status && -1 !== m.indexOf(_)) b.push(_);
        }));
        this._doCompaction(s, b, o);
      }));
    })).bind(this);
    this.compact = adapterFun("compact", (function(s, r) {
      if ("function" == typeof s) {
        r = s;
        s = {};
      }
      s = s || {};
      this._compactionQueue = this._compactionQueue || [];
      this._compactionQueue.push({
        opts: s,
        callback: r
      });
      if (1 === this._compactionQueue.length) doNextCompaction(this);
    })).bind(this);
    this.get = adapterFun("get", (function(s, r, o) {
      if ("function" == typeof r) {
        o = r;
        r = {};
      }
      if ("string" != typeof s) return o(createError(INVALID_ID));
      if (isLocalId(s) && "function" == typeof this._getLocal) return this._getLocal(s, o);
      var u = [];
      const finishOpenRevs = () => {
        var g = [], _ = u.length;
        if (!_) return o(null, g);
        u.forEach((u => {
          this.get(s, {
            rev: u,
            revs: r.revs,
            latest: r.latest,
            attachments: r.attachments,
            binary: r.binary
          }, (function(s, r) {
            if (!s) {
              for (var m, b = 0, E = g.length; b < E; b++) if (g[b].ok && g[b].ok._rev === r._rev) {
                m = true;
                break;
              }
              if (!m) g.push({
                ok: r
              });
            } else g.push({
              missing: u
            });
            if (! --_) o(null, g);
          }));
        }));
      };
      if (!r.open_revs) return this._get(s, r, ((u, g) => {
        if (u) {
          u.docId = s;
          return o(u);
        }
        var _ = g.doc, m = g.metadata, b = g.ctx;
        if (r.conflicts) {
          var E = collectConflicts(m);
          if (E.length) _._conflicts = E;
        }
        if (isDeleted(m, _._rev)) _._deleted = true;
        if (r.revs || r.revs_info) {
          for (var w = _._rev.split("-"), S = parseInt(w[0], 10), L = w[1], O = rootToLeaf(m.rev_tree), D = null, C = 0; C < O.length; C++) {
            var k = O[C], T = k.ids.map((function(s) {
              return s.id;
            })).indexOf(L);
            if (T === S - 1 || !D && -1 !== T) D = k;
          }
          if (!D) {
            (u = new Error("invalid rev tree")).docId = s;
            return o(u);
          }
          var A = D.ids.map((function(s) {
            return s.id;
          })).indexOf(_._rev.split("-")[1]) + 1, R = D.ids.length - A;
          D.ids.splice(A, R);
          D.ids.reverse();
          if (r.revs) _._revisions = {
            start: D.pos + D.ids.length - 1,
            ids: D.ids.map((function(s) {
              return s.id;
            }))
          };
          if (r.revs_info) {
            var I = D.pos + D.ids.length;
            _._revs_info = D.ids.map((function(s) {
              return {
                rev: --I + "-" + s.id,
                status: s.opts.status
              };
            }));
          }
        }
        if (r.attachments && _._attachments) {
          var x = _._attachments, P = Object.keys(x).length;
          if (0 === P) return o(null, _);
          Object.keys(x).forEach((s => {
            this._getAttachment(_._id, s, x[s], {
              rev: _._rev,
              binary: r.binary,
              ctx: b
            }, (function(r, u) {
              var g = _._attachments[s];
              g.data = u;
              delete g.stub;
              delete g.length;
              if (! --P) o(null, _);
            }));
          }));
        } else {
          if (_._attachments) for (var N in _._attachments) if (Object.prototype.hasOwnProperty.call(_._attachments, N)) _._attachments[N].stub = true;
          o(null, _);
        }
      })); else if ("all" === r.open_revs) this._getRevisionTree(s, (function(s, r) {
        if (s) return o(s);
        u = collectLeaves(r).map((function(s) {
          return s.rev;
        }));
        finishOpenRevs();
      })); else if (Array.isArray(r.open_revs)) {
        u = r.open_revs;
        for (var g = 0; g < u.length; g++) {
          var _ = u[g];
          if (!("string" == typeof _ && /^\d+-/.test(_))) return o(createError(INVALID_REV));
        }
        finishOpenRevs();
      } else return o(createError(UNKNOWN_ERROR, "function_clause"));
    })).bind(this);
    this.getAttachment = adapterFun("getAttachment", (function(s, r, o, u) {
      if (o instanceof Function) {
        u = o;
        o = {};
      }
      this._get(s, o, ((g, _) => {
        if (g) return u(g);
        if (_.doc._attachments && _.doc._attachments[r]) {
          o.ctx = _.ctx;
          o.binary = true;
          this._getAttachment(s, r, _.doc._attachments[r], o, u);
        } else return u(createError(MISSING_DOC));
      }));
    })).bind(this);
    this.allDocs = adapterFun("allDocs", (function(s, r) {
      if ("function" == typeof s) {
        r = s;
        s = {};
      }
      s.skip = "undefined" != typeof s.skip ? s.skip : 0;
      if (s.start_key) s.startkey = s.start_key;
      if (s.end_key) s.endkey = s.end_key;
      if ("keys" in s) {
        if (!Array.isArray(s.keys)) return r(new TypeError("options.keys must be an array"));
        var o = [ "startkey", "endkey", "key" ].filter((function(r) {
          return r in s;
        }))[0];
        if (o) {
          r(createError(QUERY_PARSE_ERROR, "Query parameter `" + o + "` is not compatible with multi-get"));
          return;
        }
        if (!isRemote(this)) {
          allDocsKeysParse(s);
          if (0 === s.keys.length) return this._allDocs({
            limit: 0
          }, r);
        }
      }
      return this._allDocs(s, r);
    })).bind(this);
    this.close = adapterFun("close", (function(s) {
      this._closed = true;
      this.emit("closed");
      return this._close(s);
    })).bind(this);
    this.info = adapterFun("info", (function(s) {
      this._info(((r, o) => {
        if (r) return s(r);
        o.db_name = o.db_name || this.name;
        o.auto_compaction = !!(this.auto_compaction && !isRemote(this));
        o.adapter = this.adapter;
        s(null, o);
      }));
    })).bind(this);
    this.id = adapterFun("id", (function(s) {
      return this._id(s);
    })).bind(this);
    this.bulkDocs = adapterFun("bulkDocs", (function(s, r, o) {
      if ("function" == typeof r) {
        o = r;
        r = {};
      }
      r = r || {};
      if (Array.isArray(s)) s = {
        docs: s
      };
      if (!s || !s.docs || !Array.isArray(s.docs)) return o(createError(MISSING_BULK_DOCS));
      for (var u = 0; u < s.docs.length; ++u) if ("object" != typeof s.docs[u] || Array.isArray(s.docs[u])) return o(createError(NOT_AN_OBJECT));
      var g;
      s.docs.forEach((function(s) {
        if (s._attachments) Object.keys(s._attachments).forEach((function(r) {
          g = g || attachmentNameError(r);
          if (!s._attachments[r].content_type) guardedConsole("warn", "Attachment", r, "on document", s._id, "is missing content_type");
        }));
      }));
      if (g) return o(createError(BAD_REQUEST, g));
      if (!("new_edits" in r)) if ("new_edits" in s) r.new_edits = s.new_edits; else r.new_edits = true;
      var _ = this;
      if (!r.new_edits && !isRemote(_)) s.docs.sort(compareByIdThenRev);
      cleanDocs(s.docs);
      var m = s.docs.map((function(s) {
        return s._id;
      }));
      this._bulkDocs(s, r, (function(s, u) {
        if (s) return o(s);
        if (!r.new_edits) u = u.filter((function(s) {
          return s.error;
        }));
        if (!isRemote(_)) for (var g = 0, b = u.length; g < b; g++) u[g].id = u[g].id || m[g];
        o(null, u);
      }));
    })).bind(this);
    this.registerDependentDatabase = adapterFun("registerDependentDatabase", (function(s, r) {
      var o = clone(this.__opts);
      if (this.__opts.view_adapter) o.adapter = this.__opts.view_adapter;
      var u = new this.constructor(s, o);
      upsert(this, "_local/_pouch_dependentDbs", (function diffFun(r) {
        r.dependentDbs = r.dependentDbs || {};
        if (r.dependentDbs[s]) return false;
        r.dependentDbs[s] = true;
        return r;
      })).then((function() {
        r(null, {
          db: u
        });
      })).catch(r);
    })).bind(this);
    this.destroy = adapterFun("destroy", (function(s, r) {
      if ("function" == typeof s) {
        r = s;
        s = {};
      }
      var o = "use_prefix" in this ? this.use_prefix : true;
      const destroyDb = () => {
        this._destroy(s, ((s, o) => {
          if (s) return r(s);
          this._destroyed = true;
          this.emit("destroyed");
          r(null, o || {
            ok: true
          });
        }));
      };
      if (isRemote(this)) return destroyDb();
      this.get("_local/_pouch_dependentDbs", ((s, u) => {
        if (s) if (404 !== s.status) return r(s); else return destroyDb();
        var g = u.dependentDbs, _ = this.constructor, m = Object.keys(g).map((s => {
          var r = o ? s.replace(new RegExp("^" + _.prefix), "") : s;
          return new _(r, this.__opts).destroy();
        }));
        Promise.all(m).then(destroyDb, r);
      }));
    })).bind(this);
  }
  _compact(s, r) {
    var o, u = {
      return_docs: false,
      last_seq: s.last_seq || 0
    }, g = [], _ = 0;
    const onChange = s => {
      this.activeTasks.update(o, {
        completed_items: ++_
      });
      g.push(this.compactDocument(s.id, 0));
    }, onError = s => {
      this.activeTasks.remove(o, s);
      r(s);
    }, onComplete = s => {
      var u = s.last_seq;
      Promise.all(g).then((() => upsert(this, "_local/compaction", (s => {
        if (!s.last_seq || s.last_seq < u) {
          s.last_seq = u;
          return s;
        }
        return false;
      })))).then((() => {
        this.activeTasks.remove(o);
        r(null, {
          ok: true
        });
      })).catch(onError);
    };
    this.info().then((s => {
      o = this.activeTasks.add({
        name: "database_compaction",
        total_items: s.update_seq - u.last_seq
      });
      this.changes(u).on("change", onChange).on("complete", onComplete).on("error", onError);
    }));
  }
  changes(s, r) {
    if ("function" == typeof s) {
      r = s;
      s = {};
    }
    (s = s || {}).return_docs = "return_docs" in s ? s.return_docs : !s.live;
    return new Changes2(this, s, r);
  }
  type() {
    return "function" == typeof this._type ? this._type() : this.adapter;
  }
};

AbstractPouchDB.prototype.purge = adapterFun("_purge", (function(s, r, o) {
  if ("undefined" == typeof this._purge) return o(createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter."));
  var u = this;
  u._getRevisionTree(s, ((g, _) => {
    if (g) return o(g);
    if (!_) return o(createError(MISSING_DOC));
    let m;
    try {
      m = findPathToLeaf(_, r);
    } catch (s) {
      return o(s.message || s);
    }
    u._purge(s, m, ((g, _) => {
      if (g) return o(g); else appendPurgeSeq(u, s, r).then((function() {
        return o(null, _);
      }));
    }));
  }));
}));

var TaskQueue = class {
  constructor() {
    this.isReady = false;
    this.failed = false;
    this.queue = [];
  }
  execute() {
    var s;
    if (this.failed) for (;s = this.queue.shift(); ) s(this.failed); else for (;s = this.queue.shift(); ) s();
  }
  fail(s) {
    this.failed = s;
    this.execute();
  }
  ready(s) {
    this.isReady = true;
    this.db = s;
    this.execute();
  }
  addTask(s) {
    this.queue.push(s);
    if (this.failed) this.execute();
  }
};

function parseAdapter(s, r) {
  var o = s.match(/([a-z-]*):\/\/(.*)/);
  if (o) return {
    name: /https?/.test(o[1]) ? o[1] + "://" + o[2] : o[2],
    adapter: o[1]
  };
  var u = PouchDB.adapters, g = PouchDB.preferredAdapters, _ = PouchDB.prefix, m = r.adapter;
  if (!m) for (var b = 0; b < g.length && "idb" === (m = g[b]) && "websql" in u && hasLocalStorage() && localStorage["_pouch__websqldb_" + _ + s]; ++b) guardedConsole("log", 'PouchDB is downgrading "' + s + '" to WebSQL to avoid data loss, because it was already opened with WebSQL.');
  var E = u[m];
  return {
    name: (E && "use_prefix" in E ? E.use_prefix : true) ? _ + s : s,
    adapter: m
  };
}

function inherits(s, r) {
  s.prototype = Object.create(r.prototype, {
    constructor: {
      value: s
    }
  });
}

function createClass(s, r) {
  let klass = function(...s) {
    if (!(this instanceof klass)) return new klass(...s);
    r.apply(this, s);
  };
  inherits(klass, s);
  return klass;
}

function prepareForDestruction(s) {
  function onDestroyed(r) {
    s.removeListener("closed", onClosed);
    if (!r) s.constructor.emit("destroyed", s.name);
  }
  function onClosed() {
    s.removeListener("destroyed", onDestroyed);
    s.constructor.emit("unref", s);
  }
  s.once("destroyed", onDestroyed);
  s.once("closed", onClosed);
  s.constructor.emit("ref", s);
}

var PouchInternal = class extends AbstractPouchDB {
  constructor(s, r) {
    super();
    this._setup(s, r);
  }
  _setup(s, r) {
    super._setup();
    r = r || {};
    if (s && "object" == typeof s) {
      s = (r = s).name;
      delete r.name;
    }
    if (void 0 === r.deterministic_revs) r.deterministic_revs = true;
    this.__opts = r = clone(r);
    this.auto_compaction = r.auto_compaction;
    this.purged_infos_limit = r.purged_infos_limit || 1e3;
    this.prefix = PouchDB.prefix;
    if ("string" != typeof s) throw new Error("Missing/invalid DB name");
    var o = parseAdapter((r.prefix || "") + s, r);
    r.name = o.name;
    r.adapter = r.adapter || o.adapter;
    this.name = s;
    this._adapter = r.adapter;
    PouchDB.emit("debug", [ "adapter", "Picked adapter: ", r.adapter ]);
    if (!PouchDB.adapters[r.adapter] || !PouchDB.adapters[r.adapter].valid()) throw new Error("Invalid Adapter: " + r.adapter);
    if (r.view_adapter) if (!PouchDB.adapters[r.view_adapter] || !PouchDB.adapters[r.view_adapter].valid()) throw new Error("Invalid View Adapter: " + r.view_adapter);
    this.taskqueue = new TaskQueue;
    this.adapter = r.adapter;
    PouchDB.adapters[r.adapter].call(this, r, (s => {
      if (s) return this.taskqueue.fail(s);
      prepareForDestruction(this);
      this.emit("created", this);
      PouchDB.emit("created", this.name);
      this.taskqueue.ready(this);
    }));
  }
}, PouchDB = createClass(PouchInternal, (function(s, r) {
  PouchInternal.prototype._setup.call(this, s, r);
})), ActiveTasks = class {
  constructor() {
    this.tasks = {};
  }
  list() {
    return Object.values(this.tasks);
  }
  add(s) {
    const r = v4_default();
    this.tasks[r] = {
      id: r,
      name: s.name,
      total_items: s.total_items,
      created_at: (new Date).toJSON()
    };
    return r;
  }
  get(s) {
    return this.tasks[s];
  }
  remove(s, r) {
    delete this.tasks[s];
    return this.tasks;
  }
  update(s, r) {
    const o = this.tasks[s];
    if ("undefined" != typeof o) {
      const u = {
        id: o.id,
        name: o.name,
        created_at: o.created_at,
        total_items: r.total_items || o.total_items,
        completed_items: r.completed_items || o.completed_items,
        updated_at: (new Date).toJSON()
      };
      this.tasks[s] = u;
    }
    return this.tasks;
  }
};

PouchDB.adapters = {};

PouchDB.preferredAdapters = [];

PouchDB.prefix = "_pouch_";

var eventEmitter = new import_events2.default;

function setUpEventEmitter(s) {
  Object.keys(import_events2.default.prototype).forEach((function(r) {
    if ("function" == typeof import_events2.default.prototype[r]) s[r] = eventEmitter[r].bind(eventEmitter);
  }));
  var r = s._destructionListeners = new ExportedMap;
  s.on("ref", (function onConstructorRef(s) {
    if (!r.has(s.name)) r.set(s.name, []);
    r.get(s.name).push(s);
  }));
  s.on("unref", (function onConstructorUnref(s) {
    if (r.has(s.name)) {
      var o = r.get(s.name), u = o.indexOf(s);
      if (!(u < 0)) {
        o.splice(u, 1);
        if (o.length > 1) r.set(s.name, o); else r.delete(s.name);
      }
    }
  }));
  s.on("destroyed", (function onConstructorDestroyed(s) {
    if (r.has(s)) {
      var o = r.get(s);
      r.delete(s);
      o.forEach((function(s) {
        s.emit("destroyed", true);
      }));
    }
  }));
}

setUpEventEmitter(PouchDB);

PouchDB.adapter = function(s, r, o) {
  if (r.valid()) {
    PouchDB.adapters[s] = r;
    if (o) PouchDB.preferredAdapters.push(s);
  }
};

PouchDB.plugin = function(s) {
  if ("function" == typeof s) s(PouchDB); else if ("object" != typeof s || 0 === Object.keys(s).length) throw new Error('Invalid plugin: got "' + s + '", expected an object or a function'); else Object.keys(s).forEach((function(r) {
    PouchDB.prototype[r] = s[r];
  }));
  if (this.__defaults) PouchDB.__defaults = assign$2({}, this.__defaults);
  return PouchDB;
};

PouchDB.defaults = function(s) {
  let r = createClass(PouchDB, (function(s, o) {
    o = o || {};
    if (s && "object" == typeof s) {
      s = (o = s).name;
      delete o.name;
    }
    o = assign$2({}, r.__defaults, o);
    PouchDB.call(this, s, o);
  }));
  r.preferredAdapters = PouchDB.preferredAdapters.slice();
  Object.keys(PouchDB).forEach((function(s) {
    if (!(s in r)) r[s] = PouchDB[s];
  }));
  r.__defaults = assign$2({}, this.__defaults, s);
  return r;
};

PouchDB.fetch = function(s, r) {
  return f2(s, r);
};

PouchDB.prototype.activeTasks = PouchDB.activeTasks = new ActiveTasks;

var version = "8.0.1";

PouchDB.plugin(index_browser_es_default);

PouchDB.version = version;

var index_es_default = PouchDB;

function toObject(s) {
  return s.reduce((function(s, r) {
    s[r] = true;
    return s;
  }), {});
}

var reservedWords = toObject([ "_id", "_rev", "_access", "_attachments", "_deleted", "_revisions", "_revs_info", "_conflicts", "_deleted_conflicts", "_local_seq", "_rev_tree", "_replication_id", "_replication_state", "_replication_state_time", "_replication_state_reason", "_replication_stats", "_removed" ]), dataWords = toObject([ "_access", "_attachments", "_replication_id", "_replication_state", "_replication_state_time", "_replication_state_reason", "_replication_stats" ]);

function parseRevisionInfo(s) {
  if (!/^\d+-/.test(s)) return createError(INVALID_REV);
  var r = s.indexOf("-"), o = s.substring(0, r), u = s.substring(r + 1);
  return {
    prefix: parseInt(o, 10),
    id: u
  };
}

function makeRevTreeFromRevisions(s, r) {
  for (var o = s.start - s.ids.length + 1, u = s.ids, g = [ u[0], r, [] ], _ = 1, m = u.length; _ < m; _++) g = [ u[_], {
    status: "missing"
  }, [ g ] ];
  return [ {
    pos: o,
    ids: g
  } ];
}

function parseDoc(s, r, o) {
  if (!o) o = {
    deterministic_revs: true
  };
  var u, g, _, m = {
    status: "available"
  };
  if (s._deleted) m.deleted = true;
  if (r) {
    if (!s._id) s._id = uuid();
    g = rev(s, o.deterministic_revs);
    if (s._rev) {
      if ((_ = parseRevisionInfo(s._rev)).error) return _;
      s._rev_tree = [ {
        pos: _.prefix,
        ids: [ _.id, {
          status: "missing"
        }, [ [ g, m, [] ] ] ]
      } ];
      u = _.prefix + 1;
    } else {
      s._rev_tree = [ {
        pos: 1,
        ids: [ g, m, [] ]
      } ];
      u = 1;
    }
  } else {
    if (s._revisions) {
      s._rev_tree = makeRevTreeFromRevisions(s._revisions, m);
      u = s._revisions.start;
      g = s._revisions.ids[0];
    }
    if (!s._rev_tree) {
      if ((_ = parseRevisionInfo(s._rev)).error) return _;
      u = _.prefix;
      g = _.id;
      s._rev_tree = [ {
        pos: u,
        ids: [ g, m, [] ]
      } ];
    }
  }
  invalidIdError(s._id);
  s._rev = u + "-" + g;
  var b = {
    metadata: {},
    data: {}
  };
  for (var E in s) if (Object.prototype.hasOwnProperty.call(s, E)) {
    var w = "_" === E[0];
    if (w && !reservedWords[E]) {
      var S = createError(DOC_VALIDATION, E);
      S.message = DOC_VALIDATION.message + ": " + E;
      throw S;
    } else if (w && !dataWords[E]) b.metadata[E.slice(1)] = s[E]; else b.data[E] = s[E];
  }
  return b;
}

function parseBase64(s) {
  try {
    return thisAtob(s);
  } catch (s) {
    return {
      error: createError(BAD_ARG, "Attachment is not a valid base64 string")
    };
  }
}

function preprocessString(s, r, o) {
  var u = parseBase64(s.data);
  if (u.error) return o(u.error);
  s.length = u.length;
  if ("blob" === r) s.data = binStringToBluffer(u, s.content_type); else if ("base64" === r) s.data = thisBtoa(u); else s.data = u;
  binaryMd5(u, (function(r) {
    s.digest = "md5-" + r;
    o();
  }));
}

function preprocessBlob(s, r, o) {
  binaryMd5(s.data, (function(u) {
    s.digest = "md5-" + u;
    s.length = s.data.size || s.data.length || 0;
    if ("binary" === r) blobToBinaryString(s.data, (function(r) {
      s.data = r;
      o();
    })); else if ("base64" === r) blobToBase64(s.data, (function(r) {
      s.data = r;
      o();
    })); else o();
  }));
}

function preprocessAttachment(s, r, o) {
  if (s.stub) return o();
  if ("string" == typeof s.data) preprocessString(s, r, o); else preprocessBlob(s, r, o);
}

function preprocessAttachments(s, r, o) {
  if (!s.length) return o();
  var u, g = 0;
  s.forEach((function(s) {
    var o = s.data && s.data._attachments ? Object.keys(s.data._attachments) : [], g = 0;
    if (!o.length) return done();
    function processedAttachment(s) {
      u = s;
      if (++g === o.length) done();
    }
    for (var _ in s.data._attachments) if (Object.prototype.hasOwnProperty.call(s.data._attachments, _)) preprocessAttachment(s.data._attachments[_], r, processedAttachment);
  }));
  function done() {
    g++;
    if (s.length === g) if (u) o(u); else o();
  }
}

function updateDoc(s, r, o, u, g, _, m, b) {
  if (revExists(r.rev_tree, o.metadata.rev) && !b) {
    u[g] = o;
    return _();
  }
  var E = r.winningRev || winningRev(r), w = "deleted" in r ? r.deleted : isDeleted(r, E), S = "deleted" in o.metadata ? o.metadata.deleted : isDeleted(o.metadata), L = /^1-/.test(o.metadata.rev);
  if (w && !S && b && L) {
    var O = o.data;
    O._rev = E;
    O._id = o.metadata.id;
    o = parseDoc(O, b);
  }
  var D = merge(r.rev_tree, o.metadata.rev_tree[0], s);
  if (b && (w && S && "new_leaf" !== D.conflicts || !w && "new_leaf" !== D.conflicts || w && !S && "new_branch" === D.conflicts)) {
    var C = createError(REV_CONFLICT);
    u[g] = C;
    return _();
  }
  var k = o.metadata.rev;
  o.metadata.rev_tree = D.tree;
  o.stemmedRevs = D.stemmedRevs || [];
  if (r.rev_map) o.metadata.rev_map = r.rev_map;
  var T, A = winningRev(o.metadata), R = isDeleted(o.metadata, A), I = w === R ? 0 : w < R ? -1 : 1;
  if (k === A) T = R; else T = isDeleted(o.metadata, k);
  m(o, A, R, T, true, I, g, _);
}

function rootIsMissing(s) {
  return "missing" === s.metadata.rev_tree[0].ids[1].status;
}

function processDocs(s, r, o, u, g, _, m, b, E) {
  s = s || 1e3;
  var w = b.new_edits, S = new ExportedMap, L = 0, O = r.length;
  function checkAllDocsDone() {
    if (++L === O && E) E();
  }
  r.forEach((function(s, r) {
    if (!s._id || !isLocalId(s._id)) {
      var u = s.metadata.id;
      if (S.has(u)) {
        O--;
        S.get(u).push([ s, r ]);
      } else S.set(u, [ [ s, r ] ]);
    } else {
      var m = s._deleted ? "_removeLocal" : "_putLocal";
      o[m](s, {
        ctx: g
      }, (function(s, o) {
        _[r] = s || o;
        checkAllDocsDone();
      }));
    }
  }));
  S.forEach((function(r, o) {
    var g = 0;
    function docWritten() {
      if (++g < r.length) nextDoc(); else checkAllDocsDone();
    }
    function nextDoc() {
      var E = r[g], S = E[0], L = E[1];
      if (u.has(o)) updateDoc(s, u.get(o), S, _, L, docWritten, m, w); else {
        var O = merge([], S.metadata.rev_tree[0], s);
        S.metadata.rev_tree = O.tree;
        S.stemmedRevs = O.stemmedRevs || [];
        (function insertDoc(s, r, o) {
          var u = winningRev(s.metadata), g = isDeleted(s.metadata, u);
          if ("was_delete" in b && g) {
            _[r] = createError(MISSING_DOC, "deleted");
            return o();
          }
          if (w && rootIsMissing(s)) {
            var E = createError(REV_CONFLICT);
            _[r] = E;
            return o();
          }
          m(s, u, g, g, false, g ? 0 : 1, r, o);
        })(S, L, docWritten);
      }
    }
    nextDoc();
  }));
}

var import_vuvuzela = __toESM(require_vuvuzela());

function safeJsonParse(s) {
  try {
    return JSON.parse(s);
  } catch (r) {
    return import_vuvuzela.default.parse(s);
  }
}

function safeJsonStringify(s) {
  try {
    return JSON.stringify(s);
  } catch (r) {
    return import_vuvuzela.default.stringify(s);
  }
}

var ADAPTER_VERSION = 5, DOC_STORE = "document-store", BY_SEQ_STORE = "by-sequence", ATTACH_STORE = "attach-store", ATTACH_AND_SEQ_STORE = "attach-seq-store", META_STORE = "meta-store", LOCAL_STORE = "local-store", DETECT_BLOB_SUPPORT_STORE = "detect-blob-support";

function idbError(s) {
  return function(r) {
    var o = "unknown_error";
    if (r.target && r.target.error) o = r.target.error.name || r.target.error.message;
    s(createError(IDB_ERROR, o, r.type));
  };
}

function encodeMetadata(s, r, o) {
  return {
    data: safeJsonStringify(s),
    winningRev: r,
    deletedOrLocal: o ? "1" : "0",
    seq: s.seq,
    id: s.id
  };
}

function decodeMetadata(s) {
  if (!s) return null;
  var r = safeJsonParse(s.data);
  r.winningRev = s.winningRev;
  r.deleted = "1" === s.deletedOrLocal;
  r.seq = s.seq;
  return r;
}

function decodeDoc(s) {
  if (!s) return s;
  var r = s._doc_id_rev.lastIndexOf(":");
  s._id = s._doc_id_rev.substring(0, r - 1);
  s._rev = s._doc_id_rev.substring(r + 1);
  delete s._doc_id_rev;
  return s;
}

function readBlobData(s, r, o, u) {
  if (o) if (!s) u(createBlob2([ "" ], {
    type: r
  })); else if ("string" != typeof s) u(s); else u(b64ToBluffer(s, r)); else if (!s) u(""); else if ("string" != typeof s) readAsBinaryString(s, (function(s) {
    u(thisBtoa(s));
  })); else u(s);
}

function fetchAttachmentsIfNecessary(s, r, o, u) {
  var g = Object.keys(s._attachments || {});
  if (!g.length) return u && u();
  var _ = 0;
  function checkDone() {
    if (++_ === g.length && u) u();
  }
  g.forEach((function(u) {
    if (r.attachments && r.include_docs) (function fetchAttachment(s, r) {
      var u = s._attachments[r], g = u.digest;
      o.objectStore(ATTACH_STORE).get(g).onsuccess = function(s) {
        u.body = s.target.result.body;
        checkDone();
      };
    })(s, u); else {
      s._attachments[u].stub = true;
      checkDone();
    }
  }));
}

function postProcessAttachments(s, r) {
  return Promise.all(s.map((function(s) {
    if (s.doc && s.doc._attachments) {
      var o = Object.keys(s.doc._attachments);
      return Promise.all(o.map((function(o) {
        var u = s.doc._attachments[o];
        if ("body" in u) {
          var g = u.body, _ = u.content_type;
          return new Promise((function(m) {
            readBlobData(g, _, r, (function(r) {
              s.doc._attachments[o] = assign$2(pick(u, [ "digest", "content_type" ]), {
                data: r
              });
              m();
            }));
          }));
        }
      })));
    }
  })));
}

function compactRevs(s, r, o) {
  var u = [], g = o.objectStore(BY_SEQ_STORE), _ = o.objectStore(ATTACH_STORE), m = o.objectStore(ATTACH_AND_SEQ_STORE), b = s.length;
  function checkDone() {
    if (! --b) (function deleteOrphanedAttachments() {
      if (u.length) u.forEach((function(s) {
        m.index("digestSeq").count(IDBKeyRange.bound(s + "::", s + "::", false, false)).onsuccess = function(r) {
          if (!r.target.result) _.delete(s);
        };
      }));
    })();
  }
  s.forEach((function(s) {
    var o = g.index("_doc_id_rev"), _ = r + "::" + s;
    o.getKey(_).onsuccess = function(s) {
      var r = s.target.result;
      if ("number" != typeof r) return checkDone();
      g.delete(r);
      m.index("seq").openCursor(IDBKeyRange.only(r)).onsuccess = function(s) {
        var r = s.target.result;
        if (r) {
          var o = r.value.digestSeq.split("::")[0];
          u.push(o);
          m.delete(r.primaryKey);
          r.continue();
        } else checkDone();
      };
    };
  }));
}

function openTransactionSafely(s, r, o) {
  try {
    return {
      txn: s.transaction(r, o)
    };
  } catch (s) {
    return {
      error: s
    };
  }
}

var changesHandler$1 = new Changes;

function idbBulkDocs(s, r, o, u, g, _) {
  for (var m, b, E, w, S, L, O, D, C = r.docs, k = 0, T = C.length; k < T; k++) {
    var A = C[k];
    if (!A._id || !isLocalId(A._id)) if ((A = C[k] = parseDoc(A, o.new_edits, s)).error && !O) O = A;
  }
  if (O) return _(O);
  var R = false, I = 0, x = new Array(C.length), P = new ExportedMap, N = false, B = u._meta.blobSupport ? "blob" : "base64";
  preprocessAttachments(C, B, (function(r) {
    if (r) return _(r);
    (function startTransaction() {
      var r = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE, LOCAL_STORE, ATTACH_AND_SEQ_STORE, META_STORE ], "readwrite");
      if (r.error) return _(r.error);
      (m = r.txn).onabort = idbError(_);
      m.ontimeout = idbError(_);
      m.oncomplete = complete;
      b = m.objectStore(DOC_STORE);
      E = m.objectStore(BY_SEQ_STORE);
      w = m.objectStore(ATTACH_STORE);
      S = m.objectStore(ATTACH_AND_SEQ_STORE);
      (L = m.objectStore(META_STORE)).get(META_STORE).onsuccess = function(s) {
        D = s.target.result;
        updateDocCountIfReady();
      };
      (function verifyAttachments(s) {
        var r = [];
        C.forEach((function(s) {
          if (s.data && s.data._attachments) Object.keys(s.data._attachments).forEach((function(o) {
            var u = s.data._attachments[o];
            if (u.stub) r.push(u.digest);
          }));
        }));
        if (!r.length) return s();
        var o, u = 0;
        r.forEach((function(g) {
          (function verifyAttachment(s, r) {
            w.get(s).onsuccess = function(o) {
              if (!o.target.result) {
                var u = createError(MISSING_STUB, "unknown stub attachment with digest " + s);
                u.status = 412;
                r(u);
              } else r();
            };
          })(g, (function(g) {
            if (g && !o) o = g;
            (function checkDone() {
              if (++u === r.length) s(o);
            })();
          }));
        }));
      })((function(r) {
        if (r) {
          N = true;
          return _(r);
        }
        (function fetchExistingDocs() {
          if (C.length) for (var r = 0, g = 0, _ = C.length; g < _; g++) {
            var E = C[g];
            if (!E._id || !isLocalId(E._id)) b.get(E.metadata.id).onsuccess = readMetadata; else checkDone();
          }
          function checkDone() {
            if (++r === C.length) (function idbProcessDocs() {
              processDocs(s.revs_limit, C, u, P, m, x, writeDoc, o, onAllDocsProcessed);
            })();
          }
          function readMetadata(s) {
            var r = decodeMetadata(s.target.result);
            if (r) P.set(r.id, r);
            checkDone();
          }
        })();
      }));
    })();
  }));
  function onAllDocsProcessed() {
    R = true;
    updateDocCountIfReady();
  }
  function updateDocCountIfReady() {
    if (D && R) {
      D.docCount += I;
      L.put(D);
    }
  }
  function complete() {
    if (!N) {
      changesHandler$1.notify(u._meta.name);
      _(null, x);
    }
  }
  function writeDoc(s, r, o, u, g, _, m, b) {
    s.metadata.winningRev = r;
    s.metadata.deleted = o;
    var E = s.data;
    E._id = s.metadata.id;
    E._rev = s.metadata.rev;
    if (u) E._deleted = true;
    if (E._attachments && Object.keys(E._attachments).length) return function writeAttachments(s, r, o, u, g, _) {
      var m = s.data, b = 0, E = Object.keys(m._attachments);
      function collectResults() {
        if (b === E.length) finishDoc(s, r, o, u, g, _);
      }
      function attachmentSaved() {
        b++;
        collectResults();
      }
      E.forEach((function(o) {
        var u = s.data._attachments[o];
        if (!u.stub) {
          var g = u.data;
          delete u.data;
          u.revpos = parseInt(r, 10);
          (function saveAttachment(s, r, o) {
            w.count(s).onsuccess = function(u) {
              if (u.target.result) return o();
              var g = {
                digest: s,
                body: r
              };
              w.put(g).onsuccess = o;
            };
          })(u.digest, g, attachmentSaved);
        } else {
          b++;
          collectResults();
        }
      }));
    }(s, r, o, g, m, b);
    I += _;
    updateDocCountIfReady();
    finishDoc(s, r, o, g, m, b);
  }
  function finishDoc(s, r, o, g, _, w) {
    var L = s.data, O = s.metadata;
    L._doc_id_rev = O.id + "::" + O.rev;
    delete L._id;
    delete L._rev;
    function afterPutDoc(_) {
      var E = s.stemmedRevs || [];
      if (g && u.auto_compaction) E = E.concat(compactTree(s.metadata));
      if (E && E.length) compactRevs(E, s.metadata.id, m);
      O.seq = _.target.result;
      var w = encodeMetadata(O, r, o);
      b.put(w).onsuccess = afterPutMetadata;
    }
    function afterPutMetadata() {
      x[_] = {
        ok: true,
        id: O.id,
        rev: O.rev
      };
      P.set(s.metadata.id, s.metadata);
      (function insertAttachmentMappings(s, r, o) {
        var u = 0, g = Object.keys(s.data._attachments || {});
        if (!g.length) return o();
        function checkDone() {
          if (++u === g.length) o();
        }
        function add(o) {
          var u = s.data._attachments[o].digest, g = S.put({
            seq: r,
            digestSeq: u + "::" + r
          });
          g.onsuccess = checkDone;
          g.onerror = function(s) {
            s.preventDefault();
            s.stopPropagation();
            checkDone();
          };
        }
        for (var _ = 0; _ < g.length; _++) add(g[_]);
      })(s, O.seq, w);
    }
    var D = E.put(L);
    D.onsuccess = afterPutDoc;
    D.onerror = function afterPutDocError(s) {
      s.preventDefault();
      s.stopPropagation();
      E.index("_doc_id_rev").getKey(L._doc_id_rev).onsuccess = function(s) {
        E.put(L, s.target.result).onsuccess = afterPutDoc;
      };
    };
  }
}

function runBatchedCursor(s, r, o, u, g) {
  if (-1 === u) u = 1e3;
  var _, m, b;
  function onGetAll(s) {
    m = s.target.result;
    if (_) g(_, m, b);
  }
  function onGetAllKeys(s) {
    _ = s.target.result;
    if (m) g(_, m, b);
  }
  function onCursor(s) {
    var r = s.target.result;
    if (!r) return g();
    g([ r.key ], [ r.value ], r);
  }
  if ("function" == typeof s.getAll && "function" == typeof s.getAllKeys && u > 1 && !o) {
    b = {
      continue: function continuePseudoCursor() {
        if (!_.length) return g();
        var o, b = _[_.length - 1];
        if (r && r.upper) try {
          o = IDBKeyRange.bound(b, r.upper, true, r.upperOpen);
        } catch (s) {
          if ("DataError" === s.name && 0 === s.code) return g();
        } else o = IDBKeyRange.lowerBound(b, true);
        r = o;
        _ = null;
        m = null;
        s.getAll(r, u).onsuccess = onGetAll;
        s.getAllKeys(r, u).onsuccess = onGetAllKeys;
      }
    };
    s.getAll(r, u).onsuccess = onGetAll;
    s.getAllKeys(r, u).onsuccess = onGetAllKeys;
  } else if (o) s.openCursor(r, "prev").onsuccess = onCursor; else s.openCursor(r).onsuccess = onCursor;
}

function getAll(s, r, o) {
  if ("function" != typeof s.getAll) {
    var u = [];
    s.openCursor(r).onsuccess = function onCursor(s) {
      var r = s.target.result;
      if (r) {
        u.push(r.value);
        r.continue();
      } else o({
        target: {
          result: u
        }
      });
    };
  } else s.getAll(r).onsuccess = o;
}

function allDocsKeys(s, r, o) {
  var u = new Array(s.length), g = 0;
  s.forEach((function(_, m) {
    r.get(_).onsuccess = function(r) {
      if (r.target.result) u[m] = r.target.result; else u[m] = {
        key: _,
        error: "not_found"
      };
      if (++g === s.length) o(s, u, {});
    };
  }));
}

function createKeyRange(s, r, o, u, g) {
  try {
    if (s && r) if (g) return IDBKeyRange.bound(r, s, !o, false); else return IDBKeyRange.bound(s, r, false, !o); else if (s) if (g) return IDBKeyRange.upperBound(s); else return IDBKeyRange.lowerBound(s); else if (r) if (g) return IDBKeyRange.lowerBound(r, !o); else return IDBKeyRange.upperBound(r, !o); else if (u) return IDBKeyRange.only(u);
  } catch (s) {
    return {
      error: s
    };
  }
  return null;
}

function idbAllDocs(s, r, o) {
  var u, g, _ = "startkey" in s ? s.startkey : false, m = "endkey" in s ? s.endkey : false, b = "key" in s ? s.key : false, E = "keys" in s ? s.keys : false, w = s.skip || 0, S = "number" == typeof s.limit ? s.limit : -1, L = false !== s.inclusive_end;
  if (!E) if ((g = (u = createKeyRange(_, m, L, b, s.descending)) && u.error) && !("DataError" === g.name && 0 === g.code)) return o(createError(IDB_ERROR, g.name, g.message));
  var O = [ DOC_STORE, BY_SEQ_STORE, META_STORE ];
  if (s.attachments) O.push(ATTACH_STORE);
  var D = openTransactionSafely(r, O, "readonly");
  if (D.error) return o(D.error);
  var C = D.txn;
  C.oncomplete = function onTxnComplete() {
    if (s.attachments) postProcessAttachments(P, s.binary).then(onResultsReady); else onResultsReady();
  };
  C.onabort = idbError(o);
  var k, T, A = C.objectStore(DOC_STORE), R = C.objectStore(BY_SEQ_STORE), I = C.objectStore(META_STORE), x = R.index("_doc_id_rev"), P = [];
  I.get(META_STORE).onsuccess = function(s) {
    k = s.target.result.docCount;
  };
  if (s.update_seq) (function getMaxUpdateSeq(s, r) {
    s.openCursor(null, "prev").onsuccess = function onCursor(s) {
      var o = s.target.result, u = void 0;
      if (o && o.key) u = o.key;
      return r({
        target: {
          result: [ u ]
        }
      });
    };
  })(R, (function(s) {
    if (s.target.result && s.target.result.length > 0) T = s.target.result[0];
  }));
  function allDocsInner(r, o) {
    var u = {
      id: o.id,
      key: o.id,
      value: {
        rev: r
      }
    };
    if (o.deleted) {
      if (E) {
        P.push(u);
        u.value.deleted = true;
        u.doc = null;
      }
    } else if (w-- <= 0) {
      P.push(u);
      if (s.include_docs) (function fetchDocAsynchronously(r, o, u) {
        var g = r.id + "::" + u;
        x.get(g).onsuccess = function onGetDoc(u) {
          o.doc = decodeDoc(u.target.result) || {};
          if (s.conflicts) {
            var g = collectConflicts(r);
            if (g.length) o.doc._conflicts = g;
          }
          fetchAttachmentsIfNecessary(o.doc, s, C);
        };
      })(o, u, r);
    }
  }
  function processBatch(s) {
    for (var r = 0, o = s.length; r < o && P.length !== S; r++) {
      var u = s[r];
      if (!u.error || !E) {
        var g = decodeMetadata(u);
        allDocsInner(g.winningRev, g);
      } else P.push(u);
    }
  }
  function onBatch(s, r, o) {
    if (o) {
      processBatch(r);
      if (P.length < S) o.continue();
    }
  }
  function onResultsReady() {
    var r = {
      total_rows: k,
      offset: s.skip,
      rows: P
    };
    if (s.update_seq && void 0 !== T) r.update_seq = T;
    o(null, r);
  }
  if (!g && 0 !== S) {
    if (E) return allDocsKeys(s.keys, A, onBatch);
    if (-1 === S) return getAll(A, u, (function onGetAll(r) {
      var o = r.target.result;
      if (s.descending) o = o.reverse();
      processBatch(o);
    }));
    runBatchedCursor(A, u, s.descending, S + w, onBatch);
  }
}

function checkBlobSupport(s) {
  return new Promise((function(r) {
    var o = createBlob2([ "" ]), u = s.objectStore(DETECT_BLOB_SUPPORT_STORE).put(o, "key");
    u.onsuccess = function() {
      var s = navigator.userAgent.match(/Chrome\/(\d+)/), o = navigator.userAgent.match(/Edge\//);
      r(o || !s || parseInt(s[1], 10) >= 43);
    };
    u.onerror = s.onabort = function(s) {
      s.preventDefault();
      s.stopPropagation();
      r(false);
    };
  })).catch((function() {
    return false;
  }));
}

function countDocs(s, r) {
  s.objectStore(DOC_STORE).index("deletedOrLocal").count(IDBKeyRange.only("0")).onsuccess = function(s) {
    r(s.target.result);
  };
}

var running = false, queue = [];

function tryCode(s, r, o, u) {
  try {
    s(r, o);
  } catch (s) {
    u.emit("error", s);
  }
}

function applyNext() {
  if (!running && queue.length) {
    running = true;
    queue.shift()();
  }
}

function enqueueTask(s, r, o) {
  queue.push((function runAction() {
    s((function runCallback(s, u) {
      tryCode(r, s, u, o);
      running = false;
      (0, import_immediate.default)((function runNext() {
        applyNext(o);
      }));
    }));
  }));
  applyNext();
}

function changes(s, r, o, u) {
  if ((s = clone(s)).continuous) {
    var g = o + ":" + uuid();
    changesHandler$1.addListener(o, g, r, s);
    changesHandler$1.notify(o);
    return {
      cancel: function() {
        changesHandler$1.removeListener(o, g);
      }
    };
  }
  var _ = s.doc_ids && new ExportedSet(s.doc_ids);
  s.since = s.since || 0;
  var m = s.since, b = "limit" in s ? s.limit : -1;
  if (0 === b) b = 1;
  var E, w, S, L, O = [], D = 0, C = filterChange(s), k = new ExportedMap;
  function onGetMetadata(s, r, o, u) {
    if (o.seq !== r) return u();
    if (o.winningRev === s._rev) return u(o, s);
    var g = s._id + "::" + o.winningRev;
    L.get(g).onsuccess = function(s) {
      u(o, decodeDoc(s.target.result));
    };
  }
  function finish() {
    s.complete(null, {
      results: O,
      last_seq: m
    });
  }
  var T = [ DOC_STORE, BY_SEQ_STORE ];
  if (s.attachments) T.push(ATTACH_STORE);
  var A = openTransactionSafely(u, T, "readonly");
  if (A.error) return s.complete(A.error);
  (E = A.txn).onabort = idbError(s.complete);
  E.oncomplete = function onTxnComplete() {
    if (!s.continuous && s.attachments) postProcessAttachments(O).then(finish); else finish();
  };
  w = E.objectStore(BY_SEQ_STORE);
  S = E.objectStore(DOC_STORE);
  L = w.index("_doc_id_rev");
  runBatchedCursor(w, s.since && !s.descending ? IDBKeyRange.lowerBound(s.since, true) : null, s.descending, b, (function onBatch(r, o, u) {
    if (u && r.length) {
      var g = new Array(r.length), w = new Array(r.length), L = 0;
      o.forEach((function(o, m) {
        (function fetchWinningDocAndMetadata(s, r, o) {
          if (_ && !_.has(s._id)) return o();
          var u = k.get(s._id);
          if (u) return onGetMetadata(s, r, u, o);
          S.get(s._id).onsuccess = function(g) {
            u = decodeMetadata(g.target.result);
            k.set(s._id, u);
            onGetMetadata(s, r, u, o);
          };
        })(decodeDoc(o), r[m], (function(o, _) {
          w[m] = o;
          g[m] = _;
          if (++L === r.length) (function onBatchDone() {
            for (var r = [], o = 0, _ = g.length; o < _ && D !== b; o++) {
              var m = g[o];
              if (m) {
                var E = w[o];
                r.push(processMetadataAndWinningDoc(E, m));
              }
            }
            Promise.all(r).then((function(r) {
              for (var o = 0, u = r.length; o < u; o++) if (r[o]) s.onChange(r[o]);
            })).catch(s.complete);
            if (D !== b) u.continue();
          })();
        }));
      }));
    }
    function processMetadataAndWinningDoc(r, o) {
      var u = s.processChange(o, r, s);
      m = u.seq = r.seq;
      var g = C(u);
      if ("object" == typeof g) return Promise.reject(g);
      if (!g) return Promise.resolve();
      D++;
      if (s.return_docs) O.push(u);
      if (s.attachments && s.include_docs) return new Promise((function(r) {
        fetchAttachmentsIfNecessary(o, s, E, (function() {
          postProcessAttachments([ u ], s.binary).then((function() {
            r(u);
          }));
        }));
      })); else return Promise.resolve(u);
    }
  }));
}

var blobSupportPromise, cachedDBs = new ExportedMap, openReqList = new ExportedMap;

function IdbPouch(s, r) {
  var o = this;
  enqueueTask((function(r) {
    init(o, s, r);
  }), r, o.constructor);
}

function init(s, r, o) {
  var u = r.name, g = null, _ = null;
  s._meta = null;
  function enrichCallbackError(s) {
    return function(r, o) {
      if (r && r instanceof Error && !r.reason) if (_) r.reason = _;
      s(r, o);
    };
  }
  function addDeletedOrLocalIndex(s, r) {
    var o = s.objectStore(DOC_STORE);
    o.createIndex("deletedOrLocal", "deletedOrLocal", {
      unique: false
    });
    o.openCursor().onsuccess = function(s) {
      var u = s.target.result;
      if (u) {
        var g = u.value, _ = isDeleted(g);
        g.deletedOrLocal = _ ? "1" : "0";
        o.put(g);
        u.continue();
      } else r();
    };
  }
  function migrateLocalStore(s, r) {
    var o = s.objectStore(LOCAL_STORE), u = s.objectStore(DOC_STORE), g = s.objectStore(BY_SEQ_STORE);
    u.openCursor().onsuccess = function(s) {
      var _ = s.target.result;
      if (_) {
        var m = _.value, b = m.id, E = isLocalId(b), w = winningRev(m);
        if (E) {
          var S = b + "::" + w, L = b + "::", O = b + "::~", D = g.index("_doc_id_rev"), C = IDBKeyRange.bound(L, O, false, false), k = D.openCursor(C);
          k.onsuccess = function(s) {
            if (!(k = s.target.result)) {
              u.delete(_.primaryKey);
              _.continue();
            } else {
              var r = k.value;
              if (r._doc_id_rev === S) o.put(r);
              g.delete(k.primaryKey);
              k.continue();
            }
          };
        } else _.continue();
      } else if (r) r();
    };
  }
  function migrateAttsAndSeqs(s, r) {
    var o = s.objectStore(BY_SEQ_STORE), u = s.objectStore(ATTACH_STORE), g = s.objectStore(ATTACH_AND_SEQ_STORE);
    u.count().onsuccess = function(s) {
      if (!s.target.result) return r();
      o.openCursor().onsuccess = function(s) {
        var o = s.target.result;
        if (!o) return r();
        for (var u = o.value, _ = o.primaryKey, m = Object.keys(u._attachments || {}), b = {}, E = 0; E < m.length; E++) b[u._attachments[m[E]].digest] = true;
        var w = Object.keys(b);
        for (E = 0; E < w.length; E++) {
          var S = w[E];
          g.put({
            seq: _,
            digestSeq: S + "::" + _
          });
        }
        o.continue();
      };
    };
  }
  function migrateMetadata(s) {
    var r = s.objectStore(BY_SEQ_STORE), o = s.objectStore(DOC_STORE);
    o.openCursor().onsuccess = function(s) {
      var u = s.target.result;
      if (u) {
        var g = function decodeMetadataCompat(s) {
          if (!s.data) {
            s.deleted = "1" === s.deletedOrLocal;
            return s;
          }
          return decodeMetadata(s);
        }(u.value);
        g.winningRev = g.winningRev || winningRev(g);
        if (g.seq) return onGetMetadataSeq();
        (function fetchMetadataSeq() {
          var s = g.id + "::", o = g.id + "::", u = r.index("_doc_id_rev").openCursor(IDBKeyRange.bound(s, o)), _ = 0;
          u.onsuccess = function(s) {
            var r = s.target.result;
            if (!r) {
              g.seq = _;
              return onGetMetadataSeq();
            }
            var o = r.primaryKey;
            if (o > _) _ = o;
            r.continue();
          };
        })();
      }
      function onGetMetadataSeq() {
        var s = encodeMetadata(g, g.winningRev, g.deleted);
        o.put(s).onsuccess = function() {
          u.continue();
        };
      }
    };
  }
  s._remote = false;
  s.type = function() {
    return "idb";
  };
  s._id = toPromise((function(r) {
    r(null, s._meta.instanceId);
  }));
  s._bulkDocs = function idb_bulkDocs(o, u, _) {
    idbBulkDocs(r, o, u, s, g, enrichCallbackError(_));
  };
  s._get = function idb_get(s, r, o) {
    var u, _, m, b = r.ctx;
    if (!b) {
      var E = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE ], "readonly");
      if (E.error) return o(E.error);
      b = E.txn;
    }
    function finish() {
      o(m, {
        doc: u,
        metadata: _,
        ctx: b
      });
    }
    b.objectStore(DOC_STORE).get(s).onsuccess = function(s) {
      if (!(_ = decodeMetadata(s.target.result))) {
        m = createError(MISSING_DOC, "missing");
        return finish();
      }
      var o;
      if (!r.rev) {
        o = _.winningRev;
        if (isDeleted(_)) {
          m = createError(MISSING_DOC, "deleted");
          return finish();
        }
      } else o = r.latest ? latest(r.rev, _) : r.rev;
      var g = b.objectStore(BY_SEQ_STORE), E = _.id + "::" + o;
      g.index("_doc_id_rev").get(E).onsuccess = function(s) {
        if (u = s.target.result) u = decodeDoc(u);
        if (!u) {
          m = createError(MISSING_DOC, "missing");
          return finish();
        }
        finish();
      };
    };
  };
  s._getAttachment = function(s, r, o, u, _) {
    var m;
    if (u.ctx) m = u.ctx; else {
      var b = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE ], "readonly");
      if (b.error) return _(b.error);
      m = b.txn;
    }
    var E = o.digest, w = o.content_type;
    m.objectStore(ATTACH_STORE).get(E).onsuccess = function(s) {
      readBlobData(s.target.result.body, w, u.binary, (function(s) {
        _(null, s);
      }));
    };
  };
  s._info = function idb_info(r) {
    var o, u, _ = openTransactionSafely(g, [ META_STORE, BY_SEQ_STORE ], "readonly");
    if (_.error) return r(_.error);
    var m = _.txn;
    m.objectStore(META_STORE).get(META_STORE).onsuccess = function(s) {
      u = s.target.result.docCount;
    };
    m.objectStore(BY_SEQ_STORE).openCursor(null, "prev").onsuccess = function(s) {
      var r = s.target.result;
      o = r ? r.key : 0;
    };
    m.oncomplete = function() {
      r(null, {
        doc_count: u,
        update_seq: o,
        idb_attachment_format: s._meta.blobSupport ? "binary" : "base64"
      });
    };
  };
  s._allDocs = function idb_allDocs(s, r) {
    idbAllDocs(s, g, enrichCallbackError(r));
  };
  s._changes = function idbChanges2(r) {
    return changes(r, s, u, g);
  };
  s._close = function(s) {
    g.close();
    cachedDBs.delete(u);
    s();
  };
  s._getRevisionTree = function(s, r) {
    var o = openTransactionSafely(g, [ DOC_STORE ], "readonly");
    if (o.error) return r(o.error);
    o.txn.objectStore(DOC_STORE).get(s).onsuccess = function(s) {
      var o = decodeMetadata(s.target.result);
      if (!o) r(createError(MISSING_DOC)); else r(null, o.rev_tree);
    };
  };
  s._doCompaction = function(s, r, o) {
    var u = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE, ATTACH_AND_SEQ_STORE ], "readwrite");
    if (u.error) return o(u.error);
    var _ = u.txn;
    _.objectStore(DOC_STORE).get(s).onsuccess = function(o) {
      var u = decodeMetadata(o.target.result);
      traverseRevTree(u.rev_tree, (function(s, o, u, g, _) {
        var m = o + "-" + u;
        if (-1 !== r.indexOf(m)) _.status = "missing";
      }));
      compactRevs(r, s, _);
      var g = u.winningRev, m = u.deleted;
      _.objectStore(DOC_STORE).put(encodeMetadata(u, g, m));
    };
    _.onabort = idbError(o);
    _.oncomplete = function() {
      o();
    };
  };
  s._getLocal = function(s, r) {
    var o = openTransactionSafely(g, [ LOCAL_STORE ], "readonly");
    if (o.error) return r(o.error);
    var u = o.txn.objectStore(LOCAL_STORE).get(s);
    u.onerror = idbError(r);
    u.onsuccess = function(s) {
      var o = s.target.result;
      if (!o) r(createError(MISSING_DOC)); else {
        delete o["_doc_id_rev"];
        r(null, o);
      }
    };
  };
  s._putLocal = function(s, r, o) {
    if ("function" == typeof r) {
      o = r;
      r = {};
    }
    delete s._revisions;
    var u = s._rev, _ = s._id;
    if (!u) s._rev = "0-1"; else s._rev = "0-" + (parseInt(u.split("-")[1], 10) + 1);
    var m, b = r.ctx;
    if (!b) {
      var E = openTransactionSafely(g, [ LOCAL_STORE ], "readwrite");
      if (E.error) return o(E.error);
      (b = E.txn).onerror = idbError(o);
      b.oncomplete = function() {
        if (m) o(null, m);
      };
    }
    var w, S = b.objectStore(LOCAL_STORE);
    if (u) (w = S.get(_)).onsuccess = function(g) {
      var _ = g.target.result;
      if (!_ || _._rev !== u) o(createError(REV_CONFLICT)); else S.put(s).onsuccess = function() {
        m = {
          ok: true,
          id: s._id,
          rev: s._rev
        };
        if (r.ctx) o(null, m);
      };
    }; else {
      (w = S.add(s)).onerror = function(s) {
        o(createError(REV_CONFLICT));
        s.preventDefault();
        s.stopPropagation();
      };
      w.onsuccess = function() {
        m = {
          ok: true,
          id: s._id,
          rev: s._rev
        };
        if (r.ctx) o(null, m);
      };
    }
  };
  s._removeLocal = function(s, r, o) {
    if ("function" == typeof r) {
      o = r;
      r = {};
    }
    var u, _ = r.ctx;
    if (!_) {
      var m = openTransactionSafely(g, [ LOCAL_STORE ], "readwrite");
      if (m.error) return o(m.error);
      (_ = m.txn).oncomplete = function() {
        if (u) o(null, u);
      };
    }
    var b = s._id, E = _.objectStore(LOCAL_STORE), w = E.get(b);
    w.onerror = idbError(o);
    w.onsuccess = function(g) {
      var _ = g.target.result;
      if (!_ || _._rev !== s._rev) o(createError(MISSING_DOC)); else {
        E.delete(b);
        u = {
          ok: true,
          id: b,
          rev: "0-0"
        };
        if (r.ctx) o(null, u);
      }
    };
  };
  s._destroy = function(s, r) {
    changesHandler$1.removeAllListeners(u);
    var o = openReqList.get(u);
    if (o && o.result) {
      o.result.close();
      cachedDBs.delete(u);
    }
    var g = indexedDB.deleteDatabase(u);
    g.onsuccess = function() {
      openReqList.delete(u);
      if (hasLocalStorage() && u in localStorage) delete localStorage[u];
      r(null, {
        ok: true
      });
    };
    g.onerror = idbError(r);
  };
  var m = cachedDBs.get(u);
  if (m) {
    g = m.idb;
    s._meta = m.global;
    return (0, import_immediate.default)((function() {
      o(null, s);
    }));
  }
  var b = indexedDB.open(u, ADAPTER_VERSION);
  openReqList.set(u, b);
  b.onupgradeneeded = function(s) {
    var r = s.target.result;
    if (s.oldVersion < 1) return function createSchema(s) {
      var r = s.createObjectStore(DOC_STORE, {
        keyPath: "id"
      });
      s.createObjectStore(BY_SEQ_STORE, {
        autoIncrement: true
      }).createIndex("_doc_id_rev", "_doc_id_rev", {
        unique: true
      });
      s.createObjectStore(ATTACH_STORE, {
        keyPath: "digest"
      });
      s.createObjectStore(META_STORE, {
        keyPath: "id",
        autoIncrement: false
      });
      s.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
      r.createIndex("deletedOrLocal", "deletedOrLocal", {
        unique: false
      });
      s.createObjectStore(LOCAL_STORE, {
        keyPath: "_id"
      });
      var o = s.createObjectStore(ATTACH_AND_SEQ_STORE, {
        autoIncrement: true
      });
      o.createIndex("seq", "seq");
      o.createIndex("digestSeq", "digestSeq", {
        unique: true
      });
    }(r);
    var o = s.currentTarget.transaction;
    if (s.oldVersion < 3) (function createLocalStoreSchema(s) {
      s.createObjectStore(LOCAL_STORE, {
        keyPath: "_id"
      }).createIndex("_doc_id_rev", "_doc_id_rev", {
        unique: true
      });
    })(r);
    if (s.oldVersion < 4) (function addAttachAndSeqStore(s) {
      var r = s.createObjectStore(ATTACH_AND_SEQ_STORE, {
        autoIncrement: true
      });
      r.createIndex("seq", "seq");
      r.createIndex("digestSeq", "digestSeq", {
        unique: true
      });
    })(r);
    var u = [ addDeletedOrLocalIndex, migrateLocalStore, migrateAttsAndSeqs, migrateMetadata ], g = s.oldVersion;
    (function next() {
      var s = u[g - 1];
      g++;
      if (s) s(o, next);
    })();
  };
  b.onsuccess = function(r) {
    (g = r.target.result).onversionchange = function() {
      g.close();
      cachedDBs.delete(u);
    };
    g.onabort = function(s) {
      guardedConsole("error", "Database has a global failure", s.target.error);
      _ = s.target.error;
      g.close();
      cachedDBs.delete(u);
    };
    var m, b, E, w, S = g.transaction([ META_STORE, DETECT_BLOB_SUPPORT_STORE, DOC_STORE ], "readwrite"), L = false;
    function completeSetup() {
      if ("undefined" != typeof E && L) {
        s._meta = {
          name: u,
          instanceId: w,
          blobSupport: E
        };
        cachedDBs.set(u, {
          idb: g,
          global: s._meta
        });
        o(null, s);
      }
    }
    function storeMetaDocIfReady() {
      if ("undefined" != typeof b && "undefined" != typeof m) {
        var s = u + "_id";
        if (s in m) w = m[s]; else m[s] = w = uuid();
        m.docCount = b;
        S.objectStore(META_STORE).put(m);
      }
    }
    S.objectStore(META_STORE).get(META_STORE).onsuccess = function(s) {
      m = s.target.result || {
        id: META_STORE
      };
      storeMetaDocIfReady();
    };
    countDocs(S, (function(s) {
      b = s;
      storeMetaDocIfReady();
    }));
    if (!blobSupportPromise) blobSupportPromise = checkBlobSupport(S);
    blobSupportPromise.then((function(s) {
      E = s;
      completeSetup();
    }));
    S.oncomplete = function() {
      L = true;
      completeSetup();
    };
    S.onabort = idbError(o);
  };
  b.onerror = function(s) {
    var r = s.target.error && s.target.error.message;
    if (!r) r = "Failed to open indexedDB, are you in private browsing mode?"; else if (-1 !== r.indexOf("stored database is a higher version")) r = new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter');
    guardedConsole("error", r);
    o(createError(IDB_ERROR, r));
  };
}

IdbPouch.valid = function() {
  try {
    return "undefined" != typeof indexedDB && "undefined" != typeof IDBKeyRange;
  } catch (s) {
    return false;
  }
};

function index(s) {
  s.adapter("idb", IdbPouch, true);
}

var index_es_default2 = index, IDB_NULL = Number.MIN_SAFE_INTEGER, IDB_FALSE = Number.MIN_SAFE_INTEGER + 1, IDB_TRUE = Number.MIN_SAFE_INTEGER + 2, TEST_KEY_INVALID = /^[^a-zA-Z_$]|[^a-zA-Z0-9_$]+/, TEST_PATH_INVALID = /\\.|(^|\.)[^a-zA-Z_$]|[^a-zA-Z0-9_$.]+/;

function needsSanitise(s, r) {
  if (r) return TEST_PATH_INVALID.test(s); else return TEST_KEY_INVALID.test(s);
}

var KEY_INVALID = new RegExp(TEST_KEY_INVALID.source, "g"), PATH_INVALID = new RegExp(TEST_PATH_INVALID.source, "g"), SLASH = "\\".charCodeAt(0), IS_DOT = ".".charCodeAt(0);

function sanitise(s, r) {
  var correctCharacters = function(s) {
    for (var o = "", u = 0; u < s.length; u++) {
      var g = s.charCodeAt(u);
      if (g === IS_DOT && r && 0 === u) o += "."; else if (g === SLASH && r) continue; else o += "_c" + g + "_";
    }
    return o;
  };
  if (r) return s.replace(PATH_INVALID, correctCharacters); else return s.replace(KEY_INVALID, correctCharacters);
}

function needsRewrite(s) {
  for (var r of Object.keys(s)) if (needsSanitise(r)) return true; else if (null === s[r] || "boolean" == typeof s[r]) return true; else if ("object" == typeof s[r]) return needsRewrite(s[r]);
}

function rewrite(s) {
  if (!needsRewrite(s)) return false;
  var r = Array.isArray(s), o = r ? [] : {};
  Object.keys(s).forEach((function(u) {
    var g = r ? u : sanitise(u);
    if (null === s[u]) o[g] = IDB_NULL; else if ("boolean" == typeof s[u]) o[g] = s[u] ? IDB_TRUE : IDB_FALSE; else if ("object" == typeof s[u]) o[g] = rewrite(s[u]); else o[g] = s[u];
  }));
  return o;
}

var DOC_STORE2 = "docs", META_STORE2 = "meta";

function idbError2(s) {
  return function(r) {
    var o = "unknown_error";
    if (r.target && r.target.error) o = r.target.error.name || r.target.error.message;
    s(createError(IDB_ERROR, o, r.type));
  };
}

function processAttachment(s, r, o, u) {
  delete o._attachments[s].stub;
  if (u) {
    o._attachments[s].data = r.attachments[o._attachments[s].digest].data;
    return Promise.resolve();
  }
  return new Promise((function(u) {
    readAsBinaryString(r.attachments[o._attachments[s].digest].data, (function(r) {
      o._attachments[s].data = thisBtoa(r);
      delete o._attachments[s].length;
      u();
    }));
  }));
}

function rawIndexFields(s, r) {
  return (s.views[r].options && s.views[r].options.def && s.views[r].options.def.fields || []).map((function(s) {
    if ("string" == typeof s) return s; else return Object.keys(s)[0];
  }));
}

function isPartialFilterView(s, r) {
  return r in s.views && s.views[r].options && s.views[r].options.def && s.views[r].options.def.partial_filter_selector;
}

function naturalIndexName(s) {
  return "_find_idx/" + s.join("/");
}

function correctIndexFields(s) {
  return [ "deleted" ].concat(s.map((function(s) {
    if ([ "_id", "_rev", "_deleted", "_attachments" ].includes(s)) return s.substr(1); else return "data." + sanitise(s, true);
  })));
}

var POUCHDB_IDB_VERSION = 1, versionMultiplier = Math.pow(10, 13);

function createIdbVersion() {
  return versionMultiplier * POUCHDB_IDB_VERSION + (new Date).getTime();
}

function getPouchDbVersion(s) {
  return Math.floor(s / versionMultiplier);
}

function maintainNativeIndexes(s, r) {
  var o = s.transaction.objectStore(DOC_STORE2);
  o.getAll(IDBKeyRange.bound("_design/", "_design/")).onsuccess = function(s) {
    var u = s.target.result, g = Array.from(o.indexNames), _ = u.filter((function(s) {
      return 0 === s.deleted && s.revs[s.rev].data.views;
    })).map((function(s) {
      return s.revs[s.rev].data;
    })).reduce((function(s, r) {
      return Object.keys(r.views).reduce((function(s, o) {
        var u = rawIndexFields(r, o);
        if (u && u.length > 0) s[naturalIndexName(u)] = correctIndexFields(u);
        return s;
      }), s);
    }), {}), m = Object.keys(_), b = [ "seq" ];
    g.forEach((function(s) {
      if (-1 === b.indexOf(s) && -1 === m.indexOf(s)) o.deleteIndex(s);
    }));
    var E = m.filter((function(s) {
      return -1 === g.indexOf(s);
    }));
    try {
      E.forEach((function(s) {
        o.createIndex(s, _[s]);
      }));
    } catch (s) {
      r(s);
    }
  };
}

function upgradePouchDbSchema(s, r) {
  if (r < 1) {
    s.createObjectStore(DOC_STORE2, {
      keyPath: "id"
    }).createIndex("seq", "seq", {
      unique: true
    });
    s.createObjectStore(META_STORE2, {
      keyPath: "id"
    });
  }
}

function openDatabase(s, r, o, u, g) {
  var _ = o.versionchanged ? indexedDB.open(o.name) : indexedDB.open(o.name, createIdbVersion());
  _.onupgradeneeded = function(s) {
    if (s.oldVersion > 0 && s.oldVersion < versionMultiplier) throw new Error('Incorrect adapter: you should specify the "idb" adapter to open this DB'); else if (0 === s.oldVersion && s.newVersion < versionMultiplier) {
      indexedDB.deleteDatabase(o.name);
      throw new Error("Database was deleted while open");
    }
    upgradePouchDbSchema(s.target.result, getPouchDbVersion(s.oldVersion));
    maintainNativeIndexes(_, g);
  };
  _.onblocked = function(s) {
    console.error("onblocked, this should never happen", s);
  };
  _.onsuccess = function(r) {
    var g = r.target.result;
    g.onabort = function(r) {
      console.error("Database has a global failure", r.target.error);
      delete s[o.name];
      g.close();
    };
    g.onversionchange = function() {
      console.log("Database was made stale, closing handle");
      s[o.name].versionchanged = true;
      g.close();
    };
    g.onclose = function() {
      console.log("Database was made stale, closing handle");
      if (o.name in s) s[o.name].versionchanged = true;
    };
    var _ = {
      id: META_STORE2
    }, m = g.transaction([ META_STORE2 ], "readwrite");
    m.oncomplete = function() {
      u({
        idb: g,
        metadata: _
      });
    };
    var b = m.objectStore(META_STORE2);
    b.get(META_STORE2).onsuccess = function(s) {
      var r = false;
      if (!("doc_count" in (_ = s.target.result || _))) {
        r = true;
        _.doc_count = 0;
      }
      if (!("seq" in _)) {
        r = true;
        _.seq = 0;
      }
      if (!("db_uuid" in _)) {
        r = true;
        _.db_uuid = uuid();
      }
      if (r) b.put(_);
    };
  };
  _.onerror = function(s) {
    g(s.target.error);
  };
}

function setup(s, r, o) {
  if (!s[o.name] || s[o.name].versionchanged) {
    o.versionchanged = s[o.name] && s[o.name].versionchanged;
    s[o.name] = new Promise((function(u, g) {
      openDatabase(s, r, o, u, g);
    }));
  }
  return s[o.name];
}

function info(s, r) {
  r(null, {
    doc_count: s.doc_count,
    update_seq: s.seq
  });
}

function get(s, r, o, u) {
  if (s.error) return u(s.error);
  s.txn.objectStore(DOC_STORE2).get(r).onsuccess = function(r) {
    var g, _ = r.target.result;
    if (!o.rev) g = _ && _.rev; else g = o.latest ? latest(o.rev, _) : o.rev;
    if (_ && (!_.deleted || o.rev) && g in _.revs) {
      var m = _.revs[g].data;
      m._id = _.id;
      m._rev = g;
      u(null, {
        doc: m,
        metadata: _,
        ctx: s
      });
    } else u(createError(MISSING_DOC, "missing"));
  };
}

function parseAttachment(s, r, o) {
  if (r.binary) return o(null, s); else readAsBinaryString(s, (function(s) {
    o(null, thisBtoa(s));
  }));
}

function getAttachment(s, r, o, u, g, _) {
  if (s.error) return _(s.error);
  var m;
  s.txn.objectStore(DOC_STORE2).get(r).onsuccess = function(s) {
    var r = s.target.result, u = r.revs[g.rev || r.rev].data._attachments[o].digest;
    m = r.attachments[u].data;
  };
  s.txn.oncomplete = function() {
    parseAttachment(m, g, _);
  };
  s.txn.onabort = _;
}

function bulkDocs(s, r, o, u, g, _, m) {
  var b, E, w, S = [], L = [], O = g.revs_limit || 1e3, D = -1 === g.name.indexOf("-mrview-");
  const C = g.auto_compaction;
  function docsRevsLimit(s) {
    return /^_local/.test(s.id) ? 1 : O;
  }
  function revHasAttachment(s, r, o) {
    return s.revs[r] && s.revs[r].data._attachments && Object.values(s.revs[r].data._attachments).find((function(s) {
      return s.digest === o;
    }));
  }
  function convertDocFormat(s) {
    var r = {
      id: s.metadata.id,
      rev: s.metadata.rev,
      rev_tree: s.metadata.rev_tree,
      revs: s.metadata.revs || {}
    };
    r.revs[r.rev] = {
      data: s.data,
      deleted: s.metadata.deleted
    };
    return r;
  }
  function updateSeq(s) {
    if (s === w) b.objectStore(META_STORE2).put(u);
  }
  for (var k = 0, T = r.docs.length; k < T; k++) {
    var A;
    try {
      A = parseDoc(r.docs[k], o.new_edits, g);
    } catch (s) {
      A = s;
    }
    if (A.error) return m(A);
    L.push(convertDocFormat(A));
  }
  (function preProcessAttachments() {
    var s = L.map((function(s) {
      var r = s.revs[s.rev].data;
      if (!r._attachments) return Promise.resolve(r);
      var o = Object.keys(r._attachments).map((function(s) {
        r._attachments[s].name = s;
        return function preProcessAttachment(s) {
          if (s.stub) return Promise.resolve(s);
          var r;
          if ("string" == typeof s.data) {
            if ((r = function parseBase642(s) {
              try {
                return atob(s);
              } catch (s) {
                return {
                  error: createError(BAD_ARG, "Attachment is not a valid base64 string")
                };
              }
            }(s.data)).error) return Promise.reject(r.error);
            s.data = binStringToBluffer(r, s.content_type);
          } else r = s.data;
          return new Promise((function(o) {
            binaryMd5(r, (function(u) {
              s.digest = "md5-" + u;
              s.length = r.size || r.length || 0;
              o(s);
            }));
          }));
        }(r._attachments[s]);
      }));
      return Promise.all(o).then((function(s) {
        var o = {};
        s.forEach((function(s) {
          o[s.name] = s;
          delete s.name;
        }));
        r._attachments = o;
        return r;
      }));
    }));
    return Promise.all(s);
  })().then((function() {
    s._openTransactionSafely([ DOC_STORE2, META_STORE2 ], "readwrite", (function(s, r) {
      if (s) return m(s);
      (b = r).onabort = function() {
        m(E || createError(UNKNOWN_ERROR, "transaction was aborted"));
      };
      b.ontimeout = idbError2(m);
      b.oncomplete = function() {
        _.notify(g.name);
        m(null, S);
      };
      (function fetchExistingDocs(s, r) {
        var _ = 0, m = {};
        function readDone(b) {
          if (b.target.result) m[b.target.result.id] = b.target.result;
          if (++_ === r.length) (function processDocs2(s, r, _) {
            r.forEach((function(r, m) {
              var b;
              if ("was_delete" in o && !Object.prototype.hasOwnProperty.call(_, r.id)) b = createError(MISSING_DOC, "deleted"); else if (o.new_edits && !Object.prototype.hasOwnProperty.call(_, r.id) && function rootIsMissing2(s) {
                return "missing" === s.rev_tree[0].ids[1].status;
              }(r)) b = createError(REV_CONFLICT); else if (Object.prototype.hasOwnProperty.call(_, r.id)) {
                b = function update2(s, r, u) {
                  if (r.rev in u.revs && !o.new_edits) return false;
                  var _ = /^1-/.test(r.rev);
                  if (u.deleted && !r.deleted && o.new_edits && _) {
                    var m = r.revs[r.rev].data;
                    m._rev = u.rev;
                    m._id = u.id;
                    r = convertDocFormat(parseDoc(m, o.new_edits, g));
                  }
                  var b = merge(u.rev_tree, r.rev_tree[0], docsRevsLimit(r));
                  r.stemmedRevs = b.stemmedRevs;
                  r.rev_tree = b.tree;
                  var E = u.revs;
                  E[r.rev] = r.revs[r.rev];
                  r.revs = E;
                  r.attachments = u.attachments;
                  if (o.new_edits && (u.deleted && r.deleted || !u.deleted && "new_leaf" !== b.conflicts || u.deleted && !r.deleted && "new_branch" === b.conflicts || u.rev === r.rev)) return createError(REV_CONFLICT);
                  r.wasDeleted = u.deleted;
                  return r;
                }(0, r, _[r.id]);
                if (false == b) return;
              } else {
                var L = merge([], r.rev_tree[0], docsRevsLimit(r));
                r.rev_tree = L.tree;
                r.stemmedRevs = L.stemmedRevs;
                (b = r).isNewDoc = true;
                b.wasDeleted = r.revs[r.rev].deleted ? 1 : 0;
              }
              if (b.error) S[m] = b; else {
                _[b.id] = b;
                w = m;
                (function write(s, r, o) {
                  var g = winningRev(r), _ = r.rev, m = /^_local/.test(r.id), b = r.revs[g].data;
                  const w = r.isNewDoc;
                  if (D) {
                    var L = rewrite(b);
                    if (L) {
                      r.data = L;
                      delete r.data._attachments;
                    } else r.data = b;
                  } else r.data = b;
                  r.rev = g;
                  r.deleted = r.revs[g].deleted ? 1 : 0;
                  if (!m) {
                    r.seq = ++u.seq;
                    var O = 0;
                    if (r.isNewDoc) O = r.deleted ? 0 : 1; else if (r.wasDeleted !== r.deleted) O = r.deleted ? -1 : 1;
                    u.doc_count += O;
                  }
                  delete r.isNewDoc;
                  delete r.wasDeleted;
                  let k = r.stemmedRevs || [];
                  if (C && !w) {
                    const s = compactTree(r);
                    if (s.length) k = k.concat(s);
                  }
                  if (k.length) k.forEach((function(s) {
                    delete r.revs[s];
                  }));
                  delete r.stemmedRevs;
                  if (!("attachments" in r)) r.attachments = {};
                  if (b._attachments) for (var T in b._attachments) {
                    var A = b._attachments[T];
                    if (A.stub) {
                      if (!(A.digest in r.attachments)) {
                        E = createError(MISSING_STUB);
                        s.abort();
                        return;
                      }
                      if (revHasAttachment(r, _, A.digest)) r.attachments[A.digest].revs[_] = true;
                    } else {
                      r.attachments[A.digest] = A;
                      r.attachments[A.digest].revs = {};
                      r.attachments[A.digest].revs[_] = true;
                      b._attachments[T] = {
                        stub: true,
                        digest: A.digest,
                        content_type: A.content_type,
                        length: A.length,
                        revpos: parseInt(_, 10)
                      };
                    }
                  }
                  if (!m || !r.deleted) s.objectStore(DOC_STORE2).put(r).onsuccess = function() {
                    S[o] = {
                      ok: true,
                      id: r.id,
                      rev: _
                    };
                    updateSeq(o);
                  }; else {
                    s.objectStore(DOC_STORE2).delete(r.id).onsuccess = function() {
                      S[o] = {
                        ok: true,
                        id: r.id,
                        rev: "0-0"
                      };
                    };
                    updateSeq(o);
                  }
                })(s, b, m);
              }
            }));
          })(s, r, m);
        }
        r.forEach((function(r) {
          s.objectStore(DOC_STORE2).get(r.id).onsuccess = readDone;
        }));
      })(b, L);
    }));
  })).catch((function(s) {
    m(s);
  }));
}

function allDocsKeys2(s, r, o) {
  var u = new Array(s.length), g = 0;
  s.forEach((function(_, m) {
    r.get(_).onsuccess = function(r) {
      if (r.target.result) u[m] = r.target.result; else u[m] = {
        key: _,
        error: "not_found"
      };
      if (++g === s.length) u.forEach((function(s) {
        o(s);
      }));
    };
  }));
}

function createKeyRange2(s, r, o, u, g) {
  try {
    if (s && r) if (g) return IDBKeyRange.bound(r, s, !o, false); else return IDBKeyRange.bound(s, r, false, !o); else if (s) if (g) return IDBKeyRange.upperBound(s); else return IDBKeyRange.lowerBound(s); else if (r) if (g) return IDBKeyRange.lowerBound(r, !o); else return IDBKeyRange.upperBound(r, !o); else if (u) return IDBKeyRange.only(u);
  } catch (s) {
    return {
      error: s
    };
  }
  return null;
}

function handleKeyRangeError(s, r, o, u) {
  if ("DataError" === o.name && 0 === o.code) {
    var g = {
      total_rows: r.doc_count,
      offset: s.skip,
      rows: []
    };
    if (s.update_seq) g.update_seq = r.seq;
    return u(null, g);
  }
  u(createError(IDB_ERROR, o.name, o.message));
}

function allDocs(s, r, o, u) {
  if (s.error) return u(s.error);
  if (0 === o.limit) {
    var g = {
      total_rows: r.doc_count,
      offset: o.skip,
      rows: []
    };
    if (o.update_seq) g.update_seq = r.seq;
    return u(null, g);
  }
  var _, m = [], b = [], E = "startkey" in o ? o.startkey : false, w = "endkey" in o ? o.endkey : false, S = "key" in o ? o.key : false, L = "keys" in o ? o.keys : false, O = o.skip || 0, D = "number" == typeof o.limit ? o.limit : -1, C = false !== o.inclusive_end, k = "descending" in o && o.descending ? "prev" : null;
  if (!L) if ((_ = createKeyRange2(E, w, C, S, k)) && _.error) return handleKeyRangeError(o, r, _.error, u);
  var T = s.txn.objectStore(DOC_STORE2);
  s.txn.oncomplete = function onTxnComplete() {
    Promise.all(b).then((function() {
      var s = {
        total_rows: r.doc_count,
        offset: 0,
        rows: m
      };
      if (o.update_seq) s.update_seq = r.seq;
      u(null, s);
    }));
  };
  if (L) return allDocsKeys2(o.keys, T, allDocsInner);
  function allDocsInner(s) {
    if (s.error && L) {
      m.push(s);
      return true;
    }
    var r = {
      id: s.id,
      key: s.id,
      value: {
        rev: s.rev
      }
    };
    if (s.deleted) {
      if (L) {
        m.push(r);
        r.value.deleted = true;
        r.doc = null;
      }
    } else if (O-- <= 0) {
      m.push(r);
      if (o.include_docs) (function include_doc(s, r) {
        var u = r.revs[r.rev].data;
        s.doc = u;
        s.doc._id = r.id;
        s.doc._rev = r.rev;
        if (o.conflicts) {
          var g = collectConflicts(r);
          if (g.length) s.doc._conflicts = g;
        }
        if (o.attachments && u._attachments) for (var _ in u._attachments) b.push(processAttachment(_, r, s.doc, o.binary));
      })(r, s);
      if (0 == --D) return false;
    }
    return true;
  }
  (k ? T.openCursor(_, k) : T.openCursor(_)).onsuccess = function(s) {
    var r = s.target.result && s.target.result.value;
    if (r) {
      if (/^_local/.test(r.id)) return s.target.result.continue();
      if (allDocsInner(r)) s.target.result.continue();
    }
  };
}

function changes2(s, r, o, u, g) {
  if (s.error) return g.complete(s.error);
  if (g.continuous) {
    var _ = u.name + ":" + uuid();
    r.addListener(u.name, _, o, g);
    r.notify(u.name);
    return {
      cancel: function() {
        r.removeListener(u.name, _);
      }
    };
  }
  var m = "limit" in g ? g.limit : -1;
  if (0 === m) m = 1;
  var b, E = s.txn.objectStore(DOC_STORE2).index("seq"), w = filterChange(g), S = 0, L = g.since || 0, O = [], D = [];
  if (g.descending) b = E.openCursor(null, "prev"); else b = E.openCursor(IDBKeyRange.lowerBound(g.since, true));
  s.txn.oncomplete = function onTxnComplete() {
    Promise.all(D).then((function() {
      g.complete(null, {
        results: O,
        last_seq: L
      });
    }));
  };
  b.onsuccess = function onReqSuccess(s) {
    if (s.target.result) {
      var r = s.target.result, o = r.value;
      o.data = o.revs[o.rev].data;
      o.data._id = o.id;
      o.data._rev = o.rev;
      if (o.deleted) o.data._deleted = true;
      if (g.doc_ids && -1 === g.doc_ids.indexOf(o.id)) return r.continue();
      var u = g.processChange(o.data, o, g);
      u.seq = o.seq;
      L = o.seq;
      var _ = w(u);
      if ("object" == typeof _) return g.complete(_);
      if (_) {
        S++;
        if (g.return_docs) O.push(u);
        if (g.include_docs && g.attachments && o.data._attachments) {
          var b = [];
          for (var E in o.data._attachments) {
            var C = processAttachment(E, o, u.doc, g.binary);
            b.push(C);
            D.push(C);
          }
          Promise.all(b).then((function() {
            g.onChange(u);
          }));
        } else g.onChange(u);
      }
      if (S !== m) r.continue();
    }
  };
}

function getRevisionTree(s, r, o) {
  if (s.error) return o(s.error);
  s.txn.objectStore(DOC_STORE2).get(r).onsuccess = function(s) {
    if (!s.target.result) o(createError(MISSING_DOC)); else o(null, s.target.result.rev_tree);
  };
}

function doCompaction(s, r, o, u) {
  if (s.error) return u(s.error);
  var g = s.txn.objectStore(DOC_STORE2);
  g.get(r).onsuccess = function(s) {
    var r = s.target.result;
    traverseRevTree(r.rev_tree, (function(s, r, u, g, _) {
      var m = r + "-" + u;
      if (-1 !== o.indexOf(m)) _.status = "missing";
    }));
    var u = [];
    o.forEach((function(s) {
      if (s in r.revs) {
        if (r.revs[s].data._attachments) for (var o in r.revs[s].data._attachments) u.push(r.revs[s].data._attachments[o].digest);
        delete r.revs[s];
      }
    }));
    u.forEach((function(s) {
      o.forEach((function(o) {
        delete r.attachments[s].revs[o];
      }));
      if (!Object.keys(r.attachments[s].revs).length) delete r.attachments[s];
    }));
    g.put(r);
  };
  s.txn.oncomplete = function() {
    u();
  };
}

function destroy(s, r, o, u) {
  o.removeAllListeners(s.name);
  function doDestroy() {
    indexedDB.deleteDatabase(s.name).onsuccess = function() {
      delete r[s.name];
      u(null, {
        ok: true
      });
    };
  }
  if (s.name in r) r[s.name].then((function(s) {
    s.idb.close();
    doDestroy();
  })); else doDestroy();
}

var COUCH_COLLATE_LO = null, COUCH_COLLATE_HI = "", IDB_COLLATE_LO = Number.NEGATIVE_INFINITY, IDB_COLLATE_HI = [ [ [ [ [ [ [ [ [ [ [ [] ] ] ] ] ] ] ] ] ] ] ];

function externaliseRecord(s) {
  var r = s.revs[s.rev].data;
  r._id = s.id;
  r._rev = s.rev;
  if (s.deleted) r._deleted = true;
  return r;
}

function generateKeyRange(s) {
  function defined(s, r) {
    return void 0 !== s[r];
  }
  function convert(s, r) {
    return [ 0 ].concat(s).map((function(s) {
      if (null === s && r) return IDB_NULL; else if (true === s) return IDB_TRUE; else if (false === s) return IDB_FALSE;
      if (!r) if (s === COUCH_COLLATE_LO) return IDB_COLLATE_LO; else if (Object.prototype.hasOwnProperty.call(s, COUCH_COLLATE_HI)) return IDB_COLLATE_HI;
      return s;
    }));
  }
  if (!defined(s, "inclusive_end")) s.inclusive_end = true;
  if (!defined(s, "inclusive_start")) s.inclusive_start = true;
  if (s.descending) {
    var r = s.startkey, o = s.inclusive_start;
    s.startkey = s.endkey;
    s.endkey = r;
    s.inclusive_start = s.inclusive_end;
    s.inclusive_end = o;
  }
  try {
    if (defined(s, "key")) return IDBKeyRange.only(convert(s.key, true));
    if (defined(s, "startkey") && !defined(s, "endkey")) return IDBKeyRange.bound(convert(s.startkey), [ 1 ], !s.inclusive_start, true);
    if (!defined(s, "startkey") && defined(s, "endkey")) return IDBKeyRange.upperBound(convert(s.endkey), !s.inclusive_end);
    if (defined(s, "startkey") && defined(s, "endkey")) return IDBKeyRange.bound(convert(s.startkey), convert(s.endkey), !s.inclusive_start, !s.inclusive_end); else return IDBKeyRange.only([ 0 ]);
  } catch (r) {
    console.error("Could not generate keyRange", r, s);
    throw Error("Could not generate key range with " + JSON.stringify(s));
  }
}

function getIndexHandle(s, r, o) {
  var u = naturalIndexName(r);
  return new Promise((function(g) {
    s._openTransactionSafely([ DOC_STORE2 ], "readonly", (function(_, m) {
      if (_) return idbError2(o)(_);
      m.onabort = idbError2(o);
      m.ontimeout = idbError2(o);
      if (-1 === Array.from(m.objectStore(DOC_STORE2).indexNames).indexOf(u)) s._freshen().then((function() {
        return getIndexHandle(s, r, o);
      })).then(g); else g(m.objectStore(DOC_STORE2).index(u));
    }));
  }));
}

function query(s, r, o, u) {
  var g = this, _ = r.split("/");
  return new Promise((function(s, m) {
    g.get("_design/" + _[0]).then((function(b) {
      if (isPartialFilterView(b, _[1])) return u(r, o).then(s, m);
      var E = rawIndexFields(b, _[1]);
      if (!E) throw new Error("ddoc " + b._id + " with view " + _[1] + " does not have map.options.def.fields defined.");
      var w = o.skip, S = Number.isInteger(o.limit) && o.limit;
      return getIndexHandle(g, E, m).then((function(r) {
        var u = generateKeyRange(o), g = r.openCursor(u, o.descending ? "prev" : "next"), _ = [];
        g.onerror = idbError2(m);
        g.onsuccess = function(r) {
          var o = r.target.result;
          if (!o || 0 === S) return s({
            rows: _
          });
          if (!w) {
            if (S) S -= 1;
            _.push({
              doc: externaliseRecord(o.value)
            });
            o.continue();
          } else {
            o.advance(w);
            w = false;
          }
        };
      }));
    })).catch(m);
  }));
}

function viewCleanup(s, r) {
  return r();
}

function purgeAttachments(s, r) {
  if (!s.attachments) return {};
  for (let o in s.attachments) {
    const u = s.attachments[o];
    for (let s of r) if (u.revs[s]) delete u.revs[s];
    if (0 === Object.keys(u.revs).length) delete s.attachments[o];
  }
  return s.attachments;
}

function purge(s, r, o, u) {
  if (s.error) return u(s.error);
  const g = s.txn.objectStore(DOC_STORE2), _ = [];
  let m = false;
  g.get(r).onsuccess = s => {
    const r = s.target.result;
    for (const s of o) {
      r.rev_tree = removeLeafFromRevTree(r.rev_tree, s);
      delete r.revs[s];
      _.push(s);
    }
    if (0 !== r.rev_tree.length) {
      r.rev = winningRev(r);
      r.data = r.revs[r.rev].data;
      r.attachments = purgeAttachments(r, o);
      g.put(r);
    } else {
      g.delete(r.id);
      m = true;
    }
  };
  s.txn.oncomplete = function() {
    u(null, {
      ok: true,
      deletedRevs: _,
      documentWasRemovedCompletely: m
    });
  };
}

var ADAPTER_NAME = "indexeddb", idbChanges = new Changes, openDatabases = {};

function IdbPouch2(s, r) {
  if (s.view_adapter) console.log("Please note that the indexeddb adapter manages _find indexes itself, therefore it is not using your specified view_adapter");
  var o = this, u = {}, $ = function(r) {
    return function() {
      var g = Array.prototype.slice.call(arguments);
      setup(openDatabases, o, s).then((function(s) {
        u = s.metadata;
        g.unshift(s.idb);
        r.apply(o, g);
      })).catch((function(s) {
        var r = g.pop();
        if ("function" == typeof r) r(s); else console.error(s);
      }));
    };
  }, $p = function(r) {
    return function() {
      var g = Array.prototype.slice.call(arguments);
      return setup(openDatabases, o, s).then((function(s) {
        u = s.metadata;
        g.unshift(s.idb);
        return r.apply(o, g);
      }));
    };
  }, $t = function(r, g, _) {
    g = g || [ DOC_STORE2 ];
    _ = _ || "readonly";
    return function() {
      var m = Array.prototype.slice.call(arguments), b = {};
      setup(openDatabases, o, s).then((function(s) {
        u = s.metadata;
        b.txn = s.idb.transaction(g, _);
      })).catch((function(s) {
        console.error("Failed to establish transaction safely");
        console.error(s);
        b.error = s;
      })).then((function() {
        m.unshift(b);
        r.apply(o, m);
      }));
    };
  };
  o._openTransactionSafely = function(s, r, o) {
    $t((function(s, r) {
      r(s.error, s.txn);
    }), s, r)(o);
  };
  o._remote = false;
  o.type = function() {
    return ADAPTER_NAME;
  };
  o._id = $((function(s, r) {
    r(null, u.db_uuid);
  }));
  o._info = $((function(s, r) {
    return info(u, r);
  }));
  o._get = $t(get);
  o._bulkDocs = $((function(r, g, _, m) {
    bulkDocs(o, g, _, u, s, idbChanges, m);
  }));
  o._allDocs = $t((function(s, r, o) {
    allDocs(s, u, r, o);
  }));
  o._getAttachment = $t(getAttachment);
  o._changes = $t((function(r, u) {
    changes2(r, idbChanges, o, s, u);
  }));
  o._getRevisionTree = $t(getRevisionTree);
  o._doCompaction = $t(doCompaction, [ DOC_STORE2 ], "readwrite");
  o._customFindAbstractMapper = {
    query: $p(query),
    viewCleanup: $p(viewCleanup)
  };
  o._destroy = function(r, o) {
    return destroy(s, openDatabases, idbChanges, o);
  };
  o._close = $((function(r, o) {
    delete openDatabases[s.name];
    r.close();
    o();
  }));
  o._freshen = function() {
    return new Promise((function(s) {
      o._close((function() {
        $(s)();
      }));
    }));
  };
  o._purge = $t(purge, [ DOC_STORE2 ], "readwrite");
  setTimeout((function() {
    r(null, o);
  }));
}

IdbPouch2.valid = function() {
  return true;
};

function index2(s) {
  s.adapter(ADAPTER_NAME, IdbPouch2, true);
}

var index_es_default3 = index2;

function pool(s, r) {
  return new Promise((function(o, u) {
    var g, _ = 0, m = 0, b = 0, E = s.length;
    function runNext() {
      _++;
      s[m++]().then(onSuccess, onError);
    }
    function doNext() {
      if (++b === E) if (g) u(g); else o(); else runNextBatch();
    }
    function onSuccess() {
      _--;
      doNext();
    }
    function onError(s) {
      _--;
      g = g || s;
      doNext();
    }
    function runNextBatch() {
      for (;_ < r && m < E; ) runNext();
    }
    runNextBatch();
  }));
}

var CHANGES_BATCH_SIZE = 25, MAX_SIMULTANEOUS_REVS = 50, CHANGES_TIMEOUT_BUFFER = 5e3, DEFAULT_HEARTBEAT = 1e4, supportsBulkGetMap = {};

function readAttachmentsAsBlobOrBuffer(s) {
  let r = s.doc || s.ok, o = r && r._attachments;
  if (o) Object.keys(o).forEach((function(s) {
    let r = o[s];
    r.data = b64ToBluffer(r.data, r.content_type);
  }));
}

function encodeDocId(s) {
  if (/^_design/.test(s)) return "_design/" + encodeURIComponent(s.slice(8));
  if (/^_local/.test(s)) return "_local/" + encodeURIComponent(s.slice(7)); else return encodeURIComponent(s);
}

function preprocessAttachments2(s) {
  if (!s._attachments || !Object.keys(s._attachments)) return Promise.resolve(); else return Promise.all(Object.keys(s._attachments).map((function(r) {
    let o = s._attachments[r];
    if (o.data && "string" != typeof o.data) return new Promise((function(s) {
      blobToBase64(o.data, s);
    })).then((function(s) {
      o.data = s;
    }));
  })));
}

function hasUrlPrefix(s) {
  if (!s.prefix) return false;
  let r = parseUri(s.prefix).protocol;
  return "http" === r || "https" === r;
}

function getHost(s, r) {
  if (hasUrlPrefix(r)) {
    let o = r.name.substr(r.prefix.length);
    s = r.prefix.replace(/\/?$/, "/") + encodeURIComponent(o);
  }
  let o = parseUri(s);
  if (o.user || o.password) o.auth = {
    username: o.user,
    password: o.password
  };
  let u = o.path.replace(/(^\/|\/$)/g, "").split("/");
  o.db = u.pop();
  if (-1 === o.db.indexOf("%")) o.db = encodeURIComponent(o.db);
  o.path = u.join("/");
  return o;
}

function genDBUrl(s, r) {
  return genUrl(s, s.db + "/" + r);
}

function genUrl(s, r) {
  let o = !s.path ? "" : "/";
  return s.protocol + "://" + s.host + (s.port ? ":" + s.port : "") + "/" + s.path + o + r;
}

function paramsToStr(s) {
  return "?" + Object.keys(s).map((function(r) {
    return r + "=" + encodeURIComponent(s[r]);
  })).join("&");
}

function shouldCacheBust(s) {
  let r = "undefined" != typeof navigator && navigator.userAgent ? navigator.userAgent.toLowerCase() : "", o = -1 !== r.indexOf("msie"), u = -1 !== r.indexOf("trident"), g = -1 !== r.indexOf("edge"), _ = !("method" in s) || "GET" === s.method;
  return (o || u || g) && _;
}

function HttpPouch(s, r) {
  let o = this, u = getHost(s.name, s), g = genDBUrl(u, "");
  s = clone(s);
  const ourFetch = async function(r, o) {
    (o = o || {}).headers = o.headers || new h;
    o.credentials = "include";
    if (s.auth || u.auth) {
      let r = s.auth || u.auth, g = r.username + ":" + r.password, _ = thisBtoa(unescape(encodeURIComponent(g)));
      o.headers.set("Authorization", "Basic " + _);
    }
    let g = s.headers || {};
    Object.keys(g).forEach((function(s) {
      o.headers.append(s, g[s]);
    }));
    if (shouldCacheBust(o)) r += (-1 === r.indexOf("?") ? "?" : "&") + "_nonce=" + Date.now();
    let _ = s.fetch || f2;
    return await _(r, o);
  };
  function adapterFun$$1(s, r) {
    return adapterFun(s, (function(...s) {
      setup2().then((function() {
        return r.apply(this, s);
      })).catch((function(r) {
        s.pop()(r);
      }));
    })).bind(o);
  }
  async function fetchJSON(s, r) {
    let o = {};
    (r = r || {}).headers = r.headers || new h;
    if (!r.headers.get("Content-Type")) r.headers.set("Content-Type", "application/json");
    if (!r.headers.get("Accept")) r.headers.set("Accept", "application/json");
    const u = await ourFetch(s, r);
    o.ok = u.ok;
    o.status = u.status;
    const g = await u.json();
    o.data = g;
    if (!o.ok) {
      o.data.status = o.status;
      throw generateErrorFromResponse(o.data);
    }
    if (Array.isArray(o.data)) o.data = o.data.map((function(s) {
      if (s.error || s.missing) return generateErrorFromResponse(s); else return s;
    }));
    return o;
  }
  let _;
  async function setup2() {
    if (s.skip_setup) return Promise.resolve();
    if (_) return _;
    _ = fetchJSON(g).catch((function(s) {
      if (s && s.status && 404 === s.status) {
        explainError(404, "PouchDB is just detecting if the remote exists.");
        return fetchJSON(g, {
          method: "PUT"
        });
      } else return Promise.reject(s);
    })).catch((function(s) {
      if (s && s.status && 412 === s.status) return true; else return Promise.reject(s);
    }));
    _.catch((function() {
      _ = null;
    }));
    return _;
  }
  (0, import_immediate.default)((function() {
    r(null, o);
  }));
  o._remote = true;
  o.type = function() {
    return "http";
  };
  o.id = adapterFun$$1("id", (async function(s) {
    let r;
    try {
      const s = await ourFetch(genUrl(u, ""));
      r = await s.json();
    } catch (s) {
      r = {};
    }
    s(null, r && r.uuid ? r.uuid + u.db : genDBUrl(u, ""));
  }));
  o.compact = adapterFun$$1("compact", (async function(s, r) {
    if ("function" == typeof s) {
      r = s;
      s = {};
    }
    s = clone(s);
    await fetchJSON(genDBUrl(u, "_compact"), {
      method: "POST"
    });
    (function ping() {
      o.info((function(o, u) {
        if (u && !u.compact_running) r(null, {
          ok: true
        }); else setTimeout(ping, s.interval || 200);
      }));
    })();
  }));
  o.bulkGet = adapterFun("bulkGet", (function(s, r) {
    let o = this;
    async function doBulkGet(r) {
      let o = {};
      if (s.revs) o.revs = true;
      if (s.attachments) o.attachments = true;
      if (s.latest) o.latest = true;
      try {
        const g = await fetchJSON(genDBUrl(u, "_bulk_get" + paramsToStr(o)), {
          method: "POST",
          body: JSON.stringify({
            docs: s.docs
          })
        });
        if (s.attachments && s.binary) g.data.results.forEach((function(s) {
          s.docs.forEach(readAttachmentsAsBlobOrBuffer);
        }));
        r(null, g.data);
      } catch (s) {
        r(s);
      }
    }
    function doBulkGetShim() {
      let u = MAX_SIMULTANEOUS_REVS, g = Math.ceil(s.docs.length / u), _ = 0, m = new Array(g);
      function onResult(s) {
        return function(o, u) {
          m[s] = u.results;
          if (++_ === g) r(null, {
            results: flatten(m)
          });
        };
      }
      for (let r = 0; r < g; r++) {
        let g = pick(s, [ "revs", "attachments", "binary", "latest" ]);
        g.docs = s.docs.slice(r * u, Math.min(s.docs.length, (r + 1) * u));
        bulkGet(o, g, onResult(r));
      }
    }
    let g = genUrl(u, ""), _ = supportsBulkGetMap[g];
    if ("boolean" != typeof _) doBulkGet((function(s, o) {
      if (s) {
        supportsBulkGetMap[g] = false;
        explainError(s.status, "PouchDB is just detecting if the remote supports the _bulk_get API.");
        doBulkGetShim();
      } else {
        supportsBulkGetMap[g] = true;
        r(null, o);
      }
    })); else if (_) doBulkGet(r); else doBulkGetShim();
  }));
  o._info = async function(s) {
    try {
      await setup2();
      const r = await ourFetch(genDBUrl(u, "")), o = await r.json();
      o.host = genDBUrl(u, "");
      s(null, o);
    } catch (r) {
      s(r);
    }
  };
  o.fetch = async function(s, r) {
    await setup2();
    const o = "/" === s.substring(0, 1) ? genUrl(u, s.substring(1)) : genDBUrl(u, s);
    return ourFetch(o, r);
  };
  o.get = adapterFun$$1("get", (async function(s, r, o) {
    if ("function" == typeof r) {
      o = r;
      r = {};
    }
    let g = {};
    if ((r = clone(r)).revs) g.revs = true;
    if (r.revs_info) g.revs_info = true;
    if (r.latest) g.latest = true;
    if (r.open_revs) {
      if ("all" !== r.open_revs) r.open_revs = JSON.stringify(r.open_revs);
      g.open_revs = r.open_revs;
    }
    if (r.rev) g.rev = r.rev;
    if (r.conflicts) g.conflicts = r.conflicts;
    if (r.update_seq) g.update_seq = r.update_seq;
    s = encodeDocId(s);
    function fetchAttachments(s) {
      let o = s._attachments, g = o && Object.keys(o);
      if (o && g.length) return pool(g.map((function(g) {
        return function() {
          return async function fetchData(g) {
            const _ = o[g], m = encodeDocId(s._id) + "/" + encodeAttachmentId(g) + "?rev=" + s._rev, b = await ourFetch(genDBUrl(u, m));
            let E, w;
            if ("buffer" in b) E = await b.buffer(); else E = await b.blob();
            if (r.binary) {
              let s = Object.getOwnPropertyDescriptor(E.__proto__, "type");
              if (!s || s.set) E.type = _.content_type;
              w = E;
            } else w = await new Promise((function(s) {
              blobToBase64(E, s);
            }));
            delete _.stub;
            delete _.length;
            _.data = w;
          }(g);
        };
      })), 5);
    }
    const _ = genDBUrl(u, s + paramsToStr(g));
    try {
      const s = await fetchJSON(_);
      if (r.attachments) await function fetchAllAttachments(s) {
        if (Array.isArray(s)) return Promise.all(s.map((function(s) {
          if (s.ok) return fetchAttachments(s.ok);
        }))); else return fetchAttachments(s);
      }(s.data);
      o(null, s.data);
    } catch (r) {
      r.docId = s;
      o(r);
    }
  }));
  o.remove = adapterFun$$1("remove", (async function(s, r, o, g) {
    let _;
    if ("string" == typeof r) {
      _ = {
        _id: s,
        _rev: r
      };
      if ("function" == typeof o) {
        g = o;
        o = {};
      }
    } else {
      _ = s;
      if ("function" == typeof r) {
        g = r;
        o = {};
      } else {
        g = o;
        o = r;
      }
    }
    const m = _._rev || o.rev, b = genDBUrl(u, encodeDocId(_._id)) + "?rev=" + m;
    try {
      g(null, (await fetchJSON(b, {
        method: "DELETE"
      })).data);
    } catch (s) {
      g(s);
    }
  }));
  function encodeAttachmentId(s) {
    return s.split("/").map(encodeURIComponent).join("/");
  }
  o.getAttachment = adapterFun$$1("getAttachment", (async function(s, r, o, g) {
    if ("function" == typeof o) {
      g = o;
      o = {};
    }
    const _ = o.rev ? "?rev=" + o.rev : "", m = genDBUrl(u, encodeDocId(s)) + "/" + encodeAttachmentId(r) + _;
    let b;
    try {
      const s = await ourFetch(m, {
        method: "GET"
      });
      if (!s.ok) throw s;
      b = s.headers.get("content-type");
      let r;
      if ("undefined" != typeof process && !process.browser && "function" == typeof s.buffer) r = await s.buffer(); else r = await s.blob();
      if ("undefined" != typeof process && !process.browser) {
        var E = Object.getOwnPropertyDescriptor(r.__proto__, "type");
        if (!E || E.set) r.type = b;
      }
      g(null, r);
    } catch (s) {
      g(s);
    }
  }));
  o.removeAttachment = adapterFun$$1("removeAttachment", (async function(s, r, o, g) {
    const _ = genDBUrl(u, encodeDocId(s) + "/" + encodeAttachmentId(r)) + "?rev=" + o;
    try {
      g(null, (await fetchJSON(_, {
        method: "DELETE"
      })).data);
    } catch (s) {
      g(s);
    }
  }));
  o.putAttachment = adapterFun$$1("putAttachment", (async function(s, r, o, g, _, m) {
    if ("function" == typeof _) {
      m = _;
      _ = g;
      g = o;
      o = null;
    }
    const b = encodeDocId(s) + "/" + encodeAttachmentId(r);
    let E = genDBUrl(u, b);
    if (o) E += "?rev=" + o;
    if ("string" == typeof g) {
      let s;
      try {
        s = thisAtob(g);
      } catch (s) {
        return m(createError(BAD_ARG, "Attachment is not a valid base64 string"));
      }
      g = s ? binStringToBluffer(s, _) : "";
    }
    try {
      m(null, (await fetchJSON(E, {
        headers: new h({
          "Content-Type": _
        }),
        method: "PUT",
        body: g
      })).data);
    } catch (s) {
      m(s);
    }
  }));
  o._bulkDocs = async function(s, r, o) {
    s.new_edits = r.new_edits;
    try {
      await setup2();
      await Promise.all(s.docs.map(preprocessAttachments2));
      o(null, (await fetchJSON(genDBUrl(u, "_bulk_docs"), {
        method: "POST",
        body: JSON.stringify(s)
      })).data);
    } catch (s) {
      o(s);
    }
  };
  o._put = async function(s, r, o) {
    try {
      await setup2();
      await preprocessAttachments2(s);
      o(null, (await fetchJSON(genDBUrl(u, encodeDocId(s._id)), {
        method: "PUT",
        body: JSON.stringify(s)
      })).data);
    } catch (r) {
      r.docId = s && s._id;
      o(r);
    }
  };
  o.allDocs = adapterFun$$1("allDocs", (async function(s, r) {
    if ("function" == typeof s) {
      r = s;
      s = {};
    }
    let o, g = {}, _ = "GET";
    if ((s = clone(s)).conflicts) g.conflicts = true;
    if (s.update_seq) g.update_seq = true;
    if (s.descending) g.descending = true;
    if (s.include_docs) g.include_docs = true;
    if (s.attachments) g.attachments = true;
    if (s.key) g.key = JSON.stringify(s.key);
    if (s.start_key) s.startkey = s.start_key;
    if (s.startkey) g.startkey = JSON.stringify(s.startkey);
    if (s.end_key) s.endkey = s.end_key;
    if (s.endkey) g.endkey = JSON.stringify(s.endkey);
    if ("undefined" != typeof s.inclusive_end) g.inclusive_end = !!s.inclusive_end;
    if ("undefined" != typeof s.limit) g.limit = s.limit;
    if ("undefined" != typeof s.skip) g.skip = s.skip;
    let m = paramsToStr(g);
    if ("undefined" != typeof s.keys) {
      _ = "POST";
      o = {
        keys: s.keys
      };
    }
    try {
      const g = await fetchJSON(genDBUrl(u, "_all_docs" + m), {
        method: _,
        body: JSON.stringify(o)
      });
      if (s.include_docs && s.attachments && s.binary) g.data.rows.forEach(readAttachmentsAsBlobOrBuffer);
      r(null, g.data);
    } catch (s) {
      r(s);
    }
  }));
  o._changes = function(s) {
    let r = "batch_size" in s ? s.batch_size : CHANGES_BATCH_SIZE;
    if ((s = clone(s)).continuous && !("heartbeat" in s)) s.heartbeat = DEFAULT_HEARTBEAT;
    let o = "timeout" in s ? s.timeout : 3e4;
    if ("timeout" in s && s.timeout && o - s.timeout < CHANGES_TIMEOUT_BUFFER) o = s.timeout + CHANGES_TIMEOUT_BUFFER;
    if ("heartbeat" in s && s.heartbeat && o - s.heartbeat < CHANGES_TIMEOUT_BUFFER) o = s.heartbeat + CHANGES_TIMEOUT_BUFFER;
    let g = {};
    if ("timeout" in s && s.timeout) g.timeout = s.timeout;
    let _ = "undefined" != typeof s.limit ? s.limit : false, m = _;
    if (s.style) g.style = s.style;
    if (s.include_docs || s.filter && "function" == typeof s.filter) g.include_docs = true;
    if (s.attachments) g.attachments = true;
    if (s.continuous) g.feed = "longpoll";
    if (s.seq_interval) g.seq_interval = s.seq_interval;
    if (s.conflicts) g.conflicts = true;
    if (s.descending) g.descending = true;
    if (s.update_seq) g.update_seq = true;
    if ("heartbeat" in s) if (s.heartbeat) g.heartbeat = s.heartbeat;
    if (s.filter && "string" == typeof s.filter) g.filter = s.filter;
    if (s.view && "string" == typeof s.view) {
      g.filter = "_view";
      g.view = s.view;
    }
    if (s.query_params && "object" == typeof s.query_params) for (let r in s.query_params) if (Object.prototype.hasOwnProperty.call(s.query_params, r)) g[r] = s.query_params[r];
    let b, E = "GET";
    if (s.doc_ids) {
      g.filter = "_doc_ids";
      E = "POST";
      b = {
        doc_ids: s.doc_ids
      };
    } else if (s.selector) {
      g.filter = "_selector";
      E = "POST";
      b = {
        selector: s.selector
      };
    }
    let w, S = new a;
    const fetchData = async function(o, L) {
      if (s.aborted) return;
      g.since = o;
      if ("object" == typeof g.since) g.since = JSON.stringify(g.since);
      if (s.descending) {
        if (_) g.limit = m;
      } else g.limit = !_ || m > r ? r : m;
      let O = genDBUrl(u, "_changes" + paramsToStr(g)), D = {
        signal: S.signal,
        method: E,
        body: JSON.stringify(b)
      };
      w = o;
      if (!s.aborted) try {
        await setup2();
        L(null, (await fetchJSON(O, D)).data);
      } catch (s) {
        L(s);
      }
    };
    let L = {
      results: []
    };
    const fetched = function(o, u) {
      if (s.aborted) return;
      let g = 0;
      if (u && u.results) {
        g = u.results.length;
        L.last_seq = u.last_seq;
        let r = null, o = null;
        if ("number" == typeof u.pending) r = u.pending;
        if ("string" == typeof L.last_seq || "number" == typeof L.last_seq) o = L.last_seq;
        ({}).query = s.query_params;
        u.results = u.results.filter((function(u) {
          m--;
          let g = filterChange(s)(u);
          if (g) {
            if (s.include_docs && s.attachments && s.binary) readAttachmentsAsBlobOrBuffer(u);
            if (s.return_docs) L.results.push(u);
            s.onChange(u, r, o);
          }
          return g;
        }));
      } else if (o) {
        s.aborted = true;
        s.complete(o);
        return;
      }
      if (u && u.last_seq) w = u.last_seq;
      let b = _ && m <= 0 || u && g < r || s.descending;
      if (s.continuous && !(_ && m <= 0) || !b) (0, import_immediate.default)((function() {
        fetchData(w, fetched);
      })); else s.complete(null, L);
    };
    fetchData(s.since || 0, fetched);
    return {
      cancel: function() {
        s.aborted = true;
        S.abort();
      }
    };
  };
  o.revsDiff = adapterFun$$1("revsDiff", (async function(s, r, o) {
    if ("function" == typeof r) {
      o = r;
      r = {};
    }
    try {
      o(null, (await fetchJSON(genDBUrl(u, "_revs_diff"), {
        method: "POST",
        body: JSON.stringify(s)
      })).data);
    } catch (s) {
      o(s);
    }
  }));
  o._close = function(s) {
    s();
  };
  o._destroy = async function(s, r) {
    try {
      r(null, await fetchJSON(genDBUrl(u, ""), {
        method: "DELETE"
      }));
    } catch (s) {
      if (404 === s.status) r(null, {
        ok: true
      }); else r(s);
    }
  };
}

HttpPouch.valid = function() {
  return true;
};

function index3(s) {
  s.adapter("http", HttpPouch, false);
  s.adapter("https", HttpPouch, false);
}

var index_es_default4 = index3, QueryParseError = class _QueryParseError extends Error {
  constructor(s) {
    super();
    this.status = 400;
    this.name = "query_parse_error";
    this.message = s;
    this.error = true;
    try {
      Error.captureStackTrace(this, _QueryParseError);
    } catch (s) {}
  }
}, NotFoundError = class _NotFoundError extends Error {
  constructor(s) {
    super();
    this.status = 404;
    this.name = "not_found";
    this.message = s;
    this.error = true;
    try {
      Error.captureStackTrace(this, _NotFoundError);
    } catch (s) {}
  }
}, BuiltInError = class _BuiltInError extends Error {
  constructor(s) {
    super();
    this.status = 500;
    this.name = "invalid_value";
    this.message = s;
    this.error = true;
    try {
      Error.captureStackTrace(this, _BuiltInError);
    } catch (s) {}
  }
};

function promisedCallback(s, r) {
  if (r) s.then((function(s) {
    (0, import_immediate.default)((function() {
      r(null, s);
    }));
  }), (function(s) {
    (0, import_immediate.default)((function() {
      r(s);
    }));
  }));
  return s;
}

function callbackify(s) {
  return function(...r) {
    var o = r.pop(), u = s.apply(this, r);
    if ("function" == typeof o) promisedCallback(u, o);
    return u;
  };
}

function fin(s, r) {
  return s.then((function(s) {
    return r().then((function() {
      return s;
    }));
  }), (function(s) {
    return r().then((function() {
      throw s;
    }));
  }));
}

function sequentialize(s, r) {
  return function() {
    var o = arguments, u = this;
    return s.add((function() {
      return r.apply(u, o);
    }));
  };
}

function uniq(s) {
  var r = new ExportedSet(s), o = new Array(r.size), u = -1;
  r.forEach((function(s) {
    o[++u] = s;
  }));
  return o;
}

function mapToKeysArray(s) {
  var r = new Array(s.size), o = -1;
  s.forEach((function(s, u) {
    r[++o] = u;
  }));
  return r;
}

var TaskQueue2 = class {
  constructor() {
    this.promise = new Promise((function(s) {
      s();
    }));
  }
  add(s) {
    this.promise = this.promise.catch((function() {})).then((function() {
      return s();
    }));
    return this.promise;
  }
  finish() {
    return this.promise;
  }
};

function stringify2(s) {
  if (!s) return "undefined";
  switch (typeof s) {
   case "function":
    return s.toString();

   case "string":
    return s.toString();

   default:
    return JSON.stringify(s);
  }
}

function createViewSignature(s, r) {
  return stringify2(s) + stringify2(r) + "undefined";
}

async function createView(s, r, o, u, g, _) {
  const m = createViewSignature(o, u);
  let b;
  if (!g) {
    b = s._cachedViews = s._cachedViews || {};
    if (b[m]) return b[m];
  }
  const E = s.info().then((async function(E) {
    const w = E.db_name + "-mrview-" + (g ? "temp" : stringMd5(m));
    await upsert(s, "_local/" + _, (function diffFunction(s) {
      s.views = s.views || {};
      let o = r;
      if (-1 === o.indexOf("/")) o = r + "/" + r;
      const u = s.views[o] = s.views[o] || {};
      if (!u[w]) {
        u[w] = true;
        return s;
      }
    }));
    const S = (await s.registerDependentDatabase(w)).db;
    S.auto_compaction = true;
    const L = {
      name: w,
      db: S,
      sourceDB: s,
      adapter: s.adapter,
      mapFun: o,
      reduceFun: u
    };
    let O;
    try {
      O = await L.db.get("_local/lastSeq");
    } catch (s) {
      if (404 !== s.status) throw s;
    }
    L.seq = O ? O.seq : 0;
    if (b) L.db.once("destroyed", (function() {
      delete b[m];
    }));
    return L;
  }));
  if (b) b[m] = E;
  return E;
}

var persistentQueues = {}, tempViewQueue = new TaskQueue2, CHANGES_BATCH_SIZE2 = 50;

function parseViewName(s) {
  return -1 === s.indexOf("/") ? [ s, s ] : s.split("/");
}

function isGenOne(s) {
  return 1 === s.length && /^1-/.test(s[0].rev);
}

function emitError(s, r, o) {
  try {
    s.emit("error", r);
  } catch (s) {
    guardedConsole("error", "The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function.");
    guardedConsole("error", r, o);
  }
}

function createAbstractMapReduce(s, r, o, u) {
  function tryMap(s, r, o) {
    try {
      r(o);
    } catch (u) {
      emitError(s, u, {
        fun: r,
        doc: o
      });
    }
  }
  function tryReduce(s, r, o, u, g) {
    try {
      return {
        output: r(o, u, g)
      };
    } catch (_) {
      emitError(s, _, {
        fun: r,
        keys: o,
        values: u,
        rereduce: g
      });
      return {
        error: _
      };
    }
  }
  function sortByKeyThenValue(s, r) {
    const o = collate(s.key, r.key);
    return 0 !== o ? o : collate(s.value, r.value);
  }
  function sliceResults(s, r, o) {
    o = o || 0;
    if ("number" == typeof r) return s.slice(o, r + o); else if (o > 0) return s.slice(o);
    return s;
  }
  function rowToDocId(s) {
    const r = s.value;
    return r && "object" == typeof r && r._id || s.id;
  }
  function postprocessAttachments(s) {
    return function(r) {
      if (s.include_docs && s.attachments && s.binary) (function readAttachmentsAsBlobOrBuffer2(s) {
        s.rows.forEach((function(s) {
          const r = s.doc && s.doc._attachments;
          if (r) Object.keys(r).forEach((function(s) {
            const o = r[s];
            r[s].data = b64ToBluffer(o.data, o.content_type);
          }));
        }));
      })(r);
      return r;
    };
  }
  function addHttpParam(s, r, o, u) {
    let g = r[s];
    if ("undefined" != typeof g) {
      if (u) g = encodeURIComponent(JSON.stringify(g));
      o.push(s + "=" + g);
    }
  }
  function coerceInteger(s) {
    if ("undefined" != typeof s) {
      const r = Number(s);
      if (!isNaN(r) && r === parseInt(s, 10)) return r; else return s;
    }
  }
  function checkQueryParseError(s, r) {
    const o = s.descending ? "endkey" : "startkey", u = s.descending ? "startkey" : "endkey";
    if ("undefined" != typeof s[o] && "undefined" != typeof s[u] && collate(s[o], s[u]) > 0) throw new QueryParseError("No rows can match your key range, reverse your start_key and end_key or set {descending : true}"); else if (r.reduce && false !== s.reduce) if (s.include_docs) throw new QueryParseError("{include_docs:true} is invalid for reduce"); else if (s.keys && s.keys.length > 1 && !s.group && !s.group_level) throw new QueryParseError("Multi-key fetches for reduce views must use {group: true}");
    [ "group_level", "limit", "skip" ].forEach((function(r) {
      const o = function checkPositiveInteger(s) {
        if (s) {
          if ("number" != typeof s) return new QueryParseError(`Invalid value for integer: "${s}"`);
          if (s < 0) return new QueryParseError(`Invalid value for positive integer: "${s}"`);
        }
      }(s[r]);
      if (o) throw o;
    }));
  }
  function defaultsTo(s) {
    return function(r) {
      if (404 === r.status) return s; else throw r;
    };
  }
  function getQueue(s) {
    const r = "string" == typeof s ? s : s.name;
    let o = persistentQueues[r];
    if (!o) o = persistentQueues[r] = new TaskQueue2;
    return o;
  }
  async function updateView(s, o) {
    return sequentialize(getQueue(s), (function() {
      return async function updateViewInQueue(s, o) {
        let u, g, _;
        const m = r(s.mapFun, (function emit2(s, r) {
          const o = {
            id: g._id,
            key: normalizeKey(s)
          };
          if ("undefined" != typeof r && null !== r) o.value = normalizeKey(r);
          u.push(o);
        }));
        let b = s.seq || 0, E = 0;
        const w = {
          view: s.name,
          indexed_docs: E
        };
        s.sourceDB.emit("indexing", w);
        const S = new TaskQueue2;
        function createIndexableKeysToKeyValues(s) {
          const r = new ExportedMap;
          let o;
          for (let u = 0, g = s.length; u < g; u++) {
            const g = s[u], _ = [ g.key, g.id ];
            if (u > 0 && 0 === collate(g.key, o)) _.push(u);
            r.set(toIndexableString(_), g);
            o = g.key;
          }
          return r;
        }
        try {
          await function createTask() {
            return s.sourceDB.info().then((function(r) {
              _ = s.sourceDB.activeTasks.add({
                name: "view_indexing",
                total_items: r.update_seq - b
              });
            }));
          }();
          await async function processNextBatch() {
            return function processBatch(r, w) {
              var L = r.results;
              if (!L.length && !w.length) return;
              for (let s of w) if (L.findIndex((function(r) {
                return r.id === s.docId;
              })) < 0) {
                const r = {
                  _id: s.docId,
                  doc: {
                    _id: s.docId,
                    _deleted: 1
                  },
                  changes: []
                };
                if (s.doc) {
                  r.doc = s.doc;
                  r.changes.push({
                    rev: s.doc._rev
                  });
                }
                L.push(r);
              }
              var O = function createDocIdsToChangesAndEmits(r) {
                const o = new ExportedMap;
                for (let _ = 0, E = r.length; _ < E; _++) {
                  const E = r[_];
                  if ("_" !== E.doc._id[0]) {
                    u = [];
                    g = E.doc;
                    if (!g._deleted) tryMap(s.sourceDB, m, g);
                    u.sort(sortByKeyThenValue);
                    const r = createIndexableKeysToKeyValues(u);
                    o.set(E.doc._id, [ r, E.changes ]);
                  }
                  b = E.seq;
                }
                return o;
              }(L);
              S.add(function processChange2(r, o) {
                return function() {
                  return function saveKeyValues(s, r, o) {
                    var u = "_local/lastSeq";
                    return s.db.get(u).catch(defaultsTo({
                      _id: u,
                      seq: 0
                    })).then((function(u) {
                      var g = mapToKeysArray(r);
                      return Promise.all(g.map((function(o) {
                        return async function getDocsToPersist(s, r, o) {
                          const u = "_local/doc_" + s, g = {
                            _id: u,
                            keys: []
                          }, _ = o.get(s), m = _[0], b = _[1], E = await function getMetaDoc() {
                            if (isGenOne(b)) return Promise.resolve(g); else return r.db.get(u).catch(defaultsTo(g));
                          }();
                          return function processKeyValueDocs(s, r) {
                            const o = [], u = new ExportedSet;
                            for (let s = 0, g = r.rows.length; s < g; s++) {
                              const g = r.rows[s].doc;
                              if (g) {
                                o.push(g);
                                u.add(g._id);
                                g._deleted = !m.has(g._id);
                                if (!g._deleted) {
                                  const s = m.get(g._id);
                                  if ("value" in s) g.value = s.value;
                                }
                              }
                            }
                            const g = mapToKeysArray(m);
                            g.forEach((function(s) {
                              if (!u.has(s)) {
                                const r = {
                                  _id: s
                                }, u = m.get(s);
                                if ("value" in u) r.value = u.value;
                                o.push(r);
                              }
                            }));
                            s.keys = uniq(g.concat(s.keys));
                            o.push(s);
                            return o;
                          }(E, await function getKeyValueDocs(s) {
                            if (!s.keys.length) return Promise.resolve({
                              rows: []
                            }); else return r.db.allDocs({
                              keys: s.keys,
                              include_docs: true
                            });
                          }(E));
                        }(o, s, r);
                      }))).then((function(r) {
                        var g = flatten(r);
                        u.seq = o;
                        g.push(u);
                        return s.db.bulkDocs({
                          docs: g
                        });
                      })).then((() => function updatePurgeSeq(s) {
                        return s.sourceDB.get("_local/purges").then((function(r) {
                          const o = r.purgeSeq;
                          return s.db.get("_local/purgeSeq").then((function(s) {
                            return s._rev;
                          })).catch((function(s) {
                            if (404 !== s.status) throw s;
                          })).then((function(r) {
                            return s.db.put({
                              _id: "_local/purgeSeq",
                              _rev: r,
                              purgeSeq: o
                            });
                          }));
                        })).catch((function(s) {
                          if (404 !== s.status) throw s;
                        }));
                      }(s)));
                    }));
                  }(s, r, o);
                };
              }(O, b));
              E += L.length;
              const D = {
                view: s.name,
                last_seq: r.last_seq,
                results_count: L.length,
                indexed_docs: E
              };
              s.sourceDB.emit("indexing", D);
              s.sourceDB.activeTasks.update(_, {
                completed_items: E
              });
              if (!(L.length < o.changes_batch_size)) return processNextBatch(); else return;
            }(await s.sourceDB.changes({
              return_docs: true,
              conflicts: true,
              include_docs: true,
              style: "all_docs",
              since: b,
              limit: o.changes_batch_size
            }), await function getRecentPurges() {
              return s.db.get("_local/purgeSeq").then((function(s) {
                return s.purgeSeq;
              })).catch((function(s) {
                if (s && 404 !== s.status) throw s;
                return -1;
              })).then((function(r) {
                return s.sourceDB.get("_local/purges").then((function(o) {
                  const u = o.purges.filter((function(s, o) {
                    return o > r;
                  })).map((s => s.docId)), g = u.filter((function(s, r) {
                    return u.indexOf(s) === r;
                  }));
                  return Promise.all(g.map((function(r) {
                    return s.sourceDB.get(r).then((function(s) {
                      return {
                        docId: r,
                        doc: s
                      };
                    })).catch((function(s) {
                      if (404 !== s.status) throw s;
                      return {
                        docId: r
                      };
                    }));
                  })));
                })).catch((function(s) {
                  if (s && 404 !== s.status) throw s;
                  return [];
                }));
              }));
            }());
          }();
          await S.finish();
          s.seq = b;
          s.sourceDB.activeTasks.remove(_);
        } catch (r) {
          s.sourceDB.activeTasks.remove(_, r);
        }
      }(s, o);
    }))();
  }
  function queryView(s, r) {
    return sequentialize(getQueue(s), (function() {
      return async function queryViewInQueue(s, r) {
        let u;
        const g = s.reduceFun && false !== r.reduce, _ = r.skip || 0;
        if ("undefined" != typeof r.keys && !r.keys.length) {
          r.limit = 0;
          delete r.keys;
        }
        async function fetchFromView(r) {
          r.include_docs = true;
          const o = await s.db.allDocs(r);
          u = o.total_rows;
          return o.rows.map((function(s) {
            if ("value" in s.doc && "object" == typeof s.doc.value && null !== s.doc.value) {
              const r = Object.keys(s.doc.value).sort(), o = [ "id", "key", "value" ];
              if (!(r < o || r > o)) return s.doc.value;
            }
            const r = parseIndexableString(s.doc._id);
            return {
              key: r[0],
              id: r[1],
              value: "value" in s.doc ? s.doc.value : null
            };
          }));
        }
        async function onMapResultsReady(m) {
          let b;
          if (g) b = function reduceView(s, r, u) {
            if (0 === u.group_level) delete u.group_level;
            const g = u.group || u.group_level, _ = o(s.reduceFun), m = [], b = isNaN(u.group_level) ? Number.POSITIVE_INFINITY : u.group_level;
            r.forEach((function(s) {
              const r = m[m.length - 1];
              let o = g ? s.key : null;
              if (g && Array.isArray(o)) o = o.slice(0, b);
              if (!r || 0 !== collate(r.groupKey, o)) m.push({
                keys: [ [ s.key, s.id ] ],
                values: [ s.value ],
                groupKey: o
              }); else {
                r.keys.push([ s.key, s.id ]);
                r.values.push(s.value);
              }
            }));
            r = [];
            for (let o = 0, u = m.length; o < u; o++) {
              const u = m[o], g = tryReduce(s.sourceDB, _, u.keys, u.values, false);
              if (g.error && g.error instanceof BuiltInError) throw g.error;
              r.push({
                value: g.error ? null : g.output,
                key: u.groupKey
              });
            }
            return {
              rows: sliceResults(r, u.limit, u.skip)
            };
          }(s, m, r); else if ("undefined" == typeof r.keys) b = {
            total_rows: u,
            offset: _,
            rows: m
          }; else b = {
            total_rows: u,
            offset: _,
            rows: sliceResults(m, r.limit, r.skip)
          };
          if (r.update_seq) b.update_seq = s.seq;
          if (r.include_docs) {
            const o = uniq(m.map(rowToDocId)), u = await s.sourceDB.allDocs({
              keys: o,
              include_docs: true,
              conflicts: r.conflicts,
              attachments: r.attachments,
              binary: r.binary
            });
            var E = new ExportedMap;
            u.rows.forEach((function(s) {
              E.set(s.id, s.doc);
            }));
            m.forEach((function(s) {
              var r = rowToDocId(s), o = E.get(r);
              if (o) s.doc = o;
            }));
            return b;
          } else return b;
        }
        if ("undefined" != typeof r.keys) {
          const s = r.keys.map((function(s) {
            const o = {
              startkey: toIndexableString([ s ]),
              endkey: toIndexableString([ s, {} ])
            };
            if (r.update_seq) o.update_seq = true;
            return fetchFromView(o);
          }));
          return onMapResultsReady(flatten(await Promise.all(s)));
        } else {
          const s = {
            descending: r.descending
          };
          if (r.update_seq) s.update_seq = true;
          let o, u;
          if ("start_key" in r) o = r.start_key;
          if ("startkey" in r) o = r.startkey;
          if ("end_key" in r) u = r.end_key;
          if ("endkey" in r) u = r.endkey;
          if ("undefined" != typeof o) s.startkey = r.descending ? toIndexableString([ o, {} ]) : toIndexableString([ o ]);
          if ("undefined" != typeof u) {
            let o = false !== r.inclusive_end;
            if (r.descending) o = !o;
            s.endkey = toIndexableString(o ? [ u, {} ] : [ u ]);
          }
          if ("undefined" != typeof r.key) {
            const o = toIndexableString([ r.key ]), u = toIndexableString([ r.key, {} ]);
            if (s.descending) {
              s.endkey = o;
              s.startkey = u;
            } else {
              s.startkey = o;
              s.endkey = u;
            }
          }
          if (!g) {
            if ("number" == typeof r.limit) s.limit = r.limit;
            s.skip = _;
          }
          return onMapResultsReady(await fetchFromView(s));
        }
      }(s, r);
    }))();
  }
  return {
    query: function abstractQuery(r, o, g) {
      const _ = this;
      if ("function" == typeof o) {
        g = o;
        o = {};
      }
      o = o ? function coerceOptions(s) {
        s.group_level = coerceInteger(s.group_level);
        s.limit = coerceInteger(s.limit);
        s.skip = coerceInteger(s.skip);
        return s;
      }(o) : {};
      if ("function" == typeof r) r = {
        map: r
      };
      const m = Promise.resolve().then((function() {
        return async function queryPromised(r, o, g) {
          if ("function" == typeof r._query) return function customQuery(s, r, o) {
            return new Promise((function(u, g) {
              s._query(r, o, (function(s, r) {
                if (s) return g(s);
                u(r);
              }));
            }));
          }(r, o, g);
          if (isRemote(r)) return async function httpQuery(s, r, o) {
            let u, g, _ = [], m = "GET";
            addHttpParam("reduce", o, _);
            addHttpParam("include_docs", o, _);
            addHttpParam("attachments", o, _);
            addHttpParam("limit", o, _);
            addHttpParam("descending", o, _);
            addHttpParam("group", o, _);
            addHttpParam("group_level", o, _);
            addHttpParam("skip", o, _);
            addHttpParam("stale", o, _);
            addHttpParam("conflicts", o, _);
            addHttpParam("startkey", o, _, true);
            addHttpParam("start_key", o, _, true);
            addHttpParam("endkey", o, _, true);
            addHttpParam("end_key", o, _, true);
            addHttpParam("inclusive_end", o, _);
            addHttpParam("key", o, _, true);
            addHttpParam("update_seq", o, _);
            _ = _.join("&");
            _ = "" === _ ? "" : "?" + _;
            if ("undefined" != typeof o.keys) {
              const s = 2e3, g = `keys=${encodeURIComponent(JSON.stringify(o.keys))}`;
              if (g.length + _.length + 1 <= s) _ += ("?" === _[0] ? "&" : "?") + g; else {
                m = "POST";
                if ("string" == typeof r) u = {
                  keys: o.keys
                }; else r.keys = o.keys;
              }
            }
            if ("string" == typeof r) {
              const b = parseViewName(r), E = await s.fetch("_design/" + b[0] + "/_view/" + b[1] + _, {
                headers: new h({
                  "Content-Type": "application/json"
                }),
                method: m,
                body: JSON.stringify(u)
              });
              g = E.ok;
              const w = await E.json();
              if (!g) {
                w.status = E.status;
                throw generateErrorFromResponse(w);
              }
              w.rows.forEach((function(s) {
                if (s.value && s.value.error && "builtin_reduce_error" === s.value.error) throw new Error(s.reason);
              }));
              return new Promise((function(s) {
                s(w);
              })).then(postprocessAttachments(o));
            }
            u = u || {};
            Object.keys(r).forEach((function(s) {
              if (Array.isArray(r[s])) u[s] = r[s]; else u[s] = r[s].toString();
            }));
            const b = await s.fetch("_temp_view" + _, {
              headers: new h({
                "Content-Type": "application/json"
              }),
              method: "POST",
              body: JSON.stringify(u)
            });
            g = b.ok;
            const E = await b.json();
            if (!g) {
              E.status = b.status;
              throw generateErrorFromResponse(E);
            }
            return new Promise((function(s) {
              s(E);
            })).then(postprocessAttachments(o));
          }(r, o, g);
          const _ = {
            changes_batch_size: r.__opts.view_update_changes_batch_size || CHANGES_BATCH_SIZE2
          };
          if ("string" != typeof o) {
            checkQueryParseError(g, o);
            tempViewQueue.add((async function() {
              const u = await createView(r, "temp_view/temp_view", o.map, o.reduce, true, s);
              return fin(updateView(u, _).then((function() {
                return queryView(u, g);
              })), (function() {
                return u.db.destroy();
              }));
            }));
            return tempViewQueue.finish();
          } else {
            const m = o, b = parseViewName(m), E = b[0], w = b[1], S = await r.get("_design/" + E);
            if (!(o = S.views && S.views[w])) throw new NotFoundError(`ddoc ${S._id} has no view named ${w}`);
            u(S, w);
            checkQueryParseError(g, o);
            const L = await createView(r, m, o.map, o.reduce, false, s);
            if ("ok" === g.stale || "update_after" === g.stale) {
              if ("update_after" === g.stale) (0, import_immediate.default)((function() {
                updateView(L, _);
              }));
              return queryView(L, g);
            } else {
              await updateView(L, _);
              return queryView(L, g);
            }
          }
        }(_, r, o);
      }));
      promisedCallback(m, g);
      return m;
    },
    viewCleanup: callbackify((function() {
      const r = this;
      if ("function" == typeof r._viewCleanup) return function customViewCleanup(s) {
        return new Promise((function(r, o) {
          s._viewCleanup((function(s, u) {
            if (s) return o(s);
            r(u);
          }));
        }));
      }(r);
      if (isRemote(r)) return async function httpViewCleanup(s) {
        return (await s.fetch("_view_cleanup", {
          headers: new h({
            "Content-Type": "application/json"
          }),
          method: "POST"
        })).json();
      }(r); else return async function localViewCleanup(r) {
        try {
          const o = await r.get("_local/" + s), u = new ExportedMap;
          Object.keys(o.views).forEach((function(s) {
            const r = parseViewName(s), o = "_design/" + r[0], g = r[1];
            let _ = u.get(o);
            if (!_) {
              _ = new ExportedSet;
              u.set(o, _);
            }
            _.add(g);
          }));
          const g = {
            keys: mapToKeysArray(u),
            include_docs: true
          }, _ = await r.allDocs(g), m = {};
          _.rows.forEach((function(s) {
            const r = s.key.substring(8);
            u.get(s.key).forEach((function(u) {
              let g = r + "/" + u;
              if (!o.views[g]) g = u;
              const _ = Object.keys(o.views[g]), b = s.doc && s.doc.views && s.doc.views[u];
              _.forEach((function(s) {
                m[s] = m[s] || b;
              }));
            }));
          }));
          const b = Object.keys(m).filter((function(s) {
            return !m[s];
          })).map((function(s) {
            return sequentialize(getQueue(s), (function() {
              return new r.constructor(s, r.__opts).destroy();
            }))();
          }));
          return Promise.all(b).then((function() {
            return {
              ok: true
            };
          }));
        } catch (s) {
          if (404 === s.status) return {
            ok: true
          }; else throw s;
        }
      }(r);
    }))
  };
}

var index_es_default5 = createAbstractMapReduce;

function createBuiltInError(s) {
  return new BuiltInError("builtin " + s + " function requires map values to be numbers or number arrays");
}

function sum(s) {
  for (var r = 0, o = 0, u = s.length; o < u; o++) {
    var g = s[o];
    if ("number" != typeof g) if (Array.isArray(g)) {
      r = "number" == typeof r ? [ r ] : r;
      for (var _ = 0, m = g.length; _ < m; _++) {
        var b = g[_];
        if ("number" != typeof b) throw createBuiltInError("_sum"); else if ("undefined" == typeof r[_]) r.push(b); else r[_] += b;
      }
    } else throw createBuiltInError("_sum"); else if ("number" == typeof r) r += g; else r[0] += g;
  }
  return r;
}

var log = guardedConsole.bind(null, "log"), isArray = Array.isArray, toJSON = JSON.parse;

function evalFunctionWithEval(s, r) {
  return scopeEval("return (" + s.replace(/;\s*$/, "") + ");", {
    emit: r,
    sum,
    log,
    isArray,
    toJSON
  });
}

var builtInReduce = {
  _sum: function(s, r) {
    return sum(r);
  },
  _count: function(s, r) {
    return r.length;
  },
  _stats: function(s, r) {
    return {
      sum: sum(r),
      min: Math.min.apply(null, r),
      max: Math.max.apply(null, r),
      count: r.length,
      sumsqr: function sumsqr(s) {
        for (var r = 0, o = 0, u = s.length; o < u; o++) {
          var g = s[o];
          r += g * g;
        }
        return r;
      }(r)
    };
  }
};

function getBuiltIn(s) {
  if (/^_sum/.test(s)) return builtInReduce._sum; else if (/^_count/.test(s)) return builtInReduce._count; else if (/^_stats/.test(s)) return builtInReduce._stats; else if (/^_/.test(s)) throw new Error(s + " is not a supported reduce function.");
}

function mapper(s, r) {
  if ("function" == typeof s && 2 === s.length) {
    var o = s;
    return function(s) {
      return o(s, r);
    };
  } else return evalFunctionWithEval(s.toString(), r);
}

function reducer(s) {
  var r = s.toString(), o = getBuiltIn(r);
  if (o) return o; else return evalFunctionWithEval(r);
}

function ddocValidator(s, r) {
  var o = s.views && s.views[r];
  if ("string" != typeof o.map) throw new NotFoundError("ddoc " + s._id + " has no string view named " + r + ", instead found object of type: " + typeof o.map);
}

var localDocName = "mrviews", abstract = index_es_default5(localDocName, mapper, reducer, ddocValidator);

function query2(s, r, o) {
  return abstract.query.call(this, s, r, o);
}

function viewCleanup2(s) {
  return abstract.viewCleanup.call(this, s);
}

var index4 = {
  query: query2,
  viewCleanup: viewCleanup2
}, index_browser_es_default2 = index4, CHECKPOINT_VERSION = 1, REPLICATOR = "pouchdb", CHECKPOINT_HISTORY_SIZE = 5, LOWEST_SEQ = 0;

function updateCheckpoint(s, r, o, u, g) {
  return s.get(r).catch((function(o) {
    if (404 === o.status) {
      if ("http" === s.adapter || "https" === s.adapter) explainError(404, "PouchDB is just checking if a remote checkpoint exists.");
      return {
        session_id: u,
        _id: r,
        history: [],
        replicator: REPLICATOR,
        version: CHECKPOINT_VERSION
      };
    }
    throw o;
  })).then((function(_) {
    if (!g.cancelled) if (_.last_seq !== o) {
      _.history = (_.history || []).filter((function(s) {
        return s.session_id !== u;
      }));
      _.history.unshift({
        last_seq: o,
        session_id: u
      });
      _.history = _.history.slice(0, CHECKPOINT_HISTORY_SIZE);
      _.version = CHECKPOINT_VERSION;
      _.replicator = REPLICATOR;
      _.session_id = u;
      _.last_seq = o;
      return s.put(_).catch((function(_) {
        if (409 === _.status) return updateCheckpoint(s, r, o, u, g);
        throw _;
      }));
    }
  }));
}

var CheckpointerInternal = class {
  constructor(s, r, o, u, g) {
    this.src = s;
    this.target = r;
    this.id = o;
    this.returnValue = u;
    this.opts = g || {};
  }
  writeCheckpoint(s, r) {
    var o = this;
    return this.updateTarget(s, r).then((function() {
      return o.updateSource(s, r);
    }));
  }
  updateTarget(s, r) {
    if (this.opts.writeTargetCheckpoint) return updateCheckpoint(this.target, this.id, s, r, this.returnValue); else return Promise.resolve(true);
  }
  updateSource(s, r) {
    if (this.opts.writeSourceCheckpoint) {
      var o = this;
      return updateCheckpoint(this.src, this.id, s, r, this.returnValue).catch((function(s) {
        if (isForbiddenError(s)) {
          o.opts.writeSourceCheckpoint = false;
          return true;
        }
        throw s;
      }));
    } else return Promise.resolve(true);
  }
  getCheckpoint() {
    var s = this;
    if (s.opts && s.opts.writeSourceCheckpoint && !s.opts.writeTargetCheckpoint) return s.src.get(s.id).then((function(s) {
      return s.last_seq || LOWEST_SEQ;
    })).catch((function(s) {
      if (404 !== s.status) throw s;
      return LOWEST_SEQ;
    })); else return s.target.get(s.id).then((function(r) {
      if (s.opts && s.opts.writeTargetCheckpoint && !s.opts.writeSourceCheckpoint) return r.last_seq || LOWEST_SEQ; else return s.src.get(s.id).then((function(s) {
        if (r.version !== s.version) return LOWEST_SEQ;
        var o;
        if (r.version) o = r.version.toString(); else o = "undefined";
        if (o in comparisons) return comparisons[o](r, s); else return LOWEST_SEQ;
      }), (function(o) {
        if (404 === o.status && r.last_seq) return s.src.put({
          _id: s.id,
          last_seq: LOWEST_SEQ
        }).then((function() {
          return LOWEST_SEQ;
        }), (function(o) {
          if (isForbiddenError(o)) {
            s.opts.writeSourceCheckpoint = false;
            return r.last_seq;
          }
          return LOWEST_SEQ;
        }));
        throw o;
      }));
    })).catch((function(s) {
      if (404 !== s.status) throw s;
      return LOWEST_SEQ;
    }));
  }
}, comparisons = {
  undefined: function(s, r) {
    if (0 === collate(s.last_seq, r.last_seq)) return r.last_seq; else return 0;
  },
  1: function(s, r) {
    return compareReplicationLogs(r, s).last_seq;
  }
};

function compareReplicationLogs(s, r) {
  if (s.session_id === r.session_id) return {
    last_seq: s.last_seq,
    history: s.history
  }; else return compareReplicationHistory(s.history, r.history);
}

function compareReplicationHistory(s, r) {
  var o = s[0], u = s.slice(1), g = r[0], _ = r.slice(1);
  if (!o || 0 === r.length) return {
    last_seq: LOWEST_SEQ,
    history: []
  };
  if (hasSessionId(o.session_id, r)) return {
    last_seq: o.last_seq,
    history: s
  };
  if (hasSessionId(g.session_id, u)) return {
    last_seq: g.last_seq,
    history: _
  }; else return compareReplicationHistory(u, _);
}

function hasSessionId(s, r) {
  var o = r[0], u = r.slice(1);
  if (!s || 0 === r.length) return false;
  if (s === o.session_id) return true; else return hasSessionId(s, u);
}

function isForbiddenError(s) {
  return "number" == typeof s.status && 4 === Math.floor(s.status / 100);
}

function Checkpointer(s, r, o, u, g) {
  if (!(this instanceof CheckpointerInternal)) return new CheckpointerInternal(s, r, o, u, g); else return Checkpointer;
}

var index_es_default6 = Checkpointer;

function sortObjectPropertiesByKey(s) {
  return Object.keys(s).sort(collate).reduce((function(r, o) {
    r[o] = s[o];
    return r;
  }), {});
}

function generateReplicationId(s, r, o) {
  var u = o.doc_ids ? o.doc_ids.sort(collate) : "", g = o.filter ? o.filter.toString() : "", _ = "", m = "", b = "";
  if (o.selector) b = JSON.stringify(o.selector);
  if (o.filter && o.query_params) _ = JSON.stringify(sortObjectPropertiesByKey(o.query_params));
  if (o.filter && "_view" === o.filter) m = o.view.toString();
  return Promise.all([ s.id(), r.id() ]).then((function(s) {
    var r = s[0] + s[1] + g + m + _ + u + b;
    return new Promise((function(s) {
      binaryMd5(r, s);
    }));
  })).then((function(s) {
    return "_local/" + (s = s.replace(/\//g, ".").replace(/\+/g, "_"));
  }));
}

var index_es_default7 = generateReplicationId, import_events3 = __toESM(require_events());

function fileHasChanged(s, r, o) {
  return !s._attachments || !s._attachments[o] || s._attachments[o].digest !== r._attachments[o].digest;
}

function getDocAttachments(s, r) {
  var o = Object.keys(r._attachments);
  return Promise.all(o.map((function(o) {
    return s.getAttachment(r._id, o, {
      rev: r._rev
    });
  })));
}

function getDocAttachmentsFromTargetOrSource(s, r, o) {
  var u = isRemote(r) && !isRemote(s), g = Object.keys(o._attachments);
  if (!u) return getDocAttachments(r, o); else return s.get(o._id).then((function(u) {
    return Promise.all(g.map((function(g) {
      if (fileHasChanged(u, o, g)) return r.getAttachment(o._id, g); else return s.getAttachment(u._id, g);
    })));
  })).catch((function(s) {
    if (404 !== s.status) throw s;
    return getDocAttachments(r, o);
  }));
}

function createBulkGetOpts(s) {
  var r = [];
  Object.keys(s).forEach((function(o) {
    s[o].missing.forEach((function(s) {
      r.push({
        id: o,
        rev: s
      });
    }));
  }));
  return {
    docs: r,
    revs: true,
    latest: true
  };
}

function getDocs(s, r, o, u) {
  o = clone(o);
  var g = [], _ = true;
  return Promise.resolve().then((function getAllDocs() {
    var m = createBulkGetOpts(o);
    if (m.docs.length) return s.bulkGet(m).then((function(o) {
      if (u.cancelled) throw new Error("cancelled");
      return Promise.all(o.results.map((function(o) {
        return Promise.all(o.docs.map((function(o) {
          var u = o.ok;
          if (o.error) _ = false;
          if (!u || !u._attachments) return u; else return getDocAttachmentsFromTargetOrSource(r, s, u).then((function(s) {
            var r = Object.keys(u._attachments);
            s.forEach((function(s, o) {
              var g = u._attachments[r[o]];
              delete g.stub;
              delete g.length;
              g.data = s;
            }));
            return u;
          }));
        })));
      }))).then((function(s) {
        g = g.concat(flatten(s).filter(Boolean));
      }));
    }));
  })).then((function returnResult() {
    return {
      ok: _,
      docs: g
    };
  }));
}

var STARTING_BACK_OFF = 0;

function backOff(s, r, o, u) {
  if (false !== s.retry) {
    if ("function" != typeof s.back_off_function) s.back_off_function = defaultBackOff;
    r.emit("requestError", o);
    if ("active" === r.state || "pending" === r.state) {
      r.emit("paused", o);
      r.state = "stopped";
      var g = function backoffTimeSet() {
        s.current_back_off = STARTING_BACK_OFF;
      };
      r.once("paused", (function removeBackOffTimeSet() {
        r.removeListener("active", g);
      }));
      r.once("active", g);
    }
    s.current_back_off = s.current_back_off || STARTING_BACK_OFF;
    s.current_back_off = s.back_off_function(s.current_back_off);
    setTimeout(u, s.current_back_off);
  } else {
    r.emit("error", o);
    r.removeAllListeners();
  }
}

function replicate(s, r, o, u, g) {
  var _, m, b, E, w = [], S = {
    seq: 0,
    changes: [],
    docs: []
  }, L = false, O = false, D = false, C = 0, k = 0, T = o.continuous || o.live || false, A = o.batch_size || 100, R = o.batches_limit || 10, I = o.style || "all_docs", x = false, P = o.doc_ids, N = o.selector, B = [], F = uuid();
  g = g || {
    ok: true,
    start_time: (new Date).toISOString(),
    docs_read: 0,
    docs_written: 0,
    doc_write_failures: 0,
    errors: []
  };
  var M = {};
  u.ready(s, r);
  function initCheckpointer() {
    if (b) return Promise.resolve(); else return index_es_default7(s, r, o).then((function(g) {
      m = g;
      var _ = {};
      if (false === o.checkpoint) _ = {
        writeSourceCheckpoint: false,
        writeTargetCheckpoint: false
      }; else if ("source" === o.checkpoint) _ = {
        writeSourceCheckpoint: true,
        writeTargetCheckpoint: false
      }; else if ("target" === o.checkpoint) _ = {
        writeSourceCheckpoint: false,
        writeTargetCheckpoint: true
      }; else _ = {
        writeSourceCheckpoint: true,
        writeTargetCheckpoint: true
      };
      b = new index_es_default6(s, r, m, u, _);
    }));
  }
  function writeDocs() {
    B = [];
    if (0 !== _.docs.length) {
      var s = _.docs, m = {
        timeout: o.timeout
      };
      return r.bulkDocs({
        docs: s,
        new_edits: false
      }, m).then((function(r) {
        if (u.cancelled) {
          completeReplication();
          throw new Error("cancelled");
        }
        var o = Object.create(null);
        r.forEach((function(s) {
          if (s.error) o[s.id] = s;
        }));
        var _ = Object.keys(o).length;
        g.doc_write_failures += _;
        g.docs_written += s.length - _;
        s.forEach((function(s) {
          var r = o[s._id];
          if (r) {
            g.errors.push(r);
            var _ = (r.name || "").toLowerCase();
            if ("unauthorized" === _ || "forbidden" === _) u.emit("denied", clone(r)); else throw r;
          } else B.push(s);
        }));
      }), (function(r) {
        g.doc_write_failures += s.length;
        throw r;
      }));
    }
  }
  function finishBatch() {
    if (_.error) throw new Error("There was a problem getting docs.");
    g.last_seq = k = _.seq;
    var r = clone(g);
    if (B.length) {
      r.docs = B;
      if ("number" == typeof _.pending) {
        r.pending = _.pending;
        delete _.pending;
      }
      u.emit("change", r);
    }
    L = true;
    s.info().then((function(r) {
      var o = s.activeTasks.get(E);
      if (_ && o) {
        var u = o.completed_items || 0, g = parseInt(r.update_seq, 10) - parseInt(C, 10);
        s.activeTasks.update(E, {
          completed_items: u + _.changes.length,
          total_items: g
        });
      }
    }));
    return b.writeCheckpoint(_.seq, F).then((function() {
      u.emit("checkpoint", {
        checkpoint: _.seq
      });
      L = false;
      if (u.cancelled) {
        completeReplication();
        throw new Error("cancelled");
      }
      _ = void 0;
      getChanges();
    })).catch((function(s) {
      onCheckpointError(s);
      throw s;
    }));
  }
  function getBatchDocs() {
    return getDocs(s, r, _.diffs, u).then((function(s) {
      _.error = !s.ok;
      s.docs.forEach((function(s) {
        delete _.diffs[s._id];
        g.docs_read++;
        _.docs.push(s);
      }));
    }));
  }
  function startNextBatch() {
    if (!u.cancelled && !_) if (0 !== w.length) {
      _ = w.shift();
      u.emit("checkpoint", {
        start_next_batch: _.seq
      });
      (function getDiffs() {
        var s = {};
        _.changes.forEach((function(r) {
          u.emit("checkpoint", {
            revs_diff: r
          });
          if ("_user/" !== r.id) s[r.id] = r.changes.map((function(s) {
            return s.rev;
          }));
        }));
        return r.revsDiff(s).then((function(s) {
          if (u.cancelled) {
            completeReplication();
            throw new Error("cancelled");
          }
          _.diffs = s;
        }));
      })().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch((function(s) {
        abortReplication("batch processing terminated with error", s);
      }));
    } else processPendingBatch(true);
  }
  function processPendingBatch(s) {
    if (0 !== S.changes.length) {
      if (s || O || S.changes.length >= A) {
        w.push(S);
        S = {
          seq: 0,
          changes: [],
          docs: []
        };
        if ("pending" === u.state || "stopped" === u.state) {
          u.state = "active";
          u.emit("active");
        }
        startNextBatch();
      }
    } else if (0 === w.length && !_) {
      if (T && M.live || O) {
        u.state = "pending";
        u.emit("paused");
      }
      if (O) completeReplication();
    }
  }
  function abortReplication(s, r) {
    if (!D) {
      if (!r.message) r.message = s;
      g.ok = false;
      g.status = "aborting";
      w = [];
      S = {
        seq: 0,
        changes: [],
        docs: []
      };
      completeReplication(r);
    }
  }
  function completeReplication(_) {
    if (!D) {
      if (u.cancelled) {
        g.status = "cancelled";
        if (L) return;
      }
      g.status = g.status || "complete";
      g.end_time = (new Date).toISOString();
      g.last_seq = k;
      D = true;
      s.activeTasks.remove(E, _);
      if (_) {
        (_ = createError(_)).result = g;
        var m = (_.name || "").toLowerCase();
        if ("unauthorized" === m || "forbidden" === m) {
          u.emit("error", _);
          u.removeAllListeners();
        } else backOff(o, u, _, (function() {
          replicate(s, r, o, u);
        }));
      } else {
        u.emit("complete", g);
        u.removeAllListeners();
      }
    }
  }
  function onChange(r, g, _) {
    if (u.cancelled) return completeReplication();
    if ("number" == typeof g) S.pending = g;
    if (filterChange(o)(r)) {
      S.seq = r.seq || _;
      S.changes.push(r);
      u.emit("checkpoint", {
        pending_batch: S.seq
      });
      (0, import_immediate.default)((function() {
        processPendingBatch(0 === w.length && M.live);
      }));
    } else {
      var m = s.activeTasks.get(E);
      if (m) {
        var b = m.completed_items || 0;
        s.activeTasks.update(E, {
          completed_items: ++b
        });
      }
    }
  }
  function onChangesComplete(s) {
    x = false;
    if (u.cancelled) return completeReplication();
    if (s.results.length > 0) {
      M.since = s.results[s.results.length - 1].seq;
      getChanges();
      processPendingBatch(true);
    } else {
      var complete = function() {
        if (T) {
          M.live = true;
          getChanges();
        } else O = true;
        processPendingBatch(true);
      };
      if (!_ && 0 === s.results.length) {
        L = true;
        b.writeCheckpoint(s.last_seq, F).then((function() {
          L = false;
          g.last_seq = k = s.last_seq;
          if (u.cancelled) {
            completeReplication();
            throw new Error("cancelled");
          } else complete();
        })).catch(onCheckpointError);
      } else complete();
    }
  }
  function onChangesError(s) {
    x = false;
    if (u.cancelled) return completeReplication();
    abortReplication("changes rejected", s);
  }
  function getChanges() {
    if (!x && !O && w.length < R) {
      x = true;
      if (u._changes) {
        u.removeListener("cancel", u._abortChanges);
        u._changes.cancel();
      }
      u.once("cancel", abortChanges);
      var r = s.changes(M).on("change", onChange);
      r.then(removeListener, removeListener);
      r.then(onChangesComplete).catch(onChangesError);
      if (o.retry) {
        u._changes = r;
        u._abortChanges = abortChanges;
      }
    }
    function abortChanges() {
      r.cancel();
    }
    function removeListener() {
      u.removeListener("cancel", abortChanges);
    }
  }
  function createTask(r) {
    return s.info().then((function(u) {
      var g = "undefined" == typeof o.since ? parseInt(u.update_seq, 10) - parseInt(r, 10) : parseInt(u.update_seq, 10);
      E = s.activeTasks.add({
        name: `${T ? "continuous " : ""}replication from ${u.db_name}`,
        total_items: g
      });
      return r;
    }));
  }
  function startChanges() {
    initCheckpointer().then((function() {
      if (!u.cancelled) return b.getCheckpoint().then(createTask).then((function(s) {
        C = s;
        M = {
          since: k = s,
          limit: A,
          batch_size: A,
          style: I,
          doc_ids: P,
          selector: N,
          return_docs: true
        };
        if (o.filter) if ("string" != typeof o.filter) M.include_docs = true; else M.filter = o.filter;
        if ("heartbeat" in o) M.heartbeat = o.heartbeat;
        if ("timeout" in o) M.timeout = o.timeout;
        if (o.query_params) M.query_params = o.query_params;
        if (o.view) M.view = o.view;
        getChanges();
      })); else completeReplication();
    })).catch((function(s) {
      abortReplication("getCheckpoint rejected with ", s);
    }));
  }
  function onCheckpointError(s) {
    L = false;
    abortReplication("writeCheckpoint completed with error", s);
  }
  if (!u.cancelled) {
    if (!u._addedListeners) {
      u.once("cancel", completeReplication);
      if ("function" == typeof o.complete) {
        u.once("error", o.complete);
        u.once("complete", (function(s) {
          o.complete(null, s);
        }));
      }
      u._addedListeners = true;
    }
    if ("undefined" == typeof o.since) startChanges(); else initCheckpointer().then((function() {
      L = true;
      return b.writeCheckpoint(o.since, F);
    })).then((function() {
      L = false;
      if (!u.cancelled) {
        k = o.since;
        startChanges();
      } else completeReplication();
    })).catch(onCheckpointError);
  } else completeReplication();
}

var Replication = class extends import_events3.default {
  constructor() {
    super();
    this.cancelled = false;
    this.state = "pending";
    const s = new Promise(((s, r) => {
      this.once("complete", s);
      this.once("error", r);
    }));
    this.then = function(r, o) {
      return s.then(r, o);
    };
    this.catch = function(r) {
      return s.catch(r);
    };
    this.catch((function() {}));
  }
  cancel() {
    this.cancelled = true;
    this.state = "cancelled";
    this.emit("cancel");
  }
  ready(s, r) {
    if (this._readyCalled) return;
    this._readyCalled = true;
    const onDestroy2 = () => {
      this.cancel();
    };
    s.once("destroyed", onDestroy2);
    r.once("destroyed", onDestroy2);
    function cleanup() {
      s.removeListener("destroyed", onDestroy2);
      r.removeListener("destroyed", onDestroy2);
    }
    this.once("complete", cleanup);
    this.once("error", cleanup);
  }
};

function toPouch(s, r) {
  var o = r.PouchConstructor;
  if ("string" == typeof s) return new o(s, r); else return s;
}

function replicateWrapper(s, r, o, u) {
  if ("function" == typeof o) {
    u = o;
    o = {};
  }
  if ("undefined" == typeof o) o = {};
  if (o.doc_ids && !Array.isArray(o.doc_ids)) throw createError(BAD_REQUEST, "`doc_ids` filter parameter is not a list.");
  o.complete = u;
  (o = clone(o)).continuous = o.continuous || o.live;
  o.retry = "retry" in o ? o.retry : false;
  o.PouchConstructor = o.PouchConstructor || this;
  var g = new Replication(o);
  replicate(toPouch(s, o), toPouch(r, o), o, g);
  return g;
}

function sync(s, r, o, u) {
  if ("function" == typeof o) {
    u = o;
    o = {};
  }
  if ("undefined" == typeof o) o = {};
  (o = clone(o)).PouchConstructor = o.PouchConstructor || this;
  s = toPouch(s, o);
  r = toPouch(r, o);
  return new Sync(s, r, o, u);
}

var Sync = class extends import_events3.default {
  constructor(s, r, o, u) {
    super();
    this.canceled = false;
    const g = o.push ? assign$2({}, o, o.push) : o, _ = o.pull ? assign$2({}, o, o.pull) : o;
    this.push = replicateWrapper(s, r, g);
    this.pull = replicateWrapper(r, s, _);
    this.pushPaused = true;
    this.pullPaused = true;
    const pullChange = s => {
      this.emit("change", {
        direction: "pull",
        change: s
      });
    }, pushChange = s => {
      this.emit("change", {
        direction: "push",
        change: s
      });
    }, pushDenied = s => {
      this.emit("denied", {
        direction: "push",
        doc: s
      });
    }, pullDenied = s => {
      this.emit("denied", {
        direction: "pull",
        doc: s
      });
    }, pushPaused = () => {
      this.pushPaused = true;
      if (this.pullPaused) this.emit("paused");
    }, pullPaused = () => {
      this.pullPaused = true;
      if (this.pushPaused) this.emit("paused");
    }, pushActive = () => {
      this.pushPaused = false;
      if (this.pullPaused) this.emit("active", {
        direction: "push"
      });
    }, pullActive = () => {
      this.pullPaused = false;
      if (this.pushPaused) this.emit("active", {
        direction: "pull"
      });
    };
    let m = {};
    const removeAll = s => (r, o) => {
      if ("change" === r && (o === pullChange || o === pushChange) || "denied" === r && (o === pullDenied || o === pushDenied) || "paused" === r && (o === pullPaused || o === pushPaused) || "active" === r && (o === pullActive || o === pushActive)) {
        if (!(r in m)) m[r] = {};
        m[r][s] = true;
        if (2 === Object.keys(m[r]).length) this.removeAllListeners(r);
      }
    };
    if (o.live) {
      this.push.on("complete", this.pull.cancel.bind(this.pull));
      this.pull.on("complete", this.push.cancel.bind(this.push));
    }
    function addOneListener(s, r, o) {
      if (-1 == s.listeners(r).indexOf(o)) s.on(r, o);
    }
    this.on("newListener", (function(s) {
      if ("change" === s) {
        addOneListener(this.pull, "change", pullChange);
        addOneListener(this.push, "change", pushChange);
      } else if ("denied" === s) {
        addOneListener(this.pull, "denied", pullDenied);
        addOneListener(this.push, "denied", pushDenied);
      } else if ("active" === s) {
        addOneListener(this.pull, "active", pullActive);
        addOneListener(this.push, "active", pushActive);
      } else if ("paused" === s) {
        addOneListener(this.pull, "paused", pullPaused);
        addOneListener(this.push, "paused", pushPaused);
      }
    }));
    this.on("removeListener", (function(s) {
      if ("change" === s) {
        this.pull.removeListener("change", pullChange);
        this.push.removeListener("change", pushChange);
      } else if ("denied" === s) {
        this.pull.removeListener("denied", pullDenied);
        this.push.removeListener("denied", pushDenied);
      } else if ("active" === s) {
        this.pull.removeListener("active", pullActive);
        this.push.removeListener("active", pushActive);
      } else if ("paused" === s) {
        this.pull.removeListener("paused", pullPaused);
        this.push.removeListener("paused", pushPaused);
      }
    }));
    this.pull.on("removeListener", removeAll("pull"));
    this.push.on("removeListener", removeAll("push"));
    const b = Promise.all([ this.push, this.pull ]).then((s => {
      const r = {
        push: s[0],
        pull: s[1]
      };
      this.emit("complete", r);
      if (u) u(null, r);
      this.removeAllListeners();
      return r;
    }), (s => {
      this.cancel();
      if (u) u(s); else this.emit("error", s);
      this.removeAllListeners();
      if (u) throw s;
    }));
    this.then = function(s, r) {
      return b.then(s, r);
    };
    this.catch = function(s) {
      return b.catch(s);
    };
  }
  cancel() {
    if (!this.canceled) {
      this.canceled = true;
      this.push.cancel();
      this.pull.cancel();
    }
  }
};

function replication(s) {
  s.replicate = replicateWrapper;
  s.sync = sync;
  Object.defineProperty(s.prototype, "replicate", {
    get: function() {
      var s = this;
      if ("undefined" == typeof this.replicateMethods) this.replicateMethods = {
        from: function(r, o, u) {
          return s.constructor.replicate(r, s, o, u);
        },
        to: function(r, o, u) {
          return s.constructor.replicate(s, r, o, u);
        }
      };
      return this.replicateMethods;
    }
  });
  s.prototype.sync = function(s, r, o) {
    return this.constructor.sync(this, s, r, o);
  };
}

var index_es_default8 = replication;

function massageCreateIndexRequest(s) {
  if (!(s = clone(s)).index) s.index = {};
  [ "type", "name", "ddoc" ].forEach((function(r) {
    if (s.index[r]) {
      s[r] = s.index[r];
      delete s.index[r];
    }
  }));
  if (s.fields) {
    s.index.fields = s.fields;
    delete s.fields;
  }
  if (!s.type) s.type = "json";
  return s;
}

function checkFieldValueType(s, r, o) {
  var u = "", g = r, _ = true;
  if (-1 !== [ "$in", "$nin", "$or", "$and", "$mod", "$nor", "$all" ].indexOf(s)) if (!Array.isArray(r)) u = "Query operator " + s + " must be an array.";
  if (-1 !== [ "$not", "$elemMatch", "$allMatch" ].indexOf(s)) if (!(!Array.isArray(r) && "object" == typeof r && null !== r)) u = "Query operator " + s + " must be an object.";
  if ("$mod" === s && Array.isArray(r)) if (2 !== r.length) u = "Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers."; else {
    var m = r[0], b = r[1];
    if (0 === m) {
      u = "Query operator $mod's divisor cannot be 0, cannot divide by zero.";
      _ = false;
    }
    if ("number" != typeof m || parseInt(m, 10) !== m) {
      u = "Query operator $mod's divisor is not an integer.";
      g = m;
    }
    if (parseInt(b, 10) !== b) {
      u = "Query operator $mod's remainder is not an integer.";
      g = b;
    }
  }
  if ("$exists" === s) if ("boolean" != typeof r) u = "Query operator $exists must be a boolean.";
  if ("$type" === s) {
    var E = [ "null", "boolean", "number", "string", "array", "object" ], w = '"' + E.slice(0, E.length - 1).join('", "') + '", or "' + E[E.length - 1] + '"';
    if ("string" != typeof r) u = "Query operator $type must be a string. Supported values: " + w + "."; else if (-1 == E.indexOf(r)) u = "Query operator $type must be a string. Supported values: " + w + ".";
  }
  if ("$size" === s) if (parseInt(r, 10) !== r) u = "Query operator $size must be a integer.";
  if ("$regex" === s) if ("string" != typeof r) if (o) u = "Query operator $regex must be a string."; else if (!(r instanceof RegExp)) u = "Query operator $regex must be a string or an instance of a javascript regular expression.";
  if (u) {
    if (_) u += " Received" + (null === g ? " " : Array.isArray(g) ? " array" : " " + typeof g) + ": " + ("object" == typeof g && null !== g ? JSON.stringify(g, null, "\t") : g);
    throw new Error(u);
  }
}

var requireValidation = [ "$all", "$allMatch", "$and", "$elemMatch", "$exists", "$in", "$mod", "$nin", "$nor", "$not", "$or", "$regex", "$size", "$type" ], arrayTypeComparisonOperators = [ "$in", "$nin", "$mod", "$all" ], equalityOperators = [ "$eq", "$gt", "$gte", "$lt", "$lte" ];

function validateSelector(s, r) {
  if (Array.isArray(s)) {
    for (var o of s) if ("object" == typeof o && null !== m) validateSelector(o, r);
  } else for (var u = Object.keys(s), g = 0; g < u.length; g++) {
    var _ = u[g], m = s[_];
    if (-1 !== requireValidation.indexOf(_)) checkFieldValueType(_, m, r);
    if (-1 === equalityOperators.indexOf(_)) if (-1 === arrayTypeComparisonOperators.indexOf(_)) if ("object" == typeof m && null !== m) validateSelector(m, r);
  }
}

function dbFetch(s, r, o, u) {
  var g, _;
  o.headers = new h({
    "Content-type": "application/json"
  });
  s.fetch(r, o).then((function(s) {
    g = s.status;
    _ = s.ok;
    return s.json();
  })).then((function(s) {
    if (!_) {
      s.status = g;
      var r = generateErrorFromResponse(s);
      u(r);
    } else u(null, s);
  })).catch(u);
}

function createIndex(s, r, o) {
  r = massageCreateIndexRequest(r);
  dbFetch(s, "_index", {
    method: "POST",
    body: JSON.stringify(r)
  }, o);
}

function find(s, r, o) {
  validateSelector(r.selector, true);
  dbFetch(s, "_find", {
    method: "POST",
    body: JSON.stringify(r)
  }, o);
}

function explain(s, r, o) {
  dbFetch(s, "_explain", {
    method: "POST",
    body: JSON.stringify(r)
  }, o);
}

function getIndexes(s, r) {
  dbFetch(s, "_index", {
    method: "GET"
  }, r);
}

function deleteIndex(s, r, o) {
  var u = r.ddoc, g = r.type || "json", _ = r.name;
  if (!u) return o(new Error("you must provide an index's ddoc"));
  if (!_) return o(new Error("you must provide an index's name"));
  dbFetch(s, "_index/" + [ u, g, _ ].map(encodeURIComponent).join("/"), {
    method: "DELETE"
  }, o);
}

function callbackify2(s) {
  return function(...r) {
    var o = r.pop(), u = s.apply(this, r);
    promisedCallback2(u, o);
    return u;
  };
}

function promisedCallback2(s, r) {
  s.then((function(s) {
    (0, import_immediate.default)((function() {
      r(null, s);
    }));
  }), (function(s) {
    (0, import_immediate.default)((function() {
      r(s);
    }));
  }));
  return s;
}

var flatten2 = function(...s) {
  for (var r = [], o = 0, u = s.length; o < u; o++) {
    var g = s[o];
    if (Array.isArray(g)) r = r.concat(flatten2.apply(null, g)); else r.push(g);
  }
  return r;
};

function mergeObjects(s) {
  for (var r = {}, o = 0, u = s.length; o < u; o++) r = assign$2(r, s[o]);
  return r;
}

function pick2(s, r) {
  for (var o = {}, u = 0, g = r.length; u < g; u++) {
    var _ = parseField(r[u]), m = getFieldFromDoc(s, _);
    if ("undefined" != typeof m) setFieldInDoc(o, _, m);
  }
  return o;
}

function oneArrayIsSubArrayOfOther(s, r) {
  for (var o = 0, u = Math.min(s.length, r.length); o < u; o++) if (s[o] !== r[o]) return false;
  return true;
}

function oneArrayIsStrictSubArrayOfOther(s, r) {
  if (s.length > r.length) return false; else return oneArrayIsSubArrayOfOther(s, r);
}

function oneSetIsSubArrayOfOther(s, r) {
  s = s.slice();
  for (var o = 0, u = r.length; o < u; o++) {
    var g = r[o];
    if (!s.length) break;
    var _ = s.indexOf(g);
    if (-1 === _) return false; else s.splice(_, 1);
  }
  return true;
}

function arrayToObject(s) {
  for (var r = {}, o = 0, u = s.length; o < u; o++) r[s[o]] = true;
  return r;
}

function max(s, r) {
  for (var o = null, u = -1, g = 0, _ = s.length; g < _; g++) {
    var m = s[g], b = r(m);
    if (b > u) {
      u = b;
      o = m;
    }
  }
  return o;
}

function arrayEquals(s, r) {
  if (s.length !== r.length) return false;
  for (var o = 0, u = s.length; o < u; o++) if (s[o] !== r[o]) return false;
  return true;
}

function uniq2(s) {
  for (var r = {}, o = 0; o < s.length; o++) r["$" + s[o]] = true;
  return Object.keys(r).map((function(s) {
    return s.substring(1);
  }));
}

function createDeepMultiMapper(s, r, o) {
  return function(u) {
    if (!o || matchesSelector(u, o)) {
      for (var g = [], _ = 0, m = s.length; _ < m; _++) {
        for (var b = parseField(s[_]), E = u, w = 0, S = b.length; w < S; w++) if ("undefined" == typeof (E = E[b[w]])) return;
        g.push(E);
      }
      r(g);
    }
  };
}

function createDeepSingleMapper(s, r, o) {
  var u = parseField(s);
  return function(s) {
    if (!o || matchesSelector(s, o)) {
      for (var g = s, _ = 0, m = u.length; _ < m; _++) if ("undefined" == typeof (g = g[u[_]])) return;
      r(g);
    }
  };
}

function createShallowSingleMapper(s, r, o) {
  return function(u) {
    if (!o || matchesSelector(u, o)) r(u[s]);
  };
}

function createShallowMultiMapper(s, r, o) {
  return function(u) {
    if (!o || matchesSelector(u, o)) {
      for (var g = [], _ = 0, m = s.length; _ < m; _++) g.push(u[s[_]]);
      r(g);
    }
  };
}

function checkShallow(s) {
  for (var r = 0, o = s.length; r < o; r++) if (-1 !== s[r].indexOf(".")) return false;
  return true;
}

function createMapper(s, r, o) {
  var u = checkShallow(s), g = 1 === s.length;
  if (u) if (g) return createShallowSingleMapper(s[0], r, o); else return createShallowMultiMapper(s, r, o); else if (g) return createDeepSingleMapper(s[0], r, o); else return createDeepMultiMapper(s, r, o);
}

function mapper2(s, r) {
  return createMapper(Object.keys(s.fields), r, s.partial_filter_selector);
}

function reducer2() {
  throw new Error("reduce not supported");
}

function ddocValidator2(s, r) {
  var o = s.views[r];
  if (!o.map || !o.map.fields) throw new Error("ddoc " + s._id + " with view " + r + " doesn't have map.fields defined. maybe it wasn't created by this plugin?");
}

var abstractMapper = index_es_default5("indexes", mapper2, reducer2, ddocValidator2);

function abstractMapper$1(s) {
  if (s._customFindAbstractMapper) return {
    query: function addQueryFallback(r, o) {
      var u = abstractMapper.query.bind(this);
      return s._customFindAbstractMapper.query.call(this, r, o, u);
    },
    viewCleanup: function addViewCleanupFallback() {
      var r = abstractMapper.viewCleanup.bind(this);
      return s._customFindAbstractMapper.viewCleanup.call(this, r);
    }
  }; else return abstractMapper;
}

function massageSort(s) {
  if (!Array.isArray(s)) throw new Error("invalid sort json - should be an array");
  return s.map((function(s) {
    if ("string" == typeof s) {
      var r = {};
      r[s] = "asc";
      return r;
    } else return s;
  }));
}

function massageUseIndex(s) {
  var r = [];
  if ("string" == typeof s) r.push(s); else r = s;
  return r.map((function(s) {
    return s.replace("_design/", "");
  }));
}

function massageIndexDef(s) {
  s.fields = s.fields.map((function(s) {
    if ("string" == typeof s) {
      var r = {};
      r[s] = "asc";
      return r;
    }
    return s;
  }));
  if (s.partial_filter_selector) s.partial_filter_selector = massageSelector(s.partial_filter_selector);
  return s;
}

function getKeyFromDoc(s, r) {
  for (var o = [], u = 0; u < r.def.fields.length; u++) {
    var g = getKey(r.def.fields[u]);
    o.push(getFieldFromDoc(s, parseField(g)));
  }
  return o;
}

function filterInclusiveStart(s, r, o) {
  for (var u = o.def.fields, g = 0, _ = s.length; g < _; g++) {
    var m = getKeyFromDoc(s[g].doc, o);
    if (1 === u.length) m = m[0]; else for (;m.length > r.length; ) m.pop();
    if (Math.abs(collate(m, r)) > 0) break;
  }
  return g > 0 ? s.slice(g) : s;
}

function reverseOptions(s) {
  var r = clone(s);
  delete r.startkey;
  delete r.endkey;
  delete r.inclusive_start;
  delete r.inclusive_end;
  if ("endkey" in s) r.startkey = s.endkey;
  if ("startkey" in s) r.endkey = s.startkey;
  if ("inclusive_start" in s) r.inclusive_end = s.inclusive_start;
  if ("inclusive_end" in s) r.inclusive_start = s.inclusive_end;
  return r;
}

function validateIndex(s) {
  var r = s.fields.filter((function(s) {
    return "asc" === getValue(s);
  }));
  if (0 !== r.length && r.length !== s.fields.length) throw new Error("unsupported mixed sorting");
}

function validateSort(s, r) {
  if (r.defaultUsed && s.sort) {
    var o = s.sort.filter((function(s) {
      return "_id" !== Object.keys(s)[0];
    })).map((function(s) {
      return Object.keys(s)[0];
    }));
    if (o.length > 0) throw new Error('Cannot sort on field(s) "' + o.join(",") + '" when using the default index');
  }
  if (!r.defaultUsed) ;
}

function validateFindRequest(s) {
  if ("object" != typeof s.selector) throw new Error("you must provide a selector when you find()");
}

function getUserFields(s, r) {
  var o, u = Object.keys(s), g = r ? r.map(getKey) : [];
  if (u.length >= g.length) o = u; else o = g;
  if (0 === g.length) return {
    fields: o
  }; else return {
    fields: o = o.sort((function(s, r) {
      var o = g.indexOf(s);
      if (-1 === o) o = Number.MAX_VALUE;
      var u = g.indexOf(r);
      if (-1 === u) u = Number.MAX_VALUE;
      return o < u ? -1 : o > u ? 1 : 0;
    })),
    sortOrder: r.map(getKey)
  };
}

function createIndex$1(s, r) {
  var o, u = clone((r = massageCreateIndexRequest(r)).index);
  r.index = massageIndexDef(r.index);
  validateIndex(r.index);
  function getMd5() {
    return o || (o = stringMd5(JSON.stringify(r)));
  }
  var g = r.name || "idx-" + getMd5(), _ = r.ddoc || "idx-" + getMd5(), m = "_design/" + _, b = false, E = false;
  s.constructor.emit("debug", [ "find", "creating index", m ]);
  return upsert(s, m, (function updateDdoc(s) {
    if (s._rev && "query" !== s.language) b = true;
    s.language = "query";
    s.views = s.views || {};
    if (E = !!s.views[g]) return false;
    s.views[g] = {
      map: {
        fields: mergeObjects(r.index.fields),
        partial_filter_selector: r.index.partial_filter_selector
      },
      reduce: "_count",
      options: {
        def: u
      }
    };
    return s;
  })).then((function() {
    if (b) throw new Error('invalid language for ddoc with id "' + m + '" (should be "query")');
  })).then((function() {
    var r = _ + "/" + g;
    return abstractMapper$1(s).query.call(s, r, {
      limit: 0,
      reduce: false
    }).then((function() {
      return {
        id: m,
        name: g,
        result: E ? "exists" : "created"
      };
    }));
  }));
}

function getIndexes$1(s) {
  return s.allDocs({
    startkey: "_design/",
    endkey: "_design/",
    include_docs: true
  }).then((function(s) {
    var r = {
      indexes: [ {
        ddoc: null,
        name: "_all_docs",
        type: "special",
        def: {
          fields: [ {
            _id: "asc"
          } ]
        }
      } ]
    };
    r.indexes = flatten2(r.indexes, s.rows.filter((function(s) {
      return "query" === s.doc.language;
    })).map((function(s) {
      return (void 0 !== s.doc.views ? Object.keys(s.doc.views) : []).map((function(r) {
        var o = s.doc.views[r];
        return {
          ddoc: s.id,
          name: r,
          type: "json",
          def: massageIndexDef(o.options.def)
        };
      }));
    })));
    r.indexes.sort((function(s, r) {
      return compare(s.name, r.name);
    }));
    r.total_rows = r.indexes.length;
    return r;
  }));
}

var COLLATE_LO = null, COLLATE_HI = {
  "": {}
}, SHORT_CIRCUIT_QUERY = {
  queryOpts: {
    limit: 0,
    startkey: COLLATE_HI,
    endkey: COLLATE_LO
  },
  inMemoryFields: []
};

function checkFieldInIndex(s, r) {
  for (var o = s.def.fields.map(getKey), u = 0, g = o.length; u < g; u++) if (r === o[u]) return true;
  return false;
}

function userOperatorLosesPrecision(s, r) {
  return "$eq" !== getKey(s[r]);
}

function sortFieldsByIndex(s, r) {
  var o = r.def.fields.map(getKey);
  return s.slice().sort((function(s, r) {
    var u = o.indexOf(s), g = o.indexOf(r);
    if (-1 === u) u = Number.MAX_VALUE;
    if (-1 === g) g = Number.MAX_VALUE;
    return compare(u, g);
  }));
}

function getBasicInMemoryFields(s, r, o) {
  for (var u = false, g = 0, _ = (o = sortFieldsByIndex(o, s)).length; g < _; g++) {
    var m = o[g];
    if (u || !checkFieldInIndex(s, m)) return o.slice(g);
    if (g < _ - 1 && userOperatorLosesPrecision(r, m)) u = true;
  }
  return [];
}

function getInMemoryFieldsFromNe(s) {
  var r = [];
  Object.keys(s).forEach((function(o) {
    var u = s[o];
    Object.keys(u).forEach((function(s) {
      if ("$ne" === s) r.push(o);
    }));
  }));
  return r;
}

function getInMemoryFields(s, r, o, u) {
  return sortFieldsByIndex(uniq2(flatten2(s, getBasicInMemoryFields(r, o, u), getInMemoryFieldsFromNe(o))), r);
}

function checkIndexFieldsMatch(s, r, o) {
  if (r) {
    var u = oneArrayIsStrictSubArrayOfOther(r, s), g = oneArrayIsSubArrayOfOther(o, s);
    return u && g;
  }
  return oneSetIsSubArrayOfOther(o, s);
}

var logicalMatchers = [ "$eq", "$gt", "$gte", "$lt", "$lte" ];

function isNonLogicalMatcher(s) {
  return -1 === logicalMatchers.indexOf(s);
}

function checkFieldsLogicallySound(s, r) {
  var o = r[s[0]];
  if ("undefined" == typeof o) return true; else return !(1 === Object.keys(o).length && "$ne" === getKey(o));
}

function checkIndexMatches(s, r, o, u) {
  var g = s.def.fields.map(getKey);
  if (!checkIndexFieldsMatch(g, r, o)) return false; else return checkFieldsLogicallySound(g, u);
}

function findMatchingIndexes(s, r, o, u) {
  return u.filter((function(u) {
    return checkIndexMatches(u, o, r, s);
  }));
}

function findBestMatchingIndex(s, r, o, u, g) {
  var _ = findMatchingIndexes(s, r, o, u);
  if (0 === _.length) {
    if (g) throw {
      error: "no_usable_index",
      message: "There is no index available for this selector."
    };
    var m = u[0];
    m.defaultUsed = true;
    return m;
  }
  if (1 === _.length && !g) return _[0];
  var b = arrayToObject(r);
  if (g) {
    var E = "_design/" + g[0], w = 2 === g.length ? g[1] : false, S = _.find((function(s) {
      if (w && s.ddoc === E && w === s.name) return true;
      if (s.ddoc === E) return true; else return false;
    }));
    if (!S) throw {
      error: "unknown_error",
      message: "Could not find that index or could not use that index for the query"
    };
    return S;
  }
  return max(_, (function scoreIndex(s) {
    for (var r = s.def.fields.map(getKey), o = 0, u = 0, g = r.length; u < g; u++) {
      var _ = r[u];
      if (b[_]) o++;
    }
    return o;
  }));
}

function getSingleFieldQueryOptsFor(s, r) {
  switch (s) {
   case "$eq":
    return {
      key: r
    };

   case "$lte":
    return {
      endkey: r
    };

   case "$gte":
    return {
      startkey: r
    };

   case "$lt":
    return {
      endkey: r,
      inclusive_end: false
    };

   case "$gt":
    return {
      startkey: r,
      inclusive_start: false
    };
  }
  return {
    startkey: COLLATE_LO
  };
}

function getSingleFieldCoreQueryPlan(s, r) {
  var o, u = getKey(r.def.fields[0]), g = s[u] || {}, _ = [];
  Object.keys(g).forEach((function(s) {
    if (isNonLogicalMatcher(s)) _.push(u);
    var r = getSingleFieldQueryOptsFor(s, g[s]);
    if (o) o = mergeObjects([ o, r ]); else o = r;
  }));
  return {
    queryOpts: o,
    inMemoryFields: _
  };
}

function getMultiFieldCoreQueryPlan(s, r) {
  switch (s) {
   case "$eq":
    return {
      startkey: r,
      endkey: r
    };

   case "$lte":
    return {
      endkey: r
    };

   case "$gte":
    return {
      startkey: r
    };

   case "$lt":
    return {
      endkey: r,
      inclusive_end: false
    };

   case "$gt":
    return {
      startkey: r,
      inclusive_start: false
    };
  }
}

function getMultiFieldQueryOpts(s, r) {
  var o, u, g = r.def.fields.map(getKey), _ = [], m = [], b = [];
  function finish(s) {
    if (false !== o) m.push(COLLATE_LO);
    if (false !== u) b.push(COLLATE_HI);
    _ = g.slice(s);
  }
  for (var E = 0, w = g.length; E < w; E++) {
    var S = s[g[E]];
    if (!S || !Object.keys(S).length) {
      finish(E);
      break;
    } else if (Object.keys(S).some(isNonLogicalMatcher)) {
      finish(E);
      break;
    } else if (E > 0) {
      var L = "$gt" in S || "$gte" in S || "$lt" in S || "$lte" in S, O = Object.keys(s[g[E - 1]]), D = arrayEquals(O, [ "$eq" ]), C = arrayEquals(O, Object.keys(S));
      if (L && !D && !C) {
        finish(E);
        break;
      }
    }
    for (var k = Object.keys(S), T = null, A = 0; A < k.length; A++) {
      var R = k[A], I = getMultiFieldCoreQueryPlan(R, S[R]);
      if (T) T = mergeObjects([ T, I ]); else T = I;
    }
    m.push("startkey" in T ? T.startkey : COLLATE_LO);
    b.push("endkey" in T ? T.endkey : COLLATE_HI);
    if ("inclusive_start" in T) o = T.inclusive_start;
    if ("inclusive_end" in T) u = T.inclusive_end;
  }
  var x = {
    startkey: m,
    endkey: b
  };
  if ("undefined" != typeof o) x.inclusive_start = o;
  if ("undefined" != typeof u) x.inclusive_end = u;
  return {
    queryOpts: x,
    inMemoryFields: _
  };
}

function shouldShortCircuit(s) {
  return Object.keys(s).map((function(r) {
    return s[r];
  })).some((function(s) {
    return "object" == typeof s && 0 === Object.keys(s).length;
  }));
}

function getDefaultQueryPlan(s) {
  return {
    queryOpts: {
      startkey: null
    },
    inMemoryFields: [ Object.keys(s) ]
  };
}

function getCoreQueryPlan(s, r) {
  if (r.defaultUsed) return getDefaultQueryPlan(s, r);
  if (1 === r.def.fields.length) return getSingleFieldCoreQueryPlan(s, r); else return getMultiFieldQueryOpts(s, r);
}

function planQuery(s, r) {
  var o = s.selector, u = s.sort;
  if (shouldShortCircuit(o)) return assign$2({}, SHORT_CIRCUIT_QUERY, {
    index: r[0]
  });
  var g = getUserFields(o, u), _ = g.fields, m = findBestMatchingIndex(o, _, g.sortOrder, r, s.use_index), b = getCoreQueryPlan(o, m);
  return {
    queryOpts: b.queryOpts,
    index: m,
    inMemoryFields: getInMemoryFields(b.inMemoryFields, m, o, _)
  };
}

function indexToSignature(s) {
  return s.ddoc.substring(8) + "/" + s.name;
}

function doAllDocs(s, r) {
  var o = clone(r);
  if (o.descending) {
    if ("endkey" in o && "string" != typeof o.endkey) o.endkey = "";
    if ("startkey" in o && "string" != typeof o.startkey) o.limit = 0;
  } else {
    if ("startkey" in o && "string" != typeof o.startkey) o.startkey = "";
    if ("endkey" in o && "string" != typeof o.endkey) o.limit = 0;
  }
  if ("key" in o && "string" != typeof o.key) o.limit = 0;
  if (o.limit > 0 && o.indexes_count) {
    o.original_limit = o.limit;
    o.limit += o.indexes_count;
  }
  return s.allDocs(o).then((function(s) {
    s.rows = s.rows.filter((function(s) {
      return !/^_design\//.test(s.id);
    }));
    if (o.original_limit) o.limit = o.original_limit;
    s.rows = s.rows.slice(0, o.limit);
    return s;
  }));
}

function find$1(s, r, o) {
  if (r.selector) {
    validateSelector(r.selector, false);
    r.selector = massageSelector(r.selector);
  }
  if (r.sort) r.sort = massageSort(r.sort);
  if (r.use_index) r.use_index = massageUseIndex(r.use_index);
  validateFindRequest(r);
  return getIndexes$1(s).then((function(u) {
    s.constructor.emit("debug", [ "find", "planning query", r ]);
    var g = planQuery(r, u.indexes);
    s.constructor.emit("debug", [ "find", "query plan", g ]);
    var _ = g.index;
    validateSort(r, _);
    var m = assign$2({
      include_docs: true,
      reduce: false,
      indexes_count: u.total_rows
    }, g.queryOpts);
    if ("startkey" in m && "endkey" in m && collate(m.startkey, m.endkey) > 0) return {
      docs: []
    };
    if (r.sort && "string" != typeof r.sort[0] && "desc" === getValue(r.sort[0])) {
      m.descending = true;
      m = reverseOptions(m);
    }
    if (!g.inMemoryFields.length) {
      if ("limit" in r) m.limit = r.limit;
      if ("skip" in r) m.skip = r.skip;
    }
    if (o) return Promise.resolve(g, m); else return Promise.resolve().then((function() {
      if ("_all_docs" === _.name) return doAllDocs(s, m); else {
        var r = indexToSignature(_);
        return abstractMapper$1(s).query.call(s, r, m);
      }
    })).then((function(s) {
      if (false === m.inclusive_start) s.rows = filterInclusiveStart(s.rows, m.startkey, _);
      if (g.inMemoryFields.length) s.rows = filterInMemoryFields(s.rows, r, g.inMemoryFields);
      var o = {
        docs: s.rows.map((function(s) {
          var o = s.doc;
          if (r.fields) return pick2(o, r.fields); else return o;
        }))
      };
      if (_.defaultUsed) o.warning = "No matching index found, create an index to optimize query time.";
      return o;
    }));
  }));
}

function explain$1(s, r) {
  return find$1(s, r, true).then((function(o) {
    return {
      dbname: s.name,
      index: o.index,
      selector: r.selector,
      range: {
        start_key: o.queryOpts.startkey,
        end_key: o.queryOpts.endkey
      },
      opts: {
        use_index: r.use_index || [],
        bookmark: "nil",
        limit: r.limit,
        skip: r.skip,
        sort: r.sort || {},
        fields: r.fields,
        conflicts: false,
        r: [ 49 ]
      },
      limit: r.limit,
      skip: r.skip || 0,
      fields: r.fields
    };
  }));
}

function deleteIndex$1(s, r) {
  if (!r.ddoc) throw new Error("you must supply an index.ddoc when deleting");
  if (!r.name) throw new Error("you must supply an index.name when deleting");
  var o = r.ddoc, u = r.name;
  return upsert(s, o, (function deltaFun(s) {
    if (1 === Object.keys(s.views).length && s.views[u]) return {
      _id: o,
      _deleted: true
    };
    delete s.views[u];
    return s;
  })).then((function() {
    return abstractMapper$1(s).viewCleanup.apply(s);
  })).then((function() {
    return {
      ok: true
    };
  }));
}

var createIndexAsCallback = callbackify2(createIndex$1), findAsCallback = callbackify2(find$1), explainAsCallback = callbackify2(explain$1), getIndexesAsCallback = callbackify2(getIndexes$1), deleteIndexAsCallback = callbackify2(deleteIndex$1), plugin = {};

plugin.createIndex = toPromise((function(s, r) {
  if ("object" != typeof s) return r(new Error("you must provide an index to create"));
  (isRemote(this) ? createIndex : createIndexAsCallback)(this, s, r);
}));

plugin.find = toPromise((function(s, r) {
  if ("undefined" == typeof r) {
    r = s;
    s = void 0;
  }
  if ("object" != typeof s) return r(new Error("you must provide search parameters to find()"));
  (isRemote(this) ? find : findAsCallback)(this, s, r);
}));

plugin.explain = toPromise((function(s, r) {
  if ("undefined" == typeof r) {
    r = s;
    s = void 0;
  }
  if ("object" != typeof s) return r(new Error("you must provide search parameters to explain()"));
  (isRemote(this) ? explain : explainAsCallback)(this, s, r);
}));

plugin.getIndexes = toPromise((function(s) {
  (isRemote(this) ? getIndexes : getIndexesAsCallback)(this, s);
}));

plugin.deleteIndex = toPromise((function(s, r) {
  if ("object" != typeof s) return r(new Error("you must provide an index to delete"));
  (isRemote(this) ? deleteIndex : deleteIndexAsCallback)(this, s, r);
}));

var index_browser_es_default3 = plugin, import_transform_pouch = __toESM(require_transform_pouch(), 1);

function unwrapTaskResult(s) {
  if ("ok" in s) return s.ok;
  if ("err" in s) return s.err;
}

function isTaskWaiting(s) {
  if (s instanceof Promise) return false;
  if (s instanceof Function) return true;
  throw new Error("Invalid state");
}

async function wrapEachProcess(s, r) {
  try {
    return {
      key: s,
      ok: await r
    };
  } catch (r) {
    return {
      key: s,
      err: r
    };
  }
}

async function* processAllTasksWithConcurrencyLimit(s, r) {
  const o = new Map;
  let u = 0;
  const g = r.reverse();
  for (;g.length > 0 || o.size > 0; ) {
    e: for (;o.size < s && g.length > 0; ) {
      const s = g.pop();
      if (void 0 === s) break e;
      u++;
      const r = wrapEachProcess(u, isTaskWaiting(s) ? s() : s);
      o.set(u, r);
    }
    const r = await Promise.race(o.values());
    o.delete(r.key);
    yield r;
  }
}

async function mapAllTasksWithConcurrencyLimit(s, r) {
  const o = new Map;
  for await (const u of processAllTasksWithConcurrencyLimit(s, r)) o.set(u.key, u);
  return [ ...o.entries() ].sort(((s, r) => s[0] - r[0])).map((s => s[1]));
}

var tasks = {};

function scheduleTask(s, r, o, u) {
  if (!u || !(s in tasks)) {
    cancelTask(s);
    tasks[s] = setTimeout((async () => {
      delete tasks[s];
      await o();
    }), r);
  }
}

function cancelTask(s) {
  if (s in tasks) {
    clearTimeout(tasks[s]);
    delete tasks[s];
  }
}

function cancelAllTasks() {
  for (const s in tasks) {
    clearTimeout(tasks[s]);
    delete tasks[s];
  }
}

var intervals = {};

function cancelAllPeriodicTask() {
  for (const s in intervals) {
    clearInterval(intervals[s]);
    delete intervals[s];
  }
}

index_es_default.plugin(index_es_default2).plugin(index_es_default3).plugin(index_es_default4).plugin(index_browser_es_default2).plugin(index_es_default8).plugin(index_browser_es_default3).plugin(import_transform_pouch.default);

function appendPurgeSeqs(s, r) {
  return s.get("_local/purges").then((function(o) {
    for (const [u, g] of r) {
      const r = o.purgeSeq + 1;
      o.purges.push({
        docId: u,
        rev: g,
        purgeSeq: r
      });
      if (o.purges.length > s.purged_infos_limit) o.purges.splice(0, o.purges.length - s.purged_infos_limit);
      o.purgeSeq = r;
    }
    return o;
  })).catch((function(s) {
    if (404 !== s.status) throw s;
    return {
      _id: "_local/purges",
      purges: r.map((([s, r], o) => ({
        docId: s,
        rev: r,
        purgeSeq: o
      }))),
      purgeSeq: r.length
    };
  })).then((function(r) {
    return s.put(r);
  }));
}

index_es_default.prototype.purgeMulti = adapterFun("_purgeMulti", (function(s, r) {
  if ("undefined" == typeof this._purge) return r(createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter."));
  const o = this, u = s.map((s => () => new Promise(((r, u) => {
    const [g, _] = s;
    o._getRevisionTree(g, ((u, m) => {
      if (u) return r([ s, u ]);
      if (!m) return r([ s, createError(MISSING_DOC) ]);
      let b;
      try {
        b = findPathToLeaf(m, _);
      } catch (o) {
        return r([ s, o.message || o ]);
      }
      o._purge(g, b, ((o, u) => {
        if (o) return r([ s, o ]); else return r([ s, u ]);
      }));
    }));
  }))));
  (async () => {
    const s = (await mapAllTasksWithConcurrencyLimit(1, u)).map((s => unwrapTaskResult(s)));
    await appendPurgeSeqs(o, s.filter((s => "ok" in s[1])).map((s => s[0])));
    return Object.fromEntries(s.map((s => [ s[0][0], s[1] ])));
  })().then((s => r(void 0, s))).catch((s => r(s)));
}));

var import_diff_match_patch2 = __toESM(require_diff_match_patch(), 1), ConflictResolveModal = class extends import_obsidian.Modal {
  constructor(s, r, o) {
    super(s);
    this.response = CANCELLED;
    this.isClosed = false;
    this.consumed = false;
    this.result = o;
    this.filename = r;
    sendValue("cancel-resolve-conflict:" + this.filename, true);
  }
  onOpen() {
    const {contentEl: s} = this;
    sendValue("cancel-resolve-conflict:" + this.filename, true);
    setTimeout((async () => {
      if (await waitForValue("cancel-resolve-conflict:" + this.filename)) this.sendResponse(CANCELLED);
    }), 10);
    this.titleEl.setText("Conflicting changes");
    s.empty();
    s.createEl("span", {
      text: this.filename
    });
    const r = s.createDiv("");
    r.addClass("op-scrollable");
    let o = "";
    for (const s of this.result.diff) {
      const r = s[0], u = s[1];
      if (r == import_diff_match_patch2.DIFF_DELETE) o += "<span class='deleted'>" + escapeStringToHTML(u).replace(/\n/g, "<span class='ls-mark-cr'></span>\n") + "</span>"; else if (r == import_diff_match_patch2.DIFF_EQUAL) o += "<span class='normal'>" + escapeStringToHTML(u).replace(/\n/g, "<span class='ls-mark-cr'></span>\n") + "</span>"; else if (r == import_diff_match_patch2.DIFF_INSERT) o += "<span class='added'>" + escapeStringToHTML(u).replace(/\n/g, "<span class='ls-mark-cr'></span>\n") + "</span>";
    }
    o = o.replace(/\n/g, "<br>");
    r.innerHTML = o;
    const u = s.createDiv(""), g = new Date(this.result.left.mtime).toLocaleString() + (this.result.left.deleted ? " (Deleted)" : ""), _ = new Date(this.result.right.mtime).toLocaleString() + (this.result.right.deleted ? " (Deleted)" : "");
    u.innerHTML = `\n<span class='deleted'>A:${g}</span><br /><span class='added'>B:${_}</span><br> \n        `;
    s.createEl("button", {
      text: "Keep A"
    }, (s => s.addEventListener("click", (() => this.sendResponse(this.result.right.rev)))));
    s.createEl("button", {
      text: "Keep B"
    }, (s => s.addEventListener("click", (() => this.sendResponse(this.result.left.rev)))));
    s.createEl("button", {
      text: "Concat both"
    }, (s => s.addEventListener("click", (() => this.sendResponse(LEAVE_TO_SUBSEQUENT)))));
    s.createEl("button", {
      text: "Not now"
    }, (s => s.addEventListener("click", (() => this.sendResponse(CANCELLED)))));
  }
  sendResponse(s) {
    this.response = s;
    this.close();
  }
  onClose() {
    const {contentEl: s} = this;
    s.empty();
    if (!this.consumed) {
      this.consumed = true;
      sendValue("close-resolve-conflict:" + this.filename, this.response);
      sendValue("cancel-resolve-conflict:" + this.filename, false);
    }
  }
  async waitForResult() {
    await delay(100);
    const s = await waitForValue("close-resolve-conflict:" + this.filename);
    if (s === RESULT_TIMED_OUT) return CANCELLED; else return s;
  }
}, import_obsidian4 = require("obsidian");

function noop() {}

function assign(s, r) {
  for (const o in r) s[o] = r[o];
  return s;
}

function run(s) {
  return s();
}

function blank_object() {
  return Object.create(null);
}

function run_all(s) {
  s.forEach(run);
}

function is_function(s) {
  return "function" == typeof s;
}

function safe_not_equal(s, r) {
  return s != s ? r == r : s !== r || s && "object" == typeof s || "function" == typeof s;
}

function is_empty(s) {
  return 0 === Object.keys(s).length;
}

function null_to_empty(s) {
  return null == s ? "" : s;
}

var globals = "undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : window, ResizeObserverSingleton = class _ResizeObserverSingleton {
  constructor(s) {
    __publicField(this, "_listeners", "WeakMap" in globals ? new WeakMap : void 0);
    __publicField(this, "_observer");
    __publicField(this, "options");
    this.options = s;
  }
  observe(s, r) {
    this._listeners.set(s, r);
    this._getObserver().observe(s, this.options);
    return () => {
      this._listeners.delete(s);
      this._observer.unobserve(s);
    };
  }
  _getObserver() {
    var s;
    return null != (s = this._observer) ? s : this._observer = new ResizeObserver((s => {
      var r;
      for (const o of s) {
        _ResizeObserverSingleton.entries.set(o.target, o);
        null == (r = this._listeners.get(o.target)) || r(o);
      }
    }));
  }
};

ResizeObserverSingleton.entries = "WeakMap" in globals ? new WeakMap : void 0;

var current_component, is_hydrating = false;

function start_hydrating() {
  is_hydrating = true;
}

function end_hydrating() {
  is_hydrating = false;
}

function append(s, r) {
  s.appendChild(r);
}

function append_styles(s, r, o) {
  const u = get_root_for_style(s);
  if (!u.getElementById(r)) {
    const s = element("style");
    s.id = r;
    s.textContent = o;
    append_stylesheet(u, s);
  }
}

function get_root_for_style(s) {
  if (!s) return document;
  const r = s.getRootNode ? s.getRootNode() : s.ownerDocument;
  if (r && r.host) return r; else return s.ownerDocument;
}

function append_stylesheet(s, r) {
  append(s.head || s, r);
  return r.sheet;
}

function insert(s, r, o) {
  s.insertBefore(r, o || null);
}

function detach(s) {
  if (s.parentNode) s.parentNode.removeChild(s);
}

function destroy_each(s, r) {
  for (let o = 0; o < s.length; o += 1) if (s[o]) s[o].d(r);
}

function element(s) {
  return document.createElement(s);
}

function text(s) {
  return document.createTextNode(s);
}

function space() {
  return text(" ");
}

function empty() {
  return text("");
}

function comment(s) {
  return document.createComment(s);
}

function listen(s, r, o, u) {
  s.addEventListener(r, o, u);
  return () => s.removeEventListener(r, o, u);
}

function attr(s, r, o) {
  if (null == o) s.removeAttribute(r); else if (s.getAttribute(r) !== o) s.setAttribute(r, o);
}

function init_binding_group(s) {
  let r;
  return {
    p(...o) {
      r = o;
      r.forEach((r => s.push(r)));
    },
    r() {
      r.forEach((r => s.splice(s.indexOf(r), 1)));
    }
  };
}

function children(s) {
  return Array.from(s.childNodes);
}

function set_data(s, r) {
  r = "" + r;
  if (s.data !== r) s.data = r;
}

function set_input_value(s, r) {
  s.value = null == r ? "" : r;
}

function select_option(s, r, o) {
  for (let o = 0; o < s.options.length; o += 1) {
    const u = s.options[o];
    if (u.__value === r) {
      u.selected = true;
      return;
    }
  }
  if (!o || void 0 !== r) s.selectedIndex = -1;
}

function select_value(s) {
  const r = s.querySelector(":checked");
  return r && r.__value;
}

function toggle_class(s, r, o) {
  s.classList.toggle(r, !!o);
}

function get_custom_elements_slots(s) {
  const r = {};
  s.childNodes.forEach((s => {
    r[s.slot || "default"] = true;
  }));
  return r;
}

function set_current_component(s) {
  current_component = s;
}

function get_current_component() {
  if (!current_component) throw new Error("Function called outside component initialization");
  return current_component;
}

function onMount(s) {
  get_current_component().$$.on_mount.push(s);
}

function onDestroy(s) {
  get_current_component().$$.on_destroy.push(s);
}

var dirty_components = [], binding_callbacks = [], render_callbacks = [], flush_callbacks = [], resolved_promise = Promise.resolve(), update_scheduled = false;

function schedule_update() {
  if (!update_scheduled) {
    update_scheduled = true;
    resolved_promise.then(flush);
  }
}

function add_render_callback(s) {
  render_callbacks.push(s);
}

var seen_callbacks = new Set, flushidx = 0;

function flush() {
  if (0 !== flushidx) return;
  const s = current_component;
  do {
    try {
      for (;flushidx < dirty_components.length; ) {
        const s = dirty_components[flushidx];
        flushidx++;
        set_current_component(s);
        update(s.$$);
      }
    } catch (s) {
      dirty_components.length = 0;
      flushidx = 0;
      throw s;
    }
    set_current_component(null);
    dirty_components.length = 0;
    flushidx = 0;
    for (;binding_callbacks.length; ) binding_callbacks.pop()();
    for (let s = 0; s < render_callbacks.length; s += 1) {
      const r = render_callbacks[s];
      if (!seen_callbacks.has(r)) {
        seen_callbacks.add(r);
        r();
      }
    }
    render_callbacks.length = 0;
  } while (dirty_components.length);
  for (;flush_callbacks.length; ) flush_callbacks.pop()();
  update_scheduled = false;
  seen_callbacks.clear();
  set_current_component(s);
}

function update(s) {
  if (null !== s.fragment) {
    s.update();
    run_all(s.before_update);
    const r = s.dirty;
    s.dirty = [ -1 ];
    s.fragment && s.fragment.p(s.ctx, r);
    s.after_update.forEach(add_render_callback);
  }
}

function flush_render_callbacks(s) {
  const r = [], o = [];
  render_callbacks.forEach((u => -1 === s.indexOf(u) ? r.push(u) : o.push(u)));
  o.forEach((s => s()));
  render_callbacks = r;
}

var outros, outroing = new Set;

function group_outros() {
  outros = {
    r: 0,
    c: [],
    p: outros
  };
}

function check_outros() {
  if (!outros.r) run_all(outros.c);
  outros = outros.p;
}

function transition_in(s, r) {
  if (s && s.i) {
    outroing.delete(s);
    s.i(r);
  }
}

function transition_out(s, r, o, u) {
  if (s && s.o) {
    if (outroing.has(s)) return;
    outroing.add(s);
    outros.c.push((() => {
      outroing.delete(s);
      if (u) {
        if (o) s.d(1);
        u();
      }
    }));
    s.o(r);
  } else if (u) u();
}

function ensure_array_like(s) {
  return void 0 !== (null == s ? void 0 : s.length) ? s : Array.from(s);
}

function get_spread_update(s, r) {
  const o = {}, u = {}, g = {
    $$scope: 1
  };
  let _ = s.length;
  for (;_--; ) {
    const m = s[_], b = r[_];
    if (b) {
      for (const s in m) if (!(s in b)) u[s] = 1;
      for (const s in b) if (!g[s]) {
        o[s] = b[s];
        g[s] = 1;
      }
      s[_] = b;
    } else for (const s in m) g[s] = 1;
  }
  for (const s in u) if (!(s in o)) o[s] = void 0;
  return o;
}

function get_spread_object(s) {
  return "object" == typeof s && null !== s ? s : {};
}

var SvelteElement, _boolean_attributes = [ "allowfullscreen", "allowpaymentrequest", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected" ], boolean_attributes = new Set([ ..._boolean_attributes ]);

function create_component(s) {
  s && s.c();
}

function mount_component(s, r, o) {
  const {fragment: u, after_update: g} = s.$$;
  u && u.m(r, o);
  add_render_callback((() => {
    const r = s.$$.on_mount.map(run).filter(is_function);
    if (s.$$.on_destroy) s.$$.on_destroy.push(...r); else run_all(r);
    s.$$.on_mount = [];
  }));
  g.forEach(add_render_callback);
}

function destroy_component(s, r) {
  const o = s.$$;
  if (null !== o.fragment) {
    flush_render_callbacks(o.after_update);
    run_all(o.on_destroy);
    o.fragment && o.fragment.d(r);
    o.on_destroy = o.fragment = null;
    o.ctx = [];
  }
}

function make_dirty(s, r) {
  if (-1 === s.$$.dirty[0]) {
    dirty_components.push(s);
    schedule_update();
    s.$$.dirty.fill(0);
  }
  s.$$.dirty[r / 31 | 0] |= 1 << r % 31;
}

function init2(s, r, o, u, g, _, m = null, b = [ -1 ]) {
  const E = current_component;
  set_current_component(s);
  const w = s.$$ = {
    fragment: null,
    ctx: [],
    props: _,
    update: noop,
    not_equal: g,
    bound: blank_object(),
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(r.context || (E ? E.$$.context : [])),
    callbacks: blank_object(),
    dirty: b,
    skip_bound: false,
    root: r.target || E.$$.root
  };
  m && m(w.root);
  let S = false;
  w.ctx = o ? o(s, r.props || {}, ((r, o, ...u) => {
    const _ = u.length ? u[0] : o;
    if (w.ctx && g(w.ctx[r], w.ctx[r] = _)) {
      if (!w.skip_bound && w.bound[r]) w.bound[r](_);
      if (S) make_dirty(s, r);
    }
    return o;
  })) : [];
  w.update();
  S = true;
  run_all(w.before_update);
  w.fragment = u ? u(w.ctx) : false;
  if (r.target) {
    if (r.hydrate) {
      start_hydrating();
      const s = children(r.target);
      w.fragment && w.fragment.l(s);
      s.forEach(detach);
    } else w.fragment && w.fragment.c();
    if (r.intro) transition_in(s.$$.fragment);
    mount_component(s, r.target, r.anchor);
    end_hydrating();
    flush();
  }
  set_current_component(E);
}

if ("function" == typeof HTMLElement) SvelteElement = class extends HTMLElement {
  constructor(s, r, o) {
    super();
    __publicField(this, "$$ctor");
    __publicField(this, "$$s");
    __publicField(this, "$$c");
    __publicField(this, "$$cn", false);
    __publicField(this, "$$d", {});
    __publicField(this, "$$r", false);
    __publicField(this, "$$p_d", {});
    __publicField(this, "$$l", {});
    __publicField(this, "$$l_u", new Map);
    this.$$ctor = s;
    this.$$s = r;
    if (o) this.attachShadow({
      mode: "open"
    });
  }
  addEventListener(s, r, o) {
    this.$$l[s] = this.$$l[s] || [];
    this.$$l[s].push(r);
    if (this.$$c) {
      const o = this.$$c.$on(s, r);
      this.$$l_u.set(r, o);
    }
    super.addEventListener(s, r, o);
  }
  removeEventListener(s, r, o) {
    super.removeEventListener(s, r, o);
    if (this.$$c) {
      const s = this.$$l_u.get(r);
      if (s) {
        s();
        this.$$l_u.delete(r);
      }
    }
  }
  async connectedCallback() {
    this.$$cn = true;
    if (!this.$$c) {
      let create_slot = function(s) {
        return () => {
          let r;
          return {
            c: function create() {
              r = element("slot");
              if ("default" !== s) attr(r, "name", s);
            },
            m: function mount(s, o) {
              insert(s, r, o);
            },
            d: function destroy2(s) {
              if (s) detach(r);
            }
          };
        };
      };
      await Promise.resolve();
      if (!this.$$cn || this.$$c) return;
      const s = {}, r = get_custom_elements_slots(this);
      for (const o of this.$$s) if (o in r) s[o] = [ create_slot(o) ];
      for (const s of this.attributes) {
        const r = this.$$g_p(s.name);
        if (!(r in this.$$d)) this.$$d[r] = get_custom_element_value(r, s.value, this.$$p_d, "toProp");
      }
      for (const s in this.$$p_d) if (!(s in this.$$d) && void 0 !== this[s]) {
        this.$$d[s] = this[s];
        delete this[s];
      }
      this.$$c = new this.$$ctor({
        target: this.shadowRoot || this,
        props: {
          ...this.$$d,
          $$slots: s,
          $$scope: {
            ctx: []
          }
        }
      });
      const reflect_attributes = () => {
        this.$$r = true;
        for (const s in this.$$p_d) {
          this.$$d[s] = this.$$c.$$.ctx[this.$$c.$$.props[s]];
          if (this.$$p_d[s].reflect) {
            const r = get_custom_element_value(s, this.$$d[s], this.$$p_d, "toAttribute");
            if (null == r) this.removeAttribute(this.$$p_d[s].attribute || s); else this.setAttribute(this.$$p_d[s].attribute || s, r);
          }
        }
        this.$$r = false;
      };
      this.$$c.$$.after_update.push(reflect_attributes);
      reflect_attributes();
      for (const s in this.$$l) for (const r of this.$$l[s]) {
        const o = this.$$c.$on(s, r);
        this.$$l_u.set(r, o);
      }
      this.$$l = {};
    }
  }
  attributeChangedCallback(s, r, o) {
    var u;
    if (!this.$$r) {
      s = this.$$g_p(s);
      this.$$d[s] = get_custom_element_value(s, o, this.$$p_d, "toProp");
      null == (u = this.$$c) || u.$set({
        [s]: this.$$d[s]
      });
    }
  }
  disconnectedCallback() {
    this.$$cn = false;
    Promise.resolve().then((() => {
      if (!this.$$cn) {
        this.$$c.$destroy();
        this.$$c = void 0;
      }
    }));
  }
  $$g_p(s) {
    return Object.keys(this.$$p_d).find((r => this.$$p_d[r].attribute === s || !this.$$p_d[r].attribute && r.toLowerCase() === s)) || s;
  }
};

function get_custom_element_value(s, r, o, u) {
  var g;
  const _ = null == (g = o[s]) ? void 0 : g.type;
  r = "Boolean" === _ && "boolean" != typeof r ? null != r : r;
  if (!u || !o[s]) return r; else if ("toAttribute" === u) switch (_) {
   case "Object":
   case "Array":
    return null == r ? null : JSON.stringify(r);

   case "Boolean":
    return r ? "" : null;

   case "Number":
    return null == r ? null : r;

   default:
    return r;
  } else switch (_) {
   case "Object":
   case "Array":
    return r && JSON.parse(r);

   case "Boolean":
    return r;

   case "Number":
    return null != r ? +r : r;

   default:
    return r;
  }
}

var SvelteComponent = class {
  constructor() {
    __publicField(this, "$$");
    __publicField(this, "$$set");
  }
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  $on(s, r) {
    if (!is_function(r)) return noop;
    const o = this.$$.callbacks[s] || (this.$$.callbacks[s] = []);
    o.push(r);
    return () => {
      const s = o.indexOf(r);
      if (-1 !== s) o.splice(s, 1);
    };
  }
  $set(s) {
    if (this.$$set && !is_empty(s)) {
      this.$$.skip_bound = true;
      this.$$set(s);
      this.$$.skip_bound = false;
    }
  }
}, PUBLIC_VERSION = "4";

if ("undefined" != typeof window) (window.__svelte || (window.__svelte = {
  v: new Set
})).v.add(PUBLIC_VERSION);

var subscriber_queue = [];

function writable(s, r = noop) {
  let o;
  const u = new Set;
  function set(r) {
    if (safe_not_equal(s, r)) {
      s = r;
      if (o) {
        const r = !subscriber_queue.length;
        for (const r of u) {
          r[1]();
          subscriber_queue.push(r, s);
        }
        if (r) {
          for (let s = 0; s < subscriber_queue.length; s += 2) subscriber_queue[s][0](subscriber_queue[s + 1]);
          subscriber_queue.length = 0;
        }
      }
    }
  }
  function update2(r) {
    set(r(s));
  }
  return {
    set,
    update: update2,
    subscribe: function subscribe2(g, _ = noop) {
      const m = [ g, _ ];
      u.add(m);
      if (1 === u.size) o = r(set, update2) || noop;
      g(s);
      return () => {
        u.delete(m);
        if (0 === u.size && o) {
          o();
          o = null;
        }
      };
    }
  };
}

var LiveSyncCommands = class {
  get app() {
    return this.plugin.app;
  }
  get settings() {
    return this.plugin.settings;
  }
  get localDatabase() {
    return this.plugin.localDatabase;
  }
  get vaultAccess() {
    return this.plugin.vaultAccess;
  }
  id2path(s, r, o) {
    return this.plugin.id2path(s, r, o);
  }
  async path2id(s, r) {
    return await this.plugin.path2id(s, r);
  }
  getPath(s) {
    return this.plugin.getPath(s);
  }
  constructor(s) {
    this.plugin = s;
  }
};

function add_css(s) {
  append_styles(s, "svelte-guf68w", ".deleted.svelte-guf68w{text-decoration:line-through}.svelte-guf68w{box-sizing:border-box}.scroller.svelte-guf68w{display:flex;flex-direction:column;overflow-y:scroll;max-height:60vh;user-select:text}.json-source.svelte-guf68w{white-space:pre;height:auto;overflow:auto;min-height:var(--font-ui-medium);flex-grow:1}");
}

function get_each_context(s, r, o) {
  const u = s.slice();
  u[25] = r[o];
  return u;
}

function get_each_context_1(s, r, o) {
  const u = s.slice();
  u[28] = r[o];
  return u;
}

function create_else_block(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A, R, I, x, P, N, B, F, M, V = new Date(s[3].mtime).toLocaleString() + "", G = s[5].length + "", j = new Date(s[4].mtime).toLocaleString() + "", U = s[6].length + "", q = ensure_array_like(s[11]), z = [];
  for (let r = 0; r < q.length; r += 1) z[r] = create_each_block_1(get_each_context_1(s, q, r));
  function select_block_type_1(s, r) {
    if (false != s[8]) return create_if_block_3; else return create_else_block_1;
  }
  let W = select_block_type_1(s), H = W(s), K = s[3]._id == s[4]._id && create_if_block_2(s), Q = s[3]._id == s[4]._id && create_if_block_1(s);
  return {
    c() {
      r = element("div");
      for (let s = 0; s < z.length; s += 1) z[s].c();
      o = space();
      H.c();
      u = space();
      g = element("div");
      _ = text(s[1]);
      m = space();
      if (K) K.c();
      b = text(" ,");
      E = text(V);
      w = space();
      S = text(G);
      L = text(" letters");
      O = space();
      D = element("div");
      C = text(s[2]);
      k = space();
      if (Q) Q.c();
      T = text(" ,");
      A = text(j);
      R = space();
      I = text(U);
      x = text(" letters");
      P = space();
      N = element("div");
      B = element("button");
      B.textContent = "Apply";
      attr(r, "class", "options svelte-guf68w");
      attr(g, "class", "svelte-guf68w");
      attr(D, "class", "svelte-guf68w");
      attr(B, "class", "svelte-guf68w");
      attr(N, "class", "buttons svelte-guf68w");
    },
    m(V, G) {
      insert(V, r, G);
      for (let s = 0; s < z.length; s += 1) if (z[s]) z[s].m(r, null);
      insert(V, o, G);
      H.m(V, G);
      insert(V, u, G);
      insert(V, g, G);
      append(g, _);
      append(g, m);
      if (K) K.m(g, null);
      append(g, b);
      append(g, E);
      append(g, w);
      append(g, S);
      append(g, L);
      insert(V, O, G);
      insert(V, D, G);
      append(D, C);
      append(D, k);
      if (Q) Q.m(D, null);
      append(D, T);
      append(D, A);
      append(D, R);
      append(D, I);
      append(D, x);
      insert(V, P, G);
      insert(V, N, G);
      append(N, B);
      if (!F) {
        M = listen(B, "click", s[12]);
        F = true;
      }
    },
    p(s, o) {
      if (2688 & o) {
        q = ensure_array_like(s[11]);
        let u;
        for (u = 0; u < q.length; u += 1) {
          const g = get_each_context_1(s, q, u);
          if (z[u]) z[u].p(g, o); else {
            z[u] = create_each_block_1(g);
            z[u].c();
            z[u].m(r, null);
          }
        }
        for (;u < z.length; u += 1) z[u].d(1);
        z.length = q.length;
      }
      if (W === (W = select_block_type_1(s)) && H) H.p(s, o); else {
        H.d(1);
        H = W(s);
        if (H) {
          H.c();
          H.m(u.parentNode, u);
        }
      }
      if (2 & o) set_data(_, s[1]);
      if (s[3]._id == s[4]._id) if (K) K.p(s, o); else {
        K = create_if_block_2(s);
        K.c();
        K.m(g, b);
      } else if (K) {
        K.d(1);
        K = null;
      }
      if (8 & o && V !== (V = new Date(s[3].mtime).toLocaleString() + "")) set_data(E, V);
      if (32 & o && G !== (G = s[5].length + "")) set_data(S, G);
      if (4 & o) set_data(C, s[2]);
      if (s[3]._id == s[4]._id) if (Q) Q.p(s, o); else {
        Q = create_if_block_1(s);
        Q.c();
        Q.m(D, T);
      } else if (Q) {
        Q.d(1);
        Q = null;
      }
      if (16 & o && j !== (j = new Date(s[4].mtime).toLocaleString() + "")) set_data(A, j);
      if (64 & o && U !== (U = s[6].length + "")) set_data(I, U);
    },
    d(s) {
      if (s) {
        detach(r);
        detach(o);
        detach(u);
        detach(g);
        detach(O);
        detach(D);
        detach(P);
        detach(N);
      }
      destroy_each(z, s);
      H.d(s);
      if (K) K.d();
      if (Q) Q.d();
      F = false;
      M();
    }
  };
}

function create_if_block(s) {
  let r, o, u, g, _, m;
  return {
    c() {
      r = element("div");
      r.textContent = "Just for a minute, please!";
      o = space();
      u = element("div");
      g = element("button");
      g.textContent = "Dismiss";
      attr(r, "class", "message svelte-guf68w");
      attr(g, "class", "svelte-guf68w");
      attr(u, "class", "buttons svelte-guf68w");
    },
    m(b, E) {
      insert(b, r, E);
      insert(b, o, E);
      insert(b, u, E);
      append(u, g);
      if (!_) {
        m = listen(g, "click", s[12]);
        _ = true;
      }
    },
    p: noop,
    d(s) {
      if (s) {
        detach(r);
        detach(o);
        detach(u);
      }
      _ = false;
      m();
    }
  };
}

function create_if_block_4(s) {
  let r, o, u, g, _, m, b, E, w, S, L = false, O = s[28][1] + "";
  E = init_binding_group(s[21][0]);
  return {
    c() {
      r = element("label");
      o = element("input");
      g = space();
      _ = element("div");
      m = text(O);
      attr(o, "type", "radio");
      attr(o, "name", "disp");
      o.__value = u = s[28][0];
      set_input_value(o, o.__value);
      attr(o, "class", "sls-setting-tab svelte-guf68w");
      attr(_, "class", "sls-setting-menu-btn svelte-guf68w");
      attr(r, "class", b = null_to_empty("sls-setting-label " + (s[28][0] == s[7] ? "selected" : "")) + " svelte-guf68w");
      E.p(o);
    },
    m(u, b) {
      insert(u, r, b);
      append(r, o);
      o.checked = o.__value === s[7];
      append(r, g);
      append(r, _);
      append(_, m);
      if (!w) {
        S = listen(o, "change", s[20]);
        w = true;
      }
    },
    p(s, g) {
      if (2048 & g && u !== (u = s[28][0])) {
        o.__value = u;
        set_input_value(o, o.__value);
        L = true;
      }
      if (L || 2176 & g) o.checked = o.__value === s[7];
      if (2048 & g && O !== (O = s[28][1] + "")) set_data(m, O);
      if (2176 & g && b !== (b = null_to_empty("sls-setting-label " + (s[28][0] == s[7] ? "selected" : "")) + " svelte-guf68w")) attr(r, "class", b);
    },
    d(s) {
      if (s) detach(r);
      E.r();
      w = false;
      S();
    }
  };
}

function create_each_block_1(s) {
  let r, o = ("" == s[28][0] || false != s[9][s[28][0]]) && create_if_block_4(s);
  return {
    c() {
      if (o) o.c();
      r = empty();
    },
    m(s, u) {
      if (o) o.m(s, u);
      insert(s, r, u);
    },
    p(s, u) {
      if ("" == s[28][0] || false != s[9][s[28][0]]) if (o) o.p(s, u); else {
        o = create_if_block_4(s);
        o.c();
        o.m(r.parentNode, r);
      } else if (o) {
        o.d(1);
        o = null;
      }
    },
    d(s) {
      if (s) detach(r);
      if (o) o.d(s);
    }
  };
}

function create_else_block_1(s) {
  let r;
  return {
    c() {
      r = text("NO PREVIEW");
    },
    m(s, o) {
      insert(s, r, o);
    },
    p: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_3(s) {
  let r, o = ensure_array_like(s[10]), u = [];
  for (let r = 0; r < o.length; r += 1) u[r] = create_each_block(get_each_context(s, o, r));
  return {
    c() {
      r = element("div");
      for (let s = 0; s < u.length; s += 1) u[s].c();
      attr(r, "class", "op-scrollable json-source svelte-guf68w");
    },
    m(s, o) {
      insert(s, r, o);
      for (let s = 0; s < u.length; s += 1) if (u[s]) u[s].m(r, null);
    },
    p(s, g) {
      if (1024 & g) {
        o = ensure_array_like(s[10]);
        let _;
        for (_ = 0; _ < o.length; _ += 1) {
          const m = get_each_context(s, o, _);
          if (u[_]) u[_].p(m, g); else {
            u[_] = create_each_block(m);
            u[_].c();
            u[_].m(r, null);
          }
        }
        for (;_ < u.length; _ += 1) u[_].d(1);
        u.length = o.length;
      }
    },
    d(s) {
      if (s) detach(r);
      destroy_each(u, s);
    }
  };
}

function create_each_block(s) {
  let r, o, u, g = s[25][1] + "";
  return {
    c() {
      r = element("span");
      o = text(g);
      attr(r, "class", u = null_to_empty(s[25][0] == import_diff_match_patch.DIFF_DELETE ? "deleted" : s[25][0] == import_diff_match_patch.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w");
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, _) {
      if (1024 & _ && g !== (g = s[25][1] + "")) set_data(o, g);
      if (1024 & _ && u !== (u = null_to_empty(s[25][0] == import_diff_match_patch.DIFF_DELETE ? "deleted" : s[25][0] == import_diff_match_patch.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w")) attr(r, "class", u);
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_2(s) {
  let r, o, u = revStringToRevNumber(s[3]._rev) + "";
  return {
    c() {
      r = text("Rev:");
      o = text(u);
    },
    m(s, u) {
      insert(s, r, u);
      insert(s, o, u);
    },
    p(s, r) {
      if (8 & r && u !== (u = revStringToRevNumber(s[3]._rev) + "")) set_data(o, u);
    },
    d(s) {
      if (s) {
        detach(r);
        detach(o);
      }
    }
  };
}

function create_if_block_1(s) {
  let r, o, u = revStringToRevNumber(s[4]._rev) + "";
  return {
    c() {
      r = text("Rev:");
      o = text(u);
    },
    m(s, u) {
      insert(s, r, u);
      insert(s, o, u);
    },
    p(s, r) {
      if (16 & r && u !== (u = revStringToRevNumber(s[4]._rev) + "")) set_data(o, u);
    },
    d(s) {
      if (s) {
        detach(r);
        detach(o);
      }
    }
  };
}

function create_fragment(s) {
  let r, o, u, g;
  function select_block_type(s, r) {
    if (!s[3] || !s[4]) return create_if_block; else return create_else_block;
  }
  let _ = select_block_type(s), m = _(s);
  return {
    c() {
      r = element("h2");
      o = text(s[0]);
      u = space();
      m.c();
      g = empty();
      attr(r, "class", "svelte-guf68w");
    },
    m(s, _) {
      insert(s, r, _);
      append(r, o);
      insert(s, u, _);
      m.m(s, _);
      insert(s, g, _);
    },
    p(s, [r]) {
      if (1 & r) set_data(o, s[0]);
      if (_ === (_ = select_block_type(s)) && m) m.p(s, r); else {
        m.d(1);
        m = _(s);
        if (m) {
          m.c();
          m.m(g.parentNode, g);
        }
      }
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) {
        detach(r);
        detach(u);
        detach(g);
      }
      m.d(s);
    }
  };
}

function revStringToRevNumber(s) {
  if (!s) return ""; else return s.split("-")[0];
}

function instance(s, r, o) {
  let u, g, _, m, b, E, {docs: w = []} = r, {callback: S = (async (s, r) => {
    Promise.resolve();
  })} = r, {filename: L = ""} = r, {nameA: O = "A"} = r, {nameB: D = "B"} = r, {defaultSelect: C = ""} = r, k = "", T = "", A = {}, R = {}, I = {}, x = {}, P = C;
  function docToString(s) {
    return "plain" == s.datatype ? getDocData(s.data) : readString(new Uint8Array(decodeBinary(s.data)));
  }
  s.$$set = s => {
    if ("docs" in s) o(13, w = s.docs);
    if ("callback" in s) o(14, S = s.callback);
    if ("filename" in s) o(0, L = s.filename);
    if ("nameA" in s) o(1, O = s.nameA);
    if ("nameB" in s) o(2, D = s.nameB);
    if ("defaultSelect" in s) o(15, C = s.defaultSelect);
  };
  s.$$.update = () => {
    if (991352 & s.$$.dirty) if (w && w.length >= 1) {
      if (w[0].mtime < w[1].mtime) {
        o(3, m = w[0]);
        o(4, b = w[1]);
      } else {
        o(3, m = w[1]);
        o(4, b = w[0]);
      }
      o(5, k = docToString(m));
      o(6, T = docToString(b));
      try {
        o(16, A = false);
        o(17, R = false);
        o(16, A = JSON.parse(k));
        o(17, R = JSON.parse(T));
        o(18, I = mergeObject(A, R));
        o(19, x = mergeObject(R, A));
        if (JSON.stringify(I) == JSON.stringify(x)) o(19, x = false);
      } catch (s) {
        o(19, x = false);
        o(18, I = false);
      }
    }
    if (983040 & s.$$.dirty) o(9, u = {
      "": false,
      A,
      B: R,
      AB: I,
      BA: x
    });
    if (640 & s.$$.dirty) o(8, g = P in u ? u[P] : {});
    if (65792 & s.$$.dirty) o(10, E = function getJsonDiff(s, r) {
      return function getDiff(s, r) {
        const o = new import_diff_match_patch.diff_match_patch, u = o.diff_linesToChars_(s, r), g = o.diff_main(u.chars1, u.chars2, false);
        o.diff_charsToLines_(g, u.lineArray);
        return g;
      }(JSON.stringify(s, null, 2), JSON.stringify(r, null, 2));
    }(A, g));
    if (6 & s.$$.dirty) o(11, _ = [ [ "", "Not now" ], [ "A", O || "A" ], [ "B", D || "B" ], [ "AB", `${O || "A"} + ${D || "B"}` ], [ "BA", `${D || "B"} + ${O || "A"}` ] ]);
  };
  return [ L, O, D, m, b, k, T, P, g, u, E, _, function apply() {
    if (m._id == b._id) {
      if ("A" == P) return S(m._rev, void 0);
      if ("B" == P) return S(b._rev, void 0);
    } else {
      if ("A" == P) return S(void 0, docToString(m));
      if ("B" == P) return S(void 0, docToString(b));
    }
    if ("BA" == P) return S(void 0, JSON.stringify(x, null, 2));
    if ("AB" == P) return S(void 0, JSON.stringify(I, null, 2));
    S(void 0, void 0);
  }, w, S, C, A, R, I, x, function input_change_handler() {
    P = this.__value;
    o(7, P);
  }, [ [] ] ];
}

var context, JsonResolvePane = class extends SvelteComponent {
  constructor(s) {
    super();
    init2(this, s, instance, create_fragment, safe_not_equal, {
      docs: 13,
      callback: 14,
      filename: 0,
      nameA: 1,
      nameB: 2,
      defaultSelect: 15
    }, add_css);
  }
}, JsonResolvePane_default = JsonResolvePane, JsonResolveModal = class extends import_obsidian.Modal {
  constructor(s, r, o, u, g, _, m) {
    super(s);
    this.callback = u;
    this.filename = r;
    this.docs = o;
    this.nameA = g;
    this.nameB = _;
    this.defaultSelect = m;
    waitForSignal(`cancel-internal-conflict:${r}`).then((() => this.close()));
  }
  async UICallback(s, r) {
    this.close();
    await this.callback(s, r);
    this.callback = null;
  }
  onOpen() {
    const {contentEl: s} = this;
    this.titleEl.setText("Conflicted Setting");
    s.empty();
    if (null == this.component) this.component = new JsonResolvePane_default({
      target: s,
      props: {
        docs: this.docs,
        filename: this.filename,
        nameA: this.nameA,
        nameB: this.nameB,
        defaultSelect: this.defaultSelect,
        callback: (s, r) => this.UICallback(s, r)
      }
    });
  }
  onClose() {
    const {contentEl: s} = this;
    s.empty();
    if (null != this.callback) this.callback(null);
    if (null != this.component) {
      this.component.$destroy();
      this.component = null;
    }
  }
};

function reactiveSource(s) {
  return _reactive({
    initialValue: s
  });
}

function reactive(s, r) {
  return _reactive({
    expression: s,
    initialValue: r
  });
}

function _reactive({expression: s, initialValue: r}) {
  let o, u = false;
  const g = new Set, _ = {
    depends: new Set,
    evalCount: 0,
    readCount: 0,
    markDirty() {
      u = true;
      _.markDependedDirty();
      g.forEach((s => s(_)));
    },
    markClean() {
      u = false;
    },
    markDependedDirty() {
      _.depends.forEach((s => s.markDirty()));
    },
    get value() {
      if (context) _.depends.add(context);
      if (!s) return o;
      if (u) {
        const r = o, u = s();
        if (isObjectDifferent(r, u)) {
          o = u;
          _.markClean();
          _.markDependedDirty();
        }
      }
      return o;
    },
    set value(s) {
      if (isObjectDifferent(o, s)) {
        o = s;
        _.markDirty();
      }
    },
    onChanged(s) {
      g.add(s);
    },
    offChanged(s) {
      g.delete(s);
    }
  };
  o = function initialize() {
    const o = context;
    context = _;
    const u = s ? s(r) : r;
    context = o;
    return u;
  }();
  return _;
}

var lockStats = reactiveSource({
  pending: [],
  running: [],
  count: 0
}), collectingChunks = reactiveSource(0), pluginScanningCount = reactiveSource(0), hiddenFilesProcessingCount = reactiveSource(0), hiddenFilesEventCount = reactiveSource(0), logStore = new QueueProcessor((s => s), {
  batchSize: 1,
  suspended: false,
  keepResultUntilDownstreamConnected: true
}), logMessages = reactiveSource([]), d = "​", d2 = "\n";

function serialize(s) {
  var r, o, u, g, _;
  let m = "";
  m += ":";
  m += s.category + d + s.name + d + s.term + d2;
  m += (null != (r = s.version) ? r : "") + d2;
  m += s.mtime + d2;
  for (const r of s.files) {
    m += r.filename + d + (null != (o = r.displayName) ? o : "") + d + (null != (u = r.version) ? u : "") + d2;
    const s = digestHash((null != (g = r.data) ? g : []).join());
    m += r.mtime + d + r.size + d + s + d2;
    for (const s of null != (_ = r.data) ? _ : []) m += s + d;
    m += d2;
  }
  return m;
}

function fetchToken(s, r) {
  const o = s.indexOf(d2, r), u = -1 == o ? s.length : o, g = s.indexOf(d, r), _ = -1 == g ? s.length : g, m = Math.min(u, _);
  let b = m;
  if (u < _) b = m; else b = m + 1;
  return [ b, s.substring(r, m) ];
}

function getTokenizer(s) {
  return {
    pos: 1,
    next() {
      const [r, o] = fetchToken(s, this.pos);
      this.pos = r;
      return o;
    },
    nextLine() {
      const r = s.indexOf(d2, this.pos);
      if (-1 == r) this.pos = s.length; else this.pos = r + 1;
    }
  };
}

function deserialize2(s) {
  const r = getTokenizer(s), o = r.next(), u = r.next(), g = r.next();
  r.nextLine();
  const _ = r.next();
  r.nextLine();
  const m = Number(r.next());
  r.nextLine();
  const b = Object.assign({}, {
    category: o,
    name: u,
    term: g,
    version: _,
    mtime: m,
    files: []
  });
  let E = "";
  do {
    E = r.next();
    if (!E) break;
    const s = r.next(), o = r.next();
    r.nextLine();
    const u = Number(r.next()), g = Number(r.next()), _ = r.next();
    r.nextLine();
    const m = [];
    let w = "";
    do {
      w = r.next();
      if ("" == w) break;
      m.push(w);
    } while ("" != w);
    b.files.push({
      filename: E,
      displayName: s,
      version: o,
      mtime: u,
      size: g,
      data: m,
      hash: _
    });
    r.nextLine();
  } while (E);
  return b;
}

function deserialize(s, r) {
  try {
    if (":" == s[0]) return deserialize2(s); else return JSON.parse(s);
  } catch (o) {
    try {
      return (0, import_obsidian.parseYaml)(s);
    } catch (s) {
      return r;
    }
  }
}

var pluginList = writable([]), pluginIsEnumerating = writable(false), ConfigSync = class extends LiveSyncCommands {
  constructor(s) {
    super(s);
    this.pluginDialog = void 0;
    this.periodicPluginSweepProcessor = new PeriodicProcessor(this.plugin, (async () => await this.scanAllConfigFiles(false)));
    this.pluginList = [];
    this.createMissingConfigurationEntry = throttle((() => this._createMissingConfigurationEntry()), 1e3);
    this.pluginScanProcessor = new QueueProcessor((async s => {
      const r = s[0], o = r.path || this.getPath(r), u = this.pluginList.find((s => s.documentPath == o));
      if (u && u.mtime == r.mtime) return [];
      try {
        const s = await this.loadPluginData(o);
        if (s) {
          let r = [ ...this.pluginList ];
          r = r.filter((r => r.documentPath != s.documentPath));
          r.push(s);
          this.pluginList = r;
          pluginList.set(r);
        }
        return [];
      } catch (s) {
        Logger(`Something happened at enumerating customization :${o}`, LOG_LEVEL_NOTICE);
        Logger(s, LOG_LEVEL_VERBOSE);
      }
      return [];
    }), {
      suspended: false,
      batchSize: 1,
      concurrentLimit: 10,
      delay: 100,
      yieldThreshold: 10,
      maintainDelay: false,
      totalRemainingReactiveSource: pluginScanningCount
    }).startPipeline().root.onUpdateProgress((() => {
      this.createMissingConfigurationEntry();
    }));
    this.recentProcessedInternalFiles = [];
    pluginScanningCount.onChanged((s => {
      const r = s.value;
      pluginIsEnumerating.set(0 != r);
    }));
  }
  get kvDB() {
    return this.plugin.kvDB;
  }
  showPluginSyncModal() {
    if (this.settings.usePluginSync) if (this.pluginDialog) this.pluginDialog.open(); else {
      this.pluginDialog = new PluginDialogModal(this.app, this.plugin);
      this.pluginDialog.open();
    }
  }
  hidePluginSyncModal() {
    if (null != this.pluginDialog) {
      this.pluginDialog.close();
      this.pluginDialog = void 0;
    }
  }
  onunload() {
    var s;
    this.hidePluginSyncModal();
    null == (s = this.periodicPluginSweepProcessor) || s.disable();
  }
  onload() {
    this.plugin.addCommand({
      id: "livesync-plugin-dialog-ex",
      name: "Show customization sync dialog",
      callback: () => {
        this.showPluginSyncModal();
      }
    });
  }
  getFileCategory(s) {
    if (2 == s.split("/").length && s.endsWith(".json")) return "CONFIG";
    if (4 == s.split("/").length && s.startsWith(`${this.app.vault.configDir}/themes/`)) return "THEME";
    if (s.startsWith(`${this.app.vault.configDir}/snippets/`) && s.endsWith(".css")) return "SNIPPET";
    if (s.startsWith(`${this.app.vault.configDir}/plugins/`)) if (s.endsWith("/styles.css") || s.endsWith("/manifest.json") || s.endsWith("/main.js")) return "PLUGIN_MAIN"; else if (s.endsWith("/data.json")) return "PLUGIN_DATA"; else return "";
    return "";
  }
  isTargetPath(s) {
    if (!s.startsWith(this.app.vault.configDir)) return false; else return "" != this.getFileCategory(s);
  }
  async onInitializeDatabase(s) {
    if (this.settings.usePluginSync) try {
      Logger("Scanning customizations...");
      await this.scanAllConfigFiles(s);
      Logger("Scanning customizations : done");
    } catch (s) {
      Logger("Scanning customizations : failed");
      Logger(s, LOG_LEVEL_VERBOSE);
    }
  }
  async beforeReplicate(s) {
    if (this.settings.autoSweepPlugins && this.settings.usePluginSync) await this.scanAllConfigFiles(s);
  }
  async onResume() {
    if (!this.plugin.suspended) {
      if (this.settings.autoSweepPlugins && this.settings.usePluginSync) await this.scanAllConfigFiles(false);
      this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic && !this.settings.watchInternalFileChanges ? 1e3 * PERIODIC_PLUGIN_SWEEP : 0);
    }
  }
  async reloadPluginList(s) {
    this.pluginList = [];
    pluginList.set(this.pluginList);
    await this.updatePluginList(s);
  }
  async loadPluginData(s) {
    const r = await this.localDatabase.getDBEntry(s, void 0, false, false);
    if (r) {
      const o = deserialize(getDocData(r.data), {}), u = [];
      let g = false;
      for (const s of o.files) {
        const r = {
          ...s,
          data: []
        };
        if (!s.hash) {
          const o = digestHash(getDocData(r.data));
          s.hash = o;
          g = true;
        }
        r.data = [ s.hash ];
        u.push(r);
      }
      if (g) {
        Logger(`Digest created for ${s} to improve checking`, LOG_LEVEL_VERBOSE);
        r.data = serialize(o);
        fireAndForget((() => this.localDatabase.putDBEntry(createSavingEntryFromLoadedEntry(r))));
      }
      return {
        ...o,
        documentPath: this.getPath(r),
        files: u
      };
    }
    return false;
  }
  _createMissingConfigurationEntry() {
    let s = false;
    for (const r of this.pluginList) {
      const o = `${r.category}/${r.name}`;
      if (!(o in this.plugin.settings.pluginSyncExtendedSetting)) this.plugin.settings.pluginSyncExtendedSetting[o] = {
        key: o,
        mode: MODE_SELECTIVE,
        files: []
      };
      if (this.plugin.settings.pluginSyncExtendedSetting[o].files.sort().join(",").toLowerCase() != r.files.map((s => s.filename)).sort().join(",").toLowerCase()) {
        this.plugin.settings.pluginSyncExtendedSetting[o].files = r.files.map((s => s.filename)).sort();
        s = true;
      }
    }
    if (s) this.plugin.saveSettingData();
  }
  async updatePluginList(s, r) {
    if (this.settings.usePluginSync) {
      try {
        const s = r ? await this.path2id(r) : "", o = r ? this.localDatabase.findEntries(s, s + "􏿿", {
          include_docs: true,
          key: s,
          limit: 1
        }) : this.localDatabase.findEntries(ICXHeader + "", `${ICXHeader}􏿿`, {
          include_docs: true
        });
        for await (const s of o) {
          const o = s.path || this.getPath(s);
          if (!r || r == o) this.pluginScanProcessor.enqueue(s);
        }
      } finally {
        pluginIsEnumerating.set(false);
      }
      pluginIsEnumerating.set(false);
    } else {
      this.pluginScanProcessor.clearQueue();
      this.pluginList = [];
      pluginList.set(this.pluginList);
    }
  }
  async compareUsingDisplayData(s, r) {
    const o = await this.localDatabase.getDBEntry(s.documentPath), u = await this.localDatabase.getDBEntry(r.documentPath);
    if (o && u) {
      const g = deserialize(getDocData(o.data), {});
      g.documentPath = s.documentPath;
      const _ = deserialize(getDocData(u.data), {});
      _.documentPath = r.documentPath;
      return await this.showJSONMergeDialogAndMerge(o, u, g, _);
    }
    return false;
  }
  showJSONMergeDialogAndMerge(s, r, o, u) {
    const g = {
      ...o.files[0],
      ctime: o.files[0].mtime,
      _id: `${o.documentPath}`
    }, _ = u.files[0], m = {
      ...s,
      ...g,
      datatype: "newnote"
    }, b = {
      ...r,
      ..._,
      datatype: "newnote"
    };
    return serialized("config:merge-data", (() => new Promise((s => {
      Logger("Opening data-merging dialog", LOG_LEVEL_VERBOSE);
      const r = stripAllPrefixes(m.path.split("/").slice(-1).join("/"));
      new JsonResolveModal(this.app, r, [ m, b ], (async (r, u) => {
        if (null == u) return s(false);
        try {
          s(await this.applyData(o, u));
        } catch (r) {
          Logger("Could not apply merged file");
          Logger(r, LOG_LEVEL_VERBOSE);
          s(false);
        }
      }), "📡", "🛰️", "B").open();
    }))));
  }
  async applyData(s, r) {
    Logger(`Applying ${s.displayName || s.name}..`);
    const o = this.app.vault.configDir;
    try {
      if (!s.documentPath) throw "InternalError: Document path not exist";
      const u = await this.localDatabase.getDBEntry(s.documentPath);
      if (false == u) throw "Not found on database";
      const g = deserialize(getDocData(u.data), {});
      for (const u of g.files) {
        Logger(`Applying ${u.filename} of ${s.displayName || s.name}..`);
        try {
          const g = `${o}/${u.filename}`;
          await this.vaultAccess.ensureDirectory(g);
          if (!r) {
            const s = decodeBinary(u.data);
            await this.vaultAccess.adapterWrite(g, s);
          } else await this.vaultAccess.adapterWrite(g, r);
          Logger(`Applying ${u.filename} of ${s.displayName || s.name}.. Done`);
        } catch (r) {
          Logger(`Applying ${u.filename} of ${s.displayName || s.name}.. Failed`);
          Logger(r, LOG_LEVEL_VERBOSE);
        }
      }
      const _ = `${o}/${g.files[0].filename}`;
      await this.storeCustomizationFiles(_);
      await this.updatePluginList(true, _);
      await delay(100);
      Logger(`Config ${s.displayName || s.name} has been applied`, LOG_LEVEL_NOTICE);
      if ("PLUGIN_DATA" == s.category || "PLUGIN_MAIN" == s.category) {
        const r = Object.values(this.app.plugins.manifests), u = this.app.plugins.enabledPlugins, g = r.find((r => u.has(r.id) && r.dir == `${o}/plugins/${s.name}`));
        if (g) {
          Logger(`Unloading plugin: ${g.name}`, LOG_LEVEL_NOTICE, "plugin-reload-" + g.id);
          await this.app.plugins.unloadPlugin(g.id);
          await this.app.plugins.loadPlugin(g.id);
          Logger(`Plugin reloaded: ${g.name}`, LOG_LEVEL_NOTICE, "plugin-reload-" + g.id);
        }
      } else if ("CONFIG" == s.category) scheduleTask("configReload", 250, (async () => {
        if ("yes" == await askYesNo(this.app, "Do you want to restart and reload Obsidian now?")) this.app.commands.executeCommandById("app:reload");
      }));
      return true;
    } catch (r) {
      Logger(`Applying ${s.displayName || s.name}.. Failed`);
      Logger(r, LOG_LEVEL_VERBOSE);
      return false;
    }
  }
  async deleteData(s) {
    try {
      if (s.documentPath) {
        await this.deleteConfigOnDatabase(s.documentPath);
        await this.updatePluginList(false, s.documentPath);
        Logger(`Delete: ${s.documentPath}`, LOG_LEVEL_NOTICE);
      }
      return true;
    } catch (r) {
      Logger(`Failed to delete: ${s.documentPath}`, LOG_LEVEL_NOTICE);
      return false;
    }
  }
  async parseReplicationResultItem(s) {
    if (s._id.startsWith(ICXHeader)) {
      if (this.plugin.settings.usePluginSync) await this.updatePluginList(false, s.path ? s.path : this.getPath(s));
      if (this.plugin.settings.usePluginSync && this.plugin.settings.notifyPluginOrSettingUpdated) if (!this.pluginDialog || this.pluginDialog && !this.pluginDialog.isOpened()) {
        const s = createFragment((s => {
          s.createEl("span", void 0, (s => {
            s.appendText("Some configuration has been arrived, Press ");
            s.appendChild(s.createEl("a", void 0, (s => {
              s.text = "HERE";
              s.addEventListener("click", (() => {
                this.showPluginSyncModal();
              }));
            })));
            s.appendText(" to open the config sync dialog , or press elsewhere to dismiss this message.");
          }));
        })), r = "popupUpdated-plugins";
        scheduleTask(r, 1e3, (async () => {
          var o;
          const u = await memoIfNotExist(r, (() => new import_obsidian.Notice(s, 0)));
          if (!(null == (o = null == u ? void 0 : u.noticeEl) ? void 0 : o.isShown())) memoObject(r, new import_obsidian.Notice(s, 0));
          scheduleTask(r + "-close", 2e4, (() => {
            var s;
            const o = retrieveMemoObject(r);
            if (o) {
              if (null == (s = null == o ? void 0 : o.noticeEl) ? void 0 : s.isShown()) o.hide();
              disposeMemoObject(r);
            }
          }));
        }));
      }
      return true;
    }
    return false;
  }
  async realizeSettingSyncMode() {
    var s;
    null == (s = this.periodicPluginSweepProcessor) || s.disable();
    if (!this.plugin.suspended) if (this.settings.usePluginSync) {
      if (this.settings.autoSweepPlugins) await this.scanAllConfigFiles(false);
      this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic && !this.settings.watchInternalFileChanges ? 1e3 * PERIODIC_PLUGIN_SWEEP : 0);
    }
  }
  async makeEntryFromFile(s) {
    const r = await this.vaultAccess.adapterStat(s);
    let o, u;
    if (!r) return false;
    const g = await this.vaultAccess.adapterReadBinary(s);
    let _;
    try {
      _ = await arrayBufferToBase64(g);
      if (s.toLowerCase().endsWith("/manifest.json")) {
        const r = readString(new Uint8Array(g));
        try {
          const s = JSON.parse(r);
          if ("version" in s) o = `${s.version}`;
          if ("name" in s) u = `${s.name}`;
        } catch (r) {
          Logger(`Configuration sync data: ${s} looks like manifest, but could not read the version`, LOG_LEVEL_INFO);
        }
      }
    } catch (r) {
      Logger(`The file ${s} could not be encoded`);
      Logger(r, LOG_LEVEL_VERBOSE);
      return false;
    }
    const m = r.mtime;
    return {
      filename: s.substring(this.app.vault.configDir.length + 1),
      data: _,
      mtime: m,
      size: r.size,
      version: o,
      displayName: u
    };
  }
  filenameToUnifiedKey(s, r) {
    const o = r || this.plugin.deviceAndVaultName, u = this.getFileCategory(s), g = "CONFIG" == u || "SNIPPET" == u ? s.split("/").slice(-1)[0] : "PLUGIN_ETC" == u ? s.split("/").slice(-2).join("/") : s.split("/").slice(-2)[0];
    return `${ICXHeader}${o}/${u}/${g}.md`;
  }
  async storeCustomizationFiles(s, r) {
    const o = r || this.plugin.deviceAndVaultName;
    if ("" == o) {
      Logger("We have to configure the device name", LOG_LEVEL_NOTICE);
      return;
    }
    const u = this.filenameToUnifiedKey(s, o);
    return await serialized(`plugin-${u}`, (async () => {
      const r = this.getFileCategory(s);
      let u = 0, g = [];
      const _ = "CONFIG" == r || "SNIPPET" == r ? s.split("/").reverse()[0] : s.split("/").reverse()[1], m = s.split("/").slice(0, -1).join("/"), b = this.filenameToUnifiedKey(s, o), E = await this.path2id(b), w = {
        category: r,
        files: [],
        name: _,
        mtime: 0,
        term: o
      };
      if ("CONFIG" == r || "SNIPPET" == r || "PLUGIN_ETC" == r || "PLUGIN_DATA" == r) {
        g = [ s ];
        if ("PLUGIN_ETC" == r) w.displayName = s.split("/").slice(-1).join("/");
      } else if ("PLUGIN_MAIN" == r) g = [ "manifest.json", "main.js", "styles.css" ].map((s => `${m}/${s}`)); else if ("THEME" == r) g = [ "manifest.json", "theme.css" ].map((s => `${m}/${s}`));
      for (const s of g) {
        const r = await this.makeEntryFromFile(s);
        if (false != r) {
          if (r.version) w.version = r.version;
          if (r.displayName) w.displayName = r.displayName;
          u = 0 == u ? r.mtime : (r.mtime + u) / 2;
          w.files.push(r);
        }
      }
      w.mtime = u;
      if (0 == w.files.length) {
        Logger(`Nothing left: deleting.. ${s}`);
        await this.deleteConfigOnDatabase(b);
        await this.updatePluginList(false, b);
        return;
      }
      const S = createTextBlob(serialize(w));
      try {
        const s = await this.localDatabase.getDBEntryMeta(b, void 0, false);
        let r;
        if (false === s) r = {
          _id: E,
          path: b,
          data: S,
          mtime: u,
          ctime: u,
          datatype: "newnote",
          size: S.size,
          children: [],
          deleted: false,
          type: "newnote"
        }; else {
          if (s.mtime == u) return true;
          const o = await this.localDatabase.getDBEntryFromMeta(s, {}, false, false);
          if (o) {
            const s = (await deserialize(getDocData(o.data), {})).files.map((s => ({
              prev: s,
              curr: w.files.find((r => r.filename == s.filename))
            }))).map((async s => {
              var r, o;
              try {
                return await isDocContentSame(null != (o = null == (r = s.curr) ? void 0 : r.data) ? o : [], s.prev.data);
              } catch (s) {
                return false;
              }
            }));
            if ((await Promise.all(s)).every((s => true == s))) {
              Logger(`STORAGE --\x3e DB:${b}: (config) Skipped (Same content)`, LOG_LEVEL_VERBOSE);
              return true;
            }
          }
          r = {
            ...s,
            data: S,
            mtime: u,
            size: S.size,
            datatype: "newnote",
            children: [],
            deleted: false,
            type: "newnote"
          };
        }
        const o = await this.localDatabase.putDBEntry(r);
        await this.updatePluginList(false, r.path);
        Logger(`STORAGE --\x3e DB:${b}: (config) Done`);
        return o;
      } catch (s) {
        Logger(`STORAGE --\x3e DB:${b}: (config) Failed`);
        Logger(s, LOG_LEVEL_VERBOSE);
        return false;
      }
    }));
  }
  async watchVaultRawEventsAsync(s) {
    if (!this.settings.usePluginSync) return false;
    if (!this.isTargetPath(s)) return false;
    const r = await this.vaultAccess.adapterStat(s);
    if (r && "file" != r.type) return false;
    const o = normalizePath(this.app.vault.configDir);
    if (Object.values(this.settings.pluginSyncExtendedSetting).filter((s => s.mode != MODE_SELECTIVE)).map((s => s.files)).flat().map((s => `${o}/${s}`.toLowerCase())).some((r => r.startsWith(s.toLowerCase())))) {
      Logger(`Customization file skipped: ${s}`, LOG_LEVEL_VERBOSE);
      return;
    }
    const u = ~~((r && r.mtime || 0) / 1e3), g = `${s}-${u}`;
    if (this.recentProcessedInternalFiles.contains(g)) return true;
    this.recentProcessedInternalFiles = [ g, ...this.recentProcessedInternalFiles ].slice(0, 100);
    this.storeCustomizationFiles(s).then((() => {}));
  }
  async scanAllConfigFiles(s) {
    var r;
    Logger("Scanning customizing files.", s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "scan-all-config");
    const o = this.plugin.deviceAndVaultName;
    if ("" == o) {
      Logger("We have to configure the device name", LOG_LEVEL_NOTICE);
      return;
    }
    const u = (await this.scanInternalFiles()).filter((s => this.isTargetPath(s))).map((s => ({
      key: this.filenameToUnifiedKey(s),
      file: s
    }))), g = [ ...new Set(u.map((s => s.key))) ];
    let _ = (await this.localDatabase.allDocsRaw({
      startkey: ICXHeader + "",
      endkey: `${ICXHeader}􏿿`,
      include_docs: true
    })).rows.map((s => s.doc)).filter((s => !s.deleted)).map((s => this.getPath(s))).filter((s => s.startsWith(`${ICXHeader}${o}/`)));
    for (const s of g) {
      const o = null == (r = u.find((r => r.key == s))) ? void 0 : r.file;
      if (o) {
        await this.storeCustomizationFiles(o);
        _ = _.filter((r => r != s));
      } else Logger(`scanAllConfigFiles - File not found: ${s}`, LOG_LEVEL_VERBOSE);
    }
    for (const s of _) await this.deleteConfigOnDatabase(s);
    this.updatePluginList(false).then();
  }
  async deleteConfigOnDatabase(s, r = false) {
    const o = (new Date).getTime();
    await serialized("file-x-" + s, (async () => {
      try {
        const r = await this.localDatabase.getDBEntryMeta(s, void 0, false);
        let u;
        if (false === r) {
          Logger(`STORAGE -x> DB:${s}: (config) already deleted (Not found on database)`);
          return;
        } else {
          if (r.deleted) {
            Logger(`STORAGE -x> DB:${s}: (config) already deleted`);
            return;
          }
          u = {
            ...r,
            mtime: o,
            size: 0,
            children: [],
            deleted: true,
            type: "newnote"
          };
        }
        await this.localDatabase.putRaw(u);
        await this.updatePluginList(false, s);
        Logger(`STORAGE -x> DB:${s}: (config) Done`);
      } catch (r) {
        Logger(`STORAGE -x> DB:${s}: (config) Failed`);
        Logger(r, LOG_LEVEL_VERBOSE);
        return false;
      }
    }));
  }
  async scanInternalFiles() {
    return (await this.getFiles(this.app.vault.configDir, 2)).filter((s => s.startsWith("."))).filter((s => !s.startsWith(".trash")));
  }
  async getFiles(s, r) {
    if (-1 == r) return [];
    let o;
    try {
      o = await this.app.vault.adapter.list(s);
    } catch (r) {
      Logger(`Could not traverse(ConfigSync):${s}`, LOG_LEVEL_INFO);
      Logger(r, LOG_LEVEL_VERBOSE);
      return [];
    }
    let u = [ ...o.files ];
    for (const s of o.folders) u = u.concat(await this.getFiles(s, r - 1));
    return u;
  }
};

function add_css2(s) {
  append_styles(s, "svelte-tsbdtg", ".spacer.svelte-tsbdtg{min-width:1px;flex-grow:1}button.svelte-tsbdtg{margin:2px 4px;min-width:3em;max-width:4em}button.svelte-tsbdtg:disabled{border:none;box-shadow:none;background-color:transparent;visibility:collapse}button.svelte-tsbdtg:disabled:hover{border:none;box-shadow:none;background-color:transparent;visibility:collapse}span.message.svelte-tsbdtg{color:var(--text-muted);font-size:var(--font-ui-smaller);padding:0 1em;line-height:var(--line-height-tight)}span.messages.svelte-tsbdtg{display:flex;flex-direction:column;align-items:center}.is-mobile .spacer.svelte-tsbdtg{margin-left:auto}");
}

function get_each_context2(s, r, o) {
  const u = s.slice();
  u[30] = r[o];
  return u;
}

function create_else_block_3(s) {
  let r, o, u, g, _, m, b;
  return {
    c() {
      r = element("span");
      o = space();
      u = element("span");
      u.textContent = "All the same or non-existent";
      g = space();
      _ = element("button");
      m = space();
      b = element("button");
      attr(r, "class", "spacer svelte-tsbdtg");
      attr(u, "class", "message even svelte-tsbdtg");
      _.disabled = true;
      attr(_, "class", "svelte-tsbdtg");
      b.disabled = true;
      attr(b, "class", "svelte-tsbdtg");
    },
    m(s, E) {
      insert(s, r, E);
      insert(s, o, E);
      insert(s, u, E);
      insert(s, g, E);
      insert(s, _, E);
      insert(s, m, E);
      insert(s, b, E);
    },
    p: noop,
    d(s) {
      if (s) {
        detach(r);
        detach(o);
        detach(u);
        detach(g);
        detach(_);
        detach(m);
        detach(b);
      }
    }
  };
}

function create_if_block2(s) {
  let r, o, u, g = !s[0] && create_if_block_12(s);
  return {
    c() {
      r = element("span");
      o = space();
      if (g) g.c();
      u = empty();
      attr(r, "class", "spacer svelte-tsbdtg");
    },
    m(s, _) {
      insert(s, r, _);
      insert(s, o, _);
      if (g) g.m(s, _);
      insert(s, u, _);
    },
    p(s, r) {
      if (!s[0]) if (g) g.p(s, r); else {
        g = create_if_block_12(s);
        g.c();
        g.m(u.parentNode, u);
      } else if (g) {
        g.d(1);
        g = null;
      }
    },
    d(s) {
      if (s) {
        detach(r);
        detach(o);
        detach(u);
      }
      if (g) g.d(s);
    }
  };
}

function create_if_block_12(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A, R, I = ensure_array_like(s[8]), x = [];
  for (let r = 0; r < I.length; r += 1) x[r] = create_each_block2(get_each_context2(s, I, r));
  function select_block_type_1(s, r) {
    if (s[6] || s[1] && "" != s[2]) return create_if_block_42; else return create_else_block_2;
  }
  let P = select_block_type_1(s), N = P(s), B = s[1] && create_if_block_22(s);
  return {
    c() {
      r = element("span");
      o = element("span");
      u = text(s[3]);
      g = space();
      _ = element("span");
      m = text(s[4]);
      b = space();
      E = element("span");
      w = text(s[5]);
      S = space();
      L = element("select");
      O = element("option");
      O.textContent = "-";
      for (let s = 0; s < x.length; s += 1) x[s].c();
      C = space();
      N.c();
      k = space();
      if (B) B.c();
      T = empty();
      attr(o, "class", "message svelte-tsbdtg");
      attr(_, "class", "message svelte-tsbdtg");
      attr(E, "class", "message svelte-tsbdtg");
      attr(r, "class", "messages svelte-tsbdtg");
      O.__value = D = "";
      set_input_value(O, O.__value);
      if (void 0 === s[2]) add_render_callback((() => s[24].call(L)));
    },
    m(D, I) {
      insert(D, r, I);
      append(r, o);
      append(o, u);
      append(r, g);
      append(r, _);
      append(_, m);
      append(r, b);
      append(r, E);
      append(E, w);
      insert(D, S, I);
      insert(D, L, I);
      append(L, O);
      for (let s = 0; s < x.length; s += 1) if (x[s]) x[s].m(L, null);
      select_option(L, s[2], true);
      insert(D, C, I);
      N.m(D, I);
      insert(D, k, I);
      if (B) B.m(D, I);
      insert(D, T, I);
      if (!A) {
        R = listen(L, "change", s[24]);
        A = true;
      }
    },
    p(s, r) {
      if (8 & r[0]) set_data(u, s[3]);
      if (16 & r[0]) set_data(m, s[4]);
      if (32 & r[0]) set_data(w, s[5]);
      if (256 & r[0]) {
        I = ensure_array_like(s[8]);
        let o;
        for (o = 0; o < I.length; o += 1) {
          const u = get_each_context2(s, I, o);
          if (x[o]) x[o].p(u, r); else {
            x[o] = create_each_block2(u);
            x[o].c();
            x[o].m(L, null);
          }
        }
        for (;o < x.length; o += 1) x[o].d(1);
        x.length = I.length;
      }
      if (260 & r[0]) select_option(L, s[2]);
      if (P === (P = select_block_type_1(s)) && N) N.p(s, r); else {
        N.d(1);
        N = P(s);
        if (N) {
          N.c();
          N.m(k.parentNode, k);
        }
      }
      if (s[1]) if (B) B.p(s, r); else {
        B = create_if_block_22(s);
        B.c();
        B.m(T.parentNode, T);
      } else if (B) {
        B.d(1);
        B = null;
      }
    },
    d(s) {
      if (s) {
        detach(r);
        detach(S);
        detach(L);
        detach(C);
        detach(k);
        detach(T);
      }
      destroy_each(x, s);
      N.d(s);
      if (B) B.d(s);
      A = false;
      R();
    }
  };
}

function create_each_block2(s) {
  let r, o, u, g = s[30] + "";
  return {
    c() {
      r = element("option");
      o = text(g);
      r.__value = u = s[30];
      set_input_value(r, r.__value);
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, _) {
      if (256 & _[0] && g !== (g = s[30] + "")) set_data(o, g);
      if (256 & _[0] && u !== (u = s[30])) {
        r.__value = u;
        set_input_value(r, r.__value);
      }
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_else_block_2(s) {
  let r, o, u;
  return {
    c() {
      r = element("button");
      o = space();
      u = element("button");
      r.disabled = true;
      attr(r, "class", "svelte-tsbdtg");
      u.disabled = true;
      attr(u, "class", "svelte-tsbdtg");
    },
    m(s, g) {
      insert(s, r, g);
      insert(s, o, g);
      insert(s, u, g);
    },
    p: noop,
    d(s) {
      if (s) {
        detach(r);
        detach(o);
        detach(u);
      }
    }
  };
}

function create_if_block_42(s) {
  let r, o, u, g;
  function select_block_type_2(s, r) {
    if (s[7]) return create_if_block_5; else return create_else_block_12;
  }
  let _ = select_block_type_2(s), m = _(s);
  return {
    c() {
      m.c();
      r = space();
      o = element("button");
      o.textContent = "✓";
      attr(o, "class", "svelte-tsbdtg");
    },
    m(_, b) {
      m.m(_, b);
      insert(_, r, b);
      insert(_, o, b);
      if (!u) {
        g = listen(o, "click", s[9]);
        u = true;
      }
    },
    p(s, o) {
      if (_ === (_ = select_block_type_2(s)) && m) m.p(s, o); else {
        m.d(1);
        m = _(s);
        if (m) {
          m.c();
          m.m(r.parentNode, r);
        }
      }
    },
    d(s) {
      if (s) {
        detach(r);
        detach(o);
      }
      m.d(s);
      u = false;
      g();
    }
  };
}

function create_else_block_12(s) {
  let r;
  return {
    c() {
      r = element("button");
      r.disabled = true;
      attr(r, "class", "svelte-tsbdtg");
    },
    m(s, o) {
      insert(s, r, o);
    },
    p: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_5(s) {
  let r, o, u;
  return {
    c() {
      r = element("button");
      r.textContent = "🔍";
      attr(r, "class", "svelte-tsbdtg");
    },
    m(g, _) {
      insert(g, r, _);
      if (!o) {
        u = listen(r, "click", s[10]);
        o = true;
      }
    },
    p: noop,
    d(s) {
      if (s) detach(r);
      o = false;
      u();
    }
  };
}

function create_if_block_22(s) {
  let r;
  function select_block_type_3(s, r) {
    if ("" != s[2]) return create_if_block_32; else return create_else_block2;
  }
  let o = select_block_type_3(s), u = o(s);
  return {
    c() {
      u.c();
      r = empty();
    },
    m(s, o) {
      u.m(s, o);
      insert(s, r, o);
    },
    p(s, g) {
      if (o === (o = select_block_type_3(s)) && u) u.p(s, g); else {
        u.d(1);
        u = o(s);
        if (u) {
          u.c();
          u.m(r.parentNode, r);
        }
      }
    },
    d(s) {
      if (s) detach(r);
      u.d(s);
    }
  };
}

function create_else_block2(s) {
  let r, o, u;
  return {
    c() {
      r = element("button");
      r.textContent = "📑";
      attr(r, "class", "svelte-tsbdtg");
    },
    m(g, _) {
      insert(g, r, _);
      if (!o) {
        u = listen(r, "click", s[12]);
        o = true;
      }
    },
    p: noop,
    d(s) {
      if (s) detach(r);
      o = false;
      u();
    }
  };
}

function create_if_block_32(s) {
  let r, o, u;
  return {
    c() {
      r = element("button");
      r.textContent = "🗑️";
      attr(r, "class", "svelte-tsbdtg");
    },
    m(g, _) {
      insert(g, r, _);
      if (!o) {
        u = listen(r, "click", s[11]);
        o = true;
      }
    },
    p: noop,
    d(s) {
      if (s) detach(r);
      o = false;
      u();
    }
  };
}

function create_fragment2(s) {
  let r;
  function select_block_type(s, r) {
    if (s[8].length > 0) return create_if_block2; else return create_else_block_3;
  }
  let o = select_block_type(s), u = o(s);
  return {
    c() {
      u.c();
      r = empty();
    },
    m(s, o) {
      u.m(s, o);
      insert(s, r, o);
    },
    p(s, g) {
      if (o === (o = select_block_type(s)) && u) u.p(s, g); else {
        u.d(1);
        u = o(s);
        if (u) {
          u.c();
          u.m(r.parentNode, r);
        }
      }
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
      u.d(s);
    }
  };
}

function instance2(s, r, o) {
  let {list: u = []} = r, {thisTerm: g = ""} = r, {hideNotApplicable: _ = false} = r, {selectNewest: m = 0} = r, {applyAllPluse: b = 0} = r, {applyData: E} = r, {compareData: w} = r, {deleteData: S} = r, {hidden: L} = r, {plugin: O} = r, {isMaintenanceMode: D = false} = r;
  const C = O.addOnConfigSync;
  let k = "", T = "", A = "", R = "", I = false, x = false, P = 0, N = 0, B = [];
  async function comparePlugin(s, r) {
    var o, u;
    let g = "", _ = "", m = false, b = false;
    if (!s && !r) g = ""; else if (s && !r) g = "⚠ Local only"; else if (r && !s) {
      g = "✓ Remote only";
      b = true;
    } else {
      const _ = (null !== (o = null == s ? void 0 : s.mtime) && void 0 !== o ? o : 0) - (null !== (u = null == r ? void 0 : r.mtime) && void 0 !== u ? u : 0);
      if (_ / 1e3 < -10) {
        g = "✓ Newer";
        b = true;
        m = true;
      } else if (_ / 1e3 > 10) {
        g = "⚠ Older";
        b = true;
        m = true;
      } else {
        g = "⚖️ Same old";
        b = false;
        m = true;
      }
    }
    const E = (null == s ? void 0 : s.version) || "0.0.0", w = (null == r ? void 0 : r.version) || "0.0.0";
    if ((null == s ? void 0 : s.version) || (null == r ? void 0 : r.version)) {
      const s = versionNumberString2Number(E), r = versionNumberString2Number(w);
      if (s == r) _ = "⚖️ Same ver."; else if (s > r) _ = `⚠ Lower ${E} > ${w}`; else if (s < r) _ = `✓ Higher ${E} < ${w}`;
    }
    if (m) {
      const {canApply: o, equivalency: u, canCompare: m} = await async function checkEquivalency(s, r) {
        let o = "", u = false, g = false;
        const _ = [ ...new Set([ ...s.files.map((s => s.filename)), ...r.files.map((s => s.filename)) ]) ].map((o => {
          const u = s.files.find((s => s.filename == o)), g = r.files.find((s => s.filename == o));
          if (!u && !g) return 0; else if (u && !g) return 2; else if (!u && g) return 8; else if (getDocData(u.data) == getDocData(g.data)) return 4; else return 16;
        })).reduce(((s, r) => s | r), 0);
        if (4 == _) {
          o = "⚖️ Same";
          u = false;
        } else if (_ <= 4) {
          o = "Same or local only";
          u = false;
        } else if (16 == _) {
          u = true;
          g = true;
          o = "≠ Different";
        } else {
          u = true;
          g = true;
          o = "≠ Different";
        }
        return {
          equivalency: o,
          canApply: u,
          canCompare: g
        };
      }(s, r);
      return {
        canApply: o,
        freshness: g,
        equivalency: u,
        version: _,
        canCompare: m
      };
    }
    return {
      canApply: b,
      freshness: g,
      equivalency: "",
      version: _,
      canCompare: false
    };
  }
  async function applySelected() {
    const s = u.find((s => s.term == g)), r = u.find((s => s.term == k));
    if (r && await E(r)) C.updatePluginList(true, null == s ? void 0 : s.documentPath);
  }
  s.$$set = s => {
    if ("list" in s) o(13, u = s.list);
    if ("thisTerm" in s) o(14, g = s.thisTerm);
    if ("hideNotApplicable" in s) o(15, _ = s.hideNotApplicable);
    if ("selectNewest" in s) o(16, m = s.selectNewest);
    if ("applyAllPluse" in s) o(17, b = s.applyAllPluse);
    if ("applyData" in s) o(18, E = s.applyData);
    if ("compareData" in s) o(19, w = s.compareData);
    if ("deleteData" in s) o(20, S = s.deleteData);
    if ("hidden" in s) o(0, L = s.hidden);
    if ("plugin" in s) o(21, O = s.plugin);
    if ("isMaintenanceMode" in s) o(1, D = s.isMaintenanceMode);
  };
  s.$$.update = () => {
    if (4268034 & s.$$.dirty[0]) {
      const s = m != P;
      o(22, P = m);
      (async function updateTerms(s, r, u) {
        const m = s.find((s => s.term == g));
        o(2, k = "");
        if (u) o(8, B = [ ...new Set(s.map((s => s.term))) ]); else if (_) {
          const r = [], u = [ ...new Set(s.map((s => s.term))) ];
          for (const o of u) {
            const u = s.find((s => s.term == o));
            if ((await comparePlugin(m, u)).canApply) r.push(o);
          }
          o(8, B = [ ...r ]);
        } else o(8, B = [ ...new Set(s.map((s => s.term))) ].filter((s => s != g)));
        let b = m;
        if (r) {
          for (const r of B) {
            const o = s.find((s => s.term == r));
            if (o && o.mtime && ((null == b ? void 0 : b.mtime) || 0) < o.mtime) b = o;
          }
          if (b && b.term != g) o(2, k = b.term);
        }
      })(u, s, D);
    }
    if (8519685 & s.$$.dirty[0]) {
      const s = b != N;
      o(23, N = b);
      if (s && k) if (!L) applySelected();
    }
    if (24580 & s.$$.dirty[0]) {
      o(3, T = "");
      o(4, A = "");
      o(5, R = "");
      o(6, I = false);
      if ("" == k) ; else if (k == g) {
        o(3, T = "This device");
        o(6, I = false);
      } else (async function performCompare(s, r) {
        var u, g, _;
        const m = await comparePlugin(s, r);
        o(6, I = m.canApply);
        o(3, T = m.freshness);
        o(4, A = m.equivalency);
        o(5, R = m.version);
        o(7, x = m.canCompare);
        if (1 != (null == s ? void 0 : s.files.length) || !(null === (_ = null === (g = null === (u = null == s ? void 0 : s.files) || void 0 === u ? void 0 : u.first()) || void 0 === g ? void 0 : g.filename) || void 0 === _ ? void 0 : _.endsWith(".json"))) o(7, x = false);
      })(u.find((s => s.term == g)), u.find((s => s.term == k)));
    }
  };
  return [ L, D, k, T, A, R, I, x, B, applySelected, async function compareSelected() {
    const s = u.find((s => s.term == g)), r = u.find((s => s.term == k));
    if (s && r && await w(s, r)) C.updatePluginList(true, s.documentPath);
  }, async function deleteSelected() {
    const s = u.find((s => s.term == k));
    if (s && await S(s)) C.reloadPluginList(true);
  }, async function duplicateItem() {
    const s = u.find((s => s.term == g)), r = await askString(O.app, "Duplicate", "device name", "");
    if (r) {
      if (r.contains("/")) {
        Logger('We can not use "/" to the device name', LOG_LEVEL_NOTICE);
        return;
      }
      const o = `${O.app.vault.configDir}/${s.files[0].filename}`;
      await C.storeCustomizationFiles(o, r);
      await C.updatePluginList(false, C.filenameToUnifiedKey(o, r));
    }
  }, u, g, _, m, b, E, w, S, O, P, N, function select_change_handler() {
    k = select_value(this);
    o(2, k);
    o(8, B);
  } ];
}

var PluginCombo = class extends SvelteComponent {
  constructor(s) {
    super();
    init2(this, s, instance2, create_fragment2, safe_not_equal, {
      list: 13,
      thisTerm: 14,
      hideNotApplicable: 15,
      selectNewest: 16,
      applyAllPluse: 17,
      applyData: 18,
      compareData: 19,
      deleteData: 20,
      hidden: 0,
      plugin: 21,
      isMaintenanceMode: 1
    }, add_css2, [ -1, -1 ]);
  }
}, PluginCombo_default = PluginCombo, import_obsidian3 = require("obsidian");

function add_css3(s) {
  append_styles(s, "svelte-664idh", "h3.svelte-664idh.svelte-664idh{position:sticky;top:0;background-color:var(--modal-background)}.labelrow.svelte-664idh.svelte-664idh{margin-left:0.4em;display:flex;justify-content:flex-start;align-items:center;border-top:1px solid var(--background-modifier-border);padding:4px;flex-wrap:wrap}.filerow.svelte-664idh.svelte-664idh{margin-left:1.25em;display:flex;justify-content:flex-start;align-items:center;padding-right:4px;flex-wrap:wrap}.filerow.hideeven.svelte-664idh.svelte-664idh:has(.even),.labelrow.hideeven.svelte-664idh.svelte-664idh:has(.even){display:none}.noterow.svelte-664idh.svelte-664idh{min-height:2em;display:flex}button.status.svelte-664idh.svelte-664idh{flex-grow:0;margin:2px 4px;min-width:3em;max-width:4em}.statusnote.svelte-664idh.svelte-664idh{display:flex;justify-content:flex-end;padding-right:var(--size-4-12);align-items:center;min-width:10em;flex-grow:1}.title.svelte-664idh.svelte-664idh{color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto}.filetitle.svelte-664idh.svelte-664idh{color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto}.buttons.svelte-664idh.svelte-664idh{display:flex;flex-direction:row;justify-content:flex-end;margin-top:8px;flex-wrap:wrap}.buttons.svelte-664idh>button.svelte-664idh{margin-left:4px;width:auto}label.svelte-664idh.svelte-664idh{display:flex;justify-content:center;align-items:center}label.svelte-664idh>span.svelte-664idh{margin-right:0.25em}.is-mobile .title.svelte-664idh.svelte-664idh,.is-mobile .filetitle.svelte-664idh.svelte-664idh{width:100%}.center.svelte-664idh.svelte-664idh{display:flex;justify-content:center;align-items:center;min-height:3em}.maintenancerow.svelte-664idh.svelte-664idh{display:flex;justify-content:flex-end;align-items:center}.maintenancerow.svelte-664idh label.svelte-664idh{margin-right:0.5em;margin-left:0.5em}");
}

function get_each_context3(s, r, o) {
  const u = s.slice();
  u[53] = r[o];
  return u;
}

function get_each_context_12(s, r, o) {
  var u, g, _;
  const m = s.slice();
  m[56] = r[o][0];
  m[57] = r[o][1];
  const b = `${PREFIX_PLUGIN_ALL}/${m[56]}`;
  m[58] = b;
  const E = null != (u = m[5].get(m[58])) ? u : MODE_SELECTIVE;
  m[59] = E;
  const w = `${PREFIX_PLUGIN_MAIN}/${m[56]}`;
  m[60] = w;
  const S = null != (g = m[5].get(m[60])) ? g : MODE_SELECTIVE;
  m[61] = S;
  const L = `${PREFIX_PLUGIN_DATA}/${m[56]}`;
  m[62] = L;
  const O = null != (_ = m[5].get(m[62])) ? _ : MODE_SELECTIVE;
  m[63] = O;
  return m;
}

function get_each_context_2(s, r, o) {
  const u = s.slice();
  u[66] = r[o][0];
  u[67] = r[o][1];
  return u;
}

function get_each_context_3(s, r, o) {
  var u;
  const g = s.slice();
  g[56] = r[o];
  const _ = `${g[66]}/${g[56]}`;
  g[70] = _;
  const m = null != (u = g[5].get(g[70])) ? u : MODE_SELECTIVE;
  g[71] = m;
  return g;
}

function create_if_block_8(s) {
  let r, o, u;
  return {
    c() {
      r = element("button");
      r.textContent = "Reload";
      attr(r, "class", "svelte-664idh");
    },
    m(g, _) {
      insert(g, r, _);
      if (!o) {
        u = listen(r, "click", s[28]);
        o = true;
      }
    },
    p: noop,
    d(s) {
      if (s) detach(r);
      o = false;
      u();
    }
  };
}

function create_if_block_7(s) {
  let r;
  return {
    c() {
      r = element("div");
      r.innerHTML = "<span>Updating list...</span>";
    },
    m(s, o) {
      insert(s, r, o);
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_else_block3(s) {
  let r, o, u, g, _, m = ensure_array_like(Object.entries(s[11]).filter(s[31])), b = [];
  for (let r = 0; r < m.length; r += 1) b[r] = create_each_block_2(get_each_context_2(s, m, r));
  const out = s => transition_out(b[s], 1, 1, (() => {
    b[s] = null;
  }));
  let E = ensure_array_like(groupBy(filterList(s[0], [ "PLUGIN_MAIN", "PLUGIN_DATA", "PLUGIN_ETC" ]), "name")), w = [];
  for (let r = 0; r < E.length; r += 1) w[r] = create_each_block_12(get_each_context_12(s, E, r));
  const out_1 = s => transition_out(w[s], 1, 1, (() => {
    w[s] = null;
  }));
  return {
    c() {
      for (let s = 0; s < b.length; s += 1) b[s].c();
      r = space();
      o = element("div");
      u = element("h3");
      u.textContent = "Plugins";
      g = space();
      for (let s = 0; s < w.length; s += 1) w[s].c();
      attr(u, "class", "svelte-664idh");
    },
    m(s, m) {
      for (let r = 0; r < b.length; r += 1) if (b[r]) b[r].m(s, m);
      insert(s, r, m);
      insert(s, o, m);
      append(o, u);
      append(o, g);
      for (let s = 0; s < w.length; s += 1) if (w[s]) w[s].m(o, null);
      _ = true;
    },
    p(s, u) {
      if (461157 & u[0]) {
        m = ensure_array_like(Object.entries(s[11]).filter(s[31]));
        let o;
        for (o = 0; o < m.length; o += 1) {
          const g = get_each_context_2(s, m, o);
          if (b[o]) {
            b[o].p(g, u);
            transition_in(b[o], 1);
          } else {
            b[o] = create_each_block_2(g);
            b[o].c();
            transition_in(b[o], 1);
            b[o].m(r.parentNode, r);
          }
        }
        group_outros();
        for (o = m.length; o < b.length; o += 1) out(o);
        check_outros();
      }
      if (459045 & u[0]) {
        E = ensure_array_like(groupBy(filterList(s[0], [ "PLUGIN_MAIN", "PLUGIN_DATA", "PLUGIN_ETC" ]), "name"));
        let r;
        for (r = 0; r < E.length; r += 1) {
          const g = get_each_context_12(s, E, r);
          if (w[r]) {
            w[r].p(g, u);
            transition_in(w[r], 1);
          } else {
            w[r] = create_each_block_12(g);
            w[r].c();
            transition_in(w[r], 1);
            w[r].m(o, null);
          }
        }
        group_outros();
        for (r = E.length; r < w.length; r += 1) out_1(r);
        check_outros();
      }
    },
    i(s) {
      if (!_) {
        for (let s = 0; s < m.length; s += 1) transition_in(b[s]);
        for (let s = 0; s < E.length; s += 1) transition_in(w[s]);
        _ = true;
      }
    },
    o(s) {
      b = b.filter(Boolean);
      for (let s = 0; s < b.length; s += 1) transition_out(b[s]);
      w = w.filter(Boolean);
      for (let s = 0; s < w.length; s += 1) transition_out(w[s]);
      _ = false;
    },
    d(s) {
      if (s) {
        detach(r);
        detach(o);
      }
      destroy_each(b, s);
      destroy_each(w, s);
    }
  };
}

function create_if_block_13(s) {
  let r;
  return {
    c() {
      r = element("div");
      r.textContent = "No Items.";
      attr(r, "class", "center svelte-664idh");
    },
    m(s, o) {
      insert(s, r, o);
    },
    p: noop,
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_else_block_4(s) {
  let r, o, u = s[17][s[71]] + "";
  return {
    c() {
      r = element("div");
      o = text(u);
      attr(r, "class", "statusnote svelte-664idh");
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, r) {
      if (96 & r[0] && u !== (u = s[17][s[71]] + "")) set_data(o, u);
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_6(s) {
  let r, o;
  function func_12(...r) {
    return s[33](s[66], s[56], ...r);
  }
  const u = [ s[8], {
    list: s[0].filter(func_12)
  }, {
    hidden: false
  } ];
  let g = {};
  for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
  r = new PluginCombo_default({
    props: g
  });
  return {
    c() {
      create_component(r.$$.fragment);
    },
    m(s, u) {
      mount_component(r, s, u);
      o = true;
    },
    p(o, g) {
      s = o;
      const _ = 2369 & g[0] ? get_spread_update(u, [ 256 & g[0] && get_spread_object(s[8]), 2113 & g[0] && {
        list: s[0].filter(func_12)
      }, u[2] ]) : {};
      r.$set(_);
    },
    i(s) {
      if (!o) {
        transition_in(r.$$.fragment, s);
        o = true;
      }
    },
    o(s) {
      transition_out(r.$$.fragment, s);
      o = false;
    },
    d(s) {
      destroy_component(r, s);
    }
  };
}

function create_each_block_3(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k = s[18](s[71]) + "", T = s[56] + "";
  function click_handler_6(...r) {
    return s[32](s[66], s[56], s[70], ...r);
  }
  const A = [ create_if_block_6, create_else_block_4 ], R = [];
  function select_block_type_1(s, r) {
    if (s[71] == MODE_SELECTIVE) return 0; else return 1;
  }
  w = select_block_type_1(s);
  S = R[w] = A[w](s);
  return {
    c() {
      r = element("div");
      o = element("div");
      u = element("button");
      g = text(k);
      _ = space();
      m = element("span");
      b = text(T);
      E = space();
      S.c();
      attr(u, "class", "status svelte-664idh");
      attr(m, "class", "name");
      attr(o, "class", "title svelte-664idh");
      attr(r, "class", L = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
    },
    m(s, S) {
      insert(s, r, S);
      append(r, o);
      append(o, u);
      append(u, g);
      append(o, _);
      append(o, m);
      append(m, b);
      append(r, E);
      R[w].m(r, null);
      O = true;
      if (!D) {
        C = listen(u, "click", click_handler_6);
        D = true;
      }
    },
    p(o, u) {
      s = o;
      if ((!O || 96 & u[0]) && k !== (k = s[18](s[71]) + "")) set_data(g, k);
      if ((!O || 64 & u[0]) && T !== (T = s[56] + "")) set_data(b, T);
      let _ = w;
      w = select_block_type_1(s);
      if (w === _) R[w].p(s, u); else {
        group_outros();
        transition_out(R[_], 1, 1, (() => {
          R[_] = null;
        }));
        check_outros();
        S = R[w];
        if (!S) {
          S = R[w] = A[w](s);
          S.c();
        } else S.p(s, u);
        transition_in(S, 1);
        S.m(r, null);
      }
      if (!O || 4 & u[0] && L !== (L = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(r, "class", L);
    },
    i(s) {
      if (!O) {
        transition_in(S);
        O = true;
      }
    },
    o(s) {
      transition_out(S);
      O = false;
    },
    d(s) {
      if (s) detach(r);
      R[w].d();
      D = false;
      C();
    }
  };
}

function create_each_block_2(s) {
  let r, o, u, g, _, m = s[67] + "", b = ensure_array_like(s[6][s[66]]), E = [];
  for (let r = 0; r < b.length; r += 1) E[r] = create_each_block_3(get_each_context_3(s, b, r));
  const out = s => transition_out(E[s], 1, 1, (() => {
    E[s] = null;
  }));
  return {
    c() {
      r = element("div");
      o = element("h3");
      u = text(m);
      g = space();
      for (let s = 0; s < E.length; s += 1) E[s].c();
      attr(o, "class", "svelte-664idh");
    },
    m(s, m) {
      insert(s, r, m);
      append(r, o);
      append(o, u);
      append(r, g);
      for (let s = 0; s < E.length; s += 1) if (E[s]) E[s].m(r, null);
      _ = true;
    },
    p(s, o) {
      if ((!_ || 64 & o[0]) && m !== (m = s[67] + "")) set_data(u, m);
      if (461157 & o[0]) {
        b = ensure_array_like(s[6][s[66]]);
        let u;
        for (u = 0; u < b.length; u += 1) {
          const g = get_each_context_3(s, b, u);
          if (E[u]) {
            E[u].p(g, o);
            transition_in(E[u], 1);
          } else {
            E[u] = create_each_block_3(g);
            E[u].c();
            transition_in(E[u], 1);
            E[u].m(r, null);
          }
        }
        group_outros();
        for (u = b.length; u < E.length; u += 1) out(u);
        check_outros();
      }
    },
    i(s) {
      if (!_) {
        for (let s = 0; s < b.length; s += 1) transition_in(E[s]);
        _ = true;
      }
    },
    o(s) {
      E = E.filter(Boolean);
      for (let s = 0; s < E.length; s += 1) transition_out(E[s]);
      _ = false;
    },
    d(s) {
      if (s) detach(r);
      destroy_each(E, s);
    }
  };
}

function create_if_block_52(s) {
  let r, o;
  const u = [ s[8], {
    list: s[57]
  }, {
    hidden: true
  } ];
  let g = {};
  for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
  r = new PluginCombo_default({
    props: g
  });
  return {
    c() {
      create_component(r.$$.fragment);
    },
    m(s, u) {
      mount_component(r, s, u);
      o = true;
    },
    p(s, o) {
      const g = 257 & o[0] ? get_spread_update(u, [ 256 & o[0] && get_spread_object(s[8]), 1 & o[0] && {
        list: s[57]
      }, u[2] ]) : {};
      r.$set(g);
    },
    i(s) {
      if (!o) {
        transition_in(r.$$.fragment, s);
        o = true;
      }
    },
    o(s) {
      transition_out(r.$$.fragment, s);
      o = false;
    },
    d(s) {
      destroy_component(r, s);
    }
  };
}

function create_else_block_32(s) {
  let r, o, u, g, _ = s[17][s[59]] + "";
  return {
    c() {
      r = element("div");
      o = element("div");
      u = text(_);
      g = space();
      attr(o, "class", "statusnote svelte-664idh");
      attr(r, "class", "noterow svelte-664idh");
    },
    m(s, _) {
      insert(s, r, _);
      append(r, o);
      append(o, u);
      append(r, g);
    },
    p(s, r) {
      if (33 & r[0] && _ !== (_ = s[17][s[59]] + "")) set_data(u, _);
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_23(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A, R, I, x, P, N, B, F, M, V = s[18](s[61]) + "", G = s[18](s[63]) + "";
  function click_handler_8(...r) {
    return s[35](s[56], s[60], ...r);
  }
  const j = [ create_if_block_43, create_else_block_22 ], U = [];
  function select_block_type_3(s, r) {
    if (s[61] == MODE_SELECTIVE) return 0; else return 1;
  }
  E = select_block_type_3(s);
  w = U[E] = j[E](s);
  function click_handler_9(...r) {
    return s[36](s[56], s[62], ...r);
  }
  const q = [ create_if_block_33, create_else_block_13 ], z = [];
  function select_block_type_4(s, r) {
    if (s[63] == MODE_SELECTIVE) return 0; else return 1;
  }
  I = select_block_type_4(s);
  x = z[I] = q[I](s);
  return {
    c() {
      r = element("div");
      o = element("div");
      u = element("button");
      g = text(V);
      _ = space();
      m = element("span");
      m.textContent = "MAIN";
      b = space();
      w.c();
      L = space();
      O = element("div");
      D = element("div");
      C = element("button");
      k = text(G);
      T = space();
      A = element("span");
      A.textContent = "DATA";
      R = space();
      x.c();
      P = space();
      attr(u, "class", "status svelte-664idh");
      attr(m, "class", "name");
      attr(o, "class", "filetitle svelte-664idh");
      attr(r, "class", S = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
      attr(C, "class", "status svelte-664idh");
      attr(A, "class", "name");
      attr(D, "class", "filetitle svelte-664idh");
      attr(O, "class", N = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
    },
    m(s, w) {
      insert(s, r, w);
      append(r, o);
      append(o, u);
      append(u, g);
      append(o, _);
      append(o, m);
      append(r, b);
      U[E].m(r, null);
      insert(s, L, w);
      insert(s, O, w);
      append(O, D);
      append(D, C);
      append(C, k);
      append(D, T);
      append(D, A);
      append(O, R);
      z[I].m(O, null);
      append(O, P);
      B = true;
      if (!F) {
        M = [ listen(u, "click", click_handler_8), listen(C, "click", click_handler_9) ];
        F = true;
      }
    },
    p(o, u) {
      s = o;
      if ((!B || 33 & u[0]) && V !== (V = s[18](s[61]) + "")) set_data(g, V);
      let _ = E;
      E = select_block_type_3(s);
      if (E === _) U[E].p(s, u); else {
        group_outros();
        transition_out(U[_], 1, 1, (() => {
          U[_] = null;
        }));
        check_outros();
        w = U[E];
        if (!w) {
          w = U[E] = j[E](s);
          w.c();
        } else w.p(s, u);
        transition_in(w, 1);
        w.m(r, null);
      }
      if (!B || 4 & u[0] && S !== (S = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(r, "class", S);
      if ((!B || 33 & u[0]) && G !== (G = s[18](s[63]) + "")) set_data(k, G);
      let m = I;
      I = select_block_type_4(s);
      if (I === m) z[I].p(s, u); else {
        group_outros();
        transition_out(z[m], 1, 1, (() => {
          z[m] = null;
        }));
        check_outros();
        x = z[I];
        if (!x) {
          x = z[I] = q[I](s);
          x.c();
        } else x.p(s, u);
        transition_in(x, 1);
        x.m(O, P);
      }
      if (!B || 4 & u[0] && N !== (N = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(O, "class", N);
    },
    i(s) {
      if (!B) {
        transition_in(w);
        transition_in(x);
        B = true;
      }
    },
    o(s) {
      transition_out(w);
      transition_out(x);
      B = false;
    },
    d(s) {
      if (s) {
        detach(r);
        detach(L);
        detach(O);
      }
      U[E].d();
      z[I].d();
      F = false;
      run_all(M);
    }
  };
}

function create_else_block_22(s) {
  let r, o, u = s[17][s[61]] + "";
  return {
    c() {
      r = element("div");
      o = text(u);
      attr(r, "class", "statusnote svelte-664idh");
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, r) {
      if (33 & r[0] && u !== (u = s[17][s[61]] + "")) set_data(o, u);
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_43(s) {
  let r, o;
  const u = [ s[8], {
    list: filterList(s[57], [ "PLUGIN_MAIN" ])
  }, {
    hidden: false
  } ];
  let g = {};
  for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
  r = new PluginCombo_default({
    props: g
  });
  return {
    c() {
      create_component(r.$$.fragment);
    },
    m(s, u) {
      mount_component(r, s, u);
      o = true;
    },
    p(s, o) {
      const g = 257 & o[0] ? get_spread_update(u, [ 256 & o[0] && get_spread_object(s[8]), 1 & o[0] && {
        list: filterList(s[57], [ "PLUGIN_MAIN" ])
      }, u[2] ]) : {};
      r.$set(g);
    },
    i(s) {
      if (!o) {
        transition_in(r.$$.fragment, s);
        o = true;
      }
    },
    o(s) {
      transition_out(r.$$.fragment, s);
      o = false;
    },
    d(s) {
      destroy_component(r, s);
    }
  };
}

function create_else_block_13(s) {
  let r, o, u = s[17][s[63]] + "";
  return {
    c() {
      r = element("div");
      o = text(u);
      attr(r, "class", "statusnote svelte-664idh");
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, r) {
      if (33 & r[0] && u !== (u = s[17][s[63]] + "")) set_data(o, u);
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_33(s) {
  let r, o;
  const u = [ s[8], {
    list: filterList(s[57], [ "PLUGIN_DATA" ])
  }, {
    hidden: false
  } ];
  let g = {};
  for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
  r = new PluginCombo_default({
    props: g
  });
  return {
    c() {
      create_component(r.$$.fragment);
    },
    m(s, u) {
      mount_component(r, s, u);
      o = true;
    },
    p(s, o) {
      const g = 257 & o[0] ? get_spread_update(u, [ 256 & o[0] && get_spread_object(s[8]), 1 & o[0] && {
        list: filterList(s[57], [ "PLUGIN_DATA" ])
      }, u[2] ]) : {};
      r.$set(g);
    },
    i(s) {
      if (!o) {
        transition_in(r.$$.fragment, s);
        o = true;
      }
    },
    o(s) {
      transition_out(r.$$.fragment, s);
      o = false;
    },
    d(s) {
      destroy_component(r, s);
    }
  };
}

function create_each_block_12(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A = s[18](s[59]) + "", R = s[56] + "";
  function click_handler_7(...r) {
    return s[34](s[56], s[58], ...r);
  }
  let I = s[59] == MODE_SELECTIVE && create_if_block_52(s);
  const x = [ create_if_block_23, create_else_block_32 ], P = [];
  function select_block_type_2(s, r) {
    if (s[59] == MODE_SELECTIVE) return 0; else return 1;
  }
  L = select_block_type_2(s);
  O = P[L] = x[L](s);
  return {
    c() {
      r = element("div");
      o = element("div");
      u = element("button");
      g = text(A);
      _ = space();
      m = element("span");
      b = text(R);
      E = space();
      if (I) I.c();
      S = space();
      O.c();
      D = empty();
      attr(u, "class", "status svelte-664idh");
      attr(m, "class", "name");
      attr(o, "class", "title svelte-664idh");
      attr(r, "class", w = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
    },
    m(s, w) {
      insert(s, r, w);
      append(r, o);
      append(o, u);
      append(u, g);
      append(o, _);
      append(o, m);
      append(m, b);
      append(r, E);
      if (I) I.m(r, null);
      insert(s, S, w);
      P[L].m(s, w);
      insert(s, D, w);
      C = true;
      if (!k) {
        T = listen(u, "click", click_handler_7);
        k = true;
      }
    },
    p(o, u) {
      s = o;
      if ((!C || 33 & u[0]) && A !== (A = s[18](s[59]) + "")) set_data(g, A);
      if ((!C || 1 & u[0]) && R !== (R = s[56] + "")) set_data(b, R);
      if (s[59] == MODE_SELECTIVE) if (I) {
        I.p(s, u);
        if (33 & u[0]) transition_in(I, 1);
      } else {
        I = create_if_block_52(s);
        I.c();
        transition_in(I, 1);
        I.m(r, null);
      } else if (I) {
        group_outros();
        transition_out(I, 1, 1, (() => {
          I = null;
        }));
        check_outros();
      }
      if (!C || 4 & u[0] && w !== (w = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(r, "class", w);
      let _ = L;
      L = select_block_type_2(s);
      if (L === _) P[L].p(s, u); else {
        group_outros();
        transition_out(P[_], 1, 1, (() => {
          P[_] = null;
        }));
        check_outros();
        O = P[L];
        if (!O) {
          O = P[L] = x[L](s);
          O.c();
        } else O.p(s, u);
        transition_in(O, 1);
        O.m(D.parentNode, D);
      }
    },
    i(s) {
      if (!C) {
        transition_in(I);
        transition_in(O);
        C = true;
      }
    },
    o(s) {
      transition_out(I);
      transition_out(O);
      C = false;
    },
    d(s) {
      if (s) {
        detach(r);
        detach(S);
        detach(D);
      }
      if (I) I.d();
      P[L].d(s);
      k = false;
      T();
    }
  };
}

function create_if_block3(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D = ensure_array_like(s[4]), C = [];
  for (let r = 0; r < D.length; r += 1) C[r] = create_each_block3(get_each_context3(s, D, r));
  return {
    c() {
      r = element("div");
      o = element("div");
      u = element("h3");
      u.textContent = "Maintenance Commands";
      g = space();
      _ = element("div");
      m = element("label");
      m.textContent = "Delete All of";
      b = space();
      E = element("select");
      for (let s = 0; s < C.length; s += 1) C[s].c();
      w = space();
      S = element("button");
      S.textContent = "🗑️";
      attr(u, "class", "svelte-664idh");
      attr(m, "for", "");
      attr(m, "class", "svelte-664idh");
      if (void 0 === s[7]) add_render_callback((() => s[37].call(E)));
      attr(S, "class", "status svelte-664idh");
      attr(_, "class", "maintenancerow svelte-664idh");
      attr(r, "class", "list");
    },
    m(D, k) {
      insert(D, r, k);
      append(r, o);
      append(o, u);
      append(o, g);
      append(o, _);
      append(_, m);
      append(_, b);
      append(_, E);
      for (let s = 0; s < C.length; s += 1) if (C[s]) C[s].m(E, null);
      select_option(E, s[7], true);
      append(_, w);
      append(_, S);
      if (!L) {
        O = [ listen(E, "change", s[37]), listen(S, "click", s[38]) ];
        L = true;
      }
    },
    p(s, r) {
      if (16 & r[0]) {
        D = ensure_array_like(s[4]);
        let o;
        for (o = 0; o < D.length; o += 1) {
          const u = get_each_context3(s, D, o);
          if (C[o]) C[o].p(u, r); else {
            C[o] = create_each_block3(u);
            C[o].c();
            C[o].m(E, null);
          }
        }
        for (;o < C.length; o += 1) C[o].d(1);
        C.length = D.length;
      }
      if (144 & r[0]) select_option(E, s[7]);
    },
    d(s) {
      if (s) detach(r);
      destroy_each(C, s);
      L = false;
      run_all(O);
    }
  };
}

function create_each_block3(s) {
  let r, o, u, g = s[53] + "";
  return {
    c() {
      r = element("option");
      o = text(g);
      r.__value = u = s[53];
      set_input_value(r, r.__value);
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, _) {
      if (16 & _[0] && g !== (g = s[53] + "")) set_data(o, g);
      if (16 & _[0] && u !== (u = s[53])) {
        r.__value = u;
        set_input_value(r, r.__value);
      }
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_fragment3(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A, R, I, x, P, N, B, F, M, V, G, j, U, q, z, W, H, K = s[1] && create_if_block_8(s), Q = s[3] && create_if_block_7(s);
  const J = [ create_if_block_13, create_else_block3 ], Y = [];
  function select_block_type(s, r) {
    if (0 == s[0].length) return 0; else return 1;
  }
  R = select_block_type(s);
  I = Y[R] = J[R](s);
  let X = s[1] && create_if_block3(s);
  return {
    c() {
      r = element("div");
      o = element("div");
      u = element("div");
      g = element("button");
      g.textContent = "Scan changes";
      _ = space();
      m = element("button");
      m.textContent = "Sync once";
      b = space();
      E = element("button");
      E.textContent = "Refresh";
      w = space();
      if (K) K.c();
      S = space();
      L = element("button");
      L.textContent = "Select All Shiny";
      O = space();
      D = element("div");
      C = element("button");
      C.textContent = "Apply All";
      k = space();
      if (Q) Q.c();
      T = space();
      A = element("div");
      I.c();
      x = space();
      if (X) X.c();
      P = space();
      N = element("div");
      B = element("label");
      F = element("span");
      F.textContent = "Hide not applicable items";
      M = element("input");
      V = space();
      G = element("div");
      j = element("label");
      U = element("span");
      U.textContent = "Maintenance mode";
      q = element("input");
      attr(g, "class", "svelte-664idh");
      attr(m, "class", "svelte-664idh");
      attr(E, "class", "svelte-664idh");
      attr(L, "class", "svelte-664idh");
      attr(u, "class", "buttons svelte-664idh");
      attr(C, "class", "svelte-664idh");
      attr(D, "class", "buttons svelte-664idh");
      attr(A, "class", "list");
      attr(F, "class", "svelte-664idh");
      attr(M, "type", "checkbox");
      attr(B, "class", "svelte-664idh");
      attr(N, "class", "buttons svelte-664idh");
      attr(U, "class", "svelte-664idh");
      attr(q, "type", "checkbox");
      attr(j, "class", "svelte-664idh");
      attr(G, "class", "buttons svelte-664idh");
    },
    m(I, J) {
      insert(I, r, J);
      append(r, o);
      append(o, u);
      append(u, g);
      append(u, _);
      append(u, m);
      append(u, b);
      append(u, E);
      append(u, w);
      if (K) K.m(u, null);
      append(u, S);
      append(u, L);
      append(o, O);
      append(o, D);
      append(D, C);
      append(r, k);
      if (Q) Q.m(r, null);
      append(r, T);
      append(r, A);
      Y[R].m(A, null);
      append(r, x);
      if (X) X.m(r, null);
      append(r, P);
      append(r, N);
      append(N, B);
      append(B, F);
      append(B, M);
      M.checked = s[2];
      append(r, V);
      append(r, G);
      append(G, j);
      append(j, U);
      append(j, q);
      q.checked = s[1];
      z = true;
      if (!W) {
        H = [ listen(g, "click", s[25]), listen(m, "click", s[26]), listen(E, "click", s[27]), listen(L, "click", s[29]), listen(C, "click", s[30]), listen(M, "change", s[39]), listen(q, "change", s[40]) ];
        W = true;
      }
    },
    p(s, o) {
      if (s[1]) if (K) K.p(s, o); else {
        K = create_if_block_8(s);
        K.c();
        K.m(u, S);
      } else if (K) {
        K.d(1);
        K = null;
      }
      if (s[3]) if (Q) ; else {
        Q = create_if_block_7(s);
        Q.c();
        Q.m(r, T);
      } else if (Q) {
        Q.d(1);
        Q = null;
      }
      let g = R;
      R = select_block_type(s);
      if (R === g) Y[R].p(s, o); else {
        group_outros();
        transition_out(Y[g], 1, 1, (() => {
          Y[g] = null;
        }));
        check_outros();
        I = Y[R];
        if (!I) {
          I = Y[R] = J[R](s);
          I.c();
        } else I.p(s, o);
        transition_in(I, 1);
        I.m(A, null);
      }
      if (s[1]) if (X) X.p(s, o); else {
        X = create_if_block3(s);
        X.c();
        X.m(r, P);
      } else if (X) {
        X.d(1);
        X = null;
      }
      if (4 & o[0]) M.checked = s[2];
      if (2 & o[0]) q.checked = s[1];
    },
    i(s) {
      if (!z) {
        transition_in(I);
        z = true;
      }
    },
    o(s) {
      transition_out(I);
      z = false;
    },
    d(s) {
      if (s) detach(r);
      if (K) K.d();
      if (Q) Q.d();
      Y[R].d();
      if (X) X.d();
      W = false;
      run_all(H);
    }
  };
}

var PREFIX_PLUGIN_ALL = "PLUGIN_ALL", PREFIX_PLUGIN_DATA = "PLUGIN_DATA", PREFIX_PLUGIN_MAIN = "PLUGIN_MAIN";

function filterList(s, r) {
  return s.filter((s => -1 !== r.indexOf(s.category))).sort(((s, r) => `${s.category}-${s.name}`.localeCompare(`${r.category}-${r.name}`)));
}

function groupBy(s, r) {
  let o = {};
  for (const u of s) {
    const s = r in u ? u[r] : "";
    o[s] = o[s] || [];
    o[s].push(u);
  }
  for (const s in o) o[s] = o[s].sort(((s, r) => `${s.category}-${s.name}`.localeCompare(`${r.category}-${r.name}`)));
  return Object.entries(o).sort((([s], [r]) => `${s}`.localeCompare(`${r}`)));
}

function instance3(s, r, o) {
  let u, g, _, {plugin: m} = r;
  const b = m.addOnConfigSync;
  let E = [], w = 0, S = false, L = false, O = 0, D = false;
  async function requestUpdate() {
    await b.updatePluginList(true);
  }
  async function requestReload() {
    await b.reloadPluginList(true);
  }
  let C = [];
  pluginList.subscribe((s => {
    o(0, E = s);
    o(4, C = unique(E.map((s => s.term))));
  }));
  pluginIsEnumerating.subscribe((s => {
    o(3, L = s);
  }));
  onMount((async () => {
    requestUpdate();
  }));
  async function scanAgain() {
    await b.scanAllConfigFiles(true);
    await requestUpdate();
  }
  async function replicate2() {
    await m.replicate(true);
  }
  function selectAllNewest() {
    o(21, w++, w);
  }
  function applyAll() {
    o(22, O++, O);
  }
  async function applyData(s) {
    return await b.applyData(s);
  }
  async function compareData(s, r) {
    return await b.compareUsingDisplayData(s, r);
  }
  async function deleteData(s) {
    return await b.deleteData(s);
  }
  function askMode(s, r, o) {
    var u;
    const g = new import_obsidian3.Menu;
    g.addItem((s => s.setTitle(r).setIsLabel(true)));
    g.addSeparator();
    const _ = null !== (u = A.get(o)) && void 0 !== u ? u : MODE_SELECTIVE;
    for (const r of [ MODE_SELECTIVE, MODE_AUTOMATIC, MODE_PAUSED ]) g.addItem((u => {
      u.setTitle(`${getIcon(r)}:${T[r]}`).onClick((u => {
        if (r === MODE_AUTOMATIC) askOverwriteModeForAutomatic(s, o); else setMode(o, r);
      })).setChecked(_ == r).setDisabled(_ == r);
    }));
    g.showAtMouseEvent(s);
  }
  function applyAutomaticSync(s, r) {
    var o, u;
    setMode(s, MODE_AUTOMATIC);
    const g = normalizePath(m.app.vault.configDir), _ = (null !== (u = null === (o = m.settings.pluginSyncExtendedSetting[s]) || void 0 === o ? void 0 : o.files) && void 0 !== u ? u : []).map((s => `${g}/${s}`));
    m.addOnHiddenFileSync.syncInternalFilesAndDatabase(r, true, false, _);
  }
  function askOverwriteModeForAutomatic(s, r) {
    const o = new import_obsidian3.Menu;
    o.addItem((s => s.setTitle("Initial Action").setIsLabel(true)));
    o.addSeparator();
    o.addItem((s => {
      s.setTitle("↑: Overwrite Remote").onClick((s => {
        applyAutomaticSync(r, "pushForce");
      }));
    })).addItem((s => {
      s.setTitle("↓: Overwrite Local").onClick((s => {
        applyAutomaticSync(r, "pullForce");
      }));
    })).addItem((s => {
      s.setTitle("⇅: Use newer").onClick((s => {
        applyAutomaticSync(r, "safe");
      }));
    }));
    o.showAtMouseEvent(s);
  }
  const k = {
    [MODE_SELECTIVE]: "🔀",
    [MODE_PAUSED]: "⛔",
    [MODE_AUTOMATIC]: "✨"
  }, T = {
    [MODE_SELECTIVE]: "Selective",
    [MODE_PAUSED]: "Ignore",
    [MODE_AUTOMATIC]: "Automatic"
  };
  function setMode(s, r) {
    if (s.startsWith(PREFIX_PLUGIN_ALL + "/")) {
      setMode(PREFIX_PLUGIN_DATA + s.substring(PREFIX_PLUGIN_ALL.length), r);
      setMode(PREFIX_PLUGIN_MAIN + s.substring(PREFIX_PLUGIN_ALL.length), r);
    }
    const u = unique(E.filter((r => `${r.category}/${r.name}` == s)).map((s => s.files)).flat().map((s => s.filename)));
    A.set(s, r);
    o(5, R = A);
    if (!(s in m.settings.pluginSyncExtendedSetting)) o(20, m.settings.pluginSyncExtendedSetting[s] = {
      key: s,
      mode: r,
      files: []
    }, m);
    o(20, m.settings.pluginSyncExtendedSetting[s].files = u, m);
    o(20, m.settings.pluginSyncExtendedSetting[s].mode = r, m);
    m.saveSettingData();
  }
  function getIcon(s) {
    if (s in k) return k[s];
  }
  let A = new Map, R = new Map;
  for (const {key: s, mode: r} of Object.values(m.settings.pluginSyncExtendedSetting)) A.set(s, r);
  R = A;
  let I = {}, x = "";
  async function deleteAllItems(s) {
    const r = E.filter((r => r.term == s));
    for (const s of r) await deleteData(s);
    b.reloadPluginList(true);
  }
  s.$$set = s => {
    if ("plugin" in s) o(20, m = s.plugin);
  };
  s.$$.update = () => {
    if (1048576 & s.$$.dirty[0]) o(24, g = m.deviceAndVaultName);
    if (32505858 & s.$$.dirty[0]) o(8, _ = {
      thisTerm: g,
      hideNotApplicable: u,
      selectNewest: w,
      applyAllPluse: O,
      applyData,
      compareData,
      deleteData,
      plugin: m,
      isMaintenanceMode: D
    });
    if (1048577 & s.$$.dirty[0]) {
      const s = Object.keys(m.settings.pluginSyncExtendedSetting);
      o(6, I = [ ...E, ...s.map((s => `${s}///`.split("/"))).filter((s => s[0] && s[1])).map((s => ({
        category: s[0],
        name: s[1],
        displayName: s[1]
      }))) ].sort(((s, r) => {
        var o, u;
        return (null !== (o = s.displayName) && void 0 !== o ? o : s.name).localeCompare(null !== (u = r.displayName) && void 0 !== u ? u : r.name);
      })).reduce(((s, r) => {
        var o, u;
        return {
          ...s,
          [r.category]: unique(r.category in s ? [ ...s[r.category], null !== (o = r.displayName) && void 0 !== o ? o : r.name ] : [ null !== (u = r.displayName) && void 0 !== u ? u : r.name ])
        };
      }), {}));
    }
  };
  o(23, u = false);
  return [ E, D, S, L, C, R, I, x, _, requestUpdate, requestReload, {
    CONFIG: "Configuration",
    THEME: "Themes",
    SNIPPET: "Snippets"
  }, scanAgain, replicate2, selectAllNewest, applyAll, askMode, T, getIcon, deleteAllItems, m, w, O, u, g, () => scanAgain(), () => replicate2(), () => requestUpdate(), () => requestReload(), () => selectAllNewest(), () => applyAll(), ([s, r]) => s in I, (s, r, o, u) => askMode(u, `${s}/${r}`, o), (s, r, o) => o.category == s && o.name == r, (s, r, o) => askMode(o, `${PREFIX_PLUGIN_ALL}/${s}`, r), (s, r, o) => askMode(o, `${PREFIX_PLUGIN_MAIN}/${s}/MAIN`, r), (s, r, o) => askMode(o, `${PREFIX_PLUGIN_DATA}/${s}`, r), function select_change_handler() {
    x = select_value(this);
    o(7, x);
    o(4, C);
  }, s => {
    deleteAllItems(x);
  }, function input0_change_handler() {
    S = this.checked;
    o(2, S);
  }, function input1_change_handler() {
    D = this.checked;
    o(1, D);
  } ];
}

var PluginPane = class extends SvelteComponent {
  constructor(s) {
    super();
    init2(this, s, instance3, create_fragment3, safe_not_equal, {
      plugin: 20
    }, add_css3, [ -1, -1, -1 ]);
  }
}, PluginPane_default = PluginPane, PluginDialogModal = class extends import_obsidian.Modal {
  isOpened() {
    return null != this.component;
  }
  constructor(s, r) {
    super(s);
    this.plugin = r;
  }
  onOpen() {
    const {contentEl: s} = this;
    this.titleEl.setText("Customization Sync (Beta2)");
    if (!this.component) this.component = new PluginPane_default({
      target: s,
      props: {
        plugin: this.plugin
      }
    });
  }
  onClose() {
    if (this.component) {
      this.component.$destroy();
      this.component = void 0;
    }
  }
}, InputStringDialog = class extends import_obsidian.Modal {
  constructor(s, r, o, u, g, _) {
    super(s);
    this.result = false;
    this.isManuallyClosed = false;
    this.isPassword = false;
    this.onSubmit = _;
    this.title = r;
    this.placeholder = u;
    this.key = o;
    this.isPassword = g;
  }
  onOpen() {
    const {contentEl: s} = this;
    this.titleEl.setText(this.title);
    const r = s.createDiv();
    new import_obsidian.Setting(r).setName(this.key).setClass(this.isPassword ? "password-input" : "normal-input").addText((s => s.onChange((s => {
      this.result = s;
    }))));
    new import_obsidian.Setting(r).addButton((s => s.setButtonText("Ok").setCta().onClick((() => {
      this.isManuallyClosed = true;
      this.close();
    })))).addButton((s => s.setButtonText("Cancel").setCta().onClick((() => {
      this.close();
    }))));
  }
  onClose() {
    const {contentEl: s} = this;
    s.empty();
    if (this.isManuallyClosed) this.onSubmit(this.result); else this.onSubmit(false);
  }
}, PopoverSelectString = class extends import_obsidian.FuzzySuggestModal {
  constructor(s, r, o, u, g) {
    super(s);
    this.callback = () => {};
    this.getItemsFun = () => [ "yes", "no" ];
    this.app = s;
    this.setPlaceholder((null != o ? o : "y/n) ") + r);
    if (u) this.getItemsFun = u;
    this.callback = g;
  }
  getItems() {
    return this.getItemsFun();
  }
  getItemText(s) {
    return s;
  }
  onChooseItem(s, r) {
    var o;
    null == (o = this.callback) || o.call(this, s);
    this.callback = void 0;
  }
  onClose() {
    setTimeout((() => {
      if (this.callback) {
        this.callback("");
        this.callback = void 0;
      }
    }), 100);
  }
}, MessageBox = class extends import_obsidian.Modal {
  constructor(s, r, o, u, g, _, m) {
    super(s.app);
    this.result = false;
    this.isManuallyClosed = false;
    this.timer = void 0;
    this.plugin = s;
    this.title = r;
    this.contentMd = o;
    this.buttons = u;
    this.onSubmit = m;
    this.defaultAction = g;
    this.timeout = _;
    if (this.timeout) this.timer = setInterval((() => {
      var s;
      if (void 0 !== this.timeout) {
        this.timeout--;
        if (this.timeout < 0) {
          if (this.timer) {
            clearInterval(this.timer);
            this.timer = void 0;
          }
          this.result = g;
          this.isManuallyClosed = true;
          this.close();
        } else null == (s = this.defaultButtonComponent) || s.setButtonText(`( ${this.timeout} ) ${g}`);
      }
    }), 1e3);
  }
  onOpen() {
    const {contentEl: s} = this;
    this.titleEl.setText(this.title);
    s.addEventListener("click", (() => {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = void 0;
      }
    }));
    const r = s.createDiv();
    import_obsidian.MarkdownRenderer.render(this.plugin.app, this.contentMd, r, "/", this.plugin);
    const o = new import_obsidian.Setting(s);
    o.controlEl.style.flexWrap = "wrap";
    for (const s of this.buttons) o.addButton((r => {
      r.setButtonText(s).onClick((() => {
        this.isManuallyClosed = true;
        this.result = s;
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = void 0;
        }
        this.close();
      }));
      if (s == this.defaultAction) this.defaultButtonComponent = r;
      return r;
    }));
  }
  onClose() {
    const {contentEl: s} = this;
    s.empty();
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = void 0;
    }
    if (this.isManuallyClosed) this.onSubmit(this.result); else this.onSubmit(false);
  }
};

function confirmWithMessage(s, r, o, u, g, _) {
  return new Promise((m => {
    new MessageBox(s, r, o, u, g, _, (s => m(s))).open();
  }));
}

var __save, _save_fn, __load, _load_fn, __queueSave, _queueSave_fn, sameChangePairs, YieldOperationNumbers = 100, PersistentMap = class {
  constructor(s, r) {
    __privateAdd(this, __save);
    __privateAdd(this, __load);
    __privateAdd(this, __queueSave);
    this._setCount = YieldOperationNumbers;
    this._key = s;
    this._map = new Map(null != r ? r : []);
    __privateMethod(this, __load, _load_fn).call(this, r);
  }
  flush() {
    __privateMethod(this, __save, _save_fn).call(this);
  }
  delete(s) {
    const r = this._map.delete(s);
    __privateMethod(this, __queueSave, _queueSave_fn).call(this);
    return r;
  }
  has(s) {
    return this._map.has(s);
  }
  set(s, r) {
    this._map.set(s, r);
    __privateMethod(this, __queueSave, _queueSave_fn).call(this);
    return this;
  }
  clear() {
    this._map = new Map;
    __privateMethod(this, __save, _save_fn).call(this);
  }
  get(s, r) {
    const o = this._map.get(s);
    if (void 0 === o) return r; else return o;
  }
};

__save = new WeakSet;

_save_fn = function() {
  localStorage.setItem(this._key, JSON.stringify([ ...this._map.entries() ]));
};

__load = new WeakSet;

_load_fn = function(s = []) {
  var r;
  try {
    const o = null != (r = localStorage.getItem(this._key)) ? r : "", u = "" === o ? "[]" : o, g = JSON.parse(u);
    this._map = new Map([ ...g, ...s ]);
  } catch (r) {
    console.log(`Map read error : ${this._key}`);
    console.dir(r);
    this._map = new Map([ ...s ]);
  }
  return Promise.resolve();
};

__queueSave = new WeakSet;

_queueSave_fn = function() {
  this._setCount--;
  if (this._setCount < 0) {
    this._setCount = YieldOperationNumbers;
    scheduleTask(`save-map-${this._key}`, 0, (() => __privateMethod(this, __save, _save_fn).call(this)));
  }
  scheduleTask(`save-map-${this._key}`, 150, (() => __privateMethod(this, __save, _save_fn).call(this)));
};

function initializeStores(s) {
  sameChangePairs = new PersistentMap(`ls-persist-same-changes-${s}`);
}

async function path2id(s, r) {
  const o = s.split(":"), u = o.pop(), g = normalizePath(u);
  o.push(g);
  const _ = o.join(":");
  return await path2id_base(_, r);
}

function id2path(s, r) {
  const o = id2path_base(s, r).split(":"), u = o.pop(), g = normalizePath(u);
  o.push(g);
  return o.join(":");
}

function getPath2(s) {
  return id2path(s._id, s);
}

function getPathWithoutPrefix(s) {
  return stripAllPrefixes(getPath2(s));
}

function getPathFromTFile(s) {
  return s.path;
}

var memos = {};

function memoObject(s, r) {
  memos[s] = r;
  return memos[s];
}

async function memoIfNotExist(s, r) {
  if (!(s in memos)) {
    const o = r(), u = o instanceof Promise ? await o : o;
    memos[s] = u;
  }
  return memos[s];
}

function retrieveMemoObject(s) {
  if (s in memos) return memos[s]; else return false;
}

function disposeMemoObject(s) {
  delete memos[s];
}

function isSensibleMargeApplicable(s) {
  if (s.endsWith(".md")) return true; else return false;
}

function isObjectMargeApplicable(s) {
  if (s.endsWith(".canvas")) return true;
  if (s.endsWith(".json")) return true; else return false;
}

function tryParseJSON(s, r) {
  try {
    return JSON.parse(s);
  } catch (s) {
    return r;
  }
}

var MARK_OPERATOR = "", MARK_DELETED = `${MARK_OPERATOR}__DELETED`, MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`, MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;

function unorderedArrayToObject(s) {
  return s.map((s => ({
    [s.id]: s
  }))).reduce(((s, r) => ({
    ...s,
    ...r
  })), {});
}

function objectToUnorderedArray(s) {
  const r = Object.entries(s);
  if (r.some((s => {
    var r;
    return s[0] != (null == (r = s[1]) ? void 0 : r.id);
  }))) throw new Error("Item looks like not unordered array");
  return r.map((s => s[1]));
}

function generatePatchUnorderedArray(s, r) {
  if (s.every((s => "object" == typeof s && "id" in s)) && r.every((s => "object" == typeof s && "id" in s))) {
    const o = generatePatchObj(unorderedArrayToObject(s), unorderedArrayToObject(r));
    if (Object.keys(o).length > 0) return {
      [MARK_ISARRAY]: o
    }; else return {};
  }
  return {
    [MARK_SWAPPED]: r
  };
}

function generatePatchObj(s, r) {
  const o = Object.entries(s), u = new Map(o), g = {}, _ = Object.entries(r);
  for (const [s, r] of _) if (!u.has(s)) {
    g[s] = r;
    u.delete(s);
  } else {
    const o = u.get(s);
    if (typeof o != typeof r || Array.isArray(o) !== Array.isArray(r)) g[s] = {
      [MARK_SWAPPED]: r
    }; else if ("object" == typeof o && "object" == typeof r && !Array.isArray(o) && !Array.isArray(r)) {
      const u = generatePatchObj(o, r);
      if (Object.keys(u).length > 0) g[s] = u;
    } else if ("object" == typeof o && "object" == typeof r && Array.isArray(o) && Array.isArray(r)) {
      const u = generatePatchUnorderedArray(o, r);
      if (Object.keys(u).length > 0) g[s] = u;
    } else if ("object" != typeof o && "object" != typeof r) {
      if (JSON.stringify(u.get(s)) !== JSON.stringify(r)) g[s] = r;
    } else if (JSON.stringify(u.get(s)) !== JSON.stringify(r)) g[s] = {
      [MARK_SWAPPED]: r
    };
    u.delete(s);
  }
  for (const [s] of u) g[s] = MARK_DELETED;
  return g;
}

function applyPatch(s, r) {
  const o = s, u = Object.entries(r);
  for (const [s, r] of u) if (r != MARK_DELETED) if ("object" == typeof r) {
    if (MARK_SWAPPED in r) {
      o[s] = r[MARK_SWAPPED];
      continue;
    }
    if (MARK_ISARRAY in r) {
      if (!(s in o)) o[s] = [];
      if (!Array.isArray(o[s])) throw new Error("Patch target type is mismatched (array to something)");
      const u = objectToUnorderedArray(applyPatch(unorderedArrayToObject(o[s]), r[MARK_ISARRAY]));
      o[s] = [ ...u ];
    } else {
      if (!(s in o)) {
        o[s] = r;
        continue;
      }
      o[s] = applyPatch(o[s], r);
    }
  } else o[s] = r; else delete o[s];
  return o;
}

function mergeObject(s, r) {
  const o = Object.entries(r), u = {
    ...s
  };
  if (typeof s != typeof r || Array.isArray(s) !== Array.isArray(r)) return r;
  for (const [s, r] of o) if (s in u) {
    const o = u[s];
    if (typeof r != typeof o || Array.isArray(r) !== Array.isArray(o)) u[s] = r; else if ("object" == typeof r && "object" == typeof o && !Array.isArray(r) && !Array.isArray(o)) u[s] = mergeObject(r, o); else if ("object" == typeof r && "object" == typeof o && Array.isArray(r) && Array.isArray(o)) u[s] = [ ...new Set([ ...r, ...o ]) ]; else u[s] = r;
  } else u[s] = r;
  const g = Object.fromEntries(Object.entries(u).sort(((s, r) => s[0] < r[0] ? -1 : s[0] > r[0] ? 1 : 0)));
  if (Array.isArray(s) && Array.isArray(r)) return Object.values(g); else return g;
}

function flattenObject(s, r = []) {
  if ("object" != typeof s) return [ [ r.join("."), s ] ];
  if (Array.isArray(s)) return [ [ r.join("."), JSON.stringify(s) ] ];
  const o = Object.entries(s), u = [];
  for (const [s, g] of o) {
    const o = flattenObject(g, [ ...r, s ]);
    u.push(...o);
  }
  return u;
}

function isValidPath(s) {
  if (import_obsidian.Platform.isDesktop) {
    if ("darwin" == process.platform) return isValidFilenameInDarwin(s);
    if ("linux" == process.platform) return isValidFilenameInLinux(s); else return isValidFilenameInWidows(s);
  }
  if (import_obsidian.Platform.isAndroidApp) return isValidFilenameInAndroid(s);
  if (import_obsidian.Platform.isIosApp) return isValidFilenameInDarwin(s);
  Logger("Could not determine platform for checking filename", LOG_LEVEL_VERBOSE);
  return isValidFilenameInWidows(s);
}

function isInternalMetadata(s) {
  return s.startsWith(ICHeader);
}

function stripInternalMetadataPrefix(s) {
  return s.substring(ICHeaderLength);
}

function isChunk(s) {
  return s.startsWith(CHeader);
}

function isPluginMetadata(s) {
  return s.startsWith(PSCHeader);
}

function isCustomisationSyncMetadata(s) {
  return s.startsWith(ICXHeader);
}

var askYesNo = (s, r) => new Promise((o => {
  new PopoverSelectString(s, r, void 0, void 0, (s => o(s))).open();
})), askSelectString = (s, r, o) => {
  const getItemsFun = () => o;
  return new Promise((o => {
    new PopoverSelectString(s, r, "", getItemsFun, (s => o(s))).open();
  }));
}, askString = (s, r, o, u, g = false) => new Promise((_ => {
  new InputStringDialog(s, r, o, u, g, (s => _(s))).open();
})), PeriodicProcessor = class {
  constructor(s, r) {
    this._plugin = s;
    this._process = r;
  }
  async process() {
    try {
      await this._process();
    } catch (s) {
      Logger(s);
    }
  }
  enable(s) {
    this.disable();
    if (0 != s) {
      this._timer = window.setInterval((() => fireAndForget((async () => {
        await this.process();
        if (this._plugin._unloaded) this.disable();
      }))), s);
      this._plugin.registerInterval(this._timer);
    }
  }
  disable() {
    if (void 0 !== this._timer) {
      window.clearInterval(this._timer);
      this._timer = void 0;
    }
  }
}, _requestToCouchDB = async (s, r, o, u, g, _, m) => {
  const b = String.fromCharCode.apply(null, [ ...writeString(`${r}:${o}`) ]), E = {
    url: `${s}/${g}`,
    method: m || (_ ? "PUT" : "GET"),
    headers: {
      authorization: "Basic " + window.btoa(b),
      origin: u
    },
    contentType: "application/json",
    body: _ ? JSON.stringify(_) : void 0
  };
  return await (0, import_obsidian.requestUrl)(E);
}, requestToCouchDB = async (s, r, o, u = "", g, _, m) => {
  const b = "_node/_local/_config" + (g ? "/" + g : "");
  return await _requestToCouchDB(s, r, o, u, b, _, m);
};

async function performRebuildDB(s, r) {
  if ("localOnly" == r) await s.addOnSetup.fetchLocal();
  if ("localOnlyWithChunks" == r) await s.addOnSetup.fetchLocal(true);
  if ("remoteOnly" == r) await s.addOnSetup.rebuildRemote();
  if ("rebuildBothByThisDevice" == r) await s.addOnSetup.rebuildEverything();
}

var BASE_IS_NEW = Symbol("base"), TARGET_IS_NEW = Symbol("target"), EVEN = Symbol("even"), resolution = 2e3;

function compareMTime(s, r) {
  const o = ~~(s / resolution) * resolution, u = ~~(r / resolution) * resolution;
  if (o == u) return EVEN;
  if (o > u) return BASE_IS_NEW;
  if (o < u) return TARGET_IS_NEW;
  throw new Error("Unexpected error");
}

function markChangesAreSame(s, r, o) {
  var u;
  if (r === o) return true;
  const g = "string" == typeof s ? s : s instanceof import_obsidian.TFile ? s.path : null != (u = s.path) ? u : s._id, _ = sameChangePairs.get(g, []) || [];
  if (_.some((s => s == r || s == o))) sameChangePairs.set(g, [ ...new Set([ ..._, r, o ]) ]); else sameChangePairs.set(g, [ r, o ]);
}

function isMarkedAsSameChanges(s, r) {
  var o;
  const u = "string" == typeof s ? s : s instanceof import_obsidian.TFile ? s.path : null != (o = s.path) ? o : s._id, g = sameChangePairs.get(u, []) || [];
  if (r.every((s => -1 !== g.indexOf(s)))) return EVEN;
}

function compareFileFreshness(s, r) {
  var o, u, g, _, m, b;
  if (void 0 === s && null == r) return EVEN;
  if (null == s) return TARGET_IS_NEW;
  if (null == r) return BASE_IS_NEW;
  const E = s instanceof import_obsidian.TFile ? null != (u = null == (o = null == s ? void 0 : s.stat) ? void 0 : o.mtime) ? u : 0 : null != (g = null == s ? void 0 : s.mtime) ? g : 0, w = r instanceof import_obsidian.TFile ? null != (m = null == (_ = null == r ? void 0 : r.stat) ? void 0 : _.mtime) ? m : 0 : null != (b = null == r ? void 0 : r.mtime) ? b : 0;
  if (E && w && isMarkedAsSameChanges(s, [ E, w ])) return EVEN; else return compareMTime(E, w);
}

var import_obsidian5 = require("obsidian");

function add_css4(s) {
  append_styles(s, "svelte-1mgvexx", "label.svelte-1mgvexx.svelte-1mgvexx{min-width:4em;width:4em;display:inline-flex;flex-direction:row;justify-content:flex-end}ul.svelte-1mgvexx.svelte-1mgvexx{flex-grow:1;display:inline-flex;flex-direction:column;list-style-type:none;margin-block-start:0;margin-block-end:0;margin-inline-start:0px;margin-inline-end:0px;padding-inline-start:0}li.svelte-1mgvexx.svelte-1mgvexx{padding:var(--size-2-1) var(--size-4-1);display:inline-flex;flex-grow:1;align-items:center;justify-content:flex-end;gap:var(--size-4-2)}li.svelte-1mgvexx input.svelte-1mgvexx{min-width:10em}button.iconbutton.svelte-1mgvexx.svelte-1mgvexx{max-width:4em}");
}

function get_each_context4(s, r, o) {
  const u = s.slice();
  u[15] = r[o];
  u[16] = r;
  u[17] = o;
  return u;
}

function create_each_block4(s) {
  let r, o, u, g, _, m, b, E, w, S = s[2][s[17]] + "", L = s[3][s[17]] + "";
  function input_input_handler() {
    s[8].call(_, s[16], s[17]);
  }
  function click_handler() {
    return s[9](s[17]);
  }
  return {
    c() {
      r = element("li");
      o = element("label");
      u = text(S);
      g = text(L);
      _ = element("input");
      b = element("button");
      b.textContent = "🗑";
      attr(o, "class", "svelte-1mgvexx");
      attr(_, "type", "text");
      attr(_, "class", m = null_to_empty(s[2][s[17]]) + " svelte-1mgvexx");
      attr(b, "class", "iconbutton svelte-1mgvexx");
      attr(r, "class", "svelte-1mgvexx");
    },
    m(m, S) {
      insert(m, r, S);
      append(r, o);
      append(o, u);
      append(o, g);
      append(r, _);
      set_input_value(_, s[15]);
      append(r, b);
      if (!E) {
        w = [ listen(_, "input", input_input_handler), listen(b, "click", click_handler) ];
        E = true;
      }
    },
    p(r, o) {
      s = r;
      if (4 & o && S !== (S = s[2][s[17]] + "")) set_data(u, S);
      if (8 & o && L !== (L = s[3][s[17]] + "")) set_data(g, L);
      if (4 & o && m !== (m = null_to_empty(s[2][s[17]]) + " svelte-1mgvexx")) attr(_, "class", m);
      if (1 & o && _.value !== s[15]) set_input_value(_, s[15]);
    },
    d(s) {
      if (s) detach(r);
      E = false;
      run_all(w);
    }
  };
}

function create_fragment4(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A = ensure_array_like(s[0]), R = [];
  for (let r = 0; r < A.length; r += 1) R[r] = create_each_block4(get_each_context4(s, A, r));
  return {
    c() {
      r = element("ul");
      for (let s = 0; s < R.length; s += 1) R[s].c();
      o = space();
      u = element("li");
      g = element("label");
      _ = element("button");
      _.textContent = "Add";
      m = space();
      b = element("li");
      E = element("button");
      w = text("Apply");
      L = space();
      O = element("button");
      D = text("Revert");
      attr(g, "class", "svelte-1mgvexx");
      attr(u, "class", "svelte-1mgvexx");
      E.disabled = S = s[3].some(s[11]) || s[2].every(func_1);
      O.disabled = C = s[3].some(s[13]) || s[2].every(func_3);
      attr(b, "class", "buttons svelte-1mgvexx");
      attr(r, "class", "svelte-1mgvexx");
    },
    m(S, C) {
      insert(S, r, C);
      for (let s = 0; s < R.length; s += 1) if (R[s]) R[s].m(r, null);
      append(r, o);
      append(r, u);
      append(u, g);
      append(g, _);
      append(r, m);
      append(r, b);
      append(b, E);
      append(E, w);
      append(b, L);
      append(b, O);
      append(O, D);
      if (!k) {
        T = [ listen(_, "click", s[10]), listen(E, "click", s[12]), listen(O, "click", s[14]) ];
        k = true;
      }
    },
    p(s, [u]) {
      if (45 & u) {
        A = ensure_array_like(s[0]);
        let g;
        for (g = 0; g < A.length; g += 1) {
          const _ = get_each_context4(s, A, g);
          if (R[g]) R[g].p(_, u); else {
            R[g] = create_each_block4(_);
            R[g].c();
            R[g].m(r, o);
          }
        }
        for (;g < R.length; g += 1) R[g].d(1);
        R.length = A.length;
      }
      if (12 & u && S !== (S = s[3].some(s[11]) || s[2].every(func_1))) E.disabled = S;
      if (12 & u && C !== (C = s[3].some(s[13]) || s[2].every(func_3))) O.disabled = C;
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
      destroy_each(R, s);
      k = false;
      run_all(T);
    }
  };
}

var CHECK_OK = "✔", CHECK_NG = "⚠", MARK_MODIFIED = "✏ ";

function checkRegExp(s) {
  if ("" == s.trim()) return "";
  try {
    new RegExp(s);
    return CHECK_OK;
  } catch (s) {
    return CHECK_NG;
  }
}

var func_1 = s => "" == s, func_3 = s => "" == s;

function instance4(s, r, o) {
  let u, g, {patterns: _ = []} = r, {originals: m = []} = r, {apply: b = (s => Promise.resolve())} = r;
  function revert() {
    o(0, _ = [ ...m ]);
  }
  function remove(s) {
    o(0, _[s] = "", _);
  }
  function add() {
    o(0, _ = [ ..._, "" ]);
  }
  s.$$set = s => {
    if ("patterns" in s) o(0, _ = s.patterns);
    if ("originals" in s) o(7, m = s.originals);
    if ("apply" in s) o(1, b = s.apply);
  };
  s.$$.update = () => {
    if (1 & s.$$.dirty) o(3, u = _.map((s => checkRegExp(s))));
    if (129 & s.$$.dirty) o(2, g = _.map(((s, r) => {
      var o;
      return (null !== (o = s != (null == m ? void 0 : m[r])) && void 0 !== o ? o : "") ? MARK_MODIFIED : "";
    })));
  };
  return [ _, b, g, u, revert, remove, add, m, function input_input_handler(s, r) {
    s[r] = this.value;
    o(0, _);
  }, s => remove(s), () => add(), s => s == CHECK_NG, () => b(_), s => s == CHECK_NG, () => revert() ];
}

var MultipleRegExpControl = class extends SvelteComponent {
  constructor(s) {
    super();
    init2(this, s, instance4, create_fragment4, safe_not_equal, {
      patterns: 0,
      originals: 7,
      apply: 1
    }, add_css4);
  }
}, MultipleRegExpControl_default = MultipleRegExpControl, ObsidianLiveSyncSettingTab = class extends import_obsidian.PluginSettingTab {
  constructor(s, r) {
    super(s, r);
    this.selectedScreen = "";
    this.plugin = r;
  }
  async testConnection() {
    const s = await this.plugin.replicator.connectRemoteCouchDBWithSetting(this.plugin.settings, this.plugin.isMobile, true);
    if ("string" != typeof s) this.plugin.addLog(`Connected to ${s.info.db_name}`, LOG_LEVEL_NOTICE); else this.plugin.addLog(`could not connect to ${this.plugin.settings.couchDB_URI} : ${this.plugin.settings.couchDB_DBNAME} \n(${s})`, LOG_LEVEL_NOTICE);
  }
  askReload() {
    scheduleTask("configReload", 250, (async () => {
      if ("yes" == await askYesNo(this.app, "Do you want to restart and reload Obsidian now?")) this.app.commands.executeCommandById("app:reload");
    }));
  }
  closeSetting() {
    this.plugin.app.setting.close();
  }
  display() {
    var s;
    const {containerEl: r} = this;
    let o = this.plugin.settings.encrypt, u = this.plugin.settings.passphrase, g = this.plugin.settings.useDynamicIterationCount;
    r.empty();
    r.createEl("h2", {
      text: "Settings for Self-hosted LiveSync."
    });
    r.addClass("sls-setting");
    r.removeClass("isWizard");
    const _ = r.createDiv(""), m = {}, addScreenElement = (s, r) => {
      if (!(s in m)) m[s] = [];
      m[s].push(r);
    };
    _.addClass("sls-setting-menu");
    _.innerHTML = "\n<label class='sls-setting-label c-100 wizardHidden'><input type='radio' name='disp' value='100' class='sls-setting-tab'><div class='sls-setting-menu-btn'>💬</div></label>\n<label class='sls-setting-label c-110'><input type='radio' name='disp' value='110' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🧙‍♂️</div></label>\n<label class='sls-setting-label c-20 wizardHidden'><input type='radio' name='disp' value='20' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>⚙️</div></label>\n<label class='sls-setting-label c-0'><input type='radio' name='disp' value='0' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🛰️</div></label>\n<label class='sls-setting-label c-30'><input type='radio' name='disp' value='30' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🔁</div></label>\n<label class='sls-setting-label c-60 wizardHidden'><input type='radio' name='disp' value='60' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🔌</div></label>\n<label class='sls-setting-label c-50 wizardHidden'><input type='radio' name='disp' value='50' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🧰</div></label>\n<label class='sls-setting-label c-70 wizardHidden'><input type='radio' name='disp' value='70' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🎛️</div></label>\n        ";
    const b = _.querySelectorAll(".sls-setting-label"), changeDisplay = s => {
      for (const r in m) if (r == s) m[r].forEach((s => s.removeClass("setting-collapsed"))); else m[r].forEach((s => s.addClass("setting-collapsed")));
      _.querySelectorAll(".sls-setting-label").forEach((s => {
        s.removeClass("selected");
        s.querySelector("input[type=radio]").checked = false;
      }));
      _.querySelectorAll(`.sls-setting-label.c-${s}`).forEach((s => {
        s.addClass("selected");
        s.querySelector("input[type=radio]").checked = true;
      }));
      this.selectedScreen = s;
    };
    b.forEach((s => {
      const r = s.querySelector(".sls-setting-tab");
      if (r) r.addEventListener("change", (r => {
        b.forEach((s => s.removeClass("selected")));
        changeDisplay(r.currentTarget.value);
        s.addClass("selected");
      }));
    }));
    const E = r.createDiv(), w = E.createEl("h3", {
      text: "Updates"
    }), S = E.createEl("div", {
      text: ""
    }), L = "0.22.17", O = ~~(versionNumberString2Number(L) / 1e3), D = createSpan();
    D.addClass("sls-header-button");
    D.innerHTML = "<button> OK, I read all. </button>";
    if (O > this.plugin.settings.lastReadUpdates) {
      const r = w.appendChild(D);
      null == (s = r.querySelector("button")) || s.addEventListener("click", (async () => {
        this.plugin.settings.lastReadUpdates = O;
        await this.plugin.saveSettings();
        r.remove();
      }));
    }
    import_obsidian.MarkdownRenderer.render(this.plugin.app, "### 0.22.0\nA few years passed since Self-hosted LiveSync was born, and our codebase had been very complicated. This could be patient now, but it should be a tremendous hurt.\nTherefore at v0.22.0, for future maintainability, I refined task scheduling logic totally.\n\nOf course, I think this would be our suffering in some cases. However, I would love to ask you for your cooperation and contribution.\n\nSorry for being absent so much long. And thank you for your patience!\n\nNote: we got a very performance improvement.\nNote at 0.22.2: **Now, to rescue mobile devices, Maximum file size is set to 50 by default**. Please configure the limit as you need. If you do not want to limit the sizes, set zero manually, please.\n\n#### Version history\n- 0.22.17:\n  - Fixed:\n    - Error handling on booting now works fine.\n    - Replication is now started automatically in LiveSync mode.\n    - Batch database update is now disabled in LiveSync mode.\n    - No longer automatically reconnection while off-focused.\n    - Status saves are thinned out.\n    - Now Self-hosted LiveSync waits for all files between the local database and storage to be surely checked.\n  - Improved:\n    - The job scheduler is now more robust and stable.\n    - The status indicator no longer flickers and keeps zero for a while.\n    - No longer meaningless frequent updates of status indicators.\n    - Now we can configure regular expression filters in handy UI. Thank you so much, @eth-p!\n    - `Fetch` or `Rebuild everything` is now more safely performed.\n  - Minor things\n    - Some utility function has been added.\n    - Customisation sync now less wrong messages.\n    - Digging the weeds for eradication of type errors.\n- 0.22.16:\n  - Fixed:\n    - Fixed the issue that binary files were sometimes corrupted.\n    - Fixed customisation sync data could be corrupted.\n  - Improved:\n    - Now the remote database costs lower memory.\n      - This release requires a brief wait on the first synchronisation, to track the latest changeset again.\n    - Description added for the `Device name`.\n  - Refactored:\n    - Many type-errors have been resolved.\n    - Obsolete file has been deleted.\n- 0.22.15:\n  - Improved:\n    - Faster start-up by removing too many logs which indicates normality\n    - By streamlined scanning of customised synchronisation extra phases have been deleted.\n... To continue on to `updates_old.md`.", S, "/", this.plugin);
    addScreenElement("100", E);
    const isAnySyncEnabled = () => {
      if (this.plugin.settings.liveSync) return true;
      if (this.plugin.settings.periodicReplication) return true;
      if (this.plugin.settings.syncOnFileOpen) return true;
      if (this.plugin.settings.syncOnSave) return true;
      if (this.plugin.settings.syncOnEditorSave) return true;
      if (this.plugin.settings.syncOnStart) return true;
      if (this.plugin.settings.syncAfterMerge) return true;
      if ("CONNECTED" == this.plugin.replicator.syncStatus) return true;
      if ("PAUSED" == this.plugin.replicator.syncStatus) return true; else return false;
    };
    let C = false;
    const k = r.createDiv();
    k.createEl("h3", {
      text: "Setup wizard"
    });
    new import_obsidian.Setting(k).setName("Use the copied setup URI").setDesc("To setup Self-hosted LiveSync, this method is the most preferred one.").addButton((s => {
      s.setButtonText("Use").onClick((async () => {
        this.closeSetting();
        await this.plugin.addOnSetup.command_openSetupURI();
      }));
    }));
    if (this.plugin.settings.isConfigured) new import_obsidian.Setting(k).setName("Copy current settings as a new setup URI").addButton((s => {
      s.setButtonText("Copy").onClick((async () => {
        await this.plugin.addOnSetup.command_copySetupURI();
      }));
    }));
    new import_obsidian.Setting(k).setName("Minimal setup").addButton((s => {
      s.setButtonText("Start").onClick((async () => {
        this.plugin.settings.liveSync = false;
        this.plugin.settings.periodicReplication = false;
        this.plugin.settings.syncOnSave = false;
        this.plugin.settings.syncOnEditorSave = false;
        this.plugin.settings.syncOnStart = false;
        this.plugin.settings.syncOnFileOpen = false;
        this.plugin.settings.syncAfterMerge = false;
        this.plugin.replicator.closeReplication();
        await this.plugin.saveSettings();
        r.addClass("isWizard");
        applyDisplayEnabled();
        C = true;
        changeDisplay("0");
      }));
    }));
    if (!this.plugin.settings.isConfigured) new import_obsidian.Setting(k).setName("Enable LiveSync on this device as the set-up was completed manually").addButton((s => {
      s.setButtonText("Enable").onClick((async () => {
        this.plugin.settings.isConfigured = true;
        await this.plugin.saveSettings();
        this.askReload();
      }));
    }));
    if (this.plugin.settings.isConfigured) new import_obsidian.Setting(k).setName("Discard exist settings and databases").addButton((s => {
      s.setButtonText("Discard").onClick((async () => {
        if ("yes" == await askYesNo(this.plugin.app, "Do you really want to discard exist settings and databases?")) {
          this.plugin.settings = {
            ...DEFAULT_SETTINGS
          };
          await this.plugin.saveSettingData();
          await this.plugin.resetLocalDatabase();
          this.askReload();
        }
      })).setWarning();
    }));
    k.createEl("h3", {
      text: "Online Tips"
    });
    const T = "vrtmrz/obsidian-livesync", A = "/docs/troubleshooting.md", R = `https://raw.githubusercontent.com/${T}/main`;
    k.createEl("div", "", (s => s.innerHTML = `<a href='https://github.com/${T}/blob/main${A}' target="_blank">Open in browser</a>`));
    const I = k.createEl("div", {
      text: "",
      cls: "sls-troubleshoot-preview"
    }), loadMarkdownPage = async (s, r = "") => {
      var o, u;
      I.style.minHeight = I.clientHeight + "px";
      I.empty();
      const g = (s.startsWith("/") ? s : `${r}/${s}`).split("/"), _ = g.pop(), m = g.join("/");
      let b = "";
      try {
        b = await (0, import_obsidian5.request)(`${R}${m}/${_}`);
      } catch (s) {
        b = "Error Occurred!!\n" + s.toString();
      }
      const E = b.replace(/\((.*?(.png)|(.jpg))\)/g, `(${R}${m}/$1)`);
      await import_obsidian.MarkdownRenderer.render(this.plugin.app, `<a class='sls-troubleshoot-anchor'></a> [Tips and Troubleshooting](${A}) [PageTop](${_})\n\n${E}`, I, `${R}`, this.plugin);
      null == (u = null == (o = I.querySelector(".sls-troubleshoot-anchor")) ? void 0 : o.parentElement) || u.setCssStyles({
        position: "sticky",
        top: "-1em",
        backgroundColor: "var(--modal-background)"
      });
      I.querySelectorAll("a.internal-link").forEach((s => {
        s.addEventListener("click", (async r => {
          const o = s.getAttr("data-href");
          if (o) if (o.startsWith("#")) {
            r.preventDefault();
            const s = Array.from(I.querySelectorAll("[data-heading]")).find((s => {
              var r;
              return (null == (r = s.getAttr("data-heading")) ? void 0 : r.toLowerCase().split(" ").join("-")) == o.substring(1).toLowerCase();
            }));
            if (s) {
              s.setCssStyles({
                scrollMargin: "3em"
              });
              s.scrollIntoView({
                behavior: "instant",
                block: "start"
              });
            }
          } else {
            r.preventDefault();
            await loadMarkdownPage(o, m);
            I.setCssStyles({
              scrollMargin: "1em"
            });
            I.scrollIntoView({
              behavior: "instant",
              block: "start"
            });
          }
        }));
      }));
      I.style.minHeight = "";
    };
    loadMarkdownPage(A);
    addScreenElement("110", k);
    const x = r.createDiv();
    x.createEl("h3", {
      text: "Remote Database configuration"
    });
    const P = x.createEl("div", {
      text: 'These settings are kept locked while any synchronization options are enabled. Disable these options in the "Sync Settings" tab to unlock.'
    });
    if (this.plugin.settings.couchDB_URI.startsWith("http://")) if (this.plugin.isMobile) x.createEl("div", {
      text: "Configured as using plain HTTP. We cannot connect to the remote. Please set up the credentials and use HTTPS for the remote URI."
    }).addClass("op-warn"); else x.createEl("div", {
      text: "Configured as using plain HTTP. We might fail on mobile devices."
    }).addClass("op-warn-info");
    P.addClass("op-warn-info");
    P.addClass("sls-hidden");
    const applyDisplayEnabled = () => {
      if (isAnySyncEnabled()) {
        N.forEach((s => {
          s.setDisabled(true).setTooltip("Could not change this while any synchronization options are enabled.");
        }));
        P.removeClass("sls-hidden");
      } else {
        N.forEach((s => {
          s.setDisabled(false).setTooltip("");
        }));
        P.addClass("sls-hidden");
      }
      if (this.plugin.settings.liveSync) {
        Z.forEach((s => {
          s.setDisabled(true).setTooltip("");
        }));
        X.forEach((s => {
          s.setDisabled(false).setTooltip("");
        }));
      } else if (this.plugin.settings.syncOnFileOpen || this.plugin.settings.syncOnSave || this.plugin.settings.syncOnEditorSave || this.plugin.settings.syncOnStart || this.plugin.settings.periodicReplication || this.plugin.settings.syncAfterMerge) {
        Z.forEach((s => {
          s.setDisabled(false).setTooltip("");
        }));
        X.forEach((s => {
          s.setDisabled(true).setTooltip("");
        }));
      } else {
        Z.forEach((s => {
          s.setDisabled(false).setTooltip("");
        }));
        X.forEach((s => {
          s.setDisabled(false).setTooltip("");
        }));
      }
    }, N = [];
    N.push(new import_obsidian.Setting(x).setName("URI").addText((s => s.setPlaceholder("https://........").setValue(this.plugin.settings.couchDB_URI).onChange((async s => {
      this.plugin.settings.couchDB_URI = s;
      await this.plugin.saveSettings();
    })))), new import_obsidian.Setting(x).setName("Username").setDesc("username").addText((s => s.setPlaceholder("").setValue(this.plugin.settings.couchDB_USER).onChange((async s => {
      this.plugin.settings.couchDB_USER = s;
      await this.plugin.saveSettings();
    })))), new import_obsidian.Setting(x).setName("Password").setDesc("password").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.couchDB_PASSWORD).onChange((async s => {
        this.plugin.settings.couchDB_PASSWORD = s;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "password");
    })), new import_obsidian.Setting(x).setName("Database name").addText((s => s.setPlaceholder("").setValue(this.plugin.settings.couchDB_DBNAME).onChange((async s => {
      this.plugin.settings.couchDB_DBNAME = s;
      await this.plugin.saveSettings();
    })))));
    new import_obsidian.Setting(x).setName("Test Database Connection").setClass("wizardHidden").setDesc("Open database connection. If the remote database is not found and you have the privilege to create a database, the database will be created.").addButton((s => s.setButtonText("Test").setDisabled(false).onClick((async () => {
      await this.testConnection();
    }))));
    new import_obsidian.Setting(x).setName("Check and Fix database configuration").setDesc("Check the database configuration, and fix if there are any problems.").addButton((s => s.setButtonText("Check").setDisabled(false).onClick((async () => {
      const checkConfig = async () => {
        var s, r, o, u, g, _, m, b, E, w, S;
        Logger("Checking database configuration", LOG_LEVEL_INFO);
        const L = createDiv();
        L.innerHTML = "<span></span>";
        B.replaceChildren(L);
        const addResult2 = (s, r) => {
          const o = createDiv();
          o.addClass("ob-btn-config-fix");
          if (r) o.addClasses(r);
          o.innerHTML = `${s}`;
          B.appendChild(o);
        };
        try {
          if (isCloudantURI(this.plugin.settings.couchDB_URI)) {
            Logger("This feature cannot be used with IBM Cloudant.", LOG_LEVEL_NOTICE);
            return;
          }
          const L = (await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin)).json, addConfigFixButton = (s, r, o) => {
            var u;
            const g = createDiv();
            g.addClass("ob-btn-config-fix");
            g.innerHTML = `<label>${s}</label><button>Fix</button>`;
            const _ = B.appendChild(g);
            null == (u = _.querySelector("button")) || u.addEventListener("click", (async () => {
              Logger(`CouchDB Configuration: ${s} -> Set ${r} to ${o}`);
              const u = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, void 0, r, o);
              if (200 == u.status) {
                Logger(`CouchDB Configuration: ${s} successfully updated`, LOG_LEVEL_NOTICE);
                B.removeChild(_);
                checkConfig();
              } else {
                Logger(`CouchDB Configuration: ${s} failed`, LOG_LEVEL_NOTICE);
                Logger(u.text, LOG_LEVEL_VERBOSE);
              }
            }));
          };
          addResult2("---Notice---", [ "ob-btn-config-head" ]);
          addResult2("If the server configuration is not persistent (e.g., running on docker), the values set from here will also be volatile. Once you are able to connect, please reflect the settings in the server's local.ini.", [ "ob-btn-config-info" ]);
          addResult2("--Config check--", [ "ob-btn-config-head" ]);
          if (!(this.plugin.settings.couchDB_USER in L.admins)) addResult2("⚠ You do not have administrative privileges."); else addResult2("✔ You have administrative privileges.");
          if ("true" != (null == (s = null == L ? void 0 : L.chttpd) ? void 0 : s.require_valid_user)) {
            addResult2("❗ chttpd.require_valid_user looks like wrong.");
            addConfigFixButton("Set chttpd.require_valid_user = true", "chttpd/require_valid_user", "true");
          } else addResult2("✔ chttpd.require_valid_user is ok.");
          if ("true" != (null == (r = null == L ? void 0 : L.chttpd_auth) ? void 0 : r.require_valid_user)) {
            addResult2("❗ chttpd_auth.require_valid_user looks like wrong.");
            addConfigFixButton("Set chttpd_auth.require_valid_user = true", "chttpd_auth/require_valid_user", "true");
          } else addResult2("✔ chttpd_auth.require_valid_user is ok.");
          if (!(null == L ? void 0 : L.httpd["WWW-Authenticate"])) {
            addResult2("❗ httpd.WWW-Authenticate is missing");
            addConfigFixButton("Set httpd.WWW-Authenticate", "httpd/WWW-Authenticate", 'Basic realm="couchdb"');
          } else addResult2("✔ httpd.WWW-Authenticate is ok.");
          if ("true" != (null == (o = null == L ? void 0 : L.httpd) ? void 0 : o.enable_cors)) {
            addResult2("❗ httpd.enable_cors is wrong");
            addConfigFixButton("Set httpd.enable_cors", "httpd/enable_cors", "true");
          } else addResult2("✔ httpd.enable_cors is ok.");
          if (!isCloudantURI(this.plugin.settings.couchDB_URI)) {
            if (Number(null != (g = null == (u = null == L ? void 0 : L.chttpd) ? void 0 : u.max_http_request_size) ? g : 0) < 4294967296) {
              addResult2("❗ chttpd.max_http_request_size is low)");
              addConfigFixButton("Set chttpd.max_http_request_size", "chttpd/max_http_request_size", "4294967296");
            } else addResult2("✔ chttpd.max_http_request_size is ok.");
            if (Number(null != (m = null == (_ = null == L ? void 0 : L.couchdb) ? void 0 : _.max_document_size) ? m : 0) < 5e7) {
              addResult2("❗ couchdb.max_document_size is low)");
              addConfigFixButton("Set couchdb.max_document_size", "couchdb/max_document_size", "50000000");
            } else addResult2("✔ couchdb.max_document_size is ok.");
          }
          if ("true" != (null == (b = null == L ? void 0 : L.cors) ? void 0 : b.credentials)) {
            addResult2("❗ cors.credentials is wrong");
            addConfigFixButton("Set cors.credentials", "cors/credentials", "true");
          } else addResult2("✔ cors.credentials is ok.");
          const O = ((null != (w = null == (E = null == L ? void 0 : L.cors) ? void 0 : E.origins) ? w : "") + "").split(",");
          if ("*" == (null == (S = null == L ? void 0 : L.cors) ? void 0 : S.origins) || -1 !== O.indexOf("app://obsidian.md") && -1 !== O.indexOf("capacitor://localhost") && -1 !== O.indexOf("http://localhost")) addResult2("✔ cors.origins is ok."); else {
            addResult2("❗ cors.origins is wrong");
            addConfigFixButton("Set cors.origins", "cors/origins", "app://obsidian.md,capacitor://localhost,http://localhost");
          }
          addResult2("--Connection check--", [ "ob-btn-config-head" ]);
          addResult2(`Current origin:${window.location.origin}`);
          const D = [ "app://obsidian.md", "capacitor://localhost", "http://localhost" ];
          for (const s of D) {
            const r = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, s), o = Object.fromEntries(Object.entries(r.headers).map((s => {
              s[0] = `${s[0]}`.toLowerCase();
              return s;
            })));
            addResult2(`Origin check:${s}`);
            if ("true" != o["access-control-allow-credentials"]) addResult2("❗ CORS is not allowing credential"); else addResult2("✔ CORS credential OK");
            if (o["access-control-allow-origin"] != s) addResult2(`❗ CORS Origin is unmatched:${origin}->${o["access-control-allow-origin"]}`); else addResult2("✔ CORS origin OK");
          }
          addResult2("--Done--", [ "ob-btn-config-head" ]);
          addResult2("If you have some trouble with Connection-check even though all Config-check has been passed, Please check your reverse proxy's configuration.", [ "ob-btn-config-info" ]);
          Logger("Checking configuration done", LOG_LEVEL_INFO);
        } catch (s) {
          if (401 == (null == s ? void 0 : s.status)) {
            addResult2("❗ Access forbidden.");
            addResult2("We could not continue the test.");
            Logger("Checking configuration done", LOG_LEVEL_INFO);
          } else {
            Logger("Checking configuration failed", LOG_LEVEL_NOTICE);
            Logger(s);
          }
        }
      };
      await checkConfig();
    }))));
    const B = x.createEl("div", {
      text: ""
    });
    x.createEl("h4", {
      text: "Confidentiality"
    });
    const F = new import_obsidian.Setting(x).setName("End to End Encryption").setDesc("Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommend.").addToggle((s => s.setValue(o).onChange((async s => {
      if (C) {
        this.plugin.settings.encrypt = s;
        o = s;
        await this.plugin.saveSettings();
        updateE2EControls();
      } else {
        o = s;
        updateE2EControls();
      }
    }))));
    let M = this.plugin.settings.usePathObfuscation;
    const updateE2EControls = () => {
      F.controlEl.toggleClass("sls-item-dirty", o != this.plugin.settings.encrypt);
      if (o) {
        V.settingEl.removeClass("sls-setting-hidden");
        j.settingEl.removeClass("sls-setting-hidden");
        G.settingEl.removeClass("sls-setting-hidden");
        null == V || V.controlEl.toggleClass("sls-item-dirty", u != this.plugin.settings.passphrase);
        null == j || j.controlEl.toggleClass("sls-item-dirty", g != this.plugin.settings.useDynamicIterationCount);
        null == G || G.controlEl.toggleClass("sls-item-dirty", M != this.plugin.settings.usePathObfuscation);
      } else {
        V.settingEl.addClass("sls-setting-hidden");
        j.settingEl.addClass("sls-setting-hidden");
        G.settingEl.addClass("sls-setting-hidden");
      }
      if (o != this.plugin.settings.encrypt || u != this.plugin.settings.passphrase || g != this.plugin.settings.useDynamicIterationCount || M != this.plugin.settings.usePathObfuscation) U.settingEl.removeClass("sls-setting-hidden"); else U.settingEl.addClass("sls-setting-hidden");
    }, V = new import_obsidian.Setting(x).setName("Passphrase").setDesc("Encrypting passphrase. If you change the passphrase of a existing database, overwriting the remote database is strongly recommended.").addText((s => {
      s.setPlaceholder("").setValue(u).onChange((async s => {
        if (C) {
          this.plugin.settings.passphrase = s;
          await this.plugin.saveSettings();
        } else {
          u = s;
          await this.plugin.saveSettings();
          updateE2EControls();
        }
      }));
      s.inputEl.setAttribute("type", "password");
    })), G = new import_obsidian.Setting(x).setName("Path Obfuscation").setDesc("Obfuscate paths of files. If we configured, we should rebuild the database.").addToggle((s => s.setValue(M).onChange((async s => {
      if (C) {
        this.plugin.settings.usePathObfuscation = s;
        await this.plugin.saveSettings();
      } else {
        M = s;
        await this.plugin.saveSettings();
        updateE2EControls();
      }
    })))), j = new import_obsidian.Setting(x).setName("Use dynamic iteration count (experimental)").setDesc("Balancing the encryption/decryption load against the length of the passphrase if toggled.").addToggle((s => {
      s.setValue(g).onChange((async s => {
        if (C) {
          this.plugin.settings.useDynamicIterationCount = s;
          await this.plugin.saveSettings();
        } else {
          g = s;
          await this.plugin.saveSettings();
          updateE2EControls();
        }
      }));
    })).setClass("wizardHidden"), U = new import_obsidian.Setting(x).setName("Apply").setDesc("Apply encryption settings").setClass("wizardHidden").addButton((s => s.setButtonText("Just apply").setWarning().setDisabled(false).onClick((async () => {
      await applyEncryption(false);
    })))).addButton((s => s.setButtonText("Apply and Fetch").setWarning().setDisabled(false).onClick((async () => {
      await rebuildDB("localOnly");
    })))).addButton((s => s.setButtonText("Apply and Rebuild").setWarning().setDisabled(false).onClick((async () => {
      await rebuildDB("rebuildBothByThisDevice");
    }))));
    updateE2EControls();
    const checkWorkingPassphrase = async () => {
      const s = {
        ...this.plugin.settings,
        encrypt: o,
        passphrase: u,
        useDynamicIterationCount: g
      };
      console.dir(s);
      const r = await this.plugin.replicator.connectRemoteCouchDBWithSetting(s, this.plugin.isMobile, true);
      if ("string" == typeof r) {
        Logger("Could not connect to the database.", LOG_LEVEL_NOTICE);
        return false;
      } else if (await checkSyncInfo(r.db)) return true; else {
        Logger("Failed to read remote database", LOG_LEVEL_NOTICE);
        return false;
      }
    }, applyEncryption = async s => {
      if (!o || "" != u) if (!o || await testCrypt()) {
        if (await checkWorkingPassphrase() || s) {
          if (!o) u = "";
          this.plugin.addOnSetup.suspendAllSync();
          this.plugin.addOnSetup.suspendExtraSync();
          this.plugin.settings.encrypt = o;
          this.plugin.settings.passphrase = u;
          this.plugin.settings.useDynamicIterationCount = g;
          this.plugin.settings.usePathObfuscation = M;
          this.plugin.settings.isConfigured = true;
          await this.plugin.saveSettings();
          updateE2EControls();
          if (s) await this.plugin.addOnSetup.rebuildRemote(); else {
            await this.plugin.markRemoteResolved();
            await this.plugin.replicate(true);
          }
        }
      } else Logger("WARNING! Your device would not support encryption.", LOG_LEVEL_NOTICE); else Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL_NOTICE);
    }, rebuildDB = async s => {
      if (!o || "" != u) if (!o || await testCrypt()) {
        if (!o) u = "";
        this.plugin.addOnSetup.suspendAllSync();
        this.plugin.addOnSetup.suspendExtraSync();
        this.plugin.settings.encrypt = o;
        this.plugin.settings.passphrase = u;
        this.plugin.settings.useDynamicIterationCount = g;
        this.plugin.settings.usePathObfuscation = M;
        this.plugin.settings.isConfigured = true;
        Logger("All synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.", LOG_LEVEL_NOTICE);
        await this.plugin.saveSettings();
        updateE2EControls();
        applyDisplayEnabled();
        this.closeSetting();
        await delay(2e3);
        await performRebuildDB(this.plugin, s);
      } else Logger("WARNING! Your device would not support encryption.", LOG_LEVEL_NOTICE); else Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL_NOTICE);
    };
    new import_obsidian.Setting(x).setClass("wizardOnly").addButton((s => s.setButtonText("Next").setCta().setDisabled(false).onClick((() => {
      if (!this.plugin.settings.encrypt) this.plugin.settings.passphrase = "";
      if (isCloudantURI(this.plugin.settings.couchDB_URI)) this.plugin.settings = {
        ...this.plugin.settings,
        ...PREFERRED_SETTING_CLOUDANT
      }; else this.plugin.settings = {
        ...this.plugin.settings,
        ...PREFERRED_SETTING_SELF_HOSTED
      };
      changeDisplay("30");
    }))));
    addScreenElement("0", x);
    const q = r.createDiv();
    q.createEl("h3", {
      text: "General Settings"
    });
    q.createEl("h4", {
      text: "Appearance"
    });
    new import_obsidian.Setting(q).setName("Show status inside the editor").setDesc("Reflected after reboot").addToggle((s => s.setValue(this.plugin.settings.showStatusOnEditor).onChange((async s => {
      this.plugin.settings.showStatusOnEditor = s;
      await this.plugin.saveSettings();
      this.display();
    }))));
    if (this.plugin.settings.showStatusOnEditor) new import_obsidian.Setting(q).setName("Show status as icons only").setDesc("").addToggle((s => s.setValue(this.plugin.settings.showOnlyIconsOnEditor).onChange((async s => {
      this.plugin.settings.showOnlyIconsOnEditor = s;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian.Setting(q).setName("Show status on the status bar").setDesc("Reflected after reboot.").addToggle((s => s.setValue(this.plugin.settings.showStatusOnStatusbar).onChange((async s => {
      this.plugin.settings.showStatusOnStatusbar = s;
      await this.plugin.saveSettings();
      this.display();
    }))));
    q.createEl("h4", {
      text: "Logging"
    });
    new import_obsidian.Setting(q).setName("Show only notifications").setDesc("Prevent logging and show only notification").addToggle((s => s.setValue(this.plugin.settings.lessInformationInLog).onChange((async s => {
      this.plugin.settings.lessInformationInLog = s;
      await this.plugin.saveSettings();
      this.display();
    }))));
    if (!this.plugin.settings.lessInformationInLog) new import_obsidian.Setting(q).setName("Verbose Log").setDesc("Show verbose log").addToggle((s => s.setValue(this.plugin.settings.showVerboseLog).onChange((async s => {
      this.plugin.settings.showVerboseLog = s;
      await this.plugin.saveSettings();
    }))));
    q.createEl("h4", {
      text: "Performance tweaks"
    });
    new import_obsidian.Setting(q).setName("Memory cache size (by total items)").setDesc("").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.hashCacheMaxCount + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 10) r = 10;
        this.plugin.settings.hashCacheMaxCount = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    new import_obsidian.Setting(q).setName("Memory cache size (by total characters)").setDesc("(Mega chars)").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.hashCacheMaxAmount + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 1) r = 1;
        this.plugin.settings.hashCacheMaxAmount = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    q.createEl("h4", {
      text: "Share settings via markdown"
    });
    let z, W = this.plugin.settings.settingSyncFile;
    new import_obsidian.Setting(q).setName("Filename").setDesc("If you set this, all settings are saved in a markdown file. You will also be notified when new settings were arrived. You can set different files by the platform.").addText((s => {
      s.setPlaceholder("livesync/setting.md").setValue(W).onChange((s => {
        W = s;
        if (W == this.plugin.settings.settingSyncFile) {
          z.removeCta();
          z.setDisabled(true);
        } else {
          z.setCta();
          z.setDisabled(false);
        }
      }));
    })).addButton((s => {
      s.setButtonText("Apply").onClick((async () => {
        this.plugin.settings.settingSyncFile = W;
        await this.plugin.saveSettings();
        this.display();
      }));
      z = s;
    }));
    new import_obsidian.Setting(q).setName("Write credentials in the file").setDesc("(Not recommended) If set, credentials will be stored in the file.").addToggle((s => {
      s.setValue(this.plugin.settings.writeCredentialsForSettingSync).onChange((async s => {
        this.plugin.settings.writeCredentialsForSettingSync = s;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian.Setting(q).setName("Notify all setting files").addToggle((s => {
      s.setValue(this.plugin.settings.notifyAllSettingSyncFile).onChange((async s => {
        this.plugin.settings.notifyAllSettingSyncFile = s;
        await this.plugin.saveSettings();
      }));
    }));
    q.createEl("h4", {
      text: "Advanced Confidentiality"
    });
    const H = {
      "": "Default",
      LOCALSTORAGE: "Use a custom passphrase",
      ASK_AT_LAUNCH: "Ask an passphrase at every launch"
    };
    new import_obsidian.Setting(q).setName("Encrypting sensitive configuration items").addDropdown((s => s.addOptions(H).setValue(this.plugin.settings.configPassphraseStore).onChange((async s => {
      this.plugin.settings.configPassphraseStore = s;
      this.plugin.usedPassphrase = "";
      Q.setDisabled("LOCALSTORAGE" != this.plugin.settings.configPassphraseStore);
      await this.plugin.saveSettings();
    })))).setClass("wizardHidden");
    const K = localStorage.getItem("ls-setting-passphrase") || "", Q = new import_obsidian.Setting(q).setName("Passphrase of sensitive configuration items").setDesc("This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.").addText((s => {
      s.setPlaceholder("").setValue(K).onChange((async s => {
        this.plugin.usedPassphrase = "";
        localStorage.setItem("ls-setting-passphrase", s);
        await this.plugin.saveSettings();
        updateE2EControls();
      }));
      s.inputEl.setAttribute("type", "password");
    })).setClass("wizardHidden");
    Q.setDisabled("LOCALSTORAGE" != this.plugin.settings.configPassphraseStore);
    addScreenElement("20", q);
    const J = r.createDiv();
    J.createEl("h3", {
      text: "Sync Settings"
    });
    if ("" != this.plugin.settings.versionUpFlash) {
      const s = J.createEl("div", {
        text: this.plugin.settings.versionUpFlash
      });
      s.createEl("button", {
        text: "I got it and updated."
      }, (r => {
        r.addClass("mod-cta");
        r.addEventListener("click", (async () => {
          this.plugin.settings.versionUpFlash = "";
          await this.plugin.saveSettings();
          applyDisplayEnabled();
          s.remove();
        }));
      }));
      s.addClass("op-warn");
    }
    let Y = "NONE";
    J.createEl("div", {
      text: "Please select any preset to complete wizard."
    }).addClasses([ "op-warn-info", "wizardOnly" ]);
    new import_obsidian.Setting(J).setName("Presets").setDesc("Apply preset configuration").addDropdown((s => s.addOptions({
      NONE: "",
      LIVESYNC: "LiveSync",
      PERIODIC: "Periodic w/ batch",
      DISABLE: "Disable all automatic"
    }).setValue(Y).onChange((s => Y = s)))).addButton((s => s.setButtonText("Apply").setDisabled(false).setCta().onClick((async () => {
      if ("" == Y) {
        Logger("Select any preset.", LOG_LEVEL_NOTICE);
        return;
      }
      const s = {
        batchSave: false,
        liveSync: false,
        periodicReplication: false,
        syncOnSave: false,
        syncOnEditorSave: false,
        syncOnStart: false,
        syncOnFileOpen: false,
        syncAfterMerge: false
      }, r = {
        ...s,
        liveSync: true
      }, o = {
        ...s,
        batchSave: true,
        periodicReplication: true,
        syncOnSave: false,
        syncOnEditorSave: false,
        syncOnStart: true,
        syncOnFileOpen: true,
        syncAfterMerge: true
      };
      if ("LIVESYNC" == Y) {
        this.plugin.settings = {
          ...this.plugin.settings,
          ...r
        };
        Logger("Synchronization setting configured as LiveSync.", LOG_LEVEL_NOTICE);
      } else if ("PERIODIC" == Y) {
        this.plugin.settings = {
          ...this.plugin.settings,
          ...o
        };
        Logger("Synchronization setting configured as Periodic sync with batch database update.", LOG_LEVEL_NOTICE);
      } else {
        Logger("All synchronization disabled.", LOG_LEVEL_NOTICE);
        this.plugin.settings = {
          ...this.plugin.settings,
          ...s
        };
      }
      await this.plugin.saveSettings();
      this.display();
      await this.plugin.realizeSettingSyncMode();
      if (C) {
        this.closeSetting();
        if (!this.plugin.settings.isConfigured) {
          this.plugin.settings.isConfigured = true;
          await this.plugin.saveSettings();
          await rebuildDB("localOnly");
          Logger("All done! Please set up subsequent devices with 'Copy current settings as a new setup URI' and 'Use the copied setup URI'.", LOG_LEVEL_NOTICE);
          await this.plugin.addOnSetup.command_copySetupURI();
        } else this.askReload();
      }
    }))));
    J.createEl("h4", {
      text: "Synchronization Methods"
    }).addClass("wizardHidden");
    const X = [], Z = [];
    let ee = "";
    if (this.plugin.settings.liveSync) ee = "LIVESYNC"; else if (this.plugin.settings.periodicReplication) ee = "PERIODIC";
    new import_obsidian.Setting(J).setName("Sync Mode").setClass("wizardHidden").addDropdown((s => s.addOptions({
      "": "On events",
      PERIODIC: "Periodic and On events",
      LIVESYNC: "LiveSync"
    }).setValue(ee).onChange((async s => {
      this.plugin.settings.liveSync = false;
      this.plugin.settings.periodicReplication = false;
      if ("LIVESYNC" == s) this.plugin.settings.liveSync = true; else if ("PERIODIC" == s) this.plugin.settings.periodicReplication = true;
      await this.plugin.saveSettings();
      applyDisplayEnabled();
      await this.plugin.realizeSettingSyncMode();
      this.display();
    }))));
    if (!this.plugin.settings.liveSync) {
      if (this.plugin.settings.periodicReplication) new import_obsidian.Setting(J).setName("Periodic Sync interval").setDesc("Interval (sec)").setClass("wizardHidden").addText((s => {
        s.setPlaceholder("").setValue(this.plugin.settings.periodicReplicationInterval + "").onChange((async s => {
          let r = Number(s);
          if (isNaN(r) || r > 5e3) r = 0;
          this.plugin.settings.periodicReplicationInterval = r;
          await this.plugin.saveSettings();
          applyDisplayEnabled();
        }));
        s.inputEl.setAttribute("type", "number");
      }));
      new import_obsidian.Setting(J).setName("Sync on Save").setDesc("When you save file, sync automatically").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnSave).onChange((async s => {
        this.plugin.settings.syncOnSave = s;
        await this.plugin.saveSettings();
        applyDisplayEnabled();
      }))));
      new import_obsidian.Setting(J).setName("Sync on Editor Save").setDesc("When you save file on the editor, sync automatically").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnEditorSave).onChange((async s => {
        this.plugin.settings.syncOnEditorSave = s;
        await this.plugin.saveSettings();
        applyDisplayEnabled();
      }))));
      new import_obsidian.Setting(J).setName("Sync on File Open").setDesc("When you open file, sync automatically").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnFileOpen).onChange((async s => {
        this.plugin.settings.syncOnFileOpen = s;
        await this.plugin.saveSettings();
        applyDisplayEnabled();
      }))));
      new import_obsidian.Setting(J).setName("Sync on Start").setDesc("Start synchronization after launching Obsidian.").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnStart).onChange((async s => {
        this.plugin.settings.syncOnStart = s;
        await this.plugin.saveSettings();
        applyDisplayEnabled();
      }))));
      new import_obsidian.Setting(J).setName("Sync after merging file").setDesc("Sync automatically after merging files").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncAfterMerge).onChange((async s => {
        this.plugin.settings.syncAfterMerge = s;
        await this.plugin.saveSettings();
        applyDisplayEnabled();
      }))));
    }
    J.createEl("h4", {
      text: "Deletions propagation"
    }).addClass("wizardHidden");
    new import_obsidian.Setting(J).setName("Use the trash bin").setDesc("Do not delete files that are deleted in remote, just move to trash.").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.trashInsteadDelete).onChange((async s => {
      this.plugin.settings.trashInsteadDelete = s;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian.Setting(J).setName("Keep empty folder").setDesc("Normally, a folder is deleted when it becomes empty after a synchronization. Enabling this will prevent it from getting deleted").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.doNotDeleteFolder).onChange((async s => {
      this.plugin.settings.doNotDeleteFolder = s;
      await this.plugin.saveSettings();
    }))));
    J.createEl("h4", {
      text: "Conflict resolution"
    }).addClass("wizardHidden");
    new import_obsidian.Setting(J).setName("Always overwrite with a newer file (beta)").setDesc("(Def off) Resolve conflicts by newer files automatically.").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.resolveConflictsByNewerFile).onChange((async s => {
      this.plugin.settings.resolveConflictsByNewerFile = s;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian.Setting(J).setName("Postpone resolution of inactive files").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.checkConflictOnlyOnOpen).onChange((async s => {
      this.plugin.settings.checkConflictOnlyOnOpen = s;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian.Setting(J).setName("Postpone manual resolution of inactive files").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.showMergeDialogOnlyOnActive).onChange((async s => {
      this.plugin.settings.showMergeDialogOnlyOnActive = s;
      await this.plugin.saveSettings();
    }))));
    J.createEl("h4", {
      text: "Compatibility"
    }).addClass("wizardHidden");
    new import_obsidian.Setting(J).setName("Always resolve conflict manually").setDesc("If this switch is turned on, a merge dialog will be displayed, even if the sensible-merge is possible automatically. (Turn on to previous behavior)").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.disableMarkdownAutoMerge).onChange((async s => {
      this.plugin.settings.disableMarkdownAutoMerge = s;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian.Setting(J).setName("Always reflect synchronized changes even if the note has a conflict").setDesc("Turn on to previous behavior").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.writeDocumentsIfConflicted).onChange((async s => {
      this.plugin.settings.writeDocumentsIfConflicted = s;
      await this.plugin.saveSettings();
    }))));
    J.createEl("h4", {
      text: "Hidden files"
    }).addClass("wizardHidden");
    new import_obsidian.Setting(J).setName("Hidden file synchronization").setClass("wizardHidden").settingEl.createDiv("").innerText = this.plugin.settings.syncInternalFiles ? "🔁 : Enabled" : "⏹️ : Disabled";
    if (this.plugin.settings.syncInternalFiles) new import_obsidian.Setting(J).setName("Disable Hidden files sync").setClass("wizardHidden").addButton((s => {
      s.setButtonText("Disable").onClick((async () => {
        this.plugin.settings.syncInternalFiles = false;
        await this.plugin.saveSettings();
        this.display();
      }));
    })); else new import_obsidian.Setting(J).setName("Enable Hidden files sync").setClass("wizardHidden").addButton((s => {
      s.setButtonText("Merge").onClick((async () => {
        this.closeSetting();
        await this.plugin.addOnSetup.configureHiddenFileSync("MERGE");
      }));
    })).addButton((s => {
      s.setButtonText("Fetch").onClick((async () => {
        this.closeSetting();
        await this.plugin.addOnSetup.configureHiddenFileSync("FETCH");
      }));
    })).addButton((s => {
      s.setButtonText("Overwrite").onClick((async () => {
        this.closeSetting();
        await this.plugin.addOnSetup.configureHiddenFileSync("OVERWRITE");
      }));
    }));
    if (!this.plugin.settings.watchInternalFileChanges) new import_obsidian.Setting(J).setName("Scan for hidden files before replication").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncInternalFilesBeforeReplication).onChange((async s => {
      this.plugin.settings.syncInternalFilesBeforeReplication = s;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian.Setting(J).setName("Scan hidden files periodically").setDesc("Seconds, 0 to disable").setClass("wizardHidden").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.syncInternalFilesInterval + "").onChange((async s => {
        let r = Number(s);
        if (0 !== r && (isNaN(r) || r < 10)) r = 10;
        this.plugin.settings.syncInternalFilesInterval = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    const te = "\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/", ne = te + ",\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$", ie = this.plugin.settings.syncInternalFilesIgnorePatterns.split(",").map((s => s.trim())).filter((s => "" != s)), se = new import_obsidian.Setting(J).setName("Hidden files ignore patterns").setDesc("");
    new MultipleRegExpControl_default({
      target: se.controlEl,
      props: {
        patterns: ie,
        originals: [ ...ie ],
        apply: async s => {
          this.plugin.settings.syncInternalFilesIgnorePatterns = s.map((s => s.trim())).filter((s => "" != s)).join(", ");
          await this.plugin.saveSettings();
          this.display();
        }
      }
    });
    const addDefaultPatterns = async s => {
      const r = this.plugin.settings.syncInternalFilesIgnorePatterns.split(",").map((s => s.trim())).filter((s => "" != s)), o = s.split(",").map((s => s.trim())).filter((s => "" != s)), u = new Set([ ...r, ...o ]);
      this.plugin.settings.syncInternalFilesIgnorePatterns = [ ...u ].join(", ");
      await this.plugin.saveSettings();
      this.display();
    };
    new import_obsidian.Setting(J).setName("Add default patterns").setClass("wizardHidden").addButton((s => {
      s.setButtonText("Default").onClick((async () => {
        await addDefaultPatterns(te);
      }));
    })).addButton((s => {
      s.setButtonText("Cross-platform").onClick((async () => {
        await addDefaultPatterns(ne);
      }));
    }));
    J.createEl("h4", {
      text: "Performance tweaks"
    }).addClass("wizardHidden");
    new import_obsidian.Setting(J).setName("Batch database update").setDesc("Reducing the frequency with which on-disk changes are reflected into the DB").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.batchSave).onChange((async s => {
      this.plugin.settings.batchSave = s;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian.Setting(J).setName("Enhance chunk size").setDesc("Enhance chunk size for binary files (Ratio). This cannot be increased when using IBM Cloudant.").setClass("wizardHidden").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.customChunkSize + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 1) r = 0;
        this.plugin.settings.customChunkSize = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    new import_obsidian.Setting(J).setName("Fetch chunks on demand").setDesc("(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.").setClass("wizardHidden").addToggle((s => {
      s.setValue(this.plugin.settings.readChunksOnline).onChange((async s => {
        this.plugin.settings.readChunksOnline = s;
        await this.plugin.saveSettings();
      }));
      return s;
    }));
    J.createEl("h4", {
      text: (0, import_obsidian.sanitizeHTMLToDom)("Targets")
    }).addClass("wizardHidden");
    const ae = new import_obsidian.Setting(J).setName("Synchronising files").setDesc("(RegExp) Empty to sync all files. set filter as a regular expression to limit synchronising files.").setClass("wizardHidden");
    new MultipleRegExpControl_default({
      target: ae.controlEl,
      props: {
        patterns: this.plugin.settings.syncOnlyRegEx.split("|[]|"),
        originals: [ ...this.plugin.settings.syncOnlyRegEx.split("|[]|") ],
        apply: async s => {
          this.plugin.settings.syncOnlyRegEx = s.map((s => s.trim())).filter((s => "" != s)).join("|[]|");
          await this.plugin.saveSettings();
          this.display();
        }
      }
    });
    const re = new import_obsidian.Setting(J).setName("Non-Synchronising files").setDesc("(RegExp) If this is set, any changes to local and remote files that match this will be skipped.").setClass("wizardHidden");
    new MultipleRegExpControl_default({
      target: re.controlEl,
      props: {
        patterns: this.plugin.settings.syncIgnoreRegEx.split("|[]|"),
        originals: [ ...this.plugin.settings.syncIgnoreRegEx.split("|[]|") ],
        apply: async s => {
          this.plugin.settings.syncIgnoreRegEx = s.map((s => s.trim())).filter((s => "" != s)).join("|[]|");
          await this.plugin.saveSettings();
          this.display();
        }
      }
    });
    new import_obsidian.Setting(J).setName("Maximum file size").setDesc("(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.").setClass("wizardHidden").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.syncMaxSizeInMB + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 1) r = 0;
        this.plugin.settings.syncMaxSizeInMB = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    new import_obsidian.Setting(J).setName("(Beta) Use ignore files").setDesc("If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.").setClass("wizardHidden").addToggle((s => {
      s.setValue(this.plugin.settings.useIgnoreFiles).onChange((async s => {
        this.plugin.settings.useIgnoreFiles = s;
        await this.plugin.saveSettings();
        this.display();
      }));
      return s;
    }));
    if (this.plugin.settings.useIgnoreFiles) new import_obsidian.Setting(J).setName("Ignore files").setDesc("We can use multiple ignore files, e.g.) `.gitignore, .dockerignore`").setClass("wizardHidden").addTextArea((s => {
      s.setValue(this.plugin.settings.ignoreFiles).setPlaceholder(".gitignore, .dockerignore").onChange((async s => {
        this.plugin.settings.ignoreFiles = s;
        await this.plugin.saveSettings();
      }));
      return s;
    }));
    J.createEl("h4", {
      text: (0, import_obsidian.sanitizeHTMLToDom)("Advanced settings")
    }).addClass("wizardHidden");
    J.createEl("div", {
      text: "If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value."
    }).addClass("wizardHidden");
    new import_obsidian.Setting(J).setName("Batch size").setDesc("Number of change feed items to process at a time. Defaults to 50. Minimum is 2.").setClass("wizardHidden").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.batch_size + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 2) r = 2;
        this.plugin.settings.batch_size = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    new import_obsidian.Setting(J).setName("Batch limit").setDesc("Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.").setClass("wizardHidden").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.batches_limit + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 2) r = 2;
        this.plugin.settings.batches_limit = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    new import_obsidian.Setting(J).setName("Use timeouts instead of heartbeats").setDesc("If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.").setClass("wizardHidden").addToggle((s => {
      s.setValue(this.plugin.settings.useTimeouts).onChange((async s => {
        this.plugin.settings.useTimeouts = s;
        await this.plugin.saveSettings();
      }));
      return s;
    }));
    new import_obsidian.Setting(J).setName("Batch size of on-demand fetching").setDesc("").setClass("wizardHidden").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.concurrencyOfReadChunksOnline + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 10) r = 10;
        this.plugin.settings.concurrencyOfReadChunksOnline = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    new import_obsidian.Setting(J).setName("The delay for consecutive on-demand fetches").setDesc("").setClass("wizardHidden").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.minimumIntervalOfReadChunksOnline + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r) || r < 10) r = 10;
        this.plugin.settings.minimumIntervalOfReadChunksOnline = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    addScreenElement("30", J);
    const oe = r.createDiv();
    oe.createEl("h3", {
      text: "Hatch"
    });
    new import_obsidian.Setting(oe).setName("Make report to inform the issue").addButton((s => s.setButtonText("Make report").setDisabled(false).onClick((async () => {
      let s = {};
      const r = "𝑅𝐸𝐷𝐴𝐶𝑇𝐸𝐷";
      try {
        const o = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin);
        Logger(JSON.stringify(o.json, null, 2));
        s = o.json;
        s["couch_httpd_auth"].secret = r;
        s["couch_httpd_auth"].authentication_db = r;
        s["couch_httpd_auth"].authentication_redirect = r;
        s["couchdb"].uuid = r;
        s["admins"] = r;
      } catch (r) {
        s = "Requesting information to the remote CouchDB has been failed. If you are using IBM Cloudant, it is the normal behaviour.";
      }
      const o = JSON.parse(JSON.stringify(this.plugin.settings));
      o.couchDB_DBNAME = r;
      o.couchDB_PASSWORD = r;
      const u = o.couchDB_URI.startsWith("http:") ? "(HTTP)" : o.couchDB_URI.startsWith("https:") ? "(HTTPS)" : "";
      o.couchDB_URI = isCloudantURI(o.couchDB_URI) ? "cloudant" : `self-hosted${u}`;
      o.couchDB_USER = r;
      o.passphrase = r;
      o.encryptedPassphrase = r;
      o.encryptedCouchDBConnection = r;
      o.pluginSyncExtendedSetting = {};
      const g = `---- Obsidian info ----\n${navigator.userAgent}\n---- remote config ----\n${(0, 
      import_obsidian.stringifyYaml)(s)}\n---- Plug-in config ---\nversion:${L}\n${(0, 
      import_obsidian.stringifyYaml)(o)}`;
      console.log(g);
      await navigator.clipboard.writeText(g);
      Logger("Information has been copied to clipboard", LOG_LEVEL_NOTICE);
    }))));
    if (this.plugin.replicator.remoteLockedAndDeviceNotAccepted) {
      const s = oe.createEl("div", {
        text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization, and this device was not marked as 'resolved'. it caused by some operations like this. re-initialized. Local database initialization should be required. please back your vault up, reset local database, and press 'Mark this device as resolved'. "
      });
      s.createEl("button", {
        text: "I'm ready, mark this device 'resolved'"
      }, (r => {
        r.addClass("mod-warning");
        r.addEventListener("click", (async () => {
          await this.plugin.markRemoteResolved();
          s.remove();
        }));
      }));
      s.addClass("op-warn");
    } else if (this.plugin.replicator.remoteLocked) {
      const s = oe.createEl("div", {
        text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database."
      });
      s.createEl("button", {
        text: "I'm ready, unlock the database"
      }, (r => {
        r.addClass("mod-warning");
        r.addEventListener("click", (async () => {
          await this.plugin.markRemoteUnlocked();
          s.remove();
        }));
      }));
      s.addClass("op-warn");
    }
    new import_obsidian.Setting(oe).setName("Back to non-configured").addButton((s => s.setButtonText("Back").setDisabled(false).onClick((async () => {
      this.plugin.settings.isConfigured = false;
      await this.plugin.saveSettings();
      this.askReload();
    }))));
    oe.createEl("div", {
      text: "To stop the boot up sequence for fixing problems on databases, you can put redflag.md on top of your vault (Rebooting obsidian is required)."
    }).addClass("op-warn-info");
    const addResult = (s, r, o) => {
      le.appendChild(le.createEl("div", {}, (u => {
        u.appendChild(u.createEl("h6", {
          text: s
        }));
        u.appendChild(u.createEl("div", {}, (s => {
          s.appendChild(s.createEl("div", {
            text: "Storage : Modified: " + (!r ? "Missing:" : `${new Date(r.stat.mtime).toLocaleString()}, Size:${r.stat.size}`)
          }));
          s.appendChild(s.createEl("div", {
            text: "Database: Modified: " + (!o ? "Missing:" : `${new Date(o.mtime).toLocaleString()}, Size:${o.size}`)
          }));
        })));
        if (o && r) u.appendChild(u.createEl("button", {
          text: "Show history"
        }, (s => {
          s.onClickEvent((() => {
            this.plugin.showHistory(r, o._id);
          }));
        })));
        if (r) u.appendChild(u.createEl("button", {
          text: "Storage -> Database"
        }, (s => {
          s.onClickEvent((() => {
            this.plugin.updateIntoDB(r, void 0, true);
            u.remove();
          }));
        })));
        if (o) u.appendChild(u.createEl("button", {
          text: "Database -> Storage"
        }, (s => {
          s.onClickEvent((() => {
            this.plugin.pullFile(this.plugin.getPath(o), [], true, void 0, false);
            u.remove();
          }));
        })));
        return u;
      })));
    }, checkBetweenStorageAndDatabase = async (s, r) => {
      const o = readAsBlob(r), u = createBlob(await this.plugin.vaultAccess.vaultReadAuto(s));
      if (await isDocContentSame(u, o)) Logger(`Compare: SAME: ${s.path}`); else {
        Logger(`Compare: CONTENT IS NOT MATCHED! ${s.path}`, LOG_LEVEL_NOTICE);
        addResult(s.path, s, r);
      }
    };
    new import_obsidian.Setting(oe).setName("Verify and repair all files").setDesc("Compare the content of files between on local database and storage. If not matched, you will asked which one want to keep.").addButton((s => s.setButtonText("Verify all").setDisabled(false).setWarning().onClick((async () => {
      const s = this.app.vault.getFiles(), r = [], o = this.plugin.localDatabase.findAllNormalDocs();
      for await (const s of o) r.push(this.plugin.getPath(s));
      const u = [ ...new Set([ ...r, ...s.map((s => s.path)) ]) ];
      let g = 0;
      for (const r of u) {
        g++;
        Logger(`${g}/${s.length}\n${r}`, LOG_LEVEL_NOTICE, "verify");
        if (shouldBeIgnored(r)) continue;
        const o = this.plugin.vaultAccess.getAbstractFileByPath(r), u = o instanceof import_obsidian5.TFile ? o : false;
        if (!await this.plugin.isTargetFile(r)) continue;
        if (u && this.plugin.isFileSizeExceeded(u.stat.size)) continue;
        const _ = await this.plugin.localDatabase.getDBEntry(r);
        if (!_ || !this.plugin.isFileSizeExceeded(_.size)) if (_ || !u) if (!_ || u) {
          if (u && _) await checkBetweenStorageAndDatabase(u, _);
        } else {
          Logger(`Compare: Not found on the storage: ${r}`, LOG_LEVEL_NOTICE);
          addResult(r, false, _);
        } else {
          Logger(`Compare: Not found on the local database: ${r}`, LOG_LEVEL_NOTICE);
          addResult(r, u, false);
        }
      }
      Logger("done", LOG_LEVEL_NOTICE, "verify");
    }))));
    const le = oe.createDiv({
      text: ""
    });
    new import_obsidian.Setting(oe).setName("Check and convert non-path-obfuscated files").setDesc("").addButton((s => s.setButtonText("Perform").setDisabled(false).setWarning().onClick((async () => {
      var s, r, o;
      for await (const u of this.plugin.localDatabase.findAllDocNames()) if (!u.startsWith("f:")) {
        const g = await this.plugin.path2id(u), _ = await this.plugin.localDatabase.getRaw(u);
        if (!_) continue;
        if ("newnote" != _.type && "plain" != _.type) continue;
        if (null != (s = null == _ ? void 0 : _.deleted) ? s : false) continue;
        const m = {
          ..._
        };
        m._id = g;
        m.path = u;
        delete m._rev;
        try {
          const s = await this.plugin.localDatabase.getRaw(g, {
            revs_info: true
          });
          null == (r = s._revs_info) || r.shift();
          const b = null == (o = s._revs_info) ? void 0 : o.shift();
          if (b) m._rev = b.rev; else m._rev = "1-" + `00000000000000000000000000000000${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}`.slice(-32);
          const E = await this.plugin.localDatabase.putRaw(m, {
            force: true
          });
          if (E.ok) {
            Logger(`${u} has been converted as conflicted document`, LOG_LEVEL_NOTICE);
            _._deleted = true;
            if ((await this.plugin.localDatabase.putRaw(_)).ok) Logger(`Old ${u} has been deleted`, LOG_LEVEL_NOTICE);
            await this.plugin.queueConflictCheck(u);
          } else {
            Logger(`Converting ${u} Failed!`, LOG_LEVEL_NOTICE);
            Logger(E, LOG_LEVEL_VERBOSE);
          }
        } catch (s) {
          if (404 == (null == s ? void 0 : s.status)) {
            if ((await this.plugin.localDatabase.putRaw(m)).ok) {
              Logger(`${u} has been converted`, LOG_LEVEL_NOTICE);
              _._deleted = true;
              if ((await this.plugin.localDatabase.putRaw(_)).ok) Logger(`Old ${u} has been deleted`, LOG_LEVEL_NOTICE);
            }
          } else {
            Logger(`Something went wrong on converting ${u}`, LOG_LEVEL_NOTICE);
            Logger(s, LOG_LEVEL_VERBOSE);
          }
        }
      }
      Logger("Converting finished", LOG_LEVEL_NOTICE);
    }))));
    new import_obsidian.Setting(oe).setName("Delete all customization sync data").addButton((s => s.setButtonText("Delete").setDisabled(false).setWarning().onClick((async () => {
      Logger("Deleting customization sync data", LOG_LEVEL_NOTICE);
      const s = (await this.plugin.localDatabase.allDocsRaw({
        startkey: "ix:",
        endkey: "ix:􏿿",
        include_docs: true
      })).rows.map((s => ({
        ...s.doc,
        _deleted: true
      })));
      Logger(`${(await this.plugin.localDatabase.bulkDocsRaw(s)).length} items have been removed, to confirm how many items are left, please perform it again.`, LOG_LEVEL_NOTICE);
    }))));
    new import_obsidian.Setting(oe).setName("Suspend file watching").setDesc("Stop watching for file change.").addToggle((s => s.setValue(this.plugin.settings.suspendFileWatching).onChange((async s => {
      this.plugin.settings.suspendFileWatching = s;
      await this.plugin.saveSettings();
      this.askReload();
    }))));
    new import_obsidian.Setting(oe).setName("Suspend database reflecting").setDesc("Stop reflecting database changes to storage files.").addToggle((s => s.setValue(this.plugin.settings.suspendParseReplicationResult).onChange((async s => {
      this.plugin.settings.suspendParseReplicationResult = s;
      await this.plugin.saveSettings();
      this.askReload();
    }))));
    new import_obsidian.Setting(oe).setName("Write logs into the file").setDesc("Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.").addToggle((s => s.setValue(this.plugin.settings.writeLogToTheFile).onChange((async s => {
      this.plugin.settings.writeLogToTheFile = s;
      await this.plugin.saveSettings();
    }))));
    oe.createEl("h4", {
      text: (0, import_obsidian.sanitizeHTMLToDom)("Compatibility"),
      cls: "wizardHidden"
    });
    new import_obsidian.Setting(oe).setName("Do not keep metadata of deleted files.").setClass("wizardHidden").addToggle((s => {
      s.setValue(this.plugin.settings.deleteMetadataOfDeletedFiles).onChange((async s => {
        this.plugin.settings.deleteMetadataOfDeletedFiles = s;
        await this.plugin.saveSettings();
        this.display();
      }));
    }));
    if (this.plugin.settings.deleteMetadataOfDeletedFiles) new import_obsidian.Setting(oe).setName("Delete old metadata of deleted files on start-up").setClass("wizardHidden").setDesc("(Days passed, 0 to disable automatic-deletion)").addText((s => {
      s.setPlaceholder("").setValue(this.plugin.settings.automaticallyDeleteMetadataOfDeletedFiles + "").onChange((async s => {
        let r = Number(s);
        if (isNaN(r)) r = 0;
        this.plugin.settings.automaticallyDeleteMetadataOfDeletedFiles = r;
        await this.plugin.saveSettings();
      }));
      s.inputEl.setAttribute("type", "number");
    }));
    new import_obsidian.Setting(oe).setName("Use an old adapter for compatibility").setDesc("Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.").setClass("wizardHidden").addToggle((s => s.setValue(!this.plugin.settings.useIndexedDBAdapter).onChange((async s => {
      this.plugin.settings.useIndexedDBAdapter = !s;
      await this.plugin.saveSettings();
      await rebuildDB("localOnly");
    }))));
    new import_obsidian.Setting(oe).setName("Scan changes on customization sync").setDesc("Do not use internal API").addToggle((s => s.setValue(!this.plugin.settings.watchInternalFileChanges).onChange((async s => {
      this.plugin.settings.watchInternalFileChanges = !s;
      await this.plugin.saveSettings();
    }))));
    let ce = this.plugin.settings.additionalSuffixOfDatabaseName + "";
    new import_obsidian.Setting(oe).setName("Database suffix").setDesc("LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.").addText((s => {
      s.setPlaceholder("").setValue(ce).onChange((s => {
        ce = s;
      }));
    })).addButton((s => {
      s.setButtonText("Change").onClick((async () => {
        if (this.plugin.settings.additionalSuffixOfDatabaseName != ce) {
          this.plugin.settings.additionalSuffixOfDatabaseName = ce;
          await this.plugin.saveSettings();
          Logger("Suffix has been changed. Reopening database...", LOG_LEVEL_NOTICE);
          await this.plugin.initializeDatabase();
        } else Logger("Suffix was not changed.", LOG_LEVEL_NOTICE);
      }));
    }));
    new import_obsidian.Setting(oe).setName("The Hash algorithm for chunk IDs").setDesc("xxhash64 is the current default.").setClass("wizardHidden").addDropdown((s => s.addOptions({
      "": "Old Algorithm",
      xxhash32: "xxhash32 (Fast)",
      xxhash64: "xxhash64 (Fastest)",
      sha1: "Fallback (Without WebAssembly)"
    }).setValue(this.plugin.settings.hashAlg).onChange((async s => {
      this.plugin.settings.hashAlg = s;
      await this.plugin.saveSettings();
    })))).setClass("wizardHidden");
    new import_obsidian.Setting(oe).setName("Fetch database with previous behaviour").setDesc("").addToggle((s => s.setValue(this.plugin.settings.doNotSuspendOnFetching).onChange((async s => {
      this.plugin.settings.doNotSuspendOnFetching = s;
      await this.plugin.saveSettings();
    }))));
    addScreenElement("50", oe);
    const ue = r.createDiv();
    ue.createEl("h3", {
      text: "Customization sync (beta)"
    });
    const de = new import_obsidian.Setting(ue).setName("Device name").setDesc("Unique name between all synchronized devices. To edit this setting, please disable customization sync once.").addText((s => {
      s.setPlaceholder("desktop").setValue(this.plugin.deviceAndVaultName).onChange((async s => {
        this.plugin.deviceAndVaultName = s;
        await this.plugin.saveSettings();
      }));
    })), updateDisabledOfDeviceAndVaultName = () => {
      de.setDisabled(this.plugin.settings.usePluginSync);
    };
    updateDisabledOfDeviceAndVaultName();
    new import_obsidian.Setting(ue).setName("Enable customization sync").addToggle((s => s.setValue(this.plugin.settings.usePluginSync).onChange((async r => {
      if (r && "" == this.plugin.deviceAndVaultName.trim()) {
        Logger("We have to configure `Device name` to use this feature.", LOG_LEVEL_NOTICE);
        s.setValue(false);
        return false;
      }
      this.plugin.settings.usePluginSync = r;
      this.display();
      await this.plugin.saveSettings();
    }))));
    if (this.plugin.settings.usePluginSync) {
      new import_obsidian.Setting(ue).setName("Scan customization automatically").setDesc("Scan customization before replicating.").addToggle((s => s.setValue(this.plugin.settings.autoSweepPlugins).onChange((async s => {
        this.plugin.settings.autoSweepPlugins = s;
        updateDisabledOfDeviceAndVaultName();
        await this.plugin.saveSettings();
      }))));
      if (!this.plugin.settings.watchInternalFileChanges) new import_obsidian.Setting(ue).setName("Scan customization periodically").setDesc("Scan customization every 1 minute.").addToggle((s => s.setValue(this.plugin.settings.autoSweepPluginsPeriodic).onChange((async s => {
        this.plugin.settings.autoSweepPluginsPeriodic = s;
        updateDisabledOfDeviceAndVaultName();
        await this.plugin.saveSettings();
      }))));
      new import_obsidian.Setting(ue).setName("Notify customized").setDesc("Notify when other device has newly customized.").addToggle((s => s.setValue(this.plugin.settings.notifyPluginOrSettingUpdated).onChange((async s => {
        this.plugin.settings.notifyPluginOrSettingUpdated = s;
        await this.plugin.saveSettings();
      }))));
      new import_obsidian.Setting(ue).setName("Open").setDesc("Open the dialog").addButton((s => {
        s.setButtonText("Open").setDisabled(false).onClick((() => {
          this.plugin.addOnConfigSync.showPluginSyncModal();
        }));
      }));
    }
    updateDisabledOfDeviceAndVaultName();
    addScreenElement("60", ue);
    const fe = r.createDiv();
    fe.createEl("h3", {
      text: "Maintain databases"
    });
    fe.createEl("h4", {
      text: "The remote database"
    });
    new import_obsidian.Setting(fe).setName("Lock remote database").setDesc("Lock remote database to prevent synchronization with other devices.").addButton((s => s.setButtonText("Lock").setDisabled(false).setWarning().onClick((async () => {
      await this.plugin.markRemoteLocked();
    }))));
    new import_obsidian.Setting(fe).setName("Overwrite remote database").setDesc("Overwrite remote database with local DB and passphrase.").addButton((s => s.setButtonText("Send").setWarning().setDisabled(false).onClick((async () => {
      await rebuildDB("remoteOnly");
    }))));
    fe.createEl("h4", {
      text: "The local database"
    });
    new import_obsidian.Setting(fe).setName("Fetch rebuilt DB").setDesc("Restore or reconstruct local database from remote database.").addButton((s => s.setButtonText("Fetch").setWarning().setDisabled(false).onClick((async () => {
      await this.plugin.vaultAccess.vaultCreate(FLAGMD_REDFLAG3_HR, "");
      this.plugin.performAppReload();
    })))).addButton((s => s.setButtonText("Fetch w/o restarting").setWarning().setDisabled(false).onClick((async () => {
      await rebuildDB("localOnly");
    }))));
    new import_obsidian.Setting(fe).setName("Fetch rebuilt DB (Save local documents before)").setDesc("Restore or reconstruct local database from remote database but use local chunks.").addButton((s => s.setButtonText("Save and Fetch").setWarning().setDisabled(false).onClick((async () => {
      await rebuildDB("localOnlyWithChunks");
    }))));
    new import_obsidian.Setting(fe).setName("Discard local database to reset or uninstall Self-hosted LiveSync").addButton((s => s.setButtonText("Discard").setWarning().setDisabled(false).onClick((async () => {
      await this.plugin.resetLocalDatabase();
      await this.plugin.initializeDatabase();
    }))));
    fe.createEl("h4", {
      text: "Both databases"
    });
    new import_obsidian.Setting(fe).setName("(Beta2) Clean up databases").setDesc("Delete unused chunks to shrink the database. This feature requires disabling 'Use an old adapter for compatibility'").addButton((s => s.setButtonText("DryRun").setDisabled(false).onClick((async () => {
      await this.plugin.dryRunGC();
    })))).addButton((s => s.setButtonText("Perform cleaning").setDisabled(false).setWarning().onClick((async () => {
      this.closeSetting();
      await this.plugin.dbGC();
    }))));
    new import_obsidian.Setting(fe).setName("Rebuild everything").setDesc("Rebuild local and remote database with local files.").addButton((s => s.setButtonText("Rebuild").setWarning().setDisabled(false).onClick((async () => {
      await this.plugin.vaultAccess.vaultCreate(FLAGMD_REDFLAG2_HR, "");
      this.plugin.performAppReload();
    })))).addButton((s => s.setButtonText("Rebuild w/o restarting").setWarning().setDisabled(false).onClick((async () => {
      await rebuildDB("rebuildBothByThisDevice");
    }))));
    applyDisplayEnabled();
    addScreenElement("70", fe);
    applyDisplayEnabled();
    if ("" == this.selectedScreen) if (O != this.plugin.settings.lastReadUpdates) if (this.plugin.settings.isConfigured) changeDisplay("100"); else changeDisplay("110"); else if (isAnySyncEnabled()) changeDisplay("20"); else changeDisplay("110"); else changeDisplay(this.selectedScreen);
  }
};

function isImage(s) {
  const r = s.split(".").splice(-1)[0].toLowerCase();
  return [ "png", "jpg", "jpeg", "gif", "bmp", "webp" ].includes(r);
}

function isComparableText(s) {
  const r = s.split(".").splice(-1)[0].toLowerCase();
  return isPlainText(s) || [ "md", "mdx", "txt", "json" ].includes(r);
}

function isComparableTextDecode(s) {
  const r = s.split(".").splice(-1)[0].toLowerCase();
  return [ "json" ].includes(r);
}

function readDocument(s) {
  if (0 == s.data.length) return "";
  if (isImage(s.path)) return new Uint8Array(decodeBinary(s.data));
  if ("plain" == s.type || "plain" == s.datatype) return getDocData(s.data);
  if (isComparableTextDecode(s.path)) return readString(new Uint8Array(decodeBinary(s.data)));
  if (isComparableText(s.path)) return getDocData(s.data);
  try {
    return readString(new Uint8Array(decodeBinary(s.data)));
  } catch (s) {}
  return getDocData(s.data);
}

var DocumentHistoryModal = class extends import_obsidian.Modal {
  constructor(s, r, o, u, g) {
    super(s);
    this.showDiff = false;
    this.revs_info = [];
    this.currentText = "";
    this.currentDeleted = false;
    this.BlobURLs = new Map;
    this.plugin = r;
    this.file = o instanceof import_obsidian.TFile ? getPathFromTFile(o) : o;
    this.id = u;
    this.initialRev = g;
    if (!o && u) this.file = this.plugin.id2path(u);
    if ("1" == localStorage.getItem("ols-history-highlightdiff")) this.showDiff = true;
  }
  async loadFile(s) {
    var r, o;
    if (!this.id) this.id = await this.plugin.path2id(this.file);
    const u = this.plugin.localDatabase;
    try {
      const g = await u.getRaw(this.id, {
        revs_info: true
      });
      this.revs_info = null != (o = null == (r = g._revs_info) ? void 0 : r.filter((s => "available" == (null == s ? void 0 : s.status)))) ? o : [];
      this.range.max = `${Math.max(this.revs_info.length - 1, 0)}`;
      this.range.value = this.range.max;
      this.fileInfo.setText(`${this.file} / ${this.revs_info.length} revisions`);
      await this.loadRevs(s);
    } catch (s) {
      if (isErrorOfMissingDoc(s)) {
        this.range.max = "0";
        this.range.value = "";
        this.range.disabled = true;
        this.contentView.setText("History of this file was not recorded.");
      } else {
        this.contentView.setText("Error occurred.");
        Logger(s, LOG_LEVEL_VERBOSE);
      }
    }
  }
  async loadRevs(s) {
    if (0 == this.revs_info.length) return;
    if (s) {
      const r = this.revs_info.findIndex((r => r.rev == s));
      if (r >= 0) this.range.value = "" + (this.revs_info.length - 1 - r);
    }
    const r = this.revs_info.length - 1 - this.range.value / 1, o = this.revs_info[r];
    await this.showExactRev(o.rev);
  }
  revokeURL(s) {
    const r = this.BlobURLs.get(s);
    if (r) URL.revokeObjectURL(r);
    this.BlobURLs.delete(s);
  }
  generateBlobURL(s, r) {
    this.revokeURL(s);
    const o = URL.createObjectURL(new Blob([ r ], {
      endings: "transparent",
      type: "application/octet-stream"
    }));
    this.BlobURLs.set(s, o);
    return o;
  }
  async showExactRev(s) {
    const r = this.plugin.localDatabase, o = await r.getDBEntry(this.file, {
      rev: s
    }, false, false, true);
    this.currentText = "";
    this.currentDeleted = false;
    if (false === o) {
      this.currentDeleted = true;
      this.info.innerHTML = "";
      this.contentView.innerHTML = `Could not read this revision<br>(${s})`;
    } else {
      this.currentDoc = o;
      this.info.innerHTML = `Modified:${new Date(o.mtime).toLocaleString()}`;
      let s;
      const u = readDocument(o);
      this.currentDeleted = !!o.deleted;
      if (this.showDiff) {
        const o = this.revs_info.length - 1 - (this.range.value / 1 - 1);
        if (o >= 0 && o < this.revs_info.length) {
          const g = this.revs_info[o].rev, _ = await r.getDBEntry(this.file, {
            rev: g
          }, false, false, true);
          if (false != _) if ("string" == typeof u) {
            s = "";
            const r = new import_diff_match_patch.diff_match_patch, o = readDocument(_), g = r.diff_main(o, u);
            r.diff_cleanupSemantic(g);
            for (const r of g) {
              const o = r[0], u = r[1];
              if (o == import_diff_match_patch.DIFF_DELETE) s += "<span class='history-deleted'>" + escapeStringToHTML(u) + "</span>"; else if (o == import_diff_match_patch.DIFF_EQUAL) s += "<span class='history-normal'>" + escapeStringToHTML(u) + "</span>"; else if (o == import_diff_match_patch.DIFF_INSERT) s += "<span class='history-added'>" + escapeStringToHTML(u) + "</span>";
            }
            s = s.replace(/\n/g, "<br>");
          } else if (isImage(this.file)) {
            s = `<div class='ls-imgdiff-wrap'>\n    <div class='overlay'>\n        <img class='img-base' src="${this.generateBlobURL("base", u)}">\n        <img class='img-overlay' src='${this.generateBlobURL("overlay", readDocument(_))}'>\n    </div>\n</div>`;
            this.contentView.removeClass("op-pre");
          }
        }
      }
      if (null == s) if ("string" != typeof u) {
        if (isImage(this.file)) {
          s = `<div class='ls-imgdiff-wrap'>\n<div class='overlay'>\n<img class='img-base' src="${this.generateBlobURL("base", u)}">\n</div>\n</div>`;
          this.contentView.removeClass("op-pre");
        }
      } else s = escapeStringToHTML(u);
      if (null == s) s = "string" == typeof u ? escapeStringToHTML(u) : "Binary file";
      this.contentView.innerHTML = (this.currentDeleted ? "(At this revision, the file has been deleted)\n" : "") + s;
    }
  }
  onOpen() {
    const {contentEl: s} = this;
    this.titleEl.setText("Document History");
    s.empty();
    this.fileInfo = s.createDiv("");
    this.fileInfo.addClass("op-info");
    const r = s.createDiv("");
    r.addClass("op-flex");
    r.createEl("input", {
      type: "range"
    }, (s => {
      this.range = s;
      s.addEventListener("change", (s => {
        this.loadRevs();
      }));
      s.addEventListener("input", (s => {
        this.loadRevs();
      }));
    }));
    s.createDiv("", (s => {
      s.createEl("label", {}, (s => {
        s.appendChild(createEl("input", {
          type: "checkbox"
        }, (s => {
          if (this.showDiff) s.checked = true;
          s.addEventListener("input", (r => {
            this.showDiff = s.checked;
            localStorage.setItem("ols-history-highlightdiff", true == this.showDiff ? "1" : "");
            this.loadRevs();
          }));
        })));
        s.appendText("Highlight diff");
      }));
    })).addClass("op-info");
    this.info = s.createDiv("");
    this.info.addClass("op-info");
    this.loadFile(this.initialRev);
    const o = s.createDiv({
      text: "Loading old revisions..."
    });
    this.contentView = o;
    o.addClass("op-scrollable");
    o.addClass("op-pre");
    const u = s.createDiv("");
    u.createEl("button", {
      text: "Copy to clipboard"
    }, (s => {
      s.addClass("mod-cta");
      s.addEventListener("click", (async () => {
        await navigator.clipboard.writeText(this.currentText);
        Logger("Old content copied to clipboard", LOG_LEVEL_NOTICE);
      }));
    }));
    const focusFile = async s => {
      const r = this.plugin.app.vault.getFileByPath(s);
      if (r) {
        const s = this.plugin.app.workspace.getLeaf(false);
        await s.openFile(r);
      } else Logger("The file could not view on the editor", LOG_LEVEL_NOTICE);
    };
    u.createEl("button", {
      text: "Back to this revision"
    }, (s => {
      s.addClass("mod-cta");
      s.addEventListener("click", (async () => {
        const s = stripPrefix(this.file);
        if (!isValidPath(s)) {
          Logger("Path is not valid to write content.", LOG_LEVEL_INFO);
          return;
        }
        if (!this.currentDoc) {
          Logger("No active file loaded.", LOG_LEVEL_INFO);
          return;
        }
        const r = readContent(this.currentDoc);
        await this.plugin.vaultAccess.adapterWrite(s, r);
        await focusFile(s);
        this.close();
      }));
    }));
  }
  onClose() {
    const {contentEl: s} = this;
    s.empty();
    this.BlobURLs.forEach((s => {
      console.log(s);
      if (s) URL.revokeObjectURL(s);
    }));
  }
}, WrappedNotice = class {
  constructor(s, r) {
    var o;
    let u = "";
    if (s instanceof DocumentFragment) u = null != (o = s.textContent) ? o : ""; else u = s;
    Logger(u, LOG_LEVEL_NOTICE);
  }
  setMessage(s) {
    var r;
    let o = "";
    if (s instanceof DocumentFragment) o = null != (r = s.textContent) ? r : ""; else o = s;
    Logger(o, LOG_LEVEL_NOTICE);
    return this;
  }
  hide() {}
}, _notice = WrappedNotice;

function setNoticeClass(s) {
  _notice = s;
}

var StorageEventManager = class {}, StorageEventManagerObsidian = class extends StorageEventManager {
  constructor(s) {
    super();
    this.plugin = s;
  }
  beginWatch() {
    const s = this.plugin;
    this.watchVaultChange = this.watchVaultChange.bind(this);
    this.watchVaultCreate = this.watchVaultCreate.bind(this);
    this.watchVaultDelete = this.watchVaultDelete.bind(this);
    this.watchVaultRename = this.watchVaultRename.bind(this);
    this.watchVaultRawEvents = this.watchVaultRawEvents.bind(this);
    s.registerEvent(s.app.vault.on("modify", this.watchVaultChange));
    s.registerEvent(s.app.vault.on("delete", this.watchVaultDelete));
    s.registerEvent(s.app.vault.on("rename", this.watchVaultRename));
    s.registerEvent(s.app.vault.on("create", this.watchVaultCreate));
    s.registerEvent(s.app.vault.on("raw", this.watchVaultRawEvents));
    s.fileEventQueue.startPipeline();
  }
  watchVaultCreate(s, r) {
    this.appendWatchEvent([ {
      type: "CREATE",
      file: s
    } ], r);
  }
  watchVaultChange(s, r) {
    this.appendWatchEvent([ {
      type: "CHANGED",
      file: s
    } ], r);
  }
  watchVaultDelete(s, r) {
    this.appendWatchEvent([ {
      type: "DELETE",
      file: s
    } ], r);
  }
  watchVaultRename(s, r, o) {
    if (s instanceof import_obsidian.TFile) this.appendWatchEvent([ {
      type: "DELETE",
      file: {
        path: r,
        mtime: s.stat.mtime,
        ctime: s.stat.ctime,
        size: s.stat.size,
        deleted: true
      }
    }, {
      type: "CREATE",
      file: s
    } ], o);
  }
  watchVaultRawEvents(s) {
    if (this.plugin.settings.useIgnoreFiles && this.plugin.ignoreFiles.some((r => s.endsWith(r.trim())))) this.plugin.isTargetFile(s).then((() => this._watchVaultRawEvents(s))); else this._watchVaultRawEvents(s);
  }
  _watchVaultRawEvents(s) {
    if (this.plugin.settings.syncInternalFiles || this.plugin.settings.usePluginSync) if (this.plugin.settings.watchInternalFileChanges) if (s.startsWith(this.plugin.app.vault.configDir)) if (!this.plugin.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((s => s)).map((s => new RegExp(s, "i"))).some((r => s.match(r)))) this.appendWatchEvent([ {
      type: "INTERNAL",
      file: {
        path: s,
        mtime: 0,
        ctime: 0,
        size: 0
      }
    } ], null);
  }
  async appendWatchEvent(s, r) {
    var o;
    if (this.plugin.settings.isConfigured) if (!this.plugin.settings.suspendFileWatching) for (const u of s) {
      if (shouldBeIgnored(u.file.path)) continue;
      const s = [ 0, 0, 0, 0, 0, 0 ].map((s => `${Math.floor(1e5 * Math.random())}`)).join("-"), g = u.type, _ = u.file, m = u.oldPath, b = _ instanceof import_obsidian.TFile ? _.stat.size : null != (o = null == _ ? void 0 : _.size) ? o : 0;
      if (this.plugin.isFileSizeExceeded(b) && ("CREATE" == g || "CHANGED" == g)) {
        Logger(`The storage file has been changed but exceeds the maximum size. Skipping: ${u.file.path}`, LOG_LEVEL_NOTICE);
        continue;
      }
      if (_ instanceof import_obsidian.TFolder) continue;
      if (!await this.plugin.isTargetFile(_.path)) continue;
      if (_ instanceof import_obsidian.TFile && ("CREATE" == g || "CHANGED" == g)) {
        await delay(10);
        if (this.plugin.vaultAccess.recentlyTouched(_)) continue;
      }
      const E = _ instanceof import_obsidian.TFile ? {
        ctime: _.stat.ctime,
        mtime: _.stat.mtime,
        file: _,
        path: _.path,
        size: _.stat.size
      } : _;
      this.plugin.fileEventQueue.enqueue({
        type: g,
        args: {
          file: E,
          oldPath: m,
          ctx: r
        },
        key: s
      });
    }
  }
};

async function getChunk(s, r) {
  const o = s.hashCaches.revGet(r);
  if (void 0 !== o) return {
    isNew: false,
    id: o,
    piece: r
  };
  const u = PREFIX_CHUNK + await generateHashedChunk(s, r), g = s.hashCaches.get(u);
  if (g && g != r) {
    Logger(`Hash collided! If possible, please report the following string:${u}=>\nA:--${g}--\nB:--${r}--`, LOG_LEVEL_NOTICE);
    return false;
  }
  s.hashCaches.set(u, r);
  return {
    isNew: true,
    id: u,
    piece: r
  };
}

async function generateHashedChunk(s, r) {
  const o = s.settings.passphrase;
  if ("sha1" == s.settings.hashAlg) if (s.settings.encrypt) return "+" + await sha1(`${r}-${o}-${r.length}`); else return await sha1(`${r}-${r.length}`); else if ("" === s.settings.hashAlg) if (s.settings.encrypt) {
    const u = s.h32Raw((new TextEncoder).encode(o));
    return "+" + (s.h32Raw((new TextEncoder).encode(r)) ^ u ^ r.length).toString(36);
  } else return (s.h32Raw((new TextEncoder).encode(r)) ^ r.length).toString(36); else if ("xxhash64" == s.settings.hashAlg && s.xxhash64) if (s.settings.encrypt) return "+" + s.xxhash64(`${r}-${o}-${r.length}`).toString(36); else return s.xxhash64(`${r}-${r.length}`).toString(36); else if (s.settings.encrypt) return "+" + s.xxhash32(`${r}-${o}-${r.length}`).toString(36); else return s.xxhash32(`${r}-${r.length}`).toString(36);
}

async function putDBEntry(s, r) {
  var o;
  const u = s.id2path(r._id, r), g = stripAllPrefixes(u);
  if (!s.isTargetFile(u)) {
    Logger(`File skipped:${g}`, LOG_LEVEL_VERBOSE);
    return false;
  }
  let _ = 0;
  const m = Math.floor(MAX_DOC_SIZE_BIN * (1 * (s.settings.customChunkSize || 0) + 1));
  let b = false;
  const E = s.settings.minimumChunkSize;
  if (Date.now() - r.mtime > 2592e6) b = false; else if (shouldSplitAsPlainText(u)) b = true;
  const w = r.data instanceof Blob ? r.data : createTextBlob(r.data);
  r.type = isTextBlob(w) ? "plain" : "newnote";
  r.datatype = r.type;
  const S = await splitPieces2(w, m, b, E, u), L = [];
  for await (const r of S()) {
    _++;
    L.push(getChunk(s, r));
  }
  const O = await Promise.all(L);
  if (O.some((s => false === s))) {
    Logger(`This document could not be saved:${g}`, LOG_LEVEL_NOTICE);
    return false;
  }
  const D = O.filter((s => s.isNew)).map((s => ({
    _id: s.id,
    data: s.piece,
    type: "leaf"
  }))), C = _ - D.length;
  if (D.length) {
    const r = (await s.localDatabase.bulkDocs(D)).reduce(((s, r) => {
      if ("ok" in r) {
        s.ok.push(r);
        return s;
      }
      if ("error" in r) if (409 == r.status) {
        s.skip.push(r);
        return s;
      }
      s.failed.push(r);
      return s;
    }), {
      ok: [],
      skip: [],
      failed: []
    });
    if (r.failed.length) {
      Logger(`Save failed.: ${g} :${r.failed.map((s => {
        var r;
        return null != (r = null == s ? void 0 : s.id) ? r : s.toString();
      })).join(",")}`, LOG_LEVEL_VERBOSE);
      Logger(`This document could not be saved:${g}`, LOG_LEVEL_NOTICE);
      return false;
    }
    Logger(`Chunks saved: doc: ${g} ,chunks: ${_} (new:${r.ok.length}, recycled:${r.skip.length}, cached:${C})`);
  }
  const k = {
    children: O.map((s => s.id)),
    _id: r._id,
    path: r.path,
    ctime: r.ctime,
    mtime: r.mtime,
    size: r.size,
    type: r.datatype
  };
  return null != (o = await serialized("file:" + u, (async () => {
    try {
      const r = await s.localDatabase.get(k._id);
      k._rev = r._rev;
    } catch (s) {
      if (isErrorOfMissingDoc(s)) ; else throw s;
    }
    const r = await s.localDatabase.put(k, {
      force: true
    });
    if (r.ok) return r; else return false;
  }))) ? o : false;
}

async function getDBEntryMeta(s, r, o, u = false) {
  var g, _;
  if (!s.isTargetFile(r)) return false;
  const m = await s.path2id(r);
  try {
    let b = null;
    if (o) b = await s.localDatabase.get(m, o); else b = await s.localDatabase.get(m);
    const E = null != (_ = null != (g = null == b ? void 0 : b.deleted) ? g : b._deleted) ? _ : void 0;
    if (!u && E) return false;
    if (b.type && "leaf" == b.type) return false;
    if (!b.type || b.type && "notes" == b.type || "newnote" == b.type || "plain" == b.type) {
      const s = b;
      let o = [], u = "plain";
      if ("newnote" == b.type || "plain" == b.type) {
        o = b.children;
        u = b.type;
      }
      return {
        data: "",
        _id: s._id,
        path: r,
        ctime: s.ctime,
        mtime: s.mtime,
        size: s.size,
        _rev: b._rev,
        _conflicts: b._conflicts,
        children: o,
        datatype: u,
        deleted: E,
        type: u
      };
    }
  } catch (s) {
    if (isErrorOfMissingDoc(s)) return false;
    throw s;
  }
  return false;
}

async function getDBEntryFromMeta(s, r, o, u = false, g = true, _ = false) {
  var m, b, E;
  const w = s.id2path(r._id, r);
  if (!s.isTargetFile(w)) return false;
  const S = stripAllPrefixes(w), L = null != (b = null != (m = r.deleted) ? m : r._deleted) ? b : void 0;
  if (!r.type || r.type && "notes" == r.type) {
    const s = r, o = {
      data: s.data,
      path: s.path,
      _id: s._id,
      ctime: s.ctime,
      mtime: s.mtime,
      size: s.size,
      _rev: r._rev,
      _conflicts: r._conflicts,
      children: [],
      datatype: "newnote",
      deleted: L,
      type: "newnote"
    };
    if (u) {
      Logger("--Old fashioned document--");
      Logger(o);
    }
    return o;
  }
  if ("newnote" == r.type || "plain" == r.type) {
    if (u) {
      const o = await s.localDatabase.get(r._id, {
        conflicts: true,
        revs_info: true
      });
      Logger("-- Conflicts --");
      Logger(null != (E = o._conflicts) ? E : "No conflicts");
      Logger("-- Revs info -- ");
      Logger(o._revs_info);
    }
    try {
      if (u) {
        Logger("--Bare document--");
        Logger(r);
      }
      let o = [];
      if (s.settings.readChunksOnline) {
        const u = await s.collectChunks(r.children, false, g);
        if (false === u || u.some((s => "leaf" != s.type))) {
          Logger(`Chunks of ${S} (${r._id.substring(0, 8)}) are not valid.`, LOG_LEVEL_NOTICE);
          if (u) Logger(`Missing chunks: ${u.map((s => s._id)).join(",")}`, LOG_LEVEL_VERBOSE);
          return false;
        }
        o = u.map((s => s.data));
      } else try {
        if (g) {
          o = await Promise.all(r.children.map((r => s.getDBLeaf(r, g))));
          if (u) {
            Logger("--Chunks--");
            Logger(o);
          }
        } else {
          const u = await s.localDatabase.allDocs({
            keys: r.children,
            include_docs: true
          });
          if (u.rows.some((s => "error" in s))) {
            const s = u.rows.filter((s => "error" in s)).map((s => s.key)).join(", ");
            Logger(`Chunks of ${S} (${r._id.substring(0, 8)}) are not valid.`, LOG_LEVEL_NOTICE);
            Logger(`Missing chunks: ${s}`, LOG_LEVEL_VERBOSE);
            return false;
          }
          if (u.rows.some((s => s.doc && "leaf" != s.doc.type))) {
            const s = u.rows.filter((s => s.doc && "leaf" != s.doc.type)).map((s => s.id)).join(", ");
            Logger(`Chunks of ${S} (${r._id.substring(0, 8)}) are not valid.`, LOG_LEVEL_NOTICE);
            Logger(`Corrupted chunks: ${s}`, LOG_LEVEL_VERBOSE);
            return false;
          }
          o = u.rows.map((s => s.doc.data));
        }
      } catch (s) {
        Logger(`Something went wrong on reading chunks of ${S}(${r._id.substring(0, 8)}) from database, see verbose info for detail.`, LOG_LEVEL_NOTICE);
        Logger(s, LOG_LEVEL_VERBOSE);
        return false;
      }
      const _ = {
        data: o,
        path: r.path,
        _id: r._id,
        ctime: r.ctime,
        mtime: r.mtime,
        size: r.size,
        _rev: r._rev,
        children: r.children,
        datatype: r.type,
        _conflicts: r._conflicts,
        deleted: L,
        type: r.type
      };
      if (u) {
        Logger("--Loaded Document--");
        Logger(_);
      }
      return _;
    } catch (s) {
      if (isErrorOfMissingDoc(s)) {
        Logger(`Missing document content!, could not read ${S}(${r._id.substring(0, 8)}) from database.`, LOG_LEVEL_NOTICE);
        return false;
      }
      Logger(`Something went wrong on reading ${S}(${r._id.substring(0, 8)}) from database:`, LOG_LEVEL_NOTICE);
      Logger(s);
    }
  }
  return false;
}

async function getDBEntry(s, r, o, u = false, g = true, _ = false) {
  const m = await getDBEntryMeta(s, r, o, _);
  if (m) return await getDBEntryFromMeta(s, m, o, u, g, _); else return false;
}

async function deleteDBEntry(s, r, o) {
  var u;
  if (!s.isTargetFile(r)) return false;
  const g = await s.path2id(r);
  try {
    return null != (u = await serialized("file:" + r, (async () => {
      let u = null;
      if (o) u = await s.localDatabase.get(g, o); else u = await s.localDatabase.get(g);
      const _ = o && "" != ("rev" in o ? o.rev : "");
      if (u.type && "leaf" == u.type) return false;
      if (!u.type || u.type && "notes" == u.type) {
        u._deleted = true;
        const o = await s.localDatabase.put(u, {
          force: !_
        });
        Logger(`Entry removed:${r} (${u._id.substring(0, 8)}-${o.rev})`);
        return true;
      }
      if ("newnote" == u.type || "plain" == u.type) {
        if (_) u._deleted = true; else {
          u.deleted = true;
          u.mtime = Date.now();
          if (s.settings.deleteMetadataOfDeletedFiles) u._deleted = true;
        }
        const o = await s.localDatabase.put(u, {
          force: !_
        });
        Logger(`Entry removed:${r} (${u._id.substring(0, 8)}-${o.rev})`);
        return true;
      } else return false;
    }))) ? u : false;
  } catch (s) {
    if (isErrorOfMissingDoc(s)) return false;
    throw s;
  }
}

async function deleteDBEntryPrefix(s, r) {
  let o = 0, u = 0;
  const g = [];
  do {
    const _ = await s.localDatabase.allDocs({
      include_docs: false,
      skip: o,
      limit: 100,
      conflicts: true
    });
    u = _.rows.length;
    if (u > 0) for (const o of _.rows) {
      const u = s.id2path(o.id, o.doc);
      if (u.startsWith(r)) {
        if (s.isTargetFile(u)) g.push(o.id);
      } else if (!o.id.startsWith("h:")) ;
    }
    o += u;
  } while (0 != u);
  let _ = 0, m = 0;
  for (const r of g) try {
    await serialized("file:" + r, (async () => {
      const o = await s.localDatabase.get(r);
      if ("newnote" == o.type || "plain" == o.type) {
        o.deleted = true;
        if (s.settings.deleteMetadataOfDeletedFiles) o._deleted = true;
        o.mtime = Date.now();
      } else o._deleted = true;
      await s.localDatabase.put(o, {
        force: true
      });
    }));
    _++;
  } catch (s) {
    if (isErrorOfMissingDoc(s)) m++; else throw s;
  }
  Logger(`deleteDBEntryPrefix:deleted ${_} items, skipped ${m}`);
  return true;
}

async function ensureDatabaseIsCompatible(s, r, o, u) {
  const g = {
    _id: MILSTONE_DOCID,
    type: "milestoneinfo",
    created: new Date / 1,
    locked: false,
    accepted_nodes: [ o ],
    node_chunk_info: {
      [o]: u
    }
  }, _ = {
    ...g,
    ...await resolveWithIgnoreKnownError(s.get(MILSTONE_DOCID), g)
  };
  _.node_chunk_info = {
    ...g.node_chunk_info,
    ..._.node_chunk_info
  };
  if (_.node_chunk_info[o].min != u.min || _.node_chunk_info[o].max != u.max || "undefined" == typeof _._rev) {
    _.node_chunk_info[o].min = u.min;
    _.node_chunk_info[o].max = u.max;
    await s.put(_);
  }
  let m = u.min, b = u.max;
  for (const s of _.accepted_nodes) if (s != o) if (s in _.node_chunk_info) {
    const r = _.node_chunk_info[s];
    m = Math.max(r.min, m);
    b = Math.min(r.max, b);
  } else {
    m = 0;
    b = 0;
  }
  if (b < m) if (!r.ignoreVersionCheck) return "INCOMPATIBLE";
  if (_.locked) {
    if (-1 == _.accepted_nodes.indexOf(o)) if (_.cleaned) return "NODE_CLEANED"; else return "NODE_LOCKED";
    return "LOCKED";
  }
  return "OK";
}

var LiveSyncLocalDB = class {
  constructor(s, r) {
    this.isReady = false;
    this.xxhash64 = false;
    this.hashCaches = new LRUCache(10, 1e3);
    this.changeHandler = null;
    this.chunkVersion = -1;
    this.maxChunkVersion = -1;
    this.minChunkVersion = -1;
    this.needScanning = false;
    this._chunkCollectProcessor = new QueueProcessor((async s => {
      try {
        const r = await this._collectChunks(s, false);
        if (r) r.forEach((s => sendValue(`chunk-fetch-${s._id}`, s))); else throw new Error("Failed: CollectChunksInternal");
      } catch (r) {
        Logger("Exception raised while retrieving chunks", LOG_LEVEL_NOTICE);
        Logger(r, LOG_LEVEL_VERBOSE);
        s.forEach((s => sendValue(`chunk-fetch-${s}`, [])));
      }
    }), {
      batchSize: 100,
      interval: 100,
      concurrentLimit: 1,
      maintainDelay: true,
      suspended: false,
      totalRemainingReactiveSource: collectingChunks
    });
    this.auth = {
      username: "",
      password: ""
    };
    this.dbname = s;
    this.env = r;
    this.refreshSettings();
  }
  onunload() {
    var s, r;
    this.env.beforeOnUnload(this);
    null == (s = this.changeHandler) || s.cancel();
    null == (r = this.changeHandler) || r.removeAllListeners();
    this.localDatabase.removeAllListeners();
  }
  refreshSettings() {
    const s = this.env.getSettings();
    this.settings = s;
    this.hashCaches = new LRUCache(s.hashCacheMaxCount, s.hashCacheMaxAmount);
  }
  id2path(s, r, o) {
    return this.env.id2path(s, r, o);
  }
  async path2id(s, r) {
    return await this.env.path2id(s, r);
  }
  async close() {
    var s, r;
    Logger("Database closed (by close)");
    this.isReady = false;
    null == (s = this.changeHandler) || s.cancel();
    null == (r = this.changeHandler) || r.removeAllListeners();
    if (null != this.localDatabase) await this.localDatabase.close();
    this.env.onClose(this);
  }
  async initializeDatabase() {
    var s, r;
    await this.prepareHashFunctions();
    if (null != this.localDatabase) await this.localDatabase.close();
    null == (s = this.changeHandler) || s.cancel();
    null == (r = this.changeHandler) || r.removeAllListeners();
    this.localDatabase = null;
    this.localDatabase = this.env.createPouchDBInstance(this.dbname + "-livesync-v2", {
      auto_compaction: false,
      revs_limit: 100,
      deterministic_revs: true
    });
    await this.env.onInitializeDatabase(this);
    Logger("Opening Database...");
    Logger("Database info", LOG_LEVEL_VERBOSE);
    Logger(await this.localDatabase.info(), LOG_LEVEL_VERBOSE);
    this.localDatabase.on("close", (() => {
      var s;
      Logger("Database closed.");
      this.isReady = false;
      this.localDatabase.removeAllListeners();
      null == (s = this.env.getReplicator()) || s.closeReplication();
    }));
    const o = this.localDatabase.changes({
      since: "now",
      live: true,
      filter: s => "leaf" == s.type
    }).on("change", (s => {
      if (!s.deleted) sendValue(`leaf-${s.id}`, s.doc);
    }));
    this.changeHandler = o;
    this.isReady = true;
    Logger("Database is now ready.");
    return true;
  }
  async prepareHashFunctions() {
    if (null == this.h32) if ("sha1" != this.settings.hashAlg) try {
      const {h32ToString: s, h32Raw: r, h32: o, h64: u} = await e2();
      this.xxhash64 = u;
      this.xxhash32 = o;
      this.h32 = s;
      this.h32Raw = r;
      Logger("Newer xxhash has been initialised", LOG_LEVEL_VERBOSE);
    } catch (s) {
      Logger("Could not initialise xxhash: use v1", LOG_LEVEL_VERBOSE);
      Logger(s);
      try {
        this.xxhash64 = false;
        const {h32: s, h32Raw: r} = await xxhash_wasm_default();
        this.h32 = s;
        this.h32Raw = r;
        this.xxhash32 = s => r(writeString(s));
      } catch (s) {
        Logger("Could not initialise xxhash: use sha1F", LOG_LEVEL_VERBOSE);
        Logger(s);
        this.settings.hashAlg = "sha1";
      }
    } else Logger("Fallback(SHA1) is used for hashing", LOG_LEVEL_VERBOSE);
  }
  async readChunk(s, r) {
    const o = this.hashCaches.revGet(s);
    if (o) return o;
    let u;
    try {
      u = await this.localDatabase.get(s);
    } catch (s) {
      if (!isErrorOfMissingDoc(s)) throw s;
    }
    if (void 0 === u && 0 != r) {
      const o = await waitForValue(`leaf-${s}`, r);
      if (o === RESULT_TIMED_OUT) throw new Error(`Timed out: ${s}`);
      u = o;
    }
    if (void 0 === u) throw new Error(`Missing chunks of: ${s}`);
    if ("leaf" != u.type) throw new Error(`Corrupted chunk has been detected: ${s}`);
    this.hashCaches.set(s, u.data);
    return u.data;
  }
  async getDBLeafWithTimeout(s, r) {
    try {
      return await this.readChunk(s, r);
    } catch (s) {
      Logger("Something went wrong while retrieving chunks");
      Logger(s, LOG_LEVEL_VERBOSE);
      throw s;
    }
  }
  getDBLeaf(s, r) {
    return this.getDBLeafWithTimeout(s, r ? LEAF_WAIT_TIMEOUT : 0);
  }
  async getDBEntryMeta(s, r, o = false) {
    return getDBEntryMeta(this, s, r, o);
  }
  async getDBEntry(s, r, o = false, u = true, g = false) {
    return getDBEntry(this, s, r, o, u, g);
  }
  async getDBEntryFromMeta(s, r, o = false, u = true, g = false) {
    return getDBEntryFromMeta(this, s, r, o, u, g);
  }
  async deleteDBEntry(s, r) {
    return deleteDBEntry(this, s, r);
  }
  async deleteDBEntryPrefix(s) {
    return deleteDBEntryPrefix(this, s);
  }
  async putDBEntry(s) {
    return putDBEntry(this, s);
  }
  async resetDatabase() {
    var s, r;
    null == (s = this.changeHandler) || s.cancel();
    null == (r = this.changeHandler) || r.removeAllListeners();
    this.env.getReplicator().closeReplication();
    await this.env.onResetDatabase(this);
    Logger("Database closed for reset Database.");
    this.isReady = false;
    await this.localDatabase.destroy();
    this.localDatabase = null;
    await this.initializeDatabase();
    Logger("Local Database Reset", LOG_LEVEL_NOTICE);
  }
  isTargetFile(s) {
    const r = s.startsWith("i:") ? s.substring(2) : s;
    if (r.startsWith("ix:")) return true;
    if (r.startsWith("ps:")) return true;
    if (r.includes(":")) return false;
    if (this.settings.syncOnlyRegEx) {
      const s = new RegExp(this.settings.syncOnlyRegEx);
      if (!r.match(s)) return false;
    }
    if (this.settings.syncIgnoreRegEx) {
      const s = new RegExp(this.settings.syncIgnoreRegEx);
      if (r.match(s)) return false;
    }
    return true;
  }
  async collectChunks(s, r = false, o) {
    const u = await this.collectChunksWithCache(s);
    if (0 == u.filter((s => !s.chunk)).map((s => s.id)).length) return u.map((s => s.chunk));
    this._chunkCollectProcessor.batchSize = this.settings.concurrencyOfReadChunksOnline;
    this._chunkCollectProcessor.interval = this.settings.minimumIntervalOfReadChunksOnline;
    this._chunkCollectProcessor.enqueueAll(s);
    const g = s.map((s => waitForValue(`chunk-fetch-${s}`)));
    return (await Promise.all(g)).filter(onlyNot(RESULT_TIMED_OUT));
  }
  async _collectChunks(s, r = false) {
    const o = await this.collectChunksWithCache(s), u = o.filter((s => !s.chunk)).map((s => s.id));
    if (0 == u.length) return o.map((s => s.chunk));
    const g = await this.env.getReplicator().fetchRemoteChunks(u, r);
    if (false == g) {
      Logger("Could not fetch chunks from the server. ", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_VERBOSE, "fetch");
      return false;
    }
    g.forEach((s => this.hashCaches.set(s._id, s.data)));
    await this.localDatabase.bulkDocs(g, {
      new_edits: false
    });
    const _ = Object.fromEntries([ ...o.map((s => s.chunk)).filter((s => false !== s)), ...g ].map((s => [ s._id, s ]))), m = s.map((s => {
      var r;
      return null != (r = null == _ ? void 0 : _[s]) ? r : void 0;
    }));
    if (m.some((s => void 0 === s))) return false; else return m;
  }
  async* findEntries(s, r, o) {
    let u = s, g = this.allDocsRaw({
      limit: 100,
      startkey: u,
      endkey: r,
      include_docs: true,
      ...o
    });
    do {
      const s = await g;
      if (0 === s.rows.length) break;
      u = `${s.rows[s.rows.length - 1].id}`;
      g = this.allDocsRaw({
        limit: 100,
        skip: 1,
        startkey: u,
        endkey: r,
        include_docs: true,
        ...o
      });
      for (const r of s.rows) {
        const s = r.doc;
        if ("type" in s) if ("newnote" == s.type || "plain" == s.type) yield s;
      }
    } while ("" != u);
  }
  async* findAllDocs(s) {
    const r = [ () => this.findEntries("", "_", null != s ? s : {}), () => this.findEntries("_􏿿", "h:", null != s ? s : {}), () => this.findEntries("h:􏿿", "", null != s ? s : {}) ];
    for (const s of r) {
      const r = s();
      for await (const s of r) yield s;
    }
  }
  async* findEntryNames(s, r, o) {
    let u = s, g = this.allDocsRaw({
      limit: 100,
      startkey: u,
      endkey: r,
      ...o
    });
    do {
      const s = await g;
      if (0 == s.rows.length) {
        u = "";
        break;
      }
      u = `${s.rows[s.rows.length - 1].key}`;
      g = this.allDocsRaw({
        limit: 100,
        skip: 1,
        startkey: u,
        endkey: r,
        ...o
      });
      for (const r of s.rows) yield r.id;
    } while ("" != u);
  }
  async* findAllDocNames(s) {
    const r = [ () => this.findEntryNames("", "_", null != s ? s : {}), () => this.findEntryNames("_􏿿", "h:", null != s ? s : {}), () => this.findEntryNames("h:􏿿", "i:", null != s ? s : {}), () => this.findEntryNames("i:􏿿", "ix:", null != s ? s : {}), () => this.findEntryNames("ix:􏿿", "ps:", null != s ? s : {}), () => this.findEntryNames("ps:􏿿", "", null != s ? s : {}) ];
    for (const s of r) {
      const r = s();
      for await (const s of r) if (!s.startsWith("_")) if (s != VERSIONINFO_DOCID) yield s;
    }
  }
  async* findAllNormalDocs(s) {
    const r = [ () => this.findEntries("", "_", null != s ? s : {}), () => this.findEntries("_􏿿", "h:", null != s ? s : {}), () => this.findEntries("h:􏿿", "i:", null != s ? s : {}), () => this.findEntries("i:􏿿", "ix:", null != s ? s : {}), () => this.findEntries("ix:􏿿", "ps:", null != s ? s : {}), () => this.findEntries("ps:􏿿", "", null != s ? s : {}) ];
    for (const s of r) {
      const r = s();
      for await (const s of r) if (!s._id.startsWith("_")) if ("newnote" == s.type || "plain" == s.type) yield s;
    }
  }
  async removeRevision(s, r) {
    try {
      const o = await this.localDatabase.get(s, {
        rev: r
      });
      o._deleted = true;
      await this.localDatabase.put(o);
      return true;
    } catch (o) {
      if (isErrorOfMissingDoc(o)) Logger(`Remove revision: Missing target revision, ${s}-${r}`, LOG_LEVEL_VERBOSE);
    }
    return false;
  }
  getRaw(s, r) {
    return this.localDatabase.get(s, r || {});
  }
  removeRaw(s, r, o) {
    return this.localDatabase.remove(s, r, o || {});
  }
  putRaw(s, r) {
    return this.localDatabase.put(s, r || {});
  }
  allDocsRaw(s) {
    return this.localDatabase.allDocs(s);
  }
  bulkDocsRaw(s, r) {
    return this.localDatabase.bulkDocs(s, r || {});
  }
  async collectChunksWithCache(s) {
    const r = s.map((s => this.hashCaches.has(s) ? {
      id: s,
      chunk: this.hashCaches.get(s)
    } : {
      id: s,
      chunk: false
    })), o = r.filter((s => false === s.chunk));
    if (o.length > 0) {
      const s = await this.localDatabase.allDocs({
        keys: o.map((s => s.id)),
        include_docs: true
      }), u = s.rows.filter((s => !("error" in s))).map((s => s.doc)), g = s.rows.filter((s => "error" in s)).map((s => s.key)), _ = (await this.localDatabase.allDocs({
        keys: g.map((s => `_local/${s}`)),
        include_docs: true
      })).rows.filter((s => !("error" in s))).map((s => ({
        ...s.doc,
        _id: s.id.substring(7)
      }))), m = Object.fromEntries(_.map((s => [ s._id, s.data ])));
      for (const s of u) {
        m[s._id] = s.data;
        this.hashCaches.set(s._id, s.data);
      }
      return r.map((s => ({
        id: s.id,
        chunk: false !== s.chunk ? s.chunk : s.id in m ? m[s.id] : false
      }))).map((s => ({
        id: s.id,
        chunk: false !== s.chunk ? {
          _id: s.id,
          data: s.chunk,
          type: "leaf"
        } : false
      })));
    } else return r.map((s => ({
      id: s.id,
      chunk: {
        _id: s.id,
        data: s.chunk,
        type: "leaf"
      }
    })));
  }
}, currentVersionRange = {
  min: 0,
  max: 2,
  current: 2
}, selectorOnDemandPull = {
  selector: {
    type: {
      $ne: "leaf"
    }
  }
}, selectorOnDemandPush = {};

async function* genReplication(s, r) {
  const o = [];
  let locker = () => Promise.resolve(), unlock = () => {
    locker = () => new Promise((s => unlock = s));
  };
  unlock();
  const push = function(s) {
    o.push(s);
    unlock();
  };
  s.on("complete", (s => push([ "complete", s ])));
  s.on("change", (s => push([ "change", s ])));
  s.on("active", (() => push([ "active" ])));
  s.on("denied", (s => push([ "denied", s ])));
  s.on("error", (s => push([ "error", s ])));
  s.on("paused", (s => push([ "paused", s ])));
  s.then((() => push([ "finally" ]))).catch((() => push([ "finally" ])));
  try {
    e: for (;;) {
      const s = o.shift();
      if (!s) {
        const dx = async () => {
          await locker();
          return true;
        };
        for (;;) {
          const timeout = async () => {
            await delay(100);
            return false;
          };
          if (await Promise.race([ dx(), timeout() ])) continue e;
          if (r.aborted) break e;
        }
      } else {
        yield s;
        if ("finally" == s[0]) break;
      }
    }
  } finally {
    s.cancel();
  }
}

var idbProxyableTypes, cursorAdvanceMethods, LiveSyncDBReplicator = class {
  constructor(s) {
    this.syncStatus = "NOT_CONNECTED";
    this.docArrived = 0;
    this.docSent = 0;
    this.lastSyncPullSeq = 0;
    this.maxPullSeq = 0;
    this.lastSyncPushSeq = 0;
    this.maxPushSeq = 0;
    this.nodeid = "";
    this.remoteLocked = false;
    this.remoteCleaned = false;
    this.remoteLockedAndDeviceNotAccepted = false;
    this.updateInfo = () => {
      this.env.replicationStat.value = {
        sent: this.docSent,
        arrived: this.docArrived,
        maxPullSeq: this.maxPullSeq,
        maxPushSeq: this.maxPushSeq,
        lastSyncPullSeq: this.lastSyncPullSeq,
        lastSyncPushSeq: this.lastSyncPushSeq,
        syncStatus: this.syncStatus
      };
    };
    this.env = s;
    this.initializeDatabaseForReplication();
    this.env.getDatabase().on("close", (() => {
      this.closeReplication();
    }));
  }
  async initializeDatabaseForReplication() {
    const s = this.env.getDatabase();
    try {
      const r = await resolveWithIgnoreKnownError(s.get(NODEINFO_DOCID), {
        _id: NODEINFO_DOCID,
        type: "nodeinfo",
        nodeid: "",
        v20220607: true
      });
      if ("" == r.nodeid) {
        r.nodeid = Math.random().toString(36).slice(-10);
        await s.put(r);
      }
      this.nodeid = r.nodeid;
      return true;
    } catch (s) {
      Logger(s);
    }
    return false;
  }
  async migrate(s, r) {
    Logger(`Database updated from ${s} to ${r}`, LOG_LEVEL_NOTICE);
    return true;
  }
  terminateSync() {
    if (this.controller) {
      this.controller.abort();
      this.controller = void 0;
    }
  }
  async openReplication(s, r, o, u = false) {
    await this.initializeDatabaseForReplication();
    if (r) this.openContinuousReplication(s, o, false); else return this.openOneShotReplication(s, o, false, "sync", u);
  }
  replicationActivated(s) {
    this.syncStatus = "CONNECTED";
    this.updateInfo();
    Logger("Replication activated", s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
  }
  async replicationChangeDetected(s, r, o, u) {
    try {
      if ("pull" == s.direction) {
        await this.env.processReplication(s.change.docs);
        this.docArrived += s.change.docs.length;
      } else this.docSent += s.change.docs.length;
      if (r) {
        const s = this.maxPullSeq, r = this.maxPushSeq, g = this.lastSyncPullSeq, _ = this.lastSyncPushSeq, m = 0 == _ ? "" : _ >= r ? " (LIVE)" : ` (${r - _})`, b = 0 == g ? "" : g >= s ? " (LIVE)" : ` (${s - g})`;
        Logger(`↑${this.docSent - o}${m} ↓${this.docArrived - u}${b}`, LOG_LEVEL_NOTICE, "sync");
      }
      this.updateInfo();
    } catch (s) {
      Logger("Replication callback error", LOG_LEVEL_NOTICE, "sync");
      Logger(s, LOG_LEVEL_VERBOSE);
    }
  }
  replicationCompleted(s) {
    this.syncStatus = "COMPLETED";
    this.updateInfo();
    Logger("Replication completed", s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, s ? "sync" : "");
    this.terminateSync();
  }
  replicationDenied(s) {
    this.syncStatus = "ERRORED";
    this.updateInfo();
    this.terminateSync();
    Logger("Replication denied", LOG_LEVEL_NOTICE, "sync");
    Logger(s, LOG_LEVEL_VERBOSE);
  }
  replicationErrored(s) {
    this.syncStatus = "ERRORED";
    this.terminateSync();
    this.updateInfo();
    Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
    Logger(s, LOG_LEVEL_VERBOSE);
  }
  replicationPaused() {
    this.syncStatus = "PAUSED";
    this.updateInfo();
    Logger("Replication paused", LOG_LEVEL_VERBOSE, "sync");
  }
  async processSync(s, r, o, u, g, _, m = true) {
    const b = new AbortController;
    if (this.controller) this.controller.abort();
    this.controller = b;
    const E = genReplication(s, b.signal);
    try {
      for await (const [s, m] of E) {
        const b = await globalConcurrencyController.tryAcquire(1, REPLICATION_BUSY_TIMEOUT);
        if (false === b) {
          Logger("Replication stopped for busy.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
          return "FAILED";
        }
        b();
        switch (s) {
         case "change":
          if ("direction" in m) {
            if ("pull" == m.direction) this.lastSyncPullSeq = Number(`${m.change.last_seq}`.split("-")[0]); else this.lastSyncPushSeq = Number(`${m.change.last_seq}`.split("-")[0]);
            await this.replicationChangeDetected(m, r, o, u);
          } else if ("pullOnly" == g) {
            this.lastSyncPullSeq = Number(`${m.last_seq}`.split("-")[0]);
            await this.replicationChangeDetected({
              direction: "pull",
              change: m
            }, r, o, u);
          } else if ("pushOnly" == g) {
            this.lastSyncPushSeq = Number(`${m.last_seq}`.split("-")[0]);
            this.updateInfo();
            await this.replicationChangeDetected({
              direction: "push",
              change: m
            }, r, o, u);
          }
          if (_) if (this.docSent - o + (this.docArrived - u) > 2 * this.originalSetting.batch_size) return "NEED_RESURRECT";
          break;

         case "complete":
          this.replicationCompleted(r);
          return "DONE";

         case "active":
          this.replicationActivated(r);
          break;

         case "denied":
          this.replicationDenied(m);
          return "FAILED";

         case "error":
          this.replicationErrored(m);
          Logger("Replication stopped.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
          if (this.env.getLastPostFailedBySize()) {
            if (m && 413 == (null == m ? void 0 : m.status)) {
              Logger("Something went wrong during synchronisation. Please check the log!", LOG_LEVEL_NOTICE);
              return "FAILED";
            }
            return "NEED_RETRY";
          } else {
            Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
            Logger(m);
          }
          return "FAILED";

         case "paused":
          this.replicationPaused();
          break;

         case "finally":
          break;

         default:
          Logger(`Unexpected synchronization status:${JSON.stringify(m)}`);
        }
      }
      if (m) return "DONE"; else return "CANCELLED";
    } catch (s) {
      Logger("Unexpected synchronization exception");
      Logger(s, LOG_LEVEL_VERBOSE);
      return "FAILED";
    } finally {
      this.terminateSync();
      this.controller = void 0;
    }
  }
  async openOneShotReplication(s, r, o, u, g = false) {
    if (this.controller) {
      Logger("Replication is already in progress.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
      return false;
    }
    const _ = this.env.getDatabase();
    Logger(`OneShot Sync begin... (${u})`);
    const m = await this.checkReplicationConnectivity(s, false, o, r, g);
    if (false === m) {
      Logger("Could not connect to server.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
      return false;
    }
    this.maxPullSeq = Number(`${m.info.update_seq}`.split("-")[0]);
    this.maxPushSeq = Number(`${(await _.info()).update_seq}`.split("-")[0]);
    if (r) Logger("Looking for the point last synchronized point.", LOG_LEVEL_NOTICE, "sync");
    const {db: b, syncOptionBase: E} = m;
    this.syncStatus = "STARTED";
    this.updateInfo();
    const w = this.docArrived, S = this.docSent;
    if (!o) this.originalSetting = s;
    this.terminateSync();
    const L = "sync" == u ? _.sync(b, {
      ...E
    }) : "pullOnly" == u ? _.replicate.from(b, {
      ...E,
      ...s.readChunksOnline ? selectorOnDemandPull : {}
    }) : "pushOnly" == u ? _.replicate.to(b, {
      ...E,
      ...s.readChunksOnline ? selectorOnDemandPush : {}
    }) : void 0, O = await this.processSync(L, r, S, w, u, o, false);
    if ("DONE" == O) return true;
    if ("CANCELLED" == O) return false;
    if ("FAILED" == O) return false;
    if ("NEED_RESURRECT" == O) {
      this.terminateSync();
      return await this.openOneShotReplication(this.originalSetting, r, false, u, g);
    }
    if ("NEED_RETRY" == O) {
      const o = JSON.parse(JSON.stringify(s));
      o.batch_size = Math.ceil(o.batch_size / 2) + 2;
      o.batches_limit = Math.ceil(o.batches_limit / 2) + 2;
      if (o.batch_size <= 5 && o.batches_limit <= 5) {
        Logger("We can't replicate more lower value.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
        return false;
      } else {
        Logger(`Retry with lower batch size:${o.batch_size}/${o.batches_limit}`, r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
        return await this.openOneShotReplication(o, r, true, u, g);
      }
    }
    return false;
  }
  replicateAllToServer(s, r) {
    return this.openOneShotReplication(s, null != r ? r : false, false, "pushOnly");
  }
  replicateAllFromServer(s, r) {
    return this.openOneShotReplication(s, null != r ? r : false, false, "pullOnly");
  }
  async checkReplicationConnectivity(s, r, o, u, g = false) {
    if ("" != s.versionUpFlash) {
      Logger("Open settings and check message, please.", LOG_LEVEL_NOTICE);
      return false;
    }
    const _ = s.couchDB_URI + ("" == s.couchDB_DBNAME ? "" : "/" + s.couchDB_DBNAME);
    if (this.controller) {
      Logger("Another replication running.");
      return false;
    }
    const m = await this.connectRemoteCouchDBWithSetting(s, this.env.getIsMobile(), true);
    if ("string" == typeof m) {
      Logger(`Could not connect to ${_}: ${m}`, u ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
      return false;
    }
    if (!o) {
      if (!await checkRemoteVersion(m.db, this.migrate.bind(this), VER)) {
        Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL_NOTICE);
        return false;
      }
      this.remoteCleaned = false;
      this.remoteLocked = false;
      this.remoteLockedAndDeviceNotAccepted = false;
      const r = await ensureDatabaseIsCompatible(m.db, s, this.nodeid, currentVersionRange);
      if ("INCOMPATIBLE" == r) {
        Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", LOG_LEVEL_NOTICE);
        return false;
      } else if ("NODE_LOCKED" == r) {
        Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.", LOG_LEVEL_NOTICE);
        this.remoteLockedAndDeviceNotAccepted = true;
        this.remoteLocked = true;
        return false;
      } else if ("LOCKED" == r) this.remoteLocked = true; else if ("NODE_CLEANED" == r) if (g) this.remoteLocked = true; else {
        Logger("The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.", LOG_LEVEL_NOTICE);
        this.remoteLockedAndDeviceNotAccepted = true;
        this.remoteLocked = true;
        this.remoteCleaned = true;
        return false;
      }
    }
    const b = {
      batches_limit: s.batches_limit,
      batch_size: s.batch_size
    };
    if (s.readChunksOnline) {
      b.push = {
        ...selectorOnDemandPush
      };
      b.pull = {
        ...selectorOnDemandPull
      };
    }
    const E = r ? {
      live: true,
      retry: true,
      heartbeat: s.useTimeouts ? false : 3e4,
      ...b
    } : {
      ...b
    };
    return {
      db: m.db,
      info: m.info,
      syncOptionBase: b,
      syncOption: E
    };
  }
  async openContinuousReplication(s, r, o) {
    if (this.controller) {
      Logger("Replication is already in progress.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
      return false;
    }
    const u = this.env.getDatabase();
    Logger("Before LiveSync, start OneShot once...");
    if (await this.openOneShotReplication(s, r, false, "pullOnly")) {
      Logger("LiveSync begin...");
      const g = await this.checkReplicationConnectivity(s, true, true, r);
      if (false === g) {
        Logger("Could not connect to server.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
        return false;
      }
      if (r) Logger("Looking for the point last synchronized point.", LOG_LEVEL_NOTICE, "sync");
      const {db: _, syncOption: m} = g;
      this.syncStatus = "STARTED";
      this.maxPullSeq = Number(`${g.info.update_seq}`.split("-")[0]);
      this.maxPushSeq = Number(`${(await u.info()).update_seq}`.split("-")[0]);
      this.updateInfo();
      const b = this.docArrived, E = this.docSent;
      if (!o) this.originalSetting = s;
      this.terminateSync();
      const w = u.sync(_, {
        ...m
      }), S = "sync", L = await this.processSync(w, r, E, b, S, o);
      if ("DONE" == L) return true;
      if ("FAILED" == L) return false;
      if ("NEED_RESURRECT" == L) {
        this.terminateSync();
        return await this.openContinuousReplication(this.originalSetting, r, false);
      }
      if ("NEED_RETRY" == L) {
        const o = JSON.parse(JSON.stringify(s));
        o.batch_size = Math.ceil(o.batch_size / 2) + 2;
        o.batches_limit = Math.ceil(o.batches_limit / 2) + 2;
        if (o.batch_size <= 5 && o.batches_limit <= 5) {
          Logger("We can't replicate more lower value.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
          return false;
        } else {
          Logger(`Retry with lower batch size:${o.batch_size}/${o.batches_limit}`, r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
          return await this.openContinuousReplication(o, r, true);
        }
      }
    }
    return false;
  }
  closeReplication() {
    if (this.controller) {
      this.controller.abort();
      this.controller = void 0;
      this.syncStatus = "CLOSED";
      Logger("Replication closed");
      this.updateInfo();
    }
  }
  async tryResetRemoteDatabase(s) {
    this.closeReplication();
    const r = await this.connectRemoteCouchDBWithSetting(s, this.env.getIsMobile(), true);
    if ("string" != typeof r) try {
      await r.db.destroy();
      Logger("Remote Database Destroyed", LOG_LEVEL_NOTICE);
      await this.tryCreateRemoteDatabase(s);
    } catch (s) {
      Logger("Something happened on Remote Database Destroy:", LOG_LEVEL_NOTICE);
      Logger(s, LOG_LEVEL_NOTICE);
    }
  }
  async tryCreateRemoteDatabase(s) {
    this.closeReplication();
    if ("string" != typeof await this.connectRemoteCouchDBWithSetting(s, this.env.getIsMobile(), true)) Logger("Remote Database Created or Connected", LOG_LEVEL_NOTICE);
  }
  async markRemoteLocked(s, r, o) {
    const u = s.couchDB_URI + ("" == s.couchDB_DBNAME ? "" : "/" + s.couchDB_DBNAME), g = await this.connectRemoteCouchDBWithSetting(s, this.env.getIsMobile(), true);
    if ("string" == typeof g) {
      Logger(`could not connect to ${u}:${g}`, LOG_LEVEL_NOTICE);
      return;
    }
    if (!await checkRemoteVersion(g.db, this.migrate.bind(this), VER)) {
      Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL_NOTICE);
      return;
    }
    const _ = {
      _id: MILSTONE_DOCID,
      type: "milestoneinfo",
      created: new Date / 1,
      locked: r,
      cleaned: o,
      accepted_nodes: [ this.nodeid ],
      node_chunk_info: {
        [this.nodeid]: currentVersionRange
      }
    }, m = {
      ..._,
      ...await resolveWithIgnoreKnownError(g.db.get(MILSTONE_DOCID), _)
    };
    m.node_chunk_info = {
      ..._.node_chunk_info,
      ...m.node_chunk_info
    };
    m.accepted_nodes = [ this.nodeid ];
    m.locked = r;
    m.cleaned = m.cleaned || o;
    if (r) Logger("Lock remote database to prevent data corruption", LOG_LEVEL_NOTICE); else Logger("Unlock remote database to prevent data corruption", LOG_LEVEL_NOTICE);
    await g.db.put(m);
  }
  async markRemoteResolved(s) {
    const r = s.couchDB_URI + ("" == s.couchDB_DBNAME ? "" : "/" + s.couchDB_DBNAME), o = await this.connectRemoteCouchDBWithSetting(s, this.env.getIsMobile(), true);
    if ("string" == typeof o) {
      Logger(`could not connect to ${r}:${o}`, LOG_LEVEL_NOTICE);
      return;
    }
    if (!await checkRemoteVersion(o.db, this.migrate.bind(this), VER)) {
      Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL_NOTICE);
      return;
    }
    const u = {
      _id: MILSTONE_DOCID,
      type: "milestoneinfo",
      created: new Date / 1,
      locked: false,
      accepted_nodes: [ this.nodeid ],
      node_chunk_info: {
        [this.nodeid]: currentVersionRange
      }
    }, g = {
      ...u,
      ...await resolveWithIgnoreKnownError(o.db.get(MILSTONE_DOCID), u)
    };
    g.node_chunk_info = {
      ...u.node_chunk_info,
      ...g.node_chunk_info
    };
    g.accepted_nodes = Array.from(new Set([ ...g.accepted_nodes, this.nodeid ]));
    Logger("Mark this device as 'resolved'.", LOG_LEVEL_NOTICE);
    await o.db.put(g);
  }
  connectRemoteCouchDBWithSetting(s, r, o = false, u = false) {
    if (s.encrypt && "" == s.passphrase && !s.permitEmptyPassphrase) return "Empty passphrases cannot be used without explicit permission"; else return this.env.connectRemoteCouchDB(s.couchDB_URI + ("" == s.couchDB_DBNAME ? "" : "/" + s.couchDB_DBNAME), {
      username: s.couchDB_USER,
      password: s.couchDB_PASSWORD
    }, s.disableRequestURI || r, s.encrypt ? s.passphrase : s.encrypt, s.useDynamicIterationCount, o, u);
  }
  async fetchRemoteChunks(s, r) {
    const o = await this.connectRemoteCouchDBWithSetting(this.env.getSettings(), this.env.getIsMobile(), false, true);
    if ("string" == typeof o) {
      Logger(`Could not connect to server.${o} `, r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "fetch");
      return false;
    }
    const u = await o.db.allDocs({
      keys: s,
      include_docs: true
    });
    if (u.rows.some((s => "error" in s))) {
      Logger("Some chunks are not exists both on remote and local database.", r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "fetch");
      return false;
    }
    return u.rows.map((s => s.doc));
  }
}, instanceOfAny = (s, r) => r.some((r => s instanceof r));

function getIdbProxyableTypes() {
  return idbProxyableTypes || (idbProxyableTypes = [ IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction ]);
}

function getCursorAdvanceMethods() {
  return cursorAdvanceMethods || (cursorAdvanceMethods = [ IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey ]);
}

var transactionDoneMap = new WeakMap, transformCache = new WeakMap, reverseTransformCache = new WeakMap;

function promisifyRequest(s) {
  const r = new Promise(((r, o) => {
    const unlisten = () => {
      s.removeEventListener("success", success);
      s.removeEventListener("error", error);
    }, success = () => {
      r(wrap(s.result));
      unlisten();
    }, error = () => {
      o(s.error);
      unlisten();
    };
    s.addEventListener("success", success);
    s.addEventListener("error", error);
  }));
  reverseTransformCache.set(r, s);
  return r;
}

function cacheDonePromiseForTransaction(s) {
  if (transactionDoneMap.has(s)) return;
  const r = new Promise(((r, o) => {
    const unlisten = () => {
      s.removeEventListener("complete", complete);
      s.removeEventListener("error", error);
      s.removeEventListener("abort", error);
    }, complete = () => {
      r();
      unlisten();
    }, error = () => {
      o(s.error || new DOMException("AbortError", "AbortError"));
      unlisten();
    };
    s.addEventListener("complete", complete);
    s.addEventListener("error", error);
    s.addEventListener("abort", error);
  }));
  transactionDoneMap.set(s, r);
}

var idbProxyTraps = {
  get(s, r, o) {
    if (s instanceof IDBTransaction) {
      if ("done" === r) return transactionDoneMap.get(s);
      if ("store" === r) return o.objectStoreNames[1] ? void 0 : o.objectStore(o.objectStoreNames[0]);
    }
    return wrap(s[r]);
  },
  set(s, r, o) {
    s[r] = o;
    return true;
  },
  has(s, r) {
    if (s instanceof IDBTransaction && ("done" === r || "store" === r)) return true; else return r in s;
  }
};

function replaceTraps(s) {
  idbProxyTraps = s(idbProxyTraps);
}

function wrapFunction(s) {
  if (getCursorAdvanceMethods().includes(s)) return function(...r) {
    s.apply(unwrap(this), r);
    return wrap(this.request);
  }; else return function(...r) {
    return wrap(s.apply(unwrap(this), r));
  };
}

function transformCachableValue(s) {
  if ("function" == typeof s) return wrapFunction(s);
  if (s instanceof IDBTransaction) cacheDonePromiseForTransaction(s);
  if (instanceOfAny(s, getIdbProxyableTypes())) return new Proxy(s, idbProxyTraps); else return s;
}

function wrap(s) {
  if (s instanceof IDBRequest) return promisifyRequest(s);
  if (transformCache.has(s)) return transformCache.get(s);
  const r = transformCachableValue(s);
  if (r !== s) {
    transformCache.set(s, r);
    reverseTransformCache.set(r, s);
  }
  return r;
}

var unwrap = s => reverseTransformCache.get(s);

function openDB(s, r, {blocked: o, upgrade: u, blocking: g, terminated: _} = {}) {
  const m = indexedDB.open(s, r), b = wrap(m);
  if (u) m.addEventListener("upgradeneeded", (s => {
    u(wrap(m.result), s.oldVersion, s.newVersion, wrap(m.transaction), s);
  }));
  if (o) m.addEventListener("blocked", (s => o(s.oldVersion, s.newVersion, s)));
  b.then((s => {
    if (_) s.addEventListener("close", (() => _()));
    if (g) s.addEventListener("versionchange", (s => g(s.oldVersion, s.newVersion, s)));
  })).catch((() => {}));
  return b;
}

function deleteDB(s, {blocked: r} = {}) {
  const o = indexedDB.deleteDatabase(s);
  if (r) o.addEventListener("blocked", (s => r(s.oldVersion, s)));
  return wrap(o).then((() => {}));
}

var readMethods = [ "get", "getKey", "getAll", "getAllKeys", "count" ], writeMethods = [ "put", "add", "delete", "clear" ], cachedMethods = new Map;

function getMethod(s, r) {
  if (!(s instanceof IDBDatabase && !(r in s) && "string" == typeof r)) return;
  if (cachedMethods.get(r)) return cachedMethods.get(r);
  const o = r.replace(/FromIndex$/, ""), u = r !== o, g = writeMethods.includes(o);
  if (!(o in (u ? IDBIndex : IDBObjectStore).prototype) || !(g || readMethods.includes(o))) return;
  const method = async function(s, ...r) {
    const _ = this.transaction(s, g ? "readwrite" : "readonly");
    let m = _.store;
    if (u) m = m.index(r.shift());
    return (await Promise.all([ m[o](...r), g && _.done ]))[0];
  };
  cachedMethods.set(r, method);
  return method;
}

replaceTraps((s => ({
  ...s,
  get: (r, o, u) => getMethod(r, o) || s.get(r, o, u),
  has: (r, o) => !!getMethod(r, o) || s.has(r, o)
})));

var advanceMethodProps = [ "continue", "continuePrimaryKey", "advance" ], methodMap = {}, advanceResults = new WeakMap, ittrProxiedCursorToOriginalProxy = new WeakMap, cursorIteratorTraps = {
  get(s, r) {
    if (!advanceMethodProps.includes(r)) return s[r];
    let o = methodMap[r];
    if (!o) o = methodMap[r] = function(...s) {
      advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[r](...s));
    };
    return o;
  }
};

async function* iterate(...s) {
  let r = this;
  if (!(r instanceof IDBCursor)) r = await r.openCursor(...s);
  if (!r) return;
  const o = new Proxy(r, cursorIteratorTraps);
  ittrProxiedCursorToOriginalProxy.set(o, r);
  reverseTransformCache.set(o, unwrap(r));
  for (;r; ) {
    yield o;
    r = await (advanceResults.get(o) || r.continue());
    advanceResults.delete(o);
  }
}

function isIteratorProp(s, r) {
  return r === Symbol.asyncIterator && instanceOfAny(s, [ IDBIndex, IDBObjectStore, IDBCursor ]) || "iterate" === r && instanceOfAny(s, [ IDBIndex, IDBObjectStore ]);
}

replaceTraps((s => ({
  ...s,
  get(r, o, u) {
    if (isIteratorProp(r, o)) return iterate; else return s.get(r, o, u);
  },
  has: (r, o) => isIteratorProp(r, o) || s.has(r, o)
})));

var databaseCache = {}, OpenKeyValueDatabase = async s => {
  if (s in databaseCache) {
    databaseCache[s].close();
    delete databaseCache[s];
  }
  const r = s, o = openDB(s, 1, {
    upgrade(s) {
      s.createObjectStore(r);
    }
  }), u = await o;
  databaseCache[s] = u;
  return {
    get: s => u.get(r, s),
    set: (s, o) => u.put(r, o, s),
    del: s => u.delete(r, s),
    clear: () => u.clear(r),
    keys: (s, o) => u.getAllKeys(r, s, o),
    close() {
      delete databaseCache[s];
      return u.close();
    },
    async destroy() {
      delete databaseCache[s];
      u.close();
      await deleteDB(s);
    }
  };
}, HiddenFileSync = class extends LiveSyncCommands {
  constructor() {
    super(...arguments);
    this.periodicInternalFileScanProcessor = new PeriodicProcessor(this.plugin, (async () => this.settings.syncInternalFiles && this.localDatabase.isReady && await this.syncInternalFilesAndDatabase("push", false)));
    this.internalFileProcessor = new QueueProcessor((async s => {
      Logger(`START :Applying hidden ${s.length} files change`, LOG_LEVEL_VERBOSE);
      await this.syncInternalFilesAndDatabase("pull", false, false, s);
      Logger(`DONE  :Applying hidden ${s.length} files change`, LOG_LEVEL_VERBOSE);
    }), {
      batchSize: 100,
      concurrentLimit: 1,
      delay: 10,
      yieldThreshold: 100,
      suspended: false,
      totalRemainingReactiveSource: hiddenFilesEventCount
    });
    this.recentProcessedInternalFiles = [];
    this.conflictResolutionProcessor = new QueueProcessor((async s => {
      var r, o, u;
      const g = s[0];
      sendSignal(`cancel-internal-conflict:${g}`);
      try {
        const s = await this.path2id(g, ICHeader), _ = await this.localDatabase.getRaw(s, {
          conflicts: true
        });
        if (void 0 === _._conflicts) return [];
        if (0 == _._conflicts.length) return [];
        Logger(`Hidden file conflicted:${g}`);
        const m = _._conflicts.sort(((s, r) => Number(s.split("-")[0]) - Number(r.split("-")[0]))), b = _._rev, E = m[0];
        if (g.endsWith(".json")) {
          const w = m[0], S = Number(w.split("-")[0]), L = null != (u = null == (o = null == (r = (await this.localDatabase.getRaw(s, {
            revs_info: true
          }))._revs_info) ? void 0 : r.filter((s => "available" == s.status && Number(s.rev.split("-")[0]) < S)).first()) ? void 0 : o.rev) ? u : "", O = await this.plugin.mergeObject(g, L, _._rev, w);
          if (O) {
            Logger(`Object merge:${g}`, LOG_LEVEL_INFO);
            const r = stripAllPrefixes(g);
            if (!await this.plugin.vaultAccess.adapterExists(r)) await this.vaultAccess.ensureDirectory(r);
            await this.plugin.vaultAccess.adapterWrite(r, O);
            const o = await this.vaultAccess.adapterStat(r);
            if (!o) throw new Error(`conflictResolutionProcessor: Failed to stat file ${r}`);
            await this.storeInternalFileToDatabase({
              path: r,
              ...o
            });
            await this.extractInternalFileFromDatabase(r);
            await this.localDatabase.removeRevision(s, E);
            this.conflictResolutionProcessor.enqueue(g);
            return [];
          } else Logger("Object merge is not applicable.", LOG_LEVEL_VERBOSE);
          return [ {
            path: g,
            revA: b,
            revB: E,
            id: s,
            doc: _
          } ];
        }
        await this.resolveByNewerEntry(s, g, _, b, E);
        return [];
      } catch (s) {
        Logger(`Failed to resolve conflict (Hidden): ${g}`);
        Logger(s, LOG_LEVEL_VERBOSE);
        return [];
      }
    }), {
      suspended: false,
      batchSize: 1,
      concurrentLimit: 5,
      delay: 10,
      keepResultUntilDownstreamConnected: true,
      yieldThreshold: 10,
      pipeTo: new QueueProcessor((async s => {
        const {id: r, doc: o, path: u, revA: g, revB: _} = s[0], m = await this.localDatabase.getDBEntry(u, {
          rev: g
        }), b = await this.localDatabase.getDBEntry(u, {
          rev: _
        });
        if (false == m || false == b) await this.resolveByNewerEntry(r, u, o, g, _); else if (await this.showJSONMergeDialogAndMerge(m, b)) this.conflictResolutionProcessor.enqueue(u);
      }), {
        suspended: false,
        batchSize: 1,
        concurrentLimit: 1,
        delay: 10,
        keepResultUntilDownstreamConnected: false,
        yieldThreshold: 10
      })
    });
  }
  get kvDB() {
    return this.plugin.kvDB;
  }
  getConflictedDoc(s, r) {
    return this.plugin.getConflictedDoc(s, r);
  }
  onunload() {
    var s;
    null == (s = this.periodicInternalFileScanProcessor) || s.disable();
  }
  onload() {
    this.plugin.addCommand({
      id: "livesync-scaninternal",
      name: "Sync hidden files",
      callback: () => {
        this.syncInternalFilesAndDatabase("safe", true);
      }
    });
  }
  async onInitializeDatabase(s) {
    if (this.settings.syncInternalFiles) try {
      Logger("Synchronizing hidden files...");
      await this.syncInternalFilesAndDatabase("push", s);
      Logger("Synchronizing hidden files done");
    } catch (s) {
      Logger("Synchronizing hidden files failed");
      Logger(s, LOG_LEVEL_VERBOSE);
    }
  }
  async beforeReplicate(s) {
    if (this.localDatabase.isReady && this.settings.syncInternalFiles && this.settings.syncInternalFilesBeforeReplication && !this.settings.watchInternalFileChanges) await this.syncInternalFilesAndDatabase("push", s);
  }
  async onResume() {
    var s;
    null == (s = this.periodicInternalFileScanProcessor) || s.disable();
    if (!this.plugin.suspended) {
      if (this.settings.syncInternalFiles) await this.syncInternalFilesAndDatabase("safe", false);
      this.periodicInternalFileScanProcessor.enable(this.settings.syncInternalFiles && this.settings.syncInternalFilesInterval ? 1e3 * this.settings.syncInternalFilesInterval : 0);
    }
  }
  parseReplicationResultItem(s) {
    return false;
  }
  realizeSettingSyncMode() {
    var s;
    null == (s = this.periodicInternalFileScanProcessor) || s.disable();
    if (this.plugin.suspended) return Promise.resolve();
    if (!this.plugin.isReady) return Promise.resolve();
    this.periodicInternalFileScanProcessor.enable(this.settings.syncInternalFiles && this.settings.syncInternalFilesInterval ? 1e3 * this.settings.syncInternalFilesInterval : 0);
    return Promise.resolve();
  }
  procInternalFile(s) {
    this.internalFileProcessor.enqueue(s);
  }
  async watchVaultRawEventsAsync(s) {
    var r, o, u;
    if (!this.settings.syncInternalFiles) return;
    const g = normalizePath(this.app.vault.configDir);
    if ((!this.settings.usePluginSync ? [] : Object.values(this.settings.pluginSyncExtendedSetting).filter((s => s.mode == MODE_SELECTIVE || s.mode == MODE_PAUSED)).map((s => s.files)).flat().map((s => `${g}/${s}`.toLowerCase()))).some((r => r.startsWith(s.toLowerCase())))) {
      Logger(`Hidden file skipped: ${s} is synchronized in customization sync.`, LOG_LEVEL_VERBOSE);
      return;
    }
    const _ = await this.vaultAccess.adapterStat(s);
    if (null != _ && "file" != _.type) return;
    const m = null == _ ? 0 : null != (r = null == _ ? void 0 : _.mtime) ? r : 0, b = ~~(m / 1e3), E = `${s}-${b}`;
    if (0 != m && this.recentProcessedInternalFiles.contains(E)) return;
    this.recentProcessedInternalFiles = [ E, ...this.recentProcessedInternalFiles ].slice(0, 100);
    const w = addPrefix(s, ICHeader), S = await this.localDatabase.getDBEntryMeta(w);
    if (~~((S && S.mtime || 0) / 1e3) != b) if (0 == b) await this.deleteInternalFileOnDatabase(s); else await this.storeInternalFileToDatabase({
      path: s,
      mtime: m,
      ctime: null != (o = null == _ ? void 0 : _.ctime) ? o : m,
      size: null != (u = null == _ ? void 0 : _.size) ? u : 0
    });
  }
  async resolveConflictOnInternalFiles() {
    const s = this.localDatabase.findEntries(ICHeader, ICHeaderEnd, {
      conflicts: true
    });
    this.conflictResolutionProcessor.suspend();
    try {
      for await (const r of s) if ("_conflicts" in r) if (isInternalMetadata(r._id)) this.conflictResolutionProcessor.enqueue(r.path);
    } catch (s) {
      Logger("something went wrong on resolving all conflicted internal files");
      Logger(s, LOG_LEVEL_VERBOSE);
    }
    await this.conflictResolutionProcessor.startPipeline().waitForPipeline();
  }
  async resolveByNewerEntry(s, r, o, u, g) {
    var _;
    const m = await this.localDatabase.getRaw(s, {
      rev: g
    }), b = ("mtime" in o && o.mtime || 0) < ("mtime" in m && m.mtime || 0) ? u : g;
    await this.localDatabase.removeRevision(s, b);
    Logger(`Older one has been deleted:${r}`);
    if (0 === (null == (_ = (await this.localDatabase.getRaw(s, {
      conflicts: true
    }))._conflicts) ? void 0 : _.length)) await this.extractInternalFileFromDatabase(stripAllPrefixes(r)); else this.conflictResolutionProcessor.enqueue(r);
  }
  queueConflictCheck(s) {
    this.conflictResolutionProcessor.enqueue(s);
  }
  async syncInternalFilesAndDatabase(s, r, o = false, u = false) {
    await this.resolveConflictOnInternalFiles();
    const g = r ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
    Logger("Scanning hidden files.", g, "sync_internal");
    const _ = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((s => s)).map((s => new RegExp(s, "i"))), m = normalizePath(this.app.vault.configDir);
    let b = o ? o : await this.scanInternalFiles();
    const E = !this.settings.usePluginSync ? [] : Object.values(this.settings.pluginSyncExtendedSetting).filter((s => s.mode == MODE_SELECTIVE || s.mode == MODE_PAUSED)).map((s => s.files)).flat().map((s => `${m}/${s}`.toLowerCase()));
    b = b.filter((s => E.every((r => !s.path.toLowerCase().startsWith(r)))));
    const w = (await this.localDatabase.allDocsRaw({
      startkey: ICHeader,
      endkey: ICHeaderEnd,
      include_docs: true
    })).rows.map((s => s.doc)).filter((s => !s.deleted)), S = [ ...new Set([ ...b.map((s => normalizePath(s.path))), ...w.map((s => stripAllPrefixes(this.getPath(s)))) ]) ].filter((s => !u || u && -1 !== u.indexOf(s))).filter((s => E.every((r => !s.toLowerCase().startsWith(r))))), L = S.length;
    let O = 0, D = 0;
    const C = {}, countUpdatedFolder = s => {
      const r = s.split("/");
      let o = r.shift(), u = "";
      D++;
      for (;o; ) {
        u += ("" != u ? "/" : "") + o;
        u = normalizePath(u);
        if (!(u in C)) C[u] = 0;
        C[u]++;
        o = r.shift();
      }
    };
    let k = {};
    k = await this.kvDB.get("diff-caches-internal") || {};
    const T = b.reduce(((s, r) => {
      s[r.path] = r;
      return s;
    }), {}), A = w.reduce(((s, r) => {
      s[stripAllPrefixes(this.getPath(r))] = r;
      return s;
    }), {});
    await new QueueProcessor((async s => {
      const r = s[0];
      O++;
      if (O % 100 == 0) Logger(`Hidden file: ${O}/${L}`, g, "sync_internal");
      if (!r) return [];
      if (_.some((s => r.match(s)))) return [];
      if (await this.plugin.isIgnoredByIgnoreFiles(r)) return [];
      const o = r in T ? T[r] : void 0, u = r in A ? A[r] : void 0;
      return [ {
        filename: r,
        fileOnStorage: o,
        fileOnDatabase: u
      } ];
    }), {
      suspended: true,
      batchSize: 1,
      concurrentLimit: 10,
      delay: 0,
      totalRemainingReactiveSource: hiddenFilesProcessingCount
    }).pipeTo(new QueueProcessor((async r => {
      const {filename: o, fileOnStorage: u, fileOnDatabase: g} = r[0];
      if (u && g) {
        const r = o in k ? k[o] : {
          storageMtime: 0,
          docMtime: 0
        };
        if ("pullForce" != s && "pushForce" != s && g.mtime == r.docMtime && u.mtime == r.storageMtime) return;
        const _ = function compareMTime2(s, r) {
          return ~~(s / 1e3) - ~~(r / 1e3);
        }(u.mtime, g.mtime);
        if (_ > 0 || "pushForce" == s) await this.storeInternalFileToDatabase(u);
        if (_ < 0 || "pullForce" == s) if (!await this.extractInternalFileFromDatabase(o)) return;
        r.docMtime = g.mtime;
        r.storageMtime = u.mtime;
        k[o] = r;
        countUpdatedFolder(o);
      } else if (!u && g) {
        if ("push" == s || "pushForce" == s) {
          if (g.deleted) return;
          await this.deleteInternalFileOnDatabase(o, false);
        } else if ("pull" == s || "pullForce" == s) {
          if (await this.extractInternalFileFromDatabase(o)) countUpdatedFolder(o);
        } else if ("safe" == s) {
          if (g.deleted) return;
          if (await this.extractInternalFileFromDatabase(o)) countUpdatedFolder(o);
        }
      } else if (u && !g) if ("push" == s || "pushForce" == s || "safe" == s) await this.storeInternalFileToDatabase(u); else await this.extractInternalFileFromDatabase(u.path); else throw new Error("Invalid state on hidden file sync");
    }), {
      suspended: true,
      batchSize: 1,
      concurrentLimit: 5,
      delay: 0
    })).root.enqueueAll(S).startPipeline().waitForPipeline();
    await this.kvDB.set("diff-caches-internal", k);
    if (("pull" == s || "pullForce" == s) && 0 != D) if (m in C) {
      let s = C[m];
      try {
        const r = Object.values(this.app.plugins.manifests), o = this.app.plugins.enabledPlugins, u = r.filter((s => o.has(s.id)));
        for (const r of u) if (r.dir && r.dir in C) {
          s -= C[r.dir];
          const o = r.id, u = r.name;
          this.plugin.askInPopup(`updated-${o}`, `Files in ${u} has been updated, Press {HERE} to reload ${u}, or press elsewhere to dismiss this message.`, (s => {
            s.text = "HERE";
            s.addEventListener("click", (async () => {
              Logger(`Unloading plugin: ${u}`, LOG_LEVEL_NOTICE, "plugin-reload-" + o);
              await this.app.plugins.unloadPlugin(o);
              await this.app.plugins.loadPlugin(o);
              Logger(`Plugin reloaded: ${u}`, LOG_LEVEL_NOTICE, "plugin-reload-" + o);
            }));
          }));
        }
      } catch (s) {
        Logger("Error on checking plugin status.");
        Logger(s, LOG_LEVEL_VERBOSE);
      }
      if (0 != s) this.plugin.askInPopup("updated-any-hidden", "Hidden files have been synchronized, Press  {HERE} to reload Obsidian, or press elsewhere to dismiss this message.", (s => {
        s.text = "HERE";
        s.addEventListener("click", (() => {
          this.app.commands.executeCommandById("app:reload");
        }));
      }));
    }
    Logger(`Hidden files scanned: ${D} files had been modified`, g, "sync_internal");
  }
  async storeInternalFileToDatabase(s, r = false) {
    if (await this.plugin.isIgnoredByIgnoreFiles(s.path)) return;
    const o = await this.path2id(s.path, ICHeader), u = addPrefix(s.path, ICHeader), g = createBlob(await this.plugin.vaultAccess.adapterReadAuto(s.path)), _ = s.mtime;
    return await serialized("file-" + u, (async () => {
      try {
        const m = await this.localDatabase.getDBEntry(u, void 0, false, false);
        let b;
        if (false === m) b = {
          _id: o,
          path: u,
          data: g,
          mtime: _,
          ctime: _,
          datatype: "newnote",
          size: s.size,
          children: [],
          deleted: false,
          type: "newnote"
        }; else {
          if (await isDocContentSame(readAsBlob(m), g) && !r) return;
          b = {
            ...m,
            data: g,
            mtime: _,
            size: s.size,
            datatype: m.datatype,
            children: [],
            deleted: false,
            type: m.datatype
          };
        }
        const E = await this.localDatabase.putDBEntry(b);
        Logger(`STORAGE --\x3e DB:${s.path}: (hidden) Done`);
        return E;
      } catch (r) {
        Logger(`STORAGE --\x3e DB:${s.path}: (hidden) Failed`);
        Logger(r, LOG_LEVEL_VERBOSE);
        return false;
      }
    }));
  }
  async deleteInternalFileOnDatabase(s, r = false) {
    const o = await this.path2id(s, ICHeader), u = addPrefix(s, ICHeader), g = (new Date).getTime();
    if (!await this.plugin.isIgnoredByIgnoreFiles(s)) await serialized("file-" + u, (async () => {
      try {
        const r = await this.localDatabase.getDBEntryMeta(u, void 0, true);
        let _;
        if (false === r) _ = {
          _id: o,
          path: u,
          mtime: g,
          ctime: g,
          size: 0,
          children: [],
          deleted: true,
          type: "newnote"
        }; else {
          const o = await this.localDatabase.getRaw(r._id, {
            conflicts: true
          });
          if (void 0 !== o._conflicts) for (const u of o._conflicts) {
            await this.localDatabase.removeRevision(r._id, u);
            Logger(`STORAGE -x> DB:${s}: (hidden) conflict removed ${r._rev} =>  ${u}`, LOG_LEVEL_VERBOSE);
          }
          if (r.deleted) {
            Logger(`STORAGE -x> DB:${s}: (hidden) already deleted`);
            return;
          }
          _ = {
            ...r,
            mtime: g,
            size: 0,
            children: [],
            deleted: true,
            type: "newnote"
          };
        }
        await this.localDatabase.putRaw(_);
        Logger(`STORAGE -x> DB:${s}: (hidden) Done`);
      } catch (r) {
        Logger(`STORAGE -x> DB:${s}: (hidden) Failed`);
        Logger(r, LOG_LEVEL_VERBOSE);
        return false;
      }
    }));
  }
  async extractInternalFileFromDatabase(s, r = false) {
    const o = await this.plugin.vaultAccess.adapterExists(s), u = addPrefix(s, ICHeader);
    if (!await this.plugin.isIgnoredByIgnoreFiles(s)) return await serialized("file-" + u, (async () => {
      var g;
      try {
        const _ = await this.localDatabase.getDBEntry(u, {
          conflicts: true
        }, false, true, true);
        if (false === _) throw new Error(`File not found on database.:${s}`);
        if (null == (g = null == _ ? void 0 : _._conflicts) ? void 0 : g.length) {
          Logger(`Hidden file ${s} has conflicted revisions, to keep in safe, writing to storage has been prevented`, LOG_LEVEL_INFO);
          return;
        }
        if (_.deleted || _._deleted || false) {
          if (!o) Logger(`STORAGE <x- DB:${s}: deleted (hidden) Deleted on DB, but the file is already not found on storage.`); else {
            Logger(`STORAGE <x- DB:${s}: deleted (hidden).`);
            await this.plugin.vaultAccess.adapterRemove(s);
            try {
              await this.app.vault.adapter.reconcileInternalFile(s);
            } catch (s) {
              Logger("Failed to call internal API(reconcileInternalFile)", LOG_LEVEL_VERBOSE);
              Logger(s, LOG_LEVEL_VERBOSE);
            }
          }
          return true;
        }
        if (!o) {
          await this.vaultAccess.ensureDirectory(s);
          await this.plugin.vaultAccess.adapterWrite(s, readContent(_), {
            mtime: _.mtime,
            ctime: _.ctime
          });
          try {
            await this.app.vault.adapter.reconcileInternalFile(s);
          } catch (s) {
            Logger("Failed to call internal API(reconcileInternalFile)", LOG_LEVEL_VERBOSE);
            Logger(s, LOG_LEVEL_VERBOSE);
          }
          Logger(`STORAGE <-- DB:${s}: written (hidden,new${r ? ", force" : ""})`);
          return true;
        } else {
          const o = await this.plugin.vaultAccess.adapterReadAuto(s), u = readContent(_);
          if (await isDocContentSame(o, u) && !r) return true;
          await this.plugin.vaultAccess.adapterWrite(s, u, {
            mtime: _.mtime,
            ctime: _.ctime
          });
          try {
            await this.app.vault.adapter.reconcileInternalFile(s);
          } catch (s) {
            Logger("Failed to call internal API(reconcileInternalFile)", LOG_LEVEL_VERBOSE);
            Logger(s, LOG_LEVEL_VERBOSE);
          }
          Logger(`STORAGE <-- DB:${s}: written (hidden, overwrite${r ? ", force" : ""})`);
          return true;
        }
      } catch (o) {
        Logger(`STORAGE <-- DB:${s}: written (hidden, overwrite${r ? ", force" : ""}) Failed`);
        Logger(o, LOG_LEVEL_VERBOSE);
        return false;
      }
    }));
  }
  showJSONMergeDialogAndMerge(s, r) {
    return new Promise((o => {
      Logger("Opening data-merging dialog", LOG_LEVEL_VERBOSE);
      const u = [ s, r ], g = stripAllPrefixes(s.path);
      new JsonResolveModal(this.app, g, [ s, r ], (async (s, r) => {
        var _, m, b;
        try {
          const E = g;
          let w = false;
          if (!r && !s) {
            Logger(`Skipped merging: ${E}`);
            o(false);
            return;
          }
          if (r || s) for (const r of u) if (r._rev != s) if (await this.localDatabase.deleteDBEntry(this.getPath(r), {
            rev: r._rev
          })) {
            Logger(`Conflicted revision has been deleted: ${E}`);
            w = true;
          }
          if (!s && r) {
            if (!await this.plugin.vaultAccess.adapterExists(E)) await this.vaultAccess.ensureDirectory(E);
            await this.plugin.vaultAccess.adapterWrite(E, r);
            const s = await this.plugin.vaultAccess.adapterStat(E);
            if (!s) throw new Error("Stat failed");
            const o = null != (_ = null == s ? void 0 : s.mtime) ? _ : 0;
            await this.storeInternalFileToDatabase({
              path: E,
              mtime: o,
              ctime: null != (m = null == s ? void 0 : s.ctime) ? m : o,
              size: null != (b = null == s ? void 0 : s.size) ? b : 0
            }, true);
            try {
              await this.app.vault.adapter.reconcileInternalFile(E);
            } catch (s) {
              Logger("Failed to call internal API(reconcileInternalFile)", LOG_LEVEL_VERBOSE);
              Logger(s, LOG_LEVEL_VERBOSE);
            }
            Logger(`STORAGE <-- DB:${E}: written (hidden,merged)`);
          }
          if (w) {
            await this.extractInternalFileFromDatabase(E, false);
            Logger(`STORAGE --\x3e DB:${E}: extracted (hidden,merged)`);
          }
          o(true);
        } catch (s) {
          Logger("Could not merge conflicted json");
          Logger(s, LOG_LEVEL_VERBOSE);
          o(false);
        }
      })).open();
    }));
  }
  async scanInternalFiles() {
    var s, r, o, u, g, _;
    const m = normalizePath(this.app.vault.configDir), b = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((s => s)).map((s => new RegExp(s, "i"))), E = !this.settings.usePluginSync ? [] : Object.values(this.settings.pluginSyncExtendedSetting).filter((s => s.mode == MODE_SELECTIVE || s.mode == MODE_PAUSED)).map((s => s.files)).flat().map((s => `${m}/${s}`.toLowerCase())), w = this.app.vault.getRoot().path, S = (await this.getFiles(w, [], void 0, b)).filter((s => s.startsWith("."))).filter((s => !s.startsWith(".trash"))).filter((s => E.every((r => !s.toLowerCase().startsWith(r))))).map((async s => ({
      path: s,
      stat: await this.plugin.vaultAccess.adapterStat(s)
    }))), L = [];
    for (const m of S) {
      const b = await m;
      if (await this.plugin.isIgnoredByIgnoreFiles(b.path)) continue;
      const E = null != (r = null == (s = b.stat) ? void 0 : s.mtime) ? r : 0, w = null != (u = null == (o = b.stat) ? void 0 : o.ctime) ? u : E, S = null != (_ = null == (g = b.stat) ? void 0 : g.size) ? _ : 0;
      L.push({
        ...b,
        mtime: E,
        ctime: w,
        size: S
      });
    }
    return L;
  }
  async getFiles(s, r, o, u) {
    let g;
    try {
      g = await this.app.vault.adapter.list(s);
    } catch (r) {
      Logger(`Could not traverse(HiddenSync):${s}`, LOG_LEVEL_INFO);
      Logger(r, LOG_LEVEL_VERBOSE);
      return [];
    }
    const _ = [ ...g.files.filter((s => !r.some((r => s.endsWith(r))))).filter((s => !o || o.some((r => s.match(r))))).filter((s => !u || u.every((r => !s.match(r))))) ];
    let m = [];
    for (const s of _) if (!await this.plugin.isIgnoredByIgnoreFiles(s)) m.push(s);
    e: for (const s of g.folders) {
      for (const o of r) if (s.endsWith(o)) continue e;
      if (!u || !u.some((r => s.match(r)))) if (!await this.plugin.isIgnoredByIgnoreFiles(s)) m = m.concat(await this.getFiles(s, r, o, u));
    }
    return m;
  }
}, SetupLiveSync = class extends LiveSyncCommands {
  onunload() {}
  onload() {
    this.plugin.registerObsidianProtocolHandler("setuplivesync", (async s => await this.setupWizard(s.settings)));
    this.plugin.addCommand({
      id: "livesync-copysetupuri",
      name: "Copy settings as a new setup URI",
      callback: () => fireAndForget(this.command_copySetupURI())
    });
    this.plugin.addCommand({
      id: "livesync-copysetupuri-short",
      name: "Copy settings as a new setup URI (With customization sync)",
      callback: () => fireAndForget(this.command_copySetupURIWithSync())
    });
    this.plugin.addCommand({
      id: "livesync-copysetupurifull",
      name: "Copy settings as a new setup URI (Full)",
      callback: () => fireAndForget(this.command_copySetupURIFull())
    });
    this.plugin.addCommand({
      id: "livesync-opensetupuri",
      name: "Use the copied setup URI (Formerly Open setup URI)",
      callback: () => fireAndForget(this.command_openSetupURI())
    });
  }
  onInitializeDatabase(s) {}
  beforeReplicate(s) {}
  onResume() {}
  parseReplicationResultItem(s) {
    return false;
  }
  async realizeSettingSyncMode() {}
  async command_copySetupURI(s = true) {
    const r = await askString(this.app, "Encrypt your settings", "The passphrase to encrypt the setup URI", "", true);
    if (false === r) return;
    const o = {
      ...this.settings,
      configPassphraseStore: "",
      encryptedCouchDBConnection: "",
      encryptedPassphrase: ""
    };
    if (s) delete o.pluginSyncExtendedSetting;
    const u = Object.keys(o);
    for (const s of u) if (JSON.stringify(s in o ? o[s] : "") == JSON.stringify(s in DEFAULT_SETTINGS ? DEFAULT_SETTINGS[s] : "*")) delete o[s];
    const g = encodeURIComponent(await encrypt(JSON.stringify(o), r, false)), _ = `${configURIBase}${g}`;
    await navigator.clipboard.writeText(_);
    Logger("Setup URI copied to clipboard", LOG_LEVEL_NOTICE);
  }
  async command_copySetupURIFull() {
    const s = await askString(this.app, "Encrypt your settings", "The passphrase to encrypt the setup URI", "", true);
    if (false === s) return;
    const r = {
      ...this.settings,
      configPassphraseStore: "",
      encryptedCouchDBConnection: "",
      encryptedPassphrase: ""
    }, o = encodeURIComponent(await encrypt(JSON.stringify(r), s, false)), u = `${configURIBase}${o}`;
    await navigator.clipboard.writeText(u);
    Logger("Setup URI copied to clipboard", LOG_LEVEL_NOTICE);
  }
  async command_copySetupURIWithSync() {
    await this.command_copySetupURI(false);
  }
  async command_openSetupURI() {
    const s = await askString(this.app, "Easy setup", "Set up URI", `${configURIBase}aaaaa`);
    if (false === s) return;
    if (!s.startsWith(`${configURIBase}`)) {
      Logger("Set up URI looks wrong.", LOG_LEVEL_NOTICE);
      return;
    }
    const r = decodeURIComponent(s.substring(configURIBase.length));
    console.dir(r);
    await this.setupWizard(r);
  }
  async setupWizard(s) {
    try {
      const r = JSON.parse(JSON.stringify(this.settings)), o = await askString(this.app, "Passphrase", "The passphrase to decrypt your setup URI", "", true);
      if (false === o) return;
      const u = await JSON.parse(await decrypt(s, o, false));
      if (u) {
        if ("yes" == await askYesNo(this.app, "Importing LiveSync's conf, OK?")) {
          const s = Object.assign({}, DEFAULT_SETTINGS, u);
          this.plugin.replicator.closeReplication();
          this.settings.suspendFileWatching = true;
          console.dir(s);
          s.configPassphraseStore = "";
          s.encryptedPassphrase = "";
          s.encryptedCouchDBConnection = "";
          s.additionalSuffixOfDatabaseName = `${"appId" in this.app ? this.app.appId : ""}`;
          const o = "Just import setting", g = "Set it up as secondary or subsequent device", _ = "Secondary device but try keeping local changes", m = "Reconfigure and reconstitute the data", b = "Leave everything to me";
          s.syncInternalFiles = false;
          s.usePluginSync = false;
          s.isConfigured = true;
          if (!s.useIndexedDBAdapter) s.useIndexedDBAdapter = true;
          const E = await askSelectString(this.app, "How would you like to set it up?", [ g, m, _, o, b ]);
          if (E == o) {
            this.plugin.settings = s;
            this.plugin.usedPassphrase = "";
            await this.plugin.saveSettings();
          } else if (E == g) {
            this.plugin.settings = s;
            this.plugin.usedPassphrase = "";
            await this.fetchLocal();
          } else if (E == _) {
            this.plugin.settings = s;
            this.plugin.usedPassphrase = "";
            await this.fetchLocalWithRebuild();
          } else if (E == m) {
            const r = "I know this operation will rebuild all my databases with files on this device, and files that are on the remote database and I didn't synchronize to any other devices will be lost and want to proceed indeed.";
            if (await askSelectString(this.app, "Do you really want to do this?", [ "Cancel", r ]) != r) return;
            this.plugin.settings = s;
            this.plugin.usedPassphrase = "";
            await this.rebuildEverything();
          } else if (E == b) {
            const o = await askYesNo(this.app, "Keep local DB?"), u = await askYesNo(this.app, "Keep remote DB?");
            if ("yes" == o && "yes" == u) {
              this.plugin.settings = s;
              this.plugin.usedPassphrase = "";
              this.suspendAllSync();
              this.suspendExtraSync();
              await this.plugin.saveSettings();
              if ("yes" == await askYesNo(this.app, "Unlock and replicate?")) {
                await this.plugin.replicate(true);
                await this.plugin.markRemoteUnlocked();
              }
              Logger("Configuration loaded.", LOG_LEVEL_NOTICE);
              return;
            }
            if ("no" == o && "no" == u) if ("yes" != await askYesNo(this.app, "Drop everything?")) {
              Logger("Cancelled", LOG_LEVEL_NOTICE);
              this.plugin.settings = r;
              return;
            }
            let g;
            this.plugin.settings = s;
            this.plugin.usedPassphrase = "";
            await this.plugin.saveSettings();
            if ("no" == o) {
              await this.plugin.resetLocalDatabase();
              await this.plugin.localDatabase.initializeDatabase();
              if ("yes" == await askYesNo(this.app, "Rebuild the database?")) g = this.plugin.initializeDatabase(true); else await this.plugin.markRemoteResolved();
            }
            if ("no" == u) {
              await this.plugin.tryResetRemoteDatabase();
              await this.plugin.markRemoteLocked();
            }
            if ("no" == o || "no" == u) if ("yes" == await askYesNo(this.app, "Replicate once?")) {
              if (null != g) await g;
              await this.plugin.replicate(true);
            }
          }
        }
        Logger("Configuration loaded.", LOG_LEVEL_NOTICE);
      } else Logger("Cancelled.", LOG_LEVEL_NOTICE);
    } catch (s) {
      Logger("Couldn't parse or decrypt configuration uri.", LOG_LEVEL_NOTICE);
    }
  }
  suspendExtraSync() {
    Logger("Hidden files and plugin synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.", LOG_LEVEL_NOTICE);
    this.plugin.settings.syncInternalFiles = false;
    this.plugin.settings.usePluginSync = false;
    this.plugin.settings.autoSweepPlugins = false;
  }
  async askHiddenFileConfiguration(s) {
    this.plugin.addOnSetup.suspendExtraSync();
    const r = `Would you like to enable \`Hidden File Synchronization\` or \`Customization sync\`?\n${s.enableFetch ? " - Fetch: Use files stored from other devices. \n" : ""}${s.enableOverwrite ? "- Overwrite: Use files from this device. \n" : ""}- Custom: Synchronize only customization files with a dedicated interface.\n- Keep them disabled: Do not use hidden file synchronization.\nOf course, we are able to disable these features.`, o = "Fetch", u = "Overwrite", g = "Custom", _ = "keep them disabled", m = [];
    if (null == s ? void 0 : s.enableFetch) m.push(o);
    if (null == s ? void 0 : s.enableOverwrite) m.push(u);
    m.push(g);
    m.push(_);
    const b = await confirmWithMessage(this.plugin, "Hidden file sync", r, m, _, 40);
    if (b == o) await this.configureHiddenFileSync("FETCH"); else if (b == u) await this.configureHiddenFileSync("OVERWRITE"); else if (b == _) await this.configureHiddenFileSync("DISABLE"); else if (b == g) await this.configureHiddenFileSync("CUSTOMIZE");
  }
  async configureHiddenFileSync(s) {
    this.plugin.addOnSetup.suspendExtraSync();
    if ("DISABLE" != s) {
      if ("CUSTOMIZE" != s) {
        Logger("Gathering files for enabling Hidden File Sync", LOG_LEVEL_NOTICE);
        if ("FETCH" == s) await this.plugin.addOnHiddenFileSync.syncInternalFilesAndDatabase("pullForce", true); else if ("OVERWRITE" == s) await this.plugin.addOnHiddenFileSync.syncInternalFilesAndDatabase("pushForce", true); else if ("MERGE" == s) await this.plugin.addOnHiddenFileSync.syncInternalFilesAndDatabase("safe", true);
        this.plugin.settings.syncInternalFiles = true;
        await this.plugin.saveSettings();
        Logger("Done! Restarting the app is strongly recommended!", LOG_LEVEL_NOTICE);
      } else if ("CUSTOMIZE" == s) {
        if (!this.plugin.deviceAndVaultName) {
          let s = await askString(this.app, "Device name", "Please set this device name", "desktop");
          if (!s) {
            if (import_obsidian.Platform.isAndroidApp) s = "android-app"; else if (import_obsidian.Platform.isIosApp) s = "ios"; else if (import_obsidian.Platform.isMacOS) s = "macos"; else if (import_obsidian.Platform.isMobileApp) s = "mobile-app"; else if (import_obsidian.Platform.isMobile) s = "mobile"; else if (import_obsidian.Platform.isSafari) s = "safari"; else if (import_obsidian.Platform.isDesktop) s = "desktop"; else if (import_obsidian.Platform.isDesktopApp) s = "desktop-app"; else s = "unknown";
            s += Math.random().toString(36).slice(-4);
          }
          this.plugin.deviceAndVaultName = s;
        }
        this.plugin.settings.usePluginSync = true;
        await this.plugin.saveSettings();
        await this.plugin.addOnConfigSync.scanAllConfigFiles(true);
      }
    } else {
      this.plugin.settings.syncInternalFiles = false;
      this.plugin.settings.usePluginSync = false;
      await this.plugin.saveSettings();
    }
  }
  suspendAllSync() {
    this.plugin.settings.liveSync = false;
    this.plugin.settings.periodicReplication = false;
    this.plugin.settings.syncOnSave = false;
    this.plugin.settings.syncOnEditorSave = false;
    this.plugin.settings.syncOnStart = false;
    this.plugin.settings.syncOnFileOpen = false;
    this.plugin.settings.syncAfterMerge = false;
  }
  async suspendReflectingDatabase() {
    if (!this.plugin.settings.doNotSuspendOnFetching) {
      Logger("Suspending reflection: Database and storage changes will not be reflected in each other until completely finished the fetching.", LOG_LEVEL_NOTICE);
      this.plugin.settings.suspendParseReplicationResult = true;
      this.plugin.settings.suspendFileWatching = true;
      await this.plugin.saveSettings();
    }
  }
  async resumeReflectingDatabase() {
    if (!this.plugin.settings.doNotSuspendOnFetching) {
      Logger("Database and storage reflection has been resumed!", LOG_LEVEL_NOTICE);
      this.plugin.settings.suspendParseReplicationResult = false;
      this.plugin.settings.suspendFileWatching = false;
      await this.plugin.syncAllFiles(true);
      await this.plugin.loadQueuedFiles();
      await this.plugin.saveSettings();
    }
  }
  async askUseNewAdapter() {
    if (!this.plugin.settings.useIndexedDBAdapter) {
      const s = "Now this plugin has been configured to use the old database adapter for keeping compatibility. Do you want to deactivate it?", r = "Yes, disable and use latest", o = [ r, "No, keep compatibility" ];
      if (await confirmWithMessage(this.plugin, "Database adapter", s, o, r, 10) == r) this.plugin.settings.useIndexedDBAdapter = true;
    }
  }
  async resetLocalDatabase() {
    if (this.plugin.settings.isConfigured && "" == this.plugin.settings.additionalSuffixOfDatabaseName) await this.plugin.resetLocalDatabase();
    this.plugin.settings.additionalSuffixOfDatabaseName = `${"appId" in this.app ? this.app.appId : ""}`;
    await this.plugin.resetLocalDatabase();
  }
  async fetchRemoteChunks() {
    if (!this.plugin.settings.doNotSuspendOnFetching && this.plugin.settings.readChunksOnline) {
      Logger("Fetching chunks", LOG_LEVEL_NOTICE);
      const s = await this.plugin.getReplicator().connectRemoteCouchDBWithSetting(this.settings, this.plugin.getIsMobile(), true);
      if ("string" == typeof s) Logger(s, LOG_LEVEL_NOTICE); else await fetchAllUsedChunks(this.localDatabase.localDatabase, s.db);
      Logger("Fetching chunks done", LOG_LEVEL_NOTICE);
    }
  }
  async fetchLocal(s) {
    this.suspendExtraSync();
    await this.askUseNewAdapter();
    this.plugin.settings.isConfigured = true;
    await this.suspendReflectingDatabase();
    await this.plugin.realizeSettingSyncMode();
    await this.resetLocalDatabase();
    await delay(1e3);
    await this.plugin.openDatabase();
    this.plugin.isReady = true;
    if (s) await this.plugin.initializeDatabase(true);
    await this.plugin.markRemoteResolved();
    await delay(500);
    await this.plugin.replicateAllFromServer(true);
    await delay(1e3);
    await this.plugin.replicateAllFromServer(true);
    await this.resumeReflectingDatabase();
    await this.askHiddenFileConfiguration({
      enableFetch: true
    });
  }
  async fetchLocalWithRebuild() {
    return await this.fetchLocal(true);
  }
  async rebuildRemote() {
    this.suspendExtraSync();
    this.plugin.settings.isConfigured = true;
    await this.plugin.realizeSettingSyncMode();
    await this.plugin.markRemoteLocked();
    await this.plugin.tryResetRemoteDatabase();
    await this.plugin.markRemoteLocked();
    await delay(500);
    await this.askHiddenFileConfiguration({
      enableOverwrite: true
    });
    await delay(1e3);
    await this.plugin.replicateAllToServer(true);
    await delay(1e3);
    await this.plugin.replicateAllToServer(true);
  }
  async rebuildEverything() {
    this.suspendExtraSync();
    await this.askUseNewAdapter();
    this.plugin.settings.isConfigured = true;
    await this.plugin.realizeSettingSyncMode();
    await this.resetLocalDatabase();
    await delay(1e3);
    await this.plugin.initializeDatabase(true);
    await this.plugin.markRemoteLocked();
    await this.plugin.tryResetRemoteDatabase();
    await this.plugin.markRemoteLocked();
    await delay(500);
    await this.askHiddenFileConfiguration({
      enableOverwrite: true
    });
    await delay(1e3);
    await this.plugin.replicateAllToServer(true);
    await delay(1e3);
    await this.plugin.replicateAllToServer(true);
  }
};

function add_css5(s) {
  append_styles(s, "svelte-1vjy5r1", ".svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{box-sizing:border-box}.globalhistory.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{margin-bottom:2em}table.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{width:100%}.more.svelte-1vjy5r1>div.svelte-1vjy5r1.svelte-1vjy5r1{display:flex}.more.svelte-1vjy5r1>div.svelte-1vjy5r1>button.svelte-1vjy5r1{flex-grow:1}th.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{position:sticky;top:0;backdrop-filter:blur(10px)}td.mtime.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{white-space:break-spaces}td.path.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{word-break:break-word}.row.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{display:flex;flex-direction:row;flex-wrap:wrap}.row.svelte-1vjy5r1>label.svelte-1vjy5r1.svelte-1vjy5r1{display:flex;align-items:center;min-width:5em}.row.svelte-1vjy5r1>input.svelte-1vjy5r1.svelte-1vjy5r1{flex-grow:1}.filenames.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{display:flex;flex-direction:column}.filenames.svelte-1vjy5r1>.path.svelte-1vjy5r1.svelte-1vjy5r1{font-size:70%}.rev.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{text-overflow:ellipsis;max-width:3em;display:inline-block;overflow:hidden;white-space:nowrap}");
}

function get_each_context5(s, r, o) {
  const u = s.slice();
  u[26] = r[o];
  return u;
}

function create_if_block_53(s) {
  let r;
  return {
    c() {
      r = element("div");
      r.textContent = "Gathering information...";
      attr(r, "class", " svelte-1vjy5r1");
    },
    m(s, o) {
      insert(s, r, o);
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_44(s) {
  let r;
  return {
    c() {
      r = element("th");
      r.textContent = "Chunks";
      attr(r, "class", "svelte-1vjy5r1");
    },
    m(s, o) {
      insert(s, r, o);
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_else_block_23(s) {
  let r, o, u, g;
  return {
    c() {
      r = element("div");
      o = element("button");
      o.textContent = "+1 week";
      attr(o, "class", "svelte-1vjy5r1");
      attr(r, "class", "svelte-1vjy5r1");
    },
    m(_, m) {
      insert(_, r, m);
      append(r, o);
      if (!u) {
        g = listen(o, "click", s[17]);
        u = true;
      }
    },
    p: noop,
    d(s) {
      if (s) detach(r);
      u = false;
      g();
    }
  };
}

function create_if_block_34(s) {
  let r;
  return {
    c() {
      r = element("div");
      attr(r, "class", " svelte-1vjy5r1");
    },
    m(s, o) {
      insert(s, r, o);
    },
    p: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_else_block_14(s) {
  let r, o = s[26].rev + "";
  return {
    c() {
      r = text(o);
    },
    m(s, o) {
      insert(s, r, o);
    },
    p(s, u) {
      if (32 & u && o !== (o = s[26].rev + "")) set_data(r, o);
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_if_block_24(s) {
  let r, o, u, g, _ = s[26].rev + "";
  function click_handler_2() {
    return s[19](s[26]);
  }
  return {
    c() {
      r = element("a");
      o = text(_);
      attr(r, "class", "svelte-1vjy5r1");
    },
    m(s, _) {
      insert(s, r, _);
      append(r, o);
      if (!u) {
        g = listen(r, "click", click_handler_2);
        u = true;
      }
    },
    p(r, u) {
      s = r;
      if (32 & u && _ !== (_ = s[26].rev + "")) set_data(o, _);
    },
    d(s) {
      if (s) detach(r);
      u = false;
      g();
    }
  };
}

function create_if_block_14(s) {
  let r, o, u = s[26].chunks + "";
  return {
    c() {
      r = element("td");
      o = text(u);
      attr(r, "class", "svelte-1vjy5r1");
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, r) {
      if (32 & r && u !== (u = s[26].chunks + "")) set_data(o, u);
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_each_block5(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A, R, I, x, P, N, B = s[26].mtimeDisp + "", F = s[26].dirname.split("/").join("​/") + "", M = s[26].filename + "", V = s[26].changes + "";
  function click_handler_1() {
    return s[18](s[26]);
  }
  function select_block_type_1(s, r) {
    if (s[26].isPlain) return create_if_block_24; else return create_else_block_14;
  }
  let G = select_block_type_1(s), j = G(s), U = s[1] && create_if_block_14(s);
  return {
    c() {
      r = element("tr");
      o = element("td");
      u = text(B);
      g = space();
      _ = element("td");
      m = element("div");
      b = element("span");
      E = text("/");
      w = text(F);
      S = space();
      L = element("span");
      O = element("a");
      D = text(M);
      C = space();
      k = element("td");
      T = element("span");
      j.c();
      A = space();
      R = element("td");
      I = text(V);
      x = space();
      if (U) U.c();
      attr(o, "class", "mtime svelte-1vjy5r1");
      attr(b, "class", "path svelte-1vjy5r1");
      attr(O, "class", "svelte-1vjy5r1");
      attr(L, "class", "filename svelte-1vjy5r1");
      attr(m, "class", "filenames svelte-1vjy5r1");
      attr(_, "class", "path svelte-1vjy5r1");
      attr(T, "class", "rev svelte-1vjy5r1");
      attr(k, "class", "svelte-1vjy5r1");
      attr(R, "class", "svelte-1vjy5r1");
      attr(r, "class", "svelte-1vjy5r1");
    },
    m(s, B) {
      insert(s, r, B);
      append(r, o);
      append(o, u);
      append(r, g);
      append(r, _);
      append(_, m);
      append(m, b);
      append(b, E);
      append(b, w);
      append(m, S);
      append(m, L);
      append(L, O);
      append(O, D);
      append(r, C);
      append(r, k);
      append(k, T);
      j.m(T, null);
      append(r, A);
      append(r, R);
      append(R, I);
      append(r, x);
      if (U) U.m(r, null);
      if (!P) {
        N = listen(O, "click", click_handler_1);
        P = true;
      }
    },
    p(o, g) {
      s = o;
      if (32 & g && B !== (B = s[26].mtimeDisp + "")) set_data(u, B);
      if (32 & g && F !== (F = s[26].dirname.split("/").join("​/") + "")) set_data(w, F);
      if (32 & g && M !== (M = s[26].filename + "")) set_data(D, M);
      if (G === (G = select_block_type_1(s)) && j) j.p(s, g); else {
        j.d(1);
        j = G(s);
        if (j) {
          j.c();
          j.m(T, null);
        }
      }
      if (32 & g && V !== (V = s[26].changes + "")) set_data(I, V);
      if (s[1]) if (U) U.p(s, g); else {
        U = create_if_block_14(s);
        U.c();
        U.m(r, null);
      } else if (U) {
        U.d(1);
        U = null;
      }
    },
    d(s) {
      if (s) detach(r);
      j.d();
      if (U) U.d();
      P = false;
      N();
    }
  };
}

function create_else_block4(s) {
  let r, o, u, g;
  return {
    c() {
      r = element("div");
      o = element("button");
      o.textContent = "+1 week";
      attr(o, "class", "svelte-1vjy5r1");
      attr(r, "class", "svelte-1vjy5r1");
    },
    m(_, m) {
      insert(_, r, m);
      append(r, o);
      if (!u) {
        g = listen(o, "click", s[20]);
        u = true;
      }
    },
    p: noop,
    d(s) {
      if (s) detach(r);
      u = false;
      g();
    }
  };
}

function create_if_block4(s) {
  let r;
  return {
    c() {
      r = element("div");
      attr(r, "class", " svelte-1vjy5r1");
    },
    m(s, o) {
      insert(s, r, o);
    },
    p: noop,
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_fragment5(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A, R, I, x, P, N, B, F, M, V, G, j, U, q, z, W, H, K, Q, J, Y, X, Z, ee, te, ne, ie, se, ae, re, oe, le = s[6] && create_if_block_53(s), ce = s[1] && create_if_block_44(s);
  function select_block_type(s, r) {
    if (s[6]) return create_if_block_34; else return create_else_block_23;
  }
  let ue = select_block_type(s), de = ue(s), fe = ensure_array_like(s[5]), he = [];
  for (let r = 0; r < fe.length; r += 1) he[r] = create_each_block5(get_each_context5(s, fe, r));
  function select_block_type_2(s, r) {
    if (s[6]) return create_if_block4; else return create_else_block4;
  }
  let pe = select_block_type_2(s), ge = pe(s);
  return {
    c() {
      r = element("div");
      o = element("h1");
      o.textContent = "Vault history";
      u = space();
      g = element("div");
      _ = element("div");
      m = element("label");
      m.textContent = "From:";
      b = element("input");
      E = space();
      w = element("div");
      S = element("label");
      S.textContent = "To:";
      L = element("input");
      O = space();
      D = element("div");
      C = element("label");
      C.textContent = "Info:";
      k = space();
      T = element("label");
      A = element("input");
      R = element("span");
      R.textContent = "Diff";
      I = space();
      x = element("label");
      P = element("input");
      N = element("span");
      N.textContent = "Chunks";
      B = space();
      F = element("label");
      M = element("input");
      V = element("span");
      V.textContent = "File integrity";
      G = space();
      if (le) le.c();
      j = space();
      U = element("table");
      q = element("tr");
      z = element("th");
      z.textContent = "Date";
      W = space();
      H = element("th");
      H.textContent = "Path";
      K = space();
      Q = element("th");
      Q.textContent = "Rev";
      J = space();
      Y = element("th");
      Y.textContent = "Stat";
      X = space();
      if (ce) ce.c();
      Z = space();
      ee = element("tr");
      te = element("td");
      de.c();
      ne = space();
      for (let s = 0; s < he.length; s += 1) he[s].c();
      ie = space();
      se = element("tr");
      ae = element("td");
      ge.c();
      attr(o, "class", "svelte-1vjy5r1");
      attr(m, "for", "");
      attr(m, "class", "svelte-1vjy5r1");
      attr(b, "type", "date");
      b.disabled = s[6];
      attr(b, "class", "svelte-1vjy5r1");
      attr(_, "class", "row svelte-1vjy5r1");
      attr(S, "for", "");
      attr(S, "class", "svelte-1vjy5r1");
      attr(L, "type", "date");
      L.disabled = s[6];
      attr(L, "class", "svelte-1vjy5r1");
      attr(w, "class", "row svelte-1vjy5r1");
      attr(C, "for", "");
      attr(C, "class", "svelte-1vjy5r1");
      attr(A, "type", "checkbox");
      A.disabled = s[6];
      attr(A, "class", "svelte-1vjy5r1");
      attr(R, "class", "svelte-1vjy5r1");
      attr(T, "class", "svelte-1vjy5r1");
      attr(P, "type", "checkbox");
      P.disabled = s[6];
      attr(P, "class", "svelte-1vjy5r1");
      attr(N, "class", "svelte-1vjy5r1");
      attr(x, "class", "svelte-1vjy5r1");
      attr(M, "type", "checkbox");
      M.disabled = s[6];
      attr(M, "class", "svelte-1vjy5r1");
      attr(V, "class", "svelte-1vjy5r1");
      attr(F, "class", "svelte-1vjy5r1");
      attr(D, "class", "row svelte-1vjy5r1");
      attr(g, "class", "control svelte-1vjy5r1");
      attr(z, "class", "svelte-1vjy5r1");
      attr(H, "class", "svelte-1vjy5r1");
      attr(Q, "class", "svelte-1vjy5r1");
      attr(Y, "class", "svelte-1vjy5r1");
      attr(q, "class", "svelte-1vjy5r1");
      attr(te, "colspan", "5");
      attr(te, "class", "more svelte-1vjy5r1");
      attr(ee, "class", "svelte-1vjy5r1");
      attr(ae, "colspan", "5");
      attr(ae, "class", "more svelte-1vjy5r1");
      attr(se, "class", "svelte-1vjy5r1");
      attr(U, "class", "svelte-1vjy5r1");
      attr(r, "class", "globalhistory svelte-1vjy5r1");
    },
    m(ue, fe) {
      insert(ue, r, fe);
      append(r, o);
      append(r, u);
      append(r, g);
      append(g, _);
      append(_, m);
      append(_, b);
      set_input_value(b, s[3]);
      append(g, E);
      append(g, w);
      append(w, S);
      append(w, L);
      set_input_value(L, s[4]);
      append(g, O);
      append(g, D);
      append(D, C);
      append(D, k);
      append(D, T);
      append(T, A);
      A.checked = s[0];
      append(T, R);
      append(D, I);
      append(D, x);
      append(x, P);
      P.checked = s[1];
      append(x, N);
      append(D, B);
      append(D, F);
      append(F, M);
      M.checked = s[2];
      append(F, V);
      append(r, G);
      if (le) le.m(r, null);
      append(r, j);
      append(r, U);
      append(U, q);
      append(q, z);
      append(q, W);
      append(q, H);
      append(q, K);
      append(q, Q);
      append(q, J);
      append(q, Y);
      append(q, X);
      if (ce) ce.m(q, null);
      append(U, Z);
      append(U, ee);
      append(ee, te);
      de.m(te, null);
      append(U, ne);
      for (let s = 0; s < he.length; s += 1) if (he[s]) he[s].m(U, null);
      append(U, ie);
      append(U, se);
      append(se, ae);
      ge.m(ae, null);
      if (!re) {
        oe = [ listen(b, "input", s[12]), listen(L, "input", s[13]), listen(A, "change", s[14]), listen(P, "change", s[15]), listen(M, "change", s[16]) ];
        re = true;
      }
    },
    p(s, [o]) {
      if (64 & o) b.disabled = s[6];
      if (8 & o) set_input_value(b, s[3]);
      if (64 & o) L.disabled = s[6];
      if (16 & o) set_input_value(L, s[4]);
      if (64 & o) A.disabled = s[6];
      if (1 & o) A.checked = s[0];
      if (64 & o) P.disabled = s[6];
      if (2 & o) P.checked = s[1];
      if (64 & o) M.disabled = s[6];
      if (4 & o) M.checked = s[2];
      if (s[6]) if (le) ; else {
        le = create_if_block_53(s);
        le.c();
        le.m(r, j);
      } else if (le) {
        le.d(1);
        le = null;
      }
      if (s[1]) if (ce) ; else {
        ce = create_if_block_44(s);
        ce.c();
        ce.m(q, null);
      } else if (ce) {
        ce.d(1);
        ce = null;
      }
      if (ue === (ue = select_block_type(s)) && de) de.p(s, o); else {
        de.d(1);
        de = ue(s);
        if (de) {
          de.c();
          de.m(te, null);
        }
      }
      if (1570 & o) {
        fe = ensure_array_like(s[5]);
        let r;
        for (r = 0; r < fe.length; r += 1) {
          const u = get_each_context5(s, fe, r);
          if (he[r]) he[r].p(u, o); else {
            he[r] = create_each_block5(u);
            he[r].c();
            he[r].m(U, ie);
          }
        }
        for (;r < he.length; r += 1) he[r].d(1);
        he.length = fe.length;
      }
      if (pe === (pe = select_block_type_2(s)) && ge) ge.p(s, o); else {
        ge.d(1);
        ge = pe(s);
        if (ge) {
          ge.c();
          ge.m(ae, null);
        }
      }
    },
    i: noop,
    o: noop,
    d(s) {
      if (s) detach(r);
      if (le) le.d();
      if (ce) ce.d();
      de.d();
      destroy_each(he, s);
      ge.d();
      re = false;
      run_all(oe);
    }
  };
}

function mtimeToDate(s) {
  return new Date(s).toLocaleString();
}

function instance5(s, r, o) {
  let {plugin: u} = r, g = false, _ = false, m = false, b = Date.now() - 6048e5, E = Date.now() + 1728e5;
  const w = (new Date).getTimezoneOffset();
  let S = new Date(b - w).toISOString().split("T")[0], L = new Date(E - w).toISOString().split("T")[0], O = [], D = false;
  async function getHistory(s, r, w) {
    o(6, D = true);
    const S = [], L = await async function fetchChanges() {
      var s, r, w;
      try {
        const o = u.localDatabase;
        let S = [];
        for await (const L of o.findAllNormalDocs()) {
          if (L.mtime < b) continue;
          if (!isAnyNote(L)) continue;
          const O = u.getPath(L), D = isPlainText(L.path);
          let C;
          const k = (null !== (s = (await o.getRaw(L._id, {
            revs_info: true
          }))._revs_info) && void 0 !== s ? s : []).reverse(), T = -1, A = 0, R = 1;
          for (const s of k) if ("available" == s.status) {
            const k = !D && g || m && s.rev == L._rev ? await o.getDBEntry(O, {
              rev: s.rev
            }, false, false, true) : await o.getDBEntryMeta(O, {
              rev: s.rev
            }, true);
            if (false === k) continue;
            const I = s.rev, x = "mtime" in k ? k.mtime : 0;
            if (b > x) continue;
            if (E < x) continue;
            let P = "";
            if (g && !D) {
              const s = getDocData(k.data);
              if (void 0 === C) C = s;
              if (C != s) {
                const r = new import_diff_match_patch.diff_match_patch, o = r.diff_main(C, s);
                r.diff_cleanupSemantic(o);
                C = s;
                const u = {
                  [T]: 0,
                  [A]: 0,
                  [R]: 0
                }, g = o.reduce(((s, r) => {
                  var o;
                  return {
                    ...s,
                    [r[0]]: (null !== (o = s[r[0]]) && void 0 !== o ? o : 0) + r[1].length
                  };
                }), u);
                P = `-${g[T]}, +${g[R]}`;
              }
            }
            const N = k._deleted || (null == k ? void 0 : k.deleted) || false;
            if (N) P += " 🗑️";
            if (I == L._rev) if (m) {
              const s = u.vaultAccess.getAbstractFileByPath(stripAllPrefixes(u.getPath(L)));
              if (s instanceof import_obsidian.TFile) {
                const r = await u.vaultAccess.adapterReadAuto(s), o = readAsBlob(k);
                if (await isDocContentSame(r, o)) P += " ⚖️"; else P += " ⚠️";
              }
            }
            const B = u.getPath(k), [F, ...M] = B.split("/").reverse();
            let V = "";
            if (_) {
              const s = null !== (r = null == k ? void 0 : k.children) && void 0 !== r ? r : [], u = await o.allDocsRaw({
                keys: [ ...s ]
              }), g = u.rows.length, _ = u.rows.filter((s => "error" in s)).length;
              if (0 == _) V = `✅ ${g}`; else V = `🔎 ${_} ✅ ${g}`;
            }
            S.push({
              id: k._id,
              rev: k._rev,
              path: B,
              dirname: M.reverse().join("/"),
              filename: F,
              mtime: x,
              mtimeDisp: mtimeToDate(x),
              size: null !== (w = null == k ? void 0 : k.size) && void 0 !== w ? w : 0,
              isDeleted: N,
              changes: P,
              chunks: V,
              isPlain: D
            });
          }
        }
        return [ ...S ].sort(((s, r) => r.mtime - s.mtime));
      } finally {
        o(6, D = false);
      }
    }();
    S.push(...L);
    o(5, O = [ ...S ]);
  }
  function nextWeek() {
    o(4, L = new Date(E - w + 6048e5).toISOString().split("T")[0]);
  }
  function prevWeek() {
    o(3, S = new Date(b - w - 6048e5).toISOString().split("T")[0]);
  }
  onMount((async () => {
    await getHistory();
  }));
  onDestroy((() => {}));
  function showHistory(s, r) {
    new DocumentHistoryModal(u.app, u, s, void 0, r).open();
  }
  function openFile(s) {
    u.app.workspace.openLinkText(s, s);
  }
  s.$$set = s => {
    if ("plugin" in s) o(11, u = s.plugin);
  };
  s.$$.update = () => {
    if (31 & s.$$.dirty) {
      b = new Date(S).getTime() + w;
      E = new Date(L).getTime() + w;
      getHistory();
    }
  };
  return [ g, _, m, S, L, O, D, nextWeek, prevWeek, showHistory, openFile, u, function input0_input_handler() {
    S = this.value;
    o(3, S);
  }, function input1_input_handler() {
    L = this.value;
    o(4, L);
  }, function input2_change_handler() {
    g = this.checked;
    o(0, g);
  }, function input3_change_handler() {
    _ = this.checked;
    o(1, _);
  }, function input4_change_handler() {
    m = this.checked;
    o(2, m);
  }, () => nextWeek(), s => openFile(s.path), s => showHistory(s.path, (null == s ? void 0 : s.rev) || ""), () => prevWeek() ];
}

var GlobalHistory = class extends SvelteComponent {
  constructor(s) {
    super();
    init2(this, s, instance5, create_fragment5, safe_not_equal, {
      plugin: 11
    }, add_css5);
  }
}, GlobalHistory_default = GlobalHistory, VIEW_TYPE_GLOBAL_HISTORY = "global-history", GlobalHistoryView = class extends import_obsidian.ItemView {
  getIcon() {
    return "clock";
  }
  constructor(s, r) {
    super(s);
    this.plugin = r;
  }
  getViewType() {
    return VIEW_TYPE_GLOBAL_HISTORY;
  }
  getDisplayText() {
    return "Vault history";
  }
  async onOpen() {
    this.component = new GlobalHistory_default({
      target: this.contentEl,
      props: {
        plugin: this.plugin
      }
    });
  }
  async onClose() {
    this.component.$destroy();
  }
}, import_obsidian6 = require("obsidian");

function add_css6(s) {
  append_styles(s, "svelte-1j0mkaj", ".svelte-1j0mkaj.svelte-1j0mkaj{box-sizing:border-box}.logpane.svelte-1j0mkaj.svelte-1j0mkaj{display:flex;height:100%;flex-direction:column}.log.svelte-1j0mkaj.svelte-1j0mkaj{overflow-y:scroll;user-select:text;padding-bottom:2em}.log.svelte-1j0mkaj>pre.svelte-1j0mkaj{margin:0}.log.svelte-1j0mkaj>pre.wrap-right.svelte-1j0mkaj{word-break:break-all;max-width:100%;width:100%;white-space:normal}.row.svelte-1j0mkaj.svelte-1j0mkaj{display:flex;flex-direction:row;justify-content:flex-end}.row.svelte-1j0mkaj>label.svelte-1j0mkaj{display:flex;align-items:center;min-width:5em;margin-right:1em}");
}

function get_each_context6(s, r, o) {
  const u = s.slice();
  u[11] = r[o];
  return u;
}

function create_each_block6(s) {
  let r, o, u = s[11] + "";
  return {
    c() {
      r = element("pre");
      o = text(u);
      attr(r, "class", "svelte-1j0mkaj");
      toggle_class(r, "wrap-right", s[1]);
    },
    m(s, u) {
      insert(s, r, u);
      append(r, o);
    },
    p(s, g) {
      if (1 & g && u !== (u = s[11] + "")) set_data(o, u);
      if (2 & g) toggle_class(r, "wrap-right", s[1]);
    },
    d(s) {
      if (s) detach(r);
    }
  };
}

function create_fragment6(s) {
  let r, o, u, g, _, m, b, E, w, S, L, O, D, C, k, T, A, R, I, x, P = ensure_array_like(s[0]), N = [];
  for (let r = 0; r < P.length; r += 1) N[r] = create_each_block6(get_each_context6(s, P, r));
  return {
    c() {
      r = element("div");
      o = comment(" <h1>Self-hosted LiveSync Log</h1> ");
      u = space();
      g = element("div");
      _ = element("div");
      m = element("label");
      b = element("input");
      E = element("span");
      E.textContent = "Wrap";
      w = space();
      S = element("label");
      L = element("input");
      O = element("span");
      O.textContent = "Auto scroll";
      D = space();
      C = element("label");
      k = element("input");
      T = element("span");
      T.textContent = "Pause";
      A = space();
      R = element("div");
      for (let s = 0; s < N.length; s += 1) N[s].c();
      attr(b, "type", "checkbox");
      attr(b, "class", "svelte-1j0mkaj");
      attr(E, "class", "svelte-1j0mkaj");
      attr(m, "class", "svelte-1j0mkaj");
      attr(L, "type", "checkbox");
      attr(L, "class", "svelte-1j0mkaj");
      attr(O, "class", "svelte-1j0mkaj");
      attr(S, "class", "svelte-1j0mkaj");
      attr(k, "type", "checkbox");
      attr(k, "class", "svelte-1j0mkaj");
      attr(T, "class", "svelte-1j0mkaj");
      attr(C, "class", "svelte-1j0mkaj");
      attr(_, "class", "row svelte-1j0mkaj");
      attr(g, "class", "control svelte-1j0mkaj");
      attr(R, "class", "log svelte-1j0mkaj");
      attr(r, "class", "logpane svelte-1j0mkaj");
    },
    m(P, B) {
      insert(P, r, B);
      append(r, o);
      append(r, u);
      append(r, g);
      append(g, _);
      append(_, m);
      append(m, b);
      b.checked = s[1];
      append(m, E);
      append(_, w);
      append(_, S);
      append(S, L);
      L.checked = s[2];
      append(S, O);
      append(_, D);
      append(_, C);
      append(C, k);
      k.checked = s[3];
      append(C, T);
      append(r, A);
      append(r, R);
      for (let s = 0; s < N.length; s += 1) if (N[s]) N[s].m(R, null);
      s[8](R);
      if (!I) {
        x = [ listen(b, "change", s[5]), listen(L, "change", s[6]), listen(k, "change", s[7]) ];
        I = true;
      }
    },
    p(s, [r]) {
      if (2 & r) b.checked = s[1];
      if (4 & r) L.checked = s[2];
      if (8 & r) k.checked = s[3];
      if (3 & r) {
        P = ensure_array_like(s[0]);
        let o;
        for (o = 0; o < P.length; o += 1) {
          const u = get_each_context6(s, P, o);
          if (N[o]) N[o].p(u, r); else {
            N[o] = create_each_block6(u);
            N[o].c();
            N[o].m(R, null);
          }
        }
        for (;o < N.length; o += 1) N[o].d(1);
        N.length = P.length;
      }
    },
    i: noop,
    o: noop,
    d(o) {
      if (o) detach(r);
      destroy_each(N, o);
      s[8](null);
      I = false;
      run_all(x);
    }
  };
}

function instance6(s, r, o) {
  let u, g, _ = [], m = false, b = true, E = false;
  function updateLog(s) {
    const r = s.value;
    if (!E) {
      o(0, _ = [ ...r ]);
      setTimeout((() => {
        if (g) o(4, g.scrollTop = g.scrollHeight, g);
      }), 10);
    }
  }
  onMount((async () => {
    logMessages.onChanged(updateLog);
    Logger("Log window opened");
    u = () => logMessages.offChanged(updateLog);
  }));
  onDestroy((() => {
    if (u) u();
  }));
  return [ _, m, b, E, g, function input0_change_handler() {
    m = this.checked;
    o(1, m);
  }, function input1_change_handler() {
    b = this.checked;
    o(2, b);
  }, function input2_change_handler() {
    E = this.checked;
    o(3, E);
  }, function div2_binding(s) {
    binding_callbacks[s ? "unshift" : "push"]((() => {
      g = s;
      o(4, g);
    }));
  } ];
}

var LogPane = class extends SvelteComponent {
  constructor(s) {
    super();
    init2(this, s, instance6, create_fragment6, safe_not_equal, {}, add_css6);
  }
}, LogPane_default = LogPane, VIEW_TYPE_LOG = "log-log", LogPaneView = class extends import_obsidian6.ItemView {
  getIcon() {
    return "view-log";
  }
  constructor(s, r) {
    super(s);
    this.plugin = r;
  }
  getViewType() {
    return VIEW_TYPE_LOG;
  }
  getDisplayText() {
    return "Self-hosted LiveSync Log";
  }
  async onOpen() {
    this.component = new LogPane_default({
      target: this.contentEl,
      props: {}
    });
  }
  async onClose() {
    this.component.$destroy();
  }
};

function getFileLockKey(s) {
  return `fl:${"string" == typeof s ? s : s.path}`;
}

function toArrayBuffer(s) {
  if (s instanceof Uint8Array) return s.buffer;
  if (s instanceof DataView) return s.buffer; else return s;
}

async function processReadFile(s, r) {
  return await serialized(getFileLockKey(s), (() => r()));
}

async function processWriteFile(s, r) {
  return await serialized(getFileLockKey(s), (() => r()));
}

var SerializedFileAccess = class {
  constructor(s) {
    this.touchedFiles = [];
    this.app = s;
  }
  async adapterStat(s) {
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    return await processReadFile(s, (() => this.app.vault.adapter.stat(r)));
  }
  async adapterExists(s) {
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    return await processReadFile(s, (() => this.app.vault.adapter.exists(r)));
  }
  async adapterRemove(s) {
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    return await processReadFile(s, (() => this.app.vault.adapter.remove(r)));
  }
  async adapterRead(s) {
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    return await processReadFile(s, (() => this.app.vault.adapter.read(r)));
  }
  async adapterReadBinary(s) {
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    return await processReadFile(s, (() => this.app.vault.adapter.readBinary(r)));
  }
  async adapterReadAuto(s) {
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    if (isPlainText(r)) return await processReadFile(s, (() => this.app.vault.adapter.read(r))); else return await processReadFile(s, (() => this.app.vault.adapter.readBinary(r)));
  }
  async adapterWrite(s, r, o) {
    const u = s instanceof import_obsidian.TFile ? s.path : s;
    if ("string" == typeof r) return await processWriteFile(s, (() => this.app.vault.adapter.write(u, r, o))); else return await processWriteFile(s, (() => this.app.vault.adapter.writeBinary(u, toArrayBuffer(r), o)));
  }
  async vaultCacheRead(s) {
    return await processReadFile(s, (() => this.app.vault.cachedRead(s)));
  }
  async vaultRead(s) {
    return await processReadFile(s, (() => this.app.vault.read(s)));
  }
  async vaultReadBinary(s) {
    return await processReadFile(s, (() => this.app.vault.readBinary(s)));
  }
  async vaultReadAuto(s) {
    if (isPlainText(s.path)) return await processReadFile(s, (() => this.app.vault.read(s))); else return await processReadFile(s, (() => this.app.vault.readBinary(s)));
  }
  async vaultModify(s, r, o) {
    if ("string" == typeof r) return await processWriteFile(s, (async () => {
      const u = await this.app.vault.read(s);
      if (r === u) {
        if (o && o.mtime) markChangesAreSame(s, s.stat.mtime, o.mtime);
        return false;
      }
      await this.app.vault.modify(s, r, o);
      return true;
    })); else return await processWriteFile(s, (async () => {
      const u = await this.app.vault.readBinary(s);
      if (await isDocContentSame(createBinaryBlob(u), createBinaryBlob(r))) {
        if (o && o.mtime) markChangesAreSame(s, s.stat.mtime, o.mtime);
        return false;
      }
      await this.app.vault.modifyBinary(s, toArrayBuffer(r), o);
      return true;
    }));
  }
  async vaultCreate(s, r, o) {
    if ("string" == typeof r) return await processWriteFile(s, (() => this.app.vault.create(s, r, o))); else return await processWriteFile(s, (() => this.app.vault.createBinary(s, toArrayBuffer(r), o)));
  }
  trigger(s, ...r) {
    return this.app.vault.trigger(s, ...r);
  }
  async adapterAppend(s, r, o) {
    return await this.app.vault.adapter.append(s, r, o);
  }
  async delete(s, r = false) {
    return await processWriteFile(s, (() => this.app.vault.delete(s, r)));
  }
  async trash(s, r = false) {
    return await processWriteFile(s, (() => this.app.vault.trash(s, r)));
  }
  getAbstractFileByPath(s) {
    return this.app.vault.getAbstractFileByPath(s);
  }
  getFiles() {
    return this.app.vault.getFiles();
  }
  async ensureDirectory(s) {
    const r = s.split("/");
    r.pop();
    let o = "";
    for (const s of r) {
      o += s;
      try {
        await this.app.vault.adapter.mkdir(o);
      } catch (s) {
        if ("Folder already exists." == (null == s ? void 0 : s.message)) ; else {
          Logger("Folder Create Error");
          Logger(s);
        }
      }
      o += "/";
    }
  }
  touch(s) {
    const r = s instanceof import_obsidian.TFile ? s : this.getAbstractFileByPath(s), o = `${r.path}-${r.stat.mtime}-${r.stat.size}`;
    this.touchedFiles.unshift(o);
    this.touchedFiles = this.touchedFiles.slice(0, 100);
  }
  recentlyTouched(s) {
    const r = s instanceof import_obsidian.TFile ? `${s.path}-${s.stat.mtime}-${s.stat.size}` : `${s.path}-${s.mtime}-${s.size}`;
    if (-1 == this.touchedFiles.indexOf(r)) return false; else return true;
  }
  clearTouched() {
    this.touchedFiles = [];
  }
}, isDebug = false;

setNoticeClass(import_obsidian.Notice);

setGlobalLogFunction(((s, r, o) => {
  const u = {
    message: s,
    level: r,
    key: o
  };
  logStore.enqueue(u);
}));

var recentLogs = [], recentLogProcessor = new QueueProcessor((s => {
  recentLogs = [ ...recentLogs, ...s ].splice(-200);
  logMessages.value = recentLogs;
}), {
  batchSize: 25,
  delay: 10,
  suspended: false,
  concurrentLimit: 1
}).resumePipeLine();

async function fetchByAPI(s) {
  var r, o;
  const u = await (0, import_obsidian.requestUrl)(s);
  if (u.status - u.status % 100 != 200) {
    const s = new Error(`Request Error:${u.status}`);
    if (u.json) {
      s.message = u.json.reason;
      s.name = `${null != (r = u.json.error) ? r : ""}:${null != (o = u.json.message) ? o : ""}`;
    }
    s.status = u.status;
    throw s;
  }
  return u;
}

var SETTING_HEADER = "````yaml:livesync-setting\n", SETTING_FOOTER = "\n````", ObsidianLiveSyncPlugin = class extends import_obsidian.Plugin {
  constructor() {
    super(...arguments);
    this._suspended = false;
    this.deviceAndVaultName = "";
    this.isReady = false;
    this.packageVersion = "";
    this.manifestVersion = "";
    this.addOnHiddenFileSync = new HiddenFileSync(this);
    this.addOnSetup = new SetupLiveSync(this);
    this.addOnConfigSync = new ConfigSync(this);
    this.addOns = [ this.addOnHiddenFileSync, this.addOnSetup, this.addOnConfigSync ];
    this.periodicSyncProcessor = new PeriodicProcessor(this, (async () => await this.replicate()));
    this.last_successful_post = false;
    this.vaultAccess = new SerializedFileAccess(this.app);
    this._unloaded = false;
    this.requestCount = reactiveSource(0);
    this.responseCount = reactiveSource(0);
    this.processReplication = s => this.parseReplicationResult(s);
    this.replicationStat = reactiveSource({
      sent: 0,
      arrived: 0,
      maxPullSeq: 0,
      maxPushSeq: 0,
      lastSyncPullSeq: 0,
      lastSyncPushSeq: 0,
      syncStatus: "CLOSED"
    });
    this.isRedFlagRaised = () => this.isFlagFileExist(FLAGMD_REDFLAG);
    this.isRedFlag2Raised = () => this.isFlagFileExist(FLAGMD_REDFLAG2) || this.isFlagFileExist(FLAGMD_REDFLAG2_HR);
    this.isRedFlag3Raised = () => this.isFlagFileExist(FLAGMD_REDFLAG3) || this.isFlagFileExist(FLAGMD_REDFLAG3_HR);
    this.usedPassphrase = "";
    this.vaultManager = new StorageEventManagerObsidian(this);
    this.hasFocus = true;
    this.isLastHidden = false;
    this.pendingFileEventCount = reactiveSource(0);
    this.processingFileEventCount = reactiveSource(0);
    this.fileEventQueue = new QueueProcessor((s => this.handleFileEvent(s[0])), {
      suspended: true,
      batchSize: 1,
      concurrentLimit: 5,
      delay: 100,
      yieldThreshold: FileWatchEventQueueMax,
      totalRemainingReactiveSource: this.pendingFileEventCount,
      processingEntitiesReactiveSource: this.processingFileEventCount
    }).replaceEnqueueProcessor(((s, r) => this.queueNextFileEvent(s, r)));
    this.notifies = {};
    this.statusLog = reactiveSource("");
    this._saveQueuedFiles = throttle((() => {
      const s = this.replicationResultProcessor._queue.filter((s => null != s)).map((s => {
        var r;
        return null != (r = null == s ? void 0 : s._id) ? r : "";
      }));
      fireAndForget((() => this.kvDB.set("queued-files", s)));
    }), 100);
    this.databaseQueueCount = reactiveSource(0);
    this.databaseQueuedProcessor = new QueueProcessor((async s => {
      var r;
      const o = s[0], u = this.getPath(o), g = await this.localDatabase.getDBEntryFromMeta({
        ...o
      }, {}, false, true, true);
      if (g) if (isInternalMetadata(g._id) && this.settings.syncInternalFiles) {
        const s = this.getPathWithoutPrefix(g);
        this.isTargetFile(s).then((r => r ? this.addOnHiddenFileSync.procInternalFile(s) : Logger(`Skipped (Not target:${s})`, LOG_LEVEL_VERBOSE)));
      } else if (isValidPath(this.getPath(g))) this.storageApplyingProcessor.enqueue(g); else Logger(`Skipped: ${g._id.substring(0, 8)}`, LOG_LEVEL_VERBOSE); else Logger(`Something went wrong while gathering content of ${u} (${o._id.substring(0, 8)}, ${null == (r = o._rev) ? void 0 : r.substring(0, 10)}) `, LOG_LEVEL_NOTICE);
    }), {
      suspended: true,
      batchSize: 1,
      concurrentLimit: 10,
      yieldThreshold: 1,
      delay: 0,
      totalRemainingReactiveSource: this.databaseQueueCount
    }).replaceEnqueueProcessor(((s, r) => [ ...s.filter((s => s._id != r._id)), r ])).startPipeline();
    this.storageApplyingCount = reactiveSource(0);
    this.storageApplyingProcessor = new QueueProcessor((async s => {
      const r = s[0];
      await serialized(r.path, (async () => {
        var s, o;
        const u = this.getPath(r);
        Logger(`Processing ${u} (${r._id.substring(0, 8)}: ${null == (s = r._rev) ? void 0 : s.substring(0, 5)}) :Started...`, LOG_LEVEL_VERBOSE);
        const g = this.vaultAccess.getAbstractFileByPath(this.getPathWithoutPrefix(r));
        if (g instanceof import_obsidian.TFolder) Logger(`${this.getPath(r)} is already exist as the folder`); else {
          await this.processEntryDoc(r, g instanceof import_obsidian.TFile ? g : void 0);
          Logger(`Processing ${u} (${r._id.substring(0, 8)} :${null == (o = r._rev) ? void 0 : o.substring(0, 5)}) : Done`);
        }
      }));
    }), {
      suspended: true,
      batchSize: 1,
      concurrentLimit: 6,
      yieldThreshold: 1,
      delay: 0,
      totalRemainingReactiveSource: this.storageApplyingCount
    }).replaceEnqueueProcessor(((s, r) => [ ...s.filter((s => s._id != r._id)), r ])).startPipeline();
    this.replicationResultCount = reactiveSource(0);
    this.replicationResultProcessor = new QueueProcessor((async s => {
      if (this.settings.suspendParseReplicationResult) return;
      const r = s[0];
      if (r) if (!isChunk(r._id)) {
        for (const s of this.addOns) if (await s.parseReplicationResultItem(r)) return;
        if ("versioninfo" != r.type) {
          if (r._id != SYNCINFO_ID && !r._id.startsWith("_design")) if (isAnyNote(r)) {
            if (this.databaseQueuedProcessor._isSuspended) Logger(`Processing scheduled: ${r.path}`, LOG_LEVEL_INFO);
            const s = r.size;
            if (this.isFileSizeExceeded(s)) {
              Logger(`Processing ${r.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
              return;
            }
            this.databaseQueuedProcessor.enqueue(r);
          }
        } else if (r.version > VER) {
          this.replicator.closeReplication();
          Logger("Remote database updated to incompatible version. update your Self-hosted LiveSync plugin.", LOG_LEVEL_NOTICE);
        }
      } else sendValue(`leaf-${r._id}`, r);
    }), {
      batchSize: 1,
      suspended: true,
      concurrentLimit: 100,
      delay: 0,
      totalRemainingReactiveSource: this.replicationResultCount
    }).replaceEnqueueProcessor(((s, r) => [ ...s.filter((s => s._id != r._id)), r ])).startPipeline().onUpdateProgress((() => {
      this.saveQueuedFiles();
    }));
    this.lastMessage = "";
    this.conflictProcessQueueCount = reactiveSource(0);
    this.conflictResolveQueue = new QueueProcessor((async s => {
      const r = s[0];
      await serialized(`conflict-resolve:${r}`, (async () => {
        const s = await this.checkConflictAndPerformAutoMerge(r);
        if (s !== MISSING_OR_ERROR && s !== NOT_CONFLICTED && s !== CANCELLED) if (s !== AUTO_MERGED) {
          if (this.settings.showMergeDialogOnlyOnActive) {
            const s = this.getActiveFile();
            if (s && s.path != r) {
              Logger(`${r} is conflicted. Merging process has been postponed to the file have got opened.`, LOG_LEVEL_NOTICE);
              return;
            }
          }
          Logger("conflict:Manual merge required!");
          await this.resolveConflictByUI(r, s);
        } else {
          if (this.settings.syncAfterMerge && !this.suspended) await shareRunningResult("replication", (() => this.replicate()));
          Logger("conflict:Automatically merged, but we have to check it again");
          this.conflictCheckQueue.enqueue(r);
        }
      }));
    }), {
      suspended: false,
      batchSize: 1,
      concurrentLimit: 1,
      delay: 10,
      keepResultUntilDownstreamConnected: false
    }).replaceEnqueueProcessor(((s, r) => {
      sendValue("cancel-resolve-conflict:" + r, true);
      return [ ...[ ...s ].filter((s => s != r)), r ];
    }));
    this.conflictCheckQueue = new QueueProcessor((s => {
      const r = s[0];
      if (this.vaultAccess.getAbstractFileByPath(r) instanceof import_obsidian.TFolder) return []; else return [ r ];
    }), {
      suspended: false,
      batchSize: 1,
      concurrentLimit: 5,
      delay: 10,
      keepResultUntilDownstreamConnected: true,
      pipeTo: this.conflictResolveQueue,
      totalRemainingReactiveSource: this.conflictProcessQueueCount
    });
    this.ignoreFileCache = new LRUCache(300, 25e4, true);
    this.ignoreFiles = [];
  }
  get suspended() {
    var s;
    return this._suspended || !(null == (s = this.settings) ? void 0 : s.isConfigured);
  }
  set suspended(s) {
    this._suspended = s;
  }
  getLastPostFailedBySize() {
    return !this.last_successful_post;
  }
  getDatabase() {
    return this.localDatabase.localDatabase;
  }
  getSettings() {
    return this.settings;
  }
  getIsMobile() {
    return this.isMobile;
  }
  async connectRemoteCouchDB(s, r, o, u, g, _, m) {
    if (!isValidRemoteCouchDBURI(s)) return "Remote URI is not valid";
    if (s.toLowerCase() != s) return "Remote URI and database name could not contain capital letters.";
    if (-1 !== s.indexOf(" ")) return "Remote URI and database name could not contain spaces.";
    let b = "";
    if (r.username && r.password) {
      const s = String.fromCharCode.apply(null, [ ...writeString(`${r.username}:${r.password}`) ]), o = window.btoa(s);
      b = "Basic " + o;
    } else b = "";
    const E = new index_es_default(s, {
      adapter: "http",
      auth: r,
      skip_setup: !_,
      fetch: async (r, u) => {
        var g, _;
        let m = "";
        const E = r.toString().substring(s.length), w = null != (g = null == u ? void 0 : u.method) ? g : "GET";
        if (null == u ? void 0 : u.body) {
          const r = u.body.toString().length;
          if (r > 1e7) if (isCloudantURI(s)) {
            this.last_successful_post = false;
            Logger("This request should fail on IBM Cloudant.", LOG_LEVEL_VERBOSE);
            throw new Error("This request should fail on IBM Cloudant.");
          }
          m = ` (${r})`;
        }
        if (!o && "string" == typeof r && "string" == typeof (null != (_ = null == u ? void 0 : u.body) ? _ : "")) {
          const s = null == u ? void 0 : u.body, o = {
            ...null == u ? void 0 : u.headers
          };
          if ("" != b) o["authorization"] = b;
          delete o["host"];
          delete o["Host"];
          delete o["content-length"];
          delete o["Content-Length"];
          const g = {
            url: r,
            method: null == u ? void 0 : u.method,
            body: s,
            headers: o,
            contentType: "application/json"
          };
          try {
            this.requestCount.value = this.requestCount.value + 1;
            const s = await fetchByAPI(g);
            if ("POST" == w || "PUT" == w) this.last_successful_post = s.status - s.status % 100 == 200; else this.last_successful_post = true;
            Logger(`HTTP:${w}${m} to:${E} -> ${s.status}`, LOG_LEVEL_DEBUG);
            return new Response(s.arrayBuffer, {
              headers: s.headers,
              status: s.status,
              statusText: `${s.status}`
            });
          } catch (s) {
            Logger(`HTTP:${w}${m} to:${E} -> failed`, LOG_LEVEL_VERBOSE);
            if (-1 !== r.toString().indexOf("_bulk_docs")) this.last_successful_post = false;
            Logger(s);
            throw s;
          } finally {
            this.responseCount.value = this.responseCount.value + 1;
          }
        }
        try {
          this.requestCount.value = this.requestCount.value + 1;
          const s = await fetch(r, u);
          if ("POST" == w || "PUT" == w) this.last_successful_post = s.ok; else this.last_successful_post = true;
          Logger(`HTTP:${w}${m} to:${E} -> ${s.status}`, LOG_LEVEL_DEBUG);
          if (2 !== Math.floor(s.status / 100)) {
            const r = s.clone();
            Logger(`The request may have failed. The reason sent by the server: ${r.status}: ${r.statusText}`);
            try {
              Logger(await (await r.blob()).text(), LOG_LEVEL_VERBOSE);
            } catch (s) {
              Logger("Cloud not parse response", LOG_LEVEL_VERBOSE);
            }
          }
          return s;
        } catch (s) {
          Logger(`HTTP:${w}${m} to:${E} -> failed`, LOG_LEVEL_VERBOSE);
          if (-1 !== r.toString().indexOf("_bulk_docs")) this.last_successful_post = false;
          Logger(s);
          throw s;
        } finally {
          this.responseCount.value = this.responseCount.value + 1;
        }
      }
    });
    if ("false" !== u && "string" == typeof u) enableEncryption(E, u, g, false);
    if (m) return {
      db: E,
      info: {
        db_name: "",
        doc_count: 0,
        update_seq: ""
      }
    };
    try {
      const s = await E.info();
      return {
        db: E,
        info: s
      };
    } catch (s) {
      let r = `${null == s ? void 0 : s.name}:${null == s ? void 0 : s.message}`;
      if ("TypeError" == (null == s ? void 0 : s.name) && "Failed to fetch" == (null == s ? void 0 : s.message)) r += "\n**Note** This error caused by many reasons. The only sure thing is you didn't touch the server.\nTo check details, open inspector.";
      Logger(s, LOG_LEVEL_VERBOSE);
      return r;
    }
  }
  get isMobile() {
    return this.app.isMobile;
  }
  get vaultName() {
    return this.app.vault.getName();
  }
  getActiveFile() {
    return this.app.workspace.getActiveFile();
  }
  get appId() {
    return `${"appId" in this.app ? this.app.appId : ""}`;
  }
  id2path(s, r, o) {
    const u = id2path(s, r);
    if (o && isInternalMetadata(u)) return stripInternalMetadataPrefix(u); else return u;
  }
  getPath(s) {
    return getPath2(s);
  }
  getPathWithoutPrefix(s) {
    return getPathWithoutPrefix(s);
  }
  async path2id(s, r) {
    const o = addPrefix(s, null != r ? r : "");
    return await path2id(o, this.settings.usePathObfuscation ? this.settings.passphrase : "");
  }
  createPouchDBInstance(s, r) {
    const o = null != r ? r : {};
    if (this.settings.useIndexedDBAdapter) {
      o.adapter = "indexeddb";
      o.purged_infos_limit = 1;
      return new index_es_default(s + "-indexeddb", o);
    }
    return new index_es_default(s, o);
  }
  beforeOnUnload(s) {
    this.kvDB.close();
  }
  onClose(s) {
    this.kvDB.close();
  }
  async onInitializeDatabase(s) {
    this.kvDB = await OpenKeyValueDatabase(s.dbname + "-livesync-kv");
    this.replicator = new LiveSyncDBReplicator(this);
  }
  async onResetDatabase(s) {
    this.kvDB.del("queued-files");
    await this.kvDB.destroy();
    this.kvDB = await OpenKeyValueDatabase(s.dbname + "-livesync-kv");
    this.replicator = new LiveSyncDBReplicator(this);
  }
  getReplicator() {
    return this.replicator;
  }
  getVaultName() {
    var s;
    return this.vaultName + ((null == (s = this.settings) ? void 0 : s.additionalSuffixOfDatabaseName) ? "-" + this.settings.additionalSuffixOfDatabaseName : "");
  }
  isFlagFileExist(s) {
    const r = this.vaultAccess.getAbstractFileByPath(normalizePath(s));
    if (null != r && r instanceof import_obsidian.TFile) return true; else return false;
  }
  async deleteFlagFile(s) {
    try {
      const r = this.vaultAccess.getAbstractFileByPath(normalizePath(s));
      if (null != r && r instanceof import_obsidian.TFile) await this.vaultAccess.delete(r, true);
    } catch (r) {
      Logger(`Could not delete ${s}`);
      Logger(r, LOG_LEVEL_VERBOSE);
    }
  }
  async deleteRedFlag2() {
    await this.deleteFlagFile(FLAGMD_REDFLAG2);
    await this.deleteFlagFile(FLAGMD_REDFLAG2_HR);
  }
  async deleteRedFlag3() {
    await this.deleteFlagFile(FLAGMD_REDFLAG3);
    await this.deleteFlagFile(FLAGMD_REDFLAG3_HR);
  }
  showHistory(s, r) {
    new DocumentHistoryModal(this.app, this, s, r).open();
  }
  async fileHistory() {
    const s = [];
    for await (const r of this.localDatabase.findAllDocs()) s.push({
      id: r._id,
      path: this.getPath(r),
      dispPath: this.getPathWithoutPrefix(r),
      mtime: r.mtime
    });
    s.sort(((s, r) => r.mtime - s.mtime));
    const r = s.map((s => s.dispPath)), o = await this.askSelectString("File to view History", r);
    if (o) {
      const r = s.find((s => s.dispPath == o));
      this.showHistory(r.path, r.id);
    }
  }
  async pickFileForResolve() {
    const s = [];
    for await (const r of this.localDatabase.findAllDocs({
      conflicts: true
    })) if ("_conflicts" in r) s.push({
      id: r._id,
      path: this.getPath(r),
      dispPath: this.getPathWithoutPrefix(r),
      mtime: r.mtime
    });
    s.sort(((s, r) => r.mtime - s.mtime));
    const r = s.map((s => s.dispPath));
    if (0 == r.length) {
      Logger("There are no conflicted documents", LOG_LEVEL_NOTICE);
      return false;
    }
    const o = await this.askSelectString("File to resolve conflict", r);
    if (o) {
      const r = s.find((s => s.dispPath == o));
      this.resolveConflicted(r.path);
      await this.conflictCheckQueue.waitForPipeline();
      return true;
    }
    return false;
  }
  async resolveConflicted(s) {
    if (isInternalMetadata(s)) this.addOnHiddenFileSync.queueConflictCheck(s); else if (isPluginMetadata(s)) await this.resolveConflictByNewerEntry(s); else if (isCustomisationSyncMetadata(s)) await this.resolveConflictByNewerEntry(s); else this.queueConflictCheck(s);
  }
  async collectDeletedFiles() {
    const s = this.settings.automaticallyDeleteMetadataOfDeletedFiles;
    if (s <= 0) return;
    Logger("Checking expired file history");
    const r = Date.now() - 864e5 * s, o = [];
    for await (const s of this.localDatabase.findAllDocs({
      conflicts: true
    })) if (isAnyNote(s)) if (s.deleted && s.mtime - r < 0) o.push({
      path: this.getPath(s),
      mtime: s.mtime,
      ttl: (s.mtime - r) / 1e3 / 86400,
      doc: s
    });
    if (0 != o.length) {
      for (const s of o) {
        Logger(`Deletion history expired: ${s.path}`);
        const r = s.doc;
        r._deleted = true;
        await this.localDatabase.putRaw(r);
      }
      Logger("Checking expired file history done");
    } else {
      Logger("There are no old documents");
      Logger("Checking expired file history done");
    }
  }
  async onLayoutReady() {
    this.registerFileWatchEvents();
    if (this.localDatabase.isReady) if (this.settings.isConfigured) try {
      if (this.isRedFlagRaised() || this.isRedFlag2Raised() || this.isRedFlag3Raised()) {
        this.settings.batchSave = false;
        this.addOnSetup.suspendAllSync();
        this.addOnSetup.suspendExtraSync();
        this.settings.suspendFileWatching = true;
        await this.saveSettings();
        if (this.isRedFlag2Raised()) {
          Logger(`${FLAGMD_REDFLAG2} or ${FLAGMD_REDFLAG2_HR} has been detected! Self-hosted LiveSync suspends all sync and rebuild everything.`, LOG_LEVEL_NOTICE);
          await this.addOnSetup.rebuildEverything();
          await this.deleteRedFlag2();
          if ("yes" == await this.askYesNo("Do you want to disable Suspend file watching and restart obsidian now?")) {
            this.settings.suspendFileWatching = false;
            await this.saveSettings();
            this.performAppReload();
          }
        } else if (this.isRedFlag3Raised()) {
          Logger(`${FLAGMD_REDFLAG3} or ${FLAGMD_REDFLAG3_HR} has been detected! Self-hosted LiveSync will discard the local database and fetch everything from the remote once again.`, LOG_LEVEL_NOTICE);
          await this.addOnSetup.fetchLocal();
          await this.deleteRedFlag3();
          if (this.settings.suspendFileWatching) if ("yes" == await this.askYesNo("Do you want to disable Suspend file watching and restart obsidian now?")) {
            this.settings.suspendFileWatching = false;
            await this.saveSettings();
            this.performAppReload();
          }
        } else {
          this.settings.writeLogToTheFile = true;
          await this.openDatabase();
          Logger("The red flag is raised! The whole initialize steps are skipped, and any file changes are not captured.", LOG_LEVEL_NOTICE);
        }
      } else {
        if (this.settings.suspendFileWatching) Logger("'Suspend file watching' turned on. Are you sure this is what you intended? Every modification on the vault will be ignored.", LOG_LEVEL_NOTICE);
        if (this.settings.suspendParseReplicationResult) Logger("'Suspend database reflecting' turned on. Are you sure this is what you intended? Every replicated change will be postponed until disabling this option.", LOG_LEVEL_NOTICE);
        if (!await this.initializeDatabase(false, false)) return false;
      }
      this.registerWatchEvents();
      await this.realizeSettingSyncMode();
      this.swapSaveCommand();
      if (!this.settings.liveSync && this.settings.syncOnStart) this.replicator.openReplication(this.settings, false, false);
      this.scanStat();
    } catch (s) {
      Logger("Error while loading Self-hosted LiveSync", LOG_LEVEL_NOTICE);
      Logger(s, LOG_LEVEL_VERBOSE);
    } else {
      const s = "Hello and welcome to Self-hosted LiveSync.\n\nYour device seems to **not be configured yet**. Please finish the setup and synchronise your vaults!\n\nClick anywhere to stop counting down.\n\n## At the first device\n- With Setup URI -> Use `Use the copied setup URI`.  \n  If you have configured it automatically, you should have one.\n- Without Setup URI -> Use `Setup wizard` in setting dialogue. **`Minimal setup` is recommended**.\n- What is the Setup URI? -> Do not worry! We have [some docs](https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use) now. Please refer to them once.\n\n## At the subsequent device\n- With Setup URI -> Use `Use the copied setup URI`.  \n  If you do not have it yet, you can copy it on the first device.\n- Without Setup URI -> Use `Setup wizard` in setting dialogue, but **strongly recommends using setup URI**.\n", r = "Open setting dialog", o = "Use the copied setup URI", u = "Dismiss", g = await confirmWithMessage(this, "Welcome to Self-hosted LiveSync", s, [ o, r, u ], u, 40);
      if (g === r) try {
        this.openSetting();
      } catch (s) {
        Logger("Something went wrong on opening setting dialog, please open it manually", LOG_LEVEL_NOTICE);
      } else if (g == o) fireAndForget(this.addOnSetup.command_openSetupURI());
    } else Logger("Something went wrong! The local database is not ready", LOG_LEVEL_NOTICE);
  }
  async scanStat() {
    const s = [];
    Logger("Additional safety scan..", LOG_LEVEL_VERBOSE);
    for await (const r of this.localDatabase.findAllDocs({
      conflicts: true
    })) if ("_conflicts" in r) s.push({
      path: this.getPath(r),
      mtime: r.mtime
    });
    if (s.length > 0) {
      this.askInPopup("conflicting-detected-on-safety", 'Some files have been left conflicted! Press {HERE} to resolve them, or you can do it later by "Pick a file to resolve conflict', (s => {
        s.text = "HERE";
        s.addEventListener("click", (() => {
          this.performCommand("obsidian-livesync:livesync-all-conflictcheck");
        }));
      }));
      Logger('Some files have been left conflicted! Please resolve them by "Pick a file to resolve conflict". The list is written in the log.', LOG_LEVEL_VERBOSE);
      for (const r of s) Logger(`Conflicted: ${r.path}`);
    } else Logger("There are no conflicted files", LOG_LEVEL_VERBOSE);
    Logger("Additional safety scan done", LOG_LEVEL_VERBOSE);
  }
  async askEnableV2() {
    const s = "Keep v1";
    return await confirmWithMessage(this, "binary and encryption", "Since v0.20.0, Self-hosted LiveSync uses a new format for binary files and encrypted things. In the new format, files are split at meaningful delimitations, increasing the effectiveness of deduplication.\nHowever, the new format lacks compatibility with LiveSync before v0.20.0 and related projects. Basically enabling V2 is recommended. but If you are using some related products, stay in a while, please!\nNote: We can always able to read V1 format. It will be progressively converted. And, we can change this toggle later.", [ "Enable v2", s ], s, 40) == s;
  }
  addUIs() {
    (0, import_obsidian.addIcon)("replicate", '<g transform="matrix(1.15 0 0 1.15 -8.31 -9.52)" fill="currentColor" fill-rule="evenodd">\n            <path d="m85 22.2c-0.799-4.74-4.99-8.37-9.88-8.37-0.499 0-1.1 0.101-1.6 0.101-2.4-3.03-6.09-4.94-10.3-4.94-6.09 0-11.2 4.14-12.8 9.79-5.59 1.11-9.78 6.05-9.78 12 0 6.76 5.39 12.2 12 12.2h29.9c5.79 0 10.1-4.74 10.1-10.6 0-4.84-3.29-8.88-7.68-10.2zm-2.99 14.7h-29.5c-2.3-0.202-4.29-1.51-5.29-3.53-0.899-2.12-0.699-4.54 0.698-6.46 1.2-1.61 2.99-2.52 4.89-2.52 0.299 0 0.698 0 0.998 0.101l1.8 0.303v-2.02c0-3.63 2.4-6.76 5.89-7.57 0.599-0.101 1.2-0.202 1.8-0.202 2.89 0 5.49 1.62 6.79 4.24l0.598 1.21 1.3-0.504c0.599-0.202 1.3-0.303 2-0.303 1.3 0 2.5 0.404 3.59 1.11 1.6 1.21 2.6 3.13 2.6 5.15v1.61h2c2.6 0 4.69 2.12 4.69 4.74-0.099 2.52-2.2 4.64-4.79 4.64z"/>\n            <path d="m53.2 49.2h-41.6c-1.8 0-3.2 1.4-3.2 3.2v28.6c0 1.8 1.4 3.2 3.2 3.2h15.8v4h-7v6h24v-6h-7v-4h15.8c1.8 0 3.2-1.4 3.2-3.2v-28.6c0-1.8-1.4-3.2-3.2-3.2zm-2.8 29h-36v-23h36z"/>\n            <path d="m73 49.2c1.02 1.29 1.53 2.97 1.53 4.56 0 2.97-1.74 5.65-4.39 7.04v-4.06l-7.46 7.33 7.46 7.14v-4.06c7.66-1.98 12.2-9.61 10-17-0.102-0.297-0.205-0.595-0.307-0.892z"/>\n            <path d="m24.1 43c-0.817-0.991-1.53-2.97-1.53-4.56 0-2.97 1.74-5.65 4.39-7.04v4.06l7.46-7.33-7.46-7.14v4.06c-7.66 1.98-12.2 9.61-10 17 0.102 0.297 0.205 0.595 0.307 0.892z"/>\n           </g>');
    (0, import_obsidian.addIcon)("view-log", '<g transform="matrix(1.28 0 0 1.28 -131 -411)" fill="currentColor" fill-rule="evenodd">\n        <path d="m103 330h76v12h-76z"/>\n        <path d="m106 346v44h70v-44zm45 16h-20v-8h20z"/>\n       </g>');
    (0, import_obsidian.addIcon)("custom-sync", '<g transform="rotate(-90 75 218)"  fill="currentColor" fill-rule="evenodd">\n            <path d="m272 166-9.38 9.38 9.38 9.38 9.38-9.38c1.96-1.93 5.11-1.9 7.03 0.058 1.91 1.94 1.91 5.04 0 6.98l-9.38 9.38 5.86 5.86-11.7 11.7c-8.34 8.35-21.4 9.68-31.3 3.19l-3.84 3.98c-8.45 8.7-20.1 13.6-32.2 13.6h-5.55v-9.95h5.55c9.43-0.0182 18.5-3.84 25-10.6l3.95-4.09c-6.54-9.86-5.23-23 3.14-31.3l11.7-11.7 5.86 5.86 9.38-9.38c1.96-1.93 5.11-1.9 7.03 0.0564 1.91 1.93 1.91 5.04 2e-3 6.98z"/>\n        </g>');
    this.addRibbonIcon("replicate", "Replicate", (async () => {
      await this.replicate(true);
    })).addClass("livesync-ribbon-replicate");
    this.addRibbonIcon("view-log", "Show log", (() => {
      this.showView(VIEW_TYPE_LOG);
    })).addClass("livesync-ribbon-showlog");
    this.addRibbonIcon("custom-sync", "Show Customization sync", (() => {
      this.addOnConfigSync.showPluginSyncModal();
    })).addClass("livesync-ribbon-showcustom");
    this.addCommand({
      id: "view-log",
      name: "Show log",
      callback: () => {
        this.showView(VIEW_TYPE_LOG);
      }
    });
    this.addCommand({
      id: "livesync-replicate",
      name: "Replicate now",
      callback: async () => {
        await this.replicate();
      }
    });
    this.addCommand({
      id: "livesync-dump",
      name: "Dump information of this doc ",
      callback: () => {
        const s = this.getActiveFile();
        if (s) this.localDatabase.getDBEntry(getPathFromTFile(s), {}, true, false);
      }
    });
    this.addCommand({
      id: "livesync-checkdoc-conflicted",
      name: "Resolve if conflicted.",
      editorCallback: (s, r) => {
        const o = r.file;
        if (o) this.queueConflictCheck(o);
      }
    });
    this.addCommand({
      id: "livesync-toggle",
      name: "Toggle LiveSync",
      callback: async () => {
        if (this.settings.liveSync) {
          this.settings.liveSync = false;
          Logger("LiveSync Disabled.", LOG_LEVEL_NOTICE);
        } else {
          this.settings.liveSync = true;
          Logger("LiveSync Enabled.", LOG_LEVEL_NOTICE);
        }
        await this.realizeSettingSyncMode();
        this.saveSettings();
      }
    });
    this.addCommand({
      id: "livesync-suspendall",
      name: "Toggle All Sync.",
      callback: async () => {
        if (this.suspended) {
          this.suspended = false;
          Logger("Self-hosted LiveSync resumed", LOG_LEVEL_NOTICE);
        } else {
          this.suspended = true;
          Logger("Self-hosted LiveSync suspended", LOG_LEVEL_NOTICE);
        }
        await this.realizeSettingSyncMode();
        this.saveSettings();
      }
    });
    this.addCommand({
      id: "livesync-history",
      name: "Show history",
      callback: () => {
        const s = this.getActiveFile();
        if (s) this.showHistory(s, void 0);
      }
    });
    this.addCommand({
      id: "livesync-scan-files",
      name: "Scan storage and database again",
      callback: async () => {
        await this.syncAllFiles(true);
      }
    });
    this.addCommand({
      id: "livesync-filehistory",
      name: "Pick a file to show history",
      callback: () => {
        this.fileHistory();
      }
    });
    this.addCommand({
      id: "livesync-conflictcheck",
      name: "Pick a file to resolve conflict",
      callback: () => {
        this.pickFileForResolve();
      }
    });
    this.addCommand({
      id: "livesync-all-conflictcheck",
      name: "Resolve all conflicted files",
      callback: async () => {
        for (;await this.pickFileForResolve(); ) ;
      }
    });
    this.addCommand({
      id: "livesync-runbatch",
      name: "Run pended batch processes",
      callback: async () => {
        await this.applyBatchChange();
      }
    });
    this.addCommand({
      id: "livesync-abortsync",
      name: "Abort synchronization immediately",
      callback: () => {
        this.replicator.terminateSync();
      }
    });
    this.addCommand({
      id: "livesync-global-history",
      name: "Show vault history",
      callback: () => {
        this.showGlobalHistory();
      }
    });
    this.addCommand({
      id: "livesync-export-config",
      name: "Write setting markdown manually",
      checkCallback: s => {
        if (s) return "" != this.settings.settingSyncFile;
        this.saveSettingData();
      }
    });
    this.addCommand({
      id: "livesync-import-config",
      name: "Parse setting file",
      editorCheckCallback: (s, r, o) => {
        if (s) {
          const s = r.getValue();
          return "" != this.extractSettingFromWholeText(s).body;
        }
        if (o.file) this.checkAndApplySettingFromMarkdown(o.file.path, false);
      }
    });
    this.registerView(VIEW_TYPE_GLOBAL_HISTORY, (s => new GlobalHistoryView(s, this)));
    this.registerView(VIEW_TYPE_LOG, (s => new LogPaneView(s, this)));
  }
  async onload() {
    logStore.pipeTo(new QueueProcessor((s => s.forEach((s => this.addLog(s.message, s.level, s.key)))), {
      suspended: false,
      batchSize: 20,
      concurrentLimit: 1,
      delay: 0
    })).startPipeline();
    Logger("loading plugin");
    this.addSettingTab(new ObsidianLiveSyncSettingTab(this.app, this));
    this.addUIs();
    const s = "0.22.17", r = "0.22.17";
    this.manifestVersion = s;
    this.packageVersion = r;
    Logger(`Self-hosted LiveSync v${s} ${r} `);
    await this.loadSettings();
    const o = "obsidian-live-sync-ver" + this.getVaultName(), u = localStorage.getItem(o);
    this.observeForLogs();
    if (this.settings.showStatusOnStatusbar) {
      this.statusBar = this.addStatusBarItem();
      this.statusBar.addClass("syncstatusbar");
    }
    if (~~(versionNumberString2Number(s) / 1e3) > this.settings.lastReadUpdates && this.settings.isConfigured) Logger("Self-hosted LiveSync has undergone a major upgrade. Please open the setting dialog, and check the information pane.", LOG_LEVEL_NOTICE);
    if (this.isMobile) this.settings.disableRequestURI = true;
    if (u && Number(u) < VER) {
      this.settings.liveSync = false;
      this.settings.syncOnSave = false;
      this.settings.syncOnEditorSave = false;
      this.settings.syncOnStart = false;
      this.settings.syncOnFileOpen = false;
      this.settings.syncAfterMerge = false;
      this.settings.periodicReplication = false;
      this.settings.versionUpFlash = "Self-hosted LiveSync has been upgraded and some behaviors have changed incompatibly. All automatic synchronization is now disabled temporary. Ensure that other devices are also upgraded, and enable synchronization again.";
      this.saveSettings();
    }
    localStorage.setItem(o, `${VER}`);
    await this.openDatabase();
    this.watchWorkspaceOpen = this.watchWorkspaceOpen.bind(this);
    this.watchWindowVisibility = this.watchWindowVisibility.bind(this);
    this.watchOnline = this.watchOnline.bind(this);
    this.realizeSettingSyncMode = this.realizeSettingSyncMode.bind(this);
    this.parseReplicationResult = this.parseReplicationResult.bind(this);
    this.loadQueuedFiles = this.loadQueuedFiles.bind(this);
    await Promise.all(this.addOns.map((s => s.onload())));
    this.app.workspace.onLayoutReady(this.onLayoutReady.bind(this));
  }
  async showView(s) {
    const r = this.app.workspace.getLeavesOfType(s);
    if (0 == r.length) await this.app.workspace.getLeaf(true).setViewState({
      type: s,
      active: true
    }); else r[0].setViewState({
      type: s,
      active: true
    });
    if (r.length > 0) this.app.workspace.revealLeaf(r[0]);
  }
  showGlobalHistory() {
    this.showView(VIEW_TYPE_GLOBAL_HISTORY);
  }
  onunload() {
    var s;
    cancelAllPeriodicTask();
    cancelAllTasks();
    this._unloaded = true;
    for (const s of this.addOns) s.onunload();
    if (null != this.localDatabase) this.localDatabase.onunload();
    null == (s = this.periodicSyncProcessor) || s.disable();
    if (null != this.localDatabase) {
      this.replicator.closeReplication();
      this.localDatabase.close();
    }
    Logger("unloading plugin");
  }
  async openDatabase() {
    if (null != this.localDatabase) await this.localDatabase.close();
    const s = this.getVaultName();
    Logger("Waiting for ready...");
    this.localDatabase = new LiveSyncLocalDB(s, this);
    initializeStores(s);
    return await this.localDatabase.initializeDatabase();
  }
  getPassphrase(s) {
    const r = {
      "": () => Promise.resolve("*"),
      LOCALSTORAGE: () => {
        var s;
        return Promise.resolve(null != (s = localStorage.getItem("ls-setting-passphrase")) ? s : false);
      },
      ASK_AT_LAUNCH: () => askString(this.app, "Passphrase", "passphrase", "")
    }, o = s.configPassphraseStore;
    return (o in r ? r[o] : r[""])();
  }
  async decryptConfigurationItem(s, r) {
    const o = await tryDecrypt(s, r + SALT_OF_PASSPHRASE, false);
    if (o) {
      this.usedPassphrase = r;
      return o;
    }
    return false;
  }
  tryDecodeJson(s) {
    try {
      if (!s) return false; else return JSON.parse(s);
    } catch (s) {
      return false;
    }
  }
  async encryptConfigurationItem(s, r) {
    if ("" != this.usedPassphrase) return await encrypt(s, this.usedPassphrase + SALT_OF_PASSPHRASE, false);
    const o = await this.getPassphrase(r);
    if (false === o) {
      Logger("Could not determine passphrase to save data.json! You probably make the configuration sure again!", LOG_LEVEL_URGENT);
      return "";
    }
    const u = await encrypt(s, o + SALT_OF_PASSPHRASE, false);
    if (u) {
      this.usedPassphrase = o;
      return u;
    }
    return "";
  }
  async loadSettings() {
    const s = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
    if ("undefined" == typeof s.isConfigured) if (JSON.stringify(s) !== JSON.stringify(DEFAULT_SETTINGS)) s.isConfigured = true; else {
      s.additionalSuffixOfDatabaseName = this.appId;
      s.isConfigured = false;
    }
    const r = await this.getPassphrase(s);
    if (false === r) Logger("Could not determine passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL_URGENT); else {
      if (s.encryptedCouchDBConnection) {
        const o = [ "couchDB_URI", "couchDB_USER", "couchDB_PASSWORD", "couchDB_DBNAME" ], u = this.tryDecodeJson(await this.decryptConfigurationItem(s.encryptedCouchDBConnection, r));
        if (u) {
          for (const r of o) if (r in u) s[r] = u[r];
        } else {
          Logger("Could not decrypt passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL_URGENT);
          for (const r of o) s[r] = "";
        }
      }
      if (s.encrypt && s.encryptedPassphrase) {
        const o = s.encryptedPassphrase, u = await this.decryptConfigurationItem(o, r);
        if (u) s.passphrase = u; else {
          Logger("Could not decrypt passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL_URGENT);
          s.passphrase = "";
        }
      }
    }
    this.settings = s;
    if ("workingEncrypt" in this.settings) delete this.settings.workingEncrypt;
    if ("workingPassphrase" in this.settings) delete this.settings.workingPassphrase;
    this.settings.disableRequestURI = true;
    this.settings.gcDelay = 0;
    this.settings.useHistory = true;
    const o = "obsidian-live-sync-vaultanddevicename-" + this.getVaultName();
    if ("" != this.settings.deviceAndVaultName) if (!localStorage.getItem(o)) {
      this.deviceAndVaultName = this.settings.deviceAndVaultName;
      localStorage.setItem(o, this.deviceAndVaultName);
      this.settings.deviceAndVaultName = "";
    }
    if (isCloudantURI(this.settings.couchDB_URI) && 0 != this.settings.customChunkSize) {
      Logger("Configuration verification founds problems with your configuration. This has been fixed automatically. But you may already have data that cannot be synchronised. If this is the case, please rebuild everything.", LOG_LEVEL_NOTICE);
      this.settings.customChunkSize = 0;
    }
    this.deviceAndVaultName = localStorage.getItem(o) || "";
    this.ignoreFiles = this.settings.ignoreFiles.split(",").map((s => s.trim()));
    this.fileEventQueue.delay = !this.settings.liveSync && this.settings.batchSave ? 5e3 : 100;
  }
  async saveSettingData() {
    const s = "obsidian-live-sync-vaultanddevicename-" + this.getVaultName();
    localStorage.setItem(s, this.deviceAndVaultName || "");
    const r = {
      ...this.settings
    };
    if ("" == this.usedPassphrase && !await this.getPassphrase(r)) Logger("Could not determine passphrase for saving data.json! Our data.json have insecure items!", LOG_LEVEL_NOTICE); else {
      if ("" != r.couchDB_PASSWORD || "" != r.couchDB_URI || "" != r.couchDB_USER || r.couchDB_DBNAME) {
        const s = {
          couchDB_DBNAME: r.couchDB_DBNAME,
          couchDB_PASSWORD: r.couchDB_PASSWORD,
          couchDB_URI: r.couchDB_URI,
          couchDB_USER: r.couchDB_USER
        };
        r.encryptedCouchDBConnection = await this.encryptConfigurationItem(JSON.stringify(s), r);
        r.couchDB_PASSWORD = "";
        r.couchDB_DBNAME = "";
        r.couchDB_URI = "";
        r.couchDB_USER = "";
      }
      if (r.encrypt && "" != r.passphrase) {
        r.encryptedPassphrase = await this.encryptConfigurationItem(r.passphrase, r);
        r.passphrase = "";
      }
    }
    await this.saveData(r);
    this.localDatabase.settings = this.settings;
    this.fileEventQueue.delay = !this.settings.liveSync && this.settings.batchSave ? 5e3 : 100;
    this.ignoreFiles = this.settings.ignoreFiles.split(",").map((s => s.trim()));
    if ("" != this.settings.settingSyncFile) fireAndForget((() => this.saveSettingToMarkdown(this.settings.settingSyncFile)));
  }
  extractSettingFromWholeText(s) {
    if (-1 === s.indexOf(SETTING_HEADER)) return {
      preamble: s,
      body: "",
      postscript: ""
    };
    const r = s.indexOf(SETTING_HEADER), o = -1 == r ? s.length : r, u = -1 == r ? s.length : s.indexOf(SETTING_FOOTER, o), g = -1 == u ? s.length : u, _ = s.substring(o + SETTING_HEADER.length, g);
    return {
      preamble: s.substring(0, o),
      body: _,
      postscript: s.substring(g + SETTING_FOOTER.length + 1)
    };
  }
  async parseSettingFromMarkdown(s, r) {
    const o = this.vaultAccess.getAbstractFileByPath(s);
    if (!(o instanceof import_obsidian.TFile)) return {
      preamble: "",
      body: "",
      postscript: ""
    };
    if (r) return this.extractSettingFromWholeText(r);
    const u = null != r ? r : await this.vaultAccess.vaultRead(o);
    return this.extractSettingFromWholeText(u);
  }
  async checkAndApplySettingFromMarkdown(s, r) {
    if (r && !this.settings.notifyAllSettingSyncFile) if (!this.settings.settingSyncFile || this.settings.settingSyncFile != s) {
      Logger(`Setting file (${s}) is not matched to the current configuration. skipped.`, LOG_LEVEL_DEBUG);
      return;
    }
    const {body: o} = await this.parseSettingFromMarkdown(s);
    let u = {};
    try {
      u = (0, import_obsidian.parseYaml)(o);
    } catch (s) {
      Logger("Could not parse YAML", LOG_LEVEL_NOTICE);
      Logger(s, LOG_LEVEL_VERBOSE);
      return;
    }
    if ("settingSyncFile" in u && u.settingSyncFile != s) {
      Logger("This setting file seems to backed up one. Please fix the filename or settingSyncFile value.", r ? LOG_LEVEL_INFO : LOG_LEVEL_NOTICE);
      return;
    }
    let g = {
      ...DEFAULT_SETTINGS
    };
    g = {
      ...g,
      ...u
    };
    if (!(null == g ? void 0 : g.writeCredentialsForSettingSync)) {
      g.couchDB_USER = this.settings.couchDB_USER;
      g.couchDB_PASSWORD = this.settings.couchDB_PASSWORD;
      g.passphrase = this.settings.passphrase;
    }
    if (!isObjectDifferent(this.generateSettingForMarkdown(this.settings, g.writeCredentialsForSettingSync), this.generateSettingForMarkdown(g))) {
      Logger("Setting markdown has been detected, but not changed.", r ? LOG_LEVEL_INFO : LOG_LEVEL_NOTICE);
      return;
    }
    const _ = this.settings.settingSyncFile != s ? " (This is not-active file)" : "";
    this.askInPopup("apply-setting-from-md", `Setting markdown ${s}${_} has been detected. Apply this from {HERE}.`, (s => {
      s.text = "HERE";
      s.addEventListener("click", (async () => {
        const s = "Apply settings", r = "Apply settings and restart obsidian", o = "Apply settings and restart obsidian with red_flag_rebuild.md", u = "Apply settings and restart obsidian with red_flag_fetch.md", _ = await this.askSelectString("Ready for apply the setting.", [ r, s, u, o, "Cancel" ]);
        if (_ == s || _ == r || _ == o || _ == u) {
          this.settings = g;
          await this.saveSettingData();
          if (_ == s) {
            Logger("Loaded settings have been applied!", LOG_LEVEL_NOTICE);
            return;
          }
          if (_ == o) await this.vaultAccess.vaultCreate(FLAGMD_REDFLAG2_HR, "");
          if (_ == u) await this.vaultAccess.vaultCreate(FLAGMD_REDFLAG3_HR, "");
          this.performAppReload();
        }
      }));
    }));
  }
  generateSettingForMarkdown(s, r) {
    const o = {
      ...s ? s : this.settings
    };
    delete o.encryptedCouchDBConnection;
    delete o.encryptedPassphrase;
    if (!o.writeCredentialsForSettingSync && !r) {
      delete o.couchDB_USER;
      delete o.couchDB_PASSWORD;
      delete o.passphrase;
    }
    return o;
  }
  async saveSettingToMarkdown(s) {
    const r = this.generateSettingForMarkdown();
    let o = this.vaultAccess.getAbstractFileByPath(s);
    if (!o) {
      await this.vaultAccess.ensureDirectory(s);
      const r = 'This file contains Self-hosted LiveSync settings as YAML.\nExcept for the `livesync-setting` code block, we can add a note for free.\n\nIf the name of this file matches the value of the "settingSyncFile" setting inside the `livesync-setting` block, LiveSync will tell us whenever the settings change. We can decide to accept or decline the remote setting. (In other words, we can back up this file by renaming it to another name).\n\nWe can perform a command in this file.\n- `Parse setting file` : load the setting from the file.\n\n**Note** Please handle it with all of your care if you have configured to write credentials in.\n\n\n';
      o = await this.vaultAccess.vaultCreate(s, r + SETTING_HEADER + "\n" + SETTING_FOOTER);
    }
    if (!(o instanceof import_obsidian.TFile)) {
      Logger(`Markdown Setting: ${s} already exists as a folder`, LOG_LEVEL_NOTICE);
      return;
    }
    const u = await this.vaultAccess.vaultRead(o), {preamble: g, body: _, postscript: m} = this.extractSettingFromWholeText(u), b = (0, 
    import_obsidian.stringifyYaml)(r);
    if (b == _) Logger("Markdown setting: Nothing had been changed", LOG_LEVEL_VERBOSE); else {
      await this.vaultAccess.vaultModify(o, g + SETTING_HEADER + b + SETTING_FOOTER + m);
      Logger(`Markdown setting: ${s} has been updated!`, LOG_LEVEL_VERBOSE);
    }
  }
  async saveSettings() {
    await this.saveSettingData();
    fireAndForget((() => this.realizeSettingSyncMode()));
  }
  registerFileWatchEvents() {
    this.vaultManager.beginWatch();
  }
  swapSaveCommand() {
    var s, r;
    Logger("Modifying callback of the save command", LOG_LEVEL_VERBOSE);
    const o = null == (r = null == (s = this.app.commands) ? void 0 : s.commands) ? void 0 : r["editor:save-file"], u = null == o ? void 0 : o.callback;
    if ("function" == typeof u) {
      this._initialCallback = u;
      o.callback = () => {
        scheduleTask("syncOnEditorSave", 250, (() => {
          if (this._unloaded) {
            Logger("Unload and remove the handler.", LOG_LEVEL_VERBOSE);
            o.callback = this._initialCallback;
          } else {
            Logger("Sync on Editor Save.", LOG_LEVEL_VERBOSE);
            if (this.settings.syncOnEditorSave) this.replicate();
          }
        }));
        u();
      };
    }
    const g = this;
    window.CodeMirrorAdapter.commands.save = () => {
      g.performCommand("editor:save-file");
    };
  }
  registerWatchEvents() {
    this.registerEvent(this.app.workspace.on("file-open", this.watchWorkspaceOpen));
    this.registerDomEvent(document, "visibilitychange", this.watchWindowVisibility);
    this.registerDomEvent(window, "focus", (() => this.setHasFocus(true)));
    this.registerDomEvent(window, "blur", (() => this.setHasFocus(false)));
    this.registerDomEvent(window, "online", this.watchOnline);
    this.registerDomEvent(window, "offline", this.watchOnline);
  }
  watchOnline() {
    scheduleTask("watch-online", 500, (() => fireAndForget((() => this.watchOnlineAsync()))));
  }
  async watchOnlineAsync() {
    if (navigator.onLine && this.localDatabase.needScanning) {
      this.localDatabase.needScanning = false;
      await this.syncAllFiles();
    }
  }
  setHasFocus(s) {
    this.hasFocus = s;
    this.watchWindowVisibility();
  }
  watchWindowVisibility() {
    scheduleTask("watch-window-visibility", 100, (() => fireAndForget((() => this.watchWindowVisibilityAsync()))));
  }
  async watchWindowVisibilityAsync() {
    var s;
    if (this.settings.suspendFileWatching) return;
    if (!this.settings.isConfigured) return;
    if (!this.isReady) return;
    if (this.isLastHidden && !this.hasFocus) return;
    const r = document.hidden;
    if (this.isLastHidden !== r) {
      this.isLastHidden = r;
      await this.applyBatchChange();
      if (r) {
        this.replicator.closeReplication();
        null == (s = this.periodicSyncProcessor) || s.disable();
      } else {
        if (this.suspended) return;
        await Promise.all(this.addOns.map((s => s.onResume())));
        if (this.settings.liveSync) this.replicator.openReplication(this.settings, true, false);
        if (this.settings.syncOnStart) this.replicator.openReplication(this.settings, false, false);
        this.periodicSyncProcessor.enable(this.settings.periodicReplication ? 1e3 * this.settings.periodicReplicationInterval : 0);
      }
    }
  }
  cancelRelativeEvent(s) {
    this.fileEventQueue.modifyQueue((r => [ ...r.filter((r => r.key != s.key)) ]));
  }
  queueNextFileEvent(s, r) {
    if (this.settings.batchSave && !this.settings.liveSync) {
      const o = r.args.file;
      let u = s.length;
      e: for (;u >= 0; ) {
        u--;
        if (u < 0) break e;
        if (s[u].args.file.path == o.path) {
          if (s[u].type != r.type) break e;
          s.remove(s[u]);
        }
      }
    }
    s.push(r);
    if ("DELETE" == r.type || "RENAME" == r.type) this.fileEventQueue.requestNextFlush();
    return s;
  }
  async handleFileEvent(s) {
    const r = s.args.file, o = `file-last-proc-${s.type}-${r.path}`, u = Number(await this.kvDB.get(o) || 0);
    let g = r.mtime;
    if ("DELETE" == s.type) {
      await this.deleteFromDBbyPath(r.path);
      g = r.mtime - 1;
      const s = `file-last-proc-CREATE-${r.path}`, o = `file-last-proc-CHANGED-${r.path}`;
      await this.kvDB.set(s, g);
      await this.kvDB.set(o, g);
    } else if ("INTERNAL" == s.type) {
      await this.addOnHiddenFileSync.watchVaultRawEventsAsync(r.path);
      await this.addOnConfigSync.watchVaultRawEventsAsync(r.path);
    } else {
      const o = this.vaultAccess.getAbstractFileByPath(r.path);
      if (!(o instanceof import_obsidian.TFile)) {
        Logger(`Target file was not found: ${r.path}`, LOG_LEVEL_INFO);
        return;
      }
      if (r.mtime == u) {
        Logger(`File has been already scanned on ${s.type}, skip: ${r.path}`, LOG_LEVEL_VERBOSE);
        return;
      }
      if ("CREATE" == s.type || "CHANGED" == s.type) {
        fireAndForget((() => this.checkAndApplySettingFromMarkdown(s.args.file.path, true)));
        const u = `file-last-proc-DELETED-${r.path}`;
        await this.kvDB.set(u, g);
        if (!await this.updateIntoDB(o, void 0)) {
          Logger(`STORAGE -> DB: failed, cancel the relative operations: ${o.path}`, LOG_LEVEL_INFO);
          this.cancelRelativeEvent(s);
          return;
        }
      }
      if ("RENAME" == s.type) await this.watchVaultRenameAsync(o, s.args.oldPath);
    }
    await this.kvDB.set(o, g);
  }
  flushFileEventQueue() {
    return this.fileEventQueue.flush();
  }
  watchWorkspaceOpen(s) {
    if (!this.settings.suspendFileWatching) if (this.settings.isConfigured) if (this.isReady) if (s) scheduleTask("watch-workspace-open", 500, (() => fireAndForget((() => this.watchWorkspaceOpenAsync(s)))));
  }
  async watchWorkspaceOpenAsync(s) {
    if (!this.settings.suspendFileWatching) if (this.settings.isConfigured) if (this.isReady) {
      await this.applyBatchChange();
      if (null != s) {
        if (this.settings.syncOnFileOpen && !this.suspended) await this.replicate();
        this.queueConflictCheck(s);
      }
    }
  }
  async applyBatchChange() {
    if (this.settings.batchSave && !this.settings.liveSync) return await this.flushFileEventQueue();
  }
  getFilePath(s) {
    if (s instanceof import_obsidian.TFolder) if (s.isRoot()) return ""; else return this.getFilePath(s.parent) + "/" + s.name;
    if (s instanceof import_obsidian.TFile) return this.getFilePath(s.parent) + "/" + s.name; else return this.getFilePath(s.parent) + "/" + s.name;
  }
  async watchVaultRenameAsync(s, r, o) {
    Logger(`${r} renamed to ${s.path}`, LOG_LEVEL_VERBOSE);
    if (s instanceof import_obsidian.TFile) try {
      if (await this.updateIntoDB(s, o)) await this.deleteFromDBbyPath(r); else Logger(`Could not save new file: ${s.path} `, LOG_LEVEL_NOTICE);
    } catch (s) {
      Logger(s);
    }
  }
  async addLog(s, r = LOG_LEVEL_INFO, o = "") {
    var u, g, _;
    if (r == LOG_LEVEL_DEBUG && !isDebug) return;
    if (r < LOG_LEVEL_INFO && this.settings && this.settings.lessInformationInLog) return;
    if (this.settings && !this.settings.showVerboseLog && r == LOG_LEVEL_VERBOSE) return;
    const m = this.getVaultName(), b = new Date, E = b.toLocaleString(), w = "string" == typeof s ? s : s instanceof Error ? `${s.name}:${s.message}` : JSON.stringify(s, null, 2);
    if (s instanceof Error) console.dir(s.stack);
    const S = E + "->" + w;
    console.log(m + ":" + S);
    if (!(null == (u = this.settings) ? void 0 : u.showOnlyIconsOnEditor)) this.statusLog.value = w;
    if (null == (g = this.settings) ? void 0 : g.writeLogToTheFile) {
      const s = b.toISOString().split("T")[0], r = `${PREFIXMD_LOGFILE}${s}.md`;
      if (!this.vaultAccess.getAbstractFileByPath(normalizePath(r))) this.vaultAccess.adapterAppend(normalizePath(r), "```\n");
      this.vaultAccess.adapterAppend(normalizePath(r), m + ":" + S + "\n");
    }
    recentLogProcessor.enqueue(S);
    if (r >= LOG_LEVEL_NOTICE) {
      if (!o) o = w;
      if (o in this.notifies) {
        if (!(null == (_ = this.notifies[o].notice.noticeEl) ? void 0 : _.isShown())) this.notifies[o].notice = new import_obsidian.Notice(w, 0);
        cancelTask(`notify-${o}`);
        if (o == w) {
          this.notifies[o].count++;
          this.notifies[o].notice.setMessage(`(${this.notifies[o].count}):${w}`);
        } else this.notifies[o].notice.setMessage(`${w}`);
      } else {
        const s = new import_obsidian.Notice(w, 0);
        this.notifies[o] = {
          count: 0,
          notice: s
        };
      }
      scheduleTask(`notify-${o}`, 5e3, (() => {
        const s = this.notifies[o].notice;
        delete this.notifies[o];
        try {
          s.hide();
        } catch (s) {}
      }));
    }
  }
  async processEntryDoc(s, r, o) {
    const u = null == r ? "create" : "modify", g = this.getPath(s);
    if (shouldBeIgnored(g)) return;
    if (!await this.isTargetFile(g)) return;
    const _ = await this.localDatabase.getDBEntry(g, {
      conflicts: true
    }), m = `STORAGE <- DB (${u}${o ? ",force" : ""},${_ ? null == _ ? void 0 : _.datatype : "--"}) `;
    if (_ && _._conflicts) if (this.settings.writeDocumentsIfConflicted) {
      Logger(`Processing: ${g}: Conflicted revision has been deleted, but there were more conflicts. `, LOG_LEVEL_INFO);
      await this.processEntryDoc(s, r, true);
      return;
    } else if (true != o) {
      Logger(`Processing: ${g}: Conflicted revision has been deleted, but there were more conflicts...`);
      this.queueConflictCheck(g);
      return;
    }
    if (s._deleted || s.deleted || false === _) {
      if (!r) {
        Logger(`delete skipped: ${g} :Already not exist on storage`, LOG_LEVEL_VERBOSE);
        return;
      }
      if (r.path != g) {
        Logger(`delete skipped: ${g} :Not exactly matched`, LOG_LEVEL_VERBOSE);
        return;
      }
      if (false === _) await this.deleteVaultItem(r); else await this.pullFile(g, void 0, true);
      return;
    }
    const b = compareFileFreshness(r, s), E = _;
    if (!isAnyNote(E)) {
      Logger(m + "ERROR, Invalid type: " + g + "(" + (null == E ? void 0 : E.type) || "type missing)", LOG_LEVEL_NOTICE);
      return;
    }
    if (!o && (b == BASE_IS_NEW || b == EVEN)) return;
    if (!isValidPath(g)) {
      Logger(m + "ERROR, invalid path: " + g, LOG_LEVEL_NOTICE);
      return;
    }
    const w = readContent(E);
    await this.vaultAccess.ensureDirectory(g);
    try {
      let s, o = true;
      if (!r) {
        const r = normalizePath(g);
        await this.vaultAccess.vaultCreate(r, w, {
          ctime: E.ctime,
          mtime: E.mtime
        });
        s = this.vaultAccess.getAbstractFileByPath(r);
      } else {
        o = await this.vaultAccess.vaultModify(r, w, {
          ctime: E.ctime,
          mtime: E.mtime
        });
        s = this.vaultAccess.getAbstractFileByPath(getPathFromTFile(r));
      }
      if (o) {
        Logger(m + g);
        this.vaultAccess.touch(s);
        this.vaultAccess.trigger(u, s);
      } else Logger(m + "Skipped, the file is the same: " + g, LOG_LEVEL_VERBOSE);
    } catch (s) {
      Logger(m + "ERROR, Could not write: " + g, LOG_LEVEL_NOTICE);
      Logger(s, LOG_LEVEL_VERBOSE);
    }
  }
  async deleteVaultItem(s) {
    if (s instanceof import_obsidian.TFile) if (!await this.isTargetFile(s)) return;
    const r = s.parent;
    if (this.settings.trashInsteadDelete) await this.vaultAccess.trash(s, false); else await this.vaultAccess.delete(s, true);
    Logger(`xxx <- STORAGE (deleted) ${s.path}`);
    if (r) {
      Logger(`files: ${r.children.length}`);
      if (0 == r.children.length) if (!this.settings.doNotDeleteFolder) {
        Logger(`All files under the parent directory (${r.path}) have been deleted, so delete this one.`);
        await this.deleteVaultItem(r);
      }
    }
  }
  queueConflictCheck(s) {
    const r = s instanceof import_obsidian.TFile ? getPathFromTFile(s) : s;
    if (this.settings.checkConflictOnlyOnOpen) {
      const o = this.getActiveFile();
      if (o && o.path != r) {
        Logger(`${s} is conflicted, merging process has been postponed.`, LOG_LEVEL_NOTICE);
        return;
      }
    }
    this.conflictCheckQueue.enqueue(r);
  }
  saveQueuedFiles() {
    this._saveQueuedFiles();
  }
  async loadQueuedFiles() {
    var s;
    if (this.settings.suspendParseReplicationResult) return;
    if (!this.settings.isConfigured) return;
    const r = arrayToChunkedArray([ ...new Set(null != (s = await this.kvDB.get("queued-files")) ? s : []) ], 100);
    for await (const s of r) {
      const r = await this.localDatabase.allDocsRaw({
        keys: s,
        include_docs: true,
        limit: 100
      }), o = r.rows.filter((s => s.doc)).map((s => s.doc)), u = r.rows.filter((s => !s.doc && !s.value.deleted));
      if (u.length > 0) {
        Logger("Some queued processes were not resurrected");
        Logger(JSON.stringify(u), LOG_LEVEL_VERBOSE);
      }
      this.replicationResultProcessor.enqueueAll(o);
      await this.replicationResultProcessor.waitForPipeline();
    }
  }
  parseReplicationResult(s) {
    if (this.settings.suspendParseReplicationResult && !this.replicationResultProcessor.isSuspended) this.replicationResultProcessor.suspend();
    this.replicationResultProcessor.enqueueAll(s);
    if (!this.settings.suspendParseReplicationResult && this.replicationResultProcessor.isSuspended) this.replicationResultProcessor.resume();
  }
  async realizeSettingSyncMode() {
    var s;
    this.replicator.closeReplication();
    null == (s = this.periodicSyncProcessor) || s.disable();
    this.localDatabase.refreshSettings();
    await this.applyBatchChange();
    await Promise.all(this.addOns.map((s => s.realizeSettingSyncMode())));
    if (this.suspended) return;
    await Promise.all(this.addOns.map((s => s.onResume())));
    if (this.settings.liveSync) this.replicator.openReplication(this.settings, true, false);
    const r = activeDocument.querySelector(".livesync-ribbon-showcustom");
    null == r || r.toggleClass("sls-hidden", !this.settings.usePluginSync);
    this.periodicSyncProcessor.enable(this.settings.periodicReplication ? 1e3 * this.settings.periodicReplicationInterval : 0);
  }
  observeForLogs() {
    const s = " ".repeat(10), r = new Map, o = reactiveSource(0);
    function padLeftSp(u, g) {
      var _;
      const m = `${u}`.length + 1, [b, E] = null != (_ = r.get(g)) ? _ : [ void 0, m ];
      if (u || b) {
        if (u) {
          if (b) clearTimeout(b);
          r.set(g, [ setTimeout((async () => {
            r.delete(g);
            await delay(100);
            o.value = o.value + 1;
          }), 3e3), Math.max(E, m) ]);
        }
        return ` ${g}${`${s}${u}`.slice(-E)}`;
      } else return "";
    }
    const u = reactive((() => {
      o.value;
      const s = this.databaseQueueCount.value, r = this.replicationResultCount.value, u = this.storageApplyingCount.value, g = collectingChunks.value, _ = pluginScanningCount.value, m = hiddenFilesEventCount.value + hiddenFilesProcessingCount.value, b = this.conflictProcessQueueCount.value;
      return `${padLeftSp(r, "📥")}${padLeftSp(s, "📄")}${padLeftSp(u, "💾")}${padLeftSp(g, "🧩")}${padLeftSp(_, "🔌")}${padLeftSp(m, "⚙️")}${padLeftSp(b, "🔩")}`;
    })), g = reactive((() => 0 != this.requestCount.value - this.responseCount.value ? "📲 " : "")), _ = reactive((() => {
      const s = this.replicationStat.value, r = s.sent, o = s.arrived, u = s.maxPullSeq, g = s.maxPushSeq, _ = s.lastSyncPullSeq, m = s.lastSyncPushSeq;
      let b = "", E = "", w = "";
      switch (s.syncStatus) {
       case "CLOSED":
       case "COMPLETED":
       case "NOT_CONNECTED":
        w = "⏹";
        break;

       case "STARTED":
        w = "🌀";
        break;

       case "PAUSED":
        w = "💤";
        break;

       case "CONNECTED":
        w = "⚡";
        b = 0 == m ? "" : m >= g ? " (LIVE)" : ` (${g - m})`;
        E = 0 == _ ? "" : _ >= u ? " (LIVE)" : ` (${u - _})`;
        break;

       case "ERRORED":
        w = "⚠";
        break;

       default:
        w = "?";
      }
      return {
        w,
        sent: r,
        pushLast: b,
        arrived: o,
        pullLast: E
      };
    })), m = reactive((() => {
      o.value;
      const s = this.pendingFileEventCount.value, r = this.processingFileEventCount.value, u = s - r;
      return `${padLeftSp(r, "⏳")}${padLeftSp(u, "🛫")}`;
    })), b = reactive((() => {
      const {w: s, sent: r, pushLast: o, arrived: b, pullLast: E} = _.value, w = u.value, S = m.value;
      return {
        message: `${g.value}Sync: ${s} ↑ ${r}${o} ↓ ${b}${E}${S}${w}`
      };
    })), E = reactive((() => {
      const {message: s} = b.value;
      return {
        message: s,
        status: this.statusLog.value
      };
    })), w = throttle((() => {
      const s = E.value;
      this.applyStatusBarText(s.message, s.status);
    }), 20);
    E.onChanged(w);
  }
  applyStatusBarText(s, r) {
    var o;
    const u = s.replace(/\n/g, "\\A "), g = r.replace(/\n/g, "\\A ");
    null == (o = this.statusBar) || o.setText(u.split("\n")[0]);
    if (this.settings.showStatusOnEditor) activeDocument.documentElement.style.setProperty("--sls-log-text", "'" + u + "\\A " + g + "'");
    scheduleTask("log-hide", 3e3, (() => {
      this.statusLog.value = "";
    }));
  }
  async replicate(s = false) {
    if (!this.isReady) return;
    if (isLockAcquired("cleanup")) {
      Logger("Database cleaning up is in process. replication has been cancelled", LOG_LEVEL_NOTICE);
      return;
    }
    if ("" != this.settings.versionUpFlash) {
      Logger("Open settings and check message, please. replication has been cancelled.", LOG_LEVEL_NOTICE);
      return;
    }
    await this.applyBatchChange();
    await Promise.all(this.addOns.map((r => r.beforeReplicate(s))));
    await this.loadQueuedFiles();
    const r = await this.replicator.openReplication(this.settings, false, s);
    if (!r) if (this.replicator.remoteLockedAndDeviceNotAccepted) if (this.replicator.remoteCleaned && this.settings.useIndexedDBAdapter) {
      Logger("The remote database has been cleaned.", s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
      await skipIfDuplicated("cleanup", (async () => {
        const r = `The remote database has been cleaned up.\nTo synchronize, this device must be also cleaned up. ${await purgeUnreferencedChunks(this.localDatabase.localDatabase, true)} chunk(s) will be erased from this device.\nHowever, If there are many chunks to be deleted, maybe fetching again is faster.\nWe will lose the history of this device if we fetch the remote database again.\nEven if you choose to clean up, you will see this option again if you exit Obsidian and then synchronise again.`, o = "Fetch again", u = "Cleanup", g = "Dismiss", _ = await confirmWithMessage(this, "Cleaned", r, [ o, u, g ], g, 30);
        if (_ == o) await performRebuildDB(this, "localOnly");
        if (_ == u) {
          const r = await this.getReplicator().connectRemoteCouchDBWithSetting(this.settings, this.getIsMobile(), true);
          if ("string" == typeof r) {
            Logger(r, LOG_LEVEL_NOTICE);
            return false;
          }
          await purgeUnreferencedChunks(this.localDatabase.localDatabase, false);
          this.localDatabase.hashCaches.clear();
          if (await this.replicator.openReplication(this.settings, false, s, true)) {
            await balanceChunkPurgedDBs(this.localDatabase.localDatabase, r.db);
            await purgeUnreferencedChunks(this.localDatabase.localDatabase, false);
            this.localDatabase.hashCaches.clear();
            await this.getReplicator().markRemoteResolved(this.settings);
            Logger("The local database has been cleaned up.", s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
          } else Logger("Replication has been cancelled. Please try it again.", s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
        }
      }));
    } else {
      const s = "\nThe remote database has been rebuilt.\nTo synchronize, this device must fetch everything again once.\nOr if you are sure know what had been happened, we can unlock the database from the setting dialog.\n                    ", r = "Fetch again", o = "Dismiss";
      if (await confirmWithMessage(this, "Locked", s, [ r, o ], o, 10) == r) await performRebuildDB(this, "localOnly");
    }
    return r;
  }
  async initializeDatabase(s = false, r = true) {
    this.isReady = false;
    if (!r || await this.openDatabase()) {
      if (this.localDatabase.isReady) await this.syncAllFiles(s);
      await Promise.all(this.addOns.map((r => r.onInitializeDatabase(s))));
      this.isReady = true;
      await this.flushFileEventQueue();
      return true;
    } else {
      this.isReady = false;
      return false;
    }
  }
  async replicateAllToServer(s = false) {
    if (!this.isReady) return false;
    await Promise.all(this.addOns.map((r => r.beforeReplicate(s))));
    return await this.replicator.replicateAllToServer(this.settings, s);
  }
  async replicateAllFromServer(s = false) {
    if (!this.isReady) return false; else return await this.replicator.replicateAllFromServer(this.settings, s);
  }
  async markRemoteLocked(s = false) {
    return await this.replicator.markRemoteLocked(this.settings, true, s);
  }
  async markRemoteUnlocked() {
    return await this.replicator.markRemoteLocked(this.settings, false, false);
  }
  async markRemoteResolved() {
    return await this.replicator.markRemoteResolved(this.settings);
  }
  isFileSizeExceeded(s) {
    if (this.settings.syncMaxSizeInMB > 0 && s > 0) if (1024 * this.settings.syncMaxSizeInMB * 1024 < s) return true;
    return false;
  }
  async syncAllFiles(s) {
    if (!this.settings.isConfigured) {
      if (s) Logger("LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.", LOG_LEVEL_NOTICE, "syncAll");
      return;
    }
    if (s) Logger("Initializing", LOG_LEVEL_NOTICE, "syncAll");
    Logger("Initialize and checking database files");
    Logger("Checking deleted files");
    await this.collectDeletedFiles();
    Logger("Collecting local files on the storage", LOG_LEVEL_VERBOSE);
    const r = this.vaultAccess.getFiles(), o = [];
    for (const s of r) if (await this.isTargetFile(s.path)) o.push(s);
    const u = o.map((s => s.path));
    Logger("Collecting local files on the DB", LOG_LEVEL_VERBOSE);
    const g = [];
    let _ = 0;
    for await (const r of this.localDatabase.findAllNormalDocs()) {
      _++;
      if (_ % 25 == 0) Logger(`Collecting local files on the DB: ${_}`, s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "syncAll");
      const o = getPath2(r);
      if (isValidPath(o) && await this.isTargetFile(o)) g.push(o);
    }
    Logger("Opening the key-value database", LOG_LEVEL_VERBOSE);
    const m = await this.kvDB.get("initialized") || false, b = o.filter((s => -1 == g.indexOf(getPathFromTFile(s)))), E = g.filter((s => -1 == u.indexOf(s))), w = b.map((s => s.path)), S = o.filter((s => -1 == w.indexOf(s.path)));
    Logger("Updating database by new files");
    const L = {}, O = s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, D = throttle(((s, r) => {
      L[s] = r;
      Logger(Object.values(L).join("\n"), O, "syncAll");
    }), 25), C = [], runAll = async (s, r, o) => {
      if (0 == r.length) {
        Logger(`${s}: Nothing to do`);
        return;
      }
      Logger(s);
      if (!this.localDatabase.isReady) throw Error("Database is not ready!");
      let u = 0, g = 0;
      const _ = new QueueProcessor((async r => {
        try {
          await o(r[0]);
          u++;
        } catch (r) {
          Logger(`Error while ${s}`, LOG_LEVEL_NOTICE);
          Logger(r, LOG_LEVEL_VERBOSE);
          g++;
        }
        if ((u + g) % 10 == 0) {
          const r = `${s}: DONE:${u}, FAILED:${g}, LAST:${_._queue.length}`;
          D(s, r);
        }
      }), {
        batchSize: 1,
        concurrentLimit: 10,
        delay: 0,
        suspended: true
      }, r);
      await _.waitForPipeline();
      D(s, `${s} All done: DONE:${u}, FAILED:${g}`);
    };
    C.push(runAll("UPDATE DATABASE", b, (async s => {
      if (!this.isFileSizeExceeded(s.stat.size)) {
        await this.updateIntoDB(s);
        fireAndForget((() => this.checkAndApplySettingFromMarkdown(s.path, true)));
      } else Logger(`UPDATE DATABASE: ${s.path} has been skipped due to file size exceeding the limit`, O);
    })));
    C.push(runAll("UPDATE STORAGE", E, (async s => {
      const r = await this.localDatabase.getDBEntryMeta(s, {}, true);
      if (r && !(r.deleted || r._deleted)) if (!this.isFileSizeExceeded(r.size)) {
        await this.pullFile(s, o, false, void 0, false);
        fireAndForget((() => this.checkAndApplySettingFromMarkdown(s, true)));
        Logger(`Check or pull from db:${s} OK`);
      } else Logger(`UPDATE STORAGE: ${s} has been skipped due to file size exceeding the limit`, O); else if (r) Logger(`Deletion history skipped: ${s}`, LOG_LEVEL_VERBOSE); else Logger(`entry not found: ${s}`);
    })));
    const k = new QueueProcessor((async s => {
      const r = s[0];
      return [ {
        file: r,
        id: await this.path2id(getPathFromTFile(r))
      } ];
    }), {
      batchSize: 1,
      concurrentLimit: 10,
      delay: 0,
      suspended: true
    }, S);
    k.pipeTo(new QueueProcessor((async s => {
      const r = await this.localDatabase.allDocsRaw({
        keys: s.map((s => s.id)),
        include_docs: true
      }), o = Object.fromEntries(r.rows.map((s => [ s.id, s.doc ])));
      return s.map((s => ({
        file: s.file,
        doc: o[s.id]
      })));
    }), {
      batchSize: 10,
      concurrentLimit: 5,
      delay: 10,
      suspended: false
    })).pipeTo(new QueueProcessor((async s => {
      const r = s[0];
      await this.syncFileBetweenDBandStorage(r.file, r.doc);
    }), {
      batchSize: 1,
      concurrentLimit: 5,
      delay: 10,
      suspended: false
    }));
    const T = S.length;
    let A = T;
    k.startPipeline().onUpdateProgress((() => (s => {
      if (A - s > 25) {
        D("sync", ` CHECK AND SYNC: ${s} / ${T}`);
        A = s;
      }
    })(k.totalRemaining + k.nowProcessing)));
    C.push(k.waitForPipeline());
    await Promise.all(C);
    Logger("Initialized, NOW TRACKING!");
    if (!m) await this.kvDB.set("initialized", true);
    if (s) Logger("Initialize done!", LOG_LEVEL_NOTICE, "syncAll");
  }
  async getConflictedDoc(s, r) {
    try {
      const o = await this.localDatabase.getDBEntry(s, {
        rev: r
      }, false, false, true);
      if (false === o) return false;
      let u = getDocData(o.data);
      if ("newnote" == o.datatype) u = readString(new Uint8Array(decodeBinary(o.data))); else if ("plain" == o.datatype) ;
      return {
        deleted: o.deleted || o._deleted,
        ctime: o.ctime,
        mtime: o.mtime,
        rev: r,
        data: u
      };
    } catch (s) {
      if (isErrorOfMissingDoc(s)) return false;
    }
    return false;
  }
  async mergeSensibly(s, r, o, u) {
    var g, _, m, b;
    const E = await this.getConflictedDoc(s, r), w = await this.getConflictedDoc(s, o), S = await this.getConflictedDoc(s, u);
    let L = false;
    if (false == E || false == w || false == S) return false;
    if (w.deleted && S.deleted) return false;
    const O = new import_diff_match_patch.diff_match_patch, D = O.diff_linesToChars_(E.data, w.data), C = O.diff_main(D.chars1, D.chars2, false);
    O.diff_charsToLines_(C, D.lineArray);
    const k = O.diff_linesToChars_(E.data, S.data), T = O.diff_main(k.chars1, k.chars2, false);
    O.diff_charsToLines_(T, k.lineArray);
    function splitDiffPiece(s) {
      const r = [];
      do {
        const o = s.shift();
        if (void 0 === o) return r;
        const u = o[1].split(/([^\n]*\n)/).filter((s => "" != s));
        if ("undefined" == typeof o) break;
        if (o[0] != import_diff_match_patch.DIFF_DELETE) r.push(...u.map((s => [ o[0], s ])));
        if (o[0] == import_diff_match_patch.DIFF_DELETE) {
          const g = s.shift();
          if ("undefined" != typeof g) {
            const s = g[1].split(/([^\n]*\n)/).filter((s => "" != s));
            if (g[0] == import_diff_match_patch.DIFF_INSERT) {
              for (const g of u) {
                r.push([ o[0], g ]);
                const u = s.shift();
                if ("undefined" != typeof u) r.push([ import_diff_match_patch.DIFF_INSERT, u ]);
              }
              r.push(...s.map((s => [ g[0], s ])));
            } else {
              r.push(...u.map((s => [ o[0], s ])));
              r.push(...s.map((s => [ g[0], s ])));
            }
          } else r.push(...u.map((s => [ 0, s ])));
        }
      } while (s.length > 0);
      return r;
    }
    const A = splitDiffPiece(C), R = splitDiffPiece(T);
    let I = 0, x = 0;
    const P = [];
    L = true;
    e: do {
      if (x >= A.length && I >= R.length) break e;
      const s = null != (g = A[x]) ? g : [ 0, "" ], r = null != (_ = R[I]) ? _ : [ 0, "" ];
      x++;
      I++;
      if (s[0] != import_diff_match_patch.DIFF_EQUAL || r[0] != import_diff_match_patch.DIFF_EQUAL || s[1] != r[1]) {
        if (s[0] == import_diff_match_patch.DIFF_DELETE && r[0] == import_diff_match_patch.DIFF_DELETE && s[1] == r[1]) {
          const r = x, o = I, [u, g] = [ null != (m = A[r]) ? m : [ 0, "" ], null != (b = R[o]) ? b : [ 0, "" ] ];
          if (u[0] == import_diff_match_patch.DIFF_INSERT && g[0] == import_diff_match_patch.DIFF_INSERT && u[1] != g[1]) {
            L = false;
            break;
          } else {
            P.push(s);
            continue;
          }
        }
        if (s[0] == import_diff_match_patch.DIFF_INSERT && r[0] == import_diff_match_patch.DIFF_INSERT) if (s[1] == r[1]) {
          P.push(s);
          continue;
        } else if (w.mtime <= S.mtime) {
          P.push(s);
          P.push(r);
          continue;
        } else {
          P.push(r);
          P.push(s);
          continue;
        }
        if (s[0] != import_diff_match_patch.DIFF_INSERT) if (r[0] != import_diff_match_patch.DIFF_INSERT) {
          if (r[1] != s[1]) {
            Logger(`MERGING PANIC:${s[0]},${s[1]} == ${r[0]},${r[1]}`, LOG_LEVEL_VERBOSE);
            L = false;
            break e;
          }
          if (s[0] == import_diff_match_patch.DIFF_DELETE) if (r[0] == import_diff_match_patch.DIFF_EQUAL) {
            P.push(s);
            continue;
          } else {
            L = false;
            break e;
          }
          if (r[0] == import_diff_match_patch.DIFF_DELETE) if (s[0] == import_diff_match_patch.DIFF_EQUAL) {
            P.push(r);
            continue;
          } else {
            L = false;
            break e;
          }
          Logger(`Weird condition:${s[0]},${s[1]} == ${r[0]},${r[1]}`, LOG_LEVEL_VERBOSE);
          break e;
        } else {
          x--;
          P.push(r);
        } else {
          I--;
          P.push(s);
        }
      } else P.push(s);
    } while (x < A.length || I < R.length);
    if (L) {
      Logger("Sensibly merge available", LOG_LEVEL_VERBOSE);
      return P;
    } else return false;
  }
  async mergeObject(s, r, o, u) {
    try {
      const g = await this.getConflictedDoc(s, r), _ = await this.getConflictedDoc(s, o), m = await this.getConflictedDoc(s, u);
      if (false == g || false == _ || false == m) return false;
      if (_.deleted && m.deleted) return false;
      const b = {
        data: tryParseJSON(g.data, {})
      }, E = {
        data: tryParseJSON(_.data, {})
      }, w = {
        data: tryParseJSON(m.data, {})
      }, S = generatePatchObj(b, E), L = generatePatchObj(b, w), O = new Map(flattenObject(S)), D = new Map(flattenObject(L));
      for (const [s, r] of O) if (D.has(s)) if (D.get(s) == r) D.delete(s);
      for (const [s, r] of D) if (O.has(s) && O.get(s) != r) return false;
      const C = [ {
        mtime: _.mtime,
        patch: S
      }, {
        mtime: m.mtime,
        patch: L
      } ].sort(((s, r) => s.mtime - r.mtime));
      let k = {
        ...b
      };
      for (const s of C) k = applyPatch(k, s.patch);
      return JSON.stringify(k.data);
    } catch (s) {
      Logger("Could not merge object");
      Logger(s, LOG_LEVEL_VERBOSE);
      return false;
    }
  }
  async checkConflictAndPerformAutoMerge(s) {
    var r, o;
    const u = await this.localDatabase.getDBEntry(s, {
      conflicts: true,
      revs_info: true
    }, false, false, true);
    if (false === u) return MISSING_OR_ERROR;
    if (null == u) return MISSING_OR_ERROR;
    if (!u._conflicts) return NOT_CONFLICTED;
    if (0 == u._conflicts.length) return NOT_CONFLICTED;
    const g = u._conflicts.sort(((s, r) => Number(s.split("-")[0]) - Number(r.split("-")[0])));
    if ((isSensibleMargeApplicable(s) || isObjectMargeApplicable(s)) && !this.settings.disableMarkdownAutoMerge) {
      const _ = g[0], m = Number(_.split("-")[0]), b = null != (o = null == (r = ((await this.localDatabase.getRaw(await this.path2id(s), {
        revs_info: true
      }))._revs_info || []).filter((s => "available" == s.status && Number(s.rev.split("-")[0]) < m)).first()) ? void 0 : r.rev) ? o : "";
      let E;
      if (b) {
        if (isSensibleMargeApplicable(s)) {
          const r = await this.mergeSensibly(s, b, u._rev, _);
          if (r) {
            E = r.filter((s => s[0] != import_diff_match_patch.DIFF_DELETE)).map((s => s[1])).join("");
            Logger(`Sensible merge:${s}`, LOG_LEVEL_INFO);
          } else Logger("Sensible merge is not applicable.", LOG_LEVEL_VERBOSE);
        } else if (isObjectMargeApplicable(s)) {
          const r = await this.mergeObject(s, b, u._rev, _);
          if (r) {
            Logger(`Object merge:${s}`, LOG_LEVEL_INFO);
            E = r;
          } else Logger("Object merge is not applicable.", LOG_LEVEL_VERBOSE);
        }
        if (null != E) {
          await this.localDatabase.deleteDBEntry(s, {
            rev: _
          });
          const r = this.vaultAccess.getAbstractFileByPath(stripAllPrefixes(s));
          if (r) {
            if (await this.vaultAccess.vaultModify(r, E)) await this.updateIntoDB(r);
          } else {
            const r = await this.vaultAccess.vaultCreate(s, E);
            await this.updateIntoDB(r);
          }
          await this.pullFile(s);
          Logger(`Automatically merged (sensible) :${s}`, LOG_LEVEL_INFO);
          return AUTO_MERGED;
        }
      }
    }
    const _ = await this.getConflictedDoc(s, u._rev), m = await this.getConflictedDoc(s, g[0]);
    if (false == _) {
      Logger(`could not get current revisions:${s}`, LOG_LEVEL_NOTICE);
      return MISSING_OR_ERROR;
    }
    if (false == m) {
      await this.localDatabase.deleteDBEntry(s, {
        rev: g[0]
      });
      await this.pullFile(s, void 0, true);
      Logger(`could not get old revisions, automatically used newer one:${s}`, LOG_LEVEL_NOTICE);
      return AUTO_MERGED;
    }
    const b = _.data == m.data && _.deleted == m.deleted, E = !isPlainText(s), w = this.settings.resolveConflictsByNewerFile;
    if (b || E || w) {
      let r = _;
      if (compareMTime(_.mtime, m.mtime) != TARGET_IS_NEW) r = m;
      await this.localDatabase.deleteDBEntry(s, {
        rev: r.rev
      });
      await this.pullFile(s, void 0, true);
      Logger(`Automatically merged (${b ? "same," : ""}${E ? "binary," : ""}${w ? "alwaysNewer" : ""}) :${s}`, LOG_LEVEL_NOTICE);
      return AUTO_MERGED;
    }
    const S = new import_diff_match_patch.diff_match_patch, L = S.diff_main(_.data, m.data);
    S.diff_cleanupSemantic(L);
    Logger(`conflict(s) found:${s}`);
    return {
      left: _,
      right: m,
      diff: L
    };
  }
  async resolveConflictByUI(s, r) {
    Logger("Merge:open conflict dialog", LOG_LEVEL_VERBOSE);
    const o = new ConflictResolveModal(this.app, s, r);
    o.open();
    const u = await o.waitForResult();
    if (u === CANCELLED) {
      Logger(`Merge: Cancelled ${s}`, LOG_LEVEL_INFO);
      return false;
    }
    const g = await this.localDatabase.getDBEntry(s, {
      conflicts: true
    }, false, false, true);
    if (false === g) {
      Logger(`Merge: Could not read ${s} from the local database`, LOG_LEVEL_VERBOSE);
      return false;
    }
    if (!g._conflicts) {
      Logger(`Merge: Nothing to do ${s}`, LOG_LEVEL_VERBOSE);
      return false;
    }
    const _ = u, m = r.left.rev != _ ? r.left.rev : r.right.rev;
    if (_ === LEAVE_TO_SUBSEQUENT) {
      const o = r.diff.map((s => s[1])).join("");
      await this.localDatabase.deleteDBEntry(s, {
        rev: g._conflicts[0]
      });
      const u = this.vaultAccess.getAbstractFileByPath(stripAllPrefixes(s));
      if (u) {
        if (await this.vaultAccess.vaultModify(u, o)) await this.updateIntoDB(u);
      } else {
        const r = await this.vaultAccess.vaultCreate(s, o);
        await this.updateIntoDB(r);
      }
      await this.pullFile(s);
      Logger(`Merge: Changes has been concatenated: ${s}`);
    } else if ("string" == typeof _) {
      await this.localDatabase.deleteDBEntry(s, {
        rev: _
      });
      await this.pullFile(s, void 0, true, m);
      Logger(`Conflict resolved:${s}`);
    } else {
      Logger(`Merge: Something went wrong: ${s}, (${_})`, LOG_LEVEL_NOTICE);
      return false;
    }
    if (this.settings.syncAfterMerge && !this.suspended) await shareRunningResult("replication", (() => this.replicate()));
    this.conflictCheckQueue.enqueue(s);
    return false;
  }
  async pullFile(s, r, o, u, g = true) {
    const _ = this.vaultAccess.getAbstractFileByPath(stripAllPrefixes(s));
    if (await this.isTargetFile(s)) if (null == _) {
      const r = await this.localDatabase.getDBEntry(s, u ? {
        rev: u
      } : void 0, false, g);
      if (false === r) {
        Logger(`${s} Skipped`);
        return;
      }
      await this.processEntryDoc(r, void 0, o);
    } else if (_ instanceof import_obsidian.TFile) {
      const r = _, m = await this.localDatabase.getDBEntry(s, u ? {
        rev: u
      } : void 0, false, g);
      if (false === m) {
        Logger(`${s} Skipped`);
        return;
      }
      await this.processEntryDoc(m, r, o);
    } else Logger(`target files:${s} is exists as the folder`);
  }
  async syncFileBetweenDBandStorage(s, r) {
    if (!r) throw new Error(`Missing doc:${s.path}`);
    if (!(s instanceof import_obsidian.TFile) && "path" in s) {
      const r = this.vaultAccess.getAbstractFileByPath(s.path);
      if (r instanceof import_obsidian.TFile) s = r; else throw new Error(`Missing file:${s.path}`);
    }
    switch (compareFileFreshness(s, r)) {
     case BASE_IS_NEW:
      if (!this.isFileSizeExceeded(s.stat.size)) {
        Logger("STORAGE -> DB :" + s.path);
        await this.updateIntoDB(s);
        fireAndForget((() => this.checkAndApplySettingFromMarkdown(s.path, true)));
      } else Logger(`STORAGE -> DB : ${s.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
      break;

     case TARGET_IS_NEW:
      if (!this.isFileSizeExceeded(r.size)) {
        Logger("STORAGE <- DB :" + s.path);
        const r = await this.localDatabase.getDBEntry(getPathFromTFile(s), void 0, false, false, true);
        if (false != r) await this.processEntryDoc(r, s); else Logger(`STORAGE <- DB : Cloud not read ${s.path}, possibly deleted`, LOG_LEVEL_NOTICE);
        return caches;
      } else Logger(`STORAGE <- DB : ${s.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
      break;

     case EVEN:
      Logger("STORAGE == DB :" + s.path, LOG_LEVEL_DEBUG);
      break;

     default:
      Logger("STORAGE ?? DB :" + s.path + " Something got weird");
    }
  }
  async updateIntoDB(s, r, o) {
    if (!await this.isTargetFile(s)) return true;
    if (shouldBeIgnored(s.path)) return true;
    const u = !isPlainText(s.name);
    if (u) Logger(`Reading   : ${s.path}`, LOG_LEVEL_VERBOSE);
    const g = createBlob(await this.vaultAccess.vaultReadAuto(s)), _ = determineTypeFromBlob(g);
    if (u) Logger(`Processing: ${s.path}`, LOG_LEVEL_VERBOSE);
    const m = getPathFromTFile(s), b = {
      _id: await this.path2id(m),
      path: getPathFromTFile(s),
      data: g,
      ctime: s.stat.ctime,
      mtime: s.stat.mtime,
      size: s.stat.size,
      children: [],
      datatype: _,
      type: _
    }, E = `STORAGE -> DB (${_}) `;
    if (await serialized("file-" + m, (async () => {
      if (this.vaultAccess.recentlyTouched(s)) return true;
      try {
        const s = await this.localDatabase.getDBEntry(m, void 0, false, false);
        if (false !== s) {
          const r = {
            data: s.data,
            deleted: s._deleted || s.deleted
          }, o = {
            data: b.data,
            deleted: b._deleted || b.deleted
          };
          if (r.deleted != o.deleted) return false;
          if (!await isDocContentSame(s.data, o.data)) return false;
          Logger(E + "Skipped (not changed) " + m + (b._deleted || b.deleted ? " (deleted)" : ""), LOG_LEVEL_VERBOSE);
          markChangesAreSame(s, b.mtime, s.mtime);
          return true;
        }
      } catch (s) {
        if (o) Logger(E + "Error, Could not check the diff for the old one." + (o ? "force writing." : "") + m + (b._deleted || b.deleted ? " (deleted)" : ""), LOG_LEVEL_VERBOSE); else Logger(E + "Error, Could not check the diff for the old one." + m + (b._deleted || b.deleted ? " (deleted)" : ""), LOG_LEVEL_VERBOSE);
        return !o;
      }
      return false;
    }))) {
      Logger(E + " Skip " + m, LOG_LEVEL_VERBOSE);
      return true;
    }
    const w = await this.localDatabase.putDBEntry(b);
    if (false !== w) {
      Logger(E + m);
      if (this.settings.syncOnSave && !this.suspended) scheduleTask("perform-replicate-after-save", 250, (() => this.replicate()));
    }
    return false != w;
  }
  async deleteFromDB(s) {
    if (!await this.isTargetFile(s)) return;
    const r = getPathFromTFile(s);
    Logger(`deleteDB By path:${r}`);
    await this.deleteFromDBbyPath(r);
    if (this.settings.syncOnSave && !this.suspended) await this.replicate();
  }
  async deleteFromDBbyPath(s) {
    await this.localDatabase.deleteDBEntry(s);
    if (this.settings.syncOnSave && !this.suspended) await this.replicate();
  }
  async resetLocalDatabase() {
    this.vaultAccess.clearTouched();
    await this.localDatabase.resetDatabase();
  }
  async tryResetRemoteDatabase() {
    await this.replicator.tryResetRemoteDatabase(this.settings);
  }
  async tryCreateRemoteDatabase() {
    await this.replicator.tryCreateRemoteDatabase(this.settings);
  }
  filterTargetFiles(s, r = false) {
    const o = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((s => s)).map((s => new RegExp(s, "i")));
    return s.filter((s => !o.some((r => s.path.match(r))))).filter((s => !r || r && -1 !== r.indexOf(s.path)));
  }
  async resolveConflictByNewerEntry(s) {
    const r = await this.path2id(s), o = await this.localDatabase.getRaw(r, {
      conflicts: true
    });
    if (!("_conflicts" in o) || void 0 === o._conflicts) return false;
    if (0 == o._conflicts.length) return false;
    Logger(`Hidden file conflicted:${this.getPath(o)}`);
    const u = o._conflicts.sort(((s, r) => Number(s.split("-")[0]) - Number(r.split("-")[0]))), g = o._rev, _ = u[0], m = await this.localDatabase.getRaw(r, {
      rev: _
    }), b = ("mtime" in o && o.mtime || 0) < ("mtime" in m && m.mtime || 0) ? g : _;
    await this.localDatabase.removeRevision(r, b);
    Logger(`Older one has been deleted:${this.getPath(o)}`);
    return true;
  }
  async readIgnoreFile(s) {
    try {
      const r = (await this.vaultAccess.adapterRead(s)).split(/\r?\n/g);
      this.ignoreFileCache.set(s, r);
      return r;
    } catch (r) {
      this.ignoreFileCache.set(s, false);
      return false;
    }
  }
  async getIgnoreFile(s) {
    var r;
    if (this.ignoreFileCache.has(s)) return null != (r = this.ignoreFileCache.get(s)) ? r : false; else return await this.readIgnoreFile(s);
  }
  async isIgnoredByIgnoreFiles(s) {
    if (!this.settings.useIgnoreFiles) return false;
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    if (this.ignoreFileCache.has(r)) await this.readIgnoreFile(r);
    if (!await isAcceptedAll(stripAllPrefixes(r), this.ignoreFiles, (s => this.getIgnoreFile(s)))) return true; else return false;
  }
  async isTargetFile(s) {
    const r = s instanceof import_obsidian.TFile ? s.path : s;
    if (this.settings.useIgnoreFiles && await this.isIgnoredByIgnoreFiles(s)) return false; else return this.localDatabase.isTargetFile(r);
  }
  async dryRunGC() {
    await skipIfDuplicated("cleanup", (async () => {
      const s = await this.getReplicator().connectRemoteCouchDBWithSetting(this.settings, this.isMobile);
      if ("string" != typeof s) {
        await purgeUnreferencedChunks(s.db, true, this.settings, false);
        await purgeUnreferencedChunks(this.localDatabase.localDatabase, true);
        this.localDatabase.hashCaches.clear();
      } else Logger(s);
    }));
  }
  async dbGC() {
    await skipIfDuplicated("cleanup", (async () => {
      this.getReplicator().markRemoteLocked(this.settings, true, true);
      const s = await this.getReplicator().connectRemoteCouchDBWithSetting(this.settings, this.isMobile);
      if ("string" != typeof s) {
        await purgeUnreferencedChunks(s.db, false, this.settings, true);
        await purgeUnreferencedChunks(this.localDatabase.localDatabase, false);
        this.localDatabase.hashCaches.clear();
        await balanceChunkPurgedDBs(this.localDatabase.localDatabase, s.db);
        this.localDatabase.refreshSettings();
        Logger("The remote database has been cleaned up! Other devices will be cleaned up on the next synchronisation.");
      } else Logger(s);
    }));
  }
  askYesNo(s) {
    return askYesNo(this.app, s);
  }
  askSelectString(s, r) {
    return askSelectString(this.app, s, r);
  }
  askInPopup(s, r, o) {
    const u = createFragment((s => {
      const [u, g] = r.split("{HERE}", 2);
      s.createEl("span", void 0, (s => {
        s.appendText(u);
        s.appendChild(s.createEl("a", void 0, (s => {
          o(s);
        })));
        s.appendText(g);
      }));
    })), g = "popup-" + s;
    scheduleTask(g, 1e3, (async () => {
      var s;
      const r = await memoIfNotExist(g, (() => new import_obsidian.Notice(u, 0)));
      if (!(null == (s = null == r ? void 0 : r.noticeEl) ? void 0 : s.isShown())) memoObject(g, new import_obsidian.Notice(u, 0));
      scheduleTask(g + "-close", 2e4, (() => {
        var s;
        const r = retrieveMemoObject(g);
        if (r) {
          if (null == (s = null == r ? void 0 : r.noticeEl) ? void 0 : s.isShown()) r.hide();
          disposeMemoObject(g);
        }
      }));
    }));
  }
  openSetting() {
    this.app.setting.open();
    this.app.setting.openTabById("obsidian-livesync");
  }
  performAppReload() {
    this.performCommand("app:reload");
  }
  performCommand(s) {
    this.app.commands.executeCommandById(s);
  }
};